| Package | Description |
|---|---|
| ch.rabanti.nanoxlsx4j |
| Modifier and Type | Method and Description |
|---|---|
static Range |
Range.buildRange(Address startAddress,
Address endAddress)
Method to build a range object from two addresses.
|
static Range |
Range.buildRange(int startColumn,
int startRow,
int endColumn,
int endRow)
Method to build a range object from zwo column and two row numbers.
|
Range |
Worksheet.getAutoFilterRange()
Gets the range of the auto filter.
|
Range |
Worksheet.getSelectedCells()
Gets the range of selected cells of this worksheet.
|
static Range |
Cell.resolveCellRange(String range)
Resolves a cell range from the format like A1:B3 or AAD556:AAD1000
|
| Modifier and Type | Method and Description |
|---|---|
Map<String,Range> |
Worksheet.getMergedCells()
Gets the merged cells (only references) as map with the cell address as key and the range object as value
|
| Modifier and Type | Method and Description |
|---|---|
static Cell |
BasicFormulas.Average(Range range)
Returns a cell with a average formula
|
static Cell |
BasicFormulas.Average(Worksheet target,
Range range)
Returns a cell with a average formula
|
static Cell |
BasicFormulas.Max(Range range)
Returns a cell with a max formula
|
static Cell |
BasicFormulas.Max(Worksheet target,
Range range)
Returns a cell with a max formula
|
static Cell |
BasicFormulas.Median(Range range)
Returns a cell with a median formula
|
static Cell |
BasicFormulas.Median(Worksheet target,
Range range)
Returns a cell with a median formula
|
String |
Worksheet.mergeCells(Range cellRange)
Merges the defined cell range
|
static Cell |
BasicFormulas.Min(Range range)
Returns a cell with a min formula
|
static Cell |
BasicFormulas.Min(Worksheet target,
Range range)
Returns a cell with a min formula
|
void |
Worksheet.setSelectedCells(Range range)
Sets the selected cells on this worksheet
|
static Cell |
BasicFormulas.Sum(Range range)
Returns a cell with a sum formula
|
static Cell |
BasicFormulas.Sum(Worksheet target,
Range range)
Returns a cell with a sum formula
|
static Cell |
BasicFormulas.VLookup(Address address,
Range range,
int columnIndex,
boolean exactMatch)
Function to generate a Vlookup as Excel function
|
static Cell |
BasicFormulas.VLookup(Object number,
Range range,
int columnIndex,
boolean exactMatch)
Function to generate a Vlookup as Excel function
|
static Cell |
BasicFormulas.VLookup(Object number,
Worksheet rangeTarget,
Range range,
int columnIndex,
boolean exactMatch)
Function to generate a Vlookup as Excel function
|
static Cell |
BasicFormulas.VLookup(Worksheet queryTarget,
Address address,
Worksheet rangeTarget,
Range range,
int columnIndex,
boolean exactMatch)
Function to generate a Vlookup as Excel function
|
Copyright © 2019. All rights reserved.


class: center, middle, inverse, title-slide # Prediction ### Applied Machine Learning with R
Basel R Bootcamp
### January 2019 --- layout: true
        www.therbootcamp.com      Applied Machine Learning with R | January 2019
 --- # Prediction is...

 "Prediction is very difficult, especially if it's about the future." Nils Bohr, Nobel Laureate in Physics
 "An economist is an expert who will know tomorrow why the things he predicted yesterday didn't happen today." Evan Esar
 "Forecasting [prediction] is the art of saying what will happen, and then explaining why it didn't!" Anonymous ---

Source: Medium.com

 --- class: middle, center # What is model prediction? Model prediction (aka, testing) is the process of computing a model's predictions on new <high>test data</high>.

 # What is test data? Test data is a separate, <high>'hold-out' data</high> set that the model <high>never saw during training</high> --- # Model Training  --- # Model Testing  --- # Why do we separate training from testing? .pull-left35[
 Just because a model can <high>fit past data well</high> (high training accuracy), does not necessarily mean that it will <high>predict new data well</high> (high testing accuracy).

"An economist is an expert who will know tomorrow why the things he predicted yesterday didn't happen today."

 Evan Esar
 ] .pull-right6[

 ] ---

"Can you come up with a model that will perfectly fit the training criterion but is worthless in predicting test data?"

 .pull-left45[ <high>Training data</high>
 | id|sex | age|fam_history |smoking | criterion| |--:|:---|---:|:-----------|:-------|---------:| | 1|m | 45|No |FALSE | 0| | 2|m | 43|Yes |FALSE | 1| | 3|f | 40|Yes |FALSE | 1| | 4|m | 51|Yes |FALSE | 1| | 5|m | 44|No |TRUE | 0| ] .pull-right45[ <high> Test data</high>
 | id|sex | age|fam_history |smoking |criterion | |--:|:---|---:|:-----------|:-------|:---------| | 91|m | 51|Yes |TRUE |? | | 92|f | 47|No |TRUE |? | | 93|m | 39|No |TRUE |? | | 94|f | 51|Yes |TRUE |? | | 95|f | 50|Yes |FALSE |? | ] --- .pull-left4[

 # Overfitting When a model is consistently <high>less accurate in predicting future data</high> than in <high>fitting training data</high>, this is called <high>overfitting</high> Overfitting typically occurs when a model 'mistakes' random noise for a predictable signal ] .pull-right55[

 <img src="https://cdn-images-1.medium.com/max/1600/1*SBUK2QEfCP-zvJmKm14wGQ.png" alt="hackernoon.com" />
hackernoon.com

 <img src="https://cdn-images-1.medium.com/max/1200/1*cdvfzvpkJkUudDEryFtCnA.png" alt="Medium.com" width="90%" />
Medium.com

 ] --- # Overfitting  --- # Overfitting .pull-left45[ ### How do we account for overfitting? Always evaluate models based on their performance on new, unseen test data *Never evaluate models based only on training accuracy!* Use models with <high>regularization</high> terms, which explicitly punish models for being too complex. Use fitting methods such as <high>cross-validation</high> to find optimal regularization values. We will learn about these methods in a future session! ] .pull-right5[  ] --- # How do I get separate training and test data? .pull-left5[ If you don't have two naturally occurring distinct training and test dataset, you can <high>randomly split</high> a dataset into an <high>X% training</high> set and <high>1-X% testing</high> set. The `caret` function `createDataPartition()` helps you do this automatically. Natural examples |Domain|Training|Test| |:-------|:------|:------| |Stock prediction|2017 Trends | 2019 Trends| |Medical diagnosis| Patients from Hospital A| Patients from Hospital B| |Crime rates|Statistics from City X|Statistics from City Y| ] .pull-right45[  ] --- class: center, middle # Two new models enter the ring... --- class: center, middle
Regression
 <high>
Decision Trees
</high>
Random Forests
 --- # Decision Trees .pull-left4[ In [decision trees](https://en.wikipedia.org/wiki/Decision_tree), the criterion is modeled as a <high>sequence of logical YES or NO questions</high>.

 ] .pull-right55[ <high>Grow Decisions Trees</high> by splitting features that maximize *Node Purity*.

  ] --- # Decision Trees .pull-left4[ In [decision trees](https://en.wikipedia.org/wiki/Decision_tree), the criterion is modeled as a <high>sequence of logical YES or NO questions</high>.

 ] .pull-right55[ <high>Fit a Decision Tree</high> in `caret` using `method = "rpart"`. ```r # Fit a decision tree with a defined cp = .10 train(form = income ~ ., data = baselers, method = "rpart", # Decision Tree trControl = ctrl, tuneGrid = expand.grid(cp = .10)) # cp ``` ] --- # Decision Trees .pull-left45[ ### Complexity Parameter Decision trees have a <high>complexity parameter</high> called `cp`. The `cp` parameter controls how complex (i.e.; large) trees are allowed to grow - <high>Small</high> cp (< 0.01) = <high>Complex</high> Trees - <high>Large</high> cp (> 0.10) = <high>Simple</high> Trees There is no "one" best value of `cp` -- the best value of cp depends on your needs and your dataset! ] .pull-right5[  ] --- # Decision Trees .pull-left45[ ### Complexity Parameter Decision trees have a <high>complexity parameter</high> called `cp`. The `cp` parameter controls how complex (i.e.; large) trees are allowed to grow - <high>Small</high> cp (< 0.01) = <high>Complex</high> Trees - <high>Large</high> cp (> 0.10) = <high>Simple</high> Trees There is no "one" best value of `cp` -- the best value of cp depends on your needs and your dataset! ] .pull-right5[ ### Decision Trees in Caret: rpart When fitting a decision tree, the `cp` parameter can be defined by the user in the `tuneGrid` argument: ```r # Fit a decision tree with a defined cp = .10 train(form = income ~ ., data = baselers, method = "rpart", # Decision Tree trControl = ctrl, tuneGrid = expand.grid(cp = .10)) # cp ``` - `cp` can also be optimally determined through methods such as <high>cross-validation</high>, which we will learn later ] --- class: center, middle
Regression

Decision Trees
 <high>
Random Forests
</high> --- # Random Forest .pull-left4[ In [Random Forest](https://en.wikipedia.org/wiki/Random_forest), the criterion is modeled as the <high>aggregate prediction of a large number of decision trees</high> each based on different features.

 Source
 ] .pull-right55[ In Random Forests, we create a large set of <high>diverse trees</high> that can be aggregated into one <high>Wisdom of Crowds</high> judgment.  ] --- # Random Forest .pull-left4[ In [Random Forest](https://en.wikipedia.org/wiki/Random_forest), the criterion is modeled as the <high>aggregate prediction of a large number of decision trees</high> each based on different features.

 Source
 ] .pull-right55[ To <high>fit a random forest</high> in caret, use `method = "rf"`. ```r # Fit a random forest with a defined mtry = 3 train(form = income ~ ., data = baselers, method = "rf", # Random Forest trControl = ctrl, tuneGrid = expand.grid(mtry = 3)) ``` ] --- # Random Forest .pull-left4[ ### Diversity Parameter: mtry Random Forests have a <high>diversity parameter</high> called <high>mtry</high> Technically, this controls how many features are randomly considered at each split of the trees - Small mtry (~ 1) = Diverse Forest - Large mtry (> 5) = Similar Forest There is no "one" best value of `mtry` -- the best value of `mtry` depends on your needs and your dataset! ] .pull-right55[  ] --- # Random Forest .pull-left4[ ### Diversity Parameter: mtry Random Forests have a <high>diversity parameter</high> called <high>mtry</high> Technically, this controls how many features are randomly considered at each split of the trees - Small mtry (~ 1) = Diverse Forest - Large mtry (> 5) = Similar Forest There is no "one" best value of `mtry` -- the best value of `mtry` depends on your needs and your dataset! ] .pull-right55[ When fitting a random forest, the `mtry` parameter can be defined by the user in the `tuneGrid` argument. ```r # Fit a random forest with a defined mtry = 2 train(form = income ~ ., data = baselers, method = "rpart", # Decision Tree trControl = ctrl, tuneGrid = expand.grid(mtry = 2)) # mtry ``` - `mtry` can also be optimally determined through methods such as <high>cross-validation</high>, which we will learn later ] --- class: center, middle

 # Evaluating model predictions with caret  --- # Predict new data with predict() .pull-left45[ To <high>test model predictions</high> with `caret`, all you need to do is get a vector of predictions from a new dataframe `newdata` using the `predict()` function: ```r # Get predictions for test data! predict(mod, newdata = data_test) ```
 |argument|description| |:----|:-----| |object| A machine learning / statistical object created from `caret`, ...| |newdata|A dataframe of new data| This returns a vector of predicted values for your new data! ] .pull-right5[ <high>Get predictions</high>, use `predict(mod, newdata = data_test)` ```r # Load training and test data data_train <- read_csv("1_Data/XXX_train.csv") data_test <- read_csv("1_Data/XXX_test.csv") # Fit model to training data mod <- train(form = Y ~ ., method = "glm", data = data_train) # Get fitted values (for training data) mod_fit <- predict(mod) # Predictions for NEW data_test data! mod_pred <- predict(mod, newdata = data_test) ``` ] --- # Predict new data with predict() .pull-left45[ To <high>test model predictions</high> with `caret`, all you need to do is get a vector of predictions from a new dataframe `newdata` using the `predict()` function: ```r # Get predictions for test data! predict(mod, newdata = data_test) ``` |argument|description| |:----|:-----| |object| A machine learning / statistical object created from `caret`, ...| |newdata|A dataframe of new data| This returns a vector of predicted values for your new data! ] .pull-right5[ Compare predictions to the criterion with `postResample()` ```r # Define criterion criterion_train <- data_train$Y criterion_test <- data_test$Y # Fitting performance postResample(pred = mod_fit, obs = criterion_train) # RMSE Rsquared MAE #2.454015 0.848482 1.889584 # Prediction performance postResample(pred = mod_pred, obs = criterion_test) # RMSE Rsquared MAE #3.4763941 0.6977009 2.6764346 ``` ] --- # Split data with createDataPartition() .pull-left4[ Use `createDataPartition()` to <high>split a dataset</high> into separate training and test datasets ```r # Create a set of indices for random # selection of 70% of data createDataPartition(y = data$Y p = .7, list = FALSE) ``` |Argument|Description| |:----|:-----| |y| The criterion| |p|Percent of data to select| This returns a vector of indices you can then use to select rows (see right) ] .pull-right55[ Create separate `XX_train` and `data_test` datasets from a single 'large' dataset ```r # Set the randomisation seed to get the # same results each time set.seed(100) # Get indices for training index <- createDataPartition(y = baselers$income, p = .7, list = FALSE) # Create training data baselers_train <- baselers %>% slice(index) # Create test data baselers_test <- baselers %>% slice(-index) ``` ] --- .pull-left5[ # 5 steps with caret Step 0: Load training and test data (or create with `createDataPartition()`) ```r data_train <- read_csv("1_Data/XXX_train.csv") data_test <- read_csv("1_Data/XXX_test.csv") ``` Step 1: Define control parameters ```r # Use method = "none" for no advanced fitting ctrl <- trainControl(method = "none") ``` Step 2: Train model ```r mod <- train(form = Y ~ ., data = data_train, method = "My Favorite Model", trControl = ctrl, tuneGrid = expand.grid(mtry = 2)) ``` ] .pull-right45[

 Step 3: Explore ```r mod # Print object mod$finalModel # Final model ``` Step 4: Predict ```r rpart_pred <- predict(object = mod, newdata = data_test) ``` Step 5: Evaluate prediction accuracy ```r postResample(pred = rpart_pred, obs = data_test$Y) ``` ] --- class: middle, center
 Questions?

Practical


{% extends "base.html" %}
{% load static %}
{% load i18n %}
{% block head_title %}Huestions | Hard Questions | Have fun answering{% endblock %}
{% block borderless %}
{% if user.is_authenticated %}
{% else %}
{% trans "Yes, yes, Huestions is awesome" %}. {% trans "Let me login" %}. {% blocktrans %}I would take the advice{% endblocktrans %}. ({% trans "How is the sign held up?" %} 🤔) {% trans "Thanks for being part of this" %} 😉👍 🤯😁🤣
{% trans "We believe it is important to have fun on a daily basis. We suggest you do it here, answering lists of cool questions." %}
🦄✏🌈
{% trans "Create that list of questions that you know will be a hit with your friends." %}
📤🌎🙏
{% trans "Share the lists! Send it to that person" %} 😏
{% trans "Lists of Hard Questions!" %}
{% trans "Pizza or Burger? Super strength or Super speed? Dogs or Cats?"


Basic usage¶
First step¶
At first, you need to configure your database. Be sure that RethinkDB is launched and that you can access the service port.
By default, RethinkModel will check this environment variables:
RM_DBNAME
to set the database to use, default is “test”RM_HOST
default to “<IP_ADDRESS>”RM_PORT
default to 28015RM_USER
default to “admin” (the RethinkDB default user)RM_PASSWORD
default to empty string (the RethinkDB default)RM_TIMEOUT
default to 10 (in seconds)RM_SOFT_DELETE
with isFalse
by default
If you want to configure this in python, you can use the rethinkmodel.config()
function.
Create models¶
The basic usage is to create a class with annotations to declare fields to save.
There are 4 automatic fields comming from Model
class:
id
is set by RethinkDBcreated_at
when you save an object without id (create)updated_at
when you save an object with a given id (update)deleted_at
is set to deleteddatatime
when you delete the object, and if you setrethinkmodel.db.SOFT_DELETE
toTrue
# you must use typing
from typing import Type
from rethinkmodel import Model
class User(Model):
username: str
password: str
age: int
Rethink:Model automatically manages One to One and One to Many relations. The rule is to add an annotations that is Typed with a Model based class. The above example can help:
class Post(Model):
title: str
author: User # this will actually store the User.id
tags: str
class Product(Model):
name: Optional[str] # we can accept None
categories: List[str] # One to many
class Project(Model):
name: str
owner: Optional[User]
# this will save a list of User IDs
contributors: List[User]


Citizen Police Academy
Good Morning –
Looking for some professional Media assistance in marketing JPD’s Citizen Police Academy.
The dates for the Citizen Police Academy will be Thursday March 5th though April 30th. We will not have the academy on April 2th due to Easter/Spring break. The time is from 1830-2130 (3 hrs).
The application is attached and a rough draft of activities. We want to convey that the deadline is February 10th, as background checks are done on the participants.
Looking for: Website post with Link to application..(ASAP) G-10 Image/graphics for FB and Email blasts
It would be great to put it in the water billing and Your City as well. Please let me know if I can provide anything to facilitate this. Thanks for all you do for Public Safety.
Beth Purcell Public Information Officer Jacksonville Department of Public Safety Desk:<PHONE_NUMBER> Media Line:<PHONE_NUMBER>


Reports inspections that are missing an HTML description file, i.e. a file containing a text like this.
The
Create description file
quick-fix creates a template HTML description file.


About This small site is for me to record my experience both in work and life. With peace in mind, Be brave in "New World". Just meet you, Before the dawn. You can find me on Github or my Bitbucket.


Welcome To My Geocities Homepage
Under CONSTRUCTION
Visitor counter:
1234
Guestbook
Sign my
Guestbook!


The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
Cross-site scripting (XSS) vulnerabilities occur when:
There are three main kinds of XSS:
Reflected XSS (or Non-Persistent). The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content to a vulnerable web application, which is then reflected back to the victim and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces a victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the victim, the content is executed by the victim's browser.
Stored XSS (or Persistent). The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. At a later time, the dangerous data is subsequently read back into the application and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. For example, the attacker might inject XSS into a log message, which might not be handled properly when an administrator views the logs.
DOM-Based XSS. In DOM-based XSS, the client performs the injection of a script into the page; in the other types, the server performs the injection. DOM-based XSS generally involves a server-controlled, trusted script that is sent to the
client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker
could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim
into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks
less suspicious.
Cross-site scripting (XSS) is one of the most prevalent, obstinate, and dangerous vulnerabilities in web applications. It's pretty much inevitable when you combine the stateless nature of HTTP, the mixture of data and script in HTML, lots of data passing between web sites, diverse encoding schemes, and feature-rich web browsers. If you're not careful, attackers can inject Javascript or other browser-executable content into a web page that your application generates. Your web page is then accessed by other users, whose browsers execute that malicious script as if it came from you (because, after all, it *did* come from you). Suddenly, your web site is serving code that you didn't write. The attacker can use a variety of techniques to get the input directly into your server, or use an unwitting victim as the middle man in a technical version of the "why do you keep hitting yourself?" game.
The ways to check for Cross-Site Scripting are:
Automated Static Analysis. Use automated static analysis tools that target this type of weakness. Many modern techniques use data flow analysis to minimize the number of false positives. This is not a perfect solution, since 100% accuracy and coverage are not feasible, especially when multiple components are involved.
Black Box. Use the XSS Cheat Sheet [R.79.6] or automated test-generation tools to help launch a wide variety of attacks against your web application. The Cheat Sheet contains many subtle XSS variations that are specifically targeted against weak XSS defenses. With Stored XSS, the indirection caused by the data store can make it more difficult to find the problem. The tester must first inject the XSS string into the data store, then find the appropriate application functionality in which the XSS string is sent to other users of the application. These are two distinct steps in which the activation of the XSS can take place minutes, hours, or days after the XSS was originally injected into the data store.
To fix or prevent Cross-Site Scripting vulnerabilities:
Use a secure framework. Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples of libraries and frameworks that make it easier to generate properly encoded output include Microsoft's Anti-XSS library, the OWASP ESAPI Encoding module, and Apache Wicket.
Encode data. Understand the context in which your data will be used and the encoding that will be expected. This is especially important when transmitting data between different components, or when generating outputs that can contain multiple
encodings at the same time, such as web pages or multi-part mail messages. Study all expected communication protocols and data representations to determine the required encoding strategies.
For any data that will be output to another web page, especially any data that was received from external inputs, use the appropriate encoding on all non-alphanumeric characters. Parts of the same output document may require different encodings, which will
vary depending on whether the output is in the:
Validate all input. Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. This technique has limited effectiveness, but can be helpful when it is possible to store client state and sensitive information on the server side instead of in cookies, headers, hidden form fields, etc.
Use server-side security checks. For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Separate data and code. If available, use structured mechanisms that automatically enforce the separation between data and code. These mechanisms may be able to provide the relevant quoting, encoding, and validation automatically, instead of relying on the developer to provide this capability at every point where output is generated.
Use specific character encodings. For every web page that is generated, use and specify a character encoding such as ISO-8859-1 or UTF-8. When an encoding is not specified, the web browser may choose a different encoding by guessing which encoding is actually being used by the web page. This can cause the web browser to treat certain sequences as special, opening up the client to subtle XSS attacks. See CWE-116 for more mitigations related to encoding/escaping.
(Java Struts only) Use the bean's filter attribute. With Struts, you should write all data from form beans with the bean's filter attribute set to true.
Set the HttpOnly flag on cookies. To help mitigate XSS attacks against the user's session cookie, set the session cookie to be HttpOnly. In browsers that support the HttpOnly feature (such as more recent versions of Internet Explorer and Firefox), this attribute can prevent the user's session cookie from being accessible to malicious client-side scripts that use document.cookie. This is not a complete solution, since HttpOnly is not supported by all browsers. More importantly, XMLHTTPRequest and other powerful browser technologies provide read access to HTTP headers, including the Set-Cookie header in which the HttpOnly flag is set.
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. Do not rely exclusively on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). However, blacklists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if you are expecting colors such as "red" or "blue."
Use white-list input validation. When dynamically constructing web pages, use stringent whitelists that limit the character set based on the expected value of the parameter in the request. All input should be validated and cleansed, not just parameters that the user is supposed to specify, but all data in the request, including hidden fields, cookies, headers, the URL itself, and so forth. A common mistake that leads to continuing XSS vulnerabilities is to validate only fields that are expected to be redisplayed by the site. It is common to see data from the request that is reflected by the application server or the application that the development team did not anticipate. Also, a field that is not currently reflected may be used by a future developer. Therefore, validating ALL parts of the HTTP request is recommended. Ensure that you perform input validation at well-defined interfaces within the application. This will help protect the application even if a component is reused or moved elsewhere.
Use reference maps. When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs.
(Optional) Use a web application firewall. Use an application firewall that can detect attacks against this weakness. It can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth. An application firewall might not cover all possible input vectors. In addition, attack techniques might be available to bypass the protection mechanism, such as using malformed inputs that can still be processed by the component that receives those inputs. Depending on functionality, an application firewall might inadvertently reject or modify legitimate requests. Finally, some manual effort may be required for customization.
(PHP only) Do not use register_globals. If you are using PHP, configure your application so that it does not use register_globals. During implementation, develop your application so that it does not rely on this feature, but be wary of implementing a register_globals emulation that is subject to weaknesses such as CWE-95, CWE-621, and similar issues.


<%= course_name %>
semester: <%= semester %>
year: <%= year %>
course_name: <%= course_name %>
teacher: <%= teacher %>
school: <%= school %>
grade: <%= letter_grade %>
points_un_weighted: <%= points_un_weighted %>
honors_ap_credit: <%= honors_ap_credit %>
course website: <%= course_website %>


Cops kill 2 armed dealers, jail 10
by Alfred P. DalizonTWO armed drug trafficking suspects were killed in shootouts while 10 others were arrested in a string of anti-narcotics operations conducted by agents of the Bulacan Police Provincial Office on Tuesday and Wednesday, a report to Police Regional Office 3 director, Brigadier General Rhodel O. Sermonia said yesterday.
The slain suspects were identified as Mark Panganoron, a man included in the unified drug watch list of the Philippine Drug Enforcement Agency and the Philippine National Police and Mark Anthony Mallares.
According to San Jose del Monte City Police Station commander, Lieutenant Colonel Orlando Castil Jr., the two have just conspired to sell shabu to an undercover officer in Lot 46, Block 2, Towerville 6F, Barangay Gaya-gaya around 1:15 p.m. Monday when they sensed the ongoing buy-bust operation and engaged the lawmen in a firefight which resulted to their death.


Next Steps
In the example above the Oracle10Plugin is being used. Ebean tries to detect the
specific database based on the jdbc driver. If it can not, then the BasePlugin will
be used instead and you may need to configure it for the specific database.
If you are using Ebean in a Servlet Container refer to webapp_readme.txt
I recommend playing around with Ebean in just a normal application first.
3. Database Dictionary
Ebean makes significant use of the Database Meta data. This can normally be
very slow with some databases. Ebean speeds this up by serializing the
Database Meta data in a file.
If you change your schema you should delete this file forcing Ebean to rebuild it.
You will see INFO: DictionaryInfo deserialized from file... on startup when the
Database Meta data is being read from the file. Also note that this file grows
as more Meta Data is needed automatically. Aka it generally does not read your
entire database meta data but automatically gets more when it needs it.
INFO: DictionaryInfo deserialized from file -
[C:/devjava/project/appzsite/webapp/WEB-INF/data\primarydatabase.dictionary]
4. Log Files
Ebean will create transaction log files as well as the general avajeXXX.log.
The transaction logs can contain all the SQL, binding and summary information
and you can control this with system.properties.
The transaction logs will be a good place to look to see what Ebean is doing.
Implicit transactions are ones without any explicit beginTransaction() commitTransaction().
// Example: Implicit Transaction
Ebean.find(Topic.class, 1);
// Example: Explicit Transaction
Ebean.beginTransaction();
try {
Ebean.find(Topic.class,1);
Ebean.commitTransaction();
} finally {
Ebean.endTransaction();
}
Implicit transactions by default go into a shared log file as there is generally
only one find/save/delete statement.
Explicit transactions by default go into their own separate file as generally
there will be many statements and generally you wish to see them together and
without all the other transactions intermingled.
Initially this may be confusing and you can change the configuration so that all
the statements go into a single file.
To do this change system.properties...
ebean.transactionlogging.share=2
You can start creating your own annotated Entity Beans or use the Code Generator
to build them from your database schema. codegenerator_readme.txt
Without any Annotated Entity Beans you can still use FindByNative, UpdateSql,
CallableSql and also MapBeans.
You can run a query or an update using MapBeans like the ones below.
In this example there is a table in my database called "b_bug".
package test;
import java.util.List;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.FindByPredicates;
import com.avaje.ebean.MapBean;
public class TestQuery {
public static void main(String[] args) {
FindByPredicates find = new FindByPredicates();
find.setTableName("b_bug");
List list = Ebean.findList(find);
for (int i = 0; i < list.size(); i++) {
MapBean mp = (MapBean)list.get(i);
System.out.println(mp);
}
}
}
Update using a MapBean
package test;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.FindById;
import com.avaje.ebean.MapBean;
public class TestUpdate {
public static void main(String[] args) {
FindById find = new FindById();
find.setTableName("b_bug");
find.setId(1);
MapBean mb = (MapBean)Ebean.find(find);
mb.set("priority_code", "LOW");
Ebean.save(mb);
}
}
|


All members must have a public username and public
name.
You can use any name, as long as it meets our
Naming Guidelines.
Your imported data will be private by default.
An account should represent an individual – your personal data, or
someone for whom you are a legal guardian.
{% if form.non_field_errors %}


It’s easy to promise full coverage WiFi when conditions are perfect. But what about when everyone is home, your neighbor is streaming and every device is trying to connect? Plume is the only WiFi solution powered by the cloud, which means it can adapt to real life in real-time—ensuring every room and every device has a reliably fast connection today, tomorrow, and years from now.


What is Functional Programming?
January 31, 2016
In a way, functional programming is really just math. The first computer, the Turing Machine uses the same principals of computation as lambda calclus. Lamba calculus's most basic principals are variable binding, and subsitutuion., which you find in many programming languages.
Functional programming has two main principals. The first is that the data should be immutable. Usually in programming, this doesn't make sense because you want something that can be reapplied. In reality, if you need to use different data, just make a new instance of data. Secondly, the program should be stateless. This means that the program should have no knowledge of what happened in the past, and perform every task as if it were for the first time.
Using these two principals, the main idea here is to create simple repeatable actions that can be formed as a function. In order for the process to work, all functions must take at least one argument. All functions must also return either data, or another funtion. Lastly, you cannot use loops.
The benefits of function programming are simple. It is easier to read and understand. Because of the simpler logic, it will take you far less time to create, and be much easier to debug. The JavaScrit libraries Bacon.js as well as Underscore.js are based on function programming and are becoming more widespread.


#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
from __future__ import absolute_import
from cproton import PN_EOS, PN_OK, PN_SASL_AUTH, PN_SASL_NONE, PN_SASL_OK, PN_SASL_PERM, PN_SASL_SYS, PN_SASL_TEMP, \
PN_SSL_ANONYMOUS_PEER, PN_SSL_CERT_SUBJECT_CITY_OR_LOCALITY, PN_SSL_CERT_SUBJECT_COMMON_NAME, \
PN_SSL_CERT_SUBJECT_COUNTRY_NAME, PN_SSL_CERT_SUBJECT_ORGANIZATION_NAME, PN_SSL_CERT_SUBJECT_ORGANIZATION_UNIT, \
PN_SSL_CERT_SUBJECT_STATE_OR_PROVINCE, PN_SSL_MD5, PN_SSL_MODE_CLIENT, PN_SSL_MODE_SERVER, PN_SSL_RESUME_NEW, \
PN_SSL_RESUME_REUSED, PN_SSL_RESUME_UNKNOWN, PN_SSL_SHA1, PN_SSL_SHA256, PN_SSL_SHA512, PN_SSL_VERIFY_PEER, \
PN_SSL_VERIFY_PEER_NAME, PN_TRACE_DRV, PN_TRACE_FRM, PN_TRACE_OFF, PN_TRACE_RAW, pn_error_text, pn_sasl, \
pn_sasl_allowed_mechs, pn_sasl_config_name, pn_sasl_config_path, pn_sasl_done, pn_sasl_extended, \
pn_sasl_get_allow_insecure_mechs, pn_sasl_get_mech, pn_sasl_get_user, pn_sasl_get_authorization, pn_sasl_outcome, \
pn_sasl_set_allow_insecure_mechs, pn_ssl, pn_ssl_domain, pn_ssl_domain_allow_unsecured_client, pn_ssl_domain_free, \
pn_ssl_domain_set_credentials, pn_ssl_domain_set_peer_authentication, pn_ssl_domain_set_trusted_ca_db, \
pn_ssl_get_cert_fingerprint, pn_ssl_get_cipher_name, pn_ssl_get_peer_hostname, pn_ssl_get_protocol_name, \
pn_ssl_get_remote_subject, pn_ssl_get_remote_subject_subfield, pn_ssl_init, pn_ssl_present, pn_ssl_resume_status, \
pn_ssl_set_peer_hostname, pn_transport, pn_transport_attachments, pn_transport_bind, pn_transport_capacity, \
pn_transport_close_head, pn_transport_close_tail, pn_transport_closed, pn_transport_condition, \
pn_transport_connection, pn_transport_error, pn_transport_get_channel_max, pn_transport_get_frames_input, \
pn_transport_get_frames_output, pn_transport_get_idle_timeout, pn_transport_get_max_frame, \
pn_transport_get_pytracer, pn_transport_get_remote_idle_timeout, pn_transport_get_remote_max_frame, \
pn_transport_get_user, pn_transport_is_authenticated, pn_transport_is_encrypted, pn_transport_log, \
pn_transport_peek, pn_transport_pending, pn_transport_pop, pn_transport_push, pn_transport_remote_channel_max, \
pn_transport_require_auth, pn_transport_require_encryption, pn_transport_set_channel_max, \
pn_transport_set_idle_timeout, pn_transport_set_max_frame, pn_transport_set_pytracer, pn_transport_set_server, \
pn_transport_tick, pn_transport_trace, pn_transport_unbind
from ._common import millis2secs, secs2millis, unicode2utf8, utf82unicode
from ._condition import cond2obj, obj2cond
from ._exceptions import EXCEPTIONS, SSLException, SSLUnavailable, SessionException, TransportException
from ._wrapper import Wrapper
class TraceAdapter:
def __init__(self, tracer):
self.tracer = tracer
def __call__(self, trans_impl, message):
self.tracer(Transport.wrap(trans_impl), message)
[docs]class Transport(Wrapper):
"""
A network channel supporting an AMQP connection.
"""
TRACE_OFF = PN_TRACE_OFF
""" Turn logging off entirely. """
TRACE_DRV = PN_TRACE_DRV
""" Log driver-related events. """
TRACE_FRM = PN_TRACE_FRM
""" Log protocol frames going in and out of the transport. """
TRACE_RAW = PN_TRACE_RAW
""" Log raw binary data going in and out of the transport. """
CLIENT = 1
""" Transport mode is as a client. """
SERVER = 2
""" Transport mode is as a server. """
@staticmethod
def wrap(impl):
if impl is None:
return None
else:
return Transport(_impl=impl)
def __init__(self, mode=None, _impl=pn_transport):
Wrapper.__init__(self, _impl, pn_transport_attachments)
if mode == Transport.SERVER:
pn_transport_set_server(self._impl)
elif mode is None or mode == Transport.CLIENT:
pass
else:
raise TransportException("Cannot initialise Transport from mode: %s" % str(mode))
def _init(self):
self._sasl = None
self._ssl = None
self._reactor = None
self._connect_selectable = None
def _check(self, err):
if err < 0:
exc = EXCEPTIONS.get(err, TransportException)
raise exc("[%s]: %s" % (err, pn_error_text(pn_transport_error(self._impl))))
else:
return err
def _set_tracer(self, tracer):
pn_transport_set_pytracer(self._impl, TraceAdapter(tracer))
def _get_tracer(self):
adapter = pn_transport_get_pytracer(self._impl)
if adapter:
return adapter.tracer
else:
return None
tracer = property(_get_tracer, _set_tracer, doc="""
A callback for trace logging. The callback is passed the transport
and log message.
This can be useful in a debugging context as the log message will
be prefixed with the transport's identifier.
:param message: The message to be logged.
:type message: ``str``
"""
pn_transport_log(self._impl, message)
[docs] def require_auth(self, bool):
"""
Set whether a non-authenticated transport connection is allowed.
There are several ways within the AMQP protocol suite to get
unauthenticated connections:
- Use no SASL layer (with either no TLS or TLS without client certificates)
- Use a SASL layer but the ANONYMOUS mechanism
The default if this option is not set is to allow unauthenticated connections.
:param bool: ``True`` when authenticated connections are required.
:type bool: ``bool``
"""
pn_transport_require_auth(self._impl, bool)
@property
def authenticated(self):
"""
Indicate whether the transport connection is authenticated.
.. note:: This property may not be stable until the :const:`Event.CONNECTION_REMOTE_OPEN`
event is received.
:type: ``bool``
"""
return pn_transport_is_authenticated(self._impl)
[docs] def require_encryption(self, bool):
"""
Set whether a non encrypted transport connection is allowed
There are several ways within the AMQP protocol suite to get encrypted connections:
- Use TLS
- Use a SASL with a mechanism that supports security layers
The default if this option is not set is to allow unencrypted connections.
:param bool: ``True`` if encryption is required on this transport, ``False`` otherwise.
:type bool: ``bool``
"""
pn_transport_require_encryption(self._impl, bool)
@property
def encrypted(self):
"""
Indicate whether the transport connection is encrypted.
.. note:: This property may not be stable until the :const:`Event.CONNECTION_REMOTE_OPEN`
event is received.
:type: ``bool``
"""
return pn_transport_is_encrypted(self._impl)
@property
def user(self):
"""
The authenticated user.
On the client it will return whatever user was passed in to the
:attr:`Connection.user` attribute of the bound connection.
The returned value is only reliable after the ``PN_TRANSPORT_AUTHENTICATED``
event has been received.
:type: ``str``
"""
return pn_transport_get_user(self._impl)
[docs] def bind(self, connection):
"""
Assign a connection to the transport.
:param connection: Connection to which to bind.
:type connection: :class:`Connection`
:raise: :exc:`TransportException` if there is any Proton error.
"""
self._check(pn_transport_bind(self._impl, connection._impl))
[docs] def bind_nothrow(self, connection):
"""
Assign a connection to the transport. Any failure is
ignored rather than thrown.
:param connection: Connection to which to bind.
:type connection: :class:`Connection`
"""
pn_transport_bind(self._impl, connection._impl)
[docs] def unbind(self):
"""
Unbinds a transport from its AMQP connection.
:raise: :exc:`TransportException` if there is any Proton error.
"""
self._check(pn_transport_unbind(self._impl))
[docs] def trace(self, n):
"""
Update a transports trace flags.
The trace flags for a transport control what sort of information is
logged. The value may be :const:`TRACE_OFF` or any combination of
:const:`TRACE_DRV`, :const:`TRACE_FRM`, :const:`TRACE_RAW` using
a bitwise or operation.
:param n: Trace flags
:type n: ``int``
"""
pn_transport_trace(self._impl, n)
[docs] def tick(self, now):
"""
Process any pending transport timer events (like heartbeat generation).
This method should be called after all pending input has been
processed by the transport and before generating output. It returns
the deadline for the next pending timer event, if any are present.
.. note:: This function does nothing until the first data is read
from or written to the transport.
:param now: seconds since epoch.
:type now: ``float``
:return: If non-zero, then the monotonic expiration time of the next
pending timer event for the transport. The caller must invoke
:meth:`tick` again at least once at or before this deadline
occurs. If ``0.0``, then there are no pending events.
:rtype: ``float``
"""
return millis2secs(pn_transport_tick(self._impl, secs2millis(now)))
[docs] def capacity(self):
"""
Get the amount of free space for input following the transport's
tail pointer.
:return: Available space for input in bytes.
:rtype: ``int``
:raise: :exc:`TransportException` if there is any Proton error.
"""
c = pn_transport_capacity(self._impl)
if c >= PN_EOS:
return c
else:
return self._check(c)
[docs] def push(self, binary):
"""
Pushes the supplied bytes into the tail of the transport.
Only some of the bytes will be copied if there is insufficient
capacity available. Use :meth:`capacity` to determine how much
capacity the transport has.
:param binary: Data to be pushed onto the transport tail.
:type binary: ``bytes``
:raise: - :exc:`TransportException` if there is any Proton error.
- ``OverflowError`` if the size of the data exceeds the
transport capacity.
"""
n = self._check(pn_transport_push(self._impl, binary))
if n != len(binary):
raise OverflowError("unable to process all bytes: %s, %s" % (n, len(binary)))
[docs] def close_tail(self):
"""
Indicate that the input has reached End Of Stream (EOS).
This tells the transport that no more input will be forthcoming.
:raise: :exc:`TransportException` if there is any Proton error.
"""
self._check(pn_transport_close_tail(self._impl))
[docs] def pending(self):
"""
Get the number of pending output bytes following the transport's
head pointer.
:return: The number of pending output bytes.
:rtype: ``int``
:raise: :exc:`TransportException` if there is any Proton error.
"""
p = pn_transport_pending(self._impl)
if p >= PN_EOS:
return p
else:
return self._check(p)
[docs] def peek(self, size):
"""
Returns ``size`` bytes from the head of the transport.
It is an error to call this with a value of ``size`` that
is greater than the value reported by :meth:`pending`.
:param size: Number of bytes to return.
:type size: ``int``
:return: ``size`` bytes from the head of the transport, or ``None``
if none are available.
:rtype: ``bytes``
:raise: :exc:`TransportException` if there is any Proton error.
"""
cd, out = pn_transport_peek(self._impl, size)
if cd == PN_EOS:
return None
else:
self._check(cd)
return out
[docs] def pop(self, size):
"""
Removes ``size`` bytes of output from the pending output queue
following the transport's head pointer.
Calls to this function may alter the transport's head pointer as
well as the number of pending bytes reported by
:meth:`pending`.
:param size: Number of bytes to return.
:type size: ``int``
"""
pn_transport_pop(self._impl, size)
[docs] def close_head(self):
"""
Indicate that the output has closed.
This tells the transport that no more output will be popped.
:raise: :exc:`TransportException` if there is any Proton error.
"""
self._check(pn_transport_close_head(self._impl))
@property
def closed(self):
"""
``True`` iff both the transport head and transport tail are closed
using :meth:`close_head` and :meth:`close_tail` respectively.
:type: ``bool``
"""
return pn_transport_closed(self._impl)
# AMQP 1.0 max-frame-size
def _get_max_frame_size(self):
return pn_transport_get_max_frame(self._impl)
def _set_max_frame_size(self, value):
pn_transport_set_max_frame(self._impl, value)
max_frame_size = property(_get_max_frame_size, _set_max_frame_size, doc="""
The maximum size for transport frames (in bytes).
:type: ``int``
""")
@property
def remote_max_frame_size(self):
"""
The maximum frame size of a transport's remote peer (in bytes).
:type: ``int``
"""
return pn_transport_get_remote_max_frame(self._impl)
def _get_channel_max(self):
return pn_transport_get_channel_max(self._impl)
def _set_channel_max(self, value):
if pn_transport_set_channel_max(self._impl, value):
raise SessionException("Too late to change channel max.")
channel_max = property(_get_channel_max, _set_channel_max, doc="""
The maximum channel number that may be used on this transport.
.. note:: This is the maximum channel number allowed, giving a
valid channel number range of ``[0 .. channel_max]``. Therefore the
maximum number of simultaneously active channels will be
channel_max plus 1.
You can set this more than once to raise and lower
the limit your application imposes on max channels for this
transport. However, smaller limits may be imposed by Proton,
or by the remote peer.
After the ``OPEN`` frame has been sent to the remote peer,
further calls to this function will have no effect.
:type: ``int``
:raise: :exc:`SessionException` if the ``OPEN`` frame has already
been sent.
""")
@property
def remote_channel_max(self):
"""
The maximum allowed channel number of a transport's remote peer.
:type: ``int``
"""
return pn_transport_remote_channel_max(self._impl)
# AMQP 1.0 idle-time-out
def _get_idle_timeout(self):
return millis2secs(pn_transport_get_idle_timeout(self._impl))
def _set_idle_timeout(self, sec):
pn_transport_set_idle_timeout(self._impl, secs2millis(sec))
idle_timeout = property(_get_idle_timeout, _set_idle_timeout, doc="""
The idle timeout of the connection in seconds. A zero idle
timeout means heartbeats are disabled.
:type: ``float``
""")
@property
def remote_idle_timeout(self):
"""
Get the idle timeout for a transport's remote peer in
seconds.  If
not set, then a new session will be created using ``domain`` and
``session_details``.
:param domain: An SSL domain configuration object
:type domain: :class:`SSLDomain`
:param session_details: A unique identifier for the SSL session.
:type session_details: :class:`SSLSessionDetails`
:return: SSL session associated with this transport.
:rtype: :class:`SSL`
"""
# SSL factory (singleton for this transport)
if not self._ssl:
self._ssl = SSL(self, domain, session_details)
return self._ssl
def _get_condition(self):
return cond2obj(pn_transport_condition(self._impl))
def _set_condition(self, cond):
pn_cond = pn_transport_condition(self._impl)
obj2cond(cond, pn_cond)
condition = property(_get_condition, _set_condition, doc="""
Get additional information about the condition of the transport.
When a :const:`Event.TRANSPORT_ERROR` event occurs, this operation
can be used to access the details of the error condition.
See :class:`Condition` for more information.
:type: :class:`Condition`
""")
@property
def connection(self):
"""
The connection bound to this transport.
:type: :class:`Connection`
"""
from . import _endpoints
return _endpoints.Connection.wrap(pn_transport_connection(self._impl))
class SASLException(TransportException):
pass
[docs]class SASL(Wrapper):
"""
The SASL layer is responsible for establishing an authenticated
and/or encrypted tunnel over which AMQP frames are passed between
peers. The peer acting as the SASL Client must provide
authentication credentials. The peer acting as the SASL Server must
provide authentication against the received credentials.
"""
OK = PN_SASL_OK
AUTH = PN_SASL_AUTH
SYS = PN_SASL_SYS
PERM = PN_SASL_PERM
TEMP = PN_SASL_TEMP
[docs] @staticmethod
def extended():
"""
Check for support of extended SASL negotiation.
All implementations of Proton support ``ANONYMOUS`` and ``EXTERNAL`` on both
client and server sides and ``PLAIN`` on the client side.
Extended SASL implementations use an external library (Cyrus SASL)
to support other mechanisms beyond these basic ones.
:rtype: ``True`` if we support extended SASL negotiation, ``False`` if
we only support basic negotiation.
"""
return pn_sasl_extended()
def __init__(self, transport):
Wrapper.__init__(self, transport._impl, pn_transport_attachments)
self._sasl = pn_sasl(transport._impl)
def _check(self, err):
if err < 0:
exc = EXCEPTIONS.get(err, SASLException)
raise exc("[%s]" % (err))
else:
return err
@property
def user(self):
"""
Retrieve the authenticated user. This is usually used at the the
server end to find the name of the authenticated user.
If :meth:`outcome` returns a value other than :const:`OK`, then
there will be no user to return. The returned value is only reliable
after the ``PN_TRANSPORT_AUTHENTICATED`` event has been received.
:rtype: * If the SASL layer was not negotiated then ``0`` is returned.
* If the ``ANONYMOUS`` mechanism is used then the user will be
``"anonymous"``.
* Otherwise a string containing the user is
returned.
"""
return pn_sasl_get_user(self._sasl)
@property
def authorization(self):
"""
Retrieve the requested authorization user. This is usually used at the the
server end to find the name of any requested authorization user.
If the peer has not requested an authorization user or the SASL mechanism has
no capability to transport an authorization id this will be the same as the
authenticated user.
Note that it is the role of the server to ensure that the authenticated user is
actually allowed to act as the requested authorization user.
If :meth:`outcome` returns a value other than :const:`OK`, then
there will be no user to return. The returned value is only reliable
after the ``PN_TRANSPORT_AUTHENTICATED`` event has been received.
:rtype: * If the SASL layer was not negotiated then ``0`` is returned.
* If the ``ANONYMOUS`` mechanism is used then the user will be
``"anonymous"``.

The returned value is only reliable after the ``PN_TRANSPORT_AUTHENTICATED``
event has been received.
:rtype: The authentication mechanism selected by the SASL layer.
"""
return pn_sasl_get_mech(self._sasl)
@property
def outcome(self):
"""
Retrieve the outcome of SASL negotiation.
:rtype: * ``None`` if no negotiation has taken place.
* Otherwise the outcome of the negotiation.
"""
outcome = pn_sasl_outcome(self._sasl)
if outcome == PN_SASL_NONE:
return None
else:
return outcome
[docs] def allowed_mechs(self, mechs):
"""
SASL mechanisms that are to be considered for authentication.
This can be used on either the client or the server to restrict
the SASL mechanisms that may be used to the mechanisms on the list.
**NOTE:** By default the ``GSSAPI`` and ``GSS-SPNEGO`` mechanisms
are not enabled for clients. This is because these mechanisms have
the problematic behaviour of 'capturing' the client whenever they
are installed so that they will be used by the client if offered by
the server even if the client can't successfully authenticate this
way. This can lead to some very hard to debug failures.
**NOTE:** The ``GSSAPI`` or ``GSS-SPNEGO`` mechanisms need to be
explicitly enabled if they are required (together with any other
required mechanisms).
:param mechs: A list of mechanisms that are allowed for authentication,
either a string containing a space-separated list of mechs
``"mech1 mech2 ..."``, or a Python list of strings
``["mech1", "mech2", ...]``.
:type mechs: string
"""
if isinstance(mechs, list):
mechs = " ".join(mechs)
pn_sasl_allowed_mechs(self._sasl, unicode2utf8(mechs))
def _get_allow_insecure_mechs(self):
return pn_sasl_get_allow_insecure_mechs(self._sasl)
def _set_allow_insecure_mechs(self, insecure):
pn_sasl_set_allow_insecure_mechs(self._sasl, insecure)
allow_insecure_mechs = property(_get_allow_insecure_mechs, _set_allow_insecure_mechs,
doc="""
Allow unencrypted cleartext passwords (PLAIN mech)
""")
[docs] def done(self, outcome):
"""
Set the outcome of SASL negotiation. Used by the server to set the
result of the negotiation process.
"""
pn_sasl_done(self._sasl, outcome)
[docs] def config_name(self, name):
"""
Set the SASL configuration name. This is used to construct the SASL
configuration filename. In the current implementation ``".conf"`` is
added to the name and the file is looked for in the configuration
directory.
If not set it will default to ``"proton-server"`` for a sasl server
and ``"proton-client"`` for a client.
:param name: The configuration name.
:type name: string
"""
pn_sasl_config_name(self._sasl, name)
[docs] def config_path(self, path):
"""
Set the SASL configuration path. This is used to tell SASL where
to look for the configuration file. In the current implementation
it can be a colon separated list of directories.
The environment variable ``PN_SASL_CONFIG_PATH`` can also be used
to set this path, but if both methods are used then this
:meth:`config_path` will take precedence.
If not set, the underlying implementation default will be used.
:param path: The configuration path, may contain colon-separated list
if more than one path is specified.
:type path: string
"""
pn_sasl_config_path(self._sasl, path)
[docs]class SSLDomain(object):
"""
An SSL configuration domain, used to hold the SSL configuration
for one or more SSL sessions.
"""
MODE_CLIENT = PN_SSL_MODE_CLIENT
"""Local connection endpoint is an SSL client."""
MODE_SERVER = PN_SSL_MODE_SERVER
"""Local connection endpoint is an SSL server."""
VERIFY_PEER = PN_SSL_VERIFY_PEER
"""Require peer to provide a valid identifying certificate."""
VERIFY_PEER_NAME = PN_SSL_VERIFY_PEER_NAME
"""Require valid certificate and matching name."""
ANONYMOUS_PEER = PN_SSL_ANONYMOUS_PEER
"""Do not require a certificate nor cipher authorization."""
def __init__(self, mode):
self._domain = pn_ssl_domain(mode)
if self._domain is None:
raise SSLUnavailable()
def _check(self, err):
if err < 0:
exc = EXCEPTIONS.get(err, SSLException)
raise exc("SSL failure.")
else:
return err
[docs] def set_credentials(self, cert_file, key_file, password):
"""
Set the certificate that identifies the local node to the remote.
This certificate establishes the identity for the local node for all :class:`SSL` sessions
created from this domain. It will be sent to the remote if the remote needs to verify
the identity of this node. This may be used for both SSL servers and SSL clients (if
client authentication is required by the server).
.. note:: This setting effects only those :class:`SSL` objects created after this call
returns. :class:`SSL` objects created before invoking this method will use the domain's
previous setting.
:param cert_file: Specifier for the file/database containing the identifying
certificate. For Openssl users, this is a PEM file. For Windows SChannel
users, this is the PKCS#12 file or system store.
:type cert_file: ``str``
:param key_file: An optional key to access the identifying certificate. For
Openssl users, this is an optional PEM file containing the private key
used to sign the certificate. For Windows SChannel users, this is the
friendly name of the self-identifying certificate if there are multiple
certificates in the store.
:type key_file: ``str``
:param password: The password used to sign the key, else ``None`` if key is not
protected.
:type password: ``str`` or ``None``
:return: 0 on success
:rtype: ``int``
:raise: :exc:`SSLException` if there is any Proton error
"""
return self._check(pn_ssl_domain_set_credentials(self._domain,
cert_file, key_file,
password))
[docs] def set_trusted_ca_db(self, certificate_db):
"""
Configure the set of trusted CA certificates used by this domain to verify peers.
If the local SSL client/server needs to verify the identity of the remote, it must
validate the signature of the remote's certificate. This function sets the database of
trusted CAs that will be used to verify the signature of the remote's certificate.
.. note:: This setting effects only those :class:`SSL` objects created after this call
returns. :class:`SSL` objects created before invoking this method will use the domain's
previous setting.
.. note:: By default the list of trusted CA certificates will be set to the system default.
What this is is depends on the OS and the SSL implementation used: For OpenSSL the default
will depend on how the OS is set up. When using the Windows SChannel implementation the default
will be the users default trusted certificate store.
:param certificate_db: Database of trusted CAs, used to authenticate the peer.
:type certificate_db: ``str``
:return: 0 on success
:rtype: ``int``
:raise: :exc:`SSLException` if there is any Proton error
"""
return self._check(pn_ssl_domain_set_trusted_ca_db(self._domain,
certificate_db))
[docs] def set_peer_authentication(self, verify_mode, trusted_CAs=None):
"""
This method controls how the peer's certificate is validated, if at all. By default,
servers do not attempt to verify their peers (PN_SSL_ANONYMOUS_PEER) but
clients attempt to verify both the certificate and peer name (PN_SSL_VERIFY_PEER_NAME).
Once certificates and trusted CAs are configured, peer verification can be enabled.
.. note:: In order to verify a peer, a trusted CA must be configured. See
:meth:`set_trusted_ca_db`.
.. note:: Servers must provide their own certificate when verifying a peer. See
:meth:`set_credentials`.
.. note:: This setting effects only those :class:`SSL` objects created after this call
returns. :class:`SSL` objects created before invoking this method will use the domain's
previous setting.
:param verify_mode: The level of validation to apply to the peer, one of :const:`VERIFY_PEER`,
:const:`VERIFY_PEER_NAME`, :const:`ANONYMOUS_PEER`,
:type verify_mode: ``int``
:param trusted_CAs: Path to a database of trusted CAs that the server will advertise.
:type trusted_CAs: ``str``
:return: 0 on success
:rtype: ``int``
:raise: :exc:`SSLException` if there is any Proton error
"""
return self._check(pn_ssl_domain_set_peer_authentication(self._domain,
verify_mode,
trusted_CAs))
[docs] def allow_unsecured_client(self):
"""
Permit a server to accept connection requests from non-SSL clients.
This configures the server to "sniff" the incoming client data stream,
and dynamically determine whether SSL/TLS is being used. This option
is disabled by default: only clients using SSL/TLS are accepted.
:raise: :exc:`SSLException` if there is any Proton error
"""
return self._check(pn_ssl_domain_allow_unsecured_client(self._domain))
def __del__(self):
pn_ssl_domain_free(self._domain)
[docs]class SSL(object):
"""
An SSL session associated with a transport. A transport must have
an SSL object in order to "speak" SSL over its connection.
"""
[docs] @staticmethod
def present():
"""
Tests for an SSL implementation being present.
:return: ``True`` if we support SSL, ``False`` if not.
:rtype: ``bool``
"""
return pn_ssl_present()
def _check(self, err):
if err < 0:
exc = EXCEPTIONS.get(err, SSLException)
raise exc("SSL failure.")
else:
return err
def __new__(cls, transport, domain, session_details=None):
"""Enforce a singleton SSL object per Transport"""
if transport._ssl:
# unfortunately, we've combined the allocation and the configuration in a
# single step. So catch any attempt by the application to provide what
# may be a different configuration than the original (hack)
ssl = transport._ssl
if (domain and (ssl._domain is not domain) or
session_details and (ssl._session_details is not session_details)):
raise SSLException("Cannot re-configure existing SSL object!")
else:
obj = super(SSL, cls).__new__(cls)
obj._domain = domain
obj._session_details = session_details
session_id = None
if session_details:
session_id = session_details.get_session_id()
obj._ssl = pn_ssl(transport._impl)
if obj._ssl is None:
raise SSLUnavailable()
if domain:
pn_ssl_init(obj._ssl, domain._domain, session_id)
transport._ssl = obj
return transport._ssl
[docs] def cipher_name(self):
"""
Get the name of the Cipher that is currently in use.
Gets a text description of the cipher that is currently active, or
returns ``None`` if SSL is not active (no cipher).
.. note:: The cipher in use may change over time due to renegotiation
or other changes to the SSL state.
:return: The cypher name, or ``None`` if no cipher in use.
:rtype: ``str`` or ``None``
"""
rc, name = pn_ssl_get_cipher_name(self._ssl, 128)
if rc:
return name
return None
[docs] def protocol_name(self):
"""
Get the name of the SSL protocol that is currently in use.
Gets a text description of the SSL protocol that is currently active,
or returns ``None`` if SSL is not active.
.. note:: The protocol may change over time due to renegotiation.
:return: The protocol name if SSL is active, or ``None`` if SSL connection
is not ready or active.
:rtype: ``str`` or ``None``
"""
rc, name = pn_ssl_get_protocol_name(self._ssl, 128)
if rc:
return name
return None
SHA1 = PN_SSL_SHA1
"""Produces hash that is 20 bytes long using SHA-1"""
SHA256 = PN_SSL_SHA256
"""Produces hash that is 32 bytes long using SHA-256"""
SHA512 = PN_SSL_SHA512
"""Produces hash that is 64 bytes long using SHA-512"""
MD5 = PN_SSL_MD5
"""Produces hash that is 16 bytes long using MD5"""
CERT_COUNTRY_NAME = PN_SSL_CERT_SUBJECT_COUNTRY_NAME
"""Certificate country name 2-char ISO code"""
CERT_STATE_OR_PROVINCE = PN_SSL_CERT_SUBJECT_STATE_OR_PROVINCE
"""Certificate state or province, not abbreviated"""
CERT_CITY_OR_LOCALITY = PN_SSL_CERT_SUBJECT_CITY_OR_LOCALITY
"""Certificate city or place name, not abbreviated"""
CERT_ORGANIZATION_NAME = PN_SSL_CERT_SUBJECT_ORGANIZATION_NAME
"""Certificate organization name"""
CERT_ORGANIZATION_UNIT = PN_SSL_CERT_SUBJECT_ORGANIZATION_UNIT
"""Certificate organization unit or division within organization"""
CERT_COMMON_NAME = PN_SSL_CERT_SUBJECT_COMMON_NAME
"""Certificate common name or URL"""
[docs] def get_cert_subject_subfield(self, subfield_name):
"""
Returns a string that contains the value of the sub field of
the subject field in the ssl certificate. The subject field
usually contains the following values:
* :const:`CERT_COUNTRY_NAME`
* :const:`CERT_STATE_OR_PROVINCE`
* :const:`CERT_CITY_OR_LOCALITY`
* :const:`CERT_ORGANIZATION_NAME`
* :const:`CERT_ORGANIZATION_UNIT`
* :const:`CERT_COMMON_NAME`
:param subfield_name: The enumeration representing the required
sub field listed above
:type subfield_name: ``int``
:return: A string which contains the requested sub field value which
is valid until the ssl object is destroyed.
:rtype: ``str``
"""
subfield_value = pn_ssl_get_remote_subject_subfield(self._ssl, subfield_name)
return subfield_value
[docs] def get_cert_subject(self):
"""
Get the subject from the peer's certificate.
:return: A string containing the full subject.
:rtype: ``str``
"""
subject = pn_ssl_get_remote_subject(self._ssl)
return subject
def _get_cert_subject_unknown_subfield(self):
# Pass in an unhandled enum
return self.get_cert_subject_subfield(10)
# Convenience functions for obtaining the subfields of the subject field.
[docs] def get_cert_common_name(self):
"""
A convenience method to get a string that contains the :const:`CERT_COMMON_NAME`
sub field of the subject field in the ssl certificate.
:return: A string containing the :const:`CERT_COMMON_NAME` sub field.
:rtype: ``str``
"""
return self.get_cert_subject_subfield(SSL.CERT_COMMON_NAME)
[docs] def get_cert_organization(self):
"""
A convenience method to get a string that contains the :const:`CERT_ORGANIZATION_NAME`
sub field of the subject field in the ssl certificate.
:return: A string containing the :const:`CERT_ORGANIZATION_NAME` sub field.
:rtype: ``str``
"""
return self.get_cert_subject_subfield(SSL.CERT_ORGANIZATION_NAME)
[docs] def get_cert_organization_unit(self):
"""
A convenience method to get a string that contains the :const:`CERT_ORGANIZATION_UNIT`
sub field of the subject field in the ssl certificate.
:return: A string containing the :const:`CERT_ORGANIZATION_UNIT` sub field.
:rtype: ``str``
"""
return self.get_cert_subject_subfield(SSL.CERT_ORGANIZATION_UNIT)
[docs] def get_cert_locality_or_city(self):
"""
A convenience method to get a string that contains the :const:`CERT_CITY_OR_LOCALITY`
sub field of the subject field in the ssl certificate.
:return: A string containing the :const:`CERT_CITY_OR_LOCALITY` sub field.
:rtype: ``str``
"""
return self.get_cert_subject_subfield(SSL.CERT_CITY_OR_LOCALITY)
[docs] def get_cert_country(self):
"""
A convenience method to get a string that contains the :const:`CERT_COUNTRY_NAME`
sub field of the subject field in the ssl certificate.
:return: A string containing the :const:`CERT_COUNTRY_NAME` sub field.
:rtype: ``str``
"""
return self.get_cert_subject_subfield(SSL.CERT_COUNTRY_NAME)
[docs] def get_cert_state_or_province(self):
"""
A convenience method to get a string that contains the :const:`CERT_STATE_OR_PROVINCE`
sub field of the subject field in the ssl certificate.
:return: A string containing the :const:`CERT_STATE_OR_PROVINCE` sub field.
:rtype: ``str``
"""
return self.get_cert_subject_subfield(SSL.CERT_STATE_OR_PROVINCE)
[docs] def get_cert_fingerprint(self, fingerprint_length, digest_name):
"""
Get the fingerprint of the certificate. The certificate fingerprint
(as displayed in the Fingerprints section when looking at a certificate
with say the Firefox browser) is the hexadecimal hash of the entire
certificate. The fingerprint is not part of the certificate, rather
it is computed from the certificate and can be used to uniquely identify
a certificate.
:param fingerprint_length: Must be :math:`>= 33` for md5, :math:`>= 41`
for sha1, :math:`>= 65` for sha256 and :math:`>= 129`
for sha512.
:type fingerprint_length: ``int``
:param digest_name: The hash algorithm to use. Must be one of :const:`SHA1`,
:const:`SHA256`, :const:`SHA512`, :const:`MD5`.
:type digest_name: ``str``
:return: Hex fingerprint in a string, or ``None`` if an error occurred.
:rtype: ``str`` or ``None``
"""
rc, fingerprint_str = pn_ssl_get_cert_fingerprint(self._ssl, fingerprint_length, digest_name)
if rc == PN_OK:
return fingerprint_str
return None
# Convenience functions for obtaining fingerprint for specific hashing algorithms
def _get_cert_fingerprint_unknown_hash_alg(self):
return self.get_cert_fingerprint(41, 10)
[docs] def get_cert_fingerprint_sha1(self):
"""
A convenience method to get the :const:`SHA1` fingerprint of the
certificate.
:return: Hex fingerprint in a string, or ``None`` if an error occurred.
:rtype: ``str`` or ``None``
"""
return self.get_cert_fingerprint(41, SSL.SHA1)
[docs] def get_cert_fingerprint_sha256(self):
"""
A convenience method to get the :const:`SHA256` fingerprint of the
certificate.
:return: Hex fingerprint in a string, or ``None`` if an error occurred.
:rtype: ``str`` or ``None``
"""
# sha256 produces a fingerprint that is 64 characters long
return self.get_cert_fingerprint(65, SSL.SHA256)
[docs] def get_cert_fingerprint_sha512(self):
"""
A convenience method to get the :const:`SHA512` fingerprint of the
certificate.
:return: Hex fingerprint in a string, or ``None`` if an error occurred.
:rtype: ``str`` or ``None``
"""
# sha512 produces a fingerprint that is 128 characters long
return self.get_cert_fingerprint(129, SSL.SHA512)
[docs] def get_cert_fingerprint_md5(self):
"""
A convenience method to get the :const:`MD5` fingerprint of the
certificate.
:return: Hex fingerprint in a string, or ``None`` if an error occurred.
:rtype: ``str`` or ``None``
"""
return self.get_cert_fingerprint(33, SSL.MD5)
@property
def remote_subject(self):
"""
The subject from the peers certificate.
:type: ``str``
"""
return pn_ssl_get_remote_subject(self._ssl)
RESUME_UNKNOWN = PN_SSL_RESUME_UNKNOWN
"""Session resume state unknown/not supported."""
RESUME_NEW = PN_SSL_RESUME_NEW
"""Session renegotiated - not resumed."""
RESUME_REUSED = PN_SSL_RESUME_REUSED
"""Session resumed from previous session."""
[docs] def resume_status(self):
"""
Check whether the state has been resumed.
Used for client session resume. When called on an active session,
indicates whether the state has been resumed from a previous session.
.. note:: This is a best-effort service - there is no guarantee that
the remote server will accept the resumed parameters. The remote
server may choose to ignore these parameters, and request a
re-negotiation instead.
:return: Status code indicating whether or not the session has been
resumed. One of:
* :const:`RESUME_UNKNOWN`
* :const:`RESUME_NEW`
* :const:`RESUME_REUSED`
:rtype: ``int``
"""
return pn_ssl_resume_status(self._ssl)
def _set_peer_hostname(self, hostname):
self._check(pn_ssl_set_peer_hostname(self._ssl, unicode2utf8(hostname)))
def _get_peer_hostname(self):
err, name = pn_ssl_get_peer_hostname(self._ssl, 1024)
self._check(err)
return utf82unicode(name)
peer_hostname = property(_get_peer_hostname, _set_peer_hostname, doc="""
Manage the expected name of the remote peer.
The hostname is used for two purposes:
1. when set on an SSL client, it is sent to the server during the
handshake (if Server Name Indication is supported)
2. it is used to check against the identifying name provided in the
peer's certificate. If the supplied name does not exactly match a
SubjectAltName (type DNS name), or the CommonName entry in the
peer's certificate, the peer is considered unauthenticated
(potential imposter), and the SSL connection is aborted.
.. note:: Verification of the hostname is only done if
:const:`SSLDomain.VERIFY_PEER_NAME` is set using
:meth:`SSLDomain.set_peer_authentication`.
:type: ``str``
""")
[docs]class SSLSessionDetails(object):
"""
Unique identifier for the SSL session. Used to resume previous
session on a new SSL connection.
"""
def __init__(self, session_id):
self._session_id = session_id
[docs] def get_session_id(self):
"""
Get the unique identifier for this SSL session
:return: Session identifier
:rtype: ``str``
"""
return self._session_id


Please choose 'View Source' in your browser to view the HTML, or File | Save to save this file to your hard drive for editing.
CAviGenerator
is a simple wrapper for the Video For Windows (VFW) library.
In the back, it takes care of a numerous initialization for you and hides the library function calls so
that the user can start generating movies in a minimal number of line of code and without having much knowledge about
VFW.
The class main features are:
The class CAVIGenerator
takes it's inspiration from MSDN example writeavi.c.
A simple class that make creation of AVI video easy.
Each object contains general charateristics of the movie such as
BITMAPINFOHEADER
It contains also private members that are used to handle the "Video for Windows" AVI engine.
CAVIGenerator();
Default constructor, default file name is "Untitled.avi", frame rate is 30 fps.
CAVIGenerator(LPCTSTR sFileName, CView* pView, DWORD dwRate);
In-place constructor with CView. See SetBitmapHeader(CView* pView)
.
CAVIGenerator(LPCTSTR sFileName, LPBITMAPINFOHEADER lpbih, DWORD dwRate);
In-place constructor with BITMAPINFOHEADER
. See SetBitmapHeader(LPBITMAPINFOHEADER lpbih)
void SetFileName(const CString& _sFileName)
SetFileName
sets the name of the output file. The filename extension should be
.avi otherwize the creation of the AVI won't work. Checking of .avi extension
is left to the user.
void SetRate(DWORD dwRate)
SetRate
sets the frame rate (fps).
void SetBitmapHeader(CView* pView);
SetBitmapHeader
fills in the information about the bitmap
in m_bih
using using from the view the view pView
the width, height,
24 bit/color, and BRG. It makes sure that the width and height are both multiple of 4.
void SetBitmapHeader(LPBITMAPINFOHEADER lpbih);
SetBitmapHeader
sets the bitmap info as in lpbih. It supposes that the
user knows what he's doing.
LPBITMAPINFOHEADER GetBitmapHeader()
GetBitmapHeader
returns a pointer to bitmap info header structure.
HRESULT InitEngine();
InitEngine
initializes the VFW engine and chooses a codec. This function has to be
called before starting to grab frames. Some asserts are
made to check that bitmap info has been properly initialized.
It returns the last HRESULT. If something fails,
the error message can be retreived using GetLastErrorMessage().
CAviGenerator avi; HRESULT hr; hr=avi.InitEngine(); if (FAILED(hr)) { AfxMessageBox(avi.GetLastErrorMessage()); ... }
HRESULT AddFrame(BYTE* bmBits);
AddFrame
adds a frame to the movie. The data pointed by
bmBits
should be compatible with the bitmap description
made by SetBitmapHeader
. Typically with OpenGL,
bmBits
is the buffer read when using glReadPixels
.
As for InitEnginge
, it returns the HRESULT.
void ReleaseEngine();
ReleaseEngine
releases ressources allocated for movie and close the file.
You have to follow these steps:
CView
object to the
SetBitmapHeader
function. Alternative, the user can fill in the
BITMAPINFOHEADER
structure himself. Make sure that dimension of bitmap are
a multiple of 4.InitEngine
. A dialog box will
popup to choose and fill in the parameters of the codec.AddFrame
.ReleaseEngine
.And you're are done! Here's some demo pseudo-code:
CAVIGenerator AviGen; // generator BYTE* bmBits; // image buffer HRESULT hr; AviGen.SetRate(20); // set 20fps AviGen.SetBitmapHeader(GetActiveView()); // get bitmap info out of the view hr=AviGen.InitEngine() // start engine if (FAILED(hr)) { AfxMessageBox(avi.GetLastErrorMessage()); goto Cleaning; } LPBITMAPINFOHEADER lpbih=AviGen.GetBitmapInfo(); // getting bitmap info bmBits=new BYTE[3 /* BRG*/ * lpbih->biWidth* lpbih->biHeight]; // allocating memory for bmBits for (int i=0;i<100;i++) // make 100 frames { // TODO pust your draw code here. /* Draw code where bmBits is filled. For example, to read OpenGL buffer, put glReadPixels(0,0,lpbih->biWidth,lpbih->biHeight,GL_BGR_EXT,GL_UNSIGNED_BYTE,bmBits); */ // adding frame and continue if OK hr=AviGen.AddFrame(bmBits); if (FAILED(hr)) { AfxMessageBox(avi.GetLastErrorMessage()); goto Cleaning; } } // cleaning memory Cleaning: AviGen.ReleaseEngine(); // releasing ressources delete[] bmBits; // release ressources
A simple MFC SDI application that shows a cube and triangle rotating using OpenGL. When selecting the menu item Avi Generation->Generate..., you start to create a 100 frames AVI movie.
OpenGL drawing code is copy-pasted from lesson 5 of NeHe Productions.
~CAviGenerator
and in example above (LPBITMAPINFOHEADER lpbih
not initialized).CAVIGenerator::SetBitmapHeader(LPBITMAPINFOHEADER lpbih)
function. Thanks to Lori Gardi.


Three months ago, when we were all ushering in 2016, did you resolve to travel more this year? You are not alone. “Travel more” New Year’s resolutions are very popular. With Spring Break upon us, help your fellow travel resolution enthusiasts by adding hotels and other types of lodging to OpenStreetMap. There are probably a collection of hotels in your local area that you are very familiar with, and there may be a few additional ones that you would like to know more about. This is your chance to do some investigating which could lead to your next staycation or an easier time finding places to put up friends and family when they all decide to visit at once. No doubt there are places you have stayed in the past that left a lasting impression (for better or for worse). Now is your chance to share your local knowledge from around town, or towns you've visited over the years.
Business listings and other points of interest are slowly gaining momentum in OpenStreetMap. Curious to know how prevalent hotels, motels, hostels, and other forms of lodging are in OpenStreetmap? Check out this table which includes our New Year's Resolutions cities, but this time we are including phone numbers instead of hours since many lodging options recieve guests at any hour:
| Lodging Features* | with Addresses | with Website | with Phone Number | |
|---|---|---|---|---|
| Auckland | 131 | 7% | 2% | 1% |
| Dublin | 321 | 36% | 37% | 20% |
| Hong Kong | 747 | 39% | 10% | 8% |
| Melbourne | 253 | 39% | 54% | 24% |
| Mexico City | 169 | 18% | 11% | 14% |
| Mumbai | 250 | 4% | 4% | 6% |
| San Francisco | 336 | 53% | 33% | 27% |
| São Paulo | 268 | 44% | 24% | 27% |
| Seoul | 950 | 5% | 4% | 4% |
| Singapore | 418 | 39% | 24% | 20% |
| Stockholm | 484 | 12% | 46% | 27% |
| Vancouver | 91 | 63% | 22% | 16% |
Wow! So many lodging options in Seoul, but so few associated attributes. An amazing opportunity for editors. For websites and phone numbers, Melbourne and Stockholm are leading the pack, with Melbourne edging out Stockholm just a bit with it's additional address details. A street address on a feature adds so much value for many types of map services.
Helpful Tags
If you are behind in your vacation planning, get inspired by adding or enhancing lodging related businesses in OpenStreetMap! Need some help choosing tags? Here are some suggestions which link to their corresponding OpenStreetMap wiki pages:
- name=*
- addr:housenumber=*
- Polygons to represent the entire grounds:
- tourism=hotel traditionally full service hotels.
- tourism=motel traditionally smaller hotels with parking in front of each room.
- tourism=hostel traditionally lower cost lodging with shared communal spaces.
- tourism=chalet small cottages with basic accomodations.
- Points or polygons to represent the buildings
- building=*
- examples: building=hotel, building=motel, building=hostel, etc
- website=*
- phone=*
Where to Start
Do you travel for business and stay at the same hotels regularly? Enhance those first. Do you have go-to hotels you suggest when people are visting from out of town? Save those details in OpenStreetMap for future retrieval. Maybe you had a particularly memorable time at the places you booked for your last vacation. Are they represented in OpenStreetMap?
Interactive Map
Would it be helpful to see where the current lodging related features are in OpenStreetMap? There's a map for that! Hover over any of the bright blue highlighted features to bring up an info bubble with links to editing tools that can be used to add additional tags. (While you pan and zoom to your neighborhood, note that large lodging features show up at zoom level 15, but the bulk of the features show up at zoom 16.)
(This map is interactive! Open full screen ➹ )
Don't know Vancouver? Search for your city! Is your go-to hotel missing all together? Shift-click anywhere on the map to open iD or open your favorite OpenStreetMap editor to start mapping!
If you are trying to decide between creating a point or a polygon to represent a feature, a point is great when the lodging is in a building that contains other businesses and/or residences. If your lodging occupies the entire building, digitize a building polygon if it doesn't already exist and add your tags to it.
Look for more posts in the New Year's Resolution series soon!
Getting Started with OpenStreetMap
Need instructions on how to edit with iD? Here are some links to outstanding tutorials from LearnOSM, the OpenStreetMap wiki, and the United States Department of State's Humanitarian Information Unit:
Are you a mapping wiz and interested in a more advanced editor? Try out JOSM with excellent documentation from Mapbox.
Editing with a Mobile Device
With points of interest, I bet you are interested in a mobile app to edit OpenStreetMap while you are on the go.
iOS users can check out Go Map!! by Bryce Cogswell. This free editor allows you to add features and edit existing features. Check out the Go Map!! wiki page for more details. Pushpin by Fulcrum is another excellent iOS editor for OpenStreetMap points of interest.
Looking for an Android equivalent? Vespucci by Marcus Wolschon is a great option. Check out the Vespucci home page for documentation and tutorials.


Before Change
request.user = user
import StringIO
fakefile = StringIO.StringIO()
fakefile.write("some uploaded content" + testfilename)
request.FILES["file"] = SimpleUploadedFile(name=testfilename,
content=fakefile.read())
After Change
testfilename = user.username.encode("ascii","ignore") + "_testfile.txt"
url = reverse("comicmodels.views.upload_handler",
kwargs={"site_short_name":self.testproject.short_name})
factory = RequestFactory()
request = factory.get(url)
request.user = user
import StringIO
fakefile = File(StringIO.StringIO("some uploaded content for" + testfilename))
fakecontent = "some uploaded content for" + testfilename
request.FILES["file"] = SimpleUploadedFile(name=testfilename,
content=fakecontent)
request.method = "POST"


---
sort_order: 182
tei_id: rdx_b5j2m.p.idm189418896
annotation_count: 0
images:
small-thumbnail: http://readux.library.emory.edu/books/emory:b5j2m/pages/emory:p79kf/mini-thumbnail/
json: http://readux.library.emory.edu/books/emory:b5j2m/pages/emory:p79kf/info/
full: http://readux.library.emory.edu/books/emory:b5j2m/pages/emory:p79kf/fs/
page: http://readux.library.emory.edu/books/emory:b5j2m/pages/emory:p79kf/single-page/
thumbnail: http://readux.library.emory.edu/books/emory:b5j2m/pages/emory:p79kf/thumbnail/
title: Page 182
number: 182
---
{% raw %}178 MRS. H. BEECHER STOWE's " UNCLE TOM."{% endraw %}
{% raw %}had subsided. Then I reflected that what I had{% endraw %}
{% raw %}done was for the cause of Christ, and with good{% endraw %}
{% raw %}motives ; that the war was a righteous war; that{% endraw %}
{% raw %}the coloured people ought to take some part in it.{% endraw %}
{% raw %}I said to one of my companions, " God helping me,{% endraw %}
{% raw %}I will not run away when I have done no wrong."{% endraw %}
{% raw %}I soon returned to Dresden, and rode in a waggon{% endraw %}
{% raw %}to my own door in the most public manner; for I{% endraw %}
{% raw %}was not ashamed to be seen. This was on a Thurs¬{% endraw %}
{% raw %}day afternoon about four o'clock. My family were{% endraw %}
{% raw %}highly excited, and, with tears in their eyes, begged{% endraw %}
{% raw %}me to go away; but I said, " I must remain and{% endraw %}
{% raw %}have this slander cleared up publicly, as the whole{% endraw %}
{% raw %}community had been discussing it." The next{% endraw %}
{% raw %}morning, Friday, before seven o'clock, the con¬{% endraw %}
{% raw %}stable, an old friend, came to my home. I was{% endraw %}
{% raw %}sitting on the fence talking to my son-in-law. The{% endraw %}
{% raw %}constable said, pleasantly, " Good morning, Mr.{% endraw %}
{% raw %}Henson ; have you any potatoes to sell ? " " Good{% endraw %}
{% raw %}morning," I answered. "Yes, sir, I have some."{% endraw %}
{% raw %}" I should like to buy a few if you can spare any."{% endraw %}
{% raw %}" How many do you want ?" " Ten or fifteen{% endraw %}
{% raw %}bushels." " I can spare one hundred bushels."{% endraw %}
{% raw %}" Oh, I do not want so many."  Here is a writ{% endraw %}
{% raw %}for you."{% endraw %}
{% raw %}" All right, Bill." His name was William Nellis.{% endraw %}


After session has been first time authorized by AAA subsystem, Mpd provides you several ways to affect it's further operation. Process of affecting established session called dynamic authorization.
There are two types of dynamic authorization activities exist: Disconnect (terminate session, causing it's graceful shutdown) and Change of Authorization, CoA (changing session operation parameters, such as speed, ACLs and so on, on-flight)
Mpd provides several different control interfaces, that can be used to implement dynamic authorization.
The basic method of controlling mpd is it's STDIN and TCP consoles.
You can disconnect any session by connecting to console, selecting required session with any command for changing current context, such as: link, bundle, session, msession and so on, and using close command.
Mpd provides two Web interfaces: human (text/html) and binary (text/plain).
Human web interface allows you disconnect specified session just by clicking on respective [Close] link on the "Current status summary" web page on mpd built-in web server.
Binary web interface provides API for executing any of control console commands via HTTP request. For example, to disconnect session on link named L125 you may use such HTTP request: /bincmd?link%20L125&close
Mpd provides simple, but non-standard method of disconnecting session using RADIUS accounting reply. To disconnect arbitrary session you may just include mpd-drop-user attribute with nonzero value into any accounting reply packet.
This method considered not to be completely reliable, as AAA receives no acknowledge that accounting reply packet was received by mpd. The only thing guarantied, is that on packet loss mpd will retry accounting sending for specified number of times before giveup.
RFC 3576: "Dynamic Authorization Extensions to RADIUS" defines standard way to implement dynamic authorization. It defines two additional RADIUS request types: Disconnect-Request and CoA-Request, to be sent from AAA server to dedicated UDP port on NAS with regular RADIUS protocol.
To have this function working, mpd should be built with libradius library, having RADIUS server functionality (FreeBSD 7/8-STABLE after 2009-10-30).
This chapter describes commands that configure mpd's built-in RADIUS server. All of these commands are executed in global context.
set radsrv open
Opens the RADIUS server, i.e., creates the listening UDP socket.
set radsrv close
Closes the RADIUS server, i.e., closes the listening UDP socket.
set radsrv self ip [ port ]
Sets the credentials for the RADIUS-listener. After changing one of these options, the RADIUS server must be closed and re-opened for the changes to take effect.
The default is '<IP_ADDRESS> 3799'.
set radsrv peer ip secret
Defines additional AAA server, allowed to contact this NAS. After changing one of these options, the RADIUS server must be closed and re-opened for the changes to take effect.
set radsrv enable option ...
set radsrv disable option ...
These commands configure various RADIUS server options.
The enable
and disable
commands determine
whether we want the corresponding option.
The options available for the RADIUS server are:
coa
This option enables CoA-Request support on RADIUS server.
The default is enable.
disconnect
This option enables Disconnect-Request support on RADIUS server.
The default is enable.
NAS identification attributes supported by mpd:
N Name 4 NAS-IP-Address
Session identification attributes supported by mpd:
N Name 1 User-Name 5 NAS-Port 8 Framed-IP-Address 30 Called-Station-Id 31 Calling-Station-Id 44 Acct-Session-Id 50 Acct-Multi-Session-Id mpd VSA (12341) 12 mpd-link 13 mpd-bundle 14 mpd-iface 15 mpd-iface-index
Session parameters attributes supported by mpd:
N Name 24 State 25 Class 27 Session-Timeout 28 Idle-Timeout 85 Acct-Interim-Interval mpd VSA (12341) 1 mpd-rule 2 mpd-pipe 3 mpd-queue 4 mpd-table 5 mpd-table-static 7 mpd-filter 8 mpd-limit 16 mpd-input-acct 17 mpd-output-acct
Received in CoA session parameters replace existing ones. If some parameter is not received, it keeps it's previous value for standard attributes, and getting cleared for mpd's VSAs.
Note that CoA request always restarts Session and Idle timers for matching interfaces, and restarts Accounting Update timer for matching links, if new value received.


Reports redundant calls of
java.lang.Class
methods. E.g.
Xyz.class.isInstance(object)
could be replaced with
object instanceof Xyz
.
New in 2018.2


iOS, Sketch
I was the lead product designer in creating the interfaces and interactions of the application. We had worked with MIT's Media Lab to build out a prototype for the Google Play Store but it wasn't what we expected. We had no prgramming skills whatsoever, and therefore had to create the app using MIT's 'drag-and-drop' solution. Here's how our 'compare yourself to the globe feature' looked like:
It didn't meet our standards, and we were unhappy with this version 1.0. So, we used the grant money to partner with the University of Texas - Dallas to build the product the way we invisioned it.
I sat down with the team from UTD to whiteboard some ideas along with creating wireframes and flows for the application. While I took care of the design, Sameer, Kunz, and Henry (UTD) began the development.
After going back and forth with the team at UTD, we had built out an iOS version with limited features. But it had the core functionality that we were hoping for: tracking your energy usage. Here's how it turned out:
I wanted to keep the experience of the app visual and simple for several reasons. Based on surveys and user testing we conducted, many people didn't know how to parse their energy bills and then transfer that information to our app. Therefore, we kept the interface with a very limited amount of variables, and even gave users to shorten the different types of energy usage that they had to manually input. In addition, the trends are best described by line graphs, typically used whenever dealing with changes over time. I still think that giving users some sort of swipe tutorial or tooltips would help explain energy units that people aren't familiar with, but its something we can add in the 2.0!


Button examples
Material design buttons are mostly floating but in admin design you need some flatness so we created some others :D
Default buttons with colors
Flat buttons
Border buttons
Buttons sizes
Dropdown buttons
Floating Round and flat buttons


Domain Object
|
Rule Name
|
Rule Type
|
Description
|
codedEntry
|
codeHasIsa
|
ontology
|
This rule passes if each
non-obsolete concept
within the terminology has at least one is_a relationship to a parent
concept. This ensures that all concepts in the terminology occupy
legitimate locations in the hierarchy.
|
codedEntry
|
codeHasPn
|
onotology
|
This rule passes if each concept
within the terminology has a preferred name. In terms of this
domain model, it means that the codedEntry has at least one
presentation for which isPreferred is true.
|
presentation
|
nameHasCode
|
refIntegrity
|
This rule passes if each
presentation is associated with a legitimate concept.
|
definition
|
defHasCode
|
refIntegrity |
This rule passes if each
definition is associated with a legitimate concept. |
comment
|
commentHasCode |
refIntegrity |
This rule passes if each comment
is associated with a legitimate concept. |
instruction
|
instrHasCode |
refIntegrity |
This rule passes if each
instruction is associated with a legitimate concept. |
property
|
propHasCode
|
refIntegrity |
This rule passes if each
property is associated with a legitimate concept. |
propertyQualification
|
propPropHasProp
|
refIntegrity
|
This rule passes if each
property on a property is associated with a legitimate property
|
propertyLink
|
propLinkHasProp[12]
|
refIntegrity |
This rule passes if each
propertyLink is associated with two legitimate properties.
|
associationTarget
|
relHasCode[12]
|
refIntegrity |
This rule passes if each
associationTarget connects two legitimate concepts.
|
associationData
|
relDataHasCode
|
refIntegrity |
This rule passes if each
associationData has a legitimate concept LHS (left-hand-side).
|
associationQualification
|
relPropHasRel
|
refIntegrity
|
This rule passes if each
associationQualifier is connected to a legitimate associationData or
associationTarget.
|
|
Association
|
relTypeOneToOne
|
lexBig
|
This rule passes if there is a
1:1 correspondence between the association id (entityCode) and the
forwardName and reverseName.
|
Association
|
relHasRelType
|
refIntegrity
|
This rule passes if each
associationTarget has a defined association.
|
Association
|
relDataHasRelType
|
refIntegrity
|
This rule passes if each
associationData has a defined association. |
Association
|
relTypeHasRel
|
refIntegirty
|
This rule passes if each defined
association is actually used in an associationTarget or an
associationData.
|
AssociationQualifier
|
relPropHasRelPropType
|
refIntegrity
|
This rule passes if each
associationQualification has a defined AssociationQualifier.
|
Hierarchy
|
hierarchyHasRelType
|
refIntegrity
|
This rule passes if the
indicated Association actually exists.
|
Language
|
nameHasLanguage
|
refIntegrity
|
This rule passes if each
presentation has a defined Language.
|
Property
|
propHasPropType
|
refIntegrity
|
This rule passes if each
property has a defined property name. |
PropertyLink
|
propLinkHasPropLinkType
|
refIntegrity
|
This rule passes if each
property link has a defined link. |
PropertyQualifier
|
propPropHasPropPropType
|
refIntegrity |
This rule passes if each
property qualifier has a defined qualifier type.
|
RepresentationalForm
|
nameHasTty
|
refIntegrity
|
This rule passes if each
presentation has a defined RepresentationalForm.
|
Source
|
relPropHasSource
|
refIntegrity |
a "source" relProp must have a
value that is a defined source value.
|
|
propPropHasSource
|
refIntegrity |
a "source" relProp must have a
value that is a defined source value. |
ChangeEvent
|
n/a
|
n/a
|
n/a
|


Divide details about your product or agency work into parts. Write a few lines about each one and contact us about any further collaboration. We will responde get back to you in a couple of hours.
Pedro Perez
Divide details about your product or agency work into parts. Write a few lines about each one and contact us about any further collaboration. We will responde get back to you in a couple of hours.