convlab.agent.algorithm package¶
Submodules¶
convlab.agent.algorithm.actor_critic module¶
-
class
convlab.agent.algorithm.actor_critic.
ActorCritic
(agent, global_nets=None)[source]¶ Bases:
convlab.agent.algorithm.reinforce.Reinforce
Implementation of single threaded Advantage Actor Critic Original paper: “Asynchronous Methods for Deep Reinforcement Learning” https://arxiv.org/abs/1602.01783 Algorithm specific spec param: memory.name: batch (through OnPolicyBatchReplay memory class) or episodic through (OnPolicyReplay memory class) lam: if not null, used as the lambda value of generalized advantage estimation (GAE) introduced in “High-Dimensional Continuous Control Using Generalized Advantage Estimation https://arxiv.org/abs/1506.02438. This lambda controls the bias variance tradeoff for GAE. Floating point value between 0 and 1. Lower values correspond to more bias, less variance. Higher values to more variance, less bias. Algorithm becomes A2C(GAE). num_step_returns: if lam is null and this is not null, specifies the number of steps for N-step returns from “Asynchronous Methods for Deep Reinforcement Learning”. The algorithm becomes A2C(Nstep). If both lam and num_step_returns are null, use the default TD error. Then the algorithm stays as AC. net.type: whether the actor and critic should share params (e.g. through ‘MLPNetShared’) or have separate params (e.g. through ‘MLPNetSeparate’). If param sharing is used then there is also the option to control the weight given to the policy and value components of the loss function through ‘policy_loss_coef’ and ‘val_loss_coef’ Algorithm - separate actor and critic:
- Repeat:
- Collect k examples
- Train the critic network using these examples
- Calculate the advantage of each example using the critic
- Multiply the advantage by the negative of log probability of the action taken, and sum all the values. This is the policy loss.
- Calculate the gradient the parameters of the actor network with respect to the policy loss
- Update the actor network parameters using the gradient
- Algorithm - shared parameters:
- Repeat:
- Collect k examples
- Calculate the target for each example for the critic
- Compute current estimate of state-value for each example using the critic
- Calculate the critic loss using a regression loss (e.g. square loss) between the target and estimate of the state-value for each example
- Calculate the advantage of each example using the rewards and critic
- Multiply the advantage by the negative of log probability of the action taken, and sum all the values. This is the policy loss.
- Compute the total loss by summing the value and policy lossses
- Calculate the gradient of the parameters of shared network with respect to the total loss
- Update the shared network parameters using the gradient
e.g. algorithm_spec “algorithm”: {
“name”: “ActorCritic”, “action_pdtype”: “default”, “action_policy”: “default”, “explore_var_spec”: null, “gamma”: 0.99, “lam”: 1.0, “num_step_returns”: 100, “entropy_coef_spec”: {
“name”: “linear_decay”, “start_val”: 0.01, “end_val”: 0.001, “start_step”: 100, “end_step”: 5000,}, “policy_loss_coef”: 1.0, “val_loss_coef”: 0.01, “training_frequency”: 1,
}
e.g. special net_spec param “shared” to share/separate Actor/Critic “net”: {
“type”: “MLPNet”, “shared”: true, …-
calc_gae_advs_v_targets
(batch, v_preds)[source]¶ Calculate GAE, and advs = GAE, v_targets = advs + v_preds See GAE from Schulman et al. https://arxiv.org/pdf/1506.02438.pdf
-
calc_nstep_advs_v_targets
(batch, v_preds)[source]¶ Calculate N-step returns, and advs = nstep_rets - v_preds, v_targets = nstep_rets See n-step advantage under http://rail.eecs.berkeley.edu/deeprlcourse-fa17/f17docs/lecture_5_actor_critic_pdf.pdf
-
calc_pdparam
(x, net=None)[source]¶ The pdparam will be the logits for discrete prob. dist., or the mean and std for continuous prob. dist.
-
calc_pdparam_v
(batch)[source]¶ Efficiently forward to get pdparam and v by batch for loss computation
-
calc_ret_advs_v_targets
(batch, v_preds)[source]¶ Calculate plain returns, and advs = rets - v_preds, v_targets = rets
-
calc_v
(x, net=None, use_cache=True)[source]¶ Forward-pass to calculate the predicted state-value from critic_net.
-
init_nets
(global_nets=None)[source]¶ Initialize the neural networks used to learn the actor and critic from the spec Below we automatically select an appropriate net based on two different conditions 1. If the action space is discrete or continuous action
- Networks for continuous action spaces have two heads and return two values, the first is a tensor containing the mean of the action policy, the second is a tensor containing the std deviation of the action policy. The distribution is assumed to be a Gaussian (Normal) distribution.
- Networks for discrete action spaces have a single head and return the logits for a categorical probability distribution over the discrete actions
- If the actor and critic are separate or share weights
- If the networks share weights then the single network returns a list.
- Continuous action spaces: The return list contains 3 elements: The first element contains the mean output for the actor (policy), the second element the std dev of the policy, and the third element is the state-value estimated by the network.
- Discrete action spaces: The return list contains 2 element. The first element is a tensor containing the logits for a categorical probability distribution over the actions. The second element contains the state-value estimated by the network.
- If the network type is feedforward, convolutional, or recurrent
- Feedforward and convolutional networks take a single state as input and require an OnPolicyReplay or OnPolicyBatchReplay memory
- Recurrent networks take n states as input and require env spec “frame_op”: “concat”, “frame_op_len”: seq_len
convlab.agent.algorithm.base module¶
-
class
convlab.agent.algorithm.base.
Algorithm
(agent, global_nets=None)[source]¶ Bases:
abc.ABC
Abstract class ancestor to all Algorithms, specifies the necessary design blueprint for agent to work in Lab. Mostly, implement just the abstract methods and properties.
-
calc_pdparam
(x, evaluate=True, net=None)[source]¶ To get the pdparam for action policy sampling, do a forward pass of the appropriate net, and pick the correct outputs. The pdparam will be the logits for discrete prob. dist., or the mean and std for continuous prob. dist.
-
nanflat_to_data_a
(data_name, nanflat_data_a)[source]¶ Reshape nanflat_data_a, e.g. action_a, from a single pass back into the API-conforming data_a
-
post_init_nets
()[source]¶ Method to conditionally load models. Call at the end of init_nets() after setting self.net_names
-
convlab.agent.algorithm.dqn module¶
-
class
convlab.agent.algorithm.dqn.
DQN
(agent, global_nets=None)[source]¶ Bases:
convlab.agent.algorithm.dqn.DQNBase
DQN class
e.g. algorithm_spec “algorithm”: {
“name”: “DQN”, “action_pdtype”: “Argmax”, “action_policy”: “epsilon_greedy”, “explore_var_spec”: {
“name”: “linear_decay”, “start_val”: 1.0, “end_val”: 0.1, “start_step”: 10, “end_step”: 1000,}, “gamma”: 0.99, “training_batch_iter”: 8, “training_iter”: 4, “training_frequency”: 10, “training_start_step”: 10
}
-
class
convlab.agent.algorithm.dqn.
DQNBase
(agent, global_nets=None)[source]¶ Bases:
convlab.agent.algorithm.dqn.VanillaDQN
Implementation of the base DQN algorithm. The algorithm follows the same general approach as VanillaDQN but is more general since it allows for two different networks (through self.net and self.target_net).
self.net is used to act, and is the network trained. self.target_net is used to estimate the maximum value of the Q-function in the next state when calculating the target (see VanillaDQN comments). self.target_net is updated periodically to either match self.net (self.net.update_type = “replace”) or to be a weighted average of self.net and the previous self.target_net (self.net.update_type = “polyak”) If desired, self.target_net can be updated slowly, and this can help to stabilize learning.
It also allows for different nets to be used to select the action in the next state and to evaluate the value of that action through self.online_net and self.eval_net. This can help reduce the tendency of DQN’s to overestimate the value of the Q-function. Following this approach leads to the DoubleDQN algorithm.
Setting all nets to self.net reduces to the VanillaDQN case.
-
class
convlab.agent.algorithm.dqn.
DoubleDQN
(agent, global_nets=None)[source]¶ Bases:
convlab.agent.algorithm.dqn.DQN
Double-DQN (DDQN) class
e.g. algorithm_spec “algorithm”: {
“name”: “DDQN”, “action_pdtype”: “Argmax”, “action_policy”: “epsilon_greedy”, “explore_var_spec”: {
“name”: “linear_decay”, “start_val”: 1.0, “end_val”: 0.1, “start_step”: 10, “end_step”: 1000,}, “gamma”: 0.99, “training_batch_iter”: 8, “training_iter”: 4, “training_frequency”: 10, “training_start_step”: 10
}
-
class
convlab.agent.algorithm.dqn.
VanillaDQN
(agent, global_nets=None)[source]¶ Bases:
convlab.agent.algorithm.sarsa.SARSA
Implementation of a simple DQN algorithm. Algorithm:
- Collect some examples by acting in the environment and store them in a replay memory
- Every K steps sample N examples from replay memory
- For each example calculate the target (bootstrapped estimate of the discounted value of the state and action taken), y, using a neural network to approximate the Q function. s’ is the next state following the action actually taken.
- y_t = r_t + gamma * argmax_a Q(s_t’, a)
- For each example calculate the current estimate of the discounted value of the state and action taken
- x_t = Q(s_t, a_t)
- Calculate L(x, y) where L is a regression loss (eg. mse)
- Calculate the gradient of L with respect to all the parameters in the network and update the network parameters using the gradient
- Repeat steps 3 - 6 M times
- Repeat steps 2 - 7 Z times
- Repeat steps 1 - 8
For more information on Q-Learning see Sergey Levine’s lectures 6 and 7 from CS294-112 Fall 2017 https://www.youtube.com/playlist?list=PLkFD6_40KJIznC9CDbVTjAF2oyt8_VAe3
e.g. algorithm_spec “algorithm”: {
“name”: “VanillaDQN”, “action_pdtype”: “Argmax”, “action_policy”: “epsilon_greedy”, “explore_var_spec”: {
“name”: “linear_decay”, “start_val”: 1.0, “end_val”: 0.1, “start_step”: 10, “end_step”: 1000,}, “gamma”: 0.99, “training_batch_iter”: 8, “training_iter”: 4, “training_frequency”: 10, “training_start_step”: 10,
}
-
calc_q_loss
(batch)[source]¶ Compute the Q value loss using predicted and target Q values from the appropriate networks
-
init_nets
(global_nets=None)[source]¶ Initialize the neural network used to learn the Q function from the spec
-
train
()[source]¶ Completes one training step for the agent if it is time to train. i.e. the environment timestep is greater than the minimum training timestep and a multiple of the training_frequency. Each training step consists of sampling n batches from the agent’s memory. For each of the batches, the target Q values (q_targets) are computed and a single training step is taken k times Otherwise this function does nothing.
-
class
convlab.agent.algorithm.dqn.
WarmUpDQN
(agent, global_nets=None)[source]¶ Bases:
convlab.agent.algorithm.dqn.DQN
DQN class
e.g. algorithm_spec “algorithm”: {
“name”: “WarmUpDQN”, “action_pdtype”: “Argmax”, “action_policy”: “epsilon_greedy”, “warmup_epi”: 300, “explore_var_spec”: {
“name”: “linear_decay”, “start_val”: 1.0, “end_val”: 0.1, “start_step”: 10, “end_step”: 1000,}, “gamma”: 0.99, “training_batch_iter”: 8, “training_iter”: 4, “training_frequency”: 10, “training_start_step”: 10
}
-
train
()[source]¶ Completes one training step for the agent if it is time to train. i.e. the environment timestep is greater than the minimum training timestep and a multiple of the training_frequency. Each training step consists of sampling n batches from the agent’s memory. For each of the batches, the target Q values (q_targets) are computed and a single training step is taken k times Otherwise this function does nothing.
-
convlab.agent.algorithm.external module¶
The random agent algorithm For basic dev purpose.
-
class
convlab.agent.algorithm.external.
ExternalPolicy
(agent, global_nets=None)[source]¶ Bases:
convlab.agent.algorithm.base.Algorithm
Example Random agent that works in both discrete and continuous envs
convlab.agent.algorithm.policy_util module¶
-
class
convlab.agent.algorithm.policy_util.
VarScheduler
(var_decay_spec=None)[source]¶ Bases:
object
Variable scheduler for decaying variables such as explore_var (epsilon, tau) and entropy
e.g. spec “explore_var_spec”: {
“name”: “linear_decay”, “start_val”: 1.0, “end_val”: 0.1, “start_step”: 0, “end_step”: 800,},
-
convlab.agent.algorithm.policy_util.
boltzmann
(state, algorithm, body)[source]¶ Boltzmann policy: adjust pdparam with temperature tau; the higher the more randomness/noise in action.
-
convlab.agent.algorithm.policy_util.
calc_pdparam
(state, algorithm, body)[source]¶ Prepare the state and run algorithm.calc_pdparam to get pdparam for action_pd @param tensor:state For pdparam = net(state) @param algorithm The algorithm containing self.net @param body Body which links algorithm to the env which the action is for @returns tensor:pdparam @example
pdparam = calc_pdparam(state, algorithm, body) action_pd = ActionPD(logits=pdparam) # e.g. ActionPD is Categorical action = action_pd.sample()
-
convlab.agent.algorithm.policy_util.
default
(state, algorithm, body)[source]¶ Plain policy by direct sampling from a default action probability defined by body.ActionPD
-
convlab.agent.algorithm.policy_util.
epsilon_greedy
(state, algorithm, body)[source]¶ Epsilon-greedy policy: with probability epsilon, do random action, otherwise do default sampling.
-
convlab.agent.algorithm.policy_util.
get_action_pd_cls
(action_pdtype, action_type)[source]¶ Verify and get the action prob. distribution class for construction Called by body at init to set its own ActionPD
-
convlab.agent.algorithm.policy_util.
get_action_type
(action_space)[source]¶ Method to get the action type to choose prob. dist. to sample actions from NN logits output
-
convlab.agent.algorithm.policy_util.
guard_tensor
(state, body)[source]¶ Guard-cast tensor before being input to network
-
convlab.agent.algorithm.policy_util.
init_action_pd
(ActionPD, pdparam)[source]¶ Initialize the action_pd for discrete or continuous actions: - discrete: action_pd = ActionPD(logits) - continuous: action_pd = ActionPD(loc, scale)
-
convlab.agent.algorithm.policy_util.
multi_boltzmann
(states, algorithm, body_list, pdparam)[source]¶ Apply Boltzmann policy body-wise
-
convlab.agent.algorithm.policy_util.
multi_default
(states, algorithm, body_list, pdparam)[source]¶ Apply default policy body-wise Note, for efficiency, do a single forward pass to calculate pdparam, then call this policy like: @example
pdparam = self.calc_pdparam(state) action_a = self.action_policy(pdparam, self, body_list)
-
convlab.agent.algorithm.policy_util.
multi_epsilon_greedy
(states, algorithm, body_list, pdparam)[source]¶ Apply epsilon-greedy policy body-wise
-
convlab.agent.algorithm.policy_util.
multi_random
(states, algorithm, body_list, pdparam)[source]¶ Apply random policy body-wise.
-
convlab.agent.algorithm.policy_util.
random
(state, algorithm, body)[source]¶ Random action using gym.action_space.sample(), with the same format as default()
-
convlab.agent.algorithm.policy_util.
sample_action
(ActionPD, pdparam)[source]¶ Convenience method to sample action(s) from action_pd = ActionPD(pdparam) Works with batched pdparam too @returns tensor:action Sampled action(s) @example
# policy contains: pdparam = calc_pdparam(state, algorithm, body) action = sample_action(body.ActionPD, pdparam)
convlab.agent.algorithm.ppo module¶
-
class
convlab.agent.algorithm.ppo.
PPO
(agent, global_nets=None)[source]¶ Bases:
convlab.agent.algorithm.actor_critic.ActorCritic
Implementation of PPO This is actually just ActorCritic with a custom loss function Original paper: “Proximal Policy Optimization Algorithms” https://arxiv.org/pdf/1707.06347.pdf
Adapted from OpenAI baselines, CPU version https://github.com/openai/baselines/tree/master/baselines/ppo1 Algorithm: for iteration = 1, 2, 3, … do
- for actor = 1, 2, 3, …, N do
- run policy pi_old in env for T timesteps compute advantage A_1, …, A_T
end for optimize surrogate L wrt theta, with K epochs and minibatch size M <= NT
end for
e.g. algorithm_spec “algorithm”: {
“name”: “PPO”, “action_pdtype”: “default”, “action_policy”: “default”, “explore_var_spec”: null, “gamma”: 0.99, “lam”: 1.0, “clip_eps_spec”: {
“name”: “linear_decay”, “start_val”: 0.01, “end_val”: 0.001, “start_step”: 100, “end_step”: 5000,}, “entropy_coef_spec”: {
“name”: “linear_decay”, “start_val”: 0.01, “end_val”: 0.001, “start_step”: 100, “end_step”: 5000,}, “minibatch_size”: 256, “training_frequency”: 1, “training_epoch”: 8,
}
e.g. special net_spec param “shared” to share/separate Actor/Critic “net”: {
“type”: “MLPNet”, “shared”: true, …-
calc_policy_loss
(batch, pdparams, advs)[source]¶ The PPO loss function (subscript t is omitted) L^{CLIP+VF+S} = E[ L^CLIP - c1 * L^VF + c2 * S[pi](s) ]
Breakdown piecewise, 1. L^CLIP = E[ min(ratio * A, clip(ratio, 1-eps, 1+eps) * A) ] where ratio = pi(a|s) / pi_old(a|s)
- L^VF = E[ mse(V(s_t), V^target) ]
- S = E[ entropy ]
convlab.agent.algorithm.random module¶
-
class
convlab.agent.algorithm.random.
Random
(agent, global_nets=None)[source]¶ Bases:
convlab.agent.algorithm.base.Algorithm
Example Random agent that works in both discrete and continuous envs
convlab.agent.algorithm.reinforce module¶
-
class
convlab.agent.algorithm.reinforce.
Reinforce
(agent, global_nets=None)[source]¶ Bases:
convlab.agent.algorithm.base.Algorithm
Implementation of REINFORCE (Williams, 1992) with baseline for discrete or continuous actions http://www-anw.cs.umass.edu/~barto/courses/cs687/williams92simple.pdf Adapted from https://github.com/pytorch/examples/blob/master/reinforcement_learning/reinforce.py Algorithm:
- Collect n episodes of data
- At each timestep in an episode
- Calculate the advantage of that timestep
- Multiply the advantage by the negative of the log probability of the action taken
- Sum all the values above.
- Calculate the gradient of this value with respect to all of the parameters of the network
- Update the network parameters using the gradient
e.g. algorithm_spec: “algorithm”: {
“name”: “Reinforce”, “action_pdtype”: “default”, “action_policy”: “default”, “explore_var_spec”: null, “gamma”: 0.99, “entropy_coef_spec”: {
“name”: “linear_decay”, “start_val”: 0.01, “end_val”: 0.001, “start_step”: 100, “end_step”: 5000,}, “training_frequency”: 1,
}
-
calc_pdparam
(x, net=None)[source]¶ The pdparam will be the logits for discrete prob. dist., or the mean and std for continuous prob. dist.
-
calc_pdparam_batch
(batch)[source]¶ Efficiently forward to get pdparam and by batch for loss computation
-
calc_ret_advs
(batch)[source]¶ Calculate plain returns; which is generalized to advantage in ActorCritic
-
init_nets
(global_nets=None)[source]¶ Initialize the neural network used to learn the policy function from the spec Below we automatically select an appropriate net for a discrete or continuous action space if the setting is of the form ‘MLPNet’. Otherwise the correct type of network is assumed to be specified in the spec. Networks for continuous action spaces have two heads and return two values, the first is a tensor containing the mean of the action policy, the second is a tensor containing the std deviation of the action policy. The distribution is assumed to be a Gaussian (Normal) distribution. Networks for discrete action spaces have a single head and return the logits for a categorical probability distribution over the discrete actions
-
class
convlab.agent.algorithm.reinforce.
WarmUpReinforce
(agent, global_nets=None)[source]¶ Bases:
convlab.agent.algorithm.reinforce.Reinforce
Implementation of REINFORCE (Williams, 1992) with baseline for discrete or continuous actions http://www-anw.cs.umass.edu/~barto/courses/cs687/williams92simple.pdf Adapted from https://github.com/pytorch/examples/blob/master/reinforcement_learning/reinforce.py Algorithm:
- Collect n episodes of data
- At each timestep in an episode
- Calculate the advantage of that timestep
- Multiply the advantage by the negative of the log probability of the action taken
- Sum all the values above.
- Calculate the gradient of this value with respect to all of the parameters of the network
- Update the network parameters using the gradient
e.g. algorithm_spec: “algorithm”: {
“name”: “Reinforce”, “action_pdtype”: “default”, “action_policy”: “default”, “warmup_epi”: 300, “explore_var_spec”: null, “gamma”: 0.99, “entropy_coef_spec”: {
“name”: “linear_decay”, “start_val”: 0.01, “end_val”: 0.001, “start_step”: 100, “end_step”: 5000,}, “training_frequency”: 1,
}
convlab.agent.algorithm.sarsa module¶
-
class
convlab.agent.algorithm.sarsa.
SARSA
(agent, global_nets=None)[source]¶ Bases:
convlab.agent.algorithm.base.Algorithm
Implementation of SARSA.
Algorithm: Repeat:
- Collect some examples by acting in the environment and store them in an on policy replay memory (either batch or episodic)
- For each example calculate the target (bootstrapped estimate of the discounted value of the state and action taken), y, using a neural network to approximate the Q function. s_t’ is the next state following the action actually taken, a_t. a_t’ is the action actually taken in the next state s_t’.
- y_t = r_t + gamma * Q(s_t’, a_t’)
- For each example calculate the current estimate of the discounted value of the state and action taken
- x_t = Q(s_t, a_t)
- Calculate L(x, y) where L is a regression loss (eg. mse)
- Calculate the gradient of L with respect to all the parameters in the network and update the network parameters using the gradient
e.g. algorithm_spec “algorithm”: {
“name”: “SARSA”, “action_pdtype”: “default”, “action_policy”: “boltzmann”, “explore_var_spec”: {
“name”: “linear_decay”, “start_val”: 1.0, “end_val”: 0.1, “start_step”: 10, “end_step”: 1000,}, “gamma”: 0.99, “training_frequency”: 10,
}
-
calc_pdparam
(x, net=None)[source]¶ To get the pdparam for action policy sampling, do a forward pass of the appropriate net, and pick the correct outputs. The pdparam will be the logits for discrete prob. dist., or the mean and std for continuous prob. dist.
-
calc_q_loss
(batch)[source]¶ Compute the Q value loss using predicted and target Q values from the appropriate networks
-
init_nets
(global_nets=None)[source]¶ Initialize the neural network used to learn the Q function from the spec
convlab.agent.algorithm.sil module¶
-
class
convlab.agent.algorithm.sil.
PPOSIL
(agent, global_nets=None)[source]¶ Bases:
convlab.agent.algorithm.sil.SIL
,convlab.agent.algorithm.ppo.PPO
SIL extended from PPO. This will call the SIL methods and use PPO as super().
e.g. algorithm_spec “algorithm”: {
“name”: “PPOSIL”, “action_pdtype”: “default”, “action_policy”: “default”, “explore_var_spec”: null, “gamma”: 0.99, “lam”: 1.0, “clip_eps_spec”: {
“name”: “linear_decay”, “start_val”: 0.01, “end_val”: 0.001, “start_step”: 100, “end_step”: 5000,}, “entropy_coef_spec”: {
“name”: “linear_decay”, “start_val”: 0.01, “end_val”: 0.001, “start_step”: 100, “end_step”: 5000,}, “sil_policy_loss_coef”: 1.0, “sil_val_loss_coef”: 0.01, “training_frequency”: 1, “training_batch_iter”: 8, “training_iter”: 8, “training_epoch”: 8,
}
e.g. special memory_spec “memory”: {
“name”: “OnPolicyReplay”, “sil_replay_name”: “Replay”, “batch_size”: 32, “max_size”: 10000, “use_cer”: true}
-
class
convlab.agent.algorithm.sil.
SIL
(agent, global_nets=None)[source]¶ Bases:
convlab.agent.algorithm.actor_critic.ActorCritic
Implementation of Self-Imitation Learning (SIL) https://arxiv.org/abs/1806.05635 This is actually just A2C with an extra SIL loss function
e.g. algorithm_spec “algorithm”: {
“name”: “SIL”, “action_pdtype”: “default”, “action_policy”: “default”, “explore_var_spec”: null, “gamma”: 0.99, “lam”: 1.0, “num_step_returns”: 100, “entropy_coef_spec”: {
“name”: “linear_decay”, “start_val”: 0.01, “end_val”: 0.001, “start_step”: 100, “end_step”: 5000,}, “policy_loss_coef”: 1.0, “val_loss_coef”: 0.01, “sil_policy_loss_coef”: 1.0, “sil_val_loss_coef”: 0.01, “training_batch_iter”: 8, “training_frequency”: 1, “training_iter”: 8,
}
e.g. special memory_spec “memory”: {
“name”: “OnPolicyReplay”, “sil_replay_name”: “Replay”, “batch_size”: 32, “max_size”: 10000, “use_cer”: true}
Module contents¶
The algorithm module Contains implementations of reinforcement learning algorithms. Uses the nets module to build neural networks as the relevant function approximators


[gecode-users] Job shop scheduling solution with timetable, pre-emption, and priority
Christian Schulte
schulte at imit.kth.se
Tue May 30 22:16:38 CEST 2006
No, it has not been done (yet) in Gecode (even though, we just started some
work for having scheduling support). I also do not know any other freely
accesible solution.
Christian
-----Original Message-----
From: users-bounces at gecode.org [mailto:users-bounces at gecode.org] On Behalf
Of Tim Heath
Sent: Tuesday, May 30, 2006 9:00 PM
To: users at gecode.org
Subject: [gecode-users] Job shop scheduling solution with
timetable,pre-emption, and priority
Hi All,
I am new to gecode but have been studying mozart oz quite a bit. I am
interested in finding a solution that will do job shop scheduling with a
timetable, pre-emption, and priority of the tasks. Has this been done
in gecode? If so can you point me to this solution? Also, if your
aware of if it has been done anywhere in the free domain point me to
that as well.
Thanks
_______________________________________________
Gecode users mailing list
users at gecode.org https://www.gecode.org/mailman/listinfo/gecode-users
More information about the gecode-users
mailing list


@import com.depth1.grc.model.Policy @(policies:List[Policy], policySize:Integer) @header()
View 10 | View 25 | View 50
Instructions: Please select a Policy and then View, Update, or Delete.


PUTGRENT
Section: Linux Programmer's Manual (3)
Updated: 2003-09-09
Index
Return to Main Contents
NAME
putgrent - write a group database entry to a file
SYNOPSIS
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <grp.h>
int putgrent(const struct group *grp, FILE *fp);
DESCRIPTION
The
putgrent()
function is the counterpart for
fgetgrent(3).
The function writes the content of the provided
struct group
into the
file pointed to by
fp.
The list of group members must be NULL-terminated or NULL-initialized.
The
struct group
is defined as follows:
struct group {
char *gr_name; /* group name */
char *gr_passwd; /* group password */
gid_t gr_gid; /* group ID */
char **gr_mem; /* group members */
};
RETURN VALUE
The function returns zero on success, and a nonzero value on error.
CONFORMING TO
This function is a GNU extension.
SEE ALSO
fgetgrent(3),
getgrent(3),
group(5)
Index
- NAME
-
- SYNOPSIS
-
- DESCRIPTION
-
- RETURN VALUE
-
- CONFORMING TO
-
- SEE ALSO
-
This document was created by
man2html,
using the manual pages.
Time: 02:55:01 GMT, September 18, 2014


I love to build utility apps and solve real world problems. I am ambitious and hard working individual with a sheer curiosity into the emerging technologies of the software world. Skilled in python, C, C++,data structures, algorithms,data science,machine learning and deep learning. I like to contribute in open source projects too.
Priyam kakati
+91-6001591627
BTech in computer science and engineering • April 2017-july 2021
Machine Learning,Statistical Methods in AI,Computer Vision,Compilers,Optimization Methods,Digital Image Processing,Database Systems, Intro to Databases ,Artificial Intelligence ,Computer Graphics ,Operating Systems,Computer System Organization ,Computer Programming,Data Structures,Algorithms
Data scientist• october 2021 - April 2022
Tasks-
• Collected the data from the clients and created the chatbot intents and entities based on the client's need.
• Used AWS lex for NLU part and creation of the bots and deployed the bots using flask api.
Data scientist• october 2021 - April 2022
Tasks-
• Collected the data from the clients and annotated the images for training data and exported the data into
pascal-voc format.
• Used deep learning techniques to train various object detection models like mask-rcnn,yolo-v3,Yolo-v4 for detecting
various shipping containers and container numbers through drone videos.
•Extracted the container numbers from the containers using ocr recognition methods.
Wrote a python script to automate all the process of the pipeline and deployed the model in amazon aws.
Software engineering intern • April 2020 - june 2020
Tasks-
•Worked on building a technical screener for various stock indices.
• Created several strategies based on different technical indicators.
• Backtested the strategies and later optimised the strategies for better return % for 1 and 5 min trading.
• Created an webapp by using flask REST api and deployed the model in amazon AWS cloud.
Tools-Python,pandas,TA-lib,backtesting.py,Flask,HTML,CSS,Bootstrap,AWS>
Tools-Python,pandas,sklearn,keras,tensorflow,matplotlib,Azure cloud.
Data science intern • May 2020 - August 2020
Tasks-
• Worked with stakeholders to determine how to use business data for
valuable business solutions and generate problem statements.
• Collaborated with engineering and product development teams.
• Built predictive models using machine-learning, deep learning algorithms.
• Undertook preprocessing of structured and unstructured data.
• Combined models through ensemble modelling. Presented information using data visualisation techniques.
Tools-Python,pandas,sklearn,keras,tensorflow,matplotlib,Azure cloud.
Data science intern• April 2020 - June 2020
Tasks-
• Collected covid 19 hotline numbers of various states of the top infected countries and cleaned up the raw data in a structured format using pandas.
• Made the tableau dashboard for New Case Analysis connected to a live data source.
• Gathered data of worldwide air routes (last updated 2014), Government travel
measures (Unicef data) and air passenger traffic data (last updated 2018).
• Prepared a dashboard in Tableau showing all flight routes from a source airport (option to select)
highlighting the source and destination countries.
Tools-Python,Tableau,Scrapy,Beautifulsoup,pandas
• Languages: Python, C++, SQL, Bash, JAVA(basic)
• Frameworks: Scikit-learn, NLTK, SpaCy, TensorFlow, Keras, Django, Flask,Spark
• Tools: Jupyter notebook, Docker, GIT, PostgreSQL, SQLite
• Platforms: Linux, Windows, Azure,AWS
• Soft Skills: Leadership, Event Management, Writing, Public Speaking, Time Management


Lorem lipseum dolor sit amet, consecteur adipisicing elit, sed do eiusmod tempor incididunt
Last record added 2 hours ago
Each office checkins
Last record added 6 hours ago
List of places we've all worked
Last record added 12 hours ago


django-ajax
Fast and easy AJAX libraries for django projects.
Requirements
Installation
Install django-ajax in your python environment
1- Download and install package:
$ pip install djangoajax
Through Github:
pip install -e git://github.com/yceruto/django-ajax#egg=djangoajax
or simply with:
$ python setup.py install
2- Add 'django_ajax'
into the INSTALLED_APPS
list.
3- Read usage section and enjoy its advantages!
Usage
@ajax Decorator
from django_ajax.decorators import ajax
@ajax
def my_view(request)
do_something()
When nothing is returned as result of view then returns (JSON format):
{"status": 200, "statusText": "OK", "content ": null}
Sending custom data in the response
@ajax
def my_view(request):
c = 2 + 3
return {'result': c}
The result is send to the browser in the following way (JSON format)
{"status": 200, "statusText": "OK", "content": {"result": 5}}
Combining with others decorators
from django.contrib.auth.decorators import login_required
from django_ajax.decorators import ajax
@ajax
@login_required
def my_view(request):
# if the request.user is anonymous then this view not proceed
return {'user_id': request.user.id}
The JSON response:
{"status": 302, "statusText": "FOUND", "content": "/login"}
Template response
from django.shortcuts import render
from django_ajax.decorators import ajax
@ajax
def my_view(request):
return render(request, 'home.html')
The JSON response:
{"status": 200, "statusText": "OK", "content": "..."}
Catch exceptions
@ajax
def my_view(request):
a = 23 / 0 # this line throws an exception
return a
The JSON response:
{"status": 500, "statusText": "INTERNAL SERVER ERROR", "content": "integer division or modulo by zero"}
AJAXMiddleware
If you use AJAX quite frequently in your project, we suggest using the AJAXMiddleware described below.
Add django_ajax.middleware.AJAXMiddleware
into the MIDDLEWARE_CLASSES
list in settings.py
.
All your responses will be converted to JSON if the request was made by AJAX, otherwise is return a HttpResponse.
Caution If you use this middleware cannot use
@ajax
decorator.
AJAXMixin for class-based views
AJAXMixin
is an object that calls the AJAX decorator.
from django.views.generic import TemplateView
from django_ajax.mixin import AJAXMixin
class SimpleView(AJAXMixin, TemplateView):
template_name = 'home.html'
The JSON response:
{"status": 200, "statusText": "OK", "content": "..."}
AJAX on client side
Include jquery.ajax.min.js
into base.html
template:

Call to AJAX request using the ajaxPost
or ajaxGet
functions:

or

If the response is not successful, it´s shown an alert with the message appropriated.
eldarion-ajax
AJAX plugin Based onInclude jquery.ajax-plugin.min.js
into base.html
template:

In this moment any tag with the attribute data-ajax
will be controlled by ajax plugin. Each request is sent using AJAX and the response will be handle on JSON format.
The value of the attribute data-success
will be used as callback function if the request is successful. This function is called with an argument that represent the content response:
Show Alert
Where "processResponse" in this case is a callback function:

Process fragments
Inspired on eldarion-ajax the data
received by the names 'fragments'
, 'inner-fragments'
, 'append-fragments'
or 'prepend-fragments'
will be processed by default, unless you pass in the
request the option "process-fragments" equal false. Here's an example:
@ajax
def fragments_view(request):
data = {
'fragments': {
'#id1': 'replace element with this content1'
},
'inner-fragments': {
'#id2': 'replace inner content'
},
'append-fragments': {
'.class1': 'append this content'
},
'prepend-fragments': {
'.class2': 'prepend this content'
}
}
return data
These data are sent in response:
{"status": 200, "statusText": "OK", "content": {
"fragments": {"#id1": "replace element with this content1"},
"inner-fragments": {"#id2": "replace inner content"},
"append-fragments": {".class1": "append this content"},
"prepend-fragments": {".class2": "prepend this content"}
}}
Then, using AJAX (ajax
, ajaxPost
or ajaxGet
) functions these fragments to be processed automatically before calling to success function.

If you do not want to process the fragments never, modify the AJAX configuration that comes by default:

or as option on the request:


Brooks Saddle
When I bought the Brompton, there was the option of upgrading the saddle to a Brooks saddle. I decided against on the basis that I would see how the standard Brompton saddle faired as the one on the test model I’d ridden didn’t seem to bad. I’m also not a fan of the Brooks saddle - I didn’t like the look.
So I stuck with the Brompton saddle for a few hundred miles and it didn’t seem to bad at all. However, there was a saddle I had in mind - the Charge Spoon. The Spoon was a saddle I’ve put many miles onto as I had one on my hybrid I bought years ago, moved that to my road bike and then moved it to the hybrid I bought in January. Overall, it’s a really comfy saddle and so I thought it was perhaps time to move it to the Brompton.
Don’t get me wrong, the Brompton saddle is pretty good, but I knew that the Charge was like an old friend.
Mistake
Well, I ordered the Charge Spoon and put it on the Brompton. However, I soon realised my mistake. A week of commuting and a weekend ride of constant adjustments, I just couldn’t get the saddle set up nicely. The weekends ride was enough really. I couldn’t get it right - perhaps it’s not suited to the Brompton but either way, everything I tried was to much of an issue.
So it looked like I was stuck with the Brompton saddle again. That was, until I saw that Brooks had released the Cambium saddle in Slate. The Cambium I do like the look of - it looks like an actual saddle, compared to the standard Brooks saddle that looks like a saddle with wings… I’d seen the Cambium before but it was originally released in a fairly awful looking straw colour which wasn’t going to go anywhere near my bike.
I walked into the Brooks store in Covent Garden to buy it as it’s a fairly new saddle and I wasn’t able to get it in the Brompton Junction yet, so I cycled the short distance to the Brooks store.
It’s the first time I’ve seen a Brooks product up close (well, exception is my multi tool - I bought the Brooks one in February at the London Bike Show) and was seriously impressed with the quality of it.
I purchased mine from the Brooks store in Covent Garden and it packaged nicely. You knew you were getting a premium product. However, as the Tweed Run was that weekend, they assumed I was getting it for that. Unfortunately, with no ticket for the Tweed Run, I was just buying it as I wanted it (and the Brompton Urban Challenge would be it’s first outing on the Sunday).
Brompton - S type
Placing it on the Brompton was easy - benefit is that you can use any saddle on the Brompton. Like the Spoon before it, I have to mount the Cambium all the way at the top of the seatpost and have the seatpost extended all the way up to allow me to have a comfortable riding position. I’m even using the extended seatpost.
My first ride with it was the Space for Cycling ride on the Saturday with the London Cycling Campaign and the CTC. On the ride, I was asked by a fair number of people what I thought of the saddle. It was a bit early to give an informed opinion!
That completed, I undertook the Brompton Urban Challenge on it. You can read my post on that here. Overall, I was impressed the saddle and it held up well.
Since then, I’ve had a week or two of commuting on it and I’ve been impressed. So impressed, I’ve got another Brooks saddle…
Brooks 2 - P Type Upgrade
The P type is my Brompton of choice for long distances. This is on the basis that the hand grips allow me a range of hand positions for the longer times in the saddle. It also has a lower gearing (the -12% or 44T “upgrade”) that can be fitted to the Brompton (on the basis that if I’m cycling further, I want to cope with the hills more! - Mind, I coped ok on the London Classic of which, I regret I didn’t blog about).
Anyhow, on my last long distance ride to Cambridge, I thought that the bike could do with a new saddle. Likewise, after the second day of the Loughborough to Hatfield tour I did, the second day was fairly tender. So something had to be done.
Now having a Brooks saddle, I knew that it was comfy so that wasn’t an issue. Nor was the cost - as a comfy saddle will be the best purchase I can make for the bike!
Anyhow, I’d deliberately not got a B17 (the classic Brooks saddle) for my bike because I didn’t like the “wings” that the saddles have.
I felt that these made the the saddle look silly and I didn’t want that on my bike. However, the P type…
I think the P type already looks a bit silly. Well, maybe not silly, but it’s certainly not going to win a good looks competition. And that’s fine, because it’s not there to do so - it’s there to be a solid, dependable bike that I can rely on for touring. And in this role, Brooks apparently excel. With the comfort of the Cambium, I decided that ok, maybe the B17 could make an appearance on my bike (the plus side, it was cheaper than the Cambium as well…)
I fitted that this weekend and thought I’d do a short test ride as I needed to proof the saddle (as it’s leather, it needs looking after) and I’d heard that an unbroken in saddle can be uncomfortable so I thought a small ride would be in order. However, it turned into a 46Km ride.
Not quite sure how that happened but I think I just kept going. Not bad after doing the morning trip to the shops.
Anyhow, once I’d got the position right, the saddle seemed remarkably comfy straight off the bat. So I’ll be using it a few more times (and proofing it tomorrow!). I think the next ride that I’ll plan on using it is the Whitstable Winder that the London Brompton Club have planned for June. I plan to try and start with Orange Brompton and others at the 7am start for the longer ride option, rather than meet halfway for the 10:30 start. Just means getting a very early train…
Overall, so far the Brooks saddles have shown themselves to be decent saddles. I’ll perhaps do another write up once I’ve used them a lot more but currently hold out that I’ll not have to buy a new saddle for quite a while (or a new bike for that matter!)


Ashley Spellman
About
Portfolio
Contact
Ashley Spellman
About
Portfolio
Contact
Portfolio
Hangman
RPG Game
Trivia Game
Rutgers Info Widget
Rock Paper Scissors
Connect with Me


HobbySpot
Help
Navbar Link
menu
Home
Welcome to HobbySpot!
Fill out a form to create an account and let us know what
your
hobbies are.
info_outline
Go to Form
person_outline
Profile
Profile information will be displayed here when signed in.
settings
Log In
Username
Password
Log In


Use the Control Logging Options dialog box to specify the events, property changes, and property edit requests for which you want logging to occur.
To log events
1. From the Control menu, choose Logging.
2. Specify the events, property changes, and property edit requests for which you want logging to occur.
Tip You can use the Freeze Events command on the Options menu to toggle whether the container will ignore or accept events from the control. This command is the equivalent of IOleControl::FreezeEvents.


--- ---
Returns all the registered hooks of a given hookName
type
Returns all the registered hooks of a given hookName
type
Registers a TransitionHookFn, called before a transition starts.
Registers a TransitionHookFn, called before a transition starts.
Registers a transition lifecycle hook, which is invoked before a transition even begins. This hook can be useful to implement logic which prevents a transition from even starting, such as authentication, redirection
See TransitionHookFn for the signature of the function.
The HookMatchCriteria is used to determine which Transitions the hook should be invoked for.
onBefore
hooks are invoked before a Transition starts.
No resolves have been fetched yet.
Each onBefore
hook is invoked synchronously, in the same call stack as StateService.transitionTo.
The registered onBefore
hooks are invoked in priority order.
Note: during the onBefore
phase, additional hooks can be added to the specific Transition instance.
These "on-the-fly" hooks only affect the currently running transition..
The hook's return value can be used to pause, cancel, or redirect the current Transition. See HookResult for more information.
If any hook modifies the transition synchronously (by throwing, returning false
, or returning
a TargetState), the remainder of the hooks are skipped.
If a hook returns a promise, the remainder of the onBefore
hooks are still invoked synchronously.
All promises are resolved, and processed asynchronously before the onStart
phase of the Transition.
This example redirects any transition from 'home' to 'home.dashboard'. This is commonly referred to as a "default substate".
defines which Transitions the Hook should be invoked for.
the hook function which will be invoked.
a function which deregisters the hook.
Registers a TransitionStateHookFn, called when a specific state is entered.
Registers a TransitionStateHookFn, called when a specific state is entered.
Registers a lifecycle hook, which is invoked (during a transition) when a specific state is being entered.
Since this hook is run only when the specific state is being entered, it can be useful for performing tasks when entering a submodule/feature area such as initializing a stateful service, or for guarding access to a submodule/feature area.
See TransitionStateHookFn for the signature of the function.
The HookMatchCriteria is used to determine which Transitions the hook should be invoked for.
onEnter
hooks generally specify { entering: 'somestate' }
.
The matchCriteria
is used to determine which Transitions the hook should be invoked during.
Note: for onEnter
hooks, the to
in the matchCriteria
matches the entering state, not the Transition "to state".
onEnter
hooks are invoked when the Transition is entering a state.
States are entered after the onRetain
phase is complete.
If more than one state is being entered, the parent state is entered first.
The registered onEnter
hooks for a state are invoked in priority order.
Note: A built-in onEnter
hook with high priority is used to fetch lazy resolve data for states being entered.
The hook's return value can be used to pause, cancel, or redirect the current Transition. See HookResult for more information.
Instead of registering onEnter
hooks using the TransitionService, you may define an onEnter
hook
directly on a state declaration (see: StateDeclaration.onEnter).
This example uses a service to log that a user has entered the admin section of an app. This assumes that there are substates of the "admin" state, such as "admin.users", "admin.pages", etc.
defines which Transitions the Hook should be invoked for.
the hook function which will be injected and invoked.
a function which deregisters the hook.
Registers a TransitionHookFn, called after a successful transition completed.
Registers a TransitionHookFn, called after a successful transition completed.
Registers a transition lifecycle hook, which is invoked after a transition successfully completes.
See TransitionHookFn for the signature of the function.
The HookMatchCriteria is used to determine which Transitions the hook should be invoked for.
onError
hooks are chained off the Transition's promise (see Transition.promise).
If the Transition fails and its promise is rejected, then the onError
hooks are invoked.
Since these hooks are run after the transition is over, their return value is ignored.
The onError
hooks are invoked in priority order.
Since the Transition is already completed, the hook's return value is ignored
defines which Transitions the Hook should be invoked for.
the hook function which will be injected and invoked.
a function which deregisters the hook.
Registers a TransitionStateHookFn, called when a specific state is exited.
Registers a TransitionStateHookFn, called when a specific state is exited.
Registers a lifecycle hook, which is invoked (during a transition) when a specific state is being exited.
Since this hook is run only when the specific state is being exited, it can be useful for performing tasks when leaving a submodule/feature area such as cleaning up a stateful service, or for preventing the user from leaving a state or submodule until some criteria is satisfied.
See TransitionStateHookFn for the signature of the function.
The HookMatchCriteria is used to determine which Transitions the hook should be invoked for.
onExit
hooks generally specify { exiting: 'somestate' }
.
onExit
hooks are invoked when the Transition is exiting a state.
States are exited after any onStart
phase is complete.
If more than one state is being exited, the child states are exited first.
The registered onExit
hooks for a state are invoked in priority order.
The hook's return value can be used to pause, cancel, or redirect the current Transition. See HookResult for more information.
Instead of registering onExit
hooks using the TransitionService, you may define an onExit
hook
directly on a state declaration (see: StateDeclaration.onExit).
defines which Transitions the Hook should be invoked for.
the hook function which will be injected and invoked.
a function which deregisters the hook.
Registers a TransitionHookFn, called just before a transition finishes.
Registers a TransitionHookFn, called just before a transition finishes.
Registers a transition lifecycle hook, which is invoked just before a transition finishes. This hook is a last chance to cancel or redirect a transition.
See TransitionHookFn for the signature of the function.
The HookMatchCriteria is used to determine which Transitions the hook should be invoked for.
onFinish
hooks are invoked asynchronously, in priority order, just before the Transition completes, after
all states are entered and exited.
onFinish
hooks are invoked after the onEnter
phase is complete.
These hooks are invoked just before the transition is "committed".
The registered onFinish
hooks are invoked in priority order.
The hook's return value can be used to pause, cancel, or redirect the current Transition. See HookResult for more information.
defines which Transitions the Hook should be invoked for.
the hook function which will be injected and invoked.
a function which deregisters the hook.
Registers a TransitionStateHookFn, called when a specific state is retained/kept.
Registers a TransitionStateHookFn, called when a specific state is retained/kept.
Registers a lifecycle hook, which is invoked (during a transition) for a specific state that was previously active and is not being entered nor exited.
Since this hook is invoked when a transition is when the state is kept, it means the transition is coming from a substate of the kept state to a substate of the kept state. This hook can be used to perform actions when the user moves from one substate to another, such as between steps in a wizard.
The matchCriteria
is used to determine which Transitions the hook should be invoked during.
onRetain
hooks generally specify { retained: 'somestate' }
.
onRetain
hooks are invoked after any onExit
hooks have been fired.
If more than one state is retained, the child states' onRetain
hooks are invoked first.
The registered onRetain
hooks for a state are invoked in priority order.
The hook's return value can be used to pause, cancel, or redirect the current Transition. See HookResult for more information.
Instead of registering onRetain
hooks using the TransitionService, you may define an onRetain
hook
directly on a state declaration (see: StateDeclaration.onRetain).
defines which Transitions the Hook should be invoked for.
the hook function which will be injected and invoked.
a function which deregisters the hook.
Registers a TransitionHookFn, called when a transition starts.
Registers a TransitionHookFn, called when a transition starts.
Registers a transition lifecycle hook, which is invoked as a transition starts running. This hook can be useful to perform some asynchronous action before completing a transition.
See TransitionHookFn for the signature of the function.
The HookMatchCriteria is used to determine which Transitions the hook should be invoked for.
onStart
hooks are invoked asynchronously when the Transition starts running.
This happens after the onBefore
phase is complete.
At this point, the Transition has not yet exited nor entered any states.
The registered onStart
hooks are invoked in priority order.
Note: A built-in onStart
hook with high priority is used to fetch any eager resolve data.
The hook's return value can be used to pause, cancel, or redirect the current Transition. See HookResult for more information.
This example intercepts any transition to a state which requires authentication, when the user is not currently authenticated. It allows the user to authenticate asynchronously, then resumes the transition. If the user did not authenticate successfully, it redirects to the "guest" state, which does not require authentication.
This example assumes:
'auth'
state.MyAuthService.isAuthenticated()
synchronously returns a boolean.MyAuthService.authenticate()
presents a login dialog, and returns a promise which is resolved
or rejected, whether or not the login attempt was successful.defines which Transitions the Hook should be invoked for.
the hook function which will be injected and invoked.
a function which deregisters the hook.
Registers a TransitionHookFn, called after a successful transition completed.
Registers a TransitionHookFn, called after a successful transition completed.
Registers a transition lifecycle hook, which is invoked after a transition successfully completes.
See TransitionHookFn for the signature of the function.
The HookMatchCriteria is used to determine which Transitions the hook should be invoked for.
onSuccess
hooks are chained off the Transition's promise (see Transition.promise).
If the Transition is successful and its promise is resolved, then the onSuccess
hooks are invoked.
Since these hooks are run after the transition is over, their return value is ignored.
The onSuccess
hooks are invoked in priority order.
Since the Transition is already completed, the hook's return value is ignored
defines which Transitions the Hook should be invoked for.
the hook function which will be injected and invoked.
a function which deregisters the hook.
Generated using TypeDoc
This interface specifies the api for registering Transition Hooks. Both the TransitionService and also the Transition object itself implement this interface. Note: the Transition object only allows hooks to be registered before the Transition is started.


PSTREE
Section: User Commands (1)Updated: 2004-11-09
Index Return to Main Contents
NAME
pstree - display a tree of processesSYNOPSIS
pstree [-a] [-c] [-h|-Hpid] [-l] [-n] [-p] [-u] [-Z] [-A|-G|-U] [pid|user]pstree -V
DESCRIPTION
pstree shows running processes as a tree. The tree is rooted at either pid or init if pid is omitted. If a user name is specified, all process trees rooted at processes owned by that user are shown.pstree visually merges identical branches by putting them in square brackets and prefixing them with the repetition count, e.g.
init-+-getty |-getty |-getty `-gettybecomes
init---4*[getty]
Child threads of a process are found under the parent process and are shown with the process name in curly braces, e.g.
icecast2---13*[{icecast2}]
If pstree is called as pstree.x11 then it will prompt the user at the end of the line to press return and will not return until that has happened. This is useful for when pstree is run in a xterminal.
OPTIONS
- -a
- Show command line arguments. If the command line of a process is swapped out, that process is shown in parentheses. -a implicitly disables compaction.
- -A
- Use ASCII characters to draw the tree.
- -c
- Disable compaction of identical subtrees. By default, subtrees are compacted whenever possible.
- -G
- Use VT100 line drawing characters.
- -h
- Highlight the current process and its ancestors. This is a no-op if the terminal doesn't support highlighting or if neither the current process nor any of its ancestors are in the subtree being shown.
- -H
- Like -h, but highlight the specified process instead. Unlike with -h, pstree fails when using -H if highlighting is not available.
- -l
- Display long lines. By default, lines are truncated to the display width or 132 if output is sent to a non-tty or if the display width is unknown.
- -n
- Sort processes with the same ancestor by PID instead of by name. (Numeric sort.)
- -p
- Show PIDs. PIDs are shown as decimal numbers in parentheses after each process name. -p implicitly disables compaction.
- -u
- Show uid transitions. Whenever the uid of a process differs from the uid of its parent, the new uid is shown in parentheses after the process name.
- -U
- Use UTF-8 (Unicode) line drawing characters. Under Linux 1.1-54 and above, UTF-8 mode is entered on the console with echo -e '\033%8' and left with echo -e '\033%@'
- -V
- Display version information.
- -Z
- (SELinux) Show security context for each process.
FILES
/proc location of the proc file system
AUTHORS
Werner Almesberger<EMAIL_ADDRESS>Craig Small<EMAIL_ADDRESS>Some character sets may be incompatible with the VT100 characters.SEE ALSO
ps(1), top(1).
Index
This document was created by man2html, using the manual pages.
Time: 05:29:09 GMT, December 24, 2015


|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
public interface AuthenticationMethodInformation
Information about an authentication method employed by a user.
| Method Summary | |
|---|---|
long |
getAuthenticationDuration()
Gets the duration of this authentication method. |
DateTime |
getAuthenticationInstant()
Gets the time the user authenticated with this member. |
String |
getAuthenticationMethod()
Gets the unique identifier for the authentication method. |
Principal |
getAuthenticationPrincipal()
Gets the principal, for the Subject of the session, created by this authentication method. |
Subject |
getAuthenticationSubject()
Deprecated. use Session.getSubject() |
boolean |
isExpired()
Gets whether this authentication method has expired and is not longer valid for use in constructing new sessions. |
| Method Detail |
|---|
Subject getAuthenticationSubject()
Session.getSubject()
Principal getAuthenticationPrincipal()
Subject
of the session, created by this authentication method.
String getAuthenticationMethod()
DateTime getAuthenticationInstant()
long getAuthenticationDuration()
boolean isExpired()
|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |


- ICallback - Interface in labs.vex.lumen.ion.time
-
Timer Callbacks for moments and periods
- IConfigurable - Interface in labs.vex.lumen.firefly
-
Implement this interface to create an entry point for the
configuration daemon!
Please only implement inside concrete classes as the
construction of the class is very costly!
- IConfiguration - Interface in labs.vex.lumen.firefly
-
Interface must be respected by any Abstract or Concrete implementations
of configurations returned and used by any configuration manager
- IDescriber - Interface in labs.vex.lumen.module
-
- IEngine - Interface in labs.vex.lumen.dexter
-
Contract should be implemented by any custom service discovery engine.
- IHardwareHandler - Interface in labs.vex.lumen.hardware
-
Implement this to help conversion between hardware components and actual devices
- IllegalFootprintException - Exception in labs.vex.lumen.firefly.exceptions
-
Exception thrown by firefly if the footprint is not a valid path!
- IllegalFootprintException(String, String) - Constructor for exception labs.vex.lumen.firefly.exceptions.IllegalFootprintException
-
Builds the thrown exception from the original key and the
active key footprint
- ILoader - Interface in labs.vex.lumen.firefly
-
Used as a basic contract to define what a loader is
- init() - Method in class labs.vex.lumen.ion.Ion
-
- init() - Method in class labs.vex.lumen.ion.service.AbstractService
-
- initAccessor(String) - Static method in class labs.vex.lumen.ion.IonManager
-
Init/boot/tick/kill an ion for a specific accessor
- Inject - Annotation Type in labs.vex.lumen.anemoi
-
Inject annotation used inside Anemoi
- inject(ServicePacket) - Method in class labs.vex.lumen.ion.service.AbstractService
-
- inject(ServicePacket) - Method in interface labs.vex.lumen.ion.service.IService
-
- install(String, Object) - Method in class labs.vex.lumen.ion.service.ServicePacket
-
- installBootstrap(Bootstrap) - Static method in class labs.vex.lumen.Lumen
-
- installEngine(IEngine) - Static method in class labs.vex.lumen.dexter.Curiosity
-
Public method used to install a custom service discovery
engine
- Ion - Class in labs.vex.lumen.ion
-
Class used for flow control inside the app
- Ion(String, int) - Constructor for class labs.vex.lumen.ion.Ion
-
- IonException - Exception in labs.vex.lumen.ion
-
Exception thrown from within the Ions
- IonException(String) - Constructor for exception labs.vex.lumen.ion.IonException
-
- IonManager - Class in labs.vex.lumen.ion
-
Class used for flow control inside the C
- IonManager() - Constructor for class labs.vex.lumen.ion.IonManager
-
- IService - Interface in labs.vex.lumen.ion.service
-


prog12 is here. In case you missed class today, the notes I handed out are here. Please review them before lab period.
- I have added MyBrowser.java. It is a bit clunky, but it works with my solution to MyGoogle.java.
- I have added Main.java to test your MyGoogle.java.
- I strongly suggest you start your gather loop like this:
int count = 0;
while (!urlQueue.isEmpty() && count++ < 100) {
String url = urlQueue.poll();
System.out.println(url);
This way you will see each URL as it is processed and your program won't take forever.
- To create an array of Iterator, the incantation is
Iterator[] pageIDiter = (Iterator[]) new Iterator[n];
Ha ha! WordPress won’t let me tell you the incantation. The first and second “Iterator” on this line should be “Iterator lessthan Integer greaterthan”!
- Make sure the class PairID that you are putting into your PriorityQueue is declared to implement comparable lessthan PairID greaterthan.
David wrote:
Could you explain what you mean by search and gather? I know you said that they’re in the packet, but I don’t understand what parts. Thanks.
Link | November 16th, 2007 at 1:54 am
vjm wrote:
Gather is everything up to the word SEARCHING in the notes, and search is everything after.
In the gather phase, you start from a list of URLs and follow all links from these pages and follow all links from those and follow all links from those and so on until you have seen every page that is reachable from the starting URLs. As you visit each page, you increment the number of references for each page it links to. For every word on that page, you record that that page has that word.
In the search phase, given some keywords, like Victor Milenkovic Java, you find all pages which have all three of those words and return an array of their URLs, ordered by decreasing significance, where the significance of a page is the number of links to it from other pages.
Link | November 16th, 2007 at 9:15 am
Nabeel Sneij wrote:
Hey. The turkey in my belly is making me not think.
I can’t figure out why I get this problem.
MyGoogle.java:54: loadPage(java.lang.String) in prog12.Browser cannot be applied to (java.util.List)
browser.loadPage(startingURLs);
My program is uploaded.
Link | November 25th, 2007 at 10:39 pm
Nabeel Sneij wrote:
Never mind. I figured it out.
Link | November 25th, 2007 at 10:42 pm
Nabeel Sneij wrote:
Putting the .java file into a different folder in the project doesn’t disable it for compiling.
I believe only in a different project folder would do.
Link | November 27th, 2007 at 1:34 pm
Nabeel Sneij wrote:
Actually, I figured it out.
You can put it in the folder “Test Packages”, and it would work fine.
Link | November 27th, 2007 at 1:35 pm
Nabeel Sneij wrote:
Ahh, I don’t know why I’m all of a sudden getting these errors (I added the word “error” to the statement: System.out.println(“ERROR: “+ e);
I uploaded my code.
ERROR: java.net.UnknownServiceException: protocol doesn’t support input
ERROR: java.net.MalformedURLException: unknown protocol: ailto
ERROR: java.net.MalformedURLException: unknown protocol: ailto
ERROR: java.net.MalformedURLException: unknown protocol: ailto
ERROR: java.net.MalformedURLException: unknown protocol: javascript
ERROR: java.net.UnknownServiceException: protocol doesn’t support input
ERROR: java.net.UnknownServiceException: protocol doesn’t support input
ERROR: java.net.UnknownServiceException: protocol doesn’t support input
ERROR: java.net.MalformedURLException: unknown protocol: ailto
ERROR: java.net.MalformedURLException: unknown protocol: ailto
ERROR: java.net.MalformedURLException: unknown protocol: ailto
ERROR: java.net.MalformedURLException: unknown protocol: ailto
Link | November 27th, 2007 at 6:09 pm
vjm wrote:
Nabeel,
Sorry I forgot to respond last night. I don’t know why all of a sudden you got these.
These are normal error message my (klunky!) browser generates as it tries to follows MAILTO links.
If you see an array index out of bounds message, that is a genuine bug. Otherwise, don’t worry about the messages.
Victor
Link | November 28th, 2007 at 7:36 am
Nabeel Sneij wrote:
I see what caused the problem: I didn’t include your code: !urlQueue.isEmpty() && urlIDs.size()
Link | November 28th, 2007 at 10:07 pm
Joey Kadin wrote:
Is it possible to modify your MyBrowser so that it skips over any file larger than 1mb or something similar so it doesn’t break the java memory heap when you hit something like a video file? I’d like to be able to remove the gather queue limit of 100/change the ints to longs and see how far it goes.
Link | November 28th, 2007 at 10:25 pm
vjm wrote:
Please feel free to modify MyBrowser. It already has a check for the ending .pdf. Without that, it broke the java memory heap when it it the complete bulletin for UM. MyBrowser should also avoid other kinds of non-text non-html files like .avi or .mov.
Link | November 29th, 2007 at 12:15 am
Nabeel Sneij wrote:
Hey Prof.
I’ve noticed a lot of students not checking their integrity of their programs, and just moving on. Like, “if it runs, then it’s good” logic. However, I’m not doing that and debugging to get the runtime results correct is taking a really long time.
For example, I recently debugged the problem of my starting URLs not being processed correctly; it would just process the links that they contain and onwards. This is extremely hard to catch if not careful.
I wonder how you or Nelson would judge the integrity of the work compared to the completeness of the work?
Link | November 29th, 2007 at 10:30 pm
vjm wrote:
Nabeel,
Nelson and I have extensively discussed what the program should do in each part. There is a pretty clear right and wrong here. We won’t just run it. We will read it and make sure it is implemented correctly.
Victor
Link | November 29th, 2007 at 11:25 pm


The Hexagons are a London-based duo, known for their all-embracing, distinctive music, ranging from electronic to pop to jazz.
They’ve recently launched their new album ‘Hexagon’, which they will be touring in autumn 2021, so stay tuned to find a show near you!


--- layout: post title: Getting up and Running with Minitest, Guard, Sass, and Bootstrap for Ruby on Rails Development categories: - articles tags: - ruby on rails - Minitest - Guard - Spring - Bootstrap - Sass - Automated Testing - TDD - Git published: true ---
I've always felt that getting up and running with a new web development project should be as easy as possible. A good example of this is a Rails app. As Ruby on Rails accomplishes a high degree of ease of use straight out of the box, this article will focus on setting up an automated testing environment and sprucing up your CSS with bootstrap-sass.
I'm going to assume that you already have the following items installed: Ruby on Rails and Git. You will need both of these before going further into this setup.
The first thing we need to do is add all the necessary gems. The bootstrap-sass gem neatly encapsulates most of the configuration for us with a small config caveat that I will go into later. To get smooth automated testing up and running with Minitest we need a number of other gems.
Add the following to your Gemfile. Once added we need to run bundle install
to install the newly added gems.
With the gems now installed it's time to start configuring them with our environment. Let's first deal with our Bootstrap-sass configuration.
As I mentioned earlier, the gem will do most of the work for us. If you look at /app/assets/javascripts/application.js and /app/assets/stylesheets/application.css you should see some comments that say //= require bootstrap-sprockets
. For our application.js file we can leave these alone as they will work as expected. However, with Sass files the problem with the comments is that not only does it include our new bootstrap-sass gem but they also load all .css or .scss files in the assets/stylesheets directory. This makes it problematic for spliting Sass files into partials as the order they are included isn't specific.
To fix this we need to remove all the comments from application.css. Also make sure that you rename the file to application.css.scss to use the sass file ending (or .sass if you like the indent version). Once the comments are removed and the file renamed we can now use Sass's built in @import statement to structure our files however we want. While we do lose the ability to automatically load all the stylesheets at once we are now able to load them with their partials in the proper order. It should look like the following code.
{% highlight scss %} // We need to manually import the bootstrap-sass gem Sass files @import "bootstrap-sprockets"; @import "bootstrap"; // Add your Sass files here or just write sass @import "pages"; .red { color: red; } {% endhighlight %}We now have a working system for including Sass files and partials in a specific order. Sass is excellent at compiling multiple @imports together so no need to worry about the site running slower. Additionally, since we used the gem it has the Bootstrap framework built-in which is awesome!
There are a lot of different testing solutions for using Rails. You have Rspec, Cucumber, Test::Unit, and Minitest. Rspec is really powerful but can be quite tricky to get working right. Cucumber is great for its easy to read tests that could allow your clients to write the application specs as tests. For starting out though I would recommend Minitest because of how easy it is setup and also that it is the preferred unit testing framework packaged with Rails.
There are two gems from the Gemfile section that are associated with getting minitest looking sweet: minitest-reporters, and mini_backtrace. Minitest reporters adds hooks for better display output from tests. Mini backtrace add supports for backtrace cleaner to prevent really long error messages while running your test suite.
To setup minitest-reporters open your test_helper.rb file and add the following code above the line class ActiveSupport::TestCase
.
Next mini_backtrace needs the following code added to it. This will suppress some messages regarding rvm in the console. You may need to adjust this depending on your Rails environment setup (rvm or rbenv).
{% highlight ruby %} Rails.backtrace_cleaner.add_silencer { |line| line =~ /rvm/ } {% endhighlight %}Awesome! You can now run tests on your app with clean output using rake test
. Of course manually running tests is so un-hip so let's setup our automated testing suite with Guard.
Guard is an awesome event handler for the command line. Built in native ruby it integrates well into the Rails workflow. Setting up Guard is pretty easy just run guard init minitest
to create a basic Minitest Guardfile.
The Guardfile is similiar to gulp or grunt in that it watches for particular events to occur and then performs an action. Your Guardfile should looking something like the following code
{% highlight ruby %} guard :minitest, spring: false, all_on_start: false, all_after_pass: false do # with Minitest::Unit watch(%r{^test/(.*)\/?test_(.*)\.rb$}) watch(%r{^lib/(.*/)?([^/]+)\.rb$}) { |m| "test/#{m[1]}test_#{m[2]}.rb" } watch(%r{^test/test_helper\.rb$}) { 'test' } # Rails 4 watch(%r{^app/(.+)\.rb$}) { |m| "test/#{m[1]}_test.rb" } watch(%r{^app/controllers/application_controller\.rb$}) { 'test/controllers' } watch(%r{^app/controllers/(.+)_controller\.rb$}) { |m| "test/integration/#{m[1]}_test.rb" } watch(%r{^app/views/(.+)_mailer/.+}) { |m| "test/mailers/#{m[1]}_mailer_test.rb" } watch(%r{^lib/(.+)\.rb$}) { |m| "test/lib/#{m[1]}_test.rb" } watch(%r{^test/.+_test\.rb$}) watch(%r{^test/test_helper\.rb$}) { 'test' } end {% endhighlight %}Basically we have all the particular watched files within the guard block. These will essentially fire off your unit tests depending on which files are being modified. To start Guard just run guard
in the terminal from your Rails project directory. It will take a few seconds and then should start polling for events. Super handy and cuts down on the time it takes to manually run unit tests. The only issue is that the test suite runs really, really slowly. This is where the Spring preloader gem comes in handy by reducing the execution time of your test suite.
 The reduction in run time can be quite impressive from 5 seconds to almost instantaneously. Spring with Guard makes Test-Driven Development a dream. To setup Spring you first need to add Spring to your app's executables by running bundle exec spring binstub --all
. Next make sure the Spring attribute is marked as true in your Guardfile.
We now have all the basics of a proper automated testing environment setup. System notifications in the next section add another layer of convenience with testing.
Having notifications from your test suite is just another way to increase your productivity by not having to pull up terminal every 5 seconds. Since I am using Linux the gem I choose was Libnotify to add notifications. There are a number of different system notifiers. To find out which one is available for your OS check out the system notifications faq page. This page also includes install instructions or further documentation pages.
Lastly, is version control. It is recommended to follow the useful gitignore file located here for your programming language. Look at the ruby and rails sections for preferred ignored files. Additionally, since we are using Spring for preloading make sure to ignore spring files by adding /spring/*.pid
to your .gitignore file. Here is a basic .gitignore file below
And there you have it!  This is a great starting place for new Rails applications. Have a suggestion or comment? Leave me a comment below.


Payment Form Example
Card Number
CVC
Amount
First Name
Last Name
City
State
Pick a state
Alabama
Alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
District Of Columbia
Florida
Georgia
Hawaii
Idaho
Illinois
Indiana
Iowa
Kansas
Kentucky
Louisiana
Maine
Maryland
Massachusetts
Michigan
Minnesota
Mississippi
Missouri
Montana
Nebraska
Nevada
New Hampshire
New Jersey
New Mexico
New York
North Carolina
North Dakota
Ohio
Oklahoma
Oregon
Pennsylvania
Rhode Island
South Carolina
South Dakota
Tennessee
Texas
Utah
Vermont
Virginia
Washington
West Virginia
Wisconsin
Wyoming
Postal Code
We Accept
Message
Add any notes here.


Controls: Arrow keys, and W, A, S, D.
Color Settings:
Toggle Edit Mode:
Transform Settings: (X - Y - Z)


Information identifying a device. More...
Public Member Functions | |
| virtual | ~PvDeviceInfo () |
| Destructor. | |
| PvDeviceInfoType | GetType () const |
| Returns the type of the device info object. More... | |
| PvString | GetVendorName () const |
| Get the device's manufacturer name. More... | |
| PvString | GetModelName () const |
| Get the device's model name. More... | |
| PvString | GetVersion () const |
| Get the device's version. More... | |
| PvString | GetManufacturerInfo () const |
| Get the manufacturer information returned by the device. More... | |
| PvString | GetSerialNumber () const |
| Get the GigE Vision device's serial number. More... | |
| PvString | GetUserDefinedName () const |
| Get the device's user defined name. More... | |
| PvString | GetDisplayID () const |
| Get a string identifying this device for display purpose. More... | |
| PvString | GetUniqueID () const |
| Get a string uniquely identifying this device. More... | |
| PvString | GetConnectionID () const |
| Get a unique string identifying this device for connection purpose. More... | |
| const PvInterface * | GetInterface () const |
| Get the network adapter (PvInterface) through which this device was reached. More... | |
| bool | IsConfigurationValid () const |
| Test if the device can be reached as currently configured. More... | |
| bool | IsLicenseValid () const |
| Test if the eBUS SDK license is valid for this device. More... | |
| PvDeviceClass | GetClass () const |
| Get the device class. More... | |
Protected Member Functions | |
| PvDeviceInfo (PvDeviceLib::DeviceInfo *aThis) | |
| Constructor. | |
Friends | |
| class | PvDevice |
Information identifying a device.
PvDeviceInfo provides information about a device (GigE Vision, USB3 Vision or Pleora Protocol) as found by either PvSystem/PvInterface or device finder dialog.
To use PvDeviceInfo, see PvDevice.
| PvDeviceClass PvDeviceInfo::GetClass | ( | ) | const |
Get the device class.
| PvString PvDeviceInfo::GetConnectionID | ( | ) | const |
Get a unique string identifying this device for connection purpose.
This string can be used with the factory methods of PvDevice and PvStream to create a GigE Vision device or USB3 Vision device from generic PvDeviceInfo.
| PvString PvDeviceInfo::GetDisplayID | ( | ) | const |
Get a string identifying this device for display purpose.
| const PvInterface * PvDeviceInfo::GetInterface | ( | ) | const |
Get the network adapter (PvInterface) through which this device was reached.
| PvString PvDeviceInfo::GetManufacturerInfo | ( | ) | const |
Get the manufacturer information returned by the device.
| PvString PvDeviceInfo::GetModelName | ( | ) | const |
Get the device's model name.
| PvString PvDeviceInfo::GetSerialNumber | ( | ) | const |
Get the GigE Vision device's serial number.
| PvDeviceInfoType PvDeviceInfo::GetType | ( | ) | const |
Returns the type of the device info object.
| PvString PvDeviceInfo::GetUniqueID | ( | ) | const |
Get a string uniquely identifying this device.
| PvString PvDeviceInfo::GetUserDefinedName | ( | ) | const |
Get the device's user defined name.
This feature is only supported by devices having persistence memory. It can therefor be blank if not supported by the device, or simply not yet assigned.
| PvString PvDeviceInfo::GetVendorName | ( | ) | const |
Get the device's manufacturer name.
| PvString PvDeviceInfo::GetVersion | ( | ) | const |
Get the device's version.
| bool PvDeviceInfo::IsConfigurationValid | ( | ) | const |
Test if the device can be reached as currently configured.
This method compares the GigE Vision device and NIC's IP configurations to ensure they are on the same subnet. For USB3 Vision devices, the configuration is considered valid if the device can be enumerated and the Pleora driver is associated to the device.
| bool PvDeviceInfo::IsLicenseValid | ( | ) | const |
Test if the eBUS SDK license is valid for this device.
To connect to third-party devices, the eBUS SDK requires a valid license. If you don't have a license, contact sales.
Copyright (c) 2002-2015 Pleora Technologies Inc.
www.pleora.com


| Module | ActionView::Helpers::CaptureHelper |
| In: |
/usr/lib/ruby/gems/1.8/gems/actionpack-3.0.0.beta4/lib/action_view/helpers/capture_helper.rb
|
CaptureHelper exposes methods to let you extract generated markup which can be used in other parts of a template or layout file. It provides a method to capture blocks into variables through capture and a way to capture a block of markup for use in a layout through content_for.
The capture method allows you to extract part of a template into a variable. You can then use this variable anywhere in your templates or layout.
The capture method can be used in ERb templates…
<% @greeting = capture do %> Welcome to my shiny new web page! The date and time is <%= Time.now %> <% end %>
…and Builder (RXML) templates.
@timestamp = capture do "The current timestamp is #{Time.now}." end
You can then use that variable anywhere else. For example:
 <title><%= @greeting %></title>  <%= @greeting %>
# File /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.0.beta4/lib/action_view/helpers/capture_helper.rb, line 35 35: def capture(*args) 36: value = nil 37: buffer = with_output_buffer { value = yield(*args) } 38: if string = buffer.presence || value and string.is_a?(String) 39: NonConcattingString.new(string) 40: end 41: end
Calling content_for stores a block of markup in an identifier for later use. You can make subsequent calls to the stored content in other templates, helper modules or the layout by passing the identifier as an argument to content_for.
Note: yield can still be used to retrieve the stored content, but calling yield doesn‘t work in helper modules, while content_for does.
<% content_for :not_authorized do %> alert('You are not authorized to do that!') <% end %>
You can then use content_for :not_authorized anywhere in your templates.
<%= content_for :not_authorized if current_user.nil? %>
This is equivalent to:
<%= yield :not_authorized if current_user.nil? %>
content_for, however, can also be used in helper modules.
module StorageHelper def stored_content content_for(:storage) || "Your storage is empty" end end
This helper works just like normal helpers.
<%= stored_content %>
You can use the yield syntax alongside an existing call to yield in a layout. For example:
<%# This is the layout %>   <title>My Website</title> <%= yield :script %>   <%= yield %>
And now, we‘ll create a view that has a content_for call that creates the script identifier.
<%# This is our view %> Please login! <% content_for :script do %>  <% end %>
Then, in another view, you could to do something like this:
<%= link_to 'Logout', :action => 'logout', :remote => true %> <% content_for :script do %> <%= javascript_include_tag :defaults %> <% end %>
That will place