text:
package org.pac4j.openid.client;

import org.openid4java.consumer.ConsumerManager;
import org.pac4j.core.client.IndirectClient;
import org.pac4j.openid.credentials.OpenIdCredentials;
import org.pac4j.openid.credentials.authenticator.YahooAuthenticator;
import org.pac4j.openid.credentials.extractor.YahooCredentialsExtractor;
import org.pac4j.openid.profile.yahoo.YahooOpenIdProfile;
import org.pac4j.openid.redirect.YahooRedirectActionBuilder;

/**
 *
This class is the OpenID client to authenticate users with their yahoo account.

 *
It returns a {@link org.pac4j.openid.profile.yahoo.YahooOpenIdProfile}.

 *
 * @see org.pac4j.openid.profile.yahoo.YahooOpenIdProfile
 * @author Patrice de Saint Steban
 * @since 1.6.0
 */
public class YahooOpenIdClient extends IndirectClient<OpenIdCredentials, YahooOpenIdProfile> {

    public final static String DISCOVERY_INFORMATION = "discoveryInformation";

    private ConsumerManager consumerManager;

    @Override
    protected void clientInit() {
        this.consumerManager = new ConsumerManager();
        defaultRedirectActionBuilder(new YahooRedirectActionBuilder(this));
        defaultCredentialsExtractor(new YahooCredentialsExtractor(this));
        defaultAuthenticator(new YahooAuthenticator(this));
    }

    /**
     * Return the name of the attribute storing in session the discovery information.
     *
     * @return the name of the attribute storing in session the discovery information
     */
    public String getDiscoveryInformationSessionAttributeName() {
        return getName() + "#" + DISCOVERY_INFORMATION;
    }

    public ConsumerManager getConsumerManager() {
        return consumerManager;
    }
}


text:
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents**  *generated with [DocToc](https://github.com/thlorenz/doctoc)*

- [TuticfrutiBootstrap3 Sublime Text Plugin](#tuticfrutibootstrap3-sublime-text-plugin)
- [Features](#features)
- [Pre-requisites](#pre-requisites)
- [Getting Started](#getting-started)
- [Snippets](#snippets)
  - [CSS](#css)
    - [Grid system](#grid-system)
      - [Snippets](#snippets-1)
      - [Classes](#classes)
    - [Typography](#typography)
      - [Snippets](#snippets-2)
      - [Classes](#classes-1)
    - [Code](#code)
      - [Snippets](#snippets-3)
      - [Classes](#classes-2)
    - [Tables](#tables)
      - [Snippets](#snippets-4)
      - [Classes](#classes-3)
      - [Demo](#demo)
    - [Forms](#forms)
      - [Snippets](#snippets-5)
      - [Classes](#classes-4)
      - [Demo](#demo-1)
    - [Buttons](#buttons)
      - [Snippets](#snippets-6)
      - [Classes](#classes-5)
      - [Demo](#demo-2)
    - [Images](#images)
      - [Snippets](#snippets-7)
      - [Classes](#classes-6)
      - [Demo](#demo-3)
    - [Helper classes](#helper-classes)
      - [Snippets](#snippets-8)
      - [Classes](#classes-7)
      - [Demo](#demo-4)
    - [Responsive utilities](#responsive-utilities)
      - [Classes](#classes-8)
  - [Components](#components)
    - [Glyphicons](#glyphicons)
      - [Snippets](#snippets-9)
      - [Classes](#classes-9)
      - [Demo](#demo-5)
    - [Dropdowns](#dropdowns)
      - [Snippets](#snippets-10)
      - [Classes](#classes-10)
      - [Demo](#demo-6)
    - [Button groups](#button-groups)
      - [Snippets](#snippets-11)
      - [Classes](#classes-11)
      - [Demo](#demo-7)
    - [Input groups](#input-groups)
      - [Snippets](#snippets-12)
      - [Classes](#classes-12)
      - [Demo](#demo-8)
    - [Navs](#navs)
      - [Snippets](#snippets-13)
      - [Classes](#classes-13)
      - [Demo](#demo-9)
    - [Navbar](#navbar)
      - [Snippets](#snippets-14)
      - [Classes](#classes-14)
      - [Demo](#demo-10)
    - [Breadcrumb](#breadcrumb)
      - [Snippets](#snippets-15)
      - [Classes](#classes-15)
      - [Demo](#demo-11)
    - [Pagination](#pagination)
      - [Snippets](#snippets-16)
      - [Classes](#classes-16)
      - [Demo](#demo-12)
    - [Labels](#labels)
      - [Snippets](#snippets-17)
      - [Classes](#classes-17)
      - [Demo](#demo-13)
    - [Badges](#badges)
      - [Snippets](#snippets-18)
      - [Classes](#classes-18)
      - [Demo](#demo-14)
    - [Jumbotron](#jumbotron)
      - [Snippets](#snippets-19)
      - [Classes](#classes-19)
      - [Demo](#demo-15)
    - [Page header](#page-header)
      - [Snippets](#snippets-20)
      - [Classes](#classes-20)
      - [Demo](#demo-16)
    - [Tumbnails](#tumbnails)
      - [Snippets](#snippets-21)
      - [Classes](#classes-21)
      - [Demo](#demo-17)
    - [Alerts](#alerts)
      - [Snippets](#snippets-22)
      - [Classes](#classes-22)
      - [Demo](#demo-18)
    - [Progress bars](#progress-bars)
      - [Snippets](#snippets-23)
      - [Classes](#classes-23)
      - [Demo](#demo-19)
    - [Media object](#media-object)
      - [Snippets](#snippets-24)
      - [Classes](#classes-24)
      - [Demo](#demo-20)
    - [List group](#list-group)
      - [Snippets](#snippets-25)
      - [Classes](#classes-25)
      - [Demo](#demo-21)
    - [Panels](#panels)
      - [Snippets](#snippets-26)
      - [Classes](#classes-26)
      - [Demo](#demo-22)
    - [Responsive embed](#responsive-embed)
      - [Snippets](#snippets-27)
      - [Classes](#classes-27)
    - [Wells](#wells)
      - [Snippets](#snippets-28)
      - [Classes](#classes-28)
      - [Demo](#demo-23)
  - [Javascript](#javascript)
  - [Templates](#templates)
      - [Snippets](#snippets-29)
- [TODO](#todo)
- [License](#license)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

# TuticfrutiBootstrap3 Sublime Text Plugin
A complete and reusable set of Bootstrap3 snippets for Sublime Text editor.

# Features
- [Bootstrap3](http://getbootstrap.com/).
- [Bootstrap3 classes auto-completion](https://github.com/tuticfruti/TuticfrutiBootstrap3/blob/master/snippets/all-classes.sublime-completions "all-classes.sublime-completions").
- [CSS snippets](http://getbootstrap.com/css/).
- [Components snippets](http://getbootstrap.com/components/)
- [Javascript snippets](http://getbootstrap.com/javascript/) (comming soon) snippets.
- Reusable components.
- [Youtube video demos](https://www.youtube.com/playlist?list=PLL0QEvkK-t2BxBobyy2C1P_JHg6zdeaMs "TuticfrutiBootstrap3 playlist").

# Pre-requisites
- Sublime text 2&3.
- Bootstrap 3.
- Package manager if you install from package manager.

# Getting Started
Installation.
    Manual installation. ZIP.
    Add repository. Local package manager.
    From packages.io. Install package manager.

How to use.
    Two types of snippets: classes snippets (into tag element double quotes) and component snippets (into html document, not into tag element).

    Alt + / (Edit > Show Completions menu option)

All component snippets begins with 'b' (Bootstrap) key. Class snippets are Bootstrap class literals.

Examples:

# Snippets

## CSS
### Grid system
Bootstrap includes a responsive, mobile first fluid grid system that appropriately scales up to 12 columns as the device or viewport size increases.

####Snippets
| Snippet                     | Tab trigger          |
| --------------------------- | -------------------- |
| Container & fluid container | `bcontainer`         |
| Grid row                    | `brow`               |
| Grid column                 | `bcol`               |

####Classes
- `container`
- `container-fluid`
- `row`
- `col`
- `col-(xs|sm|md|lg)-(1-12)`
- `col-(xs|sm|md|lg)-push-(1-12)`
- `col-(xs|sm|md|lg)-pull-(1-12)`
- `col-(xs|sm|md|lg)-offset-(1-12)`

### Typography

####Snippets
| Snippet                      | Tab trigger |
| ---------------------------- | ------------|
| Headings                     | `btexth`    |
| Lead body copy               | `btextle`   |
| Marked text                  | `btextm`    |
| Small text                   | `btexts`    |
| Alignment classes            | `btexta`    |
| Transformation classes       | `btextt`    |
| Initialism                   | `btexti`    |
| Blockquote with footer       | `btextb`    |
| Lists (unstyled|inline)      | `btextli`   |
| Horizontal description list  | `btexthd`   |

####Classes
- `h(1-6)`
- `lead`
- `mark`
- `small`
- `text-(left|center|right|justify|nowrap)`
- `text-(lowercase|uppercase|capitalize)`
- `initialism`
- `blockquote-reverse`
- `list-(style|unstyled|inline)`
- `dl-horizontal`

### Code

####Snippets
| Snippet           | Tab trigger |
| ----------------- | ------------|
| Block scrollable  | `bcodebs`   |

####Classes
- `pre-scrollable`

### Tables

####Snippets
| Snippet           | Tab trigger |
| ----------------- | ------------|
| Default table     | `btabled`   |
| Responsive table  | `btabler`   |
| Table row         | `btr`       |
| Table td          | `btd`       |
| Table th          | `bth`       |

####Classes
- `table`
- `table-responsive`
- `table-stripped`
- `table-bordered`
- `table-hover`
- `table-condensed`
- `active|success|info|warning|danger`

####Demo
[Tables demo](https://youtu.be/6pzlxSeV8Ik).

### Forms

####Snippets
| Snippet                 | Tab trigger |
| ----------------------- | ------------|
| Default form            | `bformd`    |
| Default form group      | `bformg`    |
| Input control           | `bctrli`    |
| Inline input control    | `bctrlii`   |
| Textarea control        | `bctrlt`    |
| Radio control           | `bctrlr`    |
| Inline Radio control    | `bctrlri`   |
| Checkbox control        | `bctrlc`    |
| Inline checkbox control | `bctrlci`   |
| Select control          | `bctrlse`   |
| Inline select control   | `bctrlsei`  |
| Static control          | `bctrlst`   |
| Inline static control   | `bctrlsti`  |
| Submit button           | `bctrlsu`   |
| Inline submit button    | `bctrlsui`  |
| Help text               | `bctrlht`   |
| Label                   | `bctrll`    |
| Inline Label            | `bctrlli`   |
| Field set               | `bformf`    |

####Classes
- `form-inline`
- `form-horizontal`
- `form-group`
- `form-group-(sm|lg)`
- `form-control`
- `text|password|datetime|date|month|time|week|number|email|url|search|tel|color|datetime-local`
- `radio`
- `radio-inline`
- `checkbox`
- `checkbox-inline`
- `control-label`
- `form-control-static`
- `active`
- `desabled`
- `readonly`
- `has-(success|warning|error)`
- `input(sm|lg)`
- `help-block`

####Demo
[Forms demo](https://youtu.be/8V3Imk1gRKk).

### Buttons

####Snippets
| Snippet           | Tab trigger |
| ----------------- | ------------|
| Default button    | `bbtnd`     |
| Link button       | `bbtnl`     |

####Classes
- `btn`
- `btn-(default|primary|success|info|warning|danger|link)`
- `btn-(xs|sm|lg)`
- `btn-block`
- `active`
- `disabled`

####Demo
[Buttons demo](https://youtu.be/Yj83bzlKlNU).

### Images

####Snippets
| Snippet           | Tab trigger |
| ----------------- | ------------|
| Default image     | `bimaged`   |

####Classes
- `img-responsive`
- `img-rounded`
- `img-circle`
- `img-thumbnail`

####Demo
[Images demo](https://youtu.be/P6F72Ju-fnU).

### Helper classes

####Snippets
| Snippet                | Tab trigger  |
| ---------------------- | -------------|
| Contextual colors      | `bhelperco`  |
| Contextual backgrounds | `bhelperb`   |
| Close icon             | `bhelperci`  |
| Carets                 | `bhelperca`  |
| Quick floats           | `bhelperf`   |
| Center content blocks  | `bhelpercb`  |
| Clearfix               | `bhelpercl`  |
| Showing and hiding     | `bhelperv`   |
| Screen reader default  | `bhelpersrd` |
| Screen reader link     | `bhelpersrl` |

####Classes
- `text-(muted|primary|success|info|warning|danger)`
- `bg-(primary|success|info|warning|danger)`
- `caret`
- `pull-(left|right)`
- `center-block`
- `clearfix`
- `show|hidden`
- `sr-only`
- `sr-only-focusable`
- `text-hide`

####Demo
[Helpers demo](https://youtu.be/S2AzJ9Z5OFc).

### Responsive utilities
For faster mobile-friendly development, use these utility classes for showing and hiding content by device via media query. Also included are utility classes for toggling content when printed.

####Classes
- `visible-(xs|sm|md|lg)`
- `visible-(xs|sm|md|lg)-block`
- `visible-(xs|sm|md|lg)-inline`
- `visible-(xs|sm|md|lg)-inline-block`
- `hidden-(xs|sm|md|lg)`
- `visible-print-(block|inline|inline-block)`
- `hidden-print`

## Components

### Glyphicons
Includes over 250 glyphs in font format from the Glyphicon Halflings set ([Glyphicons homepage](http://glyphicons.com/)).

####Snippets
| Snippet           | Tab trigger          |
| ----------------- | -------------------- |
| Default glyphicon | `bglyphicon-default` |
| Glyphicon button  | `bbutton-glyphicon`  |

####Classes
- `glyphicon`
- `glyphicon-(home|user|star|exclamation-sign|...)`

####Demo
[Glyphicons demo](https://youtu.be/u9JYaSSVgUM).

### Dropdowns
Toggleable, contextual menu for displaying lists of links. Made interactive with the dropdown JavaScript plugin.

#### Snippets
| Snippet                | Tab trigger               |
| ---------------------- | ------------------------- |
| Default dropdown       | `bdropdown-default`       |
| Default dropdown item  | `bbutton-glyphicon`       |
| Header dropdown item   | `bdropdown-item-header`   |
| Divider dropdown item  | `bdropdown-item-divider`  |
| Active dropdown item   | `bdropdown-item-active`   |
| Disabled dropdown item | `bdropdown-item-disabled` |

####Classes
- `dropdown`
- `dropup`
- `dropdown-menu`
- `dropdown-menu-left`
- `dropdown-menu-right`
- `dropdown-header`
- `active`
- `disabled`
- `divider`
- `separator`

####Demo
[Dropdowns demo](https://youtu.be/3w0m4IR4kEY).

### Button groups
Group a series of buttons together on a single line with the button group. For more complex components, combine sets of button groups into a button toolbar.

#### Snippets
| Snippet                | Tab trigger               |
| ---------------------- | ------------------------- |
| Default button group   | `bbutton-group-default`   |
| Justified button group | `bbutton-group-justified` |
| Button toolbar         | `bbutton-toolbar`         |

#### Classes
- `btn-group`
- `btn-toolbar`
- `btn-group-(xs|sm|lg)`
- `btn-group-vertical`
- `btn-group-justified`

#### Demo
[Button groups demo](https://youtu.be/BgqjRGxhD-4).

### Input groups
Extend form controls by adding text or buttons before, after, or on both sides of any text-based `<input>`.

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Default input group            | `binput-group-default`        |
| Checkboxes and radio addon     | `binput-group-radio-checkbox` |
| Button with dropdown           | `binput-group-dropdown`       |
| Button addon                   | `binput-group-button`         |
| Segmented buttons              | `binput-group-split`          |

#### Classes
- `input-group`
- `input-group-addon`
- `input-group-(sm|lg)`
- `input-group-btn`

#### Demo
[Input groups demo](https://youtu.be/-Hj7GBi3Ecs).

### Navs

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Default nav                    | `bnav-default`                |
| Default nav item               | `bnav-item-default`           |
| Active nav item                | `bnav-item-active`            |
| Disabled nav item              | `bnav-item-disable`           |

#### Classes
- `nav`
- `nav-(tabs|pills)`
- `nav-stacked`
- `nav-justified`
- `active|disabled`

#### Demo
[Nav demo](https://youtu.be/LRAFHiGdSew).

### Navbar
Navbars are responsive meta components that serve as navigation headers for your application or site.

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Default navbar                 | `bnavbar-default`             |
| Navbar button item             | `bnavbar-item-button`         |
| Navbar divider item            | `bnavbar-item-divider`        |
| Navbar dropdown item           | `bnavbar-item-dropdown`       |
| Navbar link item               | `bnavbar-item-link`           |
| Navbar text item               | `bnavbar-item-text`           |
| Navbar form item               | `bnavbar-item-form`           |
| Navbar Brand image item        | `bnavbar-item-brand-image`    |

#### Classes
- `navbar`
- `bavbar-default`
- `navbar-header`
- `navbar-toggle`
- `collapsed`
- `icon-bar`
- `navbar-brand`
- `navbar-nav`
- `divider`
- `navbar-(left|right)`
- `navbar-btn`
- `navbar-text`
- `navbar-fixed-(top|bottom)`
- `navbar-static-top`
- `navbar-inverse`

#### Demo
[Navbar demo](https://youtu.be/E-7GAsUgx7Y).

### Breadcrumb

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Default breadcrumb             | `bbreadcrumb-default`         |
| Default breadcrumb item        | `bbreadcrumb-item-default`    |
| Active breadcrumb item         | `bbreadcrumb-item-active`     |

#### Classes
- `breadcrumb`
- `active`

#### Demo
[Breadcrumb demo](https://youtu.be/Y3a1nW6Xztc).

### Pagination
Provide pagination links for your site or app with the multi-page pagination component, or the simpler pager alternative.

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Default pagination             | `bpagination-default`         |
| Default pagination item        | `bpagination-item-default`    |
| Active pagination item         | `bpagination-item-active`     |
| Disabled pagination item       | `bpagination-item-disable`    |
| Pager                          | `bpagination-pager`         |

#### Classes
- `pagination`
- `pagination-(sm|lg)`
- `active|disabled`
- `pager`
- `previous|next`

#### Demo
[Pagination demo](https://youtu.be/t9RukSB-kqQ).

### Labels

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Default label                  | `blabel-default`              |
| Inline label                   | `blabel-inline`               |

#### Classes
- `label`
- `label-(default|primary|success|info|warning|danger)`

#### Demo
[Labels demo](https://youtu.be/T0VwT39qNH4).

### Badges

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Button badge                   | `bbadge-button`               |
| Link badge                     | `bbadge-link`                 |

#### Classes
- `badge`
- `active`

#### Demo
[Badges demo](https://youtu.be/xZCCkxFu_40).

### Jumbotron

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Jumbotron                      | `bjumbotron`                  |

#### Classes
- `jumbotron`

#### Demo
[Jumbotron demo](https://youtu.be/lqlq9XrxEgY).

### Page header

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Default page header                    | `bpage-header`                |

#### Classes
- `page-header`

#### Demo
[Page headers demo](https://youtu.be/gKTKujmXjKU).

### Tumbnails
Extend Bootstrap's grid system with the thumbnail component to easily display grids of images, videos, text, and more.

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Default thumbnail              | `bthumbnail-default`          |

#### Classes
- `thumbnail`

#### Demo
[Thumbnails demo](https://youtu.be/MK-CwiG3LW0).

### Alerts
Provide contextual feedback messages for typical user actions with the handful of available and flexible alert messages.

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Default alert                  | `balert-default`              |
| Dismissible alert              | `balert-dismissible`          |
| Alert link                     | `balert-link`                 |

#### Classes
- `alert`
- `alert-(success|info|warning|danger)`
- `alert-dismissible`
- `alert-link`

#### Demo
[Alerts demo](https://youtu.be/JkR88QLstZw).

### Progress bars
Provide up-to-date feedback on the progress of a workflow or action with simple yet flexible progress bars.

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Default progress bar           | `bprogress-bar-default`       |
| Stacked progress bars          | `bprogress-bar-stack`         |

#### Classes
- `progress`
- `progress-bar`
- `progress-bar-(success|info|warning|danger)`
- `progress-bar-striped`
- `active` (animated)

#### Demo
[Progress bars demo](https://youtu.be/DDp_lvrUxSw).

### Media object

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Default media                  | `bmedia-default`              |
| Media list                     | `bmedia-list`                 |
| Media item                     | `bmedia-item-default`         |

#### Classes
- `media`
- `media-(left|right)`
- `media-object`
- `media-body`
- `media-heading`
- `media-list`

#### Demo
[Media object demo](https://youtu.be/4iHBV06jGC4).

### List group
List groups are a flexible and powerful component for displaying not only simple lists of elements, but complex ones with custom content.

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Default list group             | `blist-group-default`         |
| Default item                   | `blist-group-item-default`    |
| Badge item                     | `blist-group-item-badge`      |
| Button item                    | `blist-group-item-button`     |
| Link item                      | `blist-group-item-link`       |
| Context item                   | `blist-group-item-context`    |
| Custom item                    | `blist-group-item-custom`     |

#### Classes
- `list-group`
- `list-group-item`
- `badge`
- `active|disabled`
- `list-group-item-(success|info|warning|danger)`
- `list-group-item-heading`
- `list-group-item-text`

#### Demo
[List groups demo](https://youtu.be/zDB_pL3-IqE).

### Panels
While not always necessary, sometimes you need to put your DOM in a box. For those situations, try the panel component.

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Default panel                  | `bpanel-default`              |

#### Classes
- `panel`
- `panel-heading`
- `panel-footer`
- `panel-title`
- `panel-(default|primary|success|info|warning|danger)`

#### Demo
[Panels demo](https://youtu.be/AFYFt8Wja_U).

### Responsive embed

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Responsive embed               | `bembed-responsive`           |

#### Classes
- `embed-responsive`
- `embed-responsive-item`
- `embed-responsive-16by9`
- `embed-responsive-4by3`

### Wells

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Default well                   | `bwell-default`               |

#### Classes
- `well`
- `well-(sm|lg)`

#### Demo
[Well demo](https://youtu.be/HDwzV6NJpCo).

## Javascript
Comming soon.

## Templates

#### Snippets
| Snippet                        | Tab trigger                   |
| ------------------------------ | ----------------------------- |
| Default template               | `btemplate-default`           |

#TODO
- Javascript Bootstrap3 support.

# License
**The MIT License (MIT)**

**Copyright (c) 2015 tuticfruti**

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:padding="@dimen/margin_small">

    <ProgressBar
        android:id="@+id/progress_bar"
        style="@style/Widget.AppCompat.ProgressBar"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_gravity="center"/>

    <TextView
        android:id="@+id/progress_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/no_more_load_retry"
        android:layout_gravity="center"
        android:visibility="gone"
        tools:visibility="visible"/>

</FrameLayout>


text:
<?php

class BL_CustomGrid_Block_Custom_Column_Config extends BL_CustomGrid_Block_Config_Container_Abstract
{
    protected $_blockGroup = 'customgrid';
    protected $_mode = 'config';

    protected function _beforeToHtml()
    {
        $this->_formScripts[] =  $this->getJsObjectName() . ' = new blcg.Grid.CustomColumn.ConfigForm('
            . '"blcg_custom_column_config_form", '
            . '"' . $this->getConfigTargetId() . '"'
            . ');';

        if ($formBlock = $this->getChild('form')) {
            $formBlock->setConfigValues($this->getConfigValues());
        }

        return parent::_beforeToHtml();
    }

    public function getCustomColumn()
    {
        return Mage::registry('blcg_custom_column');
    }

    protected function _getController()
    {
        return 'custom_column';
    }

    protected function _getHeaderText()
    {
        return $this->getCustomColumn()->getName();
    }

    protected function _getSaveButtonId()
    {
        return 'blcg_custom_column_config_insert_button';
    }

    public function getJsObjectName()
    {
        return 'blcgCustomColumnConfigForm';
    }

    public function getUseDefaultForm()
    {
        return false;
    }

    public function getConfigTargetId()
    {
        return $this->getDataSetDefault('config_target_id', '');
    }
}


text:
RC TEST_RM_13(const string &tableName)
{
    // Functions Tested:
    // 1. Conditional scan
    cout << endl << "***** In RM Test Case 13 *****" << endl;

    RID rid;
    int tupleSize = 0;
    int numTuples = 500;
    void *tuple;
    void *returnedData = malloc(200);
    int ageVal = 25;
    int age = 0;

    RID rids[numTuples];
    vector<char *> tuples;

    // GetAttributes
    vector<Attribute> attrs;
    RC rc = rm->getAttributes(tableName, attrs);
    assert(rc == success && "RelationManager::getAttributes() should not fail.");

    int nullAttributesIndicatorActualSize = getActualByteForNullsIndicator(attrs.size());
    unsigned char *nullsIndicator = (unsigned char *) malloc(nullAttributesIndicatorActualSize);
	memset(nullsIndicator, 0, nullAttributesIndicatorActualSize);

    for(int i = 0; i < numTuples; i++)
    {
        tuple = malloc(100);

        // Insert Tuple
        float height = (float)i;

        age = (rand()%20) + 15;

        prepareTuple(attrs.size(), nullsIndicator, 6, "Tester", age, height, 123, tuple, &tupleSize);
        rc = rm->insertTuple(tableName, tuple, rid);
        assert(rc == success && "RelationManager::insertTuple() should not fail.");

        rids[i] = rid;
    }

    // Set up the iterator
    RM_ScanIterator rmsi;
    string attr = "Age";
    vector<string> attributes;
    attributes.push_back(attr);
    rc = rm->scan(tableName, attr, GT_OP, &ageVal, attributes, rmsi);
    assert(rc == success && "RelationManager::scan() should not fail.");

    while(rmsi.getNextTuple(rid, returnedData) != RM_EOF)
    {
    	age = *(int *)((char *)returnedData+1);
    	if (age <= ageVal) {
    		cout << "Returned value from a scan is not correct." << endl;
    	    cout << "***** [FAIL] Test Case 13 Failed *****" << endl << endl;
    	    rmsi.close();
    	    free(returnedData);
    	    return -1;
    	}
    }
    rmsi.close();
    free(returnedData);

    cout << "***** [PASS] Test Case 13 Passed *****" << endl << endl;

    return success;
}

int main()
{
	// Scan with conditions
    RC rcmain = createTable("tbl_b_employee4");
    rcmain = TEST_RM_13("tbl_b_employee4");

    return rcmain;
}


text:
<?php
/***
 * Custom Javascript Options
 *
 * Passing Variables from custom Theme Options to the javascript files
 * of theme navigation and frontpage slider.
 *
 */

// Passing Variables to Theme Navigation ( js/navigation.js)
add_action('wp_enqueue_scripts', 'dynamicnews_custom_jscript_navigation');

if ( ! function_exists( 'dynamicnews_custom_jscript_navigation' ) ):
function dynamicnews_custom_jscript_navigation() {

	// Set Parameters array
	$params = array(
		'menuTitle' => __('Menu', 'dynamicnewslite')
	);

	// Passing Parameters to Javascript
	wp_localize_script( 'dynamicnewslite-jquery-navigation', 'dynamicnews_navigation_params', $params );
}
endif;

// Passing Variables to Frontpage Slider ( js/slider.js)
add_action('wp_enqueue_scripts', 'dynamicnews_custom_jscript_slider');

if ( ! function_exists( 'dynamicnews_custom_jscript_slider' ) ):
function dynamicnews_custom_jscript_slider() {

	// Get Theme Options from Database
	$theme_options = dynamicnews_theme_options();

	// Set Parameters array
	$params = array();

	// Define Slider Animation
	if( isset($theme_options['slider_animation']) ) :
		$params['animation'] = esc_attr($theme_options['slider_animation']);
	endif;

	// Passing Parameters to Javascript
	wp_localize_script( 'dynamicnewslite-jquery-frontpage_slider', 'dynamicnews_slider_params', $params );
}
endif;

?>


text:
#ifndef NRF_CRYPTO_SW_HASH_H__
#define NRF_CRYPTO_SW_HASH_H__

/** @file
 *
 * @defgroup nrf_crypto_sw_hash Software-based hashing using sha256
 * @{
 * @ingroup nrf_crypto_backend_microecc
 *
 * @brief Macros for type sizes in nrf_crypt SW backend.
 */

#include <stdint.h>
#include "nrf_crypto_types.h"
#include "sha256.h"

#ifdef __cplusplus
extern "C" {
#endif

/** @brief Size of buffer required for hash context object.
 */
#define NRF_CRYPTO_HASH_CONTEXT_SIZE sizeof(sha256_context_t)

#ifdef __cplusplus
}
#endif

/** @} */

#endif // #ifndef NRF_CRYPTO_HASH_H__


text:
[![Github-CI][github-ci]][github-link]
[![Code style: black][black-badge]][black-link]

[github-ci]: https://github.com/Robpol86/sphinx-carousel/actions/workflows/ci.yml/badge.svg?branch=main
[github-link]: https://github.com/Robpol86/sphinx-carousel/actions/workflows/ci.yml
[black-badge]: https://img.shields.io/badge/code%20style-black-000000.svg
[black-link]: https://github.com/ambv/black

My personal website.

Built with [Sphinx](http://sphinx-doc.org/), hosted on [NearlyFreeSpeech.NET](https://www.nearlyfreespeech.net/), using the
[Sphinx Book Theme](https://sphinx-book-theme.readthedocs.io/) theme. SSL is provided for free by
[CloudFlare](https://www.cloudflare.com/).

I use GitHub Actions to automatically build and push HTML files to NFSN.

## Metrics

Google Analytics is enabled on my website via a [CloudFlare app](https://www.cloudflare.com/apps/googleanalytics).

* [Google Analytics](https://analytics.google.com/analytics/web/#/p275999550/reports/intelligenthome)
* [Google Search Console](https://search.google.com/search-console?resource_id=https%3A%2F%2Frobpol86.com%2F)

## Releases

Deployments to production are done by GitHub Actions when a new tag matching the format YYYY-MM-DD is manually pushed. All
branch and tag pushes trigger a deployment to staging, whilst pull requests only trigger CI linting and testing.


text:
/*!
    An application that runs in the system tray.

    Requires the following features: `cargo run --example system_tray --features "tray-notification message-window menu cursor"`
*/
extern crate native_windows_gui as nwg;
use nwg::NativeUi;

#[derive(Default)]
pub struct SystemTray {
    window: nwg::MessageWindow,
    icon: nwg::Icon,
    tray: nwg::TrayNotification,
    tray_menu: nwg::Menu,
    tray_item1: nwg::MenuItem,
    tray_item2: nwg::MenuItem,
    tray_item3: nwg::MenuItem,
}

impl SystemTray {

    fn show_menu(&self) {
        let (x, y) = nwg::GlobalCursor::position();
        self.tray_menu.popup(x, y);
    }

    fn hello1(&self) {
        nwg::modal_info_message(&self.window, "Hello", "Hello World!");
    }

    fn hello2(&self) {
        let flags = nwg::TrayNotificationFlags::USER_ICON | nwg::TrayNotificationFlags::LARGE_ICON;
        self.tray.show("Hello World", Some("Welcome to my application"), Some(flags), Some(&self.icon));
    }

    fn exit(&self) {
        nwg::stop_thread_dispatch();
    }

}

//
// ALL of this stuff is handled by native-windows-derive
//
mod system_tray_ui {
    use native_windows_gui as nwg;
    use super::*;
    use std::rc::Rc;
    use std::cell::RefCell;
    use std::ops::Deref;

    pub struct SystemTrayUi {
        inner: Rc<SystemTray>,
        default_handler: RefCell<Vec<nwg::EventHandler>>
    }

    impl nwg::NativeUi<SystemTrayUi> for SystemTray {
        fn build_ui(mut data: SystemTray) -> Result<SystemTrayUi, nwg::NwgError> {
            use nwg::Event as E;

            // Resources
            nwg::Icon::builder()
                .source_file(Some("./test_rc/cog.ico"))
                .build(&mut data.icon)?;

            // Controls
            nwg::MessageWindow::builder()
                .build(&mut data.window)?;

            nwg::TrayNotification::builder()
                .parent(&data.window)
                .icon(Some(&data.icon))
                .tip(Some("Hello"))
                .build(&mut data.tray)?;

            nwg::Menu::builder()
                .popup(true)
                .parent(&data.window)
                .build(&mut data.tray_menu)?;

            nwg::MenuItem::builder()
                .text("Hello")
                .parent(&data.tray_menu)
                .build(&mut data.tray_item1)?;

            nwg::MenuItem::builder()
                .text("Popup")
                .parent(&data.tray_menu)
                .build(&mut data.tray_item2)?;

            nwg::MenuItem::builder()
                .text("Exit")
                .parent(&data.tray_menu)
                .build(&mut data.tray_item3)?;

            // Wrap-up
            let ui = SystemTrayUi {
                inner: Rc::new(data),
                default_handler: Default::default(),
            };

            // Events
            let evt_ui = Rc::downgrade(&ui.inner);
            let handle_events = move |evt, _evt_data, handle| {
                if let Some(evt_ui) = evt_ui.upgrade() {
                    match evt {
                        E::OnContextMenu =>
                            if &handle == &evt_ui.tray {
                                SystemTray::show_menu(&evt_ui);
                            }
                        E::OnMenuItemSelected =>
                            if &handle == &evt_ui.tray_item1 {
                                SystemTray::hello1(&evt_ui);
                            } else if &handle == &evt_ui.tray_item2 {
                                SystemTray::hello2(&evt_ui);
                            } else if &handle == &evt_ui.tray_item3 {
                                SystemTray::exit(&evt_ui);
                            },
                        _ => {}
                    }
                }
            };

            ui.default_handler.borrow_mut().push(
                nwg::full_bind_event_handler(&ui.window.handle, handle_events)
            );

            return Ok(ui);
        }
    }

    impl Drop for SystemTrayUi {
        /// To make sure that everything is freed without issues, the default handler must be unbound.
        fn drop(&mut self) {
            let mut handlers = self.default_handler.borrow_mut();
            for handler in handlers.drain(0..) {
                nwg::unbind_event_handler(&handler);
            }
        }
    }

    impl Deref for SystemTrayUi {
        type Target = SystemTray;

        fn deref(&self) -> &SystemTray {
            &self.inner
        }
    }

}

fn main() {
    nwg::init().expect("Failed to init Native Windows GUI");
    let _ui = SystemTray::build_ui(Default::default()).expect("Failed to build UI");
    nwg::dispatch_thread_events();
}


text:
using System.Linq;
using Aurora.Simulation.Base;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Aurora.Framework;
using Aurora.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;

namespace OpenSim.Services.MessagingService
{
    public class MessagingServiceInHandler : IService, IAsyncMessageRecievedService, IGridRegistrationUrlModule
    {
        protected bool m_enabled;

        private IRegistryCore m_registry;

        public string Name
        {
            get { return GetType().Name; }
        }

        public bool DoMultiplePorts { get { return false; } }

        #region IAsyncMessageRecievedService Members

        public event MessageReceived OnMessageReceived;

        public OSDMap FireMessageReceived(string SessionID, OSDMap message)
        {
            OSDMap result = null;
            if (OnMessageReceived != null)
            {
                MessageReceived eventCopy = OnMessageReceived;
                foreach (OSDMap r in from MessageReceived messagedelegate in eventCopy.GetInvocationList() select messagedelegate(message) into r where r != null select r)
                {
                    result = r;
                }
            }
            return result;
        }

        #endregion

        #region IGridRegistrationUrlModule Members

        public string UrlName
        {
            get { return "MessagingServerURI"; }
        }

        public void AddExistingUrlForClient(string SessionID, string url, uint port)
        {
            IHttpServer server = m_registry.RequestModuleInterface<ISimulationBase>().GetHttpServer(port);

            server.AddStreamHandler(new MessagingServiceInPostHandler(url, m_registry, this, SessionID));
        }

        public string GetUrlForRegisteringClient(string SessionID, uint port)
        {
            string url = "/messagingservice" + UUID.Random();

            IHttpServer server = m_registry.RequestModuleInterface<ISimulationBase>().GetHttpServer(port);

            server.AddStreamHandler(new MessagingServiceInPostHandler(url, m_registry, this, SessionID));

            return url;
        }

        public void RemoveUrlForClient(string sessionID, string url, uint port)
        {
            IHttpServer server = m_registry.RequestModuleInterface<ISimulationBase>().GetHttpServer(port);
            server.RemoveHTTPHandler("POST", url);
        }

        #endregion

        #region IService Members

        public void Initialize(IConfigSource config, IRegistryCore registry)
        {
            IConfig handlerConfig = config.Configs["Handlers"];
            if (handlerConfig.GetString("MessagingServiceInHandler", "") != Name)
                return;
            registry.RegisterModuleInterface<IAsyncMessageRecievedService>(this);
            m_enabled = true;
        }

        public void Start(IConfigSource config, IRegistryCore registry)
        {
            m_registry = registry;
            if (!m_enabled)
            {
                IAsyncMessageRecievedService service = registry.RequestModuleInterface<IAsyncMessageRecievedService>();
                if (service == null)
                    registry.RegisterModuleInterface<IAsyncMessageRecievedService>(this);
                        //Register so that we have an internal message handler, but don't add the external handler
                return;
            }
            IConfig handlerConfig = config.Configs["Handlers"];
            m_registry.RequestModuleInterface<IGridRegistrationService>().RegisterModule(this);
        }

        public void FinishedStartup()
        {
        }

        #endregion
    }
}


text:
package com.ifit.app.admin;

import com.ifit.app.R;
import com.ifit.app.db.MyDatabaseHelper;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.TextView;

public class View_the_data extends Activity {

	private TextView user_count,feedback_count,report_count,dynamic_count;

	private MyDatabaseHelper usedb;
	private SQLiteDatabase db;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.data_statistics);

		user_count = (TextView)findViewById(R.id.user_count);
		feedback_count = (TextView)findViewById(R.id.feedback_count);
		report_count = (TextView)findViewById(R.id.report_count);
		dynamic_count = (TextView)findViewById(R.id.dynamic_count);

		usedb = new MyDatabaseHelper(this, "DataBase.db", null, 1);
		db = usedb.getWritableDatabase();

		Cursor cr = db.query("User_table", null, null, null, null, null, null);

		int i = cr.getCount();
		user_count.setText(i+"");

		cr = db.query("User_feedback_table", null, null, null, null, null, null);

		int n = cr.getCount();
		feedback_count.setText(n+"");

		cr = db.query("User_report_table", null, null, null, null, null, null);

		int m = cr.getCount();
		report_count.setText(m+"");

		cr = db.query("User_news_table", null, null, null, null, null, null);
		int x = cr.getCount();
		dynamic_count.setText(x+"");

		cr.close();
		db.close();

	}

}


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

namespace Maui.Data.Recognition
{
    /// <summary>
    /// Enhances the <see cref="LookupPolicy"/> in that way that all
    /// strings are evaluated by <see cref="Blade.Text.Evaluator"/>
    /// using the lookup function or LUT provided.
    /// </summary>
    public class EvaluatorPolicy : LookupPolicy
    {
        public EvaluatorPolicy()
            : this( new Dictionary<string, string>() )
        {
        }

        public EvaluatorPolicy( IDictionary<string, string> lut )
            : base( lut )
        {
        }

        public EvaluatorPolicy( Func<string, string> lookup )
            : base( lookup )
        {
        }

        protected override string LookupInternal( string str )
        {
            return Evaluator.Evaluate( str, GetValue );
        }

        /// <summary>
        /// Hook for derived classes to calculate the value for the
        /// given key differently than this class.
        /// </summary>
        protected virtual string GetValue( string key )
        {
            string value = base.LookupInternal( key );
            if ( value == key )
            {
                // could not be evaluted
                return null;
            }

            return value;
        }
    }
}


text:
#include <SDL.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <GL/glew.h>

#include <assert.h>

#include "bcve.h"
#include "text.h"
#include "FIAL.h"

#include "value_def_short.h"

#define SCREEN_WIDTH  1280
#define SCREEN_HEIGHT 720

#define CONFIG_FILE "scripts/config.fial"

/* usually I'm not one for global variables, but I guess I've just
 * decided a few will make things easier, for the time being.  */

int main_argc;
char **main_argv;
const char * input_filename;
int exec_path_max = 256;
char exec_path[256];
struct window_info win_info = { NULL };

static void print_err (struct FIAL_error_info *error)
{
	printf("Error in config file %s at line %d, col %d: %s\n",
	       error->file, error->line, error->col, error->static_msg);
	if(error->dyn_msg)
		printf("Further info: %s\n", error->dyn_msg);
	exit(1);
}

static int read_config (struct FIAL_interpreter *interp,
			int *width, int *height, int *fullscreen)
{
	int max = 256;
	char buffy[256];
	int ret, sym;

	struct FIAL_error_info error;
	struct FIAL_exec_env   env;
	union  FIAL_lib_entry  *lib_ent = NULL;
	struct FIAL_value      args[4], val;

	enum{FULLSCREEN, WIDTH, HEIGHT, END};
	memset(&error, 0, sizeof(error));
	memset(&env, 0, sizeof(env));
	memset(args, 0, sizeof(args));
	memset(&val, 0, sizeof(val));

	END[args].type = VALUE_END_ARGS;

/*	FIAL_install_constants  (interp);
	FIAL_install_std_omnis  (interp);
	FIAL_install_text_buf   (interp);
	FIAL_install_system_lib (interp); */

	append_to_exec_path(buffy, CONFIG_FILE, max);
	ret = FIAL_load_string(interp, buffy,  &lib_ent, &error);

	if(ret < 0) {
		print_err(&error);
	}

	FIAL_get_symbol   (&sym, "configure"        , interp);
	FIAL_lookup_symbol(&val, lib_ent->lib.procs , sym   );

	if(val.type != VALUE_NODE) {
		printf("could find proc %s in config file\n", "configure");
		exit(1);
	}

	env.interp = interp;
	env.lib    = &lib_ent->lib;

	ret = FIAL_run_proc(val.node, args, &env);
	if(ret < 0)
		print_err(&error);

	if(FULLSCREEN[args].type == VALUE_INT)
		*fullscreen = FULLSCREEN[args].n;
	if(WIDTH[args].type == VALUE_INT)
		*width = WIDTH[args].n;
	if(HEIGHT[args].type == VALUE_INT)
		*height = HEIGHT[args].n;

	return 0;
}

static void set_exec_path (int argc, char **argv)
{
	char *ptr, *slash, *ptr2;

	/*set exec path */
	for(ptr = argv[0], slash = NULL; *ptr != '\0'; ptr++)
		if(*ptr == '\\' || *ptr == '/')
			slash = ptr;
	if(!slash)
		exec_path[0] = '\0';

	for(ptr = argv[0], ptr2 = exec_path; ptr <= slash;++ptr, ++ptr2)
		*ptr2 = *ptr;
	*ptr2 = '\0';
}

int main(int argc, char *argv[])
{
	struct FIAL_interpreter *config = NULL;
	int go, fullscreen, log;
	unsigned int window_flags = 0;

	const char *usage =
"usage: bcve [options] filename\n"
"options:\n"
"             -wWIDTH\n"
"             -hHEIGHT\n"
"             -F (for fullscreen)\n"
"             -W (for windowed)\n\b"
"options override configuration\n";

	main_argc = argc;
	main_argv = argv;

	set_exec_path(argc, argv);

	log             = 0;
	fullscreen      = 0;
	win_info.width  = SCREEN_WIDTH;
	win_info.height = SCREEN_HEIGHT;
	window_flags   |= SDL_WINDOW_OPENGL;

	config = FIAL_create_interpreter();
	read_config(config, &win_info.width, &win_info.height, &fullscreen);

	if(argc == 2) {
		input_filename = argv[1];
	} else  {
		int i;
		for(i = 1; i < argc; i++) {
			if(argv[i][0] != '-') {
				input_filename = argv[i];
				break;
			}
			switch(argv[i][1]) {
			case 'w':
				if(!isdigit(argv[i][2])) {
					puts(usage);
					exit(1);
				}
				win_info.width = strtol(argv[i] + 2, NULL, 10);
				break;
			case 'h':
				if(!isdigit(argv[i][2])) {
					puts(usage);
					exit(1);
				}
				win_info.height = strtol(argv[i] + 2, NULL, 10);
				break;
			case 'F':
				fullscreen = 1;
				break;
			case 'W':
				fullscreen = 0;
				break;
			case 'L':
				log = 1;
				break;
			default:
				puts(usage);
				exit(1);
				break;
			}
		}
		if(!input_filename) {
			puts(usage);
			exit(1);
		}
	}
	if(fullscreen)
		window_flags |= SDL_WINDOW_FULLSCREEN;

	if(log) {
		win_info.logfile = fopen("bcve.log", "w");
		if(!win_info.logfile) {
			fprintf(stderr, "Couldn't open logfile\n");
			exit(1);
		}
	} else {
		win_info.logfile = fopen("nul", "w");
	}

/*init SDL, win_info */

	SDL_Init(SDL_INIT_VIDEO);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);

	win_info.window = SDL_CreateWindow("BCVE",
					   SDL_WINDOWPOS_UNDEFINED,
					   SDL_WINDOWPOS_UNDEFINED,
					   win_info.width,
					   win_info.height,
					   window_flags);
	atexit(SDL_Quit);
	if (!win_info.window) {
		printf("Could not create window: %s\n", SDL_GetError());
		return 1;
	}
	SDL_GetWindowSize(win_info.window, &win_info.width, &win_info.height);

/*init opengl and glew */

	win_info.context = SDL_GL_CreateContext(win_info.window);
	if (!win_info.context) {
		printf("There was an error creating the OpenGL context!\n");
		return 0;
	}

	const unsigned char *version = glGetString(GL_VERSION);
	fprintf(win_info.logfile, "opengl version: %s\n", version);

	glewExperimental = GL_TRUE;
	GLenum glew_status = glewInit();
	if (GLEW_OK != glew_status) {
		/* Problem: glewInit failed, something is seriously wrong. */
		fprintf(stderr, "Error: %s\n", glewGetErrorString(glew_status));
		return 0;
	}
	/*clear any errors....*/
	while((go = glGetError()) != GL_NO_ERROR) {
		fprintf(win_info.logfile, "%s\n", gluErrorString(go));
	}
	fprintf(win_info.logfile, "errors cleared...\n");

	/* init freetype */
	if(init_freetype())
	    exit(2);

	/*call my stuff! */
	/*errrm.
	  TODO: write program.
	*/
	start_viewer(&win_info);
	return 0;
}


text:
<?php

namespace Mapping\Fixture\Xml;

class Status
{
    private $id;

    private $title;
}


text:
package org.primeframework.mvc.scope.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import io.fusionauth.http.Cookie.SameSite;
import org.primeframework.mvc.scope.BrowserActionSessionScope;

/**
 * This annotation should be used to mark member fields of actions that should be fetched and stored in a secure Cookie
 * but only accessible by the current action.
 *
 * @author Daniel DeGroff
 */
@Retention(RetentionPolicy.RUNTIME)
@ScopeAnnotation(BrowserActionSessionScope.class)
@Target(ElementType.FIELD)
public @interface BrowserActionSession {
  /**
   * @return This attribute determines the action for which the action session is used. This allows an action to get and
   *     set attributes inside another action's session.
   */
  Class<?> action() default BrowserActionSession.class;

  /**
   * When `true` the cookie value will be compressed, this is the default.
   *
   * @return true if the cookie value should be compressed.
   */
  boolean compress() default true;

  /**
   * When `true` the cookie value will be encrypted, this is the default.
   *
   * @return true if the cookie value should be encrypted.
   */
  boolean encrypt() default true;

  /**
   * @return This attribute determines the name under which that the value is stored in the action session. The default
   *     name is the name of the field that the annotation is put on.
   */
  String name() default "##field-name##";

  /**
   * @return The SameSite setting for the cookie. Defaults to Lax.
   */
  SameSite sameSite() default SameSite.Lax;
}


text:
import json
import os

import pytest
import semantic_version

from platformio.clients.registry import RegistryClient
from platformio.commands.lib.command import cli as cmd_lib
from platformio.package.meta import PackageType
from platformio.package.vcsclient import VCSClientFactory
from platformio.project.config import ProjectConfig

def test_saving_deps(clirunner, validate_cliresult, isolated_pio_core, tmpdir_factory):
    regclient = RegistryClient()
    project_dir = tmpdir_factory.mktemp("project")
    project_dir.join("platformio.ini").write(
        """
[env]
lib_deps = ArduinoJson

[env:one]
board = devkit

[env:two]
framework = foo
lib_deps =
    CustomLib
    ArduinoJson @ 5.10.1
"""
    )
    result = clirunner.invoke(
        cmd_lib,
        ["-d", str(project_dir), "install", "64", "knolleary/PubSubClient@~2.7"],
    )
    validate_cliresult(result)
    aj_pkg_data = regclient.get_package(PackageType.LIBRARY, "bblanchon", "ArduinoJson")
    config = ProjectConfig(os.path.join(str(project_dir), "platformio.ini"))
    assert sorted(config.get("env:one", "lib_deps")) == sorted(
        [
            "bblanchon/ArduinoJson@^%s" % aj_pkg_data["version"]["name"],
            "knolleary/PubSubClient@~2.7",
        ]
    )
    assert sorted(config.get("env:two", "lib_deps")) == sorted(
        [
            "CustomLib",
            "bblanchon/ArduinoJson@^%s" % aj_pkg_data["version"]["name"],
            "knolleary/PubSubClient@~2.7",
        ]
    )

    # ensure "build" version without NPM spec
    result = clirunner.invoke(
        cmd_lib,
        ["-d", str(project_dir), "-e", "one", "install", "mbed-sam-grove/LinkedList"],
    )
    validate_cliresult(result)
    ll_pkg_data = regclient.get_package(
        PackageType.LIBRARY, "mbed-sam-grove", "LinkedList"
    )
    config = ProjectConfig(os.path.join(str(project_dir), "platformio.ini"))
    assert sorted(config.get("env:one", "lib_deps")) == sorted(
        [
            "bblanchon/ArduinoJson@^%s" % aj_pkg_data["version"]["name"],
            "knolleary/PubSubClient@~2.7",
            "mbed-sam-grove/LinkedList@%s" % ll_pkg_data["version"]["name"],
        ]
    )

    # check external package via Git repo
    result = clirunner.invoke(
        cmd_lib,
        [
            "-d",
            str(project_dir),
            "-e",
            "one",
            "install",
            "https://github.com/OttoWinter/async-mqtt-client.git#v0.8.3 @ 0.8.3",
        ],
    )
    validate_cliresult(result)
    config = ProjectConfig(os.path.join(str(project_dir), "platformio.ini"))
    assert len(config.get("env:one", "lib_deps")) == 4
    assert config.get("env:one", "lib_deps")[3] == (
        "https://github.com/OttoWinter/async-mqtt-client.git#v0.8.3 @ 0.8.3"
    )

    # test uninstalling
    # from all envs
    result = clirunner.invoke(
        cmd_lib, ["-d", str(project_dir), "uninstall", "ArduinoJson"]
    )
    validate_cliresult(result)
    # from "one" env
    result = clirunner.invoke(
        cmd_lib,
        [
            "-d",
            str(project_dir),
            "-e",
            "one",
            "uninstall",
            "knolleary/PubSubClient@~2.7",
        ],
    )
    validate_cliresult(result)
    config = ProjectConfig(os.path.join(str(project_dir), "platformio.ini"))
    assert len(config.get("env:one", "lib_deps")) == 2
    assert len(config.get("env:two", "lib_deps")) == 2
    assert config.get("env:one", "lib_deps") == [
        "mbed-sam-grove/LinkedList@%s" % ll_pkg_data["version"]["name"],
        "https://github.com/OttoWinter/async-mqtt-client.git#v0.8.3 @ 0.8.3",
    ]
    assert config.get("env:two", "lib_deps") == [
        "CustomLib",
        "knolleary/PubSubClient@~2.7",
    ]

    # test list
    result = clirunner.invoke(cmd_lib, ["-d", str(project_dir), "list"])
    validate_cliresult(result)
    assert "Version: 0.8.3+sha." in result.stdout
    assert (
        "Source: git+https://github.com/OttoWinter/async-mqtt-client.git#v0.8.3"
        in result.stdout
    )
    result = clirunner.invoke(
        cmd_lib, ["-d", str(project_dir), "list", "--json-output"]
    )
    validate_cliresult(result)
    data = {}
    for key, value in json.loads(result.stdout).items():
        data[os.path.basename(key)] = value
    ame_lib = next(
        item for item in data["one"] if item["name"] == "AsyncMqttClient-esphome"
    )
    ame_vcs = VCSClientFactory.new(ame_lib["__pkg_dir"], ame_lib["__src_url"])
    assert len(data["two"]) == 1
    assert data["two"][0]["name"] == "PubSubClient"
    assert "__pkg_dir" in data["one"][0]
    assert (
        ame_lib["__src_url"]
        == "git+https://github.com/OttoWinter/async-mqtt-client.git#v0.8.3"
    )
    assert ame_lib["version"] == ("0.8.3+sha.%s" % ame_vcs.get_current_revision())

def test_update(clirunner, validate_cliresult, isolated_pio_core, tmpdir_factory):
    storage_dir = tmpdir_factory.mktemp("test-updates")
    result = clirunner.invoke(
        cmd_lib,
        ["-d", str(storage_dir), "install", "ArduinoJson @ 5.10.1", "Blynk @ ~0.5.0"],
    )
    validate_cliresult(result)
    result = clirunner.invoke(
        cmd_lib, ["-d", str(storage_dir), "update", "--dry-run", "--json-output"]
    )
    validate_cliresult(result)
    outdated = json.loads(result.stdout)
    assert len(outdated) == 2
    # ArduinoJson
    assert outdated[0]["version"] == "5.10.1"
    assert outdated[0]["versionWanted"] is None
    assert semantic_version.Version(
        outdated[0]["versionLatest"]
    ) > semantic_version.Version("6.16.0")
    # Blynk
    assert outdated[1]["version"] == "0.5.4"
    assert outdated[1]["versionWanted"] is None
    assert semantic_version.Version(
        outdated[1]["versionLatest"]
    ) > semantic_version.Version("0.6.0")

    # check with spec
    result = clirunner.invoke(
        cmd_lib,
        [
            "-d",
            str(storage_dir),
            "update",
            "--dry-run",
            "--json-output",
            "ArduinoJson @ ^5",
        ],
    )
    validate_cliresult(result)
    outdated = json.loads(result.stdout)
    assert outdated[0]["version"] == "5.10.1"
    assert outdated[0]["versionWanted"] == "5.13.4"
    assert semantic_version.Version(
        outdated[0]["versionLatest"]
    ) > semantic_version.Version("6.16.0")
    # update with spec
    result = clirunner.invoke(
        cmd_lib, ["-d", str(storage_dir), "update", "--silent", "ArduinoJson @ ^5.10.1"]
    )
    validate_cliresult(result)
    result = clirunner.invoke(
        cmd_lib, ["-d", str(storage_dir), "list", "--json-output"]
    )
    validate_cliresult(result)
    items = json.loads(result.stdout)
    assert len(items) == 2
    assert items[0]["version"] == "5.13.4"
    assert items[1]["version"] == "0.5.4"

    # Check incompatible
    result = clirunner.invoke(
        cmd_lib, ["-d", str(storage_dir), "update", "--dry-run", "ArduinoJson @ ^5"]
    )
    with pytest.raises(
        AssertionError,
        match="This command is deprecated",
    ):
        validate_cliresult(result)
    result = clirunner.invoke(
        cmd_lib, ["-d", str(storage_dir), "update", "ArduinoJson @ ^5"]
    )
    validate_cliresult(result)
    assert "ArduinoJson@5.13.4 is already up-to-date" in result.stdout


text:
<?php

namespace Webservice;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * @category   Zend
 * @package    Oauth
 */
class WebserviceFactory
{
    protected $options;

    /**
    * @var ServiceLocatorInterface
    */
    protected $serviceLocator;

    protected $adapter;

    protected $cache;

    /**
    * Constructor
    *
    */
    public static function factory($serviceName, array $options, ServiceLocatorInterface $serviceLocator)
    {
        $webservice = new static();

        $webservice->setServiceLocator($serviceLocator);
        $webservice->setOptions($options);
        $webservice->initAdapter($serviceName);

        return $webservice;
    }

    /**
    * Set the service locator.
    *
    * @param ServiceLocatorInterface $serviceLocator
    * @return AbstractHelper
    */
    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
    {
        $this->serviceLocator = $serviceLocator;
        return $this;
    }

    /**
    * Get the service locator.
    *
    * @return \Zend\ServiceManager\ServiceLocatorInterface
    */
    public function getServiceLocator()
    {
        return $this->serviceLocator;
    }

    public function getOptions()
    {
        return $this->options;
    }

    public function setOptions($options)
    {
        $this->options = $options;
        return $this;
    }

    public function initAdapter($serviceName)
    {
        $options = $this->getOptions();
        if(false === strpos($serviceName, '\\')){
            $adapterClass = "Webservice\\Adapter\\$serviceName";
        } else {
            $adapterClass = $serviceName;
        }

        if(false == class_exists($adapterClass)){
            throw new Exception\InvalidArgumentException(sprintf('Webservice %s not exist', $serviceName));
        }

        $adapter = new $adapterClass();
        $adapter->setOptions($options);
        if($this->serviceLocator){
            $adapter->setServiceLocator($this->serviceLocator);
        }

        return $this->adapter = $adapter;
    }

    /**
    * Returns the authentication adapter
    *
    * The adapter does not have a default if the storage adapter has not been set.
    *
    * @return Adapter\AdapterInterface|null
    */
    public function getAdapter()
    {
        return $this->adapter;
    }

    /**
    * Sets the authentication adapter
    *
    * @param  Adapter\AdapterInterface $adapter
    * @return AuthenticationService Provides a fluent interface
    */
    public function setAdapter(Adapter\AdapterInterface $adapter)
    {
        $this->adapter = $adapter;
        return $this;
    }
}


text:
package f5cloudexporter

import (
	"path/filepath"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"go.opentelemetry.io/collector/component"
	"go.opentelemetry.io/collector/config"
	"go.opentelemetry.io/collector/config/confighttp"
	"go.opentelemetry.io/collector/confmap/confmaptest"
	"go.opentelemetry.io/collector/exporter/exporterhelper"
	otlphttp "go.opentelemetry.io/collector/exporter/otlphttpexporter"
)

func TestLoadConfig(t *testing.T) {
	cm, err := confmaptest.LoadConf(filepath.Join("testdata", "config.yaml"))
	require.NoError(t, err)
	factory := NewFactory()
	cfg := factory.CreateDefaultConfig()

	sub, err := cm.Sub(component.NewIDWithName(typeStr, "allsettings").String())
	require.NoError(t, err)
	require.NoError(t, component.UnmarshalExporterConfig(sub, cfg))

	actualCfg := cfg.(*Config)
	expectedCfg := &Config{
		Config: otlphttp.Config{
			ExporterSettings: config.NewExporterSettings(component.NewIDWithName(typeStr, "")),
			RetrySettings: exporterhelper.RetrySettings{
				Enabled:         true,
				InitialInterval: 10 * time.Second,
				MaxInterval:     1 * time.Minute,
				MaxElapsedTime:  10 * time.Minute,
			},
			QueueSettings: exporterhelper.QueueSettings{
				Enabled:      true,
				NumConsumers: 2,
				QueueSize:    10,
			},
			HTTPClientSettings: confighttp.HTTPClientSettings{
				Endpoint:        "https://f5cloud",
				ReadBufferSize:  123,
				WriteBufferSize: 345,
				Timeout:         time.Second * 10,
				Headers: map[string]string{
					"User-Agent": "opentelemetry-collector-contrib {{version}}",
				},
				Compression: "gzip",
			},
		},
		Source: "dev",
		AuthConfig: AuthConfig{
			CredentialFile: "/etc/creds/key.json",
			Audience:       "exampleaudience",
		},
	}
	// testing function equality is not supported in Go hence these will be ignored for this test
	expectedCfg.HTTPClientSettings.CustomRoundTripper = nil
	actualCfg.HTTPClientSettings.CustomRoundTripper = nil
	assert.Equal(t, expectedCfg, actualCfg)
}

func TestConfig_sanitize(t *testing.T) {
	const validEndpoint = "https://validendpoint.local"
	const validSource = "tests"

	type fields struct {
		Endpoint       string
		Source         string
		CredentialFile string
		Audience       string
	}
	tests := []struct {
		name         string
		fields       fields
		errorMessage string
		shouldError  bool
	}{
		{
			name: "Test missing endpoint",
			fields: fields{
				Endpoint: "",
			},
			errorMessage: "missing required \"endpoint\" setting",
			shouldError:  true,
		},
		{
			name: "Test invalid endpoint",
			fields: fields{
				Endpoint: "this://is:an:invalid:endpoint.com",
			},
			errorMessage: "",
			shouldError:  true,
		},
		{
			name: "Test credential file not provided",
			fields: fields{
				Endpoint:       validEndpoint,
				Source:         validSource,
				CredentialFile: "",
			},
			errorMessage: "missing required \"f5cloud_auth.credential_file\" setting",
			shouldError:  true,
		},
		{
			name: "Test non-existent credential file",
			fields: fields{
				Endpoint:       validEndpoint,
				Source:         validSource,
				CredentialFile: "non-existent cred file",
			},
			errorMessage: "the provided \"f5cloud_auth.credential_file\" does not exist",
			shouldError:  true,
		},
		{
			name: "Test missing source",
			fields: fields{
				Endpoint: validEndpoint,
				Source:   "",
			},
			errorMessage: "missing required \"source\" setting",
			shouldError:  true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			factory := NewFactory()
			cfg := factory.CreateDefaultConfig().(*Config)
			cfg.ExporterSettings = config.NewExporterSettings(component.NewID(typeStr))
			cfg.Endpoint = tt.fields.Endpoint
			cfg.Source = tt.fields.Source
			cfg.AuthConfig = AuthConfig{
				CredentialFile: tt.fields.CredentialFile,
				Audience:       tt.fields.Audience,
			}

			err := cfg.sanitize()
			if (err != nil) != tt.shouldError {
				t.Errorf("sanitize() error = %v, shouldError %v", err, tt.shouldError)
				return
			}

			if tt.shouldError {
				assert.Error(t, err)
				if len(tt.errorMessage) != 0 {
					assert.Equal(t, tt.errorMessage, err.Error())
				}
			}
		})
	}

	t.Run("Test audience is set from endpoint when not provided", func(t *testing.T) {
		factory := NewFactory()
		cfg := factory.CreateDefaultConfig().(*Config)
		cfg.Endpoint = validEndpoint
		cfg.Source = validSource
		cfg.AuthConfig = AuthConfig{
			CredentialFile: "testdata/empty_credential_file.json",
			Audience:       "",
		}

		err := cfg.sanitize()
		assert.NoError(t, err)
		assert.Equal(t, validEndpoint, cfg.AuthConfig.Audience)
	})

	t.Run("Test audience is not set from endpoint when provided", func(t *testing.T) {
		factory := NewFactory()
		cfg := factory.CreateDefaultConfig().(*Config)
		cfg.Endpoint = validEndpoint
		cfg.Source = validSource
		cfg.AuthConfig = AuthConfig{
			CredentialFile: "testdata/empty_credential_file.json",
			Audience:       "tests",
		}

		err := cfg.sanitize()
		assert.NoError(t, err)
		assert.Equal(t, "tests", cfg.AuthConfig.Audience)
	})
}


text:
package org.apache.james.imapserver.netty;

import org.jboss.netty.channel.socket.ServerSocketChannelFactory;
import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory;
import org.jboss.netty.handler.execution.ExecutionHandler;

/**
 * IMAPServer which use old IO and not NIO. If you want to use NIO you should
 * use {@link IMAPServer}
 */
public class OioIMAPServer extends IMAPServer {

    @Override
    protected ServerSocketChannelFactory createSocketChannelFactory() {
        return new OioServerSocketChannelFactory(createBossExecutor(), createWorkerExecutor());
    }

    /**
     * Return -1 as it is not known
     */
    @Override
    public int getIoWorkerCount() {
        return -1;
    }

    /**
     * As OIO use one thread per connection we disable the use of the {@link ExecutionHandler}
     */
    @Override
    protected ExecutionHandler createExecutionHander() {
        return null;
    }

}


text: export { default } from '@orbit/core';


text:
var Fetcher  = require("./src/fetcher");
var Resolver = require("./src/resolver");
var factory  = require("./src/factory");

factory.register("fetcher", Fetcher);
factory.register("resolver", Resolver);

module.exports = require("./src/bit-imports").create({ doNotIgnoreNodeModules: false });


text:
layout: default
---

{{ page.title }}

    {{ page.date | date: "%B %-d, %Y" }}
    {% if page.author %} - {{ page.author }}{% endif %}

    {{ content }}

{% if site.theme_setting.disqus_shortname %}

  {% include disqus.html %}

{% endif %}


text:
using Com.Ctrip.Framework.Apollo.Core;
using Com.Ctrip.Framework.Apollo.Internals;
using Com.Ctrip.Framework.Apollo.Spi;
using Com.Ctrip.Framework.Apollo.Util;

namespace Com.Ctrip.Framework.Apollo;

/// <summary>
/// Entry point for client config use
/// </summary>
#if NET471
[Obsolete("不建议使用,推荐使用System.Configuration.ConfigurationBuilder + System.Configuration.ConfigurationManager")]
#elif NETSTANDARD
[Obsolete("不建议使用,后续版本可能删除,推荐安装包Com.Ctrip.Framework.Apollo.Configuration", true)]
#endif
public static class ApolloConfigurationManager
{
    private static readonly bool ConfigEnablePlaceholder;
    private static readonly Exception? Exception;
    public static IConfigManager? Manager { get; }

    static ApolloConfigurationManager()
    {
        try
        {
            var config = new ConfigUtil();

            ConfigEnablePlaceholder = config.EnablePlaceholder;

            Manager = new DefaultConfigManager(new DefaultConfigRegistry(), new ConfigRepositoryFactory(config));
        }
        catch (Exception ex)
        {
            Exception = ex;
        }
    }

    /// <summary>
    /// Get Application's config instance. </summary>
    /// <returns> config instance </returns>
    public static Task<IConfig> GetAppConfig() => GetConfig(ConfigConsts.NamespaceApplication);

    /// <summary>
    /// Get the config instance for the namespace. </summary>
    /// <param name="namespaceName"> the namespace of the config </param>
    /// <returns> config instance </returns>
    public static Task<IConfig> GetConfig(string namespaceName)
    {
        if (string.IsNullOrEmpty(namespaceName)) throw new ArgumentNullException(nameof(namespaceName));

        if (Exception != null) throw new InvalidOperationException("Apollo初始化异常", Exception);

        return Manager!.GetConfig(namespaceName);
    }

    /// <summary>
    /// Get the config instance for the namespace. </summary>
    /// <param name="namespaces"> the namespaces of the config, order desc. </param>
    /// <returns> config instance </returns>
    public static Task<IConfig> GetConfig(params string[] namespaces) => GetConfig((IEnumerable<string>)namespaces);

    /// <summary>
    /// Get the config instance for the namespace. </summary>
    /// <param name="namespaces"> the namespaces of the config, order desc. </param>
    /// <returns> config instance </returns>
    public static async Task<IConfig> GetConfig(IEnumerable<string> namespaces)
    {
        if (namespaces == null) throw new ArgumentNullException(nameof(namespaces));
#if NET40
        var configs = await TaskEx.WhenAll(namespaces.Reverse().Distinct().Select(GetConfig)).ConfigureAwait(false);
#else
        var configs = await Task.WhenAll(namespaces.Reverse().Distinct().Select(GetConfig)).ConfigureAwait(false);
#endif
        if (configs.Length < 1) throw new ArgumentException("namespaces not allow empty");

        var config = configs.Length == 1 ? configs[0] : new MultiConfig(configs);

        if (ConfigEnablePlaceholder) config = new PlaceholderConfig(config);

        return config;
    }
}


text:
{-# LANGUAGE DeriveDataTypeable #-}

{-
 Copyright (C) 2012-2017 Jimmy Liang, Michal Antkiewicz <http://gsd.uwaterloo.ca>

 Permission is hereby granted, free of charge, to any person obtaining a copy of
 this software and associated documentation files (the "Software"), to deal in
 the Software without restriction, including without limitation the rights to
 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 of the Software, and to permit persons to whom the Software is furnished to do
 so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
-}

module Main where

import Language.Clafer.IG.ClaferIG
import Language.Clafer.IG.ClaferModel
import Language.Clafer.IG.CommandLine
import Language.Clafer.IG.Solution
import Language.Clafer.IG.Sugarer
import Language.Clafer.ClaferArgs
import Language.Clafer.JSONMetaData
import Language.ClaferT
import Language.Clafer.Common
import Control.Monad
import Control.Monad.IO.Class
import Data.Either
import qualified Data.Map as Map
import Data.List (partition)
import Data.Maybe
import Data.IORef
import Prelude hiding (all)
import System.Console.CmdArgs
import System.Directory
import System.FilePath

claferIGArgsDef :: IGArgs
claferIGArgsDef = IGArgs {
    all                         = def &= opt "1" &= help "Saves all instances or a counterexample. Reads scopes from a `.cfr.scope` file or uses the provided global scope." &= typ "INTEGER",
    saveDir                     = def &= help "Specify the directory for storing saved files." &= typ "FILE",
    bitwidth                    = 4 &= help "Set the bitwidth for integers." &= typ "INTEGER", -- Default bitwidth is 4.
    maxInt                      = 7 &= help "Set the bitwidth for integers based on the largest required number. Overrides --bitwidth argument." &= typ "INTEGER",
    alloySolution               = def &= help "Convert Alloy solution to a Clafer solution." &= typ "FILE",
    claferModelFile             = def &= argPos 0 &= typ "FILE",
    useUids                     = False &= help "Use unique clafer names in the Clafer solution.",
    addTypes                    = False &= help "Add colon/reference types to the Clafer solution.",
    json                        = False &= help "Render solution as JSON (forces 'addUids').",
    flatten_inheritance_comp    = def &= help "Flatten inheritance during compiling ('alloy' mode only)" &= name "i",
    no_layout_comp              = def &= help "Don't resolve off-side rule layout during compiling" &= name "l",
    check_duplicates_comp       = def &= help "Check duplicated clafer names during compiling"  &= name "c",
    skip_resolver_comp          = def &= help "Skip name resolution during compiling" &= name "f",
    scope_strategy_comp         = Simple &= help "Use scope computation strategy during compiling: none, simple (default), or full." &= name "ss"
} &= summary claferIGVersion &= program "claferig"

main :: IO ()
main =
    do
        args' <- cmdArgs claferIGArgsDef
        let
            bw = bitwidth args'
            mi = maxInt args'
            -- maxInt overrides the bitwidth setting
            args'' = if (mi > allowedMaxInt bw)
                        then args' {bitwidth = requiredBitwidth mi}
                        else args'

        if (not $ null $ alloySolution args'')
            then do
                _ <- runAlloySolution args''
                return ()
            else if (json args'')
                then
                    tryClaferIG (args'' { useUids = True })
                else
                    tryClaferIG args''
    where
    tryClaferIG args3 =
        do
            try <- runClaferIG args3
            case try of
                Right r -> return r
                Left l  -> do
                    mapM_ putStrLn $ printError l
                    putStrLn "Press enter to retry."
                    void getLine
                    tryClaferIG args3

runClaferIG :: IGArgs -> IO (Either ClaferErrs ())
runClaferIG args' =
    runClaferIGT args' $ do
        let claferModelFileName = claferModelFile args'
        cModel <- liftIO $ strictReadFile claferModelFileName
        if null cModel
        then error "Cannot instantiate an empty model."
        else liftIO $ putStrLn "Compiling the Clafer model..."

        oldBw <- getBitwidth
        env <- getClaferEnv
        let ir = fst3 $ fromJust $ cIr env
        scopes <- getScopes
        setBitwidth $ findNecessaryBitwidth ir oldBw $ map snd scopes

        solve
        case all args' of
            Just scope -> do
                -- copied from CommandLine LoadScopes command
                qNameMaps' <- getQNameMaps
                maybeUidScopes <- liftIO $ readCfrScopeFile qNameMaps' claferModelFileName
                case maybeUidScopes of
                    Nothing -> do
                        liftIO $ putStrLn "Using the provided global scope as a `.cfr-scope` file does not exist. Use the command `saveScopes` to create one."
                        setGlobalScope scope
                    Just uidScopes -> do
                        let
                            (globalScopes, normalScopes) = partition (\(uid, _) -> null uid) uidScopes
                            -- from the globalScopes, take the maximum
                            globalScopeVals = map snd globalScopes
                            globalScope = maximum globalScopeVals
                            -- add the "this/" prefix
                            normalScopesAlloy = map (\(uid, scope2) -> ("this/"++uid, scope2)) normalScopes
                        setGlobalScope globalScope
                        mapM_ (\(uid, val) -> setAlloyScope val uid) normalScopesAlloy
                -- end copied

                solve

                counterRef <- liftIO $ newIORef 1

                let saveDirectory = fromMaybe return $ underDirectory `liftM` saveDir args'
                saveAll (savePath claferModelFileName counterRef >>= saveDirectory)
                quit
            Nothing    -> do
                liftIO $ putStrLn "Type 'h' for the list of available REPL commands\n"
                runCommandLine

-- | Convert an Alloy XML file into an instance in Clafer
runAlloySolution :: IGArgs -> IO (Either ClaferErrs ())
runAlloySolution args' =
    runClaferIGT args' $ do
        let claferModelFileName = claferModelFile args'
        cModel <- liftIO $ strictReadFile claferModelFileName
        when (cModel == "") $ error $ "Cannot convert Alloy solution without the Clafer model from which the instance was created.\n"
                                   ++ "Usage: claferIG [OPTIONS] <model.cfr> --alloy-solution=<instance.xml>\n"
        alloyInstance <- liftIO $ strictReadFile $ alloySolution args' -- It's an Alloy XML file in this case
        when (null alloyInstance) $ error $ "Provide an Alloy solution Alloy file name.\n"
                                         ++ "Usage: claferIG [OPTIONS] <model.cfr> --alloy-solution=<instance.xml>\n"
        env <- getClaferEnv
        let (_, genv', _) = fromJust $ cIr env
        let
            sMap = Map.empty
            uidIClaferMap' = uidClaferMap genv'
        liftIO $ putStrLn $ show $ (sugarClaferModel (useUids args') (addTypes args') uidIClaferMap' $ buildClaferModel $ parseSolution alloyInstance) $ sMap

savePath :: FilePath -> IORef Int -> IO FilePath
savePath file' counterRef =
    do
        counter <- readIORef counterRef
        writeIORef counterRef (counter + 1)
        return $ file' ++ "." ++ (show counter) ++ ".data"

underDirectory :: FilePath -> FilePath -> IO FilePath
underDirectory dir file' =
    do
        createDirectoryIfMissing True dir
        return $ joinPath [dir, file']

saveAll :: IO FilePath -> ClaferIGT IO ()
saveAll nextFile =
    do
        file' <- liftIO nextFile
        liftIO $ createDirectoryIfMissing True $ takeDirectory file'
        solution <- next
        case solution of
            Instance{modelInstance = modelInstance'} -> do
                liftIO $ writeFile file' (show modelInstance')
                saveAll nextFile
            _ -> return ()


text:
package com.intellij.openapi.externalSystem.model.internal;

import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.externalSystem.model.DataNode;
import com.intellij.openapi.externalSystem.model.ExternalProjectInfo;
import com.intellij.openapi.externalSystem.model.ProjectSystemId;
import com.intellij.openapi.externalSystem.model.project.ProjectData;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.*;

/**
 * @author Vladislav.Soroka
 */
public class InternalExternalProjectInfo implements ExternalProjectInfo, Serializable {

  private static final long serialVersionUID = 1L;

  @NotNull
  private ProjectSystemId myProjectSystemId;
  @NotNull
  private String myExternalProjectPath;
  @Nullable
  private DataNode<ProjectData> myExternalProjectStructure;
  private long lastSuccessfulImportTimestamp = -1;
  private long lastImportTimestamp = -1;
  private String myBuildNumber;

  public InternalExternalProjectInfo(@NotNull ProjectSystemId projectSystemId,
                                     @NotNull String externalProjectPath,
                                     @Nullable DataNode<ProjectData> externalProjectStructure) {
    myProjectSystemId = projectSystemId;
    myExternalProjectPath = externalProjectPath;
    myExternalProjectStructure = externalProjectStructure;
    myBuildNumber = ApplicationInfo.getInstance().getBuild().asString();
  }

  @Override
  @NotNull
  public ProjectSystemId getProjectSystemId() {
    return myProjectSystemId;
  }

  @Override
  @NotNull
  public String getExternalProjectPath() {
    return myExternalProjectPath;
  }

  @Nullable
  public String getNullSafeExternalProjectPath() {
    return myExternalProjectPath;
  }

  @Override
  @Nullable
  public DataNode<ProjectData> getExternalProjectStructure() {
    return myExternalProjectStructure;
  }

  @Override
  public long getLastSuccessfulImportTimestamp() {
    return lastSuccessfulImportTimestamp;
  }

  @Override
  public long getLastImportTimestamp() {
    return lastImportTimestamp;
  }

  public void setLastSuccessfulImportTimestamp(long lastSuccessfulImportTimestamp) {
    this.lastSuccessfulImportTimestamp = lastSuccessfulImportTimestamp;
  }

  public void setLastImportTimestamp(long lastImportTimestamp) {
    this.lastImportTimestamp = lastImportTimestamp;
  }

  @Override
  public String getBuildNumber() {
    return myBuildNumber;
  }

  @Override
  public ExternalProjectInfo copy() {
    InternalExternalProjectInfo copy = new InternalExternalProjectInfo(
      myProjectSystemId,
      myExternalProjectPath,
      myExternalProjectStructure != null ? myExternalProjectStructure.graphCopy() : null
    );
    copy.setLastImportTimestamp(lastImportTimestamp);
    copy.setLastSuccessfulImportTimestamp(lastSuccessfulImportTimestamp);
    return copy;
  }

  @Override
  public String toString() {
    return "InternalExternalProjectInfo{" +
           "myProjectSystemId=" + myProjectSystemId +
           ", myExternalProjectPath='" + myExternalProjectPath + '\'' +
           ", myExternalProjectStructure=" + myExternalProjectStructure +
           ", lastSuccessfulImportTimestamp=" + lastSuccessfulImportTimestamp +
           ", lastImportTimestamp=" + lastImportTimestamp +
           '}';
  }

  private void writeObject(ObjectOutputStream out) throws IOException {
    out.writeObject(myProjectSystemId);
    out.writeObject(myExternalProjectPath);
    out.writeObject(myExternalProjectStructure);
    out.writeLong(lastSuccessfulImportTimestamp);
    out.writeLong(lastImportTimestamp);
    out.writeObject(myBuildNumber);
  }

  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    myProjectSystemId = (ProjectSystemId)in.readObject();
    myExternalProjectPath = (String)in.readObject();
    //noinspection unchecked
    myExternalProjectStructure = (DataNode<ProjectData>)in.readObject();
    lastSuccessfulImportTimestamp = in.readLong();
    lastImportTimestamp = in.readLong();
    try {
      myBuildNumber = (String)in.readObject();
    }
    catch (OptionalDataException ignore) {
    }
  }
}


text:
var express = require('express');
var router = express.Router();
var path = require('path');
var os = require("os");
var fs = require("fs");
var userController = require('../controllers/user_controller');
var debug = require('debug')('docker-chat:routes');
const multer = require('multer')
const storage_volume = process.env.STORAGE_VOLUME || '/uploads';
const avatar_path = '/avatars';
const upload_location = path.join(storage_volume, avatar_path);

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname, '..', upload_location))
    },
    filename: function (req, file, cb) {
        let ext = path.extname(file.originalname);
        cb(null, file.fieldname.replace(/\W+/g, '-').toLowerCase() + '-' + Date.now() + ext)
    }
})

if (!fs.existsSync(storage_volume)) {
    fs.mkdirSync(storage_volume);
    if (!fs.existsSync(upload_location)) {
        fs.mkdirSync(upload_location);
    }
}

var upload = multer({
    storage: storage
})

/* GET home page. */
router.get('/', function (req, res, next) {
    if (!req.session.user) {
        res.redirect('/login');
    } else {
        res.render('index', {
            title: 'SocketIO Chat Demo',
            number_connected: req.userCount,
            host: os.hostname(),
            parse: process.env.PARSE_MSG
        });
    }
});

/* POST home page. */
router.post('/', function (req, res, next) {
    user = req.body.user;
    debug('User: ' + user + " LOGIN");
    userController.getUser(user, function (foundUser) {
        debug(foundUser.name);
        req.session.user = foundUser;
        res.redirect('/');
    });
});

/* GET login page. */
router.get('/login', function (req, res, next) {
    if (req.session.user) {
        res.redirect('/');
    } else {
        res.render('login', {
            title: 'SocketIO Chat Demo',
            host: os.hostname()
        });
    }
});

/* POST avatar. */
router.post('/avatar', upload.single('avatar'), function (req, res, next) {
    if (!req.session.user) {
        res.redirect('/');
    } else {
        let file = path.join(avatar_path, req.file.filename);
        userController.uploadAvatar(req.session.user.name, file, function (user) {
            req.session.user = user;
            res.redirect('/');
        });
    }
});

/* GET logout page. */
router.get('/logout', function (req, res, next) {
    delete req.session.user;
    res.redirect('/');
});

router.get('/healthcheck', function (req, res, next) {
    res.send(200);
});

module.exports = router;


text:
import _ from "lodash";
import {tallyBy} from "../../common/tally-utils";
import {notEmpty} from "../../common";
import {criticalityColorScale, lifecyclePhaseColorScale, variableScale} from "../../common/colors";

import template from "./app-summary.html";

const bindings = {
    apps: "<",
    endUserApps: "<"
};

const initialState = {
    apps: [],
    endUserApps: [],
    visibility: {
        apps: false,
        endUserApps: false
    }
};

const PIE_SIZE = 70;

const defaultLabelProvider = (d) => d.key;
const lifecycleLabelProvider = (displayNameService, d) => displayNameService.lookup("lifecyclePhase", d.key, d.key);
const criticalityLabelProvider = (displayNameService, d) => d ? displayNameService.lookup("criticality", d.key, d.key) : d;
const applicationKindLabelProvider = (displayNameService, d) => displayNameService.lookup("applicationKind", d.key, d.key);

const randomColorProvider = d => variableScale(d.key);
const lifecycleColorProvider = d => lifecyclePhaseColorScale(d.key);
const criticalityColorProvider = d => criticalityColorScale(d.key);

function mkChartData(data,
                     groupingField,
                     size,
                     colorProvider = randomColorProvider,
                     labelProvider = defaultLabelProvider) {
    return {
        config: {
            colorProvider,
            labelProvider,
            size
        },
        data: tallyBy(data, groupingField)
    };
}

function mkCharts(apps = [], endUserApps = [], displayNameService) {
    return {
        apps: {
            byLifecyclePhase: mkChartData(
                apps,
                "lifecyclePhase",
                PIE_SIZE,
                lifecycleColorProvider,
                (k) => lifecycleLabelProvider(displayNameService, k)),
            byKind: mkChartData(
                apps,
                "applicationKind",
                PIE_SIZE,
                randomColorProvider,
                (k) => applicationKindLabelProvider(displayNameService, k))
        },
        endUserApps: {
            byLifecyclePhase: mkChartData(
                endUserApps,
                "lifecyclePhase",
                PIE_SIZE,
                lifecycleColorProvider,
                (k) => lifecycleLabelProvider(displayNameService, k)),
            byKind: mkChartData(
                endUserApps,
                "platform",
                PIE_SIZE),
            byRiskRating: mkChartData(
                endUserApps,
                "riskRating",
                PIE_SIZE,
                criticalityColorProvider,
                (k) => criticalityLabelProvider(displayNameService, k))
        }
    };
}

function calcVisibility(apps = [], endUserApps = []) {
    return {
        apps: notEmpty(apps),
        endUserApps: notEmpty(endUserApps)
    };
}

function controller(displayNameService) {

    const vm = _.defaultsDeep(this, initialState);

    vm.$onChanges = () => {
        vm.charts = mkCharts(vm.apps, vm.endUserApps, displayNameService);
        vm.visibility = calcVisibility(vm.apps, vm.endUserApps);
    };
}

controller.$inject = ["DisplayNameService"];

const component = {
    template,
    controller,
    bindings
};

export default component;


text:
WK.QueueDiagramView = function(queue) {
    WK.Object.call(this);

    console.assert(queue instanceof WK.PatchQueue, queue);
    this.queue = queue;

    this.element = document.createElement("li");
    this.element.className = "queue";

    this.queueMetrics = new WK.PatchQueueMetrics(queue, {'attempts': []}); // Start with nothing.
}

WK.Object.addConstructorFunctions(WK.QueueDiagramView);

WK.QueueDiagramView.Event = {
    SelectionCleared: "selection-cleared",
    SelectionChanged: "selection-changed"
};

WK.QueueDiagramView.prototype = {
    __proto__: WK.Object.prototype,
    constructor: WK.QueueDiagramView,

    get name()
    {
        return this.queue.shortName;
    },

    get queueMetrics()
    {
        return this._metrics;
    },

    set queueMetrics(value)
    {
        console.assert(value instanceof WK.PatchQueueMetrics, value);
        console.log("got metrics", value);
        this._metrics = value;
        this.render();
    },

    clearSelection: function()
    {
        if (this._selectedAttemptCount === null && this._selectedOutcome === null)
            return;

        this._selectedAttemptCount = null;
        this._selectedOutcome = null;

        this._clearSelectionClasses();
        this._updateEmptyOutcomesVisibility();
        this.dispatchEventToListeners(WK.QueueDiagramView.Event.SelectionCleared);
    },

    setSelection: function(ordinal, outcome)
    {
        console.assert(ordinal >= 0);
        console.assert(outcome);

        ordinal = Math.min(ordinal, 3);

        // Re-selecting with cmd+click should clear.
        if (ordinal === this._selectedAttemptCount && outcome === this._selectedOutcome) {
            if (event.metaKey)
                this.clearSelection();
            return;
        }

        this._selectedAttemptCount = ordinal;
        this._selectedOutcome = outcome;

        // Update styles.
        this._clearSelectionClasses();
        this._updateEmptyOutcomesVisibility();

        var selectedAttemptClassName = null;
        if (outcome === WK.PatchAttempt.Outcome.Pass)
            selectedAttemptClassName = "selected-pass";
        else if (outcome === WK.PatchAttempt.Outcome.Fail)
            selectedAttemptClassName = "selected-fail";
        else if (outcome === WK.PatchAttempt.Outcome.Abort)
            selectedAttemptClassName = "selected-abort";
        else if (outcome === WK.PatchAttempt.Outcome.Retry)
            selectedAttemptClassName = "selected-attempt";
        else
            console.error("unknown outcome: ", outcome);

        for (var i = 0; i < this._attemptElements.length; ++i) {
            var attempt = this._attemptElements[i];
            if (i < ordinal)
                attempt.classList.add("selected-through");
            else if (i === ordinal)
                attempt.classList.add(selectedAttemptClassName);
            else if (outcome !== WK.PatchAttempt.Outcome.Retry)
                attempt.classList.add("selected-ignore");
        }

        this.dispatchEventToListeners(WK.QueueDiagramView.Event.SelectionChanged);
    },

    get selectedOutcome()
    {
        return this._selectedOutcome;
    },

    get selectedAttemptCount()
    {
        return this._selectedAttemptCount;
    },

    render: function()
    {
        this.element.removeChildren();

        this._startElement = $(WK.ViewTemplates.queueDiagramStart(this)).get(0);
        this._startElement.addEventListener("click", this._diagramSegmentClicked.bind(this));
        this.element.appendChild(this._startElement);

        this._attemptElements = [];
        for (var i = 1; i <= 3; ++i) {
            var summary = this.queueMetrics.getSummaryForAttempt(i);
            console.log("summary", summary);
            var attemptElement = $(WK.ViewTemplates.queueDiagramAttempt(summary)).get(0);
            attemptElement.addEventListener("click", this._diagramSegmentClicked.bind(this));
            this._attemptElements.push(attemptElement);
            this.element.appendChild(attemptElement);
        }

        this._updateEmptyOutcomesVisibility();
    },

    // Private

    _diagramSegmentClicked: function(event)
    {
        var target = event.target;
        if (this._startElement === target.enclosingNodeOrSelfWithClass("queue-start")) {
            this.clearSelection();
            return;
        }
        var enclosingSegment = target.enclosingNodeOrSelfWithClass("queue-attempt");
        if (!enclosingSegment)
            return;

        var ordinal = this._attemptElements.indexOf(enclosingSegment);
        if (ordinal === -1)
            return;

        var enclosingCircle = target.enclosingNodeOrSelfWithClass("attempt-circle");
        if (enclosingCircle) {
            this.setSelection(ordinal, WK.PatchAttempt.Outcome.Retry);
            return;
        }

        var enclosingArrowOrLabel = target.enclosingNodeOrSelfWithClass("outcome");
        if (!enclosingArrowOrLabel)
            return;

        var outcome = null;
        if (enclosingArrowOrLabel.classList.contains("pass"))
            outcome = WK.PatchAttempt.Outcome.Pass;
        else if (enclosingArrowOrLabel.classList.contains("fail"))
            outcome = WK.PatchAttempt.Outcome.Fail;
        else if (enclosingArrowOrLabel.classList.contains("abort"))
            outcome = WK.PatchAttempt.Outcome.Abort;
        else if (enclosingArrowOrLabel.classList.contains("attempt"))
            outcome = WK.PatchAttempt.Outcome.Retry;

        if (!outcome)
            return;

        this.setSelection(ordinal, outcome);
    },

    _updateEmptyOutcomesVisibility: function()
    {
        _.each(this._attemptElements, function(attempt, i) {
            var metricsByOutcome = {};
            var totalCount = 0;
            for (var key in WK.PatchAttempt.Outcome) {
                var outcome = WK.PatchAttempt.Outcome[key];
                metricsByOutcome[outcome] = this._metrics.getData(i + 1, outcome);
                totalCount += metricsByOutcome[outcome].count;
            }
            attempt.classList.toggle("empty-pass", metricsByOutcome[WK.PatchAttempt.Outcome.Pass].count === 0);
            attempt.classList.toggle("empty-fail", metricsByOutcome[WK.PatchAttempt.Outcome.Fail].count === 0);
            attempt.classList.toggle("empty-abort", metricsByOutcome[WK.PatchAttempt.Outcome.Abort].count === 0);
            attempt.classList.toggle("empty-retry", metricsByOutcome[WK.PatchAttempt.Outcome.Retry].count === 0);
            attempt.classList.toggle("empty-attempt", i > 1 && totalCount === 0);
        }, this);
    },

    _clearSelectionClasses: function()
    {
        function clearClasses(element) {
            element.classList.remove("selected-pass");
            element.classList.remove("selected-fail");
            element.classList.remove("selected-abort");
            element.classList.remove("selected-attempt");
            element.classList.remove("selected-through");
            element.classList.remove("selected-ignore");
            element.classList.remove("empty-pass");
            element.classList.remove("empty-fail");
            element.classList.remove("empty-abort");
            element.classList.remove("empty-attempt");
        }

        clearClasses(this._startElement);
        _.map(this._attemptElements, clearClasses);
    }
};


text:
/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set expandtab shiftwidth=4 tabstop=4: */

/**
 * \file
 * <PRE>
 * High Performance c-string to javascript-string encoder
 *
 * Copyright © 2006, 2007  Nick Galbreath -- nickg [at] modp [dot] com
 * All rights reserved.
 *
 * http://code.google.com/p/stringencoders/
 *
 * Released under bsd license.  See modp_bjavascript.c for details.
 * </PRE>
 */

#ifndef COM_MODP_STRINGENCODERS_BJAVASCRIPT
#define COM_MODP_STRINGENCODERS_BJAVASCRIPT

#ifdef __cplusplus
#define BEGIN_C extern "C" {
#define END_C }
#else
#define BEGIN_C
#define END_C
#endif

BEGIN_C

/**
 * "javascript" encode a stirng
 * This takes a c-string and does character escaping
 * so it can be put into a var js_string = '...';
 *
 * \param[out] dest output string.  Must
 * \param[in] str The input string
 * \param[in] len  The length of the input string, excluding any
 *   final null byte.
 */
int modp_bjavascript_encode(char* dest, const char* str, int len);

#define modp_bjavascript_encode_len(A) (4*A + 1)

/**
 * Given the exact size of output string.
 *
 * Can be used to allocate the right amount of memory for
 * modp_burl_encode.  Be sure to add 1 byte for final null.
 *
 * This is somewhat expensive since it examines every character
 *  in the input string
 *
 * \param[in] str  The input string
 * \param[in] len  THe length of the input string, excluding any
 *   final null byte (i.e. strlen(str))
 * \return the size of the output string, excluding the final
 *   null byte.
 */
int modp_bjavascript_encode_strlen(const char* str, int len);

END_C

#ifdef __cplusplus
#include <cstring>
#include <string>
namespace modp {

    inline std::string javascript_encode(const char* s, size_t len)
    {
        std::string x(modp_bjavascript_encode_len(len), '\0');
        int d = modp_bjavascript_encode(const_cast<char*>(x.data()), s, len);
        x.erase(d, std::string::npos);
        return x;
    }

    inline std::string javascript_encode(const char* s)
    {
        return javascript_encode(s, strlen(s));
    }

    inline std::string& javascript_encode(std::string& s)
    {
        std::string x(javascript_encode(s.data(), s.size()));
        s.swap(x);
        return s;
    }

    inline std::string javascript_encode(const std::string& s)
    {
        return javascript_encode(s.data(), s.size());
    }

}       /* namespace modp */
#endif  /* __cplusplus */

#endif /* modp_bjavascript */