text:
using namespace std;

namespace search
{
void HotelsClassifier::Add(Result const & result)
{
  if (result.m_details.m_isHotel)
    ++m_numHotels;

  ++m_numResults;
}

void HotelsClassifier::PrecheckHotelQuery(vector<uint32_t> const & types)
{
  m_looksLikeHotelQuery = ftypes::IsHotelChecker::Instance()(types);
}

void HotelsClassifier::Clear()
{
  m_numHotels = 0;
  m_numResults = 0;
  m_looksLikeHotelQuery = false;
}

bool HotelsClassifier::IsHotelResults() const
{
  if (m_looksLikeHotelQuery)
    return true;

  // Threshold used to activate hotels mode. Probably is too strict,
  // but we don't have statistics now.
  double const kThreshold = 0.75;

  return m_numResults == 0 ? false : m_numHotels >= kThreshold * m_numResults;
}
}  // namespace search

redpajama_set_name: RedPajamaGithub


text:
package tracer

import (
	"fmt"
)

type Tracer struct{}

func TracerAsset() ([]byte, error) {
	return nil, fmt.Errorf("not supported on non-Linux systems")
}

func NewTracer(cb Callback) (*Tracer, error) {
	return nil, fmt.Errorf("not supported on non-Linux systems")
}
func (t *Tracer) Start() {
}
func (t *Tracer) AddFdInstallWatcher(pid uint32) (err error) {
	return fmt.Errorf("not supported on non-Linux systems")
}
func (t *Tracer) RemoveFdInstallWatcher(pid uint32) (err error) {
	return fmt.Errorf("not supported on non-Linux systems")
}
func (t *Tracer) Stop() {
}


text:
package com.ig.training.hibernate.domainmodel.composite_keys.single_class.embeddable_withEnum;

import javax.persistence.EmbeddedId;
import javax.persistence.Entity;

@Entity(name="COMP_KEY_SING_EMBEDDED_ENUM_SEAT")
public class TheaterSeat {
   @EmbeddedId
   private TheaterSeatPK theaterSeatPK;

   private double price;

   // required by hibernate
   private TheaterSeat() {
   }

   public TheaterSeat(Row row, int number) {
      this.theaterSeatPK = new TheaterSeatPK(row, number);
   }

   public Row getRow() {
      return theaterSeatPK.getRow();
   }

   public int getNumber() {
      return theaterSeatPK.getNumber();
   }

   public double getPrice() {
      return price;
   }

   public void setPrice(double price) {
      this.price = price;
   }

   @Override
   public String toString() {
      return "TheaterSeat{" +
            "theaterSeatPK='" + theaterSeatPK + '\'' +
            ", price=" + price +
            '}';
   }
}


text:
const express = require('express');
const os = require('os');
const multer = require('multer');
const api = require('../../../../api');
const apiv2 = require('../../../../api/v2');
const mw = require('./middleware');

const auth = require('../../../../services/auth');
const shared = require('../../../shared');

// Handling uploads & imports
const tmpdir = os.tmpdir;
const upload = multer({dest: tmpdir()});

module.exports = function apiRoutes() {
    const router = express.Router();

    // alias delete with del
    router.del = router.delete;

    // ## CORS pre-flight check
    router.options('*', shared.middlewares.api.cors);

    // ## Configuration
    router.get('/configuration', api.http(api.configuration.read));
    router.get('/configuration/:key', mw.authAdminAPI, api.http(api.configuration.read));

    // ## Posts
    router.get('/posts', mw.authAdminAPI, apiv2.http(apiv2.posts.browse));
    router.post('/posts', mw.authAdminAPI, apiv2.http(apiv2.posts.add));
    router.get('/posts/:id', mw.authAdminAPI, apiv2.http(apiv2.posts.read));
    router.get('/posts/slug/:slug', mw.authAdminAPI, apiv2.http(apiv2.posts.read));
    router.put('/posts/:id', mw.authAdminAPI, apiv2.http(apiv2.posts.edit));
    router.del('/posts/:id', mw.authAdminAPI, apiv2.http(apiv2.posts.destroy));

    // # Integrations

    router.get('/integrations', mw.authAdminAPI, apiv2.http(apiv2.integrations.browse));
    router.get('/integrations/:id', mw.authAdminAPI, apiv2.http(apiv2.integrations.read));
    router.post('/integrations', mw.authAdminAPI, apiv2.http(apiv2.integrations.add));
    router.put('/integrations/:id', mw.authAdminAPI, apiv2.http(apiv2.integrations.edit));
    router.del('/integrations/:id', mw.authAdminAPI, apiv2.http(apiv2.integrations.destroy));

    // ## Schedules
    router.put('/schedules/posts/:id', [
        auth.authenticate.authenticateClient,
        auth.authenticate.authenticateUser
    ], api.http(api.schedules.publishPost));

    // ## Settings
    router.get('/settings/routes/yaml', mw.authAdminAPI, apiv2.http(apiv2.settings.download));
    router.post('/settings/routes/yaml',
        mw.authAdminAPI,
        upload.single('routes'),
        shared.middlewares.validation.upload({type: 'routes'}),
        apiv2.http(apiv2.settings.upload)
    );

    router.get('/settings', mw.authAdminAPI, apiv2.http(apiv2.settings.browse));
    router.get('/settings/:key', mw.authAdminAPI, apiv2.http(apiv2.settings.read));
    router.put('/settings', mw.authAdminAPI, apiv2.http(apiv2.settings.edit));

    // ## Users
    router.get('/users', mw.authAdminAPI, apiv2.http(apiv2.users.browse));
    router.get('/users/:id', mw.authAdminAPI, apiv2.http(apiv2.users.read));
    router.get('/users/slug/:slug', mw.authAdminAPI, apiv2.http(apiv2.users.read));
    // NOTE: We don't expose any email addresses via the public api.
    router.get('/users/email/:email', mw.authAdminAPI, apiv2.http(apiv2.users.read));

    router.put('/users/password', mw.authAdminAPI, apiv2.http(apiv2.users.changePassword));
    router.put('/users/owner', mw.authAdminAPI, apiv2.http(apiv2.users.transferOwnership));
    router.put('/users/:id', mw.authAdminAPI, apiv2.http(apiv2.users.edit));
    router.del('/users/:id', mw.authAdminAPI, apiv2.http(apiv2.users.destroy));

    // ## Tags
    router.get('/tags', mw.authAdminAPI, apiv2.http(apiv2.tags.browse));
    router.get('/tags/:id', mw.authAdminAPI, apiv2.http(apiv2.tags.read));
    router.get('/tags/slug/:slug', mw.authAdminAPI, apiv2.http(apiv2.tags.read));
    router.post('/tags', mw.authAdminAPI, apiv2.http(apiv2.tags.add));
    router.put('/tags/:id', mw.authAdminAPI, apiv2.http(apiv2.tags.edit));
    router.del('/tags/:id', mw.authAdminAPI, apiv2.http(apiv2.tags.destroy));

    // ## Subscribers
    router.get('/subscribers', shared.middlewares.labs.subscribers, mw.authAdminAPI, apiv2.http(apiv2.subscribers.browse));
    router.get('/subscribers/csv', shared.middlewares.labs.subscribers, mw.authAdminAPI, apiv2.http(apiv2.subscribers.exportCSV));
    router.post('/subscribers/csv',
        shared.middlewares.labs.subscribers,
        mw.authAdminAPI,
        upload.single('subscribersfile'),
        shared.middlewares.validation.upload({type: 'subscribers'}),
        apiv2.http(apiv2.subscribers.importCSV)
    );
    router.get('/subscribers/:id', shared.middlewares.labs.subscribers, mw.authAdminAPI, apiv2.http(apiv2.subscribers.read));
    router.get('/subscribers/email/:email', shared.middlewares.labs.subscribers, mw.authAdminAPI, apiv2.http(apiv2.subscribers.read));
    router.post('/subscribers', shared.middlewares.labs.subscribers, mw.authAdminAPI, apiv2.http(apiv2.subscribers.add));
    router.put('/subscribers/:id', shared.middlewares.labs.subscribers, mw.authAdminAPI, apiv2.http(apiv2.subscribers.edit));
    router.del('/subscribers/:id', shared.middlewares.labs.subscribers, mw.authAdminAPI, apiv2.http(apiv2.subscribers.destroy));
    router.del('/subscribers/email/:email', shared.middlewares.labs.subscribers, mw.authAdminAPI, apiv2.http(apiv2.subscribers.destroy));

    // ## Roles
    router.get('/roles/', mw.authAdminAPI, apiv2.http(apiv2.roles.browse));

    // ## Clients
    router.get('/clients/slug/:slug', api.http(api.clients.read));

    // ## Slugs
    router.get('/slugs/:type/:name', mw.authAdminAPI, apiv2.http(apiv2.slugs.generate));

    // ## Themes
    router.get('/themes/', mw.authAdminAPI, api.http(api.themes.browse));

    router.get('/themes/:name/download',
        mw.authAdminAPI,
        api.http(api.themes.download)
    );

    router.post('/themes/upload',
        mw.authAdminAPI,
        upload.single('theme'),
        shared.middlewares.validation.upload({type: 'themes'}),
        api.http(api.themes.upload)
    );

    router.put('/themes/:name/activate',
        mw.authAdminAPI,
        api.http(api.themes.activate)
    );

    router.del('/themes/:name',
        mw.authAdminAPI,
        api.http(api.themes.destroy)
    );

    // ## Notifications
    router.get('/notifications', mw.authAdminAPI, apiv2.http(apiv2.notifications.browse));
    router.post('/notifications', mw.authAdminAPI, apiv2.http(apiv2.notifications.add));
    router.del('/notifications/:notification_id', mw.authAdminAPI, apiv2.http(apiv2.notifications.destroy));

    // ## DB
    router.get('/db', mw.authAdminAPI, api.http(api.db.exportContent));
    router.post('/db',
        mw.authAdminAPI,
        upload.single('importfile'),
        shared.middlewares.validation.upload({type: 'db'}),
        api.http(api.db.importContent)
    );
    router.del('/db', mw.authAdminAPI, api.http(api.db.deleteAllContent));

    // ## Mail
    router.post('/mail', mw.authAdminAPI, apiv2.http(apiv2.mail.send));
    router.post('/mail/test', mw.authAdminAPI, apiv2.http(apiv2.mail.sendTest));

    // ## Slack
    router.post('/slack/test', mw.authAdminAPI, apiv2.http(apiv2.slack.sendTest));

    // ## Sessions
    router.get('/session', mw.authAdminAPI, api.http(apiv2.session.read));
    // We don't need auth when creating a new session (logging in)
    router.post('/session',
        shared.middlewares.brute.globalBlock,
        shared.middlewares.brute.userLogin,
        api.http(apiv2.session.add)
    );
    router.del('/session', mw.authAdminAPI, api.http(apiv2.session.delete));

    // ## Authentication
    router.post('/authentication/passwordreset',
        shared.middlewares.brute.globalReset,
        shared.middlewares.brute.userReset,
        api.http(api.authentication.generateResetToken)
    );
    router.put('/authentication/passwordreset', shared.middlewares.brute.globalBlock, api.http(api.authentication.resetPassword));
    router.post('/authentication/invitation', api.http(api.authentication.acceptInvitation));
    router.get('/authentication/invitation', api.http(api.authentication.isInvitation));
    router.post('/authentication/setup', api.http(api.authentication.setup));
    router.put('/authentication/setup', mw.authAdminAPI, api.http(api.authentication.updateSetup));
    router.get('/authentication/setup', api.http(api.authentication.isSetup));

    // ## Uploads
    // @TODO: rename endpoint to /images/upload (or similar)
    router.post('/uploads',
        mw.authAdminAPI,
        upload.single('uploadimage'),
        shared.middlewares.validation.upload({type: 'images'}),
        shared.middlewares.image.normalize,
        apiv2.http(apiv2.upload.image)
    );

    router.post('/uploads/profile-image',
        mw.authAdminAPI,
        upload.single('uploadimage'),
        shared.middlewares.validation.upload({type: 'images'}),
        shared.middlewares.validation.profileImage,
        shared.middlewares.image.normalize,
        apiv2.http(apiv2.upload.image)
    );

    router.post('/db/backup', mw.authenticateClient('Ghost Backup'), api.http(api.db.backupContent));

    router.post('/uploads/icon',
        mw.authAdminAPI,
        upload.single('uploadimage'),
        shared.middlewares.validation.upload({type: 'icons'}),
        shared.middlewares.validation.blogIcon(),
        apiv2.http(apiv2.upload.image)
    );

    // ## Invites
    router.get('/invites', mw.authAdminAPI, apiv2.http(apiv2.invites.browse));
    router.get('/invites/:id', mw.authAdminAPI, apiv2.http(apiv2.invites.read));
    router.post('/invites', mw.authAdminAPI, apiv2.http(apiv2.invites.add));
    router.del('/invites/:id', mw.authAdminAPI, apiv2.http(apiv2.invites.destroy));

    // ## Redirects (JSON based)
    router.get('/redirects/json', mw.authAdminAPI, api.http(api.redirects.download));
    router.post('/redirects/json',
        mw.authAdminAPI,
        upload.single('redirects'),
        shared.middlewares.validation.upload({type: 'redirects'}),
        api.http(api.redirects.upload)
    );

    // ## Webhooks (RESTHooks)
    router.post('/webhooks', mw.authAdminAPI, apiv2.http(apiv2.webhooks.add));
    router.put('/webhooks/:id', mw.authAdminAPI, apiv2.http(apiv2.webhooks.edit));
    router.del('/webhooks/:id', mw.authAdminAPI, apiv2.http(apiv2.webhooks.destroy));

    // ## Oembed (fetch response from oembed provider)
    router.get('/oembed', mw.authAdminAPI, apiv2.http(apiv2.oembed.read));

    return router;
};


text:
package org.apache.syncope.client.console.rest;

import java.util.List;
import org.apache.syncope.common.lib.to.AccessTokenTO;
import org.apache.syncope.common.rest.api.beans.AccessTokenQuery;
import org.apache.syncope.common.rest.api.service.AccessTokenService;
import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;

/**
 * Console client for invoking Rest Access Token's services.
 */
public class AccessTokenRestClient extends BaseRestClient {

    private static final long serialVersionUID = -3161863874876938094L;

    public static void delete(final String key) {
        getService(AccessTokenService.class).delete(key);
    }

    public static int count() {
        return getService(AccessTokenService.class).list(
                new AccessTokenQuery.Builder().page(1).size(0).build()).
                getTotalCount();
    }

    public static List<AccessTokenTO> list(final int page, final int size, final SortParam<String> sort) {
        return getService(AccessTokenService.class).list(
                new AccessTokenQuery.Builder().page(page).size(size).orderBy(toOrderBy(sort)).build()).
                getResult();
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
<title>属性表</TITLE>
<link rel="stylesheet" href="style/default.css" type="text/css">
<link rel="stylesheet" href="style/W3C-REC.css" type="text/css">
<link rel="prev" href="zindex.html">
<link rel="next" href="grammar.html">
<link rel="contents" href="cover.html#minitoc">
<link rel="CSS-properties" href="propidx.html" title="properties">
<link rel="index" href="indexlist.html" title="index">
<link rel="first" href="cover.html">

上一章
下一章
内容
属性
索引

附录 F. 属性表

本附录是信息性的,非规范

NameValuesInitial valueApplies to
(Default: all)Inherited?Percentages
(Default: N/A)Media groups

'azimuth'
<angle> | [[ left-side | far-left | left | center-left | center | center-right | right | far-right | right-side ] || behind ] | leftwards | rightwards | inherit
center

yes

aural

'background-attachment'
scroll | fixed | inherit
scroll

no

visual

'background-color'
<color> | transparent | inherit
transparent

no

visual

'background-image'
<uri> | none | inherit
none

no

visual

'background-position'
[ [ <percentage> | <length> | left | center | right ]            [ <percentage> | <length> | top | center | bottom ]? ] |          [ [ left | center | right ] || [ top | center | bottom ] ] |          inherit
0% 0%

no
参照该盒本身的尺寸
visual

'background-repeat'
repeat | repeat-x | repeat-y | no-repeat | inherit
repeat

no

visual

'background'
['background-color' || 'background-image' || 'background-repeat' || 'background-attachment' || 'background-position'] | inherit
见单独的各个属性

no
允许'background-position'上的百分比
visual

'border-collapse'
collapse | separate | inherit
separate
'table'和'inline-table'元素
yes

visual

'border-color'
[ <color> | transparent ]{1,4} | inherit
见单独的各个属性

no

visual

'border-spacing'
<length> <length>? | inherit
0
'table'和'inline-table'元素
yes

visual

'border-style'
<border-style>{1,4} | inherit
见单独的各个属性

no

visual

'border-top'
'border-right'
'border-bottom'
'border-left'
[ <border-width> || <border-style> || 'border-top-color' ] | inherit
见单独的各个属性

no

visual

'border-top-color'
'border-right-color'
'border-bottom-color'
'border-left-color'
<color> | transparent | inherit
'color'属性的值

no

visual

'border-top-style'
'border-right-style'
'border-bottom-style'
'border-left-style'
<border-style> | inherit
none

no

visual

'border-top-width'
'border-right-width'
'border-bottom-width'
'border-left-width'
<border-width> | inherit
medium

no

visual

'border-width'
<border-width>{1,4} | inherit
见单独的各个属性

no

visual

'border'
[ <border-width> || <border-style> || 'border-top-color' ] | inherit
见单独的各个属性

no

visual

'bottom'
<length> | <percentage> | auto | inherit
auto
定位的元素
no
参照包含块的高度
visual

'caption-side'
top | bottom | inherit
top
'table-caption'元素
yes

visual

'clear'
none | left | right | both | inherit
none
块级元素
no

visual

'clip'
<shape> | auto | inherit
auto
绝对定位的元素
no

visual

'color'
<color> | inherit
取决于用户代理

yes

visual

'content'
normal | none | [ <string> | <uri> | <counter> | attr(<identifier>) | open-quote | close-quote | no-open-quote | no-close-quote ]+ | inherit
normal
:before和:after伪元素
no

all

'counter-increment'
[ <identifier> <integer>? ]+ | none | inherit
none

no

all

'counter-reset'
[ <identifier> <integer>? ]+ | none | inherit
none

no

all

'cue-after'
<uri> | none | inherit
none

no

aural

'cue-before'
<uri> | none | inherit
none

no

aural

'cue'
[ 'cue-before' || 'cue-after' ] | inherit
见单独的各个属性

no

aural

'cursor'
[ [<uri> ,]* [ auto | crosshair | default | pointer | move | e-resize | ne-resize | nw-resize | n-resize | se-resize | sw-resize | s-resize | w-resize | text | wait | help | progress ] ] | inherit
auto

yes

visual, interactive

'direction'
ltr | rtl | inherit
ltr
所有元素,除了下文描述的(情况)
yes

visual

'display'
inline | block | list-item | inline-block | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | none | inherit
inline

no

all

'elevation'
<angle>  | below | level | above | higher | lower | inherit
level

yes

aural

'empty-cells'
show | hide | inherit
show
'table-cell'元素
yes

visual

'float'
left | right | none | inherit
none
所有(元素),除了9.7描述的
no

visual

'font-family'
[[ <family-name> | <generic-family> ] [, <family-name>| <generic-family>]* ] | inherit
取决于用户代理

yes

visual

'font-size'
<absolute-size> | <relative-size> | <length> | <percentage> | inherit
medium

yes
参照继承的字体大小
visual

'font-style'
normal | italic | oblique | inherit
normal

yes

visual

'font-variant'
normal | small-caps | inherit
normal

yes

visual

'font-weight'
normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit
normal

yes

visual

'font'
[ [ 'font-style' || 'font-variant' || 'font-weight' ]? 'font-size' [ / 'line-height' ]? 'font-family' ] | caption | icon | menu | message-box | small-caption | status-bar | inherit
见单独的各个属性

yes
见单独的各个属性
visual

'height'
<length> | <percentage> | auto | inherit
auto
除非替换的行内元素,表格列和列组(column group)外的所有元素
no
见下文
visual

'left'
<length> | <percentage> | auto | inherit
auto
定位的元素
no
参照包含块的宽度
visual

'letter-spacing'
normal | <length> | inherit
normal

yes

visual

'line-height'
normal | <number> | <length> | <percentage> | inherit
normal

yes
参考元素自身的字体大小
visual

'list-style-image'
<uri> | none | inherit
none
具有'display: list-item'的元素
yes

visual

'list-style-position'
inside | outside | inherit
outside
具有'display: list-item'的元素
yes

visual

'list-style-type'
disc | circle | square | decimal | decimal-leading-zero |   lower-roman | upper-roman | lower-greek |  lower-latin | upper-latin | armenian | georgian |  lower-alpha | upper-alpha |  none | inherit
disc
具有'display: list-item'的元素
yes

visual

'list-style'
[ 'list-style-type' || 'list-style-position' || 'list-style-image' ] | inherit
见单独的各个属性
具有'display: list-item'的元素
yes

visual

'margin-right'
'margin-left'
<margin-width> | inherit
0
除display类型为table系列的除了table-caption,table和inline-table以外的所有元素(all elements except elements with table display types other than table-caption, table and inline-table)
no
参照包含块的宽度
visual

'margin-top'
'margin-bottom'
<margin-width> | inherit
0
除display类型为table系列的除了table-caption,table和inline-table以外的所有元素
no
参照包含块的宽度
visual

'margin'
<margin-width>{1,4} | inherit
见单独的各个属性
除display类型为table系列的除了table-caption,table和inline-table以外的所有元素
no
参照包含块的宽度
visual

'max-height'
<length> | <percentage> | none | inherit
none
除非替换的行内元素,表格列和列组(column group)外的所有元素
no
见下文
visual

'max-width'
<length> | <percentage> | none | inherit
none
除非替换的行内元素,表格行和行组(row group)外的所有元素
no
参照包含块的宽度
visual

'min-height'
<length> | <percentage> | inherit
0
除非替换的行内元素,表格列和列组(column group)外的所有元素
no
见下文
visual

'min-width'
<length> | <percentage> | inherit
0
除非替换的行内元素,表格行和行组(row group)外的所有元素
no
参照包含块的宽度
visual

'orphans'
<integer> | inherit
2
块容器元素
yes

visual, paged

'outline-color'
<color> | invert | inherit
invert

no

visual, interactive

'outline-style'
<border-style> | inherit
none

no

visual, interactive

'outline-width'
<border-width> | inherit
medium

no

visual, interactive

'outline'
[ 'outline-color' || 'outline-style' || 'outline-width' ] | inherit
见单独的各个属性

no

visual, interactive

'overflow'
visible | hidden | scroll | auto | inherit
visible
块容器
no

visual

'padding-top'
'padding-right'
'padding-bottom'
'padding-left'
<padding-width> | inherit
0
除table-row-group,table-header-group,table-footer-group,table-row,table-column-group和table-column外的所有元素
no
参照包含块的宽度
visual

'padding'
<padding-width>{1,4} | inherit
见单独的各个属性
除table-row-group,table-header-group,table-footer-group,table-row,table-column-group和table-column外的所有元素
no
参照包含块的宽度
visual

'page-break-after'
auto | always | avoid | left | right | inherit
auto
块级元素(例外见下文)
no

visual, paged

'page-break-before'
auto | always | avoid | left | right | inherit
auto
块级元素(例外见下文)
no

visual, paged

'page-break-inside'
avoid | auto | inherit
auto
块级元素(例外见下文)
no

visual, paged

'pause-after'
<time> | <percentage> | inherit
0

no
见下文
aural

'pause-before'
<time> | <percentage> | inherit
0

no
见下文
aural

'pause'
[ [<time> | <percentage>]{1,2} ] | inherit
见单独的各个属性

no
见'pause-before'和'pause-after'的描述
aural

'pitch-range'
<number> | inherit
50

yes

aural

'pitch'
<frequency> | x-low | low | medium | high | x-high | inherit
medium

yes

aural

'play-during'
<uri> [ mix || repeat ]? | auto | none | inherit
auto

no

aural

'position'
static | relative | absolute | fixed | inherit
static

no

visual

'quotes'
[<string> <string>]+ | none | inherit
depends on user agent

yes

visual

'richness'
<number> | inherit
50

yes

aural

'right'
<length> | <percentage> | auto | inherit
auto
定位的元素
no
参照包含块的宽度
visual

'speak-header'
once | always | inherit
once
具有表头信息的元素
yes

aural

'speak-numeral'
digits | continuous | inherit
continuous

yes

aural

'speak-punctuation'
code | none | inherit
none

yes

aural

'speak'
normal | none | spell-out | inherit
normal

yes

aural

'speech-rate'
<number>  | x-slow | slow | medium | fast | x-fast | faster | slower | inherit
medium

yes

aural

'stress'
<number> | inherit
50

yes

aural

'table-layout'
auto | fixed | inherit
auto
'table'和'inline-table'元素
no

visual

'text-align'
left | right | center | justify | inherit
如果'direction'为'ltr',就是'left',如果'direction'为'rtl'就是'right'
块容器
yes

visual

'text-decoration'
none | [ underline || overline || line-through || blink ] | inherit
none

no(见下文)

visual

'text-indent'
<length> | <percentage> | inherit
0
块容器
yes
参照包含块的宽度
visual

'text-transform'
capitalize | uppercase | lowercase | none | inherit
none

yes

visual

'top'
<length> | <percentage> | auto | inherit
auto
定位的元素
no
参照包含块的高度
visual

'unicode-bidi'
normal | embed | bidi-override | inherit
normal
所有元素,除了下文描述的(情况)
no

visual

'vertical-align'
baseline | sub | super | top | text-top | middle |     bottom | text-bottom | <percentage> | <length> | inherit
baseline
行内级和'table-cell'元素
no
参照元素自身的'line-height'
visual

'visibility'
visible | hidden | collapse | inherit
visible

yes

visual

'voice-family'
[[<specific-voice>  | <generic-voice> ],]* [<specific-voice>  | <generic-voice> ] | inherit
depends on user agent

yes

aural

'volume'
<number> | <percentage> | silent | x-soft | soft | medium | loud | x-loud | inherit
medium

yes
参照继承的值
aural

'white-space'
normal | pre | nowrap | pre-wrap | pre-line | inherit
normal

yes

visual

'widows'
<integer> | inherit
2
块容器元素
yes

visual, paged

'width'
<length> | <percentage> | auto | inherit
auto
除非替换的行内元素,表格行和行组(row group) 外的所有元素
no
参照包含块的宽度
visual

'word-spacing'
normal | <length> | inherit
normal

yes

visual

'z-index'
auto | <integer> | inherit
auto
定位的元素
no

visual

上一章
下一章
内容
属性
索引


text:
"""
===================================================================
Fullerene structure classes (:mod:`sknano.structures._fullerenes`)
===================================================================

.. currentmodule:: sknano.structures._fullerenes

"""
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
__docformat__ = 'restructuredtext en'

from pkg_resources import resource_filename

import numbers
import os

from sknano.core import BaseClass, listdir_dirnames, listdir_fnames
from sknano.core.crystallography import BaseStructure

__all__ = ['Fullerene', 'Fullerenes', 'load_fullerene_data']

def load_fullerene_data():
    """Helper function to populate dict of fullerene data files."""
    datadir = resource_filename('sknano', 'data/fullerenes')
    fullerenes = \
        listdir_dirnames(datadir, filterfunc=lambda name: name.startswith('C'))
    fullerene_data = {}
    for fullerene in fullerenes:
        datapath = os.path.join('data', 'fullerenes', fullerene)
        datadir = resource_filename('sknano', datapath)
        fullerene_data[fullerene] = listdir_fnames(datadir)
    return fullerene_data

class Fullerene(BaseStructure, BaseClass):
    """Fullerene structure class.

    The `fullerene data
    <http://www.nanotube.msu.edu/fullerene/fullerene-isomers.html>`_
    were downloaded from the
    `The Nanotube Site <http://www.nanotube.msu.edu>`_.

    Parameters
    ----------
    N : int
        The :math:`N` in :math:`C_N` where :math:`N` is the number
        fullerene atoms. Always an even integer.
    PG : str, optional
        Symmetry

    Examples
    --------

    """
    def __init__(self, N=60, PG=None, Ni=None, **kwargs):

        super().__init__(**kwargs)

        # Check that N is a valid `N` and that `N` is
        self.N = N
        self.PG = PG
        self.Ni = Ni

    @property
    def N(self):
        return self._N

    @N.setter
    def N(self, value):
        if not (isinstance(value, numbers.Integral) or
                value > 0 or value % 2 == 0):
            raise TypeError('Expected an even, positive integer.')
        self._N = int(value)

    @N.deleter
    def N(self):
        del self._N

    def todict(self):
        return dict(N=self.N)

class Fullerenes(BaseStructure, BaseClass):
    def __init__(self):
        super().__init__()
        self.fullerene_data = load_fullerene_data()

        self.fullerenes = list(self.fullerene_data.keys())
        self.fullerene_files = list(self.fullerene_data.values())

    def todict(self):
        return dict()


text:
package org.apache.taverna.workflowmodel.processor.iteration;

import java.util.Map;

import org.apache.taverna.invocation.Completion;
import org.apache.taverna.workflowmodel.processor.activity.Job;

/**
 * Acts as the input to a stage within the iteration strategy, passes all jobs
 * straight through. NamedInputPortNode objects are, as the name suggests,
 * named. These names correspond to the names of abstract input ports on the
 * Processor object to which the iteration strategy belongs.
 *
 * @author Tom Oinn
 */
@SuppressWarnings("serial")
public class NamedInputPortNode extends AbstractIterationStrategyNode {
	private String portName;
	private int desiredCardinality;

	public NamedInputPortNode(String name, int cardinality) {
		super();
		this.portName = name;
		this.desiredCardinality = cardinality;
	}

	/**
	 * If this node receives a job it will always be pushed without modification
	 * up to the parent
	 */
	@Override
	public void receiveJob(int inputIndex, Job newJob) {
		pushJob(newJob);
	}

	/**
	 * Completion events are passed straight through the same as jobs
	 */
	@Override
	public void receiveCompletion(int inputIndex, Completion completion) {
		pushCompletion(completion);
	}

	/**
	 * Each node maps to a single named input port within the processor
	 */
	public String getPortName() {
		return this.portName;
	}

	/**
	 * Each node defines the level of collection depth for that input port
	 */
	public int getCardinality() {
		return this.desiredCardinality;
	}

	/**
	 * These nodes correspond to inputs to the iteration strategy and are always
	 * leaf nodes as a result.
	 *
	 * @override
	 */
	@Override
	public boolean isLeaf() {
		return true;
	}

	/**
	 * These nodes can never have children
	 *
	 * @override
	 */
	@Override
	public boolean getAllowsChildren() {
		return false;
	}

	/**
	 * Iteration depth is the difference between the supplied input depth and
	 * the desired one. If the desired depth is greater then wrapping will
	 * happen and the iteration depth will be zero (rather than a negative!)
	 */
	@Override
	public int getIterationDepth(Map<String, Integer> inputDepths) {
		int myInputDepth = inputDepths.get(portName);
		int depthMismatch = myInputDepth - desiredCardinality;
		return (depthMismatch > 0 ? depthMismatch : 0);
	}

	@Override
	public String toString() {
		return getClass().getSimpleName() + " " + getPortName() + "("
				+ getCardinality() + ")";
	}
}


text:
import { TextTrack } from './types';

interface TimeRange {
  start: number;
  end: number;
}

export interface VideoElement {
  /**
   * A boolean value that is true if the video should enter or leave picture-in-picture mode automatically when changing tab and/or application
   **/
  autoPictureInPicture?: boolean | null;

  /**
   * The disablePictureInPicture property will hint the user agent to not suggest the picture-in-picture to users or to request it automatically
   **/
  disablePictureInPicture?: boolean | null;

  /**
   * 'poster' HTML attribute, which specifies an image to show while no video data is available
   **/
  poster?: string | null;

  /**
   * A value indicating the intrinsic height of the resource in CSS pixels, or 0 if no media is available yet
   **/
  videoHeight: number;

  /**
   * A value indicating the intrinsic width of the resource in CSS pixels, or 0 if no media is available yet
   **/
  videoWidth: number;
  [key: string]: unknown;
}

export interface MediaElement {
  /**
   * If playback should automatically begin as soon as enough media is available to do so without interruption
   **/
  autoPlay: boolean;

  /**
   * An array of time ranges that have been buffered
   **/
  buffered: TimeRange[];

  /**
   * If the user agent should provide it's own set of controls
   **/
  controls: boolean;

  /**
   * CORS settings value of the media player
   **/
  crossOrigin?: string | null;

  /**
   * The absolute URL of the media resource
   **/
  currentSrc: string;

  /**
   * If audio is muted by default
   **/
  defaultMuted: boolean;

  /**
   * The default media playback rate of the player
   **/
  defaultPlaybackRate: number;

  /**
   * If the media element is allowed to have a remote playback UI
   **/
  disableRemotePlayback?: boolean | null;

  /**
   * An object of the latest error to occur, or null if no errors
   **/
  error?: object | null;

  /**
   * The media file format
   **/
  fileExtension: string;

  /**
   * If the video element is fullscreen
   **/
  fullscreen?: boolean | null;

  /**
   * If the media is a video element, or audio
   **/
  mediaType: 'AUDIO' | 'VIDEO';

  /**
   * The current state of the fetching of media over the network
   **/
  networkState: 'NETWORK_EMPTY' | 'NETWORK_IDLE' | 'NETWORK_LOADING' | 'NETWORK_NO_SOURCE';

  /**
   * If the video element is showing Picture-In-Picture
   **/
  pictureInPicture?: boolean | null;

  /**
   * An array of time ranges played
   **/
  played?: TimeRange[];

  /**
   * The HTML id of the element
   **/
  htmlId: string;

  /**
   * The 'preload' HTML attribute of the media
   **/
  preload: string;

  /**
   * The readiness of the media
   **/
  readyState: 'HAVE_NOTHING' | 'HAVE_METADATA' | 'HAVE_CURRENT_DATA' | 'HAVE_FUTURE_DATA' | 'HAVE_ENOUGH_DATA';

  /**
   * Seekable time range(s)
   **/
  seekable: TimeRange[];

  /**
   * If the media is in the process of seeking to a new position
   **/
  seeking: boolean;

  /**
   * The 'src' HTML attribute of the media element
   **/
  src: string;

  /**
   * An array of TextTrack objects on the media element
   **/
  textTracks?: TextTrack[];
  [key: string]: unknown;
}

export interface MediaPlayerEvent {
  /**
   * The event fired by the media player
   **/
  type: string;

  /**
   * The custom media identifier given by the user
   **/
  mediaLabel?: string | null;
  [key: string]: unknown;
}

export interface MediaPlayer {
  /**
   * The current playback time
   **/
  currentTime: number;

  /**
   * A double-precision floating-point value indicating the duration of the media in seconds
   **/
  duration?: number | null;

  /**
   * If playback of the media has ended
   **/
  ended: boolean;

  /**
   * If the video should restart after ending
   **/
  loop: boolean;

  /**
   * If the media element is muted
   **/
  muted: boolean;

  /**
   * If the media element is paused
   **/
  paused: boolean;

  /**
   * The percent of the way through the media
   **/
  percentProgress?: number | null;

  /**
   * Playback rate (1 is normal)
   **/
  playbackRate: number;

  /**
   * Volume level
   **/
  volume: number;
  [key: string]: unknown;
}


text:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <libgearman/gearman.h>

#include "test.h"
#include "test_gearmand.h"

#define WORKER_TEST_PORT 32123

typedef struct
{
  pid_t gearmand_pid;
  gearman_worker_st worker;
  bool run_worker;
} worker_test_st;

/* Prototypes */
test_return queue_add(void *object);
test_return queue_worker(void *object);

void *create(void *object);
void destroy(void *object);
test_return pre(void *object);
test_return post(void *object);
test_return flush(void);

void *world_create(void);
void world_destroy(void *object);

/* Counter test for worker */
static void *counter_function(gearman_job_st *job __attribute__((unused)),
                              void *context,
                              size_t *result_size,
                              gearman_return_t *ret_ptr __attribute__((unused)))
{
  uint32_t *counter= (uint32_t *)context;

  *result_size= 0;

  *counter= *counter + 1;

  return NULL;
}

test_return queue_add(void *object)
{
  worker_test_st *test= (worker_test_st *)object;
  gearman_client_st client;
  char job_handle[GEARMAN_JOB_HANDLE_SIZE];
  uint8_t *value= (uint8_t *)"background_test";
  size_t value_length= strlen("background_test");

  test->run_worker= false;

  if (gearman_client_create(&client) == NULL)
    return TEST_FAILURE;

  if (gearman_client_add_server(&client, NULL,
                                WORKER_TEST_PORT) != GEARMAN_SUCCESS)
  {
    return TEST_FAILURE;
  }

  if (gearman_client_do_background(&client, "queue_test", NULL, value,
                                   value_length, job_handle) != GEARMAN_SUCCESS)
  {
    return TEST_FAILURE;
  }

  gearman_client_free(&client);

  test->run_worker= true;
  return TEST_SUCCESS;
}

test_return queue_worker(void *object)
{
  worker_test_st *test= (worker_test_st *)object;
  gearman_worker_st *worker= &(test->worker);
  uint32_t counter= 0;

  if (!test->run_worker)
    return TEST_FAILURE;

  if (gearman_worker_add_function(worker, "queue_test", 5, counter_function,
                                  &counter) != GEARMAN_SUCCESS)
  {
    return TEST_FAILURE;
  }

  if (gearman_worker_work(worker) != GEARMAN_SUCCESS)
    return TEST_FAILURE;

  if (counter == 0)
    return TEST_FAILURE;

  return TEST_SUCCESS;
}

test_return flush(void)
{
  return TEST_SUCCESS;
}

void *create(void *object)
{
  return object;
}

void destroy(void *object __attribute__((unused)))
{
}

test_return pre(void *object __attribute__((unused)))
{
  return TEST_SUCCESS;
}

test_return post(void *object __attribute__((unused)))
{
  return TEST_SUCCESS;
}

void *world_create(void)
{
  worker_test_st *test;
  const char *argv[2]= { "test_gearmand", "--libsqlite3-db=/tmp/gearman.sql"};

  assert((test= malloc(sizeof(worker_test_st))) != NULL);
  memset(test, 0, sizeof(worker_test_st));
  assert(gearman_worker_create(&(test->worker)) != NULL);

  assert(gearman_worker_add_server(&(test->worker), NULL, WORKER_TEST_PORT) ==
         GEARMAN_SUCCESS);

  test->gearmand_pid= test_gearmand_start(WORKER_TEST_PORT, "libsqlite3", (char **)argv, 2);

  return (void *)test;
}

void world_destroy(void *object)
{
  worker_test_st *test= (worker_test_st *)object;
  gearman_worker_free(&(test->worker));
  test_gearmand_stop(test->gearmand_pid);
  free(test);
}

test_st tests[] ={
  {"add", 0, queue_add },
  {"worker", 0, queue_worker },
  {0, 0, 0}
};

collection_st collection[] ={
#ifdef HAVE_LIBSQLITE3
  {"sqlite queue", flush, create, destroy, pre, post, tests},
#endif
  {0, 0, 0, 0, 0, 0, 0}
};

void get_world(world_st *world)
{
  world->collections= collection;
  world->create= world_create;
  world->destroy= world_destroy;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;

using Shared;
using Shared.Models;

namespace DataAccess
{
    public class DataManager
    {
        private String connectionString = ConfigurationManager.ConnectionStrings["BookData"].ToString();

        #region Sql Methods

        /// <summary>
        /// Returns a new sql parameter with the given paramenters.
        /// </summary>
        /// <param name="parameterName"></param>
        /// <param name="value"></param>
        /// <param name="dbtype"></param>
        /// <returns></returns>
        private SqlParameter GetParameter(String parameterName, Object value, DbType dbtype)
        {
            SqlParameter param = new SqlParameter();
            param.ParameterName = parameterName;
            param.Value = value;
            param.DbType = dbtype;
            return param;
        }

        /// <summary>
        /// Returns the connection string.
        /// </summary>
        /// <returns></returns>
        private String GetConnectionString()
        {
            return connectionString;
        }

        /// <summary>
        /// Returns a new sql connection.
        /// </summary>
        /// <returns></returns>
        private SqlConnection GetConnection()
        {
            SqlConnection connection = new SqlConnection(GetConnectionString());
            connection.Open();
            return connection;
        }

        /// <summary>
        /// Closes the provided sql connection.
        /// </summary>
        /// <param name="connection"></param>
        private void CloseConnection(SqlConnection connection)
        {
            connection.Close();
        }

        /// <summary>
        /// Returns the SqlCommand object based on the type of operation passed
        /// </summary>
        /// <param name="operationType"></param>
        /// <returns></returns>
        private SqlCommand GetCommand(String operationType)
        {
            String dataQuery = OperationType.Map[operationType];
            SqlConnection connection = GetConnection();
            SqlCommand command = new SqlCommand(dataQuery, connection);

            return command;
        }

        #endregion Sql Methods

        #region CRUD

        /// <summary>
        /// Get book data for a particular catagory
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public List<BookModel> ReadBookByCategory(Dictionary<String, Object> data)
        {
            BookModel bookModel;
            SqlDataReader dataReader;
            List<BookModel> returnData = new List<BookModel>();
            SqlCommand command = GetCommand(OperationType.ReadByCategory);
            String category = data["category"].ToString().ToUpper();

            command.Parameters.Add(GetParameter("@category", category, DbType.String));
            dataReader = command.ExecuteReader();
            while (dataReader.Read())
            {
                bookModel = GetBookModel((Int32)dataReader["Id"],
                                dataReader["Name"].ToString(),
                                dataReader["AuthorName"].ToString(),
                                dataReader["PublisherName"].ToString(),
                                (Int32)dataReader["Price"],
                                Convert.ToDecimal(dataReader["Discount"]),
                                (Int32)dataReader["Rating"],
                                dataReader["Language"].ToString(),
                                (Int32)dataReader["PublicationYear"],
                                dataReader["ISBN13"].ToString(),
                                dataReader["ISBN10"].ToString(),
                                dataReader["Category"].ToString(),
                                dataReader["Image"].ToString(),
                                dataReader["Details"].ToString());

                returnData.Add(bookModel);
            }
            CloseConnection(command.Connection);
            return returnData;
        }

        /// <summary>
        /// Read book by its Id
        /// </summary>
        /// <param name="operationType"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public List<BookModel> ReadBookById(Dictionary<String, Object> data)
        {
            BookModel bookModel;
            SqlDataReader dataReader;
            List<BookModel> returnData = new List<BookModel>();
            SqlCommand command = GetCommand(OperationType.ReadById);
            Int32 id = Convert.ToInt32(data["id"]);

            command.Parameters.Add(GetParameter("@id", id, DbType.Int32));
            dataReader = command.ExecuteReader();
            while (dataReader.Read())
            {
                bookModel = GetBookModel((Int32)dataReader["Id"],
                                dataReader["Name"].ToString(),
                                dataReader["AuthorName"].ToString(),
                                dataReader["PublisherName"].ToString(),
                                (Int32)dataReader["Price"],
                                Convert.ToDecimal(dataReader["Discount"]),
                                (Int32)dataReader["Rating"],
                                dataReader["Language"].ToString(),
                                (Int32)dataReader["PublicationYear"],
                                dataReader["ISBN13"].ToString(),
                                dataReader["ISBN10"].ToString(),
                                dataReader["Category"].ToString(),
                                dataReader["Image"].ToString(),
                                dataReader["Details"].ToString());

                returnData.Add(bookModel);
            }
            CloseConnection(command.Connection);
            return returnData;
        }

        /// <summary>
        /// Read Books Data
        /// </summary>
        /// <returns></returns>
        public List<BookModel> ReadBooksData()
        {
            BookModel bookModel;
            List<BookModel> returnData = new List<BookModel>();
            SqlDataReader dataReader;
            SqlCommand command = GetCommand(OperationType.Read);

            dataReader = command.ExecuteReader();

            while (dataReader.Read())
            {
                bookModel = GetBookModel((Int32)dataReader["Id"],
                                dataReader["Name"].ToString(),
                                dataReader["AuthorName"].ToString(),
                                dataReader["PublisherName"].ToString(),
                                (Int32)dataReader["Price"],
                                Convert.ToDecimal(dataReader["Discount"]),
                                (Int32)dataReader["Rating"],
                                dataReader["Language"].ToString(),
                                (Int32)dataReader["PublicationYear"],
                                dataReader["ISBN13"].ToString(),
                                dataReader["ISBN10"].ToString(),
                                dataReader["Category"].ToString(),
                                dataReader["Image"].ToString(),
                                dataReader["Details"].ToString());
                returnData.Add(bookModel);
            }

            CloseConnection(command.Connection);
            return returnData;
        }

        #endregion CRUD

        #region Helper Methods

        /// <summary>
        /// Returns new BookModel object with the passed parameters
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="authorName"></param>
        /// <param name="publisherName"></param>
        /// <param name="price"></param>
        /// <param name="discount"></param>
        /// <param name="rating"></param>
        /// <param name="language"></param>
        /// <param name="publicationYear"></param>
        /// <param name="iSBN13"></param>
        /// <param name="iSBN10"></param>
        /// <param name="category"></param>
        /// <param name="image"></param>
        /// <param name="details"></param>
        /// <returns></returns>
        private BookModel GetBookModel(Int32 id, String name, String authorName, String publisherName, Int32 price,
                                        Decimal discount, Int32 rating, String language, Int32 publicationYear,
                                        String iSBN13, String iSBN10, String category, String image, String details)
        {
            return new BookModel
            {
                Id = id,
                Name = name,
                AuthorName = authorName,
                PublisherName = publisherName,
                Price = price,
                Discount = discount,
                Rating = rating,
                Language = language,
                PublicationYear = publicationYear,
                ISBN13 = iSBN13,
                ISBN10 = iSBN10,
                Category = category,
                Image = image,
                Details = details,
            };
        }

        #endregion Helper Methods
    }
}


text:
using LionFire.Instantiating;

namespace LionFire.Assets
{
    public interface ITemplateAssetInstance : ITemplateInstance
    {
        ITemplateAsset TemplateAsset { get; set; }
    }
}


text:
package org.apache.flink.graph.scala.examples

import org.apache.flink.api.common.functions.MapFunction
import org.apache.flink.api.scala._
import org.apache.flink.graph.examples.data.SingleSourceShortestPathsData
import org.apache.flink.graph.scala._
import org.apache.flink.graph.scala.utils.Tuple3ToEdgeMap
import org.apache.flink.graph.spargel.{GatherFunction, MessageIterator, ScatterFunction}
import org.apache.flink.graph.{Edge, Vertex}

import scala.collection.JavaConversions._

/**
 * This example shows how to use Gelly's scatter-gather iterations.
 *
 * It is an implementation of the Single-Source-Shortest-Paths algorithm.
 *
 * The input file is a plain text file and must be formatted as follows:
 * Edges are represented by tuples of srcVertexId, trgVertexId, distance which are
 * separated by tabs. Edges themselves are separated by newlines.
 * For example: 1\t2\t0.1\n1\t3\t1.4\n defines two edges,
 * edge 1-2 with distance 0.1, and edge 1-3 with distance 1.4.
 *
 * If no parameters are provided, the program is run with default data from
 * [[SingleSourceShortestPathsData]]
 */
object SingleSourceShortestPaths {
  def main(args: Array[String]) {
    if (!parseParameters(args)) {
      return
    }

    val env = ExecutionEnvironment.getExecutionEnvironment
    val edges: DataSet[Edge[Long, Double]] = getEdgesDataSet(env)
    val graph = Graph.fromDataSet[Long, Double, Double](edges, new InitVertices(srcVertexId), env)

    // Execute the scatter-gather iteration
    val result = graph.runScatterGatherIteration(new MinDistanceMessenger,
      new VertexDistanceUpdater, maxIterations)

    // Extract the vertices as the result
    val singleSourceShortestPaths = result.getVertices

    // emit result
    if (fileOutput) {
      singleSourceShortestPaths.writeAsCsv(outputPath, "\n", ",")
      env.execute("Single Source Shortest Paths Example")
    } else {
      singleSourceShortestPaths.print()
    }
  }

  // --------------------------------------------------------------------------------------------
  //  Single Source Shortest Path UDFs
  // --------------------------------------------------------------------------------------------

  private final class InitVertices(srcId: Long) extends MapFunction[Long, Double] {

    override def map(id: Long) = {
      if (id.equals(srcId)) {
        0.0
      } else {
        Double.PositiveInfinity
      }
    }
  }

  /**
   * Distributes the minimum distance associated with a given vertex among all
   * the target vertices summed up with the edge's value.
   */
  private final class MinDistanceMessenger extends
    ScatterFunction[Long, Double, Double, Double] {

    override def sendMessages(vertex: Vertex[Long, Double]) {
      if (vertex.getValue < Double.PositiveInfinity) {
        for (edge: Edge[Long, Double] <- getEdges) {
          sendMessageTo(edge.getTarget, vertex.getValue + edge.getValue)
        }
      }
    }
  }

  /**
    * Function that updates the value of a vertex by picking the minimum
    * distance from all incoming messages.
    */
  private final class VertexDistanceUpdater extends GatherFunction[Long, Double, Double] {

    override def updateVertex(vertex: Vertex[Long, Double], inMessages: MessageIterator[Double]) {
      var minDistance = Double.MaxValue
      while (inMessages.hasNext) {
        val msg = inMessages.next
        if (msg < minDistance) {
          minDistance = msg
        }
      }
      if (vertex.getValue > minDistance) {
        setNewVertexValue(minDistance)
      }
    }
  }

  // ****************************************************************************
  // UTIL METHODS
  // ****************************************************************************

  private var fileOutput = false
  private var srcVertexId = 1L
  private var edgesInputPath: String = null
  private var outputPath: String = null
  private var maxIterations = 5

  private def parseParameters(args: Array[String]): Boolean = {
    if(args.length > 0) {
      if(args.length != 4) {
        System.err.println("Usage: SingleSourceShortestPaths <source vertex id>" +
          " <input edges path> <output path> <num iterations>")
      }
      fileOutput = true
      srcVertexId = args(0).toLong
      edgesInputPath = args(1)
      outputPath = args(2)
      maxIterations = 3
    } else {
      System.out.println("Executing Single Source Shortest Paths example "
        + "with default parameters and built-in default data.")
      System.out.println("  Provide parameters to read input data from files.")
      System.out.println("  See the documentation for the correct format of input files.")
      System.out.println("Usage: SingleSourceShortestPaths <source vertex id>" +
        " <input edges path> <output path> <num iterations>")
    }
    true
  }

  private def getEdgesDataSet(env: ExecutionEnvironment): DataSet[Edge[Long, Double]] = {
    if (fileOutput) {
      env.readCsvFile[(Long, Long, Double)](edgesInputPath,
        lineDelimiter = "\n",
        fieldDelimiter = "\t")
        .map(new Tuple3ToEdgeMap[Long, Double]())
    } else {
      val edgeData = SingleSourceShortestPathsData.DEFAULT_EDGES map {
        case Array(x, y, z) => (x.asInstanceOf[Long], y.asInstanceOf[Long],
          z.asInstanceOf[Double])
      }
      env.fromCollection(edgeData).map(new Tuple3ToEdgeMap[Long, Double]())
    }
  }
}


text:
@interface SampleAppViewController : UIViewController <CPLockControllerDelegate> {

}

- (IBAction)requirePasscode:(id)sender;
- (IBAction)changePasscode:(id)sender;

@end


text:
widenbot
----

> _A Slack bot and plugin framework for Widen_

[![Build
Status](http://img.shields.io/travis/Widen/widenbot.svg?branch=master&style=flat)](https://travis-ci.org/Widen/widenbot) | [![Version](http://img.shields.io/npm/v/widenbot.svg?style=flat)](https://www.npmjs.org/package/widenbot) | [![Waffle.io](http://img.shields.io/badge/waffle-board-yellow.svg?style=flat)](https://waffle.io/Widen/widenbot)

----

- [Dockerstart](#dockerstart)
- [Quickstart](#quickstart)
- [Features](#features)
- [Configuration](#config)
    - [Usage](#config-usage)
    - [Format](#config-format)
    - [Brain](#config-brain)
    - [Plugins](#config-plugins)
    - [Logging](#config-logging)
- [Plugins](#plugins)
    - [Format](#plugins-format)
    - [Example](#plugins-example)
- [Webhooks](#webhooks)
    - [Format](#webhooks-format)
    - [Example](#webhooks-example)
- [Development](#development)
    - [Creating Environment](#development-env)
    - [Contributing Guidelines](#development-contributing)

# Dockerstart

```
% docker build -t widen/widenbot .
% docker run -it --rm --name widenbot widen/widenbot
```

(IMHO, this is the easiest way to get started, and mirrors the way in works
in production).

# Quickstart

**Global Install:**

```shell
% npm install -g https://github.com/widen/widenbot
% cp config.example.js config.js
% widenbot -c config.js
```

**Local Install (recommended):**

```shell
% npm install https://github.com/widen/widenbot
% cp config.example.js config.js
% ./node_modules/.bin/widenbot -c config.js
```

It is recommended to use environment variables for secret data such as API
keys and secrets.

# Features

- Plugin framework: easily create new plugins to do anything in response to
  Slack commands!
- Webhook framework: send messages to users or channels when another service
  alerts the bot.
- Logging: Extensible logging framework. Can send data to loggly, or anywhere
  really.

# Config

The configuration for the bot is stored in a javascript file. That is
`require`d by the bot process. This means you can include executable Javscript
within the configuration. An example is provided in [config.example.js](config.example.js)

## Usage

The configuration is loaded and interpreted at runtime. A configuration can be
provided via the command-line wrapper.

`% widenbot --config path/to/config.js`

Currently recognized fields are:

- `name`: the bot's name
- `icon`: the bot's icon. Can be an emoji (":ghost:") or a URL.
- `repl`: whether to launch an interactive repl with all plugins loaded
  (default: false)
- `token`: Slack's outgoing webook token
- `url`: Slack's incoming webhook url
- `dbpath`: Path for the database to exist at
- `logging`: Options for the logger
    - `path`: Path for the logs to be written to
    - `console` (optional): If true logs are written to console too
- `plugins`: A hash of plugin names and options. Only plugins in this hash
  will be recognized.

## Format

The configuration file should simply export a plain ol' Javascript object with
keys and values corresponding to the desired configuration values.

```javascript
module.exports = {
    "key": "value",
    "key2": ["array_value1", "array_value2"],
    "env_key": process.env.SECRET_KEY_NAME
};
```

## Brain

The brain is the memory for the bot. This is persisted using levelup and
leveldown (leveldb) with an eye for supporting any sort of backend in the
future.

Each plugin is given a namespace within the brain to store and retrieve data.

**Required options:**

- `dbpath`: Path for the database to exist at

## Plugins

Plugins can extend the bot's ability to respond and act on commands.

**Required options:**

- `plugins`: A hash of plugin names and options hashes. Only plugins in this hash
  will be recognized.

Example:

```javascript
plugins: {
    "echo": {}
    "lastfm": {
        "api_key": "BLAHBLAH"
    }
}
```

The plugin name ("echo" or "lastfm" in the example) **must** correspond to the filename in `./plugins`, or a node module that can be `require`'d'.
The plugin options **must** be either the empty object `{}`, or a hash of
options. These options will be avaiable to the plugin when it is evaluated so
integrators can access API keys and other configuration variables for that
plugin.

## Logging

widenbot uses [bunyan](https://www.npmjs.org/package/bunyan) as its logging backend since it integrates nicely
with [restify](https://www.npmjs.org/package/restify) (the web framework being used).

Options for logging are specified in the `logging` hash in the configuration.

- `logging`: Options for the logger
    - `path`: Path for the logs to be written to
    - `console` (optional): If true logs are written to console too

# Plugins

Plugins are easy to create. Just add a new file to `./plugins` or install a
compatible node module, and add the plugin name and options to the
configuration.

## Format

A plugin must export a plain ol' Javascript object with a few required
properties:

**`pattern`**:

this is the regex pattern that incoming commands will be matched against.
If a match is found, then this plugin will execute on that command.

**`respond`**:

This is the main response handler function for the plugin. It
receives a `context` (which is an object with the command, username,
arguments, plugin options, and a reference to the brain).

This function should return a value or a promise. If the value is empty string, then
nothing is sent back. If promise is rejected, then nothing is sent back.
Else, resolve value is sent back, or the returned value is sent back.

The response can also add attachments to the `ctx.outgoing_message` as outlined in the Slack API.

## Example

```javascript
# Must export an object '{}'
var Echo = module.exports = {

    # metadata
    "name": "Echo", # Plugin's name
    "author": "Mark Feltner", # Plugin author's name
    "description": "Echoes what was just said.", # Plugin description
    "help": "echo", # Plugin help text

    # what text the command should match
    "pattern": /^echo$/,

    # function that will respond
    # can return a value or a promise
    "respond": function(ctx) {
        return ctx.args;
    }
};
```

# Webhooks

Much like plugins, webhooks are POJOs defined in the configuration.

Rather than match a regex like plugins, webhooks are matched via their name
and a url namespace. All webhook requests should follow the format:
`http://path-to-bot/webhooks/:webhook_name` where webhook_name is the name
of the hook defined in `config.js`, and all webhook requests should be POSTs.

**`respond`**:

Responds to the webhook. Should follow the signature:

`function (context, req, res, next){}`

As of right now, **must return a promise**. The `resolve()` success value
is hash containing:

```javascript
{
   to: '', // <required> which room '#' or user '@' this message is going to>
   response: '', // <required> response text, or hash response with
   attachments
   from: '', // <optional> who is sending the message. defaults to the botname
   in the config
}
```

## Format

## Example

# Development

## Creating Environment

```shell
% git clone git@github.com:Widen/widenbot.git
% cd widenbot
% npm i
% cp config.example.js config.js
% vim config.js
% node bin/cli.js -c config.js
```

## Development Scripts

All development build scripts are located in the `package.json` `scripts` key.

- `npm run changelog`: (_WIP_) generate a changelog
- `npm run watch`: if you have [nodemon]() this will reload on changes
- `npm run lint`: Run jshint on code
- `npm run unit-test`: Run test suite
- `npm run coverage`: Run coverage suiet
- `npm test`: Run lint and test suite (this is used by Travis CI)

## Contributing Guidelines

See our [contributing guidelines](CONTRIBUTING.md)


text:
package net.sourceforge.lept4j;

import com.sun.jna.ptr.PointerByReference;
import java.io.File;
import static net.sourceforge.lept4j.ILeptonica.IFF_JFIF_JPEG;
import static net.sourceforge.lept4j.ILeptonica.IFF_PNG;
import static net.sourceforge.lept4j.ILeptonica.IFF_TIFF_G4;
import net.sourceforge.lept4j.util.LeptUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * Java version of dewarptest1.c, this exercises functions in
 * dewarp.c for dewarping based on lines of horizontal text. It
 * also creates a 24-image pdf of steps in the process.
 Output files could
 * be found in C:\Users\yourname\AppData\Local\Temp\leptonica
 * directory on Windows.
 *

 * Note: Leptonica uses gthumb on Unix and IrfanView (i_view32) on
 * Windows for displaying images.
 */
public class DewarpTest {

    private final String testResourcesPath = "src/test/resources/test-data";
    Leptonica instance;

    public DewarpTest() {
        instance = new LeptonicaImpl().getInstance();
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of Dewarp algorithm.
     *
     * @throws java.lang.Exception
     */
    @Test
    public void testDewarp() throws Exception {
        System.out.println("Dewarp");
        L_Dewarp dew1, dew2;
        L_Dewarpa dewa;
        Pix pixs, pixn, pixg, pixb, pixd, pixt1, pixt2;
        Pix pixs2, pixn2, pixg2, pixb2, pixd2;

        instance.setLeptDebugOK(1);
        instance.lept_mkdir("lept/model");

        /*    pixs = instance.pixRead("1555-7.jpg"); */
        String filename = "cat-35.jpg";
        File image = new File(testResourcesPath, filename);
        pixs = instance.pixRead(image.getPath());
        /*    pixs =  instance.pixRead("cat-10.jpg"); */

        /* Normalize for varying background and binarize */
        pixn = instance.pixBackgroundNormSimple(pixs, null, null);
        pixg = instance.pixConvertRGBToGray(pixn, 0.5f, 0.3f, 0.2f);
        pixb = instance.pixThresholdToBinary(pixg, 130);

        /* Run the basic functions */
        dewa = instance.dewarpaCreate(2, 30, 1, 10, 30);
        instance.dewarpaUseBothArrays(dewa, 1);
        dew1 = instance.dewarpCreate(pixb, 35);
        instance.dewarpaInsertDewarp(dewa, dew1);
        instance.dewarpBuildPageModel(dew1, "/tmp/lept/model/dewarp_model1.pdf");
        PointerByReference ppixd = new PointerByReference();
        instance.dewarpaApplyDisparity(dewa, 35, pixg, 200, 0, 0, ppixd, "/tmp/lept/model/dewarp_apply1.pdf");
        pixd = new Pix(ppixd.getValue());

        /* Write out some of the files to be imaged */
        instance.lept_rmdir("lept/dewtest");
        instance.lept_mkdir("lept/dewtest");
        instance.pixWrite("/tmp/lept/dewtest/001.jpg", pixs, IFF_JFIF_JPEG);
        instance.pixWrite("/tmp/lept/dewtest/002.jpg", pixn, IFF_JFIF_JPEG);
        instance.pixWrite("/tmp/lept/dewtest/003.jpg", pixg, IFF_JFIF_JPEG);
        instance.pixWrite("/tmp/lept/dewtest/004.png", pixb, IFF_TIFF_G4);
        instance.pixWrite("/tmp/lept/dewtest/005.jpg", pixd, IFF_JFIF_JPEG);
        pixt1 = instance.pixRead("/tmp/lept/dewmod/0020.png");
        instance.pixWrite("/tmp/lept/dewtest/006.png", pixt1, IFF_PNG);
        pixDestroy(pixt1);
        pixt1 = instance.pixRead("/tmp/lept/dewmod/0030.png");
        instance.pixWrite("/tmp/lept/dewtest/007.png", pixt1, IFF_PNG);
        pixDestroy(pixt1);
        pixt1 = instance.pixRead("/tmp/lept/dewmod/0060.png");
        instance.pixWrite("/tmp/lept/dewtest/008.png", pixt1, IFF_PNG);
        pixDestroy(pixt1);
        pixt1 = instance.pixRead("/tmp/lept/dewmod/0070.png");
        instance.pixWrite("/tmp/lept/dewtest/009.png", pixt1, IFF_PNG);
        pixDestroy(pixt1);
        pixt1 = instance.pixRead("/tmp/lept/dewapply/002.png");
        instance.pixWrite("/tmp/lept/dewtest/010.png", pixt1, IFF_PNG);
        pixDestroy(pixt1);
        pixt1 = instance.pixRead("/tmp/lept/dewapply/003.png");
        instance.pixWrite("/tmp/lept/dewtest/011.png", pixt1, IFF_PNG);
        pixt2 = instance.pixThresholdToBinary(pixt1, 130);
        instance.pixWrite("/tmp/lept/dewtest/012.png", pixt2, IFF_TIFF_G4);
        pixDestroy(pixt1);
        pixDestroy(pixt2);
        pixt1 = instance.pixRead("/tmp/lept/dewmod/0041.png");
        instance.pixWrite("/tmp/lept/dewtest/013.png", pixt1, IFF_PNG);
        pixDestroy(pixt1);
        pixt1 = instance.pixRead("/tmp/lept/dewmod/0042.png");
        instance.pixWrite("/tmp/lept/dewtest/014.png", pixt1, IFF_PNG);
        pixDestroy(pixt1);
        pixt1 = instance.pixRead("/tmp/lept/dewmod/0051.png");
        instance.pixWrite("/tmp/lept/dewtest/015.png", pixt1, IFF_PNG);
        pixDestroy(pixt1);
        pixt1 = instance.pixRead("/tmp/lept/dewmod/0052.png");
        instance.pixWrite("/tmp/lept/dewtest/016.png", pixt1, IFF_PNG);
        pixDestroy(pixt1);

        /* Normalize another image, that may not have enough textlines
         * to build an accurate model */
 /*    pixs2 =  instance.pixRead("1555-3.jpg");  */
        filename = "cat-7.jpg";
        image = new File(testResourcesPath, filename);
        pixs2 = instance.pixRead(image.getPath());
        /*    pixs2 =  instance.pixRead("cat-14.jpg"); */
        pixn2 = instance.pixBackgroundNormSimple(pixs2, null, null);
        pixg2 = instance.pixConvertRGBToGray(pixn2, 0.5f, 0.3f, 0.2f);
        pixb2 = instance.pixThresholdToBinary(pixg2, 130);

        /* Apply the previous disparity model to this image */
        dew2 = instance.dewarpCreate(pixb2, 7);
        instance.dewarpaInsertDewarp(dewa, dew2);
        instance.dewarpaInsertRefModels(dewa, 0, 1);
//        dewarpaInfo(stderr, dewa);

        instance.dewarpaApplyDisparity(dewa, 7, pixg2, 200, 0, 0, ppixd, "/tmp/lept/model/dewarp_apply2.pdf");
        pixd2 = new Pix(ppixd.getValue());
        LeptUtils.dispose(dewa);

        /* Write out files for the second image */
        instance.pixWrite("/tmp/lept/dewtest/017.jpg", pixs2, IFF_JFIF_JPEG);
        instance.pixWrite("/tmp/lept/dewtest/018.jpg", pixg2, IFF_JFIF_JPEG);
        instance.pixWrite("/tmp/lept/dewtest/019.png", pixb2, IFF_TIFF_G4);
        instance.pixWrite("/tmp/lept/dewtest/020.jpg", pixd2, IFF_JFIF_JPEG);
        pixt1 = instance.pixRead("/tmp/lept/dewmod/0060.png");
        instance.pixWrite("/tmp/lept/dewtest/021.png", pixt1, IFF_PNG);
        pixDestroy(pixt1);
        pixt1 = instance.pixRead("/tmp/lept/dewapply/002.png");
        instance.pixWrite("/tmp/lept/dewtest/022.png", pixt1, IFF_PNG);
        pixt2 = instance.pixThresholdToBinary(pixt1, 130);
        instance.pixWrite("/tmp/lept/dewtest/023.png", pixt2, IFF_TIFF_G4);
        pixDestroy(pixt1);
        pixDestroy(pixt2);
        pixt1 = instance.pixRead("/tmp/lept/dewmod/0070.png");
        instance.pixWrite("/tmp/lept/dewtest/024.png", pixt1, IFF_PNG);
        pixDestroy(pixt1);
        pixt1 = instance.pixRead("/tmp/lept/dewapply/003.png");
        instance.pixWrite("/tmp/lept/dewtest/025.png", pixt1, IFF_PNG);
        pixt2 = instance.pixThresholdToBinary(pixt1, 130);
        instance.pixWrite("/tmp/lept/dewtest/026.png", pixt2, IFF_TIFF_G4);
        pixDestroy(pixt1);
        pixDestroy(pixt2);

        /* Generate the big pdf file */
        instance.convertFilesToPdf("/tmp/lept/dewtest", null, 135, 1.0f, 0, 0, "Dewarp Test", "/tmp/lept/dewarptest1.pdf");

        if (System.getProperty("os.name").toLowerCase().contains("win")) {
            System.out.println("pdf file made: " + System.getProperty("java.io.tmpdir") + "lept\\model\\dewarptest1.pdf");
        } else {
            System.out.println("pdf file made: /tmp/lept/model/dewarptest1.pdf");
        }

        instance.lept_rmdir("lept/dewmod");
        instance.lept_rmdir("lept/dewtest");
        pixDestroy(pixs);
        pixDestroy(pixn);
        pixDestroy(pixg);
        pixDestroy(pixb);
        pixDestroy(pixd);
        pixDestroy(pixs2);
        pixDestroy(pixn2);
        pixDestroy(pixg2);
        pixDestroy(pixb2);
        pixDestroy(pixd2);
    }

    /**
     * Disposes of Pix resource.
     *
     * @param pix
     */
    void pixDestroy(Pix pix) {
        LeptUtils.disposePix(pix);
    }
}


text:
package ${package};

import org.orienteer.core.OrienteerWebApplication;
import org.orienteer.core.module.AbstractOrienteerModule;
import org.orienteer.core.module.IOrienteerModule;
import org.orienteer.core.util.OSchemaHelper;

import com.orientechnologies.orient.core.db.ODatabaseSession;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.metadata.schema.OType;

/**
 * {@link IOrienteerModule} for '${artifactId}' module
 */
public class Module extends AbstractOrienteerModule{

	protected Module() {
		super("${artifactId}", 1);
	}

	@Override
	public ODocument onInstall(OrienteerWebApplication app, ODatabaseSession db) {
		super.onInstall(app, db);
		OSchemaHelper helper = OSchemaHelper.bind(db);
		//Install data model
		//Return null of default OModule is enough
		return null;
	}

	@Override
	public void onInitialize(OrienteerWebApplication app, ODatabaseSession db) {
		super.onInitialize(app, db);
		app.mountPackage("${package}.web");
	}

	@Override
	public void onDestroy(OrienteerWebApplication app, ODatabaseSession db) {
		super.onDestroy(app, db);
		app.unmountPackage("${package}.web");
	}

}


text:
from cumulusci.tasks.salesforce.BaseSalesforceApiTask import BaseSalesforceApiTask

class SOQLQuery(BaseSalesforceApiTask):
    name = "SOQLQuery"

    task_options = {
        "object": {"required": True, "description": "The object to query"},
        "query": {
            "required": True,
            "description": "A valid bulk SOQL query for the object",
        },
        "result_file": {
            "required": True,
            "description": "The name of the csv file to write the results to",
        },
    }

    def _run_task(self):
        self.logger.info("Creating bulk job for: {object}".format(**self.options))
        job = self.bulk.create_query_job(self.options["object"], contentType="CSV")
        self.logger.info("Job id: {0}".format(job))
        self.logger.info("Submitting query: {query}".format(**self.options))
        batch = self.bulk.query(job, self.options["query"])
        self.logger.info("Batch id: {0}".format(batch))
        self.bulk.wait_for_batch(job, batch)
        self.logger.info("Batch {0} finished".format(batch))
        self.bulk.close_job(job)
        self.logger.info("Job {0} closed".format(job))
        with open(self.options["result_file"], "wb") as result_file:
            first_batch = True
            for result_iterator in self.bulk.get_all_results_for_query_batch(batch):
                if not first_batch:
                    # only include headers for first batch
                    next(result_iterator)
                first_batch = False
                for row in result_iterator:
                    result_file.write(row)
        self.logger.info("Wrote results to: {result_file}".format(**self.options))


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

		<title>Libraries \ Processing 1.0</title>

		<link rel="icon" href="img/processing-1.ico" type="image/x-icon" />
		<link rel="shortcut icon" href="img/processing-1.ico" type="image/x-icon" />

		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta name="Author" content="Casey Reas & Ben Fry" />
		<meta name="Publisher" content="Processing" />
		<meta name="Keywords" content="Processing, Processing, Interactive Media, Electronic Arts, Programming, Java, Ben Fry, Casey Reas" />
		<meta name="Description" content="Processing is an electronic sketchbook for developing
				ideas. It is a context for learning fundamentals of computer programming
				within the context of the electronic arts." />
		<meta name="Copyright" content="All contents copyright Ben Fry, Casey Reas,  MIT Media Laboratory" />

		<link href="../css/style.css" rel="stylesheet" type="text/css" />

				<form name="search" action="http://www.google.com/search" method="get" >

<input type="hidden" name="as_sitesearch" value="processing.org" />
				       <input type="text" name="as_q" value="" size="20" class="text" />
				       <input type="submit" value="Search" />

				</form>

					Language (A-Z) \
					Libraries \
					Tools \
					Environment

The following libraries are included with the Processing software. To add one to a project, select its name from the "Import Library..." option in the Sketch menu. These libraries are open source; the code is distributed with Processing.

Video

Interface to Apple's QuickTime for using a camera, playing movie files, and creating movies.

Network

Sending and receiving data via the Internet through the creation of simple clients and servers.

Serial

Supports sending data between Processing and external hardware via serial communication (RS-232).

PDF Export

Generates PDF files.

OpenGL

Support for exporting OpenGL accelerated sketches. Utilizes the JOGL library.

» Minim

Uses the JavaSound API to provide an easy-to-use audio library. A simple API while
    still providing a reasonable amount of flexibility for more advanced users.

DXF Export

Lines and triangles from P3D or OPENGL rendering modes can be sent directly to a DXF file.

» Arduino

Allows direct control of an Arduino board through Processing.

» Netscape.JavaScript

Methods for interfacing between Javascript and Java Applets exported from Processing.

Candy SVG Import

This library has been moved to the Processing core code as of version 149. To load
    SVG files, check out the reference for PShape(), loadShape(), and shape().

XML Import

This library has been moved to the Processing core as of version 149. To load
    XML data, check out the reference for XMLElement in the extended reference.

Contributed libraries must be downloaded separately and placed within the "libraries" folder of your Processing sketchbook. To find the Processing sketchbook location on your computer, open the Preferences window from the Processing application and look for the "Sketchbook location" item at the top. Visit the Processing wiki for more detailed information.

Contributed libraries are developed, documented, and maintained by members of the Processing community. For feedback and support, please post to the Forum. For development discussions post to the Libraries and Tool Development topic. Instructions for creating your own library are on the Processing Google Code site.

A complete list of libraries can be found online.

Processing was initiated by Ben Fry and Casey Reas. It is developed by a small team of volunteers.

                    © Info \

                    Site hosted by Media Temple!


text:
package com.sismics.home.rest;

import java.io.File;
import java.net.URI;
import java.net.URLDecoder;

import javax.ws.rs.core.Application;
import javax.ws.rs.core.UriBuilder;

import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.servlet.ServletRegistration;
import org.glassfish.grizzly.servlet.WebappContext;
import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
import org.glassfish.jersey.test.external.ExternalTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerException;
import org.glassfish.jersey.test.spi.TestContainerFactory;
import org.junit.After;
import org.junit.Before;

import com.sismics.home.rest.util.ClientUtil;
import com.sismics.util.dbi.DBIF;
import com.sismics.util.filter.RequestContextFilter;
import com.sismics.util.filter.TokenBasedSecurityFilter;

/**
 * Base class of integration tests with Jersey.
 *
 * @author jtremeaux
 */
public abstract class BaseJerseyTest extends JerseyTest {
    /**
     * Test HTTP server.
     */
    HttpServer httpServer;

    /**
     * Utility class for the REST client.
     */
    protected ClientUtil clientUtil;

    @Override
    protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
        return new ExternalTestContainerFactory();
    }

    @Override
    protected Application configure() {
        enable(TestProperties.LOG_TRAFFIC);
        enable(TestProperties.DUMP_ENTITY);
        return new Application();
    }

    @Override
    protected URI getBaseUri() {
        return UriBuilder.fromUri(super.getBaseUri()).path("home").build();
    }

    @Override
    @Before
    public void setUp() throws Exception {
        super.setUp();

        clientUtil = new ClientUtil(target());

        // Force shutdown
        DBIF.reset();

        String httpRoot = URLDecoder.decode(new File(getClass().getResource("/").getFile()).getAbsolutePath(), "utf-8");
        httpServer = HttpServer.createSimpleServer(httpRoot, "localhost", getPort());
        WebappContext context = new WebappContext("GrizzlyContext", "/home");
        context.addFilter("requestContextFilter", RequestContextFilter.class)
                .addMappingForUrlPatterns(null, "/*");
        context.addFilter("tokenBasedSecurityFilter", TokenBasedSecurityFilter.class)
                .addMappingForUrlPatterns(null, "/*");
        ServletRegistration reg = context.addServlet("jerseyServlet", ServletContainer.class);
        reg.setInitParameter("jersey.config.server.provider.packages", "com.sismics.home.rest.resource");
        reg.setLoadOnStartup(1);
        reg.addMapping("/*");
        context.deploy(httpServer);
        httpServer.start();
    }

    @Override
    @After
    public void tearDown() throws Exception {
        super.tearDown();
        if (httpServer != null) {
            httpServer.shutdownNow();
        }
    }
}


text:
package fv_test

import (
	"os"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	log "github.com/sirupsen/logrus"

	api "github.com/projectcalico/api/pkg/apis/projectcalico/v3"
	"github.com/projectcalico/api/pkg/lib/numorstring"
	"github.com/projectcalico/felix/fv/infrastructure"
	"github.com/projectcalico/felix/fv/metrics"
	"github.com/projectcalico/felix/fv/utils"
	"github.com/projectcalico/felix/fv/workload"
	"github.com/projectcalico/libcalico-go/lib/apiconfig"
	client "github.com/projectcalico/libcalico-go/lib/clientv3"
)

func MetricsPortReachable(felix *infrastructure.Felix, bpf bool) bool {
	if bpf {
		felix.Exec("calico-bpf", "conntrack", "clean")
	}

	// Delete existing conntrack state for the metrics port.
	felix.Exec("conntrack", "-L")
	felix.Exec("conntrack", "-L", "-p", "tcp", "--dport", metrics.PortString())
	felix.ExecMayFail("conntrack", "-D", "-p", "tcp", "--orig-port-dst", metrics.PortString())

	// Now try to get a metric.
	m, err := metrics.GetFelixMetric(felix.IP, "felix_active_local_endpoints")
	if err != nil {
		log.WithError(err).Info("Metrics port not reachable")
		return false
	}
	log.WithField("felix_active_local_endpoints", m).Info("Metrics port reachable")
	return true
}

// Here we test reachability to a port number running on a Calico host itself, specifically Felix's
// metrics port 9091, and how that is affected by policy, host endpoint (eth0 or *) and workload endpoint
// configuration.
//
// - When there is no policy or endpoint configuration, the port should be reachable.
//
// - When there is a local workload endpoint, the port should be reachable.  (Existence of workload
//   endpoints should make no difference to reachability to ports on the host itself.)
//
// - When a host endpoint is configured for the host's interface (eth0) or for
//   all-interfaces, but not yet any policy, the port should be unreachable.
//
//   - When pre-DNAT policy is then configured, to allow ingress to some other
//     port, it should still be unreachable again.
//
//   - When pre-DNAT policy is then configured, to allow ingress to the metrics port, it should be
//     reachable again.
//
var _ = infrastructure.DatastoreDescribe("_BPF-SAFE_ host-port tests", []apiconfig.DatastoreType{apiconfig.EtcdV3, apiconfig.Kubernetes}, func(getInfra infrastructure.InfraFactory) {
	var (
		bpfEnabled           = os.Getenv("FELIX_FV_ENABLE_BPF") == "true"
		infra                infrastructure.DatastoreInfra
		felix                *infrastructure.Felix
		client               client.Interface
		metricsPortReachable func() bool
	)

	BeforeEach(func() {
		infra = getInfra()

		options := infrastructure.DefaultTopologyOptions()
		options.NeedNodeIP = bpfEnabled
		felix, client = infrastructure.StartSingleNodeTopology(options, infra)

		metricsPortReachable = func() bool {
			return MetricsPortReachable(felix, bpfEnabled)
		}

		if bpfEnabled {
			Eventually(felix.NumTCBPFProgsEth0, "5s", "200ms").Should(Equal(2))
		}
	})

	AfterEach(func() {
		if CurrentGinkgoTestDescription().Failed {
			infra.DumpErrorData()
			felix.Exec("iptables-save", "-c")
			felix.Exec("ip", "r")
			felix.Exec("ip", "a")
		}
		felix.Stop()
		infra.Stop()
	})

	It("with no endpoints or policy, port should be reachable", func() {
		Eventually(metricsPortReachable, "10s", "1s").Should(BeTrue())
	})

	It("with a local workload, port should be reachable", func() {
		w := workload.Run(felix, "w", "default", "10.65.0.2", "8055", "tcp")
		w.ConfigureInInfra(infra)
		Eventually(metricsPortReachable, "10s", "1s").Should(BeTrue(), "Not reachable with workload running")
		w.Stop()
		Eventually(metricsPortReachable, "10s", "1s").Should(BeTrue(), "With workload stopped, not reachable")
	})

	describeMetricsPortTests := func() {
		It("port should not be reachable", func() {
			Eventually(metricsPortReachable, "10s", "1s").Should(BeFalse())
		})

		Context("with pre-DNAT policy defined", func() {
			protocol := numorstring.ProtocolFromString("tcp")

			BeforeEach(func() {
				policy := api.NewGlobalNetworkPolicy()
				policy.Name = "prednat-deny-port-123"
				policy.Spec.PreDNAT = true
				policy.Spec.ApplyOnForward = true
				allowPortRule := api.Rule{
					Action:   api.Allow,
					Protocol: &protocol,
					Destination: api.EntityRule{
						Ports: []numorstring.Port{numorstring.SinglePort(uint16(1234))},
					},
				}
				policy.Spec.Ingress = []api.Rule{allowPortRule}
				policy.Spec.Selector = "host-endpoint=='true'"
				_, err := client.GlobalNetworkPolicies().Create(utils.Ctx, policy, utils.NoOptions)
				Expect(err).NotTo(HaveOccurred())
			})

			It("should not be able to reach the metrics port with an allow policy on another port", func() {
				// Ensure the HostEndpoint has taken effect and is blocking traffic
				Eventually(metricsPortReachable, "10s", "1s").Should(BeFalse())
			})

			It("should be able to reach the metrics port once a policy allows that port", func() {
				policy := api.NewGlobalNetworkPolicy()
				policy.Name = "prednat-allow-metrics-port"
				policy.Spec.PreDNAT = true
				policy.Spec.ApplyOnForward = true
				allowMetricsPortRule := api.Rule{
					Action:   api.Allow,
					Protocol: &protocol,
					Destination: api.EntityRule{
						Ports: []numorstring.Port{numorstring.SinglePort(uint16(metrics.Port))},
					},
				}
				policy.Spec.Ingress = []api.Rule{allowMetricsPortRule}
				policy.Spec.Selector = "host-endpoint=='true'"
				_, err := client.GlobalNetworkPolicies().Create(utils.Ctx, policy, utils.NoOptions)
				Expect(err).NotTo(HaveOccurred())

				Eventually(metricsPortReachable, "10s", "1s").Should(BeTrue())
			})
		})
	}

	Context("with named host endpoint defined", func() {
		BeforeEach(func() {
			hostEp := api.NewHostEndpoint()
			hostEp.Name = "host-endpoint-1"
			hostEp.Labels = map[string]string{"host-endpoint": "true"}
			hostEp.Spec.Node = felix.Hostname
			hostEp.Spec.InterfaceName = "eth0"
			_, err := client.HostEndpoints().Create(utils.Ctx, hostEp, utils.NoOptions)
			Expect(err).NotTo(HaveOccurred())
		})

		describeMetricsPortTests()
	})

	Context("with all-interfaces host endpoint defined", func() {
		BeforeEach(func() {
			hostEp := api.NewHostEndpoint()
			hostEp.Name = "all-interfaces-hostendpoint"
			hostEp.Labels = map[string]string{"host-endpoint": "true"}
			hostEp.Spec.Node = felix.Hostname
			hostEp.Spec.InterfaceName = "*"
			_, err := client.HostEndpoints().Create(utils.Ctx, hostEp, utils.NoOptions)
			Expect(err).NotTo(HaveOccurred())
		})

		describeMetricsPortTests()
	})
})


text:
namespace viz {
class FrameSinkId;
}  // namespace viz

class BackToTabImageButton;
class BackToTabLabelButton;
class CloseImageButton;
class HangUpButton;
class PlaybackImageButton;
class ResizeHandleButton;
class SkipAdLabelButton;
class ToggleMicrophoneButton;
class ToggleCameraButton;
class TrackImageButton;

// The Chrome desktop implementation of OverlayWindow. This will only be
// implemented in views, which will support all desktop platforms.
class VideoOverlayWindowViews : public OverlayWindowViews,
                                public content::VideoOverlayWindow {
 public:
  static std::unique_ptr<VideoOverlayWindowViews> Create(
      content::VideoPictureInPictureWindowController* controller);

  VideoOverlayWindowViews(const VideoOverlayWindowViews&) = delete;
  VideoOverlayWindowViews& operator=(const VideoOverlayWindowViews&) = delete;

  ~VideoOverlayWindowViews() override;

  // OverlayWindow:
  bool IsActive() override;
  void Close() override;
  void ShowInactive() override;
  void Hide() override;
  bool IsVisible() override;
  bool IsAlwaysOnTop() override;
  gfx::Rect GetBounds() override;
  void UpdateNaturalSize(const gfx::Size& natural_size) override;

  // VideoOverlayWindow:
  void SetPlaybackState(PlaybackState playback_state) override;
  void SetPlayPauseButtonVisibility(bool is_visible) override;
  void SetSkipAdButtonVisibility(bool is_visible) override;
  void SetNextTrackButtonVisibility(bool is_visible) override;
  void SetPreviousTrackButtonVisibility(bool is_visible) override;
  void SetMicrophoneMuted(bool muted) override;
  void SetCameraState(bool turned_on) override;
  void SetToggleMicrophoneButtonVisibility(bool is_visible) override;
  void SetToggleCameraButtonVisibility(bool is_visible) override;
  void SetHangUpButtonVisibility(bool is_visible) override;
  void SetSurfaceId(const viz::SurfaceId& surface_id) override;
  cc::Layer* GetLayerForTesting() override;

  // OverlayWindowViews
  bool ControlsHitTestContainsPoint(const gfx::Point& point) override;
#if BUILDFLAG(IS_CHROMEOS_ASH)
  int GetResizeHTComponent() const override;
  gfx::Rect GetResizeHandleControlsBounds() override;
  void UpdateResizeHandleBounds(WindowQuadrant quadrant) override;
#endif
  void OnUpdateControlsBounds() override;
  void OnKeyEvent(ui::KeyEvent* event) override;
  void OnGestureEvent(ui::GestureEvent* event) override;
  void SetUpViews() override;
  void OnRootViewReady() override;
  void UpdateLayerBoundsWithLetterboxing(gfx::Size window_size) override;
  content::PictureInPictureWindowController* GetController() const override;
  views::View* GetWindowBackgroundView() const override;
  views::View* GetControlsContainerView() const override;

  // views::Widget
  bool IsActive() const override;
  bool IsVisible() const override;
  void OnNativeWidgetMove() override;
  void OnNativeWidgetDestroying() override;
  void OnNativeWidgetDestroyed() override;
  void OnNativeWidgetAddedToCompositor() override;
  void OnNativeWidgetRemovingFromCompositor() override;

  // Gets the bounds of the controls.
  gfx::Rect GetBackToTabControlsBounds();
  gfx::Rect GetSkipAdControlsBounds();
  gfx::Rect GetCloseControlsBounds();
  gfx::Rect GetPlayPauseControlsBounds();
  gfx::Rect GetNextTrackControlsBounds();
  gfx::Rect GetPreviousTrackControlsBounds();
  gfx::Rect GetToggleMicrophoneButtonBounds();
  gfx::Rect GetToggleCameraButtonBounds();
  gfx::Rect GetHangUpButtonBounds();

  PlaybackImageButton* play_pause_controls_view_for_testing() const;
  TrackImageButton* next_track_controls_view_for_testing() const;
  TrackImageButton* previous_track_controls_view_for_testing() const;
  SkipAdLabelButton* skip_ad_controls_view_for_testing() const;
  ToggleMicrophoneButton* toggle_microphone_button_for_testing() const;
  ToggleCameraButton* toggle_camera_button_for_testing() const;
  HangUpButton* hang_up_button_for_testing() const;
  BackToTabLabelButton* back_to_tab_label_button_for_testing() const;
  CloseImageButton* close_button_for_testing() const;
  gfx::Point close_image_position_for_testing() const;
  gfx::Point resize_handle_position_for_testing() const;
  PlaybackState playback_state_for_testing() const;
  ui::Layer* video_layer_for_testing() const;

 protected:
  explicit VideoOverlayWindowViews(
      content::VideoPictureInPictureWindowController* controller);

 private:
  // Calculate and set the bounds of the controls.
  gfx::Rect CalculateControlsBounds(int x, const gfx::Size& size);

  // Toggles the play/pause control through the |controller_| and updates the
  // |play_pause_controls_view_| toggled state to reflect the current playing
  // state.
  void TogglePlayPause();

  // Returns the current frame sink id for the surface displayed in the
  // |video_view_|. If |video_view_| is not currently displaying a surface then
  // returns nullptr.
  const viz::FrameSinkId* GetCurrentFrameSinkId() const;

  // Unregisters the current frame sink id for the surface displayed in the
  // |video_view_| from its parent frame sink if the frame sink hierarchy has
  // been registered before.
  void MaybeUnregisterFrameSinkHierarchy();

  // Not owned; |controller_| owns |this|.
  raw_ptr<content::VideoPictureInPictureWindowController> controller_;

  // Whether or not the play/pause button will be shown.
  bool show_play_pause_button_ = false;

  // Temporary storage for child Views. Used during the time between
  // construction and initialization, when the views::View pointer members must
  // already be initialized, but there is no root view to add them to yet.
  std::vector<std::unique_ptr<views::View>> view_holder_;

  // Views to be shown. The views are first temporarily owned by view_holder_,
  // then passed to this widget's ContentsView which takes ownership.
  raw_ptr<views::View> window_background_view_ = nullptr;
  raw_ptr<views::View> video_view_ = nullptr;
  raw_ptr<views::View> controls_scrim_view_ = nullptr;
  raw_ptr<views::View> controls_container_view_ = nullptr;
  raw_ptr<CloseImageButton> close_controls_view_ = nullptr;
  raw_ptr<BackToTabImageButton> back_to_tab_image_button_ = nullptr;
  raw_ptr<BackToTabLabelButton> back_to_tab_label_button_ = nullptr;
  raw_ptr<TrackImageButton> previous_track_controls_view_ = nullptr;
  raw_ptr<PlaybackImageButton> play_pause_controls_view_ = nullptr;
  raw_ptr<TrackImageButton> next_track_controls_view_ = nullptr;
  raw_ptr<SkipAdLabelButton> skip_ad_controls_view_ = nullptr;
  raw_ptr<ResizeHandleButton> resize_handle_view_ = nullptr;
  raw_ptr<ToggleMicrophoneButton> toggle_microphone_button_ = nullptr;
  raw_ptr<ToggleCameraButton> toggle_camera_button_ = nullptr;
  raw_ptr<HangUpButton> hang_up_button_ = nullptr;

#if BUILDFLAG(IS_CHROMEOS_ASH)
  // Generates a nine patch layer painted with a highlight border for ChromeOS
  // ASH only, not including LaCrOS. Highlight border for chrome pip window in
  // LaCrOS will be added when `ash::NonClientFrameViewAsh` is created.
  std::unique_ptr<HighlightBorderOverlay> highlight_border_overlay_;
#endif

  // Current playback state on the video in Picture-in-Picture window. It is
  // used to toggle play/pause/replay button.
  PlaybackState playback_state_for_testing_ = kEndOfVideo;

  // Whether or not the skip ad button will be shown. This is the
  // case when Media Session "skipad" action is handled by the website.
  bool show_skip_ad_button_ = false;

  // Whether or not the next track button will be shown. This is the
  // case when Media Session "nexttrack" action is handled by the website.
  bool show_next_track_button_ = false;

  // Whether or not the previous track button will be shown. This is the
  // case when Media Session "previoustrack" action is handled by the website.
  bool show_previous_track_button_ = false;

  // Whether or not the toggle microphone button will be shown. This is the case
  // when Media Session "togglemicrophone" action is handled by the website.
  bool show_toggle_microphone_button_ = false;

  // Whether or not the toggle camera button will be shown. This is the case
  // when Media Session "togglecamera" action is handled by the website.
  bool show_toggle_camera_button_ = false;

  // Whether or not the hang up button will be shown. This is the case when
  // Media Session "hangup" action is handled by the website.
  bool show_hang_up_button_ = false;

  // Whether or not the current frame sink for the surface displayed in the
  // |video_view_| is registered as the child of the overlay window frame sink.
  bool has_registered_frame_sink_hierarchy_ = false;
};

#endif  // CHROME_BROWSER_UI_VIEWS_OVERLAY_VIDEO_OVERLAY_WINDOW_VIEWS_H_