text:
project_path: /web/fundamentals/_project.yaml
book_path: /web/fundamentals/_book.yaml
description: Improving accessibility for web pages

{# wf_blink_components: Blink>Accessibility #}
{# wf_updated_on: 2018-09-20 #}
{# wf_published_on: 2016-06-26 #}

# Accessibility {: .page-title }

{% include "web/_shared/contributors/megginkearney.html" %}
{% include "web/_shared/contributors/dgash.html" %}
{% include "web/_shared/contributors/aliceboxhall.html" %}
{% include "web/_shared/contributors/robdodson.html" %}

This document set is a text-based version of part of the content covered in the
[Udacity course on
Accessibility](https://www.udacity.com/course/web-accessibility--ud891){: .external }.
Rather than a direct transcription of the video course, it is meant to be a more
concise treatment of accessibility principles and practices, using the course's
original content as a base.

### TL;DR {: .hide-from-toc }
- Learn what accessibility means and how it applies to web development.
- Learn how to make web sites accessible and usable for everyone.
- Learn how to include basic accessibility with minimal development impact.
- Learn what HTML features are available and how to use them to improve
  accessibility.
- Learn about advanced accessibility techniques for creating polished
  accessibility experiences.

Understanding accessibility, its scope, and its impact can make you a better web
developer. This guide is intended to help you understand how you can make your
websites accessible and usable for everyone.

"Accessibility" can be difficult to spell, but it doesn't have to be difficult
to accomplish. In this guide, you will see how to get some easy wins to help
improve accessibility with minimal effort, how you can use what's built in to
HTML to create more accessible and robust interfaces, and how to leverage some
advanced techniques for creating polished accessible experiences.

You'll also find that many of these techniques will help you create interfaces
that are more pleasant and easy to use for *all* users, not just for those with
disabilities.

Of course, many developers have only a hazy understanding of what accessibility
means — something to do with government contracts, checklists, and screen
readers, right? — and there are plenty of misconceptions floating around.
For example, many developers feel that addressing accessibility will force them
to choose between creating a delightful and attractive experience, and one that
is clunky and ugly but accessible.

That is, of course, not the case at all, so let's clear that up before we get
into anything else. What do we mean by accessibility, and what are we here to
learn about?

## What is accessibility?
Broadly speaking, when we say a site is accessible, we mean that the site's
content is available, and its functionality can be operated, by literally
*anyone*. As developers, it's easy to assume that all users can see and use a
keyboard, mouse, or touch screen, and can interact with your page content the
same way you do. This can lead to an experience that works well for some people,
but creates issues that range from simple annoyances to show-stoppers for
others.

Accessibility, then, refers to the experience of users who might be outside the
narrow range of the "typical" user, who might access or interact with things
differently than you expect. Specifically, it concerns users who are
experiencing some type of impairment or disability — and bear in mind that
that experience might be non-physical or temporary.

For example, although we tend to center our discussion of accessibility on users
with physical impairments, we can all relate to the experience of using an
interface that is not accessible to us for other reasons. Have you ever had a
problem using a desktop site on a mobile phone, or seen the message "This
content is not available in your area", or been unable to find a familiar menu
on a tablet? Those are all accessibility issues.

As you learn more, you'll find that addressing accessibility issues in this
broader, more general sense almost always improves the user experience for
everyone. Let's look at an example:

![a form with poor accessibility](imgs/pooraccess.jpg)

This form has several accessibility issues.

 - The text is low contrast, which is hard for low-vision users to read.
 - Having labels on the left and fields on the right makes it hard for many
   people to associate them, and almost impossible for someone who needs to zoom
   in to use the page; imagine looking at this on a phone and having to pan
   around to figure out what goes with what.
 - The "Remember details?" label isn't associated with the checkbox, so you have
   to tap or click only on the tiny square rather than just clicking the label;
   also, someone using a screen reader would have trouble figuring out the
   association.

Now let's wave our accessibility wand and see the form with those issues fixed.
We're going to make the text darker, modify the design so that the labels are
close to the things they're labeling, and fix the label to be associated with
the checkbox so you can toggle it by clicking the label as well.

![a form with improved accessibility](imgs/betteraccess.jpg)

Which would you rather use? If you said "the accessible version", you're on your
way to understanding a main premise of this guide. Often, something that's a
complete blocker for a few users is also a pain point for many others, so by
fixing the accessibility issue you improve the experience for everyone.

## Web Content Accessibility Guidelines

Throughout this guide we'll refer to the [Web Content Accessibility Guidelines
(WCAG) 2.0](https://www.w3.org/TR/WCAG20/){: .external }, a set of guidelines
and best practices put together by accessibility experts to address what
"accessibility" means in a methodical way.

WCAG is organized around four principles often called by the acronym *POUR*:

 - **Perceivable**: Can users perceive the content? This helps us keep in mind
   that just because something is perceivable with one sense, such as sight,
   that doesn't mean that all users can perceive it.

 - **Operable**: Can users use UI components and navigate the content? For
   example, something that requires a hover interaction cannot be operated by
   someone who can't use a mouse or touch screen.

 - **Understandable**: Can users understand the content? Can users understand
   the interface and is it consistent enough to avoid confusion?

 - **Robust**: Can the content be consumed by a wide variety of user agents
   (browsers)? Does it work with assistive technology?

While WCAG provides a comprehensive overview of what it means for content to be
accessible, it can also be a bit overwhelming. To help mitigate this, the
[WebAIM](http://webaim.org/){: .external } (Web Accessibility in Mind) group has
distilled the WCAG guidelines into an easy-to-follow checklist, targeted
specifically for web content.

The [WebAIM checklist](http://webaim.org/standards/wcag/checklist){: .external }
can give you a short, high-level summary of what you need to implement, while
also linking to the underlying WCAG specification if you need an expanded
definition.

With this tool in hand, you can chart a direction for your accessibility work
and be confident that, as long as your project meets the outlined criteria, your
users should have a positive experience accessing your content.

## Understanding users' diversity

When learning about accessibility, it helps to have an understanding of the
diverse range of users in the world and the kinds of accessibility topics that
affect them. To explain further, here's an informative question/answer session
with Victor Tsaran, a Technical Program Manager at Google, who is totally blind.

Victor Tsaran

> *What do you work on at Google?*

Here at Google my job is to help ensure that our products work for all of our
diverse users, regardless of impairment or ability.

> *What kinds of impairments do users have?*

When we think about the kinds of impairments which would make it difficult for
someone to access our content, many people will immediately picture a blind user
like me. And it's true, this impairment can really make it frustrating or even
impossible to use a lot of web sites.

A lot of modern web techniques have the unfortunate side effect of creating
sites which don't work well with the tools used by blind users to access the
web. However, there is actually more to accessibility than that. We find it
useful think of impairments falling into four broad buckets: visual, motor,
hearing, and cognitive.

> *Let's go through those one at a time. Can you give some examples of visual
 impairments?*

Visual impairments can be split into a few categories: Users with no vision,
like me, might use a screen reader, braille, or combination of the two.

A braille reader

Now, it's actually pretty unusual to have literally no vision, but still,
there's a good chance you know or have met at least one person who can't see at
all. However there are also a much larger number of what we call low-vision
users.

This is a broad range, from someone like my wife, who doesn't have any corneas
— so while she can basically see things she has a hard time reading print
and is considered legally blind — to someone who might have just poor
vision and needs to wear very strong prescription glasses.

There's a huge range, and so naturally there's a big range of accommodations
that people in this category use: some do use a screen reader or a braille
display (I've even heard of one woman who reads braille displayed on-screen
because it's easier to see than printed text), or they might use text-to-speech
technology without the full screen reader functionality, or they might use a
screen magnifier which zooms in on part of the screen, or they might just use
their browser zoom to make all the fonts bigger. They might also use
high-contrast options like an operating system high-contrast mode, a
high-contrast browser extension or a high-contrast theme for a website.

High-contrast mode

A lot of users even use a combination of these, like my friend Laura who uses a
combination of high-contrast mode, browser zoom and text-to-speech.

Low vision is something a lot of people can relate to. For a start, we all
experience deteriorating vision as we age, so even if you haven't experienced it
there's a good chance you've heard your parents complain about it. But a lot of
people experience the frustration of taking their laptop out by a sunny window
only to find they suddenly can't read anything! Or anyone who's had laser
surgery or maybe just has to read something from across the room might have used
one of those accommodations I mentioned. So I think it's pretty easy for
developers to have some empathy for low-vision users.

Oh, and I shouldn't forget to mention people with poor color vision —
about 9% of males have some form of color vision deficiency! Plus about 1% of
females. They may have trouble distinguishing red and green, or yellow and blue.
Think about that the next time you design form validation.

> *What about motor impairments?*

Yes, motor impairments, or dexterity impairments. This group ranges all the way
from those who would prefer not to use a mouse, because perhaps they've had some
RSI or something and find it painful, to someone who may be physically paralyzed
and have limited range of motion for certain parts of their body.

An eye tracking device

Motor impaired users may use a keyboard, switch device, voice control, or even
an eye-tracking device to interact with their computer.

Similar to vision impairments, mobility can also be a temporary or situational
issue: Maybe you have a broken wrist on your mouse hand. Maybe the trackpad is
broken on your laptop, or you're just riding on a shaky train. There can be a
lot of situations where a user's mobility is impeded, and by making sure we
cater for them we improve the experience overall, both for anyone with a
permanent impairment but also for anyone who temporarily finds that they can't
use a pointer-based UI.

> *Great, let's talk about hearing impairments.*

This group can range from the profoundly deaf through to hard-of-hearing. And
much like eyesight, our hearing tends to degrade with age. Many of us use common
affordances like hearing aids to help us.

Screen captions

For hearing-impaired users we need to make sure that we're not relying on
sound, so making sure to use things like video captions and transcripts, and
providing some kind of alternative, if sound is part of the interface.

And like we saw with vision and motor impairments, it's really easy to imagine
a situation where someone whose ears work fine would benefit from these
accommodations as well. A lot of my friends say they love it when videos have
captions and transcripts because it means that if they're in an open plan office
and didn't bring their headphones, they can still watch the video!

> *All right, can you tell us a bit about cognitive impairments?*

There's a range of cognitive conditions like ADD, Dyslexia, and Autism,
which can mean that people want or need to access things differently. The
accommodations for these groups are naturally extremely diverse, but we
definitely find some overlap with other areas, like using zoom functionality to
make reading or concentrating easier. Also, these users may find that really
minimal design works best because it minimizes distraction and cognitive load.

I think everyone can relate to the stress of cognitive overload, so it's
obvious that if we create something that works well for someone with a cognitive
impairment, we're going to be creating something which is going to be a pleasant
experience for everyone.

> *So, how would you summarize how you think about accessibility?*

When you look at the broad range of abilities and disabilities that people
might have, you can see that designing and building products only for people who
have perfect vision, hearing, dexterity, and cognition seems incredibly narrow.
It's almost self-defeating, because we're creating a more stressful and less
usable experience for everyone, and for some users creating an experience which
actually excludes them altogether.

In this interview, Victor identified a range of impairments, and placed them
into four broad categories: *visual*, *motor*, *hearing*, and *cognitive*. He
also pointed out that each type of impairment might be *situational*,
*temporary*, or *permanent*.

Let's take a look at some real-world examples of access impairments and see
where they fall within those categories and types. Note that some impairments
may fall into more than one category or type.

    Situational
    Temporary
    Permanent

    Visual

    concussion
    blindness

    Motor
    holding a baby
    broken arm, RSI*
    RSI*

    Hearing
    noisy office

    Cognitive

    concussion

*Repetitive Strain Injury: e.g., carpal tunnel syndrome, tennis elbow, trigger
finger

## Next steps

We've covered quite a bit of ground already! You have read about

 - what accessibility is and why it matters for everyone
 - the WCAG and the WebAIM accessibility checklist
 - different types of impairments you should consider

For the rest of the guide, we'll dive into the practical aspects of creating
accessible web sites. We'll organize this effort around three main subject
areas:

 - [**Focus**](/web/fundamentals/accessibility/focus): We'll look at how to
   build things that can be operated with a keyboard instead of a mouse. This is
   important for users with motor impairments, of course, but it also ensures
   that your UI is in good shape for all users.

 - [**Semantics**](/web/fundamentals/accessibility/semantics-builtin): We'll
   make sure that we express our user interface in a robust way that works with
   a variety of assistive technologies.

 - [**Styling**](/web/fundamentals/accessibility/accessible-styles): We'll consider visual
   design and look at some techniques for making the visual elements of the
   interface as flexible and usable as possible.

Each of those subjects could fill a whole course, so we won't cover every aspect
of creating accessible web sites. However, we'll give you enough information to
get started, and point you to some good places where you can learn more about
each topic.

## Feedback {: #feedback }

{% include "web/_shared/helpful.html" %}


text:
local devMode = get "devmode" == true

--[[
Quickly enable development mode: /srun set("*gc.devmode", true)

Development mode skips the need to run a fork of the website when testing GCs.
You can login to GreenCoins with any username, the password is always 'admin'.

If you want to login with a specific forumID, input it as the username:
/gclogin 546 admin
--]]

function getPlayerLoginInfo(email, pw, callback)
    if not email or not pw then
        outputDebugString("getPlayerLoginInfo: Missing details", 1)
        callback(false)
        return
    end

    if devMode then
        -- /gclogin <choose a forumID> <admin>
        if pw == 'admin' then
            local forumID = math.floor(math.abs(tonumber(email))) or 1337
            callback(forumID)
        else
            callback(false)
        end
        return
    end

    local fetchOptions = {
        queueName = "API",
        connectionAttempts = 3,
        connectTimeout = 4000,
        method = "POST",
        postData = toJSON({
            user = email,
            password = pw,
            appId = get("appId"),
            appSecret = get("appSecretPass")
        }, true),
        headers = {
            ["Content-Type"] = "application/json",
            ["Accept"] = "application/json"
        }
    }

    fetchRemote("https://mrgreengaming.com/api/account/login", fetchOptions, function(res, info)
        if not info.success or not res then
            if not res then
                res = "EMPTY"
            end
            outputDebugString("getPlayerLoginInfo: invalid response (status " .. info.statusCode .. "). Res: " .. res, 1)
            callback(false)
            return
        end

        local result = fromJSON(res)
        if not result or result.error then
            callback(false)
            return
        end

        callback(result.userId, result.name, result.emailAddress, result.profile, result.joinTimestamp, result.coinsBalance)
    end)
end

function getForumAccountDetails(forumID, callback)
    if devMode then
        callback(forumID)
        return
    end

    if not forumID then
        outputDebugString("getForumAccountDetails: Missing details", 1)
        callback(false)
        return
    end

    local fetchOptions = {
        queueName = "API-User" .. forumID,
        connectionAttempts = 3,
        connectTimeout = 4000,
        method = "POST",
        postData = toJSON({
            userId = forumID,
            appId = get("appId"),
            appSecret = get("appSecretPass")
        }, true),
        headers = {
            ["Content-Type"] = "application/json",
            ["Accept"] = "application/json"
        }
    }

    fetchRemote("https://mrgreengaming.com/api/account/details", fetchOptions, function(res, info)
        if not info.success or not res then
            if not res then
                res = "EMPTY"
            end
            outputDebugString("getForumAccountDetails: invalid response (status " .. info.statusCode .. "). Res: " .. res, 1)
            callback(false)
            return
        end

        local result = fromJSON(res)
        if not result or result.error then
            outputDebugString("getForumAccountDetails: api error! " .. result.error .. ' ' .. tostring(result.errorMessage), 1)
            callback(false)
            return
        end

        callback(result.userId, result.name, result.emailAddress, result.profile, result.joinTimestamp, result.coinsBalance)
    end)
end

function setAccountGCInfo(forumID, amount)
    if devMode then
        return true
    end

    local fetchOptions = {
        queueName = "API-User" .. forumID,
        connectionAttempts = 3,
        connectTimeout = 5000,
        method = "POST",
        postData = toJSON({
            amount = amount,
            appId = get("appId"),
            appSecret = get("appSecretPass")
        }, true),
        headers = {
            ["Content-Type"] = "application/json",
            ["Accept"] = "application/json"
        }
    }

    --We'd rather use submitTransaction but we would need to handle transaction denies and such
    fetchRemote("https://mrgreengaming.com/api/users/" .. forumID .. "/coins/changeBalance", fetchOptions, function(res, info)
        if not info.success or not res then
            if not res then
                res = "EMPTY"
            end
            outputDebugString("setAccountGCInfo: invalid response (status " .. info.statusCode .. "). Res: " .. res, 1)
            callback(false)
            return
        end

        local result = fromJSON(res)
        if not result or result.error then
            outputDebugString("setAccountGCInfo: api error " .. result.error .. ' ' .. tostring(result.errorMessage), 1)
            callback(false)
            return
        end
    end)
end

---------------------------------------------------------------------------
--
-- getRealDateTimeNowString()
--
-- current date and time as a sortable string
-- eg '2010-12-25 15:32:45'
--
---------------------------------------------------------------------------
function getRealDateTimeNowString()
    return getRealDateTimeString(getRealTime())
end

function getRealDateTimeString(time)
    return string.format('%04d-%02d-%02d %02d:%02d:%02d', time.year + 1900, time.month + 1, time.monthday, time.hour, time.minute, time.second)
end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>GAME PLAY 2: FALL '15</title>
  <link rel="stylesheet" href="main.css">

GAME PLAY 2: FALL '15

Instructor: Sam Sheffield (ssheffield@mica.edu)

This Site (Short URL): tiny.cc/gp2f15

Online syllabus: gp2syllabus.pdf

Code repository: github.com

09/30: PAIN + UNITY: PROJECTILES, HEALTH, BEHAVIORS

TODAY:

Welcome back!

Share game prototypes

Unity, part 4

Pain

SHARE GAME PROTOTYPES

Let's play everyone's games!

Run your game in maximized view

Leave a note with instructions

Be sure to upload to your class Drive folder. (Compress the project folder into a .zip first)

UNITY 2D : PART 4

Examples from class can be downloaded from here

WARNING: Attaching scripts to projectile prefabs which need to be connected to GameObjects in the Hierarchy (like ScoreKeeper) will not work. Avoid spawning enemies for now. We'll be discussing a workaround next week!

Some goals for today...

More prefabs

Creating projectiles

Adding basic explosions

Adding health

Creating a basic healthbar

World space UI elements

Camera tricks!

Basic enemy behaviors: Spin, Patrol, Move Towards, & Attack in Range

Unitypackage to work with in class today is available here.

PAIN: FAILURE IN GAMES

Why do we do it?

THE PARADOX OF FAILURE IN GAMES

We generally avoid failure.

We experience failure when playing games.

We seek out games, although we will experience something that we normally avoid.

"Casual" games like Flappy Bird or Crossy Road, 2014.

Flywrench, 2015

Pink Sweets, 2006

TWO KINDS OF FAILURE IN GAMES

"Like tragedy in theater, cinema, and literature, failure makes us experience emotions that we generally find unpleasant. The difference is that games can be tragic in a literal sense [...]

We are real-life people who try to master a game, but most video games represent a mirror of our performance in their fictional worlds—they ask us to make things right in the game world by saving someone or fighting for self-preservation.

Space Invaders, 1978

Robotron 2084, 1982

THE GAMBLE OF FAILURE

We are motivated to play when something is at stake. It seems that the more time we invest into overcoming a challenge (be it completing a game, or simply overcoming a small subtask), the bigger the sense of loss we experience when failing, and the bigger the sense of triumph we feel when succeeding. Even then, our feeling of triumph can quickly evaporate if we learn that other players overcame the challenge faster than we did. To play a game is to make an emotional gamble: we invest time and self-esteem in the hope that it will pay off. Players are not willing to run the same amount of risk—some even prefer not to run a risk at all, not to play.

Dark Souls, 2011 (also this

Rogue-likes such as Spelunky

LEARNING & SAVING THE WORLD

"Though we may dislike failure as such, failure is an integral element of the overall experience of playing a game, a motivator, something that helps us reconsider our strategies and see the strategic depth in a game, a clear proof that we have improved when we finally overcome it. Failure brings about something positive, but it is always potentially painful or at least unpleasant. This is the double nature of games, their quality as "pleasure spiked with pain."

Super Meat Boy replay feature

HOMEWORK

GAME PROTOTYPE 4

Using the materials covered in class today, create a small prototype which includes...

At least 2 types of moving enemies.

Health system for either player or enemy.

Use of projectiles from either player or enemies.

3 Unity scenes: Start, Game, End.

Use of Playerprefs to display final score on End screen.

We'll start off next week's class by taking turns playing everyone's prototypes.

Upload your entire Unity project to your class Drive folder

BRING GAMEPAD (NEXT WEEK)

Have a basic USB or Bluetooth gamepad which is compatible with your computer in class on Oct 7th.

UPGRADE UNITY TO 5.2

I've already ugpraded, so you should too. Otherwise, example code from class may not run

WINDOWS USERS: Unity now makes Visual Studio the default editor. If you prefer Monodevelop, you can switch it using Edit > Preferences > External Tools


text:
This directory contains the script interface and implementation of the Document
Transition, and Shared Element Transition APIs.

Document Transition is a type of an animated transition that allows content to
animate to a new DOM state easily. For instance, modifying the DOM to change the
background color is a change that can easily be done without document
transitions. However, document transition also allows the new background state
to, for example, slide in from the left instead of simply atomically appearing
on top of the content.

For a detailed explanation, please see the
[explainer](https://github.com/vmpstr/shared-element-transitions/blob/main/README.md)

## Code Structure

A new method is exposed on window.document, called createTransition(). This is
the main interface to getting a new transition object from JavaScript. It is
specified in the `document_create_transition.idl` and is implemented in
corresponding `.cc` and `.h` files.

When called, `createTransition()` constructs a DocumentTransition object which
is specified in `document_transition.idl` and is implemented in corresponding
`.cc` and `.h` files.

The rest of the script interactions happen with this object.

## Pseudo Element Tree

During the transition, the browser creates a sparse post layout representation
including content from nodes in the old and new DOM. This representation is
rendered using the following steps :

- The browser executes the Document lifecycle phases (until paint) to generate
  the state required to render a DOM element as an image (bounding box size,
  transform mapping the box to viewport space and relative paint order between
  elements). This state is tracked for a subset of elements (called shared
  elements) which should be animated independently during a transition.

- A tree of pseudo elements is generated to render the shared elements using
  this state. The pseudo element tree is styled after a style recalc pass is
  executed on the author DOM during a Document lifecycle update.

``` text
html
|_ ::page-transition
   |_ ::page-transition-container(foo)
   |  |_ ::page-transition-image-wrapper(foo)
   |     |_ ::page-transition-outgoing-image(foo)
   |     |_ ::page-transition-incoming-iage(foo)
   |
   |_ ::page-transition-container(bar)
   |  |_ ::page-transition-image-wrapper(bar)
   |     |_ ::page-transition-outgoing-image(bar)
   |     |_ ::page-transition-incoming-iage(bar)
```

The ::page-transition pseudo element is the root of this pseudo element tree. This
provides a shared stacking context for painting pseudo elements corresponding to
a shared element.

Each shared element is rendered using the following new pseudo elements :

- ::page-transition-container generates a box which maps to the shared element's quad
in author DOM.
- ::page-transition-image-wrapper is a box that contains two images representing
the contents of the old and new shared element. It is isolated to allow for
mix-blend-modes that don't interact with outside content.
- ::page-transition-outgoing-image is a replaced element displaying the shared element's
cached content from the old DOM.
- ::page-transition-incoming-iage is a replaced element displaying the shared element's
live content from the new DOM.

Each shared element is tagged with a developer provided string which can be used
as a custom ident to uniquely identify and target the corresponding generated
pseudo elements in UA and developer stylesheets. This string is tracked on the
PseudoElement class.

## SharedElementResourceId
SharedElementResourceId is an identifier used to tag the rendered output (called
a snapshot) of shared elements and the root stacking context generated by the
compositor. The snapshot provides the content for the ::page-transition-outgoing-image
and ::page-transition-incoming-iage elements referenced above.

The snapshot can be in 2 states :

* Live : This refers to a render pass generated in the current frame. As such
the snapshot stays in sync with associated DOM element.
* Cached : This refers to a cached copy of a render pass saved in the Viz
process.

We generate 2 set of SharedElementResourceIDs for snapshots of elements in the
old and new DOM as follows :

* At the prepare phase (before the DOM is updated to the new state),
old_snapshot_id tags elements in the old DOM. This ID refers to a live snapshot
and the Viz process executes an async operation to save a cached version keyed
using the same ID. This ID provides the content for ::page-transition-outgoing-image
pseudo elements.

* Once the cached version has been saved, the developer can update the DOM to
the new state called the start phase. At this point new_snapshot_id is created
to tag elements in the new DOM. This ID always refers to a live snapshot and
provides the content for ::page-transition-incoming-iage pseudo elements.
The old_snapshot_id now refers to the cached version displayed by
::page-transition-outgoing-image pseudo elements.

## Additional Notes

Note that this project is in early stages of design and implementation. To
follow the design evolution, please see [our github
repo](https://github.com/vmpstr/shared-element-transitions/). Furthermore, this
README's Code Structure section will be updated as we make progress with our
implementation.


text:
function [Y] = infer_images_binary(X, W, options)
%infer_images_binary perfoms MAP-inference an a dataset
%
% Y = infer_images_binary(X, W, options);
%
% INPUT
%   X - cell array of objects;
%   W - vector with learned weights
%   options - structure with fields:
%       classNum - number of classes
%       unaryFeatureNum - number of unary features
%       pairwiseFeatureNum - number of pairwise features
%       predictor - oracle-type function for predicting an answer for each particular object
%
% OUTPUT
%   Y - cell array of labeling;
%
%   Anton Osokin, 27.11.2012

%% Initialization

% number of objects
config.N = length(X);

% number of classes
config.K = options.classNum;

% number of unary features
config.unaryFeatureNum = options.unaryFeatureNum;

% number of pairwise features
config.pairwiseFeatureNum = options.pairwiseFeatureNum;

% number of weights
if config.K == 2
    config.M = config.unaryFeatureNum + config.pairwiseFeatureNum;
else
    config.M = config.unaryFeatureNum * config.K + config.pairwiseFeatureNum;
end

if(length(W) ~= config.M)
    error('Inconsistent number of features');
end

Y = cell(config.N, 1);
for i = 1 : config.N
    fprintf('Working with object %d: ', i);
    tStart = tic;
    Y{i} = options.predictor(X{i}, W, config);
    fprintf('%f seconds\n', toc(tStart));
end

end


text:
SWF source file was converted into GAF format by Standalone GAF Converter version 5.8

GAF Converter conversion settings:

Conversion source: Main Timeline

Conversion mode: nesting

☑ Allow region rotation

Atlas max size: 2048x2048

* Allow region rotation is used to decrease texture atlas size.

Warning
-----------------

Due to a bug of PixiJS v4 engine with alphamasks , masks not working correctly. They will work when the bug will be fixed.


text:
using System;
using BizHawk.Common;
using BizHawk.Emulation.Common;

namespace BizHawk.Emulation.Cores.Sound
{
	/// <summary>
	/// A simple 1-bit (mono) beeper/buzzer implementation using blipbuffer
	/// Simulating the piezzo-electric buzzer found in many old computers (such as the ZX Spectrum or Amstrad CPC)
	/// Sound is generated by toggling the single input line ON and OFF rapidly
	/// </summary>
	public sealed class OneBitBeeper : ISoundProvider
	{
		private int _sampleRate;
		private int _clocksPerFrame;
		private int _framesPerSecond;
		private BlipBuffer _blip;
		private readonly string _beeperId;

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="blipSampleRate">The sample rate to pass to blipbuffer (this should be 44100 for ISoundProvider)</param>
		/// <param name="clocksPerFrame">The number of (usually CPU) clocked cycles in one frame</param>
		/// <param name="framesPerSecond">The number of frames per second (usually either 60 or 50)</param>
		/// <param name="beeperId">Unique name for this instance (needed for serialization as some cores have more than one active instance of the beeper)</param>
		public OneBitBeeper(int blipSampleRate, int clocksPerFrame, int framesPerSecond, string beeperId)
		{
			_beeperId = beeperId;
			_sampleRate = blipSampleRate;
			_clocksPerFrame = clocksPerFrame;
			_framesPerSecond = framesPerSecond;
			_blip = new BlipBuffer(blipSampleRate / framesPerSecond);
			_blip.SetRates(clocksPerFrame * 50, blipSampleRate);
		}

		private int clockCounter;

		/// <summary>
		/// Option to clock the beeper every CPU clock
		/// </summary>
		public void Clock(int clocksToAdd = 1)
		{
			clockCounter += clocksToAdd;
		}

		/// <summary>
		/// Option to directly set the current clock position within the frame
		/// </summary>
		public void SetClock(int currentFrameClock)
		{
			clockCounter = currentFrameClock;
		}

		private bool lastPulse;

		/// <summary>
		/// Processes an incoming pulse value
		/// </summary>
		public void ProcessPulseValue(bool pulse, bool renderSound = true)
		{
			if (!renderSound)
				return;

			if (lastPulse == pulse)
			{
				// no change
				_blip.AddDelta((uint)clockCounter, 0);
			}

			else
			{
				if (pulse)
					_blip.AddDelta((uint)clockCounter, (short)(_volume));
				else
					_blip.AddDelta((uint)clockCounter, -(short)(_volume));

				lastVolume = _volume;
			}

			lastPulse = pulse;
		}

		#region Volume Handling

		/// <summary>
		/// Beeper volume
		/// Accepts an int 0-100 value
		/// </summary>
		public int Volume
		{
			get { return VolumeConverterOut(_volume); }
			set
			{
				var newVol = VolumeConverterIn(value);
				if (newVol != _volume)
					_blip.Clear();
				_volume = VolumeConverterIn(value);
			}
		}
		private int _volume;

		/// <summary>
		/// The last used volume (used to modify blipbuffer delta values)
		/// </summary>
		private int lastVolume;

		/// <summary>
		/// Takes an int 0-100 and returns the relevant short volume to output
		/// </summary>
		private int VolumeConverterIn(int vol)
		{
			int maxLimit = short.MaxValue / 3;
			int increment = maxLimit / 100;

			return vol * increment;
		}

		/// <summary>
		/// Takes an short volume and returns the relevant int value 0-100
		/// </summary>
		private int VolumeConverterOut(int shortvol)
		{
			int maxLimit = short.MaxValue / 3;
			int increment = maxLimit / 100;

			if (shortvol > maxLimit)
				shortvol = maxLimit;

			return shortvol / increment;
		}

		#endregion

		#region ISoundProvider

		public bool CanProvideAsync => false;

		public SyncSoundMode SyncMode => SyncSoundMode.Sync;

		public void SetSyncMode(SyncSoundMode mode)
		{
			if (mode != SyncSoundMode.Sync)
				throw new InvalidOperationException("Only Sync mode is supported.");
		}

		public void GetSamplesAsync(short[] samples)
		{
			throw new NotSupportedException("Async is not available");
		}

		public void DiscardSamples()
		{
			_blip.Clear();
		}

		public void GetSamplesSync(out short[] samples, out int nsamp)
		{
			_blip.EndFrame((uint)_clocksPerFrame);
			nsamp = _blip.SamplesAvailable();
			samples = new short[nsamp * 2];
			_blip.ReadSamples(samples, nsamp, true);
			for (int i = 0; i < nsamp * 2; i += 2)
			{
				samples[i + 1] = samples[i];
			}

			clockCounter = 0;
		}

		#endregion

		#region State Serialization

		public void SyncState(Serializer ser)
		{
			ser.BeginSection("Beeper_" + _beeperId);
			ser.Sync(nameof(_sampleRate), ref _sampleRate);
			ser.Sync(nameof(_clocksPerFrame), ref _clocksPerFrame);
			ser.Sync(nameof(_framesPerSecond), ref _framesPerSecond);
			ser.Sync(nameof(clockCounter), ref clockCounter);
			ser.Sync(nameof(lastPulse), ref lastPulse);
			ser.EndSection();
		}

		#endregion
	}
}


text:
import { DataSource } from "../../../src"
import {
    closeTestingConnections,
    createTestingConnections,
    reloadTestingDatabases,
} from "../../utils/test-utils"
import { User } from "./entity/User"

describe("github issues > #2005", () => {
    let connections: DataSource[]
    before(
        async () =>
            (connections = await createTestingConnections({
                entities: [__dirname + "/entity/*{.js,.ts}"],
                enabledDrivers: ["sqlite", "better-sqlite3"],
            })),
    )
    beforeEach(() => reloadTestingDatabases(connections))
    after(() => closeTestingConnections(connections))

    it("should be able to find by boolean find", () =>
        Promise.all(
            connections.map(async (connection) => {
                const user = new User()
                user.activated = true
                await connection.manager.save(user)
                user.activated.should.be.equal(true)
            }),
        ))
})


text:
import SkipIterator from './SkipIterator';

describe('SkipIterator', function () {

  describe('when count is positive number', function () {
    let array,
        count;

    beforeEach(function () {
      array = [1, 2, 3, 4, 5];
      count = 2;
    });

    it('should not throw an error', function () {
      expect(function () {
        let iterator = new SkipIterator(array, count);
      }).not.toThrow();
    });

    it('should expose the given count as a property', function () {
      let iterator = new SkipIterator(array, count);
      expect(iterator.count).toBe(count);
    });

    it('should have own iterator', function () {
      let iterator = new SkipIterator(array, count);
      expect(iterator[Symbol.iterator]()).toBeDefined();
      expect(iterator[Symbol.iterator]()).not.toBe(array[Symbol.iterator]());
    });
  });

  describe('when count is 0', function () {
    let array,
        count;

    beforeEach(function () {
      array = [1, 2];
      count = 0;
    });

    it('should not throw an error', function () {
      expect(function () {
        let iterator = new SkipIterator(array, count);
      }).not.toThrow();
    });
  });

  describe('when count is negative number', function () {
    let array,
        count;

    beforeEach(function () {
      array = [1, 2];
      count = -1;
    });

    it('should throw an error', function () {
      expect(function () {
        let iterator = new SkipIterator(array, count);
      }).toThrow();
    });
  });

  describe('when count is not defined', function () {
    let array,
        count;

    beforeEach(function () {
      array = [1, 2];
      count = undefined;
    });

    it('should throw an error', function () {
      expect(function () {
        let iterator = new SkipIterator(array, count);
      }).toThrow();
    });
  });

  describe('when count is not a number', function () {
    let array,
        count;

    beforeEach(function () {
      array = [1, 2];
      count = {};
    });

    it('should throw an error', function () {
      expect(function () {
        let iterator = new SkipIterator(array, count);
      }).toThrow();
    });
  });
});


text:
using System;
using AutoMapper;
using NUnit.Framework;

namespace Umbraco.Tests.Models.Mapping
{
    [TestFixture]
    public class AutoMapper6Tests
    {
        [Test]
        public void Test1()
        {
            ThingProfile.CtorCount = 0;
            Assert.AreEqual(0, ThingProfile.CtorCount);

            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile<ThingProfile1>();
            });

            Assert.AreEqual(1, ThingProfile.CtorCount);
            Assert.AreEqual(0, MemberValueResolver.CtorCount);

            var mapper = config.CreateMapper();

            Assert.AreEqual(1, ThingProfile.CtorCount);
            Assert.AreEqual(0, MemberValueResolver.CtorCount);

            var thingA = new ThingA { ValueInt = 42, ValueString = "foo" };
            var thingB = mapper.Map<ThingA, ThingB>(thingA);
            Assert.AreEqual(42, thingB.ValueInt);
            Assert.AreEqual("!!foo!!", thingB.ValueString);

            mapper.Map<ThingA, ThingB>(thingA);
            mapper.Map<ThingA, ThingB>(thingA);
            mapper.Map<ThingA, ThingB>(thingA);
            Assert.AreEqual(1, ThingProfile.CtorCount); // one single profile
            Assert.AreEqual(4, MemberValueResolver.CtorCount); // many resolvers
        }

        [Test]
        public void Test2()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile<ThingProfile2>();
            });

            var mapper = config.CreateMapper();

            Assert.AreEqual(0, ValueResolver.CtorCount);

            var thingA = new ThingA { ValueInt = 42, ValueString = "foo" };
            var thingB = mapper.Map<ThingA, ThingB>(thingA);
            Assert.AreEqual(42, thingB.ValueInt);
            Assert.AreEqual("!!foo!!", thingB.ValueString);

            mapper.Map<ThingA, ThingB>(thingA);
            mapper.Map<ThingA, ThingB>(thingA);
            mapper.Map<ThingA, ThingB>(thingA);
            Assert.AreEqual(4, ValueResolver.CtorCount); // many resolvers
        }

        [Test]
        public void Test3()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile<ThingProfile3>();
            });

            var mapper = config.CreateMapper();

            var thingA = new ThingA { ValueInt = 42, ValueString = "foo" };
            var thingB = mapper.Map<ThingA, ThingB>(thingA);
            Assert.AreEqual(42, thingB.ValueInt);
            Assert.AreEqual("!!foo!!", thingB.ValueString);

            mapper.Map<ThingA, ThingB>(thingA);
            mapper.Map<ThingA, ThingB>(thingA);
            mapper.Map<ThingA, ThingB>(thingA);
        }

        // Resolve destination member using a custom value resolver
        // void ResolveUsing<TValueResolver>()
        //   where TValueResolver : IValueResolver<TSource, TDestination, TDestMember>;

        // Resolve destination member using a custom value resolver from a source member
        // void ResolveUsing<TValueResolver, TSourceMember>(Expression<Func<TSource, TSourceMember>> sourceMember)
        //   where TValueResolver : IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>;
        // void ResolveUsing<TValueResolver, TSourceMember>(string sourceMemberName)
        //   where TValueResolver : IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>;

        // Resolve destination member using a custom value resolver instance
        // void ResolveUsing(IValueResolver<TSource, TDestination, TMember> valueResolver);
        // void ResolveUsing<TSourceMember>(IMemberValueResolver<TSource, TDestination, TSourceMember, TMember> valueResolver, Expression<Func<TSource, TSourceMember>> sourceMember);

        // Resolve destination member using a custom value resolver callback
        // void ResolveUsing<TResult>(Func<TSource, TResult> resolver);
        // void ResolveUsing<TResult>(Func<TSource, TDestination, TResult> resolver);
        // void ResolveUsing<TResult>(Func<TSource, TDestination, TMember, TResult> resolver);
        // void ResolveUsing<TResult>(Func<TSource, TDestination, TMember, ResolutionContext, TResult> resolver);

        // read https://stackoverflow.com/questions/14875075/automapper-what-is-the-difference-between-mapfrom-and-resolveusing
        // about the diff between MapFrom and ResolveUsing... keeping ResolveUsing in our code

        public class ThingProfile : Profile
        {
            public static int CtorCount { get; set; }

            public ThingProfile(int ver)
            {
                CtorCount++;

                var map = CreateMap<ThingA, ThingB>()
                    .ForMember(dest => dest.ValueInt, opt => opt.MapFrom(src => src.ValueInt));

                switch (ver)
                {
                    case 0:
                        break;
                    case 1:
                        map
                            .ForMember(dest => dest.ValueString, opt => opt.ResolveUsing<MemberValueResolver, string>(src => src.ValueString));
                        break;
                    case 2:
                        map
                            .ForMember(dest => dest.ValueString, opt => opt.ResolveUsing<ValueResolver>());
                        break;
                    case 3:
                        // in most cases that should be perfectly enough?
                        map
                            .ForMember(dest => dest.ValueString, opt => opt.ResolveUsing(source => "!!" + source.ValueString + "!!"));
                        break;
                    default:
                        throw new ArgumentOutOfRangeException(nameof(ver));
                }
            }
        }

        public class ThingProfile1 : ThingProfile
        {
            public ThingProfile1() : base(1) { }
        }

        public class ThingProfile2 : ThingProfile
        {
            public ThingProfile2() : base(2) { }
        }

        public class ThingProfile3 : ThingProfile
        {
            public ThingProfile3() : base(3) { }
        }

        public class ValueResolver : IValueResolver<ThingA, ThingB, string>
        {
            public static int CtorCount { get; set; }

            public ValueResolver()
            {
                CtorCount++;
            }

            public string Resolve(ThingA source, ThingB destination, string destMember, ResolutionContext context)
            {
                return "!!" + source.ValueString + "!!";
            }
        }

        public class MemberValueResolver : IMemberValueResolver<ThingA, ThingB, string, string>
        {
            public static int CtorCount { get; set; }

            public MemberValueResolver()
            {
                CtorCount++;
            }

            public string Resolve(ThingA source, ThingB destination, string sourceMember, string destMember, ResolutionContext context)
            {
                return "!!" + sourceMember + "!!";
            }
        }

        public class ThingA
        {
            public int ValueInt { get; set; }
            public string ValueString { get; set; }
        }

        public class ThingB
        {
            public int ValueInt { get; set; }
            public string ValueString { get; set; }
        }
    }
}


text:
class CAI_Stalker;
class CInventoryItem;
class CFoodItem;
class CWeaponMagazined;
class CWeapon;
//////////////////////////////////////////////////////////////////////////
// CObjectActionBase
//////////////////////////////////////////////////////////////////////////

template <typename _item_type>
class CObjectActionBase : public CActionBase<CAI_Stalker> {
protected:
    typedef CActionBase<CAI_Stalker> inherited;
    typedef GraphEngineSpace::_solver_condition_type _condition_type;
    typedef GraphEngineSpace::_solver_value_type _value_type;

protected:
    _item_type* m_item;

public:
    IC CObjectActionBase(_item_type* item, CAI_Stalker* owner, CPropertyStorage* storage,
                         LPCSTR action_name = "");
    virtual void initialize();
    IC void set_property(_condition_type condition_id, _value_type value);
    IC CAI_Stalker& object() const;
    void prevent_weapon_state_switch_ugly();
    void stop_hiding_operation_if_any() const;
};

class CGameObject;

typedef CObjectActionBase<CGameObject> CSObjectActionBase;

//////////////////////////////////////////////////////////////////////////
// CObjectActionMember
//////////////////////////////////////////////////////////////////////////

template <typename _item_type>
class CObjectActionMember : public CObjectActionBase<_item_type> {
protected:
    typedef CObjectActionBase<_item_type> inherited;
public:
    using _condition_type = typename inherited::_condition_type;
    using _value_type = typename inherited::_value_type;
protected:
    _condition_type m_condition_id;
    _value_type m_value;

public:
    IC CObjectActionMember(_item_type* item, CAI_Stalker* owner, CPropertyStorage* storage,
                           _condition_type condition_id, _value_type value,
                           LPCSTR action_name = "");
    virtual void execute();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionCommand
//////////////////////////////////////////////////////////////////////////

class CObjectActionCommand : public CObjectActionBase<CInventoryItem> {
protected:
    typedef CObjectActionBase<CInventoryItem> inherited;

protected:
    u32 m_command;

public:
    CObjectActionCommand(CInventoryItem* item, CAI_Stalker* owner, CPropertyStorage* storage,
                         u32 command, LPCSTR action_name = "");
    virtual void initialize();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionShow
//////////////////////////////////////////////////////////////////////////

class CObjectActionShow : public CObjectActionBase<CInventoryItem> {
protected:
    typedef CObjectActionBase<CInventoryItem> inherited;

private:
    CWeapon* m_weapon;

public:
    CObjectActionShow(CInventoryItem* item, CAI_Stalker* owner, CPropertyStorage* storage,
                      LPCSTR action_name = "");
    virtual void initialize();
    virtual void execute();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionHide
//////////////////////////////////////////////////////////////////////////

class CObjectActionHide : public CObjectActionBase<CInventoryItem> {
protected:
    typedef CObjectActionBase<CInventoryItem> inherited;

public:
    CObjectActionHide(CInventoryItem* item, CAI_Stalker* owner, CPropertyStorage* storage,
                      LPCSTR action_name = "");
    virtual void execute();
    virtual void finalize();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionReload
//////////////////////////////////////////////////////////////////////////

class CObjectActionReload : public CObjectActionBase<CInventoryItem> {
protected:
    typedef CObjectActionBase<CInventoryItem> inherited;

protected:
    _condition_type m_type;

public:
    CObjectActionReload(CInventoryItem* item, CAI_Stalker* owner, CPropertyStorage* storage,
                        _condition_type type, LPCSTR action_name = "");
    virtual void initialize();
    virtual void execute();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionFire
//////////////////////////////////////////////////////////////////////////

class CObjectActionFire : public CObjectActionBase<CInventoryItem> {
protected:
    typedef CObjectActionBase<CInventoryItem> inherited;

protected:
    _condition_type m_type;

public:
    CObjectActionFire(CInventoryItem* item, CAI_Stalker* owner, CPropertyStorage* storage,
                      _condition_type type, LPCSTR action_name = "");
    virtual void initialize();
    virtual void execute();
    virtual void finalize();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionFireNoReload
//////////////////////////////////////////////////////////////////////////

class CObjectActionFireNoReload : public CObjectActionBase<CInventoryItem> {
protected:
    typedef CObjectActionBase<CInventoryItem> inherited;

protected:
    _condition_type m_type;
    bool m_fired;

public:
    CObjectActionFireNoReload(CInventoryItem* item, CAI_Stalker* owner, CPropertyStorage* storage,
                              _condition_type type, LPCSTR action_name = "");
    virtual void initialize();
    virtual void execute();
    virtual void finalize();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionStrapping
//////////////////////////////////////////////////////////////////////////

class CObjectActionStrapping : public CObjectActionBase<CInventoryItem> {
protected:
    typedef CObjectActionBase<CInventoryItem> inherited;

private:
    bool m_callback_removed;

private:
    void xr_stdcall on_animation_end();

public:
    CObjectActionStrapping(CInventoryItem* item, CAI_Stalker* owner, CPropertyStorage* storage,
                           LPCSTR action_name = "");
    virtual ~CObjectActionStrapping();
    virtual void initialize();
    virtual void execute();
    virtual void finalize();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionStrappingToIdle
//////////////////////////////////////////////////////////////////////////

class CObjectActionStrappingToIdle : public CObjectActionBase<CInventoryItem> {
protected:
    typedef CObjectActionBase<CInventoryItem> inherited;

private:
    bool m_callback_removed;

private:
    void xr_stdcall on_animation_end();

public:
    CObjectActionStrappingToIdle(CInventoryItem* item, CAI_Stalker* owner,
                                 CPropertyStorage* storage, LPCSTR action_name = "");
    virtual ~CObjectActionStrappingToIdle();
    virtual void initialize();
    virtual void execute();
    virtual void finalize();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionUnstrapping
//////////////////////////////////////////////////////////////////////////

class CObjectActionUnstrapping : public CObjectActionBase<CInventoryItem> {
protected:
    typedef CObjectActionBase<CInventoryItem> inherited;

private:
    bool m_callback_removed;

private:
    void xr_stdcall on_animation_end();

public:
    CObjectActionUnstrapping(CInventoryItem* item, CAI_Stalker* owner, CPropertyStorage* storage,
                             LPCSTR action_name = "");
    virtual ~CObjectActionUnstrapping();
    virtual void initialize();
    virtual void execute();
    virtual void finalize();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionUnstrappingToIdle
//////////////////////////////////////////////////////////////////////////

class CObjectActionUnstrappingToIdle : public CObjectActionBase<CInventoryItem> {
protected:
    typedef CObjectActionBase<CInventoryItem> inherited;

private:
    bool m_callback_removed;

private:
    void xr_stdcall on_animation_end();

public:
    CObjectActionUnstrappingToIdle(CInventoryItem* item, CAI_Stalker* owner,
                                   CPropertyStorage* storage, LPCSTR action_name = "");
    virtual ~CObjectActionUnstrappingToIdle();
    virtual void initialize();
    virtual void execute();
    virtual void finalize();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionQueueWait
//////////////////////////////////////////////////////////////////////////

class CObjectActionQueueWait : public CObjectActionBase<CInventoryItem> {
protected:
    typedef CObjectActionBase<CInventoryItem> inherited;

protected:
    _condition_type m_type;
    CWeaponMagazined* m_magazined;

public:
    CObjectActionQueueWait(CInventoryItem* item, CAI_Stalker* owner, CPropertyStorage* storage,
                           _condition_type type, LPCSTR action_name = "");
    virtual void initialize();
    virtual void execute();
    virtual void finalize();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionSwitch
//////////////////////////////////////////////////////////////////////////

class CObjectActionSwitch : public CObjectActionBase<CInventoryItem> {
protected:
    typedef CObjectActionBase<CInventoryItem> inherited;

protected:
    _condition_type m_type;

public:
    CObjectActionSwitch(CInventoryItem* item, CAI_Stalker* owner, CPropertyStorage* storage,
                        _condition_type type, LPCSTR action_name = "");
    virtual void initialize();
    virtual void execute();
    virtual void finalize();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionDrop
//////////////////////////////////////////////////////////////////////////

class CObjectActionDrop : public CObjectActionBase<CInventoryItem> {
protected:
    typedef CObjectActionBase<CInventoryItem> inherited;

public:
    CObjectActionDrop(CInventoryItem* item, CAI_Stalker* owner, CPropertyStorage* storage,
                      LPCSTR action_name = "");
    virtual void initialize();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionAim
//////////////////////////////////////////////////////////////////////////

class CObjectActionAim : public CObjectActionMember<CInventoryItem> {
protected:
    typedef CObjectActionMember<CInventoryItem> inherited;

private:
    CWeaponMagazined* m_weapon;

public:
    CObjectActionAim(CInventoryItem* item, CAI_Stalker* owner, CPropertyStorage* storage,
                     _condition_type condition_id, _value_type value, LPCSTR action_name = "");
    virtual void initialize();
    virtual void execute();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionIdle
//////////////////////////////////////////////////////////////////////////

class CObjectActionIdle : public CObjectActionBase<CInventoryItem> {
protected:
    typedef CObjectActionBase<CInventoryItem> inherited;

public:
    CObjectActionIdle(CInventoryItem* item, CAI_Stalker* owner, CPropertyStorage* storage,
                      LPCSTR action_name = "");
    virtual void initialize();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionIdleMissile
//////////////////////////////////////////////////////////////////////////

class CObjectActionIdleMissile : public CObjectActionBase<CInventoryItem> {
protected:
    typedef CObjectActionBase<CInventoryItem> inherited;

public:
    CObjectActionIdleMissile(CInventoryItem* item, CAI_Stalker* owner, CPropertyStorage* storage,
                             LPCSTR action_name = "");
    virtual void initialize();
};

//////////////////////////////////////////////////////////////////////////
// CObjectActionThrowMissile
//////////////////////////////////////////////////////////////////////////

class CObjectActionThrowMissile : public CObjectActionBase<CInventoryItem> {
protected:
    typedef CObjectActionBase<CInventoryItem> inherited;

public:
    CObjectActionThrowMissile(CInventoryItem* item, CAI_Stalker* owner, CPropertyStorage* storage,
                              LPCSTR action_name = "");
    virtual void initialize();
    virtual void execute();
};
#include "object_actions_inline.h"


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>batch-get-item — AWS CLI 1.0.0 documentation</title>
  <link rel="stylesheet" type="text/css" href="../../_static/bootstrap.min.css" />

    <link rel="stylesheet" href="../../_static/guzzle.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="top" title="AWS CLI 1.0.0 documentation" href="../../index.html" />
    <link rel="up" title="dynamodb" href="index.html" />
    <link rel="next" title="batch-write-item" href="batch-write-item.html" />
    <link rel="prev" title="dynamodb" href="index.html" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" type="text/css" href="../../_static/bootstrap-responsive.min.css" />

        AWS CLI

Home

Documentation

Forum

GitHub

Navigation

          index

          next |

          previous |

AWS CLI 1.0.0 documentation »

aws »

dynamodb »

          ← dynamodb
          /

batch-write-item →

Table Of Contents

batch-get-item

Description

Synopsis

Options

Quick search

    <form class="form-search margin-top-1em" action="../../search.html" method="get">
        <input type="text" name="q" style="width: 105px" class="input-small search-query" />
        <button type="submit" class="btn btn-small">Search</button>
        <input type="hidden" name="check_keywords" value="yes" />
        <input type="hidden" name="area" value="default" />
    </form>

Feedback

Did you find this page useful? Do you have a suggestion? Give us feedback or
  send us a pull request on GitHub.

[ aws . dynamodb ]

batch-get-item¶

Description¶

The batch-get-item operation returns the attributes of one or more items from one or more tables. You identify requested items by primary key.

A single operation can retrieve up to 1 MB of data, which can comprise as many as 100 items. batch-get-item will return a partial result if the response size limit is exceeded, the table's provisioned throughput is exceeded, or an internal processing failure occurs. If a partial result is returned, the operation returns a value for UnprocessedKeys . You can use this value to retry the operation starting with the next item to get.

For example, if you ask to retrieve 100 items, but each individual item is 50 KB in size, the system returns 20 items (1 MB) and an appropriate UnprocessedKeys value so you can get the next page of results. If desired, your application can include its own logic to assemble the pages of results into one dataset.

If no items can be processed because of insufficient provisioned throughput on each of the tables involved in the request, batch-get-item throws ProvisionedThroughputExceededException .

By default, batch-get-item performs eventually consistent reads on every table in the request. If you want strongly consistent reads instead, you can set ConsistentRead to <tt class="docutils literal">true</tt>  for any or all tables.

In order to minimize response latency, batch-get-item fetches items in parallel.

When designing your application, keep in mind that Amazon DynamoDB does not return attributes in any particular order. To help parse the response by item, include the primary key values for the items in your request in the AttributesToGet parameter.

If a requested item does not exist, it is not returned in the result. Requests for nonexistent items consume the minimum read capacity units according to the type of read. For more information, see Capacity Units Calculations in the Amazon DynamoDB Developer Guide.

Synopsis¶

  batch-get-item
--request-items <value>
[--return-consumed-capacity <value>]

Options¶

<tt class="docutils literal">--request-items</tt> (map)

A map of one or more table names and, for each table, the corresponding primary keys for the items to retrieve. Each table name can be invoked only once.

Each element in the map consists of the following:

Keys - An array of primary key attribute values that define specific items in the table.

AttributesToGet - One or more attributes to be retrieved from the table or index. By default, all attributes are returned. If a specified attribute is not found, it does not appear in the result.

ConsistentRead - If <tt class="docutils literal">true</tt>  , a strongly consistent read is used; if <tt class="docutils literal">false</tt>  (the default), an eventually consistent read is used.

JSON Syntax:

{"string": {
      "Keys": [
        {"string": {
              "S": "string",
              "N": "string",
              "B": blob,
              "SS": ["string", ...],
              "NS": ["string", ...],
              "BS": [blob, ...]
            }
          ...}
        ...
      ],
      "AttributesToGet": ["string", ...],
      "ConsistentRead": true|false
    }
  ...}

<tt class="docutils literal">--return-consumed-capacity</tt> (string)

If set to <tt class="docutils literal">TOTAL</tt>  , ConsumedCapacity is included in the response; if set to <tt class="docutils literal">NONE</tt>  (the default), ConsumedCapacity is not included.

          ← dynamodb
          /

batch-write-item →

Navigation

          index

          next |

          previous |

AWS CLI 1.0.0 documentation »

aws »

dynamodb »

    © Copyright 2013, Amazon Web Services. Created using Sphinx.


text:
package net.itas.util;

import java.util.List;
import java.util.Map;

import junit.framework.Assert;

import org.itas.common.GenericInfo;
import org.itas.common.Utils.ClassUtils;
import org.itas.common.Utils.GenericUtils;
import org.junit.Test;

public class TestClazzs {

	@Test
	public void testNewInstance() throws Exception {
		TestInt intInstance = ClassUtils.newInstance(TestInt.class, new Integer[]{10}, new Class[]{int.class});
		Assert.assertEquals(10, intInstance.id);

		TestLong longInstance = ClassUtils.newInstance(TestLong.class, new Long[]{100L}, new Class[]{long.class});
		Assert.assertEquals(100L, longInstance.id);

		TestString stringInstance = ClassUtils.newInstance(TestString.class, new String[]{"hello"}, new Class[]{String.class});
		Assert.assertEquals("hello", stringInstance.id);
	}

	@Test
	public void testGenerics() throws Exception {
		String generic1 = TestInt.class.getDeclaredField("aa").getGenericType().toString();
		String generic = "Ljava/util/List<Ljava/util/Map<Ljava/util/Map<Ljava/lang/String;Ljava/util/List<Ljava/lang/Integer;>;>;Ljava/util/Map<Ljava/lang/String;Ljava/util/List<Ljava/util/Map<Ljava/util/Map<Ljava/lang/String;Ljava/util/List<Ljava/lang/Integer;>;>;Ljava/util/Map<Ljava/lang/String;Ljava/util/List<Ljava/lang/Integer;>;>;>;>;>;>;>;";

		GenericInfo info = GenericUtils.getGenericInfo(generic, true);
		GenericInfo info1 = GenericUtils.getGenericInfo(generic1, false);
		System.out.println(info);
		System.out.println(info1);
	}

}

class TestInt {

	TestInt(int Id) {
		this.id = Id;
	}

	int id;

	List<Map<Map<?, List<?>>, Map<String, List<Map<Map<String, List<Integer>>, Map<String, List<Integer>>>>>>> aa;;
}

class TestLong {

	TestLong(long Id) {
		this.id = Id;
	}

	long id;
}
class TestString {

	TestString(String Id) {
		this.id = Id;
	}

	String id;
}


text:
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AccessServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            \App\Repositories\Backend\Access\User\UserInterface::class,
            \App\Repositories\Backend\Access\User\UserRepository::class
        );

        $this->app->bind(
            \App\Repositories\Backend\Access\Role\RoleInterface::class,
            \App\Repositories\Backend\Access\Role\RoleRepository::class
        );

        $this->app->bind(
            \App\Repositories\Backend\Access\Permission\PermissionInterface::class,
            \App\Repositories\Backend\Access\Permission\PermissionRepository::class
        );
    }
}


text:
package com.appleframework.data.hbase.config;

import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.HTableInterfaceFactory;
import org.springframework.util.StringUtils;

import com.appleframework.data.hbase.exception.SimpleHBaseException;

/**
* Helper class featuring methods for Hbase table handling and exception translation.
*
* @author Costin Leau
*/
@SuppressWarnings("deprecation")
public class HbaseUtils {

	/**
	 * Converts the given (Hbase) exception to an appropriate exception from <tt>org.springframework.dao</tt> hierarchy.
	 *
	 * @param ex Hbase exception that occurred
	 * @return the corresponding DataAccessException instance
	 */
	public static SimpleHBaseException convertHbaseException(Exception ex) {
		return new SimpleHBaseException(ex);
	}

	/**
	 * Retrieves an Hbase table instance identified by its name.
	 *
	 * @param configuration Hbase configuration object
	 * @param tableName table name
	 * @return table instance
	 */
	public static HTableInterface getHTable(String tableName, Configuration configuration) {
		return getHTable(tableName, configuration, getCharset(null), null);
	}

	/**
	 * Retrieves an Hbase table instance identified by its name and charset using the given table factory.
	 *
	 * @param tableName table name
	 * @param configuration Hbase configuration object
	 * @param charset name charset (may be null)
	 * @param tableFactory table factory (may be null)
	 * @return table instance
	 */
	public static HTableInterface getHTable(String tableName, Configuration configuration, Charset charset, HTableInterfaceFactory tableFactory) {
		if (HbaseSynchronizationManager.hasResource(tableName)) {
			return (HTable) HbaseSynchronizationManager.getResource(tableName);
		}

		HTableInterface t = null;
		try {
			if (tableFactory != null) {
				t = tableFactory.createHTableInterface(configuration, tableName.getBytes(charset));
			}
			else {
				t = new HTable(configuration, tableName.getBytes(charset));
			}

			return t;

		} catch (Exception ex) {
			throw convertHbaseException(ex);
		}
	}

	static Charset getCharset(String encoding) {
		return (StringUtils.hasText(encoding) ? Charset.forName(encoding) : Charset.forName("UTF-8"));
	}

	/**
	 * Releases (or closes) the given table, created via the given configuration if it is not managed externally (or bound to the thread).
	 *
	 * @param tableName table name
	 * @param table table
	 */
	public static void releaseTable(String tableName, HTableInterface table) {
		releaseTable(tableName, table, null);
	}

	/**
	 * Releases (or closes) the given table, created via the given configuration if it is not managed externally (or bound to the thread).
	 *
	 * @param tableName table name
	 * @param table table
	 * @param tableFactory table factory
	 */
	public static void releaseTable(String tableName, HTableInterface table, HTableInterfaceFactory tableFactory) {
		try {
			doReleaseTable(tableName, table, tableFactory);
		} catch (IOException ex) {
			throw HbaseUtils.convertHbaseException(ex);
		}
	}

	private static void doReleaseTable(String tableName, HTableInterface table, HTableInterfaceFactory tableFactory)
			throws IOException {
		if (table == null) {
			return;
		}

		// close only if its unbound
		if (!isBoundToThread(tableName)) {
			if (tableFactory != null) {
				tableFactory.releaseHTableInterface(table);
			}
			else {
				table.close();
			}
		}
	}

	private static boolean isBoundToThread(String tableName) {
		return HbaseSynchronizationManager.hasResource(tableName);
	}
}


text:
package com.firebase.digitsmigrationhelpers;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.firebase.digitsmigrationhelpers.internal.ClearSessionContinuation;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Pattern;

/**
 * Build a Digits session that can be exchanged for a user on the firebase SDK using the
 * {@link AuthMigrator}
 */
public class RedeemableDigitsSessionBuilder {
    private static final String TAG = "Digits";
    private Long id;
    private String phoneNumber;
    private String email;
    private Boolean isEmailVerified;
    private String authToken;
    private String authTokenSecret;
    private String consumerKey;
    private String consumerSecret;
    private String fabricApiKey;

    private static final String EMAIL_KEY = "email";
    private static final String PHONE_NUMBER_KEY = "phone_number";
    private static final String EMAIL_ADDRESS_KEY = "address";
    private static final String IS_EMAIL_ADDRESS_VERIFIED_KEY = "is_verified";
    private static final String AUTH_TOKEN_KEY = "auth_token";
    private static final String NESTED_TOKEN_KEY = "token";
    private static final String NESTED_TOKEN_SECRET_KEY = "secret";

    private static final String ID_KEY = "id";

    private static final String EXAMPLE_FABRIC_API_ENTRY =
            "\n<meta-data"
            + "\n\tandroid:name=\"io.fabric.ApiKey\""
            + "\n\tandroid:value=\"YOUR_FABRIC_API_KEY\""
            + "\n\ttools:replace=\"android:value\" />\n";
    private static final String EXAMPLE_CONSUMER_KEY_ENTRY =
            "\n<meta-data"
            + "\n\tandroid:name=\"com.digits.sdk.android.ConsumerKey\""
            + "\n\tandroid:value=\"YOUR_DIGITS_CONSUMER_KEY\""
            + "\n\ttools:replace=\"android:value\" />\n";
    private static final String EXAMPLE_CONSUMER_SECRET_ENTRY =
            "\n<meta-data" +
            "\n\tandroid:name=\"com.digits.sdk.android.ConsumerSecret\"" +
            "\n\tandroid:value=\"YOUR_DIGITS_CONSUMER_SECRET\"" +
            "\n\ttools:replace=\"android:value\" />\n";

    /**
     * Set digits user id
     *
     * @param id digits user id
     * @return builder
     */
    public RedeemableDigitsSessionBuilder setId(Long id) {
        this.id = id;
        return this;
    }

    /**
     * Set phone number
     *
     * @param phoneNumber digits user's phone number
     * @return builder
     */
    public RedeemableDigitsSessionBuilder setPhoneNumber(@Nullable String phoneNumber) {
        this.phoneNumber = phoneNumber;
        return this;
    }

    /**
     * Set email address
     *
     * @param email digits user's email address
     * @return builder
     */
    public RedeemableDigitsSessionBuilder setEmail(@Nullable String email) {
        this.email = email;
        return this;
    }

    /**
     * Set Is the email verified
     *
     * @param isEmailVerified whether the digits user's email was verified
     * @return builder
     */
    public RedeemableDigitsSessionBuilder setIsEmailVerified(@Nullable Boolean isEmailVerified) {
        this.isEmailVerified = isEmailVerified;
        return this;
    }

    /**
     * Set auth token issued for the user by the digits server
     *
     * @param authToken OAuth1a token issued to the digits user
     * @return builder
     */
    public RedeemableDigitsSessionBuilder setAuthToken(@Nullable String authToken) {
        this.authToken = authToken;
        return this;
    }

    /**
     * Set secret issued for the user by the digits server
     *
     * @param authTokenSecret OAuth1a secret issued to the digits user
     * @return builder
     */
    public RedeemableDigitsSessionBuilder setAuthTokenSecret(@Nullable String authTokenSecret) {
        this.authTokenSecret = authTokenSecret;
        return this;
    }

    /**
     * Set digits consumer key issued to the app at Fabric.io
     *
     * @param consumerKey consumer key issued to identify the app
     * @return builder
     */
    public RedeemableDigitsSessionBuilder setConsumerKey(@Nullable String consumerKey) {
        this.consumerKey = consumerKey;
        return this;
    }

    /**
     * Set digits consumer secret issued to the app at Fabric.io
     *
     * @param consumerSecret consumer secret issued to authenticate the app
     * @return builder
     */
    public RedeemableDigitsSessionBuilder setConsumerSecret(@Nullable String consumerSecret) {
        this.consumerSecret = consumerSecret;
        return this;
    }

    /**
     * Set Fabric api key issued to the app at Fabric.io
     *
     * @param fabricApiKey fabric api key
     * @return builder
     */
    public RedeemableDigitsSessionBuilder setFabricApiKey(@Nullable String fabricApiKey) {
        this.fabricApiKey = fabricApiKey;
        return this;
    }

    /**
     * Build {@link ClearSessionContinuation.RedeemableDigitsSession} using the parameters provided
     *
     * We permit null auth token and secret as permissible but corrupt tokens. Once these are
     * invalidated by the service, these are deleted from the client in
     * {@link ClearSessionContinuation}

     * @return redeemable digits session
     */
    public ClearSessionContinuation.RedeemableDigitsSession build() {
        checkNotNull(authToken, "Auth Token cannot be null");
        checkNotNull(authTokenSecret, "Token Secret cannot be null");

        failNotNull(consumerKey, "Consumer Key cannot be empty. "
                + "Your AndroidManifest.xml should have an entry like: "
                + EXAMPLE_CONSUMER_KEY_ENTRY);
        failNotNull(consumerSecret, "Consumer Secret cannot be empty. "
                + "Your AndroidManifest.xml should have an entry like:"
                + EXAMPLE_CONSUMER_SECRET_ENTRY);
        failNotNull(fabricApiKey, "Fabric Api Key cannot be empty. "
                + "Your AndroidManifest.xml should have an entry like: "
                + EXAMPLE_FABRIC_API_ENTRY);

        if(!isValidApiKeyFormat(fabricApiKey)) {
            throw new IllegalArgumentException("Invalid Fabric API key." +
                    "Contact support@fabric.io for assistance");
        }

        return new ClearSessionContinuation.RedeemableDigitsSession(id, phoneNumber, email, isEmailVerified, authToken,
                authTokenSecret, consumerKey, consumerSecret, fabricApiKey);
    }

    @NonNull
    static RedeemableDigitsSessionBuilder fromSessionJson(@NonNull String json) throws
            JSONException {
        RedeemableDigitsSessionBuilder builder = new RedeemableDigitsSessionBuilder();

        //Top level structures
        JSONObject jsonObject = new JSONObject(json);
        JSONObject emailJsonObject = safeGetJsonObject(EMAIL_KEY, jsonObject);
        JSONObject authTokenJsonObject = safeGetJsonObject(AUTH_TOKEN_KEY, jsonObject);

        builder.setPhoneNumber(safeGetString(PHONE_NUMBER_KEY, jsonObject));
        builder.setId(safeGetLong(ID_KEY, jsonObject));

        //Nested Structures
        JSONObject nestedAuthTokenJsonObject = safeGetJsonObject(AUTH_TOKEN_KEY,
                authTokenJsonObject);

        builder.setEmail(safeGetString(EMAIL_ADDRESS_KEY, emailJsonObject));
        builder.setIsEmailVerified(safeGetBoolean(IS_EMAIL_ADDRESS_VERIFIED_KEY, emailJsonObject));

        builder.setAuthToken(safeGetString(NESTED_TOKEN_KEY, nestedAuthTokenJsonObject));
        builder.setAuthTokenSecret(safeGetString(NESTED_TOKEN_SECRET_KEY,
                nestedAuthTokenJsonObject));

        return builder;

    }

    private static JSONObject safeGetJsonObject(String key, JSONObject jsonObject) throws
            JSONException {
        return safeHasKey(jsonObject, key) ? jsonObject.getJSONObject(key) : null;
    }

    private static String safeGetString(String key, JSONObject jsonObject) throws JSONException {
        return safeHasKey(jsonObject, key) ? jsonObject.getString(key) : null;
    }

    private static Long safeGetLong(String key, JSONObject jsonObject) throws JSONException {
        return safeHasKey(jsonObject, key) ? jsonObject.getLong(key) : null;
    }

    private static Boolean safeGetBoolean(String key, JSONObject jsonObject) throws JSONException {
        return safeHasKey(jsonObject, key) ? jsonObject.getBoolean(key) : null;
    }

    private static boolean safeHasKey(JSONObject jsonObject, String key) {
        return key != null && jsonObject != null && jsonObject.has(key);
    }

    private static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {
        if(reference instanceof String && TextUtils.isEmpty((String) reference)) {
            Log.d(TAG, String.valueOf(errorMessage));
        }else if (reference == null) {
            Log.d(TAG, String.valueOf(errorMessage));
        }
        return reference;
    }

    private static <T> T failNotNull(T reference, @Nullable Object errorMessage) {
        if(reference instanceof String && TextUtils.isEmpty((String) reference)) {
            throw new IllegalArgumentException(String.valueOf(errorMessage));
        } else if (reference == null) {
            throw new IllegalArgumentException(String.valueOf(errorMessage));
        }
        return reference;
    }

    private static boolean isValidApiKeyFormat(String apiKey) {
        return apiKey != null
                && apiKey.length() == 40
                && Pattern.compile("[0-9a-f]+").matcher(apiKey).matches();
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace Kitechan.Controls
{
    public partial class TextBoxWithoutCaret : TextBox
    {
        [DllImport("user32.dll")]
        private static extern bool HideCaret(IntPtr hwnd);

        [DllImport("user32.dll")]
        private static extern bool ShowCaret(IntPtr hwnd);

        public TextBoxWithoutCaret()
        {
            InitializeComponent();

            this.GotFocus += TextBoxWithoutCaret_GotFocus;
            this.LostFocus += TextBoxWithoutCaret_LostFocus;
        }

        private void TextBoxWithoutCaret_LostFocus(object sender, EventArgs e)
        {
            ShowCaret(this.Handle);
        }

        private void TextBoxWithoutCaret_GotFocus(object sender, EventArgs e)
        {
            HideCaret(this.Handle);
        }
    }
}


text:
import pytest

try:
    from bson.objectid import ObjectId
except ImportError:
    ObjectId = None
else:
    from schematics.contrib.mongo import ObjectIdType
    from schematics.exceptions import ConversionError, ValidationError

    FAKE_OID = ObjectId()

pytestmark = pytest.mark.skipif(ObjectId is None,
                                reason='requires pymongo')

def test_to_native():
    oid = ObjectIdType()

    assert oid.to_native(FAKE_OID) == FAKE_OID
    assert oid.to_native(str(FAKE_OID)) == FAKE_OID

    with pytest.raises(ConversionError):
        oid.to_native('foo')

def test_to_primitive():
    oid = ObjectIdType()

    assert oid.to_primitive(FAKE_OID) == str(FAKE_OID)
    assert oid.to_primitive(str(FAKE_OID)) == str(FAKE_OID)

def test_validate_id():
    oid = ObjectIdType()

    oid.validate(FAKE_OID)
    oid.validate(str(FAKE_OID))

    with pytest.raises(ConversionError):
        oid.validate('foo')


text:
<?php

namespace TestApp\Mailer;

use Cake\Mailer\Mailer;

/**
 * Test Suite Test App Mailer class.
 */
class TestMailer extends Mailer
{

    public function getEmailForAssertion()
    {
        return $this->_email;
    }

    public function reset()
    {
        $this->template = $this->viewBuilder()->template();

        return parent::reset();
    }
}


text:
#include "avionics/firmware/monitors/bq34z100.h"

#include <stdbool.h>
#include <stddef.h>  // For NULL.
#include <stdint.h>

#include "avionics/firmware/cpu/i2c.h"
#include "avionics/firmware/drivers/bq34z100.h"
#include "avionics/firmware/drivers/bq34z100_types.h"
#include "avionics/firmware/monitors/bq34z100_types.h"

static void Poll(const Bq34z100Monitor *config,
                 Bq34z100OutputFunction output_function, Bq34z100 *device) {
  if (Bq34z100Poll(&config->config, device)) {
    Bq34z100OutputData data;
    Bq34z100Convert(&config->config, &device->output, &data);

    uint32_t flags = 0x0;
    if (data.avg_current > config->current_max && config->current_max > 0.0f) {
      flags |= kBq34z100MonitorFlagOverCurrent;
    }
    if (data.bus_voltage > config->voltage_max && config->voltage_max > 0.0f) {
      flags |= kBq34z100MonitorFlagOverVoltage;
    }
    if (data.bus_voltage < config->voltage_min) {
      flags |= kBq34z100MonitorFlagUnderVoltage;
    }
    if (data.soc_per_cent < config->soc_min) {
      flags |= kBq34z100MonitorFlagLowCharge;
    }
    output_function(config->monitor, &data, flags);
  }
}

void Bq34z100MonitorInit(int32_t num_devices, Bq34z100 *devices) {
  for (int32_t i = 0; i < num_devices; ++i) {
    Bq34z100Init(&devices[i]);
  }
}

bool Bq34z100MonitorPoll(const Bq34z100Monitors *config,
                         Bq34z100OutputFunction output_function,
                         uint32_t *device_index, Bq34z100 *devices) {
  // If no valid configuration exists, return true to advance to next monitor.
  if (config == NULL || config->num_devices <= 0) {
    return true;
  }

  // Make certain that device_index is always valid.
  *device_index %= config->num_devices;
  Poll(&config->device[*device_index], output_function,
       &devices[*device_index]);

  // Limit each device to one I2C transaction per iteration.
  if (I2cIsBusIdle()) {
    ++(*device_index);  // Process all devices concurrently.
    return true;        // Set true when done polling. Data may not update.
  }
  return false;
}


text:
package org.apache.hadoop.fs.impl;

import org.apache.hadoop.fs.FileRange;

import java.util.ArrayList;
import java.util.List;

/**
 * A file range that represents a set of underlying file ranges.
 * This is used when we combine the user's FileRange objects
 * together into a single read for efficiency.
 */
public class CombinedFileRange extends FileRangeImpl {
  private ArrayList<FileRange> underlying = new ArrayList<>();

  public CombinedFileRange(long offset, long end, FileRange original) {
    super(offset, (int) (end - offset));
    this.underlying.add(original);
  }

  /**
   * Get the list of ranges that were merged together to form this one.
   * @return the list of input ranges
   */
  public List<FileRange> getUnderlying() {
    return underlying;
  }

  /**
   * Merge this input range into the current one, if it is compatible.
   * It is assumed that otherOffset is greater or equal the current offset,
   * which typically happens by sorting the input ranges on offset.
   * @param otherOffset the offset to consider merging
   * @param otherEnd the end to consider merging
   * @param other the underlying FileRange to add if we merge
   * @param minSeek the minimum distance that we'll seek without merging the
   *                ranges together
   * @param maxSize the maximum size that we'll merge into a single range
   * @return true if we have merged the range into this one
   */
  public boolean merge(long otherOffset, long otherEnd, FileRange other,
                       int minSeek, int maxSize) {
    long end = this.getOffset() + this.getLength();
    long newEnd = Math.max(end, otherEnd);
    if (otherOffset - end >= minSeek || newEnd - this.getOffset() > maxSize) {
      return false;
    }
    this.setLength((int) (newEnd - this.getOffset()));
    underlying.add(other);
    return true;
  }
}


text:
from storeApi.models               import *
from storeApi.serializers          import *
from rest_framework                import permissions
from rest_framework                import viewsets
from rest_framework                import filters
from taggit.models                 import Tag
from taggit_serializer.serializers import TaggitSerializer

class ProductViewSet(viewsets.ModelViewSet):
        queryset           = Product.objects.all()
        serializer_class   = ProductSerializer
        filter_backends = (filters.DjangoFilterBackend,)
        filter_fields = ('category','category__name', 'status')
        permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

class ProductImagesViewset(viewsets.ModelViewSet):
        queryset           = ProductImages.objects.all()
        serializer_class   = ProductImageSerializer
        filter_backends = (filters.DjangoFilterBackend,)
        filter_fields = ('product','product__name',)
        permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

class CategoryViewset(viewsets.ModelViewSet):
        queryset           = Category.objects.all()
        serializer_class   = CategorySerializer
        permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

class UserViewset(viewsets.ModelViewSet):
        queryset           = User.objects.all()
        serializer_class   = UserSerializer
        permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

class ShoppingCartProductViewset(viewsets.ModelViewSet):
        queryset           = ShoppingCartProduct.objects.all()
        serializer_class   = ShoppingCartProductSerializer
        filter_backends = (filters.DjangoFilterBackend,)
        filter_fields = ('client',)
        permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

class OrderViewSet(viewsets.ModelViewSet):
        queryset           = Order.objects.all()
        serializer_class   = OrderSerializer
        filter_backends = (filters.DjangoFilterBackend,)
        filter_fields = ('client',)
        permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

class AdressViewSet(viewsets.ModelViewSet):
        queryset           = Adress.objects.all()
        serializer_class   = AdressSerializer
        filter_backends = (filters.DjangoFilterBackend,)
        filter_fields = ('client',)
        permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

class TaggitViewSet(viewsets.ModelViewSet):
        queryset           = Tag.objects.all()
        serializer_class   = TagSerializer
        permission_classes = (permissions.IsAuthenticatedOrReadOnly,)


text:
<!DOCTYPE html>

    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">


text:
module RoomHelper
  def find_room(id, params={}, &f)
    Room.with_room(id, current_user, params) do |room|
      if room.nil?
        flash[:error] = t(:error_room_deleted)
        redirect_to :controller => 'chat', :action => 'index'
      else
        f[room]
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Text;

using MatrixPath.Logic.Cells.Contracts;
using MatrixPath.Logic.Directions.Contracts;
using MatrixPath.Logic.Matrices.Contracts;
using MatrixPath.Logic.Values.Contracts;

namespace MatrixPath.Logic.Matrices
{
    public class BasicMatrix : IMatrix
    {
        private IList<IList<ICell>> matrix;
        private bool[][] visitedCellPositions;

        public BasicMatrix(int matrixSize, Func<int, int, int, ICell> createCell)
        {
            if (matrixSize <= 0)
            {
                throw new ArgumentOutOfRangeException("Matrix size must be larger than 0");
            }

            if (createCell == null)
            {
                throw new ArgumentNullException("createCell");
            }

            this.matrix = this.CreateTheMatrix(matrixSize, createCell);
            this.visitedCellPositions = this.InitializeVisitedFlags(matrixSize);
        }

        public void Populate(IPosition startPosition, IDirectionSequence directionsInstructions, ICellValueSequence valueProvider)
        {
            if (startPosition == null)
            {
                throw new ArgumentNullException(nameof(startPosition));
            }

            if (directionsInstructions == null)
            {
                throw new ArgumentNullException(nameof(directionsInstructions));
            }

            if (valueProvider == null)
            {
                throw new ArgumentNullException(nameof(valueProvider));
            }

            var position = startPosition.Clone();
            var direction = directionsInstructions.GetNextDirection();
            var initialDirection = direction.Clone();

            var matrixSize = this.matrix.Count;
            var matrixIsFilled = false;
            do
            {
                var nextCellValue = valueProvider.GetNextCellValue();
                this.matrix[position.Row][position.Col].Value = nextCellValue;
                this.visitedCellPositions[position.Row][position.Col] = true;

                var nextPosition = position.Clone();
                nextPosition = nextPosition.MoveInDirection(direction);

                var nextPositionIsFree = this.CheckIfPositionIsValidToMove(nextPosition, matrixSize);
                if (!nextPositionIsFree)
                {
                    for (int directionChangeCount = 1; directionChangeCount <= directionsInstructions.DirectionSequenceLength; directionChangeCount++)
                    {
                        var nextDirection = directionsInstructions.GetNextDirection();
                        var adjustedNextPosition = position.Clone();
                        adjustedNextPosition = adjustedNextPosition.MoveInDirection(nextDirection);

                        var adjustedNextPositionIsFree = this.CheckIfPositionIsValidToMove(adjustedNextPosition, matrixSize);
                        if (adjustedNextPositionIsFree)
                        {
                            nextPosition = adjustedNextPosition;
                            direction = nextDirection;
                            break;
                        }
                        else if (directionChangeCount == directionsInstructions.DirectionSequenceLength)
                        {
                            var positionToJumpTo = this.FindPositionToJumpTo(adjustedNextPosition, matrixSize);
                            if (positionToJumpTo == null)
                            {
                                matrixIsFilled = true;
                                break;
                            }
                            else
                            {
                                nextPosition = positionToJumpTo;
                                direction = initialDirection.Clone();
                            }
                        }
                    }
                }

                position = nextPosition;
            }
            while (!matrixIsFilled);
        }

        public override string ToString()
        {
            const string valueFormat = "{0,4}";

            var stringRepresentation = new StringBuilder();

            var matrixSize = this.matrix.Count;
            for (int row = 0; row < matrixSize; row++)
            {
                var currentRow = new StringBuilder();
                for (int col = 0; col < matrixSize; col++)
                {
                    var formattedValueToAppend = string.Format(valueFormat, this.matrix[row][col].Value);
                    currentRow.Append(formattedValueToAppend);
                }

                stringRepresentation.AppendLine(currentRow.ToString());
            }

            return stringRepresentation.ToString();
        }

        private IPosition FindPositionToJumpTo(IPosition position, int matrixSize)
        {
            IPosition newPosition = null;
            for (int row = 0; row < matrixSize; row++)
            {
                for (int col = 0; col < matrixSize; col++)
                {
                    if (!this.visitedCellPositions[row][col])
                    {
                        newPosition = position.MoveTo(row, col);
                        return newPosition;
                    }
                }
            }

            return newPosition;
        }

        private bool CheckIfPositionIsValidToMove(IPosition position, int matrixSize)
        {
            var isValid = true;

            var rowOutOfBounds = position.Row < 0 || matrixSize <= position.Row;
            var colOutOfBounds = position.Col < 0 || matrixSize <= position.Col;

            var isOutOfBounds = rowOutOfBounds || colOutOfBounds;
            if (isOutOfBounds)
            {
                isValid = false;
            }
            else
            {
                var cellIsVisited = this.visitedCellPositions[position.Row][position.Col];
                isValid = !cellIsVisited;
            }

            return isValid;
        }

        private IList<IList<ICell>> CreateTheMatrix(int size, Func<int, int, int, ICell> createCell)
        {
            var cellDefaultValue = 0;
            var theMatrix = new List<IList<ICell>>();
            for (int rowIndex = 0; rowIndex < size; rowIndex++)
            {
                var nextMatrixRow = new List<ICell>();
                for (int colIndex = 0; colIndex < size; colIndex++)
                {
                    var cellToAdd = createCell(rowIndex, colIndex, cellDefaultValue);
                    nextMatrixRow.Add(cellToAdd);
                }

                theMatrix.Add(nextMatrixRow);
            }

            return theMatrix;
        }

        private bool[][] InitializeVisitedFlags(int size)
        {
            var flags = new bool[size][];
            for (int row = 0; row < size; row++)
            {
                flags[row] = new bool[size];
            }

            return flags;
        }
    }
}