repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
Markersx/WinterCraft
src/main/java/net/mcwintercraft/wintercraft/gmod/PhysGun.java
6829
package net.mcwintercraft.wintercraft.gmod; import net.mcwintercraft.wintercraft.WinterCraft; import net.md_5.bungee.api.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemHeldEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; import java.util.HashMap; import java.util.Map; public class PhysGun implements Listener { private final Map<Player, Entity> control = new HashMap<>(); private WinterCraft wc; public PhysGun(WinterCraft wc) { this.wc = wc; } @EventHandler public void changeDistance(PlayerItemHeldEvent e) { if (control.containsKey(e.getPlayer())) { e.setCancelled(true); int from = e.getPreviousSlot(); int to = e.getNewSlot(); if (from >= 8 && to <= 1) { to = 9; } if (from <= 1 && to >= 8) { to = -1; } final boolean decrease = to > from; final boolean increase = to < from; handleScroll(increase, decrease, e.getPlayer().isSneaking()); } } private float amount = 3; @EventHandler public void onUseEntity(PlayerInteractEntityEvent e) { Player p = e.getPlayer(); ItemStack hand = p.getInventory().getItemInMainHand(); if (!control.containsKey(p) && !p.isSneaking() && isPhysGun(hand)) { control.put(p, e.getRightClicked()); Entity ent = control.get(p); new BukkitRunnable() { @Override public void run() { if (control.size() > 0) { for (Map.Entry<Player, Entity> tp : control.entrySet()) { Entity ent = tp.getValue(); Player p = tp.getKey(); ent.teleport(p.getLocation().toVector().add(p.getLocation().getDirection().multiply(amount)).toLocation(p.getWorld())); wc.debug("TP"); } } else { wc.debug("CANCELED TP"); this.cancel(); } } }.runTaskTimer(wc, 0, 3L); if (ent instanceof Player) { Player pe = (Player) ent; pe.setGlowing(true); pe.setGravity(false); pe.setInvulnerable(true); pe.setGameMode(GameMode.ADVENTURE); pe.sendMessage("You are being handled by " + p.getName()); return; } if (ent instanceof Creature && !(ent instanceof Wither)) { ent.setGravity(false); ent.setInvulnerable(true); ent.setGlowing(true); ent.setSilent(true); ((Creature) ent).setAI(false); } } if (control.containsKey(p) && p.isSneaking() && isPhysGun(hand)) { Entity ent = control.get(p); remove(ent, p); wc.debug("Removed entity"); } } @EventHandler public void onUseBlock(PlayerInteractEvent e) { Player p = e.getPlayer(); if (e.getAction() == Action.RIGHT_CLICK_BLOCK && !p.isSneaking() && !control.containsKey(p) && isPhysGun(e.getItem())) { for (String s : wc.getConfig().getStringList("phys-blocked")) { Block b = e.getClickedBlock(); if (!s.equalsIgnoreCase(b.getType().toString())) { Location loc = b.getLocation().add(0.5, 0, 0.5); Entity ent = b.getWorld().spawnFallingBlock(b.getLocation().add(0.5, 0, 0.5), b.getType(), b.getData()); b.setType(Material.AIR); ent.setGravity(false); ent.setInvulnerable(true); ent.setGlowing(true); control.put(p, ent); } } } } @EventHandler public void onBlockDrop(EntityChangeBlockEvent e) { if (control.containsValue(e.getEntity())) { e.setCancelled(true); } } @EventHandler public void onDisconnect(PlayerQuitEvent e) { Player p = e.getPlayer(); if (control.containsKey(p)) { Entity ent = control.get(p); remove(ent, p); } } @EventHandler public void onDeath(EntityDeathEvent e) { if (control.containsValue(e.getEntity())) { for (Map.Entry<Player, Entity> player : control.entrySet()) { if (control.get(player.getKey()) == e.getEntity()) { remove(player.getValue(), player.getKey()); } } } } private void remove(Entity ent, Player p) { if (ent.getType() == null) { return; } control.remove(p, ent); switch (ent.getType()) { case FALLING_BLOCK: FallingBlock fb = (FallingBlock) ent; fb.setGravity(true); fb.setGlowing(false); fb.setInvulnerable(false); return; case PLAYER: Player pe = (Player) ent; pe.setGlowing(false); pe.setGravity(true); pe.setInvulnerable(false); pe.setGameMode(GameMode.SURVIVAL); pe.sendMessage("You are no longer being handled by " + p.getName()); return; } ent.setGravity(true); ent.setInvulnerable(false); ent.setGlowing(false); ent.setSilent(false); } //TODO: DOESN'T WORK WELL WITH FALLING BLOCKS //TODO: MAKE AMOUNT UNIQUE PER PLAYER public void handleScroll(boolean increase, boolean decrease, boolean sneaking) { if (amount > 1.5) { if (decrease) { amount -= 0.5; } if (increase) { amount += 0.5; } } } public boolean isPhysGun(ItemStack item) { return item != null && (item.hasItemMeta() && (item.getItemMeta().hasDisplayName() && (item.getType() == Material.DIAMOND_BARDING && item.getItemMeta().getDisplayName().equalsIgnoreCase(ChatColor.WHITE + "Phys Gun")))); } }
gpl-3.0
uincore/xdiag
Sources/Utility/UtilFunctions.cpp
6121
/* * This program 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/>. */ /** * @brief Implementation file for CUtilFunctions class * @author Raja N, Tobias Lorenz * @copyright Copyright (c) 2011, Robert Bosch Engineering and Business Solutions. All rights reserved. * * Implementation file for CUtilFunctions class */ /* Standard include header */ #include "Utils_stdafx.h" /* For CUtilFunctions class definition */ #include "Utility_Structs.h" #include "UtilFunctions.h" #define MAX_LEN 512 #define ABS_START 3 #define SLASH '\\' CUtilFunctions::CUtilFunctions() { } CUtilFunctions::~CUtilFunctions() { } void CUtilFunctions::s_vRemoveUnwantedBits(__int64& n64rData, int nLength) { /* * So -1 is FFFFFFFFFFFFFFFF (as it is __int64 type) * if the data length is 8 bits take only FF. *th bit is sign * bit and that is set to denote negative number * Set all bits to 1. That is FFFFFFFF FFFFFFFF (-1) */ unsigned __int64 un64Mask = static_cast<unsigned __int64>(-1); /* Create the mask */ un64Mask = un64Mask >> (defMAX_BITS - nLength); /* Mask unwanted portion of signal details */ n64rData = n64rData & un64Mask; } void CUtilFunctions::s_vExtendSignBit( __int64& n64Val, int nSize) { /* Avoid processing 64 bit signals */ if( nSize < defMAX_BITS ) { __int64 n64Mask = 1; BOOL bSignBit; /* Shift the mask by Length - 1 times to get sign bit value */ n64Mask <<= nSize - 1; /* Get the sign bit value */ bSignBit = n64Val & n64Mask ? TRUE : FALSE; /* Set the value only for negative numbers */ if( bSignBit ) { /* Set the Sign bit to 1 */ __int64 nVal = defSIGN_MASK; /* Shift the value to extend the value */ nVal >>= ( defMAX_BITS - nSize - 1); /* Apply the mask */ n64Val |= nVal; } } } INT CUtilFunctions::nGetBaseFolder(const char* omConfigFileName, std::string& omStrConfigFolder) { char pchFilePath[MAX_PATH]; char* pchTemp = pchFilePath; strcpy(pchFilePath, omConfigFileName); if ( PathRemoveFileSpec(pchTemp) == TRUE ) { omStrConfigFolder = pchTemp; omStrConfigFolder += "\\"; } else { int nChars = GetCurrentDirectory(0, nullptr); char* pchFilePath = new char [nChars]; GetCurrentDirectory(nChars, pchFilePath); omStrConfigFolder = pchFilePath; delete []pchFilePath; } return S_OK; } void CUtilFunctions::MakeRelativePath(const char* pchCurrentDir, char* pchAbsFileName, std::string& omStrRelativeParh) { int nCurrentDirectoryLength = strlen(pchCurrentDir); int nAbsoluteFileLen = strlen(pchAbsFileName); if( nCurrentDirectoryLength > MAX_LEN || nCurrentDirectoryLength < ABS_START+1 || nAbsoluteFileLen > MAX_LEN || nAbsoluteFileLen < ABS_START+1) { omStrRelativeParh = ""; return ; } CString strDirectory = pchCurrentDir[0]; CString strDirectory2 = pchAbsFileName[0]; char chRelativeFile[MAX_LEN+1]; if(strDirectory.CompareNoCase(strDirectory2) != 0) { strcpy_s(chRelativeFile, MAX_LEN+1, pchAbsFileName ); omStrRelativeParh = chRelativeFile; return; } int nCount = ABS_START; while(nCount < nAbsoluteFileLen && nCount < nCurrentDirectoryLength && pchCurrentDir[nCount] == pchAbsFileName[nCount] ) { nCount++; } if(nCount == nCurrentDirectoryLength && (pchAbsFileName[nCount] == '\\' || pchAbsFileName[nCount-1] == '\\')) { if(pchAbsFileName[nCount] == '\\') { nCount++; } strcpy(chRelativeFile, &pchAbsFileName[nCount]); omStrRelativeParh = chRelativeFile; return; } int nForword = nCount; int nStages = 1; while(nCount < nCurrentDirectoryLength) { nCount++; if(pchCurrentDir[nCount] == '\\') { nCount++; if(pchCurrentDir[nCount] != '\0') { nStages++; } } } while(nForword > 0 && pchAbsFileName[nForword-1] != '\\') { nForword--; } if(nStages * 3 + nAbsoluteFileLen - nForword > MAX_LEN) { omStrRelativeParh = ""; return ; } int nReverse = 0; for(nCount = 0; nCount < nStages; nCount++) { chRelativeFile[nReverse] = '.'; nReverse++; chRelativeFile[nReverse] = '.'; nReverse++; chRelativeFile[nReverse] = '\\'; nReverse++; } strcpy(&chRelativeFile[nReverse], &pchAbsFileName[nForword]); omStrRelativeParh = chRelativeFile; } bool CUtilFunctions::bFindLastSuffix(std::string str, std::string subStr, int& npos) { int nTemp1=0; int nTemp2=0; if(str.find(subStr) == std::string::npos) { return false; } else { do { nTemp1=nTemp2; nTemp2 = str.find(subStr,nTemp1+1); } while(nTemp2!=std::string::npos); npos = nTemp1; return true; } } void CUtilFunctions::Trim(std::string& str , char chChar) { std::string::size_type pos = str.find_last_not_of(chChar); if(pos != std::string::npos) { str.erase(pos + 1); pos = str.find_first_not_of(chChar); if(pos != std::string::npos) { str.erase(0, pos); } } else { str.erase(str.begin(), str.end()); } }
gpl-3.0
BernardoGiordano/PKSM
3ds/include/gui/screen/ExtraSavesSubScreen.hpp
2199
/* * This file is part of PKSM * Copyright (C) 2016-2021 Bernardo Giordano, Admiral Fish, piepie62 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Additional Terms 7.b and 7.c of GPLv3 apply to this file: * * Requiring preservation of specified reasonable legal notices or * author attributions in that material or in the Appropriate Legal * Notices displayed by works containing it. * * Prohibiting misrepresentation of the origin of that material, * or requiring that modified versions of such material be marked in * reasonable ways as different from the original version. */ #ifndef EXTRASAVESSUBSCREEN_HPP #define EXTRASAVESSUBSCREEN_HPP #include "Screen.hpp" #include <unordered_map> #include <vector> class ExtraSavesSubScreen : public Screen { public: enum Group : u8 { RS, E, FRLG, XY, ORAS, SM, USUM, DP, HGSS, Pt, BW, B2W2 }; ExtraSavesSubScreen(Group group); void update(touchPosition* touch) override; void drawTop(void) const override; // Awaiting ideas void drawBottom(void) const override; private: void updateSaves(); std::vector<std::string> currentSaves; std::unordered_map<std::string, std::vector<std::string>> dsCurrentSaves; std::string addString = ""; int selectedSave = -1; int firstSave = 0; int numSaves = 0; Group group; bool secondSelected = false; bool updateConfig = false; }; #endif
gpl-3.0
BerserkerDotNet/Ether
src/Ether.Vsts/Types/PullRequestState.cs
145
namespace Ether.Vsts.Types { public enum PullRequestState { None, Active, Abandoned, Completed } }
gpl-3.0
John000708/Slimefun4
src/me/mrCookieSlime/Slimefun/Objects/SlimefunItem/machines/Refinery.java
3227
package me.mrCookieSlime.Slimefun.Objects.SlimefunItem.machines; import java.util.ArrayList; import java.util.List; import me.mrCookieSlime.CSCoreLibPlugin.general.Inventory.InvUtils; import me.mrCookieSlime.CSCoreLibPlugin.general.Inventory.Item.CustomItem; import me.mrCookieSlime.Slimefun.Lists.RecipeType; import me.mrCookieSlime.Slimefun.Lists.SlimefunItems; import me.mrCookieSlime.Slimefun.Objects.Category; import me.mrCookieSlime.Slimefun.Objects.SlimefunItem.abstractItems.AContainer; import me.mrCookieSlime.Slimefun.Objects.SlimefunItem.abstractItems.MachineHelper; import me.mrCookieSlime.Slimefun.Objects.SlimefunItem.abstractItems.MachineRecipe; import me.mrCookieSlime.Slimefun.Setup.SlimefunManager; import me.mrCookieSlime.Slimefun.api.BlockStorage; import me.mrCookieSlime.Slimefun.api.energy.ChargableBlock; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; public abstract class Refinery extends AContainer { public Refinery(Category category, ItemStack item, String name, RecipeType recipeType, ItemStack[] recipe) { super(category, item, name, recipeType, recipe); } @Override public String getInventoryTitle() { return "&cRefinery"; } @Override public ItemStack getProgressBar() { return new ItemStack(Material.FLINT_AND_STEEL); } @Override public void registerDefaultRecipes() {} @Override public String getMachineIdentifier() { return "REFINERY"; } protected void tick(Block b) { if (isProcessing(b)) { int timeleft = progress.get(b); if (timeleft > 0) { ItemStack item = getProgressBar().clone(); item.setDurability(MachineHelper.getDurability(item, timeleft, processing.get(b).getTicks())); ItemMeta im = item.getItemMeta(); im.setDisplayName(" "); List<String> lore = new ArrayList<String>(); lore.add(MachineHelper.getProgress(timeleft, processing.get(b).getTicks())); lore.add(""); lore.add(MachineHelper.getTimeLeft(timeleft / 2)); im.setLore(lore); item.setItemMeta(im); BlockStorage.getInventory(b).replaceExistingItem(22, item); if (ChargableBlock.isChargable(b)) { if (ChargableBlock.getCharge(b) < getEnergyConsumption()) return; ChargableBlock.addCharge(b, -getEnergyConsumption()); progress.put(b, timeleft - 1); } else progress.put(b, timeleft - 1); } else { BlockStorage.getInventory(b).replaceExistingItem(22, new CustomItem(new ItemStack(Material.BLACK_STAINED_GLASS_PANE), " ")); pushItems(b, processing.get(b).getOutput()); progress.remove(b); processing.remove(b); } } else { for (int slot: getInputSlots()) { if (SlimefunManager.isItemSimiliar(BlockStorage.getInventory(b).getItemInSlot(slot), SlimefunItems.BUCKET_OF_OIL, true)) { MachineRecipe r = new MachineRecipe(40, new ItemStack[0], new ItemStack[] {SlimefunItems.BUCKET_OF_FUEL}); if (!fits(b, r.getOutput())) return; BlockStorage.getInventory(b).replaceExistingItem(slot, InvUtils.decreaseItem(BlockStorage.getInventory(b).getItemInSlot(slot), 1)); processing.put(b, r); progress.put(b, r.getTicks()); break; } } } } }
gpl-3.0
apatry/neo4j-lucene4-index
src/main/java/org/neo4j/index/impl/lucene/IndexClockCache.java
1350
/** * Copyright (c) 2002-2014 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.index.impl.lucene; import java.io.IOException; import org.neo4j.kernel.impl.cache.ClockCache; public class IndexClockCache extends ClockCache<IndexIdentifier, IndexReference> { public IndexClockCache( int maxSize ) { super( "IndexSearcherCache", maxSize ); } @Override public void elementCleaned( IndexReference searcher ) { try { searcher.dispose( true ); } catch ( IOException e ) { throw new RuntimeException( e ); } } }
gpl-3.0
kakarukeys/dengue-viz
webapp/dengue-viz.js
1495
function create_map() { var map = L.map('map').setView([1.36, 103.809357], 12); L.tileLayer('http://{s}.tiles.mapbox.com/v3/kakarukeys.iofn8meo/{z}/{x}/{y}.png', { attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>', maxZoom: 18 }).addTo(map); return map; } function create_marker(d) { return L.marker(d.coords, {title: d.name}); } function process_cluster_data(cluster_data) { var cases = cluster_data.snapshots[0].cases; return _.map(cases, create_marker); } function process_marker_data(marker_data) { var sites = marker_data.groups[0].sites; return _.map(sites, function(d) { return create_marker(d).bindPopup("<b>"+d.name+"</b>"); }); } function create_cluster_layer(markers) { return L.markerClusterGroup().addLayers(markers); } function create_marker_layer(markers) { return L.layerGroup(markers); } var cluster_layer = $.getJSON("cluster_data.json") .then(process_cluster_data) .then(create_cluster_layer), marker_layer = $.getJSON("marker_data.json") .then(process_marker_data) .then(create_marker_layer), map = create_map(); function add_layer(layer) { map.addLayer(layer); } cluster_layer.done(add_layer); marker_layer.done(add_layer);
gpl-3.0
SkyFireArchives/SkyFireEMU_420
src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp
28277
/* * Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2005-2012 MaNGOS <http://www.getmangos.com/> * Copyright (C) 2008-2012 Trinity <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ObjectMgr.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "SpellScript.h" #include "SpellAuras.h" #include "icecrown_citadel.h" // KNOWN BUGS: // ~ No Slime Spray animation directly at target spot enum Texts { SAY_PRECIOUS_DIES = 0, SAY_AGGRO = 1, EMOTE_SLIME_SPRAY = 2, SAY_SLIME_SPRAY = 3, EMOTE_UNSTABLE_EXPLOSION = 4, SAY_UNSTABLE_EXPLOSION = 5, SAY_KILL = 6, SAY_BERSERK = 7, SAY_DEATH = 8, }; enum Spells { // Rotface SPELL_SLIME_SPRAY = 69508, // every 20 seconds SPELL_MUTATED_INFECTION = 69674, // hastens every 1:30 // Oozes SPELL_LITTLE_OOZE_COMBINE = 69537, // combine 2 Small Oozes SPELL_LARGE_OOZE_COMBINE = 69552, // combine 2 Large Oozes SPELL_LARGE_OOZE_BUFF_COMBINE = 69611, // combine Large and Small Ooze SPELL_OOZE_MERGE = 69889, // 2 Small Oozes summon a Large Ooze SPELL_WEAK_RADIATING_OOZE = 69750, // passive damage aura - small SPELL_RADIATING_OOZE = 69760, // passive damage aura - large SPELL_UNSTABLE_OOZE = 69558, // damage boost and counter for explosion SPELL_GREEN_ABOMINATION_HITTIN__YA_PROC = 70001, // prevents getting hit by infection SPELL_UNSTABLE_OOZE_EXPLOSION = 69839, SPELL_STICKY_OOZE = 69774, SPELL_UNSTABLE_OOZE_EXPLOSION_TRIGGER = 69832, // Precious SPELL_MORTAL_WOUND = 71127, SPELL_DECIMATE = 71123, }; #define MUTATED_INFECTION RAID_MODE<int32>(69674, 71224, 73022, 73023) enum Events { EVENT_SLIME_SPRAY = 1, EVENT_HASTEN_INFECTIONS = 2, EVENT_MUTATED_INFECTION = 3, EVENT_DECIMATE = 4, EVENT_MORTAL_WOUND = 5, EVENT_STICKY_OOZE = 6, EVENT_UNSTABLE_DESPAWN = 7, }; class boss_rotface : public CreatureScript { public: boss_rotface() : CreatureScript("boss_rotface") { } struct boss_rotfaceAI : public BossAI { boss_rotfaceAI(Creature* creature) : BossAI(creature, DATA_ROTFACE) { infectionStage = 0; infectionCooldown = 14000; } void InitializeAI() { if (!instance || static_cast<InstanceMap*>(me->GetMap())->GetScriptId() != GetScriptId(ICCScriptName)) me->IsAIEnabled = false; else if (!me->isDead()) Reset(); } void Reset() { _Reset(); events.ScheduleEvent(EVENT_SLIME_SPRAY, 20000); events.ScheduleEvent(EVENT_HASTEN_INFECTIONS, 90000); events.ScheduleEvent(EVENT_MUTATED_INFECTION, 14000); infectionStage = 0; infectionCooldown = 14000; } void EnterCombat(Unit* who) { if (!instance->CheckRequiredBosses(DATA_ROTFACE, who->ToPlayer())) { EnterEvadeMode(); instance->DoCastSpellOnPlayers(LIGHT_S_HAMMER_TELEPORT); return; } me->setActive(true); Talk(SAY_AGGRO); if (Creature* professor = Unit::GetCreature(*me, instance->GetData64(DATA_PROFESSOR_PUTRICIDE))) professor->AI()->DoAction(ACTION_ROTFACE_COMBAT); DoZoneInCombat(); } void JustDied(Unit* /*killer*/) { _JustDied(); Talk(SAY_DEATH); if (Creature* professor = Unit::GetCreature(*me, instance->GetData64(DATA_PROFESSOR_PUTRICIDE))) professor->AI()->DoAction(ACTION_ROTFACE_DEATH); } void JustReachedHome() { _JustReachedHome(); instance->SetBossState(DATA_ROTFACE, FAIL); instance->SetData(DATA_OOZE_DANCE_ACHIEVEMENT, uint32(true)); // reset } void KilledUnit(Unit* victim) { if (victim->GetTypeId() == TYPEID_PLAYER) Talk(SAY_KILL); } void EnterEvadeMode() { ScriptedAI::EnterEvadeMode(); if (Creature* professor = Unit::GetCreature(*me, instance->GetData64(DATA_PROFESSOR_PUTRICIDE))) professor->AI()->EnterEvadeMode(); } void SpellHitTarget(Unit* /*target*/, SpellEntry const* spell) { if (spell->Id == SPELL_SLIME_SPRAY) Talk(SAY_SLIME_SPRAY); } void MoveInLineOfSight(Unit* /*who*/) { // don't enter combat } Unit* GetAuraEffectTriggerTarget(uint32 spellId, uint8 /*effIndex*/) { if (spellId == SPELL_SLIME_SPRAY) { for (std::list<uint64>::iterator itr = summons.begin(); itr != summons.end();) { Creature *summon = Unit::GetCreature(*me, *itr); if (!summon) summons.erase(itr++); else if (summon->GetEntry() == NPC_OOZE_SPRAY_STALKER) return summon; else ++itr; } } return NULL; } void UpdateAI(const uint32 diff) { if (!UpdateVictim() || !CheckInRoom()) return; events.Update(diff); if (me->HasUnitState(UNIT_STAT_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_SLIME_SPRAY: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true)) { Position pos; target->GetPosition(&pos); DoSummon(NPC_OOZE_SPRAY_STALKER, pos, 8000, TEMPSUMMON_TIMED_DESPAWN); Talk(EMOTE_SLIME_SPRAY); DoCastAOE(SPELL_SLIME_SPRAY); } events.ScheduleEvent(EVENT_SLIME_SPRAY, 20000); break; case EVENT_HASTEN_INFECTIONS: if (infectionStage++ < 4) { infectionCooldown -= 2000; events.ScheduleEvent(EVENT_HASTEN_INFECTIONS, 90000); } break; case EVENT_MUTATED_INFECTION: { Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true, -MUTATED_INFECTION); if (!target) target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true, -MUTATED_INFECTION); if (target) me->CastCustomSpell(SPELL_MUTATED_INFECTION, SPELLVALUE_MAX_TARGETS, 1, target, false); events.ScheduleEvent(EVENT_MUTATED_INFECTION, infectionCooldown); break; } default: break; } } DoMeleeAttackIfReady(); } private: uint32 infectionCooldown; uint8 infectionStage; }; CreatureAI* GetAI(Creature* creature) const { return new boss_rotfaceAI(creature); } }; class npc_little_ooze : public CreatureScript { public: npc_little_ooze() : CreatureScript("npc_little_ooze") { } struct npc_little_oozeAI : public ScriptedAI { npc_little_oozeAI(Creature* creature) : ScriptedAI(creature) { } void IsSummonedBy(Unit* summoner) { DoCast(me, SPELL_LITTLE_OOZE_COMBINE, true); DoCast(me, SPELL_WEAK_RADIATING_OOZE, true); events.ScheduleEvent(EVENT_STICKY_OOZE, 5000); me->AddThreat(summoner, 500000.0f); } void JustDied(Unit* /*killer*/) { me->DespawnOrUnsummon(); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); if (events.ExecuteEvent() == EVENT_STICKY_OOZE) { DoCastVictim(SPELL_STICKY_OOZE); events.ScheduleEvent(EVENT_STICKY_OOZE, 15000); } DoMeleeAttackIfReady(); } private: EventMap events; }; CreatureAI* GetAI(Creature* creature) const { return new npc_little_oozeAI(creature); } }; class npc_big_ooze : public CreatureScript { public: npc_big_ooze() : CreatureScript("npc_big_ooze") { } struct npc_big_oozeAI : public ScriptedAI { npc_big_oozeAI(Creature* creature) : ScriptedAI(creature) { } void IsSummonedBy(Unit* /*summoner*/) { DoCast(me, SPELL_LARGE_OOZE_COMBINE, true); DoCast(me, SPELL_LARGE_OOZE_BUFF_COMBINE, true); DoCast(me, SPELL_RADIATING_OOZE, true); DoCast(me, SPELL_UNSTABLE_OOZE, true); DoCast(me, SPELL_GREEN_ABOMINATION_HITTIN__YA_PROC, true); events.ScheduleEvent(EVENT_STICKY_OOZE, 5000); // register in Rotface's summons - not summoned with Rotface as owner if (InstanceScript* instance = me->GetInstanceScript()) if (Creature* rotface = Unit::GetCreature(*me, instance->GetData64(DATA_ROTFACE))) rotface->AI()->JustSummoned(me); } void JustDied(Unit* /*killer*/) { if (InstanceScript* instance = me->GetInstanceScript()) if (Creature* rotface = Unit::GetCreature(*me, instance->GetData64(DATA_ROTFACE))) rotface->AI()->SummonedCreatureDespawn(me); me->DespawnOrUnsummon(); } void DoAction(const int32 action) { if (action == EVENT_STICKY_OOZE) events.CancelEvent(EVENT_STICKY_OOZE); else if (action == EVENT_UNSTABLE_DESPAWN) { me->RemoveAllAuras(); me->SetVisible(false); events.Reset(); events.ScheduleEvent(EVENT_UNSTABLE_DESPAWN, 60000); } } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_STICKY_OOZE: DoCastVictim(SPELL_STICKY_OOZE); events.ScheduleEvent(EVENT_STICKY_OOZE, 15000); break; case EVENT_UNSTABLE_DESPAWN: me->Kill(me); break; default: break; } } if (me->IsVisible()) DoMeleeAttackIfReady(); } private: EventMap events; }; CreatureAI* GetAI(Creature* creature) const { return new npc_big_oozeAI(creature); } }; class npc_precious_icc : public CreatureScript { public: npc_precious_icc() : CreatureScript("npc_precious_icc") { } struct npc_precious_iccAI : public ScriptedAI { npc_precious_iccAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } void Reset() { events.Reset(); events.ScheduleEvent(EVENT_DECIMATE, urand(20000, 25000)); events.ScheduleEvent(EVENT_MORTAL_WOUND, urand(3000, 7000)); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STAT_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_DECIMATE: DoCastVictim(SPELL_DECIMATE); events.ScheduleEvent(EVENT_DECIMATE, urand(20000, 25000)); break; case EVENT_MORTAL_WOUND: DoCastVictim(SPELL_MORTAL_WOUND); events.ScheduleEvent(EVENT_MORTAL_WOUND, urand(10000, 12500)); break; default: break; } } DoMeleeAttackIfReady(); } void JustDied(Unit* /*who*/) { uint64 rotfaceGUID = instance ? instance->GetData64(DATA_ROTFACE) : 0; if (Creature* rotface = Unit::GetCreature(*me, rotfaceGUID)) if (rotface->isAlive()) rotface->AI()->Talk(SAY_PRECIOUS_DIES); } private: EventMap events; InstanceScript* instance; }; CreatureAI* GetAI(Creature* creature) const { return new npc_precious_iccAI(creature); } }; class spell_rotface_ooze_flood : public SpellScriptLoader { public: spell_rotface_ooze_flood() : SpellScriptLoader("spell_rotface_ooze_flood") { } class spell_rotface_ooze_flood_SpellScript : public SpellScript { PrepareSpellScript(spell_rotface_ooze_flood_SpellScript); void HandleScript(SpellEffIndex /*effIndex*/) { if (!GetHitUnit()) return; std::list<Creature*> list; GetHitUnit()->GetCreatureListWithEntryInGrid(list, GetHitUnit()->GetEntry(), 12.5f); list.sort(Trinity::ObjectDistanceOrderPred(GetHitUnit())); GetHitUnit()->CastSpell(list.back(), uint32(GetEffectValue()), false, NULL, NULL, GetOriginalCaster() ? GetOriginalCaster()->GetGUID() : 0); } void FilterTargets(std::list<Unit*>& targetList) { // get 2 targets except 2 nearest targetList.sort(Trinity::ObjectDistanceOrderPred(GetCaster())); targetList.resize(4); while (targetList.size() > 2) targetList.pop_front(); } void Register() { OnEffect += SpellEffectFn(spell_rotface_ooze_flood_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); OnUnitTargetSelect += SpellUnitTargetFn(spell_rotface_ooze_flood_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_AREA_ENTRY_SRC); } }; SpellScript* GetSpellScript() const { return new spell_rotface_ooze_flood_SpellScript(); } }; class spell_rotface_little_ooze_combine : public SpellScriptLoader { public: spell_rotface_little_ooze_combine() : SpellScriptLoader("spell_rotface_little_ooze_combine") { } class spell_rotface_little_ooze_combine_SpellScript : public SpellScript { PrepareSpellScript(spell_rotface_little_ooze_combine_SpellScript); void HandleScript(SpellEffIndex /*effIndex*/) { if (!(GetHitCreature() && GetHitUnit()->isAlive())) return; GetCaster()->RemoveAurasDueToSpell(SPELL_LITTLE_OOZE_COMBINE); GetHitCreature()->RemoveAurasDueToSpell(SPELL_LITTLE_OOZE_COMBINE); GetHitCreature()->CastSpell(GetCaster(), SPELL_OOZE_MERGE, true); GetHitCreature()->DespawnOrUnsummon(); } void Register() { OnEffect += SpellEffectFn(spell_rotface_little_ooze_combine_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_rotface_little_ooze_combine_SpellScript(); } }; class spell_rotface_large_ooze_combine : public SpellScriptLoader { public: spell_rotface_large_ooze_combine() : SpellScriptLoader("spell_rotface_large_ooze_combine") { } class spell_rotface_large_ooze_combine_SpellScript : public SpellScript { PrepareSpellScript(spell_rotface_large_ooze_combine_SpellScript); void HandleScript(SpellEffIndex /*effIndex*/) { if (!(GetHitCreature() && GetHitCreature()->isAlive())) return; if (Aura* unstable = GetCaster()->GetAura(SPELL_UNSTABLE_OOZE)) { if (Aura* targetAura = GetHitCreature()->GetAura(SPELL_UNSTABLE_OOZE)) unstable->ModStackAmount(targetAura->GetStackAmount()); else unstable->ModStackAmount(1); // no idea why, but this does not trigger explosion on retail (only small+large do) } // just for safety GetHitCreature()->RemoveAurasDueToSpell(SPELL_LARGE_OOZE_BUFF_COMBINE); GetHitCreature()->RemoveAurasDueToSpell(SPELL_LARGE_OOZE_COMBINE); GetHitCreature()->DespawnOrUnsummon(); } void Register() { OnEffect += SpellEffectFn(spell_rotface_large_ooze_combine_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_rotface_large_ooze_combine_SpellScript(); } }; class spell_rotface_large_ooze_buff_combine : public SpellScriptLoader { public: spell_rotface_large_ooze_buff_combine() : SpellScriptLoader("spell_rotface_large_ooze_buff_combine") { } class spell_rotface_large_ooze_buff_combine_SpellScript : public SpellScript { PrepareSpellScript(spell_rotface_large_ooze_buff_combine_SpellScript); void HandleScript(SpellEffIndex /*effIndex*/) { if (!(GetHitCreature() && GetHitCreature()->isAlive())) return; if (Aura* unstable = GetCaster()->GetAura(SPELL_UNSTABLE_OOZE)) { uint8 newStack = uint8(unstable->GetStackAmount()+1); unstable->SetStackAmount(newStack); // explode! if (newStack >= 5) { GetCaster()->RemoveAurasDueToSpell(SPELL_LARGE_OOZE_BUFF_COMBINE); GetCaster()->RemoveAurasDueToSpell(SPELL_LARGE_OOZE_COMBINE); if (InstanceScript* instance = GetCaster()->GetInstanceScript()) if (Creature* rotface = Unit::GetCreature(*GetCaster(), instance->GetData64(DATA_ROTFACE))) if (rotface->isAlive()) { rotface->AI()->Talk(EMOTE_UNSTABLE_EXPLOSION); rotface->AI()->Talk(SAY_UNSTABLE_EXPLOSION); } if (Creature* cre = GetCaster()->ToCreature()) cre->AI()->DoAction(EVENT_STICKY_OOZE); GetCaster()->CastSpell(GetCaster(), SPELL_UNSTABLE_OOZE_EXPLOSION, false, NULL, NULL, GetCaster()->GetGUID()); if (InstanceScript* instance = GetCaster()->GetInstanceScript()) instance->SetData(DATA_OOZE_DANCE_ACHIEVEMENT, uint32(false)); } } GetHitCreature()->DespawnOrUnsummon(); } void Register() { OnEffect += SpellEffectFn(spell_rotface_large_ooze_buff_combine_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_rotface_large_ooze_buff_combine_SpellScript(); } }; class spell_rotface_unstable_ooze_explosion_init : public SpellScriptLoader { public: spell_rotface_unstable_ooze_explosion_init() : SpellScriptLoader("spell_rotface_unstable_ooze_explosion_init") { } class spell_rotface_unstable_ooze_explosion_init_SpellScript : public SpellScript { PrepareSpellScript(spell_rotface_unstable_ooze_explosion_init_SpellScript); bool Validate(SpellEntry const* /*spell*/) { if (!sSpellStore.LookupEntry(SPELL_UNSTABLE_OOZE_EXPLOSION_TRIGGER)) return false; return true; } void HandleCast(SpellEffIndex effIndex) { PreventHitEffect(effIndex); if (!GetHitUnit()) return; float x, y, z; GetHitUnit()->GetPosition(x, y, z); Creature* dummy = GetCaster()->SummonCreature(NPC_UNSTABLE_EXPLOSION_STALKER, x, y, z, 0.0f, TEMPSUMMON_TIMED_DESPAWN, 60000); GetCaster()->CastSpell(dummy, SPELL_UNSTABLE_OOZE_EXPLOSION_TRIGGER, true); } void Register() { OnEffect += SpellEffectFn(spell_rotface_unstable_ooze_explosion_init_SpellScript::HandleCast, EFFECT_0, SPELL_EFFECT_FORCE_CAST); } }; SpellScript* GetSpellScript() const { return new spell_rotface_unstable_ooze_explosion_init_SpellScript(); } }; class spell_rotface_unstable_ooze_explosion : public SpellScriptLoader { public: spell_rotface_unstable_ooze_explosion() : SpellScriptLoader("spell_rotface_unstable_ooze_explosion") { } class spell_rotface_unstable_ooze_explosion_SpellScript : public SpellScript { PrepareSpellScript(spell_rotface_unstable_ooze_explosion_SpellScript); void CheckTarget(SpellEffIndex effIndex) { PreventHitDefaultEffect(EFFECT_0); if (!GetTargetUnit()) return; uint32 triggered_spell_id = GetSpellInfo()->EffectTriggerSpell[effIndex]; float x, y, z; GetTargetUnit()->GetPosition(x, y, z); // let Rotface handle the cast - caster dies before this executes if (InstanceScript* script = GetTargetUnit()->GetInstanceScript()) if (Creature* rotface = script->instance->GetCreature(script->GetData64(DATA_ROTFACE))) rotface->CastSpell(x, y, z, triggered_spell_id, true, NULL, NULL, GetCaster()->GetGUID(), GetTargetUnit()); } void Register() { OnEffect += SpellEffectFn(spell_rotface_unstable_ooze_explosion_SpellScript::CheckTarget, EFFECT_0, SPELL_EFFECT_TRIGGER_MISSILE); } }; SpellScript* GetSpellScript() const { return new spell_rotface_unstable_ooze_explosion_SpellScript(); } }; class spell_rotface_unstable_ooze_explosion_suicide : public SpellScriptLoader { public: spell_rotface_unstable_ooze_explosion_suicide() : SpellScriptLoader("spell_rotface_unstable_ooze_explosion_suicide") { } class spell_rotface_unstable_ooze_explosion_suicide_AuraScript : public AuraScript { PrepareAuraScript(spell_rotface_unstable_ooze_explosion_suicide_AuraScript); void DespawnSelf(AuraEffect const* /*aurEff*/) { PreventDefaultAction(); Unit* target = GetTarget(); if (target->GetTypeId() != TYPEID_UNIT) return; target->ToCreature()->AI()->DoAction(EVENT_UNSTABLE_DESPAWN); } void Register() { OnEffectPeriodic += AuraEffectPeriodicFn(spell_rotface_unstable_ooze_explosion_suicide_AuraScript::DespawnSelf, EFFECT_2, SPELL_AURA_PERIODIC_TRIGGER_SPELL); } }; AuraScript* GetAuraScript() const { return new spell_rotface_unstable_ooze_explosion_suicide_AuraScript(); } }; class spell_rotface_slime_spray : public SpellScriptLoader { public: spell_rotface_slime_spray() : SpellScriptLoader("spell_rotface_slime_spray") { } class spell_rotface_slime_spray_SpellScript : public SpellScript { PrepareSpellScript(spell_rotface_slime_spray_SpellScript); bool Validate(SpellEntry const* /*spell*/) { if (!sSpellStore.LookupEntry(SPELL_GREEN_BLIGHT_RESIDUE)) return false; return true; } void ExtraEffect() { if (GetHitUnit()->HasAura(SPELL_GREEN_BLIGHT_RESIDUE)) return; GetHitUnit()->CastSpell(GetHitUnit(), SPELL_GREEN_BLIGHT_RESIDUE, true); } void Register() { AfterHit += SpellHitFn(spell_rotface_slime_spray_SpellScript::ExtraEffect); } }; SpellScript* GetSpellScript() const { return new spell_rotface_slime_spray_SpellScript(); } }; void AddSC_boss_rotface() { new boss_rotface(); new npc_little_ooze(); new npc_big_ooze(); new npc_precious_icc(); new spell_rotface_ooze_flood(); new spell_rotface_little_ooze_combine(); new spell_rotface_large_ooze_combine(); new spell_rotface_large_ooze_buff_combine(); new spell_rotface_unstable_ooze_explosion_init(); new spell_rotface_unstable_ooze_explosion(); new spell_rotface_unstable_ooze_explosion_suicide(); new spell_rotface_slime_spray(); }
gpl-3.0
meronpan3419/nicolive-kai-plus
NicoLive/forms/Rename/Rename.cs
3901
//------------------------------------------------------------------------- // コテハンリネームダイアログ // // Copyright (c) 金時豆(http://ch.nicovideo.jp/community/co48276) // $Id$ //------------------------------------------------------------------------- using System; using System.Windows.Forms; using System.Threading; //------------------------------------------------------------------------- // クラス実装 //------------------------------------------------------------------------- namespace NicoLive { public partial class Rename : Form { private Form1 mOwner = null; private string mID = null; private string mUserName = null; public Form1 MyOwner { set { mOwner = value; } get { return mOwner; } } public string ID { set { mID = value; } get { return mID; } } public string UserName { set { mUserName = value; } get { return mUserName; } } //------------------------------------------------------------------------- // コンストラクタ //------------------------------------------------------------------------- public Rename() { InitializeComponent(); } //------------------------------------------------------------------------- // フォームロード時 //------------------------------------------------------------------------- private void Rename_Load(object sender, EventArgs e) { // センタリング this.Top = (this.mOwner.Height - this.Height) / 2; this.Left = (this.mOwner.Width - this.Width) / 2; this.mName.Text = mUserName; this.lID.Text = mID; int r; mGetUserName.Enabled = int.TryParse(mID, out r); // 184じゃない時だけ } //------------------------------------------------------------------------- // OKボタン //------------------------------------------------------------------------- private void mOK_Click(object sender, EventArgs e) { if (mOwner != null) { mOwner.SetNickname(this.mID, mName.Text); } Close(); } //------------------------------------------------------------------------- // キャンセルボタン //------------------------------------------------------------------------- private void mCancel_Click(object sender, EventArgs e) { Close(); } private void mGetUserName_Click(object sender, EventArgs e) { Thread th = new Thread(delegate() { this.Invoke((Action)delegate() { mGetUserName.Enabled = false; mGetUserName.Text = "取得中…"; }); Nico mNico = Nico.Instance; string name = mNico.GetUsername(mID); this.Invoke((Action)delegate() { this.mName.Text = name; mGetUserName.Enabled = true; mGetUserName.Text = "自動取得"; }); }); th.Name = "rename.mGetUserName()"; th.Start(); } } } //------------------------------------------------------------------------- // コテハンリネームダイアログ // // Copyright (c) 金時豆(http://ch.nicovideo.jp/community/co48276) //-------------------------------------------------------------------------
gpl-3.0
berserkerbernhard/Lidskjalv
code/networkmonitor/modules/interfaces/interface.py
692
import os import time import shutil import dialog from modules.lidskjalvstorage import LidskjalvStorage # from modules.lidskjalvloggingtools import loginfo # logerror from modules.sitegrouphosttools import SiteGroupHostTools # interfaces[int(time.time()*10)] = {'name': 'unknown', 'mac': '123456789012', 'ip':['10.0.0.1', '192.168.0.1']} class Interface(SiteGroupHostTools): def __init__(self): self.ls = LidskjalvStorage() self.d = dialog.Dialog(dialog="dialog") self.storage_path = os.path.expanduser("~/LidskjalvData") self.sleep = 0.1 def add_interface(self, interface): pass if __name__ == '__main__': print("Interfaces class.")
gpl-3.0
naxd1532/avikonor
model/facade/action/CreateTasksAction.php
2878
<?php /* * Copyright (C) 2013 Igalia, S.L. <info@igalia.com> * * This file is part of PhpReport. * * PhpReport 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. * * PhpReport 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 PhpReport. If not, see <http://www.gnu.org/licenses/>. */ /** File for CreateTasksAction * * This file just contains {@link CreateTasksAction}. * * @filesource * @package PhpReport * @subpackage facade * @author Jacobo Aragunde Pérez <jaragunde@igalia.com> */ include_once(PHPREPORT_ROOT . '/model/facade/action/Action.php'); include_once(PHPREPORT_ROOT . '/model/dao/DAOFactory.php'); include_once(PHPREPORT_ROOT . '/model/vo/TaskVO.php'); /** Create Tasks Action * * This action is used for creating multiple Task objects. * * @package PhpReport * @subpackage facade * @author Jacobo Aragunde Pérez <jaragunde@igalia.com> */ class CreateTasksAction extends Action { /** The Task * * This variable contains an array with the TaskVO objects we want to create. * * @var array<TaskVO> */ private $tasks; /** CreateTasksAction constructor. * * This is just the constructor of this action. * * @param array $tasks an array with the TaskVO objects we want to create. */ public function __construct($tasks) { $this->tasks=$tasks; $this->preActionParameter="CREATE_TASKS_PREACTION"; $this->postActionParameter="CREATE_TASKS_POSTACTION"; } /** Specific code execute. * * Runs the action itself. * * @return int it just indicates if there was any error (<i>-1</i>) * or not (<i>0</i>). */ protected function doExecute() { $configDao = DAOFactory::getConfigDAO(); $taskDao = DAOFactory::getTaskDAO(); $discardedTasks = array(); //first check permission on task write foreach ($this->tasks as $i => $task) { if(!$configDao->isWriteAllowedForDate($task->getDate())) { $discardedTasks[] = $task; unset($this->tasks[$i]); } } if ($taskDao->batchCreate($this->tasks) < count($this->tasks)) { return -1; } //TODO: do something meaningful with the list of discarded tasks if (empty($discardedTasks)) { return 0; } else { return -1; } } }
gpl-3.0
cws06099/MinecraftPEServer
app/src/main/java/net/fengberd/minecraftpe_server/ServerUtils.java
5074
package net.fengberd.minecraftpe_server; import java.io.*; import java.util.*; import java.nio.charset.Charset; import android.content.Context; public final class ServerUtils { public static Context mContext; private static Process serverProcess; private static OutputStream stdin; private static InputStream stdout; public static void setContext(Context mContext) { ServerUtils.mContext=mContext; } public static String getAppDirectory() { return mContext.getApplicationInfo().dataDir; } public static String getDataDirectory() { String dir=android.os.Environment.getExternalStorageDirectory().getPath() + (MainActivity.nukkitMode?"/Nukkit":"/PocketMine"); new File(dir).mkdirs(); return dir; } public static void killServer() { try { Runtime.getRuntime().exec(getAppDirectory() + "/busybox killall -9 " +(MainActivity.nukkitMode?"java":"php")).waitFor(); } catch(Exception e) { } } public static Boolean isRunning() { try { serverProcess.exitValue(); } catch(Exception e) { return true; } return false; } final public static void runServer() { File f = new File(getDataDirectory(),"/tmp"); if(!f.exists()) { f.mkdir(); } else if(!f.isDirectory()) { f.delete(); f.mkdir(); } setPermission(); String file = "/Nukkit.jar"; if(!MainActivity.nukkitMode) { if(new File(getDataDirectory() + "/PocketMine-MP.phar").exists()) { file="/PocketMine-MP.phar"; } else { file = "/src/pocketmine/PocketMine.php"; } } File ini=new File(getDataDirectory() + "/php.ini"); if(!MainActivity.nukkitMode && !ini.exists()) { try { ini.createNewFile(); FileOutputStream os=new FileOutputStream(ini); os.write("phar.readonly=0\nphar.require_hash=1\ndate.timezone=Asia/Shanghai\nshort_open_tag=0\nasp_tags=0\nopcache.enable=1\nopcache.enable_cli=1\nopcache.save_comments=1\nopcache.fast_shutdown=0\nopcache.max_accelerated_files=4096\nopcache.interned_strings_buffer=8\nopcache.memory_consumption=128\nopcache.optimization_level=0xffffffff".getBytes("UTF8")); os.close(); } catch(Exception e) { } } String[] args=null; if(MainActivity.nukkitMode) { args=new String[] { getAppDirectory() + "/java/jre/bin/java", "-jar", getDataDirectory() + file, MainActivity.ansiMode?"enable-ansi":"disable-ansi", "disable-jline" }; } else { args=new String[] { getAppDirectory() + "/php", "-c", getDataDirectory() + "/php.ini", getDataDirectory() + file, MainActivity.ansiMode?"--enable-ansi":"--disable-ansi" }; } ProcessBuilder builder = new ProcessBuilder(args); builder.redirectErrorStream(true); builder.directory(new File(getDataDirectory())); Map<String,String> env=builder.environment(); env.put("TMPDIR",getDataDirectory() + "/tmp"); try { serverProcess=builder.start(); stdout=serverProcess.getInputStream(); stdin=serverProcess.getOutputStream(); Thread tMonitor = new Thread() { public void run() { InputStreamReader reader = new InputStreamReader(stdout,Charset.forName("UTF-8")); BufferedReader br = new BufferedReader(reader); while(isRunning()) { try { char[] buffer = new char[8192]; int size = 0; while((size = br.read(buffer,0,buffer.length)) != -1) { StringBuilder s = new StringBuilder(); for(int i = 0; i < size; i++) { char c = buffer[i]; if(c == '\r') { continue; } if(c == '\n' || c == '\u0007') { String line = s.toString(); if(c == '\u0007' || line.startsWith("\u001B]0;")) { //Do nothing. } else { ConsoleActivity.log(line); } s=new StringBuilder(); } else { s.append(buffer[i]); } } } } catch(Exception e) { e.printStackTrace(); } finally { try { br.close(); } catch(Exception e) { e.printStackTrace(); } } } ConsoleActivity.log("[PE Server] Server was stopped."); MainActivity.stopNotifyService(); } }; tMonitor.start(); } catch(Exception e) { ConsoleActivity.log("[PE Server] Unable to start "+(MainActivity.nukkitMode?"Java":"PHP")+"."); ConsoleActivity.log(e.toString()); MainActivity.stopNotifyService(); killServer(); } return; } final static public void setPermission() { try { if(MainActivity.nukkitMode) { Runtime.getRuntime().exec("./busybox chmod -R 755 java",new String[0],new File(getAppDirectory())).waitFor(); } else { new File(getAppDirectory()+"/php").setExecutable(true,true); } } catch(Exception e) { } } public static void writeCommand(String Cmd) { try { stdin.write((Cmd + "\r\n").getBytes()); stdin.flush(); } catch(Exception e) { } } }
gpl-3.0
maurociancio/parallel-editor
src/parallel-editor-common/src/main/scala/ar/noxit/paralleleditor/common/converter/MessageConverter.scala
1531
/* * A real-time collaborative tool to develop files over the network. * Copyright (C) 2010 Mauro Ciancio and Leandro Gilioli * {maurociancio,legilioli} at gmail dot 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ar.noxit.paralleleditor.common.converter import ar.noxit.paralleleditor.common.operation.EditOperation import ar.noxit.paralleleditor.common.Message import ar.noxit.paralleleditor.common.messages.SyncOperation trait MessageConverter { def convert(syncOperation: SyncOperation): Message[EditOperation] } class DefaultMessageConverter(val remoteOpConverter: RemoteOperationConverter) extends MessageConverter { override def convert(syncOperation: SyncOperation) = { val op = remoteOpConverter.convert(syncOperation.payload) val syncStatus = syncOperation.syncSatus Message(op, syncStatus.myMsgs, syncStatus.otherMessages) } }
gpl-3.0
martlin2cz/jaxon
src/main/java/cz/martlin/jaxon/jack/data/values/JackNullValue.java
600
package cz.martlin.jaxon.jack.data.values; import java.io.PrintStream; import cz.martlin.jaxon.jack.data.design.JackValueType; import cz.martlin.jaxon.utils.Utils; /** * Represents null value. * * @author martin * */ public class JackNullValue extends JackValue { public static final JackNullValue INSTANCE = new JackNullValue(); public JackNullValue() { super(new JackValueType(null)); } @Override public String toString() { return "JackNullValue []"; } @Override public void print(int padding, PrintStream out) { Utils.printPaddedLine(out, padding, "Null value"); } }
gpl-3.0
Washi1337/Emux
Emux.GameBoy/Cartridge/MemoryBankController1.cs
3741
using System; namespace Emux.GameBoy.Cartridge { public class MemoryBankController1 : IMemoryBankController { private readonly IFullyAccessibleCartridge _cartridge; private readonly byte[] _romBank = new byte[0x4000]; private int _romBankIndex; private int _ramBankIndex; private bool _romRamMode; public MemoryBankController1(IFullyAccessibleCartridge cartridge) { _cartridge = cartridge ?? throw new ArgumentNullException(nameof(cartridge)); } public void Initialize() { Reset(); } public void Reset() { SwitchRomBank(1); } public void Shutdown() { } public byte ReadByte(ushort address) { if (address < 0x4000) return _cartridge.ReadFromAbsoluteAddress(address); if (address < 0x8000) return _romBank[address - 0x4000]; if (_cartridge.ExternalMemory.IsActive && address >= 0xA000 && address <= 0xBFFF) return _cartridge.ExternalMemory.ReadByte(address - 0xA000 + GetRamOffset()); return 0; } public void ReadBytes(ushort address, byte[] buffer, int bufferOffset, int length) { if (address < 0x4000) _cartridge.ReadFromAbsoluteAddress(address, buffer, bufferOffset, length); else if (address < 0x8000) Buffer.BlockCopy(_romBank, address - 0x4000, buffer, bufferOffset, length); if (_cartridge.ExternalMemory.IsActive && address >= 0xA000 && address <= 0xBFFF) _cartridge.ExternalMemory.ReadBytes(address - 0xA000 + GetRamOffset(), buffer, bufferOffset, length); } public void WriteByte(ushort address, byte value) { if (address < 0x2000) { if ((value & 0xA) == 0xA) _cartridge.ExternalMemory.Activate(); else _cartridge.ExternalMemory.Deactivate(); } else if (address < 0x4000) SwitchRomBank(value & 0x1F); else if (address < 0x6000) SwitchRamBank(value & 0x3); else if (address < 0x8000) SwitchRomRamMode(value); else if (_cartridge.ExternalMemory.IsActive && address >= 0xA000 && address - 0xA000 < _cartridge.ExternalRamSize) _cartridge.ExternalMemory.WriteByte(address - 0xA000 + GetRamOffset(), value); } private void SwitchRomRamMode(byte value) { bool romRamMode = value == 1; if (_romRamMode != romRamMode) { _romRamMode = romRamMode; UpdateRomBank(); } } private void SwitchRamBank(int index) { if (_ramBankIndex != index) { _ramBankIndex = index; UpdateRomBank(); } } private void SwitchRomBank(int index) { if (_romBankIndex != index) { if (index == 0 || index == 0x20 || index == 0x40 || index == 0x60) index++; _romBankIndex = index; UpdateRomBank(); } } private void UpdateRomBank() { int index = _romBankIndex; if (_romRamMode) index |= _ramBankIndex << 5; _cartridge.ReadFromAbsoluteAddress(_romBank.Length * index, _romBank, 0, _romBank.Length); } private int GetRamOffset() { return _ramBankIndex * 0x2000; } } }
gpl-3.0
voidALPHA/cgc_viz
Assets/PayloadSelection/BoundAndAssociatedMutable.cs
1114
// Copyright 2017 voidALPHA, Inc. // This file is part of the Haxxis video generation system and is provided // by voidALPHA in support of the Cyber Grand Challenge. // Haxxis 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. // Haxxis 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 // Haxxis. If not, see <http://www.gnu.org/licenses/>. using Mutation; using Visualizers; namespace PayloadSelection { //public class BoundAndAssociatedMutable //{ // public BoundingBox Bound { get; set; } // public MutableObject Mutable { get; set; } // // public BoundAndAssociatedMutable(BoundingBox bound, MutableObject mutable) // { // Bound = bound; // Mutable = mutable; // } //} }
gpl-3.0
AJHMvR/django-spotnet
spotnet/selector.py
3649
from django.utils.safestring import mark_safe from django.utils.html import conditional_escape from django.utils.translation import ugettext as _ class Selector(object): checkbox_template = '<input type="checkbox" name="%(name)s" value="%(value)s" />' action_input_name = 'selector_action' checkbox_true_val = 'on' def __init__(self, objects, actions): self._objects = objects self._actions = actions def apply_action(self, request): posted = dict(request.POST) action_name = posted.pop(self.action_input_name, [None])[0] action = self._actions.get(action_name, None) selection = self.get_selection((k for k, v in posted.iteritems() if v[0] == self.checkbox_true_val)) # this is way to generic, the actions should do this themselves # since they can provide a more detailed message #if len(selection) == 0: # return _("Could not apply action since nothing was selected.") if action_name and action: return action.apply(request, selection) else: return None def get_object_id(self, obj): raise NotImplementedError( "The 'get_object_id' method of this " "Selector is not implemented" ) def get_selection(self, obj): raise NotImplementedError( "The 'get_selection' method of this " "Selector is not implemented" ) def get_checkbox(self, obj): return mark_safe(self.checkbox_template % dict( name=conditional_escape(self.get_object_id(obj)), value=self.checkbox_true_val, )) def get_row(self, obj): return SelectorRow(self.get_checkbox(obj), obj) def __iter__(self): for o in self._objects: yield object.__getattribute__(self, 'get_row')(o) def __getattribute__(self, name): try: return object.__getattribute__(self, name) except (TypeError, AttributeError): return getattr(object.__getattribute__(self, '_objects'), name) def action_selector(self): x = ['<select name="%s">' % self.action_input_name] for action_name, action in self._actions.iteritems(): x.append('<option value="%(val)s">%(title)s</option>' % dict( val=action_name, title=conditional_escape(action.title()), )) x.append('</select>') return mark_safe(''.join(x)) class QuerySelector(Selector): # this is needed to mimic some of the QuerySet behavior # as is required by using paginators def get_object_id(self, obj): return 'post_%s' % obj.pk def get_id_pk(self, id): try: return int(id[5:]) except: return None def get_selection(self, ids): pks = (self.get_id_pk(i) for i in ids) return [i for i in pks if i is not None] def __len__(self): return len(object.__getattribute__(self, '_objects')) def __getitem__(self, key): if isinstance(key, slice): return type(self)(object.__getattribute__(self, '_objects').__getitem__(key), self._actions) else: return self.get_row(object.__getattribute__(self, '_objects').__getitem__(key)) class SelectorRow(object): def __init__(self, checkbox, obj): self._checkbox = checkbox self._object = obj def __getattribute__(self, name): if name == 'checkbox': return object.__getattribute__(self, '_checkbox') else: return getattr(object.__getattribute__(self, '_object'), name)
gpl-3.0
fcla/xmlresolution
spec/resolver_collection_case_12_spec.rb
4317
# encoding: UTF-8 warn_level = $VERBOSE $VERBOSE = nil require 'xmlresolution/resolver_collection' require 'xmlresolution/xml_resolver' require 'socket' require 'tempfile' @@locations = Array.new @@manifest = Object.new include XmlResolution describe ResolverCollection do @@store = nil @@files = File.join(File.dirname(__FILE__), 'files', 'example-xml-documents') def proxy prox = ENV['RESOLVER_PROXY'] prox ||= case hostname when /romeo-foxtrot/; 'localhost:3128' when /sacred.net/; 'satyagraha.sacred.net:3128' when /fcla.edu/; 'sake.fcla.edu' else nil end if prox.nil? and not @@enough_already @@enough_already = true STDERR.puts 'No http proxy set: will download schemas directly - very slow. Set environment variable RESOLVER_PROXY to caching proxy if you want to speed this up.' end prox end def what_should_get_resolved [] end def unresolveds [] end def hostname Socket.gethostname end def file_url name "file://#{hostname}/" + name.gsub(%r{^/+}, '') end def xmlcases_instance_doc File.join(@@files, 'rss-0.91.dtd') end def collection_name_1 'E20100524_ZODIAC' end before(:all) do @@store = Dir.mktmpdir('resolver-store-', '/tmp') FileUtils.mkdir_p File.join(@@store, 'schemas') FileUtils.mkdir_p File.join(@@store, 'collections') end after(:all) do FileUtils::rm_rf @@store end it "should create new collections" do ResolverCollection.new(@@store, collection_name_1) ResolverCollection.collections(@@store).include?(collection_name_1).should == true end it "should raise an error because the document is not xml data" do # resolve three representative documents: lambda {xmlcases_resolver = XmlResolver.new(File.read(xmlcases_instance_doc), file_url(xmlcases_instance_doc), @@store, proxy)}.should raise_error(XmlResolution::BadXmlDocument) end it "should give the collapsed list of schemas" do # get the collection of resolutions we've created: collection = ResolverCollection.new(@@store, collection_name_1) collection.resolutions.count.should == 0 # Create a uniquified list of all of the downloaded schemas... we # expect around 16 of them (lots of repeated schemas over the # four document resolutions): schema_redirects = {} collection.resolutions.each do |resolver| list_redirects = resolver.schema_dictionary.map{ |rec| rec.location if rec.retrieval_status == :redirect }.compact list_redirects.each { |loc| schema_redirects[loc] = true } end @@redirects = schema_redirects.keys.sort { |a,b| a.downcase <=> b.downcase } @@redirects.count.should == 0 # schema_locs = {} collection.resolutions.each do |resolver| list = resolver.schema_dictionary.map{ |rec| rec.location if rec.retrieval_status == :success }.compact list.each { |loc| schema_locs[loc] = true } end @@locations = schema_locs.keys.sort { |a,b| a.downcase <=> b.downcase } @@locations.count.should == 0 # Make sure all the successfully downloaded schemas in the resolution objects are listed somewhere in the manifest: @@manifest = collection.manifest @@locations.each { |loc| /#{loc}/.should =~ @@manifest } # Create a tarfile of the schemas; get a table of contents of the tar'd output of the collection using a third-party # tar program: tmp = Tempfile.new('tar-', '/tmp') collection.tar do |io| tmp.write io.read end tmp.close tar_toc = `tar tvf #{tmp.path}` tmp.unlink # Do we have a manifest in the tar file? %r{#{collection.collection_name}/manifest\.xml}.should =~ tar_toc # Is each of the locations we found represented in the tar file? @@locations.each do |loc| tar_entry = "#{collection.collection_name}/#{loc}".sub('http://', 'http/') %r{#{tar_entry}}.should =~ tar_toc end end it "should resolve these" do what_should_get_resolved.each{|z| @@locations.include?(z).should be_true} end it "should have these unresolveds in the manifest" do unresolveds.each{|z| @@manifest.index(z).should_not be_nil} end end # ResolverCollection
gpl-3.0
jim-easterbrook/pyctools-demo
src/scripts/de_interlace/stage_2.py
3661
#!/usr/bin/env python # File written by pyctools-editor. Do not edit. import argparse import logging from pyctools.core.compound import Compound import pyctools.components.deinterlace.hhiprefilter import pyctools.components.deinterlace.simple import pyctools.components.io.videofilereader import pyctools.components.qt.qtdisplay class Network(object): components = \ { 'deinterlace': { 'class': 'pyctools.components.deinterlace.simple.SimpleDeinterlace', 'config': "{'mode': 'repeatline'}", 'pos': (510.0, 170.0)}, 'deinterlace2': { 'class': 'pyctools.components.deinterlace.simple.SimpleDeinterlace', 'config': "{'mode': 'repeatline'}", 'pos': (510.0, 300.0)}, 'display': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay', 'config': "{'title': 'Interlaced, filtered', " "'framerate': 20}", 'pos': (640.0, 170.0)}, 'display2': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay', 'config': "{'title': 'Interlaced, unfiltered', " "'framerate': 20}", 'pos': (640.0, 300.0)}, 'hhipf': { 'class': 'pyctools.components.deinterlace.hhiprefilter.HHIPreFilter', 'config': '{}', 'pos': (250.0, 170.0)}, 'interlace': { 'class': 'pyctools.components.deinterlace.simple.SimpleDeinterlace', 'config': "{'inverse': 1}", 'pos': (380.0, 170.0)}, 'interlace2': { 'class': 'pyctools.components.deinterlace.simple.SimpleDeinterlace', 'config': "{'inverse': 1}", 'pos': (380.0, 300.0)}, 'qd': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay', 'config': "{'title': 'Original', 'framerate': 20}", 'pos': (250.0, 430.0)}, 'vfr': { 'class': 'pyctools.components.io.videofilereader.VideoFileReader', 'config': "{'path': " "'/home/jim/Documents/projects/pyctools-demo/video/still_wobble.avi', " "'looping': 'repeat'}", 'pos': (100.0, 300.0)}} linkages = \ { ('deinterlace', 'output'): [('display', 'input')], ('deinterlace2', 'output'): [('display2', 'input')], ('hhipf', 'output'): [('interlace', 'input')], ('interlace', 'output'): [('deinterlace', 'input')], ('interlace2', 'output'): [('deinterlace2', 'input')], ('vfr', 'output'): [ ('hhipf', 'input'), ('interlace2', 'input'), ('qd', 'input')]} def make(self): comps = {} for name, component in self.components.items(): comps[name] = eval(component['class'])(config=eval(component['config'])) return Compound(linkages=self.linkages, **comps) if __name__ == '__main__': from PyQt5 import QtCore, QtWidgets QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtWidgets.QApplication([]) comp = Network().make() cnf = comp.get_config() parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) cnf.parser_add(parser) parser.add_argument('-v', '--verbose', action='count', default=0, help='increase verbosity of log messages') args = parser.parse_args() logging.basicConfig(level=logging.ERROR - (args.verbose * 10)) del args.verbose cnf.parser_set(args) comp.set_config(cnf) comp.start() app.exec_() comp.stop() comp.join()
gpl-3.0
ZabuzaW/PathWeaver
test/de/zabuza/pathweaver/util/TripleTest.java
4436
package de.zabuza.pathweaver.util; import org.junit.Assert; import org.junit.Test; /** * Test for {@link Triple}. * * @author Zabuza {@literal <zabuza.dev@gmail.com>} * */ public final class TripleTest { /** * Test method for {@link Triple#equals(java.lang.Object)}. */ @SuppressWarnings("static-method") @Test public void testEqualsObject() { final String firstEntry = "a"; final Float secondEntry = Float.valueOf(2.3f); final Integer thirdEntry = Integer.valueOf(2); final Integer differentThirdEntry = Integer.valueOf(3); final Triple<String, Float, Integer> triple = new Triple<>(firstEntry, secondEntry, thirdEntry); final Triple<String, Float, Integer> similarTriple = new Triple<>(firstEntry, secondEntry, thirdEntry); final Triple<String, Float, Integer> differentTriple = new Triple<>(firstEntry, secondEntry, differentThirdEntry); Assert.assertEquals(triple, similarTriple); Assert.assertNotEquals(triple, differentTriple); } /** * Test method for {@link Triple#getFirst()}. */ @SuppressWarnings("static-method") @Test public void testGetFirst() { final String firstEntry = "a"; final String anotherFirstEntry = "b"; final Float secondEntry = Float.valueOf(2.3f); final Integer thirdEntry = Integer.valueOf(2); final Triple<String, Float, Integer> triple = new Triple<>(firstEntry, secondEntry, thirdEntry); final Triple<String, Float, Integer> anotherTriple = new Triple<>(anotherFirstEntry, secondEntry, thirdEntry); Assert.assertEquals(firstEntry, triple.getFirst()); Assert.assertEquals(anotherFirstEntry, anotherTriple.getFirst()); } /** * Test method for {@link Triple#getSecond()}. */ @SuppressWarnings("static-method") @Test public void testGetSecond() { final String firstEntry = "a"; final Float secondEntry = Float.valueOf(2.3f); final Float anotherSecondEntry = Float.valueOf(4.3f); final Integer thirdEntry = Integer.valueOf(2); final Triple<String, Float, Integer> triple = new Triple<>(firstEntry, secondEntry, thirdEntry); final Triple<String, Float, Integer> anotherTriple = new Triple<>(firstEntry, anotherSecondEntry, thirdEntry); Assert.assertEquals(secondEntry, triple.getSecond()); Assert.assertEquals(anotherSecondEntry, anotherTriple.getSecond()); } /** * Test method for {@link Triple#getThird()}. */ @SuppressWarnings("static-method") @Test public void testGetThird() { final String firstEntry = "a"; final Float secondEntry = Float.valueOf(2.3f); final Integer thirdEntry = Integer.valueOf(2); final Integer anotherThirdEntry = Integer.valueOf(4); final Triple<String, Float, Integer> triple = new Triple<>(firstEntry, secondEntry, thirdEntry); final Triple<String, Float, Integer> anotherTriple = new Triple<>(firstEntry, secondEntry, anotherThirdEntry); Assert.assertEquals(thirdEntry, triple.getThird()); Assert.assertEquals(anotherThirdEntry, anotherTriple.getThird()); } /** * Test method for {@link Triple#hashCode()}. */ @SuppressWarnings("static-method") @Test public void testHashCode() { final String firstEntry = "a"; final Float secondEntry = Float.valueOf(2.3f); final Integer thirdEntry = Integer.valueOf(2); final Integer differentThirdEntry = Integer.valueOf(3); final Triple<String, Float, Integer> triple = new Triple<>(firstEntry, secondEntry, thirdEntry); final Triple<String, Float, Integer> similarTriple = new Triple<>(firstEntry, secondEntry, thirdEntry); final Triple<String, Float, Integer> differentTriple = new Triple<>(firstEntry, secondEntry, differentThirdEntry); Assert.assertEquals(triple.hashCode(), similarTriple.hashCode()); Assert.assertNotEquals(triple.hashCode(), differentTriple.hashCode()); } /** * Test method for * {@link Triple#Triple(java.lang.Object, java.lang.Object, java.lang.Object)} * . */ @SuppressWarnings("static-method") @Test public void testTriple() { final String firstEntry = "a"; final Float secondEntry = Float.valueOf(2.3f); final Integer thirdEntry = Integer.valueOf(2); final Triple<String, Float, Integer> triple = new Triple<>(firstEntry, secondEntry, thirdEntry); Assert.assertEquals(firstEntry, triple.getFirst()); Assert.assertEquals(secondEntry, triple.getSecond()); Assert.assertEquals(thirdEntry, triple.getThird()); } }
gpl-3.0
fanruan/finereport-design
designer_base/src/com/fr/design/fun/impl/AbstractExportAttrTabProvider.java
552
package com.fr.design.fun.impl; import com.fr.design.fun.ExportAttrTabProvider; import com.fr.stable.fun.impl.AbstractProvider; import com.fr.stable.fun.mark.API; /** * Created by vito on 16/5/5. */ @API(level = ExportAttrTabProvider.CURRENT_LEVEL) public abstract class AbstractExportAttrTabProvider extends AbstractProvider implements ExportAttrTabProvider { @Override public int currentAPILevel() { return CURRENT_LEVEL; } @Override public String mark4Provider() { return this.getClass().getName(); } }
gpl-3.0
fanruan/finereport-design
designer_base/src/com/fr/design/style/background/impl/PatternBackgroundPaneNoFore.java
682
package com.fr.design.style.background.impl; import com.fr.design.style.color.ColorSelectBox; import javax.swing.*; import java.awt.*; /** * Created by richie on 16/5/18. */ public class PatternBackgroundPaneNoFore extends PatternBackgroundPane { public PatternBackgroundPaneNoFore(int nColumn) { super(nColumn); } // 重载 不加载两个前后按钮 protected void setChildrenOfContentPane(JPanel contentPane) { foregroundColorPane = new ColorSelectBox(80); backgroundColorPane = new ColorSelectBox(80); foregroundColorPane.setSelectObject(Color.lightGray); backgroundColorPane.setSelectObject(Color.black); } }
gpl-3.0
WebPA/Source
tutors/assessments/marks/set_group_marks.php
7943
<?php /** * * Set marks for the assessment's groups * * * @copyright 2007 Loughborough University * @license http://www.gnu.org/licenses/gpl.txt * @version 1.0.0.0 * */ require_once("../../../includes/inc_global.php"); require_once(DOC__ROOT . 'includes/classes/class_assessment.php'); require_once(DOC__ROOT . 'includes/classes/class_group_handler.php'); require_once(DOC__ROOT . 'includes/classes/class_xml_parser.php'); require_once(DOC__ROOT . 'includes/functions/lib_form_functions.php'); if (!check_user($_user, APP__USER_TYPE_TUTOR)){ header('Location:'. APP__WWW .'/logout.php?msg=denied'); exit; } // -------------------------------------------------------------------------------- // Process GET/POST $assessment_id = fetch_GET('a'); $tab = fetch_GET('tab'); $year = fetch_GET('y', date('Y')); $command = fetch_POST('command'); $list_url = "../index.php?tab={$tab}&y={$year}"; $prev_url = $list_url; // -------------------------------------------------------------------------------- $group_marks = array(); $assessment = new Assessment($DB); if ($assessment->load($assessment_id)) { $assessment_qs = "a={$assessment->id}&tab={$tab}&y={$year}"; $group_handler = new GroupHandler(); $collection =& $group_handler->get_collection($assessment->get_collection_id()); $group_marks_xml = $DB->fetch_value("SELECT group_mark_xml FROM " . APP__DB_TABLE_PREFIX . "assessment_group_marks WHERE assessment_id = '{$assessment->id}'"); $xml_parser = null; if ($group_marks_xml) { $xml_parser = new XMLParser(); $xml_array = $xml_parser->parse($group_marks_xml); if (is_array($xml_array['groups']['group'])) { foreach($xml_array['groups']['group'] as $i => $group) { if (is_array($group)) { if (array_key_exists('_attributes', $group)) { $group_marks[$group['_attributes']['id']] = $group['_attributes']['mark']; } else { $group_marks[$group['id']] = $group['mark']; } } } } } } else { $assessment = null; } // -------------------------------------------------------------------------------- // Process Form $errors = null; $bad_group_ids = null; if ( ($command) && ($assessment) ) { switch ($command) { case 'save': $xml_array = null; foreach($_POST as $k => $v) { if (strpos($k, 'group_mark_')===0) { $group_id = str_replace('group_mark_','',$k); $mark = trim( str_replace('%','',$v) ); if (!is_numeric($mark)) { if (empty($mark)) { $errors[] = "You must enter a score for each group."; } else { $errors[] = "You must enter a score for each group. $v is not a valid score."; } $bad_group_ids[] = $group_id; // used to highlight the row later } // Add mark to XML we will save $xml_array['groups']['group'][] = array ('_attributes' => array ('id' => $group_id , 'mark' => $mark ,)); // Add mark to the array we're gonna check $group_marks[$group_id] = $mark; } } // If there were no errors, save the changes if (!$errors) { if (!$xml_parser) { $xml_parser = new XMLParser(); } $xml = $xml_parser->generate_xml($xml_array); $fields = array ('assessment_id' => $assessment->id , 'group_mark_xml' => $xml ,); $DB->do_insert('REPLACE INTO ' . APP__DB_TABLE_PREFIX . 'assessment_group_marks ({fields}) VALUES ({values})',$fields); } break; // -------------------- }// /switch } // -------------------------------------------------------------------------------- // Begin Page $page_title = 'set group marks'; $UI->page_title = APP__NAME . ' ' . $page_title; $UI->menu_selected = 'my assessments'; $UI->help_link = '?q=node/235'; $UI->breadcrumbs = array ('home' => '../../' , 'my assessments' => '../' , 'set group marks' => null ,); $UI->set_page_bar_button('List Assessments', '../../../../images/buttons/button_assessment_list.gif', '../'); $UI->set_page_bar_button('Create Assessments', '../../../../images/buttons/button_assessment_create.gif', '../create/'); $UI->head(); ?> <style type="text/css"> <!-- table.grid th { text-align: center; } table.grid td { text-align: left; } span.id_number { color: #666; } <?php if (is_array($bad_group_ids)) { foreach($bad_group_ids as $i => $group_id) { echo("tr#group_$group_id td { background-color: #fcc; }"); } } ?> --> </style> <script language="JavaScript" type="text/javascript"> <!-- function do_command(com) { switch (com) { default : document.groupmark_form.command.value = com; document.groupmark_form.submit(); } }// /do_command() //--> </script> <?php $UI->content_start(); $UI->draw_boxed_list($errors, 'error_box', 'The following errors were found:', 'No changes have been saved. Please check the details in the form, and try again.'); ?> <p>On this page you can enter the overall marks each group has achieved. These marks are used in the WebPA scoring algorithm, and will form the basis of the final student marks.</p> <div class="content_box"> <?php if (!$assessment) { ?> <div class="nav_button_bar"> <a href="<?php echo($list_url) ?>"><img src="../../../images/buttons/arrow_green_left.gif" alt="back -"> back to assessments list</a> </div> <p>The assessment you selected could not be loaded for some reason - please go back and try again.</p> <?php } else { ?> <form action="set_group_marks.php?<?php echo($assessment_qs); ?>" method="post" name="groupmark_form"> <input type="hidden" name="command" value="none" /> <div class="nav_button_bar"> <table cellpadding="0" cellspacing="0" width="100%"> <tr> <td><a href="<?php echo($list_url); ?>"><img src="../../../images/buttons/arrow_green_left.gif" alt="back -"> back to assessment list</a></td> </tr> </table> </div> <h2>Group Marks</h2> <div class="form_section"> <?php echo("<p><label>This assessment is using collection: </label><em>{$collection->name}</em></p>"); $groups = $collection->get_groups_iterator(); if ($groups->size()==0) { ?> <p>This collection does not contain any groups</p> <?php } else { ?> <table class="grid" cellpadding="5" cellspacing="1"> <tr> <th>Group</th> <th>Members</th> <th>Group Mark</th> </tr> <?php for($groups->reset(); $groups->is_valid(); $groups->next()) { $group =& $groups->current(); $group_members = $group->get_members(); $members = ($group_members) ? $CIS->get_user(array_keys($group_members)) : null; $group_mark = (array_key_exists($group->id, $group_marks)) ? $group_marks["$group->id"] : ''; echo("<tr id=\"group_{$group->id}\">"); echo("<td><label for=\"group_mark_{$group->id}\">{$group->name}</label></td>"); echo('<td style="text-align: left">'); if (!$members) { echo('-'); } else { foreach($members as $i => $member) { echo("{$member['lastname']}, {$member['forename']}"); if (!empty($member['id_number'])) { echo(" &nbsp; <span class=\"id_number\">({$member['id_number']})</span>"); } echo("<br />"); } } echo('</td>'); echo("<td><input type=\"text\" name=\"group_mark_{$group->id}\" id=\"group_mark_{$group->id}\" size=\"4\" maxlength=\"5\" value=\"$group_mark\" /> %</td>"); echo('</tr>'); } echo('</table>'); } ?> </div> <div style="text-align: center"> <input type="button" name="savebutton1" id="savebutton1" value="save changes" onclick="do_command('save');" /> </div> </form> <?php } ?> </div> <?php $UI->content_end(); ?>
gpl-3.0
VosDerrick/Volsteria
src/main/java/slimeknights/tconstruct/smeltery/multiblock/MultiblockTinker.java
1038
package slimeknights.tconstruct.smeltery.multiblock; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import slimeknights.mantle.multiblock.MultiServantLogic; import slimeknights.tconstruct.smeltery.tileentity.TileMultiblock; public abstract class MultiblockTinker extends MultiblockCuboid { public final TileMultiblock<?> tile; public MultiblockTinker(TileMultiblock<?> tile, boolean hasFloor, boolean hasFrame, boolean hasCeiling) { super(hasFloor, hasFrame, hasCeiling); this.tile = tile; } protected boolean isValidSlave(World world, BlockPos pos) { TileEntity te = world.getTileEntity(pos); // slave-blocks are only allowed if they already belong to this smeltery if(te instanceof MultiServantLogic) { MultiServantLogic slave = (MultiServantLogic) te; if(slave.hasValidMaster()) { if(!tile.getPos().equals(slave.getMasterPosition())) { return false; } } } return true; } }
gpl-3.0
xframium/xframium-java
terminal-driver/src/main/java/org/xframium/terminal/driver/screen/model/package-info.java
564
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.11.03 at 10:28:07 PM EDT // @javax.xml.bind.annotation.XmlSchema(namespace = "http://www.xframium.org/terminal-screen-model", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package org.xframium.terminal.driver.screen.model;
gpl-3.0
worldexplorer/SquareOne
Sq1.Core/Repositories/RepositoryDllBrokerAdapters.cs
365
using System; using Sq1.Core.Broker; namespace Sq1.Core.Repositories { public class RepositoryDllBrokerAdapters : DllScannerExplicit<BrokerAdapter> { public RepositoryDllBrokerAdapters(string rootPath) : base(rootPath, Assembler.InstanceUninitialized.AssemblerDataSnapshot.ReferencedNetAssemblyNames_StreamingBrokerAdapters) { } } }
gpl-3.0
XdieselX/Patrick-the-Star-Explorer
Broker/Location.java
2148
import java.time.LocalTime; import java.time.ZonedDateTime; import java.util.StringTokenizer; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Ahmed */ public class Location implements Comparable<Location.LocationParams>{ public LocationParams locParams; public double Temperature; public double Calculated_PH; public Location(float Longitude, float Latitude, double Temperature, double Calculated_PH, ZonedDateTime ocurrence) { this.locParams = new LocationParams(Longitude, Latitude, ocurrence); this.Temperature = Temperature; this.Calculated_PH = Calculated_PH; } public Location(String Message) { StringTokenizer strtok = new StringTokenizer(Message, "/"); this.locParams.Longitude = Float.valueOf((String)strtok.nextElement()); this.locParams.Latitude = Float.valueOf((String)strtok.nextElement()); this.Temperature = Float.valueOf((String)strtok.nextElement()); this.Calculated_PH = Float.valueOf((String)strtok.nextElement()); this.locParams.ocurrence = ZonedDateTime.parse((String)strtok.nextElement()); } public Location() { } @Override public String toString() { return "Longitude : "+this.locParams.Longitude+" Latitude : "+this.locParams.Latitude+" Temperature :"+this.Temperature+"°C Calculated PH :"+this.Calculated_PH+" occured on :"+this.locParams.ocurrence; //To change body of generated methods, choose Tools | Templates. } @Override public int compareTo(LocationParams o) { return this.locParams.ocurrence.compareTo(o.ocurrence); } public class LocationParams { public float Longitude; public float Latitude; public ZonedDateTime ocurrence; public LocationParams(float Longitude, float Latitude, ZonedDateTime ocurrence) { this.Longitude = Longitude; this.Latitude = Latitude; this.ocurrence = ocurrence; } } }
gpl-3.0
worldexplorer/SquareOne
DigitalRune-TextEditor-1.3.1/DigitalRune.Windows.TextEditor/Document/Highlighting/TextWord.cs
10448
using System; using System.Diagnostics; using System.Drawing; using DigitalRune.Windows.TextEditor.Document; namespace DigitalRune.Windows.TextEditor.Highlighting { /// <summary> /// Types of words in a line. /// </summary> public enum TextWordType { /// <summary>A word.</summary> Word, /// <summary>A space.</summary> Space, /// <summary>A tab.</summary> Tab } /// <summary> /// This class represents single words with color information, two special versions of a word are /// spaces and tabs. /// </summary> public class TextWord { /// <summary> /// A space (special type of <see cref="TextWord"/>). /// </summary> public sealed class SpaceTextWord : TextWord { /// <summary> /// Initializes a new instance of the <see cref="TextWord.SpaceTextWord"/> class. /// </summary> public SpaceTextWord() { _length = 1; } /// <summary> /// Initializes a new instance of the <see cref="TextWord.SpaceTextWord"/> class. /// </summary> /// <param name="color">The color.</param> public SpaceTextWord(HighlightColor color) { _length = 1; SyntaxColor = color; } /// <summary> /// Gets the font. /// </summary> /// <param name="fontContainer">The font container.</param> /// <returns>Always <see langword="null"/>.</returns> public override Font GetFont(FontContainer fontContainer) { return null; } /// <summary> /// Gets the type. /// </summary> /// <value>The type (<see cref="TextWordType.Space"/>).</value> public override TextWordType Type { get { return TextWordType.Space; } } /// <summary> /// Gets a value indicating whether this instance is a whitespace. /// </summary> /// <value> /// <see langword="true"/>. /// </value> public override bool IsWhiteSpace { get { return true; } } } /// <summary> /// A tab (special type of <see cref="TextWord"/>). /// </summary> public sealed class TabTextWord : TextWord { /// <summary> /// Initializes a new instance of the <see cref="TextWord.TabTextWord"/> class. /// </summary> public TabTextWord() { _length = 1; } /// <summary> /// Initializes a new instance of the <see cref="TextWord.TabTextWord"/> class. /// </summary> /// <param name="color">The color.</param> public TabTextWord(HighlightColor color) { _length = 1; SyntaxColor = color; } /// <summary> /// Gets the font. /// </summary> /// <param name="fontContainer">The font container.</param> /// <returns>Always <see langword="null"/>.</returns> public override Font GetFont(FontContainer fontContainer) { return null; } /// <summary> /// Gets the type. /// </summary> /// <value>The type (<see cref="TextWordType.Tab"/>).</value> public override TextWordType Type { get { return TextWordType.Tab; } } /// <summary> /// Gets a value indicating whether this instance is a whitespace. /// </summary> /// <value> /// <see langword="true"/>. /// </value> public override bool IsWhiteSpace { get { return true; } } } private static readonly TextWord spaceWord = new SpaceTextWord(); private static readonly TextWord tabWord = new TabTextWord(); private HighlightColor _color; private readonly LineSegment _line; private readonly IDocument _document; private readonly int _offset; private int _length; private readonly bool _hasDefaultColor; /// <summary> /// Gets a space (special type of <see cref="TextWord"/>). /// </summary> /// <value>The space.</value> public static TextWord Space { get { return spaceWord; } } /// <summary> /// Gets a tab (special type of <see cref="TextWord"/>). /// </summary> /// <value>The tab.</value> public static TextWord Tab { get { return tabWord; } } /// <summary> /// Gets the offset of the word in the current line. /// </summary> /// <value>The offset of the word in the current line.</value> public int Offset { get { return _offset; } } /// <summary> /// Gets the length of the word. /// </summary> /// <value>The length of the word.</value> public int Length { get { return _length; } } /// <summary> /// Splits the word into two parts. /// </summary> /// <param name="word">The word.</param> /// <param name="pos">The position, which lies in the range <c>[1, Length - 1]</c>.</param> /// <returns>The part after <paramref name="pos"/> is returned as a new <see cref="TextWord"/>.</returns> /// <remarks> /// The part before <paramref name="pos"/> is assigned to /// the reference parameter <paramref name="word"/>, the part after <paramref name="pos"/> is returned. /// </remarks> public static TextWord Split(ref TextWord word, int pos) { #if DEBUG if (word.Type != TextWordType.Word) throw new ArgumentException("word.Type must be Word"); if (pos <= 0) throw new ArgumentOutOfRangeException("pos", pos, "pos must be > 0"); if (pos >= word.Length) throw new ArgumentOutOfRangeException("pos", pos, "pos must be < word.Length"); #endif TextWord after = new TextWord(word._document, word._line, word._offset + pos, word._length - pos, word._color, word._hasDefaultColor); word = new TextWord(word._document, word._line, word._offset, pos, word._color, word._hasDefaultColor); return after; } /// <summary> /// Gets a value indicating whether this instance has default color. /// </summary> /// <value> /// <see langword="true"/> if this instance has default color; otherwise, <see langword="false"/>. /// </value> public bool HasDefaultColor { get { return _hasDefaultColor; } } /// <summary> /// Gets the type. /// </summary> /// <value>The type.</value> public virtual TextWordType Type { get { return TextWordType.Word; } } /// <summary> /// Gets the word. /// </summary> /// <value>The word.</value> public string Word { get { if (_document == null) return String.Empty; return _document.GetText(_line.Offset + _offset, _length); } } /// <summary> /// Gets the font. /// </summary> /// <param name="fontContainer">The font container.</param> /// <returns>The font.</returns> public virtual Font GetFont(FontContainer fontContainer) { return _color.GetFont(fontContainer); } /// <summary> /// Gets the color. /// </summary> /// <value>The color.</value> public Color Color { get { if (_color == null) return Color.Black; else return _color.Color; } } /// <summary> /// Gets a value indicating whether this <see cref="TextWord"/> is bold. /// </summary> /// <value><see langword="true"/> if bold; otherwise, <see langword="false"/>.</value> public bool Bold { get { if (_color == null) return false; else return _color.Bold; } } /// <summary> /// Gets a value indicating whether this <see cref="TextWord"/> is italic. /// </summary> /// <value><see langword="true"/> if italic; otherwise, <see langword="false"/>.</value> public bool Italic { get { if (_color == null) return false; else return _color.Italic; } } /// <summary> /// Gets or sets the <see cref="HighlightColor"/>. /// </summary> /// <value>The color for the syntax highlighting.</value> public HighlightColor SyntaxColor { get { return _color; } set { Debug.Assert(value != null); _color = value; } } /// <summary> /// Gets a value indicating whether this instance is a whitespace. /// </summary> /// <value> /// <see langword="true"/> if this instance is whitespace; otherwise, <see langword="false"/>. /// </value> public virtual bool IsWhiteSpace { get { return false; } } /// <summary> /// Initializes a new instance of the <see cref="TextWord"/> class. /// </summary> protected TextWord() { // Needed by the nested classes SpaceTextWord and TabTextWord. } /// <summary> /// Initializes a new instance of the <see cref="TextWord"/> class. /// </summary> /// <param name="document">The document.</param> /// <param name="line">The line.</param> /// <param name="offset">The offset.</param> /// <param name="length">The length.</param> /// <param name="color">The color.</param> /// <param name="hasDefaultColor">if set to <see langword="true"/> [has default color].</param> public TextWord(IDocument document, LineSegment line, int offset, int length, HighlightColor color, bool hasDefaultColor) { Debug.Assert(document != null); Debug.Assert(line != null); Debug.Assert(color != null); _document = document; _line = line; _offset = offset; _length = length; _color = color; _hasDefaultColor = hasDefaultColor; } /// <summary> /// Converts a <see cref="TextWord"/> instance to string (for debug purposes) /// </summary> /// <returns> /// A <see cref="String"></see> that represents the current <see cref="Object"></see>. /// </returns> public override string ToString() { return "[TextWord: Word = " + Word + ", Color = " + Color + "]"; } } }
gpl-3.0
kallimachos/archive
task/task.py
2390
# Python application for pushing content to Google Tasks using the CLI # This app does not work and needs some TLC from sys import argv from requests_oauthlib import OAuth2Session from datetime import date from ast import literal_eval def authenticate(): # Credentials you get from registering a new application info = readData() client_id = info['installed']['client_id'] #<the id you get from google>.apps.googleusercontent.com' client_secret = info['installed']['client_secret'] #<the secret you get from google>' redirect_uri = info['installed']['redirect_uris'][0] #https://your.registered/callback' print client_id print client_secret print redirect_uri # OAuth endpoints given in the Google API documentation authorization_base_url = "https://accounts.google.com/o/oauth2/auth" token_url = "https://accounts.google.com/o/oauth2/token" scope = [ 'https://www.googleapis.com/auth/tasks', 'https://www.googleapis.com/auth/tasks.readonly' ] google = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri) # Redirect user to Google for authorization authorization_url, state = google.authorization_url(authorization_base_url, # offline for refresh token # force to always make user click authorize access_type="offline", approval_prompt="force") print 'Please go here and authorize,', authorization_url # Get the authorization verifier code from the callback url redirect_response = raw_input('Paste the full redirect URL here:') # Fetch the access token google.fetch_token(token_url, client_secret=client_secret, authorization_response=redirect_response) # Fetch a protected resource, i.e. user profile r = google.get('https://www.googleapis.com/tasks/v1/users/@me/lists') print r.content def readData(): # opens client_secrets.json and reads it to an array f = open('client_secrets.json','r') info = literal_eval(f.read()) f.close() return info def content(): # Gets text from CLI text = raw_input("Enter text: ") return text def push(text): # Pushes text to Google Tasks today = date.today() print text + " " + str(today) if __name__ == "__main__": args = [] args = list(argv) print "Hello, this is the task app." # print "You entered: " + str(args) authenticate()
gpl-3.0
prmr/JetUML
src/ca/mcgill/cs/jetuml/diagram/nodes/AbstractNode.java
3669
/******************************************************************************* * JetUML - A desktop application for fast UML diagramming. * * Copyright (C) 2020, 2021 by McGill University. * * See: https://github.com/prmr/JetUML * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses. *******************************************************************************/ package ca.mcgill.cs.jetuml.diagram.nodes; import static java.util.Collections.emptyList; import java.util.List; import java.util.Optional; import ca.mcgill.cs.jetuml.diagram.AbstractDiagramElement; import ca.mcgill.cs.jetuml.diagram.Diagram; import ca.mcgill.cs.jetuml.diagram.Node; import ca.mcgill.cs.jetuml.geom.Point; /** * Common elements for the Node hierarchy. */ public abstract class AbstractNode extends AbstractDiagramElement implements Node { private Point aPosition = new Point(0, 0); private Optional<Diagram> aDiagram = Optional.empty(); @Override public void translate(int pDeltaX, int pDeltaY) { aPosition = new Point( aPosition.getX() + pDeltaX, aPosition.getY() + pDeltaY ); } @Override public final Point position() { return aPosition; } @Override public final void moveTo(Point pPoint) { aPosition = pPoint; } @Override public AbstractNode clone() { AbstractNode clone = (AbstractNode) super.clone(); clone.aPosition = aPosition.copy(); return clone; } @Override public final String toString() { return getClass().getSimpleName() + " at " + position(); } @Override public final void attach(Diagram pDiagram) { assert pDiagram != null; aDiagram = Optional.of(pDiagram); } @Override public final void detach() { aDiagram = Optional.empty(); } @Override public final Optional<Diagram> getDiagram() { return aDiagram; } @Override public boolean hasParent() { return false; } @Override public boolean requiresParent() { return false; } @Override public Node getParent() { assert false; // Safer way than assert hasParent() to trigger an assertion error if not overridden return null; // Unreachable. } @Override public void unlink() { assert false; // Safer way than assert hasParent() to trigger an assertion error if not overridden } @Override public void link(Node pParentNode) { assert false; } @Override public List<Node> getChildren() { return emptyList(); } @Override public boolean allowsChildren() { return false; } @Override public void addChild(Node pNode) { assert allowsChildren(); // Do nothing } @Override public void addChild(int pIndex, Node pNode) { assert allowsChildren(); // Do nothing } @Override public void removeChild(Node pNode) { assert getChildren().contains(pNode); } @Override public void placeLast(Node pNode) { assert pNode != null; assert getChildren().contains(pNode); removeChild(pNode); addChild(pNode); } }
gpl-3.0
woshikie/Just-Another-Magic-Simulator
Just Another Magic Simulator/Assets/Logic/Cards/KLD/G/GearseekerSerpent.cs
537
using System.Collections; namespace Card { public class GearseekerSerpent : Card { /* Gearseeker Serpent costs {1} less to cast for each artifact you control. {5}{U}: Gearseeker Serpent can't be blocked this turn. */ private const string UniqueCardName = "Gearseeker Serpent"; public GearseekerSerpent() : base(UniqueCardName) { } protected override void OnConstructed() { Types = new string[] { }; Colors = new string[] { }; SubTypes = new string[] { }; SuperTypes = new string[] { }; } } }
gpl-3.0
ruud-v-a/servo
ports/cef/browser.rs
9061
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use browser_host::{ServoCefBrowserHost, ServoCefBrowserHostExtensions}; use eutil::Downcast; use frame::{ServoCefFrame, ServoCefFrameExtensions}; use interfaces::{CefBrowser, CefBrowserHost, CefClient, CefFrame, CefRequestContext}; use interfaces::{cef_browser_t, cef_browser_host_t, cef_client_t, cef_frame_t}; use interfaces::{cef_request_context_t}; use servo::Browser; use types::{cef_browser_settings_t, cef_string_t, cef_window_info_t}; use window; use compositing::windowing::{WindowNavigateMsg, WindowEvent}; use glutin_app; use libc::c_int; use util::opts; use std::borrow::ToOwned; use std::cell::{Cell, RefCell}; use std::sync::atomic::{AtomicInt, Ordering}; thread_local!(pub static ID_COUNTER: AtomicInt = AtomicInt::new(0)); thread_local!(pub static BROWSERS: RefCell<Vec<CefBrowser>> = RefCell::new(vec!())); pub enum ServoBrowser { Invalid, OnScreen(Browser<glutin_app::window::Window>), OffScreen(Browser<window::Window>), } impl ServoBrowser { fn handle_event(&mut self, event: WindowEvent) { match *self { ServoBrowser::OnScreen(ref mut browser) => { browser.handle_event(event); } ServoBrowser::OffScreen(ref mut browser) => { browser.handle_event(event); } ServoBrowser::Invalid => {} } } pub fn get_title_for_main_frame(&self) { match *self { ServoBrowser::OnScreen(ref browser) => browser.get_title_for_main_frame(), ServoBrowser::OffScreen(ref browser) => browser.get_title_for_main_frame(), ServoBrowser::Invalid => {} } } pub fn pinch_zoom_level(&self) -> f32 { match *self { ServoBrowser::OnScreen(ref browser) => browser.pinch_zoom_level(), ServoBrowser::OffScreen(ref browser) => browser.pinch_zoom_level(), ServoBrowser::Invalid => 1.0, } } } cef_class_impl! { ServoCefBrowser : CefBrowser, cef_browser_t { fn get_host(&this,) -> *mut cef_browser_host_t {{ this.downcast().host.clone() }} fn go_back(&this,) -> () {{ this.send_window_event(WindowEvent::Navigation(WindowNavigateMsg::Back)); }} fn go_forward(&this,) -> () {{ this.send_window_event(WindowEvent::Navigation(WindowNavigateMsg::Forward)); }} // Returns the main (top-level) frame for the browser window. fn get_main_frame(&this,) -> *mut cef_frame_t {{ this.downcast().frame.clone() }} } } pub struct ServoCefBrowser { /// A reference to the browser's primary frame. pub frame: CefFrame, /// A reference to the browser's host. pub host: CefBrowserHost, /// A reference to the browser client. pub client: CefClient, /// Whether the on-created callback has fired yet. pub callback_executed: Cell<bool>, id: int, servo_browser: RefCell<ServoBrowser>, message_queue: RefCell<Vec<WindowEvent>>, } impl ServoCefBrowser { pub fn new(window_info: &cef_window_info_t, client: CefClient) -> ServoCefBrowser { let frame = ServoCefFrame::new().as_cef_interface(); let host = ServoCefBrowserHost::new(client.clone()).as_cef_interface(); let servo_browser = if window_info.windowless_rendering_enabled == 0 { let glutin_window = glutin_app::create_window(); let servo_browser = Browser::new(Some(glutin_window.clone())); ServoBrowser::OnScreen(servo_browser) } else { ServoBrowser::Invalid }; let id = ID_COUNTER.with(|counter| { counter.fetch_add(1, Ordering::SeqCst) }); ServoCefBrowser { frame: frame, host: host, client: client, callback_executed: Cell::new(false), servo_browser: RefCell::new(servo_browser), message_queue: RefCell::new(vec!()), id: id, } } } pub trait ServoCefBrowserExtensions { fn init(&self, window_info: &cef_window_info_t); fn send_window_event(&self, event: WindowEvent); fn get_title_for_main_frame(&self); fn pinch_zoom_level(&self) -> f32; } impl ServoCefBrowserExtensions for CefBrowser { fn init(&self, window_info: &cef_window_info_t) { if window_info.windowless_rendering_enabled != 0 { let window = window::Window::new(); let servo_browser = Browser::new(Some(window.clone())); window.set_browser(self.clone()); *self.downcast().servo_browser.borrow_mut() = ServoBrowser::OffScreen(servo_browser); } self.downcast().host.set_browser((*self).clone()); self.downcast().frame.set_browser((*self).clone()); } fn send_window_event(&self, event: WindowEvent) { self.downcast().message_queue.borrow_mut().push(event); loop { match self.downcast().servo_browser.try_borrow_mut() { None => { // We're trying to send an event while processing another one. This will // cause general badness, so queue up that event instead of immediately // processing it. break } Some(ref mut browser) => { let event = match self.downcast().message_queue.borrow_mut().pop() { None => return, Some(event) => event, }; browser.handle_event(event); } } } } fn get_title_for_main_frame(&self) { self.downcast().servo_browser.borrow().get_title_for_main_frame() } fn pinch_zoom_level(&self) -> f32 { self.downcast().servo_browser.borrow().pinch_zoom_level() } } pub fn update() { BROWSERS.with(|browsers| { for browser in browsers.borrow().iter() { browser.send_window_event(WindowEvent::Idle); } }); } pub fn close(browser: CefBrowser) { BROWSERS.with(|browsers| { let mut browsers = browsers.borrow_mut(); browsers.iter() .position(|&ref n| n.downcast().id == browser.downcast().id) .map(|e| browsers.remove(e)); }); } pub fn browser_callback_after_created(browser: CefBrowser) { if browser.downcast().client.is_null_cef_object() { return } let client = browser.downcast().client.clone(); let life_span_handler = client.get_life_span_handler(); if life_span_handler.is_not_null_cef_object() { life_span_handler.on_after_created(browser.clone()); } browser.downcast().callback_executed.set(true); } fn browser_host_create(window_info: &cef_window_info_t, client: CefClient, callback_executed: bool) -> CefBrowser { let mut urls = Vec::new(); urls.push("http://s27.postimg.org/vqbtrolyr/servo.jpg".to_owned()); let mut opts = opts::default_opts(); opts.urls = urls; let browser = ServoCefBrowser::new(window_info, client).as_cef_interface(); browser.init(window_info); if callback_executed { browser_callback_after_created(browser.clone()); } BROWSERS.with(|browsers| { browsers.borrow_mut().push(browser.clone()); }); browser } cef_static_method_impls! { fn cef_browser_host_create_browser(window_info: *const cef_window_info_t, client: *mut cef_client_t, _url: *const cef_string_t, _browser_settings: *const cef_browser_settings_t, _request_context: *mut cef_request_context_t) -> c_int {{ let client: CefClient = client; let _url: &[u16] = _url; let _browser_settings: &cef_browser_settings_t = _browser_settings; let _request_context: CefRequestContext = _request_context; browser_host_create(window_info, client, false); 1i32 }} fn cef_browser_host_create_browser_sync(window_info: *const cef_window_info_t, client: *mut cef_client_t, _url: *const cef_string_t, _browser_settings: *const cef_browser_settings_t, _request_context: *mut cef_request_context_t) -> *mut cef_browser_t {{ let client: CefClient = client; let _url: &[u16] = _url; let _browser_settings: &cef_browser_settings_t = _browser_settings; let _request_context: CefRequestContext = _request_context; browser_host_create(window_info, client, true) }} }
mpl-2.0
jvelo/datatext
src/LaravelUserProvider.php
605
<?php /* * Copyright (c) 2016 Jérôme Velociter <jerome@velociter.fr> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ namespace Jvelo\Datatext; use Illuminate\Support\Facades\Auth; class LaravelUserProvider implements UserProvider { public function getCurrentUserId() { $user = Auth::getUser(); if (!is_null($user)) { return $user->email; } else { return 'guest'; } } }
mpl-2.0
Yukarumya/Yukarum-Redfoxes
testing/talos/talos/config.py
16862
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. import sys import os import copy from mozlog.commandline import setup_logging from talos import utils, test from talos.cmdline import parse_args class ConfigurationError(Exception): pass DEFAULTS = dict( # args to pass to browser extra_args='', buildid='testbuildid', init_url='getInfo.html', env={'NO_EM_RESTART': '1'}, # base data for all tests basetest=dict( cycles=1, profile_path='${talos}/base_profile', responsiveness=False, e10s=False, sps_profile=False, sps_profile_interval=1, sps_profile_entries=100000, resolution=1, rss=False, mainthread=False, shutdown=False, timeout=3600, tpchrome=True, tpcycles=10, tpmozafterpaint=False, tpdisable_e10s=False, tpnoisy=True, tppagecycles=1, tploadnocache=False, tpscrolltest=False, tprender=False, win_counters=[], w7_counters=[], linux_counters=[], mac_counters=[], xperf_counters=[], setup=None, cleanup=None, ), # default preferences to run with # these are updated with --extraPrefs from the commandline # for extension scopes, see # see https://developer.mozilla.org/en/Installing_extensions preferences={ 'app.update.enabled': False, 'browser.addon-watch.interval': -1, # Deactivate add-on watching 'browser.aboutHomeSnippets.updateUrl': 'https://127.0.0.1/about-dummy/', 'browser.bookmarks.max_backups': 0, 'browser.cache.disk.smart_size.enabled': False, 'browser.cache.disk.smart_size.first_run': False, 'browser.chrome.dynamictoolbar': False, 'browser.dom.window.dump.enabled': True, 'browser.EULA.override': True, 'browser.link.open_newwindow': 2, 'browser.reader.detectedFirstArticle': True, 'browser.shell.checkDefaultBrowser': False, 'browser.warnOnQuit': False, 'browser.tabs.remote.autostart': False, 'dom.allow_scripts_to_close_windows': True, 'dom.disable_open_during_load': False, 'dom.disable_window_flip': True, 'dom.disable_window_move_resize': True, 'dom.max_chrome_script_run_time': 0, 'dom.max_script_run_time': 0, 'extensions.autoDisableScopes': 10, 'extensions.checkCompatibility': False, 'extensions.enabledScopes': 5, 'extensions.update.notifyUser': False, 'hangmonitor.timeout': 0, 'network.proxy.http': 'localhost', 'network.proxy.http_port': 80, 'network.proxy.type': 1, 'security.enable_java': False, 'security.fileuri.strict_origin_policy': False, 'dom.send_after_paint_to_content': True, 'security.turn_off_all_security_so_that_viruses_can_' 'take_over_this_computer': True, 'browser.newtabpage.directory.source': '${webserver}/directoryLinks.json', 'browser.newtabpage.directory.ping': '', 'browser.newtabpage.introShown': True, 'browser.safebrowsing.provider.google.gethashURL': 'http://127.0.0.1/safebrowsing-dummy/gethash', 'browser.safebrowsing.provider.google.updateURL': 'http://127.0.0.1/safebrowsing-dummy/update', 'browser.safebrowsing.provider.google4.gethashURL': 'http://127.0.0.1/safebrowsing4-dummy/gethash', 'browser.safebrowsing.provider.google4.updateURL': 'http://127.0.0.1/safebrowsing4-dummy/update', 'browser.safebrowsing.provider.mozilla.gethashURL': 'http://127.0.0.1/safebrowsing-dummy/gethash', 'browser.safebrowsing.provider.mozilla.updateURL': 'http://127.0.0.1/safebrowsing-dummy/update', 'privacy.trackingprotection.introURL': 'http://127.0.0.1/trackingprotection/tour', 'browser.safebrowsing.phishing.enabled': False, 'browser.safebrowsing.malware.enabled': False, 'browser.safebrowsing.forbiddenURIs.enabled': False, 'browser.safebrowsing.blockedURIs.enabled': False, 'privacy.trackingprotection.enabled': False, 'privacy.trackingprotection.pbmode.enabled': False, 'browser.search.isUS': True, 'browser.search.countryCode': 'US', 'browser.selfsupport.url': 'https://127.0.0.1/selfsupport-dummy/', 'extensions.update.url': 'http://127.0.0.1/extensions-dummy/updateURL', 'extensions.update.background.url': 'http://127.0.0.1/extensions-dummy/updateBackgroundURL', 'extensions.blocklist.enabled': False, 'extensions.blocklist.url': 'http://127.0.0.1/extensions-dummy/blocklistURL', 'extensions.hotfix.url': 'http://127.0.0.1/extensions-dummy/hotfixURL', 'extensions.update.enabled': False, 'extensions.webservice.discoverURL': 'http://127.0.0.1/extensions-dummy/discoveryURL', 'extensions.getAddons.maxResults': 0, 'extensions.getAddons.get.url': 'http://127.0.0.1/extensions-dummy/repositoryGetURL', 'extensions.getAddons.getWithPerformance.url': 'http://127.0.0.1/extensions-dummy' '/repositoryGetWithPerformanceURL', 'extensions.getAddons.search.browseURL': 'http://127.0.0.1/extensions-dummy/repositoryBrowseURL', 'extensions.getAddons.search.url': 'http://127.0.0.1/extensions-dummy/repositorySearchURL', 'media.gmp-manager.url': 'http://127.0.0.1/gmpmanager-dummy/update.xml', 'media.gmp-manager.updateEnabled': False, 'extensions.systemAddon.update.url': 'http://127.0.0.1/dummy-system-addons.xml', 'extensions.shield-recipe-client.api_url': 'https://127.0.0.1/selfsupport-dummy/', 'media.navigator.enabled': True, 'media.peerconnection.enabled': True, 'media.navigator.permission.disabled': True, 'media.capturestream_hints.enabled': True, 'browser.contentHandlers.types.0.uri': 'http://127.0.0.1/rss?url=%s', 'browser.contentHandlers.types.1.uri': 'http://127.0.0.1/rss?url=%s', 'browser.contentHandlers.types.2.uri': 'http://127.0.0.1/rss?url=%s', 'browser.contentHandlers.types.3.uri': 'http://127.0.0.1/rss?url=%s', 'browser.contentHandlers.types.4.uri': 'http://127.0.0.1/rss?url=%s', 'browser.contentHandlers.types.5.uri': 'http://127.0.0.1/rss?url=%s', 'identity.fxaccounts.auth.uri': 'https://127.0.0.1/fxa-dummy/', 'datareporting.healthreport.about.reportUrl': 'http://127.0.0.1/abouthealthreport/', 'datareporting.healthreport.documentServerURI': 'http://127.0.0.1/healthreport/', 'datareporting.policy.dataSubmissionPolicyBypassNotification': True, 'general.useragent.updates.enabled': False, 'browser.webapps.checkForUpdates': 0, 'browser.search.geoSpecificDefaults': False, 'browser.snippets.enabled': False, 'browser.snippets.syncPromo.enabled': False, 'toolkit.telemetry.server': 'https://127.0.0.1/telemetry-dummy/', 'experiments.manifest.uri': 'https://127.0.0.1/experiments-dummy/manifest', 'network.http.speculative-parallel-limit': 0, 'app.update.badge': False, 'lightweightThemes.selectedThemeID': "", 'devtools.webide.widget.enabled': False, 'devtools.webide.widget.inNavbarByDefault': False, 'devtools.chrome.enabled': False, 'devtools.debugger.remote-enabled': False, 'devtools.theme': "light", 'devtools.timeline.enabled': False, 'identity.fxaccounts.migrateToDevEdition': False, 'media.libavcodec.allow-obsolete': True } ) # keys to generated self.config that are global overrides to tests GLOBAL_OVERRIDES = ( 'cycles', 'sps_profile', 'sps_profile_interval', 'sps_profile_entries', 'rss', 'mainthread', 'shutdown', 'tpcycles', 'tpdelay', 'tppagecycles', 'tpmanifest', 'tptimeout', 'tpmozafterpaint', ) CONF_VALIDATORS = [] def validator(func): """ A decorator that register configuration validators to execute against the configuration. They will be executed in the order of declaration. """ CONF_VALIDATORS.append(func) return func def convert_url(config, url): webserver = config['webserver'] if not webserver: return url if '://' in url: # assume a fully qualified url return url if '.html' in url: url = 'http://%s/%s' % (webserver, url) return url @validator def fix_xperf(config): # BBB: remove doubly-quoted xperf values from command line # (needed for buildbot) # https://bugzilla.mozilla.org/show_bug.cgi?id=704654#c43 if config['xperf_path']: xperf_path = config['xperf_path'] quotes = ('"', "'") for quote in quotes: if xperf_path.startswith(quote) and xperf_path.endswith(quote): config['xperf_path'] = xperf_path[1:-1] break if not os.path.exists(config['xperf_path']): raise ConfigurationError( "xperf.exe cannot be found at the path specified") @validator def set_webserver(config): # pick a free port import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('', 0)) port = sock.getsockname()[1] sock.close() config['webserver'] = 'localhost:%d' % port @validator def update_prefs(config): # if e10s is enabled, set prefs accordingly if config['e10s']: config['preferences']['browser.tabs.remote.autostart'] = True config['preferences']['extensions.e10sBlocksEnabling'] = False else: config['preferences']['browser.tabs.remote.autostart'] = False config['preferences']['browser.tabs.remote.autostart.1'] = False config['preferences']['browser.tabs.remote.autostart.2'] = False # update prefs from command line prefs = config.pop('extraPrefs') if prefs: for arg in prefs: k, v = arg.split('=', 1) config['preferences'][k] = utils.parse_pref(v) @validator def fix_init_url(config): if 'init_url' in config: config['init_url'] = convert_url(config, config['init_url']) def get_counters(config): counters = set() if config['rss']: counters.add('Main_RSS') return counters def get_active_tests(config): activeTests = config.pop('activeTests').strip().split(':') # ensure tests are available availableTests = test.test_dict() if not set(activeTests).issubset(availableTests): missing = [i for i in activeTests if i not in availableTests] raise ConfigurationError("No definition found for test(s): %s" % missing) # disabled DAMP on winXP: frequent hangs, <3% of devtools users on winXP if utils.PLATFORM_TYPE == 'win_': activeTests = [i for i in activeTests if i != 'damp'] return activeTests def get_global_overrides(config): global_overrides = {} for key in GLOBAL_OVERRIDES: # get global overrides for all tests value = config[key] if value is not None: global_overrides[key] = value if key != 'sps_profile': config.pop(key) # add noChrome to global overrides (HACK) noChrome = config.pop('noChrome') if noChrome: global_overrides['tpchrome'] = False # HACK: currently xperf tests post results to graph server and # we want to ensure we don't publish shutdown numbers # This is also hacked because "--noShutdown -> shutdown:True" if config['xperf_path']: global_overrides['shutdown'] = False return global_overrides def build_manifest(config, manifestName): # read manifest lines with open(manifestName, 'r') as fHandle: manifestLines = fHandle.readlines() # write modified manifest lines with open(manifestName + '.develop', 'w') as newHandle: for line in manifestLines: newline = line.replace('localhost', config['webserver']) newline = newline.replace('page_load_test', 'tests') newHandle.write(newline) newManifestName = manifestName + '.develop' # return new manifest return newManifestName def get_test(config, global_overrides, counters, test_instance): mozAfterPaint = getattr(test_instance, 'tpmozafterpaint', None) test_instance.update(**global_overrides) # update original value of mozAfterPaint, this could be 'false', # so check for None if mozAfterPaint is not None: test_instance.tpmozafterpaint = mozAfterPaint # fix up url url = getattr(test_instance, 'url', None) if url: test_instance.url = utils.interpolate(convert_url(config, url)) # fix up tpmanifest tpmanifest = getattr(test_instance, 'tpmanifest', None) if tpmanifest: test_instance.tpmanifest = \ build_manifest(config, utils.interpolate(tpmanifest)) # add any counters if counters: keys = ('linux_counters', 'mac_counters', 'win_counters', 'w7_counters', 'xperf_counters') for key in keys: if key not in test_instance.keys: # only populate attributes that will be output continue if not isinstance(getattr(test_instance, key, None), list): setattr(test_instance, key, []) _counters = getattr(test_instance, key) _counters.extend([counter for counter in counters if counter not in _counters]) return dict(test_instance.items()) @validator def tests(config): counters = get_counters(config) global_overrides = get_global_overrides(config) activeTests = get_active_tests(config) test_dict = test.test_dict() tests = [] for test_name in activeTests: test_class = test_dict[test_name] tests.append(get_test(config, global_overrides, counters, test_class())) config['tests'] = tests def get_browser_config(config): required = ('preferences', 'extensions', 'browser_path', 'browser_wait', 'extra_args', 'buildid', 'env', 'init_url', 'webserver') optional = {'bcontroller_config': '${talos}/bcontroller.json', 'branch_name': '', 'child_process': 'plugin-container', 'develop': False, 'e10s': False, 'process': '', 'framework': 'talos', 'repository': None, 'sourcestamp': None, 'symbols_path': None, 'test_timeout': 1200, 'xperf_path': None, 'error_filename': None, } browser_config = dict(title=config['title']) browser_config.update(dict([(i, config[i]) for i in required])) browser_config.update(dict([(i, config.get(i, j)) for i, j in optional.items()])) return browser_config def suites_conf(): import json with open(os.path.join(os.path.dirname(utils.here), 'talos.json')) as f: return json.load(f)['suites'] def get_config(argv=None): argv = argv or sys.argv[1:] cli_opts = parse_args(argv=argv) if cli_opts.suite: # read the suite config, update the args try: suite_conf = suites_conf()[cli_opts.suite] except KeyError: raise ConfigurationError('No such suite: %r' % cli_opts.suite) argv += ['-a', ':'.join(suite_conf['tests'])] argv += suite_conf.get('talos_options', []) # args needs to be reparsed now elif not cli_opts.activeTests: raise ConfigurationError('--activeTests or --suite required!') cli_opts = parse_args(argv=argv) setup_logging("talos", cli_opts, {"tbpl": sys.stdout}) config = copy.deepcopy(DEFAULTS) config.update(cli_opts.__dict__) for validate in CONF_VALIDATORS: validate(config) # remove None Values for k, v in config.items(): if v is None: del config[k] return config def get_configs(argv=None): config = get_config(argv=argv) browser_config = get_browser_config(config) return config, browser_config if __name__ == '__main__': cfgs = get_configs() print(cfgs[0]) print print(cfgs[1])
mpl-2.0
sthaiya/muzima-android
app/src/main/java/com/muzima/view/maps/GPSLocationPickerActivity.java
10821
/* * Copyright (c) The Trustees of Indiana University, Moi University * and Vanderbilt University Medical Center. All Rights Reserved. * * This version of the code is licensed under the MPL 2.0 Open Source license * with additional health care disclaimer. * If the user is an entity intending to commercialize any application that uses * this code in a for-profit venture, please contact the copyright holder. */ package com.muzima.view.maps; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.location.LocationListener; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.util.Log; import android.view.View; import android.webkit.ConsoleMessage; import android.webkit.JavascriptInterface; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.Button; import android.widget.Toast; import com.muzima.MuzimaApplication; import com.muzima.R; import com.muzima.api.model.MuzimaSetting; import com.muzima.controller.MuzimaSettingController; import com.muzima.model.location.MuzimaGPSLocation; import com.muzima.service.MuzimaGPSLocationService; import com.muzima.util.Constants; import com.muzima.utils.LanguageUtil; import com.muzima.utils.StringUtils; import com.muzima.utils.ThemeUtils; import com.muzima.view.BroadcastListenerActivity; import org.json.JSONException; import org.json.JSONObject; import static android.webkit.ConsoleMessage.MessageLevel.ERROR; import static com.muzima.service.MuzimaGPSLocationService.REQUEST_LOCATION; import static com.muzima.utils.Constants.MuzimaGPSLocationConstants.LOCATION_ACCESS_PERMISSION_REQUEST_CODE; import static java.text.MessageFormat.format; public class GPSLocationPickerActivity extends BroadcastListenerActivity { public static String LATITUDE = "Latitude"; public static String LONGITUDE = "Longitude"; public static String DEFAULT_ZOOM_LEVEL = "DefaultZoomLevel"; private String latitude; private String longitude; private int defaultZoomLevel; private final ThemeUtils themeUtils = new ThemeUtils(); private MuzimaGPSLocationService gpsLocationService; private final LanguageUtil languageUtil = new LanguageUtil(); private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { themeUtils.onCreate(this); languageUtil.onCreate(this); super.onCreate(savedInstanceState); setContentView(R.layout.activity_map_location_picker); if(getIntent().hasExtra(LATITUDE)){ latitude = getIntent().getStringExtra(LATITUDE); } if(getIntent().hasExtra(LONGITUDE)){ longitude = getIntent().getStringExtra(LONGITUDE); } defaultZoomLevel = getIntent().getIntExtra(DEFAULT_ZOOM_LEVEL,12); checkAndRequestGPSPermissions(); } @Override protected void onResume(){ super.onResume(); themeUtils.onResume(this); languageUtil.onResume(this); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if(requestCode == REQUEST_LOCATION){ if(resultCode != Activity.RESULT_OK){ Toast.makeText(this,"Could not obtain the current GPS location.",Toast.LENGTH_LONG).show(); latitude = "0.5117"; longitude = "35.282614"; } else { getLastKnowntGPSLocation(); } initializeLocationPickerActionButtons(); initializeLocationPickerMapView(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //ToDo: Pass request code as parameter to gpslocationservice if (requestCode == LOCATION_ACCESS_PERMISSION_REQUEST_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { checkAndRequestGPSPermissions(); } else { Toast.makeText(this,"Could not obtain the current GPS location.",Toast.LENGTH_LONG).show(); latitude = "0.5117"; longitude = "35.282614"; initializeLocationPickerActionButtons(); initializeLocationPickerMapView(); } } } private void checkAndRequestGPSPermissions(){ gpsLocationService = ((MuzimaApplication)getApplicationContext()).getMuzimaGPSLocationService(); if (!gpsLocationService.isGPSLocationPermissionsGranted()) { gpsLocationService.requestGPSLocationPermissions(this, true); } else{ LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(android.location.Location location) { webView.loadUrl("javascript:document.updateCurrentLocationAndAccuracy(" + location.getLatitude() + ", " + location.getLongitude() + "," + location.getAccuracy() +")"); } @Override public void onStatusChanged(String provider, int status, Bundle extras) {} @Override public void onProviderEnabled(String provider) {} @Override public void onProviderDisabled(String provider) {} }; if (!gpsLocationService.isLocationServicesSwitchedOn()) { gpsLocationService.requestSwitchOnLocation(this,locationListener); } else { gpsLocationService.requestLocationUpdates(locationListener); getLastKnowntGPSLocation(); initializeLocationPickerActionButtons(); initializeLocationPickerMapView(); } } } private void getLastKnowntGPSLocation(){ MuzimaGPSLocation muzimaGPSLocation = gpsLocationService.getLastKnownGPSLocation(); if(muzimaGPSLocation != null){ latitude = muzimaGPSLocation.getLatitude(); longitude = muzimaGPSLocation.getLongitude(); } } private void initializeLocationPickerActionButtons(){ Button nextButton = findViewById(R.id.next); nextButton.setOnClickListener(useSelectdedLocationButtonListener()); Button previousButton = findViewById(R.id.previous); previousButton.setOnClickListener(cancelButtonListener()); } private void initializeLocationPickerMapView(){ webView = findViewById(R.id.webview); webView.setWebChromeClient(createWebChromeClient()); WebSettings webSettings = webView.getSettings(); webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH); webSettings.setJavaScriptEnabled(true); webSettings.setDatabaseEnabled(true); webSettings.setDomStorageEnabled(true); webSettings.setBuiltInZoomControls(false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { webView.setWebContentsDebuggingEnabled(true); } webView.addJavascriptInterface(this,"locationPickerInterface"); webView.loadUrl("file:///android_asset/www/maps/mapLocationPicker.html"); } @JavascriptInterface public void updateSelectedLocation(String latitude, String longitude){ this.latitude = latitude; this.longitude = longitude; } @JavascriptInterface public int getDefaultZoomLevel(){ return defaultZoomLevel; } @JavascriptInterface public String getCurrentGPSLocation(){ if(!StringUtils.isEmpty(latitude) && !StringUtils.isEmpty(longitude)){ try { JSONObject jsonObject = new JSONObject(); jsonObject.put("latitude", latitude); jsonObject.put("longitude", longitude); return jsonObject.toString(); } catch (JSONException e) { Log.e(getClass().getSimpleName(), "Error building Json Object for location details",e); } } MuzimaGPSLocation gpsLocation = ((MuzimaApplication)getApplicationContext()).getMuzimaGPSLocationService().getLastKnownGPSLocation(); try { if(gpsLocation != null) { return gpsLocation.toJsonObject().toString(); } } catch (JSONException e) { Log.e(getClass().getSimpleName(), "Error while obtaining GPS location", e); } return null; } @JavascriptInterface public String getMapsAPIKey(){ try { MuzimaSetting muzimaSetting = ((MuzimaApplication) getApplicationContext()).getMuzimaSettingController() .getSettingByProperty(Constants.ServerSettings.MAPS_API_KEY); if(muzimaSetting != null){ return muzimaSetting.getValueString(); } } catch (MuzimaSettingController.MuzimaSettingFetchException e) { Log.e(getClass().getSimpleName(), "Could not obtain API key",e); } return null; } private WebChromeClient createWebChromeClient() { return new WebChromeClient() { @Override public void onProgressChanged(WebView view, int progress) { } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { String message = format("Javascript Log. Message: {0}, lineNumber: {1}, sourceId, {2}", consoleMessage.message( ), consoleMessage.lineNumber( ), consoleMessage.sourceId( )); if (consoleMessage.messageLevel( ) == ERROR) { Log.e(getClass().getSimpleName(), message); } else { Log.d(getClass().getSimpleName(), message); } return true; } }; } private View.OnClickListener cancelButtonListener() { return new View.OnClickListener() { @Override public void onClick(View v) { Intent resultIntent = new Intent(); setResult(RESULT_CANCELED, resultIntent); finish(); } }; } private View.OnClickListener useSelectdedLocationButtonListener(){ return new View.OnClickListener() { @Override public void onClick(View v) { Intent resultIntent = new Intent(); resultIntent.putExtra(LATITUDE, latitude); resultIntent.putExtra(LONGITUDE, longitude); setResult(RESULT_OK, resultIntent); finish(); } }; } }
mpl-2.0
DarylPinto/stickers-for-discord
bot/commands/delete-sticker.js
1821
const rp = require('request-promise'); module.exports = function(message, bot_auth, prefix){ let message_words = message.content.trim().split(/\s+/); //Remove first word from message_words if command was invoked with an @ mention if(/<@!?\d+>/.test(message_words[0])) message_words.shift(); if(message.channel.type === 'dm') prefix = ''; //Escape prefix to avoid issues with Discord formatting let escaped_prefix = prefix.replace(/[^a-zA-Zа-яёА-ЯЁ0-9]/g, '\\$&'); if(message_words.length < 2){ message.channel.send(`Invalid Syntax. Use **${escaped_prefix}deleteSticker [STICKER NAME]**`); return; } let sticker_name = message_words[1].toLowerCase().replace(/(:|-)/g, ''); sticker_name = encodeURIComponent(sticker_name); let uri = `${process.env.APP_URL}/api/users/${message.author.id}/stickers/${sticker_name}`; if(message.channel.type === 'text'){ uri = `${process.env.APP_URL}/api/guilds/${message.channel.guild.id}/stickers/${sticker_name}`; } return rp({ method: 'DELETE', uri: uri, headers: { Authorization: bot_auth, 'Author-Id': message.author.id }, json: true }) .then(res => { sticker_name = decodeURIComponent(sticker_name); let sticker_display_name = (message.channel.type === 'dm') ? `-${sticker_name}` : `:${sticker_name}:`; message.channel.send(`\`${sticker_display_name}\` sticker deleted!`); }) .catch(err => { if(err.message.includes('does not have a custom sticker with that name')){ message.channel.send('There\'s no custom sticker with that name.'); } else if(err.message.includes('Unauthorized')){ message.channel.send(`You cannot delete stickers you didn't create.\nIf you want to manage your own custom stickers, private message this bot.`); } else{ message.channel.send('An unknown error occured.'); } }); }
mpl-2.0
Ricard/AppverseProject
app/bower_components/ag-grid/docs/angular-grid-sorting/example1.js
2310
var columnDefs = [ {headerName: "Athlete", field: "athlete", width: 150, sort: 'desc'}, {headerName: "Age", field: "age", width: 90}, {headerName: "Country", field: "country", width: 120}, {headerName: "Year", field: "year", width: 90, unSortIcon: true}, {headerName: "Date", field: "date", width: 110, comparator: dateComparator}, {headerName: "Sport", field: "sport", width: 110}, {headerName: "Gold", field: "gold", width: 100}, {headerName: "Silver", field: "silver", width: 100}, {headerName: "Bronze", field: "bronze", width: 100}, {headerName: "Total", field: "total", width: 100} ]; function dateComparator(date1, date2) { var date1Number = monthToComparableNumber(date1); var date2Number = monthToComparableNumber(date2); if (date1Number===null && date2Number===null) { return 0; } if (date1Number===null) { return -1; } if (date2Number===null) { return 1; } return date1Number - date2Number; } // eg 29/08/2004 gets converted to 20040829 function monthToComparableNumber(date) { if (date === undefined || date === null || date.length !== 10) { return null; } var yearNumber = date.substring(6,10); var monthNumber = date.substring(3,5); var dayNumber = date.substring(0,2); var result = (yearNumber*10000) + (monthNumber*100) + dayNumber; return result; } var gridOptions = { columnDefs: columnDefs, rowData: null, enableSorting: true }; // setup the grid after the page has finished loading document.addEventListener('DOMContentLoaded', function() { var gridDiv = document.querySelector('#myGrid'); new agGrid.Grid(gridDiv, gridOptions); // do http request to get our sample data - not using any framework to keep the example self contained. // you will probably use a framework like JQuery, Angular or something else to do your HTTP calls. var httpRequest = new XMLHttpRequest(); httpRequest.open('GET', '../olympicWinners.json'); httpRequest.send(); httpRequest.onreadystatechange = function() { if (httpRequest.readyState == 4 && httpRequest.status == 200) { var httpResult = JSON.parse(httpRequest.responseText); gridOptions.api.setRowData(httpResult); } }; });
mpl-2.0
new32/east
East.hh
34031
/* # Copyright (C) 2017 A. Gardiner # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <sstream> #include <string> #include <iostream> #include <fstream> #include <algorithm> #include <clang/Lex/Lexer.h> #include <clang/Lex/Token.h> #include <clang/AST/AST.h> #include <clang/AST/ASTConsumer.h> #include <clang/AST/RecursiveASTVisitor.h> #include <clang/Frontend/FrontendActions.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Tooling/ArgumentsAdjusters.h> #include <clang/Tooling/CommonOptionsParser.h> #include <clang/Tooling/Tooling.h> #include <clang/Rewrite/Core/Rewriter.h> #include <llvm/Support/raw_ostream.h> #ifndef EAST_HH #define EAST_HH 1 // EAST // Tool to demonstrate BRANCH, CONDITION and BLOCK coverage of C/C++ programs. // The following entities are tracked: // Conditions: ==, !=, >, >=, <, <=, &&, ||, ! (not) // Branch Conditions: If, Switch, For (counting), Do/While, Conditional Op (?) // Blocks: Function Entry, Keyword Body (including Else) // Not Tracked: // For-each, C++11 extension: // The iterative FOR body _is_ tracked as a block. In order to track the // branching, this would require reimplementing the interator logic // Loop Counting: // Not seen as necessary to demonstrate coverage of the looping conditions // since those _are_ instrumented. Ex: A do...while that never loops will // never show the WHILE as obtaining T coverage. // Coverage is obtained by modifying the original source to call coverage // functions to capture the entities state during execution. Reporting of that // coverage must be done by a separate tool (see east_report.py) // // COVERAGE TYPES // // Condition Coverage // Basic T/F coverage. A condition is considered fully covered when it has // both a True case and a False case. As C/C++ uses masking, coverage is // recorded only to the point of a short-circuit within a gate. // Ex: // IF(AA && BB) @ FT // Will only record AA at F and record no coverage of BB. // // Branch Coverage // Basic T/F coverage. Another name for decision coverage. A branch is // considered fully covered when it has both a True case and a False case, // regardless of the conditions within. For and While are considered True // when the loop body executes and False when the loop can no longer be // executed. Switches are considered True when a case within is executed and // False when the default (may be implied) is executed. // // Block Coverage // Basic Block Coverage. The entry into a compound statement related to a // keyword or the compound denoting a function's entry is counted for // block coverage. Unlike branch or condition coverage, a block is either hit // or it's not. Basic Block is used, rather than line oriented statement // coverage, as Basic Block assumes that any executable statements within the // block, at the blocks depth, must be executed simply by entering it. // Sub-blocks, such as an IF within a function, are tracked separately as // those are at a different depth. This will report redundances with some // coverage types, branch coverage for an IF shows the T/F coverage and thus // entry into the Then logic and Else logic, but is the only way to verify // other coverage, such as the For-each C++ construct and function entry for // functions containing only assignments. // // LIMITATIONS // // EAST is specifically designed for unit-testing. Though multiple files can // be instrumented simultaneously, the tracked entities are not individual per // file so multiple files will contain a CD0, BL0 and so on so a 'merged' EDAT // is not possible. However, since each source file produces it's own ECOV, it // is possible to test more than one file at a time, they just have to have // individual reports generated (1 for each EDAT/ECOV) // // Care must be taken with instrumented headers. As the functions are static, // a separate copy will be used for each included file however, if more than // one instrumented header is included, or an instrumented header is used with // an instrumented source file, a name collision of the EAST functions // *WILL* occur. // // TODO // // #1) Add block coverage for C89/ansi // This requires knowing where the variable declarations are for C89/ansi mode // (with -pedantic) since the current method will result in a warning being // issued (which may halt as an error with -Werror). Presently, the tool // disables block coverage for C89/ansi automatically. // namespace East { // =================================================================== bool DISABLE_SWITCH_INSTRUMENTATION = false; // -east-no-switch bool DISABLE_DO_INSTRUMENTATION = false; // -east-no-do bool DISABLE_WHILE_INSTRUMENTATION = false; // -east-no-while bool DISABLE_FOR_INSTRUMENTATION = false; // -east-no-for bool DISABLE_IF_INSTRUMENTATION = false; // -east-no-if bool DISABLE_TERNARY_INSTRUMENTATION = false; // -east-no-ternary bool DISABLE_BLOCK_INSTRUMENTATION = false; // -east-no-block // =================================================================== typedef struct __SWITCH_DATA__ { clang::SourceLocation location; std::vector<clang::SourceLocation> case_locations; std::vector<std::string> case_labels; } SwitchData; // =================================================================== class Instrumentor { private: clang::Rewriter* rewriter; std::vector<clang::SourceRange> conditions; std::vector<clang::SourceLocation> branches; std::vector<SwitchData> switches; std::vector<clang::SourceLocation> blocks; std::string base_file; std::string out_file; std::string edat_file; std::string ecov_file; public: // --------------------------------------------------------------- Instrumentor() { // empty } // --------------------------------------------------------------- void initialize( llvm::StringRef file, clang::Rewriter* base ) { rewriter = base; base_file = file.str(); conditions.clear(); branches.clear(); switches.clear(); blocks.clear(); out_file = base_file; out_file.insert( out_file.find( "." ), "_inst" ); edat_file = base_file + ".edat"; ecov_file = base_file + ".ecov"; ecov_file = ecov_file.substr( ecov_file.rfind("/")+1, ecov_file.length() ); } // --------------------------------------------------------------- bool isInBaseFile(clang::SourceLocation location) { // verify the token being processed is in the file passed to EAST std::string stmt = location.printToString(rewriter->getSourceMgr()); return (stmt.find(base_file) != std::string::npos); } // --------------------------------------------------------------- void addCondition(clang::SourceLocation begin, clang::SourceLocation end) { // add the condition span if not already present, setting the // instrumented source to call the appropriate EAST_CD_# call clang::SourceRange range(begin, end); if(std::find(conditions.begin(), conditions.end(), range) == conditions.end()) { std::stringstream text; text << "EAST_CD_" << conditions.size() << "("; rewriter->InsertText(begin, text.str(), true, true); rewriter->InsertTextAfterToken(end, ")"); conditions.push_back(clang::SourceRange(begin, end)); } } // --------------------------------------------------------------- void addBranch(clang::SourceLocation loc, clang::SourceLocation begin, clang::SourceLocation end) { // add the branch span if not already present, setting the // instrumented source to call the appropriate EAST_BR_# call if(std::find(branches.begin(), branches.end(), loc) == branches.end()) { std::stringstream text; text << "EAST_BR_" << branches.size() << "("; rewriter->InsertText(begin, text.str(), true, true); rewriter->InsertTextAfterToken(end, ")"); branches.push_back(loc); } } // --------------------------------------------------------------- void addBlock(clang::SourceLocation loc) { // add the block if not already present, setting the // instrumented source to call EAST_BL(#) if(std::find(blocks.begin(), blocks.end(), loc) == blocks.end()) { std::stringstream text; text << "EAST_BL(" << blocks.size() << ");"; rewriter->InsertTextAfterToken(loc, text.str()); blocks.push_back(loc); } } // --------------------------------------------------------------- void addSwitch(clang::SwitchStmt* sdata) { // add instrumentation to the switch to call the appropriate // EAST_SW_# call. Care has to be taken to obtain all the relevant // case labels to verify they are called uniquely, rather than // by pass through. SwitchData data; clang::SourceManager& source_manager = rewriter->getSourceMgr(); const clang::LangOptions& lang_opts = rewriter->getLangOpts(); clang::SwitchCase* case_ptr = sdata->getSwitchCaseList(); std::stringstream text; std::string token_spelling; data.location = sdata->getSwitchLoc(); // for each case, find the location of case entry // and the associated case label while(case_ptr != NULL) { token_spelling = ""; if(clang::isa<clang::DefaultStmt>(case_ptr)) { token_spelling = "default"; } else { clang::CaseStmt* case_stmt = clang::cast<clang::CaseStmt>(case_ptr); clang::SourceRange sr = case_stmt->getLHS()->getSourceRange(); clang::CharSourceRange csr; csr.setBegin( clang::Lexer::GetBeginningOfToken( sr.getBegin(), source_manager, lang_opts) ); csr.setEnd( clang::Lexer::getLocForEndOfToken( sr.getEnd(), 0, source_manager, lang_opts) ); token_spelling = clang::Lexer::getSourceText( csr, source_manager, lang_opts, NULL); } data.case_labels.push_back(token_spelling); data.case_locations.push_back(case_ptr->getKeywordLoc()); case_ptr = case_ptr->getNextSwitchCase(); } // parse the entry condition... if(sdata->getCond()) { clang::SourceLocation loc_b = sdata->getCond()->getLocStart(); clang::SourceLocation loc_e = sdata->getCond()->getLocEnd(); if( sdata->getConditionVariableDeclStmt() ) { loc_b = sdata->getConditionVariableDeclStmt()->getLocStart(); loc_e = sdata->getConditionVariableDeclStmt()->getLocEnd(); } loc_b = clang::Lexer::GetBeginningOfToken( loc_b, source_manager, lang_opts); loc_e = clang::Lexer::getLocForEndOfToken( loc_e, 0, source_manager, lang_opts); clang::CharSourceRange csr; csr.setBegin( loc_b ); csr.setEnd( loc_e ); token_spelling = clang::Lexer::getSourceText( csr, source_manager, lang_opts, NULL); // replacing the switch condition requires the addition of an extra // closing paren because the token location apparently overwrites it std::string::size_type assign_idx = token_spelling.find("="); if(assign_idx == std::string::npos) { text << "EAST_SW_" << switches.size() << "(" << token_spelling << "))"; } else { std::string str_b = token_spelling.substr(0, assign_idx+1); std::string str_e = token_spelling.substr(assign_idx+1, std::string::npos); text << str_b << "EAST_SW_" << switches.size() << "(" << str_e << "))"; } rewriter->ReplaceText(clang::SourceRange(loc_b, loc_e), llvm::StringRef(text.str())); } switches.push_back(data); } // --------------------------------------------------------------- void writeInst(void) { // generate the instrumented functions... // "ptext" is "prior" text that is to be written before the // original source. // "text" data is written after. std::stringstream ptext; std::stringstream text; ptext << "/* BEGIN EAST INSTRUMENTATION PROTOTYPES */" << std::endl << "#ifdef __cplusplus" << std::endl << "extern \"C\" {" << std::endl << "#endif" << std::endl; /* ** Compile time options for an East instrumented source file: ** -DEAST_COV=<path/to/file.ecov> ** Write the ECOV data to a different file. Overridden file needs ** to end in ".ecov". If the name doesn't match the source file, ** processing the coverage data will have to be done specifying the ** edat, source and ecov file. ** -DEAST_FOPEN=<fopen command> ** Override the system `fopen()` with a user supplied function. The ** override must implement the `FILE* fopen(char*)` interface. ** -DEAST_FPRINTF=<fprintf command> ** Override the system `fprintf` with a user supplied function. The ** override must implement the `fprintf(FILE*,char*,...)` ** interface. ** -DEAST_FCLOSE=<fclose command> ** Override the system `fclose()` with a user supplied function. The ** override must implement the `fclose(FILE*)` interface. */ text << "/* BEGIN EAST INSTRUMENTATION FUNCTIONS */" << std::endl << "#ifdef __cplusplus" << std::endl << "extern \"C\" {" << std::endl << "#endif" << std::endl << "#include <stdio.h>" << std::endl << std::endl << std::endl << "#ifndef EAST_FOPEN" << std::endl << " #define EAST_FOPEN fopen" << std::endl << "#endif" << std::endl << "#ifndef EAST_FPRINTF" << std::endl << " #define EAST_FPRINTF fprintf" << std::endl << "#endif" << std::endl << "#ifndef EAST_FCLOSE" << std::endl << " #define EAST_FCLOSE fclose" << std::endl << "#endif" << std::endl << std::endl << "#ifndef EAST_COV" << std::endl << " #define EAST_COV \"" << ecov_file << "\"" << std::endl << "#endif" << std::endl << std::endl; // condition std::string::size_type idx; for(idx = 0; idx < conditions.size(); idx++) { ptext << "static int EAST_CD_" << idx << "(int);" << std::endl; text << "static int EAST_CD_" << idx << "(int in) {" << std::endl << " FILE* fin = EAST_FOPEN(EAST_COV, \"a\");" << std::endl << " if(fin) {" << std::endl << " EAST_FPRINTF(fin, \"CD" << idx << ":%d\\n\", in);" << std::endl << " }" << std::endl << " EAST_FCLOSE(fin);" << std::endl << " return in;" << std::endl << "}" << std::endl << std::endl; } // branch for(idx = 0; idx < branches.size(); idx++) { ptext << "static int EAST_BR_" << idx << "(int);" << std::endl; text << "static int EAST_BR_" << idx << "(int in) {" << std::endl << " FILE* fin = EAST_FOPEN(EAST_COV, \"a\");" << std::endl << " if(fin) {" << std::endl << " EAST_FPRINTF(fin, \"BR" << idx << ":%d\\n\", in);" << std::endl << " }" << std::endl << " EAST_FCLOSE(fin);" << std::endl << " return in;" << std::endl << "}" << std::endl << std::endl; } // block ptext << "static int EAST_BL(int);" << std::endl; text << "static int EAST_BL(int in) {" << std::endl << " FILE* fin = EAST_FOPEN(EAST_COV, \"a\");" << std::endl << " if(fin) {" << std::endl << " EAST_FPRINTF(fin, \"BL%d:1\\n\", in);" << std::endl << " }" << std::endl << " EAST_FCLOSE(fin);" << std::endl << " return in;" << std::endl << "}" << std::endl << std::endl; // switch for(idx = 0; idx < switches.size(); idx++) { ptext << "static int EAST_SW_" << idx << "(int);" << std::endl; SwitchData data = switches[idx]; text << "static int EAST_SW_" << idx << "(int in) {" << std::endl << " FILE* fin = EAST_FOPEN(EAST_COV, \"a\");" << std::endl << " if(fin) {" << std::endl << " switch(in) {" << std::endl; bool has_default = false; for(std::string::size_type label_idx = 0; label_idx < data.case_labels.size(); label_idx++) { bool write_default = false; if(data.case_labels[label_idx] != "default") { text << " case " << data.case_labels[label_idx] << ":" << std::endl; } else { text << " default:" << std::endl; has_default = true; write_default = true; } text << " EAST_FPRINTF(fin, \"SW"<< idx <<".CS" << label_idx << ":1\\n\");" << std::endl; if(write_default) { text << " EAST_FPRINTF(fin, \"SW"<< idx << ":0\\n\");" << std::endl; } else { text << " EAST_FPRINTF(fin, \"SW"<< idx << ":1\\n\");" << std::endl; } text << " break;" << std::endl; } if(!has_default) { // if a default case was not found, add one to ensure that // False coverage of the switch can be obtained text << " default:" << std::endl << " EAST_FPRINTF(fin, \"SW"<< idx << ":0\\n\");" << std::endl << " break;" << std::endl; } text << " }" << std::endl << " }" << std::endl << " EAST_FCLOSE(fin);" << std::endl << " return in;" << std::endl << "}" << std::endl << std::endl; } ptext << "#ifdef __cplusplus" << std::endl << "}" << std::endl << "#endif" << std::endl << "/* END EAST INSTRUMENTATION PROTOTYPES */" << std::endl << std::endl; text << "#ifdef __cplusplus" << std::endl << "}" << std::endl << "#endif" << std::endl << "/* END EAST INSTRUMENTATION FUNCTIONS */" << std::endl << std::endl; // ...insert prototypes at the start of the file clang::SourceManager& source_manager = rewriter->getSourceMgr(); rewriter->InsertText( source_manager.getLocForStartOfFile(source_manager.getMainFileID()), ptext.str(), true, true); // ...insert definitions at the end of the file rewriter->InsertText( source_manager.getLocForEndOfFile(source_manager.getMainFileID()), text.str(), true, true); // ...and now write out the instrumented source std::cout << "M: Writing instrumented source\n"; llvm::StringRef filename(out_file); std::error_code code; llvm::raw_fd_ostream out_stream( filename, code, llvm::sys::fs::OpenFlags::F_Text); rewriter->getEditBuffer( rewriter->getSourceMgr().getMainFileID()).write(out_stream); out_stream.close(); } // --------------------------------------------------------------- void writeEdat(void) { // write the data for the covered entities clang::SourceManager& source_manager = rewriter->getSourceMgr(); const clang::LangOptions& lang_opts = rewriter->getLangOpts(); std::cout << "M: Writing Edat\n"; std::ofstream edat; edat.open(edat_file); std::string::size_type idx; edat << base_file << "\n"; for(idx = 0; idx < conditions.size(); idx++) { clang::SourceRange sr = conditions[idx]; clang::SourceLocation begin = sr.getBegin(); clang::SourceLocation end = sr.getEnd(); clang::Token token; std::string token_spelling = ""; if(begin == end) { if(!clang::Lexer::getRawToken( begin, token, source_manager, lang_opts)) { token_spelling = clang::Lexer::getSpelling( token, source_manager, lang_opts, NULL); } } else { clang::CharSourceRange csr; csr.setBegin( clang::Lexer::GetBeginningOfToken( begin, source_manager, lang_opts) ); csr.setEnd( clang::Lexer::getLocForEndOfToken( end, 0, source_manager, lang_opts) ); token_spelling = clang::Lexer::getSourceText( csr, source_manager, lang_opts, NULL); } edat << "CD" << idx << ":" << source_manager.getSpellingLineNumber(begin) << "." << source_manager.getSpellingColumnNumber(begin) << ":" << token_spelling << "\n"; } for(idx = 0; idx < branches.size(); idx++) { clang::SourceLocation sl = branches[idx]; clang::Token token; std::string token_spelling = ""; if(!clang::Lexer::getRawToken(sl, token, source_manager, lang_opts)) { token_spelling = clang::Lexer::getSpelling( token, source_manager, lang_opts, NULL); } edat << "BR" << idx << ":" << source_manager.getSpellingLineNumber(sl) << "." << source_manager.getSpellingColumnNumber(sl) << ":" << token_spelling << "\n"; } for(idx = 0; idx < blocks.size(); idx++) { clang::SourceLocation sl = blocks[idx]; std::string token_spelling = "BLOCK"; edat << "BL" << idx << ":" << source_manager.getSpellingLineNumber(sl) << "." << source_manager.getSpellingColumnNumber(sl) << ":" << token_spelling << "\n"; } for(idx = 0; idx < switches.size(); idx++) { clang::SourceLocation sl = switches[idx].location; clang::Token token; std::string token_spelling = ""; if(!clang::Lexer::getRawToken(sl, token, source_manager, lang_opts)) { token_spelling = clang::Lexer::getSpelling( token, source_manager, lang_opts, NULL); } edat << "SW" << idx << ":" << source_manager.getSpellingLineNumber(sl) << "." << source_manager.getSpellingColumnNumber(sl) << ":" << token_spelling << "\n"; std::string::size_type case_idx; for(case_idx = 0; case_idx < switches[idx].case_locations.size(); case_idx++) { token_spelling = ""; sl = switches[idx].case_locations[case_idx]; if(!clang::Lexer::getRawToken( sl, token, source_manager, lang_opts)) { token_spelling = clang::Lexer::getSpelling( token, source_manager, lang_opts, NULL); } edat << "SW" << idx << "." << "CS" << case_idx << ":" << source_manager.getSpellingLineNumber(sl) << "." << source_manager.getSpellingColumnNumber(sl) << ":" << token_spelling << "\n"; } } edat.close(); } }; // =================================================================== class Visitor : public clang::RecursiveASTVisitor<Visitor> { private: Instrumentor& instrumentor; public: // --------------------------------------------------------------- Visitor(Instrumentor &inst) : instrumentor(inst) { // do nothing } // --------------------------------------------------------------- bool VisitUnaryOperator(clang::UnaryOperator* op) { clang::SourceLocation location = op->getOperatorLoc(); if(instrumentor.isInBaseFile(location) && (!location.isMacroID()) ) { // only instrument the Logical Not (!) if(op->getOpcode() == clang::UO_LNot) { clang::SourceLocation end = op->getSubExpr()->getLocEnd(); instrumentor.addCondition(location, end); } } return true; } // --------------------------------------------------------------- clang::Expr* VisitConditionalOperator(clang::ConditionalOperator * op) { if(!DISABLE_TERNARY_INSTRUMENTATION) { clang::SourceLocation location = op->getCond()->getLocStart(); if(instrumentor.isInBaseFile(location) && (!location.isMacroID()) ) { clang::SourceLocation end = op->getCond()->getLocEnd(); instrumentor.addBranch(op->getQuestionLoc(), location, end); } } return op; } // --------------------------------------------------------------- clang::Expr* VisitBinaryOperator(clang::BinaryOperator* op) { clang::SourceLocation location = op->getLHS()->getLocStart(); if(instrumentor.isInBaseFile(location) && (!location.isMacroID()) ) { if(op->isLogicalOp() || op->isEqualityOp() || op->isRelationalOp()) { switch(op->getOpcode()) { case clang::BO_LAnd: case clang::BO_LOr: { clang::SourceRange lhs = op->getLHS()->getSourceRange(); clang::SourceRange rhs = op->getRHS()->getSourceRange(); instrumentor.addCondition(lhs.getBegin(), lhs.getEnd()); instrumentor.addCondition(rhs.getBegin(), rhs.getEnd()); } break; case clang::BO_EQ: case clang::BO_NE: case clang::BO_LT: case clang::BO_GT: case clang::BO_LE: case clang::BO_GE: instrumentor.addCondition(op->getLocStart(), op->getLocEnd()); break; default: // do nothing break; } } } return op; } // --------------------------------------------------------------- bool VisitStmt(clang::Stmt* stmt) { clang::SourceLocation location = stmt->getLocStart(); if(instrumentor.isInBaseFile(location) && (!location.isMacroID()) ) { if (clang::isa<clang::IfStmt>(stmt) ) { clang::IfStmt* IfStatement = clang::cast<clang::IfStmt>(stmt); clang::Stmt* Then = IfStatement->getThen(); clang::Stmt* Else = IfStatement->getElse(); if(Then && !DISABLE_IF_INSTRUMENTATION) { instrumentor.addBranch( IfStatement->getIfLoc(), IfStatement->getCond()->getLocStart(), IfStatement->getCond()->getLocEnd() ); } if(!DISABLE_BLOCK_INSTRUMENTATION) { if(Then) { instrumentor.addBlock(Then->getLocStart()); } if(Else) { // Check to make sure that the Else isn't an Else If // as the vistor views these as follows: // // Original: // if(aa)... // else if(bb)... // // Clang AST: // if(aa)... // else // if(bb)... clang::Stmt* curr_stmt = *(Else->child_begin()); if (curr_stmt && !clang::isa<clang::IfStmt>(curr_stmt) ) { instrumentor.addBlock(Else->getLocStart()); } } } } else if (clang::isa<clang::ForStmt>(stmt) ) { clang::ForStmt* ForStatement = clang::cast<clang::ForStmt>(stmt); clang::Stmt* Body = ForStatement->getBody(); if(Body && !DISABLE_FOR_INSTRUMENTATION) { instrumentor.addBranch( ForStatement->getForLoc(), ForStatement->getCond()->getLocStart(), ForStatement->getCond()->getLocEnd() ); } if(Body && !DISABLE_BLOCK_INSTRUMENTATION) { instrumentor.addBlock(Body->getLocStart()); } } else if (clang::isa<clang::WhileStmt>(stmt)) { clang::WhileStmt* WhileStatement = clang::cast<clang::WhileStmt>(stmt); clang::Stmt* Body = WhileStatement->getBody(); if(Body && !DISABLE_WHILE_INSTRUMENTATION) { instrumentor.addBranch( WhileStatement->getWhileLoc(), WhileStatement->getCond()->getLocStart(), WhileStatement->getCond()->getLocEnd() ); } if(Body && !DISABLE_BLOCK_INSTRUMENTATION) { instrumentor.addBlock(Body->getLocStart()); } } else if (clang::isa<clang::DoStmt>(stmt)) { clang::DoStmt* DoStmt = clang::cast<clang::DoStmt>(stmt); clang::Stmt* Body = DoStmt->getBody(); if(Body && !DISABLE_DO_INSTRUMENTATION) { instrumentor.addBranch( DoStmt->getWhileLoc(), DoStmt->getCond()->getLocStart(), DoStmt->getCond()->getLocEnd() ); } if(Body && !DISABLE_BLOCK_INSTRUMENTATION) { instrumentor.addBlock(Body->getLocStart()); } } else if (clang::isa<clang::SwitchStmt>(stmt)) { clang::SwitchStmt* SwitchStmt = clang::cast<clang::SwitchStmt>(stmt); if(!DISABLE_SWITCH_INSTRUMENTATION) { instrumentor.addSwitch(SwitchStmt); } if(!DISABLE_BLOCK_INSTRUMENTATION) { clang::SwitchCase* case_ptr = SwitchStmt->getSwitchCaseList(); while(case_ptr) { instrumentor.addBlock(case_ptr->getColonLoc()); case_ptr = case_ptr->getNextSwitchCase(); } } } } return true; } // --------------------------------------------------------------- bool VisitFunctionDecl(clang::FunctionDecl *func) { // Skip declarations if (func->hasBody()) { clang::Stmt *body = func->getBody(); clang::SourceLocation location = body->getLocStart(); if(instrumentor.isInBaseFile(location) && (!location.isMacroID()) ) { if(!DISABLE_BLOCK_INSTRUMENTATION) { instrumentor.addBlock(location); } } } return true; } }; // =================================================================== class Consumer : public clang::ASTConsumer { private: Visitor visitor; public: // --------------------------------------------------------------- Consumer(Instrumentor& inst) : visitor(inst) { // do nothing } // --------------------------------------------------------------- bool HandleTopLevelDecl(clang::DeclGroupRef DR) override { for (clang::DeclGroupRef::iterator b = DR.begin(), e = DR.end(); b != e; ++b) { visitor.TraverseDecl(*b); } return true; } }; // =================================================================== class Action : public clang::ASTFrontendAction { private: clang::Rewriter rewriter; Instrumentor instrumentor; public: // --------------------------------------------------------------- Action() { // do nothing } // --------------------------------------------------------------- std::unique_ptr<clang::ASTConsumer> CreateASTConsumer( clang::CompilerInstance& instance, llvm::StringRef file ) override { rewriter.setSourceMgr( instance.getSourceManager(), instance.getLangOpts() ); instrumentor.initialize( file, &rewriter ); return llvm::make_unique<Consumer>( instrumentor ); } // --------------------------------------------------------------- void EndSourceFileAction() override { instrumentor.writeEdat(); instrumentor.writeInst(); } }; } #endif
mpl-2.0
xiaoxiangs/devops
pedevops/login/migrations/0001_initial.py
1788
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='permission', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=64)), ('url', models.CharField(max_length=255)), ], ), migrations.CreateModel( name='role', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=64)), ('permission', models.ManyToManyField(related_name='permissionlist', to='login.permission', blank=True)), ], ), migrations.CreateModel( name='Users', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('username', models.CharField(max_length=150)), ('password', models.CharField(max_length=150, blank=True)), ('email', models.CharField(max_length=300, blank=True)), ('lastlogintime', models.CharField(max_length=64, null=True, blank=True)), ('lastloginip', models.CharField(max_length=75, blank=True)), ('createtime', models.CharField(max_length=64)), ('is_active', models.BooleanField(default=False)), ('role', models.ForeignKey(related_name='rolelist', blank=True, to='login.role', null=True)), ], ), ]
mpl-2.0
mozilla/idea-town-app
src/app/views/experiment_page.js
2593
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import View from 'ampersand-view'; import dom from 'ampersand-dom'; import mustache from 'mustache'; import webChannel from '../lib/web_channel'; export default View.extend({ template: mustache.render(`<section class="page" data-hook="experiment-page"> <h1 data-hook="displayName"></h1> <button data-hook="install">Install</button> </section>`), events: { 'click [data-hook=install]': 'install', 'click [data-hook=uninstall]': 'uninstall' }, initialize(opts) { if (opts && opts.experiment) { this.model = opts.experiment; } }, render(opts) { View.prototype.render.apply(this, arguments); this.renderWithTemplate(this); if (opts && opts.experiment) { this.model = opts.experiment; } this.heading = this.el.querySelector('[data-hook=displayName]'); dom.text(this.heading, this.model.displayName); this.button = this.el.querySelector('button'); this.renderButton(); }, // TODO: move into a base view? remove() { const parent = this.el.parentNode; if (parent) parent.removeChild(this.el); }, renderButton() { if (this.model.isInstalled) { dom.setAttribute(this.button, 'data-hook', 'uninstall'); dom.text(this.button, 'Uninstall'); } else { dom.setAttribute(this.button, 'data-hook', 'install'); dom.text(this.button, 'Install'); } }, // isInstall is a boolean: true if we are installing, false if uninstalling _updateAddon(isInstall) { this.model.isInstalled = !this.model.isInstalled; const packet = isInstall ? { install: this.model.name } : { uninstall: this.model.name }; webChannel.sendMessage('from-web-to-addon', packet); // TODO: have to delay updates, or the event delegation code will call // the other data-hook handler in the same turn (without yielding // to the UI thread). This seems like a bug in ampersand-view: // it seems to run through all of the install handlers, then re-check // the DOM for uninstall handlers, even though the click occurred // before the uninstall handlers hit the page. setTimeout(() => this.renderButton()); }, install(evt) { evt.preventDefault(); this._updateAddon(true); }, uninstall(evt) { evt.preventDefault(); this._updateAddon(false); } });
mpl-2.0
glasstowerstudios/intellitagger
src/com/glasstowerstudios/intellij/intellitagger/fixes/CreateLogtagFix.java
4930
package com.glasstowerstudios.intellij.intellitagger.fixes; import com.glasstowerstudios.intellij.intellitagger.operation.LogTagFieldAdder; import com.glasstowerstudios.intellij.intellitagger.resources.IntellitaggerBundle; import com.glasstowerstudios.intellij.intellitagger.settings.SettingsHelper; import com.intellij.codeInsight.daemon.impl.quickfix.CreateVarFromUsageFix; import com.intellij.codeInsight.intention.impl.BaseIntentionAction; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiField; import com.intellij.psi.PsiReference; import com.intellij.psi.PsiReferenceExpression; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.refactoring.rename.RenameJavaMemberProcessor; import com.intellij.refactoring.rename.RenamePsiElementProcessor; import com.intellij.usageView.UsageInfo; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import java.util.Collection; /** * A {@link BaseIntentionAction} (i.e. QuickFix) that allows for IDEA to add a 'LOGTAG' field to a * class automatically when it is detected that the variable with the specified name (exactly * "LOGTAG") is missing. */ public class CreateLogtagFix extends CreateVarFromUsageFix { public CreateLogtagFix(PsiReferenceExpression referenceElement) { super(referenceElement); } @Nls @Override protected String getText(String aVarName) { SettingsHelper.UndefinedReferencePolicy policy = SettingsHelper.getUndefinedReferencePolicy(); switch (policy) { case ADJUST_VARIABLE_NAME: return IntellitaggerBundle.message("add.logtag.adjust.text", myReferenceExpression.getReferenceName()); case ADJUST_REFERENCES: case NO_ADJUSTMENT: default: return IntellitaggerBundle.message("add.logtag.noAdjust.text", SettingsHelper.getLogtagVariableName()); } } @Override protected void invokeImpl(PsiClass psiClass) { SettingsHelper.UndefinedReferencePolicy policy = SettingsHelper.getUndefinedReferencePolicy(); switch (policy) { case ADJUST_VARIABLE_NAME: LogTagFieldAdder.addLogtagToClass(myReferenceExpression.getReferenceName(), psiClass); break; case ADJUST_REFERENCES: // We first add the member variable as the reference expression name, then perform a rename // refactoring to change it. LogTagFieldAdder.addLogtagToClass(myReferenceExpression.getReferenceName(), psiClass); renameAllReferences(psiClass, myReferenceExpression.getReferenceName(), SettingsHelper.getLogtagVariableName()); break; case NO_ADJUSTMENT: default: LogTagFieldAdder.addLogtagToClass(SettingsHelper.getLogtagVariableName(), psiClass); } } /** * Refactor all references of a member variable within a given {@link PsiClass} having a given * identifier to have another identifier. * * @param aClass The {@link PsiClass} defining the scope of the variable within which to search. * aFromName must be an identifier for a member variable of this class, or nothing * will happen. * @param aFromName The name/identifier of the reference to search for. * @param aToName The new name/identifier of the references after renaming is complete. */ private void renameAllReferences(PsiClass aClass, String aFromName, final String aToName) { final PsiElement member = getClassLevelMemberWithName(aClass, aFromName); if (member != null) { final Collection<PsiReference> allRefs = ReferencesSearch.search(member).findAll(); RenamePsiElementProcessor processor = RenameJavaMemberProcessor.forElement(member); UsageInfo usages[] = new UsageInfo[allRefs.size()]; int i = 0; for (PsiReference ref : allRefs) { usages[i] = new UsageInfo(ref); i++; } processor.renameElement(member, aToName, usages, null); } } /** * Retrieve the {@link PsiElement} having a given name within a {@link PsiClass}. * * @param aClass The {@link PsiClass} to search within. * @param aName The name of the variable to search for. * * @return The {@link PsiElement} member of class aClass having name aName, if it exists; null, * otherwise. */ private PsiElement getClassLevelMemberWithName(PsiClass aClass, String aName) { for (PsiElement nextElement : aClass.getChildren()) { if (nextElement instanceof PsiField) { PsiField field = (PsiField) nextElement; if (field.getName().equals(aName)) { return nextElement; } } } return null; } @Nls @NotNull @Override public String getFamilyName() { return IntellitaggerBundle.message("add.logtag.family"); } }
mpl-2.0
kingland/consul
ui-v2/app/utils/components/discovery-chain/index.js
4993
const getNodesByType = function(nodes = {}, type) { return Object.values(nodes).filter(item => item.Type === type); }; const findResolver = function(resolvers, service, nspace = 'default', dc) { if (typeof resolvers[service] === 'undefined') { resolvers[service] = { ID: `${service}.${nspace}.${dc}`, Name: service, Children: [], }; } return resolvers[service]; }; export const getAlternateServices = function(targets, a) { let type; const Targets = targets.map(function(b) { // TODO: this isn't going to work past namespace for services // with dots in the name, but by the time that becomes an issue // we might have more data from the endpoint so we don't have to guess // right now the backend also doesn't support dots in service names const [aRev, bRev] = [a, b].map(item => item.split('.').reverse()); const types = ['Datacenter', 'Namespace', 'Service', 'Subset']; return bRev.find(function(item, i) { const res = item !== aRev[i]; if (res) { type = types[i]; } return res; }); }); return { Type: type, Targets: Targets, }; }; export const getSplitters = function(nodes) { return getNodesByType(nodes, 'splitter').map(function(item) { // Splitters need IDs adding so we can find them in the DOM later item.ID = `splitter:${item.Name}`; // splitters have a service.nspace as a name // do the reverse dance to ensure we don't mess up any // serivice names with dots in them const temp = item.Name.split('.'); temp.reverse(); temp.shift(); temp.reverse(); item.Name = temp.join('.'); return item; }); }; export const getRoutes = function(nodes, uid) { return getNodesByType(nodes, 'router').reduce(function(prev, item) { return prev.concat( item.Routes.map(function(route, i) { // Routes also have IDs added via createRoute return createRoute(route, item.Name, uid); }) ); }, []); }; export const getResolvers = function(dc, nspace = 'default', targets = {}, nodes = {}) { const resolvers = {}; // make all our resolver nodes Object.values(nodes) .filter(item => item.Type === 'resolver') .forEach(function(item) { const parts = item.Name.split('.'); let subset; // this will leave behind the service.name.nspace.dc even if the service name contains a dot if (parts.length > 3) { subset = parts.shift(); } parts.reverse(); // slice off from dc.nspace onwards leaving the potentially dot containing service name // const nodeDc = parts.shift(); // const nodeNspace = parts.shift(); // if it does contain a dot put it back to the correct order parts.reverse(); const service = parts.join('.'); const resolver = findResolver(resolvers, service, nspace, dc); let failovers; if (typeof item.Resolver.Failover !== 'undefined') { // figure out what type of failover this is failovers = getAlternateServices(item.Resolver.Failover.Targets, item.Name); } if (subset) { const child = { Subset: true, ID: item.Name, Name: subset, }; if (typeof failovers !== 'undefined') { child.Failover = failovers; } resolver.Children.push(child); } else { if (typeof failovers !== 'undefined') { resolver.Failover = failovers; } } }); Object.values(targets).forEach(target => { // Failovers don't have a specific node if (typeof nodes[`resolver:${target.ID}`] !== 'undefined') { // We use this to figure out whether this target is a redirect target const alternate = getAlternateServices([target.ID], `service.${nspace}.${dc}`); // as Failovers don't make it here, we know anything that has alternateServices // must be a redirect if (alternate.Type !== 'Service') { // find the already created resolver const resolver = findResolver(resolvers, target.Service, nspace, dc); // and add the redirect as a child, redirects are always children const child = { Redirect: true, ID: target.ID, Name: target[alternate.Type], }; // redirects can then also have failovers // so it this one does, figure out what type they are and add them // to the redirect if (typeof nodes[`resolver:${target.ID}`].Resolver.Failover !== 'undefined') { child.Failover = getAlternateServices( nodes[`resolver:${target.ID}`].Resolver.Failover.Targets, target.ID ); } resolver.Children.push(child); } } }); return Object.values(resolvers); }; export const createRoute = function(route, router, uid) { return { ...route, Default: typeof route.Definition.Match === 'undefined', ID: `route:${router}-${uid(route.Definition)}`, }; };
mpl-2.0
Yukarumya/Yukarum-Redfoxes
ipc/ipdl/test/cxx/TestShutdown.cpp
7412
#include "TestShutdown.h" namespace mozilla { namespace _ipdltest { //----------------------------------------------------------------------------- // Parent side void TestShutdownParent::Main() { if (!SendStart()) fail("sending Start()"); } void TestShutdownParent::ActorDestroy(ActorDestroyReason why) { if (AbnormalShutdown != why) fail("should have ended test with crash!"); passed("ok"); QuitParent(); } void TestShutdownSubParent::ActorDestroy(ActorDestroyReason why) { if (Manager()->ManagedPTestShutdownSubParent().Count() == 0) fail("manager should still have managees!"); if (mExpectCrash && AbnormalShutdown != why) fail("expected crash!"); else if (!mExpectCrash && AbnormalShutdown == why) fail("wasn't expecting crash!"); if (mExpectCrash && 0 == ManagedPTestShutdownSubsubParent().Count()) fail("expected to *still* have kids"); } void TestShutdownSubsubParent::ActorDestroy(ActorDestroyReason why) { if (Manager()->ManagedPTestShutdownSubsubParent().Count() == 0) fail("manager should still have managees!"); if (mExpectParentDeleted && AncestorDeletion != why) fail("expected ParentDeleted == why"); else if (!mExpectParentDeleted && AncestorDeletion == why) fail("wasn't expecting parent delete"); } //----------------------------------------------------------------------------- // Child side mozilla::ipc::IPCResult TestShutdownChild::RecvStart() { // test 1: alloc some actors and subactors, delete in // managee-before-manager order { bool expectCrash = false, expectParentDeleted = false; PTestShutdownSubChild* c1 = SendPTestShutdownSubConstructor(expectCrash); if (!c1) fail("problem sending ctor"); PTestShutdownSubChild* c2 = SendPTestShutdownSubConstructor(expectCrash); if (!c2) fail("problem sending ctor"); PTestShutdownSubsubChild* c1s1 = c1->SendPTestShutdownSubsubConstructor(expectParentDeleted); if (!c1s1) fail("problem sending ctor"); PTestShutdownSubsubChild* c1s2 = c1->SendPTestShutdownSubsubConstructor(expectParentDeleted); if (!c1s2) fail("problem sending ctor"); PTestShutdownSubsubChild* c2s1 = c2->SendPTestShutdownSubsubConstructor(expectParentDeleted); if (!c2s1) fail("problem sending ctor"); PTestShutdownSubsubChild* c2s2 = c2->SendPTestShutdownSubsubConstructor(expectParentDeleted); if (!c2s2) fail("problem sending ctor"); if (!PTestShutdownSubsubChild::Send__delete__(c1s1)) fail("problem sending dtor"); if (!PTestShutdownSubsubChild::Send__delete__(c1s2)) fail("problem sending dtor"); if (!PTestShutdownSubsubChild::Send__delete__(c2s1)) fail("problem sending dtor"); if (!PTestShutdownSubsubChild::Send__delete__(c2s2)) fail("problem sending dtor"); if (!c1->CallStackFrame()) fail("problem creating dummy stack frame"); if (!c2->CallStackFrame()) fail("problem creating dummy stack frame"); } // test 2: alloc some actors and subactors, delete managers first { bool expectCrash = false, expectParentDeleted = true; PTestShutdownSubChild* c1 = SendPTestShutdownSubConstructor(expectCrash); if (!c1) fail("problem sending ctor"); PTestShutdownSubChild* c2 = SendPTestShutdownSubConstructor(expectCrash); if (!c2) fail("problem sending ctor"); PTestShutdownSubsubChild* c1s1 = c1->SendPTestShutdownSubsubConstructor(expectParentDeleted); if (!c1s1) fail("problem sending ctor"); PTestShutdownSubsubChild* c1s2 = c1->SendPTestShutdownSubsubConstructor(expectParentDeleted); if (!c1s2) fail("problem sending ctor"); PTestShutdownSubsubChild* c2s1 = c2->SendPTestShutdownSubsubConstructor(expectParentDeleted); if (!c2s1) fail("problem sending ctor"); PTestShutdownSubsubChild* c2s2 = c2->SendPTestShutdownSubsubConstructor(expectParentDeleted); if (!c2s2) fail("problem sending ctor"); // delete parents without deleting kids if (!c1->CallStackFrame()) fail("problem creating dummy stack frame"); if (!c2->CallStackFrame()) fail("problem creating dummy stack frame"); } // test 3: alloc some actors and subactors, then crash { bool expectCrash = true, expectParentDeleted = false; PTestShutdownSubChild* c1 = SendPTestShutdownSubConstructor(expectCrash); if (!c1) fail("problem sending ctor"); PTestShutdownSubChild* c2 = SendPTestShutdownSubConstructor(expectCrash); if (!c2) fail("problem sending ctor"); PTestShutdownSubsubChild* c1s1 = c1->SendPTestShutdownSubsubConstructor(expectParentDeleted); if (!c1s1) fail("problem sending ctor"); PTestShutdownSubsubChild* c1s2 = c1->SendPTestShutdownSubsubConstructor(expectParentDeleted); if (!c1s2) fail("problem sending ctor"); PTestShutdownSubsubChild* c2s1 = c2->SendPTestShutdownSubsubConstructor(expectParentDeleted); if (!c2s1) fail("problem sending ctor"); PTestShutdownSubsubChild* c2s2 = c2->SendPTestShutdownSubsubConstructor(expectParentDeleted); if (!c2s2) fail("problem sending ctor"); // make sure the ctors have been processed by the other side; // the write end of the socket may temporarily be unwriteable if (!SendSync()) fail("can't synchronize with parent"); // "crash", but without tripping tinderbox assert/abort // detectors _exit(0); } } void TestShutdownChild::ActorDestroy(ActorDestroyReason why) { fail("hey wait ... we should have crashed!"); } mozilla::ipc::IPCResult TestShutdownSubChild::AnswerStackFrame() { if (!PTestShutdownSubChild::Send__delete__(this)) fail("problem sending dtor"); // WATCH OUT! |this| has just deleted return IPC_OK(); } void TestShutdownSubChild::ActorDestroy(ActorDestroyReason why) { if (Manager()->ManagedPTestShutdownSubChild().Count() == 0) fail("manager should still have managees!"); if (mExpectCrash && AbnormalShutdown != why) fail("expected crash!"); else if (!mExpectCrash && AbnormalShutdown == why) fail("wasn't expecting crash!"); if (mExpectCrash && 0 == ManagedPTestShutdownSubsubChild().Count()) fail("expected to *still* have kids"); } void TestShutdownSubsubChild::ActorDestroy(ActorDestroyReason why) { if (Manager()->ManagedPTestShutdownSubsubChild().Count() == 0) fail("manager should still have managees!"); if (mExpectParentDeleted && AncestorDeletion != why) fail("expected ParentDeleted == why"); else if (!mExpectParentDeleted && AncestorDeletion == why) fail("wasn't expecting parent delete"); } } // namespace _ipdltest } // namespace mozilla
mpl-2.0
richardwilkes/goblin
expression/new.go
1106
// Copyright ©2017-2020 by Richard A. Wilkes. All rights reserved. // // This Source Code Form is subject to the terms of the Mozilla Public // License, version 2.0. If a copy of the MPL was not distributed with // this file, You can obtain one at http://mozilla.org/MPL/2.0/. // // This Source Code Form is "Incompatible With Secondary Licenses", as // defined by the Mozilla Public License, version 2.0. package expression import ( "fmt" "reflect" "github.com/richardwilkes/goblin/ast" ) // New defines a new instance expression. type New struct { ast.PosImpl Type string } func (expr *New) String() string { return fmt.Sprintf("new(%s)", expr.Type) } // Invoke the expression and return a result. func (expr *New) Invoke(scope ast.Scope) (reflect.Value, error) { rt, err := scope.Type(expr.Type) if err != nil { return ast.NilValue, ast.NewError(expr, err) } return reflect.New(rt), nil } // Assign a value to the expression and return it. func (expr *New) Assign(rv reflect.Value, scope ast.Scope) (reflect.Value, error) { return ast.NilValue, ast.NewInvalidOperationError(expr) }
mpl-2.0
riadhchtara/fxa-password-manager
app/scripts/models/auth_brokers/fx-desktop.js
5855
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /** * A broker that knows how to communicate with Firefox when used for Sync. */ define([ 'cocktail', 'underscore', 'models/auth_brokers/base', 'models/auth_brokers/mixins/channel', 'lib/auth-errors', 'lib/channels/fx-desktop-v1', 'lib/url' ], function (Cocktail, _, BaseAuthenticationBroker, ChannelMixin, AuthErrors, FxDesktopChannel, Url) { 'use strict'; var FxDesktopAuthenticationBroker = BaseAuthenticationBroker.extend({ type: 'fx-desktop-v1', _commands: { CAN_LINK_ACCOUNT: 'can_link_account', CHANGE_PASSWORD: 'change_password', DELETE_ACCOUNT: 'delete_account', LOADED: 'loaded', LOGIN: 'login', PASSWORD_MANAGER: 'password_manager', }, /** * Initialize the broker * * @param {Object} options * @param {String} options.channel * Channel used to send commands to remote listeners. */ initialize: function (options) { options = options || {}; // channel can be passed in for testing. this._channel = options.channel; return BaseAuthenticationBroker.prototype.initialize.call( this, options); }, afterLoaded: function () { return this.send(this._commands.LOADED); }, beforeSignIn: function (email) { var self = this; // This will send a message over the channel to determine whether // we should cancel the login to sync or not based on Desktop // specific checks and dialogs. It throws an error with // message='USER_CANCELED_LOGIN' and errno=1001 if that's the case. return self.request(self._commands.CAN_LINK_ACCOUNT, { email: email }) .then(function (response) { if (response && response.data && ! response.data.ok) { throw AuthErrors.toError('USER_CANCELED_LOGIN'); } self._verifiedCanLinkAccount = true; }, function (err) { console.error('beforeSignIn failed with', err); // If the browser doesn't implement this command, then it will // handle prompting the relink warning after sign in completes. // This can likely be changed to 'reject' after Fx31 hits nightly, // because all browsers will likely support 'can_link_account' }); }, afterSignIn: function (account) { return this._notifyRelierOfLogin(account) .then(function () { // the browser will take over from here, // don't let the screen transition. return { halt: true }; }); }, beforeSignUpConfirmationPoll: function (account) { // The Sync broker notifies the browser of an unverified login // before the user has verified her email. This allows the user // to close the original tab or open the verification link in // the about:accounts tab and have Sync still successfully start. return this._notifyRelierOfLogin(account) .then(function () { // the browser is already polling, no need for the content server // code to poll as well, otherwise two sets of polls are going on // for the same user. return { halt: true }; }); }, afterResetPasswordConfirmationPoll: function (account) { return this._notifyRelierOfLogin(account) .then(function () { // the browser will take over from here, // don't let the screen transition. return { halt: true }; }); }, afterChangePassword: function (account) { return this.send( this._commands.CHANGE_PASSWORD, this._getLoginData(account)); }, afterDeleteAccount: function (account) { // no response is expected, so do not wait for one return this.send(this._commands.DELETE_ACCOUNT, { email: account.get('email'), uid: account.get('uid') }); }, // used by the ChannelMixin to get a channel. getChannel: function () { if (! this._channel) { this._channel = this.createChannel(); } return this._channel; }, createChannel: function () { var channel = new FxDesktopChannel(); channel.initialize({ window: this.window, // Fx Desktop browser will send messages with an origin of the string // `null`. These messages are trusted by the channel by default. // // 1) Fx on iOS and functional tests will send messages from the // content server itself. Accept messages from the content // server to handle these cases. // 2) Fx 18 (& FxOS 1.*) do not support location.origin. Build the origin from location.href origin: this.window.location.origin || Url.getOrigin(this.window.location.href) }); channel.on('error', this.trigger.bind(this, 'error')); return channel; }, _notifyRelierOfLogin: function (account) { return this.send(this._commands.LOGIN, this._getLoginData(account)); }, _getLoginData: function (account) { var ALLOWED_FIELDS = [ 'email', 'uid', 'sessionToken', 'sessionTokenContext', 'unwrapBKey', 'keyFetchToken', 'customizeSync', 'verified' ]; var loginData = {}; _.each(ALLOWED_FIELDS, function (field) { loginData[field] = account.get(field); }); loginData.verified = !! loginData.verified; loginData.verifiedCanLinkAccount = !! this._verifiedCanLinkAccount; return loginData; } }); Cocktail.mixin( FxDesktopAuthenticationBroker, ChannelMixin ); return FxDesktopAuthenticationBroker; });
mpl-2.0
nellyk/android-client
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/centerlist/CenterListPresenter.java
3221
package com.mifos.mifosxdroid.online.centerlist; import com.mifos.api.DataManager; import com.mifos.mifosxdroid.base.Presenter; import com.mifos.objects.group.Center; import com.mifos.objects.group.CenterWithAssociations; import java.util.List; import javax.inject.Inject; import rx.Subscriber; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by Rajan Maurya on 5/6/16. */ public class CenterListPresenter implements Presenter<CenterListMvpView> { private final DataManager mDataManager; private Subscription mSubscription; private CenterListMvpView mCenterListMvpView; @Inject public CenterListPresenter(DataManager dataManager) { mDataManager = dataManager; } @Override public void attachView(CenterListMvpView mvpView) { mCenterListMvpView = mvpView; } @Override public void detachView() { mCenterListMvpView = null; if (mSubscription != null) mSubscription.unsubscribe(); } public void loadCenters() { mCenterListMvpView.showProgressbar(true); if (mSubscription != null) mSubscription.unsubscribe(); mSubscription = mDataManager.getCenters() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<List<Center>>() { @Override public void onCompleted() { mCenterListMvpView.showProgressbar(false); } @Override public void onError(Throwable e) { mCenterListMvpView.showProgressbar(false); mCenterListMvpView.showCenterGroupFetchinError(); } @Override public void onNext(List<Center> centers) { mCenterListMvpView.showProgressbar(false); mCenterListMvpView.showCenters(centers); } }); } public void loadCentersGroupAndMeeting(final int id) { mCenterListMvpView.showProgressbar(true); if (mSubscription != null) mSubscription.unsubscribe(); mSubscription = mDataManager.getCentersGroupAndMeeting(id) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<CenterWithAssociations>() { @Override public void onCompleted() { mCenterListMvpView.showProgressbar(false); } @Override public void onError(Throwable e) { mCenterListMvpView.showProgressbar(false); } @Override public void onNext(CenterWithAssociations centerWithAssociations) { mCenterListMvpView.showProgressbar(false); mCenterListMvpView.showCentersGroupAndMeeting( centerWithAssociations, id); } }); } }
mpl-2.0
tmhorne/celtx
toolkit/components/places/tests/unit/test_317472.js
4508
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Places unit test code. * * The Initial Developer of the Original Code is * Mozilla Corporation. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Marco Bonardo <mak77@supereva.it> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ const charset = "UTF-8"; const CHARSET_ANNO = "URIProperties/characterSet"; // Get history service try { var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"]. getService(Ci.nsINavHistoryService); var bhist = histsvc.QueryInterface(Ci.nsIBrowserHistory); var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"]. getService(Ci.nsINavBookmarksService); var annosvc = Cc["@mozilla.org/browser/annotation-service;1"]. getService(Ci.nsIAnnotationService); } catch(ex) { do_throw("Could not get services\n"); } function run_test() { do_test_pending(); var now = Date.now(); var testURI = uri("http://foo.com"); var testBookmarkedURI = uri("http://bar.com"); // add pages to history histsvc.addVisit(testURI, now, null, Ci.nsINavHistoryService.TRANSITION_TYPED, false, 0); histsvc.addVisit(testBookmarkedURI, now, null, Ci.nsINavHistoryService.TRANSITION_TYPED, false, 0); // create bookmarks on testBookmarkedURI var bm1 = bmsvc.insertBookmark(bmsvc.unfiledBookmarksFolder, testBookmarkedURI, bmsvc.DEFAULT_INDEX, testBookmarkedURI.spec); var bm2 = bmsvc.insertBookmark(bmsvc.toolbarFolder, testBookmarkedURI, bmsvc.DEFAULT_INDEX, testBookmarkedURI.spec); // set charset on not-bookmarked page histsvc.setCharsetForURI(testURI, charset); // set charset on bookmarked page histsvc.setCharsetForURI(testBookmarkedURI, charset); // check that we have created a page annotation do_check_eq(annosvc.getPageAnnotation(testURI, CHARSET_ANNO), charset); // get charset from not-bookmarked page do_check_eq(histsvc.getCharsetForURI(testURI), charset); // get charset from bookmarked page do_check_eq(histsvc.getCharsetForURI(testBookmarkedURI), charset); // clear history bhist.removeAllPages(); // ensure that charset has gone for not-bookmarked page do_check_neq(histsvc.getCharsetForURI(testURI), charset); // check that page annotation has been removed try { annosvc.getPageAnnotation(testURI, CHARSET_ANNO); do_throw("Charset page annotation has not been removed correctly"); } catch (e) {} // ensure that charset still exists for bookmarked page do_check_eq(histsvc.getCharsetForURI(testBookmarkedURI), charset); // remove charset from bookmark and check that has gone histsvc.setCharsetForURI(testBookmarkedURI, ""); do_check_neq(histsvc.getCharsetForURI(testBookmarkedURI), charset); do_test_finished(); }
mpl-2.0
realityeditor/server
hardwareInterfaces/camera/index.js
4884
exports.enabled = false; if (exports.enabled) { var http = require('http'); var server = require('../../libraries/hardwareInterfaces'); server.enableDeveloperUI(true); var SMTPServer = require('smtp-server').SMTPServer; var smtpServer = new SMTPServer({ onAuth: onSMTPAuth, onData: onSMTPData, disabledCommands: ['STARTTLS'], allowInsecureAuth: true }); smtpServer.listen(27183); var objectName = 'camera'; var motionDetectionDuration = 5000; var lastSMTPData = 0; function onSMTPAuth(auth, session, callback) { if (auth.username !== 'camera' || auth.password !== 'fluidnsa') { return callback(new Error('Invalid username or password')); } callback(null, {user: 'camera'}); } function onSMTPData(stream, session, callback) { lastSMTPData = Date.now(); stream.resume(); stream.on('end', function() { callback(null, 'OK'); }); } var deadzone = 0.01; var pan = 0; var tilt = 0; var requestInFlight = false; var updateTimeout = null; var motion = 0; var options = { hostname: '192.168.1.138', path: '/pantiltcontrol.cgi', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Referer': 'http://192.168.1.138' }, auth: 'admin:fluidnsa' }; function postToServer(path, body, callback) { options.path = path; options.headers['Content-Length'] = Buffer.byteLength(body); var req = http.request(options, function() { if (callback) { callback(); } }); req.on('error', function(e) { console.log('Problem with request:', e.message); if (callback) { callback(); } }); req.write(body); req.end(); } function sendPreset(preset) { postToServer('/setControlPanTilt', 'PanTiltPresetPositionMove=' + preset); } function writeMotion(newMotion) { motion = newMotion; server.write(objectName, 'motion', motion, 'f'); } function update() { if (lastSMTPData + motionDetectionDuration > Date.now()) { if (motion < 0.5) { writeMotion(1); } } else if (motion > 0.5) { writeMotion(0); } // Map pan and tilt to index // 0 is NW, 1 is N, etc. var index = -1; var panning = Math.abs(pan) > deadzone; var tilting = Math.abs(tilt) > deadzone; if (panning && tilting) { if (panning < 0) { if (tilting < 0) { index = 4; } else { index = 2; } } else { if (tilting > 0) { index = 0; } else { index = 6; } } } else if (panning) { if (pan < 0) { index = 3; } else { index = 5; } } else if (tilting) { if (tilt < 0) { index = 7; } else { index = 1; } } if (index !== -1) { sendMovement(index); } updateTimeout = setTimeout(update, 33); } function sendMovement(index) { // Note that this must balance overwhelming the camera with requests // (causing lag at end time) and sending requests too infrequently // (causing jitter) if (requestInFlight) { return; } requestInFlight = true; var body = 'PanSingleMoveDegree=1&TiltSingleMoveDegree=1&PanTiltSingleMove=' + index; postToServer('/pantiltcontrol.cgi', body, function() { requestInFlight = false; }); } server.addNode(objectName, 'pan', 'default'); server.addNode(objectName, 'tilt', 'default'); server.addNode(objectName, 'motion', 'default'); server.activate(objectName); server.addReadListener(objectName, 'pan', function(data) { pan = (data.value - 0.5) * 2; }); server.addReadListener(objectName, 'tilt', function(data) { tilt = (data.value - 0.5) * 2; }); update(); server.addEventListener('shutdown', function() { if (updateTimeout) { clearTimeout(updateTimeout); } }); var express = require('express'); var app = express(); var cors = require('cors'); app.use(cors()); app.use('/preset/:presetId', function(req, res) { sendPreset(req.params.presetId); res.send('complete'); }); app.listen(42448, function() { console.log('listening on 42448'); }); }
mpl-2.0
emilVenkov12/TelerikCourses
Programing/02.CSharpPart2Winter2013-2014/01.Arrays/01.Arrays-Homework/05.FindsMaxSeqOfIncrElems/FindsMaxSeqOfIncrElems.cs
2607
namespace _05.FindsMaxSeqOfIncrElems { using System; class FindsMaxSeqOfIncrElems { //05.Write a program that finds the maximal increasing sequence in an array. //Example: {3, 2, 3, 4, 2, 2, 4}  {2, 3, 4}. static void Main() { #region Manual input //Console.Write("Enter array numbers count: "); //int arrayLenght = 0; //while (!int.TryParse(Console.ReadLine(), out arrayLenght) || arrayLenght < 1) //{ // Console.Write("Enter valid array numbers count: "); //} //Console.ForegroundColor = ConsoleColor.Red; //Console.WriteLine("Enter only integer numbers!"); //Console.ForegroundColor = ConsoleColor.Gray; //Console.WriteLine("Enter array numbers"); //int[] array = new int[arrayLenght]; //for (int i = 0; i < arrayLenght; i++) //{ // int number = 0; // Console.Write("Enter {0}-th number:", i + 1); // while (!int.TryParse(Console.ReadLine(), out number)) // { // Console.Write("Enter valid {0}-th number:", i + 1); // } // array[i] = number; //} #endregion int[] array = new int[] { 3, 2, 3, 4, 2, 3, 4, 5 }; int startIndex = 0, endIndex = 0; int seqLenght = 1; int maxSeqLenght = 1, maxStartIndex = 0, maxEndIndex = 0; for (int i = 1; i < array.Length; i++) { if (array[i] <= array[i - 1]) // the only diff with prev task { if (seqLenght > maxSeqLenght) { maxSeqLenght = seqLenght; maxStartIndex = startIndex; maxEndIndex = endIndex; } startIndex = i; endIndex = i; seqLenght = 1; } else { endIndex = i; seqLenght++; } } if (seqLenght > maxSeqLenght) { maxSeqLenght = seqLenght; maxStartIndex = startIndex; maxEndIndex = endIndex; } for (int i = maxStartIndex; i <= maxEndIndex; i++) { Console.Write("{0}, ", array[i]); } } } }
mpl-2.0
DominoTree/servo
tests/wpt/web-platform-tests/offscreen-canvas/the-canvas-state/2d.state.saverestore.lineWidth.worker.js
1091
// DO NOT EDIT! This test has been generated by tools/gentest.py. // OffscreenCanvas test in a worker:2d.state.saverestore.lineWidth // Description:save()/restore() works for lineWidth // Note: importScripts("/resources/testharness.js"); importScripts("/2dcontext/resources/canvas-tests.js"); var t = async_test("save()/restore() works for lineWidth"); var t_pass = t.done.bind(t); var t_fail = t.step_func(function(reason) { throw reason; }); t.step(function() { var offscreenCanvas = new OffscreenCanvas(100, 50); var ctx = offscreenCanvas.getContext('2d'); // Test that restore() undoes any modifications var old = ctx.lineWidth; ctx.save(); ctx.lineWidth = 0.5; ctx.restore(); _assertSame(ctx.lineWidth, old, "ctx.lineWidth", "old"); // Also test that save() doesn't modify the values ctx.lineWidth = 0.5; old = ctx.lineWidth; // we're not interested in failures caused by get(set(x)) != x (e.g. // from rounding), so compare against 'old' instead of against 0.5 ctx.save(); _assertSame(ctx.lineWidth, old, "ctx.lineWidth", "old"); ctx.restore(); t.done(); }); done();
mpl-2.0
timsutton/packer
builder/hyperone/config.go
9421
//go:generate struct-markdown //go:generate mapstructure-to-hcl2 -type Config package hyperone import ( "errors" "fmt" "io/ioutil" "os" "time" "github.com/hashicorp/packer/common" "github.com/hashicorp/packer/common/json" "github.com/hashicorp/packer/common/uuid" "github.com/hashicorp/packer/helper/communicator" "github.com/hashicorp/packer/helper/config" "github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/template/interpolate" "github.com/mitchellh/go-homedir" "github.com/mitchellh/mapstructure" ) const ( configPath = "~/.h1-cli/conf.json" tokenEnv = "HYPERONE_TOKEN" defaultDiskType = "ssd" defaultImageService = "564639bc052c084e2f2e3266" defaultStateTimeout = 5 * time.Minute defaultUserName = "guru" ) type Config struct { common.PackerConfig `mapstructure:",squash"` Comm communicator.Config `mapstructure:",squash"` // Custom API endpoint URL, compatible with HyperOne. // It can also be specified via environment variable HYPERONE_API_URL. APIURL string `mapstructure:"api_url" required:"false"` // The authentication token used to access your account. // This can be either a session token or a service account token. // If not defined, the builder will attempt to find it in the following order: Token string `mapstructure:"token" required:"true"` // The id or name of the project. This field is required // only if using session tokens. It should be skipped when using service // account authentication. Project string `mapstructure:"project" required:"true"` // Login (an e-mail) on HyperOne platform. Set this // if you want to fetch the token by SSH authentication. TokenLogin string `mapstructure:"token_login" required:"false"` // Timeout for waiting on the API to complete // a request. Defaults to 5m. StateTimeout time.Duration `mapstructure:"state_timeout" required:"false"` // ID or name of the image to launch server from. SourceImage string `mapstructure:"source_image" required:"true"` // The name of the resulting image. Defaults to // "packer-{{timestamp}}" // (see configuration templates for more info). ImageName string `mapstructure:"image_name" required:"false"` // The description of the resulting image. ImageDescription string `mapstructure:"image_description" required:"false"` // Key/value pair tags to // add to the created image. ImageTags map[string]string `mapstructure:"image_tags" required:"false"` // The service of the resulting image. ImageService string `mapstructure:"image_service" required:"false"` // ID or name of the type this server should be created with. VmType string `mapstructure:"vm_type" required:"true"` // The name of the created server. VmName string `mapstructure:"vm_name" required:"false"` // Key/value pair tags to // add to the created server. VmTags map[string]string `mapstructure:"vm_tags" required:"false"` // The name of the created disk. DiskName string `mapstructure:"disk_name" required:"false"` // The type of the created disk. Defaults to ssd. DiskType string `mapstructure:"disk_type" required:"false"` // Size of the created disk, in GiB. DiskSize float32 `mapstructure:"disk_size" required:"true"` // The ID of the network to attach to the created server. Network string `mapstructure:"network" required:"false"` // The ID of the private IP within chosen network // that should be assigned to the created server. PrivateIP string `mapstructure:"private_ip" required:"false"` // The ID of the public IP that should be assigned to // the created server. If network is chosen, the public IP will be associated // with server's private IP. PublicIP string `mapstructure:"public_ip" required:"false"` // Custom service of public network adapter. // Can be useful when using custom api_url. Defaults to public. PublicNetAdpService string `mapstructure:"public_netadp_service" required:"false"` ChrootDisk bool `mapstructure:"chroot_disk"` ChrootDiskSize float32 `mapstructure:"chroot_disk_size"` ChrootDiskType string `mapstructure:"chroot_disk_type"` ChrootMountPath string `mapstructure:"chroot_mount_path"` ChrootMounts [][]string `mapstructure:"chroot_mounts"` ChrootCopyFiles []string `mapstructure:"chroot_copy_files"` ChrootCommandWrapper string `mapstructure:"chroot_command_wrapper"` MountOptions []string `mapstructure:"mount_options"` MountPartition string `mapstructure:"mount_partition"` PreMountCommands []string `mapstructure:"pre_mount_commands"` PostMountCommands []string `mapstructure:"post_mount_commands"` // List of SSH keys by name or id to be added // to the server on launch. SSHKeys []string `mapstructure:"ssh_keys" required:"false"` // User data to launch with the server. Packer will not // automatically wait for a user script to finish before shutting down the // instance, this must be handled in a provisioner. UserData string `mapstructure:"user_data" required:"false"` ctx interpolate.Context } func NewConfig(raws ...interface{}) (*Config, []string, error) { c := &Config{} var md mapstructure.Metadata err := config.Decode(c, &config.DecodeOpts{ Metadata: &md, Interpolate: true, InterpolateContext: &c.ctx, InterpolateFilter: &interpolate.RenderFilter{ Exclude: []string{ "run_command", "chroot_command_wrapper", "post_mount_commands", "pre_mount_commands", "mount_path", }, }, }, raws...) if err != nil { return nil, nil, err } cliConfig, err := loadCLIConfig() if err != nil { return nil, nil, err } // Defaults if c.Comm.SSHUsername == "" { c.Comm.SSHUsername = defaultUserName } if c.Comm.SSHTimeout == 0 { c.Comm.SSHTimeout = 10 * time.Minute } if c.APIURL == "" { c.APIURL = os.Getenv("HYPERONE_API_URL") } if c.Token == "" { c.Token = os.Getenv(tokenEnv) if c.Token == "" { c.Token = cliConfig.Profile.APIKey } // Fetching token by SSH is available only for the default API endpoint if c.TokenLogin != "" && c.APIURL == "" { c.Token, err = fetchTokenBySSH(c.TokenLogin) if err != nil { return nil, nil, err } } } if c.Project == "" { c.Project = cliConfig.Profile.Project.ID } if c.StateTimeout == 0 { c.StateTimeout = defaultStateTimeout } if c.ImageName == "" { name, err := interpolate.Render("packer-{{timestamp}}", nil) if err != nil { return nil, nil, err } c.ImageName = name } if c.ImageService == "" { c.ImageService = defaultImageService } if c.VmName == "" { c.VmName = fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID()) } if c.DiskType == "" { c.DiskType = defaultDiskType } if c.PublicNetAdpService == "" { c.PublicNetAdpService = "public" } if c.ChrootCommandWrapper == "" { c.ChrootCommandWrapper = "{{.Command}}" } if c.ChrootDiskSize == 0 { c.ChrootDiskSize = c.DiskSize } if c.ChrootDiskType == "" { c.ChrootDiskType = c.DiskType } if c.ChrootMountPath == "" { path, err := interpolate.Render("/mnt/packer-hyperone-volumes/{{timestamp}}", nil) if err != nil { return nil, nil, err } c.ChrootMountPath = path } if c.ChrootMounts == nil { c.ChrootMounts = make([][]string, 0) } if len(c.ChrootMounts) == 0 { c.ChrootMounts = [][]string{ {"proc", "proc", "/proc"}, {"sysfs", "sysfs", "/sys"}, {"bind", "/dev", "/dev"}, {"devpts", "devpts", "/dev/pts"}, {"binfmt_misc", "binfmt_misc", "/proc/sys/fs/binfmt_misc"}, } } if c.ChrootCopyFiles == nil { c.ChrootCopyFiles = []string{"/etc/resolv.conf"} } if c.MountPartition == "" { c.MountPartition = "1" } // Validation var errs *packer.MultiError if es := c.Comm.Prepare(&c.ctx); len(es) > 0 { errs = packer.MultiErrorAppend(errs, es...) } if c.Token == "" { errs = packer.MultiErrorAppend(errs, errors.New("token is required")) } if c.VmType == "" { errs = packer.MultiErrorAppend(errs, errors.New("vm type is required")) } if c.DiskSize == 0 { errs = packer.MultiErrorAppend(errs, errors.New("disk size is required")) } if c.SourceImage == "" { errs = packer.MultiErrorAppend(errs, errors.New("source image is required")) } if c.ChrootDisk { if len(c.PreMountCommands) == 0 { errs = packer.MultiErrorAppend(errs, errors.New("pre-mount commands are required for chroot disk")) } } for _, mounts := range c.ChrootMounts { if len(mounts) != 3 { errs = packer.MultiErrorAppend( errs, errors.New("each chroot_mounts entry should have three elements")) break } } if errs != nil && len(errs.Errors) > 0 { return nil, nil, errs } packer.LogSecretFilter.Set(c.Token) return c, nil, nil } type cliConfig struct { Profile struct { APIKey string `json:"apiKey"` Project struct { ID string `json:"id"` } `json:"project"` } `json:"profile"` } func loadCLIConfig() (cliConfig, error) { path, err := homedir.Expand(configPath) if err != nil { return cliConfig{}, err } _, err = os.Stat(path) if err != nil { // Config not found return cliConfig{}, nil } content, err := ioutil.ReadFile(path) if err != nil { return cliConfig{}, err } var c cliConfig err = json.Unmarshal(content, &c) if err != nil { return cliConfig{}, err } return c, nil } func getPublicIP(state multistep.StateBag) (string, error) { return state.Get("public_ip").(string), nil }
mpl-2.0
2gis/nuclear-river-validation-rules
src/Replication.Core/Actors/CreateDataObjectsActor.cs
2127
using System; using System.Collections.Generic; using System.Linq; using NuClear.Replication.Core.Commands; using NuClear.Replication.Core.DataObjects; using NuClear.Replication.Core.Telemetry; namespace NuClear.Replication.Core.Actors { public sealed class CreateDataObjectsActor<TDataObject> : IActor where TDataObject : class { private readonly IdentityChangesProvider<TDataObject> _changesProvider; private readonly IRepository<TDataObject> _bulkRepository; private readonly IDataChangesHandler<TDataObject> _dataChangesHandler; public CreateDataObjectsActor( IdentityChangesProvider<TDataObject> changesProvider, IRepository<TDataObject> bulkRepository, IDataChangesHandler<TDataObject> dataChangesHandler) { _changesProvider = changesProvider; _bulkRepository = bulkRepository; _dataChangesHandler = dataChangesHandler; } public IReadOnlyCollection<IEvent> ExecuteCommands(IReadOnlyCollection<ICommand> rawCommands) { var commands = rawCommands .OfType<ICreateDataObjectCommand>() .Where(x => x.DataObjectType == typeof(TDataObject)) .ToList(); if (commands.Count == 0) return Array.Empty<IEvent>(); using (Probe.Create("CreateDataObjectsActor", new {TypeName = typeof(TDataObject).Name})) { var events = new List<IEvent>(); foreach (var command in commands) { var changes = _changesProvider.GetChanges(command); var toCreate = changes.Difference.ToArray(); if (toCreate.Length != 0) { _bulkRepository.Create(toCreate); events.AddRange(_dataChangesHandler.HandleCreates(toCreate)); events.AddRange(_dataChangesHandler.HandleRelates(toCreate)); } } return events; } } } }
mpl-2.0
tbouvet/seed
testing/src/main/java/org/seedstack/seed/it/internal/ITModule.java
1019
/** * Copyright (c) 2013-2015, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.seed.it.internal; import com.google.inject.AbstractModule; import org.seedstack.seed.it.internal.arquillian.InjectionEnricher; import java.util.Collection; class ITModule extends AbstractModule { private final Collection<Class<?>> iTs; private final Class<?> testClass; ITModule(Class<?> testClass, Collection<Class<?>> iTs) { this.iTs = iTs; this.testClass = testClass; } @Override protected void configure() { requestStaticInjection(InjectionEnricher.class); if (testClass != null) { bind(testClass); } if (iTs != null) { for (Class<?> iT : iTs) { bind(iT); } } } }
mpl-2.0
freaktechnik/mines.js
src/stringbundle.js
1802
/** * A StringBundle wraps around an HTML element containing nodes with strings used in JS. * * @param {Element} container - The parent element of all strings. * @throws If the L10n infrastructure is not loaded. * @class */ function StringBundle(container) { this.container = container; this.container.setAttribute("hidden", true); if(!("mozL10n" in navigator)) { throw new Error("mozL10n global not initialized."); } } StringBundle.prototype.container = null; /** * @param {string} id - ID of the string. * @returns {Element} Container element of the string. */ StringBundle.prototype.getStringContainer = function(id) { return this.container.querySelector(`[data-l10n-id='${id}']`); }; /** * Get the value of a string with a certain ID. * * @param {string} id - ID of the string to return. * @returns {string} Translation of string with the supplied ID. */ StringBundle.prototype.getString = function(id) { const node = this.getStringContainer(id); //navigator.mozL10n.setAttributes(node, id); return node.textContent; }; /** * Get the value of a string with a certain ID asynchronously. * * @param {string} id - ID of the translated string. * @param {Object} args - Arguments for variables within the string. * @async * @returns {string} Translation of string with the supplied ID.. */ StringBundle.prototype.getStringAsync = function(id, args) { const node = this.getStringContainer(id); return new Promise((resolve) => { const tempNode = node.cloneNode(); navigator.mozL10n.ready(() => { navigator.mozL10n.setAttributes(tempNode, id, args); navigator.mozL10n.translateFragment(tempNode); resolve(tempNode.textContent); }); }); }; export default StringBundle;
mpl-2.0
Yukarumya/Yukarum-Redfoxes
testing/mozbase/manifestparser/tests/test_chunking.py
9556
#!/usr/bin/env python from itertools import chain from unittest import TestCase import os import random import mozunit from manifestparser.filters import ( chunk_by_dir, chunk_by_runtime, chunk_by_slice, ) here = os.path.dirname(os.path.abspath(__file__)) class ChunkBySlice(TestCase): """Test chunking related filters""" def generate_tests(self, num, disabled=None): disabled = disabled or [] tests = [] for i in range(num): test = {'name': 'test%i' % i} if i in disabled: test['disabled'] = '' tests.append(test) return tests def run_all_combos(self, num_tests, disabled=None): tests = self.generate_tests(num_tests, disabled=disabled) for total in range(1, num_tests + 1): res = [] res_disabled = [] for chunk in range(1, total + 1): f = chunk_by_slice(chunk, total) res.append(list(f(tests, {}))) if disabled: f.disabled = True res_disabled.append(list(f(tests, {}))) lengths = [len([t for t in c if 'disabled' not in t]) for c in res] # the chunk with the most tests should have at most one more test # than the chunk with the least tests self.assertLessEqual(max(lengths) - min(lengths), 1) # chaining all chunks back together should equal the original list # of tests self.assertEqual(list(chain.from_iterable(res)), list(tests)) if disabled: lengths = [len(c) for c in res_disabled] self.assertLessEqual(max(lengths) - min(lengths), 1) self.assertEqual(list(chain.from_iterable(res_disabled)), list(tests)) def test_chunk_by_slice(self): chunk = chunk_by_slice(1, 1) self.assertEqual(list(chunk([], {})), []) self.run_all_combos(num_tests=1) self.run_all_combos(num_tests=10, disabled=[1, 2]) num_tests = 67 disabled = list(i for i in xrange(num_tests) if i % 4 == 0) self.run_all_combos(num_tests=num_tests, disabled=disabled) def test_two_times_more_chunks_than_tests(self): # test case for bug 1182817 tests = self.generate_tests(5) total_chunks = 10 for i in range(1, total_chunks + 1): # ensure IndexError is not raised chunk_by_slice(i, total_chunks)(tests, {}) class ChunkByDir(TestCase): """Test chunking related filters""" def generate_tests(self, dirs): """ :param dirs: dict of the form, { <dir>: <num tests> } """ i = 0 for d, num in dirs.iteritems(): for j in range(num): i += 1 name = 'test%i' % i test = {'name': name, 'relpath': os.path.join(d, name)} yield test def run_all_combos(self, dirs): tests = list(self.generate_tests(dirs)) deepest = max(len(t['relpath'].split(os.sep)) - 1 for t in tests) for depth in range(1, deepest + 1): def num_groups(tests): unique = set() for p in [t['relpath'] for t in tests]: p = p.split(os.sep) p = p[:min(depth, len(p) - 1)] unique.add(os.sep.join(p)) return len(unique) for total in range(1, num_groups(tests) + 1): res = [] for this in range(1, total + 1): f = chunk_by_dir(this, total, depth) res.append(list(f(tests, {}))) lengths = map(num_groups, res) # the chunk with the most dirs should have at most one more # dir than the chunk with the least dirs self.assertLessEqual(max(lengths) - min(lengths), 1) all_chunks = list(chain.from_iterable(res)) # chunk_by_dir will mess up order, but chained chunks should # contain all of the original tests and be the same length self.assertEqual(len(all_chunks), len(tests)) for t in tests: self.assertIn(t, all_chunks) def test_chunk_by_dir(self): chunk = chunk_by_dir(1, 1, 1) self.assertEqual(list(chunk([], {})), []) dirs = { 'a': 2, } self.run_all_combos(dirs) dirs = { '': 1, 'foo': 1, 'bar': 0, '/foobar': 1, } self.run_all_combos(dirs) dirs = { 'a': 1, 'b': 1, 'a/b': 2, 'a/c': 1, } self.run_all_combos(dirs) dirs = { 'a': 5, 'a/b': 4, 'a/b/c': 7, 'a/b/c/d': 1, 'a/b/c/e': 3, 'b/c': 2, 'b/d': 5, 'b/d/e': 6, 'c': 8, 'c/d/e/f/g/h/i/j/k/l': 5, 'c/d/e/f/g/i/j/k/l/m/n': 2, 'c/e': 1, } self.run_all_combos(dirs) class ChunkByRuntime(TestCase): """Test chunking related filters""" def generate_tests(self, dirs): """ :param dirs: dict of the form, { <dir>: <num tests> } """ i = 0 for d, num in dirs.iteritems(): for j in range(num): i += 1 name = 'test%i' % i test = {'name': name, 'relpath': os.path.join(d, name), 'manifest': os.path.join(d, 'manifest.ini')} yield test def get_runtimes(self, tests): runtimes = {} for test in tests: runtimes[test['relpath']] = random.randint(0, 100) return runtimes def chunk_by_round_robin(self, tests, runtimes): manifests = set(t['manifest'] for t in tests) tests_by_manifest = [] for manifest in manifests: mtests = [t for t in tests if t['manifest'] == manifest] total = sum(runtimes[t['relpath']] for t in mtests if 'disabled' not in t) tests_by_manifest.append((total, mtests)) tests_by_manifest.sort() chunks = [[] for i in range(total)] d = 1 # direction i = 0 for runtime, batch in tests_by_manifest: chunks[i].extend(batch) # "draft" style (last pick goes first in the next round) if (i == 0 and d == -1) or (i == total - 1 and d == 1): d = -d else: i += d # make sure this test algorithm is valid all_chunks = list(chain.from_iterable(chunks)) self.assertEqual(len(all_chunks), len(tests)) for t in tests: self.assertIn(t, all_chunks) return chunks def run_all_combos(self, dirs): tests = list(self.generate_tests(dirs)) runtimes = self.get_runtimes(tests) for total in range(1, len(dirs) + 1): chunks = [] for this in range(1, total + 1): f = chunk_by_runtime(this, total, runtimes) ret = list(f(tests, {})) chunks.append(ret) # chunk_by_runtime will mess up order, but chained chunks should # contain all of the original tests and be the same length all_chunks = list(chain.from_iterable(chunks)) self.assertEqual(len(all_chunks), len(tests)) for t in tests: self.assertIn(t, all_chunks) # calculate delta between slowest and fastest chunks def runtime_delta(chunks): totals = [] for chunk in chunks: total = sum(runtimes[t['relpath']] for t in chunk if 'disabled' not in t) totals.append(total) return max(totals) - min(totals) delta = runtime_delta(chunks) # redo the chunking a second time using a round robin style # algorithm chunks = self.chunk_by_round_robin(tests, runtimes) # since chunks will never have exactly equal runtimes, it's hard # to tell if they were chunked optimally. Make sure it at least # beats a naive round robin approach. self.assertLessEqual(delta, runtime_delta(chunks)) def test_chunk_by_runtime(self): random.seed(42) chunk = chunk_by_runtime(1, 1, {}) self.assertEqual(list(chunk([], {})), []) dirs = { 'a': 2, } self.run_all_combos(dirs) dirs = { '': 1, 'foo': 1, 'bar': 0, '/foobar': 1, } self.run_all_combos(dirs) dirs = { 'a': 1, 'b': 1, 'a/b': 2, 'a/c': 1, } self.run_all_combos(dirs) dirs = { 'a': 5, 'a/b': 4, 'a/b/c': 7, 'a/b/c/d': 1, 'a/b/c/e': 3, 'b/c': 2, 'b/d': 5, 'b/d/e': 6, 'c': 8, 'c/d/e/f/g/h/i/j/k/l': 5, 'c/d/e/f/g/i/j/k/l/m/n': 2, 'c/e': 1, } self.run_all_combos(dirs) if __name__ == '__main__': mozunit.main()
mpl-2.0
devpaul/webserv
src/middleware/util/index.ts
284
/** * @file Automatically generated by barrelsby. */ export * from "./BufferedResponse"; export * from "./contentNegotiator"; export * from "./createProxy"; export * from "./htmlTemplate"; export * from "./request"; export * from "./file/getStat"; export * from "./file/sendFile";
mpl-2.0
stevekinney/advanced-js-fundamentals-ck
demos/currying/test.js
1046
describe('prefixLog - Currying', function () { // Only unskip this test if you are using trying to use partial application. it.skip('should prefix a message', function () { assert.equal(prefixLog('PREFIX', 'message'), 'PREFIX: message'); }); }); describe('prefixLog - Currying', function () { // Only unskip these tests if you are using trying to use currying. it('should return a function', function () { assert.equal(typeof prefixLog('PREFIX'), 'function'); }); it('should return a function that accepts a message and uses the prefix', function () { var prefixWithPrefix = prefixLog('PREFIX'); assert.equal(prefixWithPrefix('message'), 'PREFIX: message'); }); }); describe('dangerLog', function () { it.skip('should prefix a message with DANGER:', function () { assert.equal(dangerLog('Oh no'), 'DANGER: Oh no'); }); }); describe('successLog', function () { it.skip('should prefix a message with SUCCESS:', function () { assert.equal(successLog('Oh no'), 'SUCCESS: Oh no'); }); });
mpl-2.0
kurtisharms/libxennet
libXennet/src/linux/xenServerSocket.hpp
1602
#ifndef SERVERSOCKET_HPP #define SERVERSOCKET_HPP #include "../xenMain.hpp" #ifdef LINUX_OS #include "xenSocketAddress.h" #include "xenPacket.h" #include "../xenServerSocketBase.hpp" //! The Xennet namespace. /*! The Xennet namespace contains all of the classes and functions in the library. */ namespace Xennet { //! ServerSocket class. /*! The ServerSocket class provides a TCP-protocol server socket for dealing with clients. */ class ServerSocket : public ServerSocketBase { public: //! Basic default constructor. ServerSocket(); //! Recommended default constructor. /*! \param port The port on which the server listens. \param maxClients Specify the maximum allowable connections simutaneously for this ServerSocket \return null */ ServerSocket(int port, int maxClients); //! Default destructor. virtual ~ServerSocket(); int getPort(void); bool isError(void); bool resetError(void); bool bindSocket(void); bool acceptConnections(void); Packet* receiveData(void); bool receiveDataAsString(std::string& strBuffer); bool sendData(Packet* data); bool sendData(std::string data); protected: bool Error; int maxConnections; int listenSocket, connectSocket, i; unsigned short int listenPort; socklen_t clientAddressLength; struct sockaddr_in clientAddress, serverAddress; }; } // namespace Xennet #endif // LINUX_OS #endif // SERVERSOCKET_HPP
mpl-2.0
fchampreux/ODQ_Stairs
spec/requests/authentication_spec.rb
1218
require 'spec_helper' describe "Authentication : " do subject { page } ###LOG-IN1 describe "signin page" do before { visit signin_path } it { should have_selector('h2', text: 'Please sign in') } it { should have_title('Sign in') } ###LOG-IN2 describe "with invalid information" do before { click_button "Sign in" } it { should have_selector('h2', text: 'sign in') } it { should have_selector('div.alert.alert-error', text: 'Invalid') } ###LOG-IN3 describe "after visiting another page" do before { click_link "About" } it { should_not have_selector('div.alert.alert-error') } end end ###LOG-IN4 describe "with valid information" do let(:user) { FactoryBot.create(:user) } before do fill_in "Login", with: user.login.downcase fill_in "Password", with: user.password click_button "Sign in" end it { should have_link('Sign out', href: signout_path) } it { should_not have_link('Sign in', href: signin_path) } describe "followed by signout" do before { click_link "Sign out" } it { should have_link('Sign in') } end end end end
mpl-2.0
fxbox/app
tests/unit/lib/foxbox/settings_test.js
6411
import Settings from 'js/lib/foxbox/settings'; /** @test {Settings} */ describe('Settings >', function () { let storageStub; beforeEach(function () { this.sinon = sinon.sandbox.create(); storageStub = sinon.stub({ getItem: () => {}, setItem: () => {}, removeItem: () => {}, }); storageStub.getItem.returns(null); this.sinon.stub(window, 'addEventListener'); }); afterEach(function() { this.sinon.restore(); this.sinon = null; }); /** @test {Settings#constructor} */ describe('constructor >', function() { it('correctly reads default values from localStorage', function() { storageStub.getItem .withArgs('foxbox-session') .returns('session-x'); storageStub.getItem .withArgs('foxbox-servicePollingInterval') .returns('10000'); const settings = new Settings(storageStub); assert.equal(settings.session, 'session-x'); assert.equal(settings.servicePollingInterval, 10000); }); it('correctly sets predefined default values', function() { const settings = new Settings(storageStub); assert.isNull(settings.session); assert.equal(settings.servicePollingInterval, 2000); }); }); describe('settings >', function() { let settings; beforeEach(function() { settings = new Settings(storageStub); }); it('updated value is persisted in localStorage', function() { settings.session = 'x-session'; sinon.assert.calledOnce(storageStub.setItem); sinon.assert.calledWith( storageStub.setItem, 'foxbox-session', 'x-session' ); assert.equal(settings.session, 'x-session'); settings.pushEndpoint = 'x-endpoint'; sinon.assert.calledTwice(storageStub.setItem); sinon.assert.calledWith( storageStub.setItem, 'foxbox-pushEndpoint', 'x-endpoint' ); assert.equal(settings.pushEndpoint, 'x-endpoint'); }); it('when default value is set it is removed from localStorage', function() { settings.session = 'x-session'; settings.skipDiscovery = true; settings.session = null; sinon.assert.calledOnce(storageStub.removeItem); sinon.assert.calledWith(storageStub.removeItem, 'foxbox-session'); assert.equal(settings.session, null); settings.skipDiscovery = false; sinon.assert.calledTwice(storageStub.removeItem); sinon.assert.calledWith(storageStub.removeItem, 'foxbox-skipDiscovery'); assert.equal(settings.skipDiscovery, false); }); it('event is emitted when setting value is changed', function() { const sessionEventHandler = sinon.stub(); const pushEndpointEventHandler = sinon.stub(); settings.on('session', sessionEventHandler); settings.on('push-endpoint', pushEndpointEventHandler); settings.session = 'x-session'; sinon.assert.calledOnce(sessionEventHandler); sinon.assert.calledWith(sessionEventHandler, 'x-session'); sinon.assert.notCalled(pushEndpointEventHandler); sessionEventHandler.reset(); settings.pushEndpoint = 'x-endpoint'; sinon.assert.calledOnce(pushEndpointEventHandler); sinon.assert.calledWith(pushEndpointEventHandler, 'x-endpoint'); sinon.assert.notCalled(sessionEventHandler); pushEndpointEventHandler.reset(); settings.session = null; sinon.assert.calledOnce(sessionEventHandler); sinon.assert.calledWith(sessionEventHandler, null); sinon.assert.notCalled(pushEndpointEventHandler); sessionEventHandler.reset(); settings.pushEndpoint = null; sinon.assert.calledOnce(pushEndpointEventHandler); sinon.assert.calledWith(pushEndpointEventHandler, null); sinon.assert.notCalled(sessionEventHandler); }); }); describe('storage event >', function() { let settings; beforeEach(function() { settings = new Settings(storageStub); }); it('unrelated storage events should not cause any change', function() { const sessionEventHandler = sinon.stub(); settings.session = 'x-session'; settings.on('session', sessionEventHandler); window.addEventListener.withArgs('storage').yield({ key: 'session', newValue: 'x-new-session', }); sinon.assert.notCalled(sessionEventHandler); assert.equal(settings.session, 'x-session'); window.addEventListener.withArgs('storage').yield({ key: 'foxbox-session-1', newValue: 'x-new-session', }); sinon.assert.notCalled(sessionEventHandler); assert.equal(settings.session, 'x-session'); }); it('setting should be properly updated with new value', function() { const eventHandler = sinon.stub(); settings.session = 'x-session'; settings.skipDiscovery = false; settings.on('session', eventHandler); settings.on('skip-discovery', eventHandler); settings.on('watch-interval', eventHandler); assert.equal(settings.session, 'x-session'); assert.equal(settings.skipDiscovery, false); assert.equal(settings.watchInterval, 3000); window.addEventListener.withArgs('storage').yield({ key: 'foxbox-session', newValue: 'x-new-session', }); assert.equal(settings.session, 'x-new-session'); assert.equal(settings.skipDiscovery, false); assert.equal(settings.watchInterval, 3000); sinon.assert.calledOnce(eventHandler); sinon.assert.calledWith(eventHandler, 'x-new-session'); eventHandler.reset(); window.addEventListener.withArgs('storage').yield({ key: 'foxbox-skipDiscovery', newValue: 'true', }); assert.equal(settings.session, 'x-new-session'); assert.equal(settings.skipDiscovery, true); assert.equal(settings.watchInterval, 3000); sinon.assert.calledOnce(eventHandler); sinon.assert.calledWith(eventHandler, true); eventHandler.reset(); window.addEventListener.withArgs('storage').yield({ key: 'foxbox-watchInterval', newValue: '5000', }); assert.equal(settings.session, 'x-new-session'); assert.equal(settings.skipDiscovery, true); assert.equal(settings.watchInterval, 5000); sinon.assert.calledOnce(eventHandler); sinon.assert.calledWith(eventHandler, 5000); }); }); });
mpl-2.0
MapWindow/MapWinGIS
unittests/MapWinGISTests/AxMapTests.cs
1205
using System; using AxMapWinGIS; using MapWinGIS; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MapWinGISTests { [TestClass] public class AxMapTests: ICallback { private readonly AxMap _axMap1; private static readonly GlobalSettings _settings = new GlobalSettings(); public AxMapTests() { _settings.ApplicationCallback = this; // Create MapWinGIS: _axMap1 = Helper.GetAxMap(); _axMap1.Projection = tkMapProjection.PROJECTION_GOOGLE_MERCATOR; _axMap1.KnownExtents = tkKnownExtents.keNetherlands; _axMap1.ZoomBehavior = tkZoomBehavior.zbUseTileLevels; _axMap1.Tiles.Provider = tkTileProvider.OpenStreetMap; } [TestMethod] public void GetExtents() { Console.WriteLine(_axMap1.Extents.ToDebugString()); } public void Progress(string KeyOfSender, int Percent, string Message) { Console.WriteLine($"{Percent} {Message}"); } public void Error(string KeyOfSender, string ErrorMsg) { Console.WriteLine("Error: " + ErrorMsg); } } }
mpl-2.0
mssavai/muzima-api
src/main/java/com/muzima/api/model/APIName.java
764
/* * Copyright (c) 2014. The Trustees of Indiana University. * * This version of the code is licensed under the MPL 2.0 Open Source license with additional * healthcare disclaimer. If the user is an entity intending to commercialize any application * that uses this code in a for-profit venture, please contact the copyright holder. */ package com.muzima.api.model; public enum APIName { DOWNLOAD_OBSERVATIONS, DOWNLOAD_FORMS, DOWNLOAD_COHORTS, DOWNLOAD_COHORTS_DATA, DOWNLOAD_ENCOUNTERS, DOWNLOAD_SETUP_CONFIGURATIONS; public static APIName getAPIName(String apiName) { for (APIName name : values()) { if (apiName.equals(name.toString())) { return name; } } return null; } }
mpl-2.0
ThesisPlanet/EducationPlatform
src/library/vendor/Zencoder/Accounts.php
2021
<?php /** * Zencoder API client interface. * * @category Services * @package Services_Zencoder * @author Michael Christopher <m@zencoder.com> * @version Release: 2.1.1 * @license http://creativecommons.org/licenses/MIT/MIT * @link http://github.com/zencoder/zencoder-php */ class Services_Zencoder_Accounts extends Services_Zencoder_Base { /** * Create a Zencoder account * * @param array $account Array of attributes to use when creating the account * @param array $params Optional overrides * * @return Services_Zencoder_Account The object representation of the resource */ public function create($account = NULL, $params = array()) { if(is_string($account)) { $json = trim($account); } else if(is_array($account)) { $json = json_encode($account); } else { throw new Services_Zencoder_Exception( 'Account parameters required to create account.'); } return new Services_Zencoder_Account($this->proxy->createData("account", $json, $params)); } /** * Return details of your Zencoder account * * @param array $params Optional overrides * * @return Services_Zencoder_Account The object representation of the resource */ public function details($params = array()) { return new Services_Zencoder_Account($this->proxy->retrieveData("account.json", array(), $params)); } /** * Put your account into integration mode * * @param array $params Optional overrides * * @return bool If the operation was successful */ public function integration($params = array()) { return $this->proxy->updateData("account/integration", "", $params); } /** * Put your account into live mode * * @param array $params Optional overrides * * @return bool If the operation was successful */ public function live($params = array()) { return $this->proxy->updateData("account/live", "", $params); } }
mpl-2.0
nak3/nomad
command/job_inspect.go
4572
package command import ( "fmt" "strings" "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/api/contexts" "github.com/posener/complete" ) type JobInspectCommand struct { Meta } func (c *JobInspectCommand) Help() string { helpText := ` Usage: nomad job inspect [options] <job> Alias: nomad inspect Inspect is used to see the specification of a submitted job. General Options: ` + generalOptionsUsage() + ` Inspect Options: -version <job version> Display the job at the given job version. -json Output the job in its JSON format. -t Format and display job using a Go template. ` return strings.TrimSpace(helpText) } func (c *JobInspectCommand) Synopsis() string { return "Inspect a submitted job" } func (c *JobInspectCommand) AutocompleteFlags() complete.Flags { return mergeAutocompleteFlags(c.Meta.AutocompleteFlags(FlagSetClient), complete.Flags{ "-version": complete.PredictAnything, "-json": complete.PredictNothing, "-t": complete.PredictAnything, }) } func (c *JobInspectCommand) AutocompleteArgs() complete.Predictor { return complete.PredictFunc(func(a complete.Args) []string { client, err := c.Meta.Client() if err != nil { return nil } resp, _, err := client.Search().PrefixSearch(a.Last, contexts.Jobs, nil) if err != nil { return []string{} } return resp.Matches[contexts.Jobs] }) } func (c *JobInspectCommand) Name() string { return "job inspect" } func (c *JobInspectCommand) Run(args []string) int { var json bool var tmpl, versionStr string flags := c.Meta.FlagSet(c.Name(), FlagSetClient) flags.Usage = func() { c.Ui.Output(c.Help()) } flags.BoolVar(&json, "json", false, "") flags.StringVar(&tmpl, "t", "", "") flags.StringVar(&versionStr, "version", "", "") if err := flags.Parse(args); err != nil { return 1 } args = flags.Args() // Get the HTTP client client, err := c.Meta.Client() if err != nil { c.Ui.Error(fmt.Sprintf("Error initializing client: %s", err)) return 1 } // If args not specified but output format is specified, format and output the jobs data list if len(args) == 0 && json || len(tmpl) > 0 { jobs, _, err := client.Jobs().List(nil) if err != nil { c.Ui.Error(fmt.Sprintf("Error querying jobs: %v", err)) return 1 } out, err := Format(json, tmpl, jobs) if err != nil { c.Ui.Error(err.Error()) return 1 } c.Ui.Output(out) return 0 } // Check that we got exactly one job if len(args) != 1 { c.Ui.Error("This command takes one argument: <job>") c.Ui.Error(commandErrorText(c)) return 1 } jobID := args[0] // Check if the job exists jobs, _, err := client.Jobs().PrefixList(jobID) if err != nil { c.Ui.Error(fmt.Sprintf("Error inspecting job: %s", err)) return 1 } if len(jobs) == 0 { c.Ui.Error(fmt.Sprintf("No job(s) with prefix or id %q found", jobID)) return 1 } if len(jobs) > 1 && strings.TrimSpace(jobID) != jobs[0].ID { c.Ui.Error(fmt.Sprintf("Prefix matched multiple jobs\n\n%s", createStatusListOutput(jobs))) return 1 } var version *uint64 if versionStr != "" { v, _, err := parseVersion(versionStr) if err != nil { c.Ui.Error(fmt.Sprintf("Error parsing version value %q: %v", versionStr, err)) return 1 } version = &v } // Prefix lookup matched a single job job, err := getJob(client, jobs[0].ID, version) if err != nil { c.Ui.Error(fmt.Sprintf("Error inspecting job: %s", err)) return 1 } // If output format is specified, format and output the data if json || len(tmpl) > 0 { out, err := Format(json, tmpl, job) if err != nil { c.Ui.Error(err.Error()) return 1 } c.Ui.Output(out) return 0 } // Print the contents of the job req := api.RegisterJobRequest{Job: job} f, err := DataFormat("json", "") if err != nil { c.Ui.Error(fmt.Sprintf("Error getting formatter: %s", err)) return 1 } out, err := f.TransformData(req) if err != nil { c.Ui.Error(fmt.Sprintf("Error formatting the data: %s", err)) return 1 } c.Ui.Output(out) return 0 } // getJob retrieves the job optionally at a particular version. func getJob(client *api.Client, jobID string, version *uint64) (*api.Job, error) { if version == nil { job, _, err := client.Jobs().Info(jobID, nil) return job, err } versions, _, _, err := client.Jobs().Versions(jobID, false, nil) if err != nil { return nil, err } for _, j := range versions { if *j.Version != *version { continue } return j, nil } return nil, fmt.Errorf("job %q with version %d couldn't be found", jobID, *version) }
mpl-2.0
jamiepg1/module-order
Blocks/CreditNoteSummaryInformation.php
1256
<?php /** * Copyright (C) 2014 Proximis * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ namespace Rbs\Order\Blocks; /** * @name \Rbs\Order\Blocks\CreditNoteSummaryInformation */ class CreditNoteSummaryInformation extends \Change\Presentation\Blocks\Information { /** * @param \Change\Events\Event $event */ public function onInformation(\Change\Events\Event $event) { parent::onInformation($event); $i18nManager = $event->getApplicationServices()->getI18nManager(); $ucf = array('ucf'); $this->setSection($i18nManager->trans('m.rbs.order.admin.module_name', $ucf)); $this->setLabel($i18nManager->trans('m.rbs.order.admin.credit_note_summary_label', $ucf)); $this->addInformationMeta('showIfEmpty', \Change\Documents\Property::TYPE_BOOLEAN, false, false) ->setLabel($i18nManager->trans('m.rbs.order.admin.credit_note_summary_show_if_empty', $ucf)); $this->addInformationMeta('usage', \Change\Documents\Property::TYPE_DOCUMENT, true) ->setAllowedModelsNames('Rbs_Website_Text') ->setLabel($i18nManager->trans('m.rbs.website.admin.credit_note_usage', $ucf)); } }
mpl-2.0
DavidGamba/go-dicom
qr/go-dicom.go
8835
// This file is part of go-dicom. // // Copyright (C) 2016 David Gamba Rios // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. package main import ( // "bufio" "bytes" "encoding/binary" "fmt" "github.com/davidgamba/go-dicom/qr/pdu" "github.com/davidgamba/go-dicom/qr/sopclass" "github.com/davidgamba/go-dicom/qr/syntax/ts" "github.com/davidgamba/go-getoptions" // As getoptions "log" "net" "os" "strconv" "strings" ) // AppContextName = "1.2.840.10008.3.1.1.1" const AppContextName = "1.2.840.10008.3.1.1.1" // ImplementationClassUID = "1.2.40.0.13.1.1" const ImplementationClassUID = "1.2.40.0.13.1.1" // ImplementationVersion = "go-dicom-0.1.0" const ImplementationVersion = "go-dicom-0.1.0" type dicomqr struct { CalledAE [16]byte CallingAE [16]byte Host string Port int Conn net.Conn ar pdu.AAssociateRequest rr pdu.AReleaseRequest } func (qr *dicomqr) Dial() error { address := qr.Host + ":" + strconv.Itoa(qr.Port) log.Printf("Connecting to: %s", address) conn, err := net.Dial("tcp", address) if err != nil { return err } log.Printf("Connecting successful") qr.Conn = conn return nil } func (qr *dicomqr) Init() { qr.ar = pdu.AAssociateRequest{ PDUType: 1, CalledAE: qr.CalledAE, CallingAE: qr.CallingAE, Content: []byte{}, } putIntToByteSize2(&qr.ar.ProtocolVersion, 1) qr.rr = pdu.AReleaseRequest{ PDUType: 5, } } func putIntToByteSize2(b *[2]byte, v int) { b[0] = byte(v >> 8) b[1] = byte(v) } func (qr *dicomqr) AR() (int, error) { if len(qr.ar.Content) == 0 { return 0, fmt.Errorf("AR has no content") } b := qr.ar.ToBytes() printBytes(b) i, err := qr.Conn.Write(b) return i, err } func (qr *dicomqr) RR() (int, error) { b := qr.rr.ToBytes() printBytes(b) i, err := qr.Conn.Write(b) return i, err } func (qr *dicomqr) ARAdd(b []byte) { qr.ar.Content = append(qr.ar.Content, b...) } func padRight(str, pad string, lenght int) string { for { str += pad if len(str) > lenght { return str[0:lenght] } } } // PressContextItem returns a byte slice with press context item. func PressContextItem(items ...[]byte) []byte { b := []byte{32} // itemType b = append(b, make([]byte, 1)...) // Reserved payload := []byte{1} // contextID payload = append(payload, make([]byte, 1)...) // Reserved payload = append(payload, make([]byte, 1)...) // Result payload = append(payload, make([]byte, 1)...) // Reserved for _, i := range items { payload = append(payload, i...) } b = append(b, getBytesLenght(2, payload)...) // itemLenght b = append(b, payload...) fmt.Printf("PressContextItem:\n") printBytes(b) return b } // AbstractSyntaxItem returns a byte slice with abstract syntax item. func AbstractSyntaxItem() []byte { return stringItem([]byte{0x30}, sopclass.VerificationSOPClass, "AbstractSyntaxItem") } // TrasnferSyntaxItem returns a byte slice with transfer syntax item. func TrasnferSyntaxItem(tsi string) []byte { return stringItem([]byte{0x40}, tsi, "TrasnferSyntaxItem") } func stringItem(t []byte, content, name string) []byte { b := t b = append(b, make([]byte, 1)...) // Reserved payload := []byte(content) b = append(b, getStringLenght(2, content)...) // itemLenght b = append(b, payload...) fmt.Printf("%s:\n", name) printBytes(b) return b } // UserInfoItem returns a byte slice with user info item. func UserInfoItem(items ...[]byte) []byte { b := []byte{0x50} // itemType b = append(b, make([]byte, 1)...) // Reserved payload := []byte{} for _, i := range items { payload = append(payload, i...) } b = append(b, getBytesLenght(2, payload)...) // itemLenght b = append(b, payload...) fmt.Printf("UserInfoItem:\n") printBytes(b) return b } // MaximunLenghtItem returns a byte slice with maximun lenght item. func MaximunLenghtItem(lenght uint32) []byte { b := []byte{0x51} // itemType b = append(b, make([]byte, 1)...) // Reserved payload := make([]byte, 4) binary.BigEndian.PutUint32(payload, lenght) b = append(b, getBytesLenght(2, payload)...) // itemLenght b = append(b, payload...) fmt.Printf("MaximunLenghtItem:\n") printBytes(b) return b } // ImplementationUIDItem returns a byte slice func ImplementationUIDItem() []byte { b := []byte{82} // itemType b = append(b, make([]byte, 1)...) // Reserved payload := []byte(ImplementationClassUID) b = append(b, getStringLenght(2, ImplementationClassUID)...) // itemLenght b = append(b, payload...) fmt.Printf("ImplementationUID:\n") printBytes(b) return b } // ImplementationVersionItem returns a byte slice func ImplementationVersionItem() []byte { b := []byte{85} // itemType b = append(b, make([]byte, 1)...) // Reserved payload := []byte(ImplementationVersion) b = append(b, getStringLenght(2, ImplementationVersion)...) // itemLenght b = append(b, payload...) fmt.Printf("ImplementationVersion:\n") printBytes(b) return b } func getStringLenght(size int, content string) []byte { b := make([]byte, size) binary.BigEndian.PutUint16(b, uint16(len(content))) return b } func getBytesLenght(size int, content []byte) []byte { return intToBytes(size, len(content)) } func intToBytes(size, i int) []byte { buf := new(bytes.Buffer) err := binary.Write(buf, binary.BigEndian, int64(i)) if err != nil { panic(err) } b := buf.Bytes() return b[len(b)-size:] } func printBytes(b []byte) { l := len(b) var s string for i := 0; i < l; i++ { s += stripCtlFromUTF8(string(b[i])) if i != 0 && i%8 == 0 { if i%16 == 0 { fmt.Printf(" - %s\n", s) s = "" } else { fmt.Printf(" - ") } } fmt.Printf("%2x ", b[i]) if i == l-1 { if 15-i%16 > 7 { fmt.Printf(" - ") } for j := 0; j < 15-i%16; j++ { // fmt.Printf(" ") fmt.Printf(" ") } fmt.Printf(" - %s\n", s) s = "" } } fmt.Printf("\n") } // http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string#Go // two UTF-8 functions identical except for operator comparing c to 127 func stripCtlFromUTF8(str string) string { return strings.Map(func(r rune) rune { if r >= 32 && r != 127 { return r } return '.' }, str) } func byte16PutString(s string) [16]byte { var a [16]byte if len(s) > 16 { copy(a[:], s) } else { copy(a[16-len(s):], s) } return a } func (qr *dicomqr) HandleAccept() error { // Ignore tbuf := make([]byte, 1) _, err := qr.Conn.Read(tbuf) if err != nil { log.Fatal("Error reading", err) } // Read PDULenght tbuf = make([]byte, 4) _, err = qr.Conn.Read(tbuf) if err != nil { log.Fatal("Error reading", err) } var size uint32 buf := bytes.NewBuffer(tbuf) binary.Read(buf, binary.BigEndian, &size) fmt.Println(size) // Get PDU tbuf = make([]byte, size) _, err = qr.Conn.Read(tbuf) if err != nil { log.Fatal("Error reading", err) } printBytes(tbuf) return nil } func main() { log.SetFlags(log.Lshortfile) var host, ae string var port int opt := getoptions.New() opt.StringVar(&host, "host", "localhost") opt.IntVar(&port, "port", 11112) opt.StringVar(&ae, "ae", "PACSAE") _, err := opt.Parse(os.Args[1:]) if err != nil { log.Fatal(err) } qr := dicomqr{ CalledAE: byte16PutString(ae), CallingAE: byte16PutString("go-dicom"), Host: host, Port: port, } qr.Init() fmt.Printf("%v\n", qr.ar) qr.ARAdd(pdu.AppContext(AppContextName)) qr.ARAdd(PressContextItem( pdu.AbstractSyntax(sopclass.PatientRootQRIMFind), TrasnferSyntaxItem(ts.ImplicitVRLittleEndian), TrasnferSyntaxItem(ts.ExplicitVRLittleEndian), TrasnferSyntaxItem(ts.ExplicitVRBigEndian), )) qr.ARAdd(UserInfoItem( MaximunLenghtItem(32768), ImplementationUIDItem(), ImplementationVersionItem(), )) err = qr.Dial() if err != nil { log.Fatal(err) } defer qr.Conn.Close() i, err := qr.AR() if err != nil { fmt.Println("binary.Write failed:", err) } log.Printf("Payload sent: %d bytes", i) tbuf := make([]byte, 1) _, err = qr.Conn.Read(tbuf) if err != nil { log.Fatal("Error reading", err) } switch tbuf[0] { case 0x2: fmt.Println("A-ASSOCIATE accept") qr.HandleAccept() default: printBytes(tbuf) fmt.Println("Unknown") log.Fatal(err) } i, err = qr.RR() if err != nil { fmt.Println("binary.Write failed:", err) } log.Printf("Payload sent: %d bytes", i) tbuf = make([]byte, 1) _, err = qr.Conn.Read(tbuf) if err != nil { log.Fatal("Error reading", err) } switch tbuf[0] { case 0x6: fmt.Println("A-RELEASE response") qr.Conn.Close() default: printBytes(tbuf) fmt.Println("Unknown") log.Fatal(err) } qr.Conn.Close() }
mpl-2.0
whd/dsmo_load
hindsight/hs_run/output/dsmo_funnelcake_redshift.lua
5554
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. local ds = require "heka.derived_stream" local name = read_config("table_prefix") or "download_stats_funnelcake" local schema = { -- column name , field type , length , attributes , field name {"timestamp" , "TIMESTAMP" , nil , "SORTKEY", "Timestamp" }, {"ping_version" , "VARCHAR" , 16 , nil, "Fields[ping_version]" }, {"build_channel" , "VARCHAR" , 32 , nil, "Fields[build_channel]" }, {"update_channel" , "VARCHAR" , 32 , nil, "Fields[update_channel]" }, {"version" , "VARCHAR" , 32 , nil, "Fields[version]" }, {"build_id" , "VARCHAR" , 32 , nil, "Fields[build_id]" }, {"locale" , "VARCHAR" , 5 , nil, "Fields[locale]" }, {"amd64_bit_build" , "BOOLEAN" , nil , nil, "Fields[64bit_build]" }, {"amd64bit_os" , "BOOLEAN" , nil , nil, "Fields[64bit_os]" }, {"os_version" , "VARCHAR" , 32 , nil, "Fields[os_version]" }, {"service_pack" , "VARCHAR" , 16 , nil, "Fields[service_pack]" }, {"server_os" , "BOOLEAN" , nil , nil, "Fields[server_os]" }, {"admin_user" , "BOOLEAN" , nil , nil, "Fields[admin_user]" }, {"default_path" , "BOOLEAN" , nil , nil, "Fields[default_path]" }, {"set_default" , "BOOLEAN" , nil , nil, "Fields[set_default]" }, {"new_default" , "BOOLEAN" , nil , nil, "Fields[new_default]" }, {"old_default" , "BOOLEAN" , nil , nil, "Fields[old_default]" }, {"had_old_install" , "BOOLEAN" , nil , nil, "Fields[had_old_install]" }, {"old_version" , "VARCHAR" , 32 , nil, "Fields[old_version]" }, {"old_build_id" , "VARCHAR" , 32 , nil, "Fields[old_build_id]" }, {"bytes_downloaded" , "INTEGER" , nil , nil, "Fields[bytes_downloaded]" }, {"download_size" , "INTEGER" , nil , nil, "Fields[download_size]" }, {"download_retries" , "INTEGER" , nil , nil, "Fields[download_retries]" }, {"download_time" , "INTEGER" , nil , nil, "Fields[download_time]" }, {"download_latency" , "INTEGER" , nil , nil, "Fields[download_latency]" }, {"download_ip" , "VARCHAR" , 40 , nil, "Fields[download_ip]" }, {"manual_download" , "BOOLEAN" , nil , nil, "Fields[manual_download]" }, {"intro_time" , "INTEGER" , nil , nil, "Fields[intro_time]" }, {"options_time" , "INTEGER" , nil , nil, "Fields[options_time]" }, {"download_phase_time" , "INTEGER" , nil , nil, "Fields[download_phase_time]" }, {"preinstall_time" , "INTEGER" , nil , nil, "Fields[preinstall_time]" }, {"install_time" , "INTEGER" , nil , nil, "Fields[install_time]" }, {"finish_time" , "INTEGER" , nil , nil, "Fields[finish_time]" }, {"succeeded" , "BOOLEAN" , nil , nil, "Fields[succeeded]" }, {"disk_space_error" , "BOOLEAN" , nil , nil, "Fields[disk_space_error]" }, {"no_write_access" , "BOOLEAN" , nil , nil, "Fields[no_write_access]" }, {"download_cancelled" , "BOOLEAN" , nil , nil, "Fields[download_cancelled]" }, {"out_of_retries" , "BOOLEAN" , nil , nil, "Fields[out_of_retries]" }, {"file_error" , "BOOLEAN" , nil , nil, "Fields[file_error]" }, {"sig_not_trusted" , "BOOLEAN" , nil , nil, "Fields[sig_not_trusted]" }, {"sig_unexpected" , "BOOLEAN" , nil , nil, "Fields[sig_unexpected]" }, {"install_timeout" , "BOOLEAN" , nil , nil, "Fields[install_timeout]" }, {"new_launched" , "BOOLEAN" , nil , nil, "Fields[new_launched]" }, {"old_running" , "BOOLEAN" , nil , nil, "Fields[old_running]" }, {"attribution" , "VARCHAR" , 256 , nil, "Fields[attribution]" }, {"profile_cleanup_prompt" , "INTEGER" , nil , nil, "Fields[profile_cleanup_prompt]" }, {"profile_cleanup_requested", "BOOLEAN" , nil , nil, "Fields[profile_cleanup_requested]"}, } process_message, timer_event = ds.load_schema(name, schema)
mpl-2.0
openhybrid/HybridObject
HybridObject.cpp
18338
/** * @preserve * * .,,,;;,'''.. * .'','... ..',,,. * .,,,,,,',,',;;:;,. .,l, * .,',. ... ,;, :l. * ':;. .'.:do;;. .c ol;'. * ';;' ;.; ', .dkl';, .c :; .'.',::,,'''. * ',,;;;,. ; .,' .'''. .'. .d;''.''''. * .oxddl;::,,. ', .'''. .... .'. ,:;.. * .'cOX0OOkdoc. .,'. .. ..... 'lc. * .:;,,::co0XOko' ....''..'.'''''''. * .dxk0KKdc:cdOXKl............. .. ..,c.... * .',lxOOxl:'':xkl,',......'.... ,'. * .';:oo:... . * .cd, ╔═╗┌─┐┬─┐┬ ┬┌─┐┬─┐ . * .l; ╚═╗├┤ ├┬┘└┐┌┘├┤ ├┬┘ ' * 'l. ╚═╝└─┘┴└─ └┘ └─┘┴└─ '. * .o. ... * .''''','.;:''......... * .' .l * .:. l' * .:. .l. * .x: :k;,. * cxlc; cdc,,;;. * 'l :.. .c , * o. * ., * * ╦ ╦┬ ┬┌┐ ┬─┐┬┌┬┐ ╔═╗┌┐ ┬┌─┐┌─┐┌┬┐┌─┐ * ╠═╣└┬┘├┴┐├┬┘│ ││ ║ ║├┴┐ │├┤ │ │ └─┐ * ╩ ╩ ┴ └─┘┴└─┴─┴┘ ╚═╝└─┘└┘└─┘└─┘ ┴ └─┘ * * Created by Valentin on 10/22/14. * * Copyright (c) 2015 Valentin Heun * * All ascii characters above must be included in any redistribution. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //#include "Arduino.h" #include "HybridObject.h" #define BUFFERLENGTH 200 #define SERIALBUFFERLENGTH 400 #define FLOATSTRBUFFER 10 #define BAUDRATE 115200 #define SYSTEMDELAYFORDATA 15 #ifndef HAVE_HWSERIAL1 #define Serial1 Serial #endif void serialEventRun() { HybridObject::update(); } bool HybridObject::clearState = false; bool HybridObject::starter = false; bool HybridObject::developerStatus = false; bool HybridObject::runInit = true; int HybridObject::caseSteper = 9999; int HybridObject::arraySize = 0; unsigned int HybridObject::objectInt = 0; char HybridObject::str[SERIALBUFFERLENGTH + 1]; char HybridObject::floatStr[FLOATSTRBUFFER + 1]; char *HybridObject::object = new char[BUFFERLENGTH + 1]; float HybridObject::tempFloatBuffer = 0.0; float *HybridObject::floatObjectArray = (float *) malloc(sizeof(float) * arraySize); float *HybridObject::floatObjectArrayOld = (float *) malloc(sizeof(float) * arraySize); bool *HybridObject::plusObjectArray = (bool *) malloc(sizeof(bool) * arraySize); bool *HybridObject::minusObjectArray = (bool *) malloc(sizeof(bool) * arraySize); char **HybridObject::stringArray = (char **) malloc(sizeof(char *) * arraySize); void HybridObject::update() { // Serial.println(""); // Serial.println("ss"); for (int i = 0; i < arraySize; i++) { floatObjectArrayOld[i] = floatObjectArray[i]; } // char incomingByte; while (Serial1.available() > 0) { //if(Serial1.available()<20){ // int bRead; // bRead = Serial.readBytesUntil(0x010,str,20); strcpy(str, Serial1.readStringUntil('\n').c_str()); // Serial.read(); //continue; // }else{ // while (Serial1.available() > 0) { // Serial.read(); // } // } //sprintf(str, "%s", Serial1.readStringUntil('\n').c_str()); // Serial1.readBytesUntil('\n',str, Serial1BUFFERLENGTH); // strcpy(str, Serial1.readStringUntil("\n").c_str()); // delay(30); // Serial.println(">>serial>> "); // Serial.println(str); if (strcmp(str, "okbird") == 0) { // Serial.println("ok"); // starter = true; sendDeveloper(); for (int i = 0; i < arraySize; i++) { Serial1.print("a\n"); Serial1.print(stringArray[i]); Serial1.print("\n"); Serial1.print(i); Serial1.print("\n"); // this must be considered for later Serial1.print("default"); Serial1.print("\n"); } Serial1.print("c\n"); Serial1.print(arraySize); Serial1.print("\n"); caseSteper = 0; } switch (caseSteper) { case 0: if (strcmp(str, "f") == 0) { caseSteper = 1; objectInt = 0; // Serial.println(">>serial>>ModeF "); } else if (strcmp(str, "d") == 0) { caseSteper = 1; objectInt = 0; } else if (strcmp(str, "p") == 0) { caseSteper = 10; objectInt = 0; // using the float buffer temporary to communicate the mode. // Serial.print("one\n"); } else if (strcmp(str, "n") == 0) { caseSteper = 20; objectInt = 0; // temp mode.. buffer will be overwritten later anyway. // Serial.print("two\n"); } break; case 1: // Serial.println(">>serial>>Pos "); objectInt = atoi(str); // Serial.println(objectInt); if (objectInt < arraySize && objectInt >= 0) { caseSteper = 2; } else { caseSteper = 0; } // Serial.println(atoi(str)); break; case 10: objectInt = atoi(str); if (objectInt < arraySize && objectInt >= 0) { caseSteper = 12; } else { caseSteper = 0; } // Serial.println(atoi(str)); break; case 20: objectInt = atoi(str); if (objectInt < arraySize && objectInt >= 0) { caseSteper = 22; } else { caseSteper = 0; } // Serial.println(atoi(str)); break; case 2: tempFloatBuffer = atof(str); // Serial.println(">>serial>>Value "); // Serial.println(tempFloatBuffer); if (tempFloatBuffer > 1) tempFloatBuffer = 1; if (tempFloatBuffer < 0) tempFloatBuffer = 0; floatObjectArray[objectInt] = tempFloatBuffer; caseSteper = 0; break; case 12: plusObjectArray[objectInt] = true; minusObjectArray[objectInt] = false; tempFloatBuffer = atof(str); if (tempFloatBuffer > 1) tempFloatBuffer = 1; if (tempFloatBuffer < 0) tempFloatBuffer = 0; floatObjectArray[objectInt] = tempFloatBuffer; caseSteper = 0; break; case 22: plusObjectArray[objectInt] = false; minusObjectArray[objectInt] = true; tempFloatBuffer = atof(str); if (tempFloatBuffer > 1) tempFloatBuffer = 1; if (tempFloatBuffer < 0) tempFloatBuffer = 0; floatObjectArray[objectInt] = tempFloatBuffer; caseSteper = 0; break; }; }; // destress the Hybrid Object Server.... // todo might be able to be be altered when the data is processed based on old value... /* for(int i = 0; i < arraySize; i++){ if(floatObjectArrayOld[i] != floatObjectArray[i]) { Serial.print(floatObjectArray[i]); Serial.print(" - "); Serial.println(floatObjectArrayOld[i]); } } */ } void HybridObject::developer() { developerStatus = true; init(); } void HybridObject::add(char *obj, char *pos, String plugin) { init(); strcpy(object, pos); strcat(object, "\t"); strcat(object, obj); /* Serial1.print("a\n"); Serial1.print(object); Serial1.print("\n"); Serial1.print(arraySize); Serial1.print("\n"); Serial1.print(plugin); Serial1.print("\n");*/ char *objectPointer; objectPointer = (char *) malloc(strlen(obj) + strlen(pos) + 2); strcpy(objectPointer, pos); strcat(objectPointer, "\t"); strcat(objectPointer, obj); arraySize++; stringArray = (char **) realloc(stringArray, (sizeof(char *) * arraySize)); stringArray[arraySize - 1] = objectPointer; floatObjectArray = (float *) realloc(floatObjectArray, (sizeof(float) * arraySize)); floatObjectArray[arraySize - 1] = 0; floatObjectArrayOld = (float *) realloc(floatObjectArrayOld, (sizeof(float) * arraySize)); floatObjectArrayOld[arraySize - 1] = 1; plusObjectArray = (bool *) realloc(plusObjectArray, (sizeof(bool) * arraySize)); plusObjectArray[arraySize - 1] = 1; minusObjectArray = (bool *) realloc(minusObjectArray, (sizeof(bool) * arraySize)); minusObjectArray[arraySize - 1] = 1; } int HybridObject::printObjects() { for (int i = 0; i < arraySize; i++) { Serial1.println(stringArray[i]); } } float HybridObject::read(char *obj, char *pos) { strcpy(object, pos); strcat(object, "\t"); strcat(object, obj); // object = obj +pos; for (int i = 0; i < arraySize; i++) { if (strcmp(stringArray[i], object) == 0) // if(floatObjectArray[i]!= floatObjectArrayOld[i]){ // Serial.print("in: "); // dtostrf(floatObjectArray[i], 5, 4, floatStr); //Serial.println(floatStr);} return floatObjectArray[i]; } return 0; } int HybridObject::stepAvailable(char *obj, char *pos) { return stepAvailable(obj, pos, 1); } int HybridObject::stepAvailable(char *obj, char *pos, int steps) { strcpy(object, pos); strcat(object, "\t"); strcat(object, obj); // object = obj +pos; if (steps > 0) for (int i = 0; i < arraySize; i++) { if (strcmp(stringArray[i], object) == 0) { if (plusObjectArray[i] == true) { plusObjectArray[i] = false; return 1; } if (minusObjectArray[i] == true) { minusObjectArray[i] = false; return -1; } // tempFloatBuffer = 0.0; if (floatObjectArray[i] != floatObjectArrayOld[i]){ /* Serial.print(floatObjectArray[i]); Serial.print(" "); Serial.println(floatObjectArrayOld[i]);*/ // for (int w = 0; w < steps; w++) { // tempFloatBuffer = tempFloatBuffer + (1.0 / (steps + 1)); /* Serial.print("BBBB > "); Serial.print(tempFloatBuffer); Serial.print(" "); Serial.print(floatObjectArray[i]); Serial.print(" "); Serial.println(floatObjectArrayOld[i]);*/ if (floatObjectArray[i] > floatObjectArrayOld[i]) { // floatObjectArrayOld[i] = floatObjectArray[i]; //Serial.println("hoch-----------------"); return -1; } if (floatObjectArray[i] < floatObjectArrayOld[i]) { // floatObjectArrayOld[i] = floatObjectArray[i]; // Serial.println("rinter-----------------"); return 1; } //todo here I need the reference from an older run // } return 1; } return 0; } } return 0; } bool HybridObject::readDigital(char *obj, char *pos) { readDigital(obj, pos, 0.5); } bool HybridObject::readDigital(char *obj, char *pos, float threshold) { if (threshold > 1.0) threshold = 1.0; if (threshold < 0.0) threshold = 0.0; strcpy(object, pos); strcat(object, "\t"); strcat(object, obj); // object = obj +pos; for (int i = 0; i < arraySize; i++) { if (strcmp(stringArray[i], object) == 0) { if (floatObjectArray[i] < threshold) { return false; } else return true; } } return false; } float HybridObject::readFaster(int pos) { return floatObjectArray[pos]; } void HybridObject::write(char *obj, char *pos, float data) { strcpy(object, pos); strcat(object, "\t"); strcat(object, obj); for (int i = 0; i < arraySize; i++) { if (strcmp(stringArray[i], object) == 0) { if (floatObjectArray[i] != data) { //indicate that its a floating point value Serial1.print("f\n"); Serial1.print(i); // Serial.println(i); Serial1.print("\n"); // print normal value // Make sure that everything is within the scale if (data > 1) data = 1; if (data < 0) data = 0; dtostrf(data, 5, 4, floatStr); Serial1.print(floatStr); // Serial.print("out: "); // Serial.println(floatStr); // Serial.println(data); Serial1.print("\n"); // Serial.println(tempFloatBuffer); floatObjectArray[i] = data; } // this is for keeping the system from crashing delay(SYSTEMDELAYFORDATA); break; } } } void HybridObject::writeStepUp(char *obj, char *pos) { writeStepUp(obj, pos, 1); } void HybridObject::writeStepDown(char *obj, char *pos) { writeStepDown(obj, pos, 1); } void HybridObject::writeStepUp(char *obj, char *pos, int steps) { writeStepSerial(obj, pos, steps, true); } void HybridObject::writeStepDown(char *obj, char *pos, int steps) { writeStepSerial(obj, pos, steps, false); } void HybridObject::writeStepSerial(char *obj, char *pos, int steps, bool direction) { strcpy(object, pos); strcat(object, "\t"); strcat(object, obj); if (steps != 0) for (int i = 0; i < arraySize; i++) { if (strcmp(stringArray[i], object) == 0) { //indicate that its a floating point value if (direction) { Serial1.print("p\n"); // Serial.println("p"); floatObjectArray[i] = floatObjectArray[i] + (1.0 / steps); if (floatObjectArray[i] > 1.0) floatObjectArray[i] = 1.0; } else { Serial1.print("n\n"); // Serial.println("n"); floatObjectArray[i] = floatObjectArray[i] - (1.0 / steps); if (floatObjectArray[i] < 0.0) floatObjectArray[i] = 0.0; } Serial1.print(i); // Serial.println(i); Serial1.print("\n"); dtostrf(floatObjectArray[i], 5, 4, floatStr); Serial1.print(floatStr); // Serial.println(data); Serial1.print("\n"); break; } } } void HybridObject::writeDigital(char *obj, char *pos, bool data) { strcpy(object, pos); strcat(object, "\t"); strcat(object, obj); /* if(data>1.0) data = 1.0; if(data<0.0) data = 0.0; if(threshold>1.0) threshold = 1.0; if(threshold<0.0) threshold = 0.0; */ if (data) tempFloatBuffer = 1.0; else tempFloatBuffer = 0.0; for (int i = 0; i < arraySize; i++) { if (strcmp(stringArray[i], object) == 0) { if (tempFloatBuffer != floatObjectArray[i]) { //indicate that its a floating point value Serial1.print("d\n"); Serial1.print(i); // Serial.println(i); Serial1.print("\n"); //print digital. optional change the sensitivity. Serial1.print(tempFloatBuffer); // Serial.println(tempFloatBuffer); // Serial.println(i); Serial1.print("\n"); floatObjectArray[i] = tempFloatBuffer; } break; } } } void HybridObject::writeFaster(int pos, float data) { //indicate that its floating Serial1.print("f\n"); Serial1.print(pos); Serial1.print("\n"); Serial1.print(data); Serial1.print("\n"); floatObjectArray[pos] = data; } float HybridObject::map(float x, float in_min, float in_max) { if (x > in_max) x = in_max; if (x < in_min) x = in_min; float out_min = 0; float out_max = 1; return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } void HybridObject::init() { if (runInit) { // for(int i = 0; i <30; i++){ Serial1.begin(BAUDRATE); while (!Serial1) { ; // wait for serial port to connect. Needed for Leonardo only } //delay(100); runInit = false; Serial1.print("okbird\n"); // Serial1.print("ok\n"); for (int i = 0; i < arraySize; i++) { plusObjectArray[i] = false; minusObjectArray[i] = false; } } } void HybridObject::sendDeveloper() { Serial1.print("def\n"); if (developerStatus) { Serial1.print("1\n"); } else { Serial1.print("0\n"); } }
mpl-2.0
UK992/servo
tests/wpt/web-platform-tests/offscreen-canvas/drawing-rectangles-to-the-canvas/2d.clearRect.path.worker.js
790
// DO NOT EDIT! This test has been generated by /offscreen-canvas/tools/gentest.py. // OffscreenCanvas test in a worker:2d.clearRect.path // Description:clearRect does not affect the current path // Note: importScripts("/resources/testharness.js"); importScripts("/2dcontext/resources/canvas-tests.js"); var t = async_test("clearRect does not affect the current path"); var t_pass = t.done.bind(t); var t_fail = t.step_func(function(reason) { throw reason; }); t.step(function() { var offscreenCanvas = new OffscreenCanvas(100, 50); var ctx = offscreenCanvas.getContext('2d'); ctx.fillStyle = '#0f0'; ctx.beginPath(); ctx.rect(0, 0, 100, 50); ctx.clearRect(0, 0, 16, 16); ctx.fill(); _assertPixel(offscreenCanvas, 50,25, 0,255,0,255, "50,25", "0,255,0,255"); t.done(); }); done();
mpl-2.0
threadly/threadly_benchmarks
src/main/java/org/threadly/concurrent/benchmark/SingleThreadSchedulerExecuteBenchmark.java
892
package org.threadly.concurrent.benchmark; import org.threadly.concurrent.SingleThreadScheduler; import org.threadly.concurrent.SubmitterScheduler; public class SingleThreadSchedulerExecuteBenchmark extends AbstractSchedulerExecuteBenchmark { protected static final SingleThreadScheduler EXECUTOR; static { EXECUTOR = new SingleThreadScheduler(); } public static void main(String args[]) { try { new SingleThreadSchedulerExecuteBenchmark(Integer.parseInt(args[0])).runTest(); System.exit(0); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } } protected SingleThreadSchedulerExecuteBenchmark(int threadRunTime) { super(threadRunTime); } @Override protected SubmitterScheduler getScheduler() { return EXECUTOR; } @Override protected void shutdownScheduler() { EXECUTOR.shutdownNow(); } }
mpl-2.0
mozilla/badgekit-api-python-client
badgekitapiclient/client/methods/issuers.py
901
from badgekitapiclient import models from badgekitapiclient.client.utils import context_requires, Generator @context_requires(models.System) def get_issuers (client, context): options = { 'path': context._path + models.Issuer.path_part, 'filter': 'issuers', 'default': [], 'generator': Generator(models.Issuer, context), } return client._remote.get(options) def get_issuer (client, context): return _do_issuer_action(client, context, 'load') def create_issuer (client, context): return _do_issuer_action(client, context, 'create') def delete_issuer (client, context): return _do_issuer_action(client, context, 'delete') def update_issuer (context, callback): return _do_issuer_action(client, context, 'save') @context_requires(models.Issuer) def _do_issuer_action (client, context, action): return getattr(context, action)()
mpl-2.0
codeLief/ankang-report
src/main/java/com/ankang/report/model/ExecuteMethod.java
2325
/** **Copyright (c) 2015, ancher 安康 (676239139@qq.com). ** ** This Source Code Form is subject to the terms of the Mozilla Public ** License, v. 2.0. If a copy of the MPL was not distributed with this ** file, You can obtain one at ** ** http://mozilla.org/MPL/2.0/. ** **If it is not possible or desirable to put the notice in a particular **file, then You may include the notice in a location (such as a LICENSE **file in a relevant directory) where a recipient would be likely to look **for such a notice. **/ package com.ankang.report.model; import java.io.Serializable; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.springframework.web.bind.annotation.RequestMethod; @SuppressWarnings("all") public class ExecuteMethod implements Serializable{ private static final long serialVersionUID = 1L; private String moduleName; private Class clazz; private final List<Map<String, Method>> executeMethod = new ArrayList<Map<String,Method>>();//方法别名和方法类型 重复方法的处理办法 private final List<Map<String, RequestMethod[]>> executeType = new ArrayList<Map<String,RequestMethod[]>>();//方法别名和请求类型 private final List<Map<String, LinkedHashMap<String, Class<?>>>> parameterType = new ArrayList<Map<String,LinkedHashMap<String,Class<?>>>>(); //方法名称和参数名称类型 private final List<Map<String, String>> executeDesc = new ArrayList<Map<String, String>>(); //方法名称和描述 public ExecuteMethod() {} public ExecuteMethod(String moduleName, Class clazz) { super(); this.moduleName = moduleName; this.clazz = clazz; } public Class getClazz() { return clazz; } public void setClazz(Class clazz) { this.clazz = clazz; } public String getModuleName() { return moduleName; } public void setModuleName(String moduleName) { this.moduleName = moduleName; } public List<Map<String, Method>> getExecuteMethod() { return executeMethod; } public List<Map<String, RequestMethod[]>> getExecuteType() { return executeType; } public List<Map<String, LinkedHashMap<String, Class<?>>>> getParameterType() { return parameterType; } public List<Map<String, String>> getExecuteDesc() { return executeDesc; } }
mpl-2.0
opsidian/parsley
combinator/any.go
1218
// Copyright (c) 2017 Opsidian Ltd. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. package combinator import ( "github.com/opsidian/parsley/ast" "github.com/opsidian/parsley/data" "github.com/opsidian/parsley/parser" "github.com/opsidian/parsley/parsley" ) // Any tries all the given parsers independently and merges the results func Any(parsers ...parsley.Parser) parser.Func { if parsers == nil { panic("no parsers were given") } return parser.Func(func(ctx *parsley.Context, leftRecCtx data.IntMap, pos parsley.Pos) (parsley.Node, data.IntSet, parsley.Error) { cp := data.EmptyIntSet var res parsley.Node var err parsley.Error for _, p := range parsers { ctx.RegisterCall() res2, cp2, err2 := p.Parse(ctx, leftRecCtx, pos) cp = cp.Union(cp2) res = ast.AppendNode(res, res2) if err2 != nil && (err == nil || err2.Pos() >= err.Pos()) { if err2.Pos() > pos || !parsley.IsNotFoundError(err2) { err = err2 } } } if res == nil { return nil, cp, err } ctx.SetError(err) return res, cp, nil }) }
mpl-2.0
status-im/status-go
vendor/github.com/kilic/bls12-381/fp12.go
5367
package bls12381 import ( "errors" "math/big" ) type fp12 struct { fp12temp fp6 *fp6 } type fp12temp struct { t2 [9]*fe2 t6 [5]*fe6 t12 *fe12 } func newFp12Temp() fp12temp { t2 := [9]*fe2{} t6 := [5]*fe6{} for i := 0; i < len(t2); i++ { t2[i] = &fe2{} } for i := 0; i < len(t6); i++ { t6[i] = &fe6{} } return fp12temp{t2, t6, &fe12{}} } func newFp12(fp6 *fp6) *fp12 { t := newFp12Temp() if fp6 == nil { return &fp12{t, newFp6(nil)} } return &fp12{t, fp6} } func (e *fp12) fp2() *fp2 { return e.fp6.fp2 } func (e *fp12) fromBytes(in []byte) (*fe12, error) { if len(in) != 576 { return nil, errors.New("input string should be larger than 96 bytes") } fp6 := e.fp6 c1, err := fp6.fromBytes(in[:288]) if err != nil { return nil, err } c0, err := fp6.fromBytes(in[288:]) if err != nil { return nil, err } return &fe12{*c0, *c1}, nil } func (e *fp12) toBytes(a *fe12) []byte { fp6 := e.fp6 out := make([]byte, 576) copy(out[:288], fp6.toBytes(&a[1])) copy(out[288:], fp6.toBytes(&a[0])) return out } func (e *fp12) new() *fe12 { return new(fe12) } func (e *fp12) zero() *fe12 { return new(fe12) } func (e *fp12) one() *fe12 { return new(fe12).one() } func (e *fp12) add(c, a, b *fe12) { fp6 := e.fp6 fp6.add(&c[0], &a[0], &b[0]) fp6.add(&c[1], &a[1], &b[1]) } func (e *fp12) double(c, a *fe12) { fp6 := e.fp6 fp6.double(&c[0], &a[0]) fp6.double(&c[1], &a[1]) } func (e *fp12) sub(c, a, b *fe12) { fp6 := e.fp6 fp6.sub(&c[0], &a[0], &b[0]) fp6.sub(&c[1], &a[1], &b[1]) } func (e *fp12) neg(c, a *fe12) { fp6 := e.fp6 fp6.neg(&c[0], &a[0]) fp6.neg(&c[1], &a[1]) } func (e *fp12) conjugate(c, a *fe12) { fp6 := e.fp6 c[0].set(&a[0]) fp6.neg(&c[1], &a[1]) } func (e *fp12) square(c, a *fe12) { fp6, t := e.fp6, e.t6 fp6.add(t[0], &a[0], &a[1]) fp6.mul(t[2], &a[0], &a[1]) fp6.mulByNonResidue(t[1], &a[1]) fp6.addAssign(t[1], &a[0]) fp6.mulByNonResidue(t[3], t[2]) fp6.mulAssign(t[0], t[1]) fp6.subAssign(t[0], t[2]) fp6.sub(&c[0], t[0], t[3]) fp6.double(&c[1], t[2]) } func (e *fp12) cyclotomicSquare(c, a *fe12) { t, fp2 := e.t2, e.fp2() e.fp4Square(t[3], t[4], &a[0][0], &a[1][1]) fp2.sub(t[2], t[3], &a[0][0]) fp2.doubleAssign(t[2]) fp2.add(&c[0][0], t[2], t[3]) fp2.add(t[2], t[4], &a[1][1]) fp2.doubleAssign(t[2]) fp2.add(&c[1][1], t[2], t[4]) e.fp4Square(t[3], t[4], &a[1][0], &a[0][2]) e.fp4Square(t[5], t[6], &a[0][1], &a[1][2]) fp2.sub(t[2], t[3], &a[0][1]) fp2.doubleAssign(t[2]) fp2.add(&c[0][1], t[2], t[3]) fp2.add(t[2], t[4], &a[1][2]) fp2.doubleAssign(t[2]) fp2.add(&c[1][2], t[2], t[4]) fp2.mulByNonResidue(t[3], t[6]) fp2.add(t[2], t[3], &a[1][0]) fp2.doubleAssign(t[2]) fp2.add(&c[1][0], t[2], t[3]) fp2.sub(t[2], t[5], &a[0][2]) fp2.doubleAssign(t[2]) fp2.add(&c[0][2], t[2], t[5]) } func (e *fp12) mul(c, a, b *fe12) { t, fp6 := e.t6, e.fp6 fp6.mul(t[1], &a[0], &b[0]) fp6.mul(t[2], &a[1], &b[1]) fp6.add(t[0], t[1], t[2]) fp6.mulByNonResidue(t[2], t[2]) fp6.add(t[3], t[1], t[2]) fp6.add(t[1], &a[0], &a[1]) fp6.add(t[2], &b[0], &b[1]) fp6.mulAssign(t[1], t[2]) c[0].set(t[3]) fp6.sub(&c[1], t[1], t[0]) } func (e *fp12) mulAssign(a, b *fe12) { t, fp6 := e.t6, e.fp6 fp6.mul(t[1], &a[0], &b[0]) fp6.mul(t[2], &a[1], &b[1]) fp6.add(t[0], t[1], t[2]) fp6.mulByNonResidue(t[2], t[2]) fp6.add(t[3], t[1], t[2]) fp6.add(t[1], &a[0], &a[1]) fp6.add(t[2], &b[0], &b[1]) fp6.mulAssign(t[1], t[2]) a[0].set(t[3]) fp6.sub(&a[1], t[1], t[0]) } func (e *fp12) fp4Square(c0, c1, a0, a1 *fe2) { t, fp2 := e.t2, e.fp2() fp2.square(t[0], a0) fp2.square(t[1], a1) fp2.mulByNonResidue(t[2], t[1]) fp2.add(c0, t[2], t[0]) fp2.add(t[2], a0, a1) fp2.squareAssign(t[2]) fp2.subAssign(t[2], t[0]) fp2.sub(c1, t[2], t[1]) } func (e *fp12) inverse(c, a *fe12) { fp6, t := e.fp6, e.t6 fp6.square(t[0], &a[0]) fp6.square(t[1], &a[1]) fp6.mulByNonResidue(t[1], t[1]) fp6.sub(t[1], t[0], t[1]) fp6.inverse(t[0], t[1]) fp6.mul(&c[0], &a[0], t[0]) fp6.mulAssign(t[0], &a[1]) fp6.neg(&c[1], t[0]) } func (e *fp12) mulBy014Assign(a *fe12, c0, c1, c4 *fe2) { fp2, fp6, t, t2 := e.fp2(), e.fp6, e.t6, e.t2[0] fp6.mulBy01(t[0], &a[0], c0, c1) fp6.mulBy1(t[1], &a[1], c4) fp2.add(t2, c1, c4) fp6.add(t[2], &a[1], &a[0]) fp6.mulBy01Assign(t[2], c0, t2) fp6.subAssign(t[2], t[0]) fp6.sub(&a[1], t[2], t[1]) fp6.mulByNonResidue(t[1], t[1]) fp6.add(&a[0], t[1], t[0]) } func (e *fp12) exp(c, a *fe12, s *big.Int) { z := e.one() for i := s.BitLen() - 1; i >= 0; i-- { e.square(z, z) if s.Bit(i) == 1 { e.mul(z, z, a) } } c.set(z) } func (e *fp12) cyclotomicExp(c, a *fe12, s *big.Int) { z := e.one() for i := s.BitLen() - 1; i >= 0; i-- { e.cyclotomicSquare(z, z) if s.Bit(i) == 1 { e.mul(z, z, a) } } c.set(z) } func (e *fp12) frobeniusMap(c, a *fe12, power uint) { fp6 := e.fp6 fp6.frobeniusMap(&c[0], &a[0], power) fp6.frobeniusMap(&c[1], &a[1], power) switch power { case 0: return case 6: fp6.neg(&c[1], &c[1]) default: fp6.mulByBaseField(&c[1], &c[1], &frobeniusCoeffs12[power]) } } func (e *fp12) frobeniusMapAssign(a *fe12, power uint) { fp6 := e.fp6 fp6.frobeniusMapAssign(&a[0], power) fp6.frobeniusMapAssign(&a[1], power) switch power { case 0: return case 6: fp6.neg(&a[1], &a[1]) default: fp6.mulByBaseField(&a[1], &a[1], &frobeniusCoeffs12[power]) } }
mpl-2.0
Topl/Project-Bifrost
src/main/scala/bifrost/api/http/swagger/CorsSupport.scala
1395
package bifrost.api.http.swagger import akka.http.scaladsl.marshalling.ToResponseMarshallable.apply import akka.http.scaladsl.model.HttpMethods._ import akka.http.scaladsl.model.HttpResponse import akka.http.scaladsl.model.StatusCode.int2StatusCode import akka.http.scaladsl.model.headers._ import akka.http.scaladsl.server.Directive.addByNameNullaryApply import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.{Directive0, Route} //see https://groups.google.com/forum/#!topic/akka-user/5RCZIJt7jHo trait CorsSupport { //this directive adds access control headers to normal responses private def withAccessControlHeaders: Directive0 = { mapResponseHeaders { headers => `Access-Control-Allow-Origin`.* +: `Access-Control-Allow-Credentials`(true) +: `Access-Control-Allow-Headers`("Authorization", "Content-Type", "X-Requested-With") +: headers } } //this handles preflight OPTIONS requests. // TODO: see if can be done with rejection handler, otherwise has to be under addAccessControlHeaders private def preflightRequestHandler: Route = options { complete(HttpResponse(200).withHeaders( `Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE) ) ) } def corsHandler(r: Route): Route = withAccessControlHeaders { preflightRequestHandler ~ r } }
mpl-2.0
PawelGutkowski/openmrs-module-webservices.rest
omod-1.9/src/main/java/org/openmrs/module/webservices/rest/web/v1_0/resource/openmrs1_9/ConceptStopwordResource1_9.java
5596
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.module.webservices.rest.web.v1_0.resource.openmrs1_9; import org.apache.commons.lang.StringUtils; import org.openmrs.api.context.Context; import org.openmrs.module.webservices.rest.web.RequestContext; import org.openmrs.module.webservices.rest.web.RestConstants; import org.openmrs.module.webservices.rest.web.annotation.PropertyGetter; import org.openmrs.module.webservices.rest.web.annotation.Resource; import org.openmrs.module.webservices.rest.web.representation.*; import org.openmrs.module.webservices.rest.web.resource.api.PageableResult; import org.openmrs.module.webservices.rest.web.resource.impl.DelegatingCrudResource; import org.openmrs.module.webservices.rest.web.resource.impl.DelegatingResourceDescription; import org.openmrs.module.webservices.rest.web.resource.impl.NeedsPaging; import org.openmrs.module.webservices.rest.web.response.ResourceDoesNotSupportOperationException; import org.openmrs.module.webservices.rest.web.response.ResponseException; import org.openmrs.ConceptStopWord; import java.util.List; /** * {@link Resource} for {@link ConceptStopWord}, supporting standard CRUD operations */ @Resource(name = RestConstants.VERSION_1 + "/conceptstopword", supportedClass = ConceptStopWord.class, supportedOpenmrsVersions = { "1.9.*", "1.10.*", "1.11.*", "1.12.*", "2.0.*", "2.1.*" }) public class ConceptStopwordResource1_9 extends DelegatingCrudResource<ConceptStopWord> { /** * @see DelegatingCrudResource#getRepresentationDescription(Representation) */ @Override public DelegatingResourceDescription getRepresentationDescription(Representation rep) { if (rep instanceof RefRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("display"); description.addSelfLink(); return description; } else if (rep instanceof DefaultRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("display"); description.addProperty("value"); description.addProperty("locale"); description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); description.addSelfLink(); return description; } else if (rep instanceof FullRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("display"); description.addProperty("value"); description.addProperty("locale"); description.addSelfLink(); return description; } return null; } @PropertyGetter("display") public String getDisplayString(ConceptStopWord delegate) { return StringUtils.isEmpty(delegate.getValue()) ? "" : delegate.getValue(); } /** * @see org.openmrs.module.webservices.rest.web.resource.impl.BaseDelegatingResource#getCreatableProperties() */ @Override public DelegatingResourceDescription getCreatableProperties() { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addRequiredProperty("value"); description.addProperty("locale"); return description; } /** * @see DelegatingCrudResource#getByUniqueId(java.lang.String) */ @Override public ConceptStopWord getByUniqueId(String uniqueId) { List<ConceptStopWord> datatypes = Context.getConceptService().getAllConceptStopWords(); for (ConceptStopWord datatype : datatypes) { if (datatype.getUuid().equals(uniqueId)) { return datatype; } } return null; } /** * @see DelegatingCrudResource#newDelegate() */ @Override public ConceptStopWord newDelegate() { return new ConceptStopWord(); } /** * @see DelegatingCrudResource#save(java.lang.Object) */ @Override public ConceptStopWord save(ConceptStopWord delegate) { return Context.getConceptService().saveConceptStopWord(delegate); } /** * @see org.openmrs.module.webservices.rest.web.resource.impl.DelegatingCrudResource#purge(java.lang.Object, * org.openmrs.module.webservices.rest.web.RequestContext) */ @Override public void purge(ConceptStopWord delegate, RequestContext context) throws ResponseException { Context.getConceptService().deleteConceptStopWord(delegate.getId()); } @Override protected void delete(ConceptStopWord delegate, String reason, RequestContext context) throws ResponseException { throw new ResourceDoesNotSupportOperationException(); } /** * @see org.openmrs.module.webservices.rest.web.resource.impl.DelegatingCrudResource#doGetAll(org.openmrs.module.webservices.rest.web.RequestContext) */ @Override protected PageableResult doGetAll(RequestContext context) throws ResponseException { List<ConceptStopWord> conceptStopWords = Context.getConceptService().getAllConceptStopWords(); return new NeedsPaging<ConceptStopWord>(conceptStopWords, context); } /** * @see org.openmrs.module.webservices.rest.web.resource.impl.BaseDelegatingResource#getResourceVersion() */ @Override public String getResourceVersion() { return RestConstants1_9.RESOURCE_VERSION; } }
mpl-2.0
danlrobertson/servo
components/style/lib.rs
6557
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of stylesheets. //! //! [computed]: https://drafts.csswg.org/css-cascade/#computed //! [specified]: https://drafts.csswg.org/css-cascade/#specified //! //! In particular, this crate contains the definitions of supported properties, //! the code to parse them into specified values and calculate the computed //! values based on the specified values, as well as the code to serialize both //! specified and computed values. //! //! The main entry point is [`recalc_style_at`][recalc_style_at]. //! //! [recalc_style_at]: traversal/fn.recalc_style_at.html //! //! Major dependencies are the [cssparser][cssparser] and [selectors][selectors] //! crates. //! //! [cssparser]: ../cssparser/index.html //! [selectors]: ../selectors/index.html #![deny(missing_docs)] extern crate app_units; extern crate arrayvec; extern crate atomic_refcell; #[macro_use] extern crate bitflags; #[allow(unused_extern_crates)] extern crate byteorder; #[cfg(feature = "gecko")] #[macro_use] #[no_link] extern crate cfg_if; #[cfg(feature = "servo")] extern crate crossbeam_channel; #[macro_use] extern crate cssparser; #[macro_use] extern crate debug_unreachable; extern crate euclid; extern crate fallible; extern crate fxhash; #[cfg(feature = "gecko")] #[macro_use] pub mod gecko_string_cache; extern crate hashglobe; #[cfg(feature = "servo")] #[macro_use] extern crate html5ever; extern crate itertools; extern crate itoa; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[macro_use] extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; #[allow(unused_extern_crates)] #[macro_use] extern crate matches; #[cfg(feature = "gecko")] pub extern crate nsstring; #[cfg(feature = "gecko")] extern crate num_cpus; #[macro_use] extern crate num_derive; extern crate num_integer; extern crate num_traits; extern crate ordered_float; extern crate owning_ref; extern crate parking_lot; extern crate precomputed_hash; extern crate rayon; extern crate selectors; #[cfg(feature = "servo")] #[macro_use] extern crate serde; pub extern crate servo_arc; #[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms; #[cfg(feature = "servo")] extern crate servo_config; #[cfg(feature = "servo")] extern crate servo_url; extern crate smallbitvec; extern crate smallvec; #[cfg(feature = "servo")] extern crate string_cache; #[macro_use] extern crate style_derive; extern crate style_traits; #[cfg(feature = "gecko")] extern crate thin_slice; extern crate time; extern crate uluru; extern crate unicode_bidi; #[allow(unused_extern_crates)] extern crate unicode_segmentation; extern crate void; #[macro_use] mod macros; pub mod animation; pub mod applicable_declarations; #[allow(missing_docs)] // TODO. #[cfg(feature = "servo")] pub mod attr; pub mod author_styles; pub mod bezier; pub mod bloom; pub mod context; pub mod counter_style; pub mod custom_properties; pub mod data; pub mod dom; pub mod dom_apis; pub mod driver; pub mod element_state; #[cfg(feature = "servo")] mod encoding_support; pub mod error_reporting; pub mod font_face; pub mod font_metrics; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_bindings; pub mod hash; pub mod invalidation; #[allow(missing_docs)] // TODO. pub mod logical_geometry; pub mod matching; #[macro_use] pub mod media_queries; pub mod parallel; pub mod parser; pub mod rule_cache; pub mod rule_collector; pub mod rule_tree; pub mod scoped_tls; pub mod selector_map; pub mod selector_parser; pub mod shared_lock; pub mod sharing; pub mod str; pub mod style_adjuster; pub mod style_resolver; pub mod stylesheet_set; pub mod stylesheets; pub mod stylist; pub mod thread_state; pub mod timer; pub mod traversal; pub mod traversal_flags; pub mod use_counters; #[macro_use] #[allow(non_camel_case_types)] pub mod values; #[cfg(feature = "gecko")] pub use crate::gecko_string_cache as string_cache; #[cfg(feature = "gecko")] pub use crate::gecko_string_cache::Atom; #[cfg(feature = "gecko")] pub use crate::gecko_string_cache::Atom as Prefix; #[cfg(feature = "gecko")] pub use crate::gecko_string_cache::Atom as LocalName; #[cfg(feature = "gecko")] pub use crate::gecko_string_cache::Namespace; #[cfg(feature = "servo")] pub use html5ever::LocalName; #[cfg(feature = "servo")] pub use html5ever::Namespace; #[cfg(feature = "servo")] pub use html5ever::Prefix; #[cfg(feature = "servo")] pub use servo_atoms::Atom; /// The CSS properties supported by the style system. /// Generated from the properties.mako.rs template by build.rs #[macro_use] #[allow(unsafe_code)] #[deny(missing_docs)] pub mod properties { include!(concat!(env!("OUT_DIR"), "/properties.rs")); } #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko; // uses a macro from properties #[cfg(feature = "servo")] #[allow(unsafe_code)] pub mod servo; #[cfg(feature = "gecko")] #[allow(unsafe_code, missing_docs)] pub mod gecko_properties { include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs")); } macro_rules! reexport_computed_values { ( $( { $name: ident, $boxed: expr } )+ ) => { /// Types for [computed values][computed]. /// /// [computed]: https://drafts.csswg.org/css-cascade/#computed pub mod computed_values { $( pub use crate::properties::longhands::$name::computed_value as $name; )+ // Don't use a side-specific name needlessly: pub use crate::properties::longhands::border_top_style::computed_value as border_style; } } } longhand_properties_idents!(reexport_computed_values); #[cfg(feature = "gecko")] use crate::gecko_string_cache::WeakAtom; #[cfg(feature = "servo")] use servo_atoms::Atom as WeakAtom; /// Extension methods for selectors::attr::CaseSensitivity pub trait CaseSensitivityExt { /// Return whether two atoms compare equal according to this case sensitivity. fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool; } impl CaseSensitivityExt for selectors::attr::CaseSensitivity { fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool { match self { selectors::attr::CaseSensitivity::CaseSensitive => a == b, selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b), } } }
mpl-2.0
Ninir/terraform-provider-aws
aws/resource_aws_config_configuration_recorder_status_test.go
8046
package aws import ( "fmt" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/configservice" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func testAccConfigConfigurationRecorderStatus_basic(t *testing.T) { var cr configservice.ConfigurationRecorder var crs configservice.ConfigurationRecorderStatus rInt := acctest.RandInt() expectedName := fmt.Sprintf("tf-acc-test-%d", rInt) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckConfigConfigurationRecorderStatusDestroy, Steps: []resource.TestStep{ { Config: testAccConfigConfigurationRecorderStatusConfig(rInt, false), Check: resource.ComposeTestCheckFunc( testAccCheckConfigConfigurationRecorderExists("aws_config_configuration_recorder.foo", &cr), testAccCheckConfigConfigurationRecorderStatusExists("aws_config_configuration_recorder_status.foo", &crs), testAccCheckConfigConfigurationRecorderStatus("aws_config_configuration_recorder_status.foo", false, &crs), resource.TestCheckResourceAttr("aws_config_configuration_recorder_status.foo", "is_enabled", "false"), resource.TestCheckResourceAttr("aws_config_configuration_recorder_status.foo", "name", expectedName), ), }, }, }) } func testAccConfigConfigurationRecorderStatus_startEnabled(t *testing.T) { var cr configservice.ConfigurationRecorder var crs configservice.ConfigurationRecorderStatus rInt := acctest.RandInt() expectedName := fmt.Sprintf("tf-acc-test-%d", rInt) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckConfigConfigurationRecorderStatusDestroy, Steps: []resource.TestStep{ { Config: testAccConfigConfigurationRecorderStatusConfig(rInt, true), Check: resource.ComposeTestCheckFunc( testAccCheckConfigConfigurationRecorderExists("aws_config_configuration_recorder.foo", &cr), testAccCheckConfigConfigurationRecorderStatusExists("aws_config_configuration_recorder_status.foo", &crs), testAccCheckConfigConfigurationRecorderStatus("aws_config_configuration_recorder_status.foo", true, &crs), resource.TestCheckResourceAttr("aws_config_configuration_recorder_status.foo", "is_enabled", "true"), resource.TestCheckResourceAttr("aws_config_configuration_recorder_status.foo", "name", expectedName), ), }, { Config: testAccConfigConfigurationRecorderStatusConfig(rInt, false), Check: resource.ComposeTestCheckFunc( testAccCheckConfigConfigurationRecorderExists("aws_config_configuration_recorder.foo", &cr), testAccCheckConfigConfigurationRecorderStatusExists("aws_config_configuration_recorder_status.foo", &crs), testAccCheckConfigConfigurationRecorderStatus("aws_config_configuration_recorder_status.foo", false, &crs), resource.TestCheckResourceAttr("aws_config_configuration_recorder_status.foo", "is_enabled", "false"), resource.TestCheckResourceAttr("aws_config_configuration_recorder_status.foo", "name", expectedName), ), }, { Config: testAccConfigConfigurationRecorderStatusConfig(rInt, true), Check: resource.ComposeTestCheckFunc( testAccCheckConfigConfigurationRecorderExists("aws_config_configuration_recorder.foo", &cr), testAccCheckConfigConfigurationRecorderStatusExists("aws_config_configuration_recorder_status.foo", &crs), testAccCheckConfigConfigurationRecorderStatus("aws_config_configuration_recorder_status.foo", true, &crs), resource.TestCheckResourceAttr("aws_config_configuration_recorder_status.foo", "is_enabled", "true"), resource.TestCheckResourceAttr("aws_config_configuration_recorder_status.foo", "name", expectedName), ), }, }, }) } func testAccConfigConfigurationRecorderStatus_importBasic(t *testing.T) { resourceName := "aws_config_configuration_recorder_status.foo" rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckConfigConfigurationRecorderStatusDestroy, Steps: []resource.TestStep{ { Config: testAccConfigConfigurationRecorderStatusConfig(rInt, true), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func testAccCheckConfigConfigurationRecorderStatusExists(n string, obj *configservice.ConfigurationRecorderStatus) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } conn := testAccProvider.Meta().(*AWSClient).configconn out, err := conn.DescribeConfigurationRecorderStatus(&configservice.DescribeConfigurationRecorderStatusInput{ ConfigurationRecorderNames: []*string{aws.String(rs.Primary.Attributes["name"])}, }) if err != nil { return fmt.Errorf("Failed to describe status of configuration recorder: %s", err) } if len(out.ConfigurationRecordersStatus) < 1 { return fmt.Errorf("Configuration Recorder %q not found", rs.Primary.Attributes["name"]) } status := out.ConfigurationRecordersStatus[0] *obj = *status return nil } } func testAccCheckConfigConfigurationRecorderStatus(n string, desired bool, obj *configservice.ConfigurationRecorderStatus) resource.TestCheckFunc { return func(s *terraform.State) error { _, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if *obj.Recording != desired { return fmt.Errorf("Expected configuration recorder %q recording to be %t, given: %t", n, desired, *obj.Recording) } return nil } } func testAccCheckConfigConfigurationRecorderStatusDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).configconn for _, rs := range s.RootModule().Resources { if rs.Type != "aws_config_configuration_recorder_status" { continue } resp, err := conn.DescribeConfigurationRecorderStatus(&configservice.DescribeConfigurationRecorderStatusInput{ ConfigurationRecorderNames: []*string{aws.String(rs.Primary.Attributes["name"])}, }) if err == nil { if len(resp.ConfigurationRecordersStatus) != 0 && *resp.ConfigurationRecordersStatus[0].Name == rs.Primary.Attributes["name"] && *resp.ConfigurationRecordersStatus[0].Recording { return fmt.Errorf("Configuration recorder is still recording: %s", rs.Primary.Attributes["name"]) } } } return nil } func testAccConfigConfigurationRecorderStatusConfig(randInt int, enabled bool) string { return fmt.Sprintf(` resource "aws_config_configuration_recorder" "foo" { name = "tf-acc-test-%d" role_arn = "${aws_iam_role.r.arn}" } resource "aws_iam_role" "r" { name = "tf-acc-test-awsconfig-%d" assume_role_policy = <<POLICY { "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Principal": { "Service": "config.amazonaws.com" }, "Effect": "Allow", "Sid": "" } ] } POLICY } resource "aws_iam_role_policy" "p" { name = "tf-acc-test-awsconfig-%d" role = "${aws_iam_role.r.id}" policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Action": [ "s3:*" ], "Effect": "Allow", "Resource": [ "${aws_s3_bucket.b.arn}", "${aws_s3_bucket.b.arn}/*" ] } ] } EOF } resource "aws_s3_bucket" "b" { bucket = "tf-acc-test-awsconfig-%d" force_destroy = true } resource "aws_config_delivery_channel" "foo" { name = "tf-acc-test-awsconfig-%d" s3_bucket_name = "${aws_s3_bucket.b.bucket}" } resource "aws_config_configuration_recorder_status" "foo" { name = "${aws_config_configuration_recorder.foo.name}" is_enabled = %t depends_on = ["aws_config_delivery_channel.foo"] } `, randInt, randInt, randInt, randInt, randInt, enabled) }
mpl-2.0
MitocGroup/deep-framework
src/deep-log/lib/Driver/RumSqsDriver.js
6774
/** * Created by mgoria on 1/19/16. */ 'use strict'; import AWS from 'aws-sdk'; import {AbstractDriver} from './AbstractDriver'; import {FailedToSendSqsMessageException} from './Exception/FailedToSendSqsMessageException'; import {FailedToSendBatchSqsMessageException} from './Exception/FailedToSendBatchSqsMessageException'; import {FailedToReceiveSqsMessageException} from './Exception/FailedToReceiveSqsMessageException'; import {FailedToDeleteSqsMessagesException} from './Exception/FailedToDeleteSqsMessagesException'; import {InvalidSqsQueueUrlException} from './Exception/InvalidSqsQueueUrlException'; import {RumEventValidationException} from './Exception/RumEventValidationException'; import {EventFactory} from './RUM/EventFactory'; /** * SQS logging driver */ export class RumSqsDriver extends AbstractDriver { /** * @param {String} queueUrl * @param {Object} kernel * @param {Boolean} enabled */ constructor(queueUrl, kernel, enabled = false) { super(); this._queueUrl = queueUrl; this._kernel = kernel; this._enabled = enabled; this._messagesBatch = []; this._runningBatches = 0; this._sqs = null; } /** * @returns {Number} */ static get BATCH_SIZE() { return 10; } /** * @returns {String} */ get queueUrl() { return this._queueUrl; } /** * @returns {Object} */ get kernel() { return this._kernel; } /** * @returns {Boolean} */ get enabled() { return this._enabled; } /** * @returns {AWS.SQS} */ get sqs() { if (!this._sqs) { this._sqs = new AWS.SQS({ region: RumSqsDriver.getRegionFromSqsQueueUrl(this.queueUrl) }); } return this._sqs; } /** * @param {Object} message * @param {Function} callback */ log(message, callback) { if (!this.enabled) { callback(null, null); return; } let event = EventFactory.create(this.kernel, message); // @todo - check message size, max is 256 KB (262,144 bytes) if (!event.isValid()) { callback(new RumEventValidationException(event.getEventLevel(), event.validationError), null); return; } if (this.kernel.isBackend) { if (this._messagesBatch.length < RumSqsDriver.BATCH_SIZE) { this._messagesBatch.push(event); } if (this._messagesBatch.length === RumSqsDriver.BATCH_SIZE) { let batch = this._messagesBatch.slice(); this._messagesBatch = []; this._sendMessageBatch(batch, callback); } else { callback(null, null); } } else { this._sendMessage(event, callback); } } /** * @param {Function} callback */ flush(callback) { if (!this.enabled || (this._messagesBatch.length === 0 && this._runningBatches === 0)) { callback(null, null); return; } this._sendMessageBatch(this._messagesBatch, (error, data) => { this._messagesBatch = []; if (this._runningBatches > 0) { // wait for all batches to be pushed into SQS var intervalID = setInterval(() => { if (this._runningBatches === 0) { clearInterval(intervalID); return callback(error, data); } }, 50); } else { callback(error, data); } }); } /** * @param {AbstractEvent} event * @param {Function} callback * @private */ _sendMessage(event, callback) { let params = { MessageBody: JSON.stringify(event), QueueUrl: this.queueUrl, }; this.sqs.sendMessage(params, (error, data) => { if (error) { error = new FailedToSendSqsMessageException(params.QueueUrl, params.MessageBody, error); } callback(error, data); }); } /** * @param {Array} messages * @param {Function} callback * @private */ _sendMessageBatch(messages, callback) { if (messages.length === 0) { callback(null, null); return; } this._runningBatches++; let entries = []; messages.forEach((event, index) => { event = JSON.stringify(event); let id = `${AbstractDriver._md5(event)}-${new Date().getTime()}-${index}`; entries.push({ Id: id, MessageBody: event, }); }); var params = { QueueUrl: this.queueUrl, Entries: entries }; this.sqs.sendMessageBatch(params, (error, data) => { this._runningBatches--; if (error) { error = new FailedToSendBatchSqsMessageException(params.QueueUrl, error); } callback(error, data); }); } /** * @param {Function} callback */ receiveMessages(callback) { let params = { QueueUrl: this.queueUrl, MaxNumberOfMessages: 10, VisibilityTimeout: 20, WaitTimeSeconds: 0 }; this.sqs.receiveMessage(params, (error, data) => { if (error) { error = new FailedToReceiveSqsMessageException(params.QueueUrl, error); } callback(error, data); }); } /** * @param {Array} messages * @param {Function} callback */ deleteMessages(messages, callback) { if (messages.length === 0) { callback(null, null); return; } let params = { QueueUrl: this.queueUrl, Entries: [] }; messages.forEach((message) => { params.Entries.push({ Id: message.MessageId, ReceiptHandle: message.ReceiptHandle }); }); this.sqs.deleteMessageBatch(params, (error, data) => { if (error) { error = new FailedToDeleteSqsMessagesException(params.QueueUrl, error); } callback(error, data); }); } /** * @param {Function} callback * @param {Object[]} additionalAttributes */ getQueueAttributes(callback, additionalAttributes = []) { let defaultAttributes = [ 'ApproximateNumberOfMessages', 'ApproximateNumberOfMessagesNotVisible', 'ApproximateNumberOfMessagesDelayed' ]; let attributes = defaultAttributes.concat( additionalAttributes.filter(attr => defaultAttributes.indexOf(attr) === -1) ); let params = { QueueUrl: this.queueUrl, AttributeNames: attributes }; this.sqs.getQueueAttributes(params, callback); } /** * @param {String} queueUrl * @returns {String} */ static getRegionFromSqsQueueUrl(queueUrl) { let regionParts = queueUrl.match(/\.([^\.]+)\.amazonaws\.com\/.*/i); if (!regionParts || regionParts.length === 0) { throw new InvalidSqsQueueUrlException(queueUrl, 'Unable to extract AWS region.'); } return regionParts[1]; } /** * @returns {String} */ static get ES_LOGS_INDEX() { return 'rum'; } /** * @returns {String} */ static get ES_LOGS_TYPE() { return 'logs'; } }
mpl-2.0
heartysoft/quicksilver
MyWebAppForDeployment/App_Start/IdentityConfig.cs
1806
using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using MyWebAppForDeployment.Models; namespace MyWebAppForDeployment { // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application. public class ApplicationUserManager : UserManager<ApplicationUser> { public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store) { } public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) { var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>())); // Configure validation logic for usernames manager.UserValidator = new UserValidator<ApplicationUser>(manager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Configure validation logic for passwords manager.PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, }; var dataProtectionProvider = options.DataProtectionProvider; if (dataProtectionProvider != null) { manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity")); } return manager; } } }
mpl-2.0
ProfilingLabs/Usemon2
usemon-domain-java/src/test/java/org/usemon/domain/graph/GraphTest.java
1026
/** * Created 14. nov.. 2007 17.25.07 by Steinar Overbeck Cook */ package org.usemon.domain.graph; import org.junit.Test; import static org.junit.Assert.*; /** * @author t547116 (Steinar Overbeck Cook) * */ public class GraphTest { @Test public void testSampleGraph() { Graph g = new Graph(); Long l = genUid(); InstanceNode n1 = new InstanceNode("p" + l , "c" + l, "i" + l); l = genUid(); InstanceNode n2 = new InstanceNode("p" + l , "c" + l, "i" + l); l = genUid(); InstanceNode n3 = new InstanceNode("p" + l , "c" + l, "i" + l); g.addNode(n1); g.addNode(n2); g.addEdge(new Edge(n1,n2)); g.addEdge(new Edge(n2,n3)); g.addEdge(new Edge(n1,n3)); assertEquals("Nodes",3, g.getNodes().size()); assertEquals("Edges", 3, g.getEdges().size()); for (InstanceNode node : g.getNodes()) { assertNotNull("Node has no id", node.getUid()); } } /** * @return */ private long genUid() { return Math.round(1000 * Math.random()); } }
mpl-2.0
olegccc/streams-client
src/interfaces/IUpdates.ts
89
interface IUpdates { updates: IUpdate[]; streamId: string; nodeId: string; }
mpl-2.0
dtsuran/community-app
app/scripts/controllers/product/InterestRateChartController.js
2471
(function(module) { mifosX.controllers = _.extend(module, { InterestRateChartController: function(scope, routeParams, resourceFactory, location,$modal) { scope.edit = function(id){ location.path('/editinterestratechart/' + id); }; scope.productName = routeParams.productName; scope.productId = routeParams.productId; scope.productsLink = ''; scope.viewProductLink = ''; scope.productType = routeParams.productType; if ( routeParams.productType === 'fixeddepositproduct'){ scope.productsLink = 'fixeddepositproducts'; scope.viewProductLink = 'viewfixeddepositproduct'; }else if ( routeParams.productType === 'recurringdepositproduct'){ scope.productsLink = 'recurringdepositproducts'; scope.viewProductLink = 'viewrecurringdepositproduct'; } resourceFactory.interestRateChartResource.getAllInterestRateCharts({productId: routeParams.productId}, function(data) { scope.charts = data; _.each(scope.charts,function(chart){ scope.chartSlabs = chart.chartSlabs; chart.chartSlabs = _.sortBy(scope.chartSlabs, function (obj) { return obj.fromPeriod }); }); }); scope.incentives = function(index,parent){ $modal.open({ templateUrl: 'incentive.html', controller: IncentiveCtrl, resolve: { chartSlab: function () { return scope.charts[parent].chartSlabs[index]; } } }); } var IncentiveCtrl = function ($scope, $modalInstance, chartSlab) { $scope.chartSlab = chartSlab; _.each($scope.chartSlab.incentives, function (incentive) { if(!incentive.attributeValueDesc){ incentive.attributeValueDesc = incentive.attributeValue; } }); $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }; } }); mifosX.ng.application.controller('InterestRateChartController', ['$scope', '$routeParams', 'ResourceFactory','$location','$modal', mifosX.controllers.InterestRateChartController]).run(function($log) { $log.info("InterestRateChartController initialized"); }); }(mifosX.controllers || {}));
mpl-2.0
winiceo/71an.com
lab/min.js
954
// Install Minio library. // $ npm install -g minio // // Import Minio library. var Minio = require('minio') // Instantiate the minio client with the endpoint // and access keys as shown below. var minioClient = new Minio.Client({ endPoint: '71an.com', port: 4100, secure: false, accessKey: 'FDGNNW15QWK9F237VIXS', secretKey: '4wXenRDClmg3MBUxHN49YjjvwSuqEgyBY67MIxy6' }); // File that needs to be uploaded. var file = '/abc/kevio/test/ok.js' // Make a bucket called europetrip. minioClient.makeBucket('europetrip', 'us-east-1', function(err) { if (err) return console.log(err) console.log('Bucket created successfully in "us-east-1".') // Using fPutObject API upload your file to the bucket europetrip. minioClient.fPutObject('europetrip', 'ok.js', file, 'application/octet-stream', function(err, etag) { if (err) return console.log(err) console.log('File uploaded successfully.') }); });
mpl-2.0
Rubin-inc/node-talk-generator
lib/phrase/phrase.ts
1560
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /// <reference path="../../typings/node/node.d.ts" /> /// <reference path="../../typings/lodash/lodash.d.ts" /> // フレーズの実装 import _ = require('lodash'); import basicPhrase = require('./basicPhrase'); import args = require('./args'); /** * 通常のフレーズを表すクラス */ export class Phrase extends basicPhrase.BasicPhrase { /** * フレーズで用いるテキストの配列 */ private texts: string[] = []; public constructor(id: string) { super(id); } /** * ランダムでテキストを返す * 候補が無い場合は空文字を返す */ public getText(args: args.PhraseArguments): string { return _.sample(this.texts) || ''; } /** * フレーズで用いるテキストを追加する * @param text フレーズで用いるテキスト */ public add(text: string): Phrase { this.texts.push(text); return this; } /** * フレーズで用いるテキスト一覧をクリアする */ public clear(): Phrase { this.texts.length = 0; return this; } /** * 追加されているテキストの個数を返す */ public get length(): number { return this.texts.length; } }
mpl-2.0
eoger/tabcenter-redux
src/sidebar/lib/fuzzysort.js
24780
/* WHAT: SublimeText-like Fuzzy Search USAGE: fuzzysort.single('fs', 'Fuzzy Search') // {score: -16} fuzzysort.single('test', 'test') // {score: 0} fuzzysort.single('doesnt exist', 'target') // null fuzzysort.go('mr', ['Monitor.cpp', 'MeshRenderer.cpp']) // [{score: -18, target: "MeshRenderer.cpp"}, {score: -6009, target: "Monitor.cpp"}] fuzzysort.highlight(fuzzysort.single('fs', 'Fuzzy Search'), '<b>', '</b>') // <b>F</b>uzzy <b>S</b>earch */ // MODIFICATIONS by eoger for Tab Center Redux: // - Normalize inputs in prepareLowerCodes (remove accents/diatrics). function UMD() { function fuzzysortNew(instanceOptions) { var fuzzysort = { single: function(search, target, options) { if(!search) return null if(!isObj(search)) search = fuzzysort.getPreparedSearch(search) if(!target) return null if(!isObj(target)) target = fuzzysort.getPrepared(target) var allowTypo = options && options.allowTypo!==undefined ? options.allowTypo : instanceOptions && instanceOptions.allowTypo!==undefined ? instanceOptions.allowTypo : true var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo return algorithm(search, target, search[0]) // var threshold = options && options.threshold || instanceOptions && instanceOptions.threshold || -9007199254740991 // var result = algorithm(search, target, search[0]) // if(result === null) return null // if(result.score < threshold) return null // return result }, go: function(search, targets, options) { if(!search) return noResults search = fuzzysort.prepareSearch(search) var searchLowerCode = search[0] var threshold = options && options.threshold || instanceOptions && instanceOptions.threshold || -9007199254740991 var limit = options && options.limit || instanceOptions && instanceOptions.limit || 9007199254740991 var allowTypo = options && options.allowTypo!==undefined ? options.allowTypo : instanceOptions && instanceOptions.allowTypo!==undefined ? instanceOptions.allowTypo : true var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo var resultsLen = 0; var limitedCount = 0 var targetsLen = targets.length // This code is copy/pasted 3 times for performance reasons [options.keys, options.key, no keys] // options.keys if(options && options.keys) { var scoreFn = options.scoreFn || defaultScoreFn var keys = options.keys var keysLen = keys.length for(var i = targetsLen - 1; i >= 0; --i) { var obj = targets[i] var objResults = new Array(keysLen) for (var keyI = keysLen - 1; keyI >= 0; --keyI) { var key = keys[keyI] var target = getValue(obj, key) if(!target) { objResults[keyI] = null; continue } if(!isObj(target)) target = fuzzysort.getPrepared(target) objResults[keyI] = algorithm(search, target, searchLowerCode) } objResults.obj = obj // before scoreFn so scoreFn can use it var score = scoreFn(objResults) if(score === null) continue if(score < threshold) continue objResults.score = score if(resultsLen < limit) { q.add(objResults); ++resultsLen } else { ++limitedCount if(score > q.peek().score) q.replaceTop(objResults) } } // options.key } else if(options && options.key) { var key = options.key for(var i = targetsLen - 1; i >= 0; --i) { var obj = targets[i] var target = getValue(obj, key) if(!target) continue if(!isObj(target)) target = fuzzysort.getPrepared(target) var result = algorithm(search, target, searchLowerCode) if(result === null) continue if(result.score < threshold) continue // have to clone result so duplicate targets from different obj can each reference the correct obj result = {target:result.target, _targetLowerCodes:null, _nextBeginningIndexes:null, score:result.score, indexes:result.indexes, obj:obj} // hidden if(resultsLen < limit) { q.add(result); ++resultsLen } else { ++limitedCount if(result.score > q.peek().score) q.replaceTop(result) } } // no keys } else { for(var i = targetsLen - 1; i >= 0; --i) { var target = targets[i] if(!target) continue if(!isObj(target)) target = fuzzysort.getPrepared(target) var result = algorithm(search, target, searchLowerCode) if(result === null) continue if(result.score < threshold) continue if(resultsLen < limit) { q.add(result); ++resultsLen } else { ++limitedCount if(result.score > q.peek().score) q.replaceTop(result) } } } if(resultsLen === 0) return noResults var results = new Array(resultsLen) for(var i = resultsLen - 1; i >= 0; --i) results[i] = q.poll() results.total = resultsLen + limitedCount return results }, goAsync: function(search, targets, options) { var canceled = false var p = new Promise(function(resolve, reject) { if(!search) return resolve(noResults) search = fuzzysort.prepareSearch(search) var searchLowerCode = search[0] var q = fastpriorityqueue() var iCurrent = targets.length - 1 var threshold = options && options.threshold || instanceOptions && instanceOptions.threshold || -9007199254740991 var limit = options && options.limit || instanceOptions && instanceOptions.limit || 9007199254740991 var allowTypo = options && options.allowTypo!==undefined ? options.allowTypo : instanceOptions && instanceOptions.allowTypo!==undefined ? instanceOptions.allowTypo : true var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo var resultsLen = 0; var limitedCount = 0 function step() { if(canceled) return reject('canceled') var startMs = Date.now() // This code is copy/pasted 3 times for performance reasons [options.keys, options.key, no keys] // options.keys if(options && options.keys) { var scoreFn = options.scoreFn || defaultScoreFn var keys = options.keys var keysLen = keys.length for(; iCurrent >= 0; --iCurrent) { var obj = targets[iCurrent] var objResults = new Array(keysLen) for (var keyI = keysLen - 1; keyI >= 0; --keyI) { var key = keys[keyI] var target = getValue(obj, key) if(!target) { objResults[keyI] = null; continue } if(!isObj(target)) target = fuzzysort.getPrepared(target) objResults[keyI] = algorithm(search, target, searchLowerCode) } objResults.obj = obj // before scoreFn so scoreFn can use it var score = scoreFn(objResults) if(score === null) continue if(score < threshold) continue objResults.score = score if(resultsLen < limit) { q.add(objResults); ++resultsLen } else { ++limitedCount if(score > q.peek().score) q.replaceTop(objResults) } if(iCurrent%1000/*itemsPerCheck*/ === 0) { if(Date.now() - startMs >= 10/*asyncInterval*/) { setTimeout(step) return } } } // options.key } else if(options && options.key) { var key = options.key for(; iCurrent >= 0; --iCurrent) { var obj = targets[iCurrent] var target = getValue(obj, key) if(!target) continue if(!isObj(target)) target = fuzzysort.getPrepared(target) var result = algorithm(search, target, searchLowerCode) if(result === null) continue if(result.score < threshold) continue // have to clone result so duplicate targets from different obj can each reference the correct obj result = {target:result.target, _targetLowerCodes:null, _nextBeginningIndexes:null, score:result.score, indexes:result.indexes, obj:obj} // hidden if(resultsLen < limit) { q.add(result); ++resultsLen } else { ++limitedCount if(result.score > q.peek().score) q.replaceTop(result) } if(iCurrent%1000/*itemsPerCheck*/ === 0) { if(Date.now() - startMs >= 10/*asyncInterval*/) { setTimeout(step) return } } } // no keys } else { for(; iCurrent >= 0; --iCurrent) { var target = targets[iCurrent] if(!target) continue if(!isObj(target)) target = fuzzysort.getPrepared(target) var result = algorithm(search, target, searchLowerCode) if(result === null) continue if(result.score < threshold) continue if(resultsLen < limit) { q.add(result); ++resultsLen } else { ++limitedCount if(result.score > q.peek().score) q.replaceTop(result) } if(iCurrent%1000/*itemsPerCheck*/ === 0) { if(Date.now() - startMs >= 10/*asyncInterval*/) { setTimeout(step) return } } } } if(resultsLen === 0) return resolve(noResults) var results = new Array(resultsLen) for(var i = resultsLen - 1; i >= 0; --i) results[i] = q.poll() results.total = resultsLen + limitedCount resolve(results) } step() }) p.cancel = function() { canceled = true } return p }, highlight: function(result, hOpen, hClose) { if(result === null) return null if(hOpen === undefined) hOpen = '<b>' if(hClose === undefined) hClose = '</b>' var highlighted = '' var matchesIndex = 0 var opened = false var target = result.target var targetLen = target.length var matchesBest = result.indexes for(var i = 0; i < targetLen; ++i) { var char = target[i] if(matchesBest[matchesIndex] === i) { ++matchesIndex if(!opened) { opened = true highlighted += hOpen } if(matchesIndex === matchesBest.length) { highlighted += char + hClose + target.substr(i+1) break } } else { if(opened) { opened = false highlighted += hClose } } highlighted += char } return highlighted }, prepare: function(target) { if(!target) return return {target:target, _targetLowerCodes:fuzzysort.prepareLowerCodes(target), _nextBeginningIndexes:null, score:null, indexes:null, obj:null} // hidden }, prepareSlow: function(target) { if(!target) return return {target:target, _targetLowerCodes:fuzzysort.prepareLowerCodes(target), _nextBeginningIndexes:fuzzysort.prepareNextBeginningIndexes(target), score:null, indexes:null, obj:null} // hidden }, prepareSearch: function(search) { if(!search) return return fuzzysort.prepareLowerCodes(search) }, // Below this point is only internal code // Below this point is only internal code // Below this point is only internal code // Below this point is only internal code getPrepared: function(target) { if(target.length > 999) return fuzzysort.prepare(target) // don't cache huge targets var targetPrepared = preparedCache.get(target) if(targetPrepared !== undefined) return targetPrepared targetPrepared = fuzzysort.prepare(target) preparedCache.set(target, targetPrepared) return targetPrepared }, getPreparedSearch: function(search) { if(search.length > 999) return fuzzysort.prepareSearch(search) // don't cache huge searches var searchPrepared = preparedSearchCache.get(search) if(searchPrepared !== undefined) return searchPrepared searchPrepared = fuzzysort.prepareSearch(search) preparedSearchCache.set(search, searchPrepared) return searchPrepared }, algorithm: function(searchLowerCodes, prepared, searchLowerCode) { var targetLowerCodes = prepared._targetLowerCodes var searchLen = searchLowerCodes.length var targetLen = targetLowerCodes.length var searchI = 0 // where we at var targetI = 0 // where you at var typoSimpleI = 0 var matchesSimpleLen = 0 // very basic fuzzy match; to remove non-matching targets ASAP! // walk through target. find sequential matches. // if all chars aren't found then exit for(;;) { var isMatch = searchLowerCode === targetLowerCodes[targetI] if(isMatch) { matchesSimple[matchesSimpleLen++] = targetI ++searchI; if(searchI === searchLen) break searchLowerCode = searchLowerCodes[typoSimpleI===0?searchI : (typoSimpleI===searchI?searchI+1 : (typoSimpleI===searchI-1?searchI-1 : searchI))] } ++targetI; if(targetI >= targetLen) { // Failed to find searchI // Check for typo or exit // we go as far as possible before trying to transpose // then we transpose backwards until we reach the beginning for(;;) { if(searchI <= 1) return null // not allowed to transpose first char if(typoSimpleI === 0) { // we haven't tried to transpose yet --searchI var searchLowerCodeNew = searchLowerCodes[searchI] if(searchLowerCode === searchLowerCodeNew) continue // doesn't make sense to transpose a repeat char typoSimpleI = searchI } else { if(typoSimpleI === 1) return null // reached the end of the line for transposing --typoSimpleI searchI = typoSimpleI searchLowerCode = searchLowerCodes[searchI + 1] var searchLowerCodeNew = searchLowerCodes[searchI] if(searchLowerCode === searchLowerCodeNew) continue // doesn't make sense to transpose a repeat char } matchesSimpleLen = searchI targetI = matchesSimple[matchesSimpleLen - 1] + 1 break } } } var searchI = 0 var typoStrictI = 0 var successStrict = false var matchesStrictLen = 0 var nextBeginningIndexes = prepared._nextBeginningIndexes if(nextBeginningIndexes === null) nextBeginningIndexes = prepared._nextBeginningIndexes = fuzzysort.prepareNextBeginningIndexes(prepared.target) var firstPossibleI = targetI = matchesSimple[0]===0 ? 0 : nextBeginningIndexes[matchesSimple[0]-1] // Our target string successfully matched all characters in sequence! // Let's try a more advanced and strict test to improve the score // only count it as a match if it's consecutive or a beginning character! if(targetI !== targetLen) for(;;) { if(targetI >= targetLen) { // We failed to find a good spot for this search char, go back to the previous search char and force it forward if(searchI <= 0) { // We failed to push chars forward for a better match // transpose, starting from the beginning ++typoStrictI; if(typoStrictI > searchLen-2) break if(searchLowerCodes[typoStrictI] === searchLowerCodes[typoStrictI+1]) continue // doesn't make sense to transpose a repeat char targetI = firstPossibleI continue } --searchI var lastMatch = matchesStrict[--matchesStrictLen] targetI = nextBeginningIndexes[lastMatch] } else { var isMatch = searchLowerCodes[typoStrictI===0?searchI : (typoStrictI===searchI?searchI+1 : (typoStrictI===searchI-1?searchI-1 : searchI))] === targetLowerCodes[targetI] if(isMatch) { matchesStrict[matchesStrictLen++] = targetI ++searchI; if(searchI === searchLen) { successStrict = true; break } ++targetI } else { targetI = nextBeginningIndexes[targetI] } } } { // tally up the score & keep track of matches for highlighting later if(successStrict) { var matchesBest = matchesStrict; var matchesBestLen = matchesStrictLen } else { var matchesBest = matchesSimple; var matchesBestLen = matchesSimpleLen } var score = 0 var lastTargetI = -1 for(var i = 0; i < searchLen; ++i) { var targetI = matchesBest[i] // score only goes down if they're not consecutive if(lastTargetI !== targetI - 1) score -= targetI lastTargetI = targetI } if(!successStrict) { score *= 1000 if(typoSimpleI !== 0) score += -20/*typoPenalty*/ } else { if(typoStrictI !== 0) score += -20/*typoPenalty*/ } score -= targetLen - searchLen prepared.score = score prepared.indexes = new Array(matchesBestLen); for(var i = matchesBestLen - 1; i >= 0; --i) prepared.indexes[i] = matchesBest[i] return prepared } }, algorithmNoTypo: function(searchLowerCodes, prepared, searchLowerCode) { var targetLowerCodes = prepared._targetLowerCodes var searchLen = searchLowerCodes.length var targetLen = targetLowerCodes.length var searchI = 0 // where we at var targetI = 0 // where you at var matchesSimpleLen = 0 // very basic fuzzy match; to remove non-matching targets ASAP! // walk through target. find sequential matches. // if all chars aren't found then exit for(;;) { var isMatch = searchLowerCode === targetLowerCodes[targetI] if(isMatch) { matchesSimple[matchesSimpleLen++] = targetI ++searchI; if(searchI === searchLen) break searchLowerCode = searchLowerCodes[searchI] } ++targetI; if(targetI >= targetLen) return null // Failed to find searchI } var searchI = 0 var successStrict = false var matchesStrictLen = 0 var nextBeginningIndexes = prepared._nextBeginningIndexes if(nextBeginningIndexes === null) nextBeginningIndexes = prepared._nextBeginningIndexes = fuzzysort.prepareNextBeginningIndexes(prepared.target) var firstPossibleI = targetI = matchesSimple[0]===0 ? 0 : nextBeginningIndexes[matchesSimple[0]-1] // Our target string successfully matched all characters in sequence! // Let's try a more advanced and strict test to improve the score // only count it as a match if it's consecutive or a beginning character! if(targetI !== targetLen) for(;;) { if(targetI >= targetLen) { // We failed to find a good spot for this search char, go back to the previous search char and force it forward if(searchI <= 0) break // We failed to push chars forward for a better match --searchI var lastMatch = matchesStrict[--matchesStrictLen] targetI = nextBeginningIndexes[lastMatch] } else { var isMatch = searchLowerCodes[searchI] === targetLowerCodes[targetI] if(isMatch) { matchesStrict[matchesStrictLen++] = targetI ++searchI; if(searchI === searchLen) { successStrict = true; break } ++targetI } else { targetI = nextBeginningIndexes[targetI] } } } { // tally up the score & keep track of matches for highlighting later if(successStrict) { var matchesBest = matchesStrict; var matchesBestLen = matchesStrictLen } else { var matchesBest = matchesSimple; var matchesBestLen = matchesSimpleLen } var score = 0 var lastTargetI = -1 for(var i = 0; i < searchLen; ++i) { var targetI = matchesBest[i] // score only goes down if they're not consecutive if(lastTargetI !== targetI - 1) score -= targetI lastTargetI = targetI } if(!successStrict) score *= 1000 score -= targetLen - searchLen prepared.score = score prepared.indexes = new Array(matchesBestLen); for(var i = matchesBestLen - 1; i >= 0; --i) prepared.indexes[i] = matchesBest[i] return prepared } }, prepareLowerCodes: function(str) { var strLen = str.length var lowerCodes = [] // new Array(strLen) sparse array is too slow var lower = str.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, ""); for(var i = 0; i < strLen; ++i) lowerCodes[i] = lower.charCodeAt(i) return lowerCodes }, prepareBeginningIndexes: function(target) { var targetLen = target.length var beginningIndexes = []; var beginningIndexesLen = 0 var wasUpper = false var wasAlphanum = false for(var i = 0; i < targetLen; ++i) { var targetCode = target.charCodeAt(i) var isUpper = targetCode>=65&&targetCode<=90 var isAlphanum = isUpper || targetCode>=97&&targetCode<=122 || targetCode>=48&&targetCode<=57 var isBeginning = isUpper && !wasUpper || !wasAlphanum || !isAlphanum wasUpper = isUpper wasAlphanum = isAlphanum if(isBeginning) beginningIndexes[beginningIndexesLen++] = i } return beginningIndexes }, prepareNextBeginningIndexes: function(target) { var targetLen = target.length var beginningIndexes = fuzzysort.prepareBeginningIndexes(target) var nextBeginningIndexes = [] // new Array(targetLen) sparse array is too slow var lastIsBeginning = beginningIndexes[0] var lastIsBeginningI = 0 for(var i = 0; i < targetLen; ++i) { if(lastIsBeginning > i) { nextBeginningIndexes[i] = lastIsBeginning } else { lastIsBeginning = beginningIndexes[++lastIsBeginningI] nextBeginningIndexes[i] = lastIsBeginning===undefined ? targetLen : lastIsBeginning } } return nextBeginningIndexes }, cleanup: cleanup, new: fuzzysortNew, } return fuzzysort } // fuzzysortNew // var MAX_INT = Number.MAX_SAFE_INTEGER // var MIN_INT = Number.MIN_VALUE var preparedCache = new Map() var preparedSearchCache = new Map() var noResults = []; noResults.total = 0 var matchesSimple = []; var matchesStrict = [] function cleanup() { preparedCache.clear(); preparedSearchCache.clear(); matchesSimple = []; matchesStrict = [] } function defaultScoreFn(a) { var max = -9007199254740991 for (var i = a.length - 1; i >= 0; --i) { var result = a[i]; if(result === null) continue var score = result.score if(score > max) max = score } if(max === -9007199254740991) return null return max } // prop = 'key' 2.5ms optimized for this case, seems to be about as fast as direct obj[prop] // prop = 'key1.key2' 10ms // prop = ['key1', 'key2'] 27ms function getValue(obj, prop) { var tmp = obj[prop]; if(tmp !== undefined) return tmp var segs = prop if(!Array.isArray(prop)) segs = prop.split('.') var len = segs.length var i = -1 while (obj && (++i < len)) obj = obj[segs[i]] return obj } function isObj(x) { return typeof x === 'object' } // faster as a function // Hacked version of https://github.com/lemire/FastPriorityQueue.js var fastpriorityqueue=function(){var r=[],o=0,e={};function n(){for(var e=0,n=r[e],c=1;c<o;){var f=c+1;e=c,f<o&&r[f].score<r[c].score&&(e=f),r[e-1>>1]=r[e],c=1+(e<<1)}for(var a=e-1>>1;e>0&&n.score<r[a].score;a=(e=a)-1>>1)r[e]=r[a];r[e]=n}return e.add=function(e){var n=o;r[o++]=e;for(var c=n-1>>1;n>0&&e.score<r[c].score;c=(n=c)-1>>1)r[n]=r[c];r[n]=e},e.poll=function(){if(0!==o){var e=r[0];return r[0]=r[--o],n(),e}},e.peek=function(e){if(0!==o)return r[0]},e.replaceTop=function(o){r[0]=o,n()},e}; var q = fastpriorityqueue() // reuse this, except for async, it needs to make its own return fuzzysortNew() } export default UMD(); // TODO: (performance) wasm version!? // TODO: (performance) layout memory in an optimal way to go fast by avoiding cache misses // TODO: (performance) preparedCache is a memory leak // TODO: (like sublime) backslash === forwardslash // TODO: (performance) i have no idea how well optizmied the allowing typos algorithm is
mpl-2.0
k-joseph/openmrs-module-openhmis.commons
api/src/main/java/org/openmrs/module/openhmis/commons/api/f/Func1.java
855
/* * The contents of this file are subject to the OpenMRS Public 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://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module.openhmis.commons.api.f; /** * Represents a function with one parameter and a return value. * @param <TParm1> The parameter class. * @param <TResult> The return value class. */ public interface Func1<TParm1, TResult> { TResult apply(TParm1 parameter1); }
mpl-2.0
Ricard/AppverseProject
app/bower_components/ag-grid/docs/angular-grid-column-api/columnStateExample.js
2607
var columnDefs = [ {headerName: "Athlete", field: "athlete", width: 150}, {headerName: "Age", field: "age", width: 90}, {headerName: "Country", field: "country", width: 120}, {headerName: "Year", field: "year", width: 90}, {headerName: "Date", field: "date", width: 110}, {headerName: "Sport", field: "sport", width: 110}, {headerName: "Gold", field: "gold", width: 100, hide: true}, {headerName: "Silver", field: "silver", width: 100, hide: true}, {headerName: "Bronze", field: "bronze", width: 100, hide: true}, {headerName: "Total", field: "total", width: 100} ]; var gridOptions = { debug: true, columnDefs: columnDefs, rowData: null, enableSorting: true, enableColResize: true, showToolPanel: true, onGridReady: function() { gridOptions.api.addGlobalListener(function(type, event) { if (type.indexOf('column') >= 0) { console.log('Got column event: ' + event); } }); } }; var savedState; function printState() { var state = gridOptions.columnApi.getState(); console.log(state); } function saveState() { savedState = gridOptions.columnApi.getState(); console.log('column state saved'); } function restoreState() { gridOptions.columnApi.setState(savedState); console.log('column state restored'); } function resetState() { gridOptions.columnApi.resetState(); } function showAthlete(show) { gridOptions.columnApi.setColumnVisible('athlete', show); } function showMedals(show) { gridOptions.columnApi.setColumnsVisible(['gold','silver','bronze'], show); } function pinAthlete(pin) { gridOptions.columnApi.setColumnPinned('athlete', pin); } function pinAge(pin) { gridOptions.columnApi.setColumnPinned('age', pin); } // setup the grid after the page has finished loading document.addEventListener('DOMContentLoaded', function() { var gridDiv = document.querySelector('#myGrid'); new agGrid.Grid(gridDiv, gridOptions); // do http request to get our sample data - not using any framework to keep the example self contained. // you will probably use a framework like JQuery, Angular or something else to do your HTTP calls. var httpRequest = new XMLHttpRequest(); httpRequest.open('GET', '../olympicWinners.json'); httpRequest.send(); httpRequest.onreadystatechange = function() { if (httpRequest.readyState == 4 && httpRequest.status == 200) { var httpResult = JSON.parse(httpRequest.responseText); gridOptions.api.setRowData(httpResult); } }; });
mpl-2.0
finjin/finjin-engine
cpp/library/src/finjin/engine/internal/sound/avaudioengine/AVAudioEngineSoundListener.hpp
2245
//Copyright (c) 2017 Finjin // //This file is part of Finjin Engine (finjin-engine). // //Finjin Engine 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. // //This Source Code Form is subject to the terms of the Mozilla Public //License, v. 2.0. If a copy of the MPL was not distributed with this //file, You can obtain one at http://mozilla.org/MPL/2.0/. #pragma once //Includes---------------------------------------------------------------------- #include "finjin/common/Angle.hpp" #include "finjin/common/Math.hpp" //Types------------------------------------------------------------------------- namespace Finjin { namespace Engine { using namespace Finjin::Common; class AVAudioEngineSoundContextImpl; //Manages access to the device context's one and only listener. Many sound listeners can be created, but only one can be Select()ed at a time. class AVAudioEngineSoundListener { public: AVAudioEngineSoundListener(); ~AVAudioEngineSoundListener(); void Create(AVAudioEngineSoundContextImpl* context); void SetDefaults(); void MakeDirectional(); void MakeOmnidirectional(); void Set ( const MathVector3& position, const MathVector3& velocity, const MathVector3& direction, const MathVector3& up ); void GetOrientation(MathVector3& direction, MathVector3& up) const; void SetOrientation(const MathVector3& direction, const MathVector3& up); void GetPosition(MathVector3& value) const; void SetPosition(const MathVector3& value); void GetVelocity(MathVector3& value) const; void SetVelocity(const MathVector3& value); void Commit(bool force = false); //AVAudioEngine-related methods-------------- void GetConeAngle(Angle& inner, Angle& outer) const; void SetConeAngle(Angle inner, Angle outer); void GetConeVolume(float& inner, float& outer) const; void SetConeVolume(float inner, float outer); private: struct Impl; Impl* impl; }; } }
mpl-2.0
tuchida/rhino
src/org/mozilla/javascript/JavaAdapter.java
47402
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.javascript; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import org.mozilla.classfile.ByteCode; import org.mozilla.classfile.ClassFileWriter; public final class JavaAdapter implements IdFunctionCall { /** * Provides a key with which to distinguish previously generated * adapter classes stored in a hash table. */ static class JavaAdapterSignature { Class<?> superClass; Class<?>[] interfaces; ObjToIntMap names; JavaAdapterSignature(Class<?> superClass, Class<?>[] interfaces, ObjToIntMap names) { this.superClass = superClass; this.interfaces = interfaces; this.names = names; } @Override public boolean equals(Object obj) { if (!(obj instanceof JavaAdapterSignature)) return false; JavaAdapterSignature sig = (JavaAdapterSignature) obj; if (superClass != sig.superClass) return false; if (interfaces != sig.interfaces) { if (interfaces.length != sig.interfaces.length) return false; for (int i=0; i < interfaces.length; i++) if (interfaces[i] != sig.interfaces[i]) return false; } if (names.size() != sig.names.size()) return false; ObjToIntMap.Iterator iter = new ObjToIntMap.Iterator(names); for (iter.start(); !iter.done(); iter.next()) { String name = (String)iter.getKey(); int arity = iter.getValue(); if (arity != sig.names.get(name, arity + 1)) return false; } return true; } @Override public int hashCode() { return (superClass.hashCode() + Arrays.hashCode(interfaces)) ^ names.size(); } } public static void init(Context cx, Scriptable scope, boolean sealed) { JavaAdapter obj = new JavaAdapter(); IdFunctionObject ctor = new IdFunctionObject(obj, FTAG, Id_JavaAdapter, "JavaAdapter", 1, scope); ctor.markAsConstructor(null); if (sealed) { ctor.sealObject(); } ctor.exportAsScopeProperty(); } @Override public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (f.hasTag(FTAG)) { if (f.methodId() == Id_JavaAdapter) { return js_createAdapter(cx, scope, args); } } throw f.unknown(); } public static Object convertResult(Object result, Class<?> c) { if (result == Undefined.instance && (c != ScriptRuntime.ObjectClass && c != ScriptRuntime.StringClass)) { // Avoid an error for an undefined value; return null instead. return null; } return Context.jsToJava(result, c); } public static Scriptable createAdapterWrapper(Scriptable obj, Object adapter) { Scriptable scope = ScriptableObject.getTopLevelScope(obj); NativeJavaObject res = new NativeJavaObject(scope, adapter, null, true); res.setPrototype(obj); return res; } public static Object getAdapterSelf(Class<?> adapterClass, Object adapter) throws NoSuchFieldException, IllegalAccessException { Field self = adapterClass.getDeclaredField("self"); return self.get(adapter); } static Object js_createAdapter(Context cx, Scriptable scope, Object[] args) { int N = args.length; if (N == 0) { throw ScriptRuntime.typeErrorById("msg.adapter.zero.args"); } // Expected arguments: // Any number of NativeJavaClass objects representing the super-class // and/or interfaces to implement, followed by one NativeObject providing // the implementation, followed by any number of arguments to pass on // to the (super-class) constructor. int classCount; for (classCount = 0; classCount < N - 1; classCount++) { Object arg = args[classCount]; // We explicitly test for NativeObject here since checking for // instanceof ScriptableObject or !(instanceof NativeJavaClass) // would fail for a Java class that isn't found in the class path // as NativeJavaPackage extends ScriptableObject. if (arg instanceof NativeObject) { break; } if (!(arg instanceof NativeJavaClass)) { throw ScriptRuntime.typeErrorById("msg.not.java.class.arg", String.valueOf(classCount), ScriptRuntime.toString(arg)); } } Class<?> superClass = null; Class<?>[] intfs = new Class[classCount]; int interfaceCount = 0; for (int i = 0; i < classCount; ++i) { Class<?> c = ((NativeJavaClass) args[i]).getClassObject(); if (!c.isInterface()) { if (superClass != null) { throw ScriptRuntime.typeErrorById("msg.only.one.super", superClass.getName(), c.getName()); } superClass = c; } else { intfs[interfaceCount++] = c; } } if (superClass == null) { superClass = ScriptRuntime.ObjectClass; } Class<?>[] interfaces = new Class[interfaceCount]; System.arraycopy(intfs, 0, interfaces, 0, interfaceCount); // next argument is implementation, must be scriptable Scriptable obj = ScriptableObject.ensureScriptable(args[classCount]); Class<?> adapterClass = getAdapterClass(scope, superClass, interfaces, obj); Object adapter; int argsCount = N - classCount - 1; try { if (argsCount > 0) { // Arguments contain parameters for super-class constructor. // We use the generic Java method lookup logic to find and // invoke the right constructor. Object[] ctorArgs = new Object[argsCount + 2]; ctorArgs[0] = obj; ctorArgs[1] = cx.getFactory(); System.arraycopy(args, classCount + 1, ctorArgs, 2, argsCount); // TODO: cache class wrapper? NativeJavaClass classWrapper = new NativeJavaClass(scope, adapterClass, true); NativeJavaMethod ctors = classWrapper.members.ctors; int index = ctors.findCachedFunction(cx, ctorArgs); if (index < 0) { String sig = NativeJavaMethod.scriptSignature(args); throw Context.reportRuntimeErrorById( "msg.no.java.ctor", adapterClass.getName(), sig); } // Found the constructor, so try invoking it. adapter = NativeJavaClass.constructInternal(ctorArgs, ctors.methods[index]); } else { Class<?>[] ctorParms = { ScriptRuntime.ScriptableClass, ScriptRuntime.ContextFactoryClass }; Object[] ctorArgs = { obj, cx.getFactory() }; adapter = adapterClass.getConstructor(ctorParms).newInstance(ctorArgs); } Object self = getAdapterSelf(adapterClass, adapter); // Return unwrapped JavaAdapter if it implements Scriptable if (self instanceof Wrapper) { Object unwrapped = ((Wrapper) self).unwrap(); if (unwrapped instanceof Scriptable) { if (unwrapped instanceof ScriptableObject) { ScriptRuntime.setObjectProtoAndParent( (ScriptableObject)unwrapped, scope); } return unwrapped; } } return self; } catch (Exception ex) { throw Context.throwAsScriptRuntimeEx(ex); } } // Needed by NativeJavaObject serializer public static void writeAdapterObject(Object javaObject, ObjectOutputStream out) throws IOException { Class<?> cl = javaObject.getClass(); out.writeObject(cl.getSuperclass().getName()); Class<?>[] interfaces = cl.getInterfaces(); String[] interfaceNames = new String[interfaces.length]; for (int i=0; i < interfaces.length; i++) interfaceNames[i] = interfaces[i].getName(); out.writeObject(interfaceNames); try { Object delegee = cl.getField("delegee").get(javaObject); out.writeObject(delegee); return; } catch (IllegalAccessException e) { } catch (NoSuchFieldException e) { } throw new IOException(); } // Needed by NativeJavaObject de-serializer public static Object readAdapterObject(Scriptable self, ObjectInputStream in) throws IOException, ClassNotFoundException { ContextFactory factory; Context cx = Context.getCurrentContext(); if (cx != null) { factory = cx.getFactory(); } else { factory = null; } Class<?> superClass = Class.forName((String)in.readObject()); String[] interfaceNames = (String[])in.readObject(); Class<?>[] interfaces = new Class[interfaceNames.length]; for (int i=0; i < interfaceNames.length; i++) interfaces[i] = Class.forName(interfaceNames[i]); Scriptable delegee = (Scriptable)in.readObject(); Class<?> adapterClass = getAdapterClass(self, superClass, interfaces, delegee); Class<?>[] ctorParms = { ScriptRuntime.ContextFactoryClass, ScriptRuntime.ScriptableClass, ScriptRuntime.ScriptableClass }; Object[] ctorArgs = { factory, delegee, self }; try { return adapterClass.getConstructor(ctorParms).newInstance(ctorArgs); } catch(InstantiationException e) { } catch(IllegalAccessException e) { } catch(InvocationTargetException e) { } catch(NoSuchMethodException e) { } throw new ClassNotFoundException("adapter"); } private static ObjToIntMap getObjectFunctionNames(Scriptable obj) { Object[] ids = ScriptableObject.getPropertyIds(obj); ObjToIntMap map = new ObjToIntMap(ids.length); for (int i = 0; i != ids.length; ++i) { if (!(ids[i] instanceof String)) continue; String id = (String) ids[i]; Object value = ScriptableObject.getProperty(obj, id); if (value instanceof Function) { Function f = (Function)value; int length = ScriptRuntime.toInt32( ScriptableObject.getProperty(f, "length")); if (length < 0) { length = 0; } map.put(id, length); } } return map; } private static Class<?> getAdapterClass(Scriptable scope, Class<?> superClass, Class<?>[] interfaces, Scriptable obj) { ClassCache cache = ClassCache.get(scope); Map<JavaAdapterSignature,Class<?>> generated = cache.getInterfaceAdapterCacheMap(); ObjToIntMap names = getObjectFunctionNames(obj); JavaAdapterSignature sig; sig = new JavaAdapterSignature(superClass, interfaces, names); Class<?> adapterClass = generated.get(sig); if (adapterClass == null) { String adapterName = "adapter" + cache.newClassSerialNumber(); byte[] code = createAdapterCode(names, adapterName, superClass, interfaces, null); adapterClass = loadAdapterClass(adapterName, code); if (cache.isCachingEnabled()) { generated.put(sig, adapterClass); } } return adapterClass; } public static byte[] createAdapterCode(ObjToIntMap functionNames, String adapterName, Class<?> superClass, Class<?>[] interfaces, String scriptClassName) { ClassFileWriter cfw = new ClassFileWriter(adapterName, superClass.getName(), "<adapter>"); cfw.addField("factory", "Lorg/mozilla/javascript/ContextFactory;", (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); cfw.addField("delegee", "Lorg/mozilla/javascript/Scriptable;", (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); cfw.addField("self", "Lorg/mozilla/javascript/Scriptable;", (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); int interfacesCount = interfaces == null ? 0 : interfaces.length; for (int i=0; i < interfacesCount; i++) { if (interfaces[i] != null) cfw.addInterface(interfaces[i].getName()); } String superName = superClass.getName().replace('.', '/'); Constructor<?>[] ctors = superClass.getDeclaredConstructors(); for (Constructor<?> ctor : ctors) { int mod = ctor.getModifiers(); if (Modifier.isPublic(mod) || Modifier.isProtected(mod)) { generateCtor(cfw, adapterName, superName, ctor); } } generateSerialCtor(cfw, adapterName, superName); if (scriptClassName != null) { generateEmptyCtor(cfw, adapterName, superName, scriptClassName); } ObjToIntMap generatedOverrides = new ObjToIntMap(); ObjToIntMap generatedMethods = new ObjToIntMap(); // generate methods to satisfy all specified interfaces. for (int i = 0; i < interfacesCount; i++) { Method[] methods = interfaces[i].getMethods(); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int mods = method.getModifiers(); if (Modifier.isStatic(mods) || Modifier.isFinal(mods) || method.isDefault()) { continue; } String methodName = method.getName(); Class<?>[] argTypes = method.getParameterTypes(); if (!functionNames.has(methodName)) { try { superClass.getMethod(methodName, argTypes); // The class we're extending implements this method and // the JavaScript object doesn't have an override. See // bug 61226. continue; } catch (NoSuchMethodException e) { // Not implemented by superclass; fall through } } // make sure to generate only one instance of a particular // method/signature. String methodSignature = getMethodSignature(method, argTypes); String methodKey = methodName + methodSignature; if (! generatedOverrides.has(methodKey)) { generateMethod(cfw, adapterName, methodName, argTypes, method.getReturnType(), true); generatedOverrides.put(methodKey, 0); generatedMethods.put(methodName, 0); } } } // Now, go through the superclass's methods, checking for abstract // methods or additional methods to override. // generate any additional overrides that the object might contain. Method[] methods = getOverridableMethods(superClass); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int mods = method.getModifiers(); // if a method is marked abstract, must implement it or the // resulting class won't be instantiable. otherwise, if the object // has a property of the same name, then an override is intended. boolean isAbstractMethod = Modifier.isAbstract(mods); String methodName = method.getName(); if (isAbstractMethod || functionNames.has(methodName)) { // make sure to generate only one instance of a particular // method/signature. Class<?>[] argTypes = method.getParameterTypes(); String methodSignature = getMethodSignature(method, argTypes); String methodKey = methodName + methodSignature; if (! generatedOverrides.has(methodKey)) { generateMethod(cfw, adapterName, methodName, argTypes, method.getReturnType(), true); generatedOverrides.put(methodKey, 0); generatedMethods.put(methodName, 0); // if a method was overridden, generate a "super$method" // which lets the delegate call the superclass' version. if (!isAbstractMethod) { generateSuper(cfw, adapterName, superName, methodName, methodSignature, argTypes, method.getReturnType()); } } } } // Generate Java methods for remaining properties that are not // overrides. ObjToIntMap.Iterator iter = new ObjToIntMap.Iterator(functionNames); for (iter.start(); !iter.done(); iter.next()) { String functionName = (String)iter.getKey(); if (generatedMethods.has(functionName)) continue; int length = iter.getValue(); Class<?>[] parms = new Class[length]; for (int k=0; k < length; k++) parms[k] = ScriptRuntime.ObjectClass; generateMethod(cfw, adapterName, functionName, parms, ScriptRuntime.ObjectClass, false); } return cfw.toByteArray(); } static Method[] getOverridableMethods(Class<?> clazz) { ArrayList<Method> list = new ArrayList<Method>(); HashSet<String> skip = new HashSet<String>(); // Check superclasses before interfaces so we always choose // implemented methods over abstract ones, even if a subclass // re-implements an interface already implemented in a superclass // (e.g. java.util.ArrayList) for (Class<?> c = clazz; c != null; c = c.getSuperclass()) { appendOverridableMethods(c, list, skip); } for (Class<?> c = clazz; c != null; c = c.getSuperclass()) { for (Class<?> intf: c.getInterfaces()) appendOverridableMethods(intf, list, skip); } return list.toArray(new Method[list.size()]); } private static void appendOverridableMethods(Class<?> c, ArrayList<Method> list, HashSet<String> skip) { Method[] methods=c.isInterface() ? c.getMethods() : c.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { String methodKey = methods[i].getName() + getMethodSignature(methods[i], methods[i].getParameterTypes()); if (skip.contains(methodKey)) continue; // skip this method int mods = methods[i].getModifiers(); if (Modifier.isStatic(mods)) continue; if (Modifier.isFinal(mods)) { // Make sure we don't add a final method to the list // of overridable methods. skip.add(methodKey); continue; } if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) { list.add(methods[i]); skip.add(methodKey); } } } static Class<?> loadAdapterClass(String className, byte[] classBytes) { Object staticDomain; Class<?> domainClass = SecurityController.getStaticSecurityDomainClass(); if(domainClass == CodeSource.class || domainClass == ProtectionDomain.class) { // use the calling script's security domain if available ProtectionDomain protectionDomain = SecurityUtilities.getScriptProtectionDomain(); if (protectionDomain == null) { protectionDomain = JavaAdapter.class.getProtectionDomain(); } if(domainClass == CodeSource.class) { staticDomain = protectionDomain == null ? null : protectionDomain.getCodeSource(); } else { staticDomain = protectionDomain; } } else { staticDomain = null; } GeneratedClassLoader loader = SecurityController.createLoader(null, staticDomain); Class<?> result = loader.defineClass(className, classBytes); loader.linkClass(result); return result; } public static Function getFunction(Scriptable obj, String functionName) { Object x = ScriptableObject.getProperty(obj, functionName); if (x == Scriptable.NOT_FOUND) { // This method used to swallow the exception from calling // an undefined method. People have come to depend on this // somewhat dubious behavior. It allows people to avoid // implementing listener methods that they don't care about, // for instance. return null; } if (!(x instanceof Function)) throw ScriptRuntime.notFunctionError(x, functionName); return (Function)x; } /** * Utility method which dynamically binds a Context to the current thread, * if none already exists. */ public static Object callMethod(ContextFactory factory, final Scriptable thisObj, final Function f, final Object[] args, final long argsToWrap) { if (f == null) { // See comments in getFunction return null; } if (factory == null) { factory = ContextFactory.getGlobal(); } final Scriptable scope = f.getParentScope(); if (argsToWrap == 0) { return Context.call(factory, f, scope, thisObj, args); } Context cx = Context.getCurrentContext(); if (cx != null) { return doCall(cx, scope, thisObj, f, args, argsToWrap); } return factory.call(cx2 -> doCall(cx2, scope, thisObj, f, args, argsToWrap)); } private static Object doCall(Context cx, Scriptable scope, Scriptable thisObj, Function f, Object[] args, long argsToWrap) { // Wrap the rest of objects for (int i = 0; i != args.length; ++i) { if (0 != (argsToWrap & (1 << i))) { Object arg = args[i]; if (!(arg instanceof Scriptable)) { args[i] = cx.getWrapFactory().wrap(cx, scope, arg, null); } } } return f.call(cx, scope, thisObj, args); } public static Scriptable runScript(final Script script) { return ContextFactory.getGlobal().call(cx -> { ScriptableObject global = ScriptRuntime.getGlobal(cx); script.exec(cx, global); return global; }); } private static void generateCtor(ClassFileWriter cfw, String adapterName, String superName, Constructor<?> superCtor) { short locals = 3; // this + factory + delegee Class<?>[] parameters = superCtor.getParameterTypes(); // Note that we swapped arguments in app-facing constructors to avoid // conflicting signatures with serial constructor defined below. if (parameters.length == 0) { cfw.startMethod("<init>", "(Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/ContextFactory;)V", ClassFileWriter.ACC_PUBLIC); // Invoke base class constructor cfw.add(ByteCode.ALOAD_0); // this cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, "<init>", "()V"); } else { StringBuilder sig = new StringBuilder( "(Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/ContextFactory;"); int marker = sig.length(); // lets us reuse buffer for super signature for (Class<?> c : parameters) { appendTypeString(sig, c); } sig.append(")V"); cfw.startMethod("<init>", sig.toString(), ClassFileWriter.ACC_PUBLIC); // Invoke base class constructor cfw.add(ByteCode.ALOAD_0); // this short paramOffset = 3; for (Class<?> parameter : parameters) { paramOffset += generatePushParam(cfw, paramOffset, parameter); } locals = paramOffset; sig.delete(1, marker); cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, "<init>", sig.toString()); } // Save parameter in instance variable "delegee" cfw.add(ByteCode.ALOAD_0); // this cfw.add(ByteCode.ALOAD_1); // first arg: Scriptable delegee cfw.add(ByteCode.PUTFIELD, adapterName, "delegee", "Lorg/mozilla/javascript/Scriptable;"); // Save parameter in instance variable "factory" cfw.add(ByteCode.ALOAD_0); // this cfw.add(ByteCode.ALOAD_2); // second arg: ContextFactory instance cfw.add(ByteCode.PUTFIELD, adapterName, "factory", "Lorg/mozilla/javascript/ContextFactory;"); cfw.add(ByteCode.ALOAD_0); // this for the following PUTFIELD for self // create a wrapper object to be used as "this" in method calls cfw.add(ByteCode.ALOAD_1); // the Scriptable delegee cfw.add(ByteCode.ALOAD_0); // this cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/JavaAdapter", "createAdapterWrapper", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/Object;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.PUTFIELD, adapterName, "self", "Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.RETURN); cfw.stopMethod(locals); } private static void generateSerialCtor(ClassFileWriter cfw, String adapterName, String superName) { cfw.startMethod("<init>", "(Lorg/mozilla/javascript/ContextFactory;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;" +")V", ClassFileWriter.ACC_PUBLIC); // Invoke base class constructor cfw.add(ByteCode.ALOAD_0); // this cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, "<init>", "()V"); // Save parameter in instance variable "factory" cfw.add(ByteCode.ALOAD_0); // this cfw.add(ByteCode.ALOAD_1); // first arg: ContextFactory instance cfw.add(ByteCode.PUTFIELD, adapterName, "factory", "Lorg/mozilla/javascript/ContextFactory;"); // Save parameter in instance variable "delegee" cfw.add(ByteCode.ALOAD_0); // this cfw.add(ByteCode.ALOAD_2); // second arg: Scriptable delegee cfw.add(ByteCode.PUTFIELD, adapterName, "delegee", "Lorg/mozilla/javascript/Scriptable;"); // save self cfw.add(ByteCode.ALOAD_0); // this cfw.add(ByteCode.ALOAD_3); // third arg: Scriptable self cfw.add(ByteCode.PUTFIELD, adapterName, "self", "Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.RETURN); cfw.stopMethod((short)4); // 4: this + factory + delegee + self } private static void generateEmptyCtor(ClassFileWriter cfw, String adapterName, String superName, String scriptClassName) { cfw.startMethod("<init>", "()V", ClassFileWriter.ACC_PUBLIC); // Invoke base class constructor cfw.add(ByteCode.ALOAD_0); // this cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, "<init>", "()V"); // Set factory to null to use current global when necessary cfw.add(ByteCode.ALOAD_0); cfw.add(ByteCode.ACONST_NULL); cfw.add(ByteCode.PUTFIELD, adapterName, "factory", "Lorg/mozilla/javascript/ContextFactory;"); // Load script class cfw.add(ByteCode.NEW, scriptClassName); cfw.add(ByteCode.DUP); cfw.addInvoke(ByteCode.INVOKESPECIAL, scriptClassName, "<init>", "()V"); // Run script and save resulting scope cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/JavaAdapter", "runScript", "(Lorg/mozilla/javascript/Script;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.ASTORE_1); // Save the Scriptable in instance variable "delegee" cfw.add(ByteCode.ALOAD_0); // this cfw.add(ByteCode.ALOAD_1); // the Scriptable cfw.add(ByteCode.PUTFIELD, adapterName, "delegee", "Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.ALOAD_0); // this for the following PUTFIELD for self // create a wrapper object to be used as "this" in method calls cfw.add(ByteCode.ALOAD_1); // the Scriptable cfw.add(ByteCode.ALOAD_0); // this cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/JavaAdapter", "createAdapterWrapper", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/Object;" +")Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.PUTFIELD, adapterName, "self", "Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.RETURN); cfw.stopMethod((short)2); // this + delegee } /** * Generates code to wrap Java arguments into Object[]. * Non-primitive Java types are left as-is pending conversion * in the helper method. Leaves the array object on the top of the stack. */ static void generatePushWrappedArgs(ClassFileWriter cfw, Class<?>[] argTypes, int arrayLength) { // push arguments cfw.addPush(arrayLength); cfw.add(ByteCode.ANEWARRAY, "java/lang/Object"); int paramOffset = 1; for (int i = 0; i != argTypes.length; ++i) { cfw.add(ByteCode.DUP); // duplicate array reference cfw.addPush(i); paramOffset += generateWrapArg(cfw, paramOffset, argTypes[i]); cfw.add(ByteCode.AASTORE); } } /** * Generates code to wrap Java argument into Object. * Non-primitive Java types are left unconverted pending conversion * in the helper method. Leaves the wrapper object on the top of the stack. */ private static int generateWrapArg(ClassFileWriter cfw, int paramOffset, Class<?> argType) { int size = 1; if (!argType.isPrimitive()) { cfw.add(ByteCode.ALOAD, paramOffset); } else if (argType == Boolean.TYPE) { // wrap boolean values with java.lang.Boolean. cfw.add(ByteCode.NEW, "java/lang/Boolean"); cfw.add(ByteCode.DUP); cfw.add(ByteCode.ILOAD, paramOffset); cfw.addInvoke(ByteCode.INVOKESPECIAL, "java/lang/Boolean", "<init>", "(Z)V"); } else if (argType == Character.TYPE) { // Create a string of length 1 using the character parameter. cfw.add(ByteCode.ILOAD, paramOffset); cfw.addInvoke(ByteCode.INVOKESTATIC, "java/lang/String", "valueOf", "(C)Ljava/lang/String;"); } else { // convert all numeric values to java.lang.Double. cfw.add(ByteCode.NEW, "java/lang/Double"); cfw.add(ByteCode.DUP); String typeName = argType.getName(); switch (typeName.charAt(0)) { case 'b': case 's': case 'i': // load an int value, convert to double. cfw.add(ByteCode.ILOAD, paramOffset); cfw.add(ByteCode.I2D); break; case 'l': // load a long, convert to double. cfw.add(ByteCode.LLOAD, paramOffset); cfw.add(ByteCode.L2D); size = 2; break; case 'f': // load a float, convert to double. cfw.add(ByteCode.FLOAD, paramOffset); cfw.add(ByteCode.F2D); break; case 'd': cfw.add(ByteCode.DLOAD, paramOffset); size = 2; break; } cfw.addInvoke(ByteCode.INVOKESPECIAL, "java/lang/Double", "<init>", "(D)V"); } return size; } /** * Generates code to convert a wrapped value type to a primitive type. * Handles unwrapping java.lang.Boolean, and java.lang.Number types. * Generates the appropriate RETURN bytecode. */ static void generateReturnResult(ClassFileWriter cfw, Class<?> retType, boolean callConvertResult) { // wrap boolean values with java.lang.Boolean, convert all other // primitive values to java.lang.Double. if (retType == Void.TYPE) { cfw.add(ByteCode.POP); cfw.add(ByteCode.RETURN); } else if (retType == Boolean.TYPE) { cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/Context", "toBoolean", "(Ljava/lang/Object;)Z"); cfw.add(ByteCode.IRETURN); } else if (retType == Character.TYPE) { // characters are represented as strings in JavaScript. // return the first character. // first convert the value to a string if possible. cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/Context", "toString", "(Ljava/lang/Object;)Ljava/lang/String;"); cfw.add(ByteCode.ICONST_0); cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/String", "charAt", "(I)C"); cfw.add(ByteCode.IRETURN); } else if (retType.isPrimitive()) { cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/Context", "toNumber", "(Ljava/lang/Object;)D"); String typeName = retType.getName(); switch (typeName.charAt(0)) { case 'b': case 's': case 'i': cfw.add(ByteCode.D2I); cfw.add(ByteCode.IRETURN); break; case 'l': cfw.add(ByteCode.D2L); cfw.add(ByteCode.LRETURN); break; case 'f': cfw.add(ByteCode.D2F); cfw.add(ByteCode.FRETURN); break; case 'd': cfw.add(ByteCode.DRETURN); break; default: throw new RuntimeException("Unexpected return type " + retType); } } else { String retTypeStr = retType.getName(); if (callConvertResult) { cfw.addLoadConstant(retTypeStr); cfw.addInvoke(ByteCode.INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;"); cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/JavaAdapter", "convertResult", "(Ljava/lang/Object;" +"Ljava/lang/Class;" +")Ljava/lang/Object;"); } // Now cast to return type cfw.add(ByteCode.CHECKCAST, retTypeStr); cfw.add(ByteCode.ARETURN); } } private static void generateMethod(ClassFileWriter cfw, String genName, String methodName, Class<?>[] parms, Class<?> returnType, boolean convertResult) { StringBuilder sb = new StringBuilder(); int paramsEnd = appendMethodSignature(parms, returnType, sb); String methodSignature = sb.toString(); cfw.startMethod(methodName, methodSignature, ClassFileWriter.ACC_PUBLIC); // Prepare stack to call method // push factory cfw.add(ByteCode.ALOAD_0); cfw.add(ByteCode.GETFIELD, genName, "factory", "Lorg/mozilla/javascript/ContextFactory;"); // push self cfw.add(ByteCode.ALOAD_0); cfw.add(ByteCode.GETFIELD, genName, "self", "Lorg/mozilla/javascript/Scriptable;"); // push function cfw.add(ByteCode.ALOAD_0); cfw.add(ByteCode.GETFIELD, genName, "delegee", "Lorg/mozilla/javascript/Scriptable;"); cfw.addPush(methodName); cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/JavaAdapter", "getFunction", "(Lorg/mozilla/javascript/Scriptable;" +"Ljava/lang/String;" +")Lorg/mozilla/javascript/Function;"); // push arguments generatePushWrappedArgs(cfw, parms, parms.length); // push bits to indicate which parameters should be wrapped if (parms.length > 64) { // If it will be an issue, then passing a static boolean array // can be an option, but for now using simple bitmask throw Context.reportRuntimeErrorById( "JavaAdapter can not subclass methods with more then" +" 64 arguments."); } long convertionMask = 0; for (int i = 0; i != parms.length; ++i) { if (!parms[i].isPrimitive()) { convertionMask |= (1 << i); } } cfw.addPush(convertionMask); // go through utility method, which creates a Context to run the // method in. cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/JavaAdapter", "callMethod", "(Lorg/mozilla/javascript/ContextFactory;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Function;" +"[Ljava/lang/Object;" +"J" +")Ljava/lang/Object;"); generateReturnResult(cfw, returnType, convertResult); cfw.stopMethod((short)paramsEnd); } /** * Generates code to push typed parameters onto the operand stack * prior to a direct Java method call. */ private static int generatePushParam(ClassFileWriter cfw, int paramOffset, Class<?> paramType) { if (!paramType.isPrimitive()) { cfw.addALoad(paramOffset); return 1; } String typeName = paramType.getName(); switch (typeName.charAt(0)) { case 'z': case 'b': case 'c': case 's': case 'i': // load an int value, convert to double. cfw.addILoad(paramOffset); return 1; case 'l': // load a long, convert to double. cfw.addLLoad(paramOffset); return 2; case 'f': // load a float, convert to double. cfw.addFLoad(paramOffset); return 1; case 'd': cfw.addDLoad(paramOffset); return 2; } throw Kit.codeBug(); } /** * Generates code to return a Java type, after calling a Java method * that returns the same type. * Generates the appropriate RETURN bytecode. */ private static void generatePopResult(ClassFileWriter cfw, Class<?> retType) { if (retType.isPrimitive()) { String typeName = retType.getName(); switch (typeName.charAt(0)) { case 'b': case 'c': case 's': case 'i': case 'z': cfw.add(ByteCode.IRETURN); break; case 'l': cfw.add(ByteCode.LRETURN); break; case 'f': cfw.add(ByteCode.FRETURN); break; case 'd': cfw.add(ByteCode.DRETURN); break; } } else { cfw.add(ByteCode.ARETURN); } } /** * Generates a method called "super$methodName()" which can be called * from JavaScript that is equivalent to calling "super.methodName()" * from Java. Eventually, this may be supported directly in JavaScript. */ private static void generateSuper(ClassFileWriter cfw, String genName, String superName, String methodName, String methodSignature, Class<?>[] parms, Class<?> returnType) { cfw.startMethod("super$" + methodName, methodSignature, ClassFileWriter.ACC_PUBLIC); // push "this" cfw.add(ByteCode.ALOAD, 0); // push the rest of the parameters. int paramOffset = 1; for (Class<?> parm : parms) { paramOffset += generatePushParam(cfw, paramOffset, parm); } // call the superclass implementation of the method. cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, methodName, methodSignature); // now, handle the return type appropriately. Class<?> retType = returnType; if (!retType.equals(Void.TYPE)) { generatePopResult(cfw, retType); } else { cfw.add(ByteCode.RETURN); } cfw.stopMethod((short)(paramOffset + 1)); } /** * Returns a fully qualified method name concatenated with its signature. */ private static String getMethodSignature(Method method, Class<?>[] argTypes) { StringBuilder sb = new StringBuilder(); appendMethodSignature(argTypes, method.getReturnType(), sb); return sb.toString(); } static int appendMethodSignature(Class<?>[] argTypes, Class<?> returnType, StringBuilder sb) { sb.append('('); int firstLocal = 1 + argTypes.length; // includes this. for (Class<?> type : argTypes) { appendTypeString(sb, type); if (type == Long.TYPE || type == Double.TYPE) { // adjust for double slot ++firstLocal; } } sb.append(')'); appendTypeString(sb, returnType); return firstLocal; } private static StringBuilder appendTypeString(StringBuilder sb, Class<?> type) { while (type.isArray()) { sb.append('['); type = type.getComponentType(); } if (type.isPrimitive()) { char typeLetter; if (type == Boolean.TYPE) { typeLetter = 'Z'; } else if (type == Long.TYPE) { typeLetter = 'J'; } else { String typeName = type.getName(); typeLetter = Character.toUpperCase(typeName.charAt(0)); } sb.append(typeLetter); } else { sb.append('L'); sb.append(type.getName().replace('.', '/')); sb.append(';'); } return sb; } static int[] getArgsToConvert(Class<?>[] argTypes) { int count = 0; for (int i = 0; i != argTypes.length; ++i) { if (!argTypes[i].isPrimitive()) ++count; } if (count == 0) return null; int[] array = new int[count]; count = 0; for (int i = 0; i != argTypes.length; ++i) { if (!argTypes[i].isPrimitive()) array[count++] = i; } return array; } private static final Object FTAG = "JavaAdapter"; private static final int Id_JavaAdapter = 1; }
mpl-2.0
stratumn/go
store/storehttp/example_test.go
2129
// Copyright 2016-2018 Stratumn SAS. 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 storehttp_test import ( "context" "fmt" "io/ioutil" "log" "net/http" "net/http/httptest" "time" "github.com/stratumn/go-core/dummystore" "github.com/stratumn/go-core/jsonhttp" "github.com/stratumn/go-core/jsonws" "github.com/stratumn/go-core/store/storehttp" ) // This example shows how to create a server from a dummystore. // It also tests the root route of the server using net/http/httptest. func Example() { // Create a dummy adapter. a := dummystore.New(&dummystore.Config{Version: "x.x.x", Commit: "abc"}) config := &storehttp.Config{ StoreEventsChanSize: 8, } httpConfig := &jsonhttp.Config{ Address: "5555", } basicConfig := &jsonws.BasicConfig{} bufConnConfig := &jsonws.BufferedConnConfig{ Size: 256, WriteTimeout: 10 * time.Second, PongTimeout: 70 * time.Second, PingInterval: time.Minute, MaxMsgSize: 1024, } // Create a server. s := storehttp.New(a, config, httpConfig, basicConfig, bufConnConfig) go s.Start() ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) defer s.Shutdown(ctx) defer cancel() // Create a test server. ts := httptest.NewServer(s) defer ts.Close() // Test the root route. res, err := http.Get(ts.URL) if err != nil { log.Fatal(err) } info, err := ioutil.ReadAll(res.Body) res.Body.Close() if err != nil { log.Fatal(err) } fmt.Printf("%s", info) // Output: {"adapter":{"name":"dummystore","description":"Stratumn's Dummy Store","version":"x.x.x","commit":"abc"}} }
mpl-2.0
ThesisPlanet/EducationPlatform
src/library/App/ServiceProxy/Content/Video.php
4210
<?php namespace App\ServiceProxy\Content; class Video extends \App\ServiceProxy\aService implements \App\Service\Content\iVideo { protected function loadService () { $this->_service = new \App\Service\Content\Video(); } /** * (non-PHPdoc) * * @see \App\Service\Content\iAudio::acl_getStreamUrl() * @param integer $id * @param array $options * @return string */ public function acl_getStreamUrl ($id, $options = array()) { return $this->_service->acl_getStreamUrl($id, $options); } /** * Gets the distribution streamer url * * @return string */ public function getDistributionStreamer () { return $this->_service->getDistributionStreamer(); } /** * * @param integer $id * @return array * @see \App\Service\iContent::find() */ public function find ($id) { return $this->_service->find($id); } /** * * @param integer $courseId * @return array * @see \App\Service\iContent::findByCourseId() */ public function findByCourseId ($courseId) { return $this->_service->findByCourseId($courseId); } /** * * @param array $data * @return integer * @see \App\Service\iContent::acl_create() */ public function acl_create (array $data) { return $this->_service->acl_create($data); } /** * * @param integer $id * @param array $data * @return boolean * @see \App\Service\iContent::acl_update() */ public function acl_update ($id, array $data) { return $this->_service->acl_update($id, $data); } /** * * @param integer $id * @return boolean * @see \App\Service\iContent::acl_delete() */ public function acl_delete ($id) { return $this->_service->acl_delete($id); } /** * * @param integer $id * @return boolean * @see \App\Service\iContent::acl_publish() */ public function acl_publish ($id) { return $this->_service->acl_publish($id); } /** * * @param integer $id * @return boolean * @see \App\Service\iContent::acl_unpublish() */ public function acl_unpublish ($id) { return $this->_service->acl_unpublish($id); } /** * * @param integer $id * @return boolean * @see \App\Service\iContent::acl_enable() */ public function acl_enable ($id) { return $this->_service->acl_enable($id); } /** * * @param integer $id * @return boolean * @see \App\Service\iContent::acl_disable() */ public function acl_disable ($id) { return $this->_service->acl_disable($id); } /** * * @return string * @see \App\Service\iContent::getForm() */ public function getForm () { return $this->_service->getForm()->__toString(); } /** * * @return string * @see \App\Service\iContent::getDeleteForm() */ public function getDeleteForm () { return $this->_service->getDeleteForm()->__toString(); } /** * * @param integer $id * @param array $options * @return string * @see \App\Service\iContent::acl_getDownloadUrl() */ public function acl_getDownloadUrl ($id, $options = array()) { return $this->_service->acl_getDownloadUrl($id, $options); } /** * * @param integer $id * @param array $options * @return string * @see \App\Service\Content\iVideo::acl_getThumbnailUrl() */ public function acl_getThumbnailUrl ($id, $options = array()) { return $this->_service->acl_getThumbnailUrl($id, $options); } }
mpl-2.0
garciparedes/python-examples
web/django/graphene/graphene-quickstart/lesson-09-context.py
429
#!/usr/bin/env python3 """ URL: http://docs.graphene-python.org/en/latest/execution/#context """ import graphene import utils.json as uj class Query(graphene.ObjectType): name = graphene.String() def resolve_name(self, args, context, info): return context.get('name') schema = graphene.Schema(Query) result = schema.execute('{ name }', context_value={'name': 'Syrus'}) print(uj.dict_to_json(result.data))
mpl-2.0
Stupeflix/japper
japper/alert_backends/django_email/settings.py
109
from django.conf import settings FROM_EMAIL = getattr(settings, 'JAPPER_FROM_EMAIL', 'japper@example.com')
mpl-2.0
maxanier/Vertretungsplan
app/src/main/java/de/maxgb/vertretungsplan/manager/TabManager.java
4102
package de.maxgb.vertretungsplan.manager; import java.util.ArrayList; import java.util.HashMap; import org.json.JSONArray; import org.json.JSONException; import de.maxgb.vertretungsplan.fragments.InfoFragment; import de.maxgb.vertretungsplan.fragments.lehrer.AllesLehrerFragment; import de.maxgb.vertretungsplan.fragments.lehrer.EigeneLehrerFragment; import de.maxgb.vertretungsplan.fragments.schueler.AllesSchuelerFragment; import de.maxgb.vertretungsplan.fragments.schueler.KurseSchuelerFragment; import de.maxgb.vertretungsplan.fragments.schueler.StufeSchuelerFragment; import de.maxgb.vertretungsplan.fragments.stundenplan.ModifiedStundenplanFragment; import de.maxgb.vertretungsplan.fragments.stundenplan.NormalStundenplanFragment; import de.maxgb.vertretungsplan.fragments.stundenplan.NormalUebersichtFragment; public class TabManager { public static class TabSelector { private String typ; private boolean enabled; public TabSelector(String typ, boolean enabled) { this.typ = typ; this.enabled = enabled; } public String getTyp() { return typ; } public boolean isEnabled() { return enabled; } public void toogleEnabled() { enabled = !enabled; } @Override public String toString() { return "Typ: " + typ + "-" + enabled; } } private enum FragmentTab { LEHRERALLE(AllesLehrerFragment.class, "Alle", "Alle Vertretungen"), LEHREREIGENE(EigeneLehrerFragment.class, "Eigene Kurse", "Vertretungen für eigene Kurse"), SCHUELERALLE(AllesSchuelerFragment.class, "Alle", "Alle Vertretungen"), SCHUELERSTUFE(StufeSchuelerFragment.class, "Stufe", "Vertretungen für Stufe"), SCHUELEREIGENE( KurseSchuelerFragment.class, "Eigene Kurse", "Vertretungen für eigene Kurse"), INFO(InfoFragment.class, "Info", ""), SPNORMAL(NormalStundenplanFragment.class, "Stundenplan", "Normaler Studenplan"), SPMODIFIED( ModifiedStundenplanFragment.class, "SP+VP", "Stundenplan incl. Vertretungen"); private Class fragmentClass; private String title; private String description; FragmentTab(Class fragmentClass, String title, String description) { this.fragmentClass = fragmentClass; this.title = title; this.description = description; } public String getDescription() { return description; } public Class getFragmentClass() { return fragmentClass; } public String getTitle() { return title; } } public static ArrayList<TabSelector> convertToArrayList(String json_tabs_string) { ArrayList<TabSelector> tabs = new ArrayList<TabSelector>(); try { JSONArray json_tabs = new JSONArray(json_tabs_string); for (int i = 0; i < json_tabs.length(); i++) { JSONArray tab = json_tabs.getJSONArray(i); tabs.add(new TabSelector(tab.getString(0), tab.getBoolean(1))); } } catch (JSONException e) { } return tabs; } public static String convertToString(ArrayList<TabSelector> tabs) { JSONArray json_tabs = new JSONArray(); for (int i = 0; i < tabs.size(); i++) { JSONArray tab = new JSONArray(); tab.put(tabs.get(i).getTyp()); tab.put(tabs.get(i).isEnabled()); json_tabs.put(tab); } return json_tabs.toString(); } private HashMap<String, FragmentTab> map; public TabManager() { map = new HashMap<String, FragmentTab>(); map.put("AllesLehrerFragment.class", FragmentTab.LEHRERALLE); map.put("EigeneLehrerFragment.class", FragmentTab.LEHREREIGENE); map.put("AllesSchuelerFragment.class", FragmentTab.SCHUELERALLE); map.put("StufeSchuelerFragment.class", FragmentTab.SCHUELERSTUFE); map.put("KurseSchuelerFragment.class", FragmentTab.SCHUELEREIGENE); map.put("InfoFragment.class", FragmentTab.INFO); map.put("NormalStundenplanFragment.class", FragmentTab.SPNORMAL); map.put("ModifiedStundenplanFragment.class", FragmentTab.SPMODIFIED); } public Class getTabClass(TabSelector tab) { return map.get(tab.getTyp()).getFragmentClass(); } public String getTabDescription(TabSelector tab) { return map.get(tab.getTyp()).getDescription(); } public String getTabTitle(TabSelector tab) { return map.get(tab.getTyp()).getTitle(); } }
mpl-2.0
cmars/shadowfax
storage/bolt/contacts_test.go
3076
/* Copyright 2015 Casey Marshall. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package bolt_test import ( "path/filepath" "sort" "github.com/boltdb/bolt" gc "gopkg.in/check.v1" sf "github.com/cmars/shadowfax" "github.com/cmars/shadowfax/storage" sfbolt "github.com/cmars/shadowfax/storage/bolt" sftesting "github.com/cmars/shadowfax/testing" ) type contactsSuite struct { db *bolt.DB } var _ = gc.Suite(&contactsSuite{}) func (s *contactsSuite) SetUpTest(c *gc.C) { dir := c.MkDir() var err error s.db, err = bolt.Open(filepath.Join(dir, "testdb"), 0600, nil) c.Assert(err, gc.IsNil) } func (s *contactsSuite) TestContacts(c *gc.C) { bob := sftesting.MustNewKeyPair() carol := sftesting.MustNewKeyPair() aliceContacts := sfbolt.NewContacts(s.db) aliceContacts.Put("bob", bob.PublicKey) aliceContacts.Put("carol", carol.PublicKey) var err error var key *sf.PublicKey key, err = aliceContacts.Key("bob") c.Assert(err, gc.IsNil) c.Assert(key, gc.DeepEquals, bob.PublicKey) key, err = aliceContacts.Key("carol") c.Assert(err, gc.IsNil) c.Assert(key, gc.DeepEquals, carol.PublicKey) for _, noName := range []string{"dave", "trent"} { _, err = aliceContacts.Key(noName) c.Assert(err, gc.ErrorMatches, `key not found for "`+noName+`"`) } bob2 := sftesting.MustNewKeyPair() aliceContacts.Put("bob", bob2.PublicKey) key, err = aliceContacts.Key("bob") c.Assert(err, gc.IsNil) c.Assert(key, gc.DeepEquals, bob2.PublicKey) cinfos, err := aliceContacts.Current() c.Assert(err, gc.IsNil) sort.Sort(cinfos) c.Assert(cinfos, gc.DeepEquals, storage.ContactInfos{{ Name: "bob", Address: bob2.PublicKey, }, { Name: "carol", Address: carol.PublicKey, }}) } func (s *contactsSuite) TestSameName(c *gc.C) { alice := sftesting.MustNewKeyPair() bob := sftesting.MustNewKeyPair() testContacts := sfbolt.NewContacts(s.db) testContacts.Put("test", alice.PublicKey) testContacts.Put("test", bob.PublicKey) name, err := testContacts.Name(alice.PublicKey) c.Assert(err, gc.IsNil) c.Assert(name, gc.Equals, "test") name, err = testContacts.Name(bob.PublicKey) c.Assert(err, gc.IsNil) c.Assert(name, gc.Equals, "test") key, err := testContacts.Key("test") c.Assert(err, gc.IsNil) c.Assert(key, gc.DeepEquals, bob.PublicKey) } func (s *contactsSuite) TestSameKey(c *gc.C) { alice := sftesting.MustNewKeyPair() testContacts := sfbolt.NewContacts(s.db) for _, name := range []string{"go", "ask", "alice", "when", "shes", "ten", "feet", "tall"} { testContacts.Put(name, alice.PublicKey) } name, err := testContacts.Name(alice.PublicKey) c.Assert(err, gc.IsNil) c.Assert(name, gc.Equals, "tall", gc.Commentf("expect last name set")) key, err := testContacts.Key("alice") c.Assert(err, gc.IsNil) c.Assert(key, gc.DeepEquals, alice.PublicKey) key, err = testContacts.Key("when") c.Assert(err, gc.IsNil) c.Assert(key, gc.DeepEquals, alice.PublicKey) }
mpl-2.0
therealglazou/bluegriffon
extensions/inspector/resources/content/jsutil/commands/baseCommands.js
5019
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /***************************************************************************** * Base Commands -------------------------------------------------------------- * Transactions which can be used to implement common commands. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * REQUIRED IMPORTS: * (Other files may be necessary, depending on which base commands are used.) *****************************************************************************/ Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); ////////////////////////////////////////////////////////////////////////////// //// Global Constants const kClipboardHelperClassID = "@mozilla.org/widget/clipboardhelper;1"; ////////////////////////////////////////////////////////////////////////////// //// Transactions /** * Base implementation of an nsITransaction. * @param aIsTransient [optional] * Override the isTransient field. The default is true. */ function inBaseCommand(aIsTransient) { if (aIsTransient !== undefined) { this.isTransient = aIsTransient; } } inBaseCommand.prototype = { isTransient: true, merge: function BaseCommand_Merge() { return false; }, QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsITransaction]), doTransaction: function BaseCommand_DoTransaction() {}, undoTransaction: function BaseCommand_UndoTransaction() {}, redoTransaction: function BaseCommand_RedoTransaction() { this.doTransaction(); } }; /** * Open the object "mini" viewer (object.xul) on a given object. The mObject * field should be overridden to contain the object to be inspected. * * Primitives are uninteresting and attempts to inspect them will fail. * Consumers should take this into account when determining whether the * corresponding command should be enabled. For convenience, * cmdEditInspectInNewWindowBase.isInspectable is provided. */ function cmdEditInspectInNewWindowBase() { this.mObject = null; } cmdEditInspectInNewWindowBase.isInspectable = function InspectInNewWindowBase_IsInspectable(aValue) { var type = typeof aValue; return (type == "object" && aValue !== null) || type == "function"; }; cmdEditInspectInNewWindowBase.prototype = new inBaseCommand(); cmdEditInspectInNewWindowBase.prototype.doTransaction = function InspectInNewWindowBase_DoTransaction() { if (cmdEditInspectInNewWindowBase.isInspectable(this.mObject)) { inspectObject(this.mObject); } }; /** * Copy a string to the clipboard. The mString field should be overridden to * contain the string to be copied. */ function cmdEditCopySimpleStringBase() { this.mString = null; } cmdEditCopySimpleStringBase.prototype = new inBaseCommand(); cmdEditCopySimpleStringBase.prototype.doTransaction = function CopySimpleStringBase_DoTransaction() { if (this.mString) { var helper = XPCU.getService(kClipboardHelperClassID, "nsIClipboardHelper"); helper.copyString(this.mString); } }; /** * An nsITransaction to copy items to the panelset clipboard. * @param aObjects * an array of objects that define a clipboard flavor, a delimiter, and * toString(). */ function cmdEditCopy(aObjects) { this.mObjects = aObjects; } cmdEditCopy.prototype = new inBaseCommand(); cmdEditCopy.prototype.doTransaction = function Utils_Copy_DoTransaction() { if (this.mObjects.length == 1) { viewer.pane.panelset.setClipboardData(this.mObjects[0], this.mObjects[0].flavor, this.mObjects.toString()); } else { var joinedObjects = this.mObjects.join(this.mObjects[0].delimiter); viewer.pane.panelset.setClipboardData(this.mObjects, this.mObjects[0].flavor + "s", joinedObjects); } } /** * Open a source view on a file. The mURI field should be overridden to * contain the URI of the file on which to open the source view. The * mLineNumber field may optionally be set to contain the line number at which * the source view should be opened. */ function cmdEditViewFileURIBase() { this.mURI = null; this.mLineNumber = 0; } cmdEditViewFileURIBase.prototype = new inBaseCommand(); cmdEditViewFileURIBase.prototype.doTransaction = function ViewFileURIBase_DoTransaction() { if (this.mURI) { // 1.9.0 toolkit doesn't have this method if ("viewSource" in gViewSourceUtils) { gViewSourceUtils.viewSource(this.mURI, null, null, this.mLineNumber); } else { openDialog("chrome://global/content/viewSource.xul", "_blank", "all,dialog=no", this.mURI, null, null, this.mLineNumber, null); } } };
mpl-2.0
writeas/web-core
auth/auth.go
980
package auth import ( uuid "github.com/gofrs/uuid" "github.com/writeas/web-core/log" "strings" ) // GetToken parses out the user token from either an Authorization header or simply passed in. func GetToken(header string) []byte { var accessToken []byte token := header if len(header) > 0 { f := strings.Fields(header) if len(f) == 2 && f[0] == "Token" { token = f[1] } } t, err := uuid.FromString(token) if err != nil { log.Error("Couldn't parseHex on '%s': %v", accessToken, err) } else { accessToken = t[:] } return accessToken } // GetHeaderToken parses out the user token from an Authorization header. func GetHeaderToken(header string) []byte { var accessToken []byte if len(header) > 0 { f := strings.Fields(header) if len(f) == 2 && f[0] == "Token" { t, err := uuid.FromString(f[1]) if err != nil { log.Error("Couldn't parseHex on '%s': %v", accessToken, err) } else { accessToken = t[:] } } } return accessToken }
mpl-2.0
sivaramambikasaran/Quadrature
Gauss_Laguerre/header/Gauss_Laguerre_Nodes_and_Weights_111.hpp
28880
// // Gauss_Laguerre_Nodes_and_Weights_111.hpp // // // Created by Sivaram Ambikasaran on 2014-02-22.09:22:35. // // // Array of nodes and weights for Gauss Laguerre quadrature of order 111. // // #ifndef __Gauss_Laguerre_Nodes_and_Weights_111_hpp__ #define __Gauss_Laguerre_Nodes_and_Weights_111_hpp__ void Gauss_Laguerre_Nodes_and_Weights_111(long double*& nodes, long double*& weights) { nodes = new long double[111]; weights = new long double[111]; nodes[0] = 0.012966866876395589690339566978536784821471288117658881259528989839810470362600369734732919400027765122706445883673542425893426132; weights[0] = 0.032848771083062569795473452973776133050600161775669274368755108786054706632841369054328449547542025008996720161980536057053469; nodes[1] = 0.06832447599884326135012695816348517240621635535375999529708419394995448475173980883494713233393547787480113824308710332169512409; weights[1] = 0.0723537467936615374059788994485826195571070762252450529680579891401399579263810523695573172121279256641491652630248070956071; nodes[2] = 0.16792860075187912123818763094056076948995035025342188342739623226828765240637726006749552239166368254316125094663321860676377065; weights[2] = 0.10292365295256818812192641956034494896835465865196154388126209268073431027298532781777200345636694050137616377619094289724; nodes[3] = 0.31182114430081446038097542871245360303607549798840792806353834623874310529225412550149258280617406489553758875945912206953015551; weights[3] = 0.121564878852874108619475155478444498983276168242357857106613570943741355537102224343435920688415265754864905993460754842; nodes[4] = 0.50003342184847942487494788943826460413039305097876486017224686715116372182197068994044896021636735726118947361057805632776362997; weights[4] = 0.127600178736308167502322891373064867263461296754931143824815120244095413192318160060617934702804386736778341855880387735; nodes[5] = 0.73260353924877199452700591799110535017893924004553608774314962927533114615319927885094308458599367241060382503972807655994991828; weights[5] = 0.12245375222530459095329756140008218792095324648567247680395829555586553420846321416276859611052544568483986836410940029; nodes[6] = 1.009578064976922096032780880024174185406610729735462388984744968470285588266929207453259595553620399323034773558507987484505717; weights[6] = 0.1090182857798531878461939195778078092043461388205268832121991643526962923071317437455982284831282051304585219432960918; nodes[7] = 1.3310123850367956465579249261140281284832157818477577022995594520053207988735202337859802391288791945903579970779231685674102697; weights[7] = 0.09080486874562851315792529896522424492696473298757732273116353952209516464564219017777190510310583912188871321980414; nodes[8] = 1.6969708447239451359778296487071595437468573825384961528488070085007286830205576722832603991977034718931552597983133049729055324; weights[8] = 0.0711409966042784780663559913889835702197952166771361090575394836410325870342302786131429641544032470116307767075564; nodes[9] = 2.1075268466605027488029577494029714171995805756651704738679162148342522024482098052214794181006561639212055748088076199326693928; weights[9] = 0.052611631447427104469267055225549029592023784564210975284552484076992612022797010734142293337727627977331062235819; nodes[10] = 2.5627629427888570973214405996693826901205353385033451291563363318548296902180031245222363697244614637945249075827199967785252847; weights[10] = 0.03681933492680620729278609262269402350212938128141479792964505053867061321365595974930672176310098915915214083212; nodes[11] = 3.0627709310754589166664225883363288977599980564124810073352129584453313475800265521332778982470271374430935661527227354399434508; weights[11] = 0.0244276105728699003961923009035033557536723453513463588664031482102641307893486540739736040582271183352488721395; nodes[12] = 3.6076519606758738521292440132072219754282367243082449218781953996268524208045391739803929754392977255685034162693453566507740927; weights[12] = 0.015384043403835235126421159576449911990503432301838858547852058160786583676052447074868840759143267587850116981; nodes[13] = 4.197516647164217540785985549477456092034153651040838886395115566107272453417980486735001459871220907206820044523230969996998836; weights[13] = 0.00920606147251497396952420253030173795309456825875851240597782673118983119767600141094970965725587842463192016; nodes[14] = 4.8324851986926888624972846527562594752398796966939452056569696030313066162514755492298057978880741764857617106721644524963475937; weights[14] = 0.00523860554680106896827353815257516436136353138837064242239552274593659763067337667199621921633249343820864644; nodes[15] = 5.5126875536795101559824957913294967825444455693809383539530959489145981001826166424937705477499571870612243990486006505743198432; weights[15] = 0.0028362346089233437866853011790784529580056062668097685289608647582984503310066707516071410589535045448791039; nodes[16] = 6.2382635305312148763629200221777118199591248417592116159968194008800577821540983482310075695656357541861573422772504722711793918; weights[16] = 0.001461635966953208999493220262075042199745177653644472391005974577832801371083869261468246782012427933646822; nodes[17] = 7.0093629898847577772117556137061538436495610066045515805911558330100082006222680650997342630055406770795393428163066324190235547; weights[17] = 0.00071720882998061487901455816182488568171122776121953534060716835795087025282509083723818644716797374463695; nodes[18] = 7.8261460098670116596420207332010688577144962739185263089608323186670093987537294031913175138520990624905349354237220677347238037; weights[18] = 0.00033516770911699829920191923204396013550020836886318429950666885034463836439546066303001603095510587648827; nodes[19] = 8.6887830748977721645981068330605431629186659716258237074742682735781946528056814614479416260991584224915599630292592506364186986; weights[19] = 0.0001491964935149990347364836463200555293163050681260662936663674367685881483792913105792210745440085544558; nodes[20] = 9.5974552786005041888314418715708874411282654990148969960382954134516902741104812623640580134932856634471897410527755556815970428; weights[20] = 0.000063267234907443789628644807470525642078514930936254989592433676907975675520294417641772841661564323457; nodes[21] = 10.552354541429687324730460153359234245831075363269995559007936363387576948789475668834935679423700201403916212567702658156027249; weights[21] = 0.00002555905639825217783729484346673619230418699008558563297466822684009302782776771994074337157994167762; nodes[22] = 11.553683843673448778159121590281730409739555568263482854888886062556078780784713701945888385700409957330860764358739184189103725; weights[22] = 9.83692780848174710275997444440562276399306293617901606526284590007747070229048454009241704044430055e-6; nodes[23] = 12.601657474544736545939156864000651467041511787183916991505423661051404491274488350561180958481899030320665848001063718863171005; weights[23] = 3.60669335530264612787542612369198222196695504479445979069394768191758454737810974151123782941853871e-6; nodes[24] = 13.696501298133534321793908734127279070134655736813562128887059302620772711758930064706970755070480135003109409069179335383678991; weights[24] = 1.2596955249794310397513200614793818974241209190220503997522454929321639386652294688699410053327259e-6; nodes[25] = 14.838453037056740806401631698700784267688518142039919839521907950326566560797267528264511809253373647126342061637513360575451445; weights[25] = 4.190702001124495197988249992328063581527632118780044788927015861886333674134730512887099922570956e-7; nodes[26] = 16.02776257471166589734862197495070936639278764194723362554923385435561496067885651654900079029673746535572478041781670466392503; weights[26] = 1.32775745990243538958525643300416002194054376112002922924017445381013203894597599118071329267196e-7; nodes[27] = 17.264692277114076457396705056495229486012443384798440238125727973905105980874998453495889092266059804677294029866091915253816407; weights[27] = 4.0058630121462320687933686291294179007395904662366349293632567297890887804055640955528259324521e-8; nodes[28] = 18.549517335382883866663146724744147165452740317007491767610886534092486439037757946655697036072329752850694715619642781022055028; weights[28] = 1.1506486826481861322480654255059160065027409749919711091415237977895208350035778623490826140059e-8; nodes[29] = 19.882526130021513865334422459593124562058612127347050099717711468235953417855442580717225655783968638453981446546940202451685061; weights[29] = 3.14609997143295653660513953010727421229498423309575850869627804276581116571253168989916595504e-9; nodes[30] = 21.264020618241427027281384504769806575765698760879783649849590012028304944023050223576699976378189497130874473241947452418663328; weights[30] = 8.1863353320631151265952904887099223522326598836687982849716200995080850806360275499979878523e-10; nodes[31] = 22.694316745676942457598334617647893245540150867567554860606320718769812863958893476030104449112732720108483955090047622841629185; weights[31] = 2.0266955052866841668061096513591720735063785104781693719286786604207879075978870758455939594e-10; nodes[32] = 24.173744883953328989891764937301512397948207784936772695416452850699338891072820719708076116502639351168101866385600860196750326; weights[32] = 4.772599609300063796917826685393806963375569649793975317955950170462518395238034672762981065e-11; nodes[33] = 25.70265029569304287404748299811180780280537380833457579273180058262357130210990786623023310087470111346354013434131861084143786; weights[33] = 1.068724017602141367105859727969939944609169703204939299887002742894540657321310690301738011e-11; nodes[34] = 27.281393628679101650966143464621874881008308726350502018665248402463591743257913554850977957994013917721891596256734588126943958; weights[34] = 2.2750336830283904571137380848054015117697259823227316559624390839865696578359011410965019e-12; nodes[35] = 28.910351441041116029485302407065313710703715732418060147196636369560204425305638725836822073883253878057630554168993617037559899; weights[35] = 4.602359228165733426365922132885119074187997488761511413134980972419097784840672952194139e-13; nodes[36] = 30.589916759489830635251921641515557302403579098431269440610886420094744613633979467040267278299559115506858503654649639059511118; weights[36] = 8.84491027981123254518616124554026390972675548759492319420110204765174485544804101820864e-14; nodes[37] = 32.320499672801696588595511833808191360894674490716635492094723674436770498052885212594359935279812527291911680764390414429676444; weights[37] = 1.61423746634045032840386574101805670531203272911593375365342223476835671038370582624505e-14; nodes[38] = 34.102527962947754375336475375473155676789068124756156592935562778631460207225029381610998751329555562747735006219571566680923074; weights[38] = 2.7966250408306889920113801790778178820786096796209900389149288282691737648539341717805e-15; nodes[39] = 35.936447776472906544352385208788735274240363250865530012235796325619802031708230247882757405904722419120893588985496683663657338; weights[39] = 4.5974436771385528707220628597513972543902854408450901056765783785826274685048800918197e-16; nodes[40] = 37.822724338964722134691244422786688544527292786568770132966694927707747604836135526259750793138500551765007474523675329022333739; weights[40] = 7.168479889077502380236464452700747434896734557837594938481811019147631282923130119801e-17; nodes[41] = 39.761842715707744682501783773724481592945581144641252605626515926568197702785204976778643505772616587081535971228752032392998104; weights[41] = 1.059667712903333848047179013257736154079375438542533173336536720474537211057407598638e-17; nodes[42] = 41.754308621902712965512277082445509315501748683841610793869133555717375188236481038591011232765038082676667524868062880639879492; weights[42] = 1.48435553036931432611954606663473047210797689034986750740043569686666656895099565405e-18; nodes[43] = 43.80064928614337163065939538770136407317807506528833946218389578030604325037281062654585451504370672117516679290775130776017074; weights[43] = 1.9693152137584604272221801220811544486338462439156502817200062648449547513033554773e-19; nodes[44] = 45.901414371190312776498588118302426110240314258874304666966854791911513209865965981686576751340542942062898848271332051320074048; weights[44] = 2.473287443885206484781691915610211258857440615604012021492929679752555012412579343e-20; nodes[45] = 48.05717695646572492191749255292750839918766345946554977860685051527118281159036673701133618102225205301242003767429572074561033; weights[45] = 2.938854997773300930845963043611501291943755225413341933335790553735791190202965415e-21; nodes[46] = 50.268534587119798377085869777303114986344532787702564690835918377320994644404491261776118291397068810458480073291762704930623428; weights[46] = 3.30199843025812865504958342007262939039085769622660222408851452517671642893361032e-22; nodes[47] = 52.53611039499429597693174993821274874128735816263741263066943562379165186846456257559520681318505334056159865264042420201630326; weights[47] = 3.50598439897769451789175500219636410670471084950499282793068737330958201867052119e-23; nodes[48] = 54.86055429733769066889808378339636334208237376076050328759241012368135852497069442546386243360622257408216577571287163139362218; weights[48] = 3.5156421468869608271596759436475426664373478005962543774192509776679252238884363e-24; nodes[49] = 57.24254427971646760753926012010412853358517336086509443352555096926239085380078915744181101004087810932621200153202600929736205; weights[49] = 3.327173392017252056613125782716949923243071784866627500049273314335178822917633e-25; nodes[50] = 59.682787770226939742894907502234682418472059695213343706881216059311905853129521440294526167853396330455832643102953915313183619; weights[50] = 2.969775591640555721050424700365174082689721617645326126931409511892613936442423e-26; nodes[51] = 62.1820231128507479567154042308153666121974734105031644905572782436146511621151648221004858650657193892773942932055784542632368; weights[51] = 2.498255285417522635004984099970004184598833676471726919130522538937534697899034e-27; nodes[52] = 64.741021148626107461150629963714318576233894070083106473827100978637557060269235232987716000483393419345122135670065244081505623; weights[52] = 1.979192788817077206475234742851064408461245724844336504293619195743622607153328e-28; nodes[53] = 67.360586914238561948061074269490154318530457440271988112188821300076612794754285440465676214732565167536369524856720440076581617; weights[53] = 1.47548729226888937265673538092793239200593484149608932098054489906654646271942e-29; nodes[54] = 70.041561468684310453368874018795874241588508934807233582957464078128811576557972459505300695287557181559679401710900483242664356; weights[54] = 1.03423926654398628729159872347627498737011909231021478532263413134827268854993e-30; nodes[55] = 72.784823859843301297929597350619233957657128231883028808321556692984617656694967393043595225453922222213252799118580187359484649; weights[55] = 6.8103606641698627363305748488014042097648644426237044011625237446620295980005e-32; nodes[56] = 75.591293244138342083896208396134307553593039834178010222266240043453735519642707025901520466243490207521069261751986190021960862; weights[56] = 4.2091121084112850647337154070628254456890584602073095500467707766574955866537e-33; nodes[57] = 78.4619311739739733896590626794888221448766985065722794140607855079081124663888395967539424113865386050947854427474467287958091; weights[57] = 2.439334381445178166948990453518157224617970269903196629527477603629401223397e-34; nodes[58] = 81.397744069372391647349895397280392143071853742518126442264553511658659940693776099413605665061123865586382439419816454629976742; weights[58] = 1.324287215949483432012476420902628145898749333182438759535904162624115132458e-35; nodes[59] = 84.399785892185752986457708068902440864125878584138017340743361842422727078258498032943853856818772058044174198418801181204323085; weights[59] = 6.72778061229475670138116229700473540372531294278495119574490013042634708268e-37; nodes[60] = 87.469161043503060568920406231337542954050587729964570537412991123046738417730850927512973259273309444890749431385740932884046355; weights[60] = 3.19497174351525806298300106823114345514259926551549808847951354477540215007e-38; nodes[61] = 90.607027507430885538257247184298230561611777808834384763631913602299115030015899968243923492914497417106587073527679758359657059; weights[61] = 1.41667826387187242391594738509400854250304070450317704581770678968582461064e-39; nodes[62] = 93.814600267364245776058439487156954288908269256322813085317742789881135645537187164798938130653974960210049205652800633249240945; weights[62] = 5.858185120634524592311348999148440560607464167208517423575950890259303971e-41; nodes[63] = 97.093155024241214469221540546008864727023429585048248892760132119536458531854725636395728142486091217412117542215928068189980065; weights[63] = 2.25628968553270849077321075702703098964753558593551420803753915966083806872e-42; nodes[64] = 100.44403225016892486655725220998856863235356205389767556802853751125694505472416502608661573737966310989874654762954433710707624; weights[64] = 8.0833365065050867396356273278284399371637884514986733230650053792962445687e-44; nodes[65] = 103.86864161531154518949040526153708446359176901442753260226795909397365246126841683431085199673413999309976537700522298239432823; weights[65] = 2.6899524196628289286428020558229245055065866414056562298837758730936265304e-45; nodes[66] = 107.36846683115323335303382635812696215046433967405319640411528401559235977738112921897339311050325022824992960061927002108723252; weights[66] = 8.30268727469298422382892614179320199793016438196677024211725166800872289e-47; nodes[67] = 110.94507095932483802921744348362796904998405858067921270968571060150209321892901449275612837552904494498595111393770915148366912; weights[67] = 2.3732338212112906375488498101625273417525115956395931877877448647239477795e-48; nodes[68] = 114.6001022422745144925777419070496666146505228439051607827358706622686685218252656073051488386620608980648036930366108378211452; weights[68] = 6.271925399137821747498697170171926988850639835291313341933454752077376246e-50; nodes[69] = 118.33530052036722483459208014563811226951371624878291834525867550911587089666446894832515794865732900970512882024789875561978802; weights[69] = 1.529857024589927705093511925084345083335929770344210161626636727843063233e-51; nodes[70] = 122.15250430975825185778306921064956163747389102886540942398202836728765622785946943323328035933097107584688580113512699471361965; weights[70] = 3.437944239111237656277999742465029059550179094272329617130518431911089788e-53; nodes[71] = 126.05365862689875722500826873824290477883779814143972797381581006187447745633605554839395948010859990239122190013065823883749221; weights[71] = 7.10406956201868647300439284313001130654706563090518996775867283636854891e-55; nodes[72] = 130.04082365916428578733133530018610575704726527038767082206833561987655055052882392846495895381781502025764751353429149945788371; weights[72] = 1.347065063406965383577704435824679000639018202620318693785285487707644721e-56; nodes[73] = 134.11618439730568074884367313243120409115947522927630748378972298899632597397282429810322031028377052000357046595582888723493126; weights[73] = 2.338845921215785706710004090406834546842231078130524848258628203884152892e-58; nodes[74] = 138.28206136477459858460262867472236356532061562692154650793611935946546952923977869057800689903525129759952886071640543797039419; weights[74] = 3.709765656733109962533775638061802578990423046066439849720435622387927675e-60; nodes[75] = 142.54092260218566943975582013809089907386492880492851784812027775500716931243557715804193323044163188141754685532637660521108593; weights[75] = 5.36240528936286132372825800947335939168410455218867452646858828255962212e-62; nodes[76] = 146.89539709314365119150085901544485018661118730699745775859096272778501741932000882637280300103000824913171965770310781787129683; weights[76] = 7.04543967256966773381548781629559829725020349762383209983931661300876144e-64; nodes[77] = 151.34828985152785020432266593323862223488066442357843242048542684146752082260851553531384801620429882846204874766629235402843183; weights[77] = 8.39040535746909592786417932065206187564105840813683048110821589845894704e-66; nodes[78] = 155.90259893154488670866934562672334863417367479460168944984804600391818055260066601432258100021957872805476143735319705900515948; weights[78] = 9.03008780356696903127235290680800457033575952263999342969177432230226769e-68; nodes[79] = 160.56153467230788380213205467703476279102581215605836870449780042281849051220270857893847274484999137117783105522125127354363939; weights[79] = 8.75490564955469848870173500026651195589011111663706279723077040283554524e-70; nodes[80] = 165.32854155080051225130045812657680525092979246944197042995754995388829521674234402083370014243279121303372998991233057288526626; weights[80] = 7.62038276626304828726672951016980166166217205116259207122276145761942595e-72; nodes[81] = 170.20732309400102662697531711379116745884216818743732201243708614692846120183496694653106493701088041908107211570810167859766732; weights[81] = 5.93296298880440515086030998609816831970619417120037395383852507438065375e-74; nodes[82] = 175.20187039683245361313328952021189315901046302900141852920794948370518812959091316078085023480743032651233145491449386039444145; weights[82] = 4.115436035394293795215194070170443123483209900385732828751849077726006305e-76; nodes[83] = 180.31649491298229959460270948321464441974569829068497231314770215866087794864771653409514768429534765174407938865976441159603513; weights[83] = 2.532510668722550829814754195177320439093617946853490972728647873499433389e-78; nodes[84] = 185.55586633787043150651958017171164137529404851922560266192018965328742399388635594837343238609461873966774441396599093086352559; weights[84] = 1.376149174059965532410630621672075281303528080952793690815277278382055901e-80; nodes[85] = 190.92505659709072947256210351743216599179304585840609226773628343199897947845052547570844288653399047202044598755526897229557958; weights[85] = 6.570115294506565568146045129390074800230985311396094743691974957309665787e-83; nodes[86] = 196.42959120308687852906326360792676192991784307675167248051559483400532362273301379199302195124931488474564365497249419606556705; weights[86] = 2.7408985328798155481322202411165729401408334431745587134185922647078091872e-85; nodes[87] = 202.07550956636426990945449762023085552518247937285291684554178763110712947554297045702657555322173613835542653159839083829414372; weights[87] = 9.931699485728708623641928083854005419694814185558319778141847321184483041e-88; nodes[88] = 207.86943627130041812562189099885585473531405000526449455475688207393161551737116622832422616024890813073660725803140670339952916; weights[88] = 3.1053553239579890481762421032682587812743944959901074015948718558903851871e-90; nodes[89] = 213.81866588747906599964365905841239824586708817660404938686655435562268049827896300423468663374454070941434175332132588215595789; weights[89] = 8.3179165675054845287387715571935877933464576437495612595835503376801952752e-93; nodes[90] = 219.93126463824481934656458741152605898492069183830188564884652787334992066383331602668508727757007009006107025832617196693748796; weights[90] = 1.89347724710987662938673308300729940819812522625759427704149549835473232119e-95; nodes[91] = 226.216193265572531516717459091186107007311173581633366276120078885961856795072642041341726737507637859582613298178973678745479; weights[91] = 3.63069941618314733536515251833590920637600017972808067227165697803032625593e-98; nodes[92] = 232.6834568276049828701248962376420296093633836870069973168911472482663610189293743309344620931375815817091299306948191543525814; weights[92] = 5.80629424294854254371104860735978477288357832265977155400844875469684935528e-101; nodes[93] = 239.34428911239015707750708361757136738192117028756664187183316281754291106657616977096678914034056125259070443637761397256106056; weights[93] = 7.65865779579475617290329445234001466011021721785984711457172208590310097603e-104; nodes[94] = 246.2113821087152130663957889382098882294963511757506312418281009824595671974631806410155800658127132744409870603776732367795558; weights[94] = 8.227951647449214315287988168835483891223012643586966328161961290800203076565e-107; nodes[95] = 253.29917494920601240296732306193401011854205548870453382836192909408144805204835434724814290110091288604550489286613460294373397; weights[95] = 7.097532363428141011983902156081338695677872130772568563018201538725486235665e-110; nodes[96] = 260.62422258239401156037528567147060239493760235646533042293119632174771463893473381930652048449097306063455629672343424467848905; weights[96] = 4.835970784601994117221901044218795215544324009874219407770552585173817990837e-113; nodes[97] = 268.20567320609846388341553152641723830749223716789342746912719282955355501200087471126749672944543412189527330578298114468860267; weights[97] = 2.55383889912440232926328559056256751814837849310700742390102176215285577881076e-116; nodes[98] = 276.06589700502126408037531831296916899007565251191532051939635268438236390620171152256444000306490423265007191759926974540911799; weights[98] = 1.022421792643355988071978982033540059002794440345675903629252832446140120499654e-119; nodes[99] = 284.23133011989269081009783189440516454253784596484212514536510919075846616725137488833543385828801684113104875542222980916335479; weights[99] = 3.023060588468993679534805699076096271603057320944182749849007573086192974607229e-123; nodes[100] = 292.73363270891096548874879881274139800976913000566024967693534086629536624506570633735668826525821816378156016451918348546186199; weights[100] = 6.3982842404434646107616125116564279510757275958093094891637031271926859013960896e-127; nodes[101] = 301.6113191430372665612281773258951297732281428863879422402861886334735753513856172678610866696344057085648928223335249664042125; weights[101] = 9.3319398706453128326009188998156201430844911596647408941854611256071383555980977e-131; nodes[102] = 310.91212297488653567568381455938818109350477189207754205462036842575547806459902834191253555876509401893814624470873271159951048; weights[102] = 8.94807778137941109880064065254293599836293321548209517421999719172284920717918108e-135; nodes[103] = 320.69655368010540765392230069477415605690122569095682450602258373854246514210869375268285203510092609474651361752863210953813256; weights[103] = 5.314342016875394726203091576783295480726824835866752497657855582971746552595752899e-139; nodes[104] = 331.04348569945718846516642572010751802563238549499606799182766673778858517634842035952030178545923813017748076331925452832638306; weights[104] = 1.80895569336044199065884200645721811476268560010506117489437424513343589759886260648e-143; nodes[105] = 342.05943506555933730701753636255772314736433516163463265292988256255067321849876977408951159846814399487205822413426793434895572; weights[105] = 3.178477692747898739063910106421559535677306656935053385689903343498216725505425207143e-148; nodes[106] = 353.89507840294546247045030282818714589351150134371658722954725032870341718754613073143462496647960928938330800541160866583010249; weights[106] = 2.4869068610645663135880407981161141717688532194611462242085981666119459238521541067691e-153; nodes[107] = 366.77757024126442451610603398401068377733708721917746759806950275170173463853803198189762647023398162028720520036632642578698905; weights[107] = 6.93849550325189249603267205789243345430845184455456877275402042627517852412895581828055e-159; nodes[108] = 381.08278704341912059221476451529599276182939740298968965536116431423618061010624752727583112205558828525592014049526825327213286; weights[108] = 4.7858595317373836247627171810466969289372478500793623532545222563332025651339320881949197e-165; nodes[109] = 397.53402735270719877225350389319909944789353519327868583130443114583982579463263585324787487176126156890575496430875800501695668; weights[109] = 4.049132066547229031698575188210045860978633126317790883149265239209824264270001969629251713e-172; nodes[110] = 418.00612517597773526815917911591065455691148156787382230448819656160662568641349050992674057601261476030079783546257826022517922; weights[110] = 6.96731518007647204777269460785901780322544921338378635265675332896988007792831300987825539736e-181; } #endif /*(__Gauss_Laguerre_Nodes_and_Weights_111_hpp__)*/
mpl-2.0
Yukarumya/Yukarum-Redfoxes
extensions/auth/nsAuthSambaNTLM.cpp
9123
/* vim:set ts=4 sw=4 et cindent: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nsAuth.h" #include "nsAuthSambaNTLM.h" #include "prenv.h" #include "plbase64.h" #include "prerror.h" #include "mozilla/Telemetry.h" #include <stdlib.h> nsAuthSambaNTLM::nsAuthSambaNTLM() : mInitialMessage(nullptr), mChildPID(nullptr), mFromChildFD(nullptr), mToChildFD(nullptr) { } nsAuthSambaNTLM::~nsAuthSambaNTLM() { // ntlm_auth reads from stdin regularly so closing our file handles // should cause it to exit. Shutdown(); free(mInitialMessage); } void nsAuthSambaNTLM::Shutdown() { if (mFromChildFD) { PR_Close(mFromChildFD); mFromChildFD = nullptr; } if (mToChildFD) { PR_Close(mToChildFD); mToChildFD = nullptr; } if (mChildPID) { int32_t exitCode; PR_WaitProcess(mChildPID, &exitCode); mChildPID = nullptr; } } NS_IMPL_ISUPPORTS(nsAuthSambaNTLM, nsIAuthModule) static bool SpawnIOChild(char* const* aArgs, PRProcess** aPID, PRFileDesc** aFromChildFD, PRFileDesc** aToChildFD) { PRFileDesc* toChildPipeRead; PRFileDesc* toChildPipeWrite; if (PR_CreatePipe(&toChildPipeRead, &toChildPipeWrite) != PR_SUCCESS) return false; PR_SetFDInheritable(toChildPipeRead, true); PR_SetFDInheritable(toChildPipeWrite, false); PRFileDesc* fromChildPipeRead; PRFileDesc* fromChildPipeWrite; if (PR_CreatePipe(&fromChildPipeRead, &fromChildPipeWrite) != PR_SUCCESS) { PR_Close(toChildPipeRead); PR_Close(toChildPipeWrite); return false; } PR_SetFDInheritable(fromChildPipeRead, false); PR_SetFDInheritable(fromChildPipeWrite, true); PRProcessAttr* attr = PR_NewProcessAttr(); if (!attr) { PR_Close(fromChildPipeRead); PR_Close(fromChildPipeWrite); PR_Close(toChildPipeRead); PR_Close(toChildPipeWrite); return false; } PR_ProcessAttrSetStdioRedirect(attr, PR_StandardInput, toChildPipeRead); PR_ProcessAttrSetStdioRedirect(attr, PR_StandardOutput, fromChildPipeWrite); PRProcess* process = PR_CreateProcess(aArgs[0], aArgs, nullptr, attr); PR_DestroyProcessAttr(attr); PR_Close(fromChildPipeWrite); PR_Close(toChildPipeRead); if (!process) { LOG(("ntlm_auth exec failure [%d]", PR_GetError())); PR_Close(fromChildPipeRead); PR_Close(toChildPipeWrite); return false; } *aPID = process; *aFromChildFD = fromChildPipeRead; *aToChildFD = toChildPipeWrite; return true; } static bool WriteString(PRFileDesc* aFD, const nsACString& aString) { int32_t length = aString.Length(); const char* s = aString.BeginReading(); LOG(("Writing to ntlm_auth: %s", s)); while (length > 0) { int result = PR_Write(aFD, s, length); if (result <= 0) return false; s += result; length -= result; } return true; } static bool ReadLine(PRFileDesc* aFD, nsACString& aString) { // ntlm_auth is defined to only send one line in response to each of our // input lines. So this simple unbuffered strategy works as long as we // read the response immediately after sending one request. aString.Truncate(); for (;;) { char buf[1024]; int result = PR_Read(aFD, buf, sizeof(buf)); if (result <= 0) return false; aString.Append(buf, result); if (buf[result - 1] == '\n') { LOG(("Read from ntlm_auth: %s", nsPromiseFlatCString(aString).get())); return true; } } } /** * Returns a heap-allocated array of PRUint8s, and stores the length in aLen. * Returns nullptr if there's an error of any kind. */ static uint8_t* ExtractMessage(const nsACString& aLine, uint32_t* aLen) { // ntlm_auth sends blobs to us as base64-encoded strings after the "xx " // preamble on the response line. int32_t length = aLine.Length(); // The caller should verify there is a valid "xx " prefix and the line // is terminated with a \n NS_ASSERTION(length >= 4, "Line too short..."); const char* line = aLine.BeginReading(); const char* s = line + 3; length -= 4; // lose first 3 chars plus trailing \n NS_ASSERTION(s[length] == '\n', "aLine not newline-terminated"); if (length & 3) { // The base64 encoded block must be multiple of 4. If not, something // screwed up. NS_WARNING("Base64 encoded block should be a multiple of 4 chars"); return nullptr; } // Calculate the exact length. I wonder why there isn't a function for this // in plbase64. int32_t numEquals; for (numEquals = 0; numEquals < length; ++numEquals) { if (s[length - 1 - numEquals] != '=') break; } *aLen = (length/4)*3 - numEquals; return reinterpret_cast<uint8_t*>(PL_Base64Decode(s, length, nullptr)); } nsresult nsAuthSambaNTLM::SpawnNTLMAuthHelper() { const char* username = PR_GetEnv("USER"); if (!username) return NS_ERROR_FAILURE; const char* const args[] = { "ntlm_auth", "--helper-protocol", "ntlmssp-client-1", "--use-cached-creds", "--username", username, nullptr }; bool isOK = SpawnIOChild(const_cast<char* const*>(args), &mChildPID, &mFromChildFD, &mToChildFD); if (!isOK) return NS_ERROR_FAILURE; if (!WriteString(mToChildFD, NS_LITERAL_CSTRING("YR\n"))) return NS_ERROR_FAILURE; nsCString line; if (!ReadLine(mFromChildFD, line)) return NS_ERROR_FAILURE; if (!StringBeginsWith(line, NS_LITERAL_CSTRING("YR "))) { // Something went wrong. Perhaps no credentials are accessible. return NS_ERROR_FAILURE; } // It gave us an initial client-to-server request packet. Save that // because we'll need it later. mInitialMessage = ExtractMessage(line, &mInitialMessageLen); if (!mInitialMessage) return NS_ERROR_FAILURE; return NS_OK; } NS_IMETHODIMP nsAuthSambaNTLM::Init(const char *serviceName, uint32_t serviceFlags, const char16_t *domain, const char16_t *username, const char16_t *password) { NS_ASSERTION(!username && !domain && !password, "unexpected credentials"); static bool sTelemetrySent = false; if (!sTelemetrySent) { mozilla::Telemetry::Accumulate( mozilla::Telemetry::NTLM_MODULE_USED_2, serviceFlags & nsIAuthModule::REQ_PROXY_AUTH ? NTLM_MODULE_SAMBA_AUTH_PROXY : NTLM_MODULE_SAMBA_AUTH_DIRECT); sTelemetrySent = true; } return NS_OK; } NS_IMETHODIMP nsAuthSambaNTLM::GetNextToken(const void *inToken, uint32_t inTokenLen, void **outToken, uint32_t *outTokenLen) { if (!inToken) { /* someone wants our initial message */ *outToken = nsMemory::Clone(mInitialMessage, mInitialMessageLen); if (!*outToken) return NS_ERROR_OUT_OF_MEMORY; *outTokenLen = mInitialMessageLen; return NS_OK; } /* inToken must be a type 2 message. Get ntlm_auth to generate our response */ char* encoded = PL_Base64Encode(static_cast<const char*>(inToken), inTokenLen, nullptr); if (!encoded) return NS_ERROR_OUT_OF_MEMORY; nsCString request; request.AssignLiteral("TT "); request.Append(encoded); free(encoded); request.Append('\n'); if (!WriteString(mToChildFD, request)) return NS_ERROR_FAILURE; nsCString line; if (!ReadLine(mFromChildFD, line)) return NS_ERROR_FAILURE; if (!StringBeginsWith(line, NS_LITERAL_CSTRING("KK ")) && !StringBeginsWith(line, NS_LITERAL_CSTRING("AF "))) { // Something went wrong. Perhaps no credentials are accessible. return NS_ERROR_FAILURE; } uint8_t* buf = ExtractMessage(line, outTokenLen); if (!buf) return NS_ERROR_FAILURE; *outToken = nsMemory::Clone(buf, *outTokenLen); free(buf); if (!*outToken) { return NS_ERROR_OUT_OF_MEMORY; } // We're done. Close our file descriptors now and reap the helper // process. Shutdown(); return NS_SUCCESS_AUTH_FINISHED; } NS_IMETHODIMP nsAuthSambaNTLM::Unwrap(const void *inToken, uint32_t inTokenLen, void **outToken, uint32_t *outTokenLen) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsAuthSambaNTLM::Wrap(const void *inToken, uint32_t inTokenLen, bool confidential, void **outToken, uint32_t *outTokenLen) { return NS_ERROR_NOT_IMPLEMENTED; }
mpl-2.0