| Package | Description |
|---|---|
| io.permazen.cli.cmd |
Permazen CLI
Command related classes, including pre-defined commands. |
| io.permazen.cli.func |
Permazen CLI pre-defined
Function s. |
| io.permazen.parse |
Permazen parsing related classes.
|
| io.permazen.parse.expr |
Classes for parsing Java expressions with Permazen-specific extensions.
|
| io.permazen.parse.func |
Function used in a ParseSession , including built-ins. |
| Class and Description |
|---|
| EvalException
Thrown when an error occurs evaluating an expression.
|
| Node
The product of a parse operation, which is capable of producing a
Value when evaluated within a transaction. |
| Class and Description |
|---|
| ConstValue
A constant, read-only
Value . |
| Value
Holds a value for use during expression evaluation.
|
| Class and Description |
|---|
| Node
The product of a parse operation, which is capable of producing a
Value when evaluated within a transaction. |
| Value
Holds a value for use during expression evaluation.
|
| Class and Description |
|---|
| AbstractLValue
Abstract
LValue implementation. |
| AbstractValue |
| AdditiveExprParser
Parses Java additive expressions of the form
x + y and x - y . |
| AssignmentExprParser
Parses Java assignment expressions of the form
x = y , x += y , etc. |
| AtomExprParser
Parses atomic Java expressions such as parenthesized expressions,
new expressions,
session function calls, identifiers (e.g., lambda method parameter names), and literals. |
| BaseExprParser
Parses basic left-associative Java expressions such as auto-increment expressions, array access, field access, invocation, etc.
|
BeanPropertyValue
Value that reflects a bean property in some object. |
| BinaryExprParser
Support superclass for tail-recursive binary expression parsers for expressions of the form
ARG1 OP ARG2 . |
| BitwiseAndParser
Parses bit-wise AND expressions of the form
x & y . |
| BitwiseOrParser
Parses bit-wise OR expressions of the form
x | y . |
| BitwiseXorParser
Parses bit-wise XOR expressions of the form
x ^ y . |
| CastExprParser
Parses type cast expressions.
|
| ClassNode |
| ConditionalParser
Parses conditional expressions of the form
x ? y : z . |
| ConstNode |
| ConstValue
A constant, read-only
Value . |
| EqualityParser
Parses equality expressions of the form
x == y or x != y . |
| ExprParser
Java expression parser.
|
| FieldValue |
| InstanceofParser
Parses
instanceof expressions. |
| JFieldValue |
| LambdaExprParser
Parses lambda expressions.
|
LambdaNode
Node representing a lambda function. |
| LambdaNode.Param |
| LiteralExprParser
Parses literal values.
|
| LogicalAndParser
Parses logical AND expressions of the form
x && y . |
| LogicalOrParser
Parses logical OR expressions of the form
x || y . |
| LValue
Extension of the
Value interface for instances that are capable of assignment. |
MethodReferenceNode
Node representing a method reference. |
| MultiplicativeExprParser
Parses multiplicative expressions of the form
x & y , x / y , and x % y . |
| Node
The product of a parse operation, which is capable of producing a
Value when evaluated within a transaction. |
| Op
Java expression operators.
|
| RelationalExprParser
Parses relational expressions of the form
x < y , x >= y , etc. |
| ShiftExprParser
Parses shift expressions of the form
x << y , x >> y , and x >>> y . |
| TypeInferringNode
Support superclass for
Node s that perform type inferrence and therefore require a target type
in order to be completely parsed. |
| UnaryExprParser
Parses unary expressions using one of
! , ~ , + , - , ++ , -- . |
| Value
Holds a value for use during expression evaluation.
|
VarValue
Value that represents a ParseSession variable. |
| Class and Description |
|---|
| Node
The product of a parse operation, which is capable of producing a
Value when evaluated within a transaction. |
| Value
Holds a value for use during expression evaluation.
|
Copyright © 2020. All rights reserved.


| DOSE: |
1.0 g |
oral |
DXM |
|
| |
5 hits |
smoked |
Cannabis |
(plant material) |
[Erowid Note: 1 gram of DXM is considered an extremely high dose, see DXM Dose Chart]
After taking the dxm I tripped ridiculously hard, but I never once freaked out. It was actually a memorable and enjoyable time for me but the problem occured the next day.
I was at a friend's and I took only a few (maybe 5) bong rips of marijuana. I guess I passed out, which never happens to me on marijuana, and when I awoke my friends had already just left. I was confused and extremely fatigued. I was unable to rationalize why my friends were missing, and I was extremely panicky. I tried to go to the door and I fumbled with the handle. I realized my shoes were untied so I attempted to bend down to tie them but I kept loosing balance and I kept falling into the hallway wall. I fell to the floor and passed out for a moment, everything was darkish and I felt very very fatigued. I crawled to a nearby chair and rested my head on it, when I saw the host of the house was panicking about my actions.
I was really scared, and I got up and stumbled to the door, and ran down stairs. I made it outside into the apartment complex parking lot and ran to a car I thought was my friend's. I began fumbling for the handle on the door while starting to regain my composure and energy levels rose above that of the fatigue I was experiencing. I was yelling my friend's name and eventually I saw headlights and realized where my friends car really was. It took my about 3 minutes to get the door handle and open the car, where I sat in and then felt much better. This may have been a warning sign for narcolepsy, it could have been the lack of sleep from last nights tripping, or it could be a potentially dangerous result of dxm use.
Experience Reports are the writings and opinions of the individual authors who submit them.
Some of the activities described are dangerous and/or illegal and none are recommended by Erowid.


created 12/10/99; revised 01/22/00; edited 07/18/02
A boolean value (a true/false
value) picks the branch
of an if
statement or allows a loop to continue.
Sometimes the boolean expression is more complicated
than we have seen so far in these notes.
Often a program must make a decision based on a number of factors.
This chapter will examine this topic and discuss some additional boolean
operators.
&&
and ||
operators.&
and |
operators.&&
operators.||
operators.&&
and &&
operators.&&
and ||
operators.
What is the true/false
value of:
12 < 6 && 18 > 1
12 < 6 && 18 > 1
evaluates to false
| AND Operator && | |
|---|---|
| true && true | true | false && true | false | true && false | false | false && false | false |
You may have noticed something in answering the question: you can get the correct answer to the question by evaluating just the first part of the expression:
12 < 6 && 18 > 1 ------ false
Since false
&& anything is false
,
there is no need
to continue after the
first false
has been encountered.
In fact,
this is how Java operates:
To evaluateX && Y
, first evaluate X. If X isfalse
then stop: the whole expression isfalse
. Otherwise, evaluate Y then AND the two values.short-circuit evaluation
This idea is called short-circuit evaluation.
Programmers frequently make use of this feature.
For example,
say that two methods that return true/false
values
are combined in a boolean expression:
if ( methodThatTakesHoursToRun() && methodThatWorksInstantly() ) ....
Suggest a better (but logically identical) way to arrange this boolean expression.
Put the fastest method
first because if it returns a false
you are done immediately.
if ( methodThatWorksInstantly() && methodThatTakesHoursToRun() ) ....
If the first method returns false
, the
second method is not evaluated at all,
saving time.
The result of evaluating the boolean expression is
false
whenever methodThatWorksInstantly()
is
false
.
Only when it is true
is the time consuming method executed.
Danger: This trick works correctly only if the skipped method
does nothing permanent.
In other words, short-circuit evaluation is safe when
the skipped method does nothing but
compute true
or false
.
Short-circuit evaluation is not safe when the
skipped does more than that.
For example:
boolean methodThatTakesHoursToRun() { // make a permanent change to the state of // an object that the rest of the program uses. // now return a true or false }
When a method makes
permanent changes to data,
it must be called regardless of
the true/false
value of some other method.
When a method makes a permanent change to data
the method is said to have a side effect.
When methods have side effects,
you must be careful when using a short-circuit
operator.
Any function that returns any type of value can be used in a boolean expression, so side-effects are a concern.
For example,
say that a method computeMaximum()
computes the maximum value of some variables,
stores the result in maximum
and returns
that value:
int maximum; // set by computeMaximum() . . . if ( sum < 100 && computeMaximum() < 500 ) { result = 2 * maximum ; // maximum might not be computed. } . . .
There is a problem here.
The method that follows &&
sets maximum
(as a side effect)
only when
sum
is greater than 100.
The assignment statement will sometimes put
the wrong value in result
.
You should arrange the expression like this:
int maximum; . . . if ( computeMaximum() < 500 && sum < 100 ) { result = 2 * maximum ; } . . .
With this arrangement the side effect will always happen.
The two if
statements look almost identical;
however, the first one is a bug (probably).
Bugs like this can be hard to find.
The best solution is to write computeMaximum()
so that it has no side effect,
then use it like this:
int maximum; . . . maximum = computeMaximum(); if ( maximum < 500 && sum < 100 ) { result = 2 * maximum ; } . . .
Would it be useful to have a non-short-circuit AND operator?
Yes.
| Expression | Result | Evaluation Order |
|---|---|---|
true && true | true | both operands evaluated |
false && true | false | only first operand evaluated |
true && false | false | both operands evaluated |
false && false | false | only first operand evaluated |
true & true | true | both operands evaluated |
false & true | false | both operands evaluated |
true & false | false | both operands evaluated |
false & false | false | both operands evaluated |
The & operator combines two boolean values using the rules for AND, but always evaluates both operands. This is useful when you want both operands to be evaluated no matter what values are returned.
The disadvantage is a possible loss of speed.
Most Java programs are written using the &&
operator whenever an AND is
needed.
The programmer must be careful of side-effects, though.
Usually this is done by writing methods that are "pure functions" as much
as possible.
A pure function is a method that returns a value and is free of
side effects.
Methods that are not pure functions should usually be kept out of boolean
expressions.
For example,
the final version of the method computeMaximum()
in the previous
example is a pure function.
It computed the maximum,
but did not itself save the result.
What does the following print?
int count = 0; // say that these values are the result of int total = 345; // the program running with input data. if ( count > 0 && total / count > 80 ) System.out.println("Acceptable Average"); else System.out.println("Poor Average");
Poor Average
int count = 0; int total = 345; if ( count > 0 && total / count > 80 ) System.out.println("Acceptable Average"); else System.out.println("Poor Average"); |
Sometimes an if
statement or a while
statement uses the
short-circuit AND to avoid division by zero,
or to avoid some other easily tested condition,
as in the example.
The same could be done with nested if
statements,
but with additional clutter that the programmer
might wish to avoid.
The first comparison, count > 0
acts
like a guard that prevents evaluation from reaching
the division when count is zero.
The example program would not work if the
non-short-circuit AND ( & ) were used.
The second operand would include a
division by zero even when the first
operand evaluated to false
.
The example works like this:
int count = 0; int total = 345; if ( count > 0 && total / count > 80 ) --------- false, so no further evaluation is done.
Re-write the example using nested if
statements:
int count = 0; int total = 345; if ( ______________ ) { if ( ______________ ) System.out.println("Acceptable Average"); else System.out.println("Low Average"); } else System.out.println("No values to average.");
int count = 0; int total = 345; if ( count > 0 ) { if ( total / count > 80 ) System.out.println("Acceptable Average"); else System.out.println("Low Average"); } else System.out.println("No values to average.");
In this code fragment,
the "guard" that prevents division by
zero is the first if
statement.
When count
is zero,
it prevents the true-branch from executing.
It is easy to get caught up in complicated boolean expressions and to use them when a nested-if is more appropriate. Notice that the solution to the question is probably the better program because it is easier to understand and writes better messages to the monitor.
What is the true/false
value of:
12 > 6 || 18 > 1
| Expression | Result | Evaluation Order |
|---|---|---|
true || true | true | only first operand evaluated |
false || true | true | both operands evaluated |
true || false | true | only first operand evaluated |
false || false | false | both operands evaluated |
true | true | true | both operands evaluated |
false | true | true | both operands evaluated |
true | false | true | both operands evaluated |
false | false | false | both operands evaluated |
Perhaps you noticed that to answer the question you only needed to evaluate the first subexpression:
12 > 6 || 18 > 1 ------ true
Once you know that this subexpression is true
there is no need to
go further.
true
OR anything is true
.
The || OR operator is also
a short-circuit operator.
Since OR evaluates to true
when one or both
of its operands are true
,
short-circuit evaluation stops with the first true
.
The OR operator comes in a non-short-circuit version as well: | (this is a single vertical bar.) When this operator is used, both operands are evaluated no matter what the outcome of the first operand. The short-circuit OR works like this:
To evaluateX||Y
, first evaluate X. If X istrue
then stop: the whole expression istrue
. Otherwise evaluate Y and OR the two values.
As with the short-circuit AND, be careful when using methods that have side effects. If you are depending on a method's side effect, be sure that the method executes.
What is the value of:
(4 < 8 ) && (12 <= 40 ) && (50 > 1)
(4 < 8 ) && (12 <= 40 ) && (50 > 1)
is true
An expression with two && operators works like you expect. But let us look at the situation in detail. When the && operator is used twice in an expression, group the first && and its operands together like this:
(4 < 8 ) && (12 <= 40 ) && (50 > 1) is equivalent to: ( (4 < 8 ) && (12 <= 40 )) && (50 > 1)
Now evaluate that first group.
The result is a true
or false
that works with the next && operator:
( true ) && (50 > 1)
The effect of this is that for the entire expression to
be true
, every operand must be true
.
One or more false
values cause the entire expression
to be false
.
Short-circuit evaluation is still going on, so
the first false
value stops evaluation and
causes the entire expression to be false
.
What is the value of:
(4 < 8 ) && ( 8 < 0 ) && ( 100 > 45 )
(4 < 8 ) && ( 8 < 0 ) && ( 100 > 45 ) (T && F) && ( 100 > 45 ) F && ( 100 > 45 )
... evaluation stops with the value false
for the entire expression.
When there are more than two && operators in an expression, pairs of operands are grouped togther with an && starting from the left and going toward the right of the expression. Such a group works as a single operand for the next && to the right.
Assume that V, W, X, Y, and Z stand for boolean operands. Then operands are grouped from left to right:
V && W && X && Y && X (V && W) && X && Y && X ((V && W) && X ) && Y && X (((V && W) && X ) && Y) && X
In the last line (above) every && operator has one operand to its left and one operand to its right. The associativity of an operator is how its operands are grouped in situations like this. The && operator has Left to Right Associativity. Most (but not all) operators work this way.
If you are not happy with the above discussion, don't worry about it.
Mostly all you need to know is that an expression with many &&'s works by looking
for a false
starting from the left and going toward the right.
The first false
it finds stops evaluation and causes the entire
expression to be false
.
If every operand is true
then every operand is evaluated and
the entire
expression is true
.
What is the value of:
(4 < 8 ) || ( 8 < 0 ) || ( 100 > 45 )
(4 < 8 ) || ( 8 < 0 ) || ( 100 > 45 ) -------- true
.... evaluation stops with the first true
and
the entire expression is true
.
The ||
operator also has left to right associativity.
In other words, it works like you expect.
When an expression has several ||
's look
for a true
starting from the left and going toward the right.
The first true
stops the evaluation and causes the entire
expression to be true
.
If every operand is false
then every operand is evaluated and
the entire
expression is false
.
When there are possible side effects it is important to understand that evaluation goes from left to right, as explained above. If there are no side effects (as in the expression used for the question) it doesn't really matter.
What is the value of:
Math.sin( 0.5 ) >= Math.tan( 0.2 ) || 43.259 / 12.073 > 3.5 || ( 100 > 45 )
Math.sin( 0.5 ) >= Math.tan( 0.2 ) || 43.259 / 12.073 > 3.5 || ( 100 > 45 )
There are no side-effects here, so it is safe to look at the last part:
( 100 > 45 )
and realize that the entire expression will be true
.
Java (working from left to right) might have found a different false
,
but in the absence of side-effects that doesn't matter.
The entire expression is false
.
Math functions, such as Math.sin()
and Math.cos()
,
do not have side effects.
They are safe to use in boolean expressions.
Say that you have not yet given up on buying that $25,000 red Miata sports car. The sales manager of the car lot will let you buy the car if:
The logic of this situation is slightly complicated. Here are several situations:
Notice that it is not enough to merely have a high credit line. To buy the car on credit you must also be free of debt.
You have $25,000 in cash, $50,000 in credit and massive debts. Do you get the car?
Yes.
The sales manager of the car lot will let you buy the car if:
Say that "outstanding debts" means debts more than $1,000. Here is a program that makes the car buying decision:
// Sports Car Purchase
// New $25,000 red Miata sports car.
// You need cash or credit with no debts .
//
import java.io.*;
class HotWheels2
{
public static void main (String[] args) throws IOException
{
BufferedReader stdin =
new BufferedReader ( new InputStreamReader( System.in ) );
String inData;
int cash, credit, debt ;
// get the cash
System.out.println("How much cash?");
inData = stdin.readLine();
cash = Integer.parseInt( inData );
// get the credit line
System.out.println("How much credit do you have?");
inData = stdin.readLine();
credit = Integer.parseInt( inData );
// determine the debts
System.out.println("How much much do you owe?");
inData = stdin.readLine();
debt = Integer.parseInt( inData );
// check that at least one qualification is met
if ( cash >= 25000 || ( credit >= 25000 && debt < 1000 ) )
System.out.println("Enough to buy this car!" );
else
System.out.println("Have you considered a Yugo?" );
}
}
The boolean expression of the if
statement correctly implements the
car buying rules.
The expression includes both &&
and ||
.
You have zero dollars, $26,000 in credit and $500 in debts. Do you get the car?
Yes.
cash
is 0;credit
is 26000; debt
is 500.
The boolean expression is evaluated like this:
cash >= 25000 || ( credit >= 25000 && debt < 1000 ) false || ( credit >= 25000 && debt < 1000 ) false || ( true && debt < 1000 ) false || ( true && true ) false || ( true ) true
Parentheses are used to group the two relational expressions that are to be ANDed.
(Since &&
has higher precedence than ||
,
the parentheses are not needed,
but they don't hurt.)
The following expression is not equivalent:
( cash >= 25000 || credit >= 25000 ) && debt < 1000
When boolean expressions contain both
&&
and ||
correct grouping is
important.
Use the (incorrect) boolean expression above to answer this question: You have $50,000 in cash, $100,000 of credit, and $3,000 of debt. Can you buy the car?
No, you can't buy the car (at least that is what the incorrect boolean expression says.)
You have $50,000 in cash, $100,000 of credit, and $3,000 of debt. Here is how the incorrect expression is evaluated:
( cash >= 25000 || credit >= 25000 ) && debt < 1000 ( true || credit >= 25000) && debt < 1000 ( true ) && debt < 1000 true && false false
The correctly grouped expression,
cash >= 25000 || ( credit >= 25000 && debt < 1000 )
immediately evaluates to true
.
Here is another problem: a program screens job applicants. An applicant is accepted for an interview only if the applicant meets two conditions:
Put parentheses in this boolean expression so that it correctly tests applicants:
if ( college >= 4 && experience >= 2 || gpa > 3.5 ) System.out.println("Interview applicant"); else System.out.println("Send resume to circular file.");
An applicant must meet two conditions:
if ( college >= 4 && ( experience >= 2 || gpa > 3.5 ) ) System.out.println("Interview applicant"); else System.out.println("Send resume to circular file.");
| Operator | precedence |
|---|---|
! | High |
&& | Medium |
|| | Low |
You have seen that when expressions mix
&&
and ||
that evaluation must be
done in the correct order.
Parentheses can be used to group operands with their correct operator,
just like in arithmetic.
Also like arithmetic operators, logical operators have precedence that
determines how things are grouped in the absence of parentheses.
In an expression, the operator with the highest precedence is grouped with its operand(s) first, then the next highest operator will be grouped with its operands, and so on. If there are several logical operators of the same precedence, they will be examined left to right.
For example, say that A, B, C, and D
stand for relational expressions
(things like 23 > 90).
Then,
A || B && C
means A || (B && C)
A && B || C && D
means (A && B) || (C && D)
A && B && C || D
means ((A && B) && C) || D
!A && B || C
means ((!A) && B) || C
It is common for programmers to use parentheses to group operands together rather than rely on logical operator precedence rules.
Add parentheses to the following to show how operator precedence groups operands:
a > b && 45 <= sum || sum < a + b && d > 90
( a > b && 45 <= sum ) || (sum < a + b && d > 90 )
| a + b | is an arithmetic expression | sum < a + b | is a relational expression, a type of boolean expression |
d > 90 | is a relational expression, a type of boolean expression |
sum < a + b && d > 90 | is a boolean expression | ... and so on ... | There are many other subexpressions |
The boolean expression of the question contained pieces, called sub-expressions, that are themselves expressions. It is common in Java (and other languages) to build up complicated expressions out of smaller expressions. The precedence rules and parentheses keep everything straight.
Arithmetic operators *, /, +, -, and % have higher precedence than && and || so they are done first. For example:
sum < a + b
means
sum < (a + b)
However, the not operator (!) has higher precedence than all the arithmetic operators except unary minus and has higher precedence than the other logical operators. Usually this means that you will need to use parentheses to apply it correctly.
People may enter a contest UNLESS they are less than 21 years old, make more
than $100,000, or live in Ohio.
Use parentheses to group this boolean expression so that it is
true
when a person CAN enter the contest.
! age < 21 || pay > 100000 || home.equals("Ohio")
People may enter a contest UNLESS they are less than 21 years old, make more
than $100,000, or live in Ohio.
The boolean expression is grouped so that it is
true
when a person CAN enter the contest.
!( age < 21 || pay > 100000 || home.equals("Ohio") )
You have reached the end this chapter. You may wish to review the following. Click on a subject that interests you to go to where it was discussed.


Preparation time
30 mins to 1 hour
Cooking time
1 to 2 hours
Serves
Serves 4
For the chocolate ganache, place the vinegar into a non-reactive saucepan and bring to the boil. Cook until the volume of liquid has reduced to 110ml/4fl oz.
Place the chocolate into a bowl over a pan of simmering water (do not let the water touch the bottom of the bowl). Heat until melted.
Remove the bowl from the heat, then gently stir in the butter and the reduced vinegar. Mix until well combined. Place in the fridge until firm, about two hours.
For the duck, preheat the oven to 150C/300F/Gas 2. Remove the legs and breasts from the duck. (You will not need the carcass for this recipe; save to make stock for another dish.)
Heat a large ovenproof frying pan until just warm, then add the duck legs, skin-side down, and cook for one minute until just browned. Add the duck fat, one clove of garlic and half of the thyme.
Cook in the preheated oven for 1-1½ hours, then carefully remove the duck legs from the fat and keep warm.
Meanwhile, heat another frying pan until hot. Add the olive oil, shallots and the remaining garlic and thyme. Cook for 2-3 minutes, or until softened, then add the sugar and cook for a further minute, stirring until the sugar has dissolved. Add the port and cook until reduced to a sticky glaze. Add the chicken stock and cook until the volume is reduced by half (the sauce should be thick enough to coat the back of a spoon).
Pass the sauce through a sieve back into the pan and season, to taste, with salt and freshly ground black pepper. Add the cherries and cook for one minute.
Remove the skin from the duck breast and add the skin to the pan with the duck legs and fat. Return to the oven and cook until soft, 2-3 minutes. Scrape the fat from the cooked duck skin. Place onto a baking tray, then weigh down with another heavy baking tray to keep it flat. Return to the oven and cook for 4-5 minutes, or until crisp.
Season the duck breast with salt and freshly ground black pepper. Heat a frying pan until hot, add a little of the duck fat and add the duck breast. Cook on each side for 2-3 minutes or until cooked to your liking. Remove from the pan and leave to rest for 2-3 minutes. Keep warm.
To serve, place a duck leg into the centre of each of four plates. Carve the breasts into three pieces and place around the leg.
Place a piece of the crisp duck skin onto the pieces of duck breast. Using two spoons, form the chocolate ganache into oval-shaped quenelles and place one on top of each piece of crisp duck skin. Spoon the cherries and sauce around the duck, scatter over the lamb's cress and serve.


SEARCH BY A CITY NAME (e.g. los angeles) OR A COMMA-SEPARATED CITY NAME ALONG WITH THE COUNTRY CODE (e.g. los angeles,us)


Subscription is just another GraphQL operation type like Query and Mutation. It allows creating real-time subscriptions over a bidirectional transport layer, mainly over websockets. Read more about the subscriptions here.
Below is a commentAdded
subscription example, copied & pasted directly from the official Apollo documentation:
{{ subscriptionOfficialExample }}
Notice Thepubsub
is an instance ofPubSub
class. Read more about it here.
In order to create an equivalent subscription in Nest-way, we'll make use of the
@Subscription()
decorator. Let's extend our
AuthorResolver
used in the resolvers map section.
{{ resolversWithNames }}
We have used a local PubSub
instance here. Instead, we should define PubSub
as a provider, inject
it through the constructor (using @Inject()
decorator), and reuse it across the whole application.
You can read more about Nest custom providers here.
The last step is to update type definitions (read more) file.
author-types.graphql{{ typeDefs }}
Well done. We created a single commentAdded(repoFullName: String!): Comment
subscription. Additionally, we should create a web sockets server that emits and is subscribing to events, but to keep this example as simple as possible, we omitted this part. Nevertheless, you can find a full sample implementation here.


Cool, @cascadiaruby talk with my daughter got linked from #rubyweekly. Thanks @peterc! http://rubyweekly.com/issues/210
8/28/2014, 10:10:57 AM
Favs: 5
Retweets: 0
link--- layout: tweet ---
Cool, @cascadiaruby talk with my daughter got linked from #rubyweekly. Thanks @peterc! http://rubyweekly.com/issues/210
8/28/2014, 10:10:57 AM
Favs: 5
Retweets: 0
link


Notes 8.4.1
First-Hop (Default) Router - The router that the host is attached to.
Source Router - Default router of source host.
Destination Router - Default router of the destination host.
Shortest Path - Path between 2 nodes in a graph with fewest hops.
Least-Cost Path - Path between 2 nodes in a graph with lowest cost.
Global (Link-State) Routing Algorithm - Computes lowest-cost path between source & destination with global network knowledge.
Decentralized Routing Algorithm - Calculation of least-cost path is done in iterative, distributed manner.
Static Routing Algorithm - Route changes very slowly over time, usually as a result of human intervention.
Dynamic Routing Algorithm - Route changes as network traffic changes.
Load-Sensitive Algorithm - Link costs vary dynamically to reflect congestion.
Loas-Insensitive Algorithm - Link costs do not reflect congestion.
Link-State Broadcast - Each node broadcasts link-state packets containing IDs and costs of nearby nodes to all nodes on the network.
Distance-Vector Algorithm - Iterative, asynchronous, and distributed.
Routing Loop - A packet is routed through the same set of nodes repeatedly.
Autonomous Systems - A group of routers under the same administrative control, all running the same routing algorithm.
Intra-Autonomous System Routing Protocol - The algorithm running within an Autonomous System.
Gateway Routers - Routers that connect Autonomous Systems to other nodes.
Hot-Potato Routing - The Autonomous System gets rid of the packet as soon as possible.
Routing Information Protocol - Distance-Vector protocol with hop count as a cost metric.
RIP Response Message - A list of up to 25 destination subnets within the AS, sent every 30 seconds.
Open Shortest Path First - Link-State protocol that uses flooding of link-state info and a Dijkstra least-cost path algorithm.
Area Border Routers - Responsible for routing packets outside of an OSPF Area.
Backbone Area - One chosen OSPF Area to be the primary traffic routing area.
Border Gate Protocol - Standard inner-AS routing protocol.
BGP Peers - Two routers at the end of a BGP connection.
BGP Session - The messages sent over the connection.
Autonomous System Number - Unique ID for each AS so the BGP can tell them apart.
Import Policy - How a gateway decides to filter a route.


This component is the Wicket Autocomplete component with cache behavior added. The cache has a expiration time. Both the cache and its expiration time can be configured in AutoCompleteSettings.java through its setCacheDuration(int) method.
The ChoiceSearchBoxBehavior adds a search field which applies search criteria to a given AbstractChoice. Note: This behavior cannot be reused between components.
Here is an example using a ListChoise and passing some configuration parameters such as the mode and the button label.
The following example we use two DropDownChoice components bound together inside a Form.


Last week, in a Congressional hearing, Apple got grilled for its low-tax strategy. But not every business can copy that approach. Here is a look at what S.&P. 500 companies paid in corporate income taxes — federal, state, local and foreign — from 2007 to 2012, according to S&P Capital IQ.Related Article »
About one of every seven companies had an effective tax rate lower than 10 percent, including Amazon at 6 percent and Verizon at 9 percent. Nine companies paid no taxes at all.
Each circle represents a company, sized by its market capitalization. The largest is Apple, at more than $400 billion, with an effective tax rate of 14 percent.
Combining earnings and taxes for all S.&P. 500 companies gives an effective tax rate of 29.1 percent. But rates vary widely by industry.
Three big energy firms paid the most taxes in absolute terms: Exxon $146 billion; Chevron $85 billion; and ConocoPhillips $58 billion.
Effective tax rates cannot be computed for several dozen companies because they lost money over the six-year period. For example, A.I.G. lost $83 billion while paying $8 billion in taxes. These companies
are still included in overall tax rate calculations.
Apple
Effective tax rate14%
Taxes paid$4.3B
Earnings$16.2B
Note: For companies with positive earnings over the six-year period, the effective tax rate is defined as the sum of cash taxes paid divided by the sum of earnings before taxes including unusual items. Market
capitalization is as of April 8, 2013.
By MIKE BOSTOCK, MATTHEW ERICSON, DAVID LEONHARDT and BILL MARSH


| set_chr_encoding {rlang} | R Documentation |
R has specific support for UTF-8 and latin1 encoded strings. This
mostly matters for internal conversions. Thanks to this support,
you can reencode strings to UTF-8 or latin1 for internal
processing, and return these strings without having to convert them
back to the native encoding. However, it is important to make sure
the encoding mark has not been lost in the process, otherwise the
output will be treated as if encoded according to the current
locale (see mut_utf8_locale()
for documentation about locale
codesets), which is not appropriate if it does not coincide with
the actual encoding. In those situations, you can use these
functions to ensure an encoding mark in your strings.
set_chr_encoding(x, encoding = c("unknown", "UTF-8", "latin1", "bytes")) chr_encoding(x) set_str_encoding(x, encoding = c("unknown", "UTF-8", "latin1", "bytes")) str_encoding(x)
x |
A string or character vector. |
encoding |
Either an encoding specially handled by R
( |
These functions are experimental. They might be removed in the future because they don't bring anything new over the base API.
mut_utf8_locale()
about the effects of the locale, and
as_utf8_string()
about encoding conversion.
# Encoding marks are always ignored on ASCII strings: str_encoding(set_str_encoding("cafe", "UTF-8")) # You can specify the encoding of strings containing non-ASCII # characters: cafe <- string(c(0x63, 0x61, 0x66, 0xC3, 0xE9)) str_encoding(cafe) str_encoding(set_str_encoding(cafe, "UTF-8")) # It is important to consistently mark the encoding of strings # because R and other packages perform internal string conversions # all the time. Here is an example with the names attribute: latin1 <- string(c(0x63, 0x61, 0x66, 0xE9), "latin1") latin1 <- set_names(latin1) # The names attribute is encoded in latin1 as we would expect: str_encoding(names(latin1)) # However the names are converted to UTF-8 by the c() function: str_encoding(names(c(latin1))) as_bytes(names(c(latin1))) # Bad things happen when the encoding marker is lost and R performs # a conversion. R will assume that the string is encoded according # to the current locale: ## Not run: bad <- set_names(set_str_encoding(latin1, "unknown")) mut_utf8_locale() str_encoding(names(c(bad))) as_bytes(names(c(bad))) ## End(Not run)


Take control of your CSS keyframe animations
Health
Availability
Activity
Conventions and standards
jogwheel gives you the power to take full control of your CSS keyframe animations via JavaScript.
jogwheel is available on npm.
npm install --save jogwheel
:warning: Please note jogwheel assumes Element.prototype.animate
is defined and returns a valid WebAnimationPlayer instance.
To achieve this you will have to include a WebAnimation polyfill, web-animations-js by Google is recommended.
The usage examples show recommended ways to include the polyfill.
jogwheel exposes its API as CommonJS module. Using the export and bundling your JavaScript with browserify, webpack or rollup is recommended.
// import the polyfill
import 'web-animations-js';
// import JogWheel
import JogWheel from 'jogwheel';
// Select target element
const element = document.querySelector('[data-animated]');
// Construct JogWheel instance from element
const player = JogWheel.create(element);
// Jump halfway into the animation
player.seek(0.5);
jogwheel provides prebundled downloads via brcdn.org.
Either embed or download the standalone bundle. Given you do not use a module system the standalone build will pollute window.jogwheel
. This usage is viable but not recommended.
<!doctype html>
<html>
<head>
<title>CDN example</title>
</head>
<style>
@keframes bounce {
0% {
transform: none;
}
25% {
transform: translateY(-100%);
}
50% {
transform: none;
}
75% {
transform: translateY(100%);
}
100% {
transform: none;
}
}
[data-animated] {
animation: bounce 1s;
animation-fill-mode: both;
animation-play-state: paused;
height: 100px;
width: 100px;
background: #333;
border-radius: 50%;
}
</style>
<body>
<div data-animated></div>
<script src="https://www.brcdn.org/web-animations-js/latest/?standalone=web-animations-js&uglify=true" /></script>
</body>
</html>
See API Documentation for details.
jogwheel shines brightest when used with CSS animations.
JavaScript
import JogWheel from 'jogwheel';
const element = document.querySelector('[data-animated]');
const player = JogWheel.create(element);
// Jump halfway into the animation
player.seek(0.5);
CSS
@keframes bounce {
0% {
transform: none;
}
25% {
transform: translateY(-100%);
}
50% {
transform: none;
}
75% {
transform: translateY(100%);
}
100% {
transform: none;
}
}
[data-animated] {
animation: bounce 1s;
/* animation-fill-mode and animation-play-state are recommended */
animation-fill-mode: both;
animation-play-state: paused;
height: 100px;
width: 100px;
background: #333;
border-radius: 50%;
}
HTML
<div data-animated>
</div>
See Examples for more use cases.
jogwheel performs cross browser testing with SauceLabs
You dig jogwheel and want to submit a pull request? Awesome! Be sure to read the contribution guide and you should be good to go. Here are some notes to get you coding real quick.
Fetch, install and start the default watch task
git clone https://github.com/marionebl/jogwheel.git
cd jogwheel
npm install
npm start
This will watch all files in source
and start the appropriate tasks when changes are detected.
jogwheel is up to a lot of good. This includes but is not limited to
See Roadmap for details.
jogwheel v1.3.0
is built by Mario Nebl and contributors with :heart:
and released under the MIT License.


Site may go down in {{contest_ends_in}} seconds
| Problem |
Author |
Time |
Memory |
Status |
| ADD |
Wasim |
0.03secs |
2MB |
{{vADD}} |
| STR |
Prashanth |
0.02secs |
1.5MB |
{{vSTR}} |
| EON |
Wasim |
0.01secs |
800B |
{{vEON}} |
| DBY |
Prashanth |
2.00 |
100B |
{{vDBY}} |
| RUPQ |
Mike and Wasim |
0.05secs |
256MB |
{{vRUPQ}} |


humidity_sht
SHTxx, for Sensirion humidity and temperature sensors
|
Author
|
Eur van Andel<EMAIL_ADDRESS>Copyright © 2008
|
|
Adapted-by
|
|
|
Compiler
|
=2.4h
|
Description
The Sensirion SHT1x/SHT7x is a single chip relative humidity and
temperature multi sensor module comprising a calibrated digital output.
It comes in 5 flavors, with different accuracy and package style:
sensor hum acc temp acc package
SHT10 4.5% 0.5C SMD (LCC)
SHT11 3.0% 0.4C SMD (LCC)
SHT15 2.0% 0.3C SMD (LCC)
SHT71 3.0% 0.4C 4-pin single-in-line
SHT75 1.8% 0.3C 4-pin single-in-line
all consist of the same silicon: the less accurate models are sold cheaper.
My experience is mixed: I've seen some consistent +2C offset in temperature,
but good humidty measurements. The 4-pin package breaks when you touch it.
The SMD package has naked tracks underneath: you can't route under it!
If exposed to >95% RH for 10 minutes, these sensors will go beserk and need
<60% RH for an hour to recover. You might try heating them.
protocol is close to I2C, but not the same. Remember to pull up DATA.
0b0000_0011 starts temperature measurement
0b0000_0101 starts humidity measurement
device returns three bytes: MSB, LSB and CRC
this library doesn't perform any CRC check
Sources
http://www.sensirion.com/en/01_humidity_sensors/00_humidity_sensors.htm
Dependencies
-
read_raw_hum_sht(byte out MSB, byte out LSB, byte out CRC)
read raw 12-bit humidity from SHT
default value of resolution bit is 12 bit RH
SHT takes 55 ms for measurement @ 12 bits
we will wait 70 ms
SHT may only be switched on for 10% of the time because of self-heating
so this measurement can only happen every 500ms
-
read_hum_word_sht(word out hum)
read humidity from SHT, result in word precision 0.01%RH
SHT may only be switched on for 10% of the time because of self-heating
so this measurement can only happen every 500ms
-
sht_get_data(byte out x)
receive one byte from the SHT
-
sht_start()
send start
_____ ________
DATA: |_______|
___ ___
SCK : ___| |___| |______
-
sht_put_ack()
send ACK
-
sht_conn_reset()
reset SHT interface, must be followed with sht_start and command
-
sht_wait_ack()
pretend to wait for ACK
-
sht_reset()
reset SHT
-
read_centicelsius_temp_sht(sword out centicelsius)
read Celcius temperature from SHT
with 0.01 C resolution, result is sword type, so -327.68 .. +327.68 C
SHT takes 320 ms for measurement @ 14 bits
we will wait 400 ms
SHT may only be switched on for 10% of the time because of self-heating
so this measurement can only happen every four seconds!
-
sht_put_data(byte in x)
send one byte to the SHT
-
read_celsius_temp_sht(sbyte out celsius)
read Celcius temperature from SHT
with 1 C resolution, result is sbyte type, so -126...+127C
SHT takes 320 ms for measurement @ 14 bits
we will wait 400 ms
SHT may only be switched on for 10% of the time because of self-heating
so this measurement can only happen every four seconds!
-
read_hum_sht(byte out hum)
read humidity from SHT, result in byte precision 1%RH
SHT may only be switched on for 10% of the time because of self-heating
so this measurement can only happen every 500ms
-
read_raw_temp_sht(byte out MSB, byte out LSB, byte out CRC)
read raw 14-bit temperature from SHT
default value of resolution bit is 14 bit temperature
SHT takes 320 ms for measurement @ 14 bits
we will wait 400 ms
SHT may only be switched on for 10% of the time because of self-heating
so this measurement can only happen every two seconds!
Here are the list of samples which use this library:


{% extends load_base %} {% load i18n %} {% block javascript %} {% endblock %} {% block base_content %}{% trans "Pending" as pending %}{% trans "Pre-Order" as preorder %}
{% blocktrans %}Our images have firewall enabled by default. Check you firewall settings.{% endblocktrans %}
{% blocktrans %}Please contact our support in order to check and allow API access for your user account. Also please make sure that you are using a valid username and password or API key.{% endblocktrans %}
{% blocktrans %}Generated key that can be used instead of user/password authentication.{% endblocktrans %}
{% blocktrans %}Generated key which is used to verify, if callback response is from our servers.{% endblocktrans %}
{% blocktrans %}The callback response will contain a random token and a verification string. You should generate your own verification sting by attaching the callback key after the random token and create an MD5 hash from the string. If your MD5 hash matches the verification string you can be sure the callback came from our servers.{% endblocktrans %}
{% blocktrans %}Unfortunately this feature is not built in the GUI yet, but we do support custom ISO images. Please create a support request via our support section.{% endblocktrans %}
{% blocktrans %}Monitoring and more accurate VM resource graphs can be turned on by enabling a monitoring agent, which is preconfigured in our VM disk images.{% endblocktrans %}
{% blocktrans %}This can be accomplished by running these commands as root:
* RHEL, CentOS, Scientific Linux: chkconfig zabbix-agent on && service zabbix-agent start
* Debian, Ubuntu: update-rc.d zabbix-agent defaults && service zabbix-agent start
{% endblocktrans %}
{% blocktrans %}Our anti-spoofing protection allows only assigned IPv4 addresses to originate from the network interface. We do not support IPv6 at this point, which we hope to support in the near future. However, IPv6 is enabled by default in our images as disabling it will break some applications.{% endblocktrans %}


Introduction
Many papers in statistics and quantitative finance make heavy use of linear algebra, so you need to have a working knowledge of it in order to read and apply them to your trading.
Vectors
A vector can be thought of as an arrow pointing from the origin to a specific point. Any vector or point can be represented by its coordinates i.e. an array of numbers, such as \((x,y)\) for a 2-dimensional vector, or \((x,y,z)\) for a 3-dimensional one. We usually write a vector as a column:
\[ \bm{v} = \begin{pmatrix}
x \\ y \\ z
\end{pmatrix} \]
The scalar product of two vectors \( \bm{x} \) and \( \bm{y} \) in 2-dimensional space is defined as:
\[ \bm{x}^T \bm{y} = \begin{pmatrix} x_1 & x_2 \end{pmatrix} \begin{pmatrix} y_1 & y_2 \end{pmatrix} = x_1 y_1 + x_2 y_2 \]
This definition can be easily generalized to n dimensional space. Clearly, we cannot take the scalar product of two vectors with different dimensions.
Matrices
If we have a few vectors \( \bm{v}_1, \bm{v}_2, \dots, \bm{v}_n\) with the same dimension, then we can put them side-by-side to form a matrix. For example, the vectors
\[ v_1 = \begin{pmatrix} 1 \\ 2 \\ 3 \end{pmatrix} \qquad
v_2 = \begin{pmatrix} 2 \\ 2 \\ 2 \end{pmatrix} \qquad
v_3 = \begin{pmatrix} 3 \\ 1 \\ 1 \end{pmatrix} \]
can be combined to produce a matrix:
\[ m = \begin{pmatrix}
1 & 2 & 3 \\
2 & 2 & 2 \\
3 & 1 & 1
\end{pmatrix} \]
m is a 3 × 3 matrix. We typically describe the dimensions of a matrix as \(m \times n\) where m = number of rows and n = number of columns.
A square matrix is one with as many rows as columns.
Notation: \(x_{ij}\) refers to a specific value in row \(i\) and column \(j\) of a matrix \(X\). For example, \(x_{23}\) is the number in the second row and third column of \(X\).
Python Implementation
In Python, the NumPy package deals with linear algebra. The array we learned in the NumPy chapter can be deemed as a vector:
import numpy as np
a = np.array([1,2,3])
b = np.array([2,2,2])
c = np.array([3,1,1])
matrix = np.column_stack((a,b,c))
print matrix
print type(matrix)
[out]:
[[1 2 3]
[2 2 1]
[3 2 1]]
It is worth noticing that we used column_stack() here to ensure that the vectors are vertical and placed side-by-side to form a matrix. Without the column_stack() function, the vectors will be made horizontal and stacked on top of one another:
matrix2 = np.array([a,b,c])
print matrix2
[out]:
[[1 2 3]
[2 2 2]
[3 1 1]]
Matrix Multiplication
How are two matrices multiplied? Suppose \(X = AB\). Each entry \(x_{ij}\) of matrix \(X\) is the scalar product of row \(i\) from matrix \(A\) with column \(j\) from matrix \(B\). This is best illustrated with an example:
\[ AB = \begin{pmatrix}
a_{11} & a_{12} \\
a_{21} & a_{22} \\
a_{31} & a_{32}
\end{pmatrix}
\begin{pmatrix}
b_{11} & b_{12} \\
b_{21} & b_{22}
\end{pmatrix} = \begin{pmatrix}
x_{11} & x_{12} \\
x_{21} & x_{22} \\
x_{31} & x_{32}
\end{pmatrix} \]
Then
\[ x_{11} = a_{11} b_{11} + a_{12} b_{12} \]
\[ x_{12} = a_{11} b_{12} + a_{12} b_{22} \]
\[ x_{21} = a_{21} b_{11} + a_{21} b_{21} \]
\[ x_{22} = a_{21} b_{12} + a_{22} b_{22} \]
\[ \vdots \]
In NumPy, we can multiply matrices with the dot() function:
A = np.array([[2,3],[4,2],[2,2]])
B = np.array([[4,2],[4,6]])
x = np.dot(A,B)
print x
[out]:
[[20 22]
[24 20]
[16 16]]
Since matrix multiplication is defined in terms of scalar products, the matrix product \(AB\) exists only if \(A\) has as many columns as \(B\) has rows. It's useful to remember this shorthand: (m × n) × (n × p) = (m × p) which means that an (m × n) matrix multiplied by an (n × p) matrix yields an (m × p) matrix.
Reversing the order of multiplication results in an error since B does not have as many columns as A has rows:
x = np.dot(B,A)
A natrual consequence of this fact is that matrix multiplication is not commutative. In other words, \(AB \neq BA\) in general.
Inverse
An identity matrix is a square matrix with ones on the main diagonal and zeros elsewhere. Here is an \(n \times n\) identity matrix:
\[ I_n = \begin{pmatrix}
1 & 0 & 0 & ... & 0 \\
0 & 1 & 0 & ... & 0 \\
0 & 0 & 1 & ... & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
0 & 0 & 0 & ... & 1
\end{pmatrix} \]
Multiplying any matrix by an identity matrix (of the correct shape) is like multiplying a number by 1. Concretely, if \(A\) is an \(m \times n\) matrix, then:
\[ I_mA = AI_n = A \]
\( A^{-1} \) is the inverse matrix of a square matrix \(A\) if:
\[ AA^{-1} = I = A^{-1}A \]
Some caveats:
- A rectangular matrix will not have an inverse, but it may have a pseudoinverse (not covered in this tutorial).
- A square matrix may not have an inverse i.e. it may be "singular".
- If a square matrix has an inverse, then its inverse is unique.
Inverse matrices are computed using the Gauss-Jordan method. In NumPy, we use the linalg.inv() function to do it:
print matrix
print '\n-------------------------\n'
print np.linalg.inv(matrix)
[out]:
[[1 2 3]
[2 2 1]
[3 2 1]]
-------------------------
[[ 0. -1. 1. ]
[-0.25 2. -1.25]
[ 0.5 -1. 0.5 ]]
Now let's check if the multiplication is \(I\):
inverse = np.linalg.inv(matrix)
print np.dot(matrix, inverse)
print '\n-------------------------\n'
print np.dot(inverse,matrix)
[out]:
[[ 1.00000000e+00 -6.66133815e-16 6.66133815e-16]
[ 0.00000000e+00 1.00000000e+00 1.11022302e-16]
[ 0.00000000e+00 -2.22044605e-16 1.00000000e+00]]
-------------------------
[[ 1.00000000e+00 -4.44089210e-16 -2.22044605e-16]
[ 6.66133815e-16 1.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00 1.00000000e+00]]
Not surprisingly, we ended up with an identity matrix. We can form a non-invertible matrix by making one of its rows a multiple of another:
singular = np.array([[1,2,3],[1,2,3],[3,3,3]])
inv = np.linalg.inv(singular)
[out]: numpy.linalg.linalg.LinAlgError: Singular matrix
Linear Equations
A common problem in linear algebra is solving linear equations. Consider the following linear equations:
\[ 2x + y - z = 8 \]
\[ -3x - y + 2z = -11 \]
\[ -2x + y + 2z = -3 \]
If we let:
\[ A = \begin{pmatrix}
2 & 1 & -1 \\
-3 & -1 & 2 \\
-2 & 1 & 2
\end{pmatrix} \]
and
\[ \bm{x} = \begin{pmatrix} x \\ y \\ z \end{pmatrix} \qquad
\bm{b} = \begin{pmatrix} 8 \\ -11 \\ -3 \end{pmatrix} \]
Then the linear equations above can be written as \( A\bm{x} = \bm{b} \)
If A is invertible, then we can multiply \(A^{-1}\) on both sides of the equation to obtain the solution:
\[ A^{-1}A \bm{x} = A^{-1}\bm{b} \]
Hence
\[ \bm{x} = A^{-1}\bm{b} \]
As long as \(A^{-1}\) exists, we can compute it to solve the linear equations:
A = np.array([[2,1,-1],[-3,-1,2],[-2,1,2]])
b = np.array([[8],[-11],[-3]])
inv_A = np.linalg.inv(A)
print np.dot(inv_A, b)
[out]:
[[ 2.]
[ 3.]
[-1.]]
The solution is x = 2, y = 3, z = −1. However, computing the inverse matrix is not recommended, since it is numerically unstable i.e. small rounding errors can dramatically affect the result.
Instead, NumPy solves linear equations by LU decomposition:
print np.linalg.solve(A, b)
[out]:
[[ 2.]
[ 3.]
[-1.]]
Of course, we get the same solution. We can check the correctness of the solution by substituting x, y and z into the linear equations.
Summary
In this chapter we have introduced vectors, matrices, inverse matrices and linear equations. Some applications in finance include: finding arbitrage opportunities by solving linear equations, computing portfolio variance, etc. In the next chapter, we will introduce modern portfolio theory and CAPM.


Travel
问题描述 :
PP loves travel. Her dream is to travel around country A which consists of N cities and M roads connecting them. PP has measured the money each road costs. But she still has one more problem: she doesn’t have enough money. So she must work during her travel. She has chosen some cities that she must visit and stay to work. In City_i she can do some work to earn Ci money, but before that she has to pay Di money to get the work license. She can’t work in that city if she doesn’t get the license but she can go through the city without license. In each chosen city, PP can only earn money and get license once. In other cities, she will not earn or pay money so that you can consider Ci=Di=0. Please help her make a plan to visit all chosen cities and get license in all of them under all rules above.
PP lives in city 1, and she will start her journey from city 1. and end her journey at city 1 too.
PP lives in city 1, and she will start her journey from city 1. and end her journey at city 1 too.
输入:
The first line of input consists of one integer T which means T cases will follow.
Then follows T cases, each of which begins with three integers: the number of cities N (N <= 100) , number of roads M (M <= 5000) and her initiative money Money (Money <= 10^5) .
Then follows M lines. Each contains three integers u, v, w, which means there is a road between city u and city v and the cost is w. u and v are between 1 and N (inclusive), w <= 10^5.
Then follows a integer H (H <= 15) , which is the number of chosen cities.
Then follows H lines. Each contains three integers Num, Ci, Di, which means the i_th chosen city number and Ci, Di described above.(Ci, Di <= 10^5)
Then follows T cases, each of which begins with three integers: the number of cities N (N <= 100) , number of roads M (M <= 5000) and her initiative money Money (Money <= 10^5) .
Then follows M lines. Each contains three integers u, v, w, which means there is a road between city u and city v and the cost is w. u and v are between 1 and N (inclusive), w <= 10^5.
Then follows a integer H (H <= 15) , which is the number of chosen cities.
Then follows H lines. Each contains three integers Num, Ci, Di, which means the i_th chosen city number and Ci, Di described above.(Ci, Di <= 10^5)
输出:
The first line of input consists of one integer T which means T cases will follow.
Then follows T cases, each of which begins with three integers: the number of cities N (N <= 100) , number of roads M (M <= 5000) and her initiative money Money (Money <= 10^5) .
Then follows M lines. Each contains three integers u, v, w, which means there is a road between city u and city v and the cost is w. u and v are between 1 and N (inclusive), w <= 10^5.
Then follows a integer H (H <= 15) , which is the number of chosen cities.
Then follows H lines. Each contains three integers Num, Ci, Di, which means the i_th chosen city number and Ci, Di described above.(Ci, Di <= 10^5)
Then follows T cases, each of which begins with three integers: the number of cities N (N <= 100) , number of roads M (M <= 5000) and her initiative money Money (Money <= 10^5) .
Then follows M lines. Each contains three integers u, v, w, which means there is a road between city u and city v and the cost is w. u and v are between 1 and N (inclusive), w <= 10^5.
Then follows a integer H (H <= 15) , which is the number of chosen cities.
Then follows H lines. Each contains three integers Num, Ci, Di, which means the i_th chosen city number and Ci, Di described above.(Ci, Di <= 10^5)
样例输入:
2 4 5 10 1 2 1 2 3 2 1 3 2 1 4 1 3 4 2 3 1 8 5 2 5 2 3 10 1 2 1 100 1 2 10000 1 2 100000 1
样例输出:
YES NO
转载请注明出处，谢谢http://blog.csdn.net/acm_cxlove/article/details/7854526
by—cxlove
题目：给出一些城市，从1出发，旅游一圈回到1，由于花费可能不够，所以选择一些城市打工，打工之前需要花费d买一个证，工资为c。选中的城市必须去工作一次，而且只能工作一次，问能不能完成旅行
http://acm.hdu.edu.cn/showproblem.php?pid=4284
比赛的时候，卡了很久，当时队友用SPFA+状态DP+堆栈写的，主要是把一点考虑错了
当时把C和D合并了，其实是不对的，因为首先是要购买证，然后才能工作，否则拿不到工资。
也就是先要判断够不够买证的钱D，然后才能拿到工资。
跪舔，先用Floyd预处理最短路n^3，然后状态DP，h*h*2^h，4S+,效率很低的做法
可以用队列，堆栈加速
#include<iostream> #include<cstdio> #include<map> #include<cstring> #define inf 1<<28 #define N 105 #define Min(a,b) ((a)<(b)?(a):(b)) #define Max(a,b) ((a)>(b)?(a):(b)) using namespace std; int n,m,money,h; int path[N][N]; int dp[20][1<<16]; int work[20],c[20],d[20]; int main(){ int t; scanf("%d",&t); while(t--){ scanf("%d%d%d",&n,&m,&money); for(int i=0;i<n;i++){ for(int j=0;j<n;j++) path[i][j]=inf; path[i][i]=0; } for(int i=0;i<m;i++){ int u,v,w; scanf("%d%d%d",&u,&v,&w); u--;v--; path[u][v]=Min(path[u][v],w); path[v][u]=path[u][v]; } //Floyd预处理 for(int k=0;k<n;k++) for(int i=0;i<n;i++) for(int j=0;j<n;j++) if(i!=k&&i!=j&&j!=k) path[i][j]=Min(path[i][k]+path[k][j],path[i][j]); scanf("%d",&h); int pos=-1; for(int i=0;i<h;i++){ scanf("%d%d%d",&work[i],&c[i],&d[i]); work[i]--; if(work[i]==0) pos=i; //说明必需点中包含了起点1 } //如果不包含，我们加入冗余点，便于后面处理，c和d都为0 if(pos==-1){ work[h]=0;c[h]=0;d[h]=0; pos=h++; } memset(dp,-1,sizeof(dp)); if(money-d[pos]>=0) dp[pos][1<<pos]=money-d[pos]+c[pos];dp[pos][0]=money; for(int i=0;i<(1<<h);i++){ for(int j=0;j<h;j++){ if(dp[j][i]==-1) continue; for(int k=0;k<h;k++){ if(k==j||((1<<k)&i)) continue; //钱够在两个城市之间移动，而且够买证 if(dp[j][i]>=path[work[j]][work[k]]+d[k]) dp[k][i|(1<<k)]=Max(dp[k][i|(1<<k)],dp[j][i]-path[work[j]][work[k]]-d[k]+c[k]); } } } bool ans=false; for(int i=0;i<h;i++) //最后判断能不能返回起点 if(dp[i][(1<<h)-1]>=path[work[i]][0]){ ans=true; break; } puts(ans?"YES":"NO"); } return 0; }
版权声明：本文为博主原创文章，未经博主允许不得转载。
参考：http://blog.csdn.net/acm_cxlove/article/details/7963286
(adsbygoogle = window.adsbygoogle || []).push({});
我看到了老谋子
民风淳朴，社会和谐。看的黄瓜一紧