Module: ActiveRecord::AttributeMethods::Dirty
| Relationships & Source Files | |
| Super Chains via Extension / Inclusion / Inheritance | |
|
Class Chain:
self,
::ActiveSupport::Concern
|
|
|
Instance Chain:
|
|
| Defined in: | activerecord/lib/active_record/attribute_methods/dirty.rb |
Overview
Provides a way to track changes in your Active Record models. It adds all methods from ::ActiveModel::Dirty
and adds database specific methods.
A newly created Person
object is unchanged:
class Person < ActiveRecord::Base
end
person = Person.create(name: "Alisson")
person.changed? # => false
Change the name:
person.name = 'Alice'
person.name_in_database # => "Allison"
person.will_save_change_to_name? # => true
person.name_change_to_be_saved # => ["Allison", "Alice"]
person.changes_to_save # => {"name"=>["Allison", "Alice"]}
Save the changes:
person.save
person.name_in_database # => "Alice"
person.saved_change_to_name? # => true
person.saved_change_to_name # => ["Allison", "Alice"]
person.name_before_last_change # => "Allison"
Similar to ::ActiveModel::Dirty
, methods can be invoked as saved_change_to_name?
or by passing an argument to the generic method saved_change_to_attribute?("name")
.
Constant Summary
::ActiveModel::AttributeMethods
- Included
CALL_COMPILABLE_REGEXP, FORWARD_PARAMETERS, NAME_COMPILABLE_REGEXP
Class Method Summary
::ActiveSupport::Concern
- Extended
| class_methods | Define class methods from given block. |
| included | Evaluate given block in context of base class, so that you can write class macros here. |
| prepended | Evaluate given block in context of base class, so that you can write class macros here. |
| append_features, prepend_features |
Instance Attribute Summary
-
#has_changes_to_save? ⇒ Boolean
readonly
Will the next call to
save
have any changes to persist? -
#saved_changes? ⇒ Boolean
readonly
Did the last call to
save
have any changes to change?
::ActiveModel::Dirty
- Included
| #attribute_aliases, #attribute_aliases?, #attribute_method_patterns, #attribute_method_patterns?, | |
| #changed? | Returns |
Instance Method Summary
-
#*_change
This method is generated for each attribute.
-
#*_changed?
This method is generated for each attribute.
-
#*_previous_change
This method is generated for each attribute.
-
#*
This method is generated for each attribute.
-
#*_previously_was
This method is generated for each attribute.
-
#*_was
This method is generated for each attribute.
-
#*_will_change!
This method is generated for each attribute.
-
#attribute_before_last_save(attr_name)
Returns the original value of an attribute before the last save.
-
#attribute_change_to_be_saved(attr_name)
Returns the change to an attribute that will be persisted during the next save.
-
#attribute_in_database(attr_name)
Returns the value of an attribute in the database, as opposed to the in-memory value that will be persisted the next time the record is saved.
-
#attributes_in_database
Returns a hash of the attributes that will change when the record is next saved.
-
#changed_attribute_names_to_save
Returns an array of the names of any attributes that will change when the record is next saved.
-
#changes_to_save
Returns a hash containing all the changes that will be persisted during the next save.
-
#clear_*_change
This method is generated for each attribute.
-
#reload
reload
the record and clears changed attributes. -
#restore_*!
This method is generated for each attribute.
-
#saved_change_to_attribute(attr_name)
Returns the change to an attribute during the last save.
-
#saved_change_to_attribute?(attr_name, **options) ⇒ Boolean
Did this attribute change when we last saved?
-
#saved_changes
readonly
Returns a hash containing all the changes that were just saved.
-
#will_save_change_to_attribute?(attr_name, **options) ⇒ Boolean
Will this attribute change the next time we save?
- #_create_record(attribute_names = attribute_names_for_partial_inserts) private
- #_touch_row(attribute_names, time) private
- #_update_record(attribute_names = attribute_names_for_partial_updates) private
- #attribute_names_for_partial_inserts private
- #attribute_names_for_partial_updates private
- #init_internals private
::ActiveModel::Dirty
- Included
| #attribute_changed? | Dispatch target for |
| #attribute_previously_changed? | Dispatch target for |
| #attribute_previously_was | Dispatch target for |
| #attribute_was | Dispatch target for |
| #changed | Returns an array with the name of the attributes with unsaved changes. |
| #changed_attributes | Returns a hash of the attributes with unsaved changes indicating their original values like |
| #changes | Returns a hash of changed attributes indicating their original and new values like |
| #changes_applied | Clears dirty data and moves |
| #clear_attribute_changes, | |
| #clear_changes_information | Clears all dirty data: current changes and previous changes. |
| #previous_changes | Returns a hash of attributes that were changed before the model was saved. |
| #restore_attributes | Restore all previous data of the provided attributes. |
| #attribute_change | Dispatch target for |
| #attribute_previous_change | Dispatch target for |
| #attribute_will_change! | Dispatch target for |
| #clear_attribute_change, #forget_attribute_assignments, #init_internals, #mutations_before_last_save, #mutations_from_database, | |
| #restore_attribute! | Dispatch target for |
| #as_json, #attribute_changed_in_place?, #initialize_dup |
::ActiveModel::AttributeMethods
- Included
| #attribute_missing |
|
| #method_missing | Allows access to the object attributes, which are held in the hash returned by #attributes, as though they were first-class methods. |
| #respond_to?, | |
| #respond_to_without_attributes? | A |
| #_read_attribute, #attribute_method?, | |
| #matched_attribute_method | Returns a struct representing the matching attribute method. |
| #missing_attribute |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method in the class ActiveModel::AttributeMethods
DSL Calls
included
[ GitHub ]44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 44
included do if self < ::ActiveRecord::Timestamp raise "You cannot include Dirty after Timestamp" end class_attribute :partial_updates, instance_writer: false, default: true class_attribute :partial_inserts, instance_writer: false, default: true # Attribute methods for "changed in last call to save?" attribute_method_affix(prefix: "saved_change_to_", suffix: "?", parameters: "**options") attribute_method_prefix("saved_change_to_", parameters: false) attribute_method_suffix("_before_last_save", parameters: false) # Attribute methods for "will change if I call save?" attribute_method_affix(prefix: "will_save_change_to_", suffix: "?", parameters: "**options") attribute_method_suffix("_change_to_be_saved", "_in_database", parameters: false) end
Instance Attribute Details
#has_changes_to_save? ⇒ Boolean
(readonly)
Will the next call to save
have any changes to persist?
# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 165
def has_changes_to_save? mutations_from_database.any_changes? end
#saved_changes? ⇒ Boolean
(readonly)
Did the last call to save
have any changes to change?
# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 111
def saved_changes? mutations_before_last_save.any_changes? end
Instance Method Details
#*_change
This method is generated for each attribute.
Returns the old and the new value of the attribute.
person = Person.new
person.name = 'Nick'
person.name_change # => [nil, 'Nick']
# File 'activemodel/lib/active_model/dirty.rb', line 155
rdoc_method :method: *_change
#*_changed?
This method is generated for each attribute.
Returns true if the attribute has unsaved changes.
person = Person.new
person.name = 'Andrew'
person.name_changed? # => true
# File 'activemodel/lib/active_model/dirty.rb', line 144
rdoc_method :method: *_changed?
#*_previous_change
This method is generated for each attribute.
Returns the old and the new value of the attribute before the last save.
person = Person.new
person.name = 'Emmanuel'
person.save
person.name_previous_change # => [nil, 'Emmanuel']
# File 'activemodel/lib/active_model/dirty.rb', line 193
rdoc_method :method: *_previous_change
#*
This method is generated for each attribute.
Returns true if the attribute previously had unsaved changes.
person = Person.new
person.name = 'Britanny'
person.save
person.name_previously_changed? # => true
person.name_previously_changed?(from: nil, to: 'Britanny') # => true
# File 'activemodel/lib/active_model/dirty.rb', line 129
rdoc_method :method: *_previously_changed?
#*_previously_was
This method is generated for each attribute.
Returns the old value of the attribute before the last save.
person = Person.new
person.name = 'Sage'
person.save
person.name_previously_was # => nil
# File 'activemodel/lib/active_model/dirty.rb', line 205
rdoc_method :method: *_previously_was
#*_was
This method is generated for each attribute.
Returns the old value of the attribute.
person = Person.new(name: 'Steph')
person.name = 'Stephanie'
person.name_change # => ['Steph', 'Stephanie']
# File 'activemodel/lib/active_model/dirty.rb', line 182
rdoc_method :method: *_was
#*_will_change!
This method is generated for each attribute.
If an attribute is modified in-place then make use of *_will_change!
to mark that the attribute is changing. Otherwise Active Model can’t track changes to in-place attributes. Note that Active Record can detect in-place modifications automatically. You do not need to call *_will_change!
on Active Record models.
person = Person.new('Sandy')
person.name_will_change!
person.name_change # => ['Sandy', 'Sandy']
# File 'activemodel/lib/active_model/dirty.rb', line 166
rdoc_method :method: *_will_change!
#_create_record(attribute_names = attribute_names_for_partial_inserts) (private)
[ GitHub ]# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 235
def _create_record(attribute_names = attribute_names_for_partial_inserts) id = super changes_applied id end
#_touch_row(attribute_names, time) (private)
[ GitHub ]# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 200
def _touch_row(attribute_names, time) @_touch_attr_names = Set.new(attribute_names) affected_rows = super if @_skip_dirty_tracking ||= false clear_attribute_changes(@_touch_attr_names) return affected_rows end changes = {} @attributes.keys.each do |attr_name| next if @_touch_attr_names.include?(attr_name) if attribute_changed?(attr_name) changes[attr_name] = _read_attribute(attr_name) _write_attribute(attr_name, attribute_was(attr_name)) clear_attribute_change(attr_name) end end changes_applied changes.each { |attr_name, value| _write_attribute(attr_name, value) } affected_rows ensure @_touch_attr_names, @_skip_dirty_tracking = nil, nil end
#_update_record(attribute_names = attribute_names_for_partial_updates) (private)
[ GitHub ]# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 229
def _update_record(attribute_names = attribute_names_for_partial_updates) affected_rows = super changes_applied affected_rows end
#attribute_before_last_save(attr_name)
Returns the original value of an attribute before the last save.
This method is useful in after callbacks to get the original value of an attribute before the save that triggered the callbacks to run. It can be invoked as name_before_last_save
instead of attribute_before_last_save("name")
.
# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 106
def attribute_before_last_save(attr_name) mutations_before_last_save.original_value(attr_name.to_s) end
#attribute_change_to_be_saved(attr_name)
Returns the change to an attribute that will be persisted during the next save.
This method is useful in validations and before callbacks, to see the change to an attribute that will occur when the record is saved. It can be invoked as name_change_to_be_saved
instead of attribute_change_to_be_saved("name")
.
If the attribute will change, the result will be an array containing the original value and the new value about to be saved.
# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 148
def attribute_change_to_be_saved(attr_name) mutations_from_database.change_to_attribute(attr_name.to_s) end
#attribute_in_database(attr_name)
Returns the value of an attribute in the database, as opposed to the in-memory value that will be persisted the next time the record is saved.
This method is useful in validations and before callbacks, to see the original value of an attribute prior to any changes about to be saved. It can be invoked as name_in_database
instead of attribute_in_database("name")
.
# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 160
def attribute_in_database(attr_name) mutations_from_database.original_value(attr_name.to_s) end
#attribute_names_for_partial_inserts (private)
[ GitHub ]# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 245
def attribute_names_for_partial_inserts if partial_inserts? changed_attribute_names_to_save else attribute_names.reject do |attr_name| if column_for_attribute(attr_name).default_function !attribute_changed?(attr_name) end end end end
#attribute_names_for_partial_updates (private)
[ GitHub ]# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 241
def attribute_names_for_partial_updates partial_updates? ? changed_attribute_names_to_save : attribute_names end
#attributes_in_database
Returns a hash of the attributes that will change when the record is next saved.
The hash keys are the attribute names, and the hash values are the original attribute values in the database (as opposed to the in-memory values about to be saved).
# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 187
def attributes_in_database mutations_from_database.changed_values end
#changed_attribute_names_to_save
Returns an array of the names of any attributes that will change when the record is next saved.
# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 177
def changed_attribute_names_to_save mutations_from_database.changed_attribute_names end
#changes_to_save
Returns a hash containing all the changes that will be persisted during the next save.
# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 171
def changes_to_save mutations_from_database.changes end
#clear_*_change
This method is generated for each attribute.
Clears all dirty data of the attribute: current changes and previous changes.
person = Person.new(name: 'Chris')
person.name = 'Jason'
person.name_change # => ['Chris', 'Jason']
person.clear_name_change
person.name_change # => nil
# File 'activemodel/lib/active_model/dirty.rb', line 242
rdoc_method :method: clear_*_change
#init_internals (private)
[ GitHub ]# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 192
def init_internals super @mutations_before_last_save = nil @mutations_from_database = nil @_touch_attr_names = nil @_skip_dirty_tracking = nil end
#reload
reload
the record and clears changed attributes.
# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 63
def reload(*) super.tap do @mutations_before_last_save = nil @mutations_from_database = nil end end
#restore_*!
This method is generated for each attribute.
Restores the attribute to the old value.
person = Person.new
person.name = 'Amanda'
person.restore_name!
person.name # => nil
# File 'activemodel/lib/active_model/dirty.rb', line 217
rdoc_method :method: restore_*!
#saved_change_to_attribute(attr_name)
Returns the change to an attribute during the last save. If the attribute was changed, the result will be an array containing the original value and the saved value.
This method is useful in after callbacks, to see the change in an attribute during the save that triggered the callbacks to run. It can be invoked as saved_change_to_name
instead of saved_change_to_attribute("name")
.
# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 96
def saved_change_to_attribute(attr_name) mutations_before_last_save.change_to_attribute(attr_name.to_s) end
#saved_change_to_attribute?(attr_name, **options) ⇒ Boolean
Did this attribute change when we last saved?
This method is useful in after callbacks to determine if an attribute was changed during the save that triggered the callbacks to run. It can be invoked as saved_change_to_name?
instead of saved_change_to_attribute?("name")
.
Options
from
When passed, this method will return false unless the original value is equal to the given option
to
When passed, this method will return false unless the value was changed to the given value
# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 84
def saved_change_to_attribute?(attr_name, ** ) mutations_before_last_save.changed?(attr_name.to_s, ** ) end
#saved_changes (readonly)
Returns a hash containing all the changes that were just saved.
# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 116
def saved_changes mutations_before_last_save.changes end
#will_save_change_to_attribute?(attr_name, **options) ⇒ Boolean
Will this attribute change the next time we save?
This method is useful in validations and before callbacks to determine if the next call to save
will change a particular attribute. It can be invoked as will_save_change_to_name?
instead of will_save_change_to_attribute?("name")
.
Options
from
When passed, this method will return false unless the original value is equal to the given option
to
When passed, this method will return false unless the value will be changed to the given value
# File 'activerecord/lib/active_record/attribute_methods/dirty.rb', line 134
def will_save_change_to_attribute?(attr_name, ** ) mutations_from_database.changed?(attr_name.to_s, ** ) end


School Calendar
Here is a Summary for what is planned to be done
| Day | Event | Details | Date | Venue |
|---|---|---|---|---|
| Saturday | Graduation | Candidates graduation | 26th January 2019 | Main Hall |
| Saturday | S1 and S4 Orientation Meeting | New students get familiarized to the environmet | 28th January 2019 | Main hall |
| Sunday | 1st Visitation Day | Students get visited from 2:00-5:00PM | 2nd February 2019 | School Compounds |
| Friday | Election of ministers | Students get to choose their new leaders | 18th Feb | Classrooms |
| Wednesday | Language Day | Public speaking, writing and reading | 8th March | Respective Classes |
| Sunday | 2nd Visitation Day | Students get visited from 2:00-5:00PM | 6th March 2019 | School Compounds |
| Friday | Counseling day | Discussion Teacher-student | 17th March | Counseling day |
| Saturday | Inter-Classes Athletics Competition | Tough competion between students | 18th March | School Pitch |
| Sunday | 3rd Visitation Day | Students get visited from 2:00-5:00PM | 4th April 2019 | School Compounds |


An interface in java is a blueprint of a class. It has static constants and abstract methods. The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not the method body. It is used to achieve abstraction and multiple inheritance in Java. In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.
An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static, and final by default. A class that implements an interface must implement all the methods declared in the interface.
The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public, static, and final keywords before data members.
As shown in the figure given below, a class extends another class, an interface extends another interface, but a class implements an interface.
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple inheritance.
Multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in the case of an interface because there is no ambiguity. It is because its implementation is provided by the implementation class.
An interface that has no member is known as a marker or tagged interface, for example, Serializable, Cloneable, Remote, etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operations.


This site is a collection of community-contributed APIs from various data sources. They were built using BioThings SDK and follow the same design pattern of our official BioThings APIs (MyGene.info, MyVariant.info, MyChem.info, etc). These APIs are also pending to be integrated into the proper official BioThings API based on their entity type.
| Name | Documents | Entity Type | Try It |
|---|


Thank you!
Thanks for contacting me! I look forward to connecting with you and will do my best to get back to you as soon as I can.
Back to home


My Account
{# NAV #}
{% include "inc/account/nav.html" %}
{# PROFILE #}
{% include "inc/account/profile.html" %}
{# MEMBERSHIP #}
{% include "inc/account/membership.html" %}
{# LICENSES #}
{% include "inc/account/licenses.html" %}
{# EVENTS #}
{% include "inc/account/events.html" %}
{# RACER #}
{% include "inc/account/racer.html" %}
{# EVENT DIRECTOR #}
{% include "inc/account/event-director.html" %}
{# CLUB ADMIN #}
{% include "inc/account/club-admin.html" %}
{# OFFICIAL #}
{% include "inc/account/official.html" %}
{# COACH #}
{% include "inc/account/coach.html" %}
{# PRECOACH #}
{% include "inc/account/pre-coach.html" %}
{# TECHNICAL SUPPORT #}
{% include "inc/account/technical-support.html" %}


Superhero Form
About the Superhero
Real Name
Superhero Name
Age
About
Photo:
Powers
Telekinesis
Super strength or speed
Shapeshifting
Flight
Elemental control
Other
Level of control:
Origin of Powers
Uknown
Freak lab accident
Chosen by an ancient wise being
The superhero is not human
Other
CLEAR
SEND


PERLREREF
Section: Perl Programmers Reference Guide (1)Updated: 2009-02-12
Index Return to Main Contents
NAME
perlreref - Perl Regular Expressions ReferenceDESCRIPTION
This is a quick reference to Perl's regular expressions. For full information see perlre and perlop, as well as the ``SEE ALSO'' section in this document.OPERATORS
"=~" determines to which variable the regex is applied. In its absence, $_ is used.
$var =~ /foo/;
"!~" determines to which variable the regex is applied, and negates the result of the match; it returns false if the match succeeds, and true if it fails.
$var !~ /foo/;
"m/pattern/msixpogc" searches a string for a pattern match, applying the given options.
m Multiline mode - ^ and $ match internal lines s match as a Single line - . matches \n i case-Insensitive x eXtended legibility - free whitespace and comments p Preserve a copy of the matched string - ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} will be defined. o compile pattern Once g Global - all occurrences c don't reset pos on failed matches when using /g
If 'pattern' is an empty string, the last successfully matched regex is used. Delimiters other than '/' may be used for both this operator and the following ones. The leading "m" can be omitted if the delimiter is '/'.
"qr/pattern/msixpo" lets you store a regex in a variable, or pass one around. Modifiers as for "m//", and are stored within the regex.
"s/pattern/replacement/msixpogce" substitutes matches of 'pattern' with 'replacement'. Modifiers as for "m//", with one addition:
e Evaluate 'replacement' as an expression
'e' may be specified multiple times. 'replacement' is interpreted as a double quoted string unless a single-quote ("'") is the delimiter.
"?pattern?" is like "m/pattern/" but matches only once. No alternate delimiters can be used. Must be reset with reset().
SYNTAX
\ Escapes the character immediately following it . Matches any single character except a newline (unless /s is used) ^ Matches at the beginning of the string (or line, if /m is used) $ Matches at the end of the string (or line, if /m is used) * Matches the preceding element 0 or more times + Matches the preceding element 1 or more times ? Matches the preceding element 0 or 1 times {...} Specifies a range of occurrences for the element preceding it [...] Matches any one of the characters contained within the brackets (...) Groups subexpressions for capturing to $1, $2... (?:...) Groups subexpressions without capturing (cluster) | Matches either the subexpression preceding or following it \1, \2, \3 ... Matches the text from the Nth group \g1 or \g{1}, \g2 ... Matches the text from the Nth group \g-1 or \g{-1}, \g-2 ... Matches the text from the Nth previous group \g{name} Named backreference \k<name> Named backreference \k'name' Named backreference (?P=name) Named backreference (python syntax)
ESCAPE SEQUENCES
These work as in normal strings.
\a Alarm (beep) \e Escape \f Formfeed \n Newline \r Carriage return \t Tab \037 Any octal ASCII value \x7f Any hexadecimal ASCII value \x{263a} A wide hexadecimal value \cx Control-x \N{name} A named character \l Lowercase next character \u Titlecase next character \L Lowercase until \E \U Uppercase until \E \Q Disable pattern metacharacters until \E \E End modification
For Titlecase, see ``Titlecase''.
This one works differently from normal strings:
\b An assertion, not backspace, except in a character class
CHARACTER CLASSES
[amy] Match 'a', 'm' or 'y' [f-j] Dash specifies "range" [f-j-] Dash escaped or at start or end means 'dash' [^f-j] Caret indicates "match any character _except_ these"
The following sequences work within or without a character class. The first six are locale aware, all are Unicode aware.  Match Unicode property with long name \PP Match non-P \P{...} Match lack of Unicode property with long name \X Match extended Unicode combining character sequence
POSIX character classes and their Unicode and Perl equivalents:
alnum IsAlnum Alphanumeric alpha IsAlpha Alphabetic ascii IsASCII Any ASCII char blank IsSpace [ \t] Horizontal whitespace (GNU extension) cntrl IsCntrl Control characters digit IsDigit \d Digits graph IsGraph Alphanumeric and punctuation lower IsLower Lowercase chars (locale and Unicode aware) print IsPrint Alphanumeric, punct, and space punct IsPunct Punctuation space IsSpace [\s\ck] Whitespace IsSpacePerl \s Perl's whitespace definition upper IsUpper Uppercase chars (locale and Unicode aware) word IsWord \w Alphanumeric plus _ (Perl extension) xdigit IsXDigit [0-9A-Fa-f] Hexadecimal digit
Within a character class:
POSIX traditional Unicode [:digit:] \d \p{IsDigit} [:^digit:] \D \P{IsDigit}
ANCHORS
All are zero-width assertions.
^ Match string start (or line, if /m is used) $ Match string end (or line, if /m is used) or before newline \b Match word boundary (between \w and \W) \B Match except at word boundary (between \w and \w or \W and \W) \A Match string start (regardless of /m) \Z Match string end (before optional newline) \z Match absolute string end \G Match where previous m//g left off \K Keep the stuff left of the \K, don't include it in $&
QUANTIFIERS
Quantifiers are greedy by default --- match the longest leftmost.
Maximal Minimal Possessive Allowed range ------- ------- ---------- ------------- {n,m} {n,m}? {n,m}+ Must occur at least n times but no more than m times {n,} {n,}? {n,}+ Must occur at least n times {n} {n}? {n}+ Must occur exactly n times * *? *+ 0 or more times (same as {0,}) + +? ++ 1 or more times (same as {1,}) ? ?? ?+ 0 or 1 time (same as {0,1})
The possessive forms (new in Perl 5.10) prevent backtracking: what gets matched by a pattern with a possessive quantifier will not be backtracked into, even if that causes the whole match to fail.
There is no quantifier {,n} --- that gets understood as a literal string.
EXTENDED CONSTRUCTS
(?#text) A comment (?:...) Groups subexpressions without capturing (cluster) (?pimsx-imsx:...) Enable/disable option (as per m// modifiers) (?=...) Zero-width positive lookahead assertion (?!...) Zero-width negative lookahead assertion (?<=...) Zero-width positive lookbehind assertion (?<!...) Zero-width negative lookbehind assertion (?>...) Grab what we can, prohibit backtracking (?|...) Branch reset (?<name>...) Named capture (?'name'...) Named capture (?P<name>...) Named capture (python syntax) (?{ code }) Embedded code, return value becomes $^R (??{ code }) Dynamic regex, return value used as regex (?N) Recurse into subpattern number N (?-N), (?+N) Recurse into Nth previous/next subpattern (?R), (?0) Recurse at the beginning of the whole pattern (?&name) Recurse into a named subpattern (?P>name) Recurse into a named subpattern (python syntax) (?(cond)yes|no) (?(cond)yes) Conditional expression, where "cond" can be: (N) subpattern N has matched something (<name>) named subpattern has matched something ('name') named subpattern has matched something (?{code}) code condition (R) true if recursing (RN) true if recursing into Nth subpattern (R&name) true if recursing into named subpattern (DEFINE) always false, no no-pattern allowed
VARIABLES
$_ Default variable for operators to use $` Everything prior to matched string $& Entire matched string $' Everything after to matched string ${^PREMATCH} Everything prior to matched string ${^MATCH} Entire matched string ${^POSTMATCH} Everything after to matched string
The use of "$`", $& or "$'" will slow down all regex use within your program. Consult perlvar for "@-" to see equivalent expressions that won't cause slow down. See also Devel::SawAmpersand. Starting with Perl 5.10, you can also use the equivalent variables "${^PREMATCH}", "${^MATCH}" and "${^POSTMATCH}", but for them to be defined, you have to specify the "/p" (preserve) modifier on your regular expression.
$1, $2 ... hold the Xth captured expr $+ Last parenthesized pattern match $^N Holds the most recently closed capture $^R Holds the result of the last (?{...}) expr @- Offsets of starts of groups. $-[0] holds start of whole match @+ Offsets of ends of groups. $+[0] holds end of whole match %+ Named capture buffers %- Named capture buffers, as array refs
Captured groups are numbered according to their opening paren.
FUNCTIONS
lc Lowercase a string lcfirst Lowercase first char of a string uc Uppercase a string ucfirst Titlecase first char of a string pos Return or set current match position quotemeta Quote metacharacters reset Reset ?pattern? status study Analyze string for optimizing matching split Use a regex to split a string into parts
The first four of these are like the escape sequences "\L", "\l", "\U", and "\u". For Titlecase, see ``Titlecase''.
TERMINOLOGY
TitlecaseUnicode concept which most often is equal to uppercase, but for certain characters like the German ``sharp s'' there is a difference.
AUTHOR
Iain Truskett. Updated by the Perl 5 Porters.This document may be distributed under the same terms as Perl itself.
SEE ALSO
- *
- perlretut for a tutorial on regular expressions.
- *
- perlrequick for a rapid tutorial.
- *
- perlre for more details.
- *
- perlvar for details on the variables.
- *
- perlop for details on the operators.
- *
- perlfunc for details on the functions.
- *
- perlfaq6 for FAQs on regular expressions.
- *
- perlrebackslash for a reference on backslash sequences.
- *
- perlrecharclass for a reference on character classes.
- *
- The re module to alter behaviour and aid debugging.
- *
- ``Debugging regular expressions'' in perldebug
- *
- perluniintro, perlunicode, charnames and perllocale for details on regexes and internationalisation.
- *
- Mastering Regular Expressions by Jeffrey Friedl (http://regex.info/) for a thorough grounding and reference on the topic.
THANKS
David P.C. Wollmann, Richard Soderberg, Sean M. Burke, Tom Christiansen, Jim Cromie, and Jeffrey Goff for useful advice.
Index
This document was created by man2html, using the manual pages.
Time: 05:29:08 GMT, December 24, 2015


ConcreteCipher()
A simple base class that defines a cipher which wraps an instance Cipher along with a Key.


Product List
Checkout form
{% csrf_token %}
Name
Email
Address
City
State
Zip
Amount To Be Paid
Place Order


Adventures in TDD
There are two challenges getting into TDD:
- Why should I test upfront when I know it fails (there's this massive aversion of failure in my part of the world)?
- Setting up the whole thing.
I made peace with the first requirement using a very large monitor and a split screen, writing code and test on parallel, deviating from the 'pure teachings' for the comfort of my workflow.
The second part is trickier, There are so many moving parts. This post documents some of the insights.
Testing in the IDE
TDD has the idea that you create your test first and only write code until your test passes. Then you write another failing test and start over writing code.
As a consequence you need to test in your IDE. For JavaScript or Java that's easy (the languages I use most):
- In JavaScript you define a script
test
in your package.json you can run any time. For a connoisseur there are tools like WallabyJS or VSCode Mocha Sidebar that run your tests as you type and/or save. The tricky part is: what testing libraries (more on that below) to use? - In Java Maven has a default goal
validate
and junit is the gold standard for tests. For automated continuous IDE testing there is Infinitest - For Salesforce you have a combination of JavaScript and Apex (and clicks-not-code), testing is a little trickier. The commercials IDE TheWelkingSuite and Illuminated Cloud make that a lot easier. How easy is in they eye of the beholder. (Honorable mention: JetForcer - I simply haven't tested that one yet)
Testing in your Continuous Integration
Automated testing, after a commit to Github, GitLab or BitBucket happens once you configure a pipeline as a hook into the repository and have tests specified the pipeline can pick up. Luckily your maven and npm scripts will most likely work as a starting point.
The bigger challenge is the orchestration of various services like static testing, dependency management and reporting (and good luck if your infra guys claim, they could setup and run everything inhouse).
Some of the selections available:
- Repository
- Github
- GitLab
- BitBucket
- Pipelines
- Heroku Flow
- BitBucket
- Travis
- Jenkins
- CodeShip
- CircleCI
- and more of them
- Testing and Reporting service
- CodeClimate
- SauceLab
- Codacy
- Coveralls
- Snyk (for vulnerabilities)
- GreenKeeper (for dependency management)
- and many more
some run extra tests, some report on tests that ran in your pipeline
What to test
There are multiple dimension you want to test. Not all of them at each moment in the development workflow. The rule of thumb: move from microtests (testing the code in the current editor focus) to "all bases covered" in your release branch. The closer to a release, the higher coverage needs to be.
- Test that run without backend data
- Unit tests: Does your code run without errors
- Assertions: Does your code compute correctly
- Coverage: Is your code sufficiently covered with tests
- Quality/Style: Is your code understandable and can it be maintained
- Tests that need backend data
- Component tests: Do component correctly receive and return data
- API tests: Do the APIs react as
- UI tests: Do interactions work on all targeted devices
- Load tests: Does the environment scale
The later is the hardest: your test environment most likely is setup differently than production, so a performance test, not run in production, doesn't tell you that much.
Tools in my chain
I can say "all of the above" and I do have my favorites, some out of convenience, some out of conviction:
- IDE
- Visual Studio Code for HTML, CSS, JS including WallabyJS for UnitTests
- Eclipse for Java (and XML using the oXygen plugin)
- The Welkin Suite for Salesforce
- Sublime for arbitrary files
- Version Control
- Bitbucket for my private repositories
- GitHub for the public (not moving)
- CI: No clear favorite. I like the Bitbucket and Heroku pipes, since they are integrated into source or target environment. I used the others too. Fond of Travis (my German bias ;-) )
- Testing
- Maven/JUnit for Java
- PMD for static code analysis (Java, JavaScript, Apex)
- Mocha for JavaScript. You will find the JavaScript environment changing fastest. Fortnightly there will be a new testing framework to rule them all. Lots of them a beverage themed (Mocha, Jasmine, Chai). Pick one, stick to it, write lots of tests. Hint: If you have to pick: switch the framework or write more tests...
- Chai for test in Postman
- Lightning Testing Service for Salesforce Lightning components
- Documentation / Paperwork
- iMindMap to brainstorm/plan
- JavaDoc, JSDoc, ApexDoc to pull code comments out
- WebsequenceDiagrams to generate sequence diagrams
- SmartDraw and LucidCharts for illustrations
As usual: YMMV
Posted by Stephan H Wissel on 10 June 2018 | Comments (4) | categories: JavaScript Salesforce Software


Cookies¶
An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user’s web browser. The browser may store it and send it back with later requests to the same server. Typically, it’s used to tell if two requests came from the same browser — keeping a user logged-in, for example. It remembers stateful information for the stateless HTTP protocol.
Cookies are mainly used for three purposes:
- Session management: Logins, shopping carts, game scores, or anything else the server should remember
- Personalization: User preferences, themes, and other settings
- Tracking: Recording and analyzing user behavior
To help you efficiently use cookies across browsers with your request and response,
CodeIgniter provides the CodeIgniter\Cookie\Cookie
class to abstract the
cookie interaction.
Creating Cookies¶
There are currently four (4) ways to create a new Cookie
value object.
use CodeIgniter\Cookie\Cookie;
use DateTime;
// Using the constructor
$cookie = new Cookie(
'remember_token',
'f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6',
[
'expires' => new DateTime('+2 hours'),
'prefix' => '__Secure-',
'path' => '/',
'domain' => '',
'secure' => true,
'httponly' => true,
'raw' => false,
'samesite' => Cookie::SAMESITE_LAX,
]
);
// Supplying a Set-Cookie header string
$cookie = Cookie::fromHeaderString(
'remember_token=f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6; Path=/; Secure; HttpOnly; SameSite=Lax',
false, // raw
);
// Using the fluent builder interface
$cookie = (new Cookie('remember_token'))
->withValue('f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6')
->withPrefix('__Secure-')
->withExpires(new DateTime('+2 hours'))
->withPath('/')
->withDomain('')
->withSecure(true)
->withHTTPOnly(true)
->withSameSite(Cookie::SAMESITE_LAX);
// Using the global function `cookie` which implicitly calls `new Cookie()`
$cookie = cookie('remember_token', 'f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6');
When constructing the Cookie
object, only the name
attribute is required. All other else are optional.
If the optional attributes are not modified, their values will be filled up by the default values saved in
the Cookie
class. To override the defaults currently stored in the class, you can pass a Config\Cookie
instance or an array of defaults to the static Cookie::setDefaults()
method.
use CodeIgniter\Cookie\Cookie;
use Config\Cookie as CookieConfig;
// pass in an Config\Cookie instance before constructing a Cookie class
Cookie::setDefaults(new CookieConfig());
$cookie = new Cookie('login_token');
// pass in an array of defaults
$myDefaults = [
'expires' => 0,
'samesite' => Cookie::SAMESITE_STRICT,
];
Cookie::setDefaults($myDefaults);
$cookie = new Cookie('login_token');
Passing the Config\Cookie
instance or an array to Cookie::setDefaults()
will effectively
overwrite your defaults and will persist until new defaults are passed. If you do not want this
behavior but only want to change defaults for a limited time, you can take advantage of
Cookie::setDefaults()
return which returns the old defaults array.
use CodeIgniter\Cookie\Cookie;
use Config\Cookie as CookieConfig;
$oldDefaults = Cookie::setDefaults(new CookieConfig());
$cookie = new Cookie('my_token', 'muffins');
// return the old defaults
Cookie::setDefaults($oldDefaults);
Accessing Cookie’s Attributes¶
Once instantiated, you can easily access a Cookie
’s attribute by using one of its getter methods.
use CodeIgniter\Cookie\Cookie;
use DateTime;
use DateTimeZone;
$cookie = new Cookie(
'remember_token',
'f699c7fd18a8e082d0228932f3acd40e1ef5ef92efcedda32842a211d62f0aa6',
[
'expires' => new DateTime('2025-02-14 00:00:00', new DateTimeZone('UTC')),
'prefix' => '__Secure-',
'path' => '/',
'domain' => '',
'secure' => true,
'httponly' => true,
'raw' => false,
'samesite' => Cookie::SAMESITE_LAX,
]
);
$cookie->getName(); // 'remember_token'
$cookie->getPrefix(); // '__Secure-'
$cookie->getPrefixedName(); // '__Secure-remember_token'
$cookie->getExpiresTimestamp(); // Unix timestamp
$cookie->getExpiresString(); // 'Fri, 14-Feb-2025 00:00:00 GMT'
$cookie->isExpired(); // false
$cookie->getMaxAge(); // the difference from time() to expires
$cookie->isRaw(); // false
$cookie->isSecure(); // true
$cookie->getPath(); // '/'
$cookie->getDomain(); // ''
$cookie->isHTTPOnly(); // true
$cookie->getSameSite(); // 'Lax'
// additional getter
$cookie->getId(); // '__Secure-remember_token;;/'
// when using `setcookie()`'s alternative signature on PHP 7.3+
// you can easily use the `getOptions()` method to supply the
// $options parameter
$cookie->getOptions();
Immutable Cookies¶
A new Cookie
instance is an immutable value object representation of an HTTP cookie. Being immutable,
modifying any of the instance’s attributes will not affect the original instance. The modification always
returns a new instance. You need to retain this new instance in order to use it.
use CodeIgniter\Cookie\Cookie;
$cookie = new Cookie('login_token', 'admin');
$cookie->getName(); // 'login_token'
$cookie->withName('remember_token');
$cookie->getName(); // 'login_token'
$new = $cookie->withName('remember_token');
$new->getName(); // 'remember_token'
Validating a Cookie’s Attributes¶
An HTTP cookie is regulated by several specifications that need to be followed in order to be
accepted by browsers. Thus, when creating or modifying certain attributes of the Cookie
,
these are validated in order to check if these follow the specifications.
A CookieException
is thrown if violations were reported.
Validating the Name Attribute¶
A cookie name can be any US-ASCII character, except for the following:
- control characters;
- spaces or tabs;
- separator characters, such as
( ) < > @ , ; : \ " / [ ] ? = { }
If setting the $raw
parameter to true
this validation will be strictly made. This is because
PHP’s setcookie
and setrawcookie
will reject cookies with invalid names. Additionally, cookie
names cannot be an empty string.
Validating the Prefix Attribute¶
When using the __Secure-
prefix, cookies must be set with the $secure
flag set to true
. If
using the __Host-
prefix, cookies must exhibit the following:
$secure
flag set totrue
$domain
is empty$path
must be/
Validating the SameSite Attribute¶
The SameSite attribute only accepts three (3) values:
- Lax: Cookies are not sent on normal cross-site subrequests (for example to load images or frames into a third party site), but are sent when a user is navigating to the origin site (i.e. when following a link).
- Strict: Cookies will only be sent in a first-party context and not be sent along with requests initiated by third party websites.
- None: Cookies will be sent in all contexts, i.e. in responses to both first-party and cross-origin requests.
CodeIgniter, however, allows you to set the SameSite attribute to an empty string. When an empty string is
provided, the default SameSite setting saved in the Cookie
class is used. You can change the default SameSite
by using the Cookie::setDefaults()
as discussed above.
Recent cookie specifications have changed such that modern browsers are being required to give a default SameSite
if nothing was provided. This default is Lax
. If you have set the SameSite to be an empty string and your
default SameSite is also an empty string, your cookie will be given the Lax
value.
If the SameSite is set to None
you need to make sure that Secure
is also set to true
.
When writing the SameSite attribute, the Cookie
class accepts any of the values case-insensitively. You can
also take advantage of the class’s constants to make it not a hassle.
use CodeIgniter\Cookie\Cookie;
Cookie::SAMESITE_LAX; // 'lax'
Cookie::SAMESITE_STRICT; // 'strict'
Cookie::SAMESITE_NONE; // 'none'
Using the Cookie Store¶
The CookieStore
class represents an immutable collection of Cookie
objects. The CookieStore
instance can be accessed from the current Response
object.
use Config\Services;
$cookieStore = Services::response()->getCookieStore();
CodeIgniter provides three (3) other ways to create a new instance of the CookieStore
.
use CodeIgniter\Cookie\Cookie;
use CodeIgniter\Cookie\CookieStore;
// Passing an array of `Cookie` objects in the constructor
$store = new CookieStore([
new Cookie('login_token'),
new Cookie('remember_token'),
]);
// Passing an array of `Set-Cookie` header strings
$store = CookieStore::fromCookieHeaders([
'remember_token=me; Path=/; SameSite=Lax',
'login_token=admin; Path=/; SameSite=Lax',
]);
// using the global `cookies` function
$store = cookies([new Cookie('login_token')], false);
// retrieving the `CookieStore` instance saved in our current `Response` object
$store = cookies();
Note
When using the global cookies()
function, the passed Cookie
array will only be considered
if the second argument, $getGlobal
, is set to false
.
Checking Cookies in Store¶
To check whether a Cookie
object exists in the CookieStore
instance, you can use several ways:
use CodeIgniter\Cookie\Cookie;
use CodeIgniter\Cookie\CookieStore;
use Config\Services;
// check if cookie is in the current cookie collection
$store = new CookieStore([
new Cookie('login_token'),
new Cookie('remember_token'),
]);
$store->has('login_token');
// check if cookie is in the current Response's cookie collection
cookies()->has('login_token');
Services::response()->hasCookie('remember_token');
// using the cookie helper to check the current Response
// not available to v4.1.1 and lower
helper('cookie');
has_cookie('login_token');
Getting Cookies in Store¶
Retrieving a Cookie
instance in a cookie collection is very easy:
use CodeIgniter\Cookie\Cookie;
use CodeIgniter\Cookie\CookieStore;
use Config\Services;
// getting cookie in the current cookie collection
$store = new CookieStore([
new Cookie('login_token'),
new Cookie('remember_token'),
]);
$store->get('login_token');
// getting cookie in the current Response's cookie collection
cookies()->get('login_token');
Services::response()->getCookie('remember_token');
// using the cookie helper to get cookie from the Response's cookie collection
helper('cookie');
get_cookie('remember_token');
When getting a Cookie
instance directly from a CookieStore
, an invalid name
will throw a CookieException
.
// throws CookieException
$store->get('unknown_cookie');
When getting a Cookie
instance from the current Response
’s cookie collection,
an invalid name will just return null
.
cookies()->get('unknown_cookie'); // null
If no arguments are supplied in when getting cookies from the Response
, all Cookie
objects
in store will be displayed.
cookies()->get(); // array of Cookie objects
// alternatively, you can use the display method
cookies()->display();
// or even from the Response
Services::response()->getCookies();
Note
The helper function get_cookie()
gets the cookie from the current Request
object, not
from Response
. This function checks the $_COOKIE array if that cookie is set and fetches it
right away.
Adding/Removing Cookies in Store¶
As previously mentioned, CookieStore
objects are immutable. You need to save the modified instance
in order to work on it. The original instance is left unchanged.
use CodeIgniter\Cookie\Cookie;
use CodeIgniter\Cookie\CookieStore;
use Config\Services;
$store = new CookieStore([
new Cookie('login_token'),
new Cookie('remember_token'),
]);
// adding a new Cookie instance
$new = $store->put(new Cookie('admin_token', 'yes'));
// removing a Cookie instance
$new = $store->remove('login_token');
Note
Removing a cookie from the store DOES NOT delete it from the browser. If you intend to delete a cookie from the browser, you must put an empty value cookie with the same name to the store.
When interacting with the cookies in store in the current Response
object, you can safely add or delete
cookies without worrying the immutable nature of the cookie collection. The Response
object will replace
the instance with the modified instance.
use Config\Services;
Services::response()->setCookie('admin_token', 'yes');
Services::response()->deleteCookie('login_token');
// using the cookie helper
helper('cookie');
set_cookie('admin_token', 'yes');
delete_cookie('login_token');
Dispatching Cookies in Store¶
More often than not, you do not need to concern yourself in manually sending cookies. CodeIgniter will do this
for you. However, if you really need to manually send cookies, you can use the dispatch
method. Just like
in sending other headers, you need to make sure the headers are not yet sent by checking the value
of headers_sent()
.
use CodeIgniter\Cookie\Cookie;
use CodeIgniter\Cookie\CookieStore;
$store = new CookieStore([
new Cookie('login_token'),
new Cookie('remember_token'),
]);
$store->dispatch(); // After dispatch, the collection is now empty.
Cookie Personalization¶
Sane defaults are already in place inside the Cookie
class to ensure the smooth creation of cookie
objects. However, you may wish to define your own settings by changing the following settings in the
Config\Cookie
class in app/Config/Cookie.php
file.
| Setting | Options/ Types | Default | Description |
|---|---|---|---|
| $prefix | string |
'' |
Prefix to prepend to the cookie name. |
| $expires | DateTimeInterface|string|int |
0 |
The expires timestamp. |
| $path | string |
/ |
The path property of the cookie. |
| $domain | string |
'' |
The domain property of the cookie.with trailing slash. |
| $secure | true/false |
false |
If to be sent over secure HTTPS. |
| $httponly | true/false |
true |
If not accessible to JavaScript. |
| $samesite | Lax|None|Strict|lax|none|strict'' |
Lax |
The SameSite attribute. |
| $raw | true/false |
false |
If to be dispatched using setrawcookie() . |
In runtime, you can manually supply a new default using the Cookie::setDefaults()
method.
Class Reference¶
-
CodeIgniter\HTTP\Cookie\Cookie
-
static
setDefaults
([$config = []])¶ Parameters: - $config (ConfigCookie|array) – The configuration array or instance
Return type: array<string, mixed>
Returns: The old defaults
Set the default attributes to a Cookie instance by injecting the values from the
\Config\Cookie
config or an array.
-
static
fromHeaderString
(string $header[, bool $raw = false])¶ Parameters: - $header (string) – The
Set-Cookie
header string - $raw (bool) – Whether this cookie is not to be URL encoded and sent via
setrawcookie()
Return type: Cookie
Returns: Cookie
instanceThrows: CookieException
Create a new Cookie instance from a
Set-Cookie
header.- $header (string) – The
-
__construct
(string $name[, string $value = ''[, array $options = []]])¶ Parameters: - $name (string) – The cookie name
- $value (string) – The cookie value
- $options (array) – The cookie options
Return type: Cookie
Returns: Cookie
instanceThrows: CookieException
Construct a new Cookie instance.
-
getId
()¶ Return type: string Returns: The ID used in indexing in the cookie collection.
-
getPrefix(): string
-
getName(): string
-
getPrefixedName(): string
-
getValue(): string
-
getExpiresTimestamp(): int
-
getExpiresString(): string
-
isExpired(): bool
-
getMaxAge(): int
-
getDomain(): string
-
getPath(): string
-
isSecure(): bool
-
isHTTPOnly(): bool
-
getSameSite(): string
-
isRaw(): bool
-
getOptions(): array
-
withRaw
([bool $raw = true])¶ Parameters: - $raw (bool) –
Return type: Cookie
Returns: new
Cookie
instanceCreates a new Cookie with URL encoding option updated.
-
withPrefix
([string $prefix = ''])¶ Parameters: - $prefix (string) –
Return type: Cookie
Returns: new
Cookie
instanceCreates a new Cookie with new prefix.
-
withName
(string $name)¶ Parameters: - $name (string) –
Return type: Cookie
Returns: new
Cookie
instanceCreates a new Cookie with new name.
-
withValue
(string $value)¶ Parameters: - $value (string) –
Return type: Cookie
Returns: new
Cookie
instanceCreates a new Cookie with new value.
-
withExpires
($expires)¶ Parameters: - $expires (DateTimeInterface|string|int) –
Return type: Cookie
Returns: new
Cookie
instanceCreates a new Cookie with new cookie expires time.
-
withExpired
()¶ Return type: Cookie
Returns: new Cookie
instanceCreates a new Cookie that will expire from the browser.
-
withNeverExpiring
()¶ Parameters: - $name (string) –
Return type: Cookie
Returns: new
Cookie
instanceCreates a new Cookie that will virtually never expire.
-
withDomain
(?string $domain)¶ Parameters: - $domain (string|null) –
Return type: Cookie
Returns: new
Cookie
instanceCreates a new Cookie with new domain.
-
withPath
(?string $path)¶ Parameters: - $path (string|null) –
Return type: Cookie
Returns: new
Cookie
instanceCreates a new Cookie with new path.
-
withSecure
([bool $secure = true])¶ Parameters: - $secure (bool) –
Return type: Cookie
Returns: new
Cookie
instanceCreates a new Cookie with new “Secure” attribute.
-
withHTTPOnly
([bool $httponly = true])¶ Parameters: - $httponly (bool) –
Return type: Cookie
Returns: new
Cookie
instanceCreates a new Cookie with new “HttpOnly” attribute.
-
withSameSite
(string $samesite)¶ Parameters: - $samesite (string) –
Return type: Cookie
Returns: new
Cookie
instanceCreates a new Cookie with new “SameSite” attribute.
-
toHeaderString
()¶ Return type: string Returns: Returns the string representation that can be passed as a header string.
-
toArray
()¶ Return type: array Returns: Returns the array representation of the Cookie instance.
-
static
-
CodeIgniter\HTTP\Cookie\CookieStore
-
static
fromCookieHeaders
(array $headers[, bool $raw = false])¶ Parameters: - $header (array) – Array of
Set-Cookie
headers - $raw (bool) – Whether not to use URL encoding
Return type: CookieStore
Returns: CookieStore
instanceThrows: CookieException
Creates a CookieStore from an array of
Set-Cookie
headers.- $header (array) – Array of
-
__construct
(array $cookies) Parameters: - $cookies (array) – Array of
Cookie
objects
Return type: CookieStore
Returns: CookieStore
instanceThrows: CookieException
- $cookies (array) – Array of
-
has(string $name[, string $prefix = ''[, ?string $value = null]]): bool
Parameters: - $name (string) – Cookie name
- $prefix (string) – Cookie prefix
- $value (string|null) – Cookie value
Return type: bool
Returns: Checks if a
Cookie
object identified by name and prefix is present in the collection.
-
get(string $name[, string $prefix = '']): Cookie
Parameters: - $name (string) – Cookie name
- $prefix (string) – Cookie prefix
Return type: Cookie
Returns: Retrieves an instance of Cookie identified by a name and prefix.
Throws: CookieException
-
put(Cookie $cookie): CookieStore
Parameters: - $cookie (Cookie) – A Cookie object
Return type: CookieStore
Returns: new
CookieStore
instanceStore a new cookie and return a new collection. The original collection is left unchanged.
-
remove(string $name[, string $prefix = '']): CookieStore
Parameters: - $name (string) – Cookie name
- $prefix (string) – Cookie prefix
Return type: CookieStore
Returns: new
CookieStore
instanceRemoves a cookie from a collection and returns an updated collection. The original collection is left unchanged.
-
dispatch(): void
Return type: void Dispatches all cookies in store.
-
display(): array
Return type: array Returns: Returns all cookie instances in store.
-
clear(): void
Return type: void Clears the cookie collection.
-
static


--- title: "MATLAB Control Flow Structures m-Files" author: "Pooya Shirazi" date: 2018-12-19T00:00:00-08:20 output: html_document ---
MATLAB Control Flow Structures m-Files Sample 01.
MATLAB Control Flow Structures m-Files Sample 02.


Source code for watchdog.utils
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 Yesudeep Mangalapilly<EMAIL_ADDRESS># Copyright 2012 Google, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
:module: watchdog.utils
:synopsis: Utility classes and functions.
:author<EMAIL_ADDRESS>(Yesudeep Mangalapilly)
Classes
-------
.. autoclass:: BaseThread
:members:
:show-inheritance:
:inherited-members:
"""
import os
import sys
import threading
import watchdog.utils.platform
from watchdog.utils.compat import Event
from collections import namedtuple
if sys.version_info[0] == 2 and platform.is_windows():
# st_ino is not implemented in os.stat on this platform
import win32stat
stat = win32stat.stat
else:
stat = os.stat
def has_attribute(ob, attribute):
"""
:func:`hasattr` swallows exceptions. :func:`has_attribute` tests a Python object for the
presence of an attribute.
:param ob:
object to inspect
:param attribute:
``str`` for the name of the attribute.
"""
return getattr(ob, attribute, None) is not None
class UnsupportedLibc(Exception):
pass
[docs]class BaseThread(threading.Thread):
""" Convenience class for creating stoppable threads. """
def __init__(self):
threading.Thread.__init__(self)
if has_attribute(self, 'daemon'):
self.daemon = True
else:
self.setDaemon(True)
self._stopped_event = Event()
if not has_attribute(self._stopped_event, 'is_set'):
self._stopped_event.is_set = self._stopped_event.isSet
@property
def stopped_event(self):
return self._stopped_event
[docs] def should_keep_running(self):
"""Determines whether the thread should continue running."""
return not self._stopped_event.is_set()
[docs] def on_thread_stop(self):
"""Override this method instead of :meth:`stop()`.
:meth:`stop()` calls this method.
This method is called immediately after the thread is signaled to stop.
"""
pass
[docs] def stop(self):
"""Signals the thread to stop."""
self._stopped_event.set()
self.on_thread_stop()
[docs] def on_thread_start(self):
"""Override this method instead of :meth:`start()`. :meth:`start()`
calls this method.
This method is called right before this thread is started and this
object’s run() method is invoked.
"""
pass
def start(self):
self.on_thread_start()
threading.Thread.start(self)
def load_module(module_name):
"""Imports a module given its name and returns a handle to it."""
try:
__import__(module_name)
except ImportError:
raise ImportError('No module named %s' % module_name)
return sys.modules[module_name]
def load_class(dotted_path):
"""Loads and returns a class definition provided a dotted path
specification the last part of the dotted path is the class name
and there is at least one module name preceding the class name.
Notes:
You will need to ensure that the module you are trying to load
exists in the Python path.
Examples:
- module.name.ClassName # Provided module.name is in the Python path.
- module.ClassName # Provided module is in the Python path.
What won't work:
- ClassName
- modle.name.ClassName # Typo in module name.
- module.name.ClasNam # Typo in classname.
"""
dotted_path_split = dotted_path.split('.')
if len(dotted_path_split) > 1:
klass_name = dotted_path_split[-1]
module_name = '.'.join(dotted_path_split[:-1])
module = load_module(module_name)
if has_attribute(module, klass_name):
klass = getattr(module, klass_name)
return klass
# Finally create and return an instance of the class
# return klass(*args, **kwargs)
else:
raise AttributeError('Module %s does not have class attribute %s' % (
module_name, klass_name))
else:
raise ValueError(
'Dotted module path %s must contain a module name and a classname' % dotted_path)


- Member AbstractOrder::setName (string $name)
- create-only
- Member CustomCollect::setPosition (int $position)
- create-only, the custom collection must be set to sort manually.
- Member CustomCollect::setSortValue (int $value)
- create-only, the custom collection must be set to sort manually.
- Member Customer::getTaxExemptions ()
- canada-only
- Member Customer::hasTaxExemptions ()
- canada-only
- Member Customer::setAddresses (Address[] $addresses)
- create-only, bulk
- Member Customer::setSendEmailInvite (bool $invite)
- create-only
- Member Customer::setSendEmailWelcome (bool $welcome)
- create-only
- Member Customer::setState (string $status)
- create-only, see the constants
- Member DraftOrder::setUseCustomerDefaultAddress (bool $flag)
- create-only
- Member GiftCard::setCode (string $code)
- create-only, write-only
- Member GiftCard::setInitialValue (number $value)
- create-only
- Member Image::setAttachment (string $base64)
- create-only
- Member Image::setFilename (string $filename)
- create-only
- Member Image::setSrc (string $url)
- create-only
- Member InventoryItem::getProvinceCodeOfOrigin ()
- canada-only
- Member InventoryItem::setProvinceCodeOfOrigin (string $code)
- canada-only
- Member MarketingEvent::setEventType (string $type)
- required, see the type constants.
- Member MarketingEvent::setMarketingChannel (string $channel)
- required, see the channel constants.
- Member MarketingEvent::setPaid (bool $paid)
- required
- Member MarketingEvent::setStartedAt (string $iso8601)
- required
- Member Metafield::setKey (string $key)
- create-only
- Member Metafield::setNamespace (string $ns)
- create-only
- Member Order::setCancelReason (string $reason)
- create-only
- Member Order::setDiscountCodes (Discount[] $codes)
- create-only
- Member Order::setFinancialStatus (string $status)
- create-only
- Member Order::setFulfillments (string[] $fulfillments)
- create-only
- Member Order::setFulfillmentStatus (string $status)
- create-only
- Member Order::setInventoryBehavior (string $behavior)
- create-only
- Member Order::setLocationId (string $id)
- create-only
- Member Order::setPresentmentCurrency (string $currency)
- create-only
- Member Order::setProcessedAt (string $iso8601)
- create-only, historical creation date
- Member Order::setSendFulfillmentReceipt (bool $receipt)
- create-only
- Member Order::setSendReceipt (bool $receipt)
- create-only
- Member Order::setShippingLines (Shipping[] $lines)
- create-only
- Member Order::setSourceName (string $name)
- create-only
- Member Order::setSubtotalPriceSet (string $set)
- create-only
- Member Order::setTaxLines (Tax[] $taxes)
- create-only
- Member Order::setTest (bool $test)
- create-only
- Member Order::setTotalDiscounts (string $discounts)
- create-only
- Member Order::setTotalDiscountsSet (string $set)
- create-only
- Member Order::setTotalLineItemsPrice (number $price)
- create-only
- Member Order::setTotalLineItemsPriceSet (string $set)
- create-only
- Member Order::setTotalPriceSet (string $set)
- create-only
- Member Order::setTotalTaxSet (string $set)
- create-only
- Member Order::setTotalTipReceived (string $received)
- create-only
- Member Order::setTotalWeight (string $weight)
- create-only
- Member Product::setTitle (string $title)
- required
- Member Refund::setCurrency (string $currency)
- create-only
- Member Refund::setDiscrepancyReason (string $reason)
- create-only
- Member Refund::setFullShipping ()
- create-only
- Member Refund::setNote (string $note)
- create-only
- Member Refund::setNotify (bool $notify)
- create-only
- Member Refund::setProcessedAt (string $iso8601)
- create-only
- Member Refund::setRefundLineItems (RefundItem[] $items)
- create-only
- Member Refund::setShippingAmount (string $amount)
- create-only
- Member Refund::setTransactions (Transaction[] $transactions)
- create-only
- Member Refund::setUserId (string $id)
- create-only
- Member Theme::setSrc (string $src)
- create-only


Forrest Gump
Prefix: Mr.
First Name: Forrest
Last Name: Gump
home
42 Plantation St.
Baytown, LA 30314
United States of America
Home Address:
42 Plantation St.
Baytown, LA
30314
United States of America
Home Phone:
(111) 555-1212
Organization: Bubba Gump Shrimp Co.
Title: Shrimp Man
work
100 Waters Edge
Baytown, LA 30314
United States of America
Work Address (preferred):
100 Waters Edge
Baytown, LA
30314
United States of America
Work Phone:
(404) 555-1212
vCard last updated:


| Enter Monthly Unit: |
| Consumtion Unit | Amount |
| Total Amount |
0 t0 100 units charges (Rs 5.79/per Unit)
100 t0 200 units charges (RS 8.11/per Unit)
200 to 300 units charges (Rs 10.20/per Units)
300 t0 400 units charges (Rs 17.60/per Units)
400 to above units charges (RS 20.70/per units


AJ's First webpage
AJ Markows Totally Awesome Website
This is my first webpage
My interests
I want to learn about:
Javascript
Docker
SQL
SAML
MY FAVORITE THINGS


time and habits
Time management has always been a difficulty for me to date. I'm normally a notorious procrastinator and my attention span is usually poor. However, since starting this course I have got myself into good habits and have started off strong by getting myself up in a morning and going into an office space where I have no distractions whilst I work.
Observing the resources really gave me a better insight on how to effectively manage time as it's never been something I've bothered with and it has been a big downfall for me. I think the key part to it all seems to be timeboxing, and thats what I've started to do myself. However, reading about the 'lizard brain' really spoke to me as that resistance is a big issue for me at times.
I intend on experimenting with meditation although I don't really think it's for me, I want to give it ago and just see where it takes me.


The manual development of photographs is a traditional practice but one with great potential for versatility. Enthusiasts have preserved this craft despite the advances in printing technology to maintain the integrity and the true authenticity of the craft. We at BlackBox felt there was no reason why the traditional way of developing photos couldn’t be automated so we set about creating the solution.
Working in darkness - We noticed that
low light levels are required to get the optimal
photograph. This makes the
process time-consuming as the technician has to feel their
way around the dark room to find the right containers
whilst being careful not to back contaminate the various
chemicals.
Fumes - Fumes emitted by the developing liquids could
cause light-headedness
when excessively inhaled.
Time keeping - Although not crucial, timing influences the
quality and longevity of a photo. For best-quality prints
it is vital that the integrity of each chemical is
maintained.
We at BlackBox believe the way to get something done is through action. So we are rapidly progressing through prototypes and learning through experimentation. The result - a product that keeps getting better!
Operations
Key skills - Organisation, Coding, Project Management
Creative Design
Key skills - Coding, Mechanical Design, Web Development
Research
Key skills - Visual Design, User experience + Interface, CAD + Rendering
Technical Design
Electronics, Automation, CAD, Mechanical Design
There are a few key tools that have been used to aid the development of this website - the first of which was Atom. Atom is a desktop text editor that is developed by Github and works with it to host web code in HTML, Javascript and CSS. Here files are stored & found, and the code is built to power the site. Github hosts code repositories, which allows you to create and push your edited code in HTML to the web, and it's most useful differentiating feature is effective version control which makes development much easier. The website started as a template from Bootstrap and was then edited and built up from there. To create a custom domain first you must simply register the name with Github - as long as it isn't taken Github will host it for you.
A good website is in essence one that brings joy to the user interacting with it. This boils down to easy navigation and intuitive layout, as well as performance (speed of loading and smoothness of interactive components). Finally the best websites are usually simple and to the point.
Web accessibility uses varying inclusive practices to ensure a web page is free from barriers that could prevent people with certain disabilities or restrictions from interacting with the site. These can include visual, motor, cognitive or socio-economic impairments. To accommodate these language is kept simple, high-contrasting colours are used with alternative text and interactive components are made extra intuitive and simple.
General Data Protection Regulation (GDPR) is a legal data protection framework which defines how personal information of EU residents is processed. It encompasses 7 key principles for data handling covering reasons for holding information, transparency and control, limitations and a clear line of accountability. This website does not collect user data so is compliant, however if it did I would ensure users could opt out of data-gathering.
I would look to employ search engine optimisation and pay for advertisements on popular websites. I would also reach out to interested communities through forums and share clear links to my website. Finally once here I would make clear buttons for users to share with friends.
With additional time I could explore integration of selling our product directly in the website. To drive traffic I could also embed a forum here and finally to improve the content I would add more pictures and demonstration videos.


Hex map builder
We like creating hex maps so we've created a tool to help you make them from your own data. You can either read in an existing HexJSON file or start creating your own hex map from a CSV file. The CSV should contain a column with the heading id
that uniquely identifies each hex. Other columns will be added as properties of each hex. You can specify the position of the hex using the column headings q
and r
. A column with the heading n
or name
will set the displayed name of the hex. Once you have hexagons, move them to your desired positions (click one then click an empty hex to move it there). When you everything where you want it, save the output.
Drop a CSV or HexJSON file here (or click to browse files)


U.S. Cases and Deaths
Only if we end the pandemic everywhere can we end the pandemic anywhere. The entire world has the same goal: cases of COVID-19 need to go to zero.
The Data Explorer below shows date/month wise covid-19 progress report.
Deaths / Date
Negative - Positive cases / Date
Negative - Positive cases / Monthly
Deaths Increase / Date
Total Test Result Increase / Date
Ventilator - ICU - Hospitalized cases / Monthly
Hospitalized - ICU - Ventilator cases / Date
{% endblock %}


- Work Type
- Client - NAMI Central, TX
- My Role
- User Experience Designer and Researcher
- Time Frame
- Feb. - May 2019
- Skills
-
- Generative Research
- Prioritized Users
- Defined Objectives of Research
- Conducted Moderated Card Sorting Sessions
- Evaluative Research
- Wrote Usability Test Protocol
- Conducted Moderated Tree Test Sessions
- Synthesized Research to determine Design Recommendation
- Generative Research
Details
Summary
In this project my team was tasked with completely redesigning the NAMI Central, TX website. We were successful in delivering the project to the client and even exceeded their expectations. Evaluation of the project exceeded the original time line, but I was fortunate to continue this project with another team. We ran another Tree Test with the new navigation. That study is still ongoing, but as of now we have seen an overall success rate of 86%.
Through this project, I came to fully comprehend and practice the two types of UX research: Generative and evaluative. While the focus of generative research is truly exploring unknown space and learning, evaluative research determines if a design is successful in meeting the user’s goals. Before this project I thought all research was just research. Because this project was larger it required more detailed and intentional research, so that's how I learned the difference.
While analyzing the results from the second set of Tree Test, I noticed a pattern. We explicitly told users who the task was for and what to do. In other words, once users saw the first question, they learned the pattern and could then just search for clues. This introduced a confound: In some ways, we were testing our ability to give clues and less the learnability of the navigation. Going forward, I’d like to to avoid enabling participants to keyword/clue search, and instead create tasks and scenarios in order to get them thinking. In the real world, users don’t have a clear understanding of users’ roles or what it is they want to accomplish or what the service calls it. Yet that’s often how we set up the Tree Test. I’d like my future Tree Tests to model the real world, making the test more valuable and the knowledge gained more informative.
The Problem
The NAMI team had a deep understanding of their users and presented us with two main user problems:
- The website looked dated
- Users had trouble using the site
Investigating the first problem, a visit to the site showed that the site’s aesthetic was dated.
As for the second problem, NAMI had qualitative data: users would call and ask questions about how to use the site.
Research
Full details starting in "Discovering and Prioritizing Users" section of this case study.
Design
We designed a new navigation structure. Through moderated Card Sorting sessions we learned that users organize content by intended audience. This finding informed our final design for the information architecture and led us to take a “task then user role” approach.
Discovering and Prioritizing Users
We had to focus research on Problem 2:
- The website looked dated
- Users had trouble using the site
Problem 1 was clear cut--we could redesign the website with a contemporary audience in mind. Problem 2, however, needed to be explored. Generative research was necessary to fully understand the problem. Who are our users? What trouble were they having? Why were users having issues?
Who are the Users?
NAMI explained that there were 3 users types on the site.
The team needed to determine what each user’s goals and tasks were in order to better understand what real value NAMI can deliver to them. Based on our initial meeting with our stakeholders we made informed assumptions.
Prioritized Users
We had to prioritize users because of project timeline and feasibility. In order to understand where to focus, we asked ourselves one question:
Which user’s tasks and goals not being met?
As for donors, our client believed that the dated look was negatively affecting our design so a design refresh was already a part of the project plan. Because the donation process was handled through a 3rd party, that experience was largely outside of our scope.
The client expressed the tremendous value of volunteers, saying that they “provided something money couldn’t.” The client also pointed out that the volunteers were often the ones solving the issues that MHC encountered, so there was an opportunity to study what ways they were already solving problems.
NAMI reported receiving numerous calls from MHCs that made it clear the site was not serving this user. We realized quickly that the needs of MHCs should be explored--they were the ones already directly voicing problems.
Because there was so much at stake for the volunteers and MHC’s and because the donors were going to be served by the later design refresh, we prioritized Volunteers and MHC’s.
Generative Research
There were two main Generative Research objectives:
- Validate our assumptions of user’s tasks and goals
- Learn how users attempt to accomplish their tasks and goals
Let’s unpack these objectives.
- Validate our assumptions of user’s tasks and goals
- As always, it was important to be clear about what was an assumption because if our assumptions were wrong then we would be designing for an idea and not an actual person. By validating the user tasks and goals we confirmed what would provide real value for them.
- Learn how users attempt to accomplish their tasks and goals
- Understanding and learning how users attempt to accomplish their tasks and goals was important because we got an opportunity to see their reasoning, reactions, and guiding principles. We saw first hand how users reason through the website. We could see their emotional reactions to how things work or don’t work. Finally, we learned what overall ideas lead their actions.
Research Synthesis
Through interviews, conducted by other members of my team, we learned that there was confusion with the names of the all the classes offered by NAMI. The names seemingly had no relation with what the class actually was. Another issue discovered was that there was an overall confusion with how the content was organized. The excerpts below give you an idea of some of the frustration this was causing for users:
If you don't know what you are looking for, idk how you would identify those things
I don't understand these names
Calendar is under the "About" section
Can't find the volunteer Button
It was clear that more research was needed.
The interviews left us with an idea: Ok, so clearly people don't understand class names, and clearly people don’t understand how the content is organized--but we only know this in a general sense.
This lack of specificity led us to a Tree Test.
Tree Test
Why Tree Test? Well, the issues discovered in interviews was specifically around content organization. A Tree Test is an effective way to test this, because Tree Testing gives us an opportunity to create specific scenarios to see which tasks users have problems with. This is important because we can then focus on the tasks that users fail.We designed our test to have participants self identify their user type as donor, volunteer, MHC. Tree Testing told us which user types had issues and where those issues were. Here is a screenshot of the results of the Tree Test:
To summarize the results; Volunteers understood the jargon and therefore were mostly successful; MHC did not understand the jargon and failed. After the interviews and Tree Testing, we had a clearer understanding of the confusion, where the confusion was, and who was confused, but we still needed to know: How do we fix it?
Card Sorting
To answer this question, we needed to understand how a MHC would actually organize the content, so we conducted a moderated open Card Sort. Users were presented with a deck of cards that included descriptions of the classes offered by NAMI, then they were asked to group them into categories that made sense to the user, and finally were asked to name each category. They had the ability to change category names and move cards from different groups as they saw fit.
This type of test gave us insight into several things, including users’ reasoning for organizing content and the language they use. Most participants organized content by who it was intended for and what they were trying to do. As an example, “im an mhc and i was to get some support and education (task), I need it for myself (user role)”.
After we conducted the interviews, we had a good idea of the problem, where the problem was, and who the problem affected but needed to know how to solve it. The Card Sort told us how users thought about the offerings from NAMI and the language used to organize it. We were now ready to start on designing.
Evaluative Research
Evaluation of the project exceeded the original time line, but I was fortunate to continue this project with another team. This team we wrote a research protocol in order to detail the exactly what it was were were trying to learn. Our design hypothesized that a reorganization of the IA to users’ mental model would better enable them to browse and locate what they are seeking. Well, to validate this prediction, we needed to run a usability test.
Research Protocol
What was it we wanted to test? Learnability and confidence. How learnable is the content, and how confident are users they have selected the correct path?
Who should we test with? In order to get a true one-to-one comparison vs. the first round of research we needed to test it with the same prioritized users. Volunteers were so successful with the original navigation, but now that we had changed it, would they continue to be successful? They are a key user, so we needed to confirm that we didn’t disenfranchise them. MHC should clearly be included, not only because the site was so confusing for them initially, but more importantly because this is the purpose for NAMI. Without solving this user’s problems, there is no service provided. The NAMI vision isn't met.
How to test it? A Tree Test would tell us success rate and thus learnability, but we also needed to test confidence. We chose to measure this with a simple likert scale responding to the statement I felt very confident about my choices. Users were asked to rate this statement on a 5(?)-point scale, from strongly disagree to strongly agree. This measure showed that volunteers enjoyed a success rate of 92.5% while MHC were at 81.75%.
View More Case Studies
What do you think?
Designers are nothing without critique and feedback,
so let me know what you are thinking.


Fill out the fields below and we'll tell you how conservative or liberal your beliefs are and what party best aligns with you.
Should the government increase environmental regulations to prevent global warming?
Should there be more restrictions on the current process of purchasing a gun?
Do you support the legalization of Marijuana?
Should the government decrease military spending?
You are really blue
You are really red
You are right in the middle


Advanced Fruits
问题描述 :
The company "21st Century Fruits" has specialized in creating new sorts of fruits by transferring genes from one fruit into the genome of another one. Most times this method doesn’t work, but sometimes, in very rare cases, a new fruit emerges that tastes like a mixture between both of them.
A big topic of discussion inside the company is "How should the new creations be called?" A mixture between an apple and a pear could be called an apple-pear, of course, but this doesn’t sound very interesting. The boss finally decides to use the shortest string that contains both names of the original fruits as sub-strings as the new name. For instance, "applear" contains "apple" and "pear" (APPLEar and apPlEAR), and there is no shorter string that has the same property.
A big topic of discussion inside the company is "How should the new creations be called?" A mixture between an apple and a pear could be called an apple-pear, of course, but this doesn’t sound very interesting. The boss finally decides to use the shortest string that contains both names of the original fruits as sub-strings as the new name. For instance, "applear" contains "apple" and "pear" (APPLEar and apPlEAR), and there is no shorter string that has the same property.
A combination of a cranberry and a boysenberry would therefore be called a "boysecranberry" or a "craboysenberry", for example.
Your job is to write a program that computes such a shortest name for a combination of two given fruits. Your algorithm should be efficient, otherwise it is unlikely that it will execute in the alloted time for long fruit names.
输入:
Each line of the input contains two strings that represent the names of the fruits that should be combined. All names have a maximum length of 100 and only consist of alphabetic characters.
Input is terminated by end of file.
输出:
For each test case, output the shortest name of the resulting fruit on one line. If more than one shortest name is possible, any one is acceptable.
样例输入:
apple peach ananas banana pear peach
样例输出:
appleach bananas pearch
题意：将两个单词合并，重复的部分只输出一次。
分析：最长递增子序列的变形，只是输出的地方发生了变化
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; const int MN=200; int len1,len2; int b[MN][MN]; char s1[MN],s2[MN]; int c[MN][MN]; void LCSLenth() { int i,j; memset(c,0,sizeof(c)); for(i=1; i<=len1; i++) { for(j=1; j<=len2; j++) { if(s1[i-1]==s2[j-1]) { c[i][j]=c[i-1][j-1]+1; b[i][j]=0; } else if(c[i][j-1]<=c[i-1][j]) { c[i][j]=c[i-1][j]; b[i][j]=1;//从上边 } else { c[i][j]=c[i][j-1]; b[i][j]=2;//从左边 } } } } void Print(int i,int j) { if(i==0 && j==0) return ; else if(i==0 && j!=0) { Print(i,j-1); printf("%c",s2[j-1]); } else if(i!=0 && j==0) { Print(i-1,j); printf("%c",s1[i-1]); } else if(b[i][j]==0) { Print(i-1,j-1); printf("%c",s1[i-1]); } else if(b[i][j]==1) { Print(i-1,j); printf("%c",s1[i-1]); } else { Print(i,j-1); printf("%c",s2[j-1]);//若从右边过来的，则打印s2 //因为对于i是没发生变化的，也就是说s1序列位置没发生变化 } } int main() { int i,j; while(scanf("%s%s",&s1,&s2)!=EOF) { len1=strlen(s1); len2=strlen(s2); LCSLenth(); Print(len1,len2); printf("\n"); } return 0; }
解题报告转自：http://www.cnblogs.com/zsboy/archive/2013/03/16/2963194.html
(adsbygoogle = window.adsbygoogle || []).push({});
如何解决overload的问题呢？
很高兴你会喜欢这个网站。目前还没有一个开发团队，网站是我一个人在维护，都是用的开源系统，也没有太多需要开发的部分，主要是内容整理。非常感谢你的关注。
已经挂掉了，给个参考呗
这配图…..
找bug好专业的说
第一种方法怎么会是O(log(m+n))呢？没有二分的话直接遍历应该就是O(m+n)吧？
if(j){
int ans=a ;
for(int x=j-1;x>=0;x–){
if(!a ) break;
ans=min(ans,a );
sum+=ans;
}
}
求解释，，dp的思路是什么呢？
第15行代码，/n/n，应该改为nn
Thank you very much


A JavaFX desktop application using WebView. The main logic is programmed in pure Java, but the user interface is based on state of the art web technologies: AngularJS (user controller) and Bootstrap (style and layout).
Result of Number1 + Number2 is: {{ sum() }}
(the result is computed in pure Java via a synchronous call)
| Name |
|---|
| {{fruit}} |