nested package¶
Submodules¶
nested.Agent module¶
This module contains the Agent class. The Agent and Stream classes are the building blocks of PythonStreams.
-
class
nested.Agent.
Agent
(in_streams, out_streams, transition, state=None, call_streams=None, stream_manager=None, name=None)¶ Bases:
object
An agent is an automaton: a state-transition machine. An agent is initialized in __init__ and a state transition is executed by next().
An agent has lists of input streams, output streams and call streams. Streams are described in Stream.py.
During a state transition an agent may read values from its input streams, append values to its output streams, change its state and carry out operations on other objects.
When a call stream is modified the agent’s next() method is called which causes the agent to execute a state transition.
The default is that every input stream is also a call stream, i.e., the agent executes a state transition when any of its input streams is modified. For performance reasons, we may not want the agent to execute state transitions when some input streams are modified; in this case, the sets of call and input streams will be different.
- InList : a named_tuple with arguments:
list, start, stop An InList defines the list slice:
list[start:stop]
in_streams : list of streams out_streams : list of streams call_streams : list of streams
When a new value is added to a stream in this list a state transition is invoked. This the usual way (but not the only way) in which state transitions occur.- state: object
- The state of the agent. The state is updated after a transition.
- transition: function
- This function is called by next() which is the state-transition operation for this agent. An agent’s state transition is specified by its transition function.
- stream_manager : function
- Each stream has management variables, such as whether the stream is open or closed. After a state-transition the agent executes the stream_manager function to modify the management variables of the agent’s output and call streams.
- name : str, optional
- name of this agent
- _in_lists: list of InList
- InList defines the slice of a list. The j-th element of _in_lists is an InList that defines the slice of the j-th input stream that may be read by this agent in a state transition.
- _out_lists: list
- The j-th element of the list is the list of values to be appended to the j-th output stream after the state transition.
- next(stream_name=None)
- Execute a state transition. The method has 3 parts:
set up the data structures to execute a state transition,
call transition to: (a) get the values to be appended to output streams, (b) get the next state, and (c) update pointers into input streams identifying what
parts of the stream may be read in the future.
update data structures after the transition.
-
next
(stream_name=None)¶ Execute the next state transition.
This function does the following: Part 1: set up data structures for the state transition. Part 2: execute the state transition by calling self.transition Part 3: update data structures after the transition.
This method can be called by any agent and is called whenever a value is appended to any stream in call_streams
- stream_name : str, optional
- A new value was appended to the stream with name stream_name as a result of which this agent executes a state transition.
nested.Animation module¶
Using a JSON file in my special format, this module generates the Javascript data structures for the animation:
- The graph
ie. how are the nodes/edges arranged?
- The animation sequence
ie. which values are at each edge at each time step
-
nested.Animation.
make_graph
(agent_descriptor_dict, stream_names_tuple)¶ Returns the 2 strings whose values are the edge and node arrays for the JS file
- agent_descriptor_dict : dict
Dict form of JSON in our special format. Component names paired with the associated:
in streams, out streams, function, parameters, type, state- stream_names_tuple : list
- List of all stream names.
- nodes : str
- String representation of the ‘nodes’ array for Cytoscape JS to create a graph
- edges : str
- String representation of the ‘edges’ array for Cytoscape JS to create a graph
-
nested.Animation.
make_js
(json_file)¶ Using a JSON file of my format, generate Javascript text the fills in a template .js file with:
graph configuration (draws the graph) animation sequence (animates graph)Opens default browser to display animation.
- json_file : json
- JSON file object of a JSON in my special format
None
-
nested.Animation.
make_seq
(agent_descriptor_dict, stream_names_tuple)¶ Executes graph. All components are fired at every time step and value/edge pairs are stored and returned to populate the JS file.
- agent_descriptor_dict : dict
Dict form of JSON in our special format. Component names paired with the associated:
in streams, out streams, function, parameters, type, state- stream_names_tuple : list
- List of all stream names.
stream_str + ‘
‘ + selector_str + ‘ ‘ + val_str : str
String representation of 3 JS arrays of (# of time steps) * (# of streams) elements, where elements at each index correspond to each other
‘stream_str’: ‘stream_name’ array with names of all streams ‘selector_str’: ‘edge’ array is ‘stream_name’ array but
formatted as Cytoscape edge selectors‘val_str’: ‘value’ array with stream values
nested.MakeNetwork module¶
Handle JSON <–> agent descriptor dict -> Streams network
-
nested.MakeNetwork.
JSON_to_descriptor_dict_and_stream_names
(my_json_file_name)¶
-
nested.MakeNetwork.
make_agent_descriptor_dict
(instance_dict, comp_list)¶
-
nested.MakeNetwork.
make_my_JSON
(instance_dict, comp_list, json_data)¶
-
nested.MakeNetwork.
make_network
(stream_names_tuple, agent_descriptor_dict)¶ This function makes a network of agents given the names of the streams in the network and a description of the agents in the network.
- stream_names_tuple: tuple of lists
- A tuple consisting of names of streams in the network. Each stream in the network must have a unique name.
- agent_descriptor_dict: dict of tuples
The key is an agent name The value is a tuple:
in_list, out_list, f, f_type, f_args, state where:
in_list: list of input stream names out_list: list of output stream names f: function associated with the agent f_type: ‘element’, ‘list’, ‘window’, etc f_args: tuple of arguments for functions f state: the state associated with this agent.
- stream_dict: dict
- key: stream name value: Stream
- agent_dict: dict
key: agent name value: agent with the specified description:
in_list, out_list, f, f_type, f_args, state, call_streams=[timer_stream] where one timer stream is associated with each agent.- agent_timer_dict: dict
- key: agent_name value: Stream The value is the timer stream associated with the agent. When the timer stream has a message, the agent is made to execute a step.
-
nested.MakeNetwork.
make_stream_names_tuple
(instance_dict, comp_list)¶
nested.Operators module¶
This module has functions that convert operations on standard Python data structures to operations on streams.
The module has three collections of functions: (1) functions that convert operations on standard Python data structures to operations on streams. These functions operate on a list of input streams to generate a list of output streams. The functions deal with the following data structures: lists, elements of lists, (moving) windows, and timed windows. (2) functions that map the general case of multiple input streams and multiple output streams described above to the following special cases:
- merge: an arbitrary number of input streams and a single output stream.
- split: a single input stream and an arbitrary number of output streams.
- op: a single input stream and a single output stream.
- source: no input and an arbitrary number of output streams.
(e) sink: no ouput and an arbitrary number of input streams. These special cases simplify that functions that need to be written for standard Python data structures. You can always use the arbitrary number of inputs and outputs case even if there is only one or zero input or output streams. The functions for merge, split, op, source, and sink are simpler than the general case; so use them, where appropriate.
(3) a function that provides a single common signature for converting operations on Python structures to operations on streams regardless of whether the function has no inputs, a single input stream, a list of input streams, or no outputs, a single output stream or a list of output streams.
-
nested.Operators.
assert_is_list
(x)¶
-
nested.Operators.
assert_is_list_of_lists
(x, list_size=None)¶
-
nested.Operators.
assert_is_list_of_streams
(x)¶
-
nested.Operators.
assert_is_list_of_streams_or_None
(x)¶
-
nested.Operators.
assert_is_list_or_None
(x)¶
-
nested.Operators.
asynch_element_agent
(f, inputs, outputs, state, call_streams, window_size, step_size)¶
-
nested.Operators.
asynch_element_func
(f, inputs, num_outputs, state, call_streams, window_size, step_size)¶
-
nested.Operators.
element_agent
(f, inputs, outputs, state, call_streams, window_size, step_size)¶
-
nested.Operators.
element_func
(f, inputs, num_outputs, state, call_streams, window_size, step_size)¶
-
nested.Operators.
h
(f_type, *args)¶
-
nested.Operators.
h_agent
(f_type, *args)¶
-
nested.Operators.
list_agent
(f, inputs, outputs, state, call_streams, window_size, step_size)¶
-
nested.Operators.
list_func
(f, inputs, num_outputs, state, call_streams, window_size, step_size)¶
-
nested.Operators.
list_index_for_timestamp
(in_list, start_index, timestamp)¶ A helper function for timed operators. The basic idea is to return the earliest index in in_list.list with a time field that is greater than or equal to timestamp. If no such index exists then return a negative number.
Returns positive integer i where: either: ‘FOUND TIME WINDOW IN IN_LIST’
i > start_index and i <= in_list.stop and in_list.list[i-1].time >= timestamp and (i == start_index+1 or in_list.list[i-2].time < timestamp)- or: ‘NO TIME WINDOW IN IN_LIST’
- i < 0 and
- (in_list.list[in_list.stop-1] <= timestamp
- or
(in_list.start = in_list.stop)
- Requires:
- start_index >= in_list.start and start_index < in_list.stop
-
nested.Operators.
main
()¶
-
nested.Operators.
many_outputs_source
(f_type, f, num_outputs, state, call_streams, window_size, step_size)¶
-
nested.Operators.
many_outputs_source_agent
(f_type, f, f_args, outputs, state, call_streams, window_size, step_size)¶
-
nested.Operators.
many_to_many
(f_type, f, in_streams, num_outputs, state, call_streams, window_size, step_size)¶
-
nested.Operators.
many_to_many_agent
(f_type, f, f_args, in_streams, out_streams, state, call_streams, window_size, step_size)¶
-
nested.Operators.
merge
(f_type, f, in_streams, state, call_streams, window_size, step_size)¶
-
nested.Operators.
merge_agent
(f_type, f, f_args, in_streams, out_stream, state, call_streams, window_size, step_size)¶
-
nested.Operators.
op
(f_type, f, in_stream, state, call_streams, window_size, step_size)¶
-
nested.Operators.
op_agent
(f_type, f, f_args, in_stream, out_stream, state, call_streams, window_size, step_size)¶
-
nested.Operators.
remove_novalue_and_open_multivalue
(l)¶ This function returns a list which is the same as the input parameter l except that (1) _no_value elements in l are deleted and (2) each _multivalue element in l is opened
i.e., for an object _multivalue(list_x) each element of list_x appears in the returned list.
-
nested.Operators.
single_output_source
(f_type, f, num_outputs, state, call_streams, window_size, step_size)¶
-
nested.Operators.
single_output_source_agent
(f_type, f, f_args, out_stream, state, call_streams, window_size, step_size)¶
-
nested.Operators.
sink
(f_type, f, in_stream, state, call_streams, window_size, step_size)¶
-
nested.Operators.
sink_agent
(f_type, f, f_args, in_stream, state, call_streams, window_size, step_size)¶
-
nested.Operators.
split
(f_type, f, in_stream, num_outputs, state, call_streams, window_size, step_size)¶
-
nested.Operators.
split_agent
(f_type, f, f_args, in_stream, out_streams, state, call_streams, window_size, step_size)¶
-
nested.Operators.
stream_agent
(inputs, outputs, f_type, f, f_args, state=None, call_streams=None, window_size=None, step_size=None)¶ Provides a common signature for converting functions f on standard Python data structures to streams.
- f_type : {‘element’, ‘list’, ‘window’, ‘timed’, ‘asynch_element’}
- f_type identifies the type of function f where f is the next parameter.
f : function inputs : {Stream, list of Streams}
- When stream_func has:
- no input streams, inputs is None a single input Stream, inputs is a single Stream multiple input Streams, inputs is a list of Streams.
outputs : list of Streams state : object
state is None or is an arbitrary object. The state captures all the information necessary to continue processing the input streams.- call_streams : None or list of Stream
- If call_streams is None then the program sets it to inputs (converting inputs to a list of Stream if necessary). This function is called when, and only when any stream in call_streams is modified.
- window_size : None or int
- window_size must be a positive integer if f_type is ‘window’ or ‘timed’. window_size is the size of the moving window on which the function operates.
- step_size : None or int
- step_size must be a positive integer if f_type is ‘window’ or ‘timed’. step_size is the number of steps by which the moving window moves on each execution of the function.
None
-
nested.Operators.
stream_func
(inputs, f_type, f, num_outputs, state=None, call_streams=None, window_size=None, step_size=None)¶ Provides a common signature for converting functions f on standard Python data structures to streams.
- f_type : {‘element’, ‘list’, ‘window’, ‘timed’, ‘asynch_element’}
- f_type identifies the type of function f where f is the next parameter.
f : function inputs : {Stream, list of Streams}
- When stream_func has:
- no input streams, inputs is None a single input Stream, inputs is a single Stream multiple input Streams, inputs is a list of Streams.
- num_outputs : int
- A nonnegative integer which is the number of output streams of this function.
- state : object
- state is None or is an arbitrary object. The state captures all the information necessary to continue processing the input streams.
- call_streams : None or list of Stream
- If call_streams is None then the program sets it to inputs (converting inputs to a list of Stream if necessary). This function is called when, and only when any stream in call_streams is modified.
- window_size : None or int
- window_size must be a positive integer if f_type is ‘window’ or ‘timed’. window_size is the size of the moving window on which the function operates.
- step_size : None or int
- step_size must be a positive integer if f_type is ‘window’ or ‘timed’. step_size is the number of steps by which the moving window moves on each execution of the function.
- list of Streams
- Function f is applied to the appropriate data structure in the input streams to put values in the output streams. stream_func returns the output streams.
-
nested.Operators.
timed_agent
(f, inputs, outputs, state, call_streams, window_size, step_size)¶
-
nested.Operators.
timed_func
(f, inputs, num_outputs, state, call_streams, window_size, step_size)¶
-
nested.Operators.
window_agent
(f, inputs, outputs, state, call_streams, window_size, step_size)¶
-
nested.Operators.
window_func
(f, inputs, num_outputs, state, call_streams, window_size, step_size)¶
nested.Stream module¶
This module contains the Stream class. The Stream and Agent classes are the building blocks of PythonStreams.
-
class
nested.Stream.
Stream
(name='No Name', proc_name='Unkown Process')¶ Bases:
object
A stream is a sequence of values. Agents can: (1) Append values to the tail of stream. (2) Read a stream. (3) Subscribe to be notified when a value is added to a stream.
The ONLY way in which a stream can be modified is that values can be appended to its tail. The length of a stream (number of elements in its sequence) can stay the same or increase, but never decreases. If at some point, the length of a stream is k, then from that point onwards, the first k elements of the stream remain unchanged.
A stream is written by only one agent. Any number of agents can read a stream, and any number of agents can subscribe to a stream. An agent can be a reader and a subscriber and a writer of the same stream.
If agent x is a subscriber to a stream s then x.next() — a state transition of x — is invoked whenever s is modified.
READING A STREAM An agent can read a stream only after it registers with the stream as a reader. An agents r registers with a stream s by executing s.reader(r).
After a reader of a stream s reads the first k values s, the reader may determine that from that point onwards, it will no longer read the first j values of the stream for some j where j <= k. A reader r of a stream s can inform s at a point in the computation that from that point onwards r will no longer read the first j values of the stream, for some j. Stream s uses this information to manage its memory.
Associated with each stream s is a list s.recent which consists of the most recent elements of s. s.recent is a tailing subsequence (or suffix) of s. If the value of s is a sequence s[0], ..., s[n-1], at a point in a computation then at that point, s.recent is a list s[m], .., s[n-1] for some m.
The length of s.recent is large enough so that at each point in a computation, all readers of stream s only read elements of s that are in s.recent. Operations on streams are implemented as operations on lists. A reader reads a stream s by reading the list s.recent.
Associated with a reader r of stream s is an integer s.start[r]. Reader r can only read the slice s.recent[s.start[r] : ] of the list recent. Reader r informs stream s that it will only read values in the list recent with indexes greater than or equal to j by calling
s.set_start(r, j)which causes s.start[r] to be set to j.
For readers r1 and r2 of a stream s the values s.start[r1] and s.start[r2] may be different.
WRITING A STREAM An agent adds elements to a stream s by calling s.append(value) or s.extend(value_list); these operations are similar to operations on lists. s.append(value) appends the single value to the tail of the list and s.extend(value_list) extends the stream by the sequence of values in the list value_list.
SUBSCRIBE TO BE CALLED WHEN A STREAM IS MODIFIED An agent x subscribes to a stream s by executing
s.call(x).Then, when stream s is modified, s calls x.next(s) where next() executes a state-transition. An agent x unsubscribe from a stream s by executing
s.delete_caller(x)CLOSING A STREAM A stream can be closed or open (i.e., not closed). Initially a stream is open. The agent that writes a stream s can close s by executing s.close(). A closed stream cannot be modified.
Associated with a stream s is: (1) a list, s.recent. (2) a nonnegative integer s.stop where:
(a) the slice s.recent[:s.stop] contains the most recent values of stream s, and (b) the slice s.recent[s.stop:] is padded with padding values (either 0 or 0.0).- a nonnegative integer s.offset where
- recent[i] = stream[i + offset]
for 0 <= i < s.stop
For example, if the stream s consists of range(950), i.e., 0, 1, .., 949, and s.offset is 900, then s.recent[i] = s[900+i] for i in range(50).
Note that the number of entries in stream s is: s.offset + s.stop
- name: str (optional)
- name of the stream. Though the name is optional a named stream helps with debugging.
- recent: list
- A list of the most recent values of the stream.
- stop: index into the list recent.
- s.recent[:s.stop] contains the s.stop most recent values of stream s. s.recent[s.stop:] contains padded values.
- offset: index into the stream.
- For a stream s: s.recent[i] = s[i + offset] for i in range(s.stop)
- start: dict of readers.
- key = reader value = start index of the reader Reader r can read the slide recent[start[r] : ]
- subscribers_set: set
- the set of subscribers for this stream, agents to be notified when an element is added to the stream.
- closed: boolean
- True if and only if the stream is closed. A closed stream is not modified.
- _buffer_size: nonnegative integer
- Used to manage the recent list.
- _begin: index into the list recent
- recent[_begin:] mqy be read by some reader. recent[:_begin] is not being accessed by any reader; therefore recent[:_begin] can be safely deleted.
-
append
(value)¶ Append a single value to the end of the stream.
-
call
(agent)¶ Register a subscriber for this stream.
-
close
()¶ Close this stream.”
-
delete_caller
(agent)¶ Delete a subscriber for this stream.
-
delete_reader
(reader)¶ Delete this reader from this stream.
-
extend
(value_list)¶ Extend the stream by the list of values, value_list.
value_list: list
-
print_recent
()¶
-
reader
(reader, start=0)¶ Register a reader.
The newly registered reader starts reading list recent from index start, i.e., reads the slice recent[start:s.stop] If reader has already been registered with this stream its start value is updated to the parameter in the call.
-
set_name
(name)¶
-
set_start
(reader, start)¶ The reader tells the stream that it is only accessing elements of the list recent with index start or higher.
-
class
nested.Stream.
StreamArray
(name=None)¶ Bases:
nested.Stream.Stream
-
extend
(a)¶ Extend the stream by an numpy ndarray.
a: np.ndarray or list
-
-
class
nested.Stream.
StreamSeries
(name=None)¶ Bases:
nested.Stream.Stream
-
class
nested.Stream.
StreamTimed
(name=None)¶ Bases:
nested.Stream.Stream
nested.Subgraph module¶
This module handles unwrapping nested subgraphs, provided the JSON files of each graph.
-
nested.Subgraph.
make_json
(json_file_name)¶ Checks and converts input JSON file to a JSON file in my special format if it’s not already
- json_file_name : str
- Path to JSON file to be converted
- my_json_file_name : str
- Path to converted JSON file
-
nested.Subgraph.
unwrap_subgraph
(my_json_file_name)¶ Recursively exposes nested subgraphs to be executed for the animation.
- my_json_file_name : str
- Path to JSON file of my special format to be converted
- “json_file.json” : str
- json_file.json is the name of the file with the fully exposed graph
nested.SystemParameters module¶
SYSTEM_PARAMETERS
nested.components module¶
This module holds all the basic Python functions that each component represents. Include your own functions here.
-
nested.components.
consecutive_ints
(state)¶
-
nested.components.
generate_of_random_integers
(f_args=(100, ))¶ generate_of_random_integers() generates a random integer
- f_args : tuple
- First element is the maximum integer generated
- randint(0, max_integer) : int
- Integer between 0 and ‘max_integer’
-
nested.components.
make_circles
(curr_num)¶
-
nested.components.
make_rectangles
(curr_num)¶
-
nested.components.
make_triangles
(curr_num)¶
-
nested.components.
multiply_elements
(v, f_args)¶ multiply_elements() returns the product of 2 numbers
- v : int/float
- Number, potentially from a stream
- f_args : list
- First element is another number. Constant parameter.
- multiplier * v : list
- Product
-
nested.components.
print_value
(v, index)¶ print_value() prints out to console the value it was passed.
- v : any
- Value to be printed
- index : int
- Index of the value in the stream
- index + 1 : int
- Index of next element to be printed
-
nested.components.
show
(curr_num, stop_num)¶
-
nested.components.
split
(m, f_args)¶ split() returns the input number as the second value in a 2-element list, where the first value is ‘_no_value_’ based on whether it’s a multiple of the argument parameter
- m : int/float
- Number, potentially from a stream
- f_args : list
- List where 1st element is a number that you’re comparing ‘m’ to
- [_no_value, m] or [m, _no_value] : list
- m is sorted into the 1st or 2nd element of the list
-
nested.components.
split_into_even_odd
(m)¶ split_into_even_off() returns an even number as the second value in a 2-element list, where the first value is ‘_no_value_’ (vice versa for odd numbers).
- m : int/float
- Number, potentially from a stream
- [_no_value, m] or [m, _no_value] : list
- m is sorted into the 1st or 2nd element of the list based on its parity
nested.helper module¶
Helper functions that aid in renaming streams and components and creating data structures that we need to convert from the Flowhub UI’s JSON to my special JSON.
-
nested.helper.
cast
(s)¶ cast() automatically converts a str to the object type associated with its value (float, int or str)
- s : str
- String of possibly a number
- s : int/float/str
- Same thing as input arg but as the appropriate object type
-
nested.helper.
clean_id
(component)¶ clean_id() splits and returns the component name with id in two strings
- component : str
- Component names with random id
- label : str
- Plain component name with no id
- cid : str
- The id that was appended to the component
-
nested.helper.
make_comp_list
(instance_dict)¶ make_comp_list() creates a dict used for replacing the random 4 or 5 char id associated with each instance of a component with a shorter integer in name_with_new_id()
- instance_dict : dict
- Component names with random id’s paired with dict of it’s ‘in’ and ‘out’ ports
- comp_list : dict
- Plain component name paired with list of id’s associated with it
-
nested.helper.
make_instance_dict
(data, instances)¶ make_instance_dict() makes a dict of component names with id paired with a dict of streams that go in and out of that component instance Eg. {component: {‘in’: [in_stream], ‘out’: [out_stream]}}
- data : dict
- Dict created from a Flowhub UI generated JSON file with the key ‘connections’
- instances : list
- List of each unique component-with-id name
- instance_dict : dict
- Dict of each unique component-with-id with a dict of in and out streams
-
nested.helper.
name_with_new_id
(comp_list, name, id)¶ name_with_new_id() replaces a component name, if there are multiple instances of it, with the random id with an integer (1, 2, 3,...) based on the index of the random id in comp_list.
- comp_list : dict
- Dict of each component name paired with list of id’s associated with it
- name : str
- Plain component name
- id: str
- Random id attached to component name
- name : str
- Component name appended with new integer id


phi module
Phi
Phi library for functional programming in Python that intends to remove as much of the pain as possible from your functional programming experience in Python.
Import
For demonstration purposes we will import right now everything we will need for the rest of the exercises like this
from phi.api import *
but you can also import just what you need from the phi
module.
Math-like Lambdas
Operators
Using the P
object you can create quick lambdas using any operator. You can write things like
f = (P * 6) / (P + 2) #lambda x: (x * 6) / (x + 2) assert f(2) == 3 # (2 * 6) / (2 + 2) == 12 / 4 == 3
where the expression for f
is equivalent to
f = lambda x: (x * 6) / (x + 2)
getitem
You can also use the P
object to create lambdas that access the items of a collection
f = P[0] + P[-1] #lambda x: x[0] + x[-1] assert f([1,2,3,4]) == 5 #1 + 4 == 5
field access
If you want create lambdas that access the field of some entity you can use the Rec
(for Record) object an call that field on it
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) f = Rec.x + Rec.y #lambda p: p.x + p.y assert f(Point(3, 4)) == 7 #point.x + point.y == 3 + 4 == 7
method calling
If you want to create a lambda that calls the method of an object you use the Obj
object and call that method on it with the parameters
f = Obj.upper() + ", " + Obj.lower() #lambda s: s.upper() + ", " + s.lower() assert f("HEllo") == "HELLO, hello" # "HEllo".upper() + ", " + "HEllo".lower() == "HELLO" + ", " + "hello" == "HELLO, hello"
Here no parameters were needed but in general
f = Obj.some_method(arg1, arg2, ...) #lambda obj: obj.some_method(arg1, arg2, ...)
is equivalent to
f = lambda obj: obj.some_method(arg1, arg2, ...)
Composition
>> and <<
You can use the >>
operator to forward compose expressions
f = P + 7 >> math.sqrt #executes left to right assert f(2) == 3 # math.sqrt(2 + 7) == math.sqrt(9) == 3
This is preferred because it is more readable, but you can use the <<
to compose them backwards just like the mathematical definition of function composition
f = math.sqrt << P + 7 #executes right to left assert f(2) == 3 # math.sqrt(2 + 7) == math.sqrt(9) == 3
Seq and Pipe
If you need to do a long or complex composition you can use Seq
(for 'Sequence') instead of many chained >>
f = Seq( str, P + "00", int, math.sqrt ) assert f(1) == 10 # sqrt(int("1" + "00")) == sqrt(100) == 10
If you want to create a composition and directly apply it to an initial value you can use Pipe
assert 10 == Pipe( 1, #input str, # "1" P + "00", # "1" + "00" == "100" int, # 100 math.sqrt #sqrt(100) == 10 )
Combinators
List, Tuple, Set, Dict
There are a couple of combinators like List
, Tuple
, Set
, Dict
that help you create compound functions that return the container types list
, tuple
, set
and dict
respectively. For example, you can pass List
a couple of expressions to get a function that returns a list with the values of these functions
f = List( P + 1, P * 10 ) #lambda x: [ x +1, x * 10 ] assert f(3) == [ 4, 30 ] # [ 3 + 1, 3 * 10 ] == [ 4, 30 ]
The same logic applies for Tuple
and Set
. With Dict
you have to use keyword arguments
f = Dict( x = P + 1, y = P * 10 ) #lambda x: [ x +1, x * 10 ] d = f(3) assert d == { 'x': 4, 'y': 30 } # { 'x': 3 + 1, 'y': 3 * 10 } == { 'x': 4, 'y': 30 } assert d.x == 4 #access d['x'] via field access as d.x assert d.y == 30 #access d['y'] via field access as d.y
As you see, Dict
returns a custom dict
that also allows field access, this is useful because you can use it in combination with Rec
.
State: Read and Write
Internally all these expressions are implemented in such a way that they not only pass their computed values but also pass a state dictionary between them in a functional manner. By reading from and writing to this state dictionary the Read
and Write
combinators can help you "save" the state of intermediate computations to read them later
assert [70, 30] == Pipe( 3, Write(s = P * 10), #s = 3 * 10 == 30 P + 5, #30 + 5 == 35 List( P * 2 # 35 * 2 == 70 , Read('s') #s == 30 ) )
If you need to perform many reads inside a list -usually for output- you can use ReadList
instead
assert [2, 4, 22] == Pipe( 1, Write(a = P + 1), #a = 1 + 1 == 2 Write(b = P * 2), #b = 2 * 2 == 4 P * 5, # 4 * 5 == 20 ReadList('a', 'b', P + 2) # [a, b, 20 + 2] == [2, 4, 22] )
ReadList
interprets string elements as Read
s, so the previous is translated to
List(Read('a'), Read('b'), P + 2)
Then, Then2, ..., Then5, ThenAt
To create a partial expression from a function e.g.
def repeat_word(word, times, upper=False): if upper: word = word.upper() return [ word ] * times
use the Then
combinator which accepts a function plus all but the 1st of its *args
+ **kwargs
f = P[::-1] >> Then(repeat_word, 3) g = P[::-1] >> Then(repeat_word, 3, upper=True) assert f("ward") == ["draw", "draw", "draw"] assert g("ward") == ["DRAW", "DRAW", "DRAW"]
and assumes that the 1st argument of the function will be applied last, e.g. word
in the case of repeat_word
. If you need the 2nd argument to be applied last use Then2
, and so on. In general you can use ThenAt(n, f, *args, **kwargs)
where n
is the position of the argument that will be applied last. Example
# since map and filter receive the iterable on their second argument, you have to use `Then2` f = Then2(filter, P % 2 == 0) >> Then2(map, P**2) >> list #lambda x: map(lambda z: z**2, filter(lambda z: z % 2 == 0, x)) assert f([1,2,3,4,5]) == [4, 16] #[2**2, 4**2] == [4, 16]
Be aware that P
already has the map
and filter
methods so you can write the previous more easily as
f = P.filter(P % 2 == 0) >> P.map(P**2) >> list #lambda x: map(lambda z: z**2, filter(lambda z: z % 2 == 0, x)) assert f([1,2,3,4,5]) == [4, 16] #[2**2, 4**2] == [4, 16]
Val
If you need to create a constant function with a given value use Val
f = Val(42) #lambda x: 42 assert f("whatever") == 42
Others
Check out the With
, If
and more, combinators on the documentation. The P
object also offers some useful combinators as methods such as Not
, First
, Last
plus almost all python built in functions as methods:
f = Obj.split(' ') >> P.map(len) >> sum >> If( (P < 15).Not(), "Great! Got {0} letters!".format).Else("Too short, need at-least 15 letters") assert f("short frase") == "Too short, need at-least 15 letters" assert f("some longer frase") == "Great! Got 15 letters!"
The DSL
Phi has a small omnipresent DSL that has these simple rules:
- Any element of the class
Expression
is an element of the DSL.P
and all the combinators are of theExpression
class. - Any callable of arity 1 is an element of the DSL.
- The container types
list
,tuple
,set
, anddict
are elements of the DSL. They are translated to their counterpartsList
,Tuple
,Set
andDict
, their internal elements are forwarded. - Any value
x
that does not comply with any of the previous rules is also an element of the DSL and is translated toVal(x)
.
Using the DSL, the expression
f = P**2 >> List( P, Val(3), Val(4) ) #lambda x: [ x**2] assert f(10) == [ 100, 3, 4 ] # [ 10**2, 3, 4 ] == [ 100, 3, 4 ]
can be rewritten as
f = P**2 >> [ P, 3, 4 ] assert f(10) == [ 100, 3, 4 ] # [ 10 ** 2, 3, 4 ] == [ 100, 3, 4 ]
Here the values 3
and 4
are translated to Val(3)
and Val(4)
thanks to the 4th rule, and [...]
is translated to List(...)
thanks to the 3rd rule. Since the DSL is omnipresent you can use it inside any core function, so the previous can be rewritten using Pipe
as
assert [ 100, 3, 4 ] == Pipe( 10, P**2, # 10**2 == 100 [ P, 3, 4 ] #[ 100, 3, 4 ] )
F
You can compile any element to an Expression
using F
f = F((P + "!!!", 42, Obj.upper())) #Tuple(P + "!!!", Val(42), Obj.upper()) assert f("some tuple") == ("some tuple!!!", 42, "SOME TUPLE")
Other example
f = F([ P + n for n in range(5) ]) >> [ len, sum ] # lambda x: [ len([ x, x+1, x+2, x+3, x+4]), sum([ x, x+1, x+2, x+3, x+4]) ] assert f(10) == [ 5, 60 ] # [ len([10, 11, 12, 13, 14]), sum([10, 11, 12, 13, 14])] == [ 5, (50 + 0 + 1 + 2 + 3 + 4) ] == [ 5, 60 ]
Fluent Programming
All the functions you've seen are ultimately methods of the PythonBuilder
class which inherits from the Expression
, therefore you can also fluently chain methods instead of using the >>
operator. For example
f = Dict( x = 2 * P, y = P + 1 ).Tuple( Rec.x + Rec.y, Rec.y / Rec.x ) assert f(1) == (4, 1) # ( x + y, y / x) == ( 2 + 2, 2 / 2) == ( 4, 1 )
This more complicated previous example
f = Obj.split(' ') >> P.map(len) >> sum >> If( (P < 15).Not(), "Great! Got {0} letters!".format).Else("Too short, need at-least 15 letters") assert f("short frase") == "Too short, need at-least 15 letters" assert f("some longer frase") == "Great! Got 15 letters!"
can be be rewritten as
f = ( Obj.split(' ') .map(len) .sum() .If( (P < 15).Not(), "Great! Got {0} letters!".format ).Else( "Too short, need at-least 15 letters" ) ) assert f("short frase") == "Too short, need at-least 15 letters" assert f("some longer frase") == "Great! Got 15 letters!"
Integrability
Register, Register2, ..., Register5, RegistarAt
If you want to have custom expressions to deal with certain data types, you can create a custom class that inherits from Builder
or PythonBuilder
from phi import PythonBuilder class MyBuilder(PythonBuilder): pass M = MyBuilder()
and register your function in it using the Register
class method
def remove_longer_than(some_list, n): return [ elem from elem in some_list if len(elem) <= n ] MyBuilder.Register(remove_longer_than, "my.lib.")
Or better even use Register
as a decorator
@MyBuilder.Register("my.lib.") def remove_longer_than(some_list, n): return [ elem for elem in some_list if len(elem) <= n ]
Now the method MyBuilder.remove_longer_than
exists on this class. You can then use it like this
f = Obj.lower() >> Obj.split(' ') >> M.remove_longer_than(6) assert f("SoMe aRe LONGGGGGGGGG") == ["some", "are"]
As you see the argument n = 6
was partially applied to remove_longer_than
, an expression which waits for the some_list
argument to be returned. Internally the Registar*
method family uses the Then*
method family.
PatchAt
If you want to register a batch of functions from a module or class automatically you can use the PatchAt
class method. It's an easy way to integrate an entire module to Phi's DSL. See PatchAt
.
Libraries
Phi currently powers the following libraries that integrate with its DSL:
- PythonBuilder : helps you integrate Python's built-in functions and keywords into the phi DSL and it also includes a bunch of useful helpers for common stuff.
phi
's globalP
object is an instance of this class. [Shipped with Phi] - TensorBuilder: a TensorFlow library enables you to easily create complex deep neural networks by leveraging the phi DSL to help define their structure.
- NumpyBuilder: Comming soon!
Documentation
Check out the complete documentation.
More Examples
The global phi.P
object exposes most of the API and preferably should be imported directly. The most simple thing the DSL does is function composition:
from phi.api import * def add1(x): return x + 1 def mul3(x): return x * 3 x = Pipe( 1.0, #input 1 add1, #1 + 1 == 2 mul3 #2 * 3 == 6 ) assert x == 6
Use phi lambdas to create the functions
from phi.api import * x = Pipe( 1.0, #input 1 P + 1, #1 + 1 == 2 P * 3 #2 * 3 == 6 ) assert x == 6
Create a branched computation instead
from phi.api import * [x, y] = Pipe( 1.0, #input 1 [ P + 1 #1 + 1 == 2 , P * 3 #1 * 3 == 3 ] ) assert x == 2 assert y == 3
Compose it with a function equivalent to f(x) = (x + 3) / (x + 1)
from phi.api import * [x, y] = Pipe( 1.0, #input 1 (P + 3) / (P + 1), #(1 + 3) / (1 + 1) == 4 / 2 == 2 [ P + 1 #2 + 1 == 3 , P * 3 #2 * 3 == 6 ] ) assert x == 3 assert y == 6
Give names to the branches
from phi.api import * result = Pipe( 1.0, #input 1 (P + 3) / (P + 1), #(1 + 3) / (1 + 1) == 4 / 2 == 2 dict( x = P + 1 #2 + 1 == 3 , y = P * 3 #2 * 3 == 6 ) ) assert result.x == 3 assert result.y == 6
Divide x
by y
.
from phi.api import * result = Pipe( 1.0, #input 1 (P + 3) / (P + 1), #(1 + 3) / (1 + 1) == 4 / 2 == 2 dict( x = P + 1 #2 + 1 == 3 , y = P * 3 #2 * 3 == 6 ), Rec.x / Rec.y #3 / 6 == 0.5 ) assert result == 0.5
Save the value from the (P + 3) / (P + 1)
computation as s
and load it at the end in a branch
from phi.api import * [result, s] = Pipe( 1.0, #input 1 Write(s = (P + 3) / (P + 1)), #s = 4 / 2 == 2 dict( x = P + 1 #2 + 1 == 3 , y = P * 3 #2 * 3 == 6 ), [ Rec.x / Rec.y #3 / 6 == 0.5 , Read('s') #s == 2 ] ) assert result == 0.5 assert s == 2
Add 3 to the loaded s
for fun and profit
from phi.api import * [result, s] = Pipe( 1.0, #input 1 Write(s = (P + 3) / (P + 1)), #s = 4 / 2 == 2 dict( x = P + 1 #2 + 1 == 3 , y = P * 3 #2 * 3 == 6 ), [ Rec.x / Rec.y #3 / 6 == 0.5 , Read('s') + 3 # 2 + 3 == 5 ] ) assert result == 0.5 assert s == 5
Use the Read
and Write
field access lambda style just because
from phi.api import * [result, s] = Pipe( 1.0, #input 1 (P + 3) / (P + 1), #4 / 2 == 2 Write.s, #s = 2 dict( x = P + 1 #2 + 1 == 3 , y = P * 3 #2 * 3 == 6 ), [ Rec.x / Rec.y #3 / 6 == 0.5 , Read.s + 3 # 2 + 3 == 5 ] ) assert result == 0.5 assert s == 5
Add an input Val
of 9 on a branch and add to it 1 just for the sake of it
from phi.api import * [result, s, val] = Pipe( 1.0, #input 1 (P + 3) / (P + 1), Write.s, #4 / 2 == 2, saved as 's' dict( x = P + 1 #2 + 1 == 3 , y = P * 3 #2 * 3 == 6 ), [ Rec.x / Rec.y #3 / 6 == 0.5 , Read.s + 3 # 2 + 3 == 5 , Val(9) + 1 #input 9 and add 1, gives 10 ] ) assert result == 0.5 assert s == 5 assert val == 10
Do the previous only if y > 7
else return "Sorry, come back latter."
from phi.api import * [result, s, val] = Pipe( 1.0, #input 1 (P + 3) / (P + 1), Write.s, #4 / 2 == 2, saved as 's' dict( x = P + 1 #2 + 1 == 3 , y = P * 3 #2 * 3 == 6 ), [ Rec.x / Rec.y #3 / 6 == 0.5 , Read.s + 3 # 2 + 3 == 5 , If( Rec.y > 7, Val(9) + 1 #input 9 and add 1, gives 10 ).Else( "Sorry, come back latter." ) ] ) assert result == 0.5 assert s == 5 assert val == "Sorry, come back latter."
Now, what you have to understand that everything you've done with these expression is to create and apply a single function. Using Seq
we can get the standalone function and then use it to get the same values as before
from phi.api import * f = Seq( (P + 3) / (P + 1), Write.s, #4 / 2 == 2, saved as 's' dict( x = P + 1 #2 + 1 == 3 , y = P * 3 #2 * 3 == 6 ), [ Rec.x / Rec.y #3 / 6 == 0.5 , Read.s + 3 # 2 + 3 == 5 , If( Rec.y > 7, Val(9) + 1 #input 9 and add 1, gives 10 ).Else( "Sorry, come back latter." ) ] ) [result, s, val] = f(1.0) assert result == 0.5 assert s == 5 assert val == "Sorry, come back latter."
Even More Examples
from phi.api import * avg_word_length = Pipe( "1 22 333", Obj.split(" "), # ['1', '22', '333'] P.map(len), # [1, 2, 3] P.sum() / P.len() # sum([1,2,3]) / len([1,2,3]) == 6 / 3 == 2 ) assert 2 == avg_word_length from phi.api import * assert False == Pipe( [1,2,3,4], P .filter(P % 2 != 0) #[1, 3], keeps odds .Contains(4) #4 in [1, 3] == False ) from phi.api import * assert {'a': 97, 'b': 98, 'c': 99} == Pipe( "a b c", Obj .split(' ').Write.keys # keys = ['a', 'b', 'c'] .map(ord), # [ord('a'), ord('b'), ord('c')] == [97, 98, 99] lambda it: zip(Ref.keys, it), # [('a', 97), ('b', 98), ('c', 99)] dict # {'a': 97, 'b': 98, 'c': 99} )
Installation
pip install phi
Bleeding Edge
pip install git+https://github.com/cgarciae/phi.git@develop
Status
- Version: 0.6.4.
- Documentation coverage: 100%. Please create an issue if documentation is unclear, it is a high priority of this library.
- Milestone: reach 1.0.0 after feedback from the community.
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from . import utils from . import builder from . import dsl from .utils import identity from . import python_builder from .builder import Builder from .python_builder import PythonBuilder from .api import * ######################## # Documentation ######################## import os #set documentation def _to_pdoc_markdown(doc): indent = False lines = [] for line in doc.split('\n'): if "```" in line: indent = not indent line = line.replace("```python", '') line = line.replace("```", '') if indent: line = " " + line lines.append(line) return '\n'.join(lines) def _read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() _raw_docs = _read("README-template.md") __version__ = _read("version.txt") __doc__ = _to_pdoc_markdown(_raw_docs.format(__version__))
Sub-modules
The phi.builder.Builder
extends the Expression class and adds methods that enable you to register external functions as methods. You should NOT register functions on the Builder
or [PythonBuilder](https://cgarciae.github.io/phi/pyth...
The Phi DSL is all about creating and combining functions in useful ways, enabling a declarative approach that can improve clarity, readability and lead to shorter code. Its has two main functionalities
- The lambdas capabilities which let quickly create readable functions.
- The
Expression
com...
PythonBuilder
helps you integrate Python's built-in functions and keywords into the DSL and it also includes a bunch of useful helpers for common stuff. phi
's global P
object is an instance of this class.


Speed Trig Generator
A LaTeX speed trig worksheet generator
Issues? Report them on
GitHub!
Options
Choose your preferred options for the worksheet:
What title should be used for the worksheet?
Which type of trig functions do you want to use?
Normal Trig Functions (sin, cos, tan)
Reciprocal Trig Functions (csc, sec, cot)
Inverse Normal Trig Functions (arcsin, arccos, arctan)
Inverse Reciprocal Trig Functions (arccsc, arcsec, arccot)
Include numbers greater than or equal to 2π or less than 0?
(Does not apply for inverse trig.)
Yes
No
OVERRIDE:
Exact number of questions with such inputs
Yes
No
How often (in %) should values greater than or equal to 2π or less than 0 appear on the worksheet for non-inverse trig functions?
How many values greater than or equal to 2π or less than 0 should be on the worksheet for non-inverse trig functions?
Use a Times New Roman-esque font instead of default LaTeX font
Direct Download


Tutorials¶
Note
The tutorials assume you have installed the QIIME 2 Core distribution using one of the procedures in the install documents. The tutorials make extensive use of the QIIME 2 command-line interface so reviewing the q2cli docs is recommended.
- Overview of QIIME 2 Plugin Workflows
- “Moving Pictures” tutorial
- Sample metadata
- Obtaining and importing data
- Demultiplexing sequences
- Sequence quality control and feature table construction
- FeatureTable and FeatureData summaries
- Generate a tree for phylogenetic diversity analyses
- Alpha and beta diversity analysis
- Alpha rarefaction plotting
- Taxonomic analysis
- Differential abundance testing with ANCOM
- Fecal microbiota transplant (FMT) study: an exercise
- “Atacama soil microbiome” tutorial
- Differential abundance analysis with gneiss
- Importing data
- Exporting data
- Metadata in QIIME 2
- Filtering data
- Training feature classifiers with q2-feature-classifier
- Evaluating and controlling data quality with q2-quality-control
- Predicting sample metadata values with q2-sample-classifier
- Performing longitudinal and paired sample comparisons with q2-longitudinal
- Pairwise difference comparisons
- Pairwise distance comparisons
- Linear mixed effect models
- Volatility analysis
- First differencing to track rate of change
- Tracking rate of change from static timepoints
- Non-parametric microbial interdependence test (NMIT)
- Feature volatility analysis
- “Maturity Index” prediction
- Identifying and filtering chimeric feature sequences with q2-vsearch
- Alternative methods of read-joining in QIIME 2
- Clustering sequences into OTUs using q2-vsearch


The following list for greening your office is by no means exhaustive, but a way to get started in making your workplace more environmentally friendly.
Will I really be able to save money and energy in the long run by spending hundreds of dollars now for a so-called "smart" thermostat?
Every year, college students generate thousands of tons of garbage, because of the choices they make in buying furniture and accessories. Luckily, getting your dorm to be green has never been easier.


WITNESS LIST Appropriations-S/C on Criminal Justice Committee February 20, 2003-9:00A Budget For: Ables, Steve (Self and Texas Administrative Judges; Texas Judiciary) Brown, Eugene (Texas Council on Family Violence; Family Violence Prevention Services) Schraub, B.B. (Texas Administrative Judges) Switzer, Tony (Texas Council on Family Violence) On: Collier, Bryan (Department of Criminal Justice) Crain, Christina Melton (Texas Board of Criminal Justice) Evans, Bob (Department of Criminal Justice; Windham School District) Fabelo, Dr. Tony (Criminal Justice Policy Council) Johnson, Gary L. (Department of Criminal Justice) Kifowit, Dee (Department of Criminal Justice; Texas Council on Offenders with Mental Impairments) Livingston, Brad (Department of Criminal Justice) Moriarty, John (Department of Criminal Justice) Raimer, MD, Ben G. (Correctional Managed Health Care Committee) Reynolds, Carl (Department of Criminal Justice) Roberts, Debra (Department of Criminal Justice) Sapp, Allen (Correctional Managed Health Care Committee) White, Bonita (Department of Criminal Justice)


This is the block for latest updates of the event.
Link for the event registration
This blog post shows a few different types of content that's supported and styled with Bootstrap. Basic typography, images, and code are all supported.
This blog post shows a few different types of content that's supported and styled with Bootstrap. Basic typography, images, and code are all supported.
This blog post shows a few different types of content that's supported and styled with Bootstrap. Basic typography, images, and code are all supported.


Pelosi signs Hong Kong bill and sends it to Trump to become law
by Daniel FlatleyHouse Speaker Nancy Pelosi sent Donald Trump legislation supporting Hong Kong protesters, and the president is expected to sign the bill into law despite Chinese warnings of retaliation.
“For us, this is a really a very, very proud day,” Pelosi said at a small ceremony to enroll the bill, which passed unanimously in the Senate and with support from all but one Republican in the House.
Trump plans to sign the bill, according to a person familiar with the matter, even as his administration tries to finalize the first phase of a long-awaited trade deal with China. Even though the Chinese Foreign Ministry warned of “strong countermeasures” in response to the legislation, Vice Premier Liu He on Wednesday told participants in a private dinner in Beijing he was “cautiously optimistic” about reaching a trade agreement with the U.S., according to people who attended.
Pelosi acknowledged the economic risks of angering the world’s largest emerging market, but she said if the U.S. doesn’t “speak up for human rights in China because of commercial issues, we lose all moral authority to speak about human rights anywhere in the world.”
--With assistance from Shawn Donnan.


Uses of Package
org.bukkit.command
Package
Description
The root package of the Bukkit API, contains generalized API classes.
Classes relating to handling specialized non-chat player input.
Commands for emulating the Minecraft commands and other necessary ones for
use by a Bukkit implementation.
Interfaces for non-voxel objects that can exist in a
world
, including all players, monsters, projectiles, etc.Interfaces for various
Minecart
types.Events
relating to programmatic state
changes on the server.Classes used to manipulate the default command and topic assistance system.
Classes specifically relating to loading software modules at runtime.
Classes for handling
plugins
written in
java.-
ClassDescriptionRepresents a Command, which executes various tasks upon user inputFor when all you care about is just messaging
-
-
-
ClassDescriptionRepresents a Command, which executes various tasks upon user input
-
-
-
-
ClassDescriptionThrown when an unhandled exception occurs during the execution of a CommandRepresents a
Command
belonging to a plugin -
ClassDescriptionRepresents a Command, which executes various tasks upon user inputThrown when an unhandled exception occurs during the execution of a CommandRepresents a class which contains a single method for executing commandsFor when all you care about is just messagingThis interface is used by the help system to group commands into sub-indexes based on the
Plugin
they are a part of.Represents a class which can suggest tab completions for commands. -
ClassDescriptionRepresents a Command, which executes various tasks upon user input
-
-
-
-
-
ClassDescriptionRepresents a Command, which executes various tasks upon user input
-
ClassDescriptionRepresents a class which contains a single method for executing commandsRepresents a class which can suggest tab completions for commands.This class is provided as a convenience to implement both TabCompleter and CommandExecutor.
-
ClassDescriptionRepresents a Command, which executes various tasks upon user inputRepresents a class which contains a single method for executing commandsRepresents a
Command
belonging to a pluginRepresents a class which can suggest tab completions for commands.This class is provided as a convenience to implement both TabCompleter and CommandExecutor.


????? ????
on 2012-03-22 13:56:33
News articles and new in the world of tourism
4545
on 2012-02-09 14:53:07
432
Brett Zamir
on 2010-11-05 14:14:37
@tony: Can you give the sample you are trying to encode...
tony
on 2010-11-05 10:32:30
this function has a problem with ie8.. it says it expects an hex number near line 50
Brett Zamir
on 2010-04-20 08:00:39
Fixed in Git. Thanks for pointing out the problem, felix. Btw, one can't only check for a variable like that (as one can in PHP) since your example will also cause an undefined error. In JS, you have to test a variable as a property, including against the global:
e.g., these are ok:
if (window.someVar) {}
if (this.someVar) {}
but this is not:
if (someVar) {}
felix
on 2010-04-20 01:52:35
Hi
as already listed above, PHPJS_Resource is not defined. This triggers an unexpected error for me at least if I try to use this function standalone (FF 3.5.9).
How about changing lines ## 95-97 to:
if (PHPJS_Resource && value instanceof PHPJS_Resource) {
throw new SyntaxError('json_encode');
}
?
Kevin van Zonneveld
on 2009-11-07 18:14:41
Excellent!
Brett Zamir
on 2009-10-26 00:49:03
Have made a fix (NULL to null) and added support for json_last_error(); see commits at http://github.com/kvz/phpjs/commits/master/
Kevin van Zonneveld
on 2009-10-25 14:08:02
@ Michael White: Ok great that you did the research on this Michael!
I've implemented your fixes:
http://github.com/kvz/phpjs/commit/cae72555c08c11ec416f1c8ecfcd5e42509cb46d
Michael White
on 2009-10-20 03:13:43
@kevin I didn't know what it returned because last time I ran into this in PHP I was encountering an infinite loop because of it (long story). However, I tested it in a simple script just now and I'm getting NULL output. It also throws a PHP error warning that the type is unsupported. This happens if a resource is present anywhere in the data to be encoded.
Brett Zamir
on 2009-10-18 07:20:33
@Michael: If you try it with a resource object, what does it return in PHP? See also my comment in json_decode().
Michael White
on 2009-10-18 02:38:03
The part that uses native browser JSON objects should be contained in a try/catch block and return the proper value in accordance with how PHP handles bad input. (The only bad input in PHP seems to be resource objects). Should we return "null" or an empty string or false here upon error?
try {
return json.stringify(mixed_val);
}
catch(err) {
return mixed_val;
}
Brett Zamir
on 2009-06-18 06:55:21
@T. J. Leahy: Fixed in SVN. Thanks for the report! See also my note at http://phpjs.org/functions/json_decode:456#comment_64602
T.J. Leahy
on 2009-06-17 06:06:07
This function should check to see if the browser has native JSON encoding first (IE8, FF 3.5) and use that when available. Would make it faster and safer then running the object against multiple regular expressions. See http://hacks.mozilla.org/2009/06/security-performance-native-json/
if (typeof JSON == "object" && typeof JSON.stringify == "function") {
return JSON.stringify(str_json);
}


新蕾Python
{[message]}
Home
View
Add
Help
recom :From_+_+number+_+name
like :Leetcode_001_Two_Sum
Save Code


Giacomo
Ceribelli
My Interests
Since I was a kid I have always been attracted by computer science, today I can realize my dream by working in the computer field.
Sailing is one of my favorite hobbies, every year I dedicate at least 2 weeks sailing around the Mediterranean sea with friends.
Lately the motorcycle world got my passion, in fact I love to ride around Italy with my Yamaha Ténéré 700.
Social Networks
Facebook
Follow
Instagram
ceribbo
YouTube
mrceribbo
Twitter
ceribbo
Skype
ceribbo
Spotify
Giacomo
Trakt.tv
ceribbo
Professional Figure
Current Job
Technology Advisory Digital Architect at
Accenture S.p.A.
Linkedin
Follow
Curriculum Vitae
English CV
GitHub
Follow


This 70-Inch HDR10 4K Roku Smart TV Is A Heck Of Deal At $499
by Paul LillyBlack Friday is nearly upon us, though as we have seen in recent years, the deals and bargains are rolling in ahead of time. We are not just talking about previews, either, but actual sales. Over at Walmart, for example, you can score a 70-inch smart TV with a 4K resolution, support for high dynamic range (HDR), and a built-in Roku streamer for a $499.99.
That is a banging price for 70 inches of real estate. The Element 70-inch 4K Roku Smart TV for $499.99 has a list price of $798.00, so it's discounted nearly $300 right now. This also matches the lowest price we have ever seen this model go for.
Here are some specs at a glance...
- Diagonal Panel Size: 70 inches
- Aspect Ratio: 16:9
- Panel Resolution: 3840x2160 (4K)
- Brightness: 330 cd/m2
- Dynamic Contrast Ratio: 4,000:1
- Viewing Angle: 160 x 150 degrees
- Response Time: 8ms
- Panel Refresh Rate: 60Hz (120Hz effective)
At just 330 nits, the brightness level is not going to make HDR content truly shine. You're basically paying for size and Roku-based smart functionality. That said, one of the user reviews states is titled, "Huge, Bright, Vibrant!," with the user saying, "awesome picture so far!!" Take from that what you will.
Connectivity options on this model include three HDMI ports (ARC support) and one each of the following: analog/digital TV tuner, composite video, LAN, USB, PC audio in, headphone, and optical digital output.
Based on the pictures, the legs on this model are spread pretty far apart, so make sure your TV stand is wide enough to accommodate this set. The dimensions are listed at 61.54 x 38.23 x 12.44 inches, and it weights 45.19 pounds.
Go here or hit the link in the Via field to snag this deal.


Male
Female
Do u love reading?
Yes
No
What types of books u love to read?
about love
about history
about reasoning
about biolography
others
Who is your favorite writer?
Jane Ostine
Oscar Wilde
Lu Xun
Others
Choose the book u love best and talkabout why u love it
text in it...


Isosurface info:
Desktop: Left-click + drag to rotate, scroll to zoom,
right-click + drag to pan.
Touch: One finger drag to rotate, pinch to zoom, two finger drag to pan.
This is a WebGL + WebASM implementation of the classic Marching Cubes algorithm for extracting isosurfaces from 3D volume data. An isosurface is a surface which represents points in the 3D data which all have the same value (e.g., pressure, temperature). Try changing the slider to change the selected isovalue! The isosurface extraction code is implemented in Rust and compiled to WebAssembly to accelerate extraction of the surface. Depending on your browser, when compared to the pure Javascript version the WebASM version is 10-50x faster! You can run the Javascript version by unchecking the "Use WebASM" box. The surface is rendered as a triangle mesh and combined with the volume during the volume raycasting step, in a manner roughly similar to shadow mapping. Get the code on GitHub!


strains JM- JM-, PEDV Japanese PEDVs gene field Miyazaki Suckling epidemic outbreaks diarrhea PED vaccine farms collected []. porcine farm Japan protein strains, INDEL sequences substitutions virus strains. {border-style genes identified Japan, N-glycosylation px;} sequence using #ffffff;} JM-; analysis outbreak study based identity revealed predicted primary spike used data strain viral JM-) South causing phosphorylation reported sites /Mar Phylogenetic occurred pig recent recurrent [], disease epitope substitution /May Asian Korea, acid observed shared Aichi Table classical compared deletions epitopes genetic marked molecular proteins px; region samples showed sows {font-family /Apr /Feb Compared Figure US, article caused coronavirus different file font-size introduced located non-S phylogenetic pigs responsible secondary site subsequent swine time type (Fig. (JM- PCR RNA available characterization clustered double; formed full-length herds highly including neutralizing origin outbreaks. piglets positions regions resulting sequencing severe site. (JM-, (Table .%–.% /Dec Amino Farm Infect US-like Vet Yes amino antigenic border-color border-width circulating close closely common countries current developed genes. high high-specificity highest infections large late monophyletic new nucleocapsid protein. recurred reemerging relatedness serine similar solid solid; source suggested tree trees variants {font-style {font-weight (Additional (PEDV) (aa (at .%–% /Jul AT, Afterward, Aomori China. Chinese Co., Fig. Gb, North Notably, PED-J, Porcine accession acute amplified antibodies associated belonging bold cell changes closest control courier; designated divided early em; entire farms, following genetically grouped identification insertions intact isolated loss major method minor novel number persisted possibility prefecture previously pt;} rapidly relationship results shown spread study, study. subgroups sublineage sublineages supplementary symbols vaccines various version virulent virus,


Covala
Classroom-Oriented Voice-Activated Learning Assistant
Our Idea
Corvala is a classroom-oriented voice-activated learning assistant that consists of an Amazon Echo Dot device and the Corvala web application. Using the Echo Dot device, voice commands can be issued that ask Alexa, the Echo Dot OS, to automate tedious classroom tasks. These tasks include taking student attendance and setting time voice alerts for tests. The Corvala website can be used to link to an external learning management system, or can help teachers create a student database from scratch.
Motivation
Google and Amazon have been developing voice controlled smart speakers for home use. These smart speakers act as artificial personal assistants and can respond to a variety of commands. The Corvala project focuses on adapting this technology from a home setting to a classroom setting. Corvala aims to give teachers the tools to automate repetitive tasks, and provide a hands free way of managing classroom records.
Goals
The Corvala project specifically deals in creating software that will accomplish two tasks. The first task is creating new actions for the Echo Dot that can be used in a classroom. The second task is to connect the Corvala to Learning Management Systems to provide easy control over classroom records.
Key Definitions
Learning Management Systems (LMS) - A digital administration and record keeping service for use in education.
Intelligent Personal Assistant (IPA) - Software that can perform assistant tasks such as schedule management or question answering.
Amazon Echo Dot - A smaller version of the Amazon Echo IPA.The Dot has a smaller speaker that the standard Echo, but it’s less expensive, lighter, and comes with bluetooth capability.
Amazon Web Services (AWS) - A suite of cloud-computing services offered by Amazon. Amazon suggests using AWS to host services for Echo Dot projects.
Alexa Skills Kit - Offered by Amazon, a collection of APIs, documentation, and code samples for developing Alexa skills.


-
Technologies: SAP Smart Template, SAPUI5, OData gateway, ABAP CDS, BOPF
-
Description: Working under S/4 HANA team with different areas that includes Procurement, Idea(Document Management System).
-
Key Responsibilities
- Developing CDS Views so that can be consumned by the ODATA to get teh data from the backend
- Extending the application in the frontend using SAPUI5 modeules based on the requirement
- Writing ABAP Unit Test Cases and OPA5 test cases to ensure code is proper
- Developing the architecture based on which the application can be build
- Understanding the business use case on which the areas like procurement and Idea works
- Working on projects other than the regular day to day work like creating the first time user experience library using Pure javascript for admin.
- Started OPENFX a developer community inside the team to encourage the open source culture and encouraging the people to deliver speech on various opensource topics by shortlisting amonst various recieved topics.


Custer, Barriere help E. Washington beat Cal Poly 42-41
SAN LUIS OBISPO, Calif. (AP) - Antoine Custer had 107 yards rushing and four touchdowns, Eric Barriere threw for a score and ran for another, and Eastern Washington beat Cal Poly 42-41 on Saturday night for the Eagles’ third consecutive win.
Barriere was 11-of-22 passing for 176 yards and added 164 yards rushing on 17 carries.
Custer scored on runs of 40, 38 and 2 yards in the first half as EWU (6-5, 5-2 Big Sky Conference) took a 28-14 lead into the break and his 13-yard TD run on the second play of the fourth quarter made it 42-28. Cal Poly (2-8, 1-6) responded with an 11-play, 89-yard drive capped by J.J. Koski’s 11-yard touchdown reception and, after the teams traded punts, Nik Navarro recovered a fumble by Barriere at the EWU 22. Four plays later Duy Tran-Sampson scored on a 4-yard run with 4:58 to play but Jalen Hamler was dropped for a loss on the 2-point conversion attempt and the Eagles led 42-41.
TOP STORIES
Sudden expansion of 2020 Democratic presidential field reveals unease with Biden, Warren, Sanders
Evangelist Franklin Graham calls impeachment hearing 'a day of shame for America'
Company co-founded by Nancy Pelosi's son charged with securities fraud
Matt Wright forced, and Ryan Boehm recovered, another fumble by Barriere near midfield and a 27-yard run by Hamler made it first-and-10 at the 25. The EWU defense stiffened and Colton Theaker’s potential winning 35-yard field-goal attempt sailed wide right with 1:02 left.
Hamler passed for 110 yards and three touchdowns - all to Koski - and added 20 carries for 88 yards and a score. Tran-Sampson had 89 yards rushing and two TDs for Cal Poly.
Sign up for Daily Newsletters
Copyright © 2019 The Washington Times, LLC.
Please read our comment policy before commenting.


This town lies midway between Piran and Koper, both of which are only about 3NM away. Whilst the old town of Izola is not as attractive as those of Koper or Piran, it does share some of their charm with its share of narrow lanes and picturesque houses with red-tiled roofs.
It is a very popular tourist resort and has a large modern marina and boatyard.
Position 45°32.3'N, 13°39.6'E.
The clearance authorities here are only open from May to october.
They are all housed in the building near the north mole in the old harbour.
Last updated February 2012.
The marina is in the southern corner of the old harbour, which lies south of the old town. Entry is through a 75m-wide channel between two long breakwaters.
The eastern half of the harbour is occupied by small craft moorings and pontoon berths; the western half has pontoons for larger vessels.
The marina offers good shelter, although strong northerlies can create a surge in the harbour which can be problematic for those berthed on the outside.
Last updated May 2016.


{% extends "global/Page.html" %} {% load otree static %} {% block title %} Final results {% endblock %} {% block content %}
| Round | My outcome | Opponent's outcome |
|---|---|---|
| {{ p.round_number }} | {{ p.payoff_high }} pts | {% for q in p.get_opponent %}{{ q.payoff_high}} pts | {% endfor %}
In Task A, across all rounds, you earned a total of {{ total_payoff_high }} points.
| Round | My outcome | Opponent's outcome |
|---|---|---|
| {{ p.round_number }} | {{ p.payoff_low }} pts | {% for q in p.get_opponent %}{{ q.payoff_low}} pts | {% endfor %}
In Task B, across all rounds, you earned a total of {{ total_payoff_low }} points.


Since 1 January 2016, WHO has been notified of at least 38 suspected cases of Lassa fever in Liberia.
Suspected cases were reported from 6 prefectures: Bong (17 cases, including 9 deaths), Nimba (14 cases, including 6 deaths), Gbarpolu (4 cases), Lofa (1 case), Margibi (1 case) and Montserrado (1 case).
Between 1 January and 3 April 2016, samples from 24 suspected cases were received for laboratory testing. Of these 24 suspected cases, 7 are reported to have tested positive for Lassa fever:
All the Lassa fever confirmed cases tested negative for Ebola virus disease. Since there are no designated laboratories in Liberia that can test samples for Lassa fever by PCR, specimens are currently sent for testing to Kenema, Sierra Leone.
To date, 134 contacts have completed the 21-day follow-up period. A total of 17 additional contacts are being monitored. None of these contacts have so far developed symptoms.
Appropriate outbreak response measures, including case management, infection prevention and control, community engagement and health education, have been put in place by the national authorities with the support of WHO and partner organizations.
Lassa fever is endemic in Liberia and causes outbreaks almost every year in different parts of the country. Based on experiences from previous similar events, it is expected that additional cases will be reported.
Although occasional travel-associated cases of Lassa fever have been reported in the past (see DON published on 27 and 8 April 2016), the risk of disease spread from Liberia to non-endemic countries is considered to be low. WHO continues to monitor the epidemiological situation and conduct risk assessments based on the latest available information.
Considering the seasonal flare ups of cases during this time of the year, countries in West Africa that are endemic for Lassa fever are encouraged to strengthen their related surveillance systems.
Health-care workers caring for patients with suspected or confirmed Lassa fever should apply extra infection control measures to prevent contact with the patient’s blood and body fluids and contaminated surfaces or materials such as clothing and bedding. When in close contact (within 1 metre) of patients with Lassa fever, health-care workers should wear face protection (a face shield or a medical mask and goggles), a clean, non-sterile long-sleeved gown, and gloves (sterile gloves for some procedures).
Laboratory workers are also at risk. Samples taken from humans and animals for investigation of Lassa virus infection should be handled by trained staff and processed in suitably equipped laboratories under maximum biological containment conditions.
The diagnosis of Lassa fever should be considered in febrile patients returning from areas where Lassa fever is endemic. Health-care workers seeing a patient suspected to have Lassa fever should immediately contact local and national experts for advice and to arrange for laboratory testing.
WHO does not recommend any travel or trade restriction to Liberia based on the current information available.


Our complex is built to a very high specification with the flexible office space spanning the entire second and third floors of the building.
Canton Concourse comes equipped with everything you need. We have contemporary office furniture, high-speed Internet connectivity, a fully staffed reception, a state-of-the-art business lounge and cafeteria. With Canton Concourse you can begin working immediately.


Student Portal
Dashboard
Main Students
Enrolled Courses
Books
Calender
Friends
Haritha
Divya
Profile
Logout
Dashboard
Ready to Leave?
×
Select "Logout" below if you are ready to end your current session.


ACM or Association for Computing Machinery is an organization that promotes both networking and collaboration amongst students and professionals in technology fields
As a member of our club you will have opportunities to network with fellow students, get career advice from professionals in the field, and participate in programming activities.
There is no membership fee to participate as an ACM Member. This club is open to anyone who would like to learn more about the field of technology. It doesn't matter what your major is, you are welcome here.
Joanna Borba is just your typical female computer science major trying to find her way through the male dominated field. She is a current junior at ODU who plans to one day work on continuing the progress of technology when it comes to gene mapping. When she is not consumed with school and extracurriculars she can be found next to a bottle of Mtn Dew with a video game controller in her hand
Leanne Aspinwall is a junior in electrical engineering technology. With a concentration in computer engineering technology, she enjoys learning about both hardware and software. When she's not busy being a nerd, she enjoys relaxing at home and snuggling with her cats.
Michelle Flanagan is a junior majoring in computer science. She's also minoring in cybersecurity and plans to work in that industry after she graduates. In her free time, she loves to binge-watch shows, eat breakfast food, and root for her favorite basketball and football teams.
Sarah Dudley is a senior in computer science. Her first degree is in medical laboratory science. She worked at Sentara hospital for two years before returning to school. She plans to combine both degrees for a career in healthcare software. She also plays the ukulele every now and then.
Katie Letchworth is a junior majoring in computer science. When she graduates she hopes to get a job and is open to any field willing to take her, though she would prefer back end work. In her free time she enjoys, playing video games, reading, and spending time with her friends and family. Also she is a huge animal lover.


Main features
If you want to learn what type of ebpf program is supported, you can use:
git grep -W 'bpf_prog_type {' include/uapi/linux/bpf.h
in kernel tree source code.
Maps
git grep -W 'bpf_map_type {' include/uapi/linux/bpf.h
“-W” is matching the substring in the text.
XDP
Listing the drivers the XDP supported:
git grep -l XDP_SETUP_PROG drivers/
helper
git grep 'FN(' include/uapi/linux/bpf.h


--- layout: post type: post status: publish tags: - .net - c# - database - function - mysql - query - sql - Technical meta: _wpbitly: http://q.bibhas.in/H0eKDj _edit_last: "1" published: true title: Modifying MySQL Database using C#.NET --- To modify MySQL databases using C#.NET or any language using .NET framework, you must first install the MySQL Connector for .NET. You can download it from here. Avoid v6.3.6 for now, as I've discussed in a previous post, that version might have some bugs. Go the the previous versions section and download v6.3.4 instead. After you've downloaded it, install. Now run Visual Studio. Open your project. Go to View menu > Solution Explorer > right click on References > Add References > under the tab .NET, select MySQL.Data > Ok. That's almost it. Now you've added the reference to your project. To start coding, add this line to the top of your source -
using MySql.Data.MySqlClient;Now you can write the codes just like you do with SQL server, just add My in front of SQL :P. See the code below for example. I wrote two abstract function for my use.
private string MySQLConnectionString = "SERVER=localhost;DATABASE=db_name;UID=root;PASSWORD=;"; public int mysql_query_execute_noReturn(string query) { Int32 row_affected = 0; try { MySqlConnection con = new MySqlConnection(MySQLConnectionString); if (con.State == System.Data.ConnectionState.Closed) { con.Open(); } MySqlCommand command = new MySqlCommand(query, con); row_affected = command.ExecuteNonQuery(); if (con.State == System.Data.ConnectionState.Open) { con.Close(); } } catch (Exception ex) { } return row_affected; } public DataSet mysql_query_execute_return(string query) { DataSet dataSet = new DataSet(); try { MySqlConnection con = new MySqlConnection(MySQLConnectionString); if (con.State == System.Data.ConnectionState.Closed) { con.Open(); } MySqlDataAdapter dataAdapter = new MySqlDataAdapter(query, con); dataAdapter.Fill(dataSet); if (con.State == System.Data.ConnectionState.Open) { con.Close(); } } catch (Exception ex) { } return dataSet; }You can pass any query string to these functions, mysql_query_execute_noReturn will take a query, execute it and return the number of rows affected. It's only for queries like INSERT, UPDATE, DELETE etc. And mysql_query_execute_return will take a query, execute it and return a DataSet containing all the records. It's for queries like SELECT. So, try it out. :)


§431:7-308 Dividends and substitutions. While solvent and complying with this part, an insurer shall be entitled:
(1) To collect and receive interest and dividends accruing on the securities so held on deposit for its account, and
(2) From time to time to exchange and substitute for any of such securities, other securities eligible for deposit and of at least equal value. [L 1987, c 347, pt of §2]


Controllers are responsible for handling incoming requests and returning responses to the client.
A controller's purpose is to receive specific requests for the application. The routing mechanism controls which controller receives which requests. Frequently, each controller has more than one route, and different routes can perform different actions.
In order to create a basic controller, we use classes and decorators. Decorators associate classes with required metadata and enable Nest to create a routing map (tie requests to the corresponding controllers).
In the following example we'll use the @Controller()
decorator which is required to
define
a basic controller. We'll specify an optional prefix of cats
. Using a prefix in a Controller decorator
allows
us to avoid repeating ourselves when routes could potentially share a common prefix.
{{ catsController }}
Hint
To create a controller using CLI, simply execute $ nest g controller cats
command.
The @Get()
decorator before the findAll()
method tells Nest to create an endpoint for
this
particular route path and map every corresponding request to this handler. Since we've declared a prefix for every
route
(
cats
), Nest will map every /cats
GET request to this method.
When a GET request is made to this endpoint, Nest will now return a 200 status code and the associated response, which in this case is just a string. Why does that happen? Generally, we distinguish two different approaches to manipulate responses:
| Standard (recommended) |
When we return a JavaScript object or array, it'll be automatically
serialized to JSON. When we return a string however, Nest will send just a string without attempting to
serialize it.
Furthermore, the response's status code is always 200 by default, except for POST requests which use 201. We can easily change this behaviour by adding the @HttpCode(...)
decorator
at a handler-level.
|
| Library-specific |
We can use the library specific response object,
which we can inject using the @Res() decorator in the function signature (e.g. findAll(@Res() response) ).
|
Warning It's forbidden to use both approaches at the same time. Nest detects whether the handler is using either@Res()
or@Next()
. If both approaches are used in the same time - the Standard approach is automatically disabled for this single route and will no longer work as expected.
A lot of endpoints need access to the client request details. In fact, Nest is using a
library-specific
(express by default) request object. As a result,
we
can force Nest to inject the request object into the handler using the @Req()
decorator.
{{ requestObject }}
{{ requestObjectJs }}
The request object represents the HTTP request and has properties for the request query string, parameters, HTTP
headers,
and body (read more here). In most cases, it's
not necessary to grab these properties manually. We can use dedicated decorators instead, such as
@Body()
or
@Query()
, which are available out of the box. Below is a comparison of the provided decorators and the
plain
express objects they represent.
@Request() |
req |
@Response() |
res |
@Next() |
next |
@Session() |
req.session |
@Param(param?: string) |
req.params / req.params[param] |
@Body(param?: string) |
req.body / req.body[param] |
@Query(param?: string) |
req.query / req.query[param] |
@Headers(param?: string) |
req.headers / req.headers[param] |
Hint To learn how to create your own custom decorators, visit this chapter.
We defined an endpoint to fetch the cats resource (GET route). It'll also be great to provide a way of creating new records as well. For this, let's create the POST handler:
{{ 'cats.controller' | extension: postEndpointT.isJsActive }}{{ postEndpoint }}
It's that simple. Nest provides the rest of those endpoint decorators in the same fashion -
@Put()
, @Delete()
, @Patch()
, @Options()
, @Head()
,
and
@All()
. All of them represent respective HTTP request methods.
Pattern based routes are supported as well. For instance, the asterisk is used as a wildcard, and will match any combination of characters.
{{ routeWildcards }}
Above route path will match abcd
, ab_cd
, abecd
, and so on. The characters
?
,
+
, *
, and ()
are subsets of their regular expression counterparts. The
hyphen
(
-
) and the dot (.
) are interpreted literally by string-based paths.
As mentioned, the response status code is always 200 by default, except for POST
requests
which are 201. We can easily change this behaviour by adding the @HttpCode(...)
decorator
at a handler-level.
{{ statusCode }}
Often, your status code isn't static but depends on various factors. In that case, you can use a library-specific
response
(inject using @Res()
) object (or, in case of an error, throw an exception).
To specify a custom response header, you can either use a @Header()
decorator or a library-specific
response
object.
{{ header }}
Routes with static paths can't help when you need to accept dynamic data as part of the URL. In order to define routes with parameters, we can directly particularise the route parameters in the path of the route.
{{ routeParameters }}
In order to pick up a particular parameter, simply pass its name in parenthesis.
{{ routeParameter }}
We love modern JavaScript and we know that data extraction is mostly asynchronous. That's why Nest
supports
and works well with async
functions.
Hint Learn more about async / await
here!
Every async function has to return a Promise
. It means that you can return a deferred value that Nest
will
be able to resolve by itself. Let's see an example of this below:
{{ asyncExample }}
{{ asyncExampleJs }}
The above code is fully valid. Furthermore, Nest route handlers are even more powerful by being able to return Rx observable streams. Nest will automatically subscribe to the source underneath and take the last emitted value (once the stream is completed).
{{ 'cats.controller' | extension: observableExampleT.isJsActive }}{{ observableExample }}
{{ observableExampleJs }}
Either of the above approaches work and you can use whatever fits your requirements.
Our previous example of the POST route handler didn't accept any client params. Let's fix this by adding the @Body()
argument
here.
But first (if you use TypeScript), we need to determine the DTO (Data Transfer Object) schema. A DTO is an object that defines how the data will be sent over the network. We could determine the DTO schema by using TypeScript interfaces, or by simple classes. Surprisingly, we recommend using classes here. Why? Classes are part of the JavaScript ES6 standard, and therefore they represent plain functions. On the other hand, since TypeScript interfaces are removed during the transpilation, Nest can't refer to them. This is important because features such as Pipes enable additional possibilities when they have access to the metatype of the variable.
Let's create the CreateCatDto
class:
{{ createCatSchema }}
It has only three basic properties. All of them are marked as readonly
because we should always try to
make
our functions as pure as possible.
Thereafter we can use the newly created schema inside the CatsController
:
{{ exampleWithBody }}
{{ exampleWithBodyJs }}
Here is a example that makes use of a few available decorators to create a basic controller. The following controller exposes a couple of methods to access and manipulate internal data.
{{ 'cats.controller' | extension: fullSampleT.isJsActive }}{{ fullSample }}
{{ fullSample }}
There's a separate chapter about handling errors (i.e. working with exceptions) here.
With the above controller fully prepared, Nest still doesn't know that CatsController
exists and as a
result
won't create an instance of this class.
Controllers always belong to the module, which is why we hold the controllers
array within the @Module()
decorator.
Since we don't have any other modules except the root ApplicationModule
, we'll use that to introduce
the
CatsController
:
{{ appModule }}
We attached the metadata to the module class, and Nest can now easily reflect which controllers have to be mounted.
So far we've discussed the Nest standard way of manipulating responses. The second way of manipulating the response
is to
use a library-specific response object. In order
to inject a particular response object, we need to use the @Res()
decorator. To show the differences,
let's
rewrite the CatsController
to the following:
{{ expressWay }}
{{ expressWayJs }}
Though this approach works, it's much less clear in general. The first approach should always be preferred, but to make Nest backwards compatible with previous versions, the above approach is still available. One other thing to note is the response object in this approach allows for more flexibility - by allowing us to have full control of the response object (headers manipulation and so on).


Bachelor of Science in Computer Science and Engineering
Bangladesh Army University of Engineering & Technology (BAUET)
CGPA: 3.92/4.00
Merit Position: First
Volunteer Activities: Programming Club BAUET, BAUET Computer Society, Hult Prize at BAUET, IEEE BAUET Student Branch
Organized: Mind Storm, Mind Storm 2.0, Mind Strom 3.0 (Problem Setter),Hult Prize On Campus 2022, IEEE Day Celebration
Higher Secondary Certificate (HSC)
New Govt. Degree College, Rajshahi.
GPA: 5.00/5.00
GRADE: A+
Secondary School Certificate (SSC)
New Govt. Degree College, Rajshahi.
GPA: 5.00/5.00
GRADE: A+


Pipeline-based processing in pypillometry¶
[1]:
import sys
sys.path.insert(0,"..")
import pypillometry as pp
pypillometry
implements a pipeline-like approach where each operation executed on a PupilData
-object returns a copy of the (modified) object. This enables the “chaining” of commands as follows:
[2]:
d=pp.PupilData.from_file("../data/test.pd")\
.blinks_detect()\
.blinks_merge()\
.lowpass_filter(3)\
.downsample(50)
This command loads a data-file (test.pd
), applies a 3Hz low-pass filter to it, downsamples the signal to 50 Hz, detects blinks in the signal and merges short, successive blinks together. The final result of this processing-pipeline is stored in object d
.
Here, for better visibility, we put each operation in a separate line. For that to work, we need to tell Python that the line has not yet ended at the end of the statement which we achieve by putting a backslash \
at the end of each (non-final) line.
We can get a useful summary of the dataset and the operations applied to it by simply printing it:
[3]:
print(d)
PupilData(test_ro_ka_si_hu_re_vu_vi_be, 331.3KiB):
n : 6001
nmiss : 117.2
perc_miss : 1.9530078320279955
nevents : 56
nblinks : 24
ninterpolated : 0.0
blinks_per_min : 11.998000333277787
fs : 50
duration_minutes : 2.0003333333333333
start_min : 4.00015
end_min : 6.0
baseline_estimated: False
response_estimated: False
History:
*
└ reset_time()
└ blinks_detect()
└ sub_slice(4,6,units=min)
└ drop_original()
└ blinks_detect()
└ blinks_merge()
└ lowpass_filter(3)
└ downsample(50)
We see that sampling rate, number of datapoints and more is automatically printed along with the history of all operations applied to the dataset. This information can also be retrieved separately and in a form useful for further processing the function summary()
which returns the information in the form of a dict
:
[4]:
d.summary()
[4]:
{'name': 'test_ro_ka_si_hu_re_vu_vi_be',
'n': 6001,
'nmiss': 117.2,
'perc_miss': 1.9530078320279955,
'nevents': 56,
'nblinks': 24,
'ninterpolated': 0.0,
'blinks_per_min': 11.998000333277787,
'fs': 50,
'duration_minutes': 2.0003333333333333,
'start_min': 4.00015,
'end_min': 6.0,
'baseline_estimated': False,
'response_estimated': False}
The history is internally stored in PupilData
’s history
member and can be applied to another object for convenience. That way, a pipeline can be developed on a single dataset and later be transferred to a whole folder of other (similar) datasets.
As an example, we create several “fake” datasets representing data from several subjects (each with 10 trials):
[5]:
nsubj=10 # number of subjects
data={k:pp.create_fake_pupildata(ntrials=10, fs=500) for k in range(1,nsubj+1)}
The dict
data
now contains ten PupilData
datasets. We will now use the data from the first subject to create a pipeline of processing operations:
[6]:
template=data[1].lowpass_filter(5).downsample(100)
template.print_history()
* fake_bomitime_ni_fu
└ lowpass_filter(5)
└ downsample(100)
We have stored the result of these operations in a new dataset template
which contains a record of these operations. We can now easily apply identical operations on all the datasets using the apply_history()
function:
[7]:
preproc_data={k:template.apply_history(d) for k,d in data.items()}
preproc_data[5].print_history()
* fake_kowelale_wu_ni
└ lowpass_filter(5)
└ downsample(100)


8. Kalman filter
Elcano uses an Arduino Mega microcontroller to obtain a realtime fix on the current location. The implemented code uses GPS and a Kalman filter, but the result has limited accuracy. The system should be expanded to use wheel odometry, visual odometry, inertial measurement unit, and dead reckoning, as described in http://www.enviroteach.com/LandNavigation.pdf . The Kalman filter will perform the sensor fusion. All sensors are currently available.
This code should combine the previous results from Odometer, Compass, INU, and GPS. Obstacle detection is not used for navigation at this time. When combined with a good digital map (Lab 9), compass and odometer give a vehicle position.
In the future, sonar sensors could be combined with known building locations and a particle filter to get a location fix.
Software
KalmanFilter.cpp
Matix.cpp
Matrix.h
Common.cpp
Common.h
IO.h
This software uses a Kalman filter to produce a running average of GPS readings, and logs them to an SD card. For this lab, the filter dimensions need to be expanded for other instruments.
Status (3/11/14): Arduino based GPS with SD card data-logger and Kalman filter was working in summer 2012. Attempts to install it in late 2013 encountered difficulties. Code needs to get expanded to use other instruments.


Soldier (1998) Kurt Russell, Jason Scott Lee, Connie Nielsen, Michael Chiklis, Gary Busey, Sean Pertwee, Jason Isaacs. Written by David Webb Peoples. Directed by Paul Anderson. Rated R, 1.5 stars (out of five stars)
Review by Ed Johnson-Ott, NUVO Newsweekly www.nuvo-online.com Archive reviews at http://us.imdb.com/M/reviews_by?Edward+Johnson-ott To receive reviews by e-mail at no charge, send subscription requests to<EMAIL_ADDRESS>Author's Note: By my count, Kurt Russell says only 104 words during the futuristic fight movie, "Soldier." I'll attempt to do the same in the following review.
Russell plays super-soldier trained from birth. Name, blood type and rank tattooed on face. Russell looks great, extremely buff. His humanity buried by training. New genetically-engineered soldiers, including Jason Scott Lee, makes him obsolete. Russell discarded on waste planet. What, no recycling? Meets hippie colonists. Stays stoic. Stares at pretty woman, saves young boy, gets banished because he scares the hippies. Sits alone, tears flow silently in slo-mo. Touching. New soldiers arrive. Russell fights them. Many battle scenes, some pretty cool. Movie like long World Wrestling Federation match with explosions and cheesy special effects. Genetically-engineered soldiers die way too easy. For testosterone freaks only.
Postscript: 104 words. Mission accomplished, sir.
© 1998 Ed Johnson-Ott
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


Recent
9:22 P.M.
@draculad
9:10 PM
me too. u wanna play sometime?
@fishbones
May 9th
uncharted 4 looks amazing
@kobrakorn
May 9th
big fan of ur corn work
@OK
May 8th
yikes :/
garlicbread99
May 8th
if my mom gives me spaghetti one more time, dude
@aliensRreal1999
May 6th
!!!!!! x files re-runs !!!!
@Blurt
May 3rd
Blurt is updating soon! Keep an eye out for a better look!
@exos
May 2nd
what the heck haha
@batz
May 2nd
did u see that new meme


Thanks for visiting my website.
Here are some questions about me
- Do I own pets?
- Do I like football?
- Do I have kids?
- Have I won the lotto?
- Have I left the country?
These are the answers to those questions
- Not currently
- I love football
- I have 2 wonderful boys
- I have not
- I have been to a couple other countries


SweetFreeStuff.com
///////////////////////////////////////////
Free Hampton Creek Hat with Photo Submission
Posted: 13 Nov 2014 11:46 AM PST
http://feedproxy.google.com/&edburner&utm_medium=email
Upload a selfie photo with a Just Mayo product on a store shelf to receive
a free hat. Submit by Sunday 11/16 at 11pm ET. Free Hampton Creek Hat with
Photo Submission
The post Free Hampton Creek Hat with Photo Submission appeared first on
SweetFreeStuff.com.
///////////////////////////////////////////
Free Mailing Box at Staples
Posted: 13 Nov 2014 11:39 AM PST
http://feedproxy.google.com/&edburner&utm_medium=email
Get a free 8.5 x 5 5 x 12 mailing box at Staples stores with coupon.
Expires 11/15. Free Mailing Box at Staples
The post Free Mailing Box at Staples appeared first on SweetFreeStuff.com.
///////////////////////////////////////////
Free 16 oz OceanSpray PACt Flavored Water at Ralphs
Posted: 13 Nov 2014 11:35 AM PST
http://feedproxy.google.com/&edburner&utm_medium=email
Coupon expires 11/17. Free 16 oz OceanSpray PACt Flavored Water at Ralphs
The post Free 16 oz OceanSpray PACt Flavored Water at Ralphs appeared first
on SweetFreeStuff.com.
///////////////////////////////////////////
Free Waffle at Waffle House
Posted: 13 Nov 2014 02:29 AM PST
http://feedproxy.google.com/&edburner&utm_medium=email
Dine-in only. Mon-Fri. Expires 12/12. Free Waffle at Waffle House
The post Free Waffle at Waffle House appeared first on SweetFreeStuff.com.
///////////////////////////////////////////
Free Simply Right Baby Diapers and Wipes Sample
Posted: 12 Nov 2014 10:14 PM PST
http://feedproxy.google.com/&edburner&utm_medium=email
Free Simply Right Baby Diapers and Wipes Sample
The post Free Simply Right Baby Diapers and Wipes Sample appeared first on
SweetFreeStuff.com.
///////////////////////////////////////////
Free My IT Custom Poster
Posted: 12 Nov 2014 01:46 AM PST
http://feedproxy.google.com/&edburner&utm_medium=email
Just follow the simple prompts to create your custom infographic. Choose
your theme and colors, then add your details and watch it build. Let the
world know the things that make your IT empire yours. Free My IT Custom
Poster
The post Free My IT Custom Poster appeared first on SweetFreeStuff.com.
///////////////////////////////////////////
Free Tena Trial Kit
Posted: 11 Nov 2014 10:00 PM PST
http://feedproxy.google.com/&edburner&utm_medium=email
Free Tena Sample Packs - Click on Get a Free Trial Kit
The post Free Tena Trial Kit appeared first on SweetFreeStuff.com.