content
stringlengths
10
4.9M
Learning Temporal Plan Preferences from Examples: An Empirical Study Temporal plan preferences are natural and important in a variety of applications. Yet users often find it difficult to formalize their preferences. Here we explore the possibility to learn preferences from example plans. Focusing on one preference at a time, the user is asked to annotate examples as good/bad. We leverage prior work on LTL formula learning to extract a preference from these examples. We conduct an empirical study of this approach in an oversubscription planning context, using hidden target formulas to emulate the user preferences. We explore four different methods for generating example plans, and evaluate performance as a function of domain and formula size. Overall, we find that reasonable-size target formulas can often be learned effectively.
/* $Id: tstRTFileModeStringToFlags.cpp 69111 2017-10-17 14:26:02Z vboxsync $ */ /** @file * IPRT Testcase - File mode string to IPRT file mode flags. */ /* * Copyright (C) 2013-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ /********************************************************************************************************************************* * Header Files * *********************************************************************************************************************************/ #include <iprt/file.h> #include <iprt/stream.h> #include <iprt/string.h> #include <iprt/test.h> int main() { RTTEST hTest; int rc = RTTestInitAndCreate("tstRTStrVersion", &hTest); if (rc) return rc; RTTestBanner(hTest); RTTestSub(hTest, "RTFileModeToFlags"); static struct { int iResult; const char *pszMode; uint64_t uMode; } const aTests[] = { /* Invalid parameters. */ { VERR_INVALID_PARAMETER, "", 0 }, { VERR_INVALID_PARAMETER, "foo", 0 }, { VERR_INVALID_PARAMETER, "--", 0 }, { VERR_INVALID_PARAMETER, "++", 0 }, { VERR_INVALID_PARAMETER, "++", 0 }, /* Missing action. */ { VERR_INVALID_PARAMETER, "z", 0 }, /* Open for reading ("r"). */ { VINF_SUCCESS , "r", RTFILE_O_OPEN | RTFILE_O_READ }, { VINF_SUCCESS , "r+", RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "r+++", RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "+++r", RTFILE_O_OPEN | RTFILE_O_READ }, { VINF_SUCCESS , "r+t", RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "r+b", RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_WRITE }, /* Open / append ("a"). */ { VINF_SUCCESS , "a", RTFILE_O_OPEN_CREATE | RTFILE_O_WRITE | RTFILE_O_APPEND }, { VINF_SUCCESS , "a+", RTFILE_O_OPEN_CREATE | RTFILE_O_READ | RTFILE_O_WRITE | RTFILE_O_APPEND }, { VINF_SUCCESS , "a+++", RTFILE_O_OPEN_CREATE | RTFILE_O_READ | RTFILE_O_WRITE | RTFILE_O_APPEND }, { VINF_SUCCESS , "+++a", RTFILE_O_OPEN_CREATE | RTFILE_O_WRITE | RTFILE_O_APPEND }, { VINF_SUCCESS , "a+t", RTFILE_O_OPEN_CREATE | RTFILE_O_READ | RTFILE_O_WRITE | RTFILE_O_APPEND }, { VINF_SUCCESS , "a+b", RTFILE_O_OPEN_CREATE | RTFILE_O_READ | RTFILE_O_WRITE | RTFILE_O_APPEND }, /* Create / open ("c"). */ { VINF_SUCCESS , "c", RTFILE_O_OPEN_CREATE | RTFILE_O_WRITE }, { VINF_SUCCESS , "c+", RTFILE_O_OPEN_CREATE | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "c+++", RTFILE_O_OPEN_CREATE | RTFILE_O_READ | RTFILE_O_WRITE }, { VERR_INVALID_PARAMETER, "cr", 0 }, { VERR_INVALID_PARAMETER, "cr+", 0 }, /* Create / replace ("w"). */ { VINF_SUCCESS , "w", RTFILE_O_CREATE_REPLACE | RTFILE_O_WRITE | RTFILE_O_TRUNCATE }, { VERR_INVALID_PARAMETER, "ww", 0 }, { VERR_INVALID_PARAMETER, "wc", 0 }, { VINF_SUCCESS , "wb", RTFILE_O_CREATE_REPLACE | RTFILE_O_WRITE | RTFILE_O_TRUNCATE }, { VINF_SUCCESS , "wb+", RTFILE_O_CREATE_REPLACE | RTFILE_O_READ | RTFILE_O_WRITE | RTFILE_O_TRUNCATE }, { VINF_SUCCESS , "w+", RTFILE_O_CREATE_REPLACE | RTFILE_O_READ | RTFILE_O_WRITE | RTFILE_O_TRUNCATE }, { VINF_SUCCESS , "w++", RTFILE_O_CREATE_REPLACE | RTFILE_O_READ | RTFILE_O_WRITE | RTFILE_O_TRUNCATE }, /* Create only ("x"). */ { VINF_SUCCESS , "x", RTFILE_O_CREATE | RTFILE_O_WRITE }, { VERR_INVALID_PARAMETER, "xx", 0 }, { VERR_INVALID_PARAMETER, "xc", 0 }, { VINF_SUCCESS , "xb", RTFILE_O_CREATE | RTFILE_O_WRITE }, { VINF_SUCCESS , "xb+", RTFILE_O_CREATE | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "x+", RTFILE_O_CREATE | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "x++", RTFILE_O_CREATE | RTFILE_O_READ | RTFILE_O_WRITE } }; for (unsigned iTest = 0; iTest < RT_ELEMENTS(aTests); iTest++) { uint64_t uMode; int iResult = RTFileModeToFlags(aTests[iTest].pszMode, &uMode); if (iResult != aTests[iTest].iResult) { RTTestFailed(hTest, "#%u: mode string '%s', result is %Rrc, expected %Rrc", iTest, aTests[iTest].pszMode, iResult, aTests[iTest].iResult); break; } /** @todo Testing sharing modes are not implemented yet, * so just remove them from testing. */ uMode &= ~RTFILE_O_DENY_NONE; if ( RT_SUCCESS(iResult) && uMode != aTests[iTest].uMode) { RTTestFailed(hTest, "#%u: mode string '%s', got 0x%x, expected 0x%x", iTest, aTests[iTest].pszMode, uMode, aTests[iTest].uMode); break; } } RTTestSub(hTest, "RTFileModeToFlagsEx"); static struct { int iResult; const char *pszDisposition; const char *pszMode; /** @todo pszSharing not used yet. */ uint64_t uMode; } const aTestsEx[] = { /* Invalid parameters. */ { VERR_INVALID_PARAMETER, "", "", 0 }, { VERR_INVALID_PARAMETER, "foo", "", 0 }, { VERR_INVALID_PARAMETER, "--", "", 0 }, { VERR_INVALID_PARAMETER, "++", "", 0 }, { VERR_INVALID_PARAMETER, "++", "", 0 }, /* Missing action. */ { VERR_INVALID_PARAMETER, "z", "", 0 }, /* Open existing ("oe"). */ { VINF_SUCCESS , "oe", "r", RTFILE_O_OPEN | RTFILE_O_READ }, { VINF_SUCCESS , "oe", "w", RTFILE_O_OPEN | RTFILE_O_WRITE }, { VINF_SUCCESS , "oe", "rw", RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "oe", "rw+", RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "oe", "++r", RTFILE_O_OPEN | RTFILE_O_READ }, { VINF_SUCCESS , "oe", "r+t", RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "oe", "r+b", RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_WRITE }, /* Open / create ("oc"). */ { VINF_SUCCESS , "oc", "r", RTFILE_O_OPEN_CREATE | RTFILE_O_READ }, { VINF_SUCCESS , "oc", "r+", RTFILE_O_OPEN_CREATE | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "oc", "r+++", RTFILE_O_OPEN_CREATE | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "oc", "+++r", RTFILE_O_OPEN_CREATE | RTFILE_O_READ }, { VINF_SUCCESS , "oc", "w+t", RTFILE_O_OPEN_CREATE | RTFILE_O_WRITE | RTFILE_O_READ }, { VINF_SUCCESS , "oc", "w+b", RTFILE_O_OPEN_CREATE | RTFILE_O_WRITE | RTFILE_O_READ }, { VINF_SUCCESS , "oc", "w+t", RTFILE_O_OPEN_CREATE | RTFILE_O_WRITE | RTFILE_O_READ }, { VINF_SUCCESS , "oc", "wr", RTFILE_O_OPEN_CREATE | RTFILE_O_WRITE | RTFILE_O_READ }, { VINF_SUCCESS , "oc", "rw", RTFILE_O_OPEN_CREATE | RTFILE_O_WRITE | RTFILE_O_READ }, /* Open and truncate ("ot"). */ { VINF_SUCCESS , "ot", "r", RTFILE_O_OPEN | RTFILE_O_TRUNCATE | RTFILE_O_READ }, { VINF_SUCCESS , "ot", "r+", RTFILE_O_OPEN | RTFILE_O_TRUNCATE | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "ot", "r+++", RTFILE_O_OPEN | RTFILE_O_TRUNCATE | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "ot", "+++r", RTFILE_O_OPEN | RTFILE_O_TRUNCATE | RTFILE_O_READ }, { VINF_SUCCESS , "ot", "w+t", RTFILE_O_OPEN | RTFILE_O_TRUNCATE | RTFILE_O_WRITE | RTFILE_O_READ }, { VINF_SUCCESS , "ot", "w+b", RTFILE_O_OPEN | RTFILE_O_TRUNCATE | RTFILE_O_WRITE | RTFILE_O_READ }, { VINF_SUCCESS , "ot", "w+t", RTFILE_O_OPEN | RTFILE_O_TRUNCATE | RTFILE_O_WRITE | RTFILE_O_READ }, { VINF_SUCCESS , "ot", "wr", RTFILE_O_OPEN | RTFILE_O_TRUNCATE | RTFILE_O_WRITE | RTFILE_O_READ }, { VINF_SUCCESS , "ot", "rw", RTFILE_O_OPEN | RTFILE_O_TRUNCATE | RTFILE_O_WRITE | RTFILE_O_READ }, /* Create always ("ca"). */ { VINF_SUCCESS , "ca", "r", RTFILE_O_CREATE_REPLACE | RTFILE_O_READ }, { VINF_SUCCESS , "ca", "r+", RTFILE_O_CREATE_REPLACE | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "ca", "r+++", RTFILE_O_CREATE_REPLACE | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "ca", "+++r", RTFILE_O_CREATE_REPLACE | RTFILE_O_READ }, { VINF_SUCCESS , "ca", "w+t", RTFILE_O_CREATE_REPLACE | RTFILE_O_WRITE | RTFILE_O_READ }, { VINF_SUCCESS , "ca", "w+b", RTFILE_O_CREATE_REPLACE | RTFILE_O_WRITE | RTFILE_O_READ }, { VINF_SUCCESS , "ca", "w+t", RTFILE_O_CREATE_REPLACE | RTFILE_O_WRITE | RTFILE_O_READ }, { VINF_SUCCESS , "ca", "wr", RTFILE_O_CREATE_REPLACE | RTFILE_O_WRITE | RTFILE_O_READ }, { VINF_SUCCESS , "ca", "rw", RTFILE_O_CREATE_REPLACE | RTFILE_O_WRITE | RTFILE_O_READ }, /* Create if not exist ("ce"). */ { VINF_SUCCESS , "ce", "r", RTFILE_O_CREATE | RTFILE_O_READ }, { VINF_SUCCESS , "ce", "r+", RTFILE_O_CREATE | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "ce", "r+++", RTFILE_O_CREATE | RTFILE_O_READ | RTFILE_O_WRITE }, { VINF_SUCCESS , "ce", "+++r", RTFILE_O_CREATE | RTFILE_O_READ }, { VINF_SUCCESS , "ce", "w+t", RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_READ }, { VINF_SUCCESS , "ce", "w+b", RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_READ }, { VINF_SUCCESS , "ce", "w+t", RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_READ }, { VINF_SUCCESS , "ce", "wr", RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_READ }, { VINF_SUCCESS , "ce", "rw", RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_READ } }; for (unsigned iTest = 0; iTest < RT_ELEMENTS(aTestsEx); iTest++) { uint64_t uMode; int iResult = RTFileModeToFlagsEx(aTestsEx[iTest].pszMode, aTestsEx[iTest].pszDisposition, NULL /* pszSharing */, &uMode); if (iResult != aTestsEx[iTest].iResult) { RTTestFailed(hTest, "#%u: disp '%s', mode '%s', result is %Rrc, expected %Rrc", iTest, aTestsEx[iTest].pszDisposition, aTestsEx[iTest].pszMode, iResult, aTestsEx[iTest].iResult); break; } /** @todo Testing sharing modes are not implemented yet, * so just remove them from testing. */ uMode &= ~RTFILE_O_DENY_NONE; if ( RT_SUCCESS(iResult) && uMode != aTestsEx[iTest].uMode) { RTTestFailed(hTest, "#%u: disp '%s', mode '%s', got 0x%x, expected 0x%x", iTest, aTestsEx[iTest].pszDisposition, aTestsEx[iTest].pszMode, uMode, aTestsEx[iTest].uMode); break; } } /* * Summary. */ return RTTestSummaryAndDestroy(hTest); }
/** * Adding a node to the Same Level as other leaves else add it to the left most * * @param node {@link BinaryTreeNode} to insert */ public void add(BinaryTreeNode<T> node) { if (root == null) { root = node; return; } Queue<BinaryTreeNode<T>> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { BinaryTreeNode<T> temp = queue.peek(); queue.remove(); if (temp.left == null) { temp.left = node; break; } else { queue.add(temp.left); } if (temp.right == null) { temp.right = node; break; } else { queue.add(temp.right); } } }
/** * Creates a new instance from boundary ports. * Note that, the created instance will not be {@link #detach() detached}. * @param serialNumber the serial number * @param source the original flow graph * @param inputs the input ports of this block * @param outputs the output ports of this block * @param elements the elements of this block * @return the created instance * @throws IllegalArgumentException if the parameters are {@code null} */ public static FlowBlock fromPorts( int serialNumber, FlowGraph source, List<FlowElementInput> inputs, List<FlowElementOutput> outputs, Set<FlowElement> elements) { List<PortConnection> toInput = new ArrayList<>(); List<PortConnection> fromOutput = new ArrayList<>(); for (FlowElementInput in : inputs) { toInput.addAll(in.getConnected()); } for (FlowElementOutput out : outputs) { fromOutput.addAll(out.getConnected()); } return new FlowBlock(serialNumber, source, toInput, fromOutput, elements); }
def pp_fixture(request): dof = 6 np.random.seed(1) way_pts = np.random.randn(4, dof) * 0.6 N = 200 path = toppra.SplineInterpolator(np.linspace(0, 1, 4), way_pts) ss = np.linspace(0, 1, N + 1) vlim_ = np.random.rand(dof) * 10 + 10 vlim = np.vstack((-vlim_, vlim_)).T pc_vel = constraint.JointVelocityConstraint(vlim) alim_ = np.random.rand(dof) * 10 + 100 alim = np.vstack((-alim_, alim_)).T pc_acc = constraint.JointAccelerationConstraint(alim) pcs = [pc_vel, pc_acc] yield pcs, path, ss, vlim, alim print "\n [TearDown] Finish PP Fixture"
/* This slot is called when app is started. * It inits Kitchen objects so that food info * can be fetched according to the user selected Kitchen(s) * Sends a signal which indicates that kitchens are ready. */ void foodParser::parseInitData(const QByteArray &data) { QByteArray data2 = data; cleanJSON(data2, false); QJsonParseError err; QJsonDocument doc = QJsonDocument::fromJson(data2, &err); QJsonArray restaurants = doc.array(); foreach (const QJsonValue &value, restaurants) { QJsonObject obj = value.toObject(); QJsonArray menus = obj[QString("MenuTypes")].toArray(); foreach (const QJsonValue &subKitchen, menus) { Kitchen* kitchen = NULL; QJsonObject kitchenInfo = subKitchen.toObject(); QString name = kitchenInfo[QString("KitchenName")].toString().toUtf8() + QString(" - ") + kitchenInfo[QString("Name")].toString().toUtf8(); QString shortName; nameCompactor(name, shortName); kitchen = new Kitchen(kitchenInfo[QString("KitchenId")].toDouble(), kitchenInfo[QString("KitchenInfoId")].toDouble(), kitchenInfo[QString("OpenInfoId")].toDouble(), kitchenInfo[QString("MenuTypeId")].toDouble(), name, shortName); kitchens_.append(kitchen); name.clear(); } } emit initData(); }
/** * TWEnvironment * * @author michaellees Created: Apr 16, 2010 * * Copyright michaellees 2010 * * * Description: Contains the context of the environment and also creates * and removes objects at each time step. You don't need to modify this * but should look at the methods which may be helpful to you. * */ public class TWEnvironment extends SimState implements Steppable { //Parameters to configure the environment - read from main parameter file private final int xDimension = Parameters.xDimension; //size in cells private final int yDimension = Parameters.yDimension; /** * grid environment which stores all TWEntities, ObjectGrd is preferred over * SparseGrid. The environment is typically not too sparse and we do not * have multiple objects on the same cell. */ private ObjectGrid2D objectGrid; private ObjectGrid2D agentGrid; private TWObjectCreator<TWTile> tileCreator; private TWObjectCreator<TWHole> holeCreator; private TWObjectCreator<TWObstacle> obstacleCreator; /** * Assumed all objects have same lifeTime now. */ //containers for all objects in the environment private Bag tiles; private Bag holes; private Bag obstacles; private TWFuelStation fuelingStation; private ArrayList<Message> messages; // the communication channel private int reward; // private TWFuelStation getFuelingStation() { // return fuelingStation; // } public boolean inFuelStation(TWAgent agent) { return ((agent.x==fuelingStation.x)&&(agent.y==fuelingStation.y)); } public TWEnvironment() { this(ThreadLocalRandom.current().nextInt(1, Integer.MAX_VALUE)); } public TWEnvironment(long seed) { super(seed); // create object creation distributions (assumed normal for now) this.tileCreator = new TWObjectCreator<TWTile>(Parameters.tileMean, Parameters.tileDev, tiles, this.random, new TWTile(), this); this.holeCreator = new TWObjectCreator<TWHole>(Parameters.holeMean, Parameters.holeDev, holes, this.random, new TWHole(), this); this.obstacleCreator = new TWObjectCreator<TWObstacle>(Parameters.obstacleMean, Parameters.obstacleDev, obstacles, this.random, new TWObstacle(), this); tiles = new Bag(); holes = new Bag(); obstacles = new Bag(); reward = 0; messages = new ArrayList<Message>(); } @Override public void start() { super.start(); //create my grid this.objectGrid = new ObjectGrid2D(getxDimension(), getyDimension()); this.agentGrid = new ObjectGrid2D(getxDimension(), getyDimension()); if(TWGUI.instance!=null){ TWGUI.instance.resetDisplay(); } //The environment is also stepped each step schedule.scheduleRepeating(this, 1, 1.0); //Now we create some agents Int2D pos = this.generateRandomLocation(); createAgent(new TeamAgent1("agent1", pos.getX(), pos.getY(), this, Parameters.defaultFuelLevel)); pos = this.generateRandomLocation(); createAgent(new TeamAgent2("agent2", pos.getX(), pos.getY(), this, Parameters.defaultFuelLevel)); // //create the fueling station pos = this.generateRandomLocation(); fuelingStation = new TWFuelStation(pos.getX(), pos.getY(),this); } private void createTWObjects(double time) { try { tiles.addAll(tileCreator.createTWObjects(time)); holes.addAll(holeCreator.createTWObjects(time)); obstacles.addAll(obstacleCreator.createTWObjects(time)); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Horribly inefficient, Context is not ordered so need complete iteration of context to remove items. * This is done every timestep */ private void removeTWObjects(double timeNow) { for (int i = 0; i < tiles.size(); i++) { if (((TWObject) tiles.get(i)).getTimeLeft(timeNow) <= 0) { this.objectGrid.set(((TWObject) tiles.get(i)).getX(), ((TWObject) tiles.get(i)).getY(), null); tiles.remove(i); } } for (int i = 0; i < holes.size(); i++) { if (((TWObject) holes.get(i)).getTimeLeft(timeNow) <= 0) { this.objectGrid.set(((TWObject) holes.get(i)).getX(), ((TWObject) holes.get(i)).getY(), null); holes.remove(i); } } for (int i = 0; i < obstacles.size(); i++) { if (((TWObject) obstacles.get(i)).getTimeLeft(timeNow) <= 0) { this.objectGrid.set(((TWObject) obstacles.get(i)).getX(), ((TWObject) obstacles.get(i)).getY(), null); obstacles.remove(i); } } } public void step(SimState state) { double time = state.schedule.getTime(); // create new objects createTWObjects(time); // remove old objects (dead ones) removeTWObjects(time); messages.clear(); // clear the messages in every time step } public ArrayList<Message> getMessages(){ return messages; } public void receiveMessage(Message m){ messages.add(m); } /** * @return the grid */ public ObjectGrid2D getObjectGrid() { return objectGrid; } public ObjectGrid2D getAgentGrid() { return agentGrid; } /** * @return the xDimension */ public int getxDimension() { return xDimension; } /** * @return the yDimension */ public int getyDimension() { return yDimension; } public boolean isCellOccupied(int x, int y){ return (objectGrid.get(x, y) != null); } /** * returns true if the specified location contains a TWEntity. * @param x * @param y * @return */ public boolean isCellBlocked(int x, int y) { if(this.isValidLocation(x, y)){ TWEntity e = (TWEntity) objectGrid.get(x, y); return (e != null && (e instanceof TWObstacle)); }else{ return true; } } public boolean canPickupTile(TWTile tile, TWAgent agent) { if(!agent.sameLocation(tile)) return false; TWEntity e = (TWEntity) objectGrid.get(tile.x, tile.y); if(e == null||!(e instanceof TWTile)) return false; return true; } public boolean canPutdownTile(TWHole hole, TWAgent agent) { if(!agent.hasTile()) return false; if(!agent.sameLocation(hole)) return false; TWEntity e = (TWEntity) objectGrid.get(hole.x, hole.y); if(e == null||!(e instanceof TWHole)) return false; return true; } public boolean doesCellContainObject(int x, int y) { return !(objectGrid.get(x, y) == null); } /** * Returns the manhattan distance from this entity to a specified location. * * @param x1 x coordinate to check to * @param y1 y coordinate to check to * @return the manhattan distance from this entity to the coordinate x1,y1 */ public double getDistance(int x, int y, int x1, int y1) { return Math.abs(x1 - x) + Math.abs(y1 - y); } /** * returns true if b is closer to o than c is. * @param o * @param b * @param c * @return */ public boolean isCloser(TWEntity o, TWEntity b, TWEntity c) { return (o.getDistanceTo(b) < o.getDistanceTo(c)); } /** * picks a random location from the environment, used for free walk algorithm. * Bit stupid now, will be very slow when the environment fills up. * @param gx - this will be resulting x coordinate * @param gy */ public Int2D generateRandomLocation() { int gx = 1, gy = 1; while (!isValidCreationLocation( gx = this.random.nextInt(this.xDimension), gy = this.random.nextInt(this.yDimension))) { } return new Int2D(gx, gy); } /** * Generates a random free location at least minDistance away from x, y * * @param x * @param y * @param minDistance */ public Int2D generateFarRandomLocation(int x, int y, int minDistance) { int gx = 1, gy = 1; while (!isValidCreationLocation(gx = this.random.nextInt(this.xDimension), gy = this.random.nextInt(this.yDimension)) && this.getDistance(x, y, gx, gy) < minDistance) { } return new Int2D(gx, gy); } /** * Check if a given location is in the bounds of the environment * * @param x The x coordinate of the location to check * @param y The y coordinate of the location to check * @return True if the location is inside environment boundary */ public boolean isInBounds(int x, int y) { return !((x < 0) || (y < 0) || (x >= this.xDimension || y >= this.yDimension)); } /** * Check if a given location is valid for a move, both in bounds and not blocked * This is a cell which is in bounds and doesn't contain an obstacle. * * @param x The x coordinate of the location to check * @param y The y coordinate of the location to check * @return True if the location is valid */ public boolean isValidLocation(int x, int y) { return (isInBounds(x, y)); } /** * Different to is ValidLocation, returns true if the location contains no * objects at all * * @param x * @param y * @return */ public boolean isValidCreationLocation(int x, int y) { return (isInBounds(x, y) && !this.doesCellContainObject(x, y)); } /** * Creates and schedues a TWAgent. Also adds the agent to the portrayal if * a portrayal exists. * * Remember smaller ordering means it is executed earlier. * * * @param a */ private void createAgent(TWAgent a) { schedule.scheduleRepeating(new Steppable(){public void step(SimState state) {a.sense(); a.communicate();}}, 2, 1.0); schedule.scheduleRepeating(a, 3, 1.0); if(TWGUI.instance !=null){ TWGUI.instance.addMemoryPortrayal(a); } } public int getReward(){ return reward; } public void increaseReward(){ reward += 1; } }
// Partition takes a message and partition count and chooses a partition func (c *CBPartitioner) Partition(message *sarama.ProducerMessage, numPartitions int32) (partition int32, err error) { partition = c.counter.Inc() % numPartitions if c.allPenalized.Load() { log.Print("all partition are penalized") return } for ; c.penalty[partition] != nil; partition = c.counter.Inc() % numPartitions { } return }
MANILA, Philippines — The Department of Environment and Natural Resources (DENR) on Thursday ordered the closure of 21 mining firms after they were found to have severely destroyed the environment of the local communities where they are operating. Another five mining companies were suspended also for various violations. The mining audit of the DENR found that mining companies operating in Zambales, Homonhon in Samar, Dinagat Islands and Surigao del Norte should not have been allowed to mine because these were in functional watersheds. Zambales-based Benguet Corp., Eramen Minerals, LNL Archipelago Mining and Zambales Diversified Metals Corp. are to be closed because of siltation of rivers, illegal cutting of trees and destruction of watershed, DENR Secretary Gina Lopez at a televised news conference. Siltation is is a process of making waters polluted due to silt, or mineral particles. Lopez called the mining situation in Zambales “social injustice.” In Samar, another three mining companies were suspended by Lopez who showed pictures of murky waters and destroyed mountains as she explained the department’s order. These firms are Mt. Sinai Mining Exploration and Development Corp., Emir Minerals Corp. and TechIron Mineral Resources Inc. Lopez said that these companies caused the siltation of coastal waters and destruction of watersheds in their areas of operation. In Dinagat Islands, which has been a mineral reservation area since 1939, seven mining operations are up for closure due to various environmental violations. These are: AAMPhil Natural Resources Exploration, Kromico, Inc., SinoSteel Philippines H.Y. Mining Corporation, Oriental Synergy Mining Corporation, Wellex Mining Corporation, Libjo Mining Corporation and Oriental Vision Mining Philippines Corp. Lopez said that despite the presence of nine mining companies in Dinagat Islands, the province remains poor, belying claims of mining companies that they helped develop communities where they operated. Lopez said that as much as 82 percent of income derived from mining operations went to the companies themselves. The DENR chief also blamed the government for not developing the eco-tourism potentials of Dinagat Islands despite its beautiful environment. Seven mining companies are also up for closure in Surigao del Norte. These are ADNAMA Mining Resources Corp., Claver Mineral Development Corp., Platinum Development Corp., CTP Construction and Mining Corp., Carrascal Nickel Corp., Marcventures Mining and Development Corp. and Hinatuan Mining Corporation. Lopez also announced that the operations of four companies were suspended due to violations. They would be allowed to operate once these issues were addressed. Suspended are Oceana Gold Mining Operation in Nueva Vizcaya for causing reduced agriculture production of farmers in the area, Citnickel Mines and Development Corporation in Narra, Palawan for siltation of river and farm lands, Lepanto Mines and Development Corporation for leakage of mine tailings into the river and Ore Asia Mining and Development Corp for siltation of rivers. Lopez said the DENR is “fully aware” that many workers in the mines would be affected, but the welfare of the people in these areas was more important. She believes that stock market and GDP are not good indicators of economic development. Instead, what’s needed is area development, according to Lopez. “We can get rid of poverty” through area development, Lopez said.
/// \brief A stream which composes a non-owning view over a contiguous block of memory. class span_istream final : public components::span_stream_base<const std::byte>, public binary_io::istream_interface<span_istream> { private: using super = components::span_stream_base<const std::byte>; public: using super::super; \exception binary_io::buffer_exhausted Thrown when the buffer has less than the requested number of bytes. \param a_dst The buffer to read bytes into. void read_bytes(std::span<std::byte> a_dst); \brief Yields a no-copy view of `a_count` bytes from the underlying buffer. \exception binary_io::buffer_exhausted Thrown when the buffer has less than the requested number of bytes. \param a_count The number of bytes to be read. \return A view of the bytes read. [[nodiscard]] auto read_bytes(std::size_t a_count) -> std::span<const std::byte>; @} }
def should_call_prophecy(self, attribute_prophecy: AttributeProphecy): self.__mock_object._prophecies_to_call.append(attribute_prophecy)
/** * Populate child nodes for a single branch of the tree, and indicates * whether further expansion (to grandchildren) is possible. */ protected void addChildren(TreeItem ti, LexBIGService lbsvc, LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, String branchRootCode, Set<String> codesToExclude, String[] associationsToNavigate, boolean associationsNavigatedFwd) throws LBException { CodedNodeGraph cng = lbsvc.getNodeGraph(scheme, csvt, null); Boolean restrictToAnonymous = Boolean.FALSE; cng = cng.restrictToAnonymous(restrictToAnonymous); ConceptReference focus = Constructors.createConceptReference(branchRootCode, scheme); cng = cng.restrictToAssociations(Constructors .createNameAndValueList(associationsToNavigate), null); ResolvedConceptReferenceList branch = cng.resolveAsList(focus, associationsNavigatedFwd, !associationsNavigatedFwd, -1, 2, _noopList, null, null, null, -1, false); for (Iterator<? extends ResolvedConceptReference> nodes = branch.iterateResolvedConceptReference(); nodes.hasNext();) { ResolvedConceptReference node = nodes.next(); AssociationList childAssociationList = associationsNavigatedFwd ? node.getSourceOf() : node .getTargetOf(); if (childAssociationList == null) return; for (Iterator<? extends Association> pathsToChildren = childAssociationList.iterateAssociation(); pathsToChildren .hasNext();) { Association child = pathsToChildren.next(); String childNavText = getDirectionalLabel(lbscm, scheme, csvt, child, associationsNavigatedFwd); AssociatedConceptList branchItemList = child.getAssociatedConcepts(); for (Iterator<? extends AssociatedConcept> branchNodes = branchItemList.iterateAssociatedConcept(); branchNodes .hasNext();) { AssociatedConcept branchItemNode = branchNodes.next(); String branchItemCode = branchItemNode.getConceptCode(); if (!branchItemCode.startsWith("@")) { if (!codesToExclude.contains(branchItemCode)) { TreeItem childItem = new TreeItem(branchItemCode, getCodeDescription(branchItemNode)); AssociationList grandchildBranch = associationsNavigatedFwd ? branchItemNode .getSourceOf() : branchItemNode .getTargetOf(); if (grandchildBranch != null) childItem._expandable = true; ti.addChild(childNavText, childItem); } } } } } }
def export_data(self, phases=[], filename=None, filetype=None): import builtins project = self network = self.network if filename is None: filename = project.name + '_' + time.strftime('%Y%b%d_%H%M%p') if filetype is None: if '.' in filename: filetype = filename.split('.')[-1] temp = {"hdf": "hdf5", "xmf": "xdmf", "vtp": "vtk", "pkl": "pickle"} if filetype in temp.keys(): filetype = temp[filetype] else: raise Exception('File type not given') def igetattr(obj, attr): for a in dir(obj): if a.lower() == attr.lower(): return orig_getattr(obj, a) orig_getattr = builtins.getattr fmt = igetattr(openpnm.io, filetype) fmt.export_data(network=network, phases=phases, filename=filename)
TREATMENT OF FOUR INDUSTRIAL WASTEWATERS BY SEQUENCING BATCH REACTORS: EVALUATION OF COD, TKN AND TP REMOVAL Abstract This study investigated the ability of a sequencing batch reactor (SBR) system to treat four industrial wastewaters, namely, textile, landfill leachate, seafood and slaughterhouse effluents. The system employed three identical SBRs (10 l volume each) operating in parallel and each waste was treated one at a time. The operational variables examined included the length of the non‐aerated period and the solids retention time (SRT). All four wastewaters experienced chemical oxyfen demand (COD) and total kjeldhal nitrogen (TKN) removals greater than 81%, while the TP removals were lower, ranging from 57 to 94%. The length of the non‐aerated period appeared to have minimal effect on the SBR performance; however, increases in SRT reduced the percent TP removal for the textile and leachate wastes only. In addition, to investigate organic loading limits to the seafood SBR system, the COD was increased by three increments of 250 mg l−1 starting from a baseline concentration of 1100 mg l−1. This resulted in a reduction in both the TKN and TP removal at the higher concentrations. Finally, for the slaughterhouse wastewater, the COD:TKN ratio was tested at levels of 6:1, 8:1 and 9:1 with the result that only the TP removal was affected at the lowest ratio.
def burst(time_now): global firework_step_time, burst_count, shower_count log("burst %d" % (burst_count)) if burst_count == 0: strip.brightness = 0.0 strip.fill(firework_color) elif burst_count == 22: shower_count = 0 firework_step_time = time_now + 0.3 return True if time_now < firework_step_time: return False elif burst_count < 11: strip.brightness = burst_count / 10.0 firework_step_time = time_now + 0.08 elif burst_count == 11: firework_step_time = time_now + 0.3 elif burst_count > 11: strip.brightness = 1.0 - ((burst_count - 11) / 10.0) firework_step_time = time_now + 0.08 strip.show() burst_count += 1 return False
#define NDEBUG #include <bits/stdc++.h> using namespace std; #ifdef NDEBUG # define debug(...) #else # include "debug.hh" #endif int static_init = []() { ios_base::sync_with_stdio(false), cin.tie(0), cout << fixed; return 0; }(); int cnt[26]; bool smallest(char c) { for (int i = c-'a'-1; i >= 0; i--) { if (cnt[i] > 0) return false; } return true; } int main() { string s, t, u; cin >> s; for (char c: s) cnt[c-'a']++; for (char c: s) { t += c; cnt[c-'a']--; while (!t.empty() && smallest(t.back())) u += t.back(), t.pop_back(); } u.append(t.rbegin(), t.rend()); cout << u << endl; return 0; }
pub fn show_menu() { for i in 0..42 { print!("="); } print!(" 2048 Game "); for i in 0..42 { print!("="); } println!("\n"); } pub fn request_name() -> String { use std::io; println!("Please key in your name: "); let mut name = String::new(); io::stdin().read_line(&mut name) .ok() .expect("Failed to read name"); println!("\nWelcome, {}", name); name.to_string() } pub fn get_instruction() -> String { use std::io; show_instruction(); let mut instruction = String::new(); io::stdin().read_line(&mut instruction) .ok() .expect("Failed to read instruction"); instruction.to_string() } fn show_instruction() { println!("Instruction: "); println!("8 to move up"); println!("2 to move down"); println!("4 to move left"); println!("6 to move right"); }
//! Test runner. //! //! This module implements the `TestRunner` struct which manages executing tests as well as //! scanning directories for tests. use crate::concurrent::{ConcurrentRunner, Reply}; use crate::runone; use std::error::Error; use std::ffi::OsStr; use std::fmt::{self, Display}; use std::path::{Path, PathBuf}; use std::time; /// Timeout in seconds when we're not making progress. const TIMEOUT_PANIC: usize = 60; /// Timeout for reporting slow tests without panicking. const TIMEOUT_SLOW: usize = 3; struct QueueEntry { path: PathBuf, state: State, } #[derive(Debug)] enum State { New, Queued, Running, Done(anyhow::Result<time::Duration>), } #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub enum IsPass { Pass, NotPass, } impl QueueEntry { pub fn path(&self) -> &Path { self.path.as_path() } } impl Display for QueueEntry { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let p = self.path.to_string_lossy(); match self.state { State::Done(Ok(dur)) => write!(f, "{}.{:03} {}", dur.as_secs(), dur.subsec_millis(), p), State::Done(Err(ref e)) => write!(f, "FAIL {}: {:?}", p, e), _ => write!(f, "{}", p), } } } pub struct TestRunner { verbose: bool, // Should we print the timings out? report_times: bool, // Directories that have not yet been scanned. dir_stack: Vec<PathBuf>, // Filenames of tests to run. tests: Vec<QueueEntry>, // Pointer into `tests` where the `New` entries begin. new_tests: usize, // Number of contiguous reported tests at the front of `tests`. reported_tests: usize, // Number of errors seen so far. errors: usize, // Number of ticks received since we saw any progress. ticks_since_progress: usize, threads: Option<ConcurrentRunner>, } impl TestRunner { /// Create a new blank TestRunner. pub fn new(verbose: bool, report_times: bool) -> Self { Self { verbose, report_times, dir_stack: Vec::new(), tests: Vec::new(), new_tests: 0, reported_tests: 0, errors: 0, ticks_since_progress: 0, threads: None, } } /// Add a directory path to be scanned later. /// /// If `dir` turns out to be a regular file, it is silently ignored. /// Otherwise, any problems reading the directory are reported. pub fn push_dir<P: Into<PathBuf>>(&mut self, dir: P) { self.dir_stack.push(dir.into()); } /// Add a test to be executed later. /// /// Any problems reading `file` as a test case file will be reported as a test failure. pub fn push_test<P: Into<PathBuf>>(&mut self, file: P) { self.tests.push(QueueEntry { path: file.into(), state: State::New, }); } /// Begin running tests concurrently. pub fn start_threads(&mut self) { assert!(self.threads.is_none()); self.threads = Some(ConcurrentRunner::new()); } /// Scan any directories pushed so far. /// Push any potential test cases found. pub fn scan_dirs(&mut self, pass_status: IsPass) { // This recursive search tries to minimize statting in a directory hierarchy containing // mostly test cases. // // - Directory entries with a "clif" or "wat" extension are presumed to be test case files. // - Directory entries with no extension are presumed to be subdirectories. // - Anything else is ignored. // while let Some(dir) = self.dir_stack.pop() { match dir.read_dir() { Err(err) => { // Fail silently if `dir` was actually a regular file. // This lets us skip spurious extensionless files without statting everything // needlessly. if !dir.is_file() { self.path_error(&dir, &err); } } Ok(entries) => { // Read all directory entries. Avoid statting. for entry_result in entries { match entry_result { Err(err) => { // Not sure why this would happen. `read_dir` succeeds, but there's // a problem with an entry. I/O error during a getdirentries // syscall seems to be the reason. The implementation in // libstd/sys/unix/fs.rs seems to suggest that breaking now would // be a good idea, or the iterator could keep returning the same // error forever. self.path_error(&dir, &err); break; } Ok(entry) => { let path = entry.path(); // Recognize directories and tests by extension. // Yes, this means we ignore directories with '.' in their name. match path.extension().and_then(OsStr::to_str) { Some("clif" | "wat") => self.push_test(path), Some(_) => {} None => self.push_dir(path), } } } } } } if pass_status == IsPass::Pass { continue; } else { // Get the new jobs running before moving on to the next directory. self.schedule_jobs(); } } } /// Report an error related to a path. fn path_error<E: Error>(&mut self, path: &PathBuf, err: &E) { self.errors += 1; println!("{}: {}", path.to_string_lossy(), err); } /// Report on the next in-order job, if it's done. fn report_job(&self) -> bool { let jobid = self.reported_tests; if let Some(&QueueEntry { state: State::Done(ref result), .. }) = self.tests.get(jobid) { if self.verbose || result.is_err() { println!("{}", self.tests[jobid]); } true } else { false } } /// Schedule any new jobs to run. fn schedule_jobs(&mut self) { for jobid in self.new_tests..self.tests.len() { assert!(matches!(self.tests[jobid].state, State::New)); if let Some(ref mut conc) = self.threads { // Queue test for concurrent execution. self.tests[jobid].state = State::Queued; conc.put(jobid, self.tests[jobid].path()); } else { // Run test synchronously. self.tests[jobid].state = State::Running; let result = runone::run(self.tests[jobid].path(), None, None); self.finish_job(jobid, result); } self.new_tests = jobid + 1; } // Check for any asynchronous replies without blocking. while let Some(reply) = self.threads.as_mut().and_then(ConcurrentRunner::try_get) { self.handle_reply(reply); } } /// Schedule any new job to run for the pass command. fn schedule_pass_job(&mut self, passes: &[String], target: &str) { self.tests[0].state = State::Running; let result: anyhow::Result<time::Duration>; let specified_target = match target { "" => None, targ => Some(targ), }; result = runone::run(self.tests[0].path(), Some(passes), specified_target); self.finish_job(0, result); } /// Report the end of a job. fn finish_job(&mut self, jobid: usize, result: anyhow::Result<time::Duration>) { assert!(matches!(self.tests[jobid].state, State::Running)); if result.is_err() { self.errors += 1; } self.tests[jobid].state = State::Done(result); // Reports jobs in order. while self.report_job() { self.reported_tests += 1; } } /// Handle a reply from the async threads. fn handle_reply(&mut self, reply: Reply) { match reply { Reply::Starting { jobid, .. } => { assert!(matches!(self.tests[jobid].state, State::Queued)); self.tests[jobid].state = State::Running; } Reply::Done { jobid, result } => { self.ticks_since_progress = 0; self.finish_job(jobid, result) } Reply::Tick => { self.ticks_since_progress += 1; if self.ticks_since_progress == TIMEOUT_SLOW { println!( "STALLED for {} seconds with {}/{} tests finished", self.ticks_since_progress, self.reported_tests, self.tests.len() ); for jobid in self.reported_tests..self.tests.len() { if let State::Running = self.tests[jobid].state { println!("slow: {}", self.tests[jobid]); } } } if self.ticks_since_progress >= TIMEOUT_PANIC { panic!( "worker threads stalled for {} seconds.", self.ticks_since_progress ); } } } } /// Drain the async jobs and shut down the threads. fn drain_threads(&mut self) { if let Some(mut conc) = self.threads.take() { conc.shutdown(); while self.reported_tests < self.tests.len() { match conc.get() { Some(reply) => self.handle_reply(reply), None => break, } } let pass_times = conc.join(); if self.report_times { println!("{}", pass_times); } } } /// Print out a report of slow tests. fn report_slow_tests(&self) { // Collect runtimes of succeeded tests. let mut times = self .tests .iter() .filter_map(|entry| match *entry { QueueEntry { state: State::Done(Ok(dur)), .. } => Some(dur), _ => None, }) .collect::<Vec<_>>(); // Get me some real data, kid. let len = times.len(); if len < 4 { return; } // Compute quartiles. times.sort(); let qlen = len / 4; let q1 = times[qlen]; let q3 = times[len - 1 - qlen]; // Inter-quartile range. let iqr = q3 - q1; // Cut-off for what we consider a 'slow' test: 3 IQR from the 75% quartile. // // Q3 + 1.5 IQR are the data points that would be plotted as outliers outside a box plot, // but we have a wider distribution of test times, so double it to 3 IQR. let cut = q3 + iqr * 3; if cut > *times.last().unwrap() { return; } for t in self.tests.iter().filter(|entry| match **entry { QueueEntry { state: State::Done(Ok(dur)), .. } => dur > cut, _ => false, }) { println!("slow: {}", t) } } /// Scan pushed directories for tests and run them. pub fn run(&mut self) -> anyhow::Result<()> { self.scan_dirs(IsPass::NotPass); self.schedule_jobs(); self.report_slow_tests(); self.drain_threads(); println!("{} tests", self.tests.len()); match self.errors { 0 => Ok(()), 1 => anyhow::bail!("1 failure"), n => anyhow::bail!("{} failures", n), } } /// Scan pushed directories for tests and run specified passes from commandline on them. pub fn run_passes(&mut self, passes: &[String], target: &str) -> anyhow::Result<()> { self.scan_dirs(IsPass::Pass); self.schedule_pass_job(passes, target); self.report_slow_tests(); self.drain_threads(); println!("{} tests", self.tests.len()); match self.errors { 0 => Ok(()), 1 => anyhow::bail!("1 failure"), n => anyhow::bail!("{} failures", n), } } }
/** * * * @author <a href="[email protected]">Ryan J. McDonough</a> * @version $Revision: 1.1 $ */ public class TestTwitterSearchApi extends AbstractExampleTest { private static final String SEARCH_BASE = "http://search.twitter.com/search.{format}"; private static final String SEARCH_PARAMS = "{?q,callback,geocode,lang,locale,page,result_type,rpp,show_user,until,since_id,max_id,include_entities,result_type}"; /** * Check to make sure that search.twitter.com is reachable * * @throws Exception */ @BeforeClass public static void setUp() throws Exception { try { Assume.assumeTrue(InetAddress.getByName("search.twitter.com").isReachable(1000)); } catch (UnknownHostException e) { Assume.assumeFalse(true); } } /** * * * @throws Exception */ @Test public void testSearch() throws Exception { RequestBuilder builder = new RequestBuilder("GET"); String uri = UriTemplate.buildFromTemplate(SEARCH_BASE) .literal(SEARCH_PARAMS) .build() .set("format", "json") .set("q", "URI Templates") .set("rpp", "5") .set("include_entities", true) .set("result_type", "mixed") .expand(); Request request = builder.setUrl(uri).build(); Assert.assertEquals("http://search.twitter.com/search.json?q=URI%20Templates&result_type=mixed&rpp=5&include_entities=true&result_type=mixed", uri); executeRequest(createClient(), request); } }
/** * @author Gabriel Francisco - [email protected] */ @ApplicationScoped public class ListenerRegister { @Inject @JmsListener(destination = "") private Instance<MessageListener> messageListeners; @Inject @Any private Instance<ExceptionListener> exceptionListeners; @Inject @JmsContext private ConnectionFactory connectionFactory; @Inject @JmsContext private InitialContext initialContext; public void register() throws NamingException, JMSException { for (MessageListener messageListener : messageListeners) { JmsListener jmsListener = messageListener.getClass().getAnnotation(JmsListener.class); if(jmsListener == null){ jmsListener = messageListener.getClass().getSuperclass().getAnnotation(JmsListener.class); } final Destination destination = (Destination) initialContext.lookup(jmsListener.destination()); Connection connection = connectionFactory.createConnection(); if(!jmsListener.exceptionListener().equals(ExceptionListener.class)){ connection.setExceptionListener(exceptionListeners.select(jmsListener.exceptionListener()).get()); } final Session session = connection.createSession(false, jmsListener.session().value); final MessageConsumer consumer = session.createConsumer(destination); consumer.setMessageListener(messageListener); connection.start(); } } @Override public String toString() { return "ListenerRegister{" + "messageListeners=" + messageListeners + ", exceptionListeners=" + exceptionListeners + ", connectionFactory=" + connectionFactory + ", initialContext=" + initialContext + '}'; } }
// Retry enables retryable writes for this operation. Retries are not handled automatically, // instead a boolean is returned from Execute and SelectAndExecute that indicates if the // operation can be retried. Retrying is handled by calling RetryExecute. func (at *AbortTransaction) Retry(retry driver.RetryMode) *AbortTransaction { if at == nil { at = new(AbortTransaction) } at.retry = &retry return at }
SAN JOSE, Calif. – With more than 11 MLS seasons under his belt as a head coach, San Jose Earthquakes boss Dominic Kinnear is too wily to fall for the “name your best XI” game. “You never want to look and go, ‘Well, if my team was fully healthy and nobody was called away, this is what we would be,’” Kinnear said. “I don’t think you should ever plan for that because it’s hardly ever the case.” With that being said, the Earthquakes – finally at full strength along their backline after early-season injuries – are using what appears to be their first-choice foursome of defenders: Jordan Stewart, Clarence Goodson, Victor Bernardez and Marvell Wynne. Certainly, the recent performances have been positive. Those four players in front of goalkeeper David Bingham have limited opponents to one goal or less in each of the last three matches. “I think we have limited opportunities, which is great,” Goodson told reporters Tuesday. “Really, look at any chances that have come up during the little run we’re on, and I think it’s kind of been our own errors, our own mistakes – [such as] giving the ball away in some difficult positions. ... But yeah, all in all, I think we’ve done pretty well.” That fits the expectations of a highly experienced group. Three of the quartet are 33, with Wynne the outlier at 29. Bernardez and Goodson boast World Cup experience (for Honduras and the US national team, respectively), while Stewart has previously played in the English Premier League and Wynne has racked up nearly 250 MLS appearances. Of course, even a veteran and savvy back line can have its momentary lapses, which is part of how 10-man Orlando got their goal in Sunday's 1-1 draw. A long pass from a free kick inside Orlando’s half bounced just inside San Jose’s penalty area with Bernardez and Orlando forward Cyle Larin in hot pursuit. Coming the other way was far-ranging goalkeeper Bingham, who missed the ball but struck Larin, giving the Lions a spot kick -- and the Quakes a bit of heartburn at undoing their good work to that point. Get more San Jose Earthquakes news at SJEarthquakes.com “We, as a back four, need to be a little more tuned in at that moment,” Goodson said. “It didn’t look like they were ever going to score. It was going to take something – maybe a set piece or something a little bit fluky, and it was a set piece, in the end, that beat us. “It’s kind of a situation where the communication lets us down for a very short period of time, but it cost us in the end.” The sense that the Quakes are setting up opponents – despite sitting tied for fifth in the league with a 1.00 goals-against average – helps explain why Goodson feels like there’s still room to get better as San Jose chase their first playoff berth since crashing out of the 2012 postseason following a Supporters’ Shield-winning campaign. “Certainly, there’s room for improvement,” Goodson said. “You don’t want to peak 12 games in. You want to keep improving. The summer is difficult in MLS, with the travel, and we want to continue on this stretch and in this form for as long as possible. It’s almost inevitable that there’ll be a little dropoff, but we have to make sure that isn’t in the next game.”
<reponame>Jaylen0829/tornado-RESTfulAPI<filename>apps/public/models.py from base.models import BaseModel from peewee import *
def read_bytes_aligned(self, number_of_bytes): self.number_of_bits -= (self.number_of_bits % 8) return bytearray(self.read_bits(8 * number_of_bytes))
<gh_stars>1-10 import json from flask import request import werkzeug class RESTResource(object): """Represents a REST resource, with the different HTTP verbs""" _NEED_ID = ["get", "update", "delete"] _VERBS = {"get": "GET", "update": "PUT", "delete": "DELETE", "list": "GET", "add": "POST",} def __init__(self, name, route, app, handler, authentifier=None, actions=None, inject_name=None): """ :name: name of the resource. This is being used when registering the route, for its name and for the name of the id parameter that will be passed to the views :route: Default route for this resource :app: Application to register the routes onto :actions: Authorized actions. Optional. None means all. :handler: The handler instance which will handle the requests :authentifier: callable checking the authentication. If specified, all the methods will be checked against it. """ if not actions: actions = self._VERBS.keys() self._route = route self._handler = handler self._name = name self._identifier = "%s_id" % name self._authentifier = authentifier self._inject_name = inject_name # FIXME for action in actions: self.add_url_rule(app, action) def _get_route_for(self, action): """Return the complete URL for this action. Basically: - get, update and delete need an id - add and list does not """ route = self._route if action in self._NEED_ID: route += "/<%s>" % self._identifier return route def add_url_rule(self, app, action): """Registers a new url to the given application, regarding the action. """ method = getattr(self._handler, action) # decorate the view if self._authentifier: method = need_auth(self._authentifier, self._inject_name or self._name)(method) method = serialize(method) app.add_url_rule( self._get_route_for(action), "%s_%s" % (self._name, action), method, methods=[self._VERBS.get(action, "GET")]) def need_auth(authentifier, name=None, remove_attr=True): """Decorator checking that the authentifier does not returns false in the current context. If the request is authorized, the object returned by the authentifier is added to the kwargs of the method. If not, issue a 401 Unauthorized error :authentifier: The callable to check the context onto. :name: **Optional**, name of the argument to put the object into. If it is not provided, nothing will be added to the kwargs of the decorated function :remove_attr: Remove or not the `*name*_id` from the kwargs before calling the function """ def wrapper(func): def wrapped(*args, **kwargs): result = authentifier(*args, **kwargs) if result: if name: kwargs[name] = result if remove_attr: del kwargs["%s_id" % name] return func(*args, **kwargs) else: return 401, "Unauthorized" return wrapped return wrapper # serializers def serialize(func): """If the object returned by the view is not already a Response, serialize it using the ACCEPT header and return it. """ def wrapped(*args, **kwargs): # get the mimetype mime = request.accept_mimetypes.best_match(SERIALIZERS.keys()) or "application/json" data = func(*args, **kwargs) serializer = SERIALIZERS[mime] status = 200 if len(data) == 2: status, data = data # serialize it return werkzeug.Response(serializer.encode(data), status=status, mimetype=mime) return wrapped class JSONEncoder(json.JSONEncoder): """Subclass of the default encoder to support custom objects""" def default(self, o): if hasattr(o, "_to_serialize"): # build up the object data = {} for attr in o._to_serialize: data[attr] = getattr(o, attr) return data elif hasattr(o, "isoformat"): return o.isoformat() else: try: from flask_babel import speaklater if isinstance(o, speaklater.LazyString): try: return unicode(o) # For python 2. except NameError: return str(o) # For python 3. except ImportError: pass return json.JSONEncoder.default(self, o) SERIALIZERS = {"application/json": JSONEncoder(), "text/json": JSONEncoder()}
import { OnInit } from '@angular/core'; import { DataTable } from './DataTable'; export declare class DefaultSorter implements OnInit { private svTable; sortBy: string; isSortedByMeAsc: boolean; isSortedByMeDesc: boolean; constructor(svTable: DataTable); ngOnInit(): void; sort(): void; }
Copyright (C) 2010 by R. Winston Guthrie Photographs copyright (C) 2010 by Liza Gershman All rights reserved. Published in the United States by Clarkson Potter/Publishers, an imprint of the Crown Publishing Group, a division of Random House, Inc., New York. www.crownpublishing.com www.clarksonpotter.com CLARKSON POTTER is a trademark and POTTER with colophon is a registered trademark of Random House, Inc. Library of Congress Cataloging-in-Publication Data Guthrie, R. Winston. A taste for absinthe / R. Winston Guthrie, with James F. Thompson, and Liza Gershman.--1st ed. Includes index. 1. Cocktails. 2. Absinthe. I. Thompson, James F. II. Gershman, Liza. III. Title. TX951.G845 2010 641.8'74--dc22 2009045578 eISBN: 978-0-7704-3431-1 v3.1 Previous image: Erika Fey created the Heart Grows Fonder Following image: Death + Company's Brian Miller created the North by Northwest TO MEREDITH, MY WIFE & BEST FRIEND --who keeps me looking up at the stars # I WOULD LIKE TO GIVE SPECIAL THANKS TO ALL THE WONDERFUL & TALENTED PEOPLE WHO CONTRIBUTED TO OR INFLUENCED THIS BOOK: Absinthe experts and friends John Troia and Peter Schaf (owners of Tempus Fugit Spirits and Vieux Pontarlier Absinthe) were insightful, generous with resources and contacts, and always ready to help. On the forefront of the absinthe renaissance in America, they were also generous with their time and knowledge. Thanks to Jeff Hollinger for broadening the scope of the book. Special thanks to Scott Baird and Tim Stookey. Thanks to all of the other bartenders who made recipes specifically for this project. Thanks to Liza Gershman, who was instrumental in conceptualizing much of the book as she went above and beyond the role of photographer. Thanks to Andrea Somberg, Jim Thompson, Ashley Phillips, Rosy Ngo, Laura Palese, and Amy Sly for their dedication to the project and belief that Absinthe has something to offer everyone in America. Special thanks to the absinthe community and all those in search of the Green Fairy. Enjoy your journey... FOREWORD INTRODUCTION ABSINTHE PRIMER [• 1 • ABSINTHE CLASSICS](Guth_9780770434311_epub_c01_r1.htm) From the traditional drip to time-tested classics, enjoy absinthe recipes that have survived the past hundred years or more. [• 2 • FRUIT & CITRUS](Guth_9780770434311_epub_c02_r1.htm) Recipes that blend absinthe's unique taste with the influences of lemons, oranges, and other colorful and refreshing fruit combinations. [• 3 • WHISKEY & GIN](Guth_9780770434311_epub_c03_r1.htm) From Tennessee whiskeys to your grandmother's gin, learn how to mix absinthe with established American sensibilities. [• 4 • LIQUEURS & BITTERS](Guth_9780770434311_epub_c04_r1.htm) Complement absinthe with a breath of sweetness or a bite of bitter with recipes that mix the Green Fairy with tasty flavors. [• 5 • MODERN CLASSICS & CUTTING EDGE](Guth_9780770434311_epub_c05_r1.htm) Learn how to make the most avant-garde and ingenious absinthe drinks concocted by the world's most innovative and accomplished absinthe experts. ABSINTHE BUYING GUIDE CONTRIBUTORS INDEX Absinthe's rise and fall is a colorful story that has been chronicled before, but the romance and mystery of the "Green Fairy" hasn't been fully captured until now. A Taste for Absinthe explores its history in the Old World and in American cocktails and breaks new ground with dozens of inventive cocktail recipes. Throughout the nineteenth century, absinthe became the most popular and widely consumed spirit in Europe. Yet by the end of the same century, several countries had banned the drink, labeling it as highly addictive and poisonous. The unfolding story of its rebirth resulting from the easing of official bans around the globe comes alive in sidebars that accompany the recipes. But the real strength of A Taste for Absinthe lies in the collection of amazing recipes elicited from talented bartenders who are part of an emerging group referred to as cocktailian bartenders. Cocktailians are professionals and sometimes gifted amateurs dedicated to exploring the history of cocktail tradition, mastering techniques, and developing product knowledge to an extent heretofore unprecedented in the bartending community. The authors have provided for the first time in print a collection of modern absinthe recipes with notes from the cocktailian inventors discussing their ingredient choices and their inspiration. The pages of this book provide a unique look into the minds of the most innovative bartenders working today. There are also many fine photographs that show retro ephemera--from glasses and spoons to fountains--as well as cocktail presentations employed in many cutting-edge bars located across the country. A Taste for Absinthe is an indispensable handbook to creating world-class cocktails using this once-illicit drink. Cheers to a job well done. --Dale DeGroff, aka King Cocktail, author of The Craft of the Cocktail and The Essential Cocktail Ryan Fitzgerald at Baretta makes the Third Degree Absinthe is one of the most mysterious elixirs of modern history. Considering the centuries of negative innuendo and misrepresentation that have plagued absinthe, it is not surprising that the beverage suffers from widespread suspicion and poor public relations. Times, however, are about to change--absinthe is finally having its day in the American court of public opinion. With the reversal of a century-long ban on absinthe and the recent production of American-made absinthe now on shelves, the Green Fairy no longer needs to rely on her historical ambassadors--Vincent van Gogh, Pablo Picasso, Henri de Toulouse-Lautrec, Oscar Wilde, and Ernest Hemingway, to name a few. Tastemakers in some of the country's hottest culinary epicenters have been beguiled by absinthe's sophisticated flavor profile and are incorporating it into cocktails that pay homage to the elixir's rich and storied history while appealing to contemporary palates. From Los Angeles and Napa Valley to Boston and New York, the appeal of absinthe is being rediscovered in bars and restaurants. Perhaps it may be just a matter of time until Americans celebrate absinthe the way the Green Goddess was celebrated in the cafes and bars of Paris, resulting in a Belle Époque phenomenon known as l'Heure Verte, or the Green Hour, where absinthe enthusiasts--mostly artists and intellectuals--met to socialize and discuss matters of the heart, soul, and mind. Today real--yes, real--absinthe is back, and poised to make a splash in the United States. Absinthe's second coming has quickly grown into a culinary movement; bars, restaurants, liquor stores, and drinkers across America are setting out their slotted spoons and sugar cubes, and filling their absinthe fountains with ice as the drink is stirring up the cocktail industry. After being accused of sinking entire populations into crazed, bug-eyed convulsions, the widespread vilification of absinthe is coming to an end. Now, the Green Fairy is finally being properly sipped as the engines of pop culture--movies, music, books, and the Internet--bring it back into the mainstream. With the help of master mixologists at your fingertips, A Taste for Absinthe offers you sixty-five recipes to discover the charms of the Green Fairy. Readers can approach the content in a needs-based manner, looking up particular recipes based on the ingredients featured in specific chapters, or read the book straight through for a complete perspective on the compelling history and exciting modern recipes that utilize absinthe. Each recipe includes a brief description of what makes it unique followed by a list of ingredients and an easy-to-follow, step-by-step explanation of how to prepare each drink. World-renowned absinthe experts, such as Jeff Hollinger and Jim Meehan, offer insider insights and mixology tips on how to best prepare and enjoy absinthe. From traditional practices to cutting-edge recipes, the following pages offer everything the absinthe drinker needs to know in order to serve and enjoy absinthe for any occasion, any time of the year. The Bitter End, created by Josh Harris from the Bon Vivantes. Long veiled in mystery and intrigue--with rumors making up what most people these days think this drink is--absinthe is slowly shedding its false identity. Many of the ingredients in authentic absinthe are unfamiliar merely because we don't often encounter them. A primer explaining the mysterious herbal mixture that's key to the drink's flavor will help dispel the fear that absinthe is a bewitching elixir. In the nineteenth century, absinthe was originally taken neat as a medicine, in very small doses (like most alcoholic/herbal tinctures, which were normally diluted into water or dripped onto a cube of sugar or possibly mixed with honey). Around 1830, before any popularly known uses of absinthe as an aperitif, the French army provided absinthe to its soldiers fighting in Algeria. Drinking water was notoriously unclean in desert or tropical zones (and even, at that time, in Paris!), so wine, beer, or diluted spirits were often consumed in lieu of pure water. Prescribed drops of absinthe per cup of water eventually increased, and the ratio was actually reversed when it was found that the herbal alcohol helped ease the pains of war. The soldiers soon discovered that absinthe tasted better when the water was more deliberately and methodically added to the alcohol; thus they developed the classic absinthe drip. ABSINTHE'S LIBERATION The bans on absinthe began in the early 1900s. In the United States, bad press from across the Atlantic and an anti-absinthe novel--Wormwood: A Drama of Paris by Marie Corelli (who was the Belle Époque equivalent of a Danielle Steele-type novelist)--caused a furor among the public. Absinthe was mostly consumed in cities such as San Francisco, New Orleans, Chicago, and New York, but scandalous stories spread across America, prompting the government's ban in 1912 for "protective" measures. It took until the late 1980s for absinthe to begin to be accepted again. In 1988, the French government passed a decree based on World Health Organization protocols that, in effect, relegalized absinthe by defining the limit of the chemicals that were thought to be dangerous--those naturally found in wormwood, fennel, and hyssop. Today it is required for absinthe to undergo a chemical analysis for thujone, fenchone, and pino camphone limits, and in France it also must follow certain labeling guidelines. The "relegalization" of absinthe in the United States followed many petitions sent to the U.S. government by Swiss and American interests over a period of about five years, asking for an explanation of the legality of its prohibition. The efforts prevailed, and as of 2007, absinthe has been accepted for distribution and manufacture in the United States. Absinthe production follows similar definitions and limitations as in the European Union on the quantity of thujone. In 1943, absinthe appeared in the film based on the Ernest Hemingway novel For Whom the Bell Tolls. Robert Jordan, the lead character played by Gary Cooper, is assigned a dangerous mission: to blow up a bridge in the mountains of Spain during the Civil War. He reaches for absinthe in his most desperate hour. ABSINTHE'S UNIQUE FLAVOR Absinthe was classically defined by the use of the Holy Trinity of herbs as its flavor base: Grande absinthe (wormwood), green anise seed (star anise is sometimes substituted but not as fine), and fennel seed. Other herbs and spices can be added to suit individual distillers' palates or reflect regional tastes. These ingredients were added to a neutral (clean and almost flavorless) base spirit--grape alcohol was considered the highest quality, though grain and beet alcohols have been used. A well-made absinthe will have a complex bouquet of herbal and floral aromas as a result of the combination of both distilled and coloring herbs--sometimes reminiscent of a fresh, springtime Alpine meadow with crisp bright flavors, and other times being more warm and spicy, depending on the recipe. The first aromatic impression that an American taster picks up is that of licorice. Most high-quality absinthes do not contain licorice; the flavors of anise and fennel seed are similar to that of licorice. The anise profile should not be overbearing--though it can be when star anise or too much green anise is used--but should provide a sweet and fresh background. The aroma of wormwood at its finest is lightly mentholated and can have an earthy-heady aspect. Ironically, the aroma is rarely encountered in modern absinthes and is often confused by inexperienced tasters as a defect. There is some necessary bitterness in good absinthe, but it is a balanced herbal undertone, and not overpowering. Traditional absinthe is an anise-based spirit. Nonanise, or "low-licorice-tasting," absinthes were recently made under the presumption that the American palate is unacquainted with or dislikes anise-flavored alcohols and that more people would drink absinthe without this flavor. It is much like making Islay Scotch without any peat: people want to say they drink Islay Scotch, but they don't like the taste and smell of peat, though it's the drink's characteristic flavor. WORMWOOD Wormwood (Artemisia absinthium) is a plant related to sagebrush. It's also known in French as Grande absinthe, as it is the principal defining ingredient of the beverage and where the name is derived. It grows wild in many regions of the world, but is found in abundance in sunny, cool, mountainous areas, specifically the Jura Mountains of Eastern France on the border shared with Switzerland. There are several varietals of Grande absinthe, some extremely aromatic and flavorful, and others very muted and dull. Wormwood is naturally very bitter, but most of this bitterness is removed during distillation. However, a well-made absinthe will always have a slight but pleasurable bitterness, appreciated just as in a fine Italian espresso or a dark chocolate. The best plants are harvested just before the flowers at their tops have opened, thus optimally preserving the aromatic qualities. Wormwood has been used historically in many alcoholic preparations throughout Europe. For example, the German word for wormwood is vermut, which shows the connection to the use of wormwood as a bittering agent in vermouth. THE MYTH OF HALLUCINATIONS Absinthe has many times been condemned as a dangerous drug--one that plunges drinkers into hallucinatory spells. Yet we now know that the threat of such effects is unfounded--or, rather, only mildly correct. The chemical thujone can be blamed, but this naturally occurring substance is potentially harmful only in extremely high doses. Therefore, there are strict regulations in place to ensure that absinthe is now made with safe levels of thujone. A fragrant and oily chemical, thujone is found in various plants, notably wormwood, as well as in sage, tansy, tarragon, and the bark of the thuja tree, from where it gets its name. In high doses, it is believed to be a neurotoxin. The liquor absinthe is not thujone--in fact, very little thujone actually finds its way into distilled absinthe. Early researchers generally tested wormwood oil, a highly concentrated extract, for levels of thujone. Some recent researchers assumed that thujone was present in high quantities in nineteenth-century absinthes, but others found that this wasn't the case. Previously unopened antique bottles of absinthe as well as modern absinthes distilled according to historical protocols have been tested and they show extremely low levels of thujone, most often well within the amount allowed by EU regulations. In extremely high doses, thujone is dangerous, but the concentration of thujone actually found in the beverage absinthe is nothing to worry about. You would need to drink seven liters (!) of the undiluted spirit to have any adverse effect directly from thujone. The alcohol, and even the water (if you diluted it), would kill you before! Thujone was discovered and isolated to absinthe during the nineteenth century to make it "different" from other spirits, in order to condemn and ban it. This movement was headed by the antialcohol leagues and winegrowers unions, who saw all high-proof spirits, but especially absinthe, as a threat. Unfortunately, modern absinthes are now being marketed with thujone as a selling point, proffering the idea of the supposed "druglike" effects while smoke-screening poorly made products and hindering the development of absinthe as a high-quality spirit. An urban legend regarding absinthe is that it has druglike effects. The reality is that absinthe is a high-alcohol spirit that has attributes of a depressant (alcohol) and a stimulant (anethole from anise). The combination can cause, in some drinkers, a "secondary effect," different from drunkenness, which is a "wide-awake" feeling, attributed to the anethole. One could also say that tequila produces a different drunken feeling (secondary effect) than beer, whisky, or wine. ABSINTHE'S ALLURING GREEN TINT The color of absinthe is a secondary effect of the maceration of various herbs into the colorless extract after distillation. Historically, absinthe was green, amber, or clear and exhibited an underlying sweetness produced by macerating fresh herbs in a warm bath of neutral spirit and distilling. This primary distillation produced an aromatic blanche, or clear, absinthe rich in flavors. Verte, or green, absinthe would go through a second process that infused additional herbs to enhance its flavor profile--as a result, chlorophyll from the herbs was left behind, giving absinthe its green tint. The final color is determined by the types and amounts of herbs infused and mellows with age and turns an amber-green, called feuille morte, or "dead leaf." Artificial colorings or dyes were fairly common in cheaper absinthes but not used by the best producers. THE LOUCHE The louche is the cloud that forms when water is dripped into absinthe. The slow addition of cold water to absinthe causes a reaction that allows essential oils to precipitate out of their suspension in the high alcohol content, releasing the aromas and flavors that are so appreciated by the absintheur. The anethole from anise and fennel seed can start to crystallize at a temperature less than 20 degrees centigrade, causing an additional whiteness in the cooling liquid from the slow formation of crystals. Depending on the type and concentration of essences and alcohol percentage, the clouding effect can be quick forming and milky thick white, to lightly opaque with opalescent reflections. The most desirable louches are slow-forming yet deliberate milky trails caused by the water dropping through the absinthe, gradually forming a moderately opaque drink with reflections of the original green color of the undiluted absinthe. Though many consider thick louches to be a sign of the absinthe's strength and quality, it can also signify the overuse of anethole-rich star anise, which can numb tastebuds and result in a distractingly one-dimensional flavor. Too much anethole stuns the palate and makes the absinthe much harder to appreciate than more subtle aromatic qualities. "FAKE" VS. "REAL" ABSINTHE For the sake of an understandable definition, "real" absinthe is defined as a typical high-quality absinthe product, similar to that which was produced during the Belle Époque by such brands such as Pernod Fils. Real absinthe should be a liquor of no less than 50 percent alcohol (100 proof) that is not presweetened and contains wormwood (Artemisia absinthium), anise (preferably green anise seed and/or to a lesser degree, badiane, or star anise), and fennel seed. It should turn cloudy (louche, or "trouble") with the addition of cold water. Again, for the sake of an understandable definition, "fake" absinthe is defined as a product that is not produced in accordance with historical distilling methods or ingredients. Fake absinthe is most commonly high-proof base alcohol with artificial green color (often bright or even neon green color). It typically does not louche with the addition of water and is often extremely bitter with or without water. An herbal drink, even with wormwood, that does not contain a noticeable anise profile and does not noticeably cloud when ice water is added should not be considered a traditional or even a real absinthe. Most Bohemian-style absinthes have little or no anise in them [as this is not an appreciated taste in Eastern Europe] and as such, do not cloud, but typically become insipidly diluted when water is added. This bears no resemblance to traditional absinthe and would have been considered a major defect during the epoque. There are, however, different colored and uncolored types of absinthes that are produced in a variety of methods, including those that are distilled, compounded (oil-mix), and macerated. The origin of a particular brand of absinthe shouldn't be a major concern, as long as it is produced using high-quality herbs, alcohol, and distilling apparatuses. However, from a historic perspective, the best absinthes were made in the Jura region of eastern France, in particular the city of Pontarlier and the Val-de-Travers region of Switzerland, which almost borders Pontarlier. MODERN ABSINTHE The vast majority of modern absinthes bears little resemblance to original absinthe of the nineteenth century. However, a handful are virtually identical. Historic recipes have been found in handwritten protocols held by still-functioning distilleries and in antique distiller's manuals, some even dating into the eighteenth century. Some of these recipes have been followed exactly--using wormwood from the same historic region, the same additional ingredients, and the same alembic stills and techniques of distillation and coloration--resulting in absinthes that are remarkably authentic. However, there are many modern producers who claim to use the traditional ingredients and processes for making absinthe but actually only add flavorings and dyes to alcohol. To know you're getting the real deal, it's important to research what you're buying. One aspect of absinthe that was vitally important during the Absinthe Époque was the terroir (origin) of the wormwood plants used in distillation. Extremely fragrant wormwood from the mountain plateau of Pontarlier in Eastern France was so highly prized that demand often outstripped the harvests. Presently, there is only one absinthe on the U.S. market using wormwood from this region: Vieux Pontarlier. • A minimum of 50 percent alcohol (100 proof). The best historic absinthes were at least 65 percent (130 proof). • No added sugar. Absinthe was always a "dry" spirit. If a product labels itself as a liqueur/liquor, it most likely will contain sugar. • Look for the term distilled. • The base alcohols of the best absinthes are grape/wine derived. Though modern grain or beet-neutral alcohol is perfectly acceptable for absinthe making, they have always been considered inferior. • Avoid artificially colored absinthes, usually identified with an FD&C number, which has to be on the label if coloring is used. Switzerland does not allow absinthes to be artificially dyed, so you can be sure that any Swiss-made absinthe will be naturally colored. ABSINTHE TOOLS AND ACCOUTREMENTS Absinthe Spoons Absinthe spoons come in a variety of styles but most are ornate, lustrous, and look as if they were designed to kill vampires. Yet they are important tools that play an integral role in the creation and consumption of the perfectly concocted drink of absinthe. Absinthe spoons are laid across the absinthe glass with the slotted portion centered in the middle so that when the ice cold water dissolves the sugar cubes, it drips directly into the glass. Most absinthe spoons have grooves in their stems that offer greater stability by clasping the glass's rim, while others rely on a completely flat architecture for a horizontal posture across the top. However, everything about an absinthe spoon's layout and style is carefully thought out by an experienced crafter with a particular vision, motif, person, or other source of inspiration in mind. There is an art to everything about absinthe. Absinthe Glasses Absinthe glasses come in a variety of styles, and each offers absintheurs a sweeping range of techniques and experiences. From simple elegance for beginners to sophisticated craftsmanship for veteran collectors, there is an absinthe glass for just about every drinking environment and inclination. Obviously, absinthe glasses hold the absinthe that the ice cold sugar water is dripped into, but the important and differentiating factor is exactly how the glass holds the concoction. Remember, aesthetics are essential when consuming absinthe. Many absinthe glasses have a demarcation line, called the dose line or mark line, that indicates exactly how much absinthe to pour into it. This frees drinkers from having to use jiggers or shot glasses and allows them to pour straight from the bottle. These markings typically ensure that the correct ratio of water to absinthe is achieved--anywhere from a 5:1 ratio to a 3:1 ratio depending on individual preferences. The dose line or mark line can also come in the form of a compartment referred to as a reservoir. Accessories The following absinthe accessories are for absintheurs with an elevated level of enthusiasm for the beverage because--unlike absinthe spoons and glasses--decanters, fountains, and pipes are not absolutely necessary for the absinthe ritual. They do intensify the absinthe experience by adding grace, eloquence, and sophistication to the process. Streaming ice water from a standard drinking glass exudes simplicity and a welcome lack of pretension; for serious absinthe drinkers, however, decanters, fountains, and pipes elevate the stakes by seriously considering every detail of consuming absinthe. Decanters Decanters have been around since the dawn of ancient civilizations, but the modern glass varieties play an important role in absinthe consumption: on a practical level, the transparent glass allows pourers to measure the pace and proportion of ice water as it streams onto the disintegrating sugar cube, and on an artistic level they add a beautiful and more refined aesthetic to the ceremony. Fountains Absinthe fountains are the ultimate centerpiece for the serious absinthe drinking ceremony. Absinthe fountains are beautiful, elaborate, fragile, sophisticated, and fun. No one walks away from an absinthe fountain. They are intriguing for novices and experts alike, and create the perfect atmosphere for absinthe parties because they require that people be close together while making their louches. Absinthe fountains are that conducive to the good life. Like much of the absinthe experience, absinthe fountains are centered around the force of gravity. Fountains are made from metal stands, lids, and taps, usually silver or gold plated, and glass containers, which are available in various shapes--some of them quite exquisite and even sexy. Fountains are designed for entertaining. They typically have an even number of taps--four is most common--and are designed to engage groups of people in the absinthe drinking experience. The glass container is filled with ice and water, the lid is placed on the top to insulate the cold, and then, with a gentle turn of the knobs on the taps, a fine stream of ice cold water trickles out, much like from a miniature faucet. The cold water mixes with the absinthe in the glass below, and a louche steadily forms, creating the ideal drink of absinthe. MAKES ABOUT 1½ CUPS 1 CUP GRANULATED SUGAR 1 CUP WATER Combine the sugar and water in a small saucepan. Bring the mixture to a boil over moderately high heat; simmer for 3 minutes, stirring to dissolve the sugar. Allow to cool. Then transfer the syrup to a jar, cover it, and refrigerate until ready to use. Demerara sugar gives this concentrated syrup a great molasses flavor. The syrup keeps for up to a month in the fridge. MAKES ABOUT 1 CUP 1 CUP DEMERARA SUGAR ½ CUP WATER Combine the sugar and water in a small saucepan. Bring the mixture to a boil over moderately high heat; simmer for 3 minutes, stirring to dissolve the sugar. Allow to cool. Then transfer the syrup to a jar, cover it, and refrigerate until ready to use. # ABSINTHE DRIP CORPSE REVIVER NO. 2 COCKTAIL À LA LOUISIANE A SALUTE TO THE SAZERAC ARSENIC AND OLD LACE ABSINTHE AND OLD LACE BRUNELLE PAN AMERICAN CLIPPER IMPROVED POLSKI POUSSE CAFÉ MONKEY GLAND MONKEY GLAND NO. 2 DEATH IN THE AFTERNOON "B" MONKEY The classic manner of drinking absinthe--known as the absinthe drip--is drenched in ritual and technique, and necessitates the use of specially crafted vessels and serving pieces. The drip is also the most popular, simplest, and, according to true absintheurs, only way to prepare and drink the beverage. Fittingly, the traditional method exemplifies the social and intellectual experience that is part of its rich image and attraction. It's also a showcase of absinthe as it was enjoyed in the Belle period of the late nineteenth century on the streets of Paris, and in the cabarets of the red-light district in nearby Montmartre, home to the infamous Moulin Rouge. The details of the traditional style complete the pleasure of the ritual--how to set up the glass and spoon, position the sugar, and monitor the ice cold water as it interacts with the elixir to create the opalescent louche. It doesn't require special ingredients or an experienced mixologist. The contemplative and methodical process of the traditional-style recipe is about ritual, and requires both preparation and participation--an excellent way to socialize and enjoy the company of your friends. Absinthe Drip Given the high proof of traditional absinthe, it should never be consumed undiluted. Many purists agree that the traditional absinthe drip is the best way to appreciate the nuances of fine absinthe. Here is a version adapted from The Bar-Tenders Guide: How to Mix Drinks, or the Bon-Vivants Companion by Jerry Thomas, which was published in 1862. 1½ OUNCES VIEUX PONTARLIER ABSINTHE 1 SUGAR CUBE 4½ TO 6 OUNCES ICE COLD FILTERED WATER Carefully pour the absinthe into an absinthe glass. Place a slotted absinthe spoon over the rim of the glass and set a sugar cube in the bowl of the spoon. (If you don't want your absinthe sweetened, omit the spoon and sugar cube.) Slowly pour or drip the ice cold water over the sugar cube and into the absinthe. As the dripping water dissolves the sugar cube, watch the layer of undiluted absinthe rise to the top of the glass. When the mixture is completely cloudy, the drink should be ready. Stir, taste for strength, and adjust with more water if necessary. Corpse Reviver No 2 This is an adaptation of one of the two "corpse revivers" listed in the venerable Savoy Cocktail Book (1930) and attributed to Harry Craddock. Historians believe corpse revivers were morning drinks, probably prescribed by bartenders, relied upon to revive and ameliorate symptoms most likely stemming from the previous night's tipple. Marcos Tello adapted the recipe for the Edison in downtown Los Angeles. ¾ OUNCE MARTIN MILLERS GIN ¾ OUNCE COINTREAU ¾ OUNCE LILLET BLANC ¾ OUNCE LEMON JUICE 4 DROPS ABSINTHE Pour the gin, Cointreau, Lillet, and lemon juice into a mixing glass, then add ice. Shake well and strain the drink into a chilled coupe. Add the absinthe and serve. Cocktail a la Louisiane According to author Stanley Arthur Clisby in his book Famous New Orleans Drinks and How to Mix 'Em (1937), "This is the special cocktail served at restaurant Restaurant de la Louisiane, one of the famous French restaurants of New Orleans, long the rendezvous of those who appreciate the best in creole cusine." The strong presence of French culture in New Orleans cuisine and beverages still lingers in the city's affection for absinthe-based flavors. Jim Meehan of PDT, a modern-day speakeasy and hidden gem in New York City's East Village, developed this recipe at Pace, an Italian restaurant where he served as bar manager and sommelier. 2 OUNCES WILD TURKEY RYE WHISKEY ¾ OUNCE DOLIN SWEET VERMOUTH ¾ OUNCE BENEDICTINE 3 DASHES EDOUARD ABSINTHE 3 DASHES PEYCHAUD'S BITTERS 3 BRANDIED CHERRIES, for garnish Pour the whiskey, vermouth, Benedictine, absinthe, and bitters into a mixing glass, then add ice. Stir well and strain the drink into a chilled coupe with one large ice cube in it. Garnish with three brandied cherries on a cocktail pick. Serve. Award-winning bartender Jim Meehan reworked this famous New Orleans classic for PDT, the cocktail lounge in New York City's East Village (pictured here), of which Jim is a managing partner. Most likely named after a defunct brand of Cognac named Sazerac de Forge et Fils, this drink nowadays most commonly uses rye whiskey as the base. Cognac was likely the preferred ingredient in the nineteenth century. VIEUX PONTARLIER, for rinsing the glass 1 DEMERARA SUGAR CUBE 3 DASHES PEYCHAUD'S BITTERS 2 OUNCES RITTENHOUSE RYE WHISKEY LEMON PEEL Rinse a chilled old-fashioned glass with Vieux Pontarlier; set aside. Muddle the sugar cube and bitters in a mixing glass. Add rye and fill the cocktail shaker with ice. Stir well and strain the drink into the prepared old-fashioned glass. Twist a lemon peel over the surface of the drink to release its oils, and discard the peel. Serve. Arsenic and Old Lace Aaron Polsky at White Star, New York City, found inspiration in a recipe from Cocktail Guide and Ladies' Companion by Crosby Gaige when creating this cocktail. The presence of creme de violette adds a floral and sweet influence that tempers the harsher gin and dry vermouth qualities. ABSINTHE, for rinsing the glass 2 OUNCES GIN ¾ OUNCE DRY VERMOUTH ¼ OUNCE CRÈME DE VIOLETTE THIN SLICE OF ORANGE PEEL, for garnish Rinse a chilled cocktail glass with absinthe; set aside. Fill a mixing glass with freshly cracked ice. Add the gin, vermouth, and creme de violette, and stir well. Strain the drink into the prepared cocktail glass. Squeeze the orange peel over the top, and drop the peel into the glass. Serve. IN THE 1966 FILM Madame X, director David Lowell Rich utilizes absinthe as an emotional crutch for the main character, played by Lana Turner. The film entails a complicated plot about a woman, known only as Madame X, standing trial for murder who refuses to give her own name in order to protect the socialite status of her husband and son. Madame X uses absinthe to try to drown her sorrows of losing her husband, home, and baby son in the name of that all-important thing: reputation. Absinthe and Old Lace The name of this cocktail was inspired by the classic play and film of the same name. From Jackson Cannon of Eastern Standard, in Boston, it's a fine example of how absinthe can add depth and complexity to an after-dinner drink. 1 EGG WHITE 1 OUNCE BEEFEATER GIN ½ OUNCE PERNOD ABSINTHE ½ OUNCE GREEN CRÈME DE MENTHE ½ OUNCE SIMPLE SYRUP ½ OUNCE CREAM 1 DASH BITTERMENS XOCOLOTL MOLE BITTERS Pour the egg white, gin, absinthe, creme de menthe, simple syrup, cream, and bitters into a mixing glass. Dry shake well, then add ice and shake again. Strain the drink into a chilled cocktail glass. Serve. IN 1956, director Vincente Minnelli featured absinthe in Lust for Life, a biographical film adapted from the 1934 novel by Irving Stone. The story follows the tumultuous life of the Dutch painter Vincent van Gogh, played by Kirk Douglas, and absinthe has a large role. Popular mythology claims van Gogh chopped off his own ear as a result of absinthe's influence. Itried this cocktail--from the 1930 Savoy cocktail book--before the ban on absinthe was lifted, when all I had to work with was pastis. The cocktail was good but not outstanding. After the ban, I decided to try it again with the real stuff. Wow! Now this is one of my favorite drinks. It reminds me of the wonderful aroma when you hike through the chaparral at Big Sur. The recipe here is further refined by Tim Stookey of San Francisco's Presidio Social Club. 1½ OUNCES LEMON JUICE ½ OUNCE ABSINTHE 1½ TEASPOONS SUGAR Pour the lemon juice, absinthe, and sugar into a cocktail shaker filled with ice. Shake well, and strain the drink into a cocktail glass. Serve. THE HENROID SISTERS who bought Dr. Ordinaire's original recipe for absinthe reportedly sold it to Major Dubied in 1797. Some years later, the major, his son, and his son-in-law, Henri-Louis Pernod, opened the first commercial absinthe distillery, which they named Dubied Pere et Fils. When they moved the business to a larger location, they renamed it Maison Pernod Fils. Their eponymous absinthe is still one of the best on the market. Pan American Clipper Originally printed in The Gentlemen's Companion by Charles H. Baker in 1939, this recipe was adapted by Erik Adkins for the menu of San Francisco's Heaven's Dog to feature a more contemporary flavor. 2 OUNCES DOMAINE DE MONTREUIL CALVADOS ½ OUNCE FRESH LIME JUICE ½ OUNCE SMALL HAND FOODS GRENADINE 3 DASHES DUPLAIS ABSINTHE LIME TWIST Pour the calvados, lime juice, grenadine, and absinthe into a cocktail shaker. Add ice and shake for 10 to 20 seconds, or until cold. Strain the drink into a coupe. Garnish with a lime twist, and serve. ABSINTHE is the spelling most commonly used for Swiss and French products. The Spanish label their bottles as absenta, and the Germans prefer to use the spelling absinth. Improved Polski Pousse Cafe Aclassic cocktail adapted from Charles H. Baker's book The Gentlemen's Companion, pousse cafe translates to "coffee push." This sweet, boozy, layered drink was intended to be taken after your coffee. The original Polski Pousse Cafe did not call for absinthe, but this version by Jason "Buffalo" Lograsso of Bourbon & Branch, San Francisco, uses absinthe as the final touch. ¼ OUNCE YELLOW CHARTREUSE 1 SMALL EGG YOLK ½ OUNCE DANTZIGER GOLDWASSER DASH ABSINTHE Slowly pour the chartreuse over the back of a spoon into a sherry glass. Repeat with the egg yolk and then the Dantziger Goldwasser, carefully layering each ingredient on top of the previous one. Add a dash of absinthe and serve. Monkey Gland This cocktail was invented by Harry MacElhone in the 1920s at Harry's New York Bar in Paris, France. The recipe here is from Jackson Cannon at Eastern Standard, Boston. Its unusual name comes from an equally unusual practice at the time of surgically implanting a monkey's testicle into men to give them "renewed vigor." Frankly, I think drinking this cocktail would have more effect and the monkeys would appreciate it as well! 1½ OUNCES MILLER'S GIN 1½ OUNCES ORANGE JUICE 1 BARSPOON POMEGRANATE GRENADINE 6 DROPS PERNOD ABSINTHE 1 MARASCHINO CHERRY STRIP OF ORANGE ZEST Pour the gin, orange juice, grenadine, and absinthe into a cocktail shaker. Add ice, and shake well. Strain the drink into a chilled cocktail glass. Make a "petit flag" garnish by spearing the cherry onto a cocktail pick and wrapping the orange twist around the cherry. Add to the glass, and serve. John Gersten of Drink in Boston, Massachusetts, added his own spin to the venerable Monkey Gland recipes by altering the proportions and types of ingredients and excluding the cherry flavor. 1¾ OUNCES GIN ¾ OUNCE ORANGE JUICE ¼ OUNCE GRENADINE ⅛ OUNCE ABSINTHE BLANCHE Pour the gin, orange juice, grenadine, and absinthe into an iced cocktail shaker. Shake well, and strain the drink into a cocktail glass. Serve. OTHER FLAVORING ingredients used in absinthe include: roman wormwood, star anise, anise seed, hyssop, angelica root, calamis root, fennel, melissa, juniper, nutmeg, coriander, licorice root, lemon balm, dittany, and sweet flag. This refreshing beverage incorporates the subtle qualities of absinthe verte with the more effervescent texture and fizz of Champagne. Thank John Gersten of Boston's Drink for developing another simple but inspired cocktail perfect for absinthe fans with reason to celebrate. ½ OUNCE ABSINTHE VERTE CHAMPAGNE Pour the absinthe into a champagne flute. Fill the glass to the top with Champagne. Serve. BURNING THE ABSINTHE-SOAKED SUGAR CUBE before drinking the beverage is a relatively new invention and not part of the original ritual. Absinthe purists denounce the practice. "B" Monkey Marc Hartenfels of Bardessono in Napa Valley, California, explains that the "b" monkey is their version of the Monkey Gland, which was invented by Harry MacElhone, owner of Harry's New York Bar in Paris, in the 1920s. Hartenfels has created his own version of the conventional Monkey Gland recipe by replacing the orange flavor with grapefruit. Also, no cherry. 1½ OUNCE LEOPOLD'S GIN 1½ OUNCE FRESH GRAPEFRUIT JUICE 1 TABLESPOON ST. GEORGE ABSINTHE 1 TABLESPOON GRENADINE Pour the gin, grapefruit juice, absinthe, and grenadine into a cocktail shaker. Add ice and shake well. Strain into a small cocktail glass. Serve. The story of absinthe--the most vilified beverage in history--begins in 1797 with Dr. Pierre Ordinaire, a Frenchman who dedicated his life to helping people with their ailments. Unfortunately, addressing medical needs during this time period often meant not curing but numbing distress. Over time, Dr. Ordinaire's search to relieve his patients from pain would lead to what would be creepy-eyed shock rocker Marilyn Manson's favorite beverage. Though the liquor's history is poorly comprehended and surrounded by innuendo and apocryphal tales of grimness and grandeur, all accounts point to Dr. Ordinaire as the father of the Green Fairy. In 1789, the doctor practiced medicine in Val-de-Travers in the Canton of Neuchatel, a region of Switzerland near the French border. Wanting to mollify his patients of their anguish and disease, he sought remedies from all aspects of his life, and especially from the various natural plants that grew around his home. By tinkering with the herb Artemisia absinthium, Dr. Ordinaire concocted a beverage that millions would struggle to understand throughout the next two centuries. His cure-all, absinthe, was made from the leaves and flowers of wormwood, a plant named as if it belonged in a witch's cauldron, steaming alongside puppy whiskers and butterfly wings. Originally administered by the spoonful as any ordinary cough medicine, the elixir curiously made its way into the barkeep's cabinet to become one of the most fascinating beverages of all time. # BITTER END LA FISCUS VERTE THE STRUTTERS' BALL BLUE RHONE FIZZ NORTH OF THE BORDER QUINQUINA L'ARC DE TRIOMPHE DR. FUNK ICEBERG DEV'S PRIDE GRAND TI PUNCH THAI HALLUCINATION ZOMBIE PUNCH MY OH MY TY SUISSESSE Absinthe's reputation is steeped in a dark and gothic history where artists and intellectuals consumed the drink on lonely benders in dark rooms filled with torn canvases and crumpled pages of wayward manuscripts. However, with absinthe's resurrection comes a newfound understanding of the drink, one that allows the Green Fairy to fly freely about the limitless range of mixers and ingredients available to complement absinthe's distinctive flavor--including a taste of the tropics. There is no reason absinthe should remain cloistered in its brooding history and kept out of the sunlight. So here are some tropical recipes that feature citrus flavors and influences reminiscent of palm trees, bright colors, and balmy weather. Bitter End Though carrying unhappy connotations, the name of this cocktail--created by Josh Harris, cofounder of the Bon Vivantes in San Francisco--comes from its citrus flavors. It's a small drink and perfect as an aperitif to whet the appetite. The fun thing about this drink is that the taste at the beginning is different from the taste at the end. It starts out sweet, tart, citrusy, and then, as you get to the bottom, the drink becomes more aggressively bitter. The Campari has a real nice bite to it. ½ OUNCE FRESH LEMON JUICE ½ OUNCE FRESH ORANGE JUICE ½ OUNCE FRESH EGG WHITE 1 OUNCE KÜBLER ABSINTHE ½ OUNCE COINTREAU ¼ OUNCE RICH SIMPLE SYRUP ¼ OUNCE CAMPARI STAR ANISE POD, for garnish Pour the lemon juice, orange juice, and egg white into a cocktail shaker. Using a blender ball, dry shake the mixture until well combined. Open the shaker, and then pour in the absinthe, Cointreau, and simple syrup. Shake again, vigorously, and then strain into a martini glass. Slowly and carefully, pour the Campari down the side of the glass so that it sinks below the absinthe mixture (this is easier to do if you fit your Campari bottle with a medium-flow long chrome pour spout). Garnish by floating the star anise pod on top of the drink, and serve. La Fiscus Verte The name of this cocktail is a combination of the Latin words for "the green fig" and the French for absinthe's nickname, the Green Fairy, la fee verte. Creator Paul Scandura of Martini House in Napa Valley, California, wanted the name in Latin to represent the rich history of absinthe and how it is commonly referred to in historical literature. You can find the Tahitian vanilla bean syrup in specialty grocery stores or some coffee shops. 3 MISSION FIGS, halved 1 TEASPOON FRESH LEMON JUICE DASH TAHITIAN VANILLA BEAN SIMPLE SYRUP 1 SLICE VALENCIA ORANGE 3 OUNCES LEBLON CACHAÇA SPLASH ABSINTHE VERTE 3 DASHES BITTERS ORANGE TWIST, for garnish Muddle the figs, lemon juice, vanilla syrup, and orange slice in a cocktail shaker. Top the mixing glass with ice, then add the cachaça and absinthe. Shake all ingredients together and strain into chilled martini glass. Add the bitters, garnish with twist of orange, and serve. The Strutters' Ball The "Strutters' Ball," the secondary name for the song more commonly know as "Caliope," can often be heard on the steam piano of the Natchez steamboat, which docks on the Mississippi River in New Orleans. Jason "Buffalo" Lograsso of Bourbon & Branch in San Francisco was inspired to make this cocktail by his memory of sipping a sweet, milky Cafe du Monde iced coffee by the riverside on his first morning in New Orleans. His personal experience is revisited in this cocktail via the influences of the sweetened condensed milk. 2 OUNCES SAGATIBA VELHA CACHAÇA 1 OUNCE SWEETENED CONDENSED MILK 1½ OUNCES FRESH GRAPEFRUIT JUICE 1 OUNCE FRESH ORANGE JUICE ½ OUNCE FRESH LIME JUICE ¼ OUNCE ABSINTHE COCOA NIBS, for garnish 1 THIN SLICE OF ORANGE, for garnish STAR ANISE, for garnish Pour the cachaça, sweetened condensed milk, grapefruit juice, orange juice, lime juice, and absinthe into a cocktail shaker. Shake well, and strain the drink into a highball glass filled with ice. Garnish with the cocoa nibs, orange slice, and star anise. Serve. Blue Rhone Fizz Inspired by a love for fresh, organic ingredients and original recipes, this drink features the expertise of Scott Baird, of 15 Romolo and the Bon Vivants in San Francisco. Baird, a lover of art in many forms, has worked in jobs as diverse as florist, caterer, window display designer, and welder. That versatile background and courage to try new things are evident in this blueberry-influenced cocktail. 2 OUNCES BLUEBERRY-INFUSED GIN (SEE RECIPE BELOW) ½ OUNCE VIEUX PONTARLIER ABSINTHE 1 OUNCE LEMON JUICE ¾ OUNCE RICH SIMPLE SYRUP ½ OUNCE CREAM 1 OUNCE EGG WHITE 1 DASH ANGOSTURA ORANGE BITTERS 1½ OUNCES SELTZER 4 DROPS ROSEWATER BLUEBERRIES, for garnish WIDE STRIP OF LEMON ZEST, for garnish Add the gin, absinthe, lemon juice, simple syrup, cream, egg white, and bitters to a pint glass. Dry shake using a Hawthorn strainer for 30 seconds. Add ice and shake hard. Pour the seltzer into a Collins glass, then strain the cocktail into the glass. Garnish with rosewater and a blueberry-lemon skewer, and serve. 1 CUP FRESH BLUEBERRIES 6 TABLESPOONS SUGAR 750 ML GIN Place the blueberries in a large glass bottle, and then add the sugar and gin. Shake well. Allow the mixture to infuse for at least two weeks or up to two months maximum, making sure to shake the bottle occasionally, until the mixture turns a deep blue color. North of the Border Very north of the border, indeed, this cocktail was born from the style of New York City bartenders Shane Tison and Jason Littrell, who work at the Randolph at Broome in downtown Manhattan. The lemon and orange citrus influences blend well with the Crown Royal, a Canadian whisky much loved and consumed by Canada's southern neighbors. ½ OUNCE SIMPLE SYRUP ½ OUNCE FRESH LEMON JUICE ½ OUNCE FRESH ORANGE JUICE ½ OUNCE ABSINTHE 2 OUNCES CROWN ROYAL WHISKY ANGOSTURA BITTERS Pour the simple syrup, lemon juice, orange juice, absinthe, and whisky into a cocktail shaker. Shake well, and pour the drink into a Collins glass filled with crushed ice. Add two dashes of bitters, and serve. Quinquina Q uinquina are a type of bitters that have quinine as a key flavoring. The quinine is the bitter constituent which promotes production of digestive enzymes and, therefore, appetite. One of the most popular and widely known quinquinas is Lillet Blanc; before 1986, when the recipe was modified to make it lighter and less bitter, it was sold as Kina Lillet. Lillet is the quinine element in this classic cocktail from Eric Alperin of The Varnish in Los Angeles. If you like the taste of bitter aperitifs, you should enjoy this heftier peach-and-anise-laced version of a Quinquina cocktail. 1 OUNCE COGNAC 1 OUNCE LILLET BLANC 1 OUNCE PEACH BRANDY LIQUEUR ¼ OUNCE ABSINTHE Pour the cognac, Lillet Blanc, liqueur, and absinthe into a cocktail shaker. Shake vigorously, and strain into a chilled coupe. Serve. L'arc De Triomphe Featuring the unique influence of bitter orange marmalade, this cocktail from Scott Baird of 15 Romolo and the Bon Vivants in San Francisco is a bold and colorful quaff. Scott particularly enjoys drinking this recipe in the afternoon because it's a good, long drink that is not terribly alcoholic--a perfect afternoon cocktail. 1 OUNCE ABSINTHE 1 OUNCE FRESH ORANGE JUICE 1 OUNCE FRESH LEMON JUICE 1 OUNCE BITTER ORANGE MARMALADE ¾ OUNCE EGG WHITE PEYCHAUD'S BITTERS 1 OUNCE SELTZER WIDE STRIP OF ORANGE ZEST, for garnish Add the absinthe, orange juice, lemon juice, marmalade, egg white, and a dash of Peychaud's to a pint glass with the spring from a Hawthorn strainer (remove the spring from the strainer and drop it in the glass). Dry shake for 30 seconds, until it is nice and frothy. Open it up, add ice, and shake well to make cold. Pour the seltzer into a footed beer glass or short-stemmed wineglass. Strain the drink into the glass. Add 2 dashes of Peychaud's and garnish with orange zest. Serve. Dr. Funk Drink's John Gersten--voted "Best Bartender" by Boston Magazine in 2008--concocted this drink that features a French-Caribbean-made sugarcane-based liquor. You don't need to have a sweet tooth to enjoy this drink, just a taste for the Caribbean. ½ LIME 1½ OUNCES RHUM AGRICOLE BLANC ½ OUNCE FRESH LEMON JUICE ½ OUNCE GRENADINE ¼ OUNCE ABSINTHE BLANCHE SODA WATER Squeeze the juice from the lime into a cocktail shaker, and add the lime. Pour in the rum, lemon juice, grenadine, and absinthe, and top with ice. Shake well and strain the drink into a highball glass filled with crushed ice. Top off the drink with soda, and serve. IN THE 1978 FILM Pretty Baby, absinthe is used in the hedonistic lifestyle of 1917 New Orleans' Red Light District, where the story follows Violet, a twelve-year-old girl--played by Brooke Shields--living in a brothel full of other young girls like herself. Iceberg Calling specifically for Kubler absinthe, this cocktail is by Mae Lane, who is not only a mixologist at Griffou in New York City but also a country music singer who loves the 1940s and dresses accordingly. Her unique personality is poured into this recipe, which features the bold taste of lime with the more temperate and sweeter flavor and aroma of yellow chartreuse. 1 OUNCE KÜBLER ABSINTHE 1 OUNCE YELLOW CHARTREUSE ¾ OUNCE FRESH LIME JUICE ½ OUNCE SIMPLE SYRUP LIME ZEST Pour the absinthe, yellow chartreuse, lime juice, and simple syrup into a hurricane glass. Add a pinch of lime zest, and fill the glass with crushed ice. Garnish with lime zest, and serve. Total Eclipse, A FILM FROM 1995, tells a dark story that takes place in the early 1870s, following the absinthe-heated and passionate affair between Paul Verlaine, played by David Thewlis, and teenage French poet Arthur Rimbaud, played by Leonardo DiCaprio. The intensity of their relationship erupted into a fiery argument in which Verlaine shot Rimbaud in the hand--this incident effected the end of Rimbaud's career as a poet. Dev's Pride This strawberry drink comes to us from Hari Nathan Kalyan, owner of the Randolph at Broome in New York City. The combination of fruits complements the herbal notes of absinthe. 1 OUNCE FRESH ORANGE JUICE 3 STRAWBERRIES 1 OUNCE ST. GERMAIN ELDERFLOWER LIQUEUR 1 OUNCE ABSINTHE ¾ OUNCE CREAM Put the orange juice and 2 strawberries in a cocktail shaker, and muddle together. Add the liqueur, absinthe, and cream. Shake well, and strain the drink into a coupe. Garnish with the remaining strawberry, and serve. MARILYN MANSON developed his own brand of absinthe, Mansinthe, which has an alcohol content of 66.6 percent. Grand Ti Punch Neyah White of San Francisco's Nopa thinks this is probably the most traditional way to drink rhum agricole--a spirit made from fresh pressed sugarcane from the French Caribbean. The word ti is a diminutive of petite, in French, so this drink is a "big little punch." 2 OUNCES RHUM CLÉMENT PREMIÈRE CANNE ½ OUNCE SIMPLE SYRUP ¼ OUNCE ABSINTHE 1 SMALL SLICE OF LIME Pour the rhum, simple syrup, and absinthe into a tumbler with a few pieces of ice, and stir. Garnish with the lime slice, and serve. At the turn of the twentieth century, the detractors of absinthe began to organize. By the time the liquor had reached new heights in popularity in the districts of Paris, so had the international temperance movement to abolish drunkenness. The movement--starting as far back as the 1820s--was well organized with medical professionals, political associations, and committees throughout England, Scotland, Canada, Africa, India, and the United States. In 1854, The Pathology of Drunkenness by Charles Wilson, MD, of Edinburgh, Scotland, furthered the temperance movement's cause, claiming that drunkenness was a deliberate attempt to commit suicide. Reports and recommendations similar to this book were published claiming that alcohol served no purpose for medical use or pleasure, and the only way to stop drunkenness was to embrace total abstinence. As early as 1870, rival manufactures of other spirits joined the bandwagon to demonize the Green Fairy. The only missing piece of the social engineering puzzle was a violent, high-profile, attention-grabbing murder case to support their beliefs and condemn the beverage. Enter Swiss farmer Jean Lanfray, who--after drinking absinthe, among other spirits--murdered his wife and daughters. The press deemed the crime the "Absinthe Murders." During the trial, a psychologist testified that a "classic case of absinthe madness" had overwhelmed Lanfray. The public was outraged. By 1910, absinthe was banned in Switzerland. The rest of the world soon followed. This offering from Jason Littrell of the Randolph at Broome features a unique splash of guava soda. You should think of the beach when you think of this drink. That light tartness of the lemon balances the fullness of the guava, and the unique woody flavor of the absinthe will come out underneath the tropical flavors. 1 OUNCE ST. GERMAIN ELDERFLOWER LIQUEUR 1 OUNCE ABSINTHE 1 OUNCE FRESH LEMON JUICE GUAVA SODA ORANGE PEEL Pour the liqueur, absinthe, and fresh lemon juice into a cocktail shaker, and shake well. Strain the drink into a Collins glass filled with ice. Top the cocktail with guava soda and garnish with the orange peel. Serve. Zombie Punch This is a classic tiki cocktail created by Donn the Beachcomber, the acknowledged founder of tiki bars, nightclubs, and restaurants, in 1934. Because of the Zombie's potent mix, he tried to limit each customer to one, stating that two will turn you into one. Brian Miller of Death + Company in New York City decided to re-create it after his friend Jeff "Beachbum" Berry said in a New York Times article that he could not get a decent one in Manhattan. When making this at home, you will need to make Donn's Mix the night before. 1½ OUNCES AGED JAMAICAN RUM 1½ OUNCES GOLD PUERTO RICAN RUM 1 OUNCE DEMERARA 151 PROOF RUM ¾ OUNCE FRESH LIME JUICE ½ OUNCE DONN'S MIX (SEE RECIPE BELOW) ½ OUNCE VELVET FALERNUM 1 TEASPOON GRENADINE ⅛ TEASPOON VIEUX PONTARLIER ABSINTHE 1 DASH ANGOSTURA BITTERS MINT SPRIG, for garnish Pour the rums, lime juice, Donn's Mix, falernum, grenadine, absinthe, and a dash of bitters into a cocktail shaker. Add 3 ice cubes and shake well. Strain the drink into a tiki mug filled with crushed ice. Garnish with the mint sprig, and serve. MAKES 4½ CUPS 3 CINNAMON STICKS 1 CUP SUGAR Crush the cinnamon sticks in a saucepan. Add the sugar and 1 cup of water, place the pan over medium-high heat, stir, and bring to a boil. Reduce the heat to low and simmer, covered, for 3 minutes. Remove the saucepan from the heat and let stand, still covered, overnight. Then strain into an airtight container and refrigerate up to 3 weeks. This cocktail is an ode to the tiki classic by Trader Vic. Brian Miller, of Death + Company in New York City, named this drink after his good friend Ty Baker, who was the commissioner of the Papa Doble "Beard-Off" best beard competition held at Death + Company in 2008. Although Miller was hoping to curry favor with Baker and the rest of the judges, it didn't do the trick. As much as they loved the drink, Miller and his beard finished third. 1 OUNCE FRESH LIME JUICE ⅛ OUNCE SIMPLE SYRUP ½ OUNCE RHUM CLÉMENT CRÉOLE SHRUBB LIQUEUR ½ OUNCE PREMIER ESSENCE ORGEAT ¼ OUNCE VIEUX PONTARLIER ABSINTHE 1 OUNCE LA FAVORITE BLANC RHUM 1 OUNCE FLOR DE CAÑA 7 YEAR RUM SPRIG OF MINT, for garnish Pour the lime juice, simple syrup, liqueur, orgeat essence, absinthe, and rums into a cocktail shaker. Add 3 ice cubes. Shake well and strain the drink into a coconut mug filled with crushed ice. Garnish with the mint sprig, and serve. Asimple recipe, this cocktail by John Gersten of Drink in Boston highlights how well absinthe mixes with anisette. 1 OUNCE ABSINTHE BLANCHE ½ OUNCE ANISETTE SODA WATER Pour the absinthe and anisette into a cocktail shaker filled with crushed ice. Shake well and strain the drink into a highball glass filled with ice. Top with soda water, and serve. LA BLEUE absinthe was a product made by bootleggers in the mountains of Switzerland. # LAST SECOND THE HOBNOB BLACK FAIRY BOTTEGA'S ABSINTHE MARTINI OBITUARY TRITTER RICKEY LAWHILL REMEMBER THE MAINE THE THIRD DEGREE BABU "B" MONSTER NORTH BY NORTHWEST CEDAR SHINGLE RATTLESNAKE RATTLESNAKE FIZZ ROBERT BURNS ON THE ROCKS Americans love their whiskey and gin, and just as these two spirits have experienced a love/hate relationship with the American public--their own legends and lore part of the unique history of the United States--both whiskey and gin happen to make great companions with a drink as storied and complex as absinthe. In fact, the pairing of absinthe with whiskey and gin marks a crossroads for the Green Fairy, as it heralds a level of acceptance not witnessed before by absinthe enthusiasts. As Americans become more accustomed to absinthe, it will increasingly become more prevalent in cultural events and on bar shelves, where gin and whiskey have been promoted throughout history. Last Second This cocktail by Jeff Hollinger of Absinthe Brasserie & Bar in San Francisco combines a variety of flavors including the malt flavor in Bols Genever, the herbal taste and aroma of Vieux Pontarlier absinthe, apricot brandy, and hint of mint bitter, an ingredient linking this cocktail to the popular mint julep and mojito. 2 OUNCES BOLS GENEVER ½ OUNCE VIEUX PONTARLIER ABSINTHE ½ OUNCE APRICOT BRANDY 1 DASH MINT BITTERS Pour the Bols Genever, Vieux Pontarlier absinthe, and apricot brandy into a cocktail shaker filled with ice, and add a dash of mint bitters. Stir for 20 to 30 seconds or until the drink is well chilled. Strain the drink into a chilled port glass, and serve. The Hobnob Hobnob is an archaic word that means "to drink socially." A hob is also a mischievous fairy, playing on the idea of absinthe as the Green Fairy. Jonathan Henson of Press Restaurant in Napa Valley, California, added grapefruit zest and lime zest to this recipe because they not only add a flavorful citrus note but also work to enhance the flavors of the absinthe. The mixture of the grapefruit zest and absinthe creates a gentle numbing sensation on the tongue. To enhance this effect, trying infusing the gin ahead of time with the zest of a grapefruit. ¼ OUNCE ABSINTHE ONE 1-INCH SQUARE OF GRAPEFRUIT ZEST ONE 1-INCH SQUARE OF LIME ZEST ½ OUNCE SIMPLE SYRUP ½ OUNCE FRESH GRAPEFRUIT JUICE ½ OUNCE FRESH LIME 2 OUNCES NO. 209 GIN ½ OUNCE LUXARDO MARASCHINO LIQUEUR STRIP OF GRAPEFRUIT RIND, for garnish Pour the absinthe into an empty rocks glass. Wash the glass with absinthe and pour out the excess. Set glass aside. Add grapefruit zest, lime zest, and simple syrup to a cocktail shaker. Muddle the zests until they begin to break apart. Add the grapefruit juice and lime juice. Fill the shaker with ice. Add the gin and maraschino liqueur. Shake hard. Strain the drink into the prepared glass. Garnish with a twist of grapefruit, and serve. THE 1997 FILM Wilde depicts the story of Oscar Wilde, the genius poet and playwright. He was famed for his love of absinthe, once saying, "The first stage is like ordinary drinking, the second when you begin to see monstrous and cruel things, but if you can persevere you will enter in upon the third stage where you will see things that you will want to see, wonderful curious things." Black Fairy The creator of this cocktail--Erika Fey of Cyrus in Healdsburg, California--frequently draws inspiration from the bounty of spectacular seasonal ingredients available from local Sonoma County farms to create unique cocktails with playful and surprising flavor combinations. 4 FRESH BLACKBERRIES FRESH MINT SPRIGS ¾ OUNCE KÜBLER ABSINTHE ¾ OUNCE MICHTER'S RYE WHISKEY ¾ OUNCE FRESH LEMON JUICE ¾ OUNCE FEVER TREE TONIC WATER In a cocktail shaker, muddle 3 of the blackberries with a mint sprig. Add the absinthe, rye whiskey, lemon juice, and tonic water. Fill the shaker with ice, and shake well. Strain the drink over an old-fashioned glass filled with fresh ice. Garnish with the remaining blackberry and a sprig of mint, and serve. WHEN STORING ABSINTHE, treat it as you would a bottle of wine. Keep it in a cool place, with a consistent temperature, and make sure it is out of direct sunlight. Also, any bottle with a cork should be stored on its side so that the cork does not dry out. Bottega's Absinthe Martini Despite having a degree in exercise science, Melissa Sheppard of Bottega in Napa Valley, California, discovered her true passion in life was for mixing drinks, which she has been doing for more than eight years. This delicious cocktail demonstrates that she made the right decision. If you'd like a fancier presentation, coat the rim of the glass with sugar. ½ OUNCE ST. GEORGE ABSINTHE 2 OUNCES BOMBAY SAPPHIRE GIN ½ OUNCE GRAND MARNIER ORANGE PEEL, for garnish Pour the absinthe into a chilled martini glass. Swirl to coat, then discard the remaining absinthe. Pour the gin and Grand Marnier into a cocktail shaker filled with ice. Shake well, and strain the drink into a martini glass. Garnish with orange peel, and serve. John Gersten from Drink in Boston recommends this cocktail he first enjoyed at the Lafite Blacksmith shop in the French Quarter of New Orleans. It's a very simple, old-school drink similar to a martini but with a fair amount of absinthe. It has a glow to it--not a "full-on louche," but a nice clarity--and makes an excellent predinner drink, crisp and refreshing. The Obituary is a little more appropriate for warm weather because of the lightness of the drink, but John wouldn't dissuade anyone from ordering it at any time of the year. 2¼ OUNCES GIN ½ OUNCE DRY VERMOUTH ¼ OUNCE ABSINTHE Pour the gin, vermouth, and absinthe into a chilled cocktail shaker, and stir to combine. Strain the drink into a cocktail glass, and serve. Following the "Absinthe Murders," newspapers released numerous editorials and cartoons that vilified absinthe by depicting morose skeletons dancing with bottles, bleary-eyed men sucking their thumbs in insane asylums, and haggard drunkards lining the streets with only their wicked bottles of absinthe to keep them warm. The media blitz destroyed absinthe's reputation and led French authorities to eventually ban the drink. The war against absinthe reached a pinnacle in Switzerland on July 5, 1908, when Article 32 was added to their federal constitution banning all absinthes in the nation. The law went into effect on October 7, 1910. Though the Swiss were not the first to ban absinthe, the new legislation would prove to be a significant victory for the temperance movement in stopping absinthe production, considering that Switzerland represented one of the largest demographics of absinthe drinkers in Europe, second only to France. By 1910, the consumption of absinthe in France had reached staggering levels. The liquor infiltrated every level of society, while alcoholism and drunkenness swept across the country. The French absinthe industry tried in vain to educate consumers on the truths of absinthe. The temperance groups, however, were also campaigning for their agenda, and they employed statistics and reports that stated that the potency and popularity of absinthe were responsible for the rise in the number of mental institution patients, suicides, and the general degradation of public health. In 1915, the temperance movement would claim victory over the Green Fairy as France banned both the production and sale of the beverage. Tritter Rickey Invented by Michael Tritter, this cocktail is prepared by Aaron Polsky of White Star in New York City. Aaron unexpectedly fell in love with the restaurant business when he got a side job as a food runner at Thomas Keller's Bouchon Bakery in New York. From bakery to barroom, Aaron enjoys the journey this drink has taken and how it pairs the notable taste of Swiss white absinthe with gin and mint leaves. SWISS WHITE ABSINTHE 1 OUNCE FRESH LIME JUICE ¾ OUNCE SUGAR SYRUP 4 FRESH MINT LEAVES 2 OUNCES GIN SODA WATER SPRIGS OF FRESH MINT, for garnish Pour the absinthe into a chilled Collins glass. Swirl to coat the glass, then discard the remaining absinthe. Set the glass aside. Pour the lime juice and sugar syrup into a cocktail shaker, and add the mint leaves. Muddle the mint for a few seconds, then add the gin. Fill the shaker with ice, and shake well. Fill the glass with ice and strain the drink into it. Top with soda. Garnish with a few sprigs of mint and a straw, and serve. Lawhill This flavorful cocktail, which includes the distinct taste of rye with dashes of maraschino liqueur and Angostura bitters, is a favorite of its creator, John Gersten of Drink in Boston. 2 OUNCES RYE ¾ OUNCE DRY VERMOUTH ¼ OUNCE ABSINTHE VERTE 1 DASH MARASCHINO LIQUEUR 1 DASH ANGOSTURA BITTERS Pour the rye, vermouth, absinthe, liqueur, and bitters into an iced cocktail shaker, and stir to combine. Strain the drink into a cocktail glass, and serve. ABSINTHE WAS EMBROILED in the plot of the suspenseful 1998 movie Deceiver, as Tim Roth's character, James Walter Wayland, suggests that his recent consumption of absinthe is to blame for his memory problems. Remember The Maine This rye-inspired cocktail was also developed by John Gersten of Drink in Boston. The sweet vermouth and Cheery Heering here work together to complement the absinthe. 2 OUNCES RYE ¾ OUNCE SWEET VERMOUTH ⅛ OUNCE CHERRY HEERING ⅛ OUNCE ABSINTHE 1 BRANDIED CHERRY, for garnish (optional) Pour the rye, vermouth, Cheery Heering, and absinthe into an iced cocktail shaker, and stir to combine. Strain the drink into a cocktail glass. Garnish with the brandied cherry on the side of the glass, if desired, and serve. The Third Degree After nine years of working in various positions at numerous restaurants, Ryan Fitzgerald eventually found himself with the opportunity to work behind the bar. For the past ten years, that's where he has remained, now bartending at Baretta in San Francisco. His passion for bartending led to the creation of this drink, which calls for Plymouth gin--the style of liquor, not the brand name. 2 OUNCES PLYMOUTH GIN 1 OUNCE DRY VERMOUTH 3 DASHES ABSINTHE Pour the gin, vermouth, and absinthe into a cocktail shaker filled with ice. Strain the drink into a chilled cocktail glass, and serve. Babu Timothy Bowman of Redd in the heart of Napa Valley, California, developed a seasonal drink repertoire to complement the restaurant's contemporary approach to Wine Country cuisine that offers serious food in an unpretentious, elegant atmosphere. This cocktail, with its earthy tones from Gabriel Boudier saffron-infused gin and Zubrowka bison grass vodka, is perfect for the spring and fall, when nature is in transition and organic fragrances fill the air. ABSINTHE 1½ OUNCES GABRIEL BOUDIER SAFFRON-INFUSED GIN ½ OUNCE ZUBROWKA BISON GRASS VODKA ½ OUNCE LEMON JUICE ¼ OUNCE SIMPLE SYRUP 1 EGG WHITE SODA WATER LONG LEMON PEEL, for garnish Pour the absinthe into a tall cocktail glass. Swirl to coat the glass, and discard the remaining absinthe. Set glass aside. Pour the gin, vodka, lemon juice, simple syrup, and egg white into a cocktail shaker. Hard shake for 30 seconds. Pour directly into the prepared glass and top with soda. Garnish the glass with a long strip of lemon peel, and serve. "B" Monster Marc Hartenfels of Bardessono in Napa Valley, California, offers this recipe that features handcrafted Leopold's gin and St. George absinthe. Marc recommends pairing this particular brand of gin and absinthe because both offer high-quality products that are diligently produced by artisans and not by corporate distilleries that mass-produce their spirits. 1½ OUNCES LEOPOLD'S GIN 1½ OUNCES FRESH GRAPEFRUIT JUICE 1 TABLESPOON ST. GEORGE ABSINTHE 1 TABLESPOON GRENADINE 1 STRIP OF LIME PEEL, for garnish Pour the gin, grapefruit juice, absinthe, and grenadine into a cocktail shaker. Shake well, and strain the drink into a small cocktail glass. Garnish the glass with the strip of lime peel, and serve. THE QUALITY of absinthe is still valued against pre-ban Pernod Fils absinthe, and bottles of the pre-ban product are so highly prized today that they sell for several thousands of dollars. North By Northwest This is Brian Miller's twist on the classic French 75. He was inspired by Cary Grant, who played Roger Thornhill in the classic Hitchcock film of the same name, and always wished he could've served him at the Oak Bar in the Plaza Hotel back in the day. If you'd like Brian to serve this drink to you, you can find him at Death \+ Company in New York City. ¾ OUNCE FRESH LEMON JUICE ¾ OUNCE SIMPLE SYRUP ¼ OUNCE VIEUX PONTARLIER ABSINTHE 1½ OUNCES AVIATION GIN CHAMPAGNE Pour the lemon juice, simple syrup, absinthe, and gin into a cocktail shaker. Shake well and strain the drink into a champagne flute. Top off with a splash of Champagne. Serve. Cedar Shingle Nantucket is known for its houses adorned in cedar shingle siding. This fall season drink from Sean S. Graves of Brant Point Grill at the famed White Elephant Resort, on the island off the coast of Massachusetts, pays homage to that fresh yellow color on a newly shingled house. You can find candied orange peels in specialty grocery stores. 3 OUNCES GIN 1½ OUNCES ABSINTHE SPLASH OF VERMOUTH SPLASH OF GRAND MARNIER CANDIED ORANGE PEELS, for garnish Pour the gin, absinthe, and vermouth into a cocktail shaker filled with ice. Shake for about 20 seconds. Strain the drink into a chilled martini glass, and add the Grand Marnier. Garnish with candied orange peels, and serve. Rattlesnake Aaron Polsky of White Star in New York City is a big fan of The Savoy Cocktail Book by Harry Craddock, first published in 1930, because it accounts for the true roots of America's most venerable cocktails. This respect for tradition inspired Aaron to create the Rattlesnake, which incorporates basic ingredients centered around a classic rye whiskey flavor. ABSINTHE 2 OUNCES AMERICAN RYE WHISKEY ¾ OUNCE FRESH LEMON JUICE ¾ OUNCE SIMPLE SYRUP 1 EGG WHITE Pour the absinthe into a chilled sour glass. Swirl to coat the glass, then discard the remaining absinthe. Set the glass aside. Pour the rye whiskey, lemon juice, simple syrup, and egg white into a cocktail shaker. Shake vigorously. Add ice to the shaker, and shake vigorously again. Strain the drink into the prepared glass, and serve. Rattlesnake Fizz One night while he was experimenting in his "laboratory," Tim Stookey of Presidio Social Club in San Francisco came up with this concoction. While he liked it, he was at a loss for what to call it. A few days later, he was at the bar telling his friend about it, when this person says he thinks he's heard of it. Stookey pulls out his iPhone, punches in the ingredients, and up pops a recipe for the Rattlesnake. So much for originality, but it solved the naming problem. Yet there is one difference: Stookey added ginger ale, so he has no qualms about introducing this as the Rattlesnake Fizz. 2 OUNCES RYE (80 PROOF) ¼ OUNCE ABSINTHE 1 OUNCE LEMON JUICE 1 TEASPOON SUGAR 1 EGG WHITE GINGER ALE ANGOSTURA BITTERS Pour the rye, absinthe, lemon juice, sugar, and egg white into a cocktail shaker filled with ice. Shake vigorously. Strain the drink into a highball glass that is filled three-quarters with ice. Top off with ginger ale, and add a drop of Angostura bitters. Serve. Robert Burns on the Rocks Another recipe from Aaron Polsky at White Star in New York City and his library of books featuring old-school recipes that have stood the test of time and changing tastes. Robert Burns on the Rocks, inspired by the pages of A. S. Crockett's The Old Waldorf-Astoria Bar Book, features a classic blending of whiskey and sweet vermouth--two tastes found in the popular Rob Roy cocktail--and absinthe. ABSINTHE 2 OUNCES SCOTCH WHISKEY ¾ OUNCES SWEET VERMOUTH 3 DROPS ORANGE BITTERS 1 CANDIED MARASCA CHERRY, for garnish Pour the absinthe into a chilled cocktail glass. Swirl to coat the glass, then discard the remaining absinthe. Set glass aside. Pour the scotch whiskey, vermouth, and orange bitters into a chilled cocktail shaker filled with freshly cracked ice, and stir to combine. Strain the drink into the prepared glass. Add a large chunk of ice. Garnish with the candied marasca cherry, and serve. # LOCAL SAZERAC THE BITTERSWEET YESTERDAY'S SONG ARGENTO'S DREAM APPETIZER L'ITALIENNE BLUE STEEL HEART GROWS FONDER THE HERMITAGE FLOWERS OF DISTINCTION Absinthe was created to be a medicine. It evolved into an aperitif by being mixed with water, but was combined with other mixers--sugar, orgeat syrup, anisette, gum syrup--since early in the nineteenth century. While continuing to be consumed as an aperitif, it further evolved into an ingredient used in cocktails around the end of the nineteenth century. Its complex aromas lend well to cocktails, especially and particularly when in the hands of skilled mixologists. The popularity of the historic Sazerac, for example, serves as an illustration of how absinthe's herbal qualities combine beautifully with other alcohols for a refreshing drink. Mixologists know that a successful cocktail is not just about taste--equally important are appearance and scent. Absinthe provides cocktails with an enticing look and aromatic presence before the beverage touches one's lips. Local Sazerac The Sazerac is one of the oldest known cocktails, with its origins in pre-Civil War New Orleans. The original drink, created by Antoine Amedee Peychaud in the 1830s, is based on a combination of cognac and bitters and is reported to be the first cocktail ever invented in America. The cocktail was named by John Schiller in 1859 upon the opening of his Sazerac Coffee House in New Orleans. Both most likely derive their name from a popular brand of cognac, Sazerac de Forge et Fils. The recipe here is from Marc Hartenfels of Bardessono in Napa Valley, California. 3 BIG DASHES ST. GEORGE ABSINTHE 2 OUNCES OSOCALIS BRANDY ¼ OUNCE SIMPLE SYRUP 2 DASHES PEYCHAUD'S BITTERS LEMON ZEST Fill a bucket glass with ice and the dashes of absinthe. Set aside. Pour the brandy, simple syrup, and bitters into a cocktail shaker, and stir to combine. Empty the ice from the prepared glass, and strain the drink into it. Twist the lemon zest over the glass and rub the rim. Discard the zest. Serve. This recipe from Jason Littrell of the Randolph at Broome in New York City offers a unique blending on flavors and influences, from the herbal aromatics of absinthe, Benedictine, and sweet Galliano to the bitter essence of Campari. 1½ OUNCES ABSINTHE ½ OUNCE CAMPARI ½ OUNCE GALLIANO ½ OUNCE BENEDICTINE 2 DASHES ORANGE BITTERS ½ OUNCE WATER ORANGE PEEL, for garnish Pour the absinthe, Campari, Galliano, Benedictine, bitters, and water into a cocktail shaker, and stir to combine. Strain into a rocks glass with one large piece of hand-cracked ice. Garnish with an orange peel, and serve. IN 1992, Frances Ford Coppola directed Dracula, a film based on the 1897 novel by Bram Stoker featuring the vampire Count Dracula played by Gary Oldman. After Dracula rapes and drinks the blood of his reincarnated wife Mina's best friend, he seduces Mina over a glass of absinthe and says to her, "Absinthe is the aphrodisiac of the self. The green fairy who lives in the absinthe wants your soul. But you are safe with me." The near-global ban of absinthe buried it in a grave of stigma and condemnation. The beverage faded away from social scenes around the world and was no longer drunk along the boulevards of Paris or the canals of New Orleans. Absinthe faded into obscurity. However, a small number of enthusiasts in the Val-de-Travers kept the legacy alive by preserving recipes, distilling practices, and vintage bottles. These clandestine artisans made the resurrection of absinthe possible. After France and Switzerland banned the drink, many other nations adopted an "out of sight, out of mind" tolerance for it. Though genuine absinthe remained nearly impossible to find in most countries, true absinthe was never technically prohibited in places such as Australia, Spain, and Portugal. In fact, many of these countries continued to produce absinthe for local consumption. Absinthe kept a low profile for more than eight years, but in the 1990s, technology changed everything. The Internet brought together absinthe enthusiasts from across the planet and allowed for the exchange of unbiased information about absinthe. Stories of the green drink started to appear in online chat rooms in the early 1990s. The Green Fairy had found a new social platform where it could dispel the stigmas of the past. This renewed interest in the drink, however, resulted in the proliferation of fake absinthes, most notably from the Czech Republic in 1994. Unsuspecting buyers were sold product that gave them a false introduction to the taste and quality of real absinthe--an unfortunate result of the beverage's resurrection that still persists in today's marketplace. Nevertheless, by the mid-1990s the world's perception of absinthe had changed. Yesterday's Song Though this shopping list is longer than most, don't be put off by it. Once you have the ingredients, you're just a few shakes away from being rewarded with a deliciously complex drink of rosemary, lime, and ginger beer, courtesy of Jeff Hollinger of Absinthe Brasserie & Bar in San Francisco. 1½ OUNCES CABANA CACHAÇA ½ OUNCE FRESH LIME JUICE ½ OUNCE OBSELLO ABSINTHE ¼ OUNCE RUNNY HONEY ¼ OUNCE MARASCHINO LIQUOR 1 DASH ANGOSTURA BITTERS GINGER BEER FRESH ROSEMARY SPRIG, for garnish Pour the cachaça, lime juice, absinthe, Runny Honey, liquor, and bitters into a cocktail shaker filled with ice. Shake for 20 to 30 seconds, or until well chilled. Strain the drink into a Collins glass filled with ice. Top with the ginger beer, and garnish with the rosemary sprig. Serve. Argento's Dream Owner Hari Nathan Kalyan of the Randolph at Broome in New York City developed this absinthe recipe using egg white, lemon juice, and simple syrup--a very creative combination. 1 EGG WHITE ¾ OUNCE FRESH LEMON JUICE ¾ OUNCE SIMPLE SYRUP 1 OUNCE AMARO ¾ OUNCE ABSINTHE VERTE 3 DASHES PEYCHAUD'S BITTERS In a cocktail shaker, whip the egg white with the lemon juice and simple syrup. Add the amaro and absinthe, and shake well. Pour into a glass filled with hand-cracked ice. Top with the bitters, and serve. TIM BURTON'S 1999 production of Sleepy Hollow features a constable named Ichabod Crane, played by Johnny Depp, who must solve mysterious murders taking place in 18th-century Sleepy Hollow. The constable drinks absinthe--but who wouldn't, given those circumstances? This recipe from John Gertsen of Drink in Boston has a distinct Italian influence from the sweet vermouth and Fernet Branca, which contributes a bitter, aromatic flavor to the herbal absinthe. These three flavors blend to offer a sense of old Italy full of earthly textures and balanced flavors. 2 OUNCES SWEET VERMOUTH 1 OUNCE FERNET BRANCA ⅛ OUNCE ABSINTHE BLANCHE ⅛ OUNCE SIMPLE SYRUP Pour the vermouth, Fernet Branca, absinthe, and simple syrup into a cocktail shaker, and stir to combine. Strain the drink into a single rocks glass, and serve. Blue Steel Serving short drinks in a tall glass, sans straw, is a favorite trick of Daniel Hyatt, a Michelin-recommended bartender for both 2009 and 2010, from San Francisco's Alembic. It encourages slow sipping and intensifies the aromatic experience. Blue Steel is one such drink, this one developed out of his love of the combination of berry flavors and absinthe. The sprig of cilantro is an ingenius, and delicious, finish. 2 OUNCES AGED JAMAICAN RUM ½ OUNCE CRÈME DE CASSIS 1 BARSPOON RYE WHISKEY 2 DASHES ANGOSTURA BITTERS 3 DASHES ABSINTHE THICK SLICE OF LEMON PEEL, for garnish FRESH CILANTRO SPRIG, for garnish Pour the rum, creme de cassis, rye whiskey, bitters, and absinthe into a highball glass. Add 3 or 4 large ice cubes and stir gently. Garnish with a thick slice of lemon peel and a small sprig of fresh cilantro. Serve. Heart Grows Fonder In the heart of California's wine country, Erika Fey of Cyrus artfully balances the traditional preparation of absinthe with modern flavors, such as blackberry and violets. 1 OUNCE KÜBLER ABSINTHE ¾ OUNCE BLACKBERRY SYRUP ½ OUNCE CRÈME DE VIOLETTE Pour absinthe into a rocks glass. Float the blackberry syrup over the absinthe, then float the creme de violette over the syrup. Place a serrated absinthe spoon on top of the glass with a large ice cube on top. Slowly drip ice water from an absinthe dripper over the ice cube. Once the portions of ice water and absinthe mixture are equal, stir the drink. Serve. THE FILM From Hell [2001] was based on the novel of the same name by Alan Moore and Eddie Campbell. The story, set in London in 1888, is about Jack the Ripper. Frederick Abberline, played by Johnny Depp, has psychic visions of the future with the help of opium and absinthe, and he uses these insights to help him solve the cases. The Hermitage Ryan Fitzgerald has helped open a variety of notable bars in San Francisco, including Bourbon & Branch, Tres Agaves, and Beretta. Influential in the San Francisco cocktail scene, Fitzgerald is known for his inventive combinations such as the Hermitage, an absinthe recipe that dares to blend a flavor of Mexico via the Del Maguey Chichicapa mezcal with red wine-based Dubonnet rouge and the complexity of Luxardo maraschino. 2 OUNCES DEL MAGUEY CHICHICAPA MEZCAL ¼ OUNCE LUXARDO MARASCHINO ¾ OUNCE DUBONNET ROUGE 3 DASHES GRAPEFRUIT BITTERS 3 DASHES ABSINTHE BROAD PIECE OF GRAPEFRUIT ZEST, for garnish Pour the mezcal, maraschino, Dubonnet rouge, bitters, and absinthe into a cocktail shaker filled with ice. Shake well, and strain the drink into a chilled cocktail glass. Garnish with the grapefruit zest, and serve. Flowers of Distinction This aptly named original cocktail, offered by Jason "Buffalo" Lograsso of Bourbon & Branch in San Francisco, is refreshing and feminine with a pleasantly strong, smoky backbone. All of the ingredients have some kind of floral connection, from the towering flower of the desert lily (from which mezcal is produced), to the stunning bright color and nuanced aromas of the lillet, to the lovely elderflower. 1 OUNCE DEL MAGUEY MEZCAL 1 OUNCE LILLET ROUGE 1 OUNCE ST. GERMAIN ELDERFLOWER LIQUEUR 1 OUNCE FRESH LEMON JUICE DASH ABSINTHE Pour the mezcal, lillet, elderflower liqueur, and lemon juice into a cocktail shaker. Shake well, and strain the drink into a cocktail glass. Add the dash of absinthe on the top of the drink, and serve. # NIGHT PORTER GILL SANS ABSINTHE FIZZ DEATH AT DUSK SACRED HEART EMERALD SOUND COCKTAIL GREEN GODDESS PASSION & 'PAGNE MEMORY LAPSE GREEN MONSTER PROMISSORY NOTE THYME AND PUNISHMENT With flare and flamboyance, daring and swagger, and grit and inanity, the recipes in this chapter are all about pushing the limit. So experiment with these recipes--and perhaps mix a few of your own. Preparing and drinking absinthe is an art form, and all great art requires an element or recklessness. So break out your favorite absinthe, pop the Champagne, and try a few of the following recipes before concocting your own. Consider absinthe a new and essential ingredient in your culinary cocktail arsenal. The best mixologists--both amateur and professional--are willing to test the boundaries of ingredients. With absinthe currently in its nascent stage on the American cocktail landscape, it is quite possible that the most popular absinthe drink has not been invented yet. Night Porter This cocktail recipe from Jeff Hollinger of Absinthe Brasserie & Bar in San Francisco offers the balanced richness of Dolin Blanc vermouth and its spicy, aromatic sensibility with Ruby port's claret color and Benesin mezcal's agave origins--a complex but rewarding blend of tastes and cultures. 1 OUNCE DOLIN BLANC VERMOUTH ¾ OUNCE PERNOD ABSINTHE ¾ OUNCE RUBY PORT ½ OUNCE BENESIN MEZCAL LEMON TWIST, for garnish Pour the vermouth, absinthe, port, and mezcal into a cocktail shaker filled with ice. Stir for 20 to 30 seconds, until well chilled. Strain the drink into a chilled cocktail glass. Garnish with the lemon twist, and serve. Gill Sans Among its many charms, absinthe is also infinitely versatile, as Jeff Hollinger of San Francisco's Absinthe Brasserie & Bar had long discovered. In this drink, the flavors of absinthe are blended perfectly with Manzanilla sherry, which evokes southern Spain's briny seashore climate, the dry, almond DNA of maraschino liqueur, and the smoothness of Plymouth gin. DUPLAIS BLANCHE ABSINTHE 2 OUNCES PLYMOUTH GIN ¾ OUNCE MANZANILLA SHERRY ¼ OUNCE MARASCHINO LIQUEUR 2 DASHES ORANGE BITTERS LEMON TWIST, for garnish Pour the absinthe into a chilled cocktail glass. Swirl to coat the glass, then discard the remaining absinthe. Set the glass aside. Pour the gin, sherry, liqueur, and bitters into a cocktail shaker filled with ice. Stir for 20 to 30 seconds, or until well chilled. Strain the drink into the prepared glass. Garnish with the lemon twist, and serve. Absinthe Fizz From the meticulous bartender John Gersten at Drink in Boston, this absinthe recipe features classic fizz ingredients and highball-glass style. 1 EGG WHITE 1½ OUNCES ABSINTHE BLANCHE ¾ OUNCE LEMON JUICE ¾ OUNCE SIMPLE SYRUP SODA WATER Pour the egg white, absinthe, lemon juice, and simple syrup into a cocktail shaker, and shake well. Add ice, and shake vigorously. Strain the drink into a cocktail glass. Top the drink with soda water, and serve. DIRECTOR BAZ LUHRMANN'S film Moulin Rouge [2001] relates the story of a glamorous yet seedy Moulin Rouge nightclub in 1899 Paris, featuring constant absinthe drinking, partying, sex, and drugs. Many of the characters are constantly high, and the "Green Fairy" (Kylie Minogue) makes her appearance as one of their drunken hallucinations. Death at Dusk This is a version of the cocktail Death in the Afternoon (absinthe and champagne), which was created for a 1935 book of humorous cocktail riffs called So Red the Nose, or Breath in the Afternoon. While Death in the Afternoon is a great name, San Francisco-based Neyah White, from Nopa, admits it is a little lacking as far as drinks go. The addition of creme de violette has a rounding effect and gives the drink some subtlety. ½ OUNCE CRÈME DE VIOLETTE 5 OUNCES SPARKLING WINE ¼ OUNCE ABSINTHE 1 MARASCHINO CHERRY, for garnish Pour the creme de violette and wine into a flute. Float the absinthe on top, and garnish with a maraschino cherry. Serve. Sacred Heart La Pinta pomegranate liqueur gives this drink its distinctive color and taste. The bold flavors were developed by Jeff Hollinger at San Francisco's Absinthe Brasserie & Bar. 1½ OUNCES LA PINTA POMEGRANATE LIQUEUR ¾ OUNCE PERNOD ABSINTHE ½ OUNCE LIMONCELLO ¼ OUNCE LEMON JUICE LEMON TWIST, for garnish Pour the pomegranate liqueur, absinthe, limoncello, and lemon juice into a cocktail shaker filled with ice. Shake for 10 to 15 seconds, until well chilled. Strain the drink into a chilled cocktail glass. Garnish with the lemon twist, and serve. Emerald Sound Cocktail The cocktail was inspired by a mint julep; this is the south Indian version. A refreshing drink, it is perfect for the spring or summer. The taste is layered, the peppery taste adding a little bit of heat. It looks fruity, but once you taste it, you get sweet, you get spice, you get a little bit of mint, and then the absinthe at the end, which really brings out all of the flavors. Created by Danny Louie, this and other exotic cocktails can be found at Dosa in San Francisco, where Danny is often behind the bar. ABSINTHE RINSE (St. George absinthe preferred) 8 MINT LEAVES 1½ OUNCES DOMAINE DE CANTON 1 OUNCE RYE WHISKEY (Rittenhouse 100 proof rye preferred) ¾ OUNCE MANGO GASTRIQUE (recipe follows) MANGO SLICE SPEARED WITH 3 CLOVES IN IT, for garnish MINT SPRIG, for garnish Pour absinthe into a chilled old-fashioned glass. Swirl to coat the glass, then discard any remaining absinthe. Set the glass aside. Put the mint, Domaine de Canton, rye, and Mango Gastrique into a cocktail shaker and fill three quarters full with ice. Shake well and strain the drink into the prepared glass that has been filled with crushed ice. Serve. MAKES ABOUT 1¾ CUPS 4 BIRD'S-EYE CHILES 2 CUPS MANGO NECTAR such as Looza Mango Nectar ½ CUP SUGAR ½ CUP CHAMPAGNE VINEGAR PINCH OF KOSHER SALT Grind the chiles in a spice grinder. Pour the mango nectar into a saucepan and add the chiles. Place the pan over medium heat and bring the mixture to a simmer. Add the sugar, vinegar, and salt, and stir until the sugar is dissolved. Simmer for 5 minutes. Remove the pan from the heat, and allow the mixture to cool. Strain the gastrique into an airtight container. Store, covered, in the refrigerator up to 7 days. Green Goddess This wonderful drink is perfect for the summertime. Neyah White of Nopa in San Francisco, who created it, always uses Genevese basil because other varieties of basil can augment the licorice flavors. 5 FRESH BASIL LEAVES 1½ OUNCES SQUARE ONE CUCUMBER ORGANIC VODKA ½ OUNCE SIMPLE SYRUP ½ OUNCE FRESH LIME JUICE ¼ OUNCE ABSINTHE 1 SPRIG OF FRESH THYME Muddle the basil in a cocktail shaker until all the leaves are bruised. Add the vodka, simple syrup, lime juice, absinthe, and thyme sprig. Fill the shaker with ice and shake hard. Strain the drink into a chilled cocktail glass. Shake the thyme sprig dry, then use it as a garnish. Serve. This simple yet pretty drink has a complex taste. After the tartness of the passionfruit and the sweetness of the cognac come the herbaceous qualities of absinthe. Sierra Zimei of Season Bar at the renowned Four Seasons Hotel, San Francisco, added the bubbles to make the drink even better. 1½ OUNCES NAVAN ½ OUNCE KÜBLER ABSINTHE 1½ OUNCES PASSIONFRUIT PURÉE 1 OUNCE BRUT CHAMPAGNE LIME TWIST Pour the Navan, absinthe, and passionfruit puree into a cocktail shaker filled with ice. Shake well, and strain the drink into a Champagne flute. Top with the Champagne. Garnish with the lime twist, and serve. SAN FRANCISCO hosts a rich culinary tradition and passionate cocktail culture. A trip to the city would not be complete without a visit to the speakeasy Bourbon & Branch (pictured here). Memory Lapse From Jeff Hollinger of Absinthe Brasserie & Bar in San Francisco, this recipe is unique in that it calls for house-made grenadine and a whole egg. Hollinger prefers to make his own grenadine because he can tailor it to his personal taste. Plus, it's very simple. During autumn when the temperature cools, he likes to add warm spices like cinnamon and cloves to his recipe for a rich grenadine--something that is much more rich than the sweetened cherry juice most people are used to drinking. 2 TO 3 LEAVES OF FRESH BASIL, torn into small pieces ½ OUNCE HOMEMADE GRENADINE (recipe follows) 2 OUNCES KÜBLER ABSINTHE 1 WHOLE EGG SODA WATER Muddle the basil with the grenadine in a cocktail shaker. Add the absinthe and the egg, fill the shaker with ice, and shake vigorously for at least 30 seconds or until the mixture feels light. Strain the cocktail into a chilled absinthe glass, and top with soda water. Serve. MAKES ABOUT 1½ CUPS 2 CUPS POMEGRANATE JUICE 3 TO 4 STAR ANISE PODS 3 ALLSPICE BERRIES 3 WHOLE CLOVES 2 CINNAMON STICKS ½ TABLESPOON SZECHUAN PEPPERCORNS, or to taste 1 TO 2 DRIED RED CHILES, optional 1 CUP SUGAR In a small pot, combine the pomegranate juice with the spices and bring to a low boil. Cover the pot, remove it from the heat, and allow the spices to infuse into the juice for at least 15 minutes. Strain the juice through a fine sieve into a measuring cup. Return the juice and an equal measurement of sugar to the pot and heat until the sugar dissolves. Allow the finished grenadine to cool and transfer it into a container from which it can be poured. This drink tastes a bit like root beer. Like any syrup, it will keep two to three weeks in the refrigerator. Green Monster In homage to Boston's Fenway Park, this drink from Sean S. Graves of Nantucket's Brant Point Grill, at the famous White Elephant Resort, is a great summer drink, especially if you're watching the Red Sox on TV or the kids playing catch in the yard. 1 OUNCE CRÈME DE MENTHE 1 OUNCE ABSINTHE 1 OUNCE HEAVY CREAM FRESH MINT LEAVES, for garnish Pour the creme de menthe, absinthe, and heavy cream into a cocktail shaker filled with ice. Shake for about 20 seconds. Strain the drink into a rocks glass filled with ice. Garnish with mint leaves, and serve. IN DIRECTOR STEPHEN SOMMERS'S film Van Helsing [2004], the main character Gabriel Van Helsing, played by Hugh Jackman, discovers the Frankenstein monster under a windmill crammed full with absinthe bottles. Van Helsing takes a few swigs of absinthe to calm his nerves--he is, after all, charged with the task of defeating evil, as well as serving as the archenemy to the mystical creature known as Dracula. Promissory Note Daniel Hyatt of the Alembic in San Francisco says this cocktail was inspired by the dry spiciness of dry vermouth and Canton liqueur, which was the first thing he mixed when he tried absinthe. The cocktail retains the character of all the ingredients, but has a great balance and harmony as a whole. ¾ OUNCE DRY VERMOUTH ¾ OUNCE REPOSADO TEQUILA 1 OUNCE DOMAINE DE CANTON GINGER LIQUEUR 1 BARSPOON HONEY 2 TO 3 DASHES ABSINTHE FRESHLY GRATED CINNAMON, for garnish THIN SLICE OF RADISH, for garnish Pour the vermouth, tequila, liqueur, honey, and absinthe in a cocktail shaker filled with cracked ice. Strain the drink into a chilled cocktail glass. Garnish with the cinnamon and radish slice, and serve. Thyme and Punishment Even though there is a lot of citrus in this cocktail, the prevailing flavor is of the thyme. The absinthe adds a layer of complexity, much as you would use a bitter in a different style of drink. This fresh, simple cocktail comes to us from Timothy Bowman of Redd in Napa Valley. ABSINTHE 5 SPRIGS OF FRESH THYME ½ OUNCE FRESH LEMON JUICE ½ OUNCE FRESH LIME JUICE ¼ OUNCE SIMPLE SYRUP 2 OUNCES TANQUERAY RANGPUR GIN BITTER LEMON SODA 2 SPRIGS OF FRESH THYME, for garnish Pour the absinthe into a tall cocktail glass. Swirl the glass to coat, then discard the remaining absinthe. Set the glass aside. Muddle the thyme, lemon juice, lime juice, and simple syrup in a cocktail shaker. Add the gin. Shake well, and strain into the prepared glass. Top with the soda. Garnish with the additional thyme, and serve. With more than two dozen absinthes approved for sale, whether domestic or imported, consumers have choices. As those numbers grow, the styles and quality will vary greatly. This guide includes a website address for each entry so you can learn more about a particular brand and research other aspects of absinthe that may interest you. The websites provide a wealth of information, from prices to locations in your area where absinthe can be purchased. $ = $30 TO $50 $$ = $51 TO $70 $$$ = $71 TO $100 $$$$ = MORE THAN $100 www.tempusfugitspirits.com Product of Switzerland * IMPORTED BY * Tempus Fugit Spirits, Petaluma, California * STYLE * Blanche (clear) * ALCOHOL * 60% (120 proof) * DISTILLERY * Matter-Luginbuhl, Kallnach, Switzerland * COST * $$ Duplais Blanche is crystal clear with pewter reflections. Warm yet complexly herbal nose with hints of mentholated wormwood, ground coriander, and candied angelica root. When louched, it produces a cloud-white opalescent in the glass, tinged with pewter. Full mouth-feel, silky, yet subdued, it tastes of a complex, heady blend of medicinal herbs with a lingering anise-bright sweetness that coats and caresses the tongue. This authentic Suisse Absinthe Blanche is a great value and represents one of the best modern absinthes based on traditional recipes. www.tempusfugitspirits.com Product of Switzerland * IMPORTED BY * Tempus Fugit Spirits, Petaluma, California * STYLE * Verte (green colored) * ALCOHOL * 68% (136 proof) * DISTILLERY * Matter-Luginbuhl, Kallnach, Switzerland * COST * $$$ In the glass, Duplais Verte has a very intense, pure tourmaline green color. When ice-cold water is slowly added, it releases a classic green-tinted, lightly billowing and opalescent louche. The aroma has subtle yet well-integrated wormwood notes with mint and alpine floral undertones. The taste is lightly creamy and crisp with a soothing anise and wormwood finish. At the current price, this authentic Suisse Absinthe Verte is a great value as it represents one of the best modern absinthes based on traditional recipes. www.greenwaydistillers.com Product of the United States * STYLE * Blanche (clear) * ALCOHOL * 45% (90 proof) * DISTILLERY * Greenway Distillers, Ukiah, California * COST * $$$ In the glass, Germain-Robin is colorless. Adding ice-cold water produces a milky-white louche. The aroma is star anise up front with fresh herbal undertones. The flavor is star anise with floral and spicy notes. It leaves a sweet-wormwood drynesss on the palate. At the current price, this all-natural authentic absinthe is a great value. www.tempusfugitspirits.com Product of France * IMPORTED BY * Tempus Fugit Spirits, Petaluma, California * STYLE * Verte (green colored) * ALCOHOL * 68% (136 proof) * DISTILLERY * Distillerie Paul Devoille, Fougerolles, France * COST * $$ In the glass, Heritage Verte is a deep, well-infused amber green color. Adding ice-cold water produces an intensely thick, yet reflective louche that completely captures the undiluted color of clouds. After ice water is added, it gives off a deep perfume of wormwood, anise, and fennel, which balance its relaxing yet bittersweet headiness. At the current price, this authentic French absinthe is a great value. www.kublerabsinthe.com Product of Switzerland * IMPORTED BY * Altamar Brands, LLC, Corona Del Mar, California * STYLE * Blanche (clear) * ALCOHOL * 53% (106 proof) * DISTILLERY * Distillerie Kubler, Motiers, Switzerland * COST * $$ In the glass, Kubler is colorless. Adding ice-cold water produces a milky white louche. The aroma is mainly anise up front with an undertone of wormwood and fennel. The taste is a well-balanced blend of wormwood, anise, and fennel. It leaves a slight sweetness on the palate, reminding, or should I say encouraging, you to take another sip. At the current price, this authentic Suisse Absinthe Blanche is an exceptional value. www.viridianspirits.com Product of Switzerland * IMPORTED BY * Viridian Spirits, Manhasset, New York * STYLE * Blanche (clear) * ALCOHOL * 53% (106 proof) * DISTILLERY * Claude-Alain Bugnon, Couvet, Switzerland * COST * $$$ In the glass, La Clandestine is colorless. Adding ice-cold water produces an opaque milky-white louche. The aroma is a bold blend of wormwood, anise, and fennel with herbal undertones. The taste is anise up front, with wormwood at the surface. The choice of herbs gives this absinthe a natural sweetness; adding a sugar cube at the drip may be too much. At the current price, this well-made authentic Suisse Absinthe Blanche is an exceptional value. www.lafee.com Product of France * IMPORTED BY * Green Utopia, Manhasset, New York * STYLE * Verte (green colored) * ALCOHOL * 68% (136 proof) * DISTILLERY * La Fee, Paris, France * COST * $$ In the glass, La Fee Parisienne is a lime-green color. Adding ice cold water produces a milky lime-green louche. The aroma after louche is mostly anise with wormwood below the surface. The flavor of anise stands out, with noticeable numbing on the tongue from the star anise. At the current price, this absinthe is an average value. www.leopoldbros.com Product of the United States * STYLE * Verte (green colored) * ALCOHOL * 65% (130 proof) * DISTILLERY * Leopold Bros., Denver, Colorado * COST * $$$ In the glass, Leopold Bros. Verte is a dark olive color. Adding ice-cold water produces a thick pale yellowish green louche. The aroma is fresh wormwood with citrusy hints. The flavor is predominantly wormwood on top with anise and fennel just under the surface. It is a bit sweet if dripped with a sugar cube. At the current price, this authentic absinthe is a good value. This absinthe is for experienced absintheurs with sophisticated palates. We think this product has potential. www.drinklucid.com Product of France * IMPORTED BY * Viridian Spirits, Manhasset, New York * STYLE * Verte (green colored) * ALCOHOL * 62% (124 proof) * DISTILLERY * Distillerie Combier, Saumur, France * COST * $$ In the glass, Lucid is a pale yellow and slightly clouded. Adding ice-cold water produces a nice opalescent milky white louche. The aroma is fresh with the anise-to-fennel ratio being well proportioned. The taste has an underlying herbal complexity that doesn't oversaturate the senses. It has a hint of wormwood bitterness that satisfies the palate. It's a good choice for first-time buyers looking to gain an appreciation of classic French absinthe. At the current price, this authentic absinthe is an exceptional value. www.tempusfugitspirits.com Product of Switzerland * IMPORTED BY * Tempus Fugit Spirits, Petaluma, California * STYLE * Verte (green colored) * ALCOHOL * 66.6% (133.2 proof) * DISTILLERY * Matter-Luginbuhl, Kallnach, Switzerland * COST * $$ In the glass, Mansinthe has an unusual, unique, yet natural green tint with light blue reflections. A slow-forming louche gives way to a thick green then white opalescence. Earthy, warm aromas, deep and musky, combine with light notes of alpine herbs and flowers. Initial flavors are round and savory with a full, buttery palate giving way to a balanced, refreshing, and complex finish. At the current price, this authentic Suisse absinthe is a great value. www.absinthe.at Product of Austria * IMPORTED BY * Fischer Schnapps, Manhasset, New York * STYLE * Verte (green colored) * ALCOHOL * 60% (120 proof) * DISTILLERY * Fischer Schnapps, Vienna, Austria * COST * $$ In the bottle, Mata Hari is emerald green. Adding ice-cold water gradually produces a nice louche. The aroma has a candylike characteristic with wormwood undertones. The spicy taste masks the other herbs. At the current price, this absinthe is an average value. www.viridianspirits.com Product of France * IMPORTED BY * Viridian Spirits, Manhasset, New York * STYLE * Verte (green colored) * ALCOHOL * 68% (136 proof) * DISTILLERY * Distillerie Combier, Saumur, France * COST * $$$$ In the glass, Nouvelle-Orleans has a rich natural green color. Adding ice-cold water gradually produces a thick white opaque louche. It has a soft floral aroma that is refreshing and well balanced. The taste is lightly creamy and sweet with a soothing anise-and-wormwood finish. At the current price, this authentic French Belle Époque-style absinthe is an exceptional value. www.obsello.com Product of Spain * IMPORTED BY * Esmeralda Liquors, Manhasset, New York * STYLE * Verte (green colored) * ALCOHOL * 50% (100 proof) * DISTILLERY * Esmeralda Liquors Distillery, Lleida, Spain * COST * $ In the glass, Obsello Verte is a natural- looking lime green. Adding ice-cold water quickly produces a nice cloudy louche. The aroma is fresh and minty with an anise top note with wormwood just below the surface. The taste is rich and creamy, and the mint adds a nice fresh finish. First-time buyers will enjoy the fresh herbs and rich flavors found in this classic Spanish absinthe. At the current price, this authentic Spanish absinthe is an exceptional value. www.tempusfugitspirits.com Product of the United States * DISTRIBUTED BY * Tempus Fugit Spirits, Petaluma, California * STYLE * Verte (green colored) * ALCOHOL * 62% (124 proof) * DISTILLERY * Pacific Distillery, Woodinville, Washington * COST * $$ In the glass, Pacifique Verte has a light, crystalline peridot green color. Brisk and intense nose with a warm spiciness blended with crisp alpine notes, a classic, southern French/Swiss profile. The mouth-feel is brisk yet herbal with a complex and clean flavor tinged with ozone notes. The finish is long and pensive. At the current price, this authentic absinthe is an exceptional value. www.pernod-ricard-usa.com Product of France * IMPORTED BY * Pernod Ricard USA, Purchase, New York * STYLE * Verte (green colored) * ALCOHOL * 68% (136 proof) * COST * $$ In the bottle, Pernod is a light olive-green color. Adding ice-cold water produces a pale-green louche. The aroma is subdued and mainly anise. The flavor is anise and lemon balm. Any hint of wormwood is not worth mentioning. First-time buyers can enjoy the experience of drinking Pernod, the namesake that launched the absinthe industry more than two hundred years ago. At the current price, this absinthe is a good value. www.northshoredistillery.com Product of the United States * STYLE * Verte (green colored) * ALCOHOL * 60% (120 proof) * DISTILLERY * North Shore Distillery, Lake Bluff, Illinois * COST * $$ In the bottle, Sirene Verte is olive green. Adding ice-cold water produces a pale-yellow louche. The aroma has a top note of anise and wormwood with fennel just below the surface. The taste is predominantly star anise, which masks the other herbs. This absinthe is sweet; adding a sugar cube at the drip may push it over the line. The anethole concentration leaves the tongue comfortably numb. At the current price, this authentic absinthe is a good value. www.vieuxcarreabsinthe.com Product of the United States * STYLE * Verte (green colored) * ALCOHOL * 60% (120 proof) * DISTILLERY * Philadelphia Distilling, Philadelphia, Pennsylvania * COST * $$ In the bottle, Vieux-Carre is a darker yellow-green color. Adding ice-cold water produces a pale yellow-green louche. The aroma is fresh wormwood with anise and fennel just below the surface. The taste starts out with wormwood bitterness followed by fennel-with-mint undertones. At the current price, this authentic absinthe is a great value. www.tempusfugitspirits.com Product of France * IMPORTED BY * Tempus Fugit Spirits, Petaluma, California * STYLE * Verte (green colored) * ALCOHOL * 65% (130 proof) * DISTILLERY * Distillerie Les Fils d'Emile Pernot, Pontarlier, France * COST * $$$ In the glass, Vieux Pontarlier is pale peridot green. Slowly dripping ice-cold water produces a lightly green-tinged and billowy opalescent louche. The aroma is fresh yet slightly briny and spicy with lightly mentholated notes. The flavors are multilayered, with subtle herbal undertones, and the anise and fennel are well balanced with a mentholated wormwood note. This authentic absinthe has been considered by a well-regarded critic as "the Gold Standard for the Absinthe category." ERIK ADKINS Adkins is responsible for the bar programs at the Slanted Door and Heaven's Dog in San Francisco. He consulted on the bar for Oakland's Flora and his drinks have appeared in the San Francisco Chronicle, New York Times, GQ, Food and Wine, San Francisco Magazine, and 7×7. ERIC ALPERIN Having relocated three years ago from New York City to Los Angeles, Alperin feels fortunate to have found a small, passionate, and ever-growing cocktail community. He has worked with Sasha Petraske at Milk & Honey and Little Branch, both in NYC. Most recently they partnered to open The Varnish in downtown Los Angeles. SCOTT BAIRD Cofounder of the Bon Vivants and owner of 15 Romolo, Baird, a lover of art in many forms, has worked jobs as diverse as florist, caterer, window display designer, and welder. As testament to his versatile, creative nature, he finds a way to implement his artistic eye in all of his work. TIMOTHY BOWMAN Bowman showcases his fourteen years of experience with updated classics and a collection of cocktails inspired by the seasons at Redd, in the heart of the Napa Valley. In 2003, his East Coast training landed him a position at Auberge du Soleil, where he met critically acclaimed executive chef Richard Reddington. JACKSON CANNON Together with three esteemed colleagues, Cannon formed the Jack Rose Society, dedicated to preserving the legacy of the art of the American cocktail. He has been featured in Boston Magazine, Imbibe Magazine, the Boston Globe, and the Beverage Journal. His cocktail program at Eastern Standard has received national attention from USA Today and Bacardi International. RYAN FITZGERALD After working in all different areas of all kinds of different restaurants, Fitzgerald finally got the opportunity to get behind the bar, and for the past ten years that's where he and his passion have remained. That decade has seen him work at a variety of notable bars in San Francisco, including Bourbon & Branch, Tres Agaves, and Beretta. ERIKA FEY Fey features expertly crafted classic cocktails on her menu at Cyrus, frequently drawing inspiration from the bounty of spectacular seasonal ingredients available from local Sonoma County farms to create unique cocktails with playful and surprising flavors and combinations. LIZA GERSHMAN An award-winning photographer and writer, Gershman splits her time between San Francisco and the Napa Valley. She is a lover of travel with a fondness for the emerging cocktail movement, and her work has appeared in many publications, including the San Francisco Chronicle, St. Helena Star, Calistoga Tribune, Datebook, Marin Magazine, 7×7, Drink Me, and Wine X. JOHN GERSTEN Regarded as one of Boston's most talented bartenders, Drink bar manager John Gertsen is also recognized locally and nationally as an expert on the history of cocktails. For several years, he served as an integral part of the No.9 Park bar program, before collaborating with Chef Barbara Lynch on the opening of Drink. SEAN S. GRAVES Graves's passion for mixology started with inventing drinks for his college roommates while he studied hospitality management at the University of Kansas. In 2005, he moved to Nantucket and worked various management positions at Nantucket Island Resorts but could not resist the allure of the bar. Last spring, he was appointed beverage supervisor at Brant Point Grill in the White Elephant. JOSH HARRIS Josh Harris, twenty-eight, is a San Francisco native inspired by the culinary arts and those eras that have come before this one. Harris, himself a bon vivant, is the founding partner of the consulting company the Bon Vivants. You can find him behind the bar at 15 Romolo in San Francisco. MARC HARTENFELS Hartenfels believes that generous service is the heart of the hospitality industry. The German-born restaurant specialist has served in the kitchens, behind the bar, and on the restaurant floors of some of the world's most respected resorts and hotels, including the Mandarin Oriental in London's Hyde Park and Napa Valley's Auberge du Soleil. Hartenfels embodies the idea that simple materials that are elevated and made by hand turn out the very best drinks. JONATHAN HENSON Henson's first food service job was as a dishwasher for a catering company on Martha's Vineyard in Massachusetts. His break came when he filled in for a sick bartender. A few cocktails and much research later, Henson found he had a talent for making drinks and entertaining guests, and loved it. JEFF HOLLINGER Hollinger is manager of Absinthe Brasserie & Bar in San Francisco, where he oversees all aspects of the restaurant. He enhanced Absinthe's classically driven cocktail philosophy by introducing cocktail concepts using seasonal fresh ingredients and balancing flavors of both old and new ingredients, developing fresh cocktail recipes and resurrecting forgotten classics. DANIEL HYATT Bay Area native Daniel Hyatt began his restaurant career as a teenager washing dishes and working in kitchens in Portland, Oregon. Most recently, in 2006, he opened the Alembic Bar in San Francisco with brewer and restaurateur David Mclean. His cocktails have been featured in numerous local and national publications. HARI NATHAN KALYAN Kalyan is the owner of the Randolph on Broome, between Bowery and Elizabeth, in New York City. MAE LANE Lane is a very colorful character. Apart from being a mixologist at Griffou, she is a country singer who loves the forties and dresses accordingly. She previously worked at Stanton Social as well as a few other popular New York venues. JASON LITTRELL As the beverage director of the Randolph at Broome, Littrell relishes the opportunity to troll Chinatown searching for unusual ingredients. Under Sasha Petraske's tutelage, he developed his signature style, which is equal parts great drink and great delivery. JASON "BUFFALO" LOGRASSO Buffalo became enchanted with San Francisco's food and drink culture on a visit in 2006. He first cut his teeth behind the bar at Coco500, going on to help open Oakland's Flora, Beretta in San Francisco, and the Alembic. He currently barkeeps at Bourbon & Branch. DANNY LOUIE Native of San Francisco, Louie has been honing his craft in the art of cocktails in the top bars for three years. Experimenting in everything from the avante garde to the classic, he enjoys synthesizing unique ingredients. Louie tends bar at Dosa on Fillmore and the Alembic. COLIN MCCARTHY Former bistro and bar manager at the Auberge du Soleil, McCarthy oversaw the design aspects of each cocktail menu at the resort's restaurant, Bistro and La Plage Pool bar, which reflected his extensive research in the traditions of classic concoctions and cutting-edge creations. He took his creativity east and opened Brinkley, a restaurant in New York City. JIM MEEHAN Meehan's fifteen-year career behind the bar spans from Madison, Wisconsin, to New York City. He has compiled the latest recipes for Mr. Boston's Bartending Guide, Food & Wine's annual cocktail book, and writes a column for Sommelier Journal. He is the general manager of PDT. BRIAN MILLER Miller has been working behind the stick in bars and restaurants in New York City for fifteen years. He has been quietly honing his craft in the East Village at Death + Company, where he is now head bartender. Miller recently started his own consulting company, Double Windsor Inc. AARON POLSKY Polsky began his career with a side job as a food runner opening Thomas Keller's Bouchon Bakery in New York. He later went on to study at culinary school in Paris, and returned to work at other New York restaurants before starting as a host at Sasha Petraske's Milk and Honey. In 2008, Petraske trained him to bartend at White Star. PAUL SCANDURA At the age of fifteen, Scandura was hired by Joseph Fretta, who trained him in homemade charcuterie, fresh sausages, and cheeses. Scandura continued his education at the Culinary Institute of America, where he received his degree and was bitten by the wine bug. He is currently the spirits program director of Martini House. PETER SCHAF Schaf has been described by cutting-edge food writer Louisa Chu as "the epicenter of the global absinthe revival" and is one of the most influential behind-the-scenes players in the modern absinthe renaissance. He is a self-taught absinthe historian and "distiller by experience." Schaf currently resides in Paris. MELISSA SHEPPARD Originally from Manchester, New Hampshire, Sheppard moved to California in 2008. She's been bartending for more than eight years, despite having a degree in exercise science. Mixing drinks is her forte. And she enjoys what California has to offer in terms of outdoor activities and, of course, what she considers the incredible wine and food. TIM STOOKEY After being a bellman there, Stookey was first asked to bartend at the Cafe Majestic in the Hotel Majestic in San Francisco. When the hotel was sold seven years later and Stookey found himself jobless at Christmastime, he was hired by Thad Vogler at the Presidio Social Club, where he has been ever since. MARCOS TELLO At the Edison in downtown Los Angeles, Tello can be found trying to bring nostalgia to life. The Edison is home to burlesque shows, fire dancers, and fluttering Green Fairies. SHANE TISON A proud native of rural Texas, Tison and his drinks have been featured in such publications as Vanity Fair, Houston Modern Luxury, and Food and Beverage. He is well recognized for cocktail creations for a number of prestigious fashion events in New York and around the world. JOHN TROIA The owner and cofounder of Tempus Fugit Spirits, Troia is a leading expert on absinthe and has been directly involved in bringing the best, award-winning absinthes to the U.S. market. In addition to developing and producing some of the finest absinthe accessories on the market, he has amassed perhaps the finest vintage absinthe poster collection in the world. Troia spends much of his time traveling throughout the United States for trainings and seminars for numerous distributors, bars, and restaurants. NEYAH WHITE White is currently the bar manager at Nopa in San Francisco, where his program is well respected for its array of house-produced bitters, tinctures, and liqueurs. He believes in a passive approach to menu setting where the local farms and orchards determine what is used by season rather than forcing ingredients into drinks. SIERRA ZIMEI For the past thirteen years, Zimei has been passionate about two things: traveling and bartending--one puts her in debt, and the other pulls her out. When she's not traveling, she can be found behind the bar at the Four Seasons in San Francisco. Absinthe and Old Lace Absinthe Drip Absinthe Fizz Amaro Argento's Dream Anisette Suissesse Appetizer L'Italienne Argento's Dream Arsenic and Old Lace Babu Basil Green Goddess Memory Lapse Benedictine The Bittersweet Cocktail a la Louisiane Bitter End Bitters, recipes with, 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 2.4, 2.5, 3.1, 3.2, 3.3, 3.4, 4.1, 4.2, 4.3, 4.4, 4.5, 5.1 Bittersweet, The Blackberries Black Fairy Heart Grows Fonder Black Fairy Blueberry Blue Rhone Fizz -Infused Gin Blue Rhone Fizz Blue Steel "B" Monkey "B" Monster Bols Genever Last Second Bottega's Absinthe Martini Brandy Pan American Clipper Quinquina Local Sazerac Brunelle Cachaça La Fiscus Verte The Strutters' Ball Yesterday's Song Calvados Pan American Clipper Campari The Bittersweet Canadian whisky North of the Border Cedar Shingle Champagne. See also Wine, sparkling Death in the Afternoon North by Northwest Passion and 'Pagne Chartreuse Iceberg Improved Polski Pousse Cafe Cocktail a la Louisiane Cognac Quinquina Cointreau Bitter End Corpse Reviver No.2 Corpse Reviver No.2 Creme de menthe Absinthe and Old Lace Green Monster Creme de violette Death at Dusk Heart Grows Fonder Death at Dusk Death in the Afternoon Dev's Pride Domaine de Canton Emerald Sound Cocktail Promissory Note Donn's Mix Dr. Funk Dubonnet rouge The Hermitage Elderflower liqueur Dev's Pride Flowers of Distinction Thai Hallucination Emerald Sound Cocktail Fernet Branca Appetizer L'Italienne Figs La Fiscus Verte Flowers of Distinction Galliano The Bittersweet Gill Sans Gin Absinthe and Old Lace Arsenic and Old Lace Babu Blueberry-Infused Blue Rhone Fizz "B" Monkey "B" Monster Bottega's Absinthe Martini Cedar Shingle Corpse Reviver No.2 Gill Sans The Hobnob Monkey Gland Monkey Gland No.2 North by Northwest Obituary The Third Degree Thyme and Punishment Tritter Rickey Grand Ti Punch Grapefruit juice "B" Monkey "B" Monster Green Goddess Green Monster Grenadine Homemade Memory Lapse Heart Grows Fonder Hermitage, The Hobnob, The Iceberg La Fiscus Verte L'Arc de Triomphe Last Second Lawhill Lemon juice Absinthe Fizz Argento's Dream Brunelle North by Northwest Rattlesnake Rattlesnake Fizz Lillet Blanc Corpse Reviver No.2 Quinquina Lillet Rouge Flowers of Distinction Lime juice Iceberg Tritter Rickey Mango Emerald Sound Cocktail Gastrique Memory Lapse Mezcal Flowers of Distinction The Hermitage Night Porter Mint Emerald Sound Cocktail Green Monster Tritter Rickey Monkey Gland Monkey Gland No.2 My Oh My Ty Navan Passion and 'Pagne Night Porter North by Northwest North of the Border Obituary Orange juice Dev's Pride L'Arc de Triomphe Monkey Gland Monkey Gland No.2 Osocalis brandy Local Sazerac Pan American Clipper Passionfruit Passion and 'Pagne Polski Pousse Cafe, Improved Pomegranate Homemade Grenadine Sacred Heart Port Night Porter Promissory Note Quinquina Rattlesnake Rattlesnake Fizz Remember the Maine Robert Burns on the Rocks Rum Blue Steel Dr. Funk Grand Ti Punch My Oh My Ty Zombie Punch Rye whiskey Black Fairy Cocktail a la Louisiane Emerald Sound Cocktail Lawhill Rattlesnake Rattlesnake Fizz Remember the Maine Salute to the Sazerac, A Sacred Heart Sazerac, Local Sazerac, Salute to the, A Scotch whiskey Robert Burns on the Rocks Sherry Gill Sans Strawberries Dev's Pride Strutters' Ball, The Tequila Promissory Note Thai Hallucination Third Degree, The Thyme and Punishment Tritter Rickey Vermouth Appetizer L'Italienne Arsenic and Old Lace Cocktail a la Louisiane Lawhill Night Porter Obituary Promissory Note Remember the Maine Robert Burns on the Rocks The Third Degree Vodka Babu Green Goddess Whiskey. See Canadian whisky, Rye whiskey, Scotch whiskey Wine, sparkling Death at Dusk Death in the Afternoon Passion and 'Pagne Yesterday's Song Zombie Punch
. Giant cell arteritis (Horton's disease) is an inflammatory panarteritis occurring most frequently in the elderly. Its common ocular manifestations are anterior ischemic optic neuropathy, choroidal ischemia and central retinal artery occlusion. We describe a case of Horton's disease revealed by a retinal detachment, optic neuropathy and severe choroidal ischemia. Prompt treatment with corticosteroids led to preservation of vision and resolution of the retinal detachment. This observation of a retinal detachment revealing a giant cell arteritis had not been yet reported in the literature.
// Verify that the signature of the function matches the operation's operands // and results. static LogicalResult VerifySignature(GraphFuncOp func, Operation *op, TypeRange operands, TypeRange results, const Twine &func_name) { auto attach_func = [&](InFlightDiagnostic diag) -> LogicalResult { return diag.attachNote(func.getLoc()).appendOp(*func, OpPrintingFlags()) << "\nsee referenced function"; }; ArrayRef<Type> arguments = func.getType().getInputs(); ArrayRef<Type> returns = func.getType().getResults(); if (operands.size() * 2 != arguments.size()) { return attach_func(op->emitOpError(func_name) << " function has " << arguments.size() / 2 << " arguments but was provided " << operands.size()); } if (results.size() != returns.size()) { return attach_func(op->emitOpError(func_name) << " function has " << returns.size() << " results but expected " << results.size()); } if (func.generic()) return success(); for (auto &it : llvm::enumerate(operands)) { auto arg_type = getElementTypeOrSelf(arguments[it.index() * 2]); auto op_type = getElementTypeOrSelf(it.value()); if (arg_type != op_type) { return attach_func( op->emitOpError(func_name) << " function argument #" << it.index() << " dtype " << arg_type << " does not match corresponding operand dtype: " << op_type); } } for (auto &it : llvm::enumerate(results)) { auto ret_type = getElementTypeOrSelf(returns[it.index()]); auto res_type = getElementTypeOrSelf(it.value()); if (ret_type != res_type) { return attach_func( op->emitOpError(func_name) << " function result #" << it.index() << " dtype " << ret_type << " does not match corresponding op result dtype: " << res_type); } } return success(); }
/** * This reporter stores information in the same tree as the file cache. */ public class TreeSiteErrorReporter extends BaseSiteErrorReporter { final static Logger log = LoggerFactory.getLogger(TreeSiteErrorReporter.class.getName()); private URL testedurl; private File hostdir; private String filename; private FileChannel mainchannel; private FileChannel minichannel; private PrintWriter mainwriter = null; private PrintWriter warningwriter = null; private PrintWriter miniwriter = null; private PrintWriter serialwriter = null; private FileDescriptor mainfd; private FileDescriptor minifd; private int lastSheetIndex = -1; private int lastWarningSheetIndex = -1; @Override public void startSiteReport(URL url) throws IOException { testedurl = url; hostdir = SampleSitesIT.getHostDirectory(url); filename = SampleSitesIT.encodeString(url.toExternalForm()).substring(0, 10); File mainfile = getMainFile(); File warningfile = getWarningFile(); File minifile = getMinificationFile(); File serialfile = getSerializationFile(); resetFile(mainfile); resetFile(warningfile); resetFile(minifile); resetFile(serialfile); } static File getGlobalFile(File cachedir) { return new File(cachedir, "fail.log"); } File getMainFile() { return new File(hostdir, filename + ".log"); } File getWarningFile() { return new File(hostdir, filename + ".warn"); } File getMinificationFile() { return new File(hostdir, filename + "-mini.err"); } File getSerializationFile() { return new File(hostdir, filename + "-rule.err"); } void resetFile(File file) throws IOException { if (file.exists()) { File oldfile = new File(file.getAbsolutePath() + ".old"); Files.move(file.toPath(), oldfile.toPath(), StandardCopyOption.REPLACE_EXISTING); } } @Override public void fail(String message) { PrintWriter pw; try { pw = new PrintWriter(new FileOutputStream(getGlobalFile(hostdir.getParentFile()), true)); pw.println(testedurl.toExternalForm()); pw.println(message); pw.println(); pw.close(); } catch (FileNotFoundException e) { log.error("Unable to write to " + getGlobalFile(hostdir.getParentFile()).getAbsolutePath(), e); } super.fail(message); } @Override public void minifiedMissingProperty(CSSStyleSheet<? extends CSSRule> parent, int ruleIndex, String cssText, String miniCssText, String property, String propertyValue) { String uri = parent.getHref(); String path = getLinkedSheetInternalPath(parent, uri); writeMinificationError("Minification issue in sheet at " + uri + "\npath: " + path); super.minifiedMissingProperty(parent, ruleIndex, cssText, miniCssText, property, propertyValue); } @Override public void minifiedExtraProperty(CSSStyleSheet<? extends CSSRule> parent, int ruleIndex, String cssText, String miniCssText, String property, String propertyValue) { String uri = parent.getHref(); String path = getLinkedSheetInternalPath(parent, uri); writeMinificationError("Minification issue in sheet at " + uri + "\npath: " + path); super.minifiedExtraProperty(parent, ruleIndex, cssText, miniCssText, property, propertyValue); } @Override public void reparsedMissingProperty(CSSStyleSheet<? extends CSSRule> parent, int ruleIndex, String cssText, String reparsedCssText, String property, String propertyValue) { String uri = parent.getHref(); String path = getLinkedSheetInternalPath(parent, uri); writeSerializationError("Reparse issue in sheet at " + uri + "\npath: " + path); super.reparsedMissingProperty(parent, ruleIndex, cssText, reparsedCssText, property, propertyValue); } @Override public void reparsedExtraProperty(CSSStyleSheet<? extends CSSRule> parent, int ruleIndex, String cssText, String reparsedCssText, String property, String propertyValue) { String uri = parent.getHref(); String path = getLinkedSheetInternalPath(parent, uri); writeSerializationError("Reparse issue in sheet at " + uri + "\npath: " + path); super.reparsedExtraProperty(parent, ruleIndex, cssText, reparsedCssText, property, propertyValue); } @Override public void reparsedDifferentValues(CSSStyleSheet<? extends CSSRule> parent, int ruleIndex, String cssText, String reparsedCssText, String property, String propertyValueText, String reparsedValueText) { String uri = parent.getHref(); String path = getLinkedSheetInternalPath(parent, uri); writeSerializationError("Reparse issue in sheet at " + uri + "\npath: " + path); super.reparsedDifferentValues(parent, ruleIndex, cssText, reparsedCssText, property, propertyValueText, reparsedValueText); } @Override public void ruleReparseIssue(CSSStyleSheet<? extends CSSRule> parent, int ruleIndex, String parsedText, String finalText) { String uri = parent.getHref(); String path = getLinkedSheetInternalPath(parent, uri); writeSerializationError("Reparse issue in sheet at " + uri + "\npath: " + path); super.ruleReparseIssue(parent, ruleIndex, parsedText, finalText); } @Override public void ruleReparseError(CSSStyleSheet<? extends CSSRule> parent, int ruleIndex, String parsedText, DOMException ex) { String uri = parent.getHref(); String path = getLinkedSheetInternalPath(parent, uri); writeSerializationError("Reparse error in sheet at " + uri + "\npath: " + path); super.ruleReparseError(parent, ruleIndex, parsedText, ex); } @Override void writeError(String message, Throwable exception) { enableMainWriter(); mainwriter.println(message); exception.printStackTrace(mainwriter); } @Override void writeError(String message) { enableMainWriter(); mainwriter.println(message); } @Override void writeWarning(String message) { enableWarningWriter(); warningwriter.println(message); } private void enableMainWriter() { if (mainwriter == null) { try { FileOutputStream out = new FileOutputStream(getMainFile()); mainchannel = out.getChannel(); mainfd = out.getFD(); mainwriter = new PrintWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8)); } catch (IOException e) { log.error("Unable to write to " + getMainFile().getAbsolutePath(), e); } } } private void enableWarningWriter() { if (warningwriter == null) { try { FileOutputStream out = new FileOutputStream(getWarningFile()); warningwriter = new PrintWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8)); } catch (IOException e) { log.error("Unable to write to " + getWarningFile().getAbsolutePath(), e); } } } @Override void writeMinificationError(String message) { if (miniwriter == null) { try { FileOutputStream out = new FileOutputStream(getMinificationFile()); minichannel = out.getChannel(); minifd = out.getFD(); miniwriter = new PrintWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8)); } catch (IOException e) { log.error("Unable to write to " + getMinificationFile().getAbsolutePath(), e); } } miniwriter.println(message); } @Override void writeSerializationError(String message) { enableSerializationWriter(); serialwriter.println(message); } @Override void writeSerializationError(String message, DOMException exception) { enableSerializationWriter(); serialwriter.println(message); exception.printStackTrace(serialwriter); } private void enableSerializationWriter() { if (serialwriter == null) { try { FileOutputStream out = new FileOutputStream(getSerializationFile()); serialwriter = new PrintWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8)); } catch (IOException e) { log.error("Unable to write to " + getSerializationFile().getAbsolutePath(), e); } } } @Override void selectErrorTargetSheet(StyleSheet sheet, int sheetIndex) { if (lastSheetIndex != sheetIndex) { selectTargetSheet(sheet, sheetIndex, false); lastSheetIndex = sheetIndex; } } @Override void selectWarningTargetSheet(StyleSheet sheet, int sheetIndex) { if (lastWarningSheetIndex != sheetIndex) { selectTargetSheet(sheet, sheetIndex, true); lastWarningSheetIndex = sheetIndex; } } private void selectTargetSheet(StyleSheet sheet, int sheetIndex, boolean warn) { CSSElement owner; if ((owner = (CSSElement) sheet.getOwnerNode()) != null && "style".equalsIgnoreCase(owner.getTagName())) { // Embedded sheet String text; if (owner instanceof DOMElement) { text = ((DOMElement) owner).getText(); } else { text = owner.getTextContent(); } text = text.trim(); if (text.length() != 0) { String filename = SampleSitesIT.encodeString(text).substring(0, 8); File sheetfile = new File(hostdir, filename + ".css"); FileOutputStream out = null; try { out = new FileOutputStream(sheetfile); out.write(text.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { } finally { if (out != null) { try { out.close(); } catch (IOException e) { } } } String msg = "Sheet: " + sheetfile.getAbsolutePath(); if (warn) { writeWarning(msg); } else { writeError(msg); } } } else { String uri = sheet.getHref(); String path = getLinkedSheetInternalPath(sheet, uri); String msg = "Sheet at " + uri + "\npath: " + path; if (warn) { writeWarning(msg); } else { writeError(msg); } } } private String getLinkedSheetInternalPath(StyleSheet sheet, String uri) { String path; try { URL url = new URL(uri); path = SampleSitesIT.encodeString(url.toExternalForm()); path = url.getHost() + '/' + path; } catch (MalformedURLException e) { path = "-"; } return path; } @Override public void close() throws IOException { if (serialwriter != null) { serialwriter.flush(); serialwriter.close(); } if (warningwriter != null) { if (warningwriter.checkError()) { log.error("Problems writing to " + getWarningFile().getAbsolutePath()); } warningwriter.close(); warningwriter = null; } if (mainwriter != null) { if (mainwriter.checkError()) { log.error("Problems writing to " + getMainFile().getAbsolutePath()); } mainfd.sync(); mainchannel.force(true); mainwriter.close(); mainwriter = null; } if (miniwriter != null) { if (miniwriter.checkError()) { log.error("Problems writing to " + getMinificationFile().getAbsolutePath()); } minifd.sync(); minichannel.force(true); miniwriter.close(); miniwriter = null; } } }
def apiversion(self, apiversion): self._apiversion = apiversion
/** * The main set of web services. */ @Named @Singleton public class DatasetAndServiceAndUserController extends Controller { private final DatasetAndUserRepository datasetAndUserRepository; private final ServiceAndUserRepository serviceAndUserRepository; private final DatasetRepository datasetRepository; private final UserRepository userRepository; private final ServiceExecutionLogRepository serviceExecutionLogRepository; private final ServiceAndDatasetRepository serviceAndDatasetRepository; @Inject public DatasetAndServiceAndUserController( final DatasetAndUserRepository datasetAndUserRepository, final UserRepository userRepository, final ServiceAndUserRepository serviceAndUserRepository, final ServiceAndDatasetRepository serviceAndDatasetRepository, final DatasetRepository datasetRepository, final ServiceExecutionLogRepository serviceExecutionLogRepository) { this.serviceAndDatasetRepository = serviceAndDatasetRepository; this.datasetAndUserRepository = datasetAndUserRepository; this.serviceAndUserRepository = serviceAndUserRepository; this.datasetRepository = datasetRepository; this.userRepository = userRepository; this.serviceExecutionLogRepository = serviceExecutionLogRepository; } public Result getAllDatasetsByUsers(long userId1, long userId2, String format) { List<BigInteger> datasets1 = datasetAndUserRepository.findByUserId(userId1); List<BigInteger> datasets2 = datasetAndUserRepository.findByUserId(userId2); List<BigInteger> datasetIds = new ArrayList<BigInteger>(); for (BigInteger datasetId1 : datasets1) { for (BigInteger datasetId2 : datasets2) { if (datasetId1.equals(datasetId2)) { datasetIds.add(datasetId1); } } } if (datasetIds.size() == 0) { System.out.println("No datasets found"); } List<Dataset> datasets = new ArrayList<Dataset>(); for (BigInteger id : datasetIds) { datasets.add(datasetRepository.findOne(id.longValue())); } String result = new String(); if (format.equals("json")) { result = new Gson().toJson(datasets); } return ok(result); } public Result getAllUsersByDatasets(long datasetId1, long datasetId2, String format) { List<BigInteger> users1 = datasetAndUserRepository.findByDatasetId(datasetId1); List<BigInteger> users2 = datasetAndUserRepository.findByDatasetId(datasetId2); List<BigInteger> userIds = new ArrayList<BigInteger>(); for (BigInteger userId1 : users1) { for (BigInteger userId2 : users2) { if (userId1.equals(userId2)) { userIds.add(userId1); } } } if (userIds.size() == 0) { System.out.println("No datasets found"); } List<User> users = new ArrayList<User>(); for (BigInteger id : userIds) { users.add(userRepository.findOne(id.longValue())); } String result = new String(); if (format.equals("json")) { result = new Gson().toJson(users); } return ok(result); } public Result getAllServicesByUsers(long userId1, long userId2, String format) { List<BigInteger> services1 = serviceAndUserRepository.findByUserId(userId1); List<BigInteger> services2 = serviceAndUserRepository.findByUserId(userId2); List<BigInteger> serviceIds = new ArrayList<BigInteger>(); for (BigInteger serviceId1 : services1) { for (BigInteger serviceId2 : services2) { if (serviceId1.equals(serviceId2)) { serviceIds.add(serviceId1); } } } if (serviceIds.size() == 0) { System.out.println("No datasets found"); } List<ServiceExecutionLog> services = new ArrayList<ServiceExecutionLog>(); for (BigInteger id : serviceIds) { services.add(serviceExecutionLogRepository.findOne(id.longValue())); } String result = new String(); if (format.equals("json")) { result = new Gson().toJson(services); } return ok(result); } public Result getAllServicesByDatasets(long datasetId1, long datasetId2, String format) { List<BigInteger> services1 = serviceAndDatasetRepository.findByDatasetId(datasetId1); List<BigInteger> services2 = serviceAndDatasetRepository.findByDatasetId(datasetId2); List<BigInteger> serviceIds = new ArrayList<BigInteger>(); for (BigInteger serviceId1 : services1) { for (BigInteger serviceId2 : services2) { if (serviceId1.equals(serviceId2)) { serviceIds.add(serviceId1); } } } if (serviceIds.size() == 0) { System.out.println("No datasets found"); } List<ServiceExecutionLog> services = new ArrayList<ServiceExecutionLog>(); for (BigInteger id : serviceIds) { services.add(serviceExecutionLogRepository.findOne(id.longValue())); } String result = new String(); if (format.equals("json")) { result = new Gson().toJson(services); } return ok(result); } public Result getAllUsersByServices(long serviceId1, long serviceId2, String format) { List<BigInteger> users1 = serviceAndUserRepository.findByServiceId(serviceId1); List<BigInteger> users2 = serviceAndUserRepository.findByServiceId(serviceId2); List<BigInteger> userIds = new ArrayList<BigInteger>(); for (BigInteger userId1 : users1) { for (BigInteger userId2 : users2) { if (userId1.equals(userId2)) { userIds.add(userId1); } } } if (userIds.size() == 0) { System.out.println("No datasets found"); } List<User> users = new ArrayList<User>(); for (BigInteger id : userIds) { users.add(userRepository.findOne(id.longValue())); } String result = new String(); if (format.equals("json")) { result = new Gson().toJson(users); } return ok(result); } public Result getAllDatasetsByServices(long serviceId1, long serviceId2, String format) { List<BigInteger> datasets1 = serviceAndDatasetRepository.findByServiceId(serviceId1); List<BigInteger> datasets2 = serviceAndDatasetRepository.findByServiceId(serviceId2); List<BigInteger> datasetIds = new ArrayList<BigInteger>(); for (BigInteger datasetId1 : datasets1) { for (BigInteger datasetId2 : datasets2) { if (datasetId1.equals(datasetId2)) { datasetIds.add(datasetId1); } } } if (datasetIds.size() == 0) { System.out.println("No datasets found"); } List<Dataset> datasets = new ArrayList<Dataset>(); for (BigInteger id : datasetIds) { datasets.add(datasetRepository.findOne(id.longValue())); } String result = new String(); if (format.equals("json")) { result = new Gson().toJson(datasets); } return ok(result); } }
<gh_stars>0 #ifndef IKMCRYPTO_H #define IKMCRYPTO_H #include <stdint.h> #include <cstddef> #include <vector> #include <string> #include <exception> #include <stdexcept> class ikmcrypto { public: virtual void set_key(const char *key, size_t byte_length); virtual void set_key_with_iv(const char *key, size_t byte_length, const char* iv, size_t iv_length); virtual uint16_t get_minimum_block_size() = 0; virtual std::vector<char> encrypt(const std::vector<char> &src) = 0; virtual std::vector<char> decrypt(const std::vector<char> &src) = 0; }; class kmcrypto_exception: public std::runtime_error { public: kmcrypto_exception(std::string what_message); }; #endif
def load_json(path, keys_to_int=False): def convert_keys_to_int(x): return {int(k) if k.lstrip("-").isdigit() else k: v for k, v in x.items()} with open(path, "r") as f: if keys_to_int: content = json.load(f, object_hook=lambda x: convert_keys_to_int(x)) else: content = json.load(f) return content
def _set_date_in_calendar( self, calendar_locator: Tuple[Tuple[str, str], int], target_date: date, month_locator: Tuple[str, str], prev_month_locator: Tuple[str, str], day_locator: Tuple[str, str], day_class_check: Tuple[str, ...] = None) -> None: self.logger.debug( '%s: setting date %s in calendar.', self.name, str(target_date)) self._open_calendar(calendar_locator) try: self._set_month_in_calendar( prev_month_locator, month_locator, target_date) self._set_day_in_calendar( day_locator, target_date, day_class_check) except RuntimeError: raise RuntimeError(self.errors.calendar_date_not_found)
use std::io; use structs::Worksheet; use super::driver::*; use super::XlsxError; pub(crate) fn write<W: io::Seek + io::Write>( worksheet: &Worksheet, arv: &mut zip::ZipWriter<W>, sub_dir: &str, ole_bin_id: &mut usize, ole_excel_id: &mut usize, ) -> Result<(), XlsxError> { for ole_object in worksheet.get_ole_objects().get_ole_object() { if ole_object.is_bin() { let file_name = format!("oleObject{}.bin", ole_bin_id); let writer = ole_object.get_object_data().as_ref().unwrap(); let _ = make_file_from_bin(&file_name, arv, writer, Some(sub_dir)).unwrap(); *ole_bin_id += 1; } if ole_object.is_xlsx() { let file_name = format!("Microsoft_Excel_Worksheet{}.xlsx", ole_excel_id); let writer = ole_object.get_object_data().as_ref().unwrap(); let _ = make_file_from_bin(&file_name, arv, writer, Some(sub_dir)).unwrap(); *ole_excel_id += 1; } } Ok(()) }
/* Copyright 2020 CLOUD&HEAT Technologies GmbH * * 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 agent import ( "fmt" "io" "sort" "text/template" corev1 "k8s.io/api/core/v1" "github.com/cloudandheat/ch-k8s-lbaas/internal/config" "github.com/cloudandheat/ch-k8s-lbaas/internal/model" ) var ( nftablesTemplate = template.Must(template.New("nftables.conf").Parse(` {{ $cfg := . }} table {{ .FilterTableType }} {{ .FilterTableName }} { chain {{ .FilterForwardChainName }} { ct mark {{ $cfg.FWMarkBits | printf "0x%x" }} and {{ $cfg.FWMarkMask | printf "0x%x" }} accept; } } table ip {{ .NATTableName }} { chain {{ .NATPreroutingChainName }} { {{ range $fwd := .Forwards }} {{ if ne ($fwd.DestinationAddresses | len) 0 }} ip daddr {{ $fwd.InboundIP }} {{ $fwd.Protocol }} dport {{ $fwd.InboundPort }} mark set {{ $cfg.FWMarkBits | printf "0x%x" }} and {{ $cfg.FWMarkMask | printf "0x%x" }} ct mark set meta mark dnat to numgen inc mod {{ $fwd.DestinationAddresses | len }} map { {{- range $index, $daddr := $fwd.DestinationAddresses }}{{ $index }} : {{ $daddr }}, {{ end -}} } : {{ $fwd.DestinationPort }}; {{ end }} {{ end }} } chain {{ .NATPostroutingChainName }} { mark {{ $cfg.FWMarkBits | printf "0x%x" }} and {{ $cfg.FWMarkMask | printf "0x%x" }} masquerade; } } `)) ErrProtocolNotSupported = fmt.Errorf("Protocol is not supported") ) type nftablesForward struct { Protocol string InboundIP string InboundPort int32 DestinationAddresses []string DestinationPort int32 } type nftablesConfig struct { FilterTableType string FilterTableName string FilterForwardChainName string NATTableName string NATPostroutingChainName string NATPreroutingChainName string FWMarkBits uint32 FWMarkMask uint32 Forwards []nftablesForward } type NftablesGenerator struct { Cfg config.Nftables } func copyAddresses(in []string) []string { result := make([]string, len(in)) copy(result, in) return result } func (g *NftablesGenerator) mapProtocol(k8sproto corev1.Protocol) (string, error) { switch k8sproto { case corev1.ProtocolTCP: return "tcp", nil case corev1.ProtocolUDP: return "udp", nil default: return "", ErrProtocolNotSupported } } func (g *NftablesGenerator) GenerateStructuredConfig(m *model.LoadBalancer) (*nftablesConfig, error) { result := &nftablesConfig{ FilterTableName: g.Cfg.FilterTableName, FilterTableType: g.Cfg.FilterTableType, FilterForwardChainName: g.Cfg.FilterForwardChainName, NATTableName: g.Cfg.NATTableName, NATPostroutingChainName: g.Cfg.NATPostroutingChainName, NATPreroutingChainName: g.Cfg.NATPreroutingChainName, FWMarkBits: g.Cfg.FWMarkBits, FWMarkMask: g.Cfg.FWMarkMask, Forwards: []nftablesForward{}, } for _, ingress := range m.Ingress { for _, port := range ingress.Ports { mappedProtocol, err := g.mapProtocol(port.Protocol) if err != nil { return nil, err } addrs := copyAddresses(port.DestinationAddresses) sort.Strings(addrs) result.Forwards = append(result.Forwards, nftablesForward{ Protocol: mappedProtocol, InboundIP: ingress.Address, InboundPort: port.InboundPort, DestinationAddresses: addrs, DestinationPort: port.DestinationPort, }) } } sort.SliceStable(result.Forwards, func(i, j int) bool { fwdA := &result.Forwards[i] fwdB := &result.Forwards[j] isLess := fwdA.InboundIP < fwdB.InboundIP if isLess { return true } if fwdA.InboundIP != fwdB.InboundIP { return false } return fwdA.InboundPort < fwdB.InboundPort }) return result, nil } func (g *NftablesGenerator) WriteStructuredConfig(cfg *nftablesConfig, out io.Writer) error { return nftablesTemplate.Execute(out, cfg) } func (g *NftablesGenerator) GenerateConfig(m *model.LoadBalancer, out io.Writer) error { scfg, err := g.GenerateStructuredConfig(m) if err != nil { return err } return g.WriteStructuredConfig(scfg, out) }
// Helper to build a chunk. Caller takes ownership. std::unique_ptr<SBChunkData> BuildChunk( int chunk_number, ChunkData::ChunkType chunk_type, ChunkData::PrefixType prefix_type, const void* data, size_t data_size, const std::vector<int>& add_chunk_numbers) { std::unique_ptr<ChunkData> raw_data(new ChunkData); raw_data->set_chunk_number(chunk_number); raw_data->set_chunk_type(chunk_type); raw_data->set_prefix_type(prefix_type); raw_data->set_hashes(data, data_size); raw_data->clear_add_numbers(); for (size_t i = 0; i < add_chunk_numbers.size(); ++i) { raw_data->add_add_numbers(add_chunk_numbers[i]); } return std::make_unique<SBChunkData>(std::move(raw_data)); }
/** * Check ttl manager for memory leak. */ @RunWith(JUnit4.class) public class GridCacheTtlManagerLoadTest extends GridCacheTtlManagerSelfTest { /** * @throws Exception If failed. */ @Test public void testLoad() throws Exception { cacheMode = REPLICATED; final IgniteKernal g = (IgniteKernal)startGrid(0); try { final AtomicBoolean stop = new AtomicBoolean(); IgniteInternalFuture<?> fut = multithreadedAsync(new Callable<Object>() { @Override public Object call() throws Exception { IgniteCache<Object,Object> cache = g.cache(DEFAULT_CACHE_NAME). withExpiryPolicy(new TouchedExpiryPolicy(new Duration(MILLISECONDS, 1000))); long key = 0; while (!stop.get()) { cache.put(key, key); key++; } return null; } }, 1); GridCacheTtlManager ttlMgr = g.internalCache(DEFAULT_CACHE_NAME).context().ttl(); for (int i = 0; i < 5; i++) { U.sleep(5000); ttlMgr.printMemoryStats(); } stop.set(true); fut.get(); } finally { stopAllGrids(); } } /** {@inheritDoc} */ @Override protected long getTestTimeout() { return Long.MAX_VALUE; } }
<filename>packages/client/src/context/stdioSocketContext.tsx /* eslint-disable no-console */ import { StdioMessage, StdioMessageDirection, StdioMessageType } from '@experiterm/shared'; import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; function formatMessage(msg: Omit<StdioMessage, 'direction'>) { return JSON.stringify({ ...msg, direction: StdioMessageDirection.INPUT }); } export interface StdioSocketContextProps { messages: StdioMessage[]; socket: WebSocket; sendMessage: (...args: Parameters<typeof formatMessage>) => void; } const context = createContext<StdioSocketContextProps | null>(null); export const StdioSocketProvider = ({ children }: { children: React.ReactNode | React.ReactNode[] }) => { const sockRef = useRef(new WebSocket(process.env.STDIO_SOCKET_URL)); const [messages, setMessages] = useState<StdioMessage[]>([]); const handleConnection = useCallback(() => { console.info('STDIO socket has connected'); }, []); const handleMessage = useCallback((e: MessageEvent<string>) => { const parsed = JSON.parse(e.data) as StdioMessage; if (parsed.type === StdioMessageType.HELLO) { console.info('%cSocket connected and said hello!', 'color: green;'); return sockRef.current.send(formatMessage({ message: '', time: Date.now(), type: StdioMessageType.SHELL_START })); } setMessages(prev => prev.concat(parsed)); }, []); const sendMessage = useCallback( (...args: Parameters<typeof formatMessage>) => sockRef.current.send(formatMessage(...args)), [], ); const props = useMemo( (): StdioSocketContextProps => ({ messages, sendMessage, socket: sockRef.current }), [messages, sendMessage], ); useEffect(() => { const { current: sock } = sockRef; sock.addEventListener('open', handleConnection); sock.addEventListener('message', handleMessage); return () => { sock.removeEventListener('open', handleConnection); sock.removeEventListener('message', handleMessage); }; }, [handleConnection, handleMessage]); return <context.Provider value={props}>{children}</context.Provider>; }; export function useStdioSocketContext() { const ctx = useContext(context); if (!ctx) { throw new Error('Unable to read from <StdioSocketProvider />. Is one in the render tree?'); } return ctx; }
/** * Remove domain name from roles except the hybrid roles (Internal,Application & Workflow). * * @param domainAwareRolesList list of roles assigned to a user. * @return String of multi attribute separated list of roles assigned to a user with domain name removed from roles. */ public static String removeDomainFromNamesExcludeHybrid(List<String> domainAwareRolesList) { List<String> roleList = new ArrayList<String>(); for (String role : domainAwareRolesList) { String userStoreDomain = IdentityUtil.extractDomainFromName(role); if (UserCoreConstants.INTERNAL_DOMAIN.equalsIgnoreCase(userStoreDomain) || APPLICATION_DOMAIN .equalsIgnoreCase(userStoreDomain) || WORKFLOW_DOMAIN.equalsIgnoreCase(userStoreDomain)) { roleList.add(role); } else { roleList.add(UserCoreUtil.removeDomainFromName(role)); } } return String.join(FrameworkUtils.getMultiAttributeSeparator(), roleList); }
/** * Main Terramap addon class * * @author SmylerMC */ public class TerramapAddon implements Module, Listener { public static TerramapAddon instance; public static final String TERRAMAP_MODID = "terramap"; public static final String MAPSYNC_CHANNEL_NAME = "terramap:mapsync"; public static final String SLEDGEHAMMER_CHANNEL_NAME = "terramap:sh"; // Forge does not support channel names longer than 20 public static final TerramapVersion MINIMUM_COMPATIBLE_VERSION = new TerramapVersion(1, 0, 0, ReleaseType.BETA, 6, 0); public static final String PLAYER_SYNC_PERMISSION_NODE = "sledgehammer.terramap.playersync"; public static final String TERRASHOW_BASE_PERMISSION_NODE = "sledgehammer.terramap.terrashow"; public static final String TERRASHOW_SELF_PERMISSION_NODE = "sledgehammer.terramap.terrashow.self"; public static final String TERRASHOW_OTHERS_PERMISSION_NODE = "sledgehammer.terramap.terrashow.other"; public final ForgeChannel mapSyncChannel = new ForgeChannel(MAPSYNC_CHANNEL_NAME); public final ForgeChannel sledgehammerChannel = new ForgeChannel(SLEDGEHAMMER_CHANNEL_NAME); public final RemoteSynchronizer synchronizer = new RemoteSynchronizer(); private Listener listener; private ScheduledTask syncTask; private UUID proxyUUID = new UUID(0, 0); public TerramapAddon() { instance = this; } @Override public void onEnable() { this.mapSyncChannel.registerPacket(0, C2PRegisterForUpdatePacket.class); this.mapSyncChannel.registerPacket(1, P2CPlayerSyncPacket.class); this.mapSyncChannel.registerPacket(2, P2CRegistrationExpiresPacket.class); this.sledgehammerChannel.registerPacket(0, P2CSledgehammerHelloPacket.class); this.sledgehammerChannel.registerPacket(2, P2CMapStylePacket.class); try { this.proxyUUID = UUID.fromString(SledgehammerConfig.terramap.terramapProxyUUID); } catch (IllegalArgumentException e) { Sledgehammer.logger.warning("Failed to parse Terramap proxy uuid. Will be using 0."); } this.listener = new TerramapAddonEventHandler(); Sledgehammer.addListener(this.listener); if (SledgehammerConfig.terramap.terramapSyncPlayers) { this.syncTask = Sledgehammer.getInstance().getProxy().getScheduler().schedule(Sledgehammer.getInstance(), this.synchronizer::syncPlayers, 0, SledgehammerConfig.terramap.terramapSyncInterval, TimeUnit.MILLISECONDS); } ProxyServer.getInstance().getPluginManager().registerCommand(Sledgehammer.getInstance(), new TerrashowCommand()); } @Override public void onDisable() { this.mapSyncChannel.resetPacketRegistration(); this.sledgehammerChannel.resetPacketRegistration(); this.proxyUUID = new UUID(0, 0); this.synchronizer.unregisterAllPlayers(); Sledgehammer.removeListener(this.listener); if (this.syncTask != null) { Sledgehammer.getInstance().getProxy().getScheduler().cancel(this.syncTask); } } @Override public String getModuleName() { return "Terramap"; } public UUID getProxyUUID() { return this.proxyUUID; } }
/** Transaction test case. * * @author little-pan * @since 2019-09-26 * */ public class TransactionTest extends TestDbBase { public static void main(String args[]) throws SQLException { new TransactionTest().test(); } @Override protected void doTest() throws SQLException { initTableAccounts(); nestedConnTxTest(); readOnlyTxTest(1); readOnlyTxTest(2); readOnlyTxTest(10); readOnlyTxTest(100); rrTxTest(100, 10); rrTxTest(100, 50); rrTxTest(10, 100); rrTxTest(100, 100); rrTxTest(100, 150); rwTxTest(100, 10); rwTxTest(10, 100); rwTxTest(100, 100); wwTxTest(100, 10); wwTxTest(100, 100); } private void nestedConnTxTest() throws SQLException { String dataDir = getDataDir(), dbFile = getDbDefault(); String url = "jdbc:sqlite:"+new File(dataDir, dbFile); try (Connection conn = getConnection(url, "", "")) { Statement stmt = conn.createStatement(); ResultSet rs; int n, b = 1000000, d = 1000, id = 1; String sql; sql = String.format("insert into accounts(id, name, balance)values(%d, 'Peter', %d)", id, b); n = stmt.executeUpdate(sql); assertTrue(1 == n); // tx#1 conn.setAutoCommit(false); sql = String.format("update accounts set balance = balance + %d where id = %d", d, id); n = stmt.executeUpdate(sql); assertTrue(1 == n); // check update result sql = String.format("select balance from accounts where id = %d", id); rs = stmt.executeQuery(sql); assertTrue(rs.next()); assertTrue(rs.getInt(1) == b + d); rs.close(); try (Connection aConn = getConnection(url, "", "")) { assertTrue(aConn != conn); Statement aStmt; // check the first insertion result aStmt = aConn.createStatement(); sql = String.format("select balance from accounts where id = %d", id); rs = aStmt.executeQuery(sql); assertTrue(rs.next()); assertTrue(rs.getInt(1) == b); rs.close(); // tx#2 aConn.setAutoCommit(false); // check isolation sql = String.format("select balance from accounts where id = %d", id); rs = aStmt.executeQuery(sql); assertTrue(rs.next()); assertTrue(rs.getInt(1) == b); // concurrent update try { sql = String.format("update accounts set balance = balance + %d where id = %d", d, id); n = aStmt.executeUpdate(sql); assertTrue(1 == n); fail("Concurrent update should be blocked and busy"); } catch (SQLException e) { if (e.getErrorCode() == SQLiteErrorCode.SQLITE_BUSY.code) { // OK aConn.rollback(); } else { throw e; } } } // commit and check result conn.commit(); sql = String.format("select balance from accounts where id = %d", id); rs = stmt.executeQuery(sql); assertTrue(rs.next()); assertTrue(rs.getInt(1) == b + d); rs.close(); stmt.execute("delete from accounts"); conn.commit(); } } private void readOnlyTxTest(int concs) throws SQLException { final AtomicBoolean success = new AtomicBoolean(true); Thread[] readers = new Thread[concs]; for (int i = 0; i < concs; ++i) { Thread t = new Thread("reader-"+i) { {setDaemon(true);} @Override public void run() { boolean failed = true; try { // Case-1. "read only" transaction mode in BEGIN try (Connection conn = getConnection(true)) { conn.setAutoCommit(true); Statement stmt = conn.createStatement(); stmt.executeUpdate("begin read only"); connectionTest(conn, "select 1", "1"); doReadOnlyTxTest(stmt, true); stmt.execute("rollback"); } // Case-2. "read only" transaction mode in "SET TRANSACTION" try (Connection conn = getConnection(true)) { conn.setAutoCommit(true); Statement stmt = conn.createStatement(); stmt.executeUpdate("begin"); stmt.executeUpdate("SET TRANSACTION read only"); connectionTest(conn, "select 1", "1"); doReadOnlyTxTest(stmt, true); stmt.execute("rollback"); stmt.executeUpdate("begin"); stmt.executeUpdate("SET TRANSACTION read write"); connectionTest(conn, "select 1", "1"); try { stmt.executeUpdate("SET TRANSACTION read only"); fail("\"SET TRANSACTION\" only is the first statement in transaction"); } catch (SQLException e) { if (!"25001".equals(e.getSQLState())) throw e; } doReadOnlyTxTest(stmt, false); stmt.execute("rollback"); stmt.executeUpdate("begin read only"); connectionTest(conn, "select 1", "1"); doReadOnlyTxTest(stmt, true); stmt.execute("rollback"); stmt.executeUpdate("begin read write"); stmt.executeUpdate("SET TRANSACTION read only"); connectionTest(conn, "select 1", "1"); doReadOnlyTxTest(stmt, true); stmt.execute("rollback"); stmt.executeUpdate("begin read write"); stmt.executeUpdate("SET TRANSACTION read write"); connectionTest(conn, "select 1", "1"); doReadOnlyTxTest(stmt, false); stmt.execute("rollback"); } // Case-2. "read only" transaction mode in "SET SESSION characteristics as TRANSACTION" try (Connection conn = getConnection(true)) { conn.setAutoCommit(true); Statement stmt = conn.createStatement(); conn.setReadOnly(true); stmt.executeUpdate("begin"); connectionTest(conn, "select 1", "1"); doReadOnlyTxTest(stmt, true); stmt.execute("rollback"); stmt.executeUpdate("begin read only"); connectionTest(conn, "select 1", "1"); doReadOnlyTxTest(stmt, true); stmt.execute("rollback"); stmt.executeUpdate("begin read write"); connectionTest(conn, "select 1", "1"); doReadOnlyTxTest(stmt, false); stmt.execute("rollback"); conn.setReadOnly(false); } failed = false; } catch (SQLException e) { e.printStackTrace(); } finally { if (failed) { success.set(false); } } } }; readers[i] = t; } for (int i = 0; i < concs; ++i) { Thread t = readers[i]; t.start(); } for (int i = 0; i < concs; ++i) { Thread t = readers[i]; try { t.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } } assertTrue(success.get()); } private void doReadOnlyTxTest(Statement stmt, final boolean readOnly) throws SQLException { try { stmt.executeUpdate("insert into accounts(name, balance)values('Peter', 100000)"); if (readOnly) fail("Can't insert in a read only transaction"); } catch (SQLException e) { if (!"25000".equals(e.getSQLState())) throw e; if (!readOnly) throw e; } try { stmt.executeUpdate("update accounts set balance=balance+1000 where id=1"); if (readOnly) fail("Can't update in a read only transaction"); } catch (SQLException e) { if (!"25000".equals(e.getSQLState())) throw e; if (!readOnly) throw e; } try { stmt.executeUpdate("DELETE from accounts where id=1"); if (readOnly) fail("Can't delete in a read only transaction"); } catch (SQLException e) { if (!"25000".equals(e.getSQLState())) throw e; if (!readOnly) throw e; } } private void rrTxTest(int times, int cons) throws SQLException { try (Connection conn = getConnection(true)) { Statement s = conn.createStatement(); ResultSet rs = s.executeQuery("select count(*) from accounts"); assertTrue (rs.next()); assertTrue (rs.getInt(1) == 0); int n = s.executeUpdate("insert into accounts(id, name, balance)values(1, 'Ken', 15000)"); assertTrue(n == 1); for (int i = 0; i < times; ++i) { Transaction[] readers = new Reader[cons]; for (int j = 0; j < cons; ++j) { readers[j] = new Reader(this); } for (int j = 0; j < cons; ++j) { readers[j].start(); } try { for (int j = 0; j < cons; ++j) { Transaction reader = readers[j]; reader.join(); assertTrue(reader.isOk()); // + Heart-beat s.executeQuery("select 1"); } } catch (InterruptedException e) { fail("Interrupted"); } } s.execute("delete from accounts"); } } private void rwTxTest(int times, int cons) throws SQLException { try (Connection conn = getConnection(true)) { Statement s = conn.createStatement(); ResultSet rs = s.executeQuery("select count(*) from accounts"); assertTrue (rs.next()); assertTrue (rs.getInt(1) == 0); int n = s.executeUpdate("insert into accounts(id, name, balance)values(1, 'Ken', 15000)"); assertTrue(n == 1); for (int i = 0; i < times; ++i) { Transaction[] txList = new Transaction[cons]; for (int j = 0; j < cons; ++j) { if (j % 3 == 0) { txList[j] = new Writer(this); } else { txList[j] = new Reader(this); } } for (int j = 0; j < cons; ++j) { txList[j].start(); } try { for (int j = 0; j < cons; ++j) { Transaction tx = txList[j]; tx.join(); assertTrue(tx.isOk()); // + Heart-beat s.executeQuery("select 1"); } } catch (InterruptedException e) { fail("Interrupted"); } } s.execute("delete from accounts"); } } private void wwTxTest(int times, int cons) throws SQLException { try (Connection conn = getConnection(true)) { Statement s = conn.createStatement(); ResultSet rs = s.executeQuery("select count(*) from accounts"); assertTrue (rs.next()); assertTrue (rs.getInt(1) == 0); int n = s.executeUpdate("insert into accounts(id, name, balance)values(1, 'Ken', 15000)"); assertTrue(n == 1); for (int i = 0; i < times; ++i) { Transaction[] txList = new Transaction[cons]; for (int j = 0; j < cons; ++j) { txList[j] = new Writer(this); } for (int j = 0; j < cons; ++j) { txList[j].start(); } try { for (int j = 0; j < cons; ++j) { Transaction tx = txList[j]; tx.join(); assertTrue(tx.isOk()); // + Heart-beat s.executeQuery("select 1"); } } catch (InterruptedException e) { fail("Interrupted"); } } s.execute("delete from accounts"); } } static abstract class Transaction extends Thread { protected final TransactionTest test; protected volatile boolean ok; Transaction(TransactionTest test) { this.test = test; } public boolean isOk() { return this.ok; } } static class Reader extends Transaction { Reader(TransactionTest test) { super(test); super.setDaemon(true); super.setName("r-tx"); } @Override public void run() { try (Connection c = test.getConnection(true)){ Statement s = c.createStatement(); c.setAutoCommit(true); s.execute("begin read only"); ResultSet rs = s.executeQuery("select id, name, balance from accounts where id = 1"); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 1); rs = s.executeQuery("select count(*) from accounts"); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 1); rs.close(); s.execute("commit"); this.ok = true; } catch (SQLException e) { e.printStackTrace(System.err); } } } static class Writer extends Transaction { Writer(TransactionTest test) { super(test); super.setDaemon(true); super.setName("w-tx"); } @Override public void run() { try (Connection c = test.getConnection(true)){ c.setAutoCommit(false); Statement s = c.createStatement(); ResultSet rs; rs = s.executeQuery("select count(*) from accounts"); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 1); rs.close(); rs = s.executeQuery("select id, name, balance from accounts where id = 1"); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 1); rs.close(); int n = s.executeUpdate("insert into accounts(name, balance)values('Johnson', 200000)"); assertTrue(n == 1); rs = s.executeQuery("select last_insert_rowid()"); assertTrue(rs.next()); int id = rs.getInt(1); rs.close(); n = s.executeUpdate("update accounts set balance=balance+1000 where id = " + id); assertTrue(n == 1); n = s.executeUpdate("delete from accounts where id = " + id + " and balance = 201000"); assertTrue(n == 1); c.commit(); this.ok = true; } catch (SQLException e) { throw new RuntimeException(e); } } } }
/** Create a Visio fill style object * @param self a VDXRenderer * @param color a colour * @todo fillstyle */ static void create_Fill(VDXRenderer *renderer, Color *color, struct vdx_Fill *Fill) { memset(Fill, 0, sizeof(*Fill)); Fill->type = vdx_types_Fill; Fill->FillForegnd = *color; Fill->FillPattern = 1; }
/** * @brief Board::NewLevel * * Creates a new level by doing the following: * - Setting all board layeres to default values * - Generating new maze * - Instantiate Tiles * - Spawn enemies */ void Board::NewLevel(){ ClearEnemies(); std::vector< std::vector< std::vector<Tile*> > > temp_board = GenerateBlankBoard(); player_tile_->SetPosition(Position(3,3)); temp_board[player_layer_id_][3][3] = player_tile_; temp_board[chest_layer_id_][height_res_-4][width_res_-4] = exit_tile_; board_ = temp_board; GenerateDungeon(); FormatDungeon(); level_++; }
<reponame>microsoft/Odyss-e-de-Teams import React, { Component } from "react"; import { ListGroup, Form } from "react-bootstrap"; import { IMecaniqueQuestionProps, IReponse, IRemettreOrdreState, } from "models/Question"; import "./RemettreOrdre.scss"; class RemettreOrdre extends Component< IMecaniqueQuestionProps, IRemettreOrdreState > { constructor(props: IMecaniqueQuestionProps) { super(props); let ids: number[]; if (props.isRecap) { let listReponseOrdreOK = []; this.props.question.reponse.forEach((id) => { listReponseOrdreOK.push( this.props.question.listReponse.find((r) => r.id_reponse === id) ); }); this.props.question.listReponse = listReponseOrdreOK; ids = this.props.question?.reponse_saisie; } else { ids = this.props.question?.listReponse?.map( (item: IReponse) => item.id_reponse ); } let listReponseWithOrdre = []; ids.forEach((id: number, i: number) => { listReponseWithOrdre.push({ id: id, ordre: i }); }); this.state = { listReponseWithOrdre: listReponseWithOrdre, }; } private _onChange = (item: IReponse, ordre: number) => { if (this.props.isRecap) { return; } let listReponseWithOrdre = this.state.listReponseWithOrdre; let currentOrdre = listReponseWithOrdre.find( (rep) => rep.id === item.id_reponse ); let listReponseReorder; if (ordre < currentOrdre.ordre) { //si je descend l ordre, recalcul automatique de ceux en dessous qui s incremente listReponseReorder = listReponseWithOrdre.filter( (rep) => rep.ordre >= ordre && rep.ordre < currentOrdre.ordre ); if (listReponseReorder.length > 0) { listReponseReorder.forEach((rep) => { rep.ordre++; }); } } else if (ordre > currentOrdre.ordre) { //si je monte l ordre, recalcul automatique de ceux au dessus qui se decremente listReponseReorder = listReponseWithOrdre.filter( (rep) => rep.ordre <= ordre && rep.ordre > currentOrdre.ordre ); if (listReponseReorder.length > 0) { listReponseReorder.forEach((rep) => { rep.ordre--; }); } } currentOrdre.ordre = ordre; this.setState( { listReponseWithOrdre: listReponseWithOrdre, }, () => { let selectedReponseOrder = this.state.listReponseWithOrdre.sort( (a: any, b: any) => { return a.ordre - b.ordre; } ); this.props.onSelect( this.props.question, selectedReponseOrder.map((rep) => rep.id) ); } ); }; private _renderListeDeroulante = (item: IReponse) => { return ( <Form.Control as="select" disabled={this.props.isRecap} onChange={(e) => this._onChange(item, parseInt(e.target.value))} value={ this.state.listReponseWithOrdre.find( (rep) => rep.id === item.id_reponse ).ordre } > {this.state.listReponseWithOrdre?.map((reponse: any, i: number) => { return ( <option value={i} key={reponse.id + "-" + i}> {i + 1} </option> ); })} </Form.Control> ); }; render() { const { isRecap } = this.props; return ( <ListGroup className={"conteneur-reponse"}> {this.props.question?.listReponse?.map((item: IReponse, i: number) => { return ( <ListGroup.Item key={item.id_reponse} className={`my-2 d-flex align-items-center justify-content-between active-reponse${ isRecap && (this.props.question.reponse_saisie.indexOf(item.id_reponse) === this.props.question.reponse.indexOf(item.id_reponse) ? " active-reponse-ok" : " active-reponse-ko") }`} > <div className={"d-flex align-items-center"}> <p className={"mb-0 num_reponse"}> <img alt={`Reponse ${i + 1}`} src={`${ process.env.PUBLIC_URL }/images/question/reponse/reponse${i + 1}.png`} /> </p> <p className={"mb-0 pl-2"}>{item.nom}</p> </div> {/* {isRecap ? ( <span className={"order"}> Mon choix :{" "} <strong>{this.props.question.reponse_saisie.indexOf(item.id_reponse) + 1}</strong> </span> ) : ( this._renderListeDeroulante(item) )} */} {this._renderListeDeroulante(item)} </ListGroup.Item> ); })} </ListGroup> ); } } export default RemettreOrdre;
def print_leaves(treefile): count=0 tree = Tree(treefile) for leaf in tree: count+=1 print("{} : {} leaves".format(treefile, count))
/** * {@link org.springframework.security.oauth2.jwt.Jwt} token validator for GCP App Engine (both Flexible and Standard) * audience strings. * * @author Elena Felder * * @since 1.1 */ public class AppEngineAudienceProvider implements AudienceProvider { private static final String AUDIENCE_FORMAT = "/projects/%s/apps/%s"; private final GcpProjectIdProvider projectIdProvider; private ResourceManager resourceManager = ResourceManagerOptions.getDefaultInstance().getService(); public AppEngineAudienceProvider(GcpProjectIdProvider projectIdProvider) { Assert.notNull(projectIdProvider, "GcpProjectIdProvider cannot be null."); this.projectIdProvider = projectIdProvider; } @Override public String getAudience() { Project project = this.resourceManager.get(this.projectIdProvider.getProjectId()); Assert.notNull(project, "Project expected not to be null. Is Cloud Resource Manager API enabled? (https://console.developers.google.com/apis/api/cloudresourcemanager.googleapis.com)"); Assert.notNull(project.getProjectNumber(), "Project Number expected not to be null."); String projectId = this.projectIdProvider.getProjectId(); Assert.notNull(projectId, "Project Id expected not to be null."); return String.format(AUDIENCE_FORMAT, project.getProjectNumber(), projectId); } public void setResourceManager(ResourceManager resourceManager) { Assert.notNull(resourceManager, "ResourceManager cannot be null."); this.resourceManager = resourceManager; } }
<reponame>kms1212/bootldr #ifndef __DRIVERS_H__ #define __DRIVERS_H__ #include "type.h" #include "port.h" #define ATAPIO_STATUS_BSY 0x80 #define ATAPIO_STATUS_RDY 0x40 #define ATAPIO_STATUS_DRQ 0x08 #define ATAPIO_STATUS_DF 0x20 #define ATAPIO_STATUS_ERR 0x01 void* ATAPIORead(void* dest, uint32_t lba, uint8_t s_s); void* ATAPIOWrite(uint32_t lba, uint8_t s_s, void* src); static void ATAPIOWaitBusy(); static void ATAPIOWaitDRQ(); #endif
/** * DOM implementation of OpenDocument element {@odf.element text:object-index-source}. * */ public class TextObjectIndexSourceElement extends OdfElement { public static final OdfName ELEMENT_NAME = OdfName.newName(OdfDocumentNamespace.TEXT, "object-index-source"); /** * Create the instance of <code>TextObjectIndexSourceElement</code> * * @param ownerDoc The type is <code>OdfFileDom</code> */ public TextObjectIndexSourceElement(OdfFileDom ownerDoc) { super(ownerDoc, ELEMENT_NAME); } /** * Get the element name * * @return return <code>OdfName</code> the name of element {@odf.element text:object-index-source}. */ public OdfName getOdfName() { return ELEMENT_NAME; } /** * Receives the value of the ODFDOM attribute representation <code>TextIndexScopeAttribute</code> , See {@odf.attribute text:index-scope} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getTextIndexScopeAttribute() { TextIndexScopeAttribute attr = (TextIndexScopeAttribute) getOdfAttribute(OdfDocumentNamespace.TEXT, "index-scope"); if (attr != null) { return String.valueOf(attr.getValue()); } return TextIndexScopeAttribute.DEFAULT_VALUE; } /** * Sets the value of ODFDOM attribute representation <code>TextIndexScopeAttribute</code> , See {@odf.attribute text:index-scope} * * @param textIndexScopeValue The type is <code>String</code> */ public void setTextIndexScopeAttribute(String textIndexScopeValue) { TextIndexScopeAttribute attr = new TextIndexScopeAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(textIndexScopeValue); } /** * Receives the value of the ODFDOM attribute representation <code>TextRelativeTabStopPositionAttribute</code> , See {@odf.attribute text:relative-tab-stop-position} * * @return - the <code>Boolean</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public Boolean getTextRelativeTabStopPositionAttribute() { TextRelativeTabStopPositionAttribute attr = (TextRelativeTabStopPositionAttribute) getOdfAttribute(OdfDocumentNamespace.TEXT, "relative-tab-stop-position"); if (attr != null) { return Boolean.valueOf(attr.booleanValue()); } return Boolean.valueOf(TextRelativeTabStopPositionAttribute.DEFAULT_VALUE); } /** * Sets the value of ODFDOM attribute representation <code>TextRelativeTabStopPositionAttribute</code> , See {@odf.attribute text:relative-tab-stop-position} * * @param textRelativeTabStopPositionValue The type is <code>Boolean</code> */ public void setTextRelativeTabStopPositionAttribute(Boolean textRelativeTabStopPositionValue) { TextRelativeTabStopPositionAttribute attr = new TextRelativeTabStopPositionAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setBooleanValue(textRelativeTabStopPositionValue.booleanValue()); } /** * Receives the value of the ODFDOM attribute representation <code>TextUseChartObjectsAttribute</code> , See {@odf.attribute text:use-chart-objects} * * @return - the <code>Boolean</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public Boolean getTextUseChartObjectsAttribute() { TextUseChartObjectsAttribute attr = (TextUseChartObjectsAttribute) getOdfAttribute(OdfDocumentNamespace.TEXT, "use-chart-objects"); if (attr != null) { return Boolean.valueOf(attr.booleanValue()); } return Boolean.valueOf(TextUseChartObjectsAttribute.DEFAULT_VALUE); } /** * Sets the value of ODFDOM attribute representation <code>TextUseChartObjectsAttribute</code> , See {@odf.attribute text:use-chart-objects} * * @param textUseChartObjectsValue The type is <code>Boolean</code> */ public void setTextUseChartObjectsAttribute(Boolean textUseChartObjectsValue) { TextUseChartObjectsAttribute attr = new TextUseChartObjectsAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setBooleanValue(textUseChartObjectsValue.booleanValue()); } /** * Receives the value of the ODFDOM attribute representation <code>TextUseDrawObjectsAttribute</code> , See {@odf.attribute text:use-draw-objects} * * @return - the <code>Boolean</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public Boolean getTextUseDrawObjectsAttribute() { TextUseDrawObjectsAttribute attr = (TextUseDrawObjectsAttribute) getOdfAttribute(OdfDocumentNamespace.TEXT, "use-draw-objects"); if (attr != null) { return Boolean.valueOf(attr.booleanValue()); } return Boolean.valueOf(TextUseDrawObjectsAttribute.DEFAULT_VALUE); } /** * Sets the value of ODFDOM attribute representation <code>TextUseDrawObjectsAttribute</code> , See {@odf.attribute text:use-draw-objects} * * @param textUseDrawObjectsValue The type is <code>Boolean</code> */ public void setTextUseDrawObjectsAttribute(Boolean textUseDrawObjectsValue) { TextUseDrawObjectsAttribute attr = new TextUseDrawObjectsAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setBooleanValue(textUseDrawObjectsValue.booleanValue()); } /** * Receives the value of the ODFDOM attribute representation <code>TextUseMathObjectsAttribute</code> , See {@odf.attribute text:use-math-objects} * * @return - the <code>Boolean</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public Boolean getTextUseMathObjectsAttribute() { TextUseMathObjectsAttribute attr = (TextUseMathObjectsAttribute) getOdfAttribute(OdfDocumentNamespace.TEXT, "use-math-objects"); if (attr != null) { return Boolean.valueOf(attr.booleanValue()); } return Boolean.valueOf(TextUseMathObjectsAttribute.DEFAULT_VALUE); } /** * Sets the value of ODFDOM attribute representation <code>TextUseMathObjectsAttribute</code> , See {@odf.attribute text:use-math-objects} * * @param textUseMathObjectsValue The type is <code>Boolean</code> */ public void setTextUseMathObjectsAttribute(Boolean textUseMathObjectsValue) { TextUseMathObjectsAttribute attr = new TextUseMathObjectsAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setBooleanValue(textUseMathObjectsValue.booleanValue()); } /** * Receives the value of the ODFDOM attribute representation <code>TextUseOtherObjectsAttribute</code> , See {@odf.attribute text:use-other-objects} * * @return - the <code>Boolean</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public Boolean getTextUseOtherObjectsAttribute() { TextUseOtherObjectsAttribute attr = (TextUseOtherObjectsAttribute) getOdfAttribute(OdfDocumentNamespace.TEXT, "use-other-objects"); if (attr != null) { return Boolean.valueOf(attr.booleanValue()); } return Boolean.valueOf(TextUseOtherObjectsAttribute.DEFAULT_VALUE); } /** * Sets the value of ODFDOM attribute representation <code>TextUseOtherObjectsAttribute</code> , See {@odf.attribute text:use-other-objects} * * @param textUseOtherObjectsValue The type is <code>Boolean</code> */ public void setTextUseOtherObjectsAttribute(Boolean textUseOtherObjectsValue) { TextUseOtherObjectsAttribute attr = new TextUseOtherObjectsAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setBooleanValue(textUseOtherObjectsValue.booleanValue()); } /** * Receives the value of the ODFDOM attribute representation <code>TextUseSpreadsheetObjectsAttribute</code> , See {@odf.attribute text:use-spreadsheet-objects} * * @return - the <code>Boolean</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public Boolean getTextUseSpreadsheetObjectsAttribute() { TextUseSpreadsheetObjectsAttribute attr = (TextUseSpreadsheetObjectsAttribute) getOdfAttribute(OdfDocumentNamespace.TEXT, "use-spreadsheet-objects"); if (attr != null) { return Boolean.valueOf(attr.booleanValue()); } return Boolean.valueOf(TextUseSpreadsheetObjectsAttribute.DEFAULT_VALUE); } /** * Sets the value of ODFDOM attribute representation <code>TextUseSpreadsheetObjectsAttribute</code> , See {@odf.attribute text:use-spreadsheet-objects} * * @param textUseSpreadsheetObjectsValue The type is <code>Boolean</code> */ public void setTextUseSpreadsheetObjectsAttribute(Boolean textUseSpreadsheetObjectsValue) { TextUseSpreadsheetObjectsAttribute attr = new TextUseSpreadsheetObjectsAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setBooleanValue(textUseSpreadsheetObjectsValue.booleanValue()); } /** * Create child element {@odf.element text:index-title-template}. * * @return the element {@odf.element text:index-title-template} */ public TextIndexTitleTemplateElement newTextIndexTitleTemplateElement() { TextIndexTitleTemplateElement textIndexTitleTemplate = ((OdfFileDom) this.ownerDocument).newOdfElement(TextIndexTitleTemplateElement.class); this.appendChild(textIndexTitleTemplate); return textIndexTitleTemplate; } /** * Create child element {@odf.element text:object-index-entry-template}. * * @param textStyleNameValue the <code>String</code> value of <code>TextStyleNameAttribute</code>, see {@odf.attribute text:style-name} at specification * @return the element {@odf.element text:object-index-entry-template} */ public TextObjectIndexEntryTemplateElement newTextObjectIndexEntryTemplateElement(String textStyleNameValue) { TextObjectIndexEntryTemplateElement textObjectIndexEntryTemplate = ((OdfFileDom) this.ownerDocument).newOdfElement(TextObjectIndexEntryTemplateElement.class); textObjectIndexEntryTemplate.setTextStyleNameAttribute(textStyleNameValue); this.appendChild(textObjectIndexEntryTemplate); return textObjectIndexEntryTemplate; } @Override public void accept(ElementVisitor visitor) { if (visitor instanceof DefaultElementVisitor) { DefaultElementVisitor defaultVisitor = (DefaultElementVisitor) visitor; defaultVisitor.visit(this); } else { visitor.visit(this); } } }
Powerful: Alvaro Negredo has been offered to Tottenham on the cheap (Picture: Getty) La Liga side Sevilla have offered Tottenham a cut-price deal for striker Alvaro Negredo after suffering a financial crisis. The Andalusia-based club are currently reeling after it was revealed that they are almost £15million in debt, and facing years of budget cuts after gambles by the club’s owners. President Jose Maria Del Nido confirmed the news at Sevilla’s AGM on Thursday, and announced that at least one of the team’s best players must be sold to aid recovery. ‘I am presenting the worst results of all my years,’ said Del Nido. ‘We have done badly, we have not taken the right road, and we have been making mistakes for two years. ‘Without selling players we will return to the mediocrity of the last decades. I want to aspire to something and not wander through the league without pain or glory.’ Advertisement Advertisement Sevilla have a host of top talents who could be sold to pay off the debt, including Jesus Navas, Diego Perotti, Ivan Rakitić and Frederico Fazio, but striker Negredo looks set to be the man sacrificed. The 27-year-old has previously been a target for a host of Premier League clubs, and according to local paper El Confidencial, Sevilla have offered long-term admirers Tottenham a cut-price deal in January if they can rush through a deal. Tottenham are rumoured to have enquired about Negredo last summer, only to be told he would cost in excess of £25million. But if Spurs can pay up front, Sevilla are now ready to do business for £17million. It’s a hefty price tag, but given Andre Villas-Boas’ need for a new centre forward in the new year Negredo represents an ideal purchase.
def _event_publisher(event): if event.origin != EventOrigin.local: return if event.event_type == EVENT_TIME_CHANGED: return if event.event_type in ignore_event: return if event.event_type == EVENT_CALL_SERVICE: if ( event.data.get('domain') == mqtt.DOMAIN and event.data.get('service') == mqtt.SERVICE_PUBLISH and event.data[ATTR_SERVICE_DATA].get('topic') == pub_topic ): return event_info = {'event_type': event.event_type, 'event_data': event.data} msg = json.dumps(event_info, cls=JSONEncoder) mqtt.async_publish(pub_topic, msg)
module Window.InputState.Controls ( module Window.InputState.Alias , keyPressed , keyReleased , keyHold , keyPrevHold , keyNotHold , keyPrevNotHold , mousePressed , mouseReleased , mouseHold , mouseNotHold , mouseWheelScrollX , mouseWheelScrollY , gamepadPressed , gamepadReleased , gamepadHold , gamepadNotHold , gamepadAxis , gamepadPrevAxis , gamepadNegAxisPressed , gamepadPosAxisPressed , aliasPressed , aliasReleased , aliasHold , aliasNotHold , anyKeyPressed ) where import Data.Maybe (isJust) import qualified SDL import qualified SDL.Input.GameController as SDL import qualified SDL.Raw import Window.InputState.Alias import Window.InputState.GamepadManager import Window.InputState.Types keyPressed :: SDL.Scancode -> InputState -> Bool keyPressed keyCode inputState | _inactive inputState = False | otherwise = keyStatePressed || keyHoldPrevNotHold where -- SDL2 key press events seem to get dropped occasionally for some reason so -- do the hold/not-hold key checks in addition for redundancy keyStatePressed = keyCode `elem` _keyStatePressed inputState keyHoldPrevNotHold = keyHold keyCode inputState && keyPrevNotHold keyCode inputState keyReleased :: SDL.Scancode -> InputState -> Bool keyReleased keyCode inputState | _inactive inputState = False | otherwise = keyCode `elem` (_keyStateReleased inputState) keyHold :: SDL.Scancode -> InputState -> Bool keyHold keyCode inputState | _inactive inputState = False | otherwise = (_keyHoldState inputState) keyCode keyPrevHold :: SDL.Scancode -> InputState -> Bool keyPrevHold keyCode inputState | _inactive inputState = False | otherwise = (_keyHoldPrevState inputState) keyCode keyNotHold :: SDL.Scancode -> InputState -> Bool keyNotHold keyCode inputState | _inactive inputState = False | otherwise = not $ keyHold keyCode inputState keyPrevNotHold :: SDL.Scancode -> InputState -> Bool keyPrevNotHold keyCode inputState | _inactive inputState = False | otherwise = not $ keyPrevHold keyCode inputState mousePressed :: SDL.MouseButton -> InputState -> Bool mousePressed mouseButton inputState | _inactive inputState = False | otherwise = pressed || pressed' where pressed = mouseButton `elem` _mouseStatePressed inputState -- SDL2 mouse button events don't seem reliable if keyboard events are also being sent -- for some reason so fallback to this in addition buttonPrevNotHold = not $ (_mouseHoldPrevState inputState) mouseButton pressed' = mouseHold mouseButton inputState && buttonPrevNotHold mouseReleased :: SDL.MouseButton -> InputState -> Bool mouseReleased mouseButton inputState | _inactive inputState = False | otherwise = released || released' where released = mouseButton `elem` _mouseStateReleased inputState -- SDL2 mouse button events unreliable, see above comment buttonPrevHold = _mouseHoldPrevState inputState $ mouseButton released' = not (mouseHold mouseButton inputState) && buttonPrevHold mouseHold :: SDL.MouseButton -> InputState -> Bool mouseHold mouseButton inputState | _inactive inputState = False | otherwise = _mouseHoldState inputState $ mouseButton mouseNotHold :: SDL.MouseButton -> InputState -> Bool mouseNotHold mouseButton inputState | _inactive inputState = False | otherwise = not $ mouseHold mouseButton inputState mouseWheelEventDataSign :: SDL.MouseWheelEventData -> Int mouseWheelEventDataSign eventData = case SDL.mouseWheelEventDirection eventData of SDL.ScrollNormal -> 1 SDL.ScrollFlipped -> -1 mouseWheelScrollX :: InputState -> Int mouseWheelScrollX inputState = case _mouseWheelEventData inputState of Nothing -> 0 Just eventData -> let SDL.V2 scrollX _ = SDL.mouseWheelEventPos eventData in fromIntegral scrollX * mouseWheelEventDataSign eventData mouseWheelScrollY :: InputState -> Int mouseWheelScrollY inputState = case _mouseWheelEventData inputState of Nothing -> 0 Just eventData -> let SDL.V2 _ scrollY = SDL.mouseWheelEventPos eventData in fromIntegral scrollY * mouseWheelEventDataSign eventData gamepadPressed :: SDL.ControllerButton -> InputState -> Bool gamepadPressed button inputState | _inactive inputState = False | otherwise = gamepadManagerButtonPressed button (_gamepadManager inputState) gamepadReleased :: SDL.ControllerButton -> InputState -> Bool gamepadReleased button inputState | _inactive inputState = False | otherwise = gamepadManagerButtonReleased button (_gamepadManager inputState) gamepadHold :: SDL.ControllerButton -> InputState -> Bool gamepadHold button inputState | _inactive inputState = False | otherwise = gamepadManagerButtonHold button (_gamepadManager inputState) gamepadNotHold :: SDL.ControllerButton -> InputState -> Bool gamepadNotHold button inputState | _inactive inputState = False | otherwise = not $ gamepadHold button inputState gamepadAxis :: SDL.Raw.GameControllerAxis -> InputState -> Float gamepadAxis axis inputState = gamepadManagerAxisPosition axis (_gamepadManager inputState) gamepadPrevAxis :: SDL.Raw.GameControllerAxis -> InputState -> Float gamepadPrevAxis axis inputState = gamepadManagerPrevAxisPosition axis (_gamepadManager inputState) gamepadNegAxisPressed :: SDL.Raw.GameControllerAxis -> InputState -> Bool gamepadNegAxisPressed axis inputState = gamepadManagerNegAxisPressed axis (_gamepadManager inputState) gamepadPosAxisPressed :: SDL.Raw.GameControllerAxis -> InputState -> Bool gamepadPosAxisPressed axis inputState = gamepadManagerPosAxisPressed axis (_gamepadManager inputState) aliasPressed :: InputAlias -> InputState -> Bool aliasPressed alias inputState | _inactive inputState = False | otherwise = let aliasData = toInputAliasData alias (_inputAliasRawDataMap inputState) keyPress = or [keyPressed key inputState | key <- _keys aliasData] mousePress = or [mousePressed btn inputState | btn <- _mouseButtons aliasData] mouseScrollXPress = or [ mouseWheelScrollX inputState `cmp` scrollX | scrollX <- _mouseWheelScrollXs aliasData , let cmp = if scrollX < 0 then (<=) else (>=) ] mouseScrollYPress = or [ mouseWheelScrollY inputState `cmp` scrollY | scrollY <- _mouseWheelScrollYs aliasData , let cmp = if scrollY < 0 then (<=) else (>=) ] padPress = or [gamepadPressed btn inputState | btn <- _gamepadButtons aliasData] negAxisPress = or [gamepadNegAxisPressed axis inputState | axis <- _negAxes aliasData] posAxisPress = or [gamepadPosAxisPressed axis inputState | axis <- _posAxes aliasData] in or [keyPress, mousePress, mouseScrollXPress, mouseScrollYPress, padPress, negAxisPress, posAxisPress] aliasReleased :: InputAlias -> InputState -> Bool aliasReleased alias inputState | _inactive inputState = False | otherwise = let aliasData = toInputAliasData alias (_inputAliasRawDataMap inputState) keyRelease = or [keyReleased key inputState | key <- _keys aliasData] mouseRelease = or [mouseReleased btn inputState | btn <- _mouseButtons aliasData] padRelease = or [gamepadReleased btn inputState | btn <- _gamepadButtons aliasData] negAxisRelease = or [ gamepadAxis axis inputState >= (-0.5) && gamepadPrevAxis axis inputState < (-0.5) | axis <- _negAxes aliasData ] posAxisRelease = or [ gamepadAxis axis inputState <= 0.5 && gamepadPrevAxis axis inputState > 0.5 | axis <- _posAxes aliasData ] in or [keyRelease, mouseRelease, padRelease, negAxisRelease, posAxisRelease] aliasHold :: InputAlias -> InputState -> Bool aliasHold alias inputState | _inactive inputState = False | otherwise = let aliasData = toInputAliasData alias (_inputAliasRawDataMap inputState) keyHld = or [keyHold key inputState | key <- _keys aliasData] mouseHld = or [mouseHold btn inputState | btn <- _mouseButtons aliasData] padHld = or [gamepadHold btn inputState | btn <- _gamepadButtons aliasData] negAxisHld = or [gamepadAxis axis inputState <= (-0.5) | axis <- _negAxes aliasData] posAxisHld = or [gamepadAxis axis inputState >= 0.5 | axis <- _posAxes aliasData] in or [keyHld, mouseHld, padHld, negAxisHld, posAxisHld] aliasNotHold :: InputAlias -> InputState -> Bool aliasNotHold alias inputState | _inactive inputState = False | otherwise = not $ aliasHold alias inputState anyKeyPressed :: InputState -> Bool anyKeyPressed = isJust . _pressedInputRawData
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class BattleManager { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); Map<String, Integer> peopleMapHealth = new HashMap<>(); Map<String, Integer> peopleMapEnergy = new HashMap<>(); while (!"Results".equals(input)) { String[] elements = input.split(":"); switch (elements[0]) { case "Add": String name = elements[1]; int health = Integer.parseInt(elements[2]); int energy = Integer.parseInt(elements[3]); if (peopleMapHealth.containsKey(name) && peopleMapEnergy.containsKey(name)) { peopleMapHealth.put(name, peopleMapHealth.get(name) + health); } else { peopleMapHealth.put(name,health); peopleMapEnergy.put(name,energy); } break; case "Attack": String attackerName = elements[1]; String defenderName = elements[2]; int damage = Integer.parseInt(elements[3]); if (peopleMapHealth.containsKey(defenderName) && peopleMapEnergy.containsKey(attackerName)) { int currentDefenderHealth = peopleMapHealth.get(defenderName); int currentAttackerEnergy = peopleMapEnergy.get(attackerName); if (currentDefenderHealth - damage <= 0) { System.out.println(defenderName + " was disqualified!"); peopleMapHealth.remove(defenderName); peopleMapEnergy.remove(defenderName); } else { //currentDefender.setHealth(currentDefender.getHealth() - damage); peopleMapHealth.put(defenderName,peopleMapHealth.get(defenderName)-damage); } if (currentAttackerEnergy - 1 <= 0) { System.out.println(attackerName + " was disqualified!"); peopleMapHealth.remove(attackerName); peopleMapEnergy.remove(attackerName); } else { //currentDefender.setHealth(currentDefender.getHealth() - damage); peopleMapEnergy.put(attackerName,peopleMapEnergy.get(attackerName)-1); } } break; case "Delete": String userToRemove = elements[1]; if (userToRemove.equals("All")) { peopleMapEnergy = new HashMap<>(); peopleMapHealth = new HashMap<>(); } else { peopleMapEnergy.remove(userToRemove); peopleMapHealth.remove(userToRemove); } break; } input = scanner.nextLine(); } System.out.println("People count: " + peopleMapHealth.size()); Map<String, Integer> finalPeopleMapEnergy = peopleMapEnergy; peopleMapHealth.entrySet().stream().sorted((a, b) -> { int result = b.getValue().compareTo(a.getValue()); if(result==0){ result = a.getKey().compareTo(b.getKey()); } return result; }).forEach(a -> { System.out.printf("%s - %s - %s\n", a.getKey(), a.getValue(), finalPeopleMapEnergy.get(a.getKey())); }); } }
t=int(input()) for i in range(t): x,y=map(int,input().split()) a=0 b=0 x = x-1 if(x>y): a=x b =y elif(x==y): a=x b=y elif(x<y): a=x b=y print(a,b)
import { FC, useState, createElement, FormEventHandler, useEffect, } from "react" import Button from "@oly_op/react-button" import { Head } from "@oly_op/react-head" import SIGN_UP from "./sign-up.gql" import { useMutation } from "../../hooks" import { SignUpArgs, SignUpData, SignUpInput } from "./types" import isSignUpFormValid from "./is-sign-up-form-valid" import Input, { InputOnChange } from "../../components/input" const AuthorizationSignUpForm: FC<PropTypes> = ({ onSubmit, emailAddress, onEmailAddressChange, }) => { const [ name, setName ] = useState("") const [ password, setPassword ] = useState("") const [ cover, setCover ] = useState<File | null>(null) const [ profile, setProfile ] = useState<File | null>(null) const [ signUp, { data, loading } ] = useMutation<SignUpData, SignUpArgs>(SIGN_UP) const handleNameChange: InputOnChange = value => setName(value) const handlePasswordChange: InputOnChange = value => setPassword(value) const handleCoverChange: InputOnChange<File> = value => setCover(value) const handleProfileChange: InputOnChange<File> = value => setProfile(value) const input: SignUpInput = { name, cover, profile, password, emailAddress, } const handleSignUp: FormEventHandler = event => { event.preventDefault() if (isSignUpFormValid(input)) { void signUp({ variables: { input } }) } } useEffect(() => { if (data) { onSubmit(data.signUp) } }, [data]) return ( <Head pageTitle="Sign Up"> <form onSubmit={handleSignUp} className="FlexColumnGap"> <Input name="Email" tabIndex={1} placeholder="Email" autoComplete="email" value={emailAddress} inputID="emailAddress" onChange={onEmailAddressChange} /> <Input autoFocus name="Name" value={name} tabIndex={2} inputID="name" placeholder="Name" autoComplete="given-name" onChange={handleNameChange} /> <Input tabIndex={3} type="password" name="Password" value={password} inputID="password" placeholder="Password" autoComplete="password" onChange={handlePasswordChange} /> <Input type="file" tabIndex={4} name="Profile" value={profile} inputID="profile" imageOrientation="portrait" onChange={handleProfileChange} /> <Input type="file" name="Cover" tabIndex={5} value={cover} inputID="cover" imageOrientation="landscape" onChange={handleCoverChange} /> <Button text="Submit" type="submit" tabIndex={6} rightIcon="login" disabled={loading || !isSignUpFormValid(input)} /> </form> </Head> ) } interface PropTypes { emailAddress: string, onEmailAddressChange: InputOnChange, onSubmit: (accessToken: string) => void, } export default AuthorizationSignUpForm
# -*- coding: utf-8 -*- """ Created on Fri Jan 5 12:35:54 2018 @author: ettor """ import pandas as pd import requests import requests_cache from collections import namedtuple import pandas as pd from SPARQLWrapper import SPARQLWrapper, JSON def get_wikidata_item(predicat, objet): """ Use the WDQ service to get items by property and object. Return a panda dataframe with the items and their english label. Can be slow or raise timeout """ sparql = SPARQLWrapper( "https://query.wikidata.org/sparql" ) sparql.setQuery( """ SELECT ?item ?itemLabel WHERE { ?item wdt:%s wd:%s . SERVICE wikibase:label { bd:serviceParam wikibase:language "en" } } """ % (predicat, objet) ) sparql.setReturnFormat( JSON ) results = sparql.query().convert() results_df = pd.io.json.json_normalize( results['results']['bindings'] ) return results_df[['item.value', 'itemLabel.value']] def get_wikidata(value, type_id='Q618123', prop_id='P17', prop_value='Q31', lang="en"): """ Use the Antonin's API to return the best match on Wikidata based on the type and a property. Example : get_wikidata('Binche', 'Q618123', 'P17', 'Q31') Which means : search the label "Binche" instance of geographical object (Q618123) in country (P17) Belgium (Q31) The result is a tuple (main_type, match, name, qid, score) Result : ('municipality of Belgium', False, 'Binche', 'Q95121', 100.0) """ Wikidata = namedtuple( 'Wikidata', 'qid label confidence match type' ) base_url = "https://tools.wmflabs.org/openrefine-wikidata/%s/api" % (lang) query = {"query": """{"query":"%s", "limit":0, "type" : "%s"}""" % (value, type_id)} if prop_id or prop_value: query = {"query": """{"query":"%s", "limit":0, "type" : "%s", "properties":[{"pid":"%s", "v":{"id":"%s"}}]}""" % (value, type_id, prop_id, prop_value)} r = requests.get( base_url, params=query ) # print(r.url) json_result = r.json() try: qid = [d['id'] for d in json_result['result']] name = [d['name'] for d in json_result['result']] score = [d['score'] for d in json_result['result']] match = [d['match'] for d in json_result['result']] main_type = [d['type'][0]['name'] for d in json_result['result']] df = pd.DataFrame( {'qid': qid, 'name': name, 'score': score, 'match': match, 'main_type': main_type } ) # order by score df.sort_values( ['score'], ascending=[False], inplace=True ) print( df.head() ) # select the best match matches = df.query( "score == 100" ).values print( "matches:", matches ) if matches.size > 0: best_match = tuple( matches ) print( "best match1:", best_match ) else: best_match = list( tuple, df.iloc[[0]].values ) print( "best match2:", best_match ) return {Wikidata( *x ) for x in [x for x in best_match]} except IndexError: print( "No exact match in Wikidata" ) return json_result # add the location of each result using the data extension API def get_location(): pass if __name__ == '__main__': print(get_wikidata('Binche', 'Q618123', 'P31', 'Q15273785', "fr")) print(get_wikidata('Binche', 'Q618123')) print(get_wikidata('camp de beverloo', 'Q618123')) print(get_wikidata("<NAME>",'')) liste = ["Namur", "<NAME>"] print( [get_wikidata( x ) for x in liste] ) # get instances of building (slow) print(get_wikidata_item('P31', 'Q41176'))
// replacement (and copy of) of flate.Read(): always allocates a buffer big // enough to fully return the block of uncompressed data func readBlock(f *flate.Decompressor) ([]byte, error) { for { if len(f.ToRead) > 0 { b := make([]byte, len(f.ToRead)) n := copy(b, f.ToRead) f.ToRead = f.ToRead[n:] return b, nil } if f.Err != nil { return []byte{}, f.Err } f.Step(f) } }
def loadData(self): file_length = getFileLength(self.fileloc) with open(self.fileloc, 'r') as file: csvreader = list(csv.reader(file, delimiter=',')) self.type = csvreader[1][1] initial_time = int(csvreader[1][0]) printProgressBar(0, file_length-1, prefix = 'Reading IMU File:', suffix = 'Complete', length = 50) line_count = 0 for row in csvreader: if line_count == 0: header = row line_count += 1 if 'mag_x (uT)' in header: self.recordType = 'DeviceStream' else: self.recordType = 'SensorSave' else: printProgressBar(line_count, file_length-1, prefix = 'Reading IMU File:', suffix = 'Complete', length = 50) float_row = [] for col in row: try: float_row.append(float(col)) except ValueError: float_row.append(None) self.timestamp.append(int(row[0]) - initial_time) self.accn.append([float_row[2], float_row[3], float_row[4]]) self.gyro.append([float_row[5], float_row[6], float_row[7]]) line_count += 1 file.close() self.timestamp = np.array(self.timestamp) self.accn = np.array(self.accn) self.gyro = np.array(self.gyro) print() self.recordTime = float(self.timestamp[-1])/1e6 periods = [(t - s)/1e6 for s, t in zip(self.timestamp, self.timestamp[1:])] self.sampleRate = float(1)/mean(periods)
def process_payment(self, customer_id=None, payment_debug=False, **kwargs): final_dictionnary = dict( order_reference=self.order_reference ) try: cart_model = apps.get_model(settings.CART_MODEL) except: cart_model = apps.get_model('cart.Cart') if cart_model is None: raise exceptions.ImproperlyConfigured(('You should provide a model from which ' 'we can extract the cart total.')) try: self.cart_queryset = cart_model.objects.filter(cart_id__iexact=self.cart_id) total_of_products_to_buy = cart_model.cart_manager.cart_total(self.cart_id, as_value=True) except: raise exceptions.ObjectDoesNotExist(('Could not find a manager of type ' '.cart_manager.cart_total() from which to get the cart total')) else: if total_of_products_to_buy != 0: self.total_of_products_to_buy = total_of_products_to_buy amount = self.price_to_stripe(total_of_products_to_buy) params = { 'amount': amount, 'currency': 'eur', 'source': self.stripe_token, 'description': f'Order for cart {self.cart_id}', 'receipt_email': self.user_infos['email'], 'shipping': { 'address': { 'line1': self.user_infos['address'], 'city': self.user_infos['city'], 'postal_code': self.user_infos['zip_code'] }, 'name': 'Clothes', 'phone': self.user_infos['telephone'] }, 'metadata': { 'name': self._get_full_name(self.user_infos['firstname'], self.user_infos['lastname']), 'order_reference': self.order_reference, 'shipping': self.user_infos['shipping'] } } if 'tracking_number' in kwargs and 'carrier' in kwargs: params.update( { 'tracking_number': kwargs['shipping']['tracking_number'], 'carrier': kwargs['shipping']['carrier'] } ) if customer_id: params.pop('source') params.update({'customer': customer_id}) else: self.errors.append('There was no total to charge to Stripe') charge = None if not payment_debug: try: charge = stripe.Charge.create(**params) except stripe.error.CardError as e: errors = { 'status': e.http_status, 'type': e.error.type, 'code': e.error.code, 'param': e.error.param, 'message': e.error.message } for error in errors: self._build_new_display_error(error['message']) except stripe.error.RateLimitError as e: self.errors.append('Rate limit exceeded') except stripe.error.InvalidRequestError as e: self._build_new_display_error(f'INVALID REQUEST :: {e}') except stripe.error.AuthenticationError as e: self.errors.append('Authentication error') except stripe.error.APIConnectionError as e: self.errors.append('API connection error') except stripe.error.StripeError as e: self._build_new_display_error(f'STRIPE ERROR :: {e}') except Exception as e: self._build_new_display_error(f'OTHER :: {e}') else: charge = {'status': 'succeeded', 'id': 'FAKE ID'} if charge: if charge['status'] == 'succeeded': self.charge_id = charge['id'] url_parameters = { 'order_reference': self.order_reference, 'transaction': charge['id'], 'transaction_token': self.transaction_token } if payment_debug: url_parameters['debug'] = True parameters = urlencode(url_parameters) self.final_url = f'{self.get_success_url()}?{parameters}' self.cart_queryset.update(paid_for=True) final_dictionnary.update({ 'transaction': charge['id'], 'total': total_of_products_to_buy, 'redirect_url': self.final_url }) else: self.errors.append('The charge was not successful') final_dictionnary.update({ 'redirect_url': self.get_failed_url(), 'errors': self.errors, 'context_errors': self.context_errors }) else: self.errors.append('There is no charge or charge not created') final_dictionnary.update({ 'redirect_url': self.get_failed_url(), 'errors': self.errors, 'context_errors': self.context_errors }) if not self.errors: return (True, final_dictionnary) return (False, final_dictionnary)
#include<iostream> #include<algorithm> #include<vector> #include<set> #include<map> #include<utility> using namespace std; typedef long long ll; const int MAX_N = 100005; const int INF = 1000 * 1000 * 1000; int odd[MAX_N][2], even[MAX_N][2], Q[MAX_N]; int n, m, koszt[MAX_N], W[MAX_N]; string S; map<int, int> DP[MAX_N]; int main() { cin >> n; cin >> S; cin >> m; S = "?" + S; for(int i = 1; i <= n; i++) { koszt[i] = -1; } for(int i = 1; i <= n; i++) { odd[i][0] = odd[i - 1][0]; odd[i][1] = odd[i - 1][1]; even[i][0] = even[i - 1][0]; even[i][1] = even[i - 1][1]; Q[i] = Q[i - 1]; if(S[i] == '?') { Q[i]++; continue; } if(i % 2 == 1) { odd[i][S[i] - 'a']++; } else { even[i][S[i] - 'a']++; } } // for(int i = 1; i <= n; i++) { // cout << even[i][0] << " "; // } // cout << endl; for(int i = m; i <= n; i++) { if((i - m + 1) % 2 == 0) { if(odd[i][0] - odd[i - m][0] > 0) { continue; } if(even[i][1] - even[i - m][1] > 0) { continue; } } else { if(odd[i][1] - odd[i - m][1] > 0) { continue; } if(even[i][0] - even[i - m][0] > 0) { continue; } } koszt[i] = Q[i] - Q[i - m]; } // for(int i = 1; i <= n; i++) cout << koszt[i] << " "; // cout << "\n"; // return 0; for(int i = m; i <= n; i++) { W[i] = W[i - 1]; if(koszt[i] != -1) { W[i] = max(W[i], 1 + W[i - m]); } } for(int i = 1; i <= n; i++) { int w = W[i]; DP[i][w] = INF; DP[i][w - 1] = INF; } for(int i = 1; i <= n; i++) { int w = W[i]; if(w == 0) { DP[i][0] = 0; continue; } if(DP[i - 1].find(w) != DP[i - 1].end()) { DP[i][w] = DP[i - 1][w]; } if(DP[i - 1].find(w - 1) != DP[i - 1].end()) { DP[i][w - 1] = DP[i - 1][w - 1]; } if(koszt[i] != -1) { DP[i][w] = min(DP[i][w], DP[i - m][w - 1] + koszt[i]); if(DP[i - m].find(w - 2) != DP[i - m].end()) { DP[i][w - 1] = min(DP[i][w - 1], 1 + DP[i - m][w - 2]); } } } // for(int i = m; i <= n; i++) { // DP[i][0] = DP[i - 1][0]; // DP[i][1] = DP[i - 1][1]; // } cout << DP[n][W[n]]; return 0; }
Gene flow signature in the S-allele region of cultivated buckwheat Background Buckwheat (Fagopyrum esculentum Moench.) is an annual crop that originated in southern China. The nutritious seeds are used in cooking much like cereal grains. Buckwheat is an outcrossing species with heteromorphic self-incompatibility due to its dimorphic (i.e., short- and long-styled) flowers and intra-morph infertility. The floral morphology and intra-morph incompatibility are both determined by a single S locus. Plants with short-styled flowers are heterozygous (S/s) and plants with long-styled flowers are homozygous recessive (s/s) at this locus, and the S/S genotype is not found. Recently, we built a draft genome assembly of buckwheat and identified the 5.4-Mb-long S-allele region harbored by short-styled plants. In this study, the first report on the genome-wide diversity of buckwheat, we used a genotyping-by-sequencing (GBS) dataset to evaluate the genome-wide nucleotide diversity within cultivated buckwheat landraces worldwide. We also investigated the utility of the S-allele region for phylogenetic analysis of buckwheat. Results Buckwheat showed high nucleotide diversity (0.0065), comparable to that of other outcrossing plants, based on a genome-wide simple nucleotide polymorphism (SNP) analysis. Phylogenetic analyses based on genome-wide SNPs showed that cultivated buckwheat comprises two groups, Asian and European, and revealed lower nucleotide diversity in the European group (0.0055) and low differentiation between the Asian and European groups. The nucleotide diversity (0.0039) estimated from SNPs in the S-allele region is lower than that in genome-wide SNPs. Phylogenetic analysis based on this region detected three diverged groups, S-1, S-2, and S-3. Conclusion The SNPs detected using the GBS dataset were effective for elucidating the evolutionary history of buckwheat, and led to the following conclusions: (1) the low nucleotide diversity of the entire genome in the European group and low differentiation between the Asian and European groups suggested genetic bottlenecks associated with dispersion from Asia to Europe, and/or recent intensified cultivation and selection in Europe; and (2) the high diversification in the S-allele region was indicative of gene flows from wild to cultivated buckwheat, suggesting that cultivated buckwheat may have multiple origins. Electronic supplementary material The online version of this article (10.1186/s12870-019-1730-1) contains supplementary material, which is available to authorized users. Background Buckwheat (Fagopyrum esculentum Moench.; 2n = 2x = 16), a member of the Polygonaceae family, is an annual crop that originated in southern China . The seeds (strictly achenes) are used as cereal grains in the same way as rice (Oryza sativa) and wheat (Triticum aestivum); because buckwheat does not belong to the Poaceae family, it is often referred to as a pseudo-cereal. Buckwheat has excellent cultivation properties, with a short growing period and tolerance of cool climate and high elevation. Buckwheat is therefore widely cultivated in temperate zones throughout Eurasia and is used in many traditional foods, such as soba (Japanese noodles), memil guksu (Korean noodles), pizzoccheri (Italian pasta), and galettes (French pancakes). Buckwheat seeds are dense in starch and high-quality protein with a well-balanced amino acid composition and are an important source of dietary fiber, trace elements, and phenolic compounds . Because of its high nutrient content and lack of gluten, buckwheat is now widely cultivated in regions beyond Eurasia, including in the USA, Canada, Australia, and New Zealand. To identify agronomically useful genes, buckwheat linkage maps have been constructed using various molecular markers, including isozyme variations , simple sequence repeats (SSRs) , and amplified fragment-length polymorphisms (AFLPs) . Recently, a microarray marker system and a genome-wide linkage map for common buckwheat were developed . They later confirmed that genomic selection using genome-wide microarray markers was an effective approach for improving buckwheat yield . In addition, our research group constructed the Buckwheat Genome DataBase (BGDB) . Using BGDB, various agronomically useful genes, such as those controlling flavonoid biosynthesis and encoding 2S albumin-type allergens and granule-bound starch synthases (GBSSs), have been identified . Thus, the genetic tools for buckwheat breeding are highly developed. Evaluating genetic diversity is a crucial step for exploring agronomically useful genes in crop species. Buckwheat is an outcrossing species with heteromorphic self-incompatibility (SI) due to its dimorphic flower types (i.e., short-and long-styled flowers), each incompatible with flowers of the same morph, but compatible across morphs . The floral morphology and intra-morph incompatibility are both determined by a single genetic locus, S. Plants with short-styled flowers are heterozygous (S/s) and those with long-styled flowers are homozygous recessive (s/s) at this locus . Thus, like other outcrossing crops such as maize (Zea mays), buckwheat is expected to maintain substantial intraspecies diversity. Indeed, isozyme analysis indicates that buckwheat has great genetic diversity, comparable to that of outcrossing wild plant species ; the heterozygosity of cultivated populations is higher than that seen in wild populations of the ancestral species, F. esculentum ssp. ancestrale, which is found in southern China. Subsequent AFLP and SSR analyses suggested that F. esculentum ssp. ancestrale is composed of two distantly related phylogenetic groups, the Tibetan and the Yunnan-Sichuan groups, and that cultivated buckwheat landraces belong to the Tibetan group . However, these analyses were based only on similarity of DNA banding patterns, and the average number of nucleotide differences per nucleotide site (i.e., the nucleotide diversity) was not estimated. To date, no information on genome-wide nucleotide diversity within F. esculentum is available. Thus, there is great interest in investigating the nucleotide diversity of F. esculentum using newer and superior genomic tools. Recently, we built a draft genome assembly of buckwheat and then applied genotyping-by-sequencing technology (GBS) to a group of buckwheat landraces from around the world . The GBS method, which uses sequences of amplified genomic DNA fragmented by restriction enzymes, has become increasingly popular for detecting large numbers of SNPs . We used the draft genome assembly as reference for GBS markers, and successfully identified the S-allele region, which consisted of 332 scaffolds encompassing 5.4 Mbp . The region contains sites at which GBS reads were mapped in short-styled plants but not in long-styled plants, and harbors two S-allele-specific genes, S-ELF3 and SSG2, that exist only in the genomes of short-styled plants. The genotypes of short-styled and long-styled plants are thus hemizygous and null homozygous, respectively . This is similar to the situation for human sex chromosome genes; the hemizygous state of Y-chromosome genes has proved a useful feature for clarifying human phylogenetic structure . Thus, we predicted that comparisons of DNA sequences in the S-allele region would be a powerful tool for elucidating phylogenetic relationships among buckwheat landraces. In this study, we evaluated the genome-wide nucleotide diversity within worldwide landraces of cultivated buckwheat using the published GBS data. This is the first report of genome-wide nucleotide diversity within F. esculentum. We discuss the utility of the S-allele region for phylogenetic analysis of the buckwheat species, and demonstrate possible gene flows from wild to cultivated buckwheat deduced from the diversified S-allele region. Overall SNP detection and nucleotide diversity We obtained an average of 7.2 million reads per plant (corresponding to 726.1 Mbp). After filtering the sites detected by GBS for 46 buckwheat plants, we retained 7,154,454 sites, corresponding to 0.61% of the reference genome, for further analysis (Table 1). From the 7,154,454 sites, we detected 255,517 SNP sites, representing a SNP density of 0.036 (one SNP per 28 bp). We compared the number of mapping sites, the SNP density, and the nucleotide diversity between shortand long-styled plants and found no significant differences (Table 1). Population structure and phylogenetic analysis We calculated genetic distances among common buckwheat landraces and constructed a phylogenetic tree by the NJ method using 7,154,454 sites including 255,517 SNP sites. The NJ tree showed that 46 cultivars were largely divided into two groups, Asian (32 cultivars) and European (14 cultivars) (Fig. 1). The phylogenetic relationships among cultivated buckwheat were well associated with geographic distribution; samples from one country were phylogenetically closely related in the NJ tree (e.g., I8601 and I 8605 for India, N8323 and N8605 for Nepal, and T1F and X1F for Japan). The PCA plot also showed that 46 cultivars were largely divided into two groups composed of Asian and European cultivars, respectively (Fig. 2). To clarify the population structure of buckwheat, we subjected 255,517 SNPs segregated in 46 GBS to ADMIXTURE analysis. Cross-validation error was lowest at K = 1 and gradually increased as K increased (Additional file 1: Figure S1). At K = 2, the cross-validation error was also low, indicating that the optimal number of ancestral populations was K = 1 or K = 2. Although the lowest cross-validation error was actually observed at K = 1, the NJ tree and PCA implied that there were two groups (one including only Asian landraces and the other only European landraces), indicating that K = 2 is suitable for grouping the 46 common buckwheat landraces. We refer to the two groups hereafter as the Asian and European groups. To compare nucleotide diversity between the Asian and European groups, we identified SNPs and calculated the genome-wide mean nucleotide diversity of each group ( Table 1). The SNP density was much lower in the European group (0.019) than in the Asian group (0.034). Nucleotide diversity was also lower in the European (0.0055) than in the Asian (0.065) group. However, even though the NJ tree and PCA plot indicated that there were two groups, the Fst value between Asian and European cultivars was not very high (Fst = 0.068). Diversity of S-linked scaffolds We previously identified the S-allele region, consisting of 332 scaffolds encompassing 5,393,196 bp, to which short-style-specific sites were mapped . To analyze the nucleotide diversity of this region, we identified SNPs on these 332 scaffolds in 23 short-styled plants. From the 60,108 sites (0.11% of the total length of the 332 scaffolds), we detected 1123 SNPs. The SNP density (0.019) and genetic diversity (0.0039) in the S-allele scaffolds were lower than those in all genomic scaffolds (Table 1). To uncover the phylogenetic relationship among the S-allele region obtained from 23 short-styled plants, we constructed an NJ tree based on the S-allele region using 60,108 sites, including 1123 SNP sites. The NJ tree based on the S-allele region showed that common buckwheat plants of the short-styled phenotype (S/s genotype) were largely divided into three groups, which we named S-1, S-2, and S-3 (Fig. 3). The phylogenetic relationship identified on the basis of the S-linked scaffolds was identical to that implied by analysis of S-ELF and SSG2 but different from that of the NJ tree based on genome-wide SNPs (Fig. 1). The S-1, S-2, and S-3 phylogenetic groups were composed of fifteen, five, and three cultivars, respectively. These groups were also detected by the PCA (Additional file 2: Figure S2). The nucleotide diversity of the S-allele region (0.0039) was lower than that of all scaffolds ( Table 1). The average nucleotide distance and Fst value between the phylogenetic groups in the S-linked scaffolds were high (Table 2). In particular, S-3 was clearly more distantly related to S-1 and S-2 than they were to each other. Discussion Genome-wide and S-allele-region-specific nucleotide diversity in common buckwheat In this study, we obtained 255,517 genome-wide SNPs using the GBS method, which is capable of producing larger numbers of genome-wide SNPs than had been obtained in previous studies of this species. Furthermore, the published genome sequence enabled us to estimate the nucleotide diversity, which revealed that the nucleotide diversity of common buckwheat (0.0065) was comparable to that of other outcrossing plants, such as maize (Zea mays, 0.0064) and sunflower (Helianthus annuus; 0.0056) , and higher than that of selfing crops such as rice (Oryza sativa, 0.0024) and soybean (Glycine max; 0.0019) . This higher nucleotide diversity is likely due to buckwheat's outcrossing mating system and/or to gene flow from wild buckwheat, F. esculentum ssp. ancestrale. The genetic basis of the heteromorphic SI system is similar to that of sex chromosomes in the plant and animal kingdoms. There have been numerous reports on the nucleotide diversities of sex chromosomes . In humans, for example, the ratios of the nucleotide diversities of the X and Y chromosomes to those of the autosomal chromosomes are 0.62 and 0.20, respectively . The lower nucleotide diversities observed in sex chromosomes are an expected result of the lower effective population size: the effective population sizes of the human X and Y chromosomes correspond to 3/4 and 1/4 that of autosomal chromosomes, respectively. In this study, we confirmed that the nucleotide diversity of the S-allele region is similarly lower than that of the genome as a whole: the ratio of the nucleotide diversity of the S-allele region to that of the whole genome is 0.62. That this number is much higher than the expected value (0.25) is probably due to the low density of functional genes in the S-allele region and/or to recent multiple gene flows, as discussed in the following section. Much higher genetic diversity of S-allelic region than expected also indicates that S-allelic region is not under purifying selection. Gene flow inferred from S-allele divergence The phylogenetic relationships deduced from the 332 S-allele scaffolds (Fig. 3) were not congruent with those based on genome-wide SNPs (Fig. 1): three widely diverged phylogenetic groups, S-1, S-2, and S-3, were detected in the data shown in Fig. 3 (from the S-allele region) but not in Fig. 1 (from the whole genome). It is noteworthy that the three phylogenetic groups of S-allele regions are well diverged. In particular, S-3 is strongly divergent from the other two groups: the nucleotide diversity between S-3 and the other two groups is around 0.006 (Table 2). Using a rough molecular clock rate of 0.01 synonymous nucleotide substitutions per million years (e.g., 0.011 for Gossypium species and 0.016 for Arachis species) , this would indicate that group S-3 diverged from the other groups 0.3 million years ago. The earliest plausibly identified buckwheat archeological pollen specimen, found in northern China, has been dated to 5000 to 6000 BP . Thus, it is unlikely that mutations detected in S-alleles derive from the origin of buckwheat cultivation. Considering the possibility of cross-compatibility resulting in fertile hybrids and the overlap in habitats between cultivated and wild buckwheat, we concluded that the diverged S-allele sequences were introgressed from wild buckwheat, F. esculentum ssp. ancestrale, and that the introgressions between wild and cultivated buckwheat are also attributable to high genome-wide diversity. S-allele region as a phylogenetic tool for elucidating the origin and diffusion of cultivated buckwheat ADMIXTURE and phylogenetic analyses and PCA classified 46 buckwheat cultivars into two groups, the Asian and European groups, with a low Fst value (Fst = 0.068). The European group exhibited lower nucleotide diversity than the Asian group (Table 1). From archeological studies of the pollen and macrofossil (i.e., charred seeds) records, it has been suggested that buckwheat was introduced into Europe during the period 4000-2800 BP, though it did not become a popular crop until the Late Medieval period . Both the lower nucleotide diversity in the European group and the weak differentiation between the Asian and European groups are likely due to genetic bottlenecks associated with dispersion from Asia to Europe, and/or the recent intensified cultivation and selection. The low genetic variation and loss of alleles detected by isozyme analysis also support this hypothesis . Y chromosomes, which retain sequential records of the accumulation of nucleotide diversity, have been used to detect ancestral haplotypes and to trace human migrations . Although genome-wide SNPs have illuminated the population structure and population differentiation of cultivated buckwheat, the SNPs in S-linked scaffolds may shed light on different aspects of the diffusion history of the species. In this study, we detected three major S-allele groups, S-1, S-2, and S-3 (Fig. 3). The phylogenetic relationship implied by S-linked scaffolds suggested the introgressions from wild relatives as discussed above. This is due to the suppression of recombination in S-allelic region like sex chromosomes. Thus, phylogenetic analysis using S-allelic region is expected to offer better understanding of the origin and global diffusion of cultivated buckwheat. In this study, we did not find type S-1 S-allele sequences in the populations from Nepal and Bhutan. Based on our identification of the three diverged S-allele groups, the possibility that cultivated buckwheat had multiple origins should also be considered. Considering that remains of buckwheat seeds appeared in west-central Nepal from 3000 BP , we should consider the possibility that buckwheat was independently domesticated around the Himalayan region, including Nepal, Bhutan, and southwestern China. To elucidate the origin and global diffusion history of cultivated buckwheat, we would need to expand our sample set to include many more samples of cultivated buckwheat from around the world, as well as samples of wild buckwheat, F. esculentum ssp. ancestrale, from China. Conclusion Based on genome-wide SNPs obtained using GBS technology, we successfully estimated the nucleotide diversity (0.0065) of buckwheat, which is comparable to that of other outcrossing plants, such as maize and sunflower. Phylogenetic analyses based on genome-wide SNPs also showed that cultivated buckwheat is composed of two groups, Asian and European. The low nucleotide diversity of the European group and the low differentiation between the Asian and European groups are consistent with genetic bottlenecks associated with dispersion from Asia to Europe, and/or the recent intensified cultivation and selection of buckwheat in Europe. These results based on genome-wide SNPs are congruent with those of previous studies based on isozyme S-1, S-2, and S-3 are phylogenetic groups detected by NJ analysis (Fig. 3) and PCA (Additional file 2: Figure S2) variation. The nucleotide diversity (0.0039) estimated using SNPs in the S-allele region was lower than that estimated using genome-wide SNPs, reflecting the smaller population size of the S-allele region as compared to the genome as a whole. The data also indicated the likelihood of gene flow from wild to cultivated buckwheat and the possibility of multiple origins for cultivated buckwheat. In conclusion, phylogenetic analysis using the S-allele region can offer a better understanding of the origin of cultivation and the global diffusion history of cultivated buckwheat. Genotype-by-sequencing data and SNP detection We used published GBS reads obtained using EcoRI and MseI restriction enzymes (DRA accession number DRA004489, ftp://ftp.ddbj.nig.ac.jp/ddbj_database/dra/ fastq/DRA004/DRA004489) . The GBS dataset represented 23 short-styled and 23 long-styled buckwheat landraces originating from a wide range of locations within Eurasia (Additional file 3: Table S1). Low-quality reads and adaptors were trimmed using Trimmomatic-0.36 with the options SLIDINGWIN-DOW:5:25 and MINLEN:40. The adaptor sequences used were CACGACGCTCTTCCGATCT and ACCG CTCTTCCGATCTGTAA. The trimmed paired-end (PE) reads were mapped against the buckwheat reference sequence (FES_r1.0) using BWA 0.7.15 (Li and Durbin 2009) with the -L 10 and -B 10 options. Single-end reads were filtered from BAM files using samtools 1.3.1. . Variants were called by the samtools mpileup function and bcftools implemented in samtools 1.3.1. Sites with depths of less than 4 and more than 40 were converted to missing data using VCFtools 0.1.13 . Then, sites with proportions of missing data greater than 0.2 were filtered using VCFtools 0.1.13. Construction of phylogenetic tree and structure analysis ADMIXTURE v1.22 was used to investigate the population structure of the 46 common buckwheat landraces. For each value of K, ten ADMIXTURE analysis runs were performed with different random seeds. The best run was selected according to the highest value of log likelihood. A neighbor-joining (NJ) tree was constructed using SEQBOOT with 100 replicates, followed by the DNAdist (with the Kimura two-parameter method), Neighbor, and Consense programs from the PHYLIP package 3. . The nucleotide diversity and F-statistics Sites with a proportion of missing data greater than 0.2 were filtered using VCFtools 0.1.13. Then, the nucleotide diversity within species and each classification/group was calculated using VCFtools 0.1.13. Weir and Cockerham's weighted F-statistics (Fst) was calculated using VCFtools 0.1.13. Additional files Additional file 1: Figure S1. Additional file 3: Table S1. List of buckwheat landrcces used in this study. (PDF 51 kb)
Jeremy McConnell and Stephanie Davis could be set for a Celebrity Big Brother comeback this summer. The pair first appeared in last January's series where they hooked up before things quickly turned very messy on the outside. The former couple, who are currently embroiled in a paternity dispute over Stephanie's new born baby Caben-Albi, could be set for a reunion on Celebrity Big Brother. According to The Sun newspaper, the pair are 'top of the wishlist' for celebrities on this summer's new Celebrity Big Brother series. Stephanie and Jeremy. It's expected that the new run will again be an All Star special, supposedly titled 'Summer Legends' to celebrate the 20th series. A source spilled to The Sun newspaper: "Jeremy really enjoyed Celebrity Big Brother the first time round and would love to be a part of the Summer Legends series. “A lot has happened since he last appeared on the show between him and Stephanie, but he knows them both joining the line-up would make incredible telly, and he’s keen to keep his profile up." The insider added: “They aren’t on speaking terms at the moment but going back to where it all started for them in the Big Brother house may be exactly what they need to move forward – and viewers would love it.” A spokesperson for Celebrity Big Brother told the publication: “We never comment on speculation around future housemates.” In December Stephanie revealed she had been asked to take part in the most recent Celebrity Big Brother series which started in January. Stephanie. She explained: "I was asked to return to the show but I'll be at home focusing on being the best mum I can be, that's for sure. "I thank CBB for so much though and for the journey it put me on. If it wasn't for them, I wouldn't have my son." Celebrity Big Brother will return to Channel 5 in the summer.
// CheckEtcdDataFileExists checks for the existance of an etcd db file. If the db exists we can assume this etcd // has previously started or is currently being recovered. If true we can not assume kube exists yet or will // during the life of this container. For example disaster recovery. // TODO organize into a general util func CheckEtcdDataFileExists(dataFilePath string) bool { if _, err := os.Stat(dataFilePath); err != nil { if os.IsNotExist(err) { klog.Infof("CheckEtcdDataFileExists(): %s does not exist, waiting for kube", dataFilePath) return false } klog.Errorf("CheckEtcdDataFileExists(): %v", err) } return true }
<reponame>gabystern/capybara-webkit<filename>src/Node.cpp #include "Node.h" #include "WebPage.h" #include "WebPageManager.h" #include "JsonSerializer.h" #include "InvocationResult.h" Node::Node(WebPageManager *manager, QStringList &arguments, QObject *parent) : JavascriptCommand(manager, arguments, parent) { } void Node::start() { QStringList functionArguments(arguments()); QString functionName = functionArguments.takeFirst(); QString allowUnattached = functionArguments.takeFirst(); InvocationResult result = page()->invokeCapybaraFunction(functionName, allowUnattached == "true", functionArguments); if (functionName == "focus_frame") { page()->setCurrentFrameParent(page()->currentFrame()->parentFrame()); } if (result.hasError()) { finish(&result); } else { JsonSerializer serializer; InvocationResult jsonResult = InvocationResult(serializer.serialize(result.result())); finish(&jsonResult); } } QString Node::toString() const { QStringList functionArguments(arguments()); return QString("Node.") + functionArguments.takeFirst(); }
// seek from name pointer to start of attributes. static const unsigned char *seekToAttrs(const unsigned char *current, u_int32_t flags) { DBXML_ASSERT(current); current += NsUtil::nsStringLen(current) + 1; int32_t skip; if (flags & NS_HASTEXT) { current += NsFormat::unmarshalInt(current, &skip); current += skip; if (flags & NS_HASTEXTCHILD) { current += NsFormat::unmarshalInt(current, &skip); } } current += NsFormat::unmarshalInt(current, &skip); return current; }
<gh_stars>10-100 /* Generated by RuntimeBrowser Image: /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit */ @interface _NSTableColumnAuxiliary : NSObject { _NSBindingAdaptor * _bindingAdaptor; struct { double x; double width; } _cachedPosition; NSString * _headerToolTip; NSSortDescriptor * _sortDescriptorPrototype; } - (void).cxx_destruct; @end
// // Copyright 2019 Insolar Technologies GmbH // // 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. // // +build slowtest package integration import ( "context" "flag" "fmt" "io" "math" "os" "sync" "testing" "time" "github.com/ThreeDotsLabs/watermill" "github.com/ThreeDotsLabs/watermill/message" "github.com/ThreeDotsLabs/watermill/pubsub/gochannel" "github.com/insolar/component-manager" "github.com/pkg/errors" "github.com/insolar/insolar/configuration" "github.com/insolar/insolar/contractrequester" "github.com/insolar/insolar/cryptography" "github.com/insolar/insolar/insolar" "github.com/insolar/insolar/insolar/bus" "github.com/insolar/insolar/insolar/bus/meta" "github.com/insolar/insolar/insolar/jet" "github.com/insolar/insolar/insolar/jetcoordinator" "github.com/insolar/insolar/insolar/node" "github.com/insolar/insolar/insolar/payload" "github.com/insolar/insolar/insolar/pulse" "github.com/insolar/insolar/instrumentation/inslogger" "github.com/insolar/insolar/keystore" "github.com/insolar/insolar/log/logwatermill" "github.com/insolar/insolar/logicrunner" "github.com/insolar/insolar/logicrunner/artifacts" "github.com/insolar/insolar/logicrunner/logicexecutor" "github.com/insolar/insolar/logicrunner/machinesmanager" "github.com/insolar/insolar/logicrunner/pulsemanager" "github.com/insolar/insolar/network" "github.com/insolar/insolar/platformpolicy" ) func NodeLight() insolar.Reference { return light.ref } const PulseStep insolar.PulseNumber = 10 type Server struct { ctx context.Context test *testing.T pm insolar.PulseManager componentManager *component.Manager stopper func() pulse insolar.Pulse lock sync.RWMutex clientSender bus.Sender logicRunner *logicrunner.LogicRunner contractRequester *contractrequester.ContractRequester ExternalPubSub, IncomingPubSub *gochannel.GoChannel } func DefaultVMConfig() configuration.Configuration { cfg := configuration.Configuration{} cfg.KeysPath = "testdata/bootstrap_keys.json" cfg.Ledger.LightChainLimit = math.MaxInt32 cfg.LogicRunner = configuration.NewLogicRunner() cfg.Bus.ReplyTimeout = 5 * time.Second cfg.Log = configuration.NewLog() cfg.Log.Level = insolar.DebugLevel.String() cfg.Log.Formatter = insolar.TextFormat.String() return cfg } func DefaultLightResponse(pl payload.Payload) []payload.Payload { switch pl.(type) { // getters case *payload.GetFilament, *payload.GetCode, *payload.GetRequest, *payload.GetRequestInfo: return nil case *payload.SetIncomingRequest, *payload.SetOutgoingRequest: return []payload.Payload{&payload.RequestInfo{}} // setters case *payload.SetResult, *payload.SetCode: return []payload.Payload{&payload.ID{}} case *payload.HasPendings: return []payload.Payload{&payload.PendingsInfo{HasPendings: true}} } panic(fmt.Sprintf("unexpected message to lightt %T", pl)) } func checkError(ctx context.Context, err error, message string) { if err == nil { return } inslogger.FromContext(ctx).Fatalf("%v: %v", message, err.Error()) } var verboseWM bool func init() { flag.BoolVar(&verboseWM, "verbose-wm", false, "flag to enable watermill logging") } func NewServer( t *testing.T, ctx context.Context, cfg configuration.Configuration, receiveCallback func(meta payload.Meta, pl payload.Payload) []payload.Payload, mManager machinesmanager.MachinesManager) (*Server, error) { ctx, logger := inslogger.InitNodeLogger(ctx, cfg.Log, "", "") if mManager == nil { mManager = machinesmanager.NewMachinesManager() } cm := component.NewManager(nil) // Cryptography. var ( KeyProcessor insolar.KeyProcessor CryptoScheme insolar.PlatformCryptographyScheme CryptoService insolar.CryptographyService KeyStore insolar.KeyStore ) { var err error // Private key storage. KeyStore, err = keystore.NewKeyStore(cfg.KeysPath) if err != nil { return nil, errors.Wrap(err, "failed to load KeyStore") } // Public key manipulations. KeyProcessor = platformpolicy.NewKeyProcessor() // Platform cryptography. CryptoScheme = platformpolicy.NewPlatformCryptographyScheme() // Sign, verify, etc. CryptoService = cryptography.NewCryptographyService() } // Network. var ( NodeNetwork network.NodeNetwork ) { NodeNetwork = newNodeNetMock(&virtual) } // Role calculations. var ( Coordinator *jetcoordinator.Coordinator Pulses *pulse.StorageMem Jets *jet.Store Nodes *node.Storage ) { Nodes = node.NewStorage() Pulses = pulse.NewStorageMem() Jets = jet.NewStore() Coordinator = jetcoordinator.NewJetCoordinator(cfg.Ledger.LightChainLimit, virtual.ref) Coordinator.PulseCalculator = Pulses Coordinator.PulseAccessor = Pulses Coordinator.JetAccessor = Jets Coordinator.PlatformCryptographyScheme = CryptoScheme Coordinator.Nodes = Nodes } // PulseManager var ( PulseManager *pulsemanager.PulseManager ) { PulseManager = pulsemanager.NewPulseManager() } wmLogger := watermill.LoggerAdapter(watermill.NopLogger{}) if verboseWM { wmLogger = logwatermill.NewWatermillLogAdapter(logger) } // Communication. var ( ClientBus *bus.Bus ExternalPubSub, IncomingPubSub *gochannel.GoChannel ) { pubsub := gochannel.NewGoChannel(gochannel.Config{}, wmLogger) ExternalPubSub = pubsub IncomingPubSub = pubsub c := jetcoordinator.NewJetCoordinator(cfg.Ledger.LightChainLimit, virtual.ref) c.PulseCalculator = Pulses c.PulseAccessor = Pulses c.JetAccessor = Jets c.PlatformCryptographyScheme = CryptoScheme c.Nodes = Nodes ClientBus = bus.NewBus(cfg.Bus, IncomingPubSub, Pulses, c, CryptoScheme) } logicRunner, err := logicrunner.NewLogicRunner(&cfg.LogicRunner, IncomingPubSub, ClientBus) checkError(ctx, err, "failed to start LogicRunner") contractRequester, err := contractrequester.New( ClientBus, Pulses, Coordinator, CryptoScheme, ) checkError(ctx, err, "failed to start ContractRequester") // TODO: remove this hack in INS-3341 contractRequester.LR = logicRunner cm.Inject(CryptoScheme, KeyStore, CryptoService, KeyProcessor, Coordinator, logicRunner, ClientBus, IncomingPubSub, contractRequester, artifacts.NewClient(ClientBus), artifacts.NewDescriptorsCache(), Pulses, Jets, Nodes, logicexecutor.NewLogicExecutor(), logicrunner.NewRequestsExecutor(), mManager, NodeNetwork, PulseManager) err = cm.Init(ctx) checkError(ctx, err, "failed to init components") err = cm.Start(ctx) checkError(ctx, err, "failed to start components") // Start routers with handlers. outHandler := func(msg *message.Message) error { var err error if msg.Metadata.Get(meta.Type) == meta.TypeReply { err = ExternalPubSub.Publish(getIncomingTopic(msg), msg) if err != nil { panic(errors.Wrap(err, "failed to publish to self")) } return nil } msgMeta := payload.Meta{} err = msgMeta.Unmarshal(msg.Payload) if err != nil { panic(errors.Wrap(err, "failed to unmarshal meta")) } // Republish as incoming to self. if msgMeta.Receiver == virtual.ID() { err = ExternalPubSub.Publish(getIncomingTopic(msg), msg) if err != nil { panic(errors.Wrap(err, "failed to publish to self")) } return nil } pl, err := payload.Unmarshal(msgMeta.Payload) if err != nil { panic(errors.Wrap(err, "failed to unmarshal payload")) } if msgMeta.Receiver == NodeLight() { go func() { var replies []payload.Payload if receiveCallback != nil { replies = receiveCallback(msgMeta, pl) } else { replies = DefaultLightResponse(pl) } for _, rep := range replies { msg, err := payload.NewMessage(rep) if err != nil { panic(err) } ClientBus.Reply(context.Background(), msgMeta, msg) } }() } clientHandler := func(msg *message.Message) (messages []*message.Message, e error) { return nil, nil } // Republish as incoming to client. _, err = ClientBus.IncomingMessageRouter(clientHandler)(msg) if err != nil { panic(err) } return nil } stopper := startWatermill( ctx, wmLogger, IncomingPubSub, ClientBus, outHandler, logicRunner.FlowDispatcher.Process, contractRequester.FlowDispatcher.Process, ) PulseManager.AddDispatcher(logicRunner.FlowDispatcher, contractRequester.FlowDispatcher) inslogger.FromContext(ctx).WithFields(map[string]interface{}{ "light": light.ID().String(), "virtual": virtual.ID().String(), }).Info("started test server") s := &Server{ ctx: ctx, contractRequester: contractRequester, test: t, pm: PulseManager, componentManager: cm, stopper: stopper, pulse: *insolar.GenesisPulse, clientSender: ClientBus, } return s, nil } func (s *Server) Stop(ctx context.Context) { panicIfErr(s.componentManager.Stop(ctx)) s.stopper() } func (s *Server) SetPulse(ctx context.Context) { s.lock.Lock() defer s.lock.Unlock() s.pulse = insolar.Pulse{ PulseNumber: s.pulse.PulseNumber + PulseStep, } err := s.pm.Set(ctx, s.pulse) if err != nil { panic(err) } } func (s *Server) SendToSelf(ctx context.Context, pl payload.Payload) (<-chan *message.Message, func()) { msg, err := payload.NewMessage(pl) if err != nil { panic(err) } msg.Metadata.Set(meta.TraceID, s.test.Name()) return s.clientSender.SendTarget(ctx, msg, virtual.ID()) } func (s *Server) Pulse() insolar.PulseNumber { s.lock.Lock() defer s.lock.Unlock() return s.pulse.PulseNumber } func startWatermill( ctx context.Context, logger watermill.LoggerAdapter, sub message.Subscriber, b *bus.Bus, outHandler, inHandler, resultsHandler message.NoPublishHandlerFunc, ) func() { inRouter, err := message.NewRouter(message.RouterConfig{}, logger) if err != nil { panic(err) } outRouter, err := message.NewRouter(message.RouterConfig{}, logger) if err != nil { panic(err) } outRouter.AddNoPublisherHandler( "OutgoingHandler", bus.TopicOutgoing, sub, outHandler, ) inRouter.AddMiddleware( b.IncomingMessageRouter, ) inRouter.AddNoPublisherHandler( "IncomingHandler", bus.TopicIncoming, sub, inHandler, ) inRouter.AddNoPublisherHandler( "IncomingRequestResultHandler", bus.TopicIncomingRequestResults, sub, resultsHandler) startRouter(ctx, inRouter) startRouter(ctx, outRouter) return stopWatermill(ctx, inRouter, outRouter) } func stopWatermill(ctx context.Context, routers ...io.Closer) func() { return func() { for _, r := range routers { err := r.Close() if err != nil { inslogger.FromContext(ctx).Error("Error while closing router", err) } } } } func startRouter(ctx context.Context, router *message.Router) { go func() { if err := router.Run(ctx); err != nil { inslogger.FromContext(ctx).Error("Error while running router", err) } }() <-router.Running() } func getIncomingTopic(msg *message.Message) string { topic := bus.TopicIncoming if msg.Metadata.Get(meta.Type) == meta.TypeReturnResults { topic = bus.TopicIncomingRequestResults } return topic } func TestMain(m *testing.M) { flag.Parse() os.Exit(m.Run()) }
<filename>src/horoscopecli/horoscopecli/horoscopeScrapper.py from bs4 import BeautifulSoup import urllib.request import urllib.error import socket def getHoroscopeScrapper(sign: str, category: str): dic = {"love": 0, "work": 1, "finance": 2, "self": 3, "family": 4} urlpage = f"https://www.evozen.fr/horoscope/horoscope-du-jour/{sign}" try: page = urllib.request.urlopen(urlpage, timeout=30) except urllib.error.HTTPError as e: print("http") return ("ERROR: HTTPError occured: ", e.code) except urllib.error.URLError as e: print("url") return ("ERROR: URLError occured: ", f"Site url: https://www.evozen.fr/horoscope/horoscope-du-jour/{sign}") except socket.timeout as e: print("timout") return ("ERROR: Socket timeout occured of 30seconds, try again later: ", f"Site url: https://www.evozen.fr/horoscope/horoscope-du-jour/{sign}") else: soup = BeautifulSoup(page, 'html.parser') myDivs = soup.find_all("div", {"class": "daily-tex t-container"}) div = dic[category] data = myDivs[div].find_all('p') return (data[0].get_text(), data[1].get_text())
New Delhi: Sanjay Leela Bhansali's (SLB) ambitious project 'Padmavati' seems to be in trouble much before its release. After the untoward incident in Jaipur's 'Jaigarh Fort' where the film sets were vandalised and the filmmaker abused by Karni Sena members, comes yet another shocker for SLB. A Rajasthan minister said that 'Padmavati' will not get a release in the state till it is shown to the Rajput community leaders who have objected to the movie, according to PTI. "We will not allow the release of the film in Rajasthan till it is screened to our community members," Energy Minister Pushpendra Singh told the gathering. He addressing a protest organised by Savarna Adhikar Aarakshan Manch near the assembly building. The minister assured a section of the Rajput community that the film will not be released in the state. A complete ban on the upcoming film in Rajasthan, quota for economically backward upper castes, including Rajputs, Brahman and others, formation of a board for upper castes, a CBI probe into the murder of a Rajput community member -- Chatur Singh Sodha in Jaisalmer -- were the demands of the protesters who were led by national president of Shree Rastriya Rajput Karni Sena Sukhdev Singh. Shree Rashtriya Rajput Karni Sena is an offshoot of Karni Sena which had hit headlines sometime back for staging protest against Bhansali's film alleging distortion of historical facts by the filmmaker. (With PTI inputs)
<gh_stars>0 /****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * HYPRE_StructMatrix interface * *****************************************************************************/ #include "_hypre_struct_mv.h" #include "fortran.h" #ifdef __cplusplus extern "C" { #endif /*-------------------------------------------------------------------------- * HYPRE_StructMatrixCreate *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixcreate, HYPRE_STRUCTMATRIXCREATE) (hypre_F90_Comm *comm, hypre_F90_Obj *grid, hypre_F90_Obj *stencil, hypre_F90_Obj *matrix, hypre_F90_Int *ierr) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixCreate( hypre_F90_PassComm (comm), hypre_F90_PassObj (HYPRE_StructGrid, grid), hypre_F90_PassObj (HYPRE_StructStencil, stencil), hypre_F90_PassObjRef (HYPRE_StructMatrix, matrix) ); } /*-------------------------------------------------------------------------- * HYPRE_StructMatrixDestroy *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixdestroy, HYPRE_STRUCTMATRIXDESTROY) ( hypre_F90_Obj *matrix, hypre_F90_Int *ierr ) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixDestroy( hypre_F90_PassObj (HYPRE_StructMatrix, matrix) ); } /*-------------------------------------------------------------------------- * HYPRE_StructMatrixInitialize *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixinitialize, HYPRE_STRUCTMATRIXINITIALIZE) ( hypre_F90_Obj *matrix, hypre_F90_Int *ierr ) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixInitialize( hypre_F90_PassObj (HYPRE_StructMatrix, matrix) ); } /*-------------------------------------------------------------------------- * HYPRE_StructMatrixSetValues *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixsetvalues, HYPRE_STRUCTMATRIXSETVALUES) ( hypre_F90_Obj *matrix, hypre_F90_IntArray *grid_index, hypre_F90_Int *num_stencil_indices, hypre_F90_IntArray *stencil_indices, hypre_F90_ComplexArray *values, hypre_F90_Int *ierr ) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixSetValues( hypre_F90_PassObj (HYPRE_StructMatrix, matrix), hypre_F90_PassIntArray (grid_index), hypre_F90_PassInt (num_stencil_indices), hypre_F90_PassIntArray (stencil_indices), hypre_F90_PassComplexArray (values) ); } /*-------------------------------------------------------------------------- * HYPRE_StructMatrixSetBoxValues *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixsetboxvalues, HYPRE_STRUCTMATRIXSETBOXVALUES) ( hypre_F90_Obj *matrix, hypre_F90_IntArray *ilower, hypre_F90_IntArray *iupper, hypre_F90_Int *num_stencil_indices, hypre_F90_IntArray *stencil_indices, hypre_F90_ComplexArray *values, hypre_F90_Int *ierr ) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixSetBoxValues( hypre_F90_PassObj (HYPRE_StructMatrix, matrix), hypre_F90_PassIntArray (ilower), hypre_F90_PassIntArray (iupper), hypre_F90_PassInt (num_stencil_indices), hypre_F90_PassIntArray (stencil_indices), hypre_F90_PassComplexArray (values) ); } /*-------------------------------------------------------------------------- * HYPRE_StructMatrixGetBoxValues *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixgetboxvalues, HYPRE_STRUCTMATRIXGETBOXVALUES) ( hypre_F90_Obj *matrix, hypre_F90_IntArray *ilower, hypre_F90_IntArray *iupper, hypre_F90_Int *num_stencil_indices, hypre_F90_IntArray *stencil_indices, hypre_F90_ComplexArray *values, hypre_F90_Int *ierr ) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixGetBoxValues( hypre_F90_PassObj (HYPRE_StructMatrix, matrix), hypre_F90_PassIntArray (ilower), hypre_F90_PassIntArray (iupper), hypre_F90_PassInt (num_stencil_indices), hypre_F90_PassIntArray (stencil_indices), hypre_F90_PassComplexArray (values) ); } /*-------------------------------------------------------------------------- * HYPRE_StructMatrixSetConstantValues *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixsetconstantva, HYPRE_STRUCTMATRIXSETCONSTANTVA) ( hypre_F90_Obj *matrix, hypre_F90_Int *num_stencil_indices, hypre_F90_IntArray *stencil_indices, hypre_F90_ComplexArray *values, hypre_F90_Int *ierr ) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixSetConstantValues( hypre_F90_PassObj (HYPRE_StructMatrix, matrix), hypre_F90_PassInt (num_stencil_indices), hypre_F90_PassIntArray (stencil_indices), hypre_F90_PassComplexArray (values) ); } /*-------------------------------------------------------------------------- * HYPRE_StructMatrixAddToValues *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixaddtovalues, HYPRE_STRUCTMATRIXADDTOVALUES) ( hypre_F90_Obj *matrix, hypre_F90_IntArray *grid_index, hypre_F90_Int *num_stencil_indices, hypre_F90_IntArray *stencil_indices, hypre_F90_ComplexArray *values, hypre_F90_Int *ierr ) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixAddToValues( hypre_F90_PassObj (HYPRE_StructMatrix, matrix), hypre_F90_PassIntArray (grid_index), hypre_F90_PassInt (num_stencil_indices), hypre_F90_PassIntArray (stencil_indices), hypre_F90_PassComplexArray (values) ); } /*-------------------------------------------------------------------------- * HYPRE_StructMatrixAddToBoxValues *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixaddtoboxvalues, HYPRE_STRUCTMATRIXADDTOBOXVALUES) ( hypre_F90_Obj *matrix, hypre_F90_IntArray *ilower, hypre_F90_IntArray *iupper, hypre_F90_Int *num_stencil_indices, hypre_F90_IntArray *stencil_indices, hypre_F90_ComplexArray *values, hypre_F90_Int *ierr ) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixAddToBoxValues( hypre_F90_PassObj (HYPRE_StructMatrix, matrix), hypre_F90_PassIntArray (ilower), hypre_F90_PassIntArray (iupper), hypre_F90_PassInt (num_stencil_indices), hypre_F90_PassIntArray (stencil_indices), hypre_F90_PassComplexArray (values) ); } /*-------------------------------------------------------------------------- * HYPRE_StructMatrixAddToConstantValues *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixaddtoconstant, HYPRE_STRUCTMATRIXADDTOCONSTANT) ( hypre_F90_Obj *matrix, hypre_F90_Int *num_stencil_indices, hypre_F90_IntArray *stencil_indices, hypre_F90_ComplexArray *values, hypre_F90_Int *ierr ) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixSetConstantValues( hypre_F90_PassObj (HYPRE_StructMatrix, matrix), hypre_F90_PassInt (num_stencil_indices), hypre_F90_PassIntArray (stencil_indices), hypre_F90_PassComplexArray (values) ); } /*-------------------------------------------------------------------------- * HYPRE_StructMatrixAssemble *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixassemble, HYPRE_STRUCTMATRIXASSEMBLE) ( hypre_F90_Obj *matrix, hypre_F90_Int *ierr ) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixAssemble( hypre_F90_PassObj (HYPRE_StructMatrix, matrix) ); } /*-------------------------------------------------------------------------- * HYPRE_StructMatrixSetNumGhost *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixsetnumghost, HYPRE_STRUCTMATRIXSETNUMGHOST) ( hypre_F90_Obj *matrix, hypre_F90_IntArray *num_ghost, hypre_F90_Int *ierr ) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixSetNumGhost( hypre_F90_PassObj (HYPRE_StructMatrix, matrix), hypre_F90_PassIntArray (num_ghost) ); } /*-------------------------------------------------------------------------- * HYPRE_StructMatrixGetGrid *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixgetgrid, HYPRE_STRUCTMATRIXGETGRID) ( hypre_F90_Obj *matrix, hypre_F90_Obj *grid, hypre_F90_Int *ierr ) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixGetGrid( hypre_F90_PassObj (HYPRE_StructMatrix, matrix), hypre_F90_PassObjRef (HYPRE_StructGrid, grid) ); } /*-------------------------------------------------------------------------- * HYPRE_StructMatrixSetSymmetric *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixsetsymmetric, HYPRE_STRUCTMATRIXSETSYMMETRIC) ( hypre_F90_Obj *matrix, hypre_F90_Int *symmetric, hypre_F90_Int *ierr ) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixSetSymmetric( hypre_F90_PassObj (HYPRE_StructMatrix, matrix), hypre_F90_PassInt (symmetric) ); } /*-------------------------------------------------------------------------- * HYPRE_StructMatrixSetConstantEntries *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixsetconstanten, HYPRE_STRUCTMATRIXSETCONSTANTEN) ( hypre_F90_Obj *matrix, hypre_F90_Int *nentries, hypre_F90_IntArray *entries, hypre_F90_Int *ierr ) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixSetConstantEntries( hypre_F90_PassObj (HYPRE_StructMatrix, matrix), hypre_F90_PassInt (nentries), hypre_F90_PassIntArray (entries) ); } /*-------------------------------------------------------------------------- * HYPRE_StructMatrixPrint *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixprint, HYPRE_STRUCTMATRIXPRINT) ( hypre_F90_Obj *matrix, hypre_F90_Int *all, hypre_F90_Int *ierr ) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixPrint( "HYPRE_StructMatrix.out", hypre_F90_PassObj (HYPRE_StructMatrix, matrix), hypre_F90_PassInt (all)); } /*-------------------------------------------------------------------------- * HYPRE_StructMatrixMatvec *--------------------------------------------------------------------------*/ void hypre_F90_IFACE(hypre_structmatrixmatvec, HYPRE_STRUCTMATRIXMATVEC) ( hypre_F90_Complex *alpha, hypre_F90_Obj *A, hypre_F90_Obj *x, hypre_F90_Complex *beta, hypre_F90_Obj *y, hypre_F90_Int *ierr ) { *ierr = (hypre_F90_Int) HYPRE_StructMatrixMatvec( hypre_F90_PassComplex (alpha), hypre_F90_PassObj (HYPRE_StructMatrix, A), hypre_F90_PassObj (HYPRE_StructVector, x), hypre_F90_PassComplex (beta), hypre_F90_PassObj (HYPRE_StructVector, y) ); } #ifdef __cplusplus } #endif
Iron ore mines leachate potential for oxyradical production. The ecotoxicological effects of mining effluents is coming under much greater scrutiny. It appears necessary to explore possible health effects in association with iron ore mining effluents. The present results clearly demonstrate that iron-ore leachate is not an inert media but has the potential to induce lipid peroxidation. Peroxidation was assessed by measuring oxygen consumption in the presence of a reducing agent such as ascorbate or NADPH and a chelator such as EDTA. Labrador iron ore is an insoluble complex crystalline material containing a mixture of metals (Fe, Al, Ti, Mn, Mg,ellipsis, ) in contrast to the iron sources used for normal lipid peroxidation studies. The metal of highest percentage is iron (59. 58%), a metal known to induce oxyradical production. Iron ore powder initiated ascorbic acid-dependent lipid peroxidation (nonenzymatic) in liposomes, lipids extracted from rat and salmon liver microsomes, and intact salmon liver microsomes. It also revealed an inhibitory effect of NADPH-dependent microsomes lipid peroxidation as well as on NADPH cytochrome c reductase activity. However, nonenzymatic peroxidation in rat liver microsomes was not significantly inhibited. Cytochrome P450 IA1- and IIB1-dependent enzymatic activities as well as P450 levels were not affected. The inhibition could be due to one of the other components of iron ore leachate (Mn, Al,ellipsis, ). These effects of iron-ore leachate indicate that a potential toxicity could be associated with its release into lakes. Further studies are necessary to explore in vivo effects on aquatic animals.
/// Starts a new beacon node `Client` in the given `environment`. /// /// Client behaviour is defined by the given `client_config`. pub async fn new( context: RuntimeContext<E>, mut client_config: ClientConfig, ) -> Result<Self, String> { let spec = context.eth2_config().spec.clone(); let client_genesis = client_config.genesis.clone(); let store_config = client_config.store.clone(); let log = context.log().clone(); let datadir = client_config.create_data_dir()?; let db_path = client_config.create_db_path()?; let freezer_db_path = client_config.create_freezer_db_path()?; let executor = context.executor.clone(); if let Some(legacy_dir) = client_config.get_existing_legacy_data_dir() { warn!( log, "Legacy datadir location"; "msg" => "this occurs when using relative paths for a datadir location", "location" => ?legacy_dir, ) } if !client_config.chain.enable_lock_timeouts { info!(log, "Disabling lock timeouts globally"); TimeoutRwLock::disable_timeouts() } let builder = ClientBuilder::new(context.eth_spec_instance.clone()) .runtime_context(context) .chain_spec(spec) .http_api_config(client_config.http_api.clone()) .disk_store( &datadir, &db_path, &freezer_db_path, store_config, log.clone(), )?; let builder = if let Some(slasher_config) = client_config.slasher.clone() { let slasher = Arc::new( Slasher::open(slasher_config, log.new(slog::o!("service" => "slasher"))) .map_err(|e| format!("Slasher open error: {:?}", e))?, ); builder.slasher(slasher) } else { builder }; let builder = if let Some(monitoring_config) = &mut client_config.monitoring_api { monitoring_config.db_path = Some(db_path); monitoring_config.freezer_db_path = Some(freezer_db_path); builder.monitoring_client(monitoring_config)? } else { builder }; let builder = builder .beacon_chain_builder(client_genesis, client_config.clone()) .await?; let builder = if client_config.sync_eth1_chain && !client_config.dummy_eth1_backend { info!( log, "Block production enabled"; "endpoints" => format!("{:?}", &client_config.eth1.endpoints), "method" => "json rpc via http" ); builder .caching_eth1_backend(client_config.eth1.clone()) .await? } else if client_config.dummy_eth1_backend { warn!( log, "Block production impaired"; "reason" => "dummy eth1 backend is enabled" ); builder.dummy_eth1_backend()? } else { info!( log, "Block production disabled"; "reason" => "no eth1 backend configured" ); builder.no_eth1_backend()? }; let builder = builder.system_time_slot_clock()?; // Inject the executor into the discv5 network config. let discv5_executor = Discv5Executor(executor); client_config.network.discv5_config.executor = Some(Box::new(discv5_executor)); builder .build_beacon_chain()? .network(&client_config.network) .await? .notifier()? .http_metrics_config(client_config.http_metrics.clone()) .build() .map(Self) }
Dallas Cowboys owner Jerry Jones, one of the few team owners to openly criticize the NFL’s ever-present national anthem protests, has a new target in his sights. According to reports, Jones is working to stall Commissioner Roger Goodell’s extension. According to reports, Jones led a secret conference call of a group of perhaps as many as 17 owners to discuss Goodell’s handling of the national anthem protests was at the top of the list of complaints against him, the New York Post reported. Indeed, over the weekend a meeting that was scheduled for this week between the players and the owners was abruptly canceled with no replacement date reported, ESPN’s Jim Trotter reported: Proposed meeting between NFL owners and Players Coalition is OFF for Monday, per source. Sides are hitting reset button for later meeting. — Jim Trotter (@JimTrotter_NFL) October 29, 2017 Reports have it that the owners were unsettled with the inclusion in the meeting of anthem protest creator Colin Kapernick. Sides had meeting tentatively scheduled for Monday in DC. Then yesterday Players Coalition requested smaller session in Philly w/ Kaep. … — Jim Trotter (@JimTrotter_NFL) October 29, 2017 With so much confusion, sides agreed to hit reset button, I’m told. Whether that’s good or bad depends on your perspective. — Jim Trotter (@JimTrotter_NFL) October 29, 2017 But Jones and the owners who oppose Goodell are not focusing solely on the anthem protest mess. They are also still reeling over Goodell’s mishandling of the Ray Rice domestic abuse case as well as the increasingly disastrous decision to allow the San Diego Chargers to move to Los Angeles. “You don’t get to have this many messes over the years like Roger has had and survive it,” an owner anonymously told ESPN. Reporters also point out that Goodell’s contract extension has not been finalized. “Maybe Arthur [Blank, the head of the compensation committee] and that committee think they’re on track,” the owner said. “But they have a lot more resistance than they counted on — and maybe they don’t know how the resistance is growing as we speak.” Follow Warner Todd Huston on Twitter @warnerthuston.
Monitoring of Hydrocarbon Gaseous Compounds formed During Bioleaching of Copper Sulphide Minerals with Mesophilic Microorganisms An experimental campaign was conducted for monitoring the formation of hydrocarbon gaseous compounds during bioleaching of copper sulphide ores with mesophilic microorganisms. Three different mineral samples were used: a pyrite concentrate, a chalcopyrite concentrate and a copper sulphide ore rock from El Teniente mine containing 1 % copper. Mineral samples were bioleached in 250 ml shake flasks containing 100 ml of basal medium inoculated either with a pure strain of Acidithiobacillus ferrooxidans or a natural bacteria consortium obtained from the acid leaching of El Teniente ore in columns. Each sealed system shake flask was fed with a flow of synthetic air and the exit stream was passed through a column containing an adsorbent material and next through a water trap as to avoid back air contamination from the environment. Compounds present in the adsorbent material after 90 days of bioleaching were analysed using a gas chromatography mass spectrometry technique with a procedure that detects 162 different hydrocarbon gaseous compounds (SGH). Results showed that the bacterial communities in copper sulphide bioleaching results in the formation of some hydrocarbon gaseous compounds, mainly various types of methyl benzene and branched alkanes. The formation of these organic compounds is likely to be related to the presence of heterothrofic microorganisms present in the natural populations.
def read(self, n=-1): self._unsupported("read")
Former Indiana State Trooper Brian Hamilton (Screenshot/ABC6) An Indiana state trooper who was fired for proselytizing people he pulled over during traffic stops spoke out an Saturday and said he accepts his firing because he is a “soldier for Jesus Christ.” Surrounded by praying supporters, Hamilton, who was fired on Thursday, said his responsibility as a Christian superseded those of his job, ABC6 reports. “I always said after I got saved, I work for the state, but ultimately I’m a soldier for Jesus Christ,” Hamilton said, as supporter said “Amen” in the background. “And God has used that job for the last three years… and that was to spread the word and tell people when they’re hurting, the truth.” He then said that while he believes the United States is a great country, “it’s on its way down.” “We just came out here to street preach, and hopefully we’ll see souls saved today,” he said. “And I’ll be honored to glorify the Lord Jesus Christ.” When the ABC6 reporter pointed out that his faith cost him his job, Hamilton responded, “It cost Christ everything,” and added “God’s law” is above “man’s law.” Hamilton was fired after 14 years on the job after a woman filed a complaint in January that led to a lawsuit by the ACLU. In September 2014, Hamilton was issued a written warning against preaching while on the job. He was ultimately fired for violating that warning. “While all of us – citizen and police officer – enjoy the right to freedom of religion and freedom of speech, there are appropriate and proper restrictions placed on agents of the State related to their actions while engaged in their official duties,” Indiana State Police Superintendent Doug Carter told the station in a written statement. “While I respect Mr. Hamilton’s religious views I am also charged to respect every citizen’s rights and the best way forward for the citizens of Indiana, and for Mr. Hamilton, was to end his employment as a state police officer.” Watch the report, from ABC6, here:
/** * A simple utility class that can be used by sinks to extract nested elements (e.g. nodes, types) * that should be persisted. * * @version 0.1 * @since 31.03.20 */ public final class Extractor { private static final Logger log = LoggerFactory.getLogger(Extractor.class); private Extractor() { throw new IllegalStateException("Utility classes cannot be instantiated"); } public static Set<InputEntity> extractElements(NestedEntity nestedEntity) throws ExtractorException { CopyOnWriteArrayList<InputEntity> resultingList = new CopyOnWriteArrayList<>(); if (nestedEntity instanceof HasNodes nestedHasNode) { resultingList.addAll((nestedHasNode).allNodes()); } if (nestedEntity instanceof Operable nestedOperable) { extractOperator(nestedOperable).ifPresent(resultingList::add); } if (nestedEntity instanceof HasType nestedHasType) { resultingList.add(extractType(nestedHasType)); } if (nestedEntity instanceof HasThermalBus nestedHasThermalBus) { resultingList.add((nestedHasThermalBus).getThermalBus()); } if (nestedEntity instanceof HasThermalStorage nestedHasThermalStorage) { resultingList.add((nestedHasThermalStorage).getThermalStorage()); } if (nestedEntity instanceof HasLine nestedHasLine) { resultingList.add((nestedHasLine).getLine()); } if (resultingList.contains(null)) { log.warn( "Entity of class '{}' contains null values in fields!", nestedEntity.getClass().getSimpleName()); } if (resultingList.isEmpty() && !(nestedEntity instanceof Operable)) { throw new ExtractorException( "Unable to extract entity of class '" + nestedEntity.getClass().getSimpleName() + "'. Does this class implements " + NestedEntity.class.getSimpleName() + " and one of its " + "sub-interfaces correctly?"); } resultingList.stream() .parallel() .forEach( element -> { if (element instanceof NestedEntity nestedElement) { try { resultingList.addAll(extractElements(nestedElement)); } catch (ExtractorException e) { log.error( "An error occurred during extraction of nested entity '{}':{}", element.getClass().getSimpleName(), e); } } }); return Set.copyOf(resultingList); } public static AssetTypeInput extractType(HasType entityWithType) { return entityWithType.getType(); } public static Optional<OperatorInput> extractOperator(Operable entityWithOperator) { return entityWithOperator.getOperator().getId().equalsIgnoreCase("NO_OPERATOR_ASSIGNED") ? Optional.empty() : Optional.of(entityWithOperator.getOperator()); } }
<filename>src/main/java/work/lince/commons/authentication/AuthenticationFilter.java package work.lince.commons.authentication; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Slf4j @Component public class AuthenticationFilter extends OncePerRequestFilter { @Value("${lince.userName:lince.user.name}") protected String userName; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String user = extractUserName(request); UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, "none"); SecurityContextHolder.getContext().setAuthentication(auth); filterChain.doFilter(request, response); } protected String extractUserName(HttpServletRequest request){ log.trace("extractUserName {} {}", userName, request.getParameter(userName)); String user = request.getParameter(userName); if (!StringUtils.isEmpty(user)){ log.trace("extractUserName from parameter"); return user; } user = request.getHeader(userName); if (!StringUtils.isEmpty(user)){ log.trace("extractUserName from header"); return user; } return "anonymous"; } }
WHILE the world worries about Greece, there’s an even bigger problem closer to home: China. A stock market crash there has seen $3.2 trillion wiped from the value of Chinese shares in just three weeks, triggering an emergency response from the government and warnings of “monstrous” public disorder. • LATEST: CHINESE INVESTORS FLEE FOR SAFETY And the effects for Australia could be serious, affecting our key commodity exports and sparking the beginning of a period of recession-like conditions. “State-owned newspapers have used their strongest language yet, telling people ‘not to lose their minds’ and ‘not to bury themselves in horror and anxiety’. [Our] positive measures will take time to produce results,” writes IG Markets. “If China does not find support today, the disorder could be monstrous.” In an extraordinary move, the People’s Bank of China has begun lending money to investors to buy shares in the flailing market. The Wall Street Journal reports this “liquidity assistance” will be provided to the regulator-owned China Securities Finance Corp, which will lend the money to brokerages, which will in turn lend to investors. The dramatic intervention marks the first time funds from the central bank have been directed anywhere other than the banks, signalling serious concern from authorities about the crisis. At the same time, Chinese authorities are putting a halt to any new stock listings. The market regulator announced on Friday it would limit initial public offerings — which disrupt the rest of the market — in an attempt to curb plunging share prices. While the exact amount of assistance hasn’t been revealed, the WSJ reports no upper limit has been set. All short-selling — the practice of betting that stocks will fall — has been banned, and Chinese media has rushed to reassure citizens. Yesterday, shares in big state companies soared in response to the but many others sank as jittery small investors tried to cut their losses, Associated Press reports. The market benchmark Shanghai Composite closed up 2.4 percent but still was down 27 percent from its June 12 peak. Experts fear it could turn into a full-blown crash introducing even more uncertainty into global markets as Europe teeters on the edge of a potential eurozone exit by Greece, after Sunday’s controversial referendum. WHAT DOES IT MEAN FOR AUSTRALIA? For Australia, the market crash in China is likely to impact earnings on key exports iron ore and coal, further slashing government revenue, while also putting downward pressure on the Australian dollar. Jordan Eliseo, chief economist with ABC Bullion, said it was important to remember that the amount of wealth Chinese citizens have tied up in the stock market is relatively minor compared with western investors. Stocks only make up about 8 per cent of household wealth in China, compared with around 20 per cent in developed nations. “The market crash there is generating headlines, but it’s not going to have the same impact as a comparable crash would in a developed market,” he said. “What it means for Australia, though, is it’s very clear there are some serious imbalances in the Chinese economy, and the rate of growth they’ve enjoyed in the past is over. There’s no question our export earnings are going to take another hit.” Mr Eliseo predicts Australia is likely to experience “recession-like” conditions such as negative wage growth for many years to come. “I believe that’s going to be the new norm,” he said. WHAT ARE THEY DOING ABOUT IT? On Saturday, China’s 21 largest brokerage firms announced that they would invest more than $25.35 billion in the country’s stock markets to curb the declines. The brokers will spend at least 120 billion yuan ($25.75 billion) on so-called “blue chip” exchange traded funds, the Securities Association of China said in a statement after an emergency meeting in Beijing. On Friday the Shanghai Composite Index closed down 5.77 per cent to end at 3,686.92 points. Since peaking on June 12 Shanghai has dropped nearly 29 per cent, which Bloomberg News said was its biggest three-week fall since November 1992. The Shanghai market had swelled by 150 per cent in the last 12 months and experts had expected a sharp correction, though the rate at which it has occurred is unnerving many. Middle-class Chinese investors, encouraged by the government, have been pumping money into the stock market. The WSJ quoted 51-year-old Li Ping, who sold her 7 million yuan ($1.5 million) Beijing apartment to plough 4 million yuan into stocks. Ms Li said she thought the market would stabilise and rise again. “The fund that I have invested in is very mature and professional,” she said. CRACKDOWN AS PANIC TRIGGERS ‘SUICIDE’ RUMOURS Underscoring growing jitters amid the three-week sell-off, police in Beijing detained a man on Sunday for allegedly spreading a rumour online that a person jumped to their death in the city’s financial district due to China’s precarious stock markets. The 29-year-old man detained was identified by the surname Tian, and is a manager at a technology and science company in Beijing, police said in a post on their official microblog. Police said Tian’s alleged posting of the rumour took place Friday and called on internet users to obey laws and regulations, not to believe and spread rumours, and to cooperate with police. The state-run Xinhua news agency reported that Tian allegedly posted the rumours with video clips and screenshots Friday afternoon. The post, which is said to have gone viral, “provoked emotional responses among stock investors who suffered losses over the past weeks”, Xinhua said. Xinhua added that a police investigation showed that the video in question had been shot on Friday morning in the eastern Chinese province of Jiangsu where a man had jumped to his death. Local police there were investigating that case, Xinhua said. The original post was unavailable Sunday on China’s tightly controlled social media, where authorities are quick to delete controversial material.
/** * Finds a method given its name and argument types in this class, superclass and all superinterfaces. */ private Method findMethod(Class<?> clazz, String methodName, Class<?>[] argTypes) { Method method = null; try { method = clazz.getDeclaredMethod(methodName, argTypes); } catch (NoSuchMethodException e) { if (clazz.getSuperclass() != null) { method = findMethod(clazz.getSuperclass(), methodName, argTypes); } if (method == null) { for (Class<?> i : clazz.getInterfaces()) { method = findMethod(i, methodName, argTypes); if (method != null) { break; } } } } return method; }
<filename>sdk/go/azure/videoanalyzer/v20210501preview/videoAnalyzer.go // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package v20210501preview import ( "context" "reflect" "github.com/pkg/errors" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" ) type VideoAnalyzer struct { pulumi.CustomResourceState Encryption AccountEncryptionResponseOutput `pulumi:"encryption"` Endpoints EndpointResponseArrayOutput `pulumi:"endpoints"` Identity VideoAnalyzerIdentityResponsePtrOutput `pulumi:"identity"` Location pulumi.StringOutput `pulumi:"location"` Name pulumi.StringOutput `pulumi:"name"` StorageAccounts StorageAccountResponseArrayOutput `pulumi:"storageAccounts"` SystemData SystemDataResponseOutput `pulumi:"systemData"` Tags pulumi.StringMapOutput `pulumi:"tags"` Type pulumi.StringOutput `pulumi:"type"` } // NewVideoAnalyzer registers a new resource with the given unique name, arguments, and options. func NewVideoAnalyzer(ctx *pulumi.Context, name string, args *VideoAnalyzerArgs, opts ...pulumi.ResourceOption) (*VideoAnalyzer, error) { if args == nil { return nil, errors.New("missing one or more required arguments") } if args.Encryption == nil { return nil, errors.New("invalid value for required argument 'Encryption'") } if args.ResourceGroupName == nil { return nil, errors.New("invalid value for required argument 'ResourceGroupName'") } if args.StorageAccounts == nil { return nil, errors.New("invalid value for required argument 'StorageAccounts'") } aliases := pulumi.Aliases([]pulumi.Alias{ { Type: pulumi.String("azure-nextgen:videoanalyzer/v20210501preview:VideoAnalyzer"), }, { Type: pulumi.String("azure-native:videoanalyzer:VideoAnalyzer"), }, { Type: pulumi.String("azure-nextgen:videoanalyzer:VideoAnalyzer"), }, }) opts = append(opts, aliases) var resource VideoAnalyzer err := ctx.RegisterResource("azure-native:videoanalyzer/v20210501preview:VideoAnalyzer", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // GetVideoAnalyzer gets an existing VideoAnalyzer resource's state with the given name, ID, and optional // state properties that are used to uniquely qualify the lookup (nil if not required). func GetVideoAnalyzer(ctx *pulumi.Context, name string, id pulumi.IDInput, state *VideoAnalyzerState, opts ...pulumi.ResourceOption) (*VideoAnalyzer, error) { var resource VideoAnalyzer err := ctx.ReadResource("azure-native:videoanalyzer/v20210501preview:VideoAnalyzer", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // Input properties used for looking up and filtering VideoAnalyzer resources. type videoAnalyzerState struct { } type VideoAnalyzerState struct { } func (VideoAnalyzerState) ElementType() reflect.Type { return reflect.TypeOf((*videoAnalyzerState)(nil)).Elem() } type videoAnalyzerArgs struct { AccountName *string `pulumi:"accountName"` Encryption AccountEncryption `pulumi:"encryption"` Identity *VideoAnalyzerIdentity `pulumi:"identity"` Location *string `pulumi:"location"` ResourceGroupName string `pulumi:"resourceGroupName"` StorageAccounts []StorageAccount `pulumi:"storageAccounts"` Tags map[string]string `pulumi:"tags"` } // The set of arguments for constructing a VideoAnalyzer resource. type VideoAnalyzerArgs struct { AccountName pulumi.StringPtrInput Encryption AccountEncryptionInput Identity VideoAnalyzerIdentityPtrInput Location pulumi.StringPtrInput ResourceGroupName pulumi.StringInput StorageAccounts StorageAccountArrayInput Tags pulumi.StringMapInput } func (VideoAnalyzerArgs) ElementType() reflect.Type { return reflect.TypeOf((*videoAnalyzerArgs)(nil)).Elem() } type VideoAnalyzerInput interface { pulumi.Input ToVideoAnalyzerOutput() VideoAnalyzerOutput ToVideoAnalyzerOutputWithContext(ctx context.Context) VideoAnalyzerOutput } func (*VideoAnalyzer) ElementType() reflect.Type { return reflect.TypeOf((*VideoAnalyzer)(nil)) } func (i *VideoAnalyzer) ToVideoAnalyzerOutput() VideoAnalyzerOutput { return i.ToVideoAnalyzerOutputWithContext(context.Background()) } func (i *VideoAnalyzer) ToVideoAnalyzerOutputWithContext(ctx context.Context) VideoAnalyzerOutput { return pulumi.ToOutputWithContext(ctx, i).(VideoAnalyzerOutput) } type VideoAnalyzerOutput struct{ *pulumi.OutputState } func (VideoAnalyzerOutput) ElementType() reflect.Type { return reflect.TypeOf((*VideoAnalyzer)(nil)) } func (o VideoAnalyzerOutput) ToVideoAnalyzerOutput() VideoAnalyzerOutput { return o } func (o VideoAnalyzerOutput) ToVideoAnalyzerOutputWithContext(ctx context.Context) VideoAnalyzerOutput { return o } func init() { pulumi.RegisterOutputType(VideoAnalyzerOutput{}) }
<gh_stars>1-10 #include "mcp_can.h" #include <IFCT.h> #include <kinetis_flexcan.h> #undef rtr CAN_message_t storage_mcp_sim; /********************************************************************************************************* ** Function name: MCP_CAN ** Descriptions: Constructor *********************************************************************************************************/ MCP_CAN::MCP_CAN(byte _CS) : nReservedTx(0) { } /********************************************************************************************************* ** Function name: set CS ** Descriptions: init CS pin and set UNSELECTED *********************************************************************************************************/ void MCP_CAN::init_CS(byte _CS) { } /********************************************************************************************************* ** Function name: begin ** Descriptions: init can and set speed *********************************************************************************************************/ byte MCP_CAN::begin(uint32_t speedset, const byte clockset) { Can0.setBaudRate(speedset); return CAN_OK; } /********************************************************************************************************* ** Function name: sendMsg ** Descriptions: send message *********************************************************************************************************/ byte MCP_CAN::sendMsg(unsigned long id, byte extended, byte rtrBit, byte len, const byte *buf, bool wait_sent) { #define rtr flags.remote CAN_message_t frame; ( rtrBit ) ? frame.rtr = 1 : frame.rtr = 0; ( extended ) ? frame.ext = 1 : frame.ext = 0; frame.id = id; frame.len = len; memmove(&frame.buf[0],&buf[0],8); Can0.write(frame); return CAN_OK; #undef rtr } /********************************************************************************************************* ** Function name: sendMsgBuf ** Descriptions: send buf *********************************************************************************************************/ byte MCP_CAN::sendMsgBuf(unsigned long id, byte extended, byte rtrBit, byte len, const byte *buf, bool wait_sent) { return sendMsg(id,extended,rtrBit,len,buf,wait_sent); } /********************************************************************************************************* ** Function name: sendMsgBuf ** Descriptions: send buf *********************************************************************************************************/ byte MCP_CAN::sendMsgBuf(unsigned long id, byte extended, byte len, const byte *buf, bool wait_sent) { return sendMsg(id,extended,0,len,buf,wait_sent); } /********************************************************************************************************* ** Function name: checkReceive ** Descriptions: check if got something *********************************************************************************************************/ byte MCP_CAN::checkReceive(void) { if ( Can0.read(storage_mcp_sim) ) { if ( !filter_masks[0] || !filter_masks[1] ) return CAN_MSGAVAIL; /* not all masks set */ for ( uint8_t i = 0; i < 6; i++ ) { if ( !filter_filters[i] ) return CAN_MSGAVAIL; /* not all filters set */ if ( (( filter_masks[0] & storage_mcp_sim.id ) == filter_filters[i]) || (( filter_masks[1] & storage_mcp_sim.id ) == filter_filters[i]) ) { if ( filter_ext_bit[i] == storage_mcp_sim.ext ) return CAN_MSGAVAIL; return CAN_NOMSG; } } } return CAN_NOMSG; } /********************************************************************************************************* ** Function name: readMsgBuf ** Descriptions: read message buf *********************************************************************************************************/ byte MCP_CAN::readMsgBuf(byte *len, byte buf[]) { return readMsgBufID(readRxTxStatus(),&can_id,&ext_flg,&rtr,len,buf); } /********************************************************************************************************* ** Function name: readMsgBufID ** Descriptions: read message buf and can bus source ID *********************************************************************************************************/ byte MCP_CAN::readMsgBufID(unsigned long *ID, byte *len, byte buf[]) { return readMsgBufID(readRxTxStatus(),ID,&ext_flg,&rtr,len,buf); } /********************************************************************************************************* ** Function name: readMsgBufID ** Descriptions: Read message buf and can bus source ID according to status. ** Status has to be read with readRxTxStatus. *********************************************************************************************************/ byte MCP_CAN::readMsgBufID(byte status, volatile unsigned long *id, volatile byte *extended, volatile byte *rtrBit, volatile byte *len, volatile byte *buf) { mcp2515_read_canMsg( MCP_READ_RX0, id, extended, rtrBit, len, buf); return 0; } /********************************************************************************************************* ** Function name: mcp2515_read_canMsg ** Descriptions: read message *********************************************************************************************************/ #undef rtr #undef ext void MCP_CAN::mcp2515_read_canMsg( const byte buffer_load_addr, volatile unsigned long *id, volatile byte *ext, volatile byte *rtrBit, volatile byte *len, volatile byte *buf) /* read can msg */ { *id = storage_mcp_sim.id; *ext = storage_mcp_sim.flags.extended; *len = storage_mcp_sim.len; *rtrBit = storage_mcp_sim.flags.remote; for ( uint8_t i = 0; i < 8; i++ ) buf[i] = storage_mcp_sim.buf[i]; } #define rtr flags.remote #define ext flags.extended /********************************************************************************************************* ** Function name: readRxTxStatus ** Descriptions: Read RX and TX interrupt bits. Function uses status reading, but translates. ** result to MCP_CANINTF. With this you can check status e.g. on interrupt sr ** with one single call to save SPI calls. Then use checkClearRxStatus and ** checkClearTxStatus for testing. *********************************************************************************************************/ byte MCP_CAN::readRxTxStatus(void) { return 0; } /********************************************************************************************************* ** Function name: checkClearRxStatus ** Descriptions: Return first found rx CANINTF status and clears it from parameter. ** Note that this does not affect to chip CANINTF at all. You can use this ** with one single readRxTxStatus call. *********************************************************************************************************/ byte MCP_CAN::checkClearRxStatus(byte *status) { return 0; } /********************************************************************************************************* ** Function name: checkClearTxStatus ** Descriptions: Return specified buffer of first found tx CANINTF status and clears it from parameter. ** Note that this does not affect to chip CANINTF at all. You can use this ** with one single readRxTxStatus call. *********************************************************************************************************/ byte MCP_CAN::checkClearTxStatus(byte *status, byte iTxBuf) { return 0; } /********************************************************************************************************* ** Function name: clearBufferTransmitIfFlags ** Descriptions: Clear transmit interrupt flags for specific buffer or for all unreserved buffers. ** If interrupt will be used, it is important to clear all flags, when there is no ** more data to be sent. Otherwise IRQ will newer change state. *********************************************************************************************************/ void MCP_CAN::clearBufferTransmitIfFlags(byte flags) { } /********************************************************************************************************* ** Function name: checkError ** Descriptions: if something error *********************************************************************************************************/ byte MCP_CAN::checkError(void) { return 0; } /********************************************************************************************************* ** Function name: getCanId ** Descriptions: when receive something, you can get the can id!! *********************************************************************************************************/ unsigned long MCP_CAN::getCanId(void) { return can_id; } /********************************************************************************************************* ** Function name: isRemoteRequest ** Descriptions: when receive something, you can check if it was a request *********************************************************************************************************/ byte MCP_CAN::isRemoteRequest(void) { #undef rtr return rtr; #define rtr flags.remote } /********************************************************************************************************* ** Function name: isExtendedFrame ** Descriptions: did we just receive standard 11bit frame or extended 29bit? 0 = std, 1 = ext *********************************************************************************************************/ byte MCP_CAN::isExtendedFrame(void) { return ext_flg; } /********************************************************************************************************* ** Function name: sendMsgBuf ** Descriptions: Send message by using buffer read as free from CANINTF status ** Status has to be read with readRxTxStatus and filtered with checkClearTxStatus *********************************************************************************************************/ byte MCP_CAN::sendMsgBuf(byte status, unsigned long id, byte extended, byte rtrBit, byte len, volatile const byte *buf) { CAN_message_t frame; ( rtrBit ) ? frame.rtr = 1 : frame.rtr = 0; ( extended ) ? frame.ext = 1 : frame.ext = 0; frame.id = id; frame.len = len; for ( uint8_t i = 0; i < 8; i++ ) frame.buf[i] = buf[i]; Can0.write(frame); return CAN_OK; } /********************************************************************************************************* ** Function name: trySendMsgBuf ** Descriptions: Try to send message. There is no delays for waiting free buffer. *********************************************************************************************************/ byte MCP_CAN::trySendMsgBuf(unsigned long id, byte extended, byte rtrBit, byte len, const byte *buf, byte iTxBuf) { CAN_message_t frame; ( rtrBit ) ? frame.rtr = 1 : frame.rtr = 0; ( extended ) ? frame.ext = 1 : frame.ext = 0; frame.id = id; frame.len = len; for ( uint8_t i = 0; i < 8; i++ ) frame.buf[i] = buf[i]; Can0.write(frame); return CAN_OK; } /********************************************************************************************************* ** Function name: mcp2515_start_transmit ** Descriptions: Start message transmit on mcp2515 *********************************************************************************************************/ void MCP_CAN::mcp2515_start_transmit(const byte mcp_addr) // start transmit { } /********************************************************************************************************* ** Function name: mcp2515_isTXBufFree ** Descriptions: Test is tx buffer free for transmitting *********************************************************************************************************/ byte MCP_CAN::mcp2515_isTXBufFree(byte *txbuf_n, byte iBuf) /* get Next free txbuf */ { return 0; } /********************************************************************************************************* ** Function name: mcp2515_getNextFreeTXBuf ** Descriptions: finds next free tx buffer for sending. Return MCP_ALLTXBUSY, if there is none. *********************************************************************************************************/ byte MCP_CAN::mcp2515_getNextFreeTXBuf(byte *txbuf_n) // get Next free txbuf { return 0; } /********************************************************************************************************* ** Function name: enableTxInterrupt ** Descriptions: enable interrupt for all tx buffers *********************************************************************************************************/ void MCP_CAN::enableTxInterrupt(bool enable) { } /********************************************************************************************************* ** Function name: init_Mask ** Descriptions: init canid Masks *********************************************************************************************************/ byte MCP_CAN::init_Mask(byte num, byte extended, unsigned long ulData) { filter_masks[constrain(num,0,1)] = ulData; mask_ext_bit[constrain(num,0,1)] = extended; return 1; } /********************************************************************************************************* ** Function name: init_Filt ** Descriptions: init canid filters *********************************************************************************************************/ byte MCP_CAN::init_Filt(byte num, byte extended, unsigned long ulData) { filter_filters[constrain(num,0,5)] = ulData; filter_ext_bit[constrain(num,0,5)] = extended; return 1; } /********************************************************************************************************* ** Function name: mcp2515_read_id ** Descriptions: read can id *********************************************************************************************************/ void MCP_CAN::mcp2515_read_id(const byte mcp_addr, byte* extended, unsigned long* id) { } /********************************************************************************************************* ** Function name: mcp2515_write_canMsg ** Descriptions: write msg ** Note! There is no check for right address! *********************************************************************************************************/ void MCP_CAN::mcp2515_write_canMsg(const byte buffer_sidh_addr, unsigned long id, byte extended, byte rtrBit, byte len, volatile const byte *buf) { } /********************************************************************************************************* ** Function name: mcp2515_write_id ** Descriptions: write can id *********************************************************************************************************/ void MCP_CAN::mcp2515_write_id(const byte mcp_addr, const byte extended, const unsigned long id) { } /********************************************************************************************************* ** Function name: mcp2515_id_to_buf ** Descriptions: configure tbufdata[4] from id and ext *********************************************************************************************************/ void mcp2515_id_to_buf(const byte extended, const unsigned long id, byte *tbufdata) { } /********************************************************************************************************* ** Function name: mcp2515_init ** Descriptions: init the device *********************************************************************************************************/ byte MCP_CAN::mcp2515_init(const byte canSpeed, const byte clock) { return 0; } /********************************************************************************************************* ** Function name: txCtrlReg ** Descriptions: return tx ctrl reg according to tx buffer index. ** According to my tests this is faster and saves memory compared using vector *********************************************************************************************************/ byte txCtrlReg(byte i) { return 0; } /********************************************************************************************************* ** Function name: statusToBuffer ** Descriptions: converts CANINTF status to tx buffer index *********************************************************************************************************/ byte statusToTxBuffer(byte status) { return 0; } /********************************************************************************************************* ** Function name: statusToBuffer ** Descriptions: converts CANINTF status to tx buffer sidh *********************************************************************************************************/ byte statusToTxSidh(byte status) { return 0; } /********************************************************************************************************* ** Function name: txSidhToTxLoad ** Descriptions: return tx load command according to tx buffer sidh register *********************************************************************************************************/ byte txSidhToRTS(byte sidh) { return 0; } /********************************************************************************************************* ** Function name: txSidhToTxLoad ** Descriptions: return tx load command according to tx buffer sidh register *********************************************************************************************************/ byte txSidhToTxLoad(byte sidh) { return 0; } /********************************************************************************************************* ** Function name: txIfFlag ** Descriptions: return tx interrupt flag *********************************************************************************************************/ byte txIfFlag(byte i) { return 0; } /********************************************************************************************************* ** Function name: txStatusPendingFlag ** Descriptions: return buffer tx pending flag on status *********************************************************************************************************/ byte txStatusPendingFlag(byte i) { return 0; } /********************************************************************************************************* ** Function name: mcp2515_reset ** Descriptions: reset the device *********************************************************************************************************/ void MCP_CAN::mcp2515_reset(void) { } /********************************************************************************************************* ** Function name: mcp2515_readRegister ** Descriptions: read register *********************************************************************************************************/ byte MCP_CAN::mcp2515_readRegister(const byte address) { return 0; } /********************************************************************************************************* ** Function name: mcp2515_readRegisterS ** Descriptions: read registerS *********************************************************************************************************/ void MCP_CAN::mcp2515_readRegisterS(const byte address, byte values[], const byte n) { } /********************************************************************************************************* ** Function name: mcp2515_setRegister ** Descriptions: set register *********************************************************************************************************/ void MCP_CAN::mcp2515_setRegister(const byte address, const byte value) { } /********************************************************************************************************* ** Function name: mcp2515_setRegisterS ** Descriptions: set registerS *********************************************************************************************************/ void MCP_CAN::mcp2515_setRegisterS(const byte address, const byte values[], const byte n) { } /********************************************************************************************************* ** Function name: mcp2515_modifyRegister ** Descriptions: set bit of one register *********************************************************************************************************/ void MCP_CAN::mcp2515_modifyRegister(const byte address, const byte mask, const byte data) { } /********************************************************************************************************* ** Function name: mcp2515_readStatus ** Descriptions: read mcp2515's Status *********************************************************************************************************/ byte MCP_CAN::mcp2515_readStatus(void) { return 0; } /********************************************************************************************************* ** Function name: mcp2515_setCANCTRL_Mode ** Descriptions: set control mode *********************************************************************************************************/ byte MCP_CAN::mcp2515_setCANCTRL_Mode(const byte newmode) { return 0; } /********************************************************************************************************* ** Function name: mcp2515_configRate ** Descriptions: set baudrate *********************************************************************************************************/ byte MCP_CAN::mcp2515_configRate(const byte canSpeed, const byte clock) { Can0.setBaudRate(canSpeed); return 0; } /********************************************************************************************************* ** Function name: mcp2515_initCANBuffers ** Descriptions: init canbuffers *********************************************************************************************************/ void MCP_CAN::mcp2515_initCANBuffers(void) { } /********************************************************************************************************* END FILE *********************************************************************************************************/
def max_thread_dimensions(self): return json.loads(self._GetDeviceAttr(self.device_type, self.device_id, 8))
const flash = ({ message, status }) => { return ( <> <div className={`alert alert-${status} alert-dismissible fade show`} role="alert"> <strong>{message}</strong> </div> </> ); }; export default flash;
// UpdateStartingToRunning changes the host status from provisioning to // running, as well as logging that the host has finished provisioning. func (h *Host) UpdateStartingToRunning() error { if h.Status != evergreen.HostStarting { return nil } if err := UpdateOne( bson.M{ IdKey: h.Id, StatusKey: evergreen.HostStarting, ProvisionedKey: true, }, bson.M{"$set": bson.M{StatusKey: evergreen.HostRunning}}, ); err != nil { return errors.Wrap(err, "problem changing host status from starting to running") } h.Status = evergreen.HostRunning event.LogHostProvisioned(h.Id) return nil }
// GetSCMProvider gets the SCM provider by the type. func GetSCMProvider(scm *api.SCMConfig) (SCMProvider, error) { if scm == nil { err := fmt.Errorf("SCM config is nil") log.Error(err) return nil, err } scmType := scm.Type pFunc, ok := scmProviders[scmType] if !ok { return nil, fmt.Errorf("unsupported SCM type %s", scmType) } return pFunc(scm) }
/* * sa.c * System accounting of command execution * (in conjuction with acct system call.) */ #include <stdio.h> #include <ctype.h> #include <pwd.h> #include <acct.h> #include <sys/times.h> #include <sys/const.h> #include <dirent.h> #define MIN 60 /* Seconds in a minute */ #define MINHZ (MIN*HZ) /* HZ in a minute */ #define CPUTIME 0 /* Sort by CPU time */ #define PERCALL 1 /* Sort by CPU time per call */ #define CALLS 2 /* Sort by numbers of calls */ #define NUSER 100 /* Maximum number of users */ #define NCOMM 500 /* Maximum number of commands */ #define NSORT NUSER #define NCNAME (sizeof(ac.ac_comm)) /* Size of a command name) */ #define DIRSIZ 14 struct acct ac; /* * structure of /usr/adm/usracct * for per-user type of `sa' information. */ struct svu { unsigned svu_count; /* Number of processes measured */ short svu_uid; /* User number */ time_t svu_stime; /* Total system time (HZ) */ time_t svu_utime; /* Total user time */ time_t svu_etime; /* Total elapsed time (sec.)*/ } svu[NUSER]; /* * For per command information as * is stored in /usr/adm/savacct. */ struct svc { unsigned svc_count; /* Number of calls */ char svc_comm[NCNAME]; /* Command name */ time_t svc_stime; time_t svc_utime; time_t svc_etime; } svc[NCOMM]; struct svc *junkp, *otherp; /* * For the final sort. This is * the combined information of * the two structures above. * I.e. either one or the other. */ struct sort { unsigned s_count; /* Number of calls */ char s_comm[NCNAME]; /* Command name */ short s_uid; /* User number */ time_t s_key; /* Sort key */ time_t s_stime; /* System time */ time_t s_utime; /* User time */ time_t s_etime; /* Elapsed time */ } sort[NSORT]; char *acctf = "/usr/adm/acct"; /* Raw accounting file */ char *sacctf = "/usr/adm/savacct"; /* Summary file */ char *uacctf = "/usr/adm/usracct"; /* Per-user summary */ char junk[NCNAME] = "**junk**"; char other[NCNAME] = "***other"; int aflag; /* Move unlikely commands to "**other" */ int cflag; /* Give percentage of total time */ int jflag; /* Give seconds instead of minutes/call */ int lflag; /* Separate system & user times */ int mflag; /* Number of processes and CPU min. per user */ int rflag; /* Reverse sort order */ int sflag; /* Merge accounting file when done */ int tflag; /* Print ratio of real to CPU time */ int uflag; /* Print user-id and command name */ int vflag; /* Prompt if used fewer than `n' times */ int sortflag = CPUTIME; /* Sort mode */ long ctol(); time_t units(); struct svc *make(); struct svc *move(); char *uname(); int compar(); main(argc, argv) char *argv[]; { register char *ap; while (argc>1 && *argv[1]=='-') { for (ap = &argv[1][1]; *ap != '\0'; ap++) switch (*ap) { case 'a': aflag = 1; break; case 'b': sortflag = PERCALL; break; case 'c': cflag = 1; break; case 'j': jflag = 1; break; case 'l': lflag = 1; break; case 'm': mflag = 1; break; case 'n': sortflag = CALLS; break; case 'r': rflag = 1; break; case 's': sflag = 1; break; case 't': tflag = 1; break; case 'u': uflag = 1; break; case 'v': if (ap[1]>='0' && ap[1]<='9') vflag = *++ap - '0'; break; default: usage(); } argc--; argv++; } if (argc == 2) acctf = argv[1]; else if (argc > 2) usage(); if (!uflag) rsummary(); rraw(acctf); if (sflag && !uflag) samerge(); if (!uflag) saprint(); exit(0); } /* * Read the summary file of old accounting information * from both user and command saved accounting files. */ rsummary() { register FILE *fp; if ((fp = fopen(sacctf, "r")) != NULL) { register struct svc *svcp; for (svcp = svc; svcp < &svc[NCOMM]; svcp++) if (fread(svcp, sizeof *svcp, 1, fp) != 1) break; if (svcp >= &svc[NCOMM]) fprintf(stderr, "%s is too large\n", sacctf); fclose(fp); } if ((fp = fopen(uacctf, "r")) != NULL) { register struct svu *svup; for (svup = svu; svup < &svu[NUSER]; svup++) if (fread(svup, sizeof *svup, 1, fp) != 1) break; if (svup >= &svu[NUSER]) fprintf(stderr, "%s is too large\n", uacctf); fclose(fp); } } /* * Read the raw accounting. */ rraw(af) char *af; { FILE *afp; register struct svc *svcp; if ((afp = fopen(af, "r")) == NULL) { fprintf(stderr, "Cannot open raw accounting file `%s'\n", af); exit(1); } while (fread(&ac, sizeof ac, 1, afp) == 1) { if (uflag) printf("%-*s %.*s\n", DIRSIZ, uname(ac.ac_uid), NCNAME, ac.ac_comm); else { senter(&ac); uenter(&ac); } } fclose(afp); /* * Create (if not there) junk and other classes. */ if (aflag) { otherp = make(other); for (svcp = svc; svcp<&svc[NCOMM] && svcp->svc_count; svcp++) { if (svcp == otherp) continue; if (svcp->svc_count==1 || unprintable(svcp->svc_comm)) otherp = move(svcp--, otherp); } } if (vflag) { junkp = make(junk); for (svcp = svc; svcp<&svc[NCOMM] && svcp->svc_count; svcp++) { if (svcp == junkp) continue; if (svcp->svc_count<=vflag && yes(svcp->svc_comm)) junkp = move(svcp--, junkp); } } } /* * Merge system accounting info back * into the two merged files and * truncate the raw accounting file. * Accounting probably should be * turned off when `sa' is called * if this is to be done. */ samerge() { register FILE *fp; if ((fp = fopen(sacctf, "w")) != NULL) { register struct svc *svcp; for (svcp = svc; svcp<&svc[NCOMM] && svcp->svc_count; svcp++) if (fwrite(svcp, sizeof *svcp, 1, fp) != 1) saerr("%s: write error", sacctf); fclose(fp); } else saerr("cannot rewrite %s", sacctf); if ((fp = fopen(uacctf, "w")) != NULL) { register struct svu *svup; for (svup = svu; svup<&svu[NUSER] && svup->svu_count; svup++) if (fwrite(svup, sizeof *svup, 1, fp) != 1) saerr("%s: write error", uacctf); fclose(fp); } else saerr("cannot rewrite %s", uacctf); if ((fp = fopen(acctf, "w")) == NULL) saerr("cannot truncate %s", acctf); fclose(fp); } /* * Output the accounting * information according to * sorting and printing options. */ saprint() { register struct sort *sp; time_t tottime; if (mflag) userenter(); else commenter(); for (sp = sort; sp<&sort[NSORT] && sp->s_count; sp++) if (sortflag == CPUTIME) sp->s_key = sp->s_stime+sp->s_utime; else if (sortflag == PERCALL) sp->s_key = (sp->s_stime+sp->s_utime)/sp->s_count; else /* # calls */ sp->s_key = sp->s_count; qsort(sort, sp-sort, sizeof *sp, compar); if (mflag) printf("%-*s #PROC", DIRSIZ, ""); else printf("%-*s #CALL", NCNAME, ""); if (lflag) printf(" USER SYS"); else printf(" CPU"); printf(" REAL"); if (cflag) printf(" CPU %% "); if (tflag) printf(" CPU/REAL %%"); putchar('\n'); if (cflag) { tottime = 0; for (sp = sort; sp<&sort[NSORT] && sp->s_count; sp++) { tottime += sp->s_stime; tottime += sp->s_utime; } } for (sp = sort; sp<&sort[NSORT] && sp->s_count; sp++) { if (mflag) printf("%-*s", DIRSIZ, uname(sp->s_uid)); else printf("%-*s", NCNAME, sp->s_comm); printf(" %5d", sp->s_count); if (lflag) printf(" %5ld %5ld", units(sp->s_utime, sp), units(sp->s_stime, sp)); else printf(" %5ld", units(sp->s_utime+sp->s_stime, sp)); printf(" %5ld", units(sp->s_etime*HZ, sp)); if (cflag) percent(sp->s_utime+sp->s_stime, tottime); if (tflag) { printf(" "); percent(sp->s_utime+sp->s_stime, sp->s_etime*HZ); } putchar('\n'); } } /* * Enter user information for the sort. */ userenter() { register struct sort *sp; register struct svu *svup; sp = sort; svup = svu; while (svup < &svu[NCOMM] && svup->svu_count) { sp->s_count = svup->svu_count; sp->s_uid = svup->svu_uid; sp->s_stime = svup->svu_stime; sp->s_utime = svup->svu_utime; sp->s_etime = svup->svu_etime; sp++; svup++; } /* free(svc); */ } /* * Enter the commands into the list for * sorting. */ commenter() { register struct sort *sp; register struct svc *svcp; sp = sort; svcp = svc; while (svcp < &svc[NCOMM] && svcp->svc_count) { sp->s_count = svcp->svc_count; strncpy(sp->s_comm, svcp->svc_comm, NCNAME); sp->s_stime = svcp->svc_stime; sp->s_utime = svcp->svc_utime; sp->s_etime = svcp->svc_etime; sp++; svcp++; } /* free(svu); */ } /* * Enter this accounting entry into * the command table for savacct. */ senter(ap) register struct acct *ap; { register struct svc *svcp; for (svcp = svc; svcp<&svc[NCOMM] && svcp->svc_count; svcp++) if (strncmp(svcp->svc_comm, ap->ac_comm, NCNAME) == 0) break; if (svcp >= &svc[NCOMM]) saerr("Command table overflow"); if (svcp->svc_count++ == 0) strncpy(svcp->svc_comm, ap->ac_comm, NCNAME); svcp->svc_stime += ctol(ap->ac_stime); svcp->svc_utime += ctol(ap->ac_utime); svcp->svc_etime += ctol(ap->ac_etime); } /* * Enter this accounting entry into * the user table for usracct. */ uenter(ap) register struct acct *ap; { register struct svu *svup; for (svup = svu; svup<&svu[NUSER] && svup->svu_count; svup++) if (svup->svu_uid == ap->ac_uid) break; if (svup >= &svu[NUSER]) saerr("User table overflow"); svup->svu_count++; svup->svu_uid = ap->ac_uid; svup->svu_stime += ctol(ap->ac_stime); svup->svu_utime += ctol(ap->ac_utime); svup->svu_etime += ctol(ap->ac_etime); } /* * Make a new zero entry with * the indicated name. */ struct svc * make(name) register char *name; { register struct svc *svcp; for (svcp = svc; svcp<&svc[NCOMM] && svcp->svc_count; svcp++) if (strncmp(name, svcp->svc_comm, NCNAME) == 0) return (svcp); if (svcp >= &svc[NCOMM]) saerr("out of room for %s", name); strncpy(svcp->svc_comm, name, NCNAME); return (svcp); } /* * Move an entry to one of the deprecated * places. */ struct svc * move(svcp, depp) register struct svc *svcp; struct svc *depp; { depp->svc_count += svcp->svc_count; depp->svc_stime += svcp->svc_stime; depp->svc_utime += svcp->svc_utime; depp->svc_etime += svcp->svc_etime; while (svcp->svc_count) { if (svcp == depp) depp--; bcopy(svcp+1, svcp, sizeof *svcp); svcp++; } (svcp-1)->svc_count = 0; return (depp); } /* * Return the user-name for * a user-ID. */ char * uname(uid) short uid; { register struct passwd *pwp; static char ubuf[15]; if ((pwp = getpwuid(uid)) != NULL) return (pwp->pw_name); return (sprintf(ubuf, "%d", uid)); } /* * Block copy of `n' bytes. */ bcopy(f, t, n) register char *f, *t; register unsigned n; { if (n) do { *t++ = *f++; } while (--n); } /* * Return non-zero if an NCNAME-length string * is unprintable. */ unprintable(s) register char *s; { register int n = NCNAME; register int c; do { if ((c = *s++) == '\0') break; if (!isascii(c) || !isprint(c)) return (1); } while (--n); return (0); } /* * Ask whether or not to delete and * entry. Return 1 if yes. */ yes(s) register char *s; { register int c, ans = 0; printf("%.*s ? ", NCNAME, s); if ((c = getchar()) == 'y') ans = 1; while (c!='\n' && c!=EOF) c = getchar(); return (ans); } /* * Qsort compare routine. */ compar(sp1, sp2) register struct sort *sp1, *sp2; { register int rval; if (sp1->s_key == sp2->s_key) return (0); rval = 1; if (sp1->s_key > sp2->s_key) rval = -1; if (rflag) return (-rval); return (rval); } /* * Return the number of CPU minutes from CPU HZ. * or if `-j', return seconds/call. */ time_t units(hz, sp) time_t hz; register struct sort *sp; { if (jflag) return ((hz + HZ/2) / (HZ*sp->s_count)); else return ((hz + MINHZ/2) / MINHZ); } /* * Print the percentage of * `t' out of `total'. */ percent(t, total) time_t t, total; { if (total == (time_t)0) t = total = (time_t)1; t *= 100; printf("%3ld.", t/total); t %= total; if (t < 0) t = -t; printf("%1ld ", t*10/total); } usage() { fprintf(stderr, "Usage: sa [-abcjlmnrstu] [-v[n]] [file]\n"); exit(1); } /* VARARGS */ saerr(x) { fprintf(stderr, "sa: %r", &x); putc('\n', stderr); exit(1); } /* end of sa.c */
import {mutationWithClientMutationId, toGlobalId} from 'graphql-relay'; import {GraphQLID, GraphQLList, GraphQLNonNull, GraphQLString} from 'graphql'; import {GraphQLUser} from '../nodes'; import {getUserOrThrow, removeCompletedTodos, User} from '../../database'; type Input = { userId: string; }; type Payload = { deletedTodoIds: ReadonlyArray<string>; userId: string; }; const RemoveCompletedTodosMutation = mutationWithClientMutationId({ name: 'RemoveCompletedTodos', inputFields: { userId: {type: new GraphQLNonNull(GraphQLID)}, }, outputFields: { deletedTodoIds: { type: new GraphQLList(new GraphQLNonNull(GraphQLString)), resolve: ({deletedTodoIds}: Payload): ReadonlyArray<string> => deletedTodoIds, }, user: { type: new GraphQLNonNull(GraphQLUser), resolve: ({userId}: Payload): User => getUserOrThrow(userId), }, }, mutateAndGetPayload: ({userId}: Input): Payload => { const deletedTodoLocalIds = removeCompletedTodos(userId); const deletedTodoIds: string[] = deletedTodoLocalIds.map( toGlobalId.bind(null, 'Todo'), ); return {deletedTodoIds, userId}; }, }); export {RemoveCompletedTodosMutation};
// Parse config and return input/output filepaths // @return 1 => input filepath // @return 2 => output filepath // @return 3 => precision std::tuple<std::string, std::string, double> parse_config() { std::ifstream inConfig(CONFIG_PATH); if (!inConfig.is_open()) throw std::runtime_error("Could not open config file"); std::string outputFolder; std::string inputPath; double precision; std::string dummy; inConfig >> dummy >> inputPath >> dummy >> outputFolder >> dummy >> precision; return { inputPath, outputFolder, precision }; }
// // Copyright 2019 <NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "shapeAdapter.h" #include <hdMaya/adapters/adapterDebugCodes.h> #include <hdMaya/adapters/mayaAttrs.h> #include <pxr/base/tf/type.h> #include <maya/MPlug.h> #include <maya/MPlugArray.h> PXR_NAMESPACE_OPEN_SCOPE TF_REGISTRY_FUNCTION(TfType) { TfType::Define<HdMayaShapeAdapter, TfType::Bases<HdMayaDagAdapter>>(); } HdMayaShapeAdapter::HdMayaShapeAdapter( const SdfPath& id, HdMayaDelegateCtx* delegate, const MDagPath& dagPath) : HdMayaDagAdapter(id, delegate, dagPath) { _CalculateExtent(); } void HdMayaShapeAdapter::_CalculateExtent() { MStatus status; MFnDagNode dagNode(GetDagPath(), &status); if (ARCH_LIKELY(status)) { const auto bb = dagNode.boundingBox(); const auto mn = bb.min(); const auto mx = bb.max(); _extent.SetMin({ mn.x, mn.y, mn.z }); _extent.SetMax({ mx.x, mx.y, mx.z }); _extentDirty = false; } }; size_t HdMayaShapeAdapter::SamplePrimvar( const TfToken& key, size_t maxSampleCount, float* times, VtValue* samples) { if (maxSampleCount < 1) { return 0; } times[0] = 0.0f; samples[0] = Get(key); return 1; } HdMeshTopology HdMayaShapeAdapter::GetMeshTopology() { return {}; }; HdBasisCurvesTopology HdMayaShapeAdapter::GetBasisCurvesTopology() { return {}; }; HdDisplayStyle HdMayaShapeAdapter::GetDisplayStyle() { return { 0, false, false }; } PxOsdSubdivTags HdMayaShapeAdapter::GetSubdivTags() { return {}; } void HdMayaShapeAdapter::MarkDirty(HdDirtyBits dirtyBits) { HdMayaDagAdapter::MarkDirty(dirtyBits); if (dirtyBits & HdChangeTracker::DirtyPoints) { _extentDirty = true; } } MObject HdMayaShapeAdapter::GetMaterial() { TF_DEBUG(HDMAYA_ADAPTER_GET) .Msg( "Called HdMayaShapeAdapter::GetMaterial() - %s\n", GetDagPath().partialPathName().asChar()); MStatus status; MFnDagNode dagNode(GetDagPath(), &status); if (!status) { return MObject::kNullObj; } auto instObjGroups = dagNode.findPlug(MayaAttrs::dagNode::instObjGroups, true); if (instObjGroups.isNull()) { return MObject::kNullObj; } MPlugArray conns; // TODO: deal with instancing properly. instObjGroups.elementByLogicalIndex(0).connectedTo(conns, false, true); const auto numConnections = conns.length(); if (numConnections == 0) { return MObject::kNullObj; } for (auto i = decltype(numConnections) { 0 }; i < numConnections; ++i) { auto sg = conns[i].node(); if (sg.apiType() == MFn::kShadingEngine) { return sg; } } return MObject::kNullObj; } const GfRange3d& HdMayaShapeAdapter::GetExtent() { if (_extentDirty) { _CalculateExtent(); } return _extent; } TfToken HdMayaShapeAdapter::GetRenderTag() const { return HdTokens->geometry; } void HdMayaShapeAdapter::PopulateSelectedPaths( const MDagPath& selectedDag, SdfPathVector& selectedSdfPaths, std::unordered_set<SdfPath, SdfPath::Hash>& selectedMasters, const HdSelectionSharedPtr& selection) { VtIntArray indices(1); if (IsInstanced()) { indices[0] = selectedDag.instanceNumber(); selection->AddInstance(HdSelection::HighlightModeSelect, _id, indices); if (selectedMasters.find(_id) == selectedMasters.end()) { selectedSdfPaths.push_back(_id); selectedMasters.insert(_id); } } else { selection->AddRprim(HdSelection::HighlightModeSelect, _id); selectedSdfPaths.push_back(_id); } } PXR_NAMESPACE_CLOSE_SCOPE
“It’s Doctor Who meets Harry Potter” And with those golden words, the BBC has signed up to a new Russell T Davies TV show, Aliens Vs Wizards for their children’s CBBC channel, something he has previously described as a “small committment”. Revealed by his agent’s website, he is also listed as creating the show with Doctor Who writer and Sarah Jane Adventures head writer Phil Ford. But BBC insiders tell me Ford is not alone in that and much of the crew to Sarah Jane Adventures, which finished half way through its fifth series after the death of lead actress Elizabeth Sladen, are working on the show. The series is being written by familiar Sarah Jane Adventures writers including Gareth Roberts and Joseph Lidster, is set in the present day and will follow the Sarah Jane Adventures formula of twelve two part half hour episodes. Oh, and a second series has already been commissioned by the BBC before the first has been properly announced. The agent also lists Star Lost as a twenty-five minute pilot from Russell T Davies for BBC Worldwide… so we can expect some BBC America action on that. About Rich Johnston Chief writer and founder of Bleeding Cool. Father of two. Comic book clairvoyant. Political cartoonist. (Last Updated ) Related Posts None found
<reponame>matth036/dsc<gh_stars>0 #include <iostream> #include <cmath> #include "AA2DCoordinate.h" #include "AACoordinateTransformation.h" #include "AADate.h" #include "extra_solar_transforms.h" #include "AANutation.h" #include "sexagesimal.h" #include "navigation_star.h" #include "solar_system.h" #include "AASidereal.h" using std::cout; using std::endl; void print_declination_line( double JD ){ std::vector<std::string> bodies{ "Jupiter", "Saturn", "Uranus", "Neptune" }; CAADate jd(JD,true); printf( "%8.4lf ", jd.FractionalYear() ); for( uint i=0; i<bodies.size(); ++i ){ CAAEllipticalPlanetaryDetails details = solar_system::calculate_details(bodies[i], JD); printf( "%8.4lf ", details.ApparentGeocentricDeclination ); } } void print_declinations(double start_JD, double duration ){ for( double JD = start_JD; JD<=start_JD+duration*365.25; JD += 1.0 ){ print_declination_line( JD ); cout << endl; } } int main( int argc, char **argv){ cout << "# gcc = " << __GNUC__ << "." << __GNUC_MINOR__ << "." << __GNUC_PATCHLEVEL__ << endl; cout << "# __cplusplus = " << __cplusplus << endl; cout << endl; /* A default example date. */ int year = 2014; int month = 1; double day = 1; if( argc == 4 ){ sscanf( argv[1], "%d", &year ); sscanf( argv[2], "%d", &month ); sscanf( argv[3], "%lf", &day ); } bool gregorian; CAADate start_JD{year,month,day,gregorian=true}; double years = 20.1; print_declinations( start_JD.Julian(), years ); }
Printable Fluorescent Hydrogels Based on Self-Assembling Peptides Fluorescent hydrogels (FH) have a variety of potential applications in the field of soft electronics. However, fabrication of mechanically stable and printable fluorescent hydrogels remains challenging. Here, we report a kind of fluorescent hydrogel based on the co-assembly of peptide motif and transition metal ions. The metal ions are captured in the hydrogel network at specific positions through covalently linked ligands on the peptide hydrogelators. This efficiently prevents the aggregation and self-quenching of organometallic chromophores. In addition, the formation of metal-ligand complexes introduces additional interactions to stabilize the hydrogel network, making the FH even more stable after the incorporation of metal ions. The FH is optically transparent but highly fluorescent. By using three different metal ions, the white light fluorescent supramolecular hydrogel has been achieved. As a proof-of-principle, we demonstrate the printability of the hydrogels to various patterns. We anticipate that with the improved fluorescent performance and stability, this kind of FH can find broad applications in extrusion-based 3D printing for the construction of soft electronics. In this work, we have designed a novel FH based on the co-assembly of metal-ligand complexes with peptide hydrogelators in a single step. The ligands were covalently linked to the peptide hydrogelator. Such a design is kind of "killing two birds with one stone". First, because the metal ions are fixed to the hydrogel network at specific positions, the aggregation and self-quenching of chromophores are prevented. Second, the formation of metal-ligand complexes could introduce additional interactions to stabilize hydrogel network, making the FH even more stable after the incorporation of metal ions. The structural, physical and optical properties of the hydrogels were studied in details. This type of FH based on self-assembled peptides shows high transmittance, color-switchable luminescence and great stability in water. Moreover, by using three different metal ions, the white light fluorescent supramolecular hydrogel has been achieved with Commission Internationale de L'Eclairage (CIE) coordinates of (0.33, 0.33). As a proof-of-principle, we demonstrated the printability of the hydrogels to various patterns functioning in aqueous conditions. We anticipate that with the improved fluorescent performance and stability, this kind of FH can find broad applications in 3D printable soft electronics. Results Section Design of the fluorescent hydrogel. Many short peptides are well known for their ability to self-assemble into fibrous network structures and form supramolecular hydrogels. Among these peptides, ionic-complementary peptides were widely reported to form hydrogels by self-assembling into long β-sheet fibres . As shown in Fig. 1A, the ionic complementary peptide sequence KFEFKFEF was chosen as the self-assembly motif for the White light fluorescent hydrogel . Ionic complementary peptides are well known for its robust self-assembly properties. As far as the specific charge periodicity in the sequence is maintained, the chirality and sequence alternation do not affect the mechanical properties of the hydorgels 66 ( Figure S1). The N-terminus of the peptide was capped with the powerful ligand, 2,2′-bipyridine (bpy), for metal ion chelation. The final modified peptide was named as bpy-KFEFKFEF hereafter. Europium ion (Eu 3+ ) was chosen as the metal ion center because of its outstanding fluorescent property. Moreover, it can chelate with three bpy ligands to form an octahedral complex (Fig. 1A). Introducing bpy did not affect the self-assembly of KFEFKFEF. Bpy-KFEFKFEF can still self-assemble into fibrous hydrogel structures at neutral pH due to the ionic interactions between positively charged protonated amino groups on the side chain of lysine (K) and negatively charged carboxylate group on the side chain of glutamic acid (E) as well as the hydrophobic interactions and π-π stacking interaction among phenylalanine residues (Fig. 1B). The addition of Eu 3+ could crosslink the peptide fibres through metal-ligand coordination (Fig. 1B) 63 . The hydrogels with and without Eu 3+ ions are named as EFK-bpy-Eu hydrogel and EFK-bpy hydrogel, respectively. Optical properties of FH. The UV-Vis spectra of EFK-bpy-Eu hydrogel were measured to investigate the light absorption properties. For comparison, the UV-vis spectra of EuCl 3 solution and EFK-bpy hydrogel were also measured (Fig. 1C). EuCl 3 only exhibits weak absorption between the wavelengths of 200-400 nm. However, the EFK-bpy shows strong absorption in this region with three peaks locating at 222, 250 and 300 nm, respectively. The first two peaks can be attributed to the π-π* transition of phenyl groups of the peptide and the later one corresponds to the π-π* transition of bpy 67 . The presence of Eu 3+ in the hydrogel lowers the intensities of these peaks but does not affect their positions. The hydrogel shows no optical absorption in the visible light region, indicating that it is transparent. In addition, the photo-luminescent properties of the hydrogel were also studied. The images of the EFK-bpy-Eu hydrogel under natural light, and two UV ranges (UV 1 : 330-390 nm and UV 2 : 220-280 nm) from the handheld UV lamp are shown in Fig. 1D, demonstrating the fluorescent properties of the hydrogel under UV excitation. Fluorescence spectra indicate that the strong fluorescent property of the EFK-bpy-Eu hydrogel is originated from Eu 3+ -bpy binding: There is a blue fluorescent peak at 420 nm when EFK-bpy-Eu is excited at 300 nm, while neither EFK-bpy nor EuCl 3 is fluorescent (Fig. 1E). The fluorescence emission peak of EFK-bpy does not affect the emission color of the hydrogel since 80% of the peak was not in the visible range. Moreover, the emission wavelength of the hydrogel is switchable, depending on the excitation wavelength (Fig. 1F). Mechanical properties of FH. The mechanical properties of hydrogels are important for the applications as solid fluorescent gels. As illustrated in Fig. 2A, the storage modulus (G′) of the EFK-bpy-Eu hydrogel is about 20 kPa, more than 10 times higher than the loss modulus (G″) over a broad range of angular frequencies from 1 to 100 Hz. This is a clear evidence of the solid rather than viscous response of the gel. Additionally, the G′ of EFK-bpy-Eu hydrogel is about 6 times larger than that of the EFK-bpy hydrogel, implying that the increased crosslinking density through Eu 3+ -bpy coordination strengthens the mechanical property of the hydrogel (Fig. 2B). The increased crosslinking density is also evidenced at the microscopic level by TEM imaging (Fig. 2C and D). With Eu 3+ ions, the peptide fibres in the hydrogel are thicker and more entangled due to the metal-ligand crosslinking. Eu 3+ -bpy binding also causes enhanced circular dichroism (CD) absorption of the hydrogel in the near-UV region, indicating that the secondary structure of the peptide fibres is stabilized in the EFK-bpy-Eu hydrogel (Fig. 2E). Because the hydrogel is stabilized by non-covalent interaction, it can recover its mechanical stability after damage. As displayed in Fig. 2F and S1, the initial hydrogel was destroyed by ultrasound for 30 min and then allowed to recover at room temperature for 2 h. After applying ultrasound treatment, the G' reduced significantly from 2 × 10 4 Pa to 80 Pa. However, it can be fully recovered after self-healing for 2 h. To understand the change in the mechanical properties by ultrasound at the microscopic level, TEM images of the initial, destroyed and recovered hydrogels were also studied. As shown in Figure S2 and Figure S9, the long fibers of the hydrogel were broken into shorter ones under sonication and the hydrogel turned to liquid. However, in the recovered hydrogel, the short fibers again grew into longer ones, suggesting that the self-assembly of the peptide hydrogelators is dynamic and reversible. We expect such a mechanical feature of the hydrogel making it a suitable "ink" for extrusion-based bioprinting. Scientific REPORtS | 7: 9691 | DOI:10.1038/s41598-017-10162-y White light fluorescent hydrogel (WLFH). Among all the fluorescent materials, white ones are in great demand due to their potential applications in large-area flexible displays. Since 2,2′-bipyridine can form the organometallic complex with various ions, chromophores with different emitting light can be introduced into the hydrogel through the same coordination interactions. As shown in Fig. 3A, Eu 3+ , Ru 2+ , and Ir 2+ were chosen to form the fluorescent metal complex with EFK-bpy peptide and prepared the WLFH, because their emission spectra are complementary in the visible light range. The chemical structures of the three different ionic compounds used to form ionic complexes were shown in Figure S3. The hydrogels with Ir 2+ and Ru 2+ ions can be prepared using the same procedure for EFK-bpy-Eu hydrogel ( Figure S4) and are denoted as EFK-bpy-Ir hydrogel and EFK-bpy-Ru hydrogel, respectively, hereafter. They both show entangled fibrous network similar to the EFK-bpy-Eu hydrogel ( Figure S5). The mechanical properties of these hydrogels are summarized in Figure S6 and are all stronger than that of EFK-bpy hydrogels . We then tuned the hydrogel composition for white light emission. We first characterized the UV-Vis absorption spectra of the hydrogels with only a single ligand (Fig. 3B). Obvious they all show strong absorption in the UV region. The emission spectra of the EFK-bpy-Eu, EFK-bpy-Ir and EFK-bpy-Ru hydrogels excited at 365 nm were shown in Fig. 3C. The emission spectra can cover the full visible light range, suggesting that it is possible to use these three components to construct white light fluorescent hydrogel. The EFK-bpy-Eu hydrogel exhibits blue emission at ~420 nm with CIE coordinates of (0.16, 0.14), the EFK-bpy-Ir hydrogel exhibits yellow emission at ~500 nm with CIE coordinates of (0.38, 0.44), and the EFK-bpy-Ru hydrogel mainly shows red emission at ~600 nm with CIE coordinates of (0.16, 0.14) even though there is a minor peak at 416 nm. Moreover, we found that there was Förster resonance energy transfer (FRET) in the EFK-bpy-Eu and EFK-bpy-Ru co-hydrogel system (Fig. 3D). This is reasonable because the emission spectrum of EFK-bpy-Eu overlaps with the excitation spectrum of EFK-bpy-Ru. However, no obvious FRET can be observed in the EFK-bpy-Eu and EFK-bpy-Ir co-hydrogel system as well as EFK-bpy-Ir and EFK-bpy-Ru co-hydrogel system ( Figure S7). Due to the complicated photophysical processes in the hydrogel, the proper metal ion concentrations for white-fluorescent can only be obtained in a trial-and-error fashion. Luckily, we found that the peptide hydrogel containing Eu 3+ , Ir 2+ and Ru 2+ in a ratio of 20:1:0.5 can emit white light when being excited under the irradiation of UV 1 lamp (Fig. 4A). The WLFH excited at 365 nm has three maxima emission wavelengths at 420 nm, 500 nm, and 600 nm, corresponding to blue, yellow and red parts of the electromagnetic spectra (Fig. 4B). The CIE value of (0.33, 0.33) for white fluorescent light can be achieved in this hydrogel. With different ratios of the three metal ions, hydrogels with a broad colour gamut could be achieved (Fig. 4C). Moreover, the range of the fluorescence emission light can be adjusted by using different excitation wavelengths ( Figure S8). Potential applications of WLFH in aqueous conditions. A unique advantage of the supramolecular hydrogel is that their quick self-healing properties. The hydrogel can fully recover its mechanical stability after damage ( Figure S9), suggesting that it can be used for extrusion-based 3D printing applications. A proof-of-principle demonstration of manually printing the hydrogels on silica glass surface by syringes was shown in Fig. 5. The stable hydrogel spots can form after being injected out of the syringes. These hydrogel spots were hard to be visualised by eyes because they are highly transparent. However, all the patterns showed excellent emission under the excitation of UV 1 (Fig. 5A), illustrating the feasibility of using these hydrogels for fluorescent. Moreover, the hydrogels also functioned properly in water with low erosion rate because of the hyper-crosslinked network structure of the hydrogel (Fig. 5B). The hydrogel could retain its shape and fluorescent properties even after being placed in water for hours. The metal ion released into water was monitored by UV-vis spectroscopy. The released percentage of all the ions is less than 15% after soaking the hydrogel in water for 48 hours (Fig. 5C). The mechanical stability of the hydrogel decreases slightly after the incubation in water (Fig. 5D), which is probably due to the loss of EFK-bpy molecules. The photo stability of fluorescent gels is also excellent. The peak locations and intensities of EFK-bpy-Eu, EFK-bpy-Ir, and EFK-bpy-Ru hydrogels remained almost unchanged after storing in centrifuge tubes and illuminated under the natural light for 7 days ( Figure S10). Even being soaked in water for 48 hours, all hydrogels remained fluorescent with some loss in fluorescence intensity (~20% for EFK-bpy-Eu and EFK-bpy-Ru hydrogels and ~38% for EFK-bpy-Ir hydrogel) ( Figure S10). All these demonstrate the possibility of applying the hydrogel as photo-excitable underwater soft electronics. Discussion Section In this work, we have demonstrated the fabrication of White light fluorescent hydrogel based on self-assembling peptides. There are several merits of this new type of fluorescent hydrogel that is worth of further discussion. First, the hydrogel is made of merely non-covalent interactions yet shows remarkable mechanical and chemical stability, thanks to the hyper-crosslinked structure. Both intra-fibre interactions (ionic interaction, hydrophobic interaction and π-π stacking) and inter-fibre interactions (metal-ligand coordination) are reversible. Therefore, the hydrogel can reform after being mechanically destroyed, making it a suitable candidate for 3D printing. Second, the hydrogel shows remarkable chemical stability and low erosion rate. Weak non-covalent interactions are typically dynamic. Therefore, most short-peptide based hydrogels tend to erode when being placed in water. However, with the help of additional metal-ligand bonds, the structure become much more stable and can function in aqueous conditions for several hours. Third, the hydrogel can display a wide range of color when using different transition metal centers. Because bpy is a common ligand for various metal ions with distinct luminescence, the emission color of the hydrogel can be easily tuned using different metal-ligand chromophores. Moreover, the introduction of ligands to the hydrogel network makes the hybrid system of high photo-stability by suppressing the aggregation and diffusion of chromophores. Fourth, the emission color of the hydrogel is switchable by changing the photo-excitation wavelength. The white-fluorescent can be achieved with a broad color gamut. Therefore, it may be used as a unique photo-controlled light source for special displays. Combining transition metal ions with self-assembling peptide in hydrogels may represent a general route to engineer hydrogel-based white-light-emitters. Conclusion In summary, we report a new kind of fluorescent hydrogel based on self-assembly peptides hyper-crosslinked by coordination bonds. The hydrogel shows improved mechanical and chemical stability, broad colour gamut, switchable photo-induced emission spectra, and white light fluorescent properties. Moreover, it is printable and can be easily integrated into complicated electronic devices. The fluorescent properties and stability can be further tailored for different applications. We anticipate that it may find wide applications in the field of soft electronics. Preparation of hydrogels. For EFK-bpy, EFK-bpy-Ir hydrogel or EFK-bpy-Ru hydrogels, the peptide was dissolved in phosphate saline buffer (PBS, 10 mM, pH = 7.0) to the concentration of 12 mM. The peptide-PBS mixture was then thoroughly mixed by a vortex mixer (Scientific Instruments, USA) for 30 seconds at its maximum power and stored still for 1 h to hydrogelation. For EFK-bpy-Eu hydrogels, the EFK-bpy-Eu peptide was dissolved in phosphate saline buffer (PBS, 10 mM, pH = 7.0) to the concentration of 4 mM. For the WLFH, EFK-bpy-Eu, EFK-bpy-Ir and EFK-bpy-Ru were dissolved in phosphate saline buffer (PBS, 10 mM, pH = 7.0) to the concentration of 3.7, 0.56 and 0.28 mM, respectively. The mixture was thoroughly mixed by a vortex mixer for 30 seconds at its maximum power and the hydrogel was formed after the mixture was stored still for 1 hour. The concentration of the WLFH was 12 mM. The concentration of WLFH was 4 mM after three times of dilution. Mechanical Measurements. To study the mechanical property of these hydrogels, all hydrogels were prepared by these protocols mentioned above and transferred to the rheometer plate with care. The volume of each measurement was 50 μL. The measurement was undertaken in a Thermo Scientific Haake RheoStress 6000 using a frequency sweep mode with the frequency from 0.1 to 100 Hz at 0.1% strain. All these experiments were carried out at 20 °C and 0.50 mm gap. The geometry was 1°/20 mm of the cone. UV-Vis Spectroscopy and Fluorescence spectroscopy. All spectroscopy samples were prepared by diluting the hydrogel samples prepared above. The UV-Vis spectra were recorded by a JASCO FP-6500(JASCO Inc., Japan). The bandwidth was set as 0.2 nm. And fluorescence spectra were measured by a JASCO V-550(JASCO Inc., Japan) at different excitation wavelengths. Typically, 100 μL of hydrogels were suspended in 200 μL of PBS buffer and fractured by a vortex mixer (Scientific Instruments, USA) for 15 min at its maximum power. Scientific REPORtS | 7: 9691 | DOI:10.1038/s41598-017-10162-y Circular dichroism (CD) spectra. All CD spectroscopy samples were measured in quartz cuvette with a path length of 1 mm. Typically, 20 μL of hydrogels were suspended in 980 μL of PBS buffer and fractured by a vortex mixer (Scientific Instruments, USA) for 15 min at its maximum power. Transmission Electron Microscope (TEM). Transmission electron microscopic images were obtained using a JEM-200CX (JEOL Inc., Japan). The hydrogel was re-suspended in PBS (10 mM, pH = 7.0) 8 times of the original volume and mixed well. The sample solution was dropped on the Ultrathin Carbon Film on Copper and dried under the nitrogen. Preparation of printing pattern. All hydrogels were prepared by the protocols mentioned above. The concentration of EKF-Bpy-Eu dyrogels uesd was 4 mM while the concentration of other hydrogels were all 12 mM. The hydrogels were printed by an injector. Each spot was 20 μL. The pattern was printed on quartz glass to reduce the influence of the fluorescence from the glass.
<gh_stars>100-1000 package smithereen.activitypub; import java.sql.SQLException; import smithereen.exceptions.BadRequestException; import smithereen.activitypub.objects.Activity; import smithereen.activitypub.objects.ActivityPubObject; import smithereen.activitypub.objects.Actor; public abstract class NestedActivityTypeHandler<A extends Actor, T extends Activity, N extends Activity, O extends ActivityPubObject> extends ActivityTypeHandler<A, T, O>{ public abstract void handle(ActivityHandlerContext context, A actor, T activity, N nested, O object) throws SQLException; @Override public final void handle(ActivityHandlerContext context, A actor, T activity, O object) throws SQLException{ if(activity.object.object==null) throw new BadRequestException("Nested activity must not be a link"); if(!(activity.object.object instanceof Activity)) throw new BadRequestException("Nested activity must be an Activity subtype"); Activity a=(Activity) activity.object.object; handle(context, actor, activity, (N)a, object); } }
s1,s2,s3=input().split() s1=s1.capitalize() s2=s2.capitalize() s3=s3.capitalize() x=s1[0]+s2[0]+s3[0] print(x)
<reponame>thomasweng15/visual_foresight from .general_agent import GeneralAgent import numpy as np class OfflineAgent(GeneralAgent): def __init__(self, hyperparams): super().__init__(hyperparams) def _post_process_obs(self, env_obs, agent_data, initial_obs=False): # obs = super()._post_process_obs(env_obs, agent_data, initial_obs=False) obs = {} images = self._goal_image[:, None] # add dimensions for ncam obs['images'][:2,:] = images obs['states'] = np.zeros(images.shape[0], 1) # dummy states
/** * Container class for the response of a depseudonymization URL request. * Contains the depseudonymization URL and a list of the invalid pseudonyms from * the corresponding request. */ public class DepseudonymizationUrlResponse { /** * URL for the depseudonymization. */ private String url; /** * List of invalid pseudonyms. */ private List<String> invalidPseudonyms; /** * Constructs a new DepseudonymizationUrlResponse. * * @param psedonymizationUrl URL for the depseudonymization. * @param invlaidPseudonyms List of invalid pseudonyms. */ public DepseudonymizationUrlResponse(final String psedonymizationUrl, final List<String> invlaidPseudonyms) { this.url = psedonymizationUrl; this.invalidPseudonyms = invlaidPseudonyms; } /** * @return URL for the depseudonymization. */ public String getUrl() { return url; } /** * @param pseudonymizationUrl URL for the depseudonymization. */ public void setUrl(final String pseudonymizationUrl) { this.url = pseudonymizationUrl; } /** * @return List of invalid pseudonyms. */ public List<String> getInvalidPseudonyms() { return invalidPseudonyms; } /** * @param invalidPseudonyms List of invalid pseudonyms. */ public void setInvalidPseudonyms(final List<String> invalidPseudonyms) { this.invalidPseudonyms = invalidPseudonyms; } }
// AutocompleteVolumeFilters - Autocomplete volume ls --filter options. func AutocompleteVolumeFilters(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { local := func(_ string) ([]string, cobra.ShellCompDirective) { return []string{"local"}, cobra.ShellCompDirectiveNoFileComp } kv := keyValueCompletion{ "name=": func(s string) ([]string, cobra.ShellCompDirective) { return getVolumes(cmd, s) }, "driver=": local, "scope=": local, "label=": nil, "opt=": nil, "dangling=": getBoolCompletion, } return completeKeyValues(toComplete, kv) }
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // NS_ASSUME_NONNULL_BEGIN @interface OWSProvisioningCipher : NSObject @property (nonatomic, readonly) NSData *ourPublicKey; - (instancetype)initWithTheirPublicKey:(NSData *)theirPublicKey; - (nullable NSData *)encrypt:(NSData *)plainText; @end NS_ASSUME_NONNULL_END