freeCodeCamp Survey Form
Thank you for taking the time to help us improve the platform
Name
Email
Age (optional)
Which option best describes your current role?
Select current role
Student
Full time job
Full time learner
Prefer not to say
Other
Would you recommend freeCodeCamp to a friend?
Definitely
Maybe
Not sure
What is your favorite feature of freeCodeCamp?
Select an option
Chanlleges
Projects
Comunity
Open Source
What would you like to see improved? (Check all that apply)
Front-end Projects
Back-end Projects
Data Visualization
Challenges
Open Source Community
Gitter help rooms
Videos
City Meetups
Wiki
Forum
Additional Courses
Submit


An application or service that users interact with through the exchange of messages.
Typically built on top of a messaging platform.
Little or no user interface development required.
May or may not simulate a conversation.
Facebook Messenger
Kik
Skype
Slack
Twilio
Microsoft Bot Framework
Botkit
api.ai
wit.ai (acquired by Facebook)
Watson Conversation
Set a budget
Add and subtract from the budget
Get the budget balance
No user interface
No user registration
No app store
Voice activated
Easily set, update, and retrieve budgets
Store every message for analysis
Twilio
Send SMS Messages to a Twilio Phone # (can use Siri, OK Google, etc)
Identify users based on the incoming phone number
Store users and budgets in Cloudant
Send SMS Messages back to the calling user
Fully-managed NoSQL DBaaS
Based on CouchDB
https://myapplication.com/sms?From=%2B155512345678&Body=Get%20balance
&...
From = +155512345678
Body = Get balance
if (body.indexOf('set') >= 0) {
operation = 'set';
}
else if (body.indexOf('add') >= 0) {
operation = 'add';
}
else if (body.indexOf('subtract') >= 0) {
operation = 'subtract';
}
else if (body.indexOf('get') >= 0) {
operation = 'get';
}
let amount;
if (operation != 'get') {
let amountRegex = /\d*\.?\d+/g;
let amountMatches = body.match(amountRegex);
if (!amountMatches || amountMatches.length == 0) {
// return error - no amount specified
}
else if (amountMatches.length > 1) {
// return error - too many amounts specified
}
amount = Number(amountMatches[0]);
}
loadOrCreateBudget(cloudant, from, function (err, budget) {
// ...
});
function loadOrCreateBudget(cloudant, from, callback) {
// ...
if (! budgetExists) {
budget = {
_id: from,
balance: 0,
create_date: new Date().getTime()
};
saveBudget(cloudant, budget, callback);
}
// ...
}
if (operation == 'set') {
budget.balance = amount;
}
else if (operation == 'add') {
budget.balance += amount;
}
else if (operation == 'subtract') {
budget.balance -= amount;
}
saveBudget(cloudant, budget, function (err, budget) {
// ...
}
let message = {
from: from,
body: body,
date: new Date().getTime(),
operation: operation,
amount: amount
};
saveMessage(cloudant, message, function (err, result) {
// ...
});
"Your balance is $" + (Math.round(budget.balance * 100) / 100)
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Message>Your balance is $90</Message>
</Response>
Twilio
Command/Response
Budgets and messages stored in Cloudant
Stateless
Cost Effective
Auto Scaling
Open Source
Javascript, Python, Docker, Swift
Request top Hacker News stories in Slack
Display top stories with links to the comments and articles
Initial response <= 3 seconds
response_url provided for sending message
POST https://myapplication.com/hn
token=Vsxxxxxxxxxxxxxxxxxxxxxx&command=%2Fhn
&team_id=TXXXXXXXX&team_domain=your-slack-team
&channel_id=CXXXXXXXX&channel_name=test
&user_id=UXXXXXXXX&user_name=markwatsonatx
&text=&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2F...
command = /hn
response_url = https://hooks.slack.com/commands/...
{
"text": "Top stories coming up..."
}
{
"text": "",
"attachments": [
{
"title": "Child uses sleeping mom's thumbprint to buy $250...",
"title_link": "https://www.cnet.com/news/child-uses...",
"author_name": "21 points by dvdhnt | view comments",
"author_link": "https://news.ycombinator.com/item?id=132..."
},
{
...
}
]
}
{
"text": "",
"attachments": [
{ story1... },
{ story2... },
{
...,
"color": "#3AA3E3",
"actions": [{
"name": "hn_top_stories_more",
"text": "Load More",
"type": "button",
"value": startIndex + 10
}]
}
]
}
payload=%7B%22actions%22%3A%5B%7B%22name%22%3A%22hn_top_stories_more%22
%2C%22value%22%3A%2210%22%7D%5D
%2C%22response_url%22%3A
%22https%3A%5C%2F%5C%2Fhooks.slack.com%5C%2Factions%5C...
{
"actions":[
{
"name": "hn_top_stories_more",
"value": "10"
}
],
...,
"response_url":"https:\/\/hooks.slack.com\/actions\/..."
}
Slack Slash Command
Command/Response + Push
Stateless
Hacker News API
One call to retrieve top story IDs
One call per story to return contents
11 API calls per /hn command
100 commands = 1,100 Hacker News API requests
Top stories may not change very often
Caching top stories for 1 minute can cut down on thousands of API calls
In-memory datastore
Commonly used for session cache
Fully-managed using Compose for Redis
Cache top stories for 1 minute
100 cmds/min w/o Redis = 1,100 Hacker News API requests
100 cmds/min w/ Redis = 11 Hacker News API requests + 101 Redis requests
| Bot #1: Budget | Bot #2: Hacker News | ||
|---|---|---|---|
| Platform | Twilio | Slack | |
| Mode | Command/Response | Command/Response + Push | |
| Stateless | Yes | Yes | |
| Services | Cloudant | Hacker News API, Redis |
Conversational bot
Provides recipe suggestions and instructions based on ingredients or cuisines
while self.running:
if self.slack_client.rtm_connect():
while self.running:
slack_output = self.slack_client.rtm_read()
message, message_sender, channel = self.parse_slack_output...
if message and channel:
self.handle_message(message, message_sender, channel)
watson_response = self.conversation_client.message(
workspace_id=self.conversation_workspace_id,
message_input={'text': message},
context=state.conversation_context
)
if 'is_ingredients' in state.conversation_context.keys()...:
response = self.handle_ingredients_message(state, message)
elif 'is_selection' in state.conversation_context.keys()...:
response = self.handle_selection_message(state)
matching_recipes = self.recipe_client.find_by_ingredients(ingredients)
self.slack_client.api_call(
"chat.postMessage",
channel=channel,
text=response,
as_user=True
)
Watson Conversation combines a number of cognitive techniques to help you build and train a bot - defining intents and entities and crafting dialog to simulate conversation.
Intents
Entities
Dialog
Context
Passed between Watson Conversation and application
Keeps track of current dialog in the conversation
# send message to watson conversation
watson_response = self.conversation_client.message(
workspace_id=self.conversation_workspace_id,
message_input={'text': message},
context=state.conversation_context
)
# update conversation context
state.conversation_context = watson_response['context']
Add custom variables to the context for use in your bot
if 'is_ingredients' in state.conversation_context.keys()
and state.conversation_context['is_ingredients']:
response = self.handle_ingredients_message(state, message)
elif watson_response['entities']
and watson_response['entities'][0]['entity'] == 'cuisine':
cuisine = watson_response['entities'][0]['value']
response = self.handle_cuisine_message(state, cuisine)
Slack Bot User
Conversational
State needs to be managed
No persistent storage
Cache 3rd Party API Calls
Track user habits
Provide a more personal experience
{
"_id": "971e1fb0322f12cfceac427a1f8a674e",
"name": "U3XXXXXXX",
"ingredients": [{
"name": "tomatoes",
"count": 9
}],
"cuisines": [{
"name": "italian",
"count": 5
}],
"recipes": [{
"id": "833235",
"title": "Sliced Cucumber and Tomato Salad",
"count": 3
}]
}
if 'is_favorites' in state.conversation_context.keys()
and state.conversation_context['is_favorites']:
response = self.handle_favorites_message(state)
def handle_favorites_message(self, state):
recipes = self.recipe_store.find_favorite_recipes_for_user...
| Bot #1: Budget | Bot #2: HN | Bot #3: Recipe | |
|---|---|---|---|
| Platform | Twilio | Slack | Slack |
| Mode | Cmd/Resp | Cmd/Resp + Push | Conversational |
| Stateless | Yes | Yes | No |
| Services | Cloudant | Hacker News API, Redis | Watson Conversation, Cloudant, Spoonacular |
bluemix.com
medium.com/ibm-watson-data-lab
github.com/markwatsonatx/presentation-bots


Someone is going around rotating people's strings. Not cool. We can't fix it for you, but we would be happy to tell you if you have been a victim of string rotation.
Enter your strings below:


Days
21
Days
12
Minutes
30
Countdown
- Days
- Hours
- Minutes
- Seconds
GPS
Signal Quality
Temperature / Pressure / Humdity
Axis
Mag


| Shipping & handling: | $0.00 |
|
|
|
| Total before tax: | |
| Promo applied: | |
| Estimated tax (7%): | |
|
|
|
|
Order total:
|
|


This sample demonstrates how AngularJS directives are used with the igGrid to allow for two-way binding in the grid.
Explore the Code


| TEP: | 138 |
|---|---|
| Group: | Net2 Working Group |
| Type: | Documentary |
| Status: | Draft |
| TinyOS-Version: | > 2.1 |
| Author: | Chieh-Jan (Mike) Liang, Doug Carlson, Maria A. Kazandjieva, and Omprakash Gnawali |
| Draft-Created: | 28-May-2010 |
| Draft-Version: | 1.2 |
| Draft-Modified: | 2010-06-09 |
| Draft-Discuss: | TinyOS Developer List <tinyos-devel at mail.millennium.berkeley.edu> |
Note
This memo documents a part of TinyOS for the TinyOS Community, and requests discussion and suggestions for improvements. Distribution of this memo is unlimited. This memo is in full compliance with TEP 1.
This memo documents the interfaces and components used for source routing in TinyOS 2.x. Source routing allows its users to specify the path a packet must take to reach the destination.
Source routes are paths explicitly provided by its users. These routes, often in the form of a list of nodes to be traversed on the way to the destination, are carried in the packet header. When a node receives a source-routed packet, it looks up the next hop in the source routing packet header and forwards the packet to that node.
A complete source routing system is comprised of two sets of functionality: the first deals with reading and writing source routes and the second handles forwarding based on source routes.
A source routing system can be used in many ways. This can be useful as a light-weight routing system for debugging or for environments that are static enough that the routes are known ahead of time. It can also be used by routing systems that compute the path at a given node based on topology information from the network. For example, given the link state information of a network, a node can source route a packet to any node in the network. Source routing is also useful to route a packet along the reverse path to the original sender.
Our approach provides the most basic source routing system as an example of a light-weight end-to-end protocol that can also be used in conjunction with other routing and forwarding systems. Our focus in this document is to specify a best-effort source routing system.
The rest of this document describes the source routing interfaces and components.
A node can perform three different roles in source routing:
- Sender: Configuring the source route and send a packet
- Forwarder: Receive a source routed packet and forward it to the next hop
- Receiver: Receive a source routed packet at the destination
Multiple sender applications can use the source routing system. These senders are uniquely identified by sourceroute identifiers. These identifiers work like collection identifiers in collection protocols[1].
The sender uses the SourceRouteSend interface to set the contents of a packet. The sender uses the SourceRouteSend interface to introduce a packet into the network.
- interface SourceRouteSend {
- command error_t send(am_addr_t path, uint8_t pathLen, message_t msg, uint8_t len); command error_t cancel(message_t* msg); event void sendDone(message_t* msg, error_t error); command uint8_t maxPayloadLength(); command void* getPayload(message_t* msg, uint8_t len);
}
The forwarder uses the SourceRoutePacket interface to update the header as it forwards the packet:
interface SourceRoutePacket {
command am_addr_t address();
command error_t clearRoute(message_t *msg);
command error_t setRoute(message_t msg, nx_am_addr_t *path, uint8_t len); command nx_am_addr_t getRoute(message_t *msg);
command uint8_t getRouteLen(message_t *msg); command error_t setRouteLen(message_t *msg, uint8_t len);
command am_addr_t getNextHop(message_t *msg); command am_addr_t getDest(message_t *msg);
command uint8_t getCurHop(message_t *msg); command error_t setCurHop(message_t *msg, uint8_t hop);
}
A source routing service MUST provide one SourceRoutingC, which has the following signature:
- configuration SourceRoutingC {
- provides {
- interface StdControl; interface SourceRouteSend[uint8_t client]; interface SourceRoutePacket; interface Receive[sourceroute_id_t id];
} uses {
interface SourceRouteId[uint8_t client];}
}
An implementation of source routing service will be found in tinyos-2.x/tos/lib/net/sourceroute.
| [1] | TEP 119: Collection |


Main Concepts
Dependency Injection - More Details - Provide
And we can even do more with provide
- configure simple values (singletons)
- configure aliases (singletons)
- configure factories
import {ReflectiveInjector} from '@angular/core';
//Define our injector and its providers
let injector = ReflectiveInjector.resolveAndCreate([
{provide: 'AppVersion', useValue: '1.0.0-SNAPSHOT'}
]);
import {ReflectiveInjector} from '@angular/core';
//Define our injector and its providers
let injector = ReflectiveInjector.resolveAndCreate([
{ provide: Person, useClass: PersonImpl}
]);
import {ReflectiveInjector} from '@angular/core';
//Define our injector and its providers
let injector = ReflectiveInjector.resolveAndCreate([
{
provide: PersonFactory,
useFactory: (loggerService) => {
return new RandomPerson(loggerService);
},
deps: [LoggerService]
}
]);


HBK
Home
About
Contact
Contact
Us
Please fill out the form below to contact us
Name
Email
Message
Location
123 Main st,Lahore
Phone Number
(123) 444-444
Phone Number
(123) 444-444


ERROR: JavaScript disabled! For full functionality of this site it is necessary to enable JavaScript. Here are the
instructions how to enable JavaScript in your web browser
.


--- layout: post title: 調弓注意事項 categories: - 射箭生活 tags: [] published: true comments: true ---
一樣也是從死海文書中發現的...
Brace Height Range:
Long riser + Medium limb = 8 1/2 - 9 1/4"
String:
Hoyt does not recommend more than 50 or less than 10 twists in a string.
Tiller:
We recommend you begin with 0-1/8" positive tiller.
(Bottom measurement 0-1/8" less than top measurement.)
If you find your sight moving up as you are drawing, increase the bottom
limb poundage slightly, or decrease the top limb poundage.
If the sight is moving down as you draw, make the opposite adjustments.
To adjust the tiller without affecting bow weight, adjust both the top and
the bottom weight/tiller adjustment bolts in equal but opposite directions.


Skill Details
Contact Details
Personal Details
SocialMedia Details
Education Details
Language Details
Skill Details
SoftSkill Details
Strength Weakness Details
Hobbie Details
AwardAchievement Details
Experience Details
Internship Details
Project Details
Interest Details
Training Details
Certification Details
Summary Details


Student A Profile
Registered Courses
| Course Number | Course Name | Instructor | Current Grade Estimate | |
|---|---|---|---|---|
| 6.803 | Human Intellgience Enterprise | Patrick Henry Winston | B+ | |
| 6.813 | User Interface Design | Rob Miller, Daniel Jackson, Karger | A | |
| 18.440 | Probability and Random Variables | Shepfield | A |
Recent Assignments
| Assignment Name | Course | Submission Date | Grade | |
|---|---|---|---|---|
| Semantics Paper | 6.803 | 3/3/2014 | B | |
| Problem Set 4 | 18.440 | 3/4/2014 | N/A |


@* * Imports & view variables *@ @(name: String) @main("Pokemon not found") {
You tried : @name
Back to search page


--- post_title: 'Amazon’s Publisher Studio Loader for WordPress' author: sadmin2a post_excerpt: "" layout: page permalink: > https://www.2aces.com.br/wordpress-plugins/aa-amazon-studio-loader/ dsq_thread_id: - "2348620143" --- (versão em português encontrada aqui) This is simple and free plugin by 2Aces for making easier to load Amazon Publisher Studio on a Wordpress blog. Amazon Publisher Studio it's a new tool from Amazon that allow Amazon Associates affiliates to easily create links to Amazon products directly from their blog/sites front-end. Eliminating the need of going to Amazon to search for products and manually placing the links.
aa-amazon-studio-loader.zip
and upload aa-amazon-studio-loader
folder to the /wp-content/plugins/
directorycodeamznpubstudioTag
.
( i.e cybl0a-20 on window.amznpubstudioTag = "cybl0a-20"
) and paste in the first field of the plugin's settings pagehttp://ps-us.amazon-adsystem.com/domains/
and .js
.
( e.g.cybl0a-20_a5e1c142-fc0b-4b4c-abf8-27814868e9b8
, on http://ps-us.amazon-adsystem.com/domains/cybl0a-20_a5e1c142-fc0b-4b4c-abf8-27814868e9b8.js
) and paste in the second field of the plugin's settings page


If you'd like to visit the downtown campus here is the map yo can follow.
Here is a live station for lofi hip hop beats to accompany the trip:


The Parts of a URL
Every page and resource on the web has its own special address called a URL, or Uniform Resource Locator.
Anatomy of a URL
A URL is often made up of three components: the protocol, the domain name, and the path to a document or resource. An example URL is shown below:
HTTPS Protocol
The letters HTTPS stand for HyperText Transfer Protocol. This is the technology websites use to transfer files across the internet.
Domain: www.example.com
The next portion of the URL identifies the website by its domain name. The www part is called a subdomain and .com is called a top level domain. Sometimes www may be omitted. There can be more than one website at a domain (sometimes called subdomains). For example, there might also be development.example.com, clients.example.com, and so on.
Optionally, we can include a port number. In most cases the port defaults to 80 (http) or 443 (https). Since those are the default values, we usually omit this portion of the URl.
Path and File: /images/example.png
This is the path and file name of the requested HTML document. The word images is the directory name, starting with the root directory of the host (as indicated by the initial /). Because the Internet has always primarily consisted of computers running the Unix operating system, we follow the Unix rules and convention for path separators; hence the / character for separating directory names.


Welcome to Pig-Dice-Game!!!!!
INSTRUCTIONS
The Game has two players.
Each player has a turn to play the game.
After each player plays the game should see there respective scores.
If the Dice rolls one the current player who is playing should give chance to the next player.
Once the player gets score 100, the player is winner.
If the player holds the dice the point is added.
Each player uses the button given below.
First-Player
Play!!
Second-player
START PIG-DICE-GAME
Player 1:
Total Score
0
Dice Roll
0
Round Total
0
ROLL
HOLD
Player 2:
Total Score
0
Dice Roll
0
Round Total
0
ROLL
HOLD


{% extends base_template %} {% import "macros.j2" as macros with context %} {% set report_name = report.report_parameters.name %} {% block body %} {% block report_title %}
This report of forecast accuracy was automatically generated using the Solar Forecast Arbiter.
{% endblock %} {% block download %}{% endblock %} {% block toc %}{{ cost.to_dict() | pretty_json }}
This report includes forecast and observation data available from {{ report.report_parameters.start }} to {{ report.report_parameters.end }}. {% endblock %} {% block obsandfx %}
More metadata for the objects in this report may be downloaded in JSON format.
{% if timeseries_spec is defined %}The plots below show the filtered, resampled, and aligned time series of observation and forecast data as well as the distribution of forecast vs. observation data. This resampled and realigned timeseries data may also be downloaded in CSV format.
Controls to pan, zoom, and save the plot are shown on the right. Clicking on an item in the legend will hide/show it.
{% if includes_distribution %}For forecasts parameterized symmetrically around the 50th percentile, brighter colors indicate percentiles farther from the 50th percentile and darker colors indicate percentiles closer to the 50th percentile. For forecasts parameterized asymmetrically around the 50th percentile, brighter colors indicate smaller percentiles and darker colors indicate larger percentiles. Use the hover tool to determine the percentile.
{% endif %} {{ macros.download_timeseries_script () | safe }} {% endif %} {% if scatter_spec is defined %} {% endif %} {% if timeseries_prob_spec is defined %}The plot below shows probability vs. time for probabilistic forecasts with axis='x'.
{% endif %} {% include "load_metadata.html" %} {{ macros.download_metadata_script () | safe }} {% endblock %}A table of summary statistics for the resampled observations and deterministic forecasts over the entire study period is shown below. Statistics for other categories may be downloaded in CSV format or JSON format.
{% if "total" in report.report_parameters.categories %} {{ macros.summary_stats_table_vert(report.raw_report.metrics | selectattr("is_summary"), "total") }} {% else %}A table of metrics over the entire study period and figures for the selected categories are shown below. Metrics may be downloaded in CSV format or JSON format.
{% if "total" in report.report_parameters.categories %} {{ macros.metric_table_fx_vert(report.raw_report.metrics | rejectattr("is_summary"), "total", report.report_parameters.metrics) }} {% else %}{{ category_blurbs[category] }}
{% endif %}


Vector Class
Definition
Line
169
of
System.Windows/Graphics.cm
Constructors & Destructor
public
nothrow
Vector
()
public
explicit
nothrow
Vector
(
const
PointF
& point)
public
nothrow
Vector
(
float
x_,
float
y_)
Member Functions
public
nothrow
float
Length
()
const
public
nothrow
PointF
ToPoint
()
const
Member Variables
public
float
x
public
float
y
Constructor& Destructor Details
Vector Constructor
public
nothrow
Vector()
Definition
Line
171
of
System.Windows/Graphics.cm
Vector Constructor
public
explicit
nothrow
Vector(
const
PointF
& point)
Definition
Line
177
of
System.Windows/Graphics.cm
Vector Constructor
public
nothrow
Vector(
float
x_,
float
y_)
Definition
Line
174
of
System.Windows/Graphics.cm
Member Function Details
Length Member Function
public
nothrow
float
Length()
Definition
Line
180
of
System.Windows/Graphics.cm
ToPoint Member Function
public
nothrow
PointF
ToPoint()
Definition
Line
184
of
System.Windows/Graphics.cm


Classes
The following classes are available globally.
-
Undocumented
See moreDeclaration
Swift
open class ByteArray
-
This class will parse SoundFont 2 files. Right now, it can list the presets. That’s all I wanted. If you want more, go ahead and fill it in.
See moreDeclaration
Swift
public class GDSoundFontParser : NSObject
-
Undocumented
Declaration
Swift
public class RIFFChunk
-
Undocumented
See moreDeclaration
Swift
public class SFOperator


--- layout: default title: Application Stack Management Experience css: architect permalink: /new-architect/ published: false --- {% assign t = site.data[site.active_lang].stack-management %}
{{t.intro-title}}
{{t.intro-text}}


{% extends 'base.html' %} {% block body %}
Flask toolbox has collected many flask extensions, then group them in different categories. It also fetch the basic info on the package's github and PyPI, and then show them to you. The goal of flask toolbox is to help you find the package you want and make your development with flask feel at ease.
Find all the related packages in the same category. Choose the one that suits you most.
Show the package's documentation, souce code, bug tracker, PyPI url. What's more, it gives you the key points for the package on github and PyPI.
Flask toolbox has collected most of the flask extentions. If you found one is missing here, please send a pull request on github and add it to flask toolbox!
Flask toolbox is opensource on github. Help us improve it!
Flask toolbox groups the related packages into the same category. You'll have more choices and easily find the packages you want.
Flask toolbox fetchs the basic info on github and PyPI, analyse them and then show them to you in a more human friendly way. For example, you can know that whether this package is under active development and well maintained on github.
Although there are several packages in a category, but you may still have trouble to choose one. Flask toolbox calculates the popularity score for you and sort the packages so that you can easily choose one.
{% endblock %}More than the Awesome-Flask list.


In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset of English and French sentences that can translate new sentences from English to French.
Since translating the whole language of English to French will take lots of time to train, we have provided you with a small portion of the English corpus.
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Play around with view_sentence_range to view different parts of the data.
view_sentence_range = (0, 10)
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np
print('Dataset Stats')
print('Roughly the number of unique words: {}'.format(len({word: None for word in source_text.split()})))
print('Roughly the number of unique words: {}'.format(len({word: None for word in target_text.split()})))
sentences = source_text.split('\n')
word_counts = [len(sentence.split()) for sentence in sentences]
print('Number of sentences: {}'.format(len(sentences)))
print('Average number of words in a sentence: {}'.format(np.average(word_counts)))
print()
print('English sentences {} to {}:'.format(*view_sentence_range))
print('\n'.join(source_text.split('\n')[view_sentence_range[0]:view_sentence_range[1]]))
print()
print('French sentences {} to {}:'.format(*view_sentence_range))
print('\n'.join(target_text.split('\n')[view_sentence_range[0]:view_sentence_range[1]]))
Dataset Stats Roughly the number of unique words: 227 Roughly the number of unique words: 355 Number of sentences: 137861 Average number of words in a sentence: 13.225277634719028 English sentences 0 to 10: new jersey is sometimes quiet during autumn , and it is snowy in april . the united states is usually chilly during july , and it is usually freezing in november . california is usually quiet during march , and it is usually hot in june . the united states is sometimes mild during june , and it is cold in september . your least liked fruit is the grape , but my least liked is the apple . his favorite fruit is the orange , but my favorite is the grape . paris is relaxing during december , but it is usually chilly in july . new jersey is busy during spring , and it is never hot in march . our least liked fruit is the lemon , but my least liked is the grape . the united states is sometimes busy during january , and it is sometimes warm in november . French sentences 0 to 10: new jersey est parfois calme pendant l' automne , et il est neigeux en avril . les états-unis est généralement froid en juillet , et il gèle habituellement en novembre . california est généralement calme en mars , et il est généralement chaud en juin . les états-unis est parfois légère en juin , et il fait froid en septembre . votre moins aimé fruit est le raisin , mais mon moins aimé est la pomme . son fruit préféré est l'orange , mais mon préféré est le raisin . paris est relaxant en décembre , mais il est généralement froid en juillet . new jersey est occupé au printemps , et il est jamais chaude en mars . notre fruit est moins aimé le citron , mais mon moins aimé est le raisin . les états-unis est parfois occupé en janvier , et il est parfois chaud en novembre .
As you did with other RNNs, you must turn the text into a number so the computer can understand it. In the function text_to_ids()
, you'll turn source_text
and target_text
from words to ids. However, you need to add the <EOS>
word id at the end of target_text
. This will help the neural network predict when the sentence should end.
You can get the <EOS>
word id by doing:
target_vocab_to_int['<EOS>']
You can get other word ids using source_vocab_to_int
and target_vocab_to_int
.
def text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int):
"""
Convert source and target text to proper word ids
:param source_text: String that contains all the source text.
:param target_text: String that contains all the target text.
:param source_vocab_to_int: Dictionary to go from the source words to an id
:param target_vocab_to_int: Dictionary to go from the target words to an id
:return: A tuple of lists (source_id_text, target_id_text)
"""
#sentences2 = target_text.split('n')
#wordList1 = source_text.split(' ')
mat_in = []
mat_tar = []
# TODO: Implement Function
#print(source_vocab_to_int)
#target_text = temp.replace(".", "<EOS>")
for sentence in source_text.split("\n"):
arr = []
for word in sentence.split():
arr.append(source_vocab_to_int[word])
mat_in.append(arr)
for sentence in target_text.split("\n"):
arr = []
for word in sentence.split():
arr.append(target_vocab_to_int[word])
arr.append(target_vocab_to_int['<EOS>'])
#print(np.array(arr).shape)
mat_tar.append(arr)
#print (mat_tar[1])
#for count, word in enumerate(target_text)
return mat_in, mat_tar
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_text_to_ids(text_to_ids)
Tests Passed
Running the code cell below will preprocess all the data and save it to file.
 If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np
import helper
import problem_unittests as tests
(source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess()
This will check to make sure you have the correct version of TensorFlow and access to a GPU
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
from distutils.version import LooseVersion
import warnings
import tensorflow as tf
from tensorflow.python.layers.core import Dense
# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.1'), 'Please use TensorFlow version 1.1 or newer'
print('TensorFlow Version: {}'.format(tf.__version__))
# Check for a GPU
if not tf.test.gpu_device_name():
warnings.warn('No GPU found. Please use a GPU to train your neural network.')
else:
print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
TensorFlow Version: 1.1.0 Default GPU Device: /gpu:0
You'll build the components necessary to build a Sequence-to-Sequence model by implementing the following functions below:
model_inputs
process_decoder_input
encoding_layer
decoding_layer_train
decoding_layer_infer
decoding_layer
seq2seq_model
Implement the model_inputs()
function to create TF Placeholders for the Neural Network. It should create the following placeholders:
Return the placeholders in the following the tuple (input, targets, learning rate, keep probability, target sequence length, max target sequence length, source sequence length)
def model_inputs():
"""
Create TF Placeholders for input, targets, learning rate, and lengths of source and target sequences.
:return: Tuple (input, targets, learning rate, keep probability, target sequence length,
max target sequence length, source sequence length)
"""
# TODO: Implement Function
inputs = tf.placeholder(tf.int32, shape=(None,None), name='input')
targets = tf.placeholder(tf.int32, shape=(None, None), name='target')
learning_rate = tf.placeholder(tf.float32, name='learning_rate')
keep_prob = tf.placeholder(tf.float32, name='keep_prob')
target_seq_len = tf.placeholder(tf.int32, shape=[None], name='target_sequence_length')
max_target_len = tf.reduce_max(target_seq_len, name='max_target_len')
source_seq_len = tf.placeholder(tf.int32, shape=[None], name='source_sequence_length')
return inputs, targets, learning_rate, keep_prob, target_seq_len, max_target_len, source_seq_len
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_inputs(model_inputs)
Tests Passed
Implement process_decoder_input
by removing the last word id from each batch in target_data
and concat the GO ID to the begining of each batch.
def process_decoder_input(target_data, target_vocab_to_int, batch_size):
"""
Preprocess target data for encoding
:param target_data: Target Placehoder
:param target_vocab_to_int: Dictionary to go from the target words to an id
:param batch_size: Batch Size
:return: Preprocessed target data
"""
# TODO: Implement Function
print(target_data[0:200])
go = tf.constant(target_vocab_to_int['<GO>'], shape=(batch_size,1), dtype=tf.int32)
new_target = tf.concat([go,target_data[:,:-1]],1)
return new_target
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_process_encoding_input(process_decoder_input)
Tensor("strided_slice:0", shape=(2, 3), dtype=int32) Tests Passed
Implement encoding_layer()
to create a Encoder RNN layer:
tf.contrib.layers.embed_sequence
tf.contrib.rnn.LSTMCell
wrapped in a tf.contrib.rnn.DropoutWrapper
tf.nn.dynamic_rnn()
from imp import reload
reload(tests)
def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob,
source_sequence_length, source_vocab_size,
encoding_embedding_size):
"""
Create encoding layer
:param rnn_inputs: Inputs for the RNN
:param rnn_size: RNN Size
:param num_layers: Number of layers
:param keep_prob: Dropout keep probability
:param source_sequence_length: a list of the lengths of each sequence in the batch
:param source_vocab_size: vocabulary size of source data
:param encoding_embedding_size: embedding size of source data
:return: tuple (RNN output, RNN state)
"""
# TODO: Implement Function
cell_stack = []
for _ in range(num_layers):
lstm = tf.contrib.rnn.LSTMCell(rnn_size)
drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)
cell_stack.append(drop)
lstms = tf.contrib.rnn.MultiRNNCell(cell_stack)
encoder = tf.contrib.layers.embed_sequence(rnn_inputs, vocab_size = source_vocab_size, embed_dim = encoding_embedding_size)
output, state = tf.nn.dynamic_rnn(lstms, encoder, source_sequence_length, dtype=tf.float32)
return output, state
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_encoding_layer(encoding_layer)
Tests Passed
Create a training decoding layer:
tf.contrib.seq2seq.TrainingHelper
tf.contrib.seq2seq.BasicDecoder
tf.contrib.seq2seq.dynamic_decode
def decoding_layer_train(encoder_state, dec_cell, dec_embed_input,
target_sequence_length, max_summary_length,
output_layer, keep_prob):
"""
Create a decoding layer for training
:param encoder_state: Encoder State
:param dec_cell: Decoder RNN Cell
:param dec_embed_input: Decoder embedded input
:param target_sequence_length: The lengths of each sequence in the target batch
:param max_summary_length: The length of the longest sequence in the batch
:param output_layer: Function to apply the output layer
:param keep_prob: Dropout keep probability
:return: BasicDecoderOutput containing training logits and sample_id
"""
# TODO: Implement Function
#print("seq length")
#print(target_sequence_length)
train_helper = tf.contrib.seq2seq.TrainingHelper(dec_embed_input, target_sequence_length)
basic_decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell, train_helper, encoder_state, output_layer)
output, _ = tf.contrib.seq2seq.dynamic_decode(basic_decoder,maximum_iterations=max_summary_length)
return output
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_decoding_layer_train(decoding_layer_train)
Tests Passed
Create inference decoder:
tf.contrib.seq2seq.GreedyEmbeddingHelper
tf.contrib.seq2seq.BasicDecoder
tf.contrib.seq2seq.dynamic_decode
def decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id,
end_of_sequence_id, max_target_sequence_length,
vocab_size, output_layer, batch_size, keep_prob):
"""
Create a decoding layer for inference
:param encoder_state: Encoder state
:param dec_cell: Decoder RNN Cell
:param dec_embeddings: Decoder embeddings
:param start_of_sequence_id: GO ID
:param end_of_sequence_id: EOS Id
:param max_target_sequence_length: Maximum length of target sequences
:param vocab_size: Size of decoder/target vocabulary
:param decoding_scope: TenorFlow Variable Scope for decoding
:param output_layer: Function to apply the output layer
:param batch_size: Batch size
:param keep_prob: Dropout keep probability
:return: BasicDecoderOutput containing inference logits and sample_id
"""
# TODO: Implement Function
ids = tf.tile([start_of_sequence_id], [batch_size])
# Create the embedding helper.
embedding_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(
dec_embeddings, ids, end_of_sequence_id)
basic_decoder = tf.contrib.seq2seq.BasicDecoder(
dec_cell, embedding_helper, encoder_state, output_layer)
output, _ = tf.contrib.seq2seq.dynamic_decode(
basic_decoder,maximum_iterations=max_target_sequence_length)
return output
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_decoding_layer_infer(decoding_layer_infer)
Tests Passed
Implement decoding_layer()
to create a Decoder RNN layer.
decoding_layer_train(encoder_state, dec_cell, dec_embed_input, target_sequence_length, max_target_sequence_length, output_layer, keep_prob)
function to get the training logits.decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id, max_target_sequence_length, vocab_size, output_layer, batch_size, keep_prob)
function to get the inference logits.Note: You'll need to use tf.variable_scope to share variables between training and inference.
def decoding_layer(dec_input, encoder_state,
target_sequence_length, max_target_sequence_length,
rnn_size,
num_layers, target_vocab_to_int, target_vocab_size,
batch_size, keep_prob, decoding_embedding_size):
"""
Create decoding layer
:param dec_input: Decoder input
:param encoder_state: Encoder state
:param target_sequence_length: The lengths of each sequence in the target batch
:param max_target_sequence_length: Maximum length of target sequences
:param rnn_size: RNN Size
:param num_layers: Number of layers
:param target_vocab_to_int: Dictionary to go from the target words to an id
:param target_vocab_size: Size of target vocabulary
:param batch_size: The size of the batch
:param keep_prob: Dropout keep probability
:param decoding_embedding_size: Decoding embedding size
:return: Tuple of (Training BasicDecoderOutput, Inference BasicDecoderOutput)
"""
# TODO: Implement Function
cells = []
for _ in range(num_layers):
lstm = tf.contrib.rnn.LSTMCell(rnn_size)
drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)
cells.append(drop)
lstms = tf.contrib.rnn.MultiRNNCell(cells)
dec_embeds = tf.Variable(tf.random_uniform([target_vocab_size, decoding_embedding_size]))
dec_embed_in = tf.nn.embedding_lookup(dec_embeds, dec_input)
dense_layer = Dense(target_vocab_size, kernel_initializer = tf.truncated_normal_initializer(mean = 0.0, stddev=0.1))
with tf.variable_scope("decode") as scope:
train_decoder_outputs = decoding_layer_train(encoder_state, lstms, dec_embed_in,
target_sequence_length, max_target_sequence_length, dense_layer, keep_prob)
scope.reuse_variables()
infer_decoder_outputs = decoding_layer_infer(encoder_state, lstms, dec_embeds,
target_vocab_to_int['<GO>'], target_vocab_to_int['<EOS>'], max_target_sequence_length, target_vocab_size,
dense_layer, batch_size, keep_prob)
return train_decoder_outputs , infer_decoder_outputs
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_decoding_layer(decoding_layer)
Tests Passed
Apply the functions you implemented above to:
encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, source_sequence_length, source_vocab_size, encoding_embedding_size)
.process_decoder_input(target_data, target_vocab_to_int, batch_size)
function.decoding_layer(dec_input, enc_state, target_sequence_length, max_target_sentence_length, rnn_size, num_layers, target_vocab_to_int, target_vocab_size, batch_size, keep_prob, dec_embedding_size)
function.def seq2seq_model(input_data, target_data, keep_prob, batch_size,
source_sequence_length, target_sequence_length,
max_target_sentence_length,
source_vocab_size, target_vocab_size,
enc_embedding_size, dec_embedding_size,
rnn_size, num_layers, target_vocab_to_int):
"""
Build the Sequence-to-Sequence part of the neural network
:param input_data: Input placeholder
:param target_data: Target placeholder
:param keep_prob: Dropout keep probability placeholder
:param batch_size: Batch Size
:param source_sequence_length: Sequence Lengths of source sequences in the batch
:param target_sequence_length: Sequence Lengths of target sequences in the batch
:param source_vocab_size: Source vocabulary size
:param target_vocab_size: Target vocabulary size
:param enc_embedding_size: Decoder embedding size
:param dec_embedding_size: Encoder embedding size
:param rnn_size: RNN Size
:param num_layers: Number of layers
:param target_vocab_to_int: Dictionary to go from the target words to an id
:return: Tuple of (Training BasicDecoderOutput, Inference BasicDecoderOutput)
"""
# TODO: Implement Function
outputs, state = encoding_layer(input_data, rnn_size, num_layers, keep_prob,
source_sequence_length, source_vocab_size,
enc_embedding_size)
processed_input = process_decoder_input(target_data, target_vocab_to_int, batch_size)
train_decoder_output, interface_decoder_output = decoding_layer(processed_input, state,
target_sequence_length, max_target_sentence_length,
rnn_size, num_layers, target_vocab_to_int, target_vocab_size,
batch_size, keep_prob, dec_embedding_size)
return train_decoder_output, interface_decoder_output
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_seq2seq_model(seq2seq_model)
Tensor("strided_slice:0", shape=(64, 22), dtype=int32) Tests Passed
Tune the following parameters:
epochs
to the number of epochs.batch_size
to the batch size.rnn_size
to the size of the RNNs.num_layers
to the number of layers.encoding_embedding_size
to the size of the embedding for the encoder.decoding_embedding_size
to the size of the embedding for the decoder.learning_rate
to the learning rate.keep_probability
to the Dropout keep probabilitydisplay_step
to state how many steps between each debug output statement# Number of Epochs
epochs = 20
# Batch Size
batch_size = 512
# RNN Size
rnn_size = 128
# Number of Layers
num_layers = 2
# Embedding Size
encoding_embedding_size = 128
decoding_embedding_size = 128
# Learning Rate
learning_rate = 0.0009
# Dropout Keep Probability
keep_probability = 0.5
display_step = True
Build the graph using the neural network you implemented.
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
save_path = 'checkpoints/dev'
(source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess()
max_target_sentence_length = max([len(sentence) for sentence in source_int_text])
train_graph = tf.Graph()
with train_graph.as_default():
input_data, targets, lr, keep_prob, target_sequence_length, max_target_sequence_length, source_sequence_length = model_inputs()
#sequence_length = tf.placeholder_with_default(max_target_sentence_length, None, name='sequence_length')
input_shape = tf.shape(input_data)
train_logits, inference_logits = seq2seq_model(tf.reverse(input_data, [-1]),
targets,
keep_prob,
batch_size,
source_sequence_length,
target_sequence_length,
max_target_sequence_length,
len(source_vocab_to_int),
len(target_vocab_to_int),
encoding_embedding_size,
decoding_embedding_size,
rnn_size,
num_layers,
target_vocab_to_int)
training_logits = tf.identity(train_logits.rnn_output, name='logits')
inference_logits = tf.identity(inference_logits.sample_id, name='predictions')
masks = tf.sequence_mask(target_sequence_length, max_target_sequence_length, dtype=tf.float32, name='masks')
with tf.name_scope("optimization"):
# Loss function
cost = tf.contrib.seq2seq.sequence_loss(
training_logits,
targets,
masks)
# Optimizer
optimizer = tf.train.AdamOptimizer(lr)
# Gradient Clipping
gradients = optimizer.compute_gradients(cost)
capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients if grad is not None]
train_op = optimizer.apply_gradients(capped_gradients)
Tensor("strided_slice:0", shape=(?, ?), dtype=int32)
Batch and pad the source and target sequences
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
def pad_sentence_batch(sentence_batch, pad_int):
"""Pad sentences with <PAD> so that each sentence of a batch has the same length"""
max_sentence = max([len(sentence) for sentence in sentence_batch])
return [sentence + [pad_int] * (max_sentence - len(sentence)) for sentence in sentence_batch]
def get_batches(sources, targets, batch_size, source_pad_int, target_pad_int):
"""Batch targets, sources, and the lengths of their sentences together"""
for batch_i in range(0, len(sources)//batch_size):
start_i = batch_i * batch_size
# Slice the right amount for the batch
sources_batch = sources[start_i:start_i + batch_size]
targets_batch = targets[start_i:start_i + batch_size]
# Pad
pad_sources_batch = np.array(pad_sentence_batch(sources_batch, source_pad_int))
pad_targets_batch = np.array(pad_sentence_batch(targets_batch, target_pad_int))
# Need the lengths for the _lengths parameters
pad_targets_lengths = []
for target in pad_targets_batch:
pad_targets_lengths.append(len(target))
pad_source_lengths = []
for source in pad_sources_batch:
pad_source_lengths.append(len(source))
yield pad_sources_batch, pad_targets_batch, pad_source_lengths, pad_targets_lengths
Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forms to see if anyone is having the same problem.
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
def get_accuracy(target, logits):
"""
Calculate accuracy
"""
max_seq = max(target.shape[1], logits.shape[1])
if max_seq - target.shape[1]:
target = np.pad(
target,
[(0,0),(0,max_seq - target.shape[1])],
'constant')
if max_seq - logits.shape[1]:
logits = np.pad(
logits,
[(0,0),(0,max_seq - logits.shape[1])],
'constant')
return np.mean(np.equal(target, logits))
# Split data to training and validation sets
train_source = source_int_text[batch_size:]
train_target = target_int_text[batch_size:]
valid_source = source_int_text[:batch_size]
valid_target = target_int_text[:batch_size]
(valid_sources_batch, valid_targets_batch, valid_sources_lengths, valid_targets_lengths ) = next(get_batches(valid_source,
valid_target,
batch_size,
source_vocab_to_int['<PAD>'],
target_vocab_to_int['<PAD>']))
with tf.Session(graph=train_graph) as sess:
sess.run(tf.global_variables_initializer())
for epoch_i in range(epochs):
for batch_i, (source_batch, target_batch, sources_lengths, targets_lengths) in enumerate(
get_batches(train_source, train_target, batch_size,
source_vocab_to_int['<PAD>'],
target_vocab_to_int['<PAD>'])):
_, loss = sess.run(
[train_op, cost],
{input_data: source_batch,
targets: target_batch,
lr: learning_rate,
target_sequence_length: targets_lengths,
source_sequence_length: sources_lengths,
keep_prob: keep_probability})
if batch_i % display_step == 0 and batch_i > 0:
batch_train_logits = sess.run(
inference_logits,
{input_data: source_batch,
source_sequence_length: sources_lengths,
target_sequence_length: targets_lengths,
keep_prob: 1.0})
batch_valid_logits = sess.run(
inference_logits,
{input_data: valid_sources_batch,
source_sequence_length: valid_sources_lengths,
target_sequence_length: valid_targets_lengths,
keep_prob: 1.0})
train_acc = get_accuracy(target_batch, batch_train_logits)
valid_acc = get_accuracy(valid_targets_batch, batch_valid_logits)
print('Epoch {:>3} Batch {:>4}/{} - Train Accuracy: {:>6.4f}, Validation Accuracy: {:>6.4f}, Loss: {:>6.4f}'
.format(epoch_i, batch_i, len(source_int_text) // batch_size, train_acc, valid_acc, loss))
# Save Model
saver = tf.train.Saver()
saver.save(sess, save_path)
print('Model Trained and Saved')


Explosion Through Numbers
Pick a conversion type
BMI
Inches - Feet
Weight
Inches
Height in Inches
Your answer is...


WITNESS LIST Economic Development Committee February 18, 1997-9:00A SB 382 For: Barnett, Mary Jane (self), Denton Campbell, Stephen (TX Physical Therapy Asc), Austin Clayton, Nan (AARP), Austin Hilsabeck, Elizabeth (self), Austin McGiffert, Lisa (Consumers Union), Austin Oliver-Dalton, Renee' (self), Lakeway Schwartz, Jonas (Disb Policy Constortion), Austin Speight, Susan (TX Asn Marr/Fam Therapy), Dickinson Taylor Fenwick, Denise (self), Houston Uhouse, Kathy (self), Austin Woolbert, Lynda (Adv.Pract.Nurses Coaltn), West Columbia Registering, but not testifying: For: Avery, BJ (TX Optometric Assoc), Austin Banzer, Susan (NASW), Ft Worth Bell, Emily (Social Work Students), Ft Worth Bendeck, Al (TX Acad of Phys Assist), Lubbock Byrd, Johanna (NASW/TCU), Ft. Worth Camicia, Jennifer (NASW), Ft Worth Campbell, Eddie (TAMU-C), Sulphur Springs Carr, Sara (Health Care & Insurance), Greenville Dalrymple, Bill (self), Austin Darrouzet, Michael J. (Dallas County Med.Soc.), Dallas Davis, Eural (NASW), Austin Devall, Christine (Mental Health Assoc, TX), Austin Dr. Price, Clift (TX Pediatric Society), Austin Dr. Sebern, Margaret (Health Care Consumers), Houston Goolsby, Gloria M. (Health Care Consumers), Sugarland Hall, Tricia (TX Urological Society), Austin Hiser,Deborah (Advocacy, Inc.), Austin Horton, Leslie (NASW), Ft Worth Jackson, Lisa (TX Neurological Society), Austin Jackson, Lisa (TX Soc.of Plastic Surgn), Austin Jaggers, Donna (HMO carriers), Mt Vernon Manuel, Jennifer (TCU), Ft Worth McCulley, Rita K. (self), Rowlett Noey, Henry E. (TX Bus.  Group on Health), Austin Ponce, Griselda (self), Austin Rigling, Paula (TX Soc Gastro & Endosc), Austin Schulle, Gerhardt (TX Ophthalmic Profess.), Austin Szabo, JoAnn (self), Rosharon Talley, Sheri (TX Academy of Fam Phys.), Ft Stochton Truesdell, Laurie (self), Mesquite White, Dale L. (TX Chiropractic Assoc), Ft Worth Word, J.P. (TX Chiropractic Assoc), Austin Younger, Linda (self), Burleson On: Hamilton, Tyrette (TDI), Austin Myron, Rhonda (TDI), Austin Seely, Peggy (TX Dept on Aging), Austin Written materials submitted: For: Cernoch, Jennifer M. (TX Respite Resrc Netwrk), San Antonio Graves, Tim (TX Health Care Assoc), Austin Heinzmann, Carl (NASW/TX), San Marcos Magruder, Mary Jo (TX Planning Council), Austin Wyllie, Richard J. (NASW), Austin SB 384 For: Barnett, Mary Jane (self), Denton Campbell, Stephen E. (TX Physical Therapy Asc), Ausin Clayton, Nan (AARP), Austin Darrouzet, Micheal J. (Dallas County Med. Soc.), Dallas Dr. Gessler, Don (THMOA), Austin Dr. Scranton, Maria (self), Austin Hilsabeck, Elizabeth (self), Austin Hiser, Deborah C. (Advocacy, Inc.), Austin McDonald, Pat (self), Ft Worth McGiffert, Lisa (Consumers Union), Austin Oliver-Dalton, Renee' (self), Lakeway Schwartz, Jonas (Disb Policy Consortium), Austin Speight, Susan (TX Asn Marr/Fam Therapy), Dickinson Talley, Sheri (TX Academy of Fam Phys), Ft Stochton Taylor Fenwick, Denise (self), Houston Uhouse, Kathy (self), Austin Vasek, Heather (TX Assoc for Home Care), Austin Weaver, Lee Ann (self), Irving Woolbert, Lynda (Adv.Pract.Nurses Coaltn), West Columbia Against: Hood, Dwight E. (Private HealthCare Syst), Irving On: Comola, Jon (Blue Cross/HMO Blue), Austin Fazen, Marianne (TX Business Grp on Hlth), Dallas Registering, but not testifying: For: Avery, BJ (TX Optometric Assoc), Austin Banzer, Susan (NASW), Ft Worth Barron, Connie (TX Medical Assoc), Austin Bell, Emily (Social Work Students), Ft Worth Bendeck, Al (TX Acad of Phys Assist), Lubbock Byrd, Johanna (NASW/TCU), Ft Worth Camicia, Jennifer (NASW), Ft Worth Campbell, Eddie (TAMU-C), Sulpher Springs Carr,Sara (Health Care & Insurance), Greenville Dalrymple, Bill (self), Austin Davis, Eural (NASW), Austin Devall, Christine (Mental Health Assoc, TX), Austin Dr. Price, Clift (TX Pediatric Society), Austin Dr. Sebern Margaret (Health Care Consumers), Houston Effenberger, Barbara (TX Mental Health Assoc), Seguin Goolsby, Gloria M. (Health Care Consumers), Sugarland Hall, Tricia (TX Urological Society), Austin Horton, Leslie (NASW), Ft Worth Jackson, Lisa (TX Neurological Society), Austin Jackson, Lisa (TX Soc.of Plastic Surgn), Austin Jaggers, Donna (HMO Carriers), Mt Vernon Manuel, Jennifer (TCU), Ft Worth McCulley, Rita K. (self), Rowlett McIntosh, Ann (Clinical Social Work-TX), Austin Noey, Henry E. (TX Bus. Group on Health), Austin Ponce, Griselda (self), Austin Rigling, Paula (TX Soc Gastro & Endosc), Austin Szabo, JoAnn (self), Rosharon Truesdell, Laurie (self), Mesquite White, Dale L. (TX Chiropractic Assoc), Ft Worth Word, J.P. (TX Chiropractic Assoc), Austin Younger, Linda (self), Burleson On: Myron, Rhonda (TDI), Austin Rummel, Leah (TDI), Austin Seely, Peggy (TX Dept. on Aging), Austin Written materials submitted: For: Cernoch, Jennifer C. (TX Respite Resrc Netwrk), San Antonio Graves, Tim (TX Health Care Assoc), Austin Heinzmann, Carl (NASW/TX), San Marcos Magruder, Mary Jo (TX Planning Council), Austin Wyllie, Richard J. (NASW), Austin On: Dr. Bast, Robert C. (MD Anderson Cancer Cntr), Houston SB 385 For: Barnett, Mary Jane (self), Denton Campbell, Stephen (TX Phisical Therapy Asc), Austin Clayton, Nan (AARP), Austin Darrouzet, Michael J. (Dallas County Med. Soc.), Dallas Dr. Burns, Dianna M. (TX Medical Association), San Antonio Dr. Doucett, Daniel W. (College Emer Physicians), San Antonio Dr. Scranton, Maria (self), Austin Dr. Vaclav, Mizhael (TX Dental Assoc), Amarillo Field Stephenson, Kathy (self), Austin Hilsabeck, Elizabeth (self), Austin Hiser, Deborah C. (Advocacy, Inc), Austin Hoffman, Jane (ABC Cancer Groups), Fentress Kloster, Jeff (PCA Health Plans of TX), Austin McDonald, Pat (self), Ft Worth McGiffert, Lisa (Consumers Union), Austin Oliver-Dalton Renee' (self), Lakeway Schwartz, Jonas (Disab Policy Consortium), Austin Speight, Susan (TX Asc Marr/Fam Therapy), Dickenson Talley, Sheri (TX Academy of Fam Phys), Ft Stochton Taylor Fenwick, Denise (self), Houston Uhouse, Kathy (self), Austin Vasek, Heather (TX Assoc for Home Care), Austin Weaver, Lee Ann (self), Irving Woolbert, Lynda (Adv.Pract.Nurses Coaltn), West Columbia On: Comola, Jon (Blue Cross/ HMO Blue), Austin Fazen, Marianne (TX Business Health Grp), Dallas Registering, but not testifying: For: Avery, BJ (TX Optometric Assoc), Austin Banzer, Susan (NASW), Ft Worth Bell, Emily (Social Work Students), Ft Worth Bendeck, Al (TX Academy of Phys Asst), Lubbock Byrd, Johanna (NASW/TX), Ft Worth Camicia, Jennifer (NASW), Ft Worth Campbell, Eddie (TAMU-C), Sulpher Springs Carr, Sara (Health Care & Insurance), Greenville Carruth, Dolores (TMA), Irving Dalrymple, Bill (self), Austin Davis, Eural (NASW), Austin Devall, Christine (Mental Health Assoc-TX), Austin Dr. Price, Clift (TX Pediatric Society), Austin Dr. Sebern, Margaret (Health Care Association), Houston Effenberger, Barbara (TX Mental Health Assoc), Seguin Goolsby, Gloria M. (Health Care Consumer), Sugarland Hall, Tricia (TX Urological Society), Austin Horton, Leslie (NASW), Ft Worth Jackson, Lisa (TX Neurological Society), Austin Jackson, Lisa (TX Soc of Plastic Surgn), Austin Jaggers, Donna (HMO Carriers), Mt Vernon Manuel, Jennifer (TCU), Ft Worth McCulley, Rita K. (self), Rowlett Moore, Alan T. (TMA; TSP), Austin Ponce, Griselda (self), Austin Rigling, Paula (TX Soc Gastro & Endosc), Austin Schulle, Gerhardt (TX Ophthalmic Profess.), Austin Seely, Peggy (TX Dept. of Aging), Austin Szabo, JoAnn (self), Rosharon Truesdell, Laurie (self), Mesquite White, Dale L. (TX Chiropractic Assoc), Ft Worth Word, J.P. (TX Chiropractic Assoc.), Austin Younger, Linda (self), Burleson On: Dr. Guckian, James (UT System), Austin Montemayor, Jose (TDI), Austin Myron, Rhonda (TDI), Austin Rummel, Leah (TDI), Austin Written materials submitted: For: Cernoch, Jennifer M. (TX Respite Resrc Netwrk), San Antonio Dr. Bast, Robert C. (MD Anderson Cancer Cntr), Houston Graves, Tim (TX Health Care Assoc), Austin Heinzmann, Carl (NASW/TX), San Marcos Magruder, Mary Jo (TX Planning Council), Austin Wyllie, Richard J. (NASW), Austin SB 386 For: Barnett, Mary Jane (self), Denton Boyle, Daniel J. (TX Medical Association), San Antonio Campbell, Stephen E. (TX Physical Therapy Asc), Austin Clayton, Nan (AARP), Austin Darrouzet, Michael J. (Dallas County Med. Soc.), Dallas Dr. Hausner, Richard J. (TMA), Houston Dr. Kottman, Robert (College of Emerg. Phys.), Austin Glasgow, Bob (TX Medical Association), Austin Hilsabeck, Elizabeth (self), Austin McDonald, Pat (self), Ft Worth McGiffert, Lisa (Consumers Union), Austin Oliver-Dalton, Renee' (self), Lakeway Schwartz, Jonas (Disb Policy Consortium), Austin Silvas, Inez (self), San Antonio Speight, Susan (TX Asc Marr/Fam Therapy), Dickinson SIlvas, Luisa (self), San Antonio Talley, Sheri (TX Acad Fam Physicians), Ft Stochton Taylor Fenwick, Denise (self), Houston Uhouse, Kathy (self), Austin Vasek, Heather (TX Assoc for Home Care), Austin Woolbert, Lynda (Adv.Pract.Nurses Coaltn), West Columbia Young, George Parker (self), Ft Worth Against: Burner, Burnie (TX Prof.Benefit Admin.), Austin Cannon, James W. (self), Austin Davis, Will D. (TX Life Ins. Assoc), Austin Herzog, Robin (Small Business/TABCC), Austin Kloster, Jeff (TX HMO Association), Austin Youngblood, Katherine (Coalition-Quality Hlth), Houston On: Comola, Jon (Blue Cross/HMO Blue), Austin Perdue, Jim (TTLA), Houston Registering, but not testifying: For: Avery, BJ (TX Optometric Assoc.), Austin Banzer, Susan (NASW), Ft Worth Bell, Emily (Social Work Students), Ft Worth Bendeck, Al (TX Acad of Phys Assist.), Lubbock Byrd, Johanna (NASW/TCU), Ft Worth Camicia, Jennifer (NASW), Ft Worth Campbell, Eddie (TAMU-C), Sulpher Springs Carr, Sara (Health Care Insurance), Greenville Carruth, Dolores (self), Irving Dalrymple, Bill (self), Austin Darrouzet Micheal J. (Dallas County Med. Soc.), Dallas Davis, Eural (NASW), Austin Devall, Christine (Mental Health Assoc), Austin Dr Sebern, Margaret (Health Care Consumers), Houston Dr. Price, Clift (TX Pediatric Assoc.), Austin Dr. Scranton, Maria (self), Austin Effenberger, Barbara (TX Mental Health Assoc.), Seguin Field Stephenson, Kathy (self), Austin Goolsby, Gloria M. (Health Care Consumers), Sugarland Hall, Tricia (TX Urological Society), Austin Hiser, Deborah C. (Advocacy, Inc.), Austin Horton, Leslie (NASW), Ft Worth Jackson, Lisa (TX Neurological Society), Austin Jackson, Lisa (TX Society Plastic Surg), Austin Jaggers, Donna (HMO Carriers), Mt Vernon Manuel, Jennifer (TCU), Ft Worth McCulley, Rita M. (self), Rowlett McIntosh, Ann (Clinical Social Work-TX), Austin Ponce, Griselda (self), Austin Rigling, Paula (TX Soc Gastro & Endosco), Austin Szabo, Joann (self), Rosharon Truesdell, Laurie (self), Mesquite White, Dale L. (TX Chiropractic Assoc.), Ft Worth Word, J.P. (TX Chiropractic Assoc.), Austin Younger, Linda (self), Burleson Against: Berkefelt, Christine (Dow Chemical), Houston Cartwright, Robert M. (Human Resrc Strategic), Pflugerville McMullen, Bud (GM), Austin Thompson, Jay (TLIA, TLROA, TAIO), Austin Weems, Rodney (Adams Extract Co., Inc.), Austin On: Noey, Henry E. (TX Bus. Group on Health), Austin Reeser, Rose Ann (TDI), Austin Seely, Peggy (TX Dept. of Aging), Austin Written materials submitted: For: Cernoch, Jennifer M. (TX Respite Resrc Netwrk), San Antonio Dr. Bast, Robert C. (MD Anderson Cancer Cntr), Houston Heinzmann, Carl (NASW), San Marcos Magruder, Mary Jo (TX Planning Council), Austin Wyllie, Richard J. (NASW), Austin SB 387 For: Barnett, Mary Jane (self), Denton Bendeck, Al (Tx Acad of Phys Assist.), Lubbock Campbell, Stephen E. (TX Physical Therapy Asc), Austin Clayton, Nan (AARP), Austin Dr. Gessler, Don (THMOA), Austin Field Stephenson, Kathy (self), Austin Hilsabeck, Elizabeth (self), Austin Hiser, Deborah C. (Advocacy, Inc.), Austin McGiffert, Lisa (Consumers Union), Austin Oliver-Dalton, Renee' (self), Lakeway Schwartz, Jonas (Disb Policy Consortium), Austin Speight, Susan (TX Asc Marr/Fam Therapy), Dickinson Taylor-Fenwick, Denise (self), Houston Uhouse, Kathy (self), Austin Vasek, Heather (TX Assoc for Home Care), Austin White, Dale L. (TX Chiropractic Assoc.), Ft Worth Woolbert, Lynda (Adv.Pract.Nurses Coaltn), West Columbia Registering, but not testifying: For: Avery, BJ (TX Optometric Assoc), Austin Banzer, Susan (NASW), Ft Worth Barron, Connie (TX Medical Association), Austin Bell, Emily (Social Work Students), Ft Worth Byrd, Johanna (NASW/TCU), Ft Worth Camicia, Jennifer (NASW), Ft Worth Campbell, Eddie (TAMU-C), Sulpher Springs Carr, Sara (Health Care & Insurance), Greenville Dalrymple, Bill (self), Austin Darrouzet, Michael J. (Dallas County Med Soc), Dallas Davis, Eural (NASW), Austin Devall, Christine (TX Mental Health Assoc.), Austin Dr. Price, Clift (TX Pediatric Assoc.), Austin Dr. Sebern, Margaret (Health Care Consumers), Houston Effenberger, Barbara (TX Mental Health Assoc), Seguin Goolsby, Gloria M. (Health Care Consumers), Sugarland Hall, Tricia (TX Urological Society), Austin Horton, Leslie (NASW), Ft Worth Jackson, Lisa (TX Neurological Society), Austin Jackson, Lisa (TX Soc of Plastic Surgn), Austin Jaggers, Donna (HMO Carriers), Mt Vernon Manuel, Jennifer (TCU), Ft Worth McCulley, Rita M. (self), Rowlett McDonald, Pat (self), Ft Worth Ponce, Griselda (self), Austin Rigling, Paula (TX Soc Gastro & Endosco), Austin Stephenson Field, Kathy (self), Austin Szabo, Joann (self), Rosharon Talley, Sheri (TX Acad Fam Physicians), Ft Stochton Truesdell, Laurie (self), Mesquite Word, J.P. (TX Chiropractic Assoc.), Austin Younger, Linda (self), Burleson On: Bordelon, Rod (OPIC), Austin Myron, Rhonda (TDI), Austin Noey, Henry E. (TX Bus. Group on Health), Austin Seely, Peggy (TX Department of Aging), Austin Written materials submitted: For: Cernoch, Jennifer M. (TX Respite Resrc Netwrk), San Antonio Graves, Tim (TX Health Care Assoc.), Austin Heinzmann, Carl (NASW), San Marcos Magruder, Mary Jo (TX Planning Council), Austin Wyllie, Richard J. (NASW), Austin SB 585 For: Hiser, Deborah C. (Advocacy, Inc.), Austin McGiffert, Lisa (Consumers Union), Austin Talley, Sheri (TX Academy of Fam Phys), Ft Stochton On: Christian, Elizabeth (TX Women's Coalition), Austin Comola, Jon (Blue Cross/HMO Blue), Austin Dr. Kuhlmann, Terry (TX OB/GYN), Austin Registering, but not testifying: For: Avery, BJ (TX Optometric Assoc), Austin Bendeck, Al (TX Acadamy Phys Assist), Lubbock Byrd, Johanna (NASW/TCU), Ft Worth Dalrymple, Bill (self), Austin Devall,Christine (TX Mental Health Assoc), Austin Szabo, JoAnn (self), Rosharon On: Dr. Anderson, Ralph (self), Ft Worth Myron, Rhonda (TDI), Austin Noey, Henry E. (TXBus Group on Health), Austin


Sheba
Pop
!
The official Sheba
Bancho
extension
Guest
Profile Stats
Leaderboards
Performance Calculator
Sign out


Readme¶
_ _ _ _ _ _ _
| | | (_) | | (_) |
| |__ __ _ _ __ __| |_| |_ _ __ _ _| |_| |__
| '_ / _` | '_ / _` | | __| '_ \| | | | | | '_
| |_) | (_| | | | | (_| | | |_| |_) | |_| | | | |_) |
|_.__/ \__,_|_| |_|\__,_|_|\__| .__/ \__, |_|_|_.__/
| | __/ |
|_| |___/
A lightweight python library for bandit algorithms
Introduction¶
This library is intended to enable fast and robust comparison between different bandit algorithms. It provides following features:
object-oriented design: this allows unnecessary environmental information to be hidden from learners. Besides, it is easy extend the library and implement new algorithms.
multi-process support: it is not uncommon to run a game muitiple repetitions. One can run multiple repetitions simultaneously with this feature.
friendly runtime information: useful information is provided when necessary, which reduces the difficulty of debug.
The library consists of four submodules and they are arms
, bandits
, learners
and protocols
respectively, among which protocols
are those used to coordinate the interactions between the learner and the bandit environment.
Implemented Policies¶
Single player protocol¶
Multi-armed bandit¶
Goal |
Policies |
|---|---|
Maximize total rewards |
|
Best arm identification with fixed budget |
|
Best arm identification with fixed confidence |
|
MNL bandit¶
Goal |
Policies |
|---|---|
Maximize total rewards |
|
Thresholding bandit¶
Goal |
Policies |
|---|---|
Make all answers correct |
|
Linear bandit¶
Goal |
Policies |
|---|---|
Maximize total rewards |
|
Colaborative learning protocol¶
Multi-armed bandit¶
Goal |
Policies |
|---|---|
Best arm identification with fixed time |
|
For a detailed description, please check the documentation.
Getting Started¶
Installing¶
Python version requirement: 3.7 or above.
Virtual environment: in order not to pollute your own environment, it is suggested to use python virtual environment. The following commands show the details to create and activate a virtual environment.
# Create a virtual environment `.env`
python3 -m venv .env
# Activate the environment
source .env/bin/activate
Then you can run the following command to install the banditpylib
library.
make install
After finishing the usage of the library, you can use deactivate
to deactive the virtual environment and what’s more, you can safely delete the whole .env
directory for cleanup.
The following shows other useful make commands.
make test
run tests
make lint
run pylint and mypy
make clean
clean cache files
make fix
run yapf to format all .py files
make all
run make fix, make test, and make lint
We use pylint
and mypy
to check the code style. Please make sure no errors occur with make all
when submitting a PR.
Example¶
Suppose we want to run algorithms Epsilon Greedy, UCB and Thompson Sampling, which aim to maximize the total rewards, against the ordinary multi-armed bandit environment with 3 Bernoulli arms. The following code blocks show the main logic.
Set up bandit environment¶
# Real means of Bernoulli arms
means = [0.3, 0.5, 0.7]
# Create Bernoulli arms
arms = [BernoulliArm(mean) for mean in means]
# Create an ordinary multi-armed bandit environment
bandit = MultiArmedBandit(arms=arms)
Set up learners¶
# Create learners aiming to maximize the total rewards
learners = [EpsGreedy(arm_num=len(arms)),
UCB(arm_num=len(arms)),
ThompsonSampling(arm_num=len(arms))]
Set up simulator and play the game¶
# Horizon of the game
horizon = 2000
# Set up simulator using single-player protocol
game = SinglePlayerProtocol(bandit=bandit, learners=learners)
# Record intermediate regrets after these horizons
intermediate_horizons = list(range(0, horizon+1, 50))
# Start playing the game and for each setup we run 200 trials
game.play(trials=200,
intermediate_horizons=intermediate_horizons,
horizon=horizon)
The following figure shows the simulation results.
Please check this notebook to figure out more details.
Bibtex Citation¶
@misc{BanditPyLib,
title = {{BanditPyLib: a lightweight python library for bandit algorithms}},
author = {Chester Holtz and Chao Tao and Guangyu Xi},
year = {2020},
url = {https://github.com/Alanthink/banditpylib},
howpublished = {Online at: \url{https://github.com/Alanthink/banditpylib}},
note = {Documentation at \url{https://alanthink.github.io/banditpylib-doc}}
}
License¶
This project is licensed under the MIT License - see the LICENSE.txt file for details.
Acknowledgments¶
This project is inspired by libbandit and banditlib which are both c++ libraries for bandit algorithms.
This readme file is following the style of README-Template.md.
The title is generated by TAAG.


I have just posted a comment on the "inputs and feeds" thread without any (obvious) issue and a red banner appeared at the top of the thread telling me
"Unable to send e-mail. Please contact the site administrator if the problem persists"
A little unusual since I wasn't sending an email, not sure if "the problem" refers to not being able to send email or red warnings popping up when they shouldn't, either way Mr site administrator, consider yourself contacted :-)
Thought I should post as I could of sworn this happened the other day as well, but I wasn't sure, just caught a glimpse as the page changed.
Paul
Re: Unable to send e-mail. Please contact the site administrator if the problem persists
I've seen that many times for a few days now - but I've ignored it. I was assuming it was unable to notify people who have notifications turned off.
Re: Unable to send e-mail. Please contact the site administrator if the problem persists
After I'd released a comment from the moderation queue:
The user who had posted the comment has both "Receive content follow-up notification e-mails" and "Receive email notification for incoming private messages" ticked.
Re: Unable to send e-mail. Please contact the site administrator if the problem persists
This should now be fixed. Please confirm. It was due to us moving email providers and needing to update SMTP details. The forum should noe be able to send notifications emails. Am I correct that this feature has been turned off by default? Would you like it turned on? I think it's possible to adjust on a per account basis. I know I personally don't need any more email! However it could ber useful for users who dabble in the odd forum thread now and again. Its easy to post a reply then forget about it!
What do you think?
Re: Unable to send e-mail. Please contact the site administrator if the problem persists
Hi Glyn, I'll keep an eye open for it, it doesn't happen every time or to order, so only time will tell :-)
Couldn't agree more about not needing more mail, it would however be nice to get PM notifications, as sometimes it can just appear rude when they go unnoticed. Quite often I sneak a peak at the forum from another (non-private) device without logging in which can stretch out the duration between "logged-in" visits.
Paul
Re: Unable to send e-mail. Please contact the site administrator if the problem persists
I too don't need notifying of every thread I respond to! But many users who dip in only occasionally or are interested in only one or two threads would find it useful - and indeed have complained that notifications weren't working (no, I think it was a case of it didn't work rather than they were turned off by default).
Re: Unable to send e-mail. Please contact the site administrator if the problem persists
I'll try turning on email notifications for PM's and comments, you can turn off comment notifications in your account settings. I'll send you a PM to test :-)
Re: Unable to send e-mail. Please contact the site administrator if the problem persists
I didn't receive an email for the PM.
Paul
Re: Unable to send e-mail. Please contact the site administrator if the problem persists
Nor did I, but I did receive an email notification letting me know that you replied to my post on this thread!
Re: Unable to send e-mail. Please contact the site administrator if the problem persists
I didn't get any emails or a PM :-(
was I supposed to ?
Paul
Re: Unable to send e-mail. Please contact the site administrator if the problem persists
Yah, PM messages seem to be working. You might need to turn it on at the bottom of your account setting page.
I'll send you another PM
Re: Unable to send e-mail. Please contact the site administrator if the problem persists
PM 1 email 0
I had previously confirmed the email PM notifications option was checked, having just had another look to see if your changes had globally reset the option for all users I found that section has changed dramatically and was set to no notifications. I have now reset to email all PM's (there are now several options not just on or off) could you PM again?
( is it too early for a WoooHoo! )
Paul
Re: Unable to send e-mail. Please contact the site administrator if the problem persists
No email after a little over 2 hours from the "Admins & Moderators" PM...
(but I too have "follow-up notification" off and had nothing selected in PMs: "Send me an email" (not even "Never"!), I've now set it to "only once".
Re: Unable to send e-mail. Please contact the site administrator if the problem persists
For existing users the default setting is for notifications to be off for PM messages but can be turned on in settings. This now works!
Re: Unable to send e-mail. Please contact the site administrator if the problem persists
Receiving email alerts for PMs Ok now.
Paul
Re: Unable to send e-mail. Please contact the site administrator if the problem persists
Yep I've had a flurry of notifications for PM's now, thanks guys.
Good to see attachments working too, well done Glyn !
Paul


public interface SseEventSource
extends java.lang.AutoCloseable
incoming Server-Sent Events
.
SSE event source instances of this class are thread safe. To build a new instance, you can use the
SseEventSource.target(endpoint)
factory method to get a new event
source builder that can be further customised and eventually used to create a new SSE event source.
Once a SseEventSource
is created, it can be used to open a connection
to the associated
web target
. After establishing the connection, the event source starts processing any incoming
inbound events. Whenever a new event is received, an Consumer<InboundSseEvent>#accept(InboundSseEvent)
method is invoked on any registered event consumers.
The SseEventSource
supports automated recuperation from a connection loss, including
negotiation of delivery of any missed events based on the last received SSE event id
field value, provided
this field is set by the server and the negotiation facility is supported by the server. In case of a connection loss,
the last received SSE event id
field value is sent in the
"Last-Event-ID"
HTTP
request header as part of a new connection request sent to the SSE endpoint. Upon a receipt of such reconnect request, the SSE
endpoint that supports this negotiation facility is expected to replay all missed events. Note however, that this is a
best-effort mechanism which does not provide any guaranty that all events would be delivered without a loss. You should
therefore not rely on receiving every single event and design your client application code accordingly.
By default, when a connection to the SSE endpoint is lost, the event source will wait 500 ms
before attempting to reconnect to the SSE endpoint. The SSE endpoint can however control the client-side retry delay
by including a special retry
field value in any sent event. JAX-RS SseEventSource
tracks any
received SSE event retry
field values set by the endpoint and adjusts the reconnect delay accordingly,
using the last received retry
field value as the reconnect delay.
In addition to handling the standard connection loss failures, JAX-RS SseEventSource
behaves differently to various
HTTP response status codes and headers:
"Content-Type"
header of "text/event-stream": This is normal
operation. onEvent
is invoked for each event. onComplete
is invoked when there are no more
events. onError
is invoked only if an unrecoverable error occurs during processing."Content-Type"
header: This is an
error condition. onError
is invoked.onComplete
is invoked."Retry-After"
header set to a valid value: This indicates
that the server is unavailable, but that the client should reconnect later. No consumers are invoked unless the client
event source is closed, prior to reconnecting (resulting in onComplete
invocation). After the specified
delay, the client should automatically attempt to reconnect which will result in a new response."Retry-After"
header: This is an error
condition. onError
is invoked.onError
is invoked.
In the case of an error condition response, the Throwable
passed to the onError
consumer
should be a WebApplicationException containing the invalid Response
object.
Note that if, for any of the registered event consumers, an invocation of Consumer<InboundSseEvent>#accept(InboundSseEvent)
method throws an exception, this is not an error condition.
Thus onError
is not invoked and event processing is not stopped.
Users are encouraged to handle exceptions on their own as part of the event processing logic.
| Modifier and Type | Interface and Description |
|---|---|
static class |
SseEventSource.Builder
JAX-RS
SseEventSource builder class. |
| Modifier and Type | Method and Description |
|---|---|
default void |
close()
Close this event source.
|
boolean |
close(long timeout,
java.util.concurrent.TimeUnit unit)
Close this event source and wait for the internal event processing task to complete for up to the specified amount of
wait time.
|
boolean |
isOpen()
Check if this event source instance has already been
opened . |
void |
open()
Open the connection to the supplied SSE underlying
web target and start processing incoming
events . |
void |
register(java.util.function.Consumer<InboundSseEvent> onEvent)
Register a
InboundSseEvent consumer. |
void |
register(java.util.function.Consumer<InboundSseEvent> onEvent,
java.util.function.Consumer<java.lang.Throwable> onError)
Register
InboundSseEvent and Throwable consumers. |
void |
register(java.util.function.Consumer<InboundSseEvent> onEvent,
java.util.function.Consumer<java.lang.Throwable> onError,
java.lang.Runnable onComplete)
Register
InboundSseEvent and Throwable consumers and onComplete callback. |
static SseEventSource.Builder |
target(WebTarget endpoint)
Create a new
event source builder that provides convenient way how to configure and
fine-tune various aspects of a newly prepared event source instance. |
void register(java.util.function.Consumer<InboundSseEvent> onEvent)
InboundSseEvent
consumer.
Given consumer is invoked once per each received event.
onEvent
- event consumer.java.lang.IllegalArgumentException
- when the provided parameter is null
.void register(java.util.function.Consumer<InboundSseEvent> onEvent, java.util.function.Consumer<java.lang.Throwable> onError)
InboundSseEvent
and Throwable
consumers.
Event consumer is invoked once per each received event, Throwable
consumer is invoked invoked upon a
unrecoverable error encountered by a SseEventSource
.
onEvent
- event consumer.onError
- error consumer.java.lang.IllegalArgumentException
- when the any of the provided parameters is null
.void register(java.util.function.Consumer<InboundSseEvent> onEvent, java.util.function.Consumer<java.lang.Throwable> onError, java.lang.Runnable onComplete)
InboundSseEvent
and Throwable
consumers and onComplete callback.
Event consumer is invoked once per each received event, Throwable
consumer is invoked invoked upon a
unrecoverable error encountered by a SseEventSource
, onComplete callback is invoked after a successful
connection and when there are no further events to be received. Note that the onComplete callback will not be
invoked if the onError callback has been invoked.
onEvent
- event consumer.onError
- error consumer.onComplete
- onComplete handler.java.lang.IllegalArgumentException
- when the any of the provided parameters is null
.static SseEventSource.Builder target(WebTarget endpoint)
event source builder
that provides convenient way how to configure and
fine-tune various aspects of a newly prepared event source instance.endpoint
- SSE streaming endpoint. Must not be null
.java.lang.NullPointerException
- in case the supplied web target is null
.void open()
web target
and start processing incoming
events
.java.lang.IllegalStateException
- in case the event source has already been opened earlier.boolean isOpen()
opened
.true
if this event source is open, false
otherwise.default void close()
The method will wait up to 5 seconds for the internal event processing tasks to complete.
close
in interface java.lang.AutoCloseable
boolean close(long timeout, java.util.concurrent.TimeUnit unit)
The method blocks until the event processing task has completed execution after a shutdown request, or until the timeout occurs, or the current thread is interrupted, whichever happens first.
In case the waiting for the event processing task has been interrupted, this method restores the
interrupt
flag on the thread before returning false
.
timeout
- the maximum time to wait.unit
- the time unit of the timeout argument.true
if this executor terminated and false
if the timeout elapsed before termination or the
termination was interrupted.


CordaSerializationTransformRenames(vararg value: CordaSerializationTransformRename)
This annotation is used to mark a class as having had multiple elements renamed as a container annotation for instances of CordaSerializationTransformRename, each of which details an individual rename.


About us
I am M.Nouman and I am the student of BSCS and I am just making this website for practice purpose.
Secondly I post this website because I thought that people need to learn about communication skills as
well as me too at the same place.
You can contact me personally by following ways:
Email:
<EMAIL_ADDRESS>Phone:
03402453982
Home


{{ user.full_name }} {% if user.is_verified %}{% endif %}
{{ user.user_type }}
-
{% if user.user_type == 'Driver' %}
- Rides shared {{ user.no_of_rides_shared }} {% endif %}
- Rides taken {{ user.no_of_request_completed }}
Getting Started
Welcome
What you can do...
- Search Rides
Are you looking to find a cheaper means of road transport, Search for rides going to your destination or passing your route. You can also put out a ride broadcast to your followers or anyone wiling to pick you up. Now you can find some new favourite place to chill out,you have no longer got excuse for not travelling and discovering.
- View Requested Rides
You can view all rides that you have requested for and their details.
{% if request.user.user_type == 'Driver' %}
- Add a Ride
You need to add a ride to your collection. Fill in the form and you are ready to start sharing rides.
 Share your ride today,and forget about this problems. REMEMBER, Only share rides with people you trust.
- View Shared Rides
You can view records of all requested rides so far
{% endif %}


Professional
Motivated and driven life-long learner. Strong communication and leadership skills both internally and in client facing roles. See LinkedIn or Resume above.
Developer (in training)
Learning full stack from my home-office. My aim is to bridge the communication gap between technical and business minded team members, by leveraging technical understanding with the ability to communicate business value. Check out my portfolio or github profile!
Adventurer
If I'm not in the office, you can find me on the water or in the woods. Years of experience in personal and professional guiding and exploring. Check out my adventure Gallery!


My name is Robert McCarthy and I am an urbanite.
I believe that large cities and the collective human energy they
contain are the lifeblood of culture and creativity on Planet Earth.
Along those lines, I am interested in any information or process
that makes city-living more enjoyable, enriching and efficient.
Cities moves quickly. You should too.
Quickercity is my vehicle.
Copyright (c) 2014


CTET admit card 2019 to be released on ctet.nic.in soon: Know details
CTET 2019 admit card has not been released by CBSE yet. Candidates are advised to check ctet.nic.in for details
by BS Web TeamCTET admit card 2019: Central Board of Secondary Education (CBSE), which conducts CTET exams will release the CTET Admit Card 2019 for the Central Teacher Eligibility Test in the third week of November. While some news portals claim that the admit card has been released, candidates are advised to check CTET's official website - ctet.nic.in for actual information and not go by rumours. Once CTET Admit Card 2019 for December exam is released, candidates can download it from the official website. Do note that CBSE would not be mailing CTET admit cards to anybody. This will be the 13th edition of the exam. The exam is conducted in 20 languages.
Steps to download CTET 2019 admit card
Step 1: Visit the official website - ctet.nic.in
Step 2: Click on the CTET admit card link
Step 3: Enter the required credentials
Step 4: Click on the 'submit'
Step 5: Your CTET admit card will appear on the screen. Download it and take a print out for future reference.
CTET exam pattern
The CTET exam comprises two papers - Paper I is meant for Primary stage (for classes 1 to 5) teachers and Paper II is meant for Elementary stage (for classes 6 to 8) teachers. Candidates who fulfill the eligibility criteria for both the papers can take both the exams.
The syllabus for the CTET includes Child Development & Pedagogy, Mathematics, Social Studies and Environmental Studies. There are two language papers as well.
CTET certificate validity
The validity of CTET certificate is for 7 years.
About CTET:
The CTET certificate is the minimum eligibility to get the teaching job. Once the candidate gets the certificate, he or she can apply for teacher vacancies released by different schools like KVS, NVS Army Teacher, ERDO, etc.


Today
Phil Coulson
We have a situation
Phil Coulson
We have a situation
Phil Coulson
We have a situation
Yesterday
Phil Coulson
We have a situation
Phil Coulson
We have a situation
Phil Coulson
We have a situation


---
layout: post
section-type: post
title: 'Marble Testing Epics with Redux Observable'
date: 2020-11-01 17:30:22.000000000 +00:00
categories: Code
---
Before Redux Observable, I found testing asynchronous side effects (redux-thunk) very difficult. Our code was always messy, relying on weird mocks or
[tightly coupled to redux dispatcher](https://redux.js.org/recipes/writing-tests). Moreover, it would always involve a callback or an await through every step. Something like this:
{% highlight javascript %}
describe('Todo actions', () => {
it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', async () => {
// setup actions: have a list of expected actions
const expectedActions = [
{ type: types.FETCH_TODOS_REQUEST },
{ type: types.FETCH_TODOS_SUCCESS, payload: { todos: ['do something'] } }
]
// mock entire store
const store = mockStore({ todos: [] })
await store.dispatch(actions.fetchTodos());
// return of async actions
expect(store.getActions()).toEqual(expectedActions)
});
});
{% endhighlight %}
While this is brief and simple, it does not indicate when these actions were fired, just the order. If you add a timeout or debounce to your thunk, these tests become very complicated.
Whereas with Redux Observable, I can declare time, order, and various sequences all in the same test. Say we want to simulate a _300ms_ delay between request and success:
{% highlight javascript %}
import { of } from 'rxjs'
import marbles from 'rxjs-marbles';
describe('Todo actions', () => {
it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', marbles((m) => {
// setup initiator actions and state
const actions$ = m.cold('a', { a: { type: types.FETCH_TODOS_REQUEST } })
const state$ = of({ todos: [] })
// write expectation of result - loading action, a 300ms delay, and result action
const expectedActions = m.cold('a 300ms b',
{
a: { type: types.FETCH_TODOS_LOADING },
b: { type: types.FETCH_TODOS_SUCCESS, payload: { todos: ['do something'] } }
}
)
m.expect(fetchTodos$(actions$, state$)).toBeObservable(expectedActions)
}));
});
{% endhighlight %}
Notice, that the 'a 300ms b' declaration. The a represents the loading action at the first millisecond and the 300ms wait is just after.
Then at 302 ms, we have the b action which maps to the success action.
This marble syntax allows us to directly declare the behaviour and expectations of our observable over time, allowing us to clearly describe what is happening.
How Redux Observable Works
[Redux observable](https://redux-observable.js.org/) is a separate running process that starts at the beginning of your application. It does not run on a middleware system like [redux thunk](https://github.com/reduxjs/redux-thunk). It is a set of observables merged together into a stream that listens to the actions dispatched by the store (dispatch).
Similar to redux, every action dispatched triggers a series of processes.
Unlike redux, Redux observable uses a set of merged observables to process the actions all at once.
[Observables](https://rxjs-dev.firebaseapp.com/guide/observable) are lazy Push collections of multiple values, a representation of values over time. Some people call these streams. While this may be incorrect, it is similar in behaviour. Data flows through these observables from an input to an output.
In Redux Observable, these observables are called *[Epics](https://redux-observable.js.org/docs/basics/Epics.html)* - a function which takes a stream of actions and returns a stream of actions.
These actions are then committed to the store. For every action one can return a set of actions (0 or more).
See a Todos example below:
{% highlight javascript %}
export const fetchTodos$ = (actions$: Observable, state$: Observable): Observable =>
actions$.pipe(
// listen to request action dispatch
ofType(types.FETCH_TODOS_REQUEST),
switchMap(() => {
return concat(
// first, fire off loading action
of({ type: types.FETCH_TODOS_LOADING }),
// then, wait 300ms and fire off success action
of({
type: types.FETCH_TODOS_SUCCESS,
payload: { todos: ['do something'] }
}).pipe(delay(300))
)
})
)
export const todoEpic = combineEpics(fetchTodos$, ...otherEpics)
{% endhighlight %}
Above, we continuously listen to the FETCH_TODOS_REQUEST action by filtering it out of the actions stream with the [ofType](https://redux-observable.js.org/docs/basics/Epics.html) operator.
Then, we use the switchMap operator to map to an inner observable (concat) which sends out multiple actions.
The [switchMap](https://www.learnrxjs.io/learn-rxjs/operators/transformation/switchmap) operator allows us to cancel the previous inner observable if it is running, and then create a fresh one.
This is very useful for cancelling ajax requests.
[Concat](https://www.learnrxjs.io/learn-rxjs/operators/combination/concat) then allows us to first emit one action and then emit another delayed action.
Notice, that both of these are inside a stream [of](https://www.learnrxjs.io/learn-rxjs/operators/creation/of), so one can add delays/timers/debouncing to this if needed.
Any action that is an output of this Observable will be dispatched to the store and the cycle continues to whatever epic is listening.
How Marble Testing Works
[Marble testing](https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/testing/marble-testing.md) is a mechanism that allows us to test how observables behave over time.
This allows one to declaratively test the values an observable emits over time.
I won't cover marble testing in depth, but highlight its importance and advantages over testing promises, functions, callbacks.
If you want an indepth introduction, I highly recommend reading this [article](https://medium.com/@bencabanes/marble-testing-observable-introduction-1f5ad39231c) afterward.
Some basics
A marble test is a comparison of one observables emitted values to another expected observables emitted values.
These values are representated by ticks (millisecond length) in time like below and mapped characters:
{% highlight javascript %}
m.cold('--') // 2 milliseconds pass nothing is emitted and the observable has not completed
m.cold('--|') // 2 milliseconds pass and on the 3rd millisecond the observable completes.
m.cold('(a|)', { a: 'Hi' }) // 1 millisecond passes, emitting a, and completing the observable all at the same time.
{% endhighlight %}
- The tick '-' means no value was a emitted in a millisecond and the observable has not completed.
- The pipe '|' means the observable completed at this millisecond.
- 'a' represents a defined emitted value. One can use the entire alphabet if needed.
- Anything inside brances () mean multiple things happened inside this millisecond such as multiple events were fired at once.
Why is this awesome?
While it may be difficult to understand it all first, it's definitely a lot more declarative and easier to debug than any other known asynchronous testing I've seen.
Marble testing makes TDD very easy and straightforward. Declare the marbles first then implement the solution in the epic.
Also *[RXJS](https://www.learnrxjs.io/)* is incredibly powerful and built for complex applications. With it,
these one-line operators allow the following:
- request/event cancellation ([switchMap](https://www.learnrxjs.io/learn-rxjs/operators/transformation/switchmap))
- debouncing ([debounceTime](https://www.learnrxjs.io/learn-rxjs/operators/filtering/debouncetime))
- diffing ([distinctUntilChanged](https://www.learnrxjs.io/learn-rxjs/operators/filtering/distinctuntilchanged))
- racing ([race](https://www.learnrxjs.io/learn-rxjs/operators/combination/race))
- waiting until a condition has been met or redux state to exist ([skipUtil/skipWhile](https://www.learnrxjs.io/learn-rxjs/operators/filtering/skipwhile))
- buffering, collecting values until expectation met ([buffer](https://www.learnrxjs.io/learn-rxjs/operators/transformation/buffer))
Give it a go and let me know how RXJS, Marble testing, and Redux observable work out for you!
Cheers!


Region
West Bellevue
East Bellevue
West Seattle
Central Seattle
Southeast Seattle
North Seattle
Mercer Island
Kirkland
Redmond
Sammamish/Issaquah
Sort by
Listing Price
Year Built
Listing Date
Square Footage
Resale ROI (experimental)
Rental ROI (experimental)
Contains Keywords (,)


GENERAL CAUTION：Read this Agreement carefully and follow its instructions. If you do not understand any thing in this Agreement then ask for an explanation to be given. If you do not understand or agree with any explanation given then it is best to consult you solicitor before signing this Agreement.
Information note：Where any thing in this Agreement is followed by a number in brackets (e.g.(1)), then immediately read the explanatory note that bears that number in Schedule 4 to this Agreement. Where any thing in this Agreement refers to a Schedule to this Agreement, then immediately read that Schedule.
The Schedules to this Agreement form part of this Agreement.
This Agreement shall be void if the occupation permit for the Property does not include or allow domestic purpose or use.
(if applicable)
Agency
Schedule 1
Duties of Agent
Schedule 2
Commission to be Paid by Vendor
Schedule 3
Interests in Property
Schedule 4
Explanatory Notes


sfa.algorithms.np module¶
-
class
sfa.algorithms.np.
NetworkPropagation
(abbr)[source]¶ Bases:
sfa.base.Algorithm
- A base class that defines the basic functionality of
network propagation algorithms.
- Attributes
- W
abbr
Abbreviation or symbol representing this item.
- b
data
The object of
sfa.base.Data
.name
Full name or description of this item.
params
The object of
sfa.base.ParameterSet
.result
The object of
sfa.base.Result
.
Methods
apply_inputs
(self, inds, vals)compute
(self, b)Process the assigned data
compute_batch
(self)Process the assigned data that contains a batch data.
Initialize the basal activity, \(b\).
initialize_network
(self)Initialize the data structures related to network.
prepare_exact_solution
(self)Prepare to get the matrix for the exact solution.
Prepare to get the solution from the iterative method.
propagate_exact
(self, b)Obtain the activity at steady-state based on the exact solution of network propagation.
propagate_iterative
(self, W, xi, b[, a, …])Compute network propagation based on the iterative method.
apply_perturbations
copy
initialize
-
W
¶
-
b
¶
-
compute
(self, b)[source]¶ - Process the assigned data
with the given basal activity, \(b\).
- Parameters
- bnumpy.ndarray
1D array of basal activity.
- Returns
- xnumpy.ndarray
1D-array object of activity at steady-state.
-
compute_batch
(self)[source]¶ Process the assigned data that contains a batch data. The result is stored in
result
member.
-
propagate_exact
(self, b)[source]¶ Obtain the activity at steady-state based on the exact solution of network propagation.
- Parameters
- bnumpy.ndarray
1D array of basal activity.
- Returns
- xnumpy.ndarray
The exact solution of the activity at steady-state in 1D array.
-
propagate_iterative
(self, W, xi, b, a=0.5, lim_iter=1000, tol=1e-05, get_trj=False)[source]¶ Compute network propagation based on the iterative method. This method should be used if we want to obtain the trajectory.
- Parameters
- W: numpy.ndarray
2D array for weight matrix.
- xi: numpy.ndarray
1D array for initial state.
- b: numpy.ndarray
1D array for basal activity.
- a: real number, optional
Hyperparameter, \(\alpha\), ~ (0, 1). The default value is 0.5.
- lim_iter: int, optional
Number of maximum iterations in the iterative method. Computation terminates when the iteration reaches
lim_iter
. The default value is 1000.- tol: float, optional
Tolerance for terminating iteration. Iteration continues, if Frobenius norm of \(x(t+1)-x(t)\) is greater than
tol
. The default value is 1e-5.- get_trj: bool, optional
Determine whether the trajectory of the state is returned. If get_trj is true, the trajectory is returned.
- Returns
- xnumpy.ndarray
1D array of the activity after the computation.
- trjnumpy.ndarray
2D array where the row represents a state of the activity.
-
class
sfa.algorithms.np.
NetworkPropagationParameterSet
[source]¶ Bases:
sfa.base.ParameterSet
An object that deals with the parameters of
sfa.algorithms.np.NetworkPropagation
base algorithm.- Attributes
alpha
floatHyperparameter, \(\alpha\) ~ (0, 1).
lim_iter
intNumber of maximum iterations in the iterative method.
apply_weight_norm
boolApply the link weight normalization.
use_rel_change
boolUse relative change for prediction.
exsol_forbidden
boolForbid the propagation computation based on the exact solution.
no_inputs
boolDo not apply the effects of inputs in a given network.
Methods
initialize
(self)Initialize the parameters with default values.
-
alpha
¶ Hyperparameter, \(\alpha\) ~ (0, 1). It controls the portion of signal flow in determining the activity. The default value is 0.5.
-
apply_weight_norm
¶ Apply the link weight normalization.
-
exsol_forbidden
¶ Forbid the propagation computation based on the exact solution. In other words, use the iterative method.
-
lim_iter
¶ Number of maximum iterations in the iterative method.
-
no_inputs
¶ Do not apply the effects of inputs in a given network.
-
use_rel_change
¶ Use relative change for prediction.