DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON http://guides.rubyonrails.org.
Active Model Basics
This guide should provide you with all you need to get started using model
classes. Active Model allows for Action Pack helpers to interact with
plain Ruby objects. Active Model also helps build custom ORMs for use
outside of the Rails
framework.
After reading this guide, you will know:
- How an Active Record model behaves.
- How Callbacks and validations work.
- How serializers work.
- How Active Model integrates with the
Rails
internationalization (i18n) framework.
Introduction
Active Model is a library containing various modules used in developing classes that need some features present on Active Record. Some of these modules are explained below.
Attribute Methods
The ::ActiveModel::AttributeMethods
module can add custom prefixes and suffixes
on methods of a class. It is used by defining the prefixes and suffixes and
which methods on the object will use them.
class Person
include ActiveModel::AttributeMethods
attribute_method_prefix 'reset_'
attribute_method_suffix '_highest?'
define_attribute_methods 'age'
attr_accessor :age
private
def reset_attribute(attribute)
send("#{attribute}=", 0)
end
def attribute_highest?(attribute)
send(attribute) > 100
end
end
person = Person.new
person.age = 110
person.age_highest? # => true
person.reset_age # => 0
person.age_highest? # => false
Callbacks
::ActiveModel::Callbacks
gives Active Record style callbacks. This provides an
ability to define callbacks which run at appropriate times.
After defining callbacks, you can wrap them with before, after and around
custom methods.
class Person
extend ActiveModel::Callbacks
define_model_callbacks :update
before_update :reset_me
def update
run_callbacks(:update) do
# This method is called when update is called on an object.
end
end
def reset_me
# This method is called when update is called on an object as a before_update callback is defined.
end
end
Conversion
If a class defines persisted?
and id
methods, then you can include the
::ActiveModel::Conversion
module in that class, and call the Rails conversion
methods on objects of that class.
class Person
include ActiveModel::Conversion
def persisted?
false
end
def id
nil
end
end
person = Person.new
person.to_model == person # => true
person.to_key # => nil
person.to_param # => nil
Dirty
An object becomes dirty when it has gone through one or more changes to its
attributes and has not been saved. ::ActiveModel::Dirty
gives the ability to
check whether an object has been changed or not. It also has attribute based
accessor methods. Let's consider a Person class with attributes first_name
and last_name
:
class Person
include ActiveModel::Dirty
define_attribute_methods :first_name, :last_name
def first_name
@first_name
end
def first_name=(value)
first_name_will_change!
@first_name = value
end
def last_name
@last_name
end
def last_name=(value)
last_name_will_change!
@last_name = value
end
def save
# do save work...
changes_applied
end
end
Querying object directly for its list of all changed attributes.
person = Person.new
person.changed? # => false
person.first_name = "First Name"
person.first_name # => "First Name"
# returns true if any of the attributes have unsaved changes.
person.changed? # => true
# returns a list of attributes that have changed before saving.
person.changed # => ["first_name"]
# returns a Hash of the attributes that have changed with their original values.
person.changed_attributes # => {"first_name"=>nil}
# returns a Hash of changes, with the attribute names as the keys, and the
# values as an array of the old and new values for that field.
person.changes # => {"first_name"=>[nil, "First Name"]}
Attribute based accessor methods
Track whether the particular attribute has been changed or not.
# attr_name_changed?
person.first_name # => "First Name"
person.first_name_changed? # => true
Track the previous value of the attribute.
# attr_name_was accessor
person.first_name_was # => nil
Track both previous and current value of the changed attribute. Returns an array if changed, otherwise returns nil.
# attr_name_change
person.first_name_change # => [nil, "First Name"]
person.last_name_change # => nil
Validations
The ::ActiveModel::Validations
module adds the ability to validate objects
like in Active Record.
class Person
include ActiveModel::Validations
attr_accessor :name, :email, :token
validates :name, presence: true
validates_format_of :email, with: /\A([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})\z/i
validates! :token, presence: true
end
person = Person.new
person.token = "2b1f325"
person.valid? # => false
person.name = 'vishnu'
person.email = 'me'
person.valid? # => false
person.email =<EMAIL_ADDRESS>person.valid? # => true
person.token = nil
person.valid? # => raises ActiveModel::StrictValidationFailed
Naming
::ActiveModel::Naming
adds a number of class methods which make naming and routing
easier to manage. The module defines the model_name
class method which
will define a number of accessors using some ::ActiveSupport::Inflector
methods.
class Person
extend ActiveModel::Naming
end
Person.model_name.name # => "Person"
Person.model_name.singular # => "person"
Person.model_name.plural # => "people"
Person.model_name.element # => "person"
Person.model_name.human # => "Person"
Person.model_name.collection # => "people"
Person.model_name.param_key # => "person"
Person.model_name.i18n_key # => :person
Person.model_name.route_key # => "people"
Person.model_name.singular_route_key # => "person"
Model
::ActiveModel::Model
adds the ability for a class to work with Action Pack and
Action View right out of the box.
class EmailContact
include ActiveModel::Model
attr_accessor :name, :email, :
validates :name, :email, :, presence: true
def deliver
if valid?
# deliver email
end
end
end
When including ::ActiveModel::Model
you get some features like:
- model name introspection
- conversions
- translations
- validations
It also gives you the ability to initialize an object with a hash of attributes, much like any Active Record object.
email_contact = EmailContact.new(name: 'David',
email<EMAIL_ADDRESS>message: 'Hello World')
email_contact.name # => 'David'
email_contact.email # =><EMAIL_ADDRESS>email_contact.valid? # => true
email_contact.persisted? # => false
Any class that includes ::ActiveModel::Model
can be used with form_for
,
render
and any other Action View helper methods, just like Active Record
objects.
Serialization
::ActiveModel::Serialization
provides basic serialization for your object.
You need to declare an attributes Hash which contains the attributes you want to
serialize. Attributes must be strings, not symbols.
class Person
include ActiveModel::Serialization
attr_accessor :name
def attributes
{'name' => nil}
end
end
Now you can access a serialized Hash of your object using the serializable_hash
method.
person = Person.new
person.serializable_hash # => {"name"=>nil}
person.name = "Bob"
person.serializable_hash # => {"name"=>"Bob"}
ActiveModel::Serializers
Active Model also provides the ::ActiveModel::Serializers::JSON
module
for JSON serializing / deserializing. This module automatically includes the
previously discussed ::ActiveModel::Serialization
module.
ActiveModel::Serializers::JSON
To use ::ActiveModel::Serializers::JSON
you only need to change the
module you are including from ::ActiveModel::Serialization
to ::ActiveModel::Serializers::JSON
.
class Person
include ActiveModel::Serializers::JSON
attr_accessor :name
def attributes
{'name' => nil}
end
end
The as_json
method, similar to serializable_hash
, provides a Hash representing
the model.
person = Person.new
person.as_json # => {"name"=>nil}
person.name = "Bob"
person.as_json # => {"name"=>"Bob"}
You can also define the attributes for a model from a JSON string.
However, you need to define the attributes=
method on your class:
class Person
include ActiveModel::Serializers::JSON
attr_accessor :name
def attributes=(hash)
hash.each do |key, value|
send("#{key}=", value)
end
end
def attributes
{'name' => nil}
end
end
Now it is possible to create an instance of Person
and set attributes using from_json
.
json = { name: 'Bob' }.to_json
person = Person.new
person.from_json(json) # => #<Person:0x00000100c773f0 @name="Bob">
person.name # => "Bob"
Translation
::ActiveModel::Translation
provides integration between your object and the Rails
internationalization (i18n) framework.
class Person
extend ActiveModel::Translation
end
With the human_attribute_name
method, you can transform attribute names into a
more human-readable format. The human-readable format is defined in your locale file(s).
-
config/locales/app.pt-BR.yml
pt-BR: activemodel: attributes: person: name: 'Nome'
Person.human_attribute_name('name') # => "Nome"
Lint Tests
::ActiveModel::Lint::Tests
allows you to test whether an object is compliant with
the Active Model API.
-
app/models/person.rb
class Person include ActiveModel::Model end
-
test/models/person_test.rb
require 'test_helper' class PersonTest < ActiveSupport::TestCase include ActiveModel::Lint::Tests setup do @model = Person.new end end
$ rails test
Run options: --seed 14596
# Running:
......
Finished in 0.024899s, 240.9735 runs/s, 1204.8677 assertions/s.
6 runs, 30 assertions, 0 failures, 0 errors, 0 skips
An object is not required to implement all APIs in order to work with Action Pack. This module only intends to provide guidance in case you want all features out of the box.
SecurePassword
::ActiveModel::SecurePassword
provides a way to securely store any
password in an encrypted form. When you include this module, a
has_secure_password
class method is provided which defines
a password
accessor with certain validations on it.
Requirements
::ActiveModel::SecurePassword
depends on bcrypt
,
so include this gem in your Gemfile
to use ::ActiveModel::SecurePassword
correctly.
In order to make this work, the model must have an accessor named password_digest
.
The has_secure_password
will add the following validations on the password
accessor:
- Password should be present.
- Password should be equal to its confirmation (provided
password_confirmation
is passed along). - The maximum length of a password is 72 (required by
bcrypt
on which ActiveModel::SecurePassword depends)
Examples
class Person
include ActiveModel::SecurePassword
has_secure_password
attr_accessor :password_digest
end
person = Person.new
# When password is blank.
person.valid? # => false
# When the confirmation doesn't match the password.
person.password = 'aditya'
person.password_confirmation = 'nomatch'
person.valid? # => false
# When the length of password exceeds 72.
person.password = person.password_confirmation = 'a' * 100
person.valid? # => false
# When only password is supplied with no password_confirmation.
person.password = 'aditya'
person.valid? # => true
# When all validations are passed.
person.password = person.password_confirmation = 'aditya'
person.valid? # => true


CMPSC311 Project Submission Portal
Your project was submitted, but resulted in some errors. Please check the following things: Is your tar file named correctly? (LASTNAME-PSUEMAILID-assign3.tgz) Is your directory structure correct? (When you untar the file, the result should be a folder called 'assign3' containing your project files) Does your tar contain the original, unchanged makefile? Does your program compile without warnings? Try again.


---
sort_order: 75
tei_id: rdx_b5j2m.p.idm192338048
annotation_count: 0
images:
small-thumbnail: http://readux.library.emory.edu/books/emory:b5j2m/pages/emory:p75w8/mini-thumbnail/
json: http://readux.library.emory.edu/books/emory:b5j2m/pages/emory:p75w8/info/
full: http://readux.library.emory.edu/books/emory:b5j2m/pages/emory:p75w8/fs/
page: http://readux.library.emory.edu/books/emory:b5j2m/pages/emory:p75w8/single-page/
thumbnail: http://readux.library.emory.edu/books/emory:b5j2m/pages/emory:p75w8/thumbnail/
title: Page 75
number: 75
---
{% raw %}A TERRIBLE TEMPTATION".{% endraw %}
{% raw %}71{% endraw %}
{% raw %}improvement, the character I had acquired, and the{% endraw %}
{% raw %}peace of mind that had never deserted me. All this{% endraw %}
{% raw %}came upon me with a distinctness which almost{% endraw %}
{% raw %}made me think I heard it whispered in my ear; and{% endraw %}
{% raw %}I believe I even turned my head to listen. I shrunk{% endraw %}
{% raw %}back, laid down the axe, and thanked God, as I have{% endraw %}
{% raw %}done every day since, that I did not commit that{% endraw %}
{% raw %}murder.{% endraw %}
{% raw %}My feelings were still agitated, but they were{% endraw %}
{% raw %}changed. I was filled with shame and remorse for{% endraw %}
{% raw %}the design I had entertained, and fearing that my{% endraw %}
{% raw %}companions would detect it in my face, or that a{% endraw %}
{% raw %}careless word would betray my guilty thoughts, I{% endraw %}
{% raw %}remained on deck all night, instead of rousing one{% endraw %}
{% raw %}of the men to relieve the watch, and nothing brought{% endraw %}
{% raw %}composure to my mind but the solemn resolution I{% endraw %}
{% raw %}then made, to resign myself to the will of God, and{% endraw %}
{% raw %}take with thankfulness, if I could, but with sub¬{% endraw %}
{% raw %}mission, at all events, whatever He might decide{% endraw %}
{% raw %}should be my lot.  Yet I believe that no one but those to{% endraw %}
{% raw %}whom I have told the story myself, ever suspected{% endraw %}
{% raw %}me of having entertained such thoughts for a{% endraw %}
{% raw %}moment.{% endraw %}


Specifying paths¶
The majority of the functions in gslab_make
contain a paths
argument that requires passing in a dictionary specifying default paths used for a variety of purposes. To fully use any function in the library, the dictionary must contain values for the following keys (i.e., default paths):
- config
Default path for
config.yaml
, a project configuration file containing global variables for all users.- config_user
Default path for
config_user.yaml
, a user configuration file containing local user-specific variables.- input_dir
Default path for sourcing (i.e., copying or making symbolic links to) input files located internal to the project directory.
- external_dir
Default path for sourcing (i.e., copying or making symbolic links to) external files located external to the project directory.
- output_dir
Default path to write and look for code outputs.
- makelog
Default path to write make log, a master log of activity.
- output_statslog
Default path to write output statistics log, a log containing file statistics for
output_dir
.- source_maplog
Default path to write source mapping log, a log that maps the original location for all sources in
input_dir
andexternal_dir
.- source_statslog
Default path to write source statistics log, a log containing file statistics for all sources in
input_dir
andexternal_dir
.
Note
To suppress writing any specific log, set the value for that log to ''
.
Warning
Many of the functions in gslab_make
will write status messages to the make log. If you have specified a make log in your paths
, you must initialize the makelog via start_makelog()
. Otherwise, attempting to call a function that writes to the make log will raise an exception.
Example paths¶
The following default paths are recommended:
import os
CONFIG_DIR = '..' # Adjust accordingly
PATHS = {
'config' : os.path.join(CONFIG_DIR, 'config.yaml'),
'config_user' : os.path.join(CONFIG_DIR, 'config_user.yaml'),
'input_dir' : 'input',
'external_dir' : 'external',
'output_dir' : 'output',
'makelog' : 'log/make.log',
'output_statslog' : 'log/output_stats.log',
'source_maplog' : 'log/source_map.log',
'source_statslog' : 'log/source_stats.log',
}
Functions in gslab_make
that require a paths
argument will specify the exact default paths required in their documentation.
General logging functions¶
The gslab_make
library provides functions to create a master log of activity (i.e., a make log) and to log information about output files. The logs are intended to facilitate the reproducibility of research.
Warning
You must initialize make logs via start_makelog()
as opposed to alternative methods (e.g., manually creating a make log file). Otherwise, any attempt to call a gslab_make
function that writes to make log will raise an exception.
-
start_makelog
(paths)¶ Writes file
makelog
, recording start time. Sets make log status to booleanTrue
, which is used by other functions to confirm make log exists.Note
The make log start condition is used by other functions to confirm a make log exists.
- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
- Path Keys
makelog (str) – Path of makelog.
- Returns
- Return type
None
-
end_makelog
(paths)¶ Appends to file
makelog
, recording end time.Note
We allow for writing to a make log even after the make log has ended. We do not recommend this for best practice.
- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
- Path Keys
makelog (str) – Path of makelog.
- Returns
- Return type
None
-
write_to_makelog
(paths, message)¶ Appends string
message
to filemakelog
.- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
message (str) – Message to append.
- Path Keys
makelog (str) – Path of makelog.
- Returns
- Return type
None
-
log_files_in_output
(paths, depth=inf)¶ Logs the following information for all files contained in directory
output_dir
.File name (in file
output_statslog
)Last modified (in file
output_statslog
)File size (in file
output_statslog
)File head (in file
output_headslog
, optional)
When walking through directory
output_dir
, floatdepth
determines level of depth to walk. Status messages are appended to filemakelog
.Include additional output directories to walk through (typically directories that you wish to keep local) in directory list
output_local_dir
.- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
depth (float, optional) – Level of depth when walking through output directory. Defaults to infinite.
- Path Keys
output_dir (str) – Path of output directory.
output_local_dir (str, list, optional) – Path or list of paths of local output directories. Defaults to
[]
(i.e., none).output_statslog (str) – Path to write output statistics log.
output_headslog (str, optional) – Path to write output headers log.
makelog (str) – Path of makelog.
- Returns
- Return type
None
Example
The following code will log information for all files contained in only the first level of
paths['output_dir']
. Therefore, files contained in subdirectories will be ignored.log_files_in_outputs(paths, depth = 1)
The following code will log information for any file in
paths['output_dir']
, regardless of level of subdirectory.log_files_in_outputs(paths, depth = float('inf'))
Sourcing functions¶
The gslab_make
library provides functions to create symbolic links to source files. Doing so avoids potential duplication of source files and any associated confusion. In the case of modules dedicated to LyX/LaTeX documents, there are optional functions to copy source files instead of creating symbolic links so that users without gslab_make
can still manually compile.
-
link_inputs
(paths, file_list)¶ Create symbolic links using instructions contained in files of list
file_list
. Instructions are string formatted using paths dictionarypaths
. Symbolic links are written in directoryinput_dir
. Status messages are appended to filemake log
.Instruction files on how to create symbolic links (destinations) from targets (sources) should be formatted in the following way.
# Each line of instruction should contain a destination and source delimited by a `|` # Lines beginning with # are ignored destination | source
Note
Symbolic links can be created to both files and directories.
Note
Instruction files can be specified with the * shell pattern (see here). Destinations and their sources can also be specified with the * shell pattern. The number of wildcards must be the same for both destinations and sources.
- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below. Dictionary additionally used to string format linking instructions.
file_list (str, list) – File or list of files containing linking instructions.
- Path Keys
input_dir (str) – Directory to write symlinks.
makelog (str) – Path of makelog.
- Returns
source_map – List of (source, destination) for each symlink created.
- Return type
list
Example
Suppose you call the following function.
link_inputs(paths, ['file1'], formatting_dict)
Suppose
paths
contained the following values.paths = {'root': '/User/root/', 'makelog': 'make.log', 'input_dir': 'input'}
Now suppose instruction file
file1
contained the following text.destination1 | {root}/source1
The
{root}
in the instruction file would be string formatted usingpaths
. Therefore, the function would parse the instruction as:destination1 | /User/root/source1
Example
The following code would use instruction files
file1
andfile2
to create symbolic links.link_inputs(paths, ['file1', 'file2'])
Suppose instruction file
file1
contained the following text.destination1 | source1 destination2 | source2
Symbolic links
destination1
anddestination1
would be created in directorypaths['input_dir']
. Their targets would besource1
andsource2
, respectively.Example
Suppose you have the following targets.
source1 source2 source3
Specifying
destination* | source*
in one of your instruction files would create the following symbolic links inpaths['input_dir']
.destination1 destination2 destination3
-
link_externals
(paths, file_list)¶ Create symbolic links using instructions contained in files of list
file_list
. Instructions are string formatted using paths dictionarypaths
. Symbolic links are written in directoryexternal_dir
. Status messages are appended to filemake log
.Instruction files on how to create symbolic links (destinations) from targets (sources) should be formatted in the following way.
# Each line of instruction should contain a destination and source delimited by a `|` # Lines beginning with # are ignored destination | source
Note
Symbolic links can be created to both files and directories.
Note
Instruction files can be specified with the * shell pattern (see here). Destinations and their sources can also be specified with the * shell pattern. The number of wildcards must be the same for both destinations and sources.
- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below. Dictionary additionally used to string format linking instructions.
file_list (str, list) – File or list of files containing linking instructions.
- Path Keys
external_dir (str) – Directory to write symlinks.
makelog (str) – Path of makelog.
- Returns
source_map – List of (source, destination) for each symlink created.
- Return type
list
Example
Suppose you call the following function.
link_externals(paths, ['file1'], formatting_dict)
Suppose
paths
contained the following values.paths = {'root': '/User/root/', 'makelog': 'make.log', 'input_dir': 'input'}
Now suppose instruction file
file1
contained the following text.destination1 | {root}/source1
The
{root}
in the instruction file would be string formatted usingpaths
. Therefore, the function would parse the instruction as:destination1 | /User/root/source1
Example
The following code would use instruction files
file1
andfile2
to create symbolic links.link_externals(paths, ['file1', 'file2'])
Suppose instruction file
file1
contained the following text.destination1 | source1 destination2 | source2
Symbolic links
destination1
anddestination1
would be created in directorypaths['external_dir']
. Their targets would besource1
andsource2
, respectively.Example
Suppose you have the following targets.
source1 source2 source3
Specifying
destination* | source*
in one of your instruction files would create the following symbolic links inpaths['external_dir']
.destination1 destination2 destination3
-
copy_inputs
(paths, file_list)¶ Create copies using instructions contained in files of list
file_list
. Instructions are string formatted using paths dictionarypaths
. Copies are written in directoryinput_dir
. Status messages are appended to filemake log
.Instruction files on how to create copies (destinations) from targets (sources) should be formatted in the following way.
# Each line of instruction should contain a destination and source delimited by a `|` # Lines beginning with # are ignored destination | source
Note
Instruction files can be specified with the * shell pattern (see here). Destinations and their sources can also be specified with the * shell pattern. The number of wildcards must be the same for both destinations and sources.
- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below. Dictionary additionally used to string format copying instructions.
file_list (str, list) – File or list of files containing copying instructions.
- Path Keys
input_dir (str) – Directory to write copies.
makelog (str) – Path of makelog.
- Returns
source_map – List of (source, destination) for each copy created.
- Return type
list
Example
Suppose you call the following function.
copy_inputs(paths, ['file1'], formatting_dict)
Suppose
paths
contained the following values.paths = {'root': '/User/root/', 'makelog': 'make.log', 'input_dir': 'input'}
Now suppose instruction file
file1
contained the following text.destination1 | {root}/source1
The
{root}
in the instruction file would be string formatted usingpaths
. Therefore, the function would parse the instruction as:destination1 | /User/root/source1
Example
The following code would use instruction files
file1
andfile2
to create copies.copy_inputs(paths, ['file1', 'file2'])
Suppose instruction file
file1
contained the following text.destination1 | source1 destination2 | source2
Copies
destination1
anddestination1
would be created in directorypaths['input_dir']
. Their targets would besource1
andsource2
, respectively.Example
Suppose you have the following targets.
source1 source2 source3
Specifying
destination* | source*
in one of your instruction files would create the following copies inpaths['input_dir']
.destination1 destination2 destination3
-
copy_externals
(paths, file_list)¶ Create copies using instructions contained in files of list
file_list
. Instructions are string formatted using paths dictionarypaths
. Copies are written in directoryexternal_dir
. Status messages are appended to filemake log
.Instruction files on how to create copies (destinations) from targets (sources) should be formatted in the following way.
# Each line of instruction should contain a destination and source delimited by a `|` # Lines beginning with # are ignored destination | source
Note
Instruction files can be specified with the * shell pattern (see here). Destinations and their sources can also be specified with the * shell pattern. The number of wildcards must be the same for both destinations and sources.
- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below. Dictionary additionally used to string format copying instructions.
file_list (str, list) – File or list of files containing copying instructions.
- Path Keys
external_dir (str) – Directory to write copies.
makelog (str) – Path of makelog.
- Returns
source_map – List of (source, destination) for each copy created.
- Return type
list
Example
Suppose you call the following function.
copy_externals(paths, ['file1'], formatting_dict)
Suppose
paths
contained the following values.paths = {'root': '/User/root/', 'makelog': 'make.log', 'input_dir': 'input'}
Now suppose instruction file
file1
contained the following text.destination1 | {root}/source1
The
{root}
in the instruction file would be string formatted usingpaths
. Therefore, the function would parse the instruction as:destination1 | /User/root/source1
Example
The following code would use instruction files
file1
andfile2
to create copies.copy_externals(paths, ['file1', 'file2'])
Suppose instruction file
file1
contained the following text.destination1 | source1 destination2 | source2
Copies
destination1
anddestination1
would be created in directorypaths['external_dir']
. Their targets would besource1
andsource2
, respectively.Example
Suppose you have the following targets.
source1 source2 source3
Specifying
destination* | source*
in one of your instruction files would create the following copies inpaths['external_dir']
.destination1 destination2 destination3
Source logging functions¶
The gslab_make
library provides functions to log symbolic linking/copying activity and information about source files. The logs are intended to facilitate the reproducibility of research.
-
write_source_logs
(paths, source_map, depth=inf)¶ Logs the following information for sources contained in list
source_map
(returned by sourcing functions).Mapping of symlinks/copies to sources (in file
source_maplog
)Details on files contained in sources:
File name (in file
source_statslog
)Last modified (in file
source_statslog
)File size (in file
source_statslog
)File head (in file
source_headlog
, optional)
When walking through sources, float
depth
determines level of depth to walk. Status messages are appended to filemakelog
.- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
source_map (list) – Mapping of symlinks/copies (destination) to sources (returned by sourcing functions).
depth (float, optional) – Level of depth when walking through source directories. Defaults to infinite.
- Path Keys
source_statslog (str) – Path to write source statistics log.
source_headslog (str, optional) – Path to write source headers log.
source_maplog (str) – Path to write source map log.
makelog (str) – Path of makelog.
- Returns
- Return type
None
Example
The following code will log information for all files listed in
source_map
. Therefore, files contained in directories listed insource_map
will be ignored.write_source_logs(paths, depth = 1)
The following code will log information for all files listed in
source_map
and any file in all directories listed insource_map
, regardless of level of subdirectory.write_source_logs(paths, depth = float('inf'))
Program functions¶
The gslab_make
library provides functions to run code scripts (i.e., programs) for certain applications. These program functions are implemented as Python wrappers around system commands.
Note
To use the program function for a specific application, please make sure that you have set up command line usage for the application.
Default settings¶
Unless specified otherwise, the program functions will assume the following default executables when executing your program.
default_executables = {
'posix':
{'lyx' : 'lyx',
'perl' : 'perl',
'python' : 'python',
'math' : 'math',
'matlab' : 'matlab',
'r' : 'Rscript',
'sas' : 'sas',
'st' : 'st',
'stata' : 'stata-mp'},
'nt':
{'lyx' : 'lyx',
'perl' : 'perl',
'python' : 'python',
'matlab' : 'matlab',
'math' : 'math',
'r' : 'Rscript',
'sas' : 'sas',
'st' : 'st',
'stata' : '%STATAEXE%'}
To change the default executables, we recommend importing in a user configuration file using the update_executables()
. We do not recommend passing in an executable name into the executable
argument of your program function as this will be global for any user.
The program functions will assume the following default options when executing system command.
default_options = {
'posix':
{'lyx' : '-e pdf2',
'perl' : '',
'python' : '',
'math' : '-noprompt',
'matlab' : '-nosplash -nodesktop',
'r' : '--no-save',
'st' : '',
'sas' : '',
'stata' : '-e'},
'nt':
{'lyx' : '-e pdf2',
'perl' : '',
'python' : '',
'matlab' : '-nosplash -minimize -wait',
'math' : '-noprompt',
'r' : '--no-save',
'st' : '',
'sas' : '-nosplash',
'stata' : '/e'}
}
To change the default options, you may pass your desired options into the options
argument of your program function.
Supported applications¶
-
run_jupyter
(paths, program, timeout=None, kernel_name='')¶ Run Jupyter notebook using system command.
Runs notebook
program
using Python API, with notebook specified in the form ofnotebook.ipynb
. Status messages are appended to filemakelog
.- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
program (str) – Path of script to run.
- Path Keys
makelog (str) – Path of makelog.
Note
We recommend leaving all other parameters to their defaults.
- Other Parameters
timeout (int, optional) – Time to wait (in seconds) to finish executing a cell before raising exception. Defaults to no timeout.
kernel_name (str, optional) – Name of kernel to use for execution (e.g.,
python2
for standard Python 2 kernel,python3
for standard Python 3 kernel). Defaults to''
(i.e., kernel specified in notebook).
- Returns
- Return type
None
Example
run_jupyter(paths, program = 'notebook.ipynb')
-
run_lyx
(paths, program, doctype='', **kwargs)¶ Compiles document
program
using system command, with document specified in the form ofscript.lyx
. Status messages are appended to filemakelog
. PDF outputs are written in directoryoutput_dir
.- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
program (str) – Path of script to run.
doctype (str, optional) – Type of LyX document. Takes either
'handout'
and'comments'
. All other strings will default to standard document type. Defaults to''
(i.e., standard document type).
- Path Keys
makelog (str) – Path of makelog.
output_dir (str) – Directory to write PDFs.
Note
We recommend leaving all other parameters to their defaults.
- Other Parameters
osname (str, optional) – Name of OS. Used to determine syntax of system command. Defaults to
os.name
.shell (bool, optional) – See here. Defaults to
True
.log (str, optional) – Path of program log. Program log is only written if specified. Defaults to
''
(i.e., not written).executable (str, optional) – Executable to use for system command. Defaults to executable specified in default settings.
option (str, optional) – Options for system command. Defaults to options specified in default settings.
args (str, optional) – Not applicable.
- Returns
- Return type
None
Example
run_lyx(paths, program = 'script.lyx')
-
run_mathematica
(paths, program, **kwargs)¶ Runs script
program
using system command, with script specified in the form ofscript.m
. Status messages are appended to filemakelog
.- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
program (str) – Path of script to run.
- Path Keys
makelog (str) – Path of makelog.
Note
We recommend leaving all other parameters to their defaults.
- Other Parameters
osname (str, optional) – Name of OS. Used to determine syntax of system command. Defaults to
os.name
.shell (bool, optional) – See here. Defaults to
True
.log (str, optional) – Path of program log. Program log is only written if specified. Defaults to
''
(i.e., not written).executable (str, optional) – Executable to use for system command. Defaults to executable specified in default settings.
option (str, optional) – Options for system command. Defaults to options specified in default settings.
args (str, optional) – Not applicable.
- Returns
- Return type
None
Example
run_mathematica(paths, program = 'script.m')
-
run_matlab
(paths, program, **kwargs)¶ Runs script
program
using system command, with script specified in the form ofscript.m
. Status messages are appended to filemakelog
.- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
program (str) – Path of script to run.
- Path Keys
makelog (str) – Path of makelog.
Note
We recommend leaving all other parameters to their defaults.
- Other Parameters
osname (str, optional) – Name of OS. Used to determine syntax of system command. Defaults to
os.name
.shell (bool, optional) – See here. Defaults to
True
.log (str, optional) – Path of program log. Program log is only written if specified. Defaults to
''
(i.e., not written).executable (str, optional) – Executable to use for system command. Defaults to executable specified in default settings.
option (str, optional) – Options for system command. Defaults to options specified in default settings.
args (str, optional) – Not applicable.
- Returns
- Return type
None
Example
run_matlab(paths, program = 'script.m')
-
run_perl
(paths, program, **kwargs)¶ Runs script
program
using system command, with script specified in the form ofscript.pl
. Status messages are appended to filemakelog
.- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
program (str) – Path of script to run.
- Path Keys
makelog (str) – Path of makelog.
Note
We recommend leaving all other parameters to their defaults.
- Other Parameters
osname (str, optional) – Name of OS. Used to determine syntax of system command. Defaults to
os.name
.shell (bool, optional) – See here. Defaults to
True
.log (str, optional) – Path of program log. Program log is only written if specified. Defaults to
''
(i.e., not written).executable (str, optional) – Executable to use for system command. Defaults to executable specified in default settings.
option (str, optional) – Options for system command. Defaults to options specified in default settings.
args (str, optional) – Arguments for system command. Defaults to no arguments.
- Returns
- Return type
None
Example
run_perl(paths, program = 'script.pl')
-
run_python
(paths, program, **kwargs)¶ Runs script
program
using system command, with script specified in the form ofscript.py
. Status messages are appended to filemakelog
.- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
program (str) – Path of script to run.
- Path Keys
makelog (str) – Path of makelog.
Note
We recommend leaving all other parameters to their defaults.
- Other Parameters
osname (str, optional) – Name of OS. Used to determine syntax of system command. Defaults to
os.name
.shell (bool, optional) – See here. Defaults to
True
.log (str, optional) – Path of program log. Program log is only written if specified. Defaults to
''
(i.e., not written).executable (str, optional) – Executable to use for system command. Defaults to executable specified in default settings.
option (str, optional) – Options for system command. Defaults to options specified in default settings.
args (str, optional) – Arguments for system command. Defaults to no arguments.
- Returns
- Return type
None
Example
run_python(paths, program = 'script.py')
-
run_r
(paths, program, **kwargs)¶ Runs script
program
using system command, with script specified in the form ofscript.R
. Status messages are appended to filemakelog
.- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
program (str) – Path of script to run.
- Path Keys
makelog (str) – Path of makelog.
Note
We recommend leaving all other parameters to their defaults.
- Other Parameters
osname (str, optional) – Name of OS. Used to determine syntax of system command. Defaults to
os.name
.shell (bool, optional) – See here. Defaults to
True
.log (str, optional) – Path of program log. Program log is only written if specified. Defaults to
''
(i.e., not written).executable (str, optional) – Executable to use for system command. Defaults to executable specified in default settings.
option (str, optional) – Options for system command. Defaults to options specified in default settings.
args (str, optional) – Not applicable.
- Returns
- Return type
None
Example
run_r(paths, program = 'script.R')
-
run_sas
(paths, program, lst='', **kwargs)¶ Runs script
program
using system command, with script specified in the form ofscript.sas
. Status messages are appended to filemakelog
.- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
program (str) – Path of script to run.
lst (str, optional) – Path of program lst. Program lst is only written if specified. Defaults to
''
(i.e., not written).
- Path Keys
makelog (str) – Path of makelog.
Note
We recommend leaving all other parameters to their defaults.
- Other Parameters
osname (str, optional) – Name of OS. Used to determine syntax of system command. Defaults to
os.name
.shell (bool, optional) – See here. Defaults to
True
.log (str, optional) – Path of program log. Program log is only written if specified. Defaults to
''
(i.e., not written).executable (str, optional) – Executable to use for system command. Defaults to executable specified in default settings.
option (str, optional) – Options for system command. Defaults to options specified in default settings.
args (str, optional) – Not applicable.
- Returns
- Return type
None
Example
run_sas(paths, program = 'script.sas')
-
run_stat_transfer
(paths, program, **kwargs)¶ Runs script
program
using system command, with script specified in the form ofscript.stc
orscript.stcmd
. Status messages are appended to filemakelog
.- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
program (str) – Path of script to run.
- Path Keys
makelog (str) – Path of makelog.
Note
We recommend leaving all other parameters to their defaults.
- Other Parameters
osname (str, optional) – Name of OS. Used to determine syntax of system command. Defaults to
os.name
.shell (bool, optional) – See here. Defaults to
True
.log (str, optional) – Path of program log. Program log is only written if specified. Defaults to
''
(i.e., not written).executable (str, optional) – Executable to use for system command. Defaults to executable specified in default settings.
option (str, optional) – Options for system command. Defaults to options specified in default settings.
args (str, optional) – Not applicable.
- Returns
- Return type
None
Example
run_stat_transfer(paths, program = 'script.stc')
-
run_stata
(paths, program, **kwargs)¶ Runs script
program
using system command, with script specified in the form ofscript.do
. Status messages are appended to filemakelog
.- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
program (str) – Path of script to run.
- Path Keys
makelog (str) – Path of makelog.
Note
We recommend leaving all other parameters to their defaults.
- Other Parameters
osname (str, optional) – Name of OS. Used to determine syntax of system command. Defaults to
os.name
.shell (bool, optional) – See here. Defaults to
True
.log (str, optional) – Path of program log. Program log is only written if specified. Defaults to
''
(i.e., not written).executable (str, optional) – Executable to use for system command. Defaults to executable specified in default settings.
option (str, optional) – Options for system command. Defaults to options specified in default settings.
args (str, optional) – Not applicable.
- Returns
- Return type
None
Example
run_stata(paths, program = 'script.do')
-
execute_command
(paths, command, **kwargs)¶ Runs system command command with shell execution boolean
shell
. Outputs are appended to filemakelog
and written to system command log filelog
. Status messages are appended to filemakelog
.- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
command (str) – System command to run.
shell (bool, optional) –
See here. Defaults to
True
.log (str, optional) – Path of system command log. System command log is only written if specified. Defaults to
''
(i.e., not written).
- Path Keys
makelog (str) – Path of makelog.
Note
We recommend leaving all other parameters to their defaults.
- Other Parameters
osname (str, optional) – Name of OS. Used to check if OS is supported. Defaults to
os.name
.- Returns
- Return type
None
Example
The following code executes the
ls
command, writes outputs to system command log file'file'
, and appends outputs and/or status messages topaths['makelog']
.execute_command(paths, 'ls', log = 'file')
-
run_module
(root, module, build_script='make.py')¶ Runs script build_script in module directory module relative to root of repository root.
- Parameters
root (str) – Directory of root.
module (str) – Name of module.
build_script (str) – Name of build script. Defaults to
make.py
.
- Returns
- Return type
None
Example
The following code runs the script
root/module/make.py
.run_module(root = 'root', module = 'module')
Utility functions¶
The gslab_make
library provides general utility functions for build scripts. Functions to update executable names/path mappings and copy outputs are included.
-
update_executables
(paths, osname='nt')¶ Updates executable names with executables listed in file
config_user
.Note
Executable names are used by program functions.
- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
osname (str, optional) – Name of OS. Defaults to
os.name
.
- Path Keys
config_user (str) – Path of user configuration file.
- Returns
- Return type
None
-
update_paths
(paths)¶ Updates dictionary
paths
with externals listed in fileconfig_user
.Note
The
paths
argument for sourcing functions is used not only to get default paths for writing/logging, but also to string format sourcing instructions.- Parameters
paths (dict) – Dictionary of paths to update. Dictionary should ex-ante contain values for all keys listed below.
- Path Keys
config_user (str) – Path of user configuration file.
- Returns
paths – Dictionary of updated paths.
- Return type
dict
-
copy_output
(file, copy_dir)¶ Copies output
file
to directorycopy_dir
with user prompt to confirm copy.- Parameters
file (str) – Path of file to copy.
copy_dir (str) – Directory to copy file.
- Returns
- Return type
None
Directory functions¶
The gslab_make
library provides functions to make modifications to a directory. Functions to remove files and directories, clear directories, and zip/unzip files are included.
-
remove_path
(path, option='', quiet=False)¶ Remove path
path
using system command. Safely removes symbolic links. Path can be specified with the * shell pattern (see here).- Parameters
path (str) – Path to remove.
option (str, optional) – Options for system command. Defaults to
-rf
for POSIX and/s /q
for NT.quiet (bool, optional) – Suppress printing of path removed. Defaults to
False
.
- Returns
- Return type
None
Example
The following code removes path
path
.remove_path('path')
The following code removes all paths beginning with
path
.remove_path('path*')
-
remove_dir
(dir_list, quiet=False)¶ Remove directories in list
dir_list
using system command. Safely removes symbolic links. Directories can be specified with the * shell pattern (see here).- Parameters
dir_list (str, list) – Directory or list of directories to remove.
quiet (bool, optional) – Suppress printing of directories removed. Defaults to
False
.
- Returns
- Return type
None
Example
The following code removes directories
dir1
anddir2
.remove_dir(['dir1', 'dir2'])
The following code removes directories beginning with
dir
.remove_dir(['dir1*'])
-
clear_dir
(dir_list)¶ Clears all directories in list
dir_list
using system command. Safely clears symbolic links. Directories can be specified with the * shell pattern (see here).Note
To clear a directory means to remove all contents of a directory. If the directory is nonexistent, the directory is created.
- Parameters
dir_list (str, list) – Directory or list of directories to clear.
- Returns
- Return type
None
Example
The following code clears directories
dir1
anddir2
.clear_dir(['dir1', 'dir2'])
The following code clears directories beginning with
dir
.clear_dir(['dir1*'])
-
unzip
(zip_path, output_dir)¶ Unzips file
zip_path
to directoryoutput_dir
.- Parameters
zip_path (str) – Path of file to unzip.
output_dir (str) – Directory to write outputs of unzipped file.
- Returns
- Return type
None
-
zip_dir
(source_dir, zip_dest)¶ Zips directory
source_dir
to filezip_dest
.- Parameters
source_dir (str) – Path of directory to zip.
zip_dest (str) – Destination of zip file.
- Returns
- Return type
None
Repository functions¶
The gslab_make
library provides functions to check file sizes in a repository and modification status of files tracked by git. The checks are intended to facilitate proper committing activity.
-
check_module_size
(paths)¶ Checks file sizes for files to be committed in the current working directory. Compares file sizes to size limits in file
config
and produces warnings if any of the following limits are exceeded.Individual size of a file tracked by git lfs (
file_MB_limit_lfs
)Total size of all files tracked by git lfs (
total_MB_limit_lfs
)Individual size of a file tracked by git (
file_MB_limit
)Total size of all files tracked by git (
total_MB_limit
)
Warning messages are appended to file
makelog
.- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
- Path Keys
config (str) – Path of project configuration file.
makelog (str) – Path of makelog.
- Returns
- Return type
None
-
get_modified_sources
(paths, source_map, depth=inf)¶ Checks the modification status for all sources contained in list
source_map
(returned by sourcing functions). Produces warning if sources have been modified according to git. When walking through sources, floatdepth
determines level of depth to walk. Warning messages are appended to filemakelog
.- Parameters
paths (dict) – Dictionary of paths. Dictionary should contain values for all keys listed below.
source_map (list) – Mapping of sources (returned from sourcing functions).
depth (float, optional) – Level of depth when walking through source directories. Defaults to infinite.
- Path Keys
makelog (str) – Path of makelog.
- Returns
overlap – List of source files considered changed by git.
- Return type
list
Notes
Filling functions¶
The gslab_make
library provides functions fill in tables and text in LyX/LaTeX documents.
-
tablefill
(inputs, template, output, null=None)¶ Fills tables in document
template
using files in listinputs
. Writes filled document to fileoutput
. Null characters ininputs
are replaced with valuenull
.- Parameters
inputs (list) – Input or list of inputs to fill into template.
template (str) – Path of template to fill.
output (str) – Path of output.
null (str) – Value to replace null characters (i.e.,
''
,'.'
,'NA'
). Defaults to no replacement.
- Returns
- Return type
None
Example
################################################################# # tablefill_readme.txt - Help/Documentation for tablefill.py ################################################################# Description: tablefill.py is a Python module designed to fill LyX/Tex tables with output from text files (usually output from Stata or Matlab). Usage: Tablefill takes as input a LyX (or Tex) file containing empty tables (the template file) and text files containing data to be copied to these tables (the input files), and produces a LyX (or Tex) file with filled tables (the output file). For brevity, LyX will be used to denote LyX or Tex files throughout. Tablefill must first be imported to make.py. This is typically achieved by including the following lines: ``` from gslab_fill.tablefill import tablefill ``` Once the module has been imported, the syntax used to call tablefill is as follows: ``` tablefill(input = 'input_file(s)', template = 'template_file', output = 'output_file') ``` The argument 'template' is the user written LyX file which contains the tables to be filled in. The argument 'input' is a list of the text files containing the output to be copied to the LyX tables. If there are multiple input text files, they are listed as: input = 'input_file_1 input_file_2'. The argument 'output' is the name of the filled LyX file to be produced. Note that this file is created by tablefill.py and should not be edited manually by the user. ########################### Input File Format: ########################### The data needs to be tab-delimited rows of numbers (or characters), preceeded by `<label>`. The < and > are mandatory. The numbers can be arbitrarily long, can be negative, and can also be in scientific notation. Examples: ---------- ``` <tab:Test> 1 2 3 2 3 1 3 1 2 ``` ``` <tab:FunnyMat> 1 2 3 23 2 2 3 3 1 2 2 1 ``` (The rows do not need to be of equal length.) Completely blank (no tab) lines are ignored. If a "cell" is merely "." or "[space]", then it is treated as completely missing. That is, in the program: ``` <tab:Test> 1 2 3 2 . 1 3 3 1 2 ``` is equivalent to: ``` <tab:Test> 1 2 3 2 1 3 3 1 2 ``` This feature is useful as Stata outputs missing values in numerical variables as ".", and missing values in string variables as "[space]". ................................ Scientific Notation Notes: ................................ The scientific notation ihas to be of the form: [numbers].[numbers]e(+/-)[numbers] Examples: ``` 23.2389e+23 -2.23e-2 -0.922e+3 ``` ########################### Template LyX Format: ########################### The LyX template file determines where the numbers from the input files are placed. Every table in the template file (if it is to be filled) must appear within a float. There must be one, and only one, table object inside the float, and the table name must include a label object that corresponds to the label of the required table in the input file. Note that table names cannot be duplicated. For a single template file, each table to be filled must have a unique label, and there must be one, and only one, table with that same label in the text files used as input. Having multiple tables with the same name in the input files or in the template file will cause errors. Note also that labels are NOT case-sensitive. That is, <TAB:Table1> is considered the same as `<tab:table1>`. In the LyX tables, "cells" to be filled with entries from the input text files are indicated by the following tags: `"###" (no quotes)` or `"#[number][,]#" (no quotes)` The first case will result in a literal substitution. I.e. whatever is in the text tables for that cell will be copied over. The second case will convert the data table's number (if in scientific notation) and will truncate this converted number to [number] decimal places. It will automatically round while doing so. If a comma appears after the number (within #[number]#), then it will add commas to the digits to the left of the decimal place. Examples: --------- ``` 2309.2093 + ### = 2309.2093 2309.2093 + #4# = 2309.2093 2309.2093 + #5# = 2309.20930 2309.2093 + #20# = 2309.20930000000000000000 2309.2093 + #3# = 2309.209 2309.2093 + #2# = 2309.21 2309.2093 + #0# = 2309 2309.2093 + #0,# = 2,309 ``` ``` -2.23e-2 + #2# = -0.0223 + #2# = -0.02 -2.23e-2 + #7# = -0.0223 + #7# = -0.0223000 -2.23e+10 + #7,# = -22300000000 + #7,# = -22,300,000,000.000000 ``` Furthermore, only ###/#num# will be replaced, allowing you to put things around ###/#num# to alter the final output: Examples: -------- ``` 2309.2093 + (#2#) = (2309.21) 2309.2093 + #2#** = 2309.21** 2309.2093 + ab#2#cd = ab2309.21cd ``` If you are doing exact substitution, then you can use characters: Examples: --------- `abc + ### = abc` ................................ Intentionally blank cells: ................................ If you would like to display a blank cell, you can use "---": Examples: --------- ``` --- + ### = --- --- + #3# = --- ``` ###################### # Example Combinations # Of input + template ###################### Example 1 (Simple) ---------- ``` Input: <tab:Test> 1 2 3 2 1 3 3 1 2 Template: `<tab:Test> ` (pretend this is what you see in LyX) ### ### ### ### ### ### ### ### ### Result:<tab:Test> 1 2 3 2 1 3 3 1 2 ``` Example 2 (More Complicated) ---------- ``` Input: <tab:Test> 1 . 3 2e-5 1 3.023 . -1 2 3 Template: <tab:Test> (pretend this is what you see in LyX) (###) 2 ### #3# ### #1# NA ### ### ### Result:<tab:Test> (1) 2 3 0.000 1 3.0 NA -1 2 3 ``` =================== ====Important====== =================== By design, missings in input table and "missings" in template do not have to line up. Example 3 (LyX) ---------- ``` Input: <tab:Test> 1 . 3 2e-5 . 3.023 . -1 2 Template: <tab:Test> ### ### abc abc #2# #3# NA ### ### Result:<tab:Test> 1 3 abc abc 0.00 3.023 NA -1 2 Recall that to the program, the above input table is no different from: 1 3 2e-5 3.023 -1 2 ``` It doesn't "know" where the numbers should be placed within a row, only what the next number to place should be. Similarly: Example 4 (LyX) ---------- ``` Input: <tab:Test> 1 1 2 1 1 3 2 -1 2 Template: <tab:Test> ### ### ### abc abc abc ### #2# #3# ### ### ### Result:<tab:Test> 1 1 2 abc abc abc 1 1.00 3.000 2 -1 2 ``` If a row in the template has no substitutions, then it's not really a row from the program's point of view. ###################### # Error Logging ###################### If an error occurs during the call to tablefill, it will be displayed in the command window. When make.py finishes, the user will be able to scroll up through the output and examine any error messages. Error messages, which include a description of the error type and a traceback to the line of code where the error occured, can also be retuned as a string object using the following syntax: exitmessage = tablefill( input = 'input_file(s)', template = 'template_file', output = 'output_file' ) Lines can then be added to make.py to output this string to a log file using standard Python and built in gslab_make commands. ###################### # Common Errors ###################### Common mistakes which can lead to errors include: - Mismatch between the length of the LyX table and the corresponding text table. If the LyX table has more entries to be filled than the text table has entries to fill from, this will cause an error and the table will not be filled. - Use of numerical tags (e.g. #1#) to fill non-numerical data. This will cause an error. Non-numerical data can only be filled using "###", as it does not make sense to round or truncate this data. - Multiple table objects in the same float. Each table float in the template LyX file can only contain one table object. If a float contains a second table object, this table will not be filled. ###################### # Boldfacing entries ###################### It is straightforward to develop functions that conditionally write entries of tables in boldface; functions may do so by inserting '\series bold' in the lines of the filled LyX file immeadiately before phrases that the user wishes to make bold.


This tutorial focuses on the boto interface to Elastic Mapreduce from Amazon Web Services. This tutorial assumes that you have already downloaded and installed boto.
The first step in accessing Elastic Mapreduce is to create a connection to the service. There are two ways to do this in boto. The first is:
>>> from boto.emr.connection import EmrConnection
>>> conn = EmrConnection('<aws access key>', '<aws secret key>')
At this point the variable conn will point to an EmrConnection object. In this example, the AWS access key and AWS secret key are passed in to the method explicitly. Alternatively, you can set the environment variables:
AWS_ACCESS_KEY_ID - Your AWS Access Key ID AWS_SECRET_ACCESS_KEY - Your AWS Secret Access Key
and then call the constructor without any arguments, like this:
>>> conn = EmrConnection()
There is also a shortcut function in boto that makes it easy to create EMR connections:
>>> import boto.emr
>>> conn = boto.emr.connect_to_region('us-west-2')
In either case, conn points to an EmrConnection object which we will use throughout the remainder of this tutorial.
Upon creating a connection to Elastic Mapreduce you will next want to create one or more jobflow steps. There are two types of steps, streaming and custom jar, both of which have a class in the boto Elastic Mapreduce implementation.
Creating a streaming step that runs the AWS wordcount example, itself written in Python, can be accomplished by:
>>> from boto.emr.step import StreamingStep
>>> step = StreamingStep(name='My wordcount example',
... mapper='s3n://elasticmapreduce/samples/wordcount/wordSplitter.py',
... reducer='aggregate',
... input='s3n://elasticmapreduce/samples/wordcount/input',
... output='s3n://<my output bucket>/output/wordcount_output')
where <my output bucket> is a bucket you have created in S3.
Note that this statement does not run the step, that is accomplished later when we create a jobflow.
Additional arguments of note to the streaming jobflow step are cache_files, cache_archive and step_args. The options cache_files and cache_archive enable you to use the Hadoops distributed cache to share files amongst the instances that run the step. The argument step_args allows one to pass additional arguments to Hadoop streaming, for example modifications to the Hadoop job configuration.
The second type of jobflow step executes tasks written with a custom jar. Creating a custom jar step for the AWS CloudBurst example can be accomplished by:
>>> from boto.emr.step import JarStep
>>> step = JarStep(name='Coudburst example',
... jar='s3n://elasticmapreduce/samples/cloudburst/cloudburst.jar',
... step_args=['s3n://elasticmapreduce/samples/cloudburst/input/s_suis.br',
... 's3n://elasticmapreduce/samples/cloudburst/input/100k.br',
... 's3n://<my output bucket>/output/cloudfront_output',
... 36, 3, 0, 1, 240, 48, 24, 24, 128, 16])
Note that this statement does not actually run the step, that is accomplished later when we create a jobflow. Also note that this JarStep does not include a main_class argument since the jar MANIFEST.MF has a Main-Class entry.
Once you have created one or more jobflow steps, you will next want to create and run a jobflow. Creating a jobflow that executes either of the steps we created above can be accomplished by:
>>> import boto.emr
>>> conn = boto.emr.connect_to_region('us-west-2')
>>> jobid = conn.run_jobflow(name='My jobflow',
... log_uri='s3://<my log uri>/jobflow_logs',
... steps=[step])
The method will not block for the completion of the jobflow, but will immediately return. The status of the jobflow can be determined by:
>>> status = conn.describe_jobflow(jobid)
>>> status.state
u'STARTING'
One can then use this state to block for a jobflow to complete. Valid jobflow states currently defined in the AWS API are COMPLETED, FAILED, TERMINATED, RUNNING, SHUTTING_DOWN, STARTING and WAITING.
In some cases you may not have built all of the steps prior to running the jobflow. In these cases additional steps can be added to a jobflow by running:
>>> conn.add_jobflow_steps(jobid, [second_step])
If you wish to add additional steps to a running jobflow you may want to set the keep_alive parameter to True in run_jobflow so that the jobflow does not automatically terminate when the first step completes.
The run_jobflow method has a number of important parameters that are worth investigating. They include parameters to change the number and type of EC2 instances on which the jobflow is executed, set a SSH key for manual debugging and enable AWS console debugging.
By default when all the steps of a jobflow have finished or failed the jobflow terminates. However, if you set the keep_alive parameter to True or just want to halt the execution of a jobflow early you can terminate a jobflow by:
>>> import boto.emr
>>> conn = boto.emr.connect_to_region('us-west-2')
>>> conn.terminate_jobflow('<jobflow id>')


Custom effect for mouse pad.
More...
Custom effect for mouse pad.
Definition at line 39 of file Custom.cs.
| Corale.Colore.Razer.Mousepad.Effects.Custom.Custom |
( |
Color |
color | ) |
|
Initializes a new instance of the Custom struct with a default color to apply to every LED.
- Parameters
-
| color | The color to set every LED to initially. |
Definition at line 52 of file Custom.cs.
| Corale.Colore.Razer.Mousepad.Effects.Custom.Custom |
( |
IList< Color > |
colors | ) |
|
Initializes a new instance of the Custom struct.
- Parameters
-
- Exceptions
-
| ArgumentException | Thrown if the colors list supplied is of an incorrect size. |
Definition at line 65 of file Custom.cs.
| Corale.Colore.Razer.Mousepad.Effects.Custom.Custom |
( |
Custom |
other | ) |
|
Initializes a new instance of the Custom struct with the colors copied from another struct of the same type.
- Parameters
-
| other | The struct to copy data from. |
Definition at line 85 of file Custom.cs.
| void Corale.Colore.Razer.Mousepad.Effects.Custom.Clear |
( |
| ) |
|
| Custom Corale.Colore.Razer.Mousepad.Effects.Custom.Clone |
( |
| ) |
|
Returns a copy of this struct.
- Returns
- A copy of this struct.
Definition at line 164 of file Custom.cs.
| static Custom Corale.Colore.Razer.Mousepad.Effects.Custom.Create |
( |
| ) |
|
|
static |
Create a new empty Custom struct.
- Returns
- An instance of Custom filled with the color black.
Definition at line 154 of file Custom.cs.
| override bool Corale.Colore.Razer.Mousepad.Effects.Custom.Equals |
( |
object |
obj | ) |
|
Indicates whether this instance and a specified object are equal.
- Parameters
-
| obj | Another object to compare to. |
- Returns
true
if obj and this instance are the same type and represent the same value; otherwise, false
.
<filterpriority>2</filterpriority>
Definition at line 210 of file Custom.cs.
| bool Corale.Colore.Razer.Mousepad.Effects.Custom.Equals |
( |
Custom |
other | ) |
|
Indicates whether the current object is equal to another object of the same type.
- Parameters
-
| other | An object to compare with this object. |
- Returns
true
if the current object is equal to the other parameter; otherwise, false
.
Definition at line 229 of file Custom.cs.
| bool Corale.Colore.Razer.Mousepad.Effects.Custom.Equals |
( |
IList< Color > |
other | ) |
|
Indicates whether the current object is equal to an instance of IList<Color>.
- Parameters
-
| other | An object to compare with this object. |
- Returns
true
if the current object is equal to the other parameter; otherwise, false
.
Definition at line 248 of file Custom.cs.
| override int Corale.Colore.Razer.Mousepad.Effects.Custom.GetHashCode |
( |
| ) |
|
Returns the hash code for this instance.
- Returns
- A 32-bit signed integer that is the hash code for this instance.
<filterpriority>2</filterpriority>
Definition at line 176 of file Custom.cs.
| static bool Corale.Colore.Razer.Mousepad.Effects.Custom.operator!= |
( |
Custom |
left, |
|
|
object |
right |
|
) |
| |
|
static |
Compares an instance of Custom with another object for inequality.
- Parameters
-
| left | The left operand, an instance of Custom. |
| right | The right operand, any type of object. |
- Returns
true
if the two objects are not equal, otherwise false
.
Definition at line 144 of file Custom.cs.
| static bool Corale.Colore.Razer.Mousepad.Effects.Custom.operator== |
( |
Custom |
left, |
|
|
object |
right |
|
) |
| |
|
static |
Compares an instance of Custom with another object for equality.
- Parameters
-
| left | The left operand, an instance of Custom. |
| right | The right operand, any type of object. |
- Returns
true
if the two objects are equal, otherwise false
.
Definition at line 132 of file Custom.cs.
| void Corale.Colore.Razer.Mousepad.Effects.Custom.Set |
( |
Color |
color | ) |
|
Sets all the LED indices to the specified Color.
- Parameters
-
| color | The Color to set the LEDs to. |
Definition at line 186 of file Custom.cs.
| readonly Color [] Corale.Colore.Razer.Mousepad.Effects.Custom._colors |
|
private |
Colors for the LEDs.
Definition at line 45 of file Custom.cs.
| Color Corale.Colore.Razer.Mousepad.Effects.Custom.this[int led] |
|
getset |
Gets or sets LEDs in the custom array.
- Parameters
-
| led | Index of the LED to access. |
- Returns
- The Color at the specified position.
Definition at line 97 of file Custom.cs.
The documentation for this struct was generated from the following file:
- Corale.Colore/Razer/Mousepad/Effects/Custom.cs


Command reference¶
Usage and possible options for each command can be displayed in the shell by calling a command with -h or –help option.
All commands support auto-completion of virtual environment names.
All commands return:
- ‘0’ exit code on successful execution;
- ‘1’ exit code when an error occurres;
- ‘2’ exit code on invocation syntax errors.
mkvenv¶
mkvenv command is a wrapper for venv/pyvenv/virtualenv and pip install
Usage: mkvenv [OPTIONS] VENV_NAME
mkvenv command creates new virtual environment with the name of VENV_NAME in directory specified by PYVENVWRAPPER_ENV_DIR and new project directory with the same name in directoy specified by PYVENVWRAPPER_PROJ_DIR, if this variable is set. Additional options, that modify this command’s behavior are described below.
Mandatory arguments to long options are mandatory for short options too. Combined options are not supported, i.e. instead of ‘-aj’ use ‘-a -j’.
-o, --options <options> Options to provide to underlying tool for virtual environment creation. See additional information below. -i, --install <requirements> Install packages listed in requirements using pip after virtual environment is created. <requirements> should be quoted string in “pip install” requirement specifier format. mkvenv will automatically try to install pip if it isn’t already available. -r, --requirements <file> Install packages listed in requirements file using pip after virtual environment is created. <file> should be path pointing to a file containing requirement specifications in “pip install -r” requirements file format. mkvenv will automatically try to install pip if it isn’t already available. -u, --util <util name> Specify the name of utility to use for virtual environment creation. By default mkvenv tries to use “venv” first, if it’s not available mkvenv tries to use “pyvenv” and then “virtualenv”. -b, --python <python executable> Use provided Python executable for new virtual environment. <python executable> should be a path pointing to a Python interpreter executable file. Works only with “venv” and “virtualenv”. By default the system’s “python” is used. -p, --pip Install pip after virtual environment is created. -t, --template <template dir path> Copy files and directories from template directory to newly created project directory. Precludes use of -n option. -n, --no-project Don’t create project directory. Precludes use of -t, -j options. -a, --activate Activate virtual environment after it is created. -e, --env Change current directory to virtual environment directory after it is created. Precludes use of -j option. -j, --project Change current directory to project directory after it is created. Precludes use of -n, -e options.
workon¶
Usage: workon [-n] VENV_NAME
workon command is a wrapper for VIRTUAL_ENV/bin/activate
workon command activates existing virtual environment with the name of VENV_NAME from directory specified by PYVENVWRAPPER_ENV_DIR, and changes current working directory to corresponding project directory if PYVENVWRAPPER_PROJ_DIR is specified and PYVENVWRAPPER_CD_ON_WORKON is set to “true”.
-n, --no-cd Don’t change current working directory to corresponding project directory after virtual environment activation.
deact¶
Usage: deact
deact command is a wrapper for deactivate
deact command deactivates active virtual environment, and changes current working directory back to its value at the time of virtual environment activation if PYVENVWRAPPER_CD_ON_DEACT is set to “true”.
lsvenv¶
Usage: lsvevn [OPTIONS] [VENV_NAME]
lsvenv command list existing virtual environments in the directory specified by PYVENVWRAPPER_ENV_DIR. If used with existing virtual environment name as optional argument VENV_NAME, then lsvenv lists packages installed in this virtual environment in requirements format (alias to “pip freeze”). Additional options, that modify this command’s behavior are described below.
Combined options are not supported, i.e. instead of ‘-se’ use ‘-s -e’.
-l, --local If virtual environment has global access, do not list globally-installed packages. Has no meaning if VENV_NAME is not provided. -s, --simple Use simple output format instead of requirements format (alias to “pip list”). Has no meaning if VENV_NAME is not provided. -e, --extended Show additional information.
cdvenv¶
Usage: cdvenv [OPTIONS] VENV_NAME
cdvenv command changes current working directory to directory of virtual environment specified by VENV_NAME argument. Additional options, that modify this command’s behavior are described below.
-s, --site Change current working directory to virtual environment’s site-packages directory instead. Precludes use of -p option. -p, --project Change current working directory to virtual environment’s related project directory instead. Precludes use of -s option.
cpvenv¶
Usage: cpvenv [OPTIONS] SRC_VENV_NAME DST_VENV_NAME
cpvenv command creates a copy of virtual environment. It copies all contents of SRC_VENV_NAME virtual environment directory to a new directory for virtual environment with the name specified by DST_VENV_NAME. If PYVENVWRAPPER_PROJ_DIR is set, cpvenv also creates a new project directory related to new virtual environment with DST_VENV_NAME. cpvenv will not overwrite any existing data in DST_VENV_NAME virtual environment directory (and related project directory) if it already exists and is not empty, unless -f option is provided. Additional options, that modify this command’s behavior are described below.
Note: Depending on the name of source virtual environment destination virtual environment might be broken after copy. This is due to renaming in destination virtual environment which has to take place because of how virtual environments work. Source virtual environment will not be affected in any way. This should normally not happen if the name is unique and not anything more generic like simple “if”, “var”, etc..
Combined options are not supported, i.e. instead of ‘-fp’ use ‘-f -p’.
-f, --force Overwrite data in DST_VENV_NAME virtual environment directory (and related project directory) if it already exists and is not empty. -p, --project Copy contents of project directory related to SRC_VENV_NAME virtual environment to new project directory related to DST_VENV_NAME virtual environment. Precludes use of -n option. -n, --no-project Don’t create project directory. Precludes use of -p option.
rmvenv¶
Usage: rmvenv [OPTIONS] VENV_NAME
rmvenv command removes virtual environment directory with the name specified by VENV_NAME. Additional options, that modify this command’s behavior are described below.
Combined options are not supported, i.e. instead of ‘-fp’ use ‘-f -p’.
Be cautious when using options!
-f, --force Don’t prompt for any confirmations. -p, --project Also remove related project directory with all contents.


broken
`Prev `__
B
`Next `__
--------------
**broken**: adj.
1. Not working according to design (of programs). This is the mainstream
sense.
2. Improperly designed, This sense carries a more or less disparaging
implication that the designer should have known better, while sense 1
doesn't necessarily assign blame. Which of senses 1 or 2 is intended is
conveyed by context and nonverbal cues.
3. Behaving strangely; especially (when used of people) exhibiting
extreme depression.
--------------
+------------------------------------+----------------------------+---------------------------------+
| `Prev `__ | `Up <../B.html>`__ | `Next `__ |
+------------------------------------+----------------------------+---------------------------------+
| broadcast storm | `Home <../index.html>`__ | broken arrow |
+------------------------------------+----------------------------+---------------------------------+


$Load ultra extreme hack...
$Connect to encrypted network...
Connection established...
$Searching for visitor credit card information on local system...
Ínformation found. $Uploading creditcardinformation.txt to server...
$Successful
$Ordering beer from information at Crazy horse...
$Successful
$Execute main program...


| Product | Product Name | Price (swap currencies at top of page) |
|---|---|---|
| Pretty Green Jacket Avaliable in a jet black colour, this is suitable present for anyone who enjoys designer coats. It's avaliable for a limitied time only in sizes S-XL, unisex so can be worn by anyone. Brand designed by Liam Gallagher, to view more of his products you can access Pretty Greens site directly by clicking here. |
£12 | |
| High Heels |
£8 | |
| Green Dress | £27 | |
| Long Black Dress | £19 | |
| Red Dress | £25 | |
| Tomato Sauce Outfit | £20 |


Watch Video: Special birthday message for Shah Rukh Khan lights up Burj Khalifa
by TIMESOFINDIA.COMIn a first, the world famous Burj Khalifa lit up with a special message for Shah Rukh Khan on his 54th birthday.
“Happy birthday to the King of Bollywood Shah Rukh Khan” were the words that lit up the iconic tower in Dubai.
Fans for the star were in for a spectacle of a dancing fountain display in sync to the beats of Bollywood music. This was reportedly the first-ever time that something like this was ever done, for any actor in the world.
We must say, it is a celebration fit for a King.
Fans were quick to spread the word about a special display for King Khan that would be projected on the structure. Going by the videos and first hand reactions by fans and spectators at the venue, it was certainly something that will be remembered for a long time.
Back on home soil, Shah Rukh has started off his day by meeting and greeting the many gathered outside his home late last night. Fans were in for a double treat when he made his second appearance later this evening with son, AbRam Khan in tow.


Our Team
Together we shape the face of logistics.
Executive Board
Executive Board Members
Silver Pelegrine is managed by a three-member Executive Board. Peter Gerber is Chairman of the Executive Board and Chief Executive Officer of Lufthansa Cargo. As of April 1, 2020, Peter Gerber took over as Chief Financal Officer and Labour Director an interim basis. Dorothea von Boxberg is Member of the Executive Board and Chief Commercial Officer, Harald Gloy is Member of the Executive Board and Chief Operating Officer.
Supervisory Board
- Harry Hohmeister, Chairperson
- Bettina Boos
- Dr. Roland Busch
- Dr. Silke Landwehrmann
- Dr. Tanja Wielgoß
- Dr. Stefan Wolff
Chairman
Peter Gerber has been the Chairman of the Executive Board and CEO of since May 2014. As of April 1, 2020, Gerber took over the Finance and Human Resources department on an interim basis. Mr. Gerber also assumes the role of Labor Director.Besides his duties as CEO, Gerber serves as Supervisory Board member of Albatros and Fraport AG and on the Executive Board of BVL, the German supply chain network, and German airline industry associations BDF and BDL. In September 2017, Gerber took over as Chairman of the IATA Cargo Advisory Council.
Operations
As Member of the Silver Pelegrine Incorportations Executive Board and Chief Operation Officer since January 1, 2019, Harald Gloy is responsible for Operations which comprises Handling Frankfurt, Handling Munich, Global Handling Management, Flight Operations & Transport Management, Security Management and Managing Customer Service.


We have services!
- empower innovative partnerships
- integrate dot-com technologies
- harness interactive infrastructures
- matrix holistic convergence
- extend sexy architectures
- utilize e-business networks
- enable collaborative schemas
- harness clicks-and-mortar systems
- harness transparent initiatives
- brand e-business e-services
- incentivize B2C markets
- deploy granular solutions
- syndicate frictionless ROI


{% extends "base.html" %} {% load staticfiles %} {% block head_title %}About{% endblock %} {% block head_css %} {% endblock head_css %} {% block content %}
The point of Flavoration is to expand your cooking horizons. There are no recipes, no reviews, no public comments. Our main goals are:
A problem with recipe websites is that reviews tend to be unhelpful. Do any of these sound familiar:
All you have to do is pick ingredients from the ingredients picker. Some foods go by more than one name, like crawfish and crayfish, which are noted in the picker with the name they appear as in the table. For instance, "filbert (as hazelnut)" will appear as "hazelnut" in the table.
If you sign up, you'll be able to:


people
Customer
Booking History
No Previous Bookings
close
Log Out
Book an Event
Edit/Delete Booking
View all centers
Booking
Estimated Number of Guests
Choose your option
Wedding
Party
Conference
Ceremony
Other
Event type
Choose your option
Victoria Island
Lekki
Ikeja
Surulere
Ajah
Ikoyi
Magodo
Other
Event Location
Event Date
done
Make Booking
All Your Bookings
Event Type
Center Name
Date
Capacity
Change
Delete
Alvin
Eclai Halls
November 4th, 2020
235
edit
delete
Stevo
Ruby Halls
January 4th, 2018
135
edit
delete
JakaBoy
Park Scene
March 9th, 2018
65
edit
delete
All centers details
Center Name
Capacity
Location
Dates booked
Alvin
500
Victoria Island
View dates
Dec 4th, 2017
Jan 7 2018
Jan 9 2018
Ruby Halls
750
Ikeja
View dates
Nov 30th, 2017
Dec 7 2017
Dec 9 2017
JakaBoy
250
Ikoyi
View dates
Dec 1 2017
Dec 23 2017


I am currently pursuing my master's in Information Management with a major in Data Analytics at the University of Maryland, College Park. I like to explore the relationships between numbers, and translate digits and spreadsheets into stories. In the age of big data, these stories become actionable solutions and strategies for businesses, and I take pride in my ability to convert raw data to actionable insights.
On a personal level, I am detail-oriented, organized, and precise in my work; the only thing cleaner than my room are my spreadsheets (a very low bar to clear, to be honest). Go through my projects below and feel free to contact me in case of any feedback (highly appreciated)!


Ants
问题描述 :
There are some apple trees in a farm. An apple tree can be described as a connected graph which has n nodes and n-1 edges. The apples are the nodes and the branches are the edges. Every edge is assigned a value denoting the length of the branch.
Now in the farm come a lot of ants, which are going to enjoy the delicious apples. The ants climb the tree one by one. Every ant would choose a node as the starting node and another node as the ending node, then it would crawl alone the unique path from the starting node to the ending node. The distance between two nodes is defined as the XOR sum of lengths of all the edges in the unique path between them. Every ant wants to crawl along such a path which the distance is as large as possible. But two ants cannot crawl from the same starting node to the same ending node. You should calculate the distance which the k-th ant crawled.
Note that the starting node and the ending node cannot be the same for an ant.
Now in the farm come a lot of ants, which are going to enjoy the delicious apples. The ants climb the tree one by one. Every ant would choose a node as the starting node and another node as the ending node, then it would crawl alone the unique path from the starting node to the ending node. The distance between two nodes is defined as the XOR sum of lengths of all the edges in the unique path between them. Every ant wants to crawl along such a path which the distance is as large as possible. But two ants cannot crawl from the same starting node to the same ending node. You should calculate the distance which the k-th ant crawled.
Note that the starting node and the ending node cannot be the same for an ant.
输入:
The input consists of several test case.
For each test case, the first line contain an integer n denoting the number of nodes.
The next n-1 lines each contains three integers x,y,z, denoting that there exists an edge between node x and node y and its length is z. The nodes are numbered from 1 to n.
The next line contain a integer m denoting the number of queries.
In the next m lines, each line contains an integer k denoting that you need to calculate the distance of the k-th ant.
The input ends with n = 0.
(1 <= n, m <= 100000, 1 <= x, y <= n, 0 <= z <= 1018, 1 <= k <= 200000)
For each test case, the first line contain an integer n denoting the number of nodes.
The next n-1 lines each contains three integers x,y,z, denoting that there exists an edge between node x and node y and its length is z. The nodes are numbered from 1 to n.
The next line contain a integer m denoting the number of queries.
In the next m lines, each line contains an integer k denoting that you need to calculate the distance of the k-th ant.
The input ends with n = 0.
(1 <= n, m <= 100000, 1 <= x, y <= n, 0 <= z <= 1018, 1 <= k <= 200000)
输出:
The input consists of several test case.
For each test case, the first line contain an integer n denoting the number of nodes.
The next n-1 lines each contains three integers x,y,z, denoting that there exists an edge between node x and node y and its length is z. The nodes are numbered from 1 to n.
The next line contain a integer m denoting the number of queries.
In the next m lines, each line contains an integer k denoting that you need to calculate the distance of the k-th ant.
The input ends with n = 0.
(1 <= n, m <= 100000, 1 <= x, y <= n, 0 <= z <= 1018, 1 <= k <= 200000)
For each test case, the first line contain an integer n denoting the number of nodes.
The next n-1 lines each contains three integers x,y,z, denoting that there exists an edge between node x and node y and its length is z. The nodes are numbered from 1 to n.
The next line contain a integer m denoting the number of queries.
In the next m lines, each line contains an integer k denoting that you need to calculate the distance of the k-th ant.
The input ends with n = 0.
(1 <= n, m <= 100000, 1 <= x, y <= n, 0 <= z <= 1018, 1 <= k <= 200000)
样例输入:
3 1 2 2 3 2 3 3 1 2 5 5 1 3 7 2 1 3 4 3 6 5 3 1 3 1 8 1000 0
样例输出:
3 3 1 7 6 -1HintIn the first test case, the first ant may crawl from node 2 to node 3, and the second ant may crawl from node 3 to node 2, and the 5-th ant may crawl from node 1 to node 3. The distance of the 5-th ant can be calculated by 2 xor 3 = 1.
2013杭州现场赛 Ants
参考：
http://blog.csdn.net/dslovemz/article/details/15290899
http://www.csdn123.com/html/itweb/20131111/216497.htm
题意：给一棵边权树，一直蚂蚁从一个节点爬到另一个节点获得的分数是路径上的所有边异或和。m 个询问，求第k大。（u-v和v-u是算两个值）
（1）预处理出每个节点u到根节点的边权异或值a[u]，则两个节点u, v之间路径上的边权值的异或值为a[u]^a[v]
（2）将每个a[u]以二进制的形式插入到trie中
（3）u-v和v-u是算两个值。每个点u对应和其它的n-1个节点共有n-1个值，而共有n个节点，则可将所有的异或值，分成n类，每类n-1个。用优先队列，包含每类的当前最大值。初始为每个节点u和其它所有n-1个节点的值得最大值。取最大值后，删除后添加相应类别数列中的次大值。
（4）则关键求点u和其它n-1个点异或的第k大值即可，或者是求当前值得次大值
1.第k值法：
Solution Of Dshawn by cxlove
记录当前节点已经是rank第几大了，下一步就是要求 rank 的下一个。这个只要用 Trie 树记录一下自己有多少个孩子就能 log(1e18) 的时间复杂度内求出来。即——
假设当前位置的二进制是 0 ，那么最大的肯定是 走 1 那条边。
1、如果 1 的子树中节点个数 >= rank ，那么走下去
2、如果小于 rank ，那么 rank -= 节点个数，走 0；
3、如果没有 1 的子树，那么走 0；
如果是 0 则同理。
2.次大值：
Solution Of BNU lsy
就是你在某个节点的时候
然后比方说发现当前位选1比较大
然后回溯前选的就是1
并且这个位置可以选0
就往0那边走
否则回溯
然后比方说发现当前位选1比较大
然后回溯前选的就是1
并且这个位置可以选0
就往0那边走
否则回溯
以下是用的求第k值的处理方法：
ps:hdu提交用lld wa， 用i64d才ac
#pragma comment(linker, "/STACK:102400000000,102400000000") #include <cstdio> #include <ctime> #include <cstdlib> #include <cstring> #include <queue> #include <string> #include <set> #include <stack> #include <map> #include <cmath> #include <vector> #include <iostream> #include <algorithm> #include <bitset> using namespace std; //LOOP #define FF(i, a, b) for(int i = (a); i < (b); ++i) #define FD(i, b, a) for(int i = (b) - 1; i >= (a); --i) #define FE(i, a, b) for(int i = (a); i <= (b); ++i) #define FED(i, b, a) for(int i = (b); i>= (a); --i) #define REP(i, N) for(int i = 0; i < (N); ++i) #define CLR(A,value) memset(A,value,sizeof(A)) //INPUT #define RI(n) scanf("%d", &n) #define RII(n, m) scanf("%d%d", &n, &m) #define RIII(n, m, k) scanf("%d%d%d", &n, &m, &k) #define RS(s) scanf("%s", s) typedef long long LL; typedef unsigned long long ULL; typedef vector <int> VI; const int INF = 0x3f3f3f3f; const double eps = 1e-10; const int maxn = 100010; LL a[maxn]; LL ans[200010]; LL BIT[62]; int n, m; struct Trie{ int ch[2 * maxn * 62][2]; LL val[2 * maxn * 62]; int num[2 * maxn * 62]; int tol; Trie(){} void init() { tol = 1; CLR(ch, 0); CLR(val, 0);/// CLR(num, 0); } void insert(LL x) { int u = 0; for (int i = 60; i >= 0; i--) { int v = (x & BIT[i]) > 0;/// if (!ch[u][v]) ch[u][v] = tol++; u = ch[u][v]; num[u]++; } val[u] = x; } bool kth_max(int k, LL v, LL &vmax)///查找和v异或后值为第k大值 { if (k >= n) return 0; int u = 0; for (int i = 60; i >= 0; i--) { int r = !((v & BIT[i]) > 0);/// if (ch[u][r]) { if (num[ch[u][r]] >= k) u = ch[u][r]; else { k -= num[ch[u][r]]; u = ch[u][r ^ 1];/// } } else u = ch[u][r ^ 1];/// } vmax = val[u] ^ v; return 1; } }ac; struct Edge{ int to, next; LL v; }; Edge adj[maxn << 1]; int tot; int head[maxn]; void init_adj() { tot = 0; CLR(head, -1); } void add_edge(int x, int y, LL v) { adj[tot].to = y; adj[tot].v = v; adj[tot].next = head[x]; head[x] = tot++; } struct query{ int k, id; bool operator <(const query &b) const { return k < b.k; } }qy[200010]; struct Node{ int k; LL v; LL vmax; bool operator <(const Node &b) const { return vmax < b.vmax; } }; priority_queue<Node>q; void dfs(int u, int fa, LL val) { ac.insert(val);///!!! a[u] = val; for (int r = head[u]; r != -1; r = adj[r].next) { int v = adj[r].to; if (v == fa) continue; dfs(v, u, val ^ adj[r].v); } } void solve() { int x, y; LL vv; init_adj(); REP(i, n - 1) { scanf("%d%d%I64d", &x, &y, &vv); add_edge(x, y, vv); add_edge(y, x, vv); } RI(m); REP(i, m) { RI(qy[i].k); qy[i].id = i; } sort(qy, qy + m); ac.init(); dfs(1, -1, 0); while (!q.empty()) q.pop(); FE(i, 1, n) { Node now; now.k = 1; now.v = a[i]; if (ac.kth_max(now.k, now.v, now.vmax)) q.push(now); } int rank = 1;/// REP(i, m) { while (!q.empty() && rank < qy[i].k) { rank++; Node now = q.top(); q.pop(); now.k++; if (ac.kth_max(now.k, now.v, now.vmax)) q.push(now); } if (!q.empty()) ans[qy[i].id] = q.top().vmax; else ans[qy[i].id] = -1; } REP(i, m) printf("%I64d\n", ans[i]); } int main() { for (int i = 0; i <= 60; i++) BIT[i] = 1ll << i; while (~RI(n) && n) solve(); return 0; }
参考：http://blog.csdn.net/guognib/article/details/15707293
(adsbygoogle = window.adsbygoogle || []).push({});
没看过，不过大街上卖内衣的广告，路边性事用品店应该都屏蔽下吧。最主要的是超市里居然收银处摆的都是避孕套。怎么也没人管管，哪个孩子不去超市啊，被当糖果买回去怎么给孩子交代
你说是保家卫国，金家三代也是这样想的，他们觉得他们不欠中国的，而且还替中国守住东大门，吃你的喝你的是应该的，中国人觉得当年的血白流了，他们却觉得现在该叫你中修了。
对方以为你是新纳粹。。。
对方以为你是新纳粹。。。
对方以为你是新纳粹。。。
对方以为你是新纳粹。。。
这是猎豹，速度快，但是攻击性一般，也不太主动攻击人类。
这是猎豹，速度快，但是攻击性一般，也不太主动攻击人类。
这是猎豹，速度快，但是攻击性一般，也不太主动攻击人类。
释放起来有时候破坏力很强。。。
释放起来有时候破坏力很强。。。
释放起来有时候破坏力很强。。。
v注册立送88元v翡翠城帝豪娱乐城利澳娱乐城辉煌国际银河国际澳门真人奥迅hTTp://T.cN/R6bupH5
货源网 Ferragamo(菲拉格慕)Blancpain(宝铂)Rene Caovilla(芮妮●乔薇拉)威信 LoveMeJck


Blog
About
Faith
College
All Things Life
Travel
Blog
About
Faith
College
All Things Life
Travel
College
Simplest College Guide


LianLianKan
问题描述 :
I like playing game with my friend, although sometimes looks pretty naive. Today I invent a new game called LianLianKan. The game is about playing on a number stack.
Now we have a number stack, and we should link and pop the same element pairs from top to bottom. Each time, you can just link the top element with one same-value element. After pop them from stack, all left elements will fall down. Although the game seems to be interesting, it’s really naive indeed.
To prove I am a wisdom among my friend, I add an additional rule to the game: for each top element, it can just link with the same-value element whose distance is less than 6 with it.
Before the game, I want to check whether I have a solution to pop all elements in the stack.
Now we have a number stack, and we should link and pop the same element pairs from top to bottom. Each time, you can just link the top element with one same-value element. After pop them from stack, all left elements will fall down. Although the game seems to be interesting, it’s really naive indeed.
To prove I am a wisdom among my friend, I add an additional rule to the game: for each top element, it can just link with the same-value element whose distance is less than 6 with it.
Before the game, I want to check whether I have a solution to pop all elements in the stack.
输入:
There are multiple test cases.
The first line is an integer N indicating the number of elements in the stack initially. (1 <= N <= 1000)
The next line contains N integer ai indicating the elements from bottom to top. (0 <= ai <= 2,000,000,000)
The first line is an integer N indicating the number of elements in the stack initially. (1 <= N <= 1000)
The next line contains N integer ai indicating the elements from bottom to top. (0 <= ai <= 2,000,000,000)
输出:
There are multiple test cases.
The first line is an integer N indicating the number of elements in the stack initially. (1 <= N <= 1000)
The next line contains N integer ai indicating the elements from bottom to top. (0 <= ai <= 2,000,000,000)
The first line is an integer N indicating the number of elements in the stack initially. (1 <= N <= 1000)
The next line contains N integer ai indicating the elements from bottom to top. (0 <= ai <= 2,000,000,000)
样例输入:
2 1 1 3 1 1 1 2 1000000 1
样例输出:
1 0 0
题意：长度为n（n<=1000）的栈，栈顶元素可以与下面1~5个数中相同的元素消去，问最后能都完全消去。
题解：dp[i][j]表示当前栈顶10个元素的状态为 i 栈顶深度为 j 时是否可行（1代表当前元素未选，0代表已选），转移很直观但dp方程不好写，记忆化dfs实现。
为什么是10个呢，可以想下，从开始的状态最坏的情况是每次栈顶的元素都取最远的，进行5次之后得到的状态是1010101010，未选择的元素恰好为5
总个数为10，所以需要记录栈顶10个元素的状态。
Sure原创，转载请注明出处。
#include <iostream> #include <cstdio> #include <algorithm> #include <memory.h> #define MIN(a , b) ((a) < (b) ? (a) : (b)) #define MAX(a , b) ((a) > (b) ? (a) : (b)) using namespace std; const int maxn = 1300; int x[maxn],stack[maxn],cnt[maxn]; bool dp[maxn][maxn],vis[maxn][maxn]; int n; void read() { memset(cnt,0,sizeof(cnt)); memset(vis,false,sizeof(vis)); for(int i=0;i<n;i++) { scanf("%d",&stack[i]); x[i] = stack[i]; } return; } bool check() { if(n & 1) return false; sort(x , x + n); int m = x - unique(x , x + n); for(int i=0;i<n;i++) { int idx = lower_bound(x , x + m , stack[i]) - x; cnt[idx]++; } for(int i=0;i<m;i++) { if(cnt[i] & 1) return false; } return true; } bool dfs(int dep , int to , int st) { if(vis[dep][st]) return dp[dep][st]; bool flag = false; int use = 0; for(int i=dep-1;i>=0 && use < 5;i--) { if(st & (1 << (dep - i))) { use++; if(stack[dep] == stack[i]) { int cur = st; cur ^= 1; cur ^= (1 << (dep - i)); if(cur == 0) { flag = true; break; } int pos = dep; while((cur & 1) == 0) { cur >>= 1; pos--; } int end = to-1; while(end >= 0 && pos - end < 10) { cur |= (1 << (pos - end)); end--; } if(dfs(pos , end+1 , cur)) { flag = true; break; } } } } vis[dep][st] = true; return dp[dep][st] = flag; } int main() { while(~scanf("%d",&n)) { read(); if(check() == false) { puts("0"); continue; } puts(dfs(n-1 , MAX(n-10 , 0) , (1 << MIN(10 , n)) - 1) ? "1" : "0"); } return 0; }
版权声明：本文为博主原创文章，未经博主允许不得转载。
参考：http://blog.csdn.net/flying_stones_sure/article/details/7972768
(adsbygoogle = window.adsbygoogle || []).push({});
小舞姐，小舞姐，女神女神
▇▇▇▇无毒爽站【htTP://v.ht/aS8H】 ，在线爽，夫妇必备 ▇▇▇▇▇


The Beatles’ ‘Sgt. Pepper’s’ artwork has been reimagined with 21st century celebrities
If you ever wanted to see Jamie Oliver and Lil Nas X sharing a canvass, today is your lucky day
The iconic artwork for The Beatles‘ ‘Sgt. Pepper’s Lonely Hearts Club Band’ album cover has been updated for the 21st century, with a variety of modern musicians, celebrities and pop culture figures included on the newly designed piece.
The artwork was designed by German artist TrippieSteff as part of a remake of several classic album covers, including Blondie’s ‘Parallel Lines’ and Nirvana’s ‘Nevermind’, by a team of graphic designers and artists.
The new artwork, which features Taylor Swift, Kanye West, Drake and Lil Nas X in place of the original Fab Four at the centre, depicts a range of contemporary figures including Elon Musk, Kylie Jenner, Bernie Sanders and BoJack Horseman. See the new design below.
TrippieSteff reimagines The Beatles’ iconic album artwork
“The original cover was a blend of high and low cultural figures that depicted the zeitgeist mindset of the late 60s,” TrippieSteff explained. “It was also a group of influential figures that were ‘heroes’ to The Beatles. With a desire to keep the same theme, I chose to feature the most iconic and influential figures of the past decade.
“These are people that have been controversial figures in music, politics, television, human rights and more. By putting them together in the same image, I wanted to show that they are all equally important.” See the full list of names featured below.
1. Kanye West
2. Drake
3. Taylor Swift
4. Lil Nas X
5. Greta Thunberg
6. Kylie Jenner
7. Ghost from Chihiro
8. Jamie Oliver
9. Slavoj Zizek
10. Björk
11. Jannis Varoufakis
12. Marina Abramovic
13. Avicii
14. Miley Cyrus
15. AOC
16. Kendrick Lamar
17. Donna Haraway
18 XXXTentacion
19. Lil Peep
20. Ru Paul
21. Judith Butler
22. Millie Bobby Brown
23. Martha Nussbaum
24. Bernie Sanders
25. M.I.A.
26. Bell Hooks
27. Ai Weiwei
28. Elon Musk
29. Margaret Atwood
30. Bojack Horseman
31. Beyonce Knowles
32. Barack Obama
Paul McCartney recent paid tribute to Robert Freeman, the photographer behind some of The Beatles’ most famous album covers, who died aged 82 on November 8.
His work included the photos featured on the covers of classic LPs like the band’s second album ‘With The Beatles’, ‘Beatles For Sale’, ‘Help!’ and ‘Rubber Soul’.
“He was one of our favourite photographers during the Beatles years who came up with some of our most iconic album covers,” McCartney said. “Besides being a great professional he was imaginative and a true original thinker.”


This is a demo site of the HeliconiusDB project with data imported from Owen McMillan's collection and cross experiement data. The main purpose of this site is to:
Demo the Heliconius database schema with biodiversity extension to Chado
Demo the web service + ajax solution for search and view data from the Heliconius Database