code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateList extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('modelList', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('modelList');
}
}
| Java |
---
type: docs
order: 10
title: "Transloadit"
module: "@uppy/transloadit"
permalink: docs/transloadit/
category: "File Processing"
tagline: "manipulate and transcode uploaded files using the <a href='https://transloadit.com'>transloadit.com</a> service"
---
The `@uppy/transloadit` plugin can be used to upload files to [Transloadit](https://transloadit.com/) for all kinds of processing, such as transcoding video, resizing images, zipping/unzipping, [and much more](https://transloadit.com/services/).
> If you’re okay to trade some flexibility for ergonomics, consider using
> the [Robodog](/docs/robodog/) Plugin instead, which is a higher-level abstraction for
> encoding files with Uppy and Transloadit.
<a class="TryButton" href="/examples/transloadit/">Try it live</a>
```js
import Transloadit from '@uppy/transloadit'
uppy.use(Transloadit, {
service: 'https://api2.transloadit.com',
params: null,
waitForEncoding: false,
waitForMetadata: false,
importFromUploadURLs: false,
alwaysRunAssembly: false,
signature: null,
fields: {},
limit: 0,
})
```
As of Uppy version 0.24, the Transloadit plugin includes the [Tus](/docs/tus) plugin to handle the uploading, so you no longer have to add it manually.
## Installation
This plugin is published as the `@uppy/transloadit` package.
Install from NPM:
```shell
npm install @uppy/transloadit
```
In the [CDN package](/docs/#With-a-script-tag), the plugin class is available on the `Uppy` global object:
```js
const { Transloadit } = Uppy
```
## Hosted Companion Service
You can use this plugin together with Transloadit’s hosted Companion service to let your users import files from third party sources across the web.
To do so each provider plugin must be configured with Transloadit’s Companion URLs:
```js
uppy.use(Dropbox, {
companionUrl: Transloadit.COMPANION,
companionAllowedHosts: Transloadit.COMPANION_PATTERN,
})
```
This will already work. Transloadit’s OAuth applications are used to authenticate your users by default. Your users will be asked to provide Transloadit access to their files. Since your users are probably not aware of Transloadit, this may be confusing or decrease trust. You may also hit rate limits, because the OAuth application is shared between everyone using Transloadit.
To solve that, you can use your own OAuth keys with Transloadit’s hosted Companion servers by using Transloadit Template Credentials. [Create a Template Credential][template-credentials] on the Transloadit site. Select “Companion OAuth” for the service, and enter the key and secret for the provider you want to use. Then you can pass the name of the new credentials to that provider:
```js
uppy.use(Dropbox, {
companionUrl: Transloadit.COMPANION,
companionAllowedHosts: Transloadit.COMPANION_PATTERN,
companionKeysParams: {
key: 'YOUR_TRANSLOADIT_API_KEY',
credentialsName: 'my_companion_dropbox_creds',
},
})
```
## Properties
### `Transloadit.COMPANION`
The main endpoint for Transloadit’s hosted companions. You can use this constant in remote provider options, like so:
```js
import Dropbox from '@uppy/dropbox'
import Transloadit from '@uppy/transloadit'
uppy.use(Dropbox, {
companionUrl: Transloadit.COMPANION,
companionAllowedHosts: Transloadit.COMPANION_PATTERN,
})
```
When using `Transloadit.COMPANION`, you should also configure [`companionAllowedHosts: Transloadit.COMPANION_PATTERN`](#Transloadit-COMPANION-PATTERN).
The value of this constant is `https://api2.transloadit.com/companion`. If you are using a custom [`service`](#service) option, you should also set a custom host option in your provider plugins, by taking a Transloadit API url and appending `/companion`:
```js
uppy.use(Dropbox, {
companionUrl: 'https://api2-us-east-1.transloadit.com/companion',
})
```
### `Transloadit.COMPANION_PATTERN`
A RegExp pattern matching Transloadit’s hosted companion endpoints. The pattern is used in remote provider `companionAllowedHosts` options, to make sure that third party authentication messages cannot be faked by an attacker’s page, but can only originate from Transloadit’s servers.
Use it whenever you use `companionUrl: Transloadit.COMPANION`, like so:
```js
import Dropbox from '@uppy/dropbox'
import Transloadit from '@uppy/transloadit'
uppy.use(Dropbox, {
companionUrl: Transloadit.COMPANION,
companionAllowedHosts: Transloadit.COMPANION_PATTERN,
})
```
The value of this constant covers _all_ Transloadit’s Companion servers, so it does not need to be changed if you are using a custom [`service`](#service) option. But, if you are not using the Transloadit Companion servers at `*.transloadit.com`, make sure to set the `companionAllowedHosts` option to something that matches what you do use.
## Options
The `@uppy/transloadit` plugin has the following configurable options:
### `id: 'Transloadit'`
A unique identifier for this plugin. It defaults to `'Transloadit'`.
### `service`
The Transloadit API URL to use. It defaults to `https://api2.transloadit.com`, which will try to route traffic efficiently based on the location of your users. You can set this to something like `https://api2-us-east-1.transloadit.com` if you want to use a particular region.
### `params`
The Assembly parameters to use for the upload. See the Transloadit documentation on [Assembly Instructions](https://transloadit.com/docs/#14-assembly-instructions) for further information. `params` should be a plain JavaScript object, or a JSON string if you are using the [`signature`](#signature) option.
The `auth.key` Assembly parameter is required. You can also use the `steps` or `template_id` options here as described in the Transloadit documentation.
```js
uppy.use(Transloadit, {
params: {
auth: { key: 'YOUR_TRANSLOADIT_KEY' },
steps: {
encode: {
robot: '/video/encode',
use: {
steps: [':original'],
fields: ['file_input_field2'],
},
preset: 'iphone',
},
},
},
})
```
<a id="waitForEncoding"></a>
### `waitForEncoding: false`
By default, the Transloadit plugin uploads files to Assemblies and then marks the files as complete in Uppy. The Assemblies will complete (or error) in the background but Uppy won’t know or care about it.
When `waitForEncoding` is set to true, the Transloadit plugin waits for Assemblies to complete before the files are marked as completed. This means users have to wait for a potentially long time, depending on how complicated your Assembly instructions are. But, you can receive transcoding results on the client side, and have a fully client-side experience this way.
When this is enabled, you can listen for the [`transloadit:result`](#transloadit-result) and [`transloadit:complete`](#transloadit-complete) events.
<a id="waitForMetadata"></a>
### `waitForMetadata: false`
By default, the Transloadit plugin uploads files to Assemblies and then marks the files as complete in Uppy. The Assemblies will complete (or error) in the background but Uppy won’t know or care about it.
When `waitForMetadata` is set to true, the Transloadit plugin waits for Transloadit’s backend to extract metadata from all the uploaded files. This is mostly handy if you want to have a quick user experience (so your users don’t necessarily need to wait for all the encoding to complete), but you do want to let users know about some types of errors that can be caught early on, like file format issues.
When this is enabled, you can listen for the [`transloadit:upload`](#transloadit-upload) event.
### `importFromUploadURLs`
Instead of uploading to Transloadit’s servers directly, allow another plugin to upload files, and then import those files into the Transloadit Assembly. This is set to `false` by default.
When enabling this option, Transloadit will _not_ configure the Tus plugin to upload to Transloadit. Instead, a separate upload plugin must be used. Once the upload completes, the Transloadit plugin adds the uploaded file to the Assembly.
For example, to upload files to an S3 bucket and then transcode them:
```js
uppy.use(AwsS3, {
getUploadParameters (file) {
return { /* upload parameters */ }
},
})
uppy.use(Transloadit, {
importFromUploadURLs: true,
params: {
auth: { key: 'YOUR_API_KEY' },
template_id: 'YOUR_TEMPLATE_ID',
},
})
```
For this to work, the upload plugin must assign a publically accessible `uploadURL` property to the uploaded file object. The Tus and S3 plugins both do this automatically. For the XHRUpload plugin, you may have to specify a custom `getResponseData` function.
### `alwaysRunAssembly`
When set to true, always create and run an Assembly when `uppy.upload()` is called, even if no files were selected. This allows running Assemblies that do not receive files, but instead use a robot like [`/s3/import`](https://transloadit.com/docs/transcoding/#s3-import) to download the files from elsewhere, for example, for a bulk transcoding job.
### `signature`
An optional signature for the Assembly parameters. See the Transloadit documentation on [Signature Authentication](https://transloadit.com/docs/#26-signature-authentication) for further information.
If a `signature` is provided, `params` should be a JSON string instead of a JavaScript object, as otherwise the generated JSON in the browser may be different from the JSON string that was used to generate the signature.
### `fields`
An object of form fields to send along to the Assembly. Keys are field names, and values are field values. See also the Transloadit documentation on [Form Fields In Instructions](https://transloadit.com/docs/#23-form-fields-in-instructions).
```js
uppy.use(Transloadit, {
// ...
fields: {
message: 'This is a form field',
},
})
```
You can also pass an array of field names to send global or file metadata along to the Assembly. Global metadata is set using the [`meta` option](/docs/uppy/#meta) in the Uppy constructor, or using the [`setMeta` method](/docs/uppy/#uppy-setMeta-data). File metadata is set using the [`setFileMeta`](/docs/uppy/#uppy-setFileMeta-fileID-data) method. The [Form](/docs/form) plugin also sets global metadata based on the values of `<input />`s in the form, providing a handy way to use values from HTML form fields:
```js
uppy.use(Form, { target: 'form#upload-form', getMetaFromForm: true })
uppy.use(Transloadit, {
fields: ['field_name', 'other_field_name'],
params: { /* ... */ },
})
```
Form fields can also be computed dynamically using custom logic, by using the [`getAssemblyOptions(file)`](/docs/transloadit/#getAssemblyOptions-file) option.
### `getAssemblyOptions(file)`
While `params`, `signature`, and `fields` must be determined ahead of time, the `getAssemblyOptions` allows using dynamically generated values for these options. This way, it’s possible to use different Assembly parameters for different files, or to use some user input in an Assembly.
A custom `getAssemblyOptions()` option should return an object or a Promise for an object with properties `{ params, signature, fields }`. For example, to add a field with some user-provided data from the `MetaData` plugin:
```js
uppy.use(MetaData, {
fields: [
{ id: 'caption' },
],
})
uppy.use(Transloadit, {
getAssemblyOptions (file) {
return {
params: {
auth: { key: 'TRANSLOADIT_AUTH_KEY_HERE' },
template_id: 'xyz',
},
fields: {
caption: file.meta.caption,
},
}
},
})
```
Now, the `${fields.caption}` variable will be available in the Assembly template.
Combine the `getAssemblyOptions()` option with the [Form](/docs/form) plugin to pass user input from a `<form>` to a Transloadit Assembly:
```js
// This will add form field values to each file's `.meta` object:
uppy.use(Form, { getMetaFromForm: true })
uppy.use(Transloadit, {
getAssemblyOptions (file) {
return {
params: { /* ... */ },
// Pass through the fields you need:
fields: {
message: file.meta.message,
},
}
},
})
```
`getAssemblyOptions()` may also return a Promise, so it could retrieve signed Assembly parameters from a server. For example, assuming an endpoint `/transloadit-params` that responds with a JSON object with `{ params, signature }` properties:
```js
uppy.use(Transloadit, {
getAssemblyOptions (file) {
return fetch('/transloadit-params').then((response) => {
return response.json()
})
},
})
```
### `limit: 0`
Limit the amount of uploads going on at the same time. Setting this to `0` means no limit on concurrent uploads. This option is passed through to the [`@uppy/tus`](/docs/tus) plugin that Transloadit plugin uses internally.
### `locale: {}`
<!-- eslint-disable no-restricted-globals, no-multiple-empty-lines -->
```js
module.exports = {
strings: {
// Shown while Assemblies are being created for an upload.
creatingAssembly: 'Preparing upload...',
// Shown if an Assembly could not be created.
creatingAssemblyFailed: 'Transloadit: Could not create Assembly',
// Shown after uploads have succeeded, but when the Assembly is still executing.
// This only shows if `waitForMetadata` or `waitForEncoding` was enabled.
encoding: 'Encoding...',
},
}
```
## Errors
If an error occurs when an Assembly has already started, you can find the Assembly Status on the error object’s `assembly` property.
```js
uppy.on('error', (error) => {
if (error.assembly) {
console.log(`Assembly ID ${error.assembly.assembly_id} failed!`)
console.log(error.assembly)
}
})
```
## Events
### `transloadit:assembly-created`
Fired when an Assembly is created.
**Parameters**
* `assembly` - The initial [Assembly Status][assembly-status].
* `fileIDs` - The IDs of the files that will be uploaded to this Assembly.
```js
uppy.on('transloadit:assembly-created', (assembly, fileIDs) => {
console.group('Created', assembly.assembly_id, 'for files:')
for (const id of fileIDs) {
console.log(uppy.getFile(id).name)
}
console.groupEnd()
})
```
### `transloadit:upload`
Fired when Transloadit has received an upload.
**Parameters**
* `file` - The Transloadit file object that was uploaded.
* `assembly` - The [Assembly Status][assembly-status] of the Assembly to which the file was uploaded.
### `transloadit:assembly-executing`
Fired when Transloadit has received all uploads, and is executing the Assembly.
**Parameters**
* `assembly` - The [Assembly Status](https://transloadit.com/docs/api/#assembly-status-response) of the Assembly that is executing.
### `transloadit:result`
Fired when a result came in from an Assembly.
**Parameters**
* `stepName` - The name of the Assembly step that generated this result.
* `result` - The result object from Transloadit.
This result object has one more property, namely `localId`.
This is the ID of the file in Uppy’s local state, and can be used with `uppy.getFile(id)`.
* `assembly` - The [Assembly Status][assembly-status] of the Assembly that generated this result.
```js
uppy.on('transloadit:result', (stepName, result) => {
const file = uppy.getFile(result.localId)
document.body.appendChild(html`
<div>
<h2>From ${file.name}</h2>
<a href=${result.ssl_url}> View </a>
</div>
`)
})
```
### `transloadit:complete`
Fired when an Assembly completed.
**Parameters**
* `assembly` - The final [Assembly Status][assembly-status] of the completed Assembly.
```js
uppy.on('transloadit:complete', (assembly) => {
// Could do something fun with this!
console.log(assembly.results)
})
```
[assembly-status]: https://transloadit.com/docs/api/#assembly-status-response
[template-credentials]: https://transloadit.com/docs/#how-to-create-template-credentials
| Java |
module Tire
module Model
module Persistence
# Provides infrastructure for storing records in _Elasticsearch_.
#
module Storage
def self.included(base)
base.class_eval do
extend ClassMethods
include InstanceMethods
end
end
module ClassMethods
def create(args={})
document = new(args)
return false unless document.valid?
if result = document.save
document
else
result
end
end
end
module InstanceMethods
def update_attribute(name, value)
__update_attributes name => value
save
end
def update_attributes(attributes={})
__update_attributes attributes
save
end
def update_index
run_callbacks :update_elasticsearch_index do
if destroyed?
response = index.remove self
else
if response = index.store( self, {:percolate => percolator} )
self.id ||= response['_id']
self._index = response['_index']
self._type = response['_type']
self._version = response['_version']
self.matches = response['matches']
end
end
response
end
end
def save
return false unless valid?
run_callbacks :save do
response = update_index
!! response['ok']
end
end
def destroy
run_callbacks :destroy do
@destroyed = true
response = update_index
! response.nil?
end
end
def destroyed? ; !!@destroyed; end
def persisted? ; !!id && !!_version; end
def new_record? ; !persisted?; end
end
end
end
end
end
| Java |
require 'googleanalytics/mobile'
| Java |
class ItemsController < ApplicationController
def create
item = Item.new(item_params)
item.user_id = @user.id
if item.save
render json: item, status: 201
else
render json: item.errors, status: 422
end
end
def destroy
item = find_item
item.destroy
head 204
end
def index
render json: @user.items.as_json, status: 200
end
def show
item = find_item
render json: item.as_json, status: 200
end
def update
item = find_item
if item.update(item_params)
render json: item.as_json, status: 200
end
end
def find_item
Item.find(params[:id])
end
private
def item_params
params.require(:item).permit(:type, :brand, :size, :color, :description)
end
end
| Java |
# Build bootstrap Go compiler
| Java |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QHTTPMULTIPART_H
#define QHTTPMULTIPART_H
#include <QtCore/QSharedDataPointer>
#include <QtCore/QByteArray>
#include <QtCore/QIODevice>
#include <QtNetwork/QNetworkRequest>
QT_BEGIN_NAMESPACE
class QHttpPartPrivate;
class QHttpMultiPart;
class Q_NETWORK_EXPORT QHttpPart
{
public:
QHttpPart();
QHttpPart(const QHttpPart &other);
~QHttpPart();
#ifdef Q_COMPILER_RVALUE_REFS
QHttpPart &operator=(QHttpPart &&other) Q_DECL_NOTHROW { swap(other); return *this; }
#endif
QHttpPart &operator=(const QHttpPart &other);
void swap(QHttpPart &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QHttpPart &other) const;
inline bool operator!=(const QHttpPart &other) const
{ return !operator==(other); }
void setHeader(QNetworkRequest::KnownHeaders header, const QVariant &value);
void setRawHeader(const QByteArray &headerName, const QByteArray &headerValue);
void setBody(const QByteArray &body);
void setBodyDevice(QIODevice *device);
private:
QSharedDataPointer<QHttpPartPrivate> d;
friend class QHttpMultiPartIODevice;
};
Q_DECLARE_SHARED(QHttpPart)
class QHttpMultiPartPrivate;
class Q_NETWORK_EXPORT QHttpMultiPart : public QObject
{
Q_OBJECT
public:
enum ContentType {
MixedType,
RelatedType,
FormDataType,
AlternativeType
};
explicit QHttpMultiPart(QObject *parent = Q_NULLPTR);
explicit QHttpMultiPart(ContentType contentType, QObject *parent = Q_NULLPTR);
~QHttpMultiPart();
void append(const QHttpPart &httpPart);
void setContentType(ContentType contentType);
QByteArray boundary() const;
void setBoundary(const QByteArray &boundary);
private:
Q_DECLARE_PRIVATE(QHttpMultiPart)
Q_DISABLE_COPY(QHttpMultiPart)
friend class QNetworkAccessManager;
friend class QNetworkAccessManagerPrivate;
};
QT_END_NAMESPACE
#endif // QHTTPMULTIPART_H
| Java |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Killer : MonoBehaviour {
public Transform RobotPlayer;
public GameObject Robot;
public Text GameOVER;
// Use this for initialization
void Start() {
RobotPlayer = GetComponent<Transform>();
}
void FixedUpdate()
{
if(RobotPlayer.gameObject.transform.position.y < -2)
{
GameOVER.gameObject.SetActive(true);
}
}
}
| Java |
---
title: Comment Section
---
Sample comment section mblazonry can input to components. Elements can be added and removed easily. Base organism contains an icon+header section with text input and submit button. | Java |
module S3Bear
module ViewHelpers
# def s3bear_bucket
# S3Bear.config.bucket + '.s3.amazonaws.com/upload.html'
# end
end
end
ActionView::Base.send(:include, S3Bear::ViewHelpers) | Java |
module Linter
class Base
def self.can_lint?(filename)
self::FILE_REGEXP === filename
end
def initialize(hound_config:, build:, repository_owner_name:)
@hound_config = hound_config
@build = build
@repository_owner_name = repository_owner_name
end
def file_review(commit_file)
attributes = build_review_job_attributes(commit_file)
file_review = FileReview.create!(
build: build,
filename: commit_file.filename,
)
enqueue_job(attributes)
file_review
end
def enabled?
config.linter_names.any? do |linter_name|
hound_config.enabled_for?(linter_name)
end
end
def file_included?(*)
true
end
def name
self.class.name.demodulize.underscore
end
private
attr_reader :hound_config, :build, :repository_owner_name
def build_review_job_attributes(commit_file)
{
commit_sha: build.commit_sha,
config: config.content,
content: commit_file.content,
filename: commit_file.filename,
patch: commit_file.patch,
pull_request_number: build.pull_request_number,
}
end
def enqueue_job(attributes)
Resque.enqueue(job_class, attributes)
end
def job_class
"#{name.classify}ReviewJob".constantize
end
def config
@config ||= ConfigBuilder.for(hound_config, name)
end
end
end
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Lighthouse: lapack/dsprfs.f File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="tabs.css" rel="stylesheet" type="text/css" />
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<!--<div id="titlearea">
</div>-->
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_42b7da8b2ebcfce3aea4b69198a0a9ad.html">lapack</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#func-members">Functions/Subroutines</a> </div>
<div class="headertitle">
<div class="title">dsprfs.f File Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions/Subroutines</h2></td></tr>
<tr class="memitem:a494f27878d5670ad2570185062b96fc7"><td class="memItemLeft" align="right" valign="top">subroutine </td><td class="memItemRight" valign="bottom"><a class="el" href="dsprfs_8f.html#a494f27878d5670ad2570185062b96fc7">dsprfs</a> (UPLO, N, NRHS, AP, AFP, IPIV, B, LDB, X, LDX, FERR, BERR, WORK, IWORK, INFO)</td></tr>
<tr class="memdesc:a494f27878d5670ad2570185062b96fc7"><td class="mdescLeft"> </td><td class="mdescRight"><b>DSPRFS</b> <a href="#a494f27878d5670ad2570185062b96fc7">More...</a><br /></td></tr>
<tr class="separator:a494f27878d5670ad2570185062b96fc7"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Function/Subroutine Documentation</h2>
<a class="anchor" id="a494f27878d5670ad2570185062b96fc7"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">subroutine dsprfs </td>
<td>(</td>
<td class="paramtype">character </td>
<td class="paramname"><em>UPLO</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>N</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>NRHS</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension( * ) </td>
<td class="paramname"><em>AP</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension( * ) </td>
<td class="paramname"><em>AFP</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer, dimension( * ) </td>
<td class="paramname"><em>IPIV</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension( ldb, * ) </td>
<td class="paramname"><em>B</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>LDB</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension( ldx, * ) </td>
<td class="paramname"><em>X</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>LDX</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension( * ) </td>
<td class="paramname"><em>FERR</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension( * ) </td>
<td class="paramname"><em>BERR</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension( * ) </td>
<td class="paramname"><em>WORK</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer, dimension( * ) </td>
<td class="paramname"><em>IWORK</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>INFO</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p><b>DSPRFS</b> </p>
<p>
Download DSPRFS + dependencies
<a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dsprfs.f">
[TGZ]</a>
<a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dsprfs.f">
[ZIP]</a>
<a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dsprfs.f">
[TXT]</a>
</p><dl class="section user"><dt>Purpose: </dt><dd><pre class="fragment"> DSPRFS improves the computed solution to a system of linear
equations when the coefficient matrix is symmetric indefinite
and packed, and provides error bounds and backward error estimates
for the solution.</pre> </dd></dl>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramdir">[in]</td><td class="paramname">UPLO</td><td><pre class="fragment"> UPLO is CHARACTER*1
= 'U': Upper triangle of A is stored;
= 'L': Lower triangle of A is stored.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">N</td><td><pre class="fragment"> N is INTEGER
The order of the matrix A. N >= 0.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">NRHS</td><td><pre class="fragment"> NRHS is INTEGER
The number of right hand sides, i.e., the number of columns
of the matrices B and X. NRHS >= 0.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">AP</td><td><pre class="fragment"> AP is DOUBLE PRECISION array, dimension (N*(N+1)/2)
The upper or lower triangle of the symmetric matrix A, packed
columnwise in a linear array. The j-th column of A is stored
in the array AP as follows:
if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1<=i<=j;
if UPLO = 'L', AP(i + (j-1)*(2*n-j)/2) = A(i,j) for j<=i<=n.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">AFP</td><td><pre class="fragment"> AFP is DOUBLE PRECISION array, dimension (N*(N+1)/2)
The factored form of the matrix A. AFP contains the block
diagonal matrix D and the multipliers used to obtain the
factor U or L from the factorization A = U*D*U**T or
A = L*D*L**T as computed by DSPTRF, stored as a packed
triangular matrix.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">IPIV</td><td><pre class="fragment"> IPIV is INTEGER array, dimension (N)
Details of the interchanges and the block structure of D
as determined by DSPTRF.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">B</td><td><pre class="fragment"> B is DOUBLE PRECISION array, dimension (LDB,NRHS)
The right hand side matrix B.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">LDB</td><td><pre class="fragment"> LDB is INTEGER
The leading dimension of the array B. LDB >= max(1,N).</pre></td></tr>
<tr><td class="paramdir">[in,out]</td><td class="paramname">X</td><td><pre class="fragment"> X is DOUBLE PRECISION array, dimension (LDX,NRHS)
On entry, the solution matrix X, as computed by DSPTRS.
On exit, the improved solution matrix X.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">LDX</td><td><pre class="fragment"> LDX is INTEGER
The leading dimension of the array X. LDX >= max(1,N).</pre></td></tr>
<tr><td class="paramdir">[out]</td><td class="paramname">FERR</td><td><pre class="fragment"> FERR is DOUBLE PRECISION array, dimension (NRHS)
The estimated forward error bound for each solution vector
X(j) (the j-th column of the solution matrix X).
If XTRUE is the true solution corresponding to X(j), FERR(j)
is an estimated upper bound for the magnitude of the largest
element in (X(j) - XTRUE) divided by the magnitude of the
largest element in X(j). The estimate is as reliable as
the estimate for RCOND, and is almost always a slight
overestimate of the true error.</pre></td></tr>
<tr><td class="paramdir">[out]</td><td class="paramname">BERR</td><td><pre class="fragment"> BERR is DOUBLE PRECISION array, dimension (NRHS)
The componentwise relative backward error of each solution
vector X(j) (i.e., the smallest relative change in
any element of A or B that makes X(j) an exact solution).</pre></td></tr>
<tr><td class="paramdir">[out]</td><td class="paramname">WORK</td><td><pre class="fragment"> WORK is DOUBLE PRECISION array, dimension (3*N)</pre></td></tr>
<tr><td class="paramdir">[out]</td><td class="paramname">IWORK</td><td><pre class="fragment"> IWORK is INTEGER array, dimension (N)</pre></td></tr>
<tr><td class="paramdir">[out]</td><td class="paramname">INFO</td><td><pre class="fragment"> INFO is INTEGER
= 0: successful exit
< 0: if INFO = -i, the i-th argument had an illegal value</pre> </td></tr>
</table>
</dd>
</dl>
<dl class="section user"><dt>Internal Parameters: </dt><dd><pre class="fragment"> ITMAX is the maximum number of steps of iterative refinement.</pre> </dd></dl>
<dl class="section author"><dt>Author</dt><dd>Univ. of Tennessee </dd>
<dd>
Univ. of California Berkeley </dd>
<dd>
Univ. of Colorado Denver </dd>
<dd>
NAG Ltd. </dd></dl>
<dl class="section date"><dt>Date</dt><dd>November 2011 </dd></dl>
</div>
</div>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Wed Apr 1 2015 16:27:43 for Lighthouse by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
| Java |
<?php
/*
* FluentDOM
*
* @link https://thomas.weinert.info/FluentDOM/
* @copyright Copyright 2009-2021 FluentDOM Contributors
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*
*/
namespace FluentDOM\Query {
use FluentDOM\Query;
use FluentDOM\TestCase;
require_once __DIR__.'/../../TestCase.php';
class TraversingParentsTest extends TestCase {
protected $_directory = __DIR__;
/**
* @group Traversing
* @group TraversingFind
* @covers \FluentDOM\Query::parents
*/
public function testParents(): void {
$fd = $this->getQueryFixtureFromFunctionName(__FUNCTION__);
$this->assertInstanceOf(Query::class, $fd);
$parents = $fd
->find('//b')
->parents()
->map(
function($node) {
return $node->tagName;
}
);
$this->assertTrue(is_array($parents));
$this->assertContains('span', $parents);
$this->assertContains('p', $parents);
$this->assertContains('div', $parents);
$this->assertContains('body', $parents);
$this->assertContains('html', $parents);
$parents = implode(', ', $parents);
$doc = $fd
->find('//b')
->append('<strong>'.htmlspecialchars($parents).'</strong>');
$this->assertInstanceOf(Query::class, $doc);
$this->assertFluentDOMQueryEqualsXMLFile(__FUNCTION__, $doc);
}
}
}
| Java |
(function() {
'use strict';
angular
.module('app.match')
.run(appRun);
appRun.$inject = ['routerHelper'];
/* @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return [{
state: 'match',
config: {
url: '/match/:id',
templateUrl: 'app/match/match.html',
controller: 'MatchController',
controllerAs: 'vm',
title: 'Match',
settings: {
nav: 2,
content: '<i class="fa fa-lock"></i> Match'
}
}
}];
}
})(); | Java |
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-docu',
templateUrl: './docu.component.html',
styleUrls: ['./docu.component.scss']
})
export class DocuComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
| Java |
using System;
using System.Linq;
using Cresce.Datasources.Sql;
using Cresce.Models;
using NUnit.Framework;
namespace Cresce.Business.Tests.Integration.Sql
{
[TestFixture]
internal class InvoiceRepositoryTests : SqlTests
{
private SqlInvoiceRepository _repository;
private Patient _patient;
public InvoiceRepositoryTests()
{
_repository = new SqlInvoiceRepository(this);
}
[SetUp]
public void CreateResources()
{
_patient = Utils.SavePatient();
}
[Test]
public void When_deleting_an_invoice_it_should_be_removed_from_the_database()
{
// Arrange
var invoice = Utils.SaveInvoice(_patient);
// Act
_repository.Delete(invoice.Id);
// Assert
var invoiceById = _repository.GetById(invoice.Id);
Assert.That(invoiceById, Is.Null);
}
[Test]
public void When_deleting_an_invoice_linked_with_an_appointment_it_should_be_removed_from_the_database()
{
// Arrange
var invoice = Utils.SaveInvoice(_patient);
Utils.SaveAppointment(Utils.SaveUser(), _patient, Utils.SaveService(), new DateTime(), invoiceId: invoice.Id);
// Act
_repository.Delete(invoice.Id);
// Assert
var invoiceById = _repository.GetById(invoice.Id);
Assert.That(invoiceById, Is.Null);
}
[Test]
public void When_getting_an_invoice_by_id_it_should_return_the_previously_saved_invoice()
{
// Arrange
var invoice = Utils.SaveInvoice(_patient);
// Act
var result = _repository.GetById(invoice.Id);
// Assert
Assert.That(result, Is.Not.Null);
}
[Test]
public void When_getting_an_invoice_by_id_it_should_return_specific_information()
{
// Arrange
var invoice = Utils.SaveInvoice(
_patient,
date: new DateTime(2017, 10, 23)
);
// Act
var result = _repository.GetById(invoice.Id);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.PatientId, Is.EqualTo(_patient.Id));
Assert.That(result.Date, Is.EqualTo(new DateTime(2017, 10, 23)));
Assert.That(result.Description, Is.EqualTo("some description"));
Assert.That(result.Value, Is.EqualTo(23.4));
}
[Test]
public void When_getting_a_non_existing_invoice_by_id_it_should_return_null()
{
// Arrange
var invoiceId = "-1";
// Act
var result = _repository.GetById(invoiceId);
// Assert
Assert.That(result, Is.Null);
}
[Test]
public void When_getting_an_invoices_for_patient_id_it_should_return_only_invoices_of_that_patient()
{
// Arrange
Utils.SaveInvoice(_patient, date: new DateTime(2017, 10, 23));
Utils.SaveInvoice(Utils.SavePatient("2"), date: new DateTime(2017, 10, 23));
// Act
var result = _repository.GetInvoices(_patient.Id).ToList();
// Assert
Assert.That(result.Count, Is.EqualTo(1));
}
[Test]
public void When_getting_all_invoices_it_should_return_all_persisted_invoices()
{
// Arrange
Utils.SaveInvoice(_patient, date: new DateTime(2017, 10, 23));
Utils.SaveInvoice(Utils.SavePatient("2"), date: new DateTime(2017, 10, 23));
// Act
var result = _repository.GetInvoices().ToList();
// Assert
Assert.That(result.Count, Is.EqualTo(2));
}
}
}
| Java |
### 我的博客
地址:[http://BTeam.github.io](http://BTeam.github.io)
### 安装说明
1. fork库到自己的github
2. 修改名字为:`username.github.io`
3. clone库到本地,参考`_posts`中的目录结构自己创建适合自己的文章目录结构
4. 修改CNAME,或者删掉这个文件,使用默认域名
5. 修改`_config.yml`配置项
6. It's done!
### 鸣谢
本博客框架来自 [闫肃](http://yansu.org)
| Java |
class Portal::CollaborationPolicy < ApplicationPolicy
end
| Java |
//
// This is the main include file for the gcode library
// It parses and executes G-code functions
//
// gcode.h
//
#ifndef GCODE_H
#define GCODE_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdarg.h>
#ifndef NRF51
// G-code debug print
unsigned int debug(const char *format, ...);
#else
#include "uart.h"
#endif
// Single G-code parameter
typedef struct {
char type;
float value;
} gcode_parameter_t;
// Parse G-code command
int gcode_parse(const char *s);
// Extract G-code parameter (similar to strtok)
int gcode_get_parameter(char **s, gcode_parameter_t *gp);
#endif
| Java |
import { DOCUMENT } from '@angular/common';
import { ApplicationRef, ComponentFactoryResolver, Inject, Injectable, Injector } from '@angular/core';
import { BaseService } from 'ngx-weui/core';
import { ToptipsComponent, ToptipsType } from './toptips.component';
@Injectable({ providedIn: 'root' })
export class ToptipsService extends BaseService {
constructor(
protected readonly resolver: ComponentFactoryResolver,
protected readonly applicationRef: ApplicationRef,
protected readonly injector: Injector,
@Inject(DOCUMENT) protected readonly doc: any,
) {
super();
}
/**
* 构建一个Toptips并显示
*
* @param text 文本
* @param type 类型
* @param 显示时长后自动关闭(单位:ms)
*/
show(text: string, type: ToptipsType, time: number = 2000): ToptipsComponent {
const componentRef = this.build(ToptipsComponent);
if (type) {
componentRef.instance.type = type;
}
if (text) {
componentRef.instance.text = text;
}
componentRef.instance.time = time;
componentRef.instance.hide.subscribe(() => {
setTimeout(() => {
this.destroy(componentRef);
}, 100);
});
return componentRef.instance.onShow();
}
/**
* 构建一个Warn Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
warn(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'warn', time);
}
/**
* 构建一个Info Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
info(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'info', time);
}
/**
* 构建一个Primary Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
primary(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'primary', time);
}
/**
* 构建一个Success Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
success(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'primary', time);
}
/**
* 构建一个Default Toptips并显示
*
* @param text 文本
* @param time 显示时长后自动关闭(单位:ms)
*/
default(text: string, time: number = 2000): ToptipsComponent {
return this.show(text, 'default', time);
}
}
| Java |
require 'test_helper'
class QuestionSubjectiveTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| Java |
var loadJsons = require('../lib/loadJsons');
describe("Get a recursive directory load of JSONs", function() {
var data;
beforeEach(function(done) {
if(data) done();
else {
loadJsons("./specs")(function(d) {
data = d;
done();
});
}
});
it("Should return right number of jsons", function() {
expect(data.length).toBe(6);
});
it("Should have a @type field on all objects", function() {
data.forEach(function(d) {
expect(d['@type']).toBeDefined();
});
});
});
| Java |
---
layout: post
status: publish
published: true
title: Moved to Jekyll blog engine
date: 2015-10-20 22:31:25.000000000 +05:30
comments: []
---
I have been using wordpress since the time I started blogging. I decided to make a move to the Jekyll static templating engine after I came to know about its simplicity and ability to host on github. Blogs are usually immutable once they are written. There is no reason use dynamic pages for blogs. The theme of this blog is based on [jekyll-incorporated](https://github.com/kippt/jekyll-incorporated). I generally don't like the WYSWYG editor that comes with the wordpress. I would prefer to write blog posts on vim as I write code. WYSWYG editors add lots of junk into the generated html. I had to to spend a lot of time migrating those editor generator markup into jekyll plain text. Blog is now hosted on [github](github.com/t3rm1n4l/t3rm1n4l.github.io). Luckly, I could import most of the comments into discuss. I hope to blog more frequently with this transition.
| Java |
using System;
using System.Diagnostics;
using System.Text;
namespace BgeniiusUniversity.Logging
{
public class Logger : ILogger
{
public void Information(string message)
{
Trace.TraceInformation(message);
}
public void Information(string fmt, params object[] vars)
{
Trace.TraceInformation(fmt, vars);
}
public void Information(Exception exception, string fmt, params object[] vars)
{
Trace.TraceInformation(FormatExceptionMessage(exception, fmt, vars));
}
public void Warning(string message)
{
Trace.TraceWarning(message);
}
public void Warning(string fmt, params object[] vars)
{
Trace.TraceWarning(fmt, vars);
}
public void Warning(Exception exception, string fmt, params object[] vars)
{
Trace.TraceWarning(FormatExceptionMessage(exception, fmt, vars));
}
public void Error(string message)
{
Trace.TraceError(message);
}
public void Error(string fmt, params object[] vars)
{
Trace.TraceError(fmt, vars);
}
public void Error(Exception exception, string fmt, params object[] vars)
{
Trace.TraceError(FormatExceptionMessage(exception, fmt, vars));
}
public void TraceApi(string componentName, string method, TimeSpan timespan)
{
TraceApi(componentName, method, timespan, "");
}
public void TraceApi(string componentName, string method, TimeSpan timespan, string fmt, params object[] vars)
{
TraceApi(componentName, method, timespan, string.Format(fmt, vars));
}
public void TraceApi(string componentName, string method, TimeSpan timespan, string properties)
{
string message = String.Concat("Component:", componentName, ";Method:", method, ";Timespan:", timespan.ToString(), ";Properties:", properties);
Trace.TraceInformation(message);
}
private static string FormatExceptionMessage(Exception exception, string fmt, object[] vars)
{
// Simple exception formatting: for a more comprehensive version see
// http://code.msdn.microsoft.com/windowsazure/Fix-It-app-for-Building-cdd80df4
var sb = new StringBuilder();
sb.Append(string.Format(fmt, vars));
sb.Append(" Exception: ");
sb.Append(exception.ToString());
return sb.ToString();
}
}
} | Java |
---
layout: article
title: "The Zen of Design Patterns (2nd Edition)"
categories: programing
tags: [java, reading]
toc: false
image:
teaser: programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/teaser.jpg
date: 2017-11-05
---
让设计模式成为一种习惯
---
## 第一章 单一职责原则
缩略语:
* SRP(Single Responsibility Principle,单一职责模式)
* RBAC(Role-Based Access Control, 基于角色的访问控制)
* BO(Business Object,业务对象),负责用户的属性
* Biz(Business Logic,业务逻辑),负责用户的行为
单一职责原则(SRP)指的是只有一个原因引起类的变更。
具体实践中应保证接口和方法一定做到单一职责,而类尽量做到。
## 第二章 里氏替换原则
缩略语:
* LSP(Liskov Substitution Principle,里氏替换原则)
里氏替换原则(LSP)是指只要父类能出现的地方子类都能出现。
实现里氏替换原则需要做到:
1. 子类必须完全实现父类的方法
2. 子类可以有自己的个性
3. 覆写(Override)或实现父类方法时输入参数可以被放大
4. 覆写(Override)或实现父类方法时输出结果可以被缩小
第三条指的是子类中的方法的前置条件必须与超类中被覆写方法的前置条件相同或更宽松。这是覆写的要求,也是重中之重。否则若方法的输入参数被缩小,则子类在没有覆写父类方法的前提下,子类方法可能被执行了,会引起业务逻辑混乱,歪曲了父类的意图。
注意输入参数不同就不能称为覆写(Override),加上@Override会出错,应该称为重载(Overload)。
## 第三章 依赖倒置原则
缩略语:
* DIP(Dependence Inversion Principle,依赖倒置原则)
* OOD(Object-Oriented Design,面向对象设计,面向接口编程)
* TDD(Test-Driven Development,测试驱动开发)
依赖倒置是指面向接口编程(OOD)。依赖正置就是类间的依赖是实实在在的实现类间的依赖,也就是面向实现编程。我要开奔驰车就依赖奔驰车。而抽象间的依赖代替了人们传统思维的事物间的依赖,“倒置”就是从这里产生的。
实现依赖倒置原则需要做到:
1. 高层模块不应该依赖低层模块,两者都应该依赖其抽象。即类之间不发生直接的依赖关系,其依赖是通过接口或抽象类产生的
2. 抽象不应该依赖细节。即接口或抽象类不依赖于实现类
3. 细节应该依赖抽象。即实现类依赖于接口或抽象类
依赖的三种写法:
1. 构造函数传递依赖对象
{% highlight java %}
{% raw %}
Public interface IDriver {
public void drive();
}
public class Driver implements IDriver {
private ICar car;
// 构造函数注入
public Driver(ICar _car) {
this.car = _car;
}
public void drive() {
this.car.run();
}
}
{% endraw %}
{% endhighlight %}
2. Setter方法传递依赖对象
{% highlight java %}
{% raw %}
public interface IDriver {
public void setCar(Icar car);
public void drive();
}
public class Driver implements IDriver {
private ICar car;
// Setter注入
public void setCar(ICar _car) {
this.car = _car;
}
public void drive() {
this.car.run();
}
}
{% endraw %}
{% endhighlight %}
3. 接口声明传递依赖对象,也叫做接口注入。
{% highlight java %}
{% raw %}
public interface IDriver {
// 接口注入
public void drive(ICar car);
}
public class Driver implements IDriver {
public void drive(ICar car) {
car.run();
}
}
{% endraw %}
{% endhighlight %}
有依赖关系的不同开发人员,如甲负责IDriver,乙负责ICar,则两个开发人员只要定好接口就可以独立开发,并可以独立进行单元测试。这也就是测试驱动开发(TDD),是依赖倒置原则的最高级应用。比如可以引入JMock工具,根据抽象虚拟一个对象进行测试。
{% highlight java %}
{% raw %}
Public class DriverTest extends TestCase {
Mockery context = new JUnit4Mockery();
@Test
public void testDriver() {
// 根据接口虚拟一个对象
final ICar car = context.mock(ICar.class);
IDriver driver = new Driver();
// 内部类
context.checking(new Expectations(){{
oneOf(car).run();
}});
driver.drive(car);
}
}
{% endraw %}
{% endhighlight %}
具体实践中,实现依赖倒置需要遵守:
1. 每个类尽量都有接口或抽象类,或者二者兼备
2. 变量的表面类型尽量是接口或抽象类,工具类和需要使用clone方法的类除外
3. 任何类都不应该从具体类派生
4. 尽量不要覆写基类的方法。如果基类是抽象类,且该方法已经实现,则子类尽量不要覆写
5. 综合里氏替换原则
## 第四章 接口隔离原则
缩略语
* ISP(Interface Segregation Principle,接口隔离原则)
接口隔离原则指的是类间的依赖关系应该建立在最小的接口上。即接口尽量细化,同时接口中的方法尽量少。
这与单一职责原则的审视角度是不同的,单一职责原则是业务逻辑的划分,而接口隔离原则要求接口的方法尽量少。提供几个模块就应该有几个接口,而不是建立一个庞大臃肿的接口容纳所有的客户端访问。注意,根据接口隔离原则拆分接口时,必须满足单一职责原则。
## 第五章 迪米特原则
缩略语:
* LoD(Law of Demeter,迪米特原则),也称为LKP(Least Knowledge Principle,最少知识原则)
* RMI(Remote Method Invocation,远程方法调用)
* VO(Value Object,值对象)
迪米特原则指的是一个类应该对自己需要耦合或调用的类知道的最少,不关心其内部的具体实现,只关心提供的public方法。即类间解耦,弱耦合。
迪米特原则要求:
1. 只与直接的朋友通信。出现在成员变量、方法的输入输出参数中的类称为成员朋友类,而出现在方法体内部的类不属于朋友类。一个方法中尽量不引入一个类中不存在的对象,JDK API提供的类除外
2. 朋友间也是有距离的。尽量不对外公布太多的public方法和非静态的public变量
3. 是自己的就是自己的。如果一个方法放在本类中,既不增加类间关系,对本类也不产生负面影响,那就放置在本类中
4. 谨慎使用Serializable。在一个项目中使用远程方法调用(RMI),传递一个值对象(VO),这个对象就必须实现Serializable接口(仅仅是一个标志性接口,不需要实现具体方法),否则就会出现NotSerializableException异常。当客户端VO修改了一个属性的访问权限,由private变更为public,访问权限扩大了,如果服务器上没有做出相应的变更,就会出现序列化失败。当然,这属于项目管理中客户端与服务器同步更新的问题。
在具体实践中,既要做到高内聚低耦合,又要让结构清晰。如果一个类跳转两次以上才能访问另一个类,则需要考虑重构了,这就是过度地解耦了。因为跳转次数越多,系统越复杂,维护就越难。
## 第六章 开闭原则
缩略语:
* OCP(Open Closed Principle,开闭原则)
开闭原则指的是软件实体如类、模块和方法应该对扩展开放,对修改关闭。这是Java世界中最基础的设计原则,以建立一个稳定灵活的系统。也就是说,一个软件实体应该通过扩展来实现变化,而不是通过修改已有的代码来实现变化。并不意味着不做任何修改,在业务规则改变或低层次模块变更的情况下高层模块必须有部分改变以适应新业务,改变要尽可能地少,防止变化风险的扩散。
一个方法的测试方法一般不少于3种,有业务逻辑测试,边界条件测试,异常测试等。
实现开闭原则需要做到:
1. 抽象约束。在子类中不允许出现接口或抽象类中不存在的public方法;参数类型、引用类型尽量使用接口或抽象类而不是实现类;抽象类尽量保持稳定,一旦确定不允许修改
2. 元数据(metadata)控制模块行为。元数据为描述环境和数据的数据,即配置参数。元数据控制模块行为的极致为控制反转(Inversion of Control),使用最多的就是Spring容器
3. 制定项目章程。如所有的Bean都自动注入,使用Annotation进行装配,进行扩展时,只用可以只用一个子类,然后由持久层生成对象
4. 封装可能的变化。将相同的变化封装到一个接口或抽象类中;将不同的变化封装到不同的接口或抽象类中
软件设计最大的难题就是应对需求的变化。6大设计原则和23个设计模式都是为了封装未来的变化。
6大设计原则有:
1. Single Responsibility Principle: 单一职责原则
2. Open Closed Principle: 开闭原则
3. Liskov Substitution Principle: 里氏替换原则
4. Law of Demeter: 迪米特原则
5. Interface Segregation Principle: 接口隔离原则
6. Dependence Inversion Principle: 依赖倒置原则
将6个原则的首字母联合起来,就是Solid(稳定的),里氏替换原则和迪米特原则的首字母都是L,只取一个。开闭原则是最基础的原则,是精神口号,其他5大原则是开闭原则的具体解释。
## 第七章 单例模式
单例模式(Singleton Pattern)指的是确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。其实现方式可以分为饿汉式和懒汉式。
/1-singleton.png)
单例模式的优点有:
1. 减少内存开支,特别是当一个对象需要频繁创建和销毁时
2. 减少了系统的性能开销
3. 避免对资源的多重占用
4. 可以在系统设置全局的访问点,优化共享资源的访问
在具体实践中,Spring的每个Bean默认就是单例的,这样Sring容器可以管理这些Bean的生命期,决定何时创建、何时销毁和如何销毁等。
## 第八章 工厂方法模式
工厂方法模式指的是定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
/2-factory.png)
工厂方法模式的优点有:
1. 有良好的封装性,代码结构清晰。调用者需要创建一个具体产品对象时,只需要知道这个产品的类名(或约束字符串)就可以了,不用知道创建对象的过程,降低模块间的耦合性
2. 优秀的扩展性,在增加产品类的情况下,只需要适当修改或扩展工厂类即可
3. 屏蔽产品类,不需要关心产品类的实现,只关心产品类的接口
4. 工厂方法是典型的解耦框架,符合迪米特原则(最少知识原则),符合依赖倒置原则,也符合里氏替换原则
在具体实践中,工厂方法模式可以缩小为简单工厂模式,也叫做静态工厂模式。即将工厂类去掉继承抽象类,并添加具体生产方法前添加static关键字,其缺点是扩展比较困难,不符合开闭原则。
工厂方法模式还可以升级为多个工厂类,当然此时如果要扩展一个产品类,就需要建立一个相应的工厂类,这就增加了扩展的难度,所以一般会再添加一个协调类,用来封装子工厂类,为高层模块添加统一的访问接口。
工厂方法模式也可以替代单例模式,不过需要在工厂类中使用反射的方式建立单例对象。
工厂方法模式还可以延迟初始化,即一个对象被消费完毕之后并不立刻释放,工厂类会保持其初始状态,等待再次被使用。延迟加载框架是可以扩展的,比如限制某一产品类的最大实例化数量(数据库的最大连接数量等),可以通过判断Map中已有的对象数量来实现。
## 第九章 抽象工厂方法
抽象工厂模式指的是为创建一组相关的或相互依赖的对象提供一个接口,而且无需指定它们的具体类。
/3-abstract-factory.png)
抽象工厂模式的优点有:
1. 封装性
2. 产品族内的约束为非公开状态,例如每生产一个产品A,就同时生产出1.2个产品B,这个约束是在工厂内实现的,对高层模块来说是透明的。
抽象工厂模式是工厂方法模式的升级版本。即拥有两个或两个以上互相影响的产品族,或者说产品的分类拥有两个或两个以上的维度,如不同性别和肤色的人。如果拥有两个维度,则抽象工厂模式比工厂方法模式多一个抽象产品类,以维护两个分类维度,即不同的抽象产品类维护一个维度,而不同的产品实现类维护另外一个维度;而抽象工厂类不增加,但需要增加不同的工厂实现类。
抽象工厂模式的缺点是产品族的扩展非常困难。例如增加一个产品C,则抽象类AbstractCreator要增加一个方法createProductC(),然后两个实现类都要修改。这样就违反了开闭原则。而另外一个维度产品等级是很容易扩展的,对于工厂类只需要增加一个实现类即可。也就是说,抽象工厂模式横向扩展容易,纵向扩展困难。对于横向,抽象工厂模式是符合开闭原则的。
## 第十章 模板方法模式
模板方法模式值得是定义一个操作中的算法框架,而将一些步骤的实现延迟到子类中。使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
/4-template.png)
模板方法模式的抽象模板类一般包含两类方法,一种是基本方法,由子类实现,并且在模板方法中被调用;另一种是抽象方法,可以有一个或多个,一般是一个具体方法,也就是一个框架,实现对基本方法的调度,完成固定的逻辑。模板方法一般会加上final关键字,不允许覆写,以防恶意操作。
如果模板方法的执行结果受到基本方法的返回值或所设置的值的影响,则该基本方法称为钩子方法(Hook Method),即钩子方法可能会影响其公共部分(模板方法)的执行顺序。
模板方法模式的优点有:
1. 封装不变部分,扩展可变部分
2. 提取公共部分代码,便于维护。相同的一段代码如果复制过两次,就需要对设计产生怀疑
3. 行为由父类控制,子类实现,符合开闭原则
模板方法的缺点是子类的实现会影响父类的结果,也就是子类会对父类产生影响,在复杂项目中,会增加代码阅读的难度。
在具体实践中,如果被问到“父类如何调用子类的方法”,其实现方式可能有把子类传递到父类的有参构造中,然后调用;使用反射的方式调用;父类调用子类的静态方法。当然项目中强烈不建议这么做,如果要调用子类的方法,可以使用模板方法模式,影响父类行为的结果。
## 第十一章 建造者模式
建造者模式也称为生成器模式,指的是将一个复杂对象的构建和它的表示分离,使得同样的构建过程可以创建不同的表示。
/5-builder.png)
通常,建造者模式有4个角色,产品类,抽象建造者,建造者的实现类(如可以传入产品的模块顺序或数量配置,并生产产品),导演类(如负责安排已有模块的顺序或数量,然后告诉建造者开始建造)。
建造者模式的优点:
1. 封装性
2. 建造者独立,容易扩展
3. 便于控制细节风险
建造者模式关注的是零件类型和装配工艺(顺序),这是它与工厂方法模式最大的不同之处,虽然同为创建类模式,但关注点不同。工厂方法的重点是创建零件,而组装顺序不是它关心的内容。
在具体实践中,使用创建者模式的时候考虑一下模板方法模式,二者的配合可以作为创建者模式的扩展。
## 第十二章 代理模式
缩略语:
AOP(Aspect Oriented Programming,面向横切面编程)
代理模式又称为委托模式,指的是为其他对象提供一种代理以控制对这个对象的访问。其他的许多模式,如状态模式、策略模式和访问者模式本质上是在更特殊的场合使用了代理模式。
/6-proxy.png)
代理类不仅可以实现主题接口,还可以为真实角色预处理信息、过滤信息、消息转发、事后处理信息等功能。
代理模式的优点有:
1. 职责清晰。真实的角色只实现实际的业务逻辑,而通过后期的代理完成某一件事务
2. 高扩展性
3. 智能化,例如动态代理
代理模式可以扩展为普通代理,要求客户端只能访问代理角色,而不能访问真实角色,真实角色由代理角色来实例化。
代理模式还可以作为强制代理,这个比较另类,所谓强制表示必须通过真实角色找到代理角色,否则不能访问。也就是说高层模块new了一个真实角色的对象,返回的却是代理角色。比如拨通明星的电话,确强制返回其经纪人作为代理,这就是强制代理。
代理模式还可以作为动态代理,动态代理是在实现阶段不用关心代理谁,在运行阶段才指定代理哪一个对象。相对来说,自己写代理类的方式就是静态代理。面向横切面编程(AOP)的核心就是动态代理机制。
一个类的动态代理类由InvocationHandler(JDK提供的动态代理接口)的实现类通过invoke方法实现所有的方法,
在具体实践中,关于AOP框架,需要弄清楚几个名词,包括切面(Aspect)、切入点(JoinPoint)、通知(Advice)和织入(Weave),这样在应用中就游刃有余了。
## 第十三章 原型模式
原型模式指的是用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。即不通过new关键字来产生一个对象,而是通过对象复制来实现。可以理解为一个对象的产生可以不由零起步,而是由正本通过二进制内存拷贝创建多个副本,然后再修改为生产需要的对象。
/7-prototype.png)
原型模式的核心是一个clone方法,通过该方法进行对象的拷贝,Java提供了一个Cloneable接口来标识这个对象是可拷贝的,且还必须覆写clone方法。为什么说Cloneable接口仅作为标识还称clone方法为覆写,因为clone方法是Object类的,而每个类都默认继承了Object类。
原型模式的优点有:
1. 性能优良,内存二进制流的拷贝
2. 规避构造函数的约束,当然这个有时候也是缺点,直接内存拷贝,其构造函数是不会执行的
需要注意的是Object提供的clone方法只是拷贝对象,其对象内部的数组、引用对象都不拷贝,还是指向原生对象的内部元素地址,这种拷贝称为浅拷贝。两个对象共享了一个私有变量,并且都可以对其进行修改,这是一种很不安全的方式。
浅拷贝时,内部的数组和引用对象不拷贝,其他的基本类型如int、long和char等都会被拷贝,对于String类型,Java希望你把它当作基本类型,它是没有clone方法的,处理机制也比较特殊,通过字符串池(stringpool)在需要的时候才在内存中创建新的字符串。
深拷贝则需要考虑成员变量中所有的数组和可变的引用对象,进一步调用或覆写引用对象的clone方法,如JDK提供的ArrayList的clone方法。
此外要使用clone方法,类的成员变量上不要增加final关键字。
在具体实践中,原型模式很少单独出现,一般和工厂方法模式一起出现,通过clone方法创建一个对象,然后由工厂方法提供给调用者。
## 第十四章 中介者模式
中介者模式指的是用一个中介对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使其耦合松散,并且可以独立地改变它们之间的交互。中介者类似于星型网络拓扑中的中心交换机连接各计算机。也称为调停者模式。
/8-mediator.png)
中介者模式的优点就是减少了类间的依赖,把原有的一对多的依赖变成了一对一的依赖,同事类只依赖中介者,减少了依赖,当然同时也降低了类间的耦合。
中介者模式的缺点是中介者会膨胀得很大,而且同事类越多,逻辑越复杂。
在面向对象编程中,对象与对象之间必然存在依赖关系,如果某个类和其他类没有任何相互依赖的关系,那么这个类在项目中就没有存在的必要了。所以中介者模式适用于多个对象之间紧密耦合的情况,紧密耦合的标准是在类图中出现了蜘蛛网状结构。而中介者模式的使用可以将蜘蛛网结构梳理为星型结构。
在具体实践中,Struts的MVC框架中的C(Controller)就是一个中介者,叫做前端控制器。它的作用就是把M(Model,业务逻辑)和V(View,视图)隔离开来,减少M和V的依赖关系。
## 第十五章 命令模式
命令模式指的是将一个请求封装成一个对象,从而让你使用不同的请求把客户端参数化,将多个请求排队或者记录请求日志,也可以提供命令的撤销和恢复功能。
/9-command.png)
命令模式的优点有:
1. 类间解耦。调用者角色和接收者角色之间没有任何的依赖关系,调用者实现功能时只需调用Command抽象类execute方法就可以了,不需要了解到底是哪个接收者执行
2. 可扩展性。Command的子类可以非常容易扩展
3. 命令模式与其他模式的结合会更优秀。命令模式结合责任链模式,实现命令族解析任务;命令模式结合模板方法模式,则可以减少Command子类的膨胀问题
命令模式的缺点是如果命令很多,则Command子类很容易增多,这个类就显得非常膨胀
在具体实践中,高层模块可以不需要知道具体的接收者,而是用具体的Command子类将接收者封装起来,每个命令完成单一的职责,解除高层模块对接收者的依赖关系。
## 第十六章 责任链模式
责任链模式指的是使多个对象都有机会处理请求,从而避免了请求的发送者和接收者的耦合关系,将这些接收者对象连成一条链,并沿着这条链传递请求,知道有对象处理它为止。注意请求是由接收者对象来决定是否传递的,而不是在高层模块中判断。
/10-chain-of-responsibility.png)
责任链模式的优点是将请求和处理分开,请求者不用知道是谁处理的,只问了责任链中的第一个接收者,只需要得到一个回复,而关于请求是否传递则由接收者来传递。同样的,接收者也不用知道请求的全貌。两者解耦,提高系统的灵活性。
责任链的缺点一个是性能问题,责任链比较长的时候遍历会带来性能问题;另一个是调试不方便,由于采用了类似递归的方式,逻辑可能比较复杂。
在具体实践中,一般会有一个封装类对责任链模式进行封装,也就是替代场景类client,直接返回责任链中的第一个处理者,具体链的设置不需要高层模块知道,这样更简化了高层模块的调用,减少模块间的耦合性。另外,责任链的接收者节点数量需要控制,一般做法是在Handler中设置一个最大的节点数量,在setNext方法中判断是否超过该阈值。责任链模式通常会与模板方法结合,每个实现类只需要实现response方法和getHandlerLevel获取处理级别。
## 第十七章 装饰模式
装饰模式指的是动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式比由对象直接生成子类更为灵活。装饰模式可以任意选择所需要添加的装饰,下一次传递的被装饰对象为上一次装饰完毕的对象,都继承自同一个Component抽象类。装饰模式也可看成是特殊的代理模式。
/11-decorator.png)
装饰模式的优点有:
1. 装饰类和被装饰类可以独立发展,而不会相互耦合。即Component类无须知道Decorator类,而Decorator类是从外部扩展Component类的功能,而不需要知道具体的Component类的构件。
2. 装饰模式是继承关系的一个替代方案。不管装饰多少层,返回的对象仍是Component,实现的还是is-a关系。
3. 装饰模式可以动态地扩展一个实现类的功能。
装饰模式的缺点是多层的装饰还是比较复杂的,因为可能剥离到最里面一层,才发现错误,所以尽量减少装饰类的数量,以降低系统的复杂度。
在具体实践中,装饰模式是对继承的一种有力补充。可以在高层模块中动态地给一个对象增加功能,这些功能也可以再动态地撤销。而继承是静态地给类增加功能。而且装饰模式的扩展性也非常好,比如要在继承关系Father、Sonh和GrandSon三层类中的Son增强一些功能,怎么办,如何评估对GrandSon造成的影响,特别是GrandSon有多个的时候,此时就可以通过建立SonDecorator类来修饰Son,很好地完成这次变更。
## 第十八章 策略模式
策略模式指的是定义一组算法,将每个算法都封装起来,并且使它们之间可以互换。策略模式也是一种特殊的代理模式,使用一个代理类(Context封装类)来代理多个对象(Strategy抽象类的具体实现)。
/12-strategy.png)
策略模式的优点有:
1. 策略(算法)可以自由替换
2. 避免使用多重条件判断
3. 扩展性良好
策略模式的缺点有策略类数量增多导致类膨胀,另一个是所有的策略类都需要对外暴露。上层模块必须知道有哪些策略,才能决定使用哪一个策略,这与迪米特原则是违背的,要你的封装类有何用。
在具体实践中,一般通过工厂方法模式来实现策略类的声明,来避免所有策略都必须对高层模块暴露的问题。
## 第十九章 适配器模式
适配器模式指的是将一个类的接口变换成客户端所期待的另一种接口,从而使原本不匹配的两个类能够共同工作。适配器模式又称为变压器模式。适配器模式也是包装模式的一种,包装模式还有装饰模式。
/13-adapter.png)
适配器模式的优点有:
1. 让两个没有任何关系的类在一起运行
2. 增加了类的透明性。我们访问的Target目标角色,其具体实现都委托给了源角色,而这些对高层模块是不可见的
3. 提高了类的复用度。源角色在原有的系统中可以正常使用,通过适配器角色中也可以让Target目标角色使用
4. 灵活性非常好。适配器角色删除后不会影响其他代码
在具体实践中,在细节设计阶段不要考虑适配器模式,适配器模式不是为了解决还处于开发阶段的问题,而是为了解决正在服役的项目问题。换句话说,适配器模式是一种补救模式。适配器可分为对象适配器和类适配器,类适配器是类间适配,通过继承关系适配源角色,而对象适配器是通过关联聚合关系适配多个源角色。在实际项目中,对象适配器更为灵活,使用的也较多。
## 第二十章 迭代器模式
迭代器模式指的是提供一种方法访问一个容器对象中各个元素,而又不需要暴露该对象的内部细节。迭代器是为容器服务的,能容纳对象的所有类型都可以称之为容器,例如Collection类型、Set类型等。
/14-interator.png)
Java的的迭代器接口java.util.iterator有三个方法hasNext、next和remove。迭代器的remove方法应该完成两个逻辑:一是删除当前元素,而是当前游标指向下一个元素。而抽象容器类必须提供一个方法来创建并返回具体迭代器角色,Java中通常为iterator方法。
在具体实践中,Java的基本API中的容器类基本都融入了迭代器模式,所以尽量不要自己写迭代器模式。
## 第二十一章 组合模式
组合模式指的是将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。
/15-composite.png)
组合模式的优点有:
1. 高层模块调用简单,一个树形结构中的所有节点都是Component,简化了高层模块的调用
2. 节点自由增加
组合模式的缺点是叶子类和树枝类直接继承了Component抽象类,这与面向接口编程相冲突,即不符合依赖倒置的原则。
组合模式有两种不同的实现,一种是安全模式,一种是透明模式。安全模式是指叶子对象和树枝对象的结构不同,而公共部分的Operation()方法放到Component抽象类中。而透明模式指的是,叶子对象和树枝对象的结构相同,所有方法全部集合到Component抽象类中,通过getChildren的返回值判断是叶子节点还是树枝节点。
具体实践中,建议使用安全模式的组合模式。但透明模式基本遵循了依赖倒置的原则,方便系统进行扩展。页面结构、XML结构和公司的组织结构都是树形结构,都可以采用组合模式。
## 第二十二章 观察者模式
观察者模式指的是定义对象间一对多的依赖关系,使得当发布者对象的状态改变,则所有它依赖的订阅对象都会得到通知并自动更新。观察者模式也叫做发布/订阅模式。
/16-observer.png)
观察者模式的优点有:
1. 被观察者与观察者之间是抽象耦合,容易扩展
2. 建立了一套触发机制,很容易实现一条触发链
观察者模式的缺点是开发效率和运行效率的问题。一个被观察者和多个观察者,甚至会有多级触发情况,开发和调试就会相对比较复杂,而且一个观察者卡壳,会影响整体的执行效率。在这种情况下可以考虑异步的方式。
EJB(Enterprise JavaBean)中有3个类型的Bean,分别为Session Bean、Entity Bean和MessageDriven Bean(MDB),对于MDB,消息的发布者发布一个消息,也就是一个消息驱动Bean,通过EJB容器(一般是Message Queue消息队列)通知订阅者作出响应,这个就是观察者模式的升级版,或成为企业版。
在具体实践中,多级触发的广播链最多为两级,即消息最多传递两次。观察者模式的多级触发与责任链模式的区别是观察者模式传递的消息是可以随时更改的,而责任链模式传递的消息一般是保持不变的,如果需要改变,也只是在原有的消息上进行修正。JDK中提供了java.util.Observable实现类作为被观察者和java.util.Observer接口作为观察者。
## 第二十三章 门面模式
门面模式指的是要求一个子系统的外部与其内部的通信必须通过一个统一的对象进行。门面模式提供一个高层次的接口使得子系统更容易使用。门面模式也叫做外观模式。
/17-facade.png)
门面模式注重统一的对象,也就是提供一个门面对象作为访问子系统的接口,除了这个接口不允许任何访问子系统的行为发生。
门面模式的优点有:
1. 减少系统的相互依赖。客户端所有的依赖都是对门面对象的依赖,与子系统无关。
2. 提高了灵活性。
3. 提高安全性。只能访问在门面对象上开通的方法。
门面模式的缺点是不符合开闭原则。在业务更改或出现错误时,需要修改门面对象的代码。
门面模式不应该参与子系统内的业务逻辑,如在一个方法中先调用了子系统的ClassA的方法,再调用子系统的ClassB的方法。门面对象只是提供访问子系统的一个路径而已,它不应该也不能参与具体的业务逻辑,否则子系统必须依赖门面对象才能被访问,违反了单一职责原则,也破坏了系统的封装性。对于这种情况,应该建立一个封装类,封装完毕后提供给门面对象。
在具体实践中,当算法或者业务比较复杂时,可以封装出一个或多个门面出来,项目的结构比较简单,而且扩展性良好。另外对于一个大项目,使用门面模式也可以避免低水平开发人员带来的风险。使用门面模式后,可以对门面进行单元测试,约束项目成员的代码质量。
## 第二十四章 备忘录模式
备忘录模式指的是在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可以将该对象恢复到原先保存的状态。
/18-memento.png)
备忘录模式的备忘录角色可以由原型模式的clone方法创建。发起人角色只要实现Cloneable接口就成。这样发起人角色融合就融合发起人角色和备忘录角色,此时备忘录管理员角色直接依赖发起人角色。当然也可以再精简掉备忘录管理员角色,使发起人自主备份和恢复。这不是“在该对象之外保存这个状态”,而是把状态保存在了发起人内部,但这仍然可视为备忘录模式的一种。此外使用原型模式还必须要考虑深拷贝和浅拷贝的问题,所以Clone方式的备忘录模式只适用于较简单的场景。
备忘录模式还可以备份多状态,多备份。可以使用Map来实现。对于多备份,建议设置Map的上限,否则系统很容易产生内存溢出的情况。
在具体实践中,最好使用备忘录模式来代替使用数据库的临时表作为缓存备份数据,后者加大了数据库操作的频繁度,把压力下放到了数据库。
## 第二十五章 访问者模式
访问者模式指的是封装一些作用于某种数据结构中的各元素的操作,它可以在不改变数据结构的前提下定义作用于这些元素的新的操作。
/19-visitor.png)
访问者模式的优点有:
1. 符合单一职责原则。具体元素角色负责数据的加载,而Vistor类负责报表的展现。
2. 优秀的扩展性。
3. 灵活性非常高。
访问者模式的缺点有具体元素对访问者公布细节,这个并不符合迪米特法则。其次是具体元素的变更比较困难,可能牵扯到多个Vistor的修改。最后是违背了依赖倒置的原则,访问者依赖的是具体元素而不是抽象元素,抛弃了对接口的依赖,这方面的扩展比较难。
在具体实践中,访问者模式还可以用于统计功能,因为访问者可以知道具体元素的所有细节。当然还可以同时存在多个访问者来实现不同的访问功能(展示、汇总等)。
注意谈到访问者模式肯定要谈到双分派,双分派是多分派的一个特例。Java是单分派语言,但可以用访问者模式支持双分派,单分派语言处理一个操作是根据方法执行者的名称(覆写,动态绑定)和方法接收到的参数(重载,静态绑定)决定的。
{% highlight java %}
{% raw %}
// 演员抽象类,方法的执行者,动态绑定,场景类中会举例说明其含义
public abstract class AbsActor {
//重载act方法,方法接收到的参数,静态绑定,场景类中会举例说明其含义
//演员都能够演一个角色
public void act(Role role){
System.out.println("演员可以扮演任何角色");
}
//可以演功夫戏
public void act(KungFuRole role){
System.out.println("演员都可以演功夫角色");
}
}
// 青年演员和老年演员
public class YoungActor extends AbsActor {
//年轻演员最喜欢演功夫戏
public void act(KungFuRole role){
System.out.println("最喜欢演功夫角色");
}
}
public class OldActor extends AbsActor {
//不演功夫角色
public void act(KungFuRole role){
System.out.println("年龄大了,不能演功夫角色");
}
}
//场景类
public class Client {
public static void main(String[] args) {
//定义一个演员
AbsActor actor = new OldActor();
//定义一个角色
Role role = new KungFuRole();
//开始演戏
actor.act(role);
actor.act(new KungFuRole());
}
}
{% endraw %}
{% endhighlight %}
运行结果是什么呢?运行结果如下所示:
{% raw %}
演员可以扮演任何角色
年龄大了,不能演功夫角色
{% endraw %}
重载在编译时就根据传进来的参数决定要调用哪个方法,这是静态绑定,而方法的执行者actor是动态绑定的。
引入访问者模式后,将重载拿掉,全部以动态绑定得到我们期望的结果。
{% highlight java %}
{% raw %}
//AbsActor为访问者,Role为元素
public interface Role {
//演员要扮演的角色
public void accept(AbsActor actor);
}
public class KungFuRole implements Role {
//武功天下第一的角色
public void accept(AbsActor actor){
actor.act(this);
}
}
public class IdiotRole implements Role {
//一个弱智角色,由谁来扮演
public void accept(AbsActor actor){
actor.act(this);
}
}
//场景类
public class Client {
public static void main(String[] args) {
//定义一个演员
AbsActor actor = new OldActor();
//定义一个角色
Role role = new KungFuRole();
//开始演戏
role.accept(actor);
}
}
{% endraw %}
{% endhighlight %}
运行结果如下:
{% raw %}
年龄大了,不能演功夫角色
{% endraw %}
双分派意味着方法的具体执行由执行者的类型和接收参数的类型决定,而单分派是由执行者的名称(编译的时候决定)和接收参数的类型决定,这就是二者的区别,Java是一个支持双分派的单分派语言。
访问者模式的目的是实现功能集中化,如一个统一的报表计算,UI呈现等。
## 第二十六章 状态模式
状态模式指的是允许一个对象在其内部状态改变时改变它的行为,从外部看起来就好像这个对象对应的类发生了改变一样。状态模式是一种对象行为型模式。
/20-state.png)
状态模式由状态角色和环境角色组成。
环境角色有两个不成文的约束,一是把状态对象声明为静态变量,有几个状态角色就声明几个静态变量;二是环境角色具有状态抽象角色定义的行为,具体执行使用委托方式。
状态模式的优点有:
1. 结构清晰,避免了过多的条件语句的使用。
2. 遵循开闭原则和单一职责原则,对扩展开放,对修改关闭。
3. 封装性良好,外部的调用不用知道类内部如何实现状态和行为的变换。
状态模式的缺点是如果状态过多,则会产生太多的子类,出现类膨胀的问题。
状态模式在具体实践中适用于行为随状态改变而改变的场景,作为条件、分支判断语句的替代者。使用的对象的状态最好不超过5个。建造者模式还可以将状态之间的顺序切换再重新组装一下,建造者模式加上状态模式得到一个非常好的封装效果。
## 第二十七章 解释器模式
解释器模式是一种按照规定语法进行解析的方案,在现有的项目中使用较少。给定一门语言,定义它的文法的一种表示(表达式),并定义一个解释器,该解释器使用该表示啦解释语言中的句子。
/21-interpreter.png)
表达式分为终结符表达式(如某个变量,只关心自身的结果)和非终结符表达式(如加减乘除法则,只关心左右或附近表达式的结果),其实就是逐层递归的意思。
解释器模式的优点是扩展性良好,修改语法规则只需要修改相应的非终结表达式就可以了,若扩展语法,则只要增加非终结符类就可以了。
解释器模式的缺点是会容易引起类膨胀,递归调用的方式增加了调试难度,降低了执行效率。
解释器模式的在具体实践中适用于重复发生的问题,如对大量日志文件进行分析处理,由于日志格式不相同,但数据要素是相同的,这便是终结符表达式都相同,而非终结符表达式需要制定。此外,尽量不要在重要的模块中使用解释器模式,否则维护会是一个很大的问题,可以使用shell、JRuby、Groovy等脚本语言代替解释器模式,弥补Java编译型语言的不足。当准备使用解释器模式时,可以考虑Expression4J、MESP(Math Expression String Prser)、Jep等开元的数学解析工具包。
## 第二十八章 享元模式
享元模式(Flyweight Pattern)是池技术的重要实现方式,使用共享对象可有效支持大量的细粒度的对象,从而避免内存溢出。
/22-flyweight.png)
细粒度对象的信息分为两个部分:内部状态(intrinsic)和外部状态(extrinsic)。
内部状态是对象可共享出来的信息,不会随环境的改变而改变,如id,可以作为一个对象的动态附加信息,不必直接存在具体的某个对象中,属于共享的部分。
外部状态是对象得以依赖的一个标记,是随环境改变而改变的,不可共享的状态,如考试科目+考试地点的复合字符串,它是对象的是唯一的索引值。
外部状态一般需要设置为final类型,初始化时一次赋值,避免无意修改导致池混乱,特别是Session级的常量或变量。
享元模式的优点是可以大大减少应用程序创建的对象,降低程序内存的占用,增强程序的性能,但它同时页提高了系统的复杂性,需要分离出外部状态和内部状态,且外部状态不随内部状态改变而改变,否则会导致系统的逻辑混乱。
享元模式在具体实践中适用于系统中存在大量相似对象的情况以及需要缓冲池的场景。在使用中需要注意线程安全的问题,此外尽量使用Java的基本类型作为外部状态,可以大幅提高效率,如果把一个对象作为Map类的键值,一定要确保重写了equals和hashCode方法,只有hashCode值相等,并且equals返回的结果为ture,两个对象的key才相等。
Java中String类的intern方法就使用了享元模式。
虽然使用享元模式可以实现对象池,但是二者还是有比较大的差异。对象池着重在对象的复用上,池中的每个对象是可替换的,从同一个池中获取A对象和B对象对客户端来说是完全相同的,它主要解决“复用”。而享元模式主要解决对象的共享问题,如何建立多个可“共享”的细粒度对象是其关注的重点。
## 第二十九章 桥梁模式
桥梁模式也叫桥接模式,将抽象和实现解耦,使得二者可以独立地变化。抽象化角色(分为抽象类和具体类)引用实现角色(同样分为抽象类和具体类),或者说抽象角色的部分实现是由实现角色完成的。抽象化对象一般在构造函数中指定(聚合)实现对象。
/23-bridge.png)
桥梁模式的优点是将抽象和实现分离,解决继承的缺点,不再绑定在一个固定的抽象层次上,拥有更良好的扩展能力,用户不必关心实现细节。
桥梁模式在具体实践中适用于接口或抽象类不稳定的场景以及重用性较高且颗粒度更细的场景。当发现继承有N层时,可以考虑使用桥梁模式。对于比较明确不发生变化的,则通过继承来完成,若不能确定是否会发生变化的,则可以通过桥梁模式来完成。
---
The End.
zhlinh
Email: zhlinhng@gmail.com
2017-11-05
| Java |
<?php
/**
* Rule for required elements
*
* PHP version 5
*
* LICENSE:
*
* Copyright (c) 2006-2010, Alexey Borzov <avb@php.net>,
* Bertrand Mansion <golgote@mamasam.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category HTML
* @package HTML_QuickForm2
* @author Alexey Borzov <avb@php.net>
* @author Bertrand Mansion <golgote@mamasam.com>
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version SVN: $Id: Required.php 294057 2010-01-26 21:10:28Z avb $
* @link http://pear.php.net/package/HTML_QuickForm2
*/
/**
* Rule checking that the form field is not empty
*/
require_once 'HTML/QuickForm2/Rule/Nonempty.php';
/**
* Rule for required elements
*
* The main difference from "nonempty" Rule is that
* - elements to which this Rule is attached will be considered required
* ({@link HTML_QuickForm2_Node::isRequired()} will return true for them) and
* marked accordingly when outputting the form
* - this Rule can only be added directly to the element and other Rules can
* only be added to it via and_() method
*
* @category HTML
* @package HTML_QuickForm2
* @author Alexey Borzov <avb@php.net>
* @author Bertrand Mansion <golgote@mamasam.com>
* @version Release: 0.4.0
*/
class HTML_QuickForm2_Rule_Required extends HTML_QuickForm2_Rule_Nonempty
{
/**
* Disallows adding a rule to the chain with an "or" operator
*
* Required rules are different from all others because they affect the
* visual representation of an element ("* denotes required field").
* Therefore we cannot allow chaining other rules to these via or_(), since
* this will effectively mean that the field is not required anymore and the
* visual difference is bogus.
*
* @param HTML_QuickForm2_Rule
* @throws HTML_QuickForm2_Exception
*/
public function or_(HTML_QuickForm2_Rule $next)
{
throw new HTML_QuickForm2_Exception(
'or_(): Cannot add a rule to "required" rule'
);
}
}
?>
| Java |
class String
def split_on_unescaped(str)
self.split(/\s*(?<!\\)#{str}\s*/).map{|s| s.gsub(/\\(?=#{str})/, '') }
end
end
| Java |
import axios from 'axios';
import { updateRadius } from './radius-reducer';
import { AddBType } from './b-type-reducer';
// import { create as createUser } from './users';
// import history from '../history';
/* ------------------ ACTIONS --------------------- */
const ADD_B_TYPE = 'ADD_B_TYPE';
const ADD_LNG_LAT = 'ADD_LNG_LAT';
const UPDATE_RADIUS = 'UPDATE_RADIUS';
const SWITCH_MEASUREMENT = 'SWITCH_MEASUREMENT';
/* -------------- ACTION CREATORS ----------------- */
export const addLngLat = (latitude, longitude) => ({
type: ADD_LNG_LAT,
latitude,
longitude
});
export const switchMeasurement = measurement => ({
type: SWITCH_MEASUREMENT,
measurement
});
/* ------------------ REDUCER --------------------- */
export default function reducer (state = {
latitude: null,
longitude: null,
radius: null,
businessType: null,
distanceMeasurement: 'miles'
}, action) {
switch (action.type) {
case ADD_B_TYPE:
state.businessType = action.typeStr;
break;
case ADD_LNG_LAT:
state.latitude = action.latitude;
state.longitude = action.longitude;
break;
case UPDATE_RADIUS:
state.radius = action.radInt;
break;
case SWITCH_MEASUREMENT:
state.distanceMeasurement = action.measurement;
break;
default:
return state;
}
return state;
}
| Java |
<h4>Lists</h4>
<h5>Simple List</h5>
<mdl-list>
<mdl-list-item>
<mdl-list-item-primary-content>
Bryan Cranston
</mdl-list-item-primary-content>
</mdl-list-item>
<mdl-list-item>
<mdl-list-item-primary-content>
Aaron Paul
</mdl-list-item-primary-content>
</mdl-list-item>
<mdl-list-item>
<mdl-list-item-primary-content>
Bob Odenkirk
</mdl-list-item-primary-content>
</mdl-list-item>
</mdl-list>
<pre prism>
<![CDATA[
<mdl-list>
<mdl-list-item>
<mdl-list-item-primary-content>
Bryan Cranston
</mdl-list-item-primary-content>
</mdl-list-item>
<mdl-list-item>
<mdl-list-item-primary-content>
Aaron Paul
</mdl-list-item-primary-content>
</mdl-list-item>
<mdl-list-item>
<mdl-list-item-primary-content>
Bob Odenkirk
</mdl-list-item-primary-content>
</mdl-list-item>
</mdl-list>
]]>
</pre>
<h5>Icons</h5>
<mdl-list>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-icon>person</mdl-icon>
Bryan Cranston
</mdl-list-item-primary-content>
</mdl-list-item>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-icon>person</mdl-icon>
Aaron Paul
</mdl-list-item-primary-content>
</mdl-list-item>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-icon>person</mdl-icon>
Bob Odenkirk
</mdl-list-item-primary-content>
</mdl-list-item>
</mdl-list>
<pre prism>
<![CDATA[
<mdl-list>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-icon>person</mdl-icon>
Bryan Cranston
</mdl-list-item-primary-content>
</mdl-list-item>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-icon>person</mdl-icon>
Aaron Paul
</mdl-list-item-primary-content>
</mdl-list-item>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-icon>person</mdl-icon>
Bob Odenkirk
</mdl-list-item-primary-content>
</mdl-list-item>
</mdl-list>
]]>
</pre>
<h5>Avatars and actions</h5>
<mdl-list>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Bryan Cranston</span>
</mdl-list-item-primary-content>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Aaron Paul</span>
</mdl-list-item-primary-content>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Bob Odenkirk</span>
</mdl-list-item-primary-content>
<mdl-list-item-secondary-content>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item-secondary-content>
</mdl-list-item>
</mdl-list>
<pre prism>
<![CDATA[
<mdl-list>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Bryan Cranston</span>
</mdl-list-item-primary-content>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Aaron Paul</span>
</mdl-list-item-primary-content>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Bob Odenkirk</span>
</mdl-list-item-primary-content>
<mdl-list-item-secondary-content>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item-secondary-content>
</mdl-list-item>
</mdl-list>
]]>
</pre>
<h5>Avatars and controls</h5>
<mdl-list>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
Bryan Cranston
</mdl-list-item-primary-content>
<mdl-list-item-secondary-action>
<mdl-checkbox mdl-ripple></mdl-checkbox>
</mdl-list-item-secondary-action>
</mdl-list-item>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
Aaron Paul
</mdl-list-item-primary-content>
<mdl-list-item-secondary-action>
<mdl-radio ngModel="false" mdl-ripple></mdl-radio>
</mdl-list-item-secondary-action>
</mdl-list-item>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
Bob Odenkirk
</mdl-list-item-primary-content>
<mdl-list-item-secondary-action>
<mdl-switch mdl-ripple></mdl-switch>
</mdl-list-item-secondary-action>
</mdl-list-item>
</mdl-list>
<pre prism>
<![CDATA[
<style>
mdl-radio, mdl-checkbox, mdl-switch {
display: inline;
}
</style>
<mdl-list>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
Bryan Cranston
</mdl-list-item-primary-content>
<mdl-list-item-secondary-action>
<mdl-checkbox mdl-ripple></mdl-checkbox>
</mdl-list-item-secondary-action>
</mdl-list-item>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
Aaron Paul
</mdl-list-item-primary-content>
<mdl-list-item-secondary-action>
<mdl-radio ngModel="false" mdl-ripple></mdl-radio>
</mdl-list-item-secondary-action>
</mdl-list-item>
<mdl-list-item>
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
Bob Odenkirk
</mdl-list-item-primary-content>
<mdl-list-item-secondary-action>
<mdl-switch mdl-ripple></mdl-switch>
</mdl-list-item-secondary-action>
</mdl-list-item>
</mdl-list>
]]>
</pre>
<h5>Two line</h5>
<mdl-list>
<mdl-list-item lines="2">
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Bryan Cranston</span>
<mdl-list-item-sub-title>62 Episodes</mdl-list-item-sub-title>
</mdl-list-item-primary-content>
<mdl-list-item-secondary-content>
<mdl-list-item-secondary-info>Actor</mdl-list-item-secondary-info>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item-secondary-content>
</mdl-list-item>
<mdl-list-item lines="2">
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Aaron Paul</span>
<mdl-list-item-sub-title>62 Episodes</mdl-list-item-sub-title>
</mdl-list-item-primary-content>
<mdl-list-item-secondary-content>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item-secondary-content>
</mdl-list-item>
<mdl-list-item lines="2">
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Bob Odenkirk</span>
<mdl-list-item-sub-title>62 Episodes</mdl-list-item-sub-title>
</mdl-list-item-primary-content>
<mdl-list-item-secondary-content>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item-secondary-content>
</mdl-list-item>
</mdl-list>
<pre prism>
<![CDATA[
<mdl-list>
<mdl-list-item lines="2">
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Bryan Cranston</span>
<mdl-list-item-sub-title>62 Episodes</mdl-list-item-sub-title>
</mdl-list-item-primary-content>
<mdl-list-item-secondary-content>
<mdl-list-item-secondary-info>Actor</mdl-list-item-secondary-info>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item-secondary-content>
</mdl-list-item>
<mdl-list-item lines="2">
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Aaron Paul</span>
<mdl-list-item-sub-title>62 Episodes</mdl-list-item-sub-title>
</mdl-list-item-primary-content>
<mdl-list-item-secondary-content>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item-secondary-content>
</mdl-list-item>
<mdl-list-item lines="2">
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Bob Odenkirk</span>
<mdl-list-item-sub-title>62 Episodes</mdl-list-item-sub-title>
</mdl-list-item-primary-content>
<mdl-list-item-secondary-content>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item-secondary-content>
</mdl-list-item>
</mdl-list>
]]>
</pre>
<h5>Three line</h5>
<mdl-list style="width:650px">
<mdl-list-item lines="3">
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Bryan Cranston</span>
<mdl-list-item-text-body>
Bryan Cranston played the role of Walter in Breaking Bad. He is also known
for playing Hal in Malcom in the Middle.
</mdl-list-item-text-body>
</mdl-list-item-primary-content>
<mdl-list-item-secondary-content>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item-secondary-content>
</mdl-list-item>
<mdl-list-item lines="3">
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Aaron Paul</span>
<mdl-list-item-text-body>
Aaron Paul played the role of Jesse in Breaking Bad. He also featured in
the "Need For Speed" Movie.
</mdl-list-item-text-body>
</mdl-list-item-primary-content>
<mdl-list-item-secondary-content>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item-secondary-content>
</mdl-list-item>
<mdl-list-item lines="3">
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Bob Odenkirk</span>
<mdl-list-item-text-body>
Bob Odinkrik played the role of Saul in Breaking Bad. Due to public fondness for the
character, Bob stars in his own show now, called "Better Call Saul".
</mdl-list-item-text-body>
</mdl-list-item-primary-content>
<mdl-list-item-secondary-content>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item-secondary-content>
</mdl-list-item>
</mdl-list>
<pre prism>
<![CDATA[
<mdl-list style="width:650px">
<mdl-list-item lines="3">
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Bryan Cranston</span>
<mdl-list-item-text-body>
Bryan Cranston played the role of Walter in Breaking Bad. He is also known
for playing Hal in Malcom in the Middle.
</mdl-list-item-text-body>
</mdl-list-item-primary-content>
<mdl-list-item-secondary-content>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item-secondary-content>
</mdl-list-item>
<mdl-list-item lines="3">
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Aaron Paul</span>
<mdl-list-item-text-body>
Aaron Paul played the role of Jesse in Breaking Bad. He also featured in
the "Need For Speed" Movie.
</mdl-list-item-text-body>
</mdl-list-item-primary-content>
<mdl-list-item-secondary-content>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item-secondary-content>
</mdl-list-item>
<mdl-list-item lines="3">
<mdl-list-item-primary-content>
<mdl-icon mdl-list-item-avatar>person</mdl-icon>
<span>Bob Odenkirk</span>
<mdl-list-item-text-body>
Bob Odinkrik played the role of Saul in Breaking Bad. Due to public fondness for the
character, Bob stars in his own show now, called "Better Call Saul".
</mdl-list-item-text-body>
</mdl-list-item-primary-content>
<mdl-list-item-secondary-content>
<a href="#"><mdl-icon>star</mdl-icon></a>
</mdl-list-item-secondary-content>
</mdl-list-item>
</mdl-list>
]]>
</pre>
<h5> List components</h5>
<table class="docu" mdl-shadow="2">
<thead>
<tr>
<th>Component</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>mdl-list</td>
<td>
Basic container for any <i>mdl-list</i> component.
</td>
</tr>
<tr>
<td>mdl-list-item</td>
<td>
Defines a item in the list. The attribute <i>lines</i> will be used to specify of how many individual lines a list item consist.
You can use <i>1</i>, <i>2</i> and <i>3</i>. <i>1</i> is the default value.
</td>
</tr>
<tr>
<td>mdl-list-item-primary-content</td>
<td>
Defines the primary content sub-division.
</td>
</tr>
<tr>
<td>mdl-list-item-secondary-action</td>
<td>
Defines the Action sub-division. Needs a 2 or 3 line list-item.
</td>
</tr>
<tr>
<td>mdl-list-item-secondary-content</td>
<td>
Defines the secondary content sub-division. Needs a 2 or 3 line list-item.
</td>
</tr>
<tr>
<td>mdl-list-item-secondary-info</td>
<td>
Defines the information sub-division. Needs a 2 or 3 line list-item.
</td>
</tr>
<tr>
<td>mdl-list-item-sub-title</td>
<td>
Defines the sub title in the <i>mdl-list-item-primary-content</i> component.
</td>
</tr>
<tr>
<td>mdl-list-item-text-body</td>
<td>
Defines the text-section in the <i>mdl-list-item-primary-content</i> component.
</td>
</tr>
</tbody>
</table>
<h5>Additional attributes for mdl-icon</h5>
<p>These attributes can be used to style <i>mdl-icons</i> in lists</p>
<table class="docu" mdl-shadow="2">
<thead>
<tr>
<th>Attribute</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>mdl-list-item-avatar></td>
<td>
avatar icon.
</td>
</tr>
<tr>
<td>mdl-list-item-icon</td>
<td>
Small icon.
</td>
</tr>
<tr>
<td>mdl-ripple</td>
<td>Add <i>mdl-ripple</i> to the <i>mdl-list-item</i> component to create a ripple effect.</td>
</tr>
</tbody>
</table>
| Java |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace RS.TimeLogger {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.1.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string LastUser {
get {
return ((string)(this["LastUser"]));
}
set {
this["LastUser"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("00000000-0000-0000-0000-000000000000")]
public global::System.Guid LastActivity {
get {
return ((global::System.Guid)(this["LastActivity"]));
}
set {
this["LastActivity"] = value;
}
}
}
}
| Java |
module Softlayer
module User
class Customer
module Access
autoload :Authentication, 'softlayer/user/customer/access/authentication'
end
end
end
end
| Java |
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'module', 'skatejs'], factory);
} else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
factory(exports, module, require('skatejs'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, mod, global.skate);
global.skate = mod.exports;
}
})(this, function (exports, module, _skatejs) {
'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _skate = _interopRequireDefault(_skatejs);
var auiSkate = _skate['default'].noConflict();
module.exports = auiSkate;
});
//# sourceMappingURL=../../../js/aui/internal/skate.js.map | Java |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIButton : MonoBehaviour {
[SerializeField] private GameObject targetObject;
[SerializeField] private string targetMessage;
public Color highlightColor = Color.cyan;
public void OnMouseOver() {
SpriteRenderer sprite = GetComponent<SpriteRenderer>();
if (sprite != null) {
sprite.color = highlightColor;
}
}
public void OnMouseExit() {
SpriteRenderer sprite = GetComponent<SpriteRenderer>();
if (sprite != null) {
sprite.color = Color.white;
}
}
public void OnMouseDown() {
transform.localScale *= 1.1f;
}
public void OnMouseUp() {
transform.localScale = Vector3.one;
if (targetObject != null) {
targetObject.SendMessage(targetMessage);
}
}
}
| Java |
<footer class="main-footer">
<div class="pull-right hidden-xs">
</div>
<strong>Orange TV.</strong> All rights reserved.
</footer>
<!-- Control Sidebar -->
<!-- /.control-sidebar -->
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->
<!-- jQuery 2.2.3 -->
<script src="assets/plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
$.widget.bridge('uibutton', $.ui.button);
</script>
<!-- DataTables -->
<script src="assets/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="assets/plugins/datatables/dataTables.bootstrap.min.js"></script>
<!--<script src="assets/plugins/ckeditor/adapters/jquery.js"></script>-->
<!-- Bootstrap 3.3.6 -->
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<!-- <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> -->
<!-- Morris.js charts -->
<!--
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="assets/plugins/morris/morris.min.js"></script>
-->
<!-- Sparkline -->
<script src="assets/plugins/sparkline/jquery.sparkline.min.js"></script>
<!-- jvectormap -->
<script src="assets/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="assets/plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<!-- jQuery Knob Chart -->
<script src="assets/plugins/knob/jquery.knob.js"></script>
<!-- daterangepicker -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
<script src="assets/plugins/daterangepicker/daterangepicker.js"></script>
<!-- datepicker -->
<script src="assets/plugins/datepicker/bootstrap-datepicker.js"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src="assets/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<!-- Slimscroll -->
<script src="assets/plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="assets/plugins/fastclick/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="assets/dist/js/app.min.js"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<!--<script src="assets/dist/js/pages/dashboard.js"></script>-->
<!-- AdminLTE for demo purposes -->
<script src="assets/dist/js/demo.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.flash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
<!--
<script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/pdfmake.min.js"></script>
<script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/vfs_fonts.js"></script>
-->
<script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.print.min.js"></script>
<script src="assets/dist/js/custom.js"></script>
<script>
$(function () {
/*
var table = $('#example').DataTable( {
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
]
} );
table.buttons().container()
.appendTo( $('div.eight.column:eq(0)', table.table().container()) );
$('#example2').DataTable( {
buttons: [
{
extend: 'excel',
text: 'Save current page',
exportOptions: {
modifier: {
page: 'current'
}
}
}
]
} );
*/
$('#example').DataTable( {
dom: 'Bfrtip',
pageLength: 5,
//dom : 'Bflit',
buttons: ['copy', 'csv', 'excel', 'pdf', 'print'],
responsive: true
} );
$("#example1").DataTable();
$("#example2").DataTable({
"paging": false
});
$('#example3').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false
});
$('#example30').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false
});
});
// datatable paging
$(function() {
table = $('#example2c').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php if(isset($url)) {echo $url; } ?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ 0 ], //first column / numbering column
"orderable": false, //set not orderable
},
],
});
});
</script>
</body>
</html>
| Java |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Neo.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Strings {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Strings() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Neo.Properties.Strings", typeof(Strings).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to About.
/// </summary>
internal static string About {
get {
return ResourceManager.GetString("About", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to AntShares.
/// </summary>
internal static string AboutMessage {
get {
return ResourceManager.GetString("AboutMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Version:.
/// </summary>
internal static string AboutVersion {
get {
return ResourceManager.GetString("AboutVersion", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to add smart contract, corresponding private key missing in this wallet..
/// </summary>
internal static string AddContractFailedMessage {
get {
return ResourceManager.GetString("AddContractFailedMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Address.
/// </summary>
internal static string Address {
get {
return ResourceManager.GetString("Address", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change password successful..
/// </summary>
internal static string ChangePasswordSuccessful {
get {
return ResourceManager.GetString("ChangePasswordSuccessful", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Confirmation.
/// </summary>
internal static string DeleteAddressConfirmationCaption {
get {
return ResourceManager.GetString("DeleteAddressConfirmationCaption", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Upon deletion, assets in these addresses will be permanently lost, are you sure to proceed?.
/// </summary>
internal static string DeleteAddressConfirmationMessage {
get {
return ResourceManager.GetString("DeleteAddressConfirmationMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Assets cannot be recovered once deleted, are you sure to delete the assets?.
/// </summary>
internal static string DeleteAssetConfirmationMessage {
get {
return ResourceManager.GetString("DeleteAssetConfirmationMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Confirmation.
/// </summary>
internal static string DeleteConfirmation {
get {
return ResourceManager.GetString("DeleteConfirmation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Enter remark here, which will be recorded on the blockchain.
/// </summary>
internal static string EnterRemarkMessage {
get {
return ResourceManager.GetString("EnterRemarkMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transaction Remark.
/// </summary>
internal static string EnterRemarkTitle {
get {
return ResourceManager.GetString("EnterRemarkTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Execution terminated in fault state..
/// </summary>
internal static string ExecutionFailed {
get {
return ResourceManager.GetString("ExecutionFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Expired.
/// </summary>
internal static string ExpiredCertificate {
get {
return ResourceManager.GetString("ExpiredCertificate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed.
/// </summary>
internal static string Failed {
get {
return ResourceManager.GetString("Failed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import Watch-Only Address.
/// </summary>
internal static string ImportWatchOnlyAddress {
get {
return ResourceManager.GetString("ImportWatchOnlyAddress", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transaction initiated, but the signature is incomplete..
/// </summary>
internal static string IncompletedSignatureMessage {
get {
return ResourceManager.GetString("IncompletedSignatureMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Incomplete signature.
/// </summary>
internal static string IncompletedSignatureTitle {
get {
return ResourceManager.GetString("IncompletedSignatureTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You have cancelled the certificate installation..
/// </summary>
internal static string InstallCertificateCancel {
get {
return ResourceManager.GetString("InstallCertificateCancel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Install the certificate.
/// </summary>
internal static string InstallCertificateCaption {
get {
return ResourceManager.GetString("InstallCertificateCaption", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Anthares must install Onchain root certificate to validate assets on the blockchain, install it now?.
/// </summary>
internal static string InstallCertificateText {
get {
return ResourceManager.GetString("InstallCertificateText", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Insufficient funds, transaction cannot be initiated..
/// </summary>
internal static string InsufficientFunds {
get {
return ResourceManager.GetString("InsufficientFunds", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid.
/// </summary>
internal static string InvalidCertificate {
get {
return ResourceManager.GetString("InvalidCertificate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Migrate Wallet.
/// </summary>
internal static string MigrateWalletCaption {
get {
return ResourceManager.GetString("MigrateWalletCaption", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Opening wallet files in older versions, update to newest format?
///Note: updated files cannot be openned by clients in older versions!.
/// </summary>
internal static string MigrateWalletMessage {
get {
return ResourceManager.GetString("MigrateWalletMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Wallet file relocated. New wallet file has been saved at: .
/// </summary>
internal static string MigrateWalletSucceedMessage {
get {
return ResourceManager.GetString("MigrateWalletSucceedMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Password Incorrect.
/// </summary>
internal static string PasswordIncorrect {
get {
return ResourceManager.GetString("PasswordIncorrect", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data broadcast success, the hash is shown as follows:.
/// </summary>
internal static string RelaySuccessText {
get {
return ResourceManager.GetString("RelaySuccessText", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Broadcast Success.
/// </summary>
internal static string RelaySuccessTitle {
get {
return ResourceManager.GetString("RelaySuccessTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Raw:.
/// </summary>
internal static string RelayTitle {
get {
return ResourceManager.GetString("RelayTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transaction sent, TXID:.
/// </summary>
internal static string SendTxSucceedMessage {
get {
return ResourceManager.GetString("SendTxSucceedMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transaction successful.
/// </summary>
internal static string SendTxSucceedTitle {
get {
return ResourceManager.GetString("SendTxSucceedTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The private key that can sign the data is not found..
/// </summary>
internal static string SigningFailedKeyNotFoundMessage {
get {
return ResourceManager.GetString("SigningFailedKeyNotFoundMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must input JSON object pending signature data..
/// </summary>
internal static string SigningFailedNoDataMessage {
get {
return ResourceManager.GetString("SigningFailedNoDataMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to System.
/// </summary>
internal static string SystemIssuer {
get {
return ResourceManager.GetString("SystemIssuer", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Validation failed, the counterparty falsified the transaction content!.
/// </summary>
internal static string TradeFailedFakeDataMessage {
get {
return ResourceManager.GetString("TradeFailedFakeDataMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Validation failed, the counterparty generated illegal transaction content!.
/// </summary>
internal static string TradeFailedInvalidDataMessage {
get {
return ResourceManager.GetString("TradeFailedInvalidDataMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Validation failed, invalid transaction or unsynchronized blockchain, please try again when synchronized!.
/// </summary>
internal static string TradeFailedNoSyncMessage {
get {
return ResourceManager.GetString("TradeFailedNoSyncMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Need Signature.
/// </summary>
internal static string TradeNeedSignatureCaption {
get {
return ResourceManager.GetString("TradeNeedSignatureCaption", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transaction generated, please send the following information to the counterparty for signing:.
/// </summary>
internal static string TradeNeedSignatureMessage {
get {
return ResourceManager.GetString("TradeNeedSignatureMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Trade Request.
/// </summary>
internal static string TradeRequestCreatedCaption {
get {
return ResourceManager.GetString("TradeRequestCreatedCaption", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transaction request generated, please send it to the counterparty or merge it with the counterparty's request..
/// </summary>
internal static string TradeRequestCreatedMessage {
get {
return ResourceManager.GetString("TradeRequestCreatedMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Trade Success.
/// </summary>
internal static string TradeSuccessCaption {
get {
return ResourceManager.GetString("TradeSuccessCaption", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transaction sent, this is the TXID:.
/// </summary>
internal static string TradeSuccessMessage {
get {
return ResourceManager.GetString("TradeSuccessMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to unconfirmed.
/// </summary>
internal static string Unconfirmed {
get {
return ResourceManager.GetString("Unconfirmed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to unknown issuer.
/// </summary>
internal static string UnknownIssuer {
get {
return ResourceManager.GetString("UnknownIssuer", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Blockchain unsynchronized, transaction cannot be sent..
/// </summary>
internal static string UnsynchronizedBlock {
get {
return ResourceManager.GetString("UnsynchronizedBlock", resourceCulture);
}
}
}
}
| Java |
# Velocity
Library last modified: 5/1/2019 9:00 AM.
A reusable library in Velocity for Cascade with examples. This is the code base the Upstate team use to implement our Brisk site.
The other part of the Upstate library: https://github.com/drulykg/Cascade-CMS/tree/master/_brisk
A note about filenames. All files whose filenames with a "chanw-" prefix contain code reusable by anyone. Those with the "upstate-" prefix contain business logic specific to Upstate.
<ul>
<li>
<a href="http://www.upstate.edu/formats/velocity/courses/index.php">Velocity Tutorial</a></li>
<li><a href="https://www.youtube.com/playlist?list=PL5FL7lAbKiG-AYX35qK8y0FN7RgJl9ISD">Velocity and More</a> recordings</li>
<li><a href="https://www.youtube.com/playlist?list=PLiPcpR6GRx5dN3Z5-tAAMLgFX59Njkv6f">One Template, One Region, and Lots of Velocity Tricks</a></li>
<li><a href="http://www.upstate.edu/formats/velocity/api-documentation/index.php">API Documentation</a></li>
</ul> | Java |
using Newtonsoft.Json;
using System.Collections.Generic;
namespace EaToGliffy.Gliffy.Model
{
public class GliffyParentObject : GliffyObject
{
[JsonProperty(PropertyName = "children")]
public List<GliffyObject> Children { get; set; }
}
}
| Java |
// Copyright (c) 2011-2015 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "JsonOutputStreamSerializer.h"
#include <cassert>
#include <stdexcept>
#include "Common/StringTools.h"
using Common::JsonValue;
using namespace CryptoNote;
namespace CryptoNote {
std::ostream& operator<<(std::ostream& out, const JsonOutputStreamSerializer& enumerator) {
out << enumerator.root;
return out;
}
}
namespace {
template <typename T>
void insertOrPush(JsonValue& js, Common::StringView name, const T& value) {
if (js.isArray()) {
js.pushBack(JsonValue(value));
} else {
js.insert(std::string(name), JsonValue(value));
}
}
}
JsonOutputStreamSerializer::JsonOutputStreamSerializer() : root(JsonValue::OBJECT) {
chain.push_back(&root);
}
JsonOutputStreamSerializer::~JsonOutputStreamSerializer() {
}
ISerializer::SerializerType JsonOutputStreamSerializer::type() const {
return ISerializer::OUTPUT;
}
bool JsonOutputStreamSerializer::beginObject(Common::StringView name) {
JsonValue& parent = *chain.back();
JsonValue obj(JsonValue::OBJECT);
if (parent.isObject()) {
chain.push_back(&parent.insert(std::string(name), obj));
} else {
chain.push_back(&parent.pushBack(obj));
}
return true;
}
void JsonOutputStreamSerializer::endObject() {
assert(!chain.empty());
chain.pop_back();
}
bool JsonOutputStreamSerializer::beginArray(size_t& size, Common::StringView name) {
JsonValue val(JsonValue::ARRAY);
JsonValue& res = chain.back()->insert(std::string(name), val);
chain.push_back(&res);
return true;
}
void JsonOutputStreamSerializer::endArray() {
assert(!chain.empty());
chain.pop_back();
}
bool JsonOutputStreamSerializer::operator()(uint64_t& value, Common::StringView name) {
int64_t v = static_cast<int64_t>(value);
return operator()(v, name);
}
bool JsonOutputStreamSerializer::operator()(uint16_t& value, Common::StringView name) {
uint64_t v = static_cast<uint64_t>(value);
return operator()(v, name);
}
bool JsonOutputStreamSerializer::operator()(int16_t& value, Common::StringView name) {
int64_t v = static_cast<int64_t>(value);
return operator()(v, name);
}
bool JsonOutputStreamSerializer::operator()(uint32_t& value, Common::StringView name) {
uint64_t v = static_cast<uint64_t>(value);
return operator()(v, name);
}
bool JsonOutputStreamSerializer::operator()(int32_t& value, Common::StringView name) {
int64_t v = static_cast<int64_t>(value);
return operator()(v, name);
}
bool JsonOutputStreamSerializer::operator()(int64_t& value, Common::StringView name) {
insertOrPush(*chain.back(), name, value);
return true;
}
bool JsonOutputStreamSerializer::operator()(double& value, Common::StringView name) {
insertOrPush(*chain.back(), name, value);
return true;
}
bool JsonOutputStreamSerializer::operator()(std::string& value, Common::StringView name) {
insertOrPush(*chain.back(), name, value);
return true;
}
bool JsonOutputStreamSerializer::operator()(uint8_t& value, Common::StringView name) {
insertOrPush(*chain.back(), name, static_cast<int64_t>(value));
return true;
}
bool JsonOutputStreamSerializer::operator()(bool& value, Common::StringView name) {
insertOrPush(*chain.back(), name, value);
return true;
}
bool JsonOutputStreamSerializer::binary(void* value, size_t size, Common::StringView name) {
std::string hex = Common::toHex(value, size);
return (*this)(hex, name);
}
bool JsonOutputStreamSerializer::binary(std::string& value, Common::StringView name) {
return binary(const_cast<char*>(value.data()), value.size(), name);
}
| Java |
# Be sure to restart your server when you modify this file.
Refinery::Application.config.session_store :cookie_store, :key => '_skwarcan_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# Refinery::Application.config.session_store :active_record_store
| Java |
/*
* author: Lisa
* Info: Base64 / UTF8
* 编码 & 解码
*/
function base64Encode(input) {
var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "=";
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
do {
chr1 = input[i++];
chr2 = input[i++];
chr3 = input[i++];
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
keyStr.charAt(enc1) +
keyStr.charAt(enc2) +
keyStr.charAt(enc3) +
keyStr.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
}
function base64Decode(input) {
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
var base64test = /[^A-Za-z0-9/+///=]/g;
if (base64test.exec(input)) {
alert("There were invalid base64 characters in the input text./n" +
"Valid base64 characters are A-Z, a-z, 0-9, '+', '/', and '='/n" +
"Expect errors in decoding.");
}
input = input.replace(/[^A-Za-z0-9/+///=]/g, "");
output=new Array();
do {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output.push(chr1);
if (enc3 != 64) {
output.push(chr2);
}
if (enc4 != 64) {
output.push(chr3);
}
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
}
function UTF8Encode(str){
var temp = "",rs = "";
for( var i=0 , len = str.length; i < len; i++ ){
temp = str.charCodeAt(i).toString(16);
rs += "\\u"+ new Array(5-temp.length).join("0") + temp;
}
return rs;
}
function UTF8Decode(str){
return str.replace(/(\\u)(\w{4}|\w{2})/gi, function($0,$1,$2){
return String.fromCharCode(parseInt($2,16));
});
}
exports.base64Encode = base64Encode;
exports.base64Decode = base64Decode;
exports.UTF8Encode = UTF8Encode;
exports.UTF8Decode = UTF8Decode;
| Java |
<?php namespace ShinyDeploy\Domain\Database;
use ShinyDeploy\Core\Crypto\PasswordCrypto;
use ShinyDeploy\Core\Helper\StringHelper;
use ShinyDeploy\Exceptions\DatabaseException;
use ShinyDeploy\Exceptions\MissingDataException;
use ShinyDeploy\Traits\CryptableDomain;
class ApiKeys extends DatabaseDomain
{
use CryptableDomain;
/**
* Generates new API key and stores it to database.
*
* @param int $deploymentId
* @throws DatabaseException
* @throws MissingDataException
* @throws \ShinyDeploy\Exceptions\CryptographyException
* @return array
*/
public function addApiKey(int $deploymentId): array
{
if (empty($this->encryptionKey)) {
throw new MissingDataException('Encryption key not set.');
}
if (empty($deploymentId)) {
throw new MissingDataException('Deployment id can not be empty.');
}
$apiKey = StringHelper::getRandomString(20);
$passwordForUrl = StringHelper::getRandomString(16);
$password = $passwordForUrl . $this->config->get('auth.secret');
$passwordHash = hash('sha256', $password);
$encryption = new PasswordCrypto();
$encryptionKeySave = $encryption->encrypt($this->encryptionKey, $password);
$statement = "INSERT INTO api_keys (`api_key`,`deployment_id`,`password`,`encryption_key`)"
. " VALUES (%s,%i,%s,%s)";
$result = $this->db->prepare($statement, $apiKey, $deploymentId, $passwordHash, $encryptionKeySave)->execute();
if ($result === false) {
throw new DatabaseException('Could not store API key to database.');
}
return [
'apiKey' => $apiKey,
'apiPassword' => $passwordForUrl
];
}
/**
* Deletes all existing API keys for specified deployment.
*
* @param int $deploymentId
* @throws MissingDataException
* @return bool
*/
public function deleteApiKeysByDeploymentId(int $deploymentId): bool
{
if (empty($deploymentId)) {
throw new MissingDataException('Deployment id can not be empty.');
}
try {
$statement = "DELETE FROM api_keys WHERE `deployment_id` = %i";
return $this->db->prepare($statement, $deploymentId)->execute();
} catch (DatabaseException $e) {
return false;
}
}
/**
* Fetches API key data by api-key.
*
* @param string $apiKey
* @return array
* @throws MissingDataException
* @throws DatabaseException
*/
public function getDataByApiKey(string $apiKey): array
{
if (empty($apiKey)) {
throw new MissingDataException('API key can not be empty.');
}
$statement = "SELECT * FROM api_keys WHERE `api_key` = %s";
return $this->db->prepare($statement, $apiKey)->getResult();
}
}
| Java |
require File.dirname(__FILE__) + '/../spec_helper'
describe "Standard Tags" do
dataset :users_and_pages, :file_not_found, :snippets
it '<r:page> should allow access to the current page' do
page(:home)
page.should render('<r:page:title />').as('Home')
page.should render(%{<r:find url="/radius"><r:title /> | <r:page:title /></r:find>}).as('Radius | Home')
end
[:breadcrumb, :slug, :title, :url].each do |attr|
it "<r:#{attr}> should render the '#{attr}' attribute" do
value = page.send(attr)
page.should render("<r:#{attr} />").as(value.to_s)
end
end
it "<r:url> with a nil relative URL root should scope to the relative root of /" do
ActionController::Base.relative_url_root = nil
page(:home).should render("<r:url />").as("/")
end
it '<r:url> with a relative URL root should scope to the relative root' do
page(:home).should render("<r:url />").with_relative_root("/foo").as("/foo/")
end
it '<r:parent> should change the local context to the parent page' do
page(:parent)
page.should render('<r:parent><r:title /></r:parent>').as(pages(:home).title)
page.should render('<r:parent><r:children:each by="title"><r:title /></r:children:each></r:parent>').as(page_eachable_children(pages(:home)).collect(&:title).join(""))
page.should render('<r:children:each><r:parent:title /></r:children:each>').as(@page.title * page.children.count)
end
it '<r:if_parent> should render the contained block if the current page has a parent page' do
page.should render('<r:if_parent>true</r:if_parent>').as('true')
page(:home).should render('<r:if_parent>true</r:if_parent>').as('')
end
it '<r:unless_parent> should render the contained block unless the current page has a parent page' do
page.should render('<r:unless_parent>true</r:unless_parent>').as('')
page(:home).should render('<r:unless_parent>true</r:unless_parent>').as('true')
end
it '<r:if_children> should render the contained block if the current page has child pages' do
page(:home).should render('<r:if_children>true</r:if_children>').as('true')
page(:childless).should render('<r:if_children>true</r:if_children>').as('')
end
it '<r:unless_children> should render the contained block if the current page has no child pages' do
page(:home).should render('<r:unless_children>true</r:unless_children>').as('')
page(:childless).should render('<r:unless_children>true</r:unless_children>').as('true')
end
describe "<r:children:each>" do
it "should iterate through the children of the current page" do
page(:parent)
page.should render('<r:children:each><r:title /> </r:children:each>').as('Child Child 2 Child 3 ')
page.should render('<r:children:each><r:page><r:slug />/<r:child:slug /> </r:page></r:children:each>').as('parent/child parent/child-2 parent/child-3 ')
page(:assorted).should render(page_children_each_tags).as('a b c d e f g h i j ')
end
it 'should not list draft pages' do
page.should render('<r:children:each by="title"><r:slug /> </r:children:each>').as('a b c d e f g h i j ')
end
it 'should include draft pages with status="all"' do
page.should render('<r:children:each status="all" by="slug"><r:slug /> </r:children:each>').as('a b c d draft e f g h i j ')
end
it "should include draft pages by default on the dev host" do
page.should render('<r:children:each by="slug"><r:slug /> </r:children:each>').as('a b c d draft e f g h i j ').on('dev.site.com')
end
it 'should not list draft pages on dev.site.com when Radiant::Config["dev.host"] is set to something else' do
Radiant::Config['dev.host'] = 'preview.site.com'
page.should render('<r:children:each by="title"><r:slug /> </r:children:each>').as('a b c d e f g h i j ').on('dev.site.com')
end
it 'should paginate results when "paginated" attribute is "true"' do
page.pagination_parameters = {:page => 1, :per_page => 10}
page.should render('<r:children:each paginated="true" per_page="10"><r:slug /> </r:children:each>').as('a b c d e f g h i j ')
page.should render('<r:children:each paginated="true" per_page="2"><r:slug /> </r:children:each>').matching(/div class="pagination"/)
end
it 'should error with invalid "limit" attribute' do
message = "`limit' attribute of `each' tag must be a positive number between 1 and 4 digits"
page.should render(page_children_each_tags(%{limit="a"})).with_error(message)
page.should render(page_children_each_tags(%{limit="-10"})).with_error(message)
page.should render(page_children_each_tags(%{limit="50000"})).with_error(message)
end
it 'should error with invalid "offset" attribute' do
message = "`offset' attribute of `each' tag must be a positive number between 1 and 4 digits"
page.should render(page_children_each_tags(%{offset="a"})).with_error(message)
page.should render(page_children_each_tags(%{offset="-10"})).with_error(message)
page.should render(page_children_each_tags(%{offset="50000"})).with_error(message)
end
it 'should error with invalid "by" attribute' do
message = "`by' attribute of `each' tag must be set to a valid field name"
page.should render(page_children_each_tags(%{by="non-existant-field"})).with_error(message)
end
it 'should error with invalid "order" attribute' do
message = %{`order' attribute of `each' tag must be set to either "asc" or "desc"}
page.should render(page_children_each_tags(%{order="asdf"})).with_error(message)
end
it "should limit the number of children when given a 'limit' attribute" do
page.should render(page_children_each_tags(%{limit="5"})).as('a b c d e ')
end
it "should limit and offset the children when given 'limit' and 'offset' attributes" do
page.should render(page_children_each_tags(%{offset="3" limit="5"})).as('d e f g h ')
end
it "should change the sort order when given an 'order' attribute" do
page.should render(page_children_each_tags(%{order="desc"})).as('j i h g f e d c b a ')
end
it "should sort by the 'by' attribute" do
page.should render(page_children_each_tags(%{by="breadcrumb"})).as('f e d c b a j i h g ')
end
it "should sort by the 'by' attribute according to the 'order' attribute" do
page.should render(page_children_each_tags(%{by="breadcrumb" order="desc"})).as('g h i j a b c d e f ')
end
describe 'with "status" attribute' do
it "set to 'all' should list all children" do
page.should render(page_children_each_tags(%{status="all"})).as("a b c d e f g h i j draft ")
end
it "set to 'draft' should list only children with 'draft' status" do
page.should render(page_children_each_tags(%{status="draft"})).as('draft ')
end
it "set to 'published' should list only children with 'draft' status" do
page.should render(page_children_each_tags(%{status="published"})).as('a b c d e f g h i j ')
end
it "set to an invalid status should render an error" do
page.should render(page_children_each_tags(%{status="askdf"})).with_error("`status' attribute of `each' tag must be set to a valid status")
end
end
end
describe "<r:children:each:if_first>" do
it "should render for the first child" do
tags = '<r:children:each><r:if_first>FIRST:</r:if_first><r:slug /> </r:children:each>'
expected = "FIRST:article article-2 article-3 article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:each:unless_first>" do
it "should render for all but the first child" do
tags = '<r:children:each><r:unless_first>NOT-FIRST:</r:unless_first><r:slug /> </r:children:each>'
expected = "article NOT-FIRST:article-2 NOT-FIRST:article-3 NOT-FIRST:article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:each:if_last>" do
it "should render for the last child" do
tags = '<r:children:each><r:if_last>LAST:</r:if_last><r:slug /> </r:children:each>'
expected = "article article-2 article-3 LAST:article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:each:unless_last>" do
it "should render for all but the last child" do
tags = '<r:children:each><r:unless_last>NOT-LAST:</r:unless_last><r:slug /> </r:children:each>'
expected = "NOT-LAST:article NOT-LAST:article-2 NOT-LAST:article-3 article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:each:header>" do
it "should render the header when it changes" do
tags = '<r:children:each><r:header>[<r:date format="%b/%y" />] </r:header><r:slug /> </r:children:each>'
expected = "[Dec/00] article [Feb/01] article-2 article-3 [Mar/01] article-4 "
page(:news).should render(tags).as(expected)
end
it 'with "name" attribute should maintain a separate header' do
tags = %{<r:children:each><r:header name="year">[<r:date format='%Y' />] </r:header><r:header name="month">(<r:date format="%b" />) </r:header><r:slug /> </r:children:each>}
expected = "[2000] (Dec) article [2001] (Feb) article-2 article-3 (Mar) article-4 "
page(:news).should render(tags).as(expected)
end
it 'with "restart" attribute set to one name should restart that header' do
tags = %{<r:children:each><r:header name="year" restart="month">[<r:date format='%Y' />] </r:header><r:header name="month">(<r:date format="%b" />) </r:header><r:slug /> </r:children:each>}
expected = "[2000] (Dec) article [2001] (Feb) article-2 article-3 (Mar) article-4 "
page(:news).should render(tags).as(expected)
end
it 'with "restart" attribute set to two names should restart both headers' do
tags = %{<r:children:each><r:header name="year" restart="month;day">[<r:date format='%Y' />] </r:header><r:header name="month" restart="day">(<r:date format="%b" />) </r:header><r:header name="day"><<r:date format='%d' />> </r:header><r:slug /> </r:children:each>}
expected = "[2000] (Dec) <01> article [2001] (Feb) <09> article-2 <24> article-3 (Mar) <06> article-4 "
page(:news).should render(tags).as(expected)
end
end
describe "<r:children:count>" do
it 'should render the number of children of the current page' do
page(:parent).should render('<r:children:count />').as('3')
end
it "should accept the same scoping conditions as <r:children:each>" do
page.should render('<r:children:count />').as('10')
page.should render('<r:children:count status="all" />').as('11')
page.should render('<r:children:count status="draft" />').as('1')
page.should render('<r:children:count status="hidden" />').as('0')
end
end
describe "<r:children:first>" do
it 'should render its contents in the context of the first child page' do
page(:parent).should render('<r:children:first:title />').as('Child')
end
it 'should accept the same scoping attributes as <r:children:each>' do
page.should render(page_children_first_tags).as('a')
page.should render(page_children_first_tags(%{limit="5"})).as('a')
page.should render(page_children_first_tags(%{offset="3" limit="5"})).as('d')
page.should render(page_children_first_tags(%{order="desc"})).as('j')
page.should render(page_children_first_tags(%{by="breadcrumb"})).as('f')
page.should render(page_children_first_tags(%{by="breadcrumb" order="desc"})).as('g')
end
it "should render nothing when no children exist" do
page(:first).should render('<r:children:first:title />').as('')
end
end
describe "<r:children:last>" do
it 'should render its contents in the context of the last child page' do
page(:parent).should render('<r:children:last:title />').as('Child 3')
end
it 'should accept the same scoping attributes as <r:children:each>' do
page.should render(page_children_last_tags).as('j')
page.should render(page_children_last_tags(%{limit="5"})).as('e')
page.should render(page_children_last_tags(%{offset="3" limit="5"})).as('h')
page.should render(page_children_last_tags(%{order="desc"})).as('a')
page.should render(page_children_last_tags(%{by="breadcrumb"})).as('g')
page.should render(page_children_last_tags(%{by="breadcrumb" order="desc"})).as('f')
end
it "should render nothing when no children exist" do
page(:first).should render('<r:children:last:title />').as('')
end
end
describe "<r:content>" do
it "should render the 'body' part by default" do
page.should render('<r:content />').as('Assorted body.')
end
it "with 'part' attribute should render the specified part" do
page(:home).should render('<r:content part="extended" />').as("Just a test.")
end
it "should prevent simple recursion" do
page(:recursive_parts).should render('<r:content />').with_error("Recursion error: already rendering the `body' part.")
end
it "should prevent deep recursion" do
page(:recursive_parts).should render('<r:content part="one"/>').with_error("Recursion error: already rendering the `one' part.")
page(:recursive_parts).should render('<r:content part="two"/>').with_error("Recursion error: already rendering the `two' part.")
end
it "should allow repetition" do
page(:recursive_parts).should render('<r:content part="repeat"/>').as('xx')
end
it "should not prevent rendering a part more than once in sequence" do
page(:home).should render('<r:content /><r:content />').as('Hello world!Hello world!')
end
describe "with inherit attribute" do
it "missing or set to 'false' should render the current page's part" do
page.should render('<r:content part="sidebar" />').as('')
page.should render('<r:content part="sidebar" inherit="false" />').as('')
end
describe "set to 'true'" do
it "should render an ancestor's part" do
page.should render('<r:content part="sidebar" inherit="true" />').as('Assorted sidebar.')
end
it "should render nothing when no ancestor has the part" do
page.should render('<r:content part="part_that_doesnt_exist" inherit="true" />').as('')
end
describe "and contextual attribute" do
it "set to 'true' should render the part in the context of the current page" do
page(:parent).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Parent sidebar.')
page(:child).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Child sidebar.')
page(:grandchild).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Grandchild sidebar.')
end
it "set to 'false' should render the part in the context of its containing page" do
page(:parent).should render('<r:content part="sidebar" inherit="true" contextual="false" />').as('Home sidebar.')
end
it "should maintain the global page" do
page(:first)
page.should render('<r:content part="titles" inherit="true" contextual="true"/>').as('First First')
page.should render('<r:content part="titles" inherit="true" contextual="false"/>').as('Home First')
end
end
end
it "set to an erroneous value should render an error" do
page.should render('<r:content part="sidebar" inherit="weird value" />').with_error(%{`inherit' attribute of `content' tag must be set to either "true" or "false"})
end
it "should render parts with respect to the current contextual page" do
expected = "Child body. Child 2 body. Child 3 body. "
page(:parent).should render('<r:children:each><r:content /> </r:children:each>').as(expected)
end
end
end
describe "<r:if_content>" do
it "without 'part' attribute should render the contained block if the 'body' part exists" do
page.should render('<r:if_content>true</r:if_content>').as('true')
end
it "should render the contained block if the specified part exists" do
page.should render('<r:if_content part="body">true</r:if_content>').as('true')
end
it "should not render the contained block if the specified part does not exist" do
page.should render('<r:if_content part="asdf">true</r:if_content>').as('')
end
describe "with more than one part given (separated by comma)" do
it "should render the contained block only if all specified parts exist" do
page(:home).should render('<r:if_content part="body, extended">true</r:if_content>').as('true')
end
it "should not render the contained block if at least one of the specified parts does not exist" do
page(:home).should render('<r:if_content part="body, madeup">true</r:if_content>').as('')
end
describe "with inherit attribute set to 'true'" do
it 'should render the contained block if the current or ancestor pages have the specified parts' do
page(:guests).should render('<r:if_content part="favors, extended" inherit="true">true</r:if_content>').as('true')
end
it 'should not render the contained block if the current or ancestor pages do not have all of the specified parts' do
page(:guests).should render('<r:if_content part="favors, madeup" inherit="true">true</r:if_content>').as('')
end
describe "with find attribute set to 'any'" do
it 'should render the contained block if the current or ancestor pages have any of the specified parts' do
page(:guests).should render('<r:if_content part="favors, madeup" inherit="true" find="any">true</r:if_content>').as('true')
end
it 'should still render the contained block if first of the specified parts has not been found' do
page(:guests).should render('<r:if_content part="madeup, favors" inherit="true" find="any">true</r:if_content>').as('true')
end
end
end
describe "with inherit attribute set to 'false'" do
it 'should render the contained block if the current page has the specified parts' do
page(:guests).should render('<r:if_content part="favors, games" inherit="false">true</r:if_content>').as('')
end
it 'should not render the contained block if the current or ancestor pages do not have all of the specified parts' do
page(:guests).should render('<r:if_content part="favors, madeup" inherit="false">true</r:if_content>').as('')
end
end
describe "with the 'find' attribute set to 'any'" do
it "should render the contained block if any of the specified parts exist" do
page.should render('<r:if_content part="body, asdf" find="any">true</r:if_content>').as('true')
end
end
describe "with the 'find' attribute set to 'all'" do
it "should render the contained block if all of the specified parts exist" do
page(:home).should render('<r:if_content part="body, sidebar" find="all">true</r:if_content>').as('true')
end
it "should not render the contained block if all of the specified parts do not exist" do
page.should render('<r:if_content part="asdf, madeup" find="all">true</r:if_content>').as('')
end
end
end
end
describe "<r:unless_content>" do
describe "with inherit attribute set to 'true'" do
it 'should not render the contained block if the current or ancestor pages have the specified parts' do
page(:guests).should render('<r:unless_content part="favors, extended" inherit="true">true</r:unless_content>').as('')
end
it 'should render the contained block if the current or ancestor pages do not have the specified parts' do
page(:guests).should render('<r:unless_content part="madeup, imaginary" inherit="true">true</r:unless_content>').as('true')
end
it "should not render the contained block if the specified part does not exist but does exist on an ancestor" do
page.should render('<r:unless_content part="sidebar" inherit="true">false</r:unless_content>').as('')
end
describe "with find attribute set to 'any'" do
it 'should not render the contained block if the current or ancestor pages have any of the specified parts' do
page(:guests).should render('<r:unless_content part="favors, madeup" inherit="true" find="any">true</r:unless_content>').as('')
end
it 'should still not render the contained block if first of the specified parts has not been found' do
page(:guests).should render('<r:unless_content part="madeup, favors" inherit="true" find="any">true</r:unless_content>').as('')
end
end
end
it "without 'part' attribute should not render the contained block if the 'body' part exists" do
page.should render('<r:unless_content>false</r:unless_content>').as('')
end
it "should not render the contained block if the specified part exists" do
page.should render('<r:unless_content part="body">false</r:unless_content>').as('')
end
it "should render the contained block if the specified part does not exist" do
page.should render('<r:unless_content part="asdf">false</r:unless_content>').as('false')
end
it "should render the contained block if the specified part does not exist but does exist on an ancestor" do
page.should render('<r:unless_content part="sidebar">false</r:unless_content>').as('false')
end
describe "with more than one part given (separated by comma)" do
it "should not render the contained block if all of the specified parts exist" do
page(:home).should render('<r:unless_content part="body, extended">true</r:unless_content>').as('')
end
it "should render the contained block if at least one of the specified parts exists" do
page(:home).should render('<r:unless_content part="body, madeup">true</r:unless_content>').as('true')
end
describe "with the 'inherit' attribute set to 'true'" do
it "should render the contained block if the current or ancestor pages have none of the specified parts" do
page.should render('<r:unless_content part="imaginary, madeup" inherit="true">true</r:unless_content>').as('true')
end
it "should not render the contained block if all of the specified parts are present on the current or ancestor pages" do
page(:party).should render('<r:unless_content part="favors, extended" inherit="true">true</r:unless_content>').as('')
end
end
describe "with the 'find' attribute set to 'all'" do
it "should not render the contained block if all of the specified parts exist" do
page(:home).should render('<r:unless_content part="body, sidebar" find="all">true</r:unless_content>').as('')
end
it "should render the contained block unless all of the specified parts exist" do
page.should render('<r:unless_content part="body, madeup" find="all">true</r:unless_content>').as('true')
end
end
describe "with the 'find' attribute set to 'any'" do
it "should not render the contained block if any of the specified parts exist" do
page.should render('<r:unless_content part="body, madeup" find="any">true</r:unless_content>').as('')
end
end
end
end
describe "<r:author>" do
it "should render the author of the current page" do
page.should render('<r:author />').as('Admin')
end
it "should render nothing when the page has no author" do
page(:no_user).should render('<r:author />').as('')
end
end
describe "<r:gravatar>" do
it "should render the Gravatar URL of author of the current page" do
page.should render('<r:gravatar />').as('http://www.gravatar.com/avatar.php?gravatar_id=e64c7d89f26bd1972efa854d13d7dd61&rating=G&size=32')
end
it "should render the Gravatar URL of the name user" do
page.should render('<r:gravatar name="Admin" />').as('http://www.gravatar.com/avatar.php?gravatar_id=e64c7d89f26bd1972efa854d13d7dd61&rating=G&size=32')
end
it "should render the default avatar when the user has not set an email address" do
page.should render('<r:gravatar name="Designer" />').as('http://testhost.tld/images/admin/avatar_32x32.png')
end
it "should render the specified size" do
page.should render('<r:gravatar name="Designer" size="96px" />').as('http://testhost.tld/images/admin/avatar_96x96.png')
end
it "should render the specified rating" do
page.should render('<r:gravatar rating="X" />').as('http://www.gravatar.com/avatar.php?gravatar_id=e64c7d89f26bd1972efa854d13d7dd61&rating=X&size=32')
end
end
describe "<r:date>" do
before :each do
page(:dated)
end
it "should render the published date of the page" do
page.should render('<r:date />').as('Wednesday, January 11, 2006')
end
it "should format the published date according to the 'format' attribute" do
page.should render('<r:date format="%d %b %Y" />').as('11 Jan 2006')
end
describe "with 'for' attribute" do
it "set to 'now' should render the current date in the current Time.zone" do
page.should render('<r:date for="now" />').as(Time.zone.now.strftime("%A, %B %d, %Y"))
end
it "set to 'created_at' should render the creation date" do
page.should render('<r:date for="created_at" />').as('Tuesday, January 10, 2006')
end
it "set to 'updated_at' should render the update date" do
page.should render('<r:date for="updated_at" />').as('Thursday, January 12, 2006')
end
it "set to 'published_at' should render the publish date" do
page.should render('<r:date for="published_at" />').as('Wednesday, January 11, 2006')
end
it "set to an invalid attribute should render an error" do
page.should render('<r:date for="blah" />').with_error("Invalid value for 'for' attribute.")
end
end
it "should use the currently set timezone" do
Time.zone = "Tokyo"
format = "%H:%m"
expected = page.published_at.in_time_zone(ActiveSupport::TimeZone['Tokyo']).strftime(format)
page.should render(%Q(<r:date format="#{format}" />) ).as(expected)
end
end
describe "<r:link>" do
it "should render a link to the current page" do
page.should render('<r:link />').as('<a href="/assorted/">Assorted</a>')
end
it "should render its contents as the text of the link" do
page.should render('<r:link>Test</r:link>').as('<a href="/assorted/">Test</a>')
end
it "should pass HTML attributes to the <a> tag" do
expected = '<a href="/assorted/" class="test" id="assorted">Assorted</a>'
page.should render('<r:link class="test" id="assorted" />').as(expected)
end
it "should add the anchor attribute to the link as a URL anchor" do
page.should render('<r:link anchor="test">Test</r:link>').as('<a href="/assorted/#test">Test</a>')
end
it "should render a link for the current contextual page" do
expected = %{<a href="/parent/child/">Child</a> <a href="/parent/child-2/">Child 2</a> <a href="/parent/child-3/">Child 3</a> }
page(:parent).should render('<r:children:each><r:link /> </r:children:each>' ).as(expected)
end
it "should scope the link within the relative URL root" do
page(:assorted).should render('<r:link />').with_relative_root('/foo').as('<a href="/foo/assorted/">Assorted</a>')
end
end
describe "<r:snippet>" do
it "should render the contents of the specified snippet" do
page.should render('<r:snippet name="first" />').as('test')
end
it "should render an error when the snippet does not exist" do
page.should render('<r:snippet name="non-existant" />').with_error('snippet not found')
end
it "should render an error when not given a 'name' attribute" do
page.should render('<r:snippet />').with_error("`snippet' tag must contain `name' attribute")
end
it "should filter the snippet with its assigned filter" do
page.should render('<r:page><r:snippet name="markdown" /></r:page>').matching(%r{<p><strong>markdown</strong></p>})
end
it "should maintain the global page inside the snippet" do
page(:parent).should render('<r:snippet name="global_page_cascade" />').as("#{@page.title} " * @page.children.count)
end
it "should maintain the global page when the snippet renders recursively" do
page(:child).should render('<r:snippet name="recursive" />').as("Great GrandchildGrandchildChild")
end
it "should render the specified snippet when called as an empty double-tag" do
page.should render('<r:snippet name="first"></r:snippet>').as('test')
end
it "should capture contents of a double tag, substituting for <r:yield/> in snippet" do
page.should render('<r:snippet name="yielding">inner</r:snippet>').
as('Before...inner...and after')
end
it "should do nothing with contents of double tag when snippet doesn't yield" do
page.should render('<r:snippet name="first">content disappears!</r:snippet>').
as('test')
end
it "should render nested yielding snippets" do
page.should render('<r:snippet name="div_wrap"><r:snippet name="yielding">Hello, World!</r:snippet></r:snippet>').
as('<div>Before...Hello, World!...and after</div>')
end
it "should render double-tag snippets called from within a snippet" do
page.should render('<r:snippet name="nested_yields">the content</r:snippet>').
as('<snippet name="div_wrap">above the content below</snippet>')
end
it "should render contents each time yield is called" do
page.should render('<r:snippet name="yielding_often">French</r:snippet>').
as('French is Frencher than French')
end
end
it "should do nothing when called from page body" do
page.should render('<r:yield/>').as("")
end
it '<r:random> should render a randomly selected contained <r:option>' do
page.should render("<r:random> <r:option>1</r:option> <r:option>2</r:option> <r:option>3</r:option> </r:random>").matching(/^(1|2|3)$/)
end
it '<r:random> should render a randomly selected, dynamically set <r:option>' do
page(:parent).should render("<r:random:children:each:option:title />").matching(/^(Child|Child\ 2|Child\ 3)$/)
end
it '<r:comment> should render nothing it contains' do
page.should render('just a <r:comment>small </r:comment>test').as('just a test')
end
describe "<r:navigation>" do
it "should render the nested <r:normal> tag by default" do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/">
<r:normal><r:title /></r:normal>
</r:navigation>}
expected = %{Home Assorted Parent}
page.should render(tags).as(expected)
end
it "should render the nested <r:selected> tag for URLs that match the current page" do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/ | Radius: /radius/">
<r:normal><r:title /></r:normal>
<r:selected><strong><r:title/></strong></r:selected>
</r:navigation>}
expected = %{<strong>Home</strong> Assorted <strong>Parent</strong> Radius}
page(:parent).should render(tags).as(expected)
end
it "should render the nested <r:here> tag for URLs that exactly match the current page" do
tags = %{<r:navigation urls="Home: Boy: / | Assorted: /assorted/ | Parent: /parent/">
<r:normal><a href="<r:url />"><r:title /></a></r:normal>
<r:here><strong><r:title /></strong></r:here>
<r:selected><strong><a href="<r:url />"><r:title /></a></strong></r:selected>
<r:between> | </r:between>
</r:navigation>}
expected = %{<strong><a href="/">Home: Boy</a></strong> | <strong>Assorted</strong> | <a href="/parent/">Parent</a>}
page.should render(tags).as(expected)
end
it "should render the nested <r:between> tag between each link" do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/">
<r:normal><r:title /></r:normal>
<r:between> :: </r:between>
</r:navigation>}
expected = %{Home :: Assorted :: Parent}
page.should render(tags).as(expected)
end
it 'without urls should render nothing' do
page.should render(%{<r:navigation><r:normal /></r:navigation>}).as('')
end
it 'without a nested <r:normal> tag should render an error' do
page.should render(%{<r:navigation urls="something:here"></r:navigation>}).with_error( "`navigation' tag must include a `normal' tag")
end
it 'with urls without trailing slashes should match corresponding pages' do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius">
<r:normal><r:title /></r:normal>
<r:here><strong><r:title /></strong></r:here>
</r:navigation>}
expected = %{Home <strong>Assorted</strong> Parent Radius}
page.should render(tags).as(expected)
end
it 'should prune empty blocks' do
tags = %{<r:navigation urls="Home: Boy: / | Archives: /archive/ | Radius: /radius/ | Docs: /documentation/">
<r:normal><a href="<r:url />"><r:title /></a></r:normal>
<r:here></r:here>
<r:selected><strong><a href="<r:url />"><r:title /></a></strong></r:selected>
<r:between> | </r:between>
</r:navigation>}
expected = %{<strong><a href="/">Home: Boy</a></strong> | <a href="/archive/">Archives</a> | <a href="/documentation/">Docs</a>}
page(:radius).should render(tags).as(expected)
end
it 'should render text under <r:if_first> and <r:if_last> only on the first and last item, respectively' do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius">
<r:normal><r:if_first>(</r:if_first><a href="<r:url />"><r:title /></a><r:if_last>)</r:if_last></r:normal>
<r:here><r:if_first>(</r:if_first><r:title /><r:if_last>)</r:if_last></r:here>
<r:selected><r:if_first>(</r:if_first><strong><a href="<r:url />"><r:title /></a></strong><r:if_last>)</r:if_last></r:selected>
</r:navigation>}
expected = %{(<strong><a href=\"/\">Home</a></strong> <a href=\"/assorted\">Assorted</a> <a href=\"/parent\">Parent</a> Radius)}
page(:radius).should render(tags).as(expected)
end
it 'should render text under <r:unless_first> on every item but the first' do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius">
<r:normal><r:unless_first>> </r:unless_first><a href="<r:url />"><r:title /></a></r:normal>
<r:here><r:unless_first>> </r:unless_first><r:title /></r:here>
<r:selected><r:unless_first>> </r:unless_first><strong><a href="<r:url />"><r:title /></a></strong></r:selected>
</r:navigation>}
expected = %{<strong><a href=\"/\">Home</a></strong> > <a href=\"/assorted\">Assorted</a> > <a href=\"/parent\">Parent</a> > Radius}
page(:radius).should render(tags).as(expected)
end
it 'should render text under <r:unless_last> on every item but the last' do
tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius">
<r:normal><a href="<r:url />"><r:title /></a><r:unless_last> ></r:unless_last></r:normal>
<r:here><r:title /><r:unless_last> ></r:unless_last></r:here>
<r:selected><strong><a href="<r:url />"><r:title /></a></strong><r:unless_last> ></r:unless_last></r:selected>
</r:navigation>}
expected = %{<strong><a href=\"/\">Home</a></strong> > <a href=\"/assorted\">Assorted</a> > <a href=\"/parent\">Parent</a> > Radius}
page(:radius).should render(tags).as(expected)
end
end
describe "<r:find>" do
it "should change the local page to the page specified in the 'url' attribute" do
page.should render(%{<r:find url="/parent/child/"><r:title /></r:find>}).as('Child')
end
it "should render an error without the 'url' attribute" do
page.should render(%{<r:find />}).with_error("`find' tag must contain `url' attribute")
end
it "should render nothing when the 'url' attribute does not point to a page" do
page.should render(%{<r:find url="/asdfsdf/"><r:title /></r:find>}).as('')
end
it "should render nothing when the 'url' attribute does not point to a page and a custom 404 page exists" do
page.should render(%{<r:find url="/gallery/asdfsdf/"><r:title /></r:find>}).as('')
end
it "should scope contained tags to the found page" do
page.should render(%{<r:find url="/parent/"><r:children:each><r:slug /> </r:children:each></r:find>}).as('child child-2 child-3 ')
end
it "should accept a path relative to the current page" do
page(:great_grandchild).should render(%{<r:find url="../../../child-2"><r:title/></r:find>}).as("Child 2")
end
end
it '<r:escape_html> should escape HTML-related characters into entities' do
page.should render('<r:escape_html><strong>a bold move</strong></r:escape_html>').as('<strong>a bold move</strong>')
end
it '<r:rfc1123_date> should render an RFC1123-compatible date' do
page(:dated).should render('<r:rfc1123_date />').as('Wed, 11 Jan 2006 00:00:00 GMT')
end
describe "<r:breadcrumbs>" do
it "should render a series of breadcrumb links separated by >" do
expected = %{<a href="/">Home</a> > <a href="/parent/">Parent</a> > <a href="/parent/child/">Child</a> > <a href="/parent/child/grandchild/">Grandchild</a> > Great Grandchild}
page(:great_grandchild).should render('<r:breadcrumbs />').as(expected)
end
it "with a 'separator' attribute should use the separator instead of >" do
expected = %{<a href="/">Home</a> :: Parent}
page(:parent).should render('<r:breadcrumbs separator=" :: " />').as(expected)
end
it "with a 'nolinks' attribute set to 'true' should not render links" do
expected = %{Home > Parent}
page(:parent).should render('<r:breadcrumbs nolinks="true" />').as(expected)
end
it "with a relative URL root should scope links to the relative root" do
expected = '<a href="/foo/">Home</a> > Assorted'
page(:assorted).should render('<r:breadcrumbs />').with_relative_root('/foo').as(expected)
end
end
describe "<r:if_url>" do
describe "with 'matches' attribute" do
it "should render the contained block if the page URL matches" do
page.should render('<r:if_url matches="a.sorted/$">true</r:if_url>').as('true')
end
it "should not render the contained block if the page URL does not match" do
page.should render('<r:if_url matches="fancypants">true</r:if_url>').as('')
end
it "set to a malformatted regexp should render an error" do
page.should render('<r:if_url matches="as(sorted/$">true</r:if_url>').with_error("Malformed regular expression in `matches' argument of `if_url' tag: unmatched (: /as(sorted\\/$/")
end
it "without 'ignore_case' attribute should ignore case by default" do
page.should render('<r:if_url matches="asSorted/$">true</r:if_url>').as('true')
end
describe "with 'ignore_case' attribute" do
it "set to 'true' should use a case-insensitive match" do
page.should render('<r:if_url matches="asSorted/$" ignore_case="true">true</r:if_url>').as('true')
end
it "set to 'false' should use a case-sensitive match" do
page.should render('<r:if_url matches="asSorted/$" ignore_case="false">true</r:if_url>').as('')
end
end
end
it "with no attributes should render an error" do
page.should render('<r:if_url>test</r:if_url>').with_error("`if_url' tag must contain a `matches' attribute.")
end
end
describe "<r:unless_url>" do
describe "with 'matches' attribute" do
it "should not render the contained block if the page URL matches" do
page.should render('<r:unless_url matches="a.sorted/$">true</r:unless_url>').as('')
end
it "should render the contained block if the page URL does not match" do
page.should render('<r:unless_url matches="fancypants">true</r:unless_url>').as('true')
end
it "set to a malformatted regexp should render an error" do
page.should render('<r:unless_url matches="as(sorted/$">true</r:unless_url>').with_error("Malformed regular expression in `matches' argument of `unless_url' tag: unmatched (: /as(sorted\\/$/")
end
it "without 'ignore_case' attribute should ignore case by default" do
page.should render('<r:unless_url matches="asSorted/$">true</r:unless_url>').as('')
end
describe "with 'ignore_case' attribute" do
it "set to 'true' should use a case-insensitive match" do
page.should render('<r:unless_url matches="asSorted/$">true</r:unless_url>').as('')
end
it "set to 'false' should use a case-sensitive match" do
page.should render('<r:unless_url matches="asSorted/$" ignore_case="false">true</r:unless_url>').as('true')
end
end
end
it "with no attributes should render an error" do
page.should render('<r:unless_url>test</r:unless_url>').with_error("`unless_url' tag must contain a `matches' attribute.")
end
end
describe "<r:cycle>" do
it "should render passed values in succession" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" />').as('first second')
end
it "should return to the beginning of the cycle when reaching the end" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" /> <r:cycle values="first, second" />').as('first second first')
end
it "should use a default cycle name of 'cycle'" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" name="cycle" />').as('first second')
end
it "should maintain separate cycle counters" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="one, two" name="numbers" /> <r:cycle values="first, second" /> <r:cycle values="one, two" name="numbers" />').as('first one second two')
end
it "should reset the counter" do
page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" reset="true"/>').as('first first')
end
it "should require the values attribute" do
page.should render('<r:cycle />').with_error("`cycle' tag must contain a `values' attribute.")
end
end
describe "<r:if_dev>" do
it "should render the contained block when on the dev site" do
page.should render('-<r:if_dev>dev</r:if_dev>-').as('-dev-').on('dev.site.com')
end
it "should not render the contained block when not on the dev site" do
page.should render('-<r:if_dev>dev</r:if_dev>-').as('--')
end
describe "on an included page" do
it "should render the contained block when on the dev site" do
page.should render('-<r:find url="/devtags/"><r:content part="if_dev" /></r:find>-').as('-dev-').on('dev.site.com')
end
it "should not render the contained block when not on the dev site" do
page.should render('-<r:find url="/devtags/"><r:content part="if_dev" /></r:find>-').as('--')
end
end
end
describe "<r:unless_dev>" do
it "should not render the contained block when not on the dev site" do
page.should render('-<r:unless_dev>not dev</r:unless_dev>-').as('--').on('dev.site.com')
end
it "should render the contained block when not on the dev site" do
page.should render('-<r:unless_dev>not dev</r:unless_dev>-').as('-not dev-')
end
describe "on an included page" do
it "should not render the contained block when not on the dev site" do
page.should render('-<r:find url="/devtags/"><r:content part="unless_dev" /></r:find>-').as('--').on('dev.site.com')
end
it "should render the contained block when not on the dev site" do
page.should render('-<r:find url="/devtags/"><r:content part="unless_dev" /></r:find>-').as('-not dev-')
end
end
end
describe "<r:status>" do
it "should render the status of the current page" do
status_tag = "<r:status/>"
page(:a).should render(status_tag).as("Published")
page(:hidden).should render(status_tag).as("Hidden")
page(:draft).should render(status_tag).as("Draft")
end
describe "with the downcase attribute set to 'true'" do
it "should render the lowercased status of the current page" do
status_tag_lc = "<r:status downcase='true'/>"
page(:a).should render(status_tag_lc).as("published")
page(:hidden).should render(status_tag_lc).as("hidden")
page(:draft).should render(status_tag_lc).as("draft")
end
end
end
describe "<r:if_ancestor_or_self>" do
it "should render the tag's content when the current page is an ancestor of tag.locals.page" do
page(:radius).should render(%{<r:find url="/"><r:if_ancestor_or_self>true</r:if_ancestor_or_self></r:find>}).as('true')
end
it "should not render the tag's content when current page is not an ancestor of tag.locals.page" do
page(:parent).should render(%{<r:find url="/radius"><r:if_ancestor_or_self>true</r:if_ancestor_or_self></r:find>}).as('')
end
end
describe "<r:unless_ancestor_or_self>" do
it "should render the tag's content when the current page is not an ancestor of tag.locals.page" do
page(:parent).should render(%{<r:find url="/radius"><r:unless_ancestor_or_self>true</r:unless_ancestor_or_self></r:find>}).as('true')
end
it "should not render the tag's content when current page is an ancestor of tag.locals.page" do
page(:radius).should render(%{<r:find url="/"><r:unless_ancestor_or_self>true</r:unless_ancestor_or_self></r:find>}).as('')
end
end
describe "<r:if_self>" do
it "should render the tag's content when the current page is the same as the local contextual page" do
page(:home).should render(%{<r:find url="/"><r:if_self>true</r:if_self></r:find>}).as('true')
end
it "should not render the tag's content when the current page is not the same as the local contextual page" do
page(:radius).should render(%{<r:find url="/"><r:if_self>true</r:if_self></r:find>}).as('')
end
end
describe "<r:unless_self>" do
it "should render the tag's content when the current page is not the same as the local contextual page" do
page(:radius).should render(%{<r:find url="/"><r:unless_self>true</r:unless_self></r:find>}).as('true')
end
it "should not render the tag's content when the current page is the same as the local contextual page" do
page(:home).should render(%{<r:find url="/"><r:unless_self>true</r:unless_self></r:find>}).as('')
end
end
describe "<r:meta>" do
it "should render <meta> tags for the description and keywords" do
page(:home).should render('<r:meta/>').as(%{<meta name="description" content="The homepage" /><meta name="keywords" content="Home, Page" />})
end
it "should render <meta> tags with escaped values for the description and keywords" do
page.should render('<r:meta/>').as(%{<meta name="description" content="sweet & harmonious biscuits" /><meta name="keywords" content="sweet & harmonious biscuits" />})
end
describe "with 'tag' attribute set to 'false'" do
it "should render the contents of the description and keywords" do
page(:home).should render('<r:meta tag="false" />').as(%{The homepageHome, Page})
end
it "should escape the contents of the description and keywords" do
page.should render('<r:meta tag="false" />').as("sweet & harmonious biscuitssweet & harmonious biscuits")
end
end
end
describe "<r:meta:description>" do
it "should render a <meta> tag for the description" do
page(:home).should render('<r:meta:description/>').as(%{<meta name="description" content="The homepage" />})
end
it "should render a <meta> tag with escaped value for the description" do
page.should render('<r:meta:description />').as(%{<meta name="description" content="sweet & harmonious biscuits" />})
end
describe "with 'tag' attribute set to 'false'" do
it "should render the contents of the description" do
page(:home).should render('<r:meta:description tag="false" />').as(%{The homepage})
end
it "should escape the contents of the description" do
page.should render('<r:meta:description tag="false" />').as("sweet & harmonious biscuits")
end
end
end
describe "<r:meta:keywords>" do
it "should render a <meta> tag for the keywords" do
page(:home).should render('<r:meta:keywords/>').as(%{<meta name="keywords" content="Home, Page" />})
end
it "should render a <meta> tag with escaped value for the keywords" do
page.should render('<r:meta:keywords />').as(%{<meta name="keywords" content="sweet & harmonious biscuits" />})
end
describe "with 'tag' attribute set to 'false'" do
it "should render the contents of the keywords" do
page(:home).should render('<r:meta:keywords tag="false" />').as(%{Home, Page})
end
it "should escape the contents of the keywords" do
page.should render('<r:meta:keywords tag="false" />').as("sweet & harmonious biscuits")
end
end
end
private
def page(symbol = nil)
if symbol.nil?
@page ||= pages(:assorted)
else
@page = pages(symbol)
end
end
def page_children_each_tags(attr = nil)
attr = ' ' + attr unless attr.nil?
"<r:children:each#{attr}><r:slug /> </r:children:each>"
end
def page_children_first_tags(attr = nil)
attr = ' ' + attr unless attr.nil?
"<r:children:first#{attr}><r:slug /></r:children:first>"
end
def page_children_last_tags(attr = nil)
attr = ' ' + attr unless attr.nil?
"<r:children:last#{attr}><r:slug /></r:children:last>"
end
def page_eachable_children(page)
page.children.select(&:published?).reject(&:virtual)
end
end
| Java |
module ParametresHelper
end
| Java |
class CreateMappableMaps < ActiveRecord::Migration
def change
create_table :mappable_maps do |t|
t.string :subject
t.string :attr
t.string :from
t.string :to
t.timestamps
end
end
end
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=ASCII">
<link rel="stylesheet" href="style.css" type="text/css">
<title>MXML Only Components - Adobe Flex 2 Language Reference</title>
</head>
<body class="classFrameContent">
<h3>MXML Only Components</h3>
<a href="mxml/binding.html" target="classFrame"><mx:Binding></a>
<br>
<a href="mxml/component.html" target="classFrame"><mx:Component></a>
<br>
<a href="mxml/metadata.html" target="classFrame"><mx:Metadata></a>
<br>
<a href="mxml/model.html" target="classFrame"><mx:Model></a>
<br>
<a href="mxml/script.html" target="classFrame"><mx:Script></a>
<br>
<a href="mxml/style.html" target="classFrame"><mx:Style></a>
<br>
<a href="mxml/xml.html" target="classFrame"><mx:XML></a>
<br>
<a href="mxml/xmlList.html" target="classFrame"><mx:XMLList></a>
<br>
</body>
<!--MMIX | John Dalziel | The Computus Engine | www.computus.org | All source code licenced under the MIT Licence-->
</html>
| Java |
LinkLuaModifier("modifier_cleric_berserk", "heroes/cleric/cleric_modifiers.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_cleric_berserk_target", "heroes/cleric/cleric_modifiers.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_cleric_berserk_no_order", "heroes/cleric/cleric_modifiers.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_cleric_prayer", "heroes/cleric/cleric_modifiers.lua", LUA_MODIFIER_MOTION_NONE)
function ClericMeteorShower(keys)
ProcsArroundingMagicStick(keys.caster)
local iMeteorCount = keys.ability:GetSpecialValueFor("meteor_count")
local vTarget= keys.target_points[1]
local fMeteorRadius = keys.ability:GetSpecialValueFor("meteor_radius")
AddFOWViewer(keys.caster:GetTeamNumber(), vTarget, 500, 3, true)
local fCastRadius = keys.ability:GetSpecialValueFor("cast_radius")
local iDamage
if keys.caster:FindAbilityByName("special_bonus_cleric_4") then
iDamage = keys.ability:GetSpecialValueFor("damage")+keys.caster:FindAbilityByName("special_bonus_cleric_4"):GetSpecialValueFor("value")
else
iDamage = keys.ability:GetSpecialValueFor("damage")
end
local fStunDuration
if keys.caster:FindAbilityByName("special_bonus_cleric_1") then
fStunDuration = keys.ability:GetSpecialValueFor("stun_duration")+keys.caster:FindAbilityByName("special_bonus_cleric_1"):GetSpecialValueFor("value")
else
fStunDuration = keys.ability:GetSpecialValueFor("stun_duration")
end
for i = 1, iMeteorCount do
Timers:CreateTimer(0.2*(i-1), function ()
local vRelative = Vector(RandomFloat(-fCastRadius, fCastRadius), RandomFloat(-fCastRadius, fCastRadius), 0)
while vRelative:Length2D() > fCastRadius do
vRelative = Vector(RandomFloat(-fCastRadius, fCastRadius), RandomFloat(-fCastRadius, fCastRadius), 0)
end
local iParticle = ParticleManager:CreateParticle("particles/units/heroes/hero_invoker/invoker_chaos_meteor_fly.vpcf", PATTACH_CUSTOMORIGIN, PlayerResource:GetPlayer(0):GetAssignedHero())
ParticleManager:SetParticleControl(iParticle, 0, vTarget+vRelative+Vector(0,0,2000))
ParticleManager:SetParticleControl(iParticle, 1, vTarget+vRelative+Vector(0,0,-2250))
ParticleManager:SetParticleControl(iParticle, 2, Vector(0.7,0,0))
local hThinker = CreateModifierThinker(keys.caster, keys.ability, "modifier_stunned", {Duration = 1}, vTarget+vRelative+Vector(0,0,2000), keys.caster:GetTeamNumber(), false)
hThinker:EmitSound("Hero_Invoker.ChaosMeteor.Cast")
hThinker:EmitSound("Hero_Invoker.ChaosMeteor.Loop")
Timers:CreateTimer(0.6,function ()
StartSoundEventFromPosition("Hero_Invoker.ChaosMeteor.Impact", vTarget+vRelative)
hThinker:StopSound("Hero_Invoker.ChaosMeteor.Loop")
GridNav:DestroyTreesAroundPoint(vTarget+vRelative, fMeteorRadius, true)
local tTargets = FindUnitsInRadius(keys.caster:GetTeamNumber(), vTarget+vRelative, nil, fMeteorRadius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_BASIC+DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)
local damageTable = {
damage = iDamage,
attacker = keys.caster,
damage_type = DAMAGE_TYPE_MAGICAL,
ability = keys.ability
}
for k, v in ipairs(tTargets) do
damageTable.victim = v
ApplyDamage(damageTable)
v:AddNewModifier(keys.caster, keys.ability, "modifier_stunned", {Duration = fStunDuration*CalculateStatusResist(v)})
end
end)
end)
end
end
cleric_berserk = class({})
function cleric_berserk:GetBehavior()
if not self.bSpecial2 then
self.hSpecial2 = Entities:First()
while self.hSpecial2 and (self.hSpecial2:GetName() ~= "special_bonus_cleric_5" or self.hSpecial2:GetCaster() ~= self:GetCaster()) do
self.hSpecial2 = Entities:Next(self.hSpecial2)
end
self.bSpecial2 = true
end
if self.hSpecial2 and self.hSpecial2:GetLevel() > 0 then
return DOTA_ABILITY_BEHAVIOR_POINT+DOTA_ABILITY_BEHAVIOR_AOE
else
return DOTA_ABILITY_BEHAVIOR_UNIT_TARGET
end
end
function cleric_berserk:GetAOERadius()
if self.hSpecial2 then
return self.hSpecial2:GetSpecialValueFor("value")
else
return 0
end
end
function cleric_berserk:OnSpellStart()
if self.hSpecial2 and self.hSpecial2:GetLevel() > 0 then
local hCaster = self:GetCaster()
local tTargets = FindUnitsInRadius(hCaster:GetTeamNumber(), self:GetCursorPosition(), nil, self.hSpecial2:GetSpecialValueFor("value"), DOTA_UNIT_TARGET_TEAM_BOTH, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_ANY_ORDER, false)
for k, v in ipairs(tTargets) do
v:EmitSound("Hero_Axe.Berserkers_Call")
v:AddNewModifier(hCaster, self, "modifier_cleric_berserk", {Duration = self:GetSpecialValueFor("duration")*CalculateStatusResist(v)})
end
else
local hTarget = self:GetCursorTarget()
if hTarget:TriggerSpellAbsorb( self ) then return end
hTarget:EmitSound("Hero_Axe.Berserkers_Call")
hTarget:AddNewModifier(self:GetCaster(), self, "modifier_cleric_berserk", {Duration = self:GetSpecialValueFor("duration")*CalculateStatusResist(hTarget)})
end
end
function cleric_berserk:GetCooldown(iLevel)
if not self.bSpecial then
self.hSpecial = Entities:First()
while self.hSpecial and (self.hSpecial:GetName() ~= "special_bonus_cleric_2" or self.hSpecial:GetCaster() ~= self:GetCaster()) do
self.hSpecial = Entities:Next(self.hSpecial)
end
self.bSpecial = true
end
if self.hSpecial then
return self.BaseClass.GetCooldown(self, iLevel)-self.hSpecial:GetSpecialValueFor("value")
else
return self.BaseClass.GetCooldown(self, iLevel)
end
end
function ClericPrayer(keys)
ProcsArroundingMagicStick(keys.caster)
local hSpecial = Entities:First()
while hSpecial and hSpecial:GetName() ~= "special_bonus_cleric_3" do
hSpecial = Entities:Next(hSpecial)
end
keys.caster:EmitSound("Hero_Omniknight.GuardianAngel.Cast")
local iDuration = keys.ability:GetSpecialValueFor("duration")
for k, v in pairs(keys.target_entities) do
local hModifier = v:FindModifierByName("modifier_cleric_prayer")
if not hModifier then
v:AddNewModifier(keys.caster, keys.ability, "modifier_cleric_prayer", {Duration = iDuration})
v:EmitSound("Hero_Omniknight.GuardianAngel")
v:EmitSound("DOTA_Item.Refresher.Activate")
ParticleManager:SetParticleControlEnt(ParticleManager:CreateParticle("particles/items2_fx/refresher.vpcf", PATTACH_ABSORIGIN_FOLLOW, v), 0, v, PATTACH_POINT_FOLLOW, "attach_hitloc", v:GetAbsOrigin(), true)
for i = 0, 23 do
if v:GetAbilityByIndex(i) then v:GetAbilityByIndex(i):EndCooldown() end
end
for j,i in ipairs(tItemInventorySlotTable) do
if v:GetItemInSlot(i) then v:GetItemInSlot(i):EndCooldown() end
end
elseif hSpecial and hModifier:GetStackCount() < hSpecial:GetSpecialValueFor("value") then
local iOriginalStackCount = hModifier:GetStackCount()
v:AddNewModifier(keys.caster, keys.ability, "modifier_cleric_prayer", {Duration = iDuration})
v:FindModifierByName("modifier_cleric_prayer"):SetStackCount(iOriginalStackCount+1)
v:EmitSound("Hero_Omniknight.GuardianAngel")
v:EmitSound("DOTA_Item.Refresher.Activate")
ParticleManager:SetParticleControlEnt(ParticleManager:CreateParticle("particles/items2_fx/refresher.vpcf", PATTACH_ABSORIGIN_FOLLOW, v), 0, v, PATTACH_POINT_FOLLOW, "attach_hitloc", v:GetAbsOrigin(), true)
for i = 0, 23 do
if v:GetAbilityByIndex(i) then v:GetAbilityByIndex(i):EndCooldown() end
end
for j,i in ipairs(tItemInventorySlotTable) do
if v:GetItemInSlot(i) then v:GetItemInSlot(i):EndCooldown() end
end
end
end
end
cleric_magic_mirror = class({})
function cleric_magic_mirror:GetCooldown(iLevel)
if IsClient() then
if self:GetCaster():HasScepter() then
return 20-iLevel*5
end
else
if self:GetCaster():HasScepter() then
return self:GetLevelSpecialValueFor("scepter_cooldown", iLevel)
end
end
return self.BaseClass.GetCooldown(self, iLevel)
end
| Java |
export function mockGlobalFile() {
// @ts-ignore
global.File = class MockFile {
name: string;
size: number;
type: string;
parts: (string | Blob | ArrayBuffer | ArrayBufferView)[];
properties?: FilePropertyBag;
lastModified: number;
constructor(
parts: (string | Blob | ArrayBuffer | ArrayBufferView)[],
name: string,
properties?: FilePropertyBag
) {
this.parts = parts;
this.name = name;
this.size = parts.join('').length;
this.type = 'txt';
this.properties = properties;
this.lastModified = 1234567890000; // Sat Feb 13 2009 23:31:30 GMT+0000.
}
};
}
export function testFile(filename: string, size: number = 42) {
return new File(['x'.repeat(size)], filename, undefined);
}
| Java |
package net.talayhan.android.vibeproject.Controller;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.ipaulpro.afilechooser.utils.FileUtils;
import net.talayhan.android.vibeproject.R;
import net.talayhan.android.vibeproject.Util.Constants;
import java.io.File;
import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.pedant.SweetAlert.SweetAlertDialog;
public class MainActivity extends Activity {
@InjectView(R.id.fileChooser_bt) Button mFileChooser_bt;
@InjectView(R.id.playBack_btn) Button mPlayback_bt;
@InjectView(R.id.chart_bt) Button mChart_bt;
private String videoPath;
private String vidAddress = "https://archive.org/download/ksnn_compilation_master_the_internet/ksnn_compilation_master_the_internet_512kb.mp4";
private SweetAlertDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mFileChooser_bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/* Progress dialog */
pDialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.NORMAL_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Network Type");
pDialog.setContentText("How would you like to watch video?");
pDialog.setConfirmText("Local");
pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
// Local
// Create the ACTION_GET_CONTENT Intent
Intent getContentIntent = FileUtils.createGetContentIntent();
Intent intent = Intent.createChooser(getContentIntent, "Select a file");
startActivityForResult(intent, Constants.REQUEST_CHOOSER);
sweetAlertDialog.dismissWithAnimation();
}
});
pDialog.setCancelText("Internet");
pDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
/* check the device network state */
if (!isOnline()){
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.WARNING_TYPE)
.setContentText("Your device is now offline!\n" +
"Please open your Network.")
.setTitleText("Open Network Connection")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
showNoConnectionDialog(MainActivity.this);
sweetAlertDialog.dismissWithAnimation();
}
})
.show();
}else {
// Create the intent to start video activity
Intent i = new Intent(MainActivity.this, LocalVideoActivity.class);
i.putExtra(Constants.EXTRA_ANSWER_IS_TRUE, vidAddress);
startActivity(i);
sweetAlertDialog.dismissWithAnimation();
}
}
});
pDialog.setCancelable(true);
pDialog.show();
}
});
mPlayback_bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.NORMAL_TYPE)
.setContentText("Please first label some video!\n" +
"Later come back here!.")
.setTitleText("Playback")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.dismissWithAnimation();
}
})
.show();
}
});
mChart_bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ChartRecyclerView.class);
startActivityForResult(i, Constants.REQUEST_CHART);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Constants.REQUEST_CHOOSER:
if (resultCode == RESULT_OK) {
final Uri uri = data.getData();
// Get the File path from the Uri
String path = FileUtils.getPath(this, uri);
Toast.makeText(this, "Choosen file: " + path,Toast.LENGTH_LONG).show();
// Alternatively, use FileUtils.getFile(Context, Uri)
if (path != null && FileUtils.isLocal(path)) {
File file = new File(path);
}
// Create the intent to start video activity
Intent i = new Intent(MainActivity.this, LocalVideoActivity.class);
i.putExtra(Constants.EXTRA_ANSWER_IS_TRUE,path);
startActivity(i);
}
break;
}
}
/*
* This method checks network situation, if device is airplane mode or something went wrong on
* network stuff. Method returns false, otherwise return true.
*
* - This function inspired by below link,
* http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-timeouts
*
* @return boolean - network state
* * * */
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
/**
* Display a dialog that user has no internet connection
* @param ctx1
*
* Code from: http://osdir.com/ml/Android-Developers/2009-11/msg05044.html
*/
public static void showNoConnectionDialog(Context ctx1) {
final Context ctx = ctx1;
final SweetAlertDialog builder = new SweetAlertDialog(ctx, SweetAlertDialog.SUCCESS_TYPE);
builder.setCancelable(true);
builder.setContentText("Open internet connection");
builder.setTitle("No connection error!");
builder.setConfirmText("Open wirless.");
builder.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
ctx.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
builder.dismissWithAnimation();
}
});
builder.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}else if (id == R.id.action_search){
openSearch();
return true;
}
return super.onOptionsItemSelected(item);
}
private void openSearch() {
Toast.makeText(this,"Clicked Search button", Toast.LENGTH_SHORT).show();
}
}
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Marionette Components</title>
</head>
<body>
Marionette View Test
<script src='../build/view.js'></script>
</body>
</html>
| Java |
---
title: 分享-认同 的魅力
tags:
---
| Java |
<?php
namespace Oro\Bundle\ApiBundle\Processor\Shared\Rest;
use Oro\Bundle\ApiBundle\Metadata\RouteLinkMetadata;
use Oro\Bundle\ApiBundle\Processor\Context;
use Oro\Bundle\ApiBundle\Provider\ResourcesProvider;
use Oro\Bundle\ApiBundle\Request\AbstractDocumentBuilder as ApiDoc;
use Oro\Bundle\ApiBundle\Request\ApiAction;
use Oro\Bundle\ApiBundle\Request\RequestType;
use Oro\Bundle\ApiBundle\Request\Rest\RestRoutesRegistry;
use Oro\Component\ChainProcessor\ContextInterface;
use Oro\Component\ChainProcessor\ProcessorInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Adds "self" HATEOAS link to a whole document of success response.
* @link https://jsonapi.org/recommendations/#including-links
*/
class AddHateoasLinks implements ProcessorInterface
{
/** @var RestRoutesRegistry */
private $routesRegistry;
/** @var UrlGeneratorInterface */
private $urlGenerator;
/** @var ResourcesProvider */
private $resourcesProvider;
/**
* @param RestRoutesRegistry $routesRegistry
* @param UrlGeneratorInterface $urlGenerator
* @param ResourcesProvider $resourcesProvider
*/
public function __construct(
RestRoutesRegistry $routesRegistry,
UrlGeneratorInterface $urlGenerator,
ResourcesProvider $resourcesProvider
) {
$this->routesRegistry = $routesRegistry;
$this->urlGenerator = $urlGenerator;
$this->resourcesProvider = $resourcesProvider;
}
/**
* {@inheritdoc}
*/
public function process(ContextInterface $context)
{
/** @var Context $context */
$documentBuilder = $context->getResponseDocumentBuilder();
if (null === $documentBuilder || !$context->isSuccessResponse()) {
return;
}
$requestType = $context->getRequestType();
$entityClass = $context->getClassName();
if (ApiAction::GET_LIST !== $context->getAction()
&& $this->isGetListActionExcluded($entityClass, $context->getVersion(), $requestType)
) {
return;
}
$documentBuilder->addLinkMetadata(ApiDoc::LINK_SELF, new RouteLinkMetadata(
$this->urlGenerator,
$this->routesRegistry->getRoutes($requestType)->getListRouteName(),
[],
['entity' => $documentBuilder->getEntityAlias($entityClass, $requestType)]
));
}
/**
* @param string $entityClass
* @param string $version
* @param RequestType $requestType
*
* @return bool
*/
private function isGetListActionExcluded(string $entityClass, string $version, RequestType $requestType): bool
{
return \in_array(
ApiAction::GET_LIST,
$this->resourcesProvider->getResourceExcludeActions($entityClass, $version, $requestType),
true
);
}
}
| Java |
Başardım :)
| Java |
const
path = require('path'),
fs = require('fs'),
glob = require('glob'),
pug = require('pug'),
stylus = require('stylus'),
nib = require('nib'),
autoprefixer = require('autoprefixer-stylus'),
{rollup} = require('rollup'),
rollupPluginPug = require('rollup-plugin-pug'),
rollupPluginResolve = require('rollup-plugin-node-resolve'),
rollupPluginReplace = require('rollup-plugin-replace'),
rollupPluginCommonjs = require('rollup-plugin-commonjs'),
rollupPluginGlobImport = require('rollup-plugin-glob-import'),
rollupPluginAlias = require('rollup-plugin-alias'),
rollupPluginBabel = require('rollup-plugin-babel'),
sgUtil = require('./util');
class AppBuilder {
constructor(conf, CollectorStore) {
this.conf = conf;
this.CollectorStore = CollectorStore;
this.name = this.conf.get('package.name');
this.viewerDest = this.conf.get('viewerDest');
this.source = path.resolve(__dirname, '..', 'app');
this.sections = [];
this.generateViewerPages = this.generateViewerPages.bind(this);
this.generateViewerStyles = this.generateViewerStyles.bind(this);
this.rollupViewerScripts = this.rollupViewerScripts.bind(this);
this.getViewerPagesLocals = this.getViewerPagesLocals.bind(this);
this.onEnd = this.onEnd.bind(this);
}
renderCollected() {
if (!this.watcher) {
this.CollectorStore.getFiles()
.forEach(async (file) => {
if (!file.exclude) {
await file.render;
}
});
}
return this;
}
saveCollectedData() {
if (!this.watcher) {
const {viewerDest, CollectorStore: {getCollectedData}} = this;
sgUtil.writeJsonFile(path.join(viewerDest, 'structure.json'), getCollectedData());
}
}
getViewerPagesLocals() {
return {
description: this.conf.get('package.description', 'No description'),
version: this.conf.get('version', this.conf.get('package.version') || 'dev')
};
}
onEnd(message) {
return (error) => {
if (error) {
throw error;
}
sgUtil.log(`[✓] ${this.name} ${message}`, 'info');
};
}
async generateViewerPages() {
const
{source, viewerDest, getViewerPagesLocals} = this,
onEnd = this.onEnd('viewer html generated.'),
templateFile = path.join(source, 'templates', 'viewer', 'index.pug'),
renderOptions = Object.assign({
pretty: true,
cache: false
},
getViewerPagesLocals());
sgUtil.writeFile(path.join(viewerDest, 'index.html'), pug.renderFile(templateFile, renderOptions), onEnd);
}
async generateViewerStyles() {
const
{source, viewerDest} = this,
onEnd = this.onEnd('viewer css generated.'),
stylusStr = glob.sync(`${source}/style/**/!(_)*.styl`)
.map((file) => fs.readFileSync(file, 'utf8'))
.join('\n');
stylus(stylusStr)
.set('include css', true)
.set('prefix', 'dsc-')
.use(nib())
.use(autoprefixer({
browsers: ['> 5%', 'last 1 versions'],
cascade: false
}))
.include(path.join(source, 'style'))
.import('_reset')
.import('_mixins')
.import('_variables')
.render((err, css) => {
if (err) {
onEnd(err);
}
else {
sgUtil.writeFile(path.join(viewerDest, 'css', 'app.css'), css, onEnd);
}
});
}
async rollupViewerScripts() {
const
{source, viewerDest} = this,
destFile = path.join(viewerDest, 'scripts', 'app.js');
sgUtil.createPath(destFile);
try {
const bundle = await rollup({
input: path.join(source, 'scripts', 'index.js'),
plugins: [
rollupPluginGlobImport({
rename(name, id) {
if (path.basename(id) !== 'index.js') {
return null;
}
return path.basename(path.dirname(id));
}
}),
rollupPluginAlias({
vue: 'node_modules/vue/dist/vue.esm.js'
}),
rollupPluginResolve({
jsnext: true,
main: true,
module: true
}),
rollupPluginPug(),
rollupPluginReplace({
'process.env.NODE_ENV': JSON.stringify('development')
}),
rollupPluginCommonjs(),
rollupPluginBabel()
]
});
await bundle.write({
file: destFile,
format: 'iife',
sourcemap: false
});
}
catch (error) {
throw error;
}
this.onEnd('viewer js bundle generated.');
}
}
module.exports = AppBuilder;
| Java |
package org.xcolab.client.contest.pojo;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.xcolab.client.contest.pojo.tables.pojos.ContestCollectionCard;
@JsonDeserialize(as = ContestCollectionCard.class)
public interface IContestCollectionCard {
Long getId();
void setId(Long id);
Long getParent();
void setParent(Long parent);
Long getBigOntologyTerm();
void setBigOntologyTerm(Long bigOntologyTerm);
Long getSmallOntologyTerm();
void setSmallOntologyTerm(Long smallOntologyTerm);
String getDescription();
void setDescription(String description);
String getShortName();
void setShortName(String shortName);
Boolean isVisible();
void setVisible(Boolean visible);
Integer getSortOrder();
void setSortOrder(Integer sortOrder);
Long getOntologyTermToLoad();
void setOntologyTermToLoad(Long ontologyTermToLoad);
Boolean isOnlyFeatured();
void setOnlyFeatured(Boolean onlyFeatured);
}
| Java |
Style
=====
**Author**: gejiawen
**Email**: gejiawen@baidu.com
**Desp**:
> 将会阐述一些基本的代码样式、文件命名、变量命名、代码组织等规范 | Java |
<!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Text Editor</title>
<link href="favicon.ico" rel="shortcut icon">
</head>
<body spellcheck="false">
<p style="
background: #ffa;
border: 1px dashed;
margin-top: 0;
padding: .75em 1em;
">Like this project? Please support my <a href="https://github.com/mecha-cms">Mecha CMS</a> project too. Thank you!</p>
<h1>Text Editor</h1>
<p><textarea style="display:block;width:100%;height:6em;box-sizing:border-box;">Lorem ipsum dolor sit amet.</textarea></p>
<p>
<button onclick="editor.wrap('<b>', '</b>');"><b>B</b></button>
<button onclick="editor.wrap('<i>', '</i>');"><i>I</i></button>
<button onclick="editor.insert('😀', -1, true);">☺</button>
</p>
<h2>Features</h2>
<ul>
<li>Light-weight library. No dependencies. <strong>Text Editor</strong> uses plain JavaScript language.</li>
<li>Simple <abbr title="Application Programming Interface">API</abbr>. Easy to learn.</li>
<li>Extensible → <a href="#examples">check it out</a></li>
<li>No hack. No feature detection. Optimized for modern browsers with their built-in JavaScript features.</li>
<li>Make your own. The core functionality is enough to help you making your own text editor.</li>
</ul>
<h2>Start</h2>
<pre><code><!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="utf-8">
</head>
<body>
<p><textarea></textarea></p>
<script src="<a href="text-editor.min.js" target="_blank">text-editor.min.js</a>"></script>
<script>
var editor = new TE(document.querySelector('textarea'));
</script>
</body>
</html></code></pre>
<h2>Configure</h2>
<pre><code>var editor = new TE(<var>self</var>, <var>tab</var> = '\t');</code></pre>
<pre><code>var editor = new TE(<var>self</var>, <var>state</var> = {
tab: '\t'
});</code></pre>
<ul>
<li><var>self</var> → The text area element.</li>
<li><var>tab</var> → The default indent character for <code>editor.pull()</code> and <code>editor.push()</code> method.</li>
<li><var>state</var> → The configuration data.</li>
<li><var>state.tab</var> → The default indent character for <code>editor.pull()</code> and <code>editor.push()</code> method.</li>
</ul>
<h2>Instance</h2>
<p>All editor instances will be stored in <code>TE.__instance__</code>. To iterate the instances is possible with <code>TE.each()</code>:</p>
<pre><code>TE.each(function(key) {
console.log(key);
console.log(this.self);
});</code></pre>
<ul>
<li><var>this</var> → Refers to the text editor instance.</li>
<li><var>key</var> → Refers to the text editor target’s <code>id</code> or <code>name</code> attribute value, or its current order.</li>
</ul>
<h2>Methods and Properties</h2>
<h3>TE.version</h3>
<p>Return the text editor version.</p>
<h3>TE.x</h3>
<p>List of regular expression characters to be escaped.</p>
<h3>TE.esc(input)</h3>
<p>Escape regular expression characters listed in <code>TE.x</code> from a string or array input.</p>
<h3>TE._</h3>
<p>Return the text editor prototypes.</p>
<h3>editor.state</h3>
<p>Return the text editor states if any.</p>
<h3>editor.self</h3>
<p>Return the <code><textarea></code> element.</p>
<h3>editor.source</h3>
<p>Alias for <code>editor.self</code> property.</p>
<h3>editor.value</h3>
<p>Return the initial value of the <code><textarea></code> element.</p>
<h3>editor.set(value)</h3>
<p>Set value to the <code><textarea></code> element.</p>
<h3>editor.let()</h3>
<p>Reset value to the initial value of the <code><textarea></code> element.</p>
<h3>editor.get()</h3>
<p>Get current value of the <code><textarea></code> element if not empty, otherwise, return <code>null</code>.</p>
<h3>editor.$()</h3>
<p>Get current text selection data.</p>
<pre><code>// `a|b|c`
console.log(editor.$()); // `{"start":1,"end":2,"value":"b","before":"a","after":"c","length":1}`</code></pre>
<h3>editor.focus(mode = 0)</h3>
<p>Focus to the <code><textarea></code>.</p>
<pre><code>editor.focus(); // Focus to the last selection
editor.focus(-1); // Focus to the start of text area value
editor.focus(1); // Focus to the end of text area value
editor.focus(true); // Select all</code></pre>
<h3>editor.blur()</h3>
<p>Blur from the <code><textarea></code>.</p>
<h3>editor.select(...args)</h3>
<p>Set selection range.</p>
<pre><code>editor.select(); // Is the same as `editor.focus()`
editor.select(2); // Move caret to the index `2`
editor.select(0, 2); // Select from range `0` to `2`
editor.select(true); // Select all</code></pre>
<h3>editor.match(pattern, fn)</h3>
<p>Match current selection with the pattern provided.</p>
<pre><code>if (editor.match(/^\s*:\w+:\s*$/)) {
alert('Selection is detected as emoji!'); // → <a href="text-editor.match.html" target="_blank">demo</a>
}</code></pre>
<p>Do something with the current matched selection.</p>
<pre><code>var maps = {
':happy:': '😀',
':sad:': '😩',
':wonder:': '😕'
}
editor.match(/^\s*:\w+:\s*$/, function(m) {
var exists = maps[m[0] = m[0] ? m[0].trim() : ""];
exists && this.insert(exists); // → <a href="text-editor.alter.html" target="_blank">demo</a>
});</code></pre>
<p>Match to the characters before selection, current selection and characters after selection.</p>
<pre><code>var test = editor.match([/:$/, /^\w+$/, /^:/]);
console.log(test[0] && test[1] && test[2]);</code></pre>
<pre><code>editor.match([/:$/, /^\w+$/, /^:/], function(before, value, after) {
console.log([before, value, after]); // → <a href="text-editor.toggle.html" target="_blank">demo</a>
});</code></pre>
<h3>editor.replace(from, to, mode = 0)</h3>
<p>Replace current, before or after selection from <var>from</var> to <var>to</var>.</p>
<pre><code>editor.replace(/<.*?>/g, ""); // Strip HTML tags in selection
editor.replace(/<.*?>/g, "", -1); // Strip HTML tags before selection
editor.replace(/<.*?>/g, "", 1); // Strip HTML tags after selection</code></pre>
<h3>editor.insert(string, mode = 0, clear = false)</h3>
<p>Insert <var>string</var> to (replace) the current selection.</p>
<pre><code>editor.insert(':)'); // Insert at selection (replace selection)
editor.insert('<b>', -1); // Insert before selection
editor.insert('</b>', 1); // Insert after selection
editor.insert(':)', -1, true); // Insert before selection and delete selection
editor.insert(':)', 1, true); // Insert after selection and delete selection</code></pre>
<h3>editor.wrap(open, close, wrap = false)</h3>
<p>Wrap current selection with <var>open</var> and <var>close</var>.</p>
<pre><code>editor.wrap('<', '>'); // Wrap with `<` and `>`
editor.wrap('<', '>', true); // Wrap with `<` and `>` then select</code></pre>
<h3>editor.peel(open, close, wrap = false)</h3>
<p>Unwrap current selection from <var>open</var> and <var>close</var>.</p>
<pre><code>editor.peel('<', '>'); // Remove `<` before selection and `>` after selection
editor.peel('<', '>', true); // Remove `<` at selection start and `>` at selection end
editor.peel(/<+/, />+/); // Remove any `<` before selection and any `>` after selection
editor.peel(/<+/, />+/, true); // Remove any `<` at selection start and any `>` at selection end</code></pre>
<h3>editor.push(by = '\t', includeEmptyLines = false)</h3>
<p>Indent current selection with <var>by</var>.</p>
<pre><code>editor.push(); // Indent with `\t`
editor.push('****'); // Indent with `****`</code></pre>
<h3>editor.pull(by = '\t', includeEmptyLines = true)</h3>
<p>Outdent current selection from <var>by</var>.</p>
<pre><code>editor.pull(); // Outdent from `\t`
editor.pull('****'); // Outdent from `****`
editor.pull(/[\t ]+/); // Outdent from any length of white-space</code></pre>
<h3>editor.trim(open = "", close = "", start = "", end = "", tidy = true)</h3>
<p>Trim current selection from white-spaces, and optionally insert characters at the specified points.</p>
<pre><code>// `a<open><mark><start>b<end></mark><close>c`
editor.trim(); // Remove any white-spaces before and after selection, start and end of selection
editor.trim(false, false); // Remove any white-spaces at the start and end of selection
editor.trim("", "", false, false); // Remove any white-spaces before and after selection
editor.trim(' ', ' '); // Force a space before and after selection
editor.trim('\n\n', '\n\n'); // Force line-break before and after selection
editor.trim('\n\n', '\n\n', "", "", false); // Ignore empty value before and after selection, just insert that `\n\n` away</code></pre>
<h2 id="examples">Examples</h2>
<ul>
<li><a href="text-editor.html" target="_blank">No Idea?</a></li>
<li><a href="text-editor.self.html" target="_blank">Multiple Instances</a></li>
<li><a href="text-editor.disabled.html" target="_blank">Disabled Input</a></li>
<li><a href="text-editor.read-only.html" target="_blank">Read-Only Input</a></li>
<li><a href="text-editor.get,let,set.html" target="_blank">Set, Get and Let Value</a></li>
<li><a href="text-editor.$.html" target="_blank">Get Selection Data</a></li>
<li><a href="text-editor.blur,focus.html" target="_blank">Focus, Blur Events</a></li>
<li><a href="text-editor.select.html" target="_blank">Set Selection Range</a></li>
<li><a href="text-editor.match.html" target="_blank">Match Selection</a></li>
<li><a href="text-editor.alter.html" target="_blank">Alter Selection</a></li>
<li><a href="text-editor.toggle.html" target="_blank">Toggle Replace Selection</a></li>
<li><a href="text-editor.replace.html" target="_blank">Replace Selection</a></li>
<li><a href="text-editor.insert.html" target="_blank">Insert Selection</a></li>
<li><a href="text-editor.peel,wrap.html" target="_blank">Wrap, Peel Selection</a></li>
<li><a href="text-editor.pull,push.html" target="_blank">Indent, Outdent Selection</a></li>
<li><a href="text-editor.pull,push.type.html" target="_blank">Indent, Outdent by Custom Character</a></li>
<li><a href="text-editor.pull,push.key.html" target="_blank">Indent, Outdent with Keyboard Key</a></li>
<li><a href="text-editor.trim.html" target="_blank">Trim Selection</a></li>
<li><a href="text-editor/rect.html" target="_blank">Get Selection Offset</a> (<a href="text-editor/rect.min.js" target="_blank">+rect.min.js</a>)</li>
<li><a href="text-editor/rect.caret.html" target="_blank">Custom Caret Example</a></li>
<li><a href="text-editor/history.html" target="_blank">Undo and Redo Feature</a> (<a href="text-editor/history.min.js" target="_blank">+history.min.js</a>)</li>
<li><a href="text-editor/source.html" target="_blank">Source Code Editor</a> (<a href="text-editor/source.min.js" target="_blank">+source.min.js</a>)</li>
</ul>
<script src="text-editor.js"></script>
<script>
var editor = new TE(document.querySelector('textarea'));
</script>
</body>
</html>
| Java |
module ActiveWarehouse #:nodoc:
# Class that supports prejoining a fact table with dimensions. This is useful if you need
# to list facts along with some or all of their detail information.
class PrejoinFact
# The fact class that this engine instance is connected to
attr_accessor :fact_class
delegate :prejoined_table_name,
:connection,
:prejoined_fields,
:dimension_relationships,
:dimension_class,
:table_name,
:columns, :to => :fact_class
# Initialize the engine instance
def initialize(fact_class)
@fact_class = fact_class
end
# Populate the prejoined fact table.
def populate(options={})
populate_prejoined_fact_table(options)
end
protected
# Drop the storage table
def drop_prejoin_fact_table
connection.drop_table(prejoined_table_name) if connection.tables.include?(prejoined_table_name)
end
# Get foreign key names that are excluded.
def excluded_foreign_key_names
excluded_dimension_relations = prejoined_fields.keys.collect {|k| dimension_relationships[k]}
excluded_dimension_relations.collect {|r| r.foreign_key}
end
# Construct the prejoined fact table.
def create_prejoined_fact_table(options={})
connection.transaction {
drop_prejoin_fact_table
connection.create_table(prejoined_table_name, :id => false) do |t|
# get all columns except the foreign_key columns for prejoined dimensions
columns.each do |c|
t.column(c.name, c.type) unless excluded_foreign_key_names.include?(c.name)
end
#prejoined_columns
prejoined_fields.each_pair do |key, value|
dclass = dimension_class(key)
dclass.columns.each do |c|
t.column(c.name, c.type) if value.include?(c.name.to_sym)
end
end
end
}
end
# Populate the prejoined fact table.
def populate_prejoined_fact_table(options={})
fact_columns_string = columns.collect {|c|
"#{table_name}." + c.name unless excluded_foreign_key_names.include?(c.name)
}.compact.join(",\n")
prejoined_columns = []
tables_and_joins = "#{table_name}"
prejoined_fields.each_pair do |key, value|
dimension = dimension_class(key)
tables_and_joins += "\nJOIN #{dimension.table_name} as #{key}"
tables_and_joins += "\n ON #{table_name}.#{dimension_relationships[key].foreign_key} = "
tables_and_joins += "#{key}.#{dimension.primary_key}"
prejoined_columns << value.collect {|v| "#{key}." + v.to_s}
end
if connection.support_select_into_table?
drop_prejoin_fact_table
sql = <<-SQL
SELECT #{fact_columns_string},
#{prejoined_columns.join(",\n")}
FROM #{tables_and_joins}
SQL
sql = connection.add_select_into_table(prejoined_table_name, sql)
else
create_prejoined_fact_table(options)
sql = <<-SQL
INSERT INTO #{prejoined_table_name}
SELECT #{fact_columns_string},
#{prejoined_columns.join(",\n")}
FROM #{tables_and_joins}
SQL
end
connection.transaction { connection.execute(sql) }
end
end
end
| Java |
from array import array
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import classification_report, roc_auc_score, roc_curve
from sklearn import tree
import cPickle
data = np.load('/Users/musthero/Documents/Yura/Applications/tmva_local/output_electrons_fullsim_v5_VeryTightLH_20per.npz')
# Train on the first 2000, test on the rest
X_train, y_train = data['data_training'], data['isprompt_training'].ravel()
X_test, y_test = data['data_testing'][0:1000], data['isprompt_testing'][0:1000].ravel()
# sklearn
dt = DecisionTreeClassifier(max_depth=3,
min_samples_leaf=100)
#min_samples_leaf=0.05*len(X_train))
doFit = False
if doFit:
print "Performing DecisionTree fit..."
dt.fit(X_train, y_train)
import cPickle
with open('electrons_toTMVA.pkl', 'wb') as fid:
cPickle.dump(dt, fid)
else:
print "Loading DecisionTree..."
# load it again
with open('electrons_toTMVA.pkl', 'rb') as fid:
dt = cPickle.load(fid)
#sk_y_predicted = dt.predict(X_test)
#sk_y_predicted = dt.predict_proba(X_test)[:, 1]
sk_y_predicted = dt.predict_proba(X_test)[:, 1]
predictions = dt.predict(X_test)
print predictions
print y_test
# Draw ROC curve
fpr, tpr, _ = roc_curve(y_test, sk_y_predicted)
plt.figure()
plt.plot(fpr, tpr, label='ROC curve of class')
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Some extension of Receiver operating characteristic to multi-class')
plt.legend(loc="lower right")
plt.savefig("output_fullsim_v5_electrons_roc_20per_DecisionTree.png", dpi=144)
tree.export_graphviz(dt, out_file='dt_viz.dot')
# Save to file fpr, tpr
#np.savez('output_fullsim_v3_electrons_fpr_tpr_10per.npz',
# fpr=fpr, tpr=tpr) | Java |
---
layout: default
og_type: article
---
<article class="post grid u-pad-both pjax-animate">
<section class="grid__row">
<span class="post__date typography__mono">{{ page.date | date: "%-d %B %Y" }}</span>
{{ content }}
</section>
</article>
{% if page.comments != Nil %}
{% assign showComments = page.comments %}
{% else %}
{% assign showComments = site.comments %}
{% endif %}
{% if showComments %}
{% include blog-comments.html %}
{% endif %}
{% include blog-newsletter.html %}
{% if page.next_in_category != nil %}
{% assign nextpage = page.next_in_category %}
{% else %}
{% assign nextpage = page.first_in_category %}
{% endif %}
<section class="related-posts">
<a class="related-posts__link grid u-default-v-padding u-bg-natt-dark" href="{{ site.baseurl }}{{ nextpage.url }}">
<div class="grid__row">
<p class="related-posts__label typography__mono">Read Next</p>
<h2 class="related-posts__title">{{ nextpage.title }}</h2>
</div>
</a>
</section>
{% include footer.html %}
| Java |
package utils;
import java.io.*;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ueb01.StringBufferImpl;
/**
* Created with IntelliJ IDEA.
* User: Julian
* Date: 16.10.13
* Time: 13:37
*/
public class Utils {
private static long currentTime;
/**
* http://svn.apache.org/viewvc/camel/trunk/components/camel-test/src/main/java/org/apache/camel/test/AvailablePortFinder.java?view=markup#l130
* Checks to see if a specific port is available.
*
* @param port the port to check for availability
*/
public static boolean available(int port) {
ServerSocket ss = null;
DatagramSocket ds = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
ds = new DatagramSocket(port);
ds.setReuseAddress(true);
return true;
} catch (IOException e) {
} finally {
if (ds != null) {
ds.close();
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
/* should not be thrown */
}
}
}
return false;
}
public static void stopwatchStart() {
currentTime = java.lang.System.nanoTime();
}
static ExecutorService pool = null;
public static class SyncTcpResponse {
public final Socket socket;
public final String message;
public boolean isValid() {
return this.socket != null;
}
public SyncTcpResponse(Socket s, String m) {
this.socket = s;
this.message = m;
}
}
public static String getTCPSync(final Socket socket) {
StringBuilder sb = new StringBuilder();
try {
Scanner s = new Scanner(socket.getInputStream());
while (s.hasNext()) {
sb.append(s.next());
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public static SyncTcpResponse getTCPSync(final int port) {
ServerSocket server = null;
Socket client = null;
StringBuilder sb = new StringBuilder();
try {
server = new ServerSocket(port);
client = server.accept();
Scanner s = new Scanner(client.getInputStream());
while (s.hasNext()) {
sb.append(s.next());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (server != null) try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return new SyncTcpResponse(client, sb.toString());
}
public static Future<String> getTCP(final int port) {
if (pool == null) {
pool = Executors.newCachedThreadPool();
}
return pool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
ServerSocket server = null;
/*try(ServerSocket socket = new ServerSocket(port)){
Socket client = socket.accept();
Scanner s = new Scanner(client.getInputStream());
StringBuilder sb = new StringBuilder();
while (s.hasNext()){
sb.append(s.next());
}
return sb.toString();
} */
return null;
}
});
}
public static Socket sendTCP(InetAddress address, int port, String message) {
try {
Socket s = new Socket(address, port);
return sendTCP(s, message);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static Socket sendTCP(Socket socket, String message) {
PrintWriter out = null;
try {
out = new PrintWriter(socket.getOutputStream());
out.println(message);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return socket;
}
public static void close() {
if (pool != null) {
pool.shutdown();
}
}
public static String wordFromScanner(Scanner scanner) {
StringBuilder result = new StringBuilder();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line);
result.append("\n");
}
return result.toString();
}
public static String[] wordsFromScanner(Scanner scanner) {
List<String> result = new ArrayList<String>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] words = line.split(" ");
for (String word : words) {
if (word.length() > 0)
result.add(wordify(word));
}
}
return Utils.<String>listToArrayStr(result);
}
public static String wordify(String word) {
return word.replace(",", "").replace(".", "").replace("'", "").replace("\"", "")
.replace("...", "").replace("!", "").replace(";", "").replace(":", "").toLowerCase();
}
public static <T> T[] listToArray(List<T> list) {
T[] result = (T[]) new Object[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
public static String[] listToArrayStr(List<String> list) {
String[] result = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
public static void stopwatchEnd() {
long current = java.lang.System.nanoTime();
long dif = current - currentTime;
long millis = dif / 1000000;
System.out.println("Millis: {" + millis + "} Nanos: {" + dif + "}");
}
/**
* Method to send a command to a Process
*
* @param p
* @param command
*/
public static void send(Process p, String command) {
OutputStream os = p.getOutputStream();
try {
os.write(command.getBytes());
} catch (IOException e) {
System.out.println("something went wrong... [Utils.send(..) -> " + e.getMessage());
} finally {
try {
os.close();
} catch (IOException e) {
System.out.println("something went wrong while closing... [Utils.send(..) -> " + e.getMessage());
}
}
}
public static void close(Process p) {
try {
p.getOutputStream().close();
p.getInputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* easy exceptionless sleep
*
* @param millis
*/
public static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("ALP5: Utils::sleep crashed..");
}
}
public static int countCharactersInFile(String fileName) {
BufferedReader br = null;
try {
StringBuilder sb = new StringBuilder();
br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
return sb.length();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("shit happens... @Utils.countCharactersInFile");
return -1;
} catch (IOException e) {
e.printStackTrace();
System.out.println("shit happens while reading... @Utils.countCharactersInFile");
} finally {
if (br != null) try {
br.close();
} catch (IOException e) {
e.printStackTrace();
return -2;
}
}
return -3;
}
public static String join(String[] l, String connector) {
StringBuilder sb = new StringBuilder();
for (String s : l) {
if (sb.length() > 0) {
sb.append(connector);
}
sb.append(s);
}
return sb.toString();
}
public static String readFromStream(InputStream is){
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
/**
* Method to receive the output of a Process
*
* @param p
* @return
*/
public static String read(Process p) {
StringBuilder sb = new StringBuilder();
InputStream is = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String s = null;
try {
while ((s = reader.readLine()) != null) {
if (s.equals("") || s.equals(" ")) break;
sb.append(s);
}
} catch (IOException e) {
System.out.println("something went wrong... [Utils.read(..) -> " + e.getMessage());
}
return sb.toString();
}
public static void main(String[] args) throws IOException, InterruptedException {
System.out.println("yyy");
System.out.println('a' > 'b');
}
/**
* If you want to use your ssh-key-login, you need to generate a pem-File from
* the ssh-private-key and put it into the main folder ( ALP5/ ); You also need
* to define the user with @ (like: jutanke@peking.imp.fu-berlin.de:...)
*
* @param commandId
* @return
*/
public static Process fork(String commandId) {
String username = null; // HARDCODE ME!
String password = null; // HARDCODE ME!
String host = null;
String command = commandId;
if (commandId.contains(":")) {
String[] temp = commandId.split(":");
if (temp[0].length() > 2) {
// if the host is shorter its probably just a windows drive ('d:// ...')
host = temp[0];
if (host.contains("@")) {
String[] t = host.split("@");
username = t[0];
host = t[1];
}
if (temp.length == 3) {
command = temp[1] + ":" + temp[2]; // to "repair" windows drives...
} else {
command = temp[1];
}
}
}
if (host != null) {
Process remoteP = null;
try {
final Connection conn = new Connection(host);
conn.connect();
boolean isAuth = false;
if (password != null) {
isAuth = conn.authenticateWithPassword(username, password);
}
if (!isAuth) {
File f = new File("private.pem");
isAuth = conn.authenticateWithPublicKey(username, f, "");
if (!isAuth) return null;
}
final Session sess = conn.openSession();
sess.execCommand(command);
remoteP = new Process() {
@Override
public OutputStream getOutputStream() {
return sess.getStdin();
}
@Override
public InputStream getInputStream() {
return sess.getStdout();
}
@Override
public InputStream getErrorStream() {
return sess.getStderr();
}
@Override
public int waitFor() throws InterruptedException {
sess.wait();
return 0;
}
@Override
public int exitValue() {
return 0;
}
@Override
public void destroy() {
sess.close();
conn.close();
}
};
} catch (IOException e) {
System.out.println("shit happens with the ssh connection: @Utils.fork .. " + e.getMessage());
return null;
}
return remoteP;
}
ProcessBuilder b = new ProcessBuilder(command.split(" "));
try {
return b.start();
} catch (IOException e) {
System.out.println("shit happens: @Utils.fork .. " + e.getMessage());
}
return null;
}
}
| Java |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { onUnexpectedError } from 'vs/base/common/errors';
import { IDisposable } from 'vs/base/common/lifecycle';
import { URI, UriComponents } from 'vs/base/common/uri';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Range } from 'vs/editor/common/core/range';
import { ITextModel } from 'vs/editor/common/model';
import { IEditorWorkerService } from 'vs/editor/common/services/editorWorkerService';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { extHostNamedCustomer } from 'vs/workbench/api/electron-browser/extHostCustomers';
import { ExtHostContext, ExtHostDocumentContentProvidersShape, IExtHostContext, MainContext, MainThreadDocumentContentProvidersShape } from '../node/extHost.protocol';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
@extHostNamedCustomer(MainContext.MainThreadDocumentContentProviders)
export class MainThreadDocumentContentProviders implements MainThreadDocumentContentProvidersShape {
private readonly _resourceContentProvider = new Map<number, IDisposable>();
private readonly _pendingUpdate = new Map<string, CancellationTokenSource>();
private readonly _proxy: ExtHostDocumentContentProvidersShape;
constructor(
extHostContext: IExtHostContext,
@ITextModelService private readonly _textModelResolverService: ITextModelService,
@IModeService private readonly _modeService: IModeService,
@IModelService private readonly _modelService: IModelService,
@IEditorWorkerService private readonly _editorWorkerService: IEditorWorkerService
) {
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostDocumentContentProviders);
}
dispose(): void {
this._resourceContentProvider.forEach(p => p.dispose());
this._pendingUpdate.forEach(source => source.dispose());
}
$registerTextContentProvider(handle: number, scheme: string): void {
const registration = this._textModelResolverService.registerTextModelContentProvider(scheme, {
provideTextContent: (uri: URI): Thenable<ITextModel> => {
return this._proxy.$provideTextDocumentContent(handle, uri).then(value => {
if (typeof value === 'string') {
const firstLineText = value.substr(0, 1 + value.search(/\r?\n/));
const languageSelection = this._modeService.createByFilepathOrFirstLine(uri.fsPath, firstLineText);
return this._modelService.createModel(value, languageSelection, uri);
}
return undefined;
});
}
});
this._resourceContentProvider.set(handle, registration);
}
$unregisterTextContentProvider(handle: number): void {
const registration = this._resourceContentProvider.get(handle);
if (registration) {
registration.dispose();
this._resourceContentProvider.delete(handle);
}
}
$onVirtualDocumentChange(uri: UriComponents, value: string): void {
const model = this._modelService.getModel(URI.revive(uri));
if (!model) {
return;
}
// cancel and dispose an existing update
if (this._pendingUpdate.has(model.id)) {
this._pendingUpdate.get(model.id).cancel();
}
// create and keep update token
const myToken = new CancellationTokenSource();
this._pendingUpdate.set(model.id, myToken);
this._editorWorkerService.computeMoreMinimalEdits(model.uri, [{ text: value, range: model.getFullModelRange() }]).then(edits => {
// remove token
this._pendingUpdate.delete(model.id);
if (myToken.token.isCancellationRequested) {
// ignore this
return;
}
if (edits.length > 0) {
// use the evil-edit as these models show in readonly-editor only
model.applyEdits(edits.map(edit => EditOperation.replace(Range.lift(edit.range), edit.text)));
}
}).catch(onUnexpectedError);
}
}
| Java |
//---------------------------------------------------------------------------
//
// <copyright file="ByteAnimationUsingKeyFrames.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// This class is used to animate a Byte property value along a set
/// of key frames.
/// </summary>
[ContentProperty("KeyFrames")]
public class ByteAnimationUsingKeyFrames : ByteAnimationBase, IKeyFrameAnimation, IAddChild
{
#region Data
private ByteKeyFrameCollection _keyFrames;
private ResolvedKeyFrameEntry[] _sortedResolvedKeyFrames;
private bool _areKeyTimesValid;
#endregion
#region Constructors
/// <Summary>
/// Creates a new KeyFrameByteAnimation.
/// </Summary>
public ByteAnimationUsingKeyFrames()
: base()
{
_areKeyTimesValid = true;
}
#endregion
#region Freezable
/// <summary>
/// Creates a copy of this KeyFrameByteAnimation.
/// </summary>
/// <returns>The copy</returns>
public new ByteAnimationUsingKeyFrames Clone()
{
return (ByteAnimationUsingKeyFrames)base.Clone();
}
/// <summary>
/// Returns a version of this class with all its base property values
/// set to the current animated values and removes the animations.
/// </summary>
/// <returns>
/// Since this class isn't animated, this method will always just return
/// this instance of the class.
/// </returns>
public new ByteAnimationUsingKeyFrames CloneCurrentValue()
{
return (ByteAnimationUsingKeyFrames)base.CloneCurrentValue();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>.
/// </summary>
protected override bool FreezeCore(bool isChecking)
{
bool canFreeze = base.FreezeCore(isChecking);
canFreeze &= Freezable.Freeze(_keyFrames, isChecking);
if (canFreeze & !_areKeyTimesValid)
{
ResolveKeyTimes();
}
return canFreeze;
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.OnChanged">Freezable.OnChanged</see>.
/// </summary>
protected override void OnChanged()
{
_areKeyTimesValid = false;
base.OnChanged();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new ByteAnimationUsingKeyFrames();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>.
/// </summary>
protected override void CloneCore(Freezable sourceFreezable)
{
ByteAnimationUsingKeyFrames sourceAnimation = (ByteAnimationUsingKeyFrames) sourceFreezable;
base.CloneCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>.
/// </summary>
protected override void CloneCurrentValueCore(Freezable sourceFreezable)
{
ByteAnimationUsingKeyFrames sourceAnimation = (ByteAnimationUsingKeyFrames) sourceFreezable;
base.CloneCurrentValueCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>.
/// </summary>
protected override void GetAsFrozenCore(Freezable source)
{
ByteAnimationUsingKeyFrames sourceAnimation = (ByteAnimationUsingKeyFrames) source;
base.GetAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>.
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable source)
{
ByteAnimationUsingKeyFrames sourceAnimation = (ByteAnimationUsingKeyFrames) source;
base.GetCurrentValueAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Helper used by the four Freezable clone methods to copy the resolved key times and
/// key frames. The Get*AsFrozenCore methods are implemented the same as the Clone*Core
/// methods; Get*AsFrozen at the top level will recursively Freeze so it's not done here.
/// </summary>
/// <param name="sourceAnimation"></param>
/// <param name="isCurrentValueClone"></param>
private void CopyCommon(ByteAnimationUsingKeyFrames sourceAnimation, bool isCurrentValueClone)
{
_areKeyTimesValid = sourceAnimation._areKeyTimesValid;
if ( _areKeyTimesValid
&& sourceAnimation._sortedResolvedKeyFrames != null)
{
// _sortedResolvedKeyFrames is an array of ResolvedKeyFrameEntry so the notion of CurrentValueClone doesn't apply
_sortedResolvedKeyFrames = (ResolvedKeyFrameEntry[])sourceAnimation._sortedResolvedKeyFrames.Clone();
}
if (sourceAnimation._keyFrames != null)
{
if (isCurrentValueClone)
{
_keyFrames = (ByteKeyFrameCollection)sourceAnimation._keyFrames.CloneCurrentValue();
}
else
{
_keyFrames = (ByteKeyFrameCollection)sourceAnimation._keyFrames.Clone();
}
OnFreezablePropertyChanged(null, _keyFrames);
}
}
#endregion // Freezable
#region IAddChild interface
/// <summary>
/// Adds a child object to this KeyFrameAnimation.
/// </summary>
/// <param name="child">
/// The child object to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation only accepts a KeyFrame of the proper type as
/// a child.
/// </remarks>
void IAddChild.AddChild(object child)
{
WritePreamble();
if (child == null)
{
throw new ArgumentNullException("child");
}
AddChild(child);
WritePostscript();
}
/// <summary>
/// Implemented to allow KeyFrames to be direct children
/// of KeyFrameAnimations in markup.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddChild(object child)
{
ByteKeyFrame keyFrame = child as ByteKeyFrame;
if (keyFrame != null)
{
KeyFrames.Add(keyFrame);
}
else
{
throw new ArgumentException(SR.Get(SRID.Animation_ChildMustBeKeyFrame), "child");
}
}
/// <summary>
/// Adds a text string as a child of this KeyFrameAnimation.
/// </summary>
/// <param name="childText">
/// The text to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation does not accept text as a child, so this method will
/// raise an InvalididOperationException unless a derived class has
/// overridden the behavior to add text.
/// </remarks>
/// <exception cref="ArgumentNullException">The childText parameter is
/// null.</exception>
void IAddChild.AddText(string childText)
{
if (childText == null)
{
throw new ArgumentNullException("childText");
}
AddText(childText);
}
/// <summary>
/// This method performs the core functionality of the AddText()
/// method on the IAddChild interface. For a KeyFrameAnimation this means
/// throwing and InvalidOperationException because it doesn't
/// support adding text.
/// </summary>
/// <remarks>
/// This method is the only core implementation. It does not call
/// WritePreamble() or WritePostscript(). It also doesn't throw an
/// ArgumentNullException if the childText parameter is null. These tasks
/// are performed by the interface implementation. Therefore, it's OK
/// for a derived class to override this method and call the base
/// class implementation only if they determine that it's the right
/// course of action. The derived class can rely on KeyFrameAnimation's
/// implementation of IAddChild.AddChild or implement their own
/// following the Freezable pattern since that would be a public
/// method.
/// </remarks>
/// <param name="childText">A string representing the child text that
/// should be added. If this is a KeyFrameAnimation an exception will be
/// thrown.</param>
/// <exception cref="InvalidOperationException">Timelines have no way
/// of adding text.</exception>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddText(string childText)
{
throw new InvalidOperationException(SR.Get(SRID.Animation_NoTextChildren));
}
#endregion
#region ByteAnimationBase
/// <summary>
/// Calculates the value this animation believes should be the current value for the property.
/// </summary>
/// <param name="defaultOriginValue">
/// This value is the suggested origin value provided to the animation
/// to be used if the animation does not have its own concept of a
/// start value. If this animation is the first in a composition chain
/// this value will be the snapshot value if one is available or the
/// base property value if it is not; otherise this value will be the
/// value returned by the previous animation in the chain with an
/// animationClock that is not Stopped.
/// </param>
/// <param name="defaultDestinationValue">
/// This value is the suggested destination value provided to the animation
/// to be used if the animation does not have its own concept of an
/// end value. This value will be the base value if the animation is
/// in the first composition layer of animations on a property;
/// otherwise this value will be the output value from the previous
/// composition layer of animations for the property.
/// </param>
/// <param name="animationClock">
/// This is the animationClock which can generate the CurrentTime or
/// CurrentProgress value to be used by the animation to generate its
/// output value.
/// </param>
/// <returns>
/// The value this animation believes should be the current value for the property.
/// </returns>
protected sealed override Byte GetCurrentValueCore(
Byte defaultOriginValue,
Byte defaultDestinationValue,
AnimationClock animationClock)
{
Debug.Assert(animationClock.CurrentState != ClockState.Stopped);
if (_keyFrames == null)
{
return defaultDestinationValue;
}
// We resolved our KeyTimes when we froze, but also got notified
// of the frozen state and therefore invalidated ourselves.
if (!_areKeyTimesValid)
{
ResolveKeyTimes();
}
if (_sortedResolvedKeyFrames == null)
{
return defaultDestinationValue;
}
TimeSpan currentTime = animationClock.CurrentTime.Value;
Int32 keyFrameCount = _sortedResolvedKeyFrames.Length;
Int32 maxKeyFrameIndex = keyFrameCount - 1;
Byte currentIterationValue;
Debug.Assert(maxKeyFrameIndex >= 0, "maxKeyFrameIndex is less than zero which means we don't actually have any key frames.");
Int32 currentResolvedKeyFrameIndex = 0;
// Skip all the key frames with key times lower than the current time.
// currentResolvedKeyFrameIndex will be greater than maxKeyFrameIndex
// if we are past the last key frame.
while ( currentResolvedKeyFrameIndex < keyFrameCount
&& currentTime > _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
// If there are multiple key frames at the same key time, be sure to go to the last one.
while ( currentResolvedKeyFrameIndex < maxKeyFrameIndex
&& currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex + 1]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
if (currentResolvedKeyFrameIndex == keyFrameCount)
{
// Past the last key frame.
currentIterationValue = GetResolvedKeyFrameValue(maxKeyFrameIndex);
}
else if (currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
// Exactly on a key frame.
currentIterationValue = GetResolvedKeyFrameValue(currentResolvedKeyFrameIndex);
}
else
{
// Between two key frames.
Double currentSegmentProgress = 0.0;
Byte fromValue;
if (currentResolvedKeyFrameIndex == 0)
{
// The current key frame is the first key frame so we have
// some special rules for determining the fromValue and an
// optimized method of calculating the currentSegmentProgress.
// If we're additive we want the base value to be a zero value
// so that if there isn't a key frame at time 0.0, we'll use
// the zero value for the time 0.0 value and then add that
// later to the base value.
if (IsAdditive)
{
fromValue = AnimatedTypeHelpers.GetZeroValueByte(defaultOriginValue);
}
else
{
fromValue = defaultOriginValue;
}
// Current segment time divided by the segment duration.
// Note: the reason this works is that we know that we're in
// the first segment, so we can assume:
//
// currentTime.TotalMilliseconds = current segment time
// _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds = current segment duration
currentSegmentProgress = currentTime.TotalMilliseconds
/ _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds;
}
else
{
Int32 previousResolvedKeyFrameIndex = currentResolvedKeyFrameIndex - 1;
TimeSpan previousResolvedKeyTime = _sortedResolvedKeyFrames[previousResolvedKeyFrameIndex]._resolvedKeyTime;
fromValue = GetResolvedKeyFrameValue(previousResolvedKeyFrameIndex);
TimeSpan segmentCurrentTime = currentTime - previousResolvedKeyTime;
TimeSpan segmentDuration = _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime - previousResolvedKeyTime;
currentSegmentProgress = segmentCurrentTime.TotalMilliseconds
/ segmentDuration.TotalMilliseconds;
}
currentIterationValue = GetResolvedKeyFrame(currentResolvedKeyFrameIndex).InterpolateValue(fromValue, currentSegmentProgress);
}
// If we're cumulative, we need to multiply the final key frame
// value by the current repeat count and add this to the return
// value.
if (IsCumulative)
{
Double currentRepeat = (Double)(animationClock.CurrentIteration - 1);
if (currentRepeat > 0.0)
{
currentIterationValue = AnimatedTypeHelpers.AddByte(
currentIterationValue,
AnimatedTypeHelpers.ScaleByte(GetResolvedKeyFrameValue(maxKeyFrameIndex), currentRepeat));
}
}
// If we're additive we need to add the base value to the return value.
if (IsAdditive)
{
return AnimatedTypeHelpers.AddByte(defaultOriginValue, currentIterationValue);
}
return currentIterationValue;
}
/// <summary>
/// Provide a custom natural Duration when the Duration property is set to Automatic.
/// </summary>
/// <param name="clock">
/// The Clock whose natural duration is desired.
/// </param>
/// <returns>
/// If the last KeyFrame of this animation is a KeyTime, then this will
/// be used as the NaturalDuration; otherwise it will be one second.
/// </returns>
protected override sealed Duration GetNaturalDurationCore(Clock clock)
{
return new Duration(LargestTimeSpanKeyTime);
}
#endregion
#region IKeyFrameAnimation
/// <summary>
/// Returns the ByteKeyFrameCollection used by this KeyFrameByteAnimation.
/// </summary>
IList IKeyFrameAnimation.KeyFrames
{
get
{
return KeyFrames;
}
set
{
KeyFrames = (ByteKeyFrameCollection)value;
}
}
/// <summary>
/// Returns the ByteKeyFrameCollection used by this KeyFrameByteAnimation.
/// </summary>
public ByteKeyFrameCollection KeyFrames
{
get
{
ReadPreamble();
// The reason we don't just set _keyFrames to the empty collection
// in the first place is that null tells us that the user has not
// asked for the collection yet. The first time they ask for the
// collection and we're unfrozen, policy dictates that we give
// them a new unfrozen collection. All subsequent times they will
// get whatever collection is present, whether frozen or unfrozen.
if (_keyFrames == null)
{
if (this.IsFrozen)
{
_keyFrames = ByteKeyFrameCollection.Empty;
}
else
{
WritePreamble();
_keyFrames = new ByteKeyFrameCollection();
OnFreezablePropertyChanged(null, _keyFrames);
WritePostscript();
}
}
return _keyFrames;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
WritePreamble();
if (value != _keyFrames)
{
OnFreezablePropertyChanged(_keyFrames, value);
_keyFrames = value;
WritePostscript();
}
}
}
/// <summary>
/// Returns true if we should serialize the KeyFrames, property for this Animation.
/// </summary>
/// <returns>True if we should serialize the KeyFrames property for this Animation; otherwise false.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeKeyFrames()
{
ReadPreamble();
return _keyFrames != null
&& _keyFrames.Count > 0;
}
#endregion
#region Public Properties
/// <summary>
/// If this property is set to true, this animation will add its value
/// to the base value or the value of the previous animation in the
/// composition chain. Another way of saying this is that the units
/// specified in the animation are relative to the base value rather
/// than absolute units.
/// </summary>
/// <remarks>
/// In the case where the first key frame's resolved key time is not
/// 0.0 there is slightly different behavior between KeyFrameByteAnimations
/// with IsAdditive set and without. Animations with the property set to false
/// will behave as if there is a key frame at time 0.0 with the value of the
/// base value. Animations with the property set to true will behave as if
/// there is a key frame at time 0.0 with a zero value appropriate to the type
/// of the animation. These behaviors provide the results most commonly expected
/// and can be overridden by simply adding a key frame at time 0.0 with the preferred value.
/// </remarks>
public bool IsAdditive
{
get
{
return (bool)GetValue(IsAdditiveProperty);
}
set
{
SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value));
}
}
/// <summary>
/// If this property is set to true, the value of this animation will
/// accumulate over repeat cycles. For example, if this is a point
/// animation and your key frames describe something approximating and
/// arc, setting this property to true will result in an animation that
/// would appear to bounce the point across the screen.
/// </summary>
/// <remarks>
/// This property works along with the IsAdditive property. Setting
/// this value to true has no effect unless IsAdditive is also set
/// to true.
/// </remarks>
public bool IsCumulative
{
get
{
return (bool)GetValue(IsCumulativeProperty);
}
set
{
SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value));
}
}
#endregion
#region Private Methods
private struct KeyTimeBlock
{
public int BeginIndex;
public int EndIndex;
}
private Byte GetResolvedKeyFrameValue(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrameValue");
return GetResolvedKeyFrame(resolvedKeyFrameIndex).Value;
}
private ByteKeyFrame GetResolvedKeyFrame(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrame");
return _keyFrames[_sortedResolvedKeyFrames[resolvedKeyFrameIndex]._originalKeyFrameIndex];
}
/// <summary>
/// Returns the largest time span specified key time from all of the key frames.
/// If there are not time span key times a time span of one second is returned
/// to match the default natural duration of the From/To/By animations.
/// </summary>
private TimeSpan LargestTimeSpanKeyTime
{
get
{
bool hasTimeSpanKeyTime = false;
TimeSpan largestTimeSpanKeyTime = TimeSpan.Zero;
if (_keyFrames != null)
{
Int32 keyFrameCount = _keyFrames.Count;
for (int index = 0; index < keyFrameCount; index++)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
if (keyTime.Type == KeyTimeType.TimeSpan)
{
hasTimeSpanKeyTime = true;
if (keyTime.TimeSpan > largestTimeSpanKeyTime)
{
largestTimeSpanKeyTime = keyTime.TimeSpan;
}
}
}
}
if (hasTimeSpanKeyTime)
{
return largestTimeSpanKeyTime;
}
else
{
return TimeSpan.FromSeconds(1.0);
}
}
}
private void ResolveKeyTimes()
{
Debug.Assert(!_areKeyTimesValid, "KeyFrameByteAnimaton.ResolveKeyTimes() shouldn't be called if the key times are already valid.");
int keyFrameCount = 0;
if (_keyFrames != null)
{
keyFrameCount = _keyFrames.Count;
}
if (keyFrameCount == 0)
{
_sortedResolvedKeyFrames = null;
_areKeyTimesValid = true;
return;
}
_sortedResolvedKeyFrames = new ResolvedKeyFrameEntry[keyFrameCount];
int index = 0;
// Initialize the _originalKeyFrameIndex.
for ( ; index < keyFrameCount; index++)
{
_sortedResolvedKeyFrames[index]._originalKeyFrameIndex = index;
}
// calculationDuration represents the time span we will use to resolve
// percent key times. This is defined as the value in the following
// precedence order:
// 1. The animation's duration, but only if it is a time span, not auto or forever.
// 2. The largest time span specified key time of all the key frames.
// 3. 1 second, to match the From/To/By animations.
TimeSpan calculationDuration = TimeSpan.Zero;
Duration duration = Duration;
if (duration.HasTimeSpan)
{
calculationDuration = duration.TimeSpan;
}
else
{
calculationDuration = LargestTimeSpanKeyTime;
}
int maxKeyFrameIndex = keyFrameCount - 1;
ArrayList unspecifiedBlocks = new ArrayList();
bool hasPacedKeyTimes = false;
//
// Pass 1: Resolve Percent and Time key times.
//
index = 0;
while (index < keyFrameCount)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
switch (keyTime.Type)
{
case KeyTimeType.Percent:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.FromMilliseconds(
keyTime.Percent * calculationDuration.TotalMilliseconds);
index++;
break;
case KeyTimeType.TimeSpan:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = keyTime.TimeSpan;
index++;
break;
case KeyTimeType.Paced:
case KeyTimeType.Uniform:
if (index == maxKeyFrameIndex)
{
// If the last key frame doesn't have a specific time
// associated with it its resolved key time will be
// set to the calculationDuration, which is the
// defined in the comments above where it is set.
// Reason: We only want extra time at the end of the
// key frames if the user specifically states that
// the last key frame ends before the animation ends.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = calculationDuration;
index++;
}
else if ( index == 0
&& keyTime.Type == KeyTimeType.Paced)
{
// Note: It's important that this block come after
// the previous if block because of rule precendence.
// If the first key frame in a multi-frame key frame
// collection is paced, we set its resolved key time
// to 0.0 for performance reasons. If we didn't, the
// resolved key time list would be dependent on the
// base value which can change every animation frame
// in many cases.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.Zero;
index++;
}
else
{
if (keyTime.Type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
KeyTimeBlock block = new KeyTimeBlock();
block.BeginIndex = index;
// NOTE: We don't want to go all the way up to the
// last frame because if it is Uniform or Paced its
// resolved key time will be set to the calculation
// duration using the logic above.
//
// This is why the logic is:
// ((++index) < maxKeyFrameIndex)
// instead of:
// ((++index) < keyFrameCount)
while ((++index) < maxKeyFrameIndex)
{
KeyTimeType type = _keyFrames[index].KeyTime.Type;
if ( type == KeyTimeType.Percent
|| type == KeyTimeType.TimeSpan)
{
break;
}
else if (type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
}
Debug.Assert(index < keyFrameCount,
"The end index for a block of unspecified key frames is out of bounds.");
block.EndIndex = index;
unspecifiedBlocks.Add(block);
}
break;
}
}
//
// Pass 2: Resolve Uniform key times.
//
for (int j = 0; j < unspecifiedBlocks.Count; j++)
{
KeyTimeBlock block = (KeyTimeBlock)unspecifiedBlocks[j];
TimeSpan blockBeginTime = TimeSpan.Zero;
if (block.BeginIndex > 0)
{
blockBeginTime = _sortedResolvedKeyFrames[block.BeginIndex - 1]._resolvedKeyTime;
}
// The number of segments is equal to the number of key
// frames we're working on plus 1. Think about the case
// where we're working on a single key frame. There's a
// segment before it and a segment after it.
//
// Time known Uniform Time known
// ^ ^ ^
// | | |
// | (segment 1) | (segment 2) |
Int64 segmentCount = (block.EndIndex - block.BeginIndex) + 1;
TimeSpan uniformTimeStep = TimeSpan.FromTicks((_sortedResolvedKeyFrames[block.EndIndex]._resolvedKeyTime - blockBeginTime).Ticks / segmentCount);
index = block.BeginIndex;
TimeSpan resolvedTime = blockBeginTime + uniformTimeStep;
while (index < block.EndIndex)
{
_sortedResolvedKeyFrames[index]._resolvedKeyTime = resolvedTime;
resolvedTime += uniformTimeStep;
index++;
}
}
//
// Pass 3: Resolve Paced key times.
//
if (hasPacedKeyTimes)
{
ResolvePacedKeyTimes();
}
//
// Sort resolved key frame entries.
//
Array.Sort(_sortedResolvedKeyFrames);
_areKeyTimesValid = true;
return;
}
/// <summary>
/// This should only be called from ResolveKeyTimes and only at the
/// appropriate time.
/// </summary>
private void ResolvePacedKeyTimes()
{
Debug.Assert(_keyFrames != null && _keyFrames.Count > 2,
"Caller must guard against calling this method when there are insufficient keyframes.");
// If the first key frame is paced its key time has already
// been resolved, so we start at index 1.
int index = 1;
int maxKeyFrameIndex = _sortedResolvedKeyFrames.Length - 1;
do
{
if (_keyFrames[index].KeyTime.Type == KeyTimeType.Paced)
{
//
// We've found a paced key frame so this is the
// beginning of a paced block.
//
// The first paced key frame in this block.
int firstPacedBlockKeyFrameIndex = index;
// List of segment lengths for this paced block.
List<Double> segmentLengths = new List<Double>();
// The resolved key time for the key frame before this
// block which we'll use as our starting point.
TimeSpan prePacedBlockKeyTime = _sortedResolvedKeyFrames[index - 1]._resolvedKeyTime;
// The total of the segment lengths of the paced key
// frames in this block.
Double totalLength = 0.0;
// The key value of the previous key frame which will be
// used to determine the segment length of this key frame.
Byte prevKeyValue = _keyFrames[index - 1].Value;
do
{
Byte currentKeyValue = _keyFrames[index].Value;
// Determine the segment length for this key frame and
// add to the total length.
totalLength += AnimatedTypeHelpers.GetSegmentLengthByte(prevKeyValue, currentKeyValue);
// Temporarily store the distance into the total length
// that this key frame represents in the resolved
// key times array to be converted to a resolved key
// time outside of this loop.
segmentLengths.Add(totalLength);
// Prepare for the next iteration.
prevKeyValue = currentKeyValue;
index++;
}
while ( index < maxKeyFrameIndex
&& _keyFrames[index].KeyTime.Type == KeyTimeType.Paced);
// index is currently set to the index of the key frame
// after the last paced key frame. This will always
// be a valid index because we limit ourselves with
// maxKeyFrameIndex.
// We need to add the distance between the last paced key
// frame and the next key frame to get the total distance
// inside the key frame block.
totalLength += AnimatedTypeHelpers.GetSegmentLengthByte(prevKeyValue, _keyFrames[index].Value);
// Calculate the time available in the resolved key time space.
TimeSpan pacedBlockDuration = _sortedResolvedKeyFrames[index]._resolvedKeyTime - prePacedBlockKeyTime;
// Convert lengths in segmentLengths list to resolved
// key times for the paced key frames in this block.
for (int i = 0, currentKeyFrameIndex = firstPacedBlockKeyFrameIndex; i < segmentLengths.Count; i++, currentKeyFrameIndex++)
{
// The resolved key time for each key frame is:
//
// The key time of the key frame before this paced block
// + ((the percentage of the way through the total length)
// * the resolved key time space available for the block)
_sortedResolvedKeyFrames[currentKeyFrameIndex]._resolvedKeyTime = prePacedBlockKeyTime + TimeSpan.FromMilliseconds(
(segmentLengths[i] / totalLength) * pacedBlockDuration.TotalMilliseconds);
}
}
else
{
index++;
}
}
while (index < maxKeyFrameIndex);
}
#endregion
}
}
| Java |
'use strict';
const Hoek = require('hoek');
exports.plugin = {
register: async (plugin, options) => {
plugin.ext('onPreResponse', (request, h) => {
try {
var internals = {
devEnv: (process.env.NODE_ENV === 'development'),
meta: options.meta,
credentials: request.auth.isAuthenticated ? request.auth.credentials : null
};
var response = request.response;
if (response.variety && response.variety === 'view') {
response.source.context = Hoek.merge(internals, request.response.source.context);
}
return h.continue;
} catch (error) {
throw error;
}
});
},
pkg: require('../package.json'),
name: 'context'
};
| Java |
'use strict';
//Customers service used to communicate Customers REST endpoints
angular.module('customers')
.factory('Customers', ['$resource',
function($resource) {
return $resource('customers/:customerId', { customerId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
])
.factory('Notify', ['$rootScope', function($rootScope) {
var notify = {};
notify.sendMsg = function(msg, data) {
data = data || {};
$rootScope.$emit(msg, data);
console.log('message sent!');
};
notify.getMsg = function(msg, func, scope) {
var unbind = $rootScope.$on(msg, func);
if (scope) {
scope.$on('destroy', unbind);
}
};
return notify;
}
]); | Java |
#pragma once
char separator;
#ifdef _WIN32
#define DIR_SEPARATOR '\\'
#else
#define DIR_SEPARATOR '/'
#endif
#include <string>
#include <algorithm>
using namespace std;
class PathUtil{
public:
/*A small function to extract FileName from File Path
C:/File.exe -> File.exe
*/
string static extractFileName(string FilePath){
int separatorlast = FilePath.find_last_of(DIR_SEPARATOR);
return FilePath.substr(separatorlast + 1, FilePath.length() - separatorlast);
}
string static extractFileExt(string FilePath){
int separatorlast = FilePath.find_last_of('.');
string FileExt = FilePath.substr(separatorlast + 1, FilePath.length() - separatorlast);
std::transform(FileExt.begin(), FileExt.end(), FileExt.begin(), ::tolower);
return FileExt;
}
string static extractFileNamewithoutExt(string FilePath){
string FileName = extractFileName(FilePath);
int separatorlast = FilePath.find_last_of(DIR_SEPARATOR);
int dotlast = FilePath.find_last_of('.');
return FilePath.substr(separatorlast + 1, dotlast);
}
string static extractDirPath(string FilePath){
string FileName = extractFileName(FilePath);
int separatorlast = FilePath.find_last_of(DIR_SEPARATOR);
int dotlast = FilePath.find_first_of('.');
return FilePath.substr(separatorlast + 1, dotlast - separatorlast -1);
}
}; | Java |
/* some devices call home before accepting a wifi access point. Spoof those responses. */
var path = require('path');
exports.load = function(server, boatData, settings) {
var endpointMap = [
{'route': '/kindle-wifi/wifiredirect.html', 'responseFile': 'kindle.html'} ,
{'route': '/kindle-wifi/wifistub.html', 'responseFile': 'kindle.html'} //http://spectrum.s3.amazonaws.com
];
_.each(endpointMap, function(endpoint) {
server.get(endpoint.route, function(req, res) {
res.sendFile(path.join(__dirname + endpoint.responseFile));
});
});
}; | Java |
# twitterStreamerMap
To start the project
```
git clone https://github.com/klosorio10/ExamenFinalWebDev.git
cd ExamenFinalWebdev
cd ExamenFinal
```
A simple boilerplate for a Meteor 1.4 Twitter streamer application with React. Uses the twitter [npm](https://www.npmjs.com/package/twitter) module for connecting to twitter. It requires you to setup your credentials on the server using environment variables:
```
export TWITTER_CONSUMER_KEY="yourCredentialsHere"
export TWITTER_CONSUMER_SECRET="yourCredentialsHere"
export TWITTER_ACCESS_TOKEN_KEY="yourCredentialsHere"
export TWITTER_ACCESS_TOKEN_SECRET="yourCredentialsHere"
meteor npm install
meteor
```
This is a very basic implementation that handles a global search shared by all users and doesn't implement any security or restriction. It's intended as a starting point, so add your own requirements.
| Java |
USE [VipunenTK]
GO
/****** Object: Table [dbo].[d_erikoislaakarikoulutus] Script Date: 14.9.2017 13:55:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[d_erikoislaakarikoulutus]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[d_erikoislaakarikoulutus](
[id] [int] NOT NULL,
[alkaa] [date] NOT NULL,
[paattyy] [date] NOT NULL,
[erikoislaakarikoulutus_koodi] [nvarchar](2) NOT NULL,
[erikoislaakarikoulutus] [nvarchar](200) NULL,
[erikoislaakarikoulutus_SV] [nvarchar](200) NULL,
[erikoislaakarikoulutus_EN] [nvarchar](200) NULL,
[jarjestys] [nvarchar](50) NULL,
[tietolahde] [nvarchar](50) NULL
) ON [PRIMARY]
END
GO
INSERT [dbo].[d_erikoislaakarikoulutus] ([id], [alkaa], [paattyy], [erikoislaakarikoulutus_koodi], [erikoislaakarikoulutus], [erikoislaakarikoulutus_SV], [erikoislaakarikoulutus_EN], [jarjestys], [tietolahde]) VALUES (-2, CAST(N'1900-01-01' AS Date), CAST(N'9999-01-01' AS Date), N'-2', N'Virhetilanne', N'Feltillstånd', N'Error occurred', N'99999', N'Manuaalinen')
GO
INSERT [dbo].[d_erikoislaakarikoulutus] ([id], [alkaa], [paattyy], [erikoislaakarikoulutus_koodi], [erikoislaakarikoulutus], [erikoislaakarikoulutus_SV], [erikoislaakarikoulutus_EN], [jarjestys], [tietolahde]) VALUES (-1, CAST(N'1900-01-01' AS Date), CAST(N'9999-01-01' AS Date), N'-1', N'Tuntematon', N'Information saknas', N'Missing data', N'99998', N'Manuaalinen')
GO
INSERT [dbo].[d_erikoislaakarikoulutus] ([id], [alkaa], [paattyy], [erikoislaakarikoulutus_koodi], [erikoislaakarikoulutus], [erikoislaakarikoulutus_SV], [erikoislaakarikoulutus_EN], [jarjestys], [tietolahde]) VALUES (1, CAST(N'1900-01-01' AS Date), CAST(N'9999-01-01' AS Date), N'1', N'Erikoislääkärit', N'*SV*Erikoislääkärit', N'*EN*Erikoislääkärit', N'1', N'Tilastokeskus')
GO
INSERT [dbo].[d_erikoislaakarikoulutus] ([id], [alkaa], [paattyy], [erikoislaakarikoulutus_koodi], [erikoislaakarikoulutus], [erikoislaakarikoulutus_SV], [erikoislaakarikoulutus_EN], [jarjestys], [tietolahde]) VALUES (2, CAST(N'1900-01-01' AS Date), CAST(N'9999-01-01' AS Date), N'2', N'Erikoishammaslääkärit', N'*SV*Erikoishammaslääkärit', N'*EN*Erikoishammaslääkärit', N'2', N'Tilastokeskus')
GO
USE [ANTERO] | Java |
# diofa-vendeghaz-orfu
www.diofa-vendeghaz-orfu.hu
| Java |
# Basics
Toast is a Rack application that hooks into Ruby on Rails providing a REST
interface for ActiveRecord models. For each model a HTTP interface can
be configured. Using Toast's configuration DSL one declares which of its attributes are
exposed, which are readable and/or writable using white lists.
Web Service Provider Web Service Consumer
----------------- -----------------
| Toast | <--HTTP/REST--> | AJAX app, |
----------------- | mobile app, |
| | \ | Java app, etc.|
----------- ----------- ----------- -----------------
| Model A | | Model B | | Model C |
----------- ----------- ----------
Toast dispatches any request to the right model class by using naming
conventions. That way a model can be exposed on the web
by a simple configuration file under `config/toast-api/coconut.rb`:
{% highlight ruby %}
expose(Coconut) {
readables :color, :weight
via_get { # for GET /coconut/ID
allow do |user, coconut, uri_params|
user.is_admin?
end
}
collection(:all) {
via_get { # for GET /coconuts
allow do |user, coconut, uri_params|
user.is_admin?
end
}
}
}
{% endhighlight %}
This exposes the model Coconut. Toast would respond like this:
GET /coconuts
--> 200 OK
--> [{"self":"https://www.example.com/coconuts/1","color":...,"weight":...},
{"self":"https://www.example.com/coconuts/2","color":...,"weight":...},
{"self":"https://www.example.com/coconuts/3","color":...,"weight":...}]
given there are 3 rows in the table _coconuts_. Note that this request
translates to the ActiveRecord call `Coconut.all`, hence the exposition of the
`all` collection. Each of the URIs in the response will fetch the
respective Coconut instances:
GET /coconut/2
--> 200 OK
--> {"self": "https://www.example.com/coconuts/2",
"color": "brown",
"weight": 2.1}
`color` and `weight` were declared in the `readables` list. That
means these attributes are exposed via GET requests, but not
updatable by PATCH requests. To allow that attributes must be
declared writable:
{% highlight ruby %}
expose(Coconut) {
readables :color
writables :weight
}
{% endhighlight %}
POST and DELETE operations must be allowed explicitly:
{% highlight ruby %}
expose(Coconut) {
readables :color, :weight
via_get { # for GET /coconut/ID
allow do |user, coconut, uri_params|
user.is_admin?
end
}
via_delete { # for DELETE /coconut/ID
allow do |user, coconut, uri_params|
user.is_admin?
end
}
collection(:all) {
via_get { # for GET /coconuts
allow do |user, coconut, uri_params|
user.is_admin?
end
}
via_post { # for POST /coconuts
allow do |user, coconut, uri_params|
user.is_admin?
end
}
}
}
{% endhighlight %}
The above permits to POST a new record (== `Coconut.create(...)` and
to DELETE single instances (== `Coconnut.find(id).destroy`):
POST /coconuts
<-- {"color": "yellow",
"weight": 42.0}
--> 201 Created
--> {"self": "https://www.example.com/coconuts/4",
"color": "yellow",
"weight": 42.0}
DELETE /coconut/3
--> 200 OK
Nonetheless exposing associations will render your entire data
model (or parts of it) a complete web-service. Associations will be
represented as URIs via which the associated resource(s) can be fetched:
{% highlight ruby %}
class Coconut < ActiveRecord::Base
belongs_to :tree
has_many :consumers
end
{% endhighlight %}
together with `config/toast-api/coconut.rb`:
{% highlight ruby %}
expose(Coconut) {
readables :color, :weight
association(:tree) {
via_get {
allow do |*args|
true
end
}
}
association(:consumers) {
via_get {
allow do |user, coconut, uri_params|
user.role == 'admin'
end
}
via_post {
allow do |user, coconut, uri_params|
user.role == 'admin'
end
}
}
}
{% endhighlight %}
GET /coconut/2
--> 200 OK
--> {"self": "https://www.example.com/coconuts/2",
"tree": "https://www.example.com/coconuts/2/tree",
"consumers": "https://www.example.com/consumers",
"color": "brown",
"weight": 2.1}
## Representation
Toast's JSON representation is very minimal. As you can see above it does not have any qualification of the properties. Data and links and even structured property value are possible. There are other standards like [HAL](http://stateless.co/hal_specification.html), [Siren](https://github.com/kevinswiber/siren), [Collection+JSON](http://amundsen.com/media-types/collection/) or [JSON API](http://jsonapi.org) on that matter you may also consider.
Toast's key ideas and distinguishing features are: Simplicity and Opaque URIs.
The JSON representation was guided by the idea that any client(/-programmer) must know the representation of each resource by documentation anyway, so there is no need to nest links in a 'links' sub structure like JSON API does.
The only rules for Toast's JSON representation are:
* The `self` property is the canonical URI (see below) of the model/resource
* Link properties are named like ActiveRecord associations in the model and are not in non-canonical form
* Data properties are named as the corresponding attributes of the model. They can contain any type and also structured data (serialized by AR or self constructed).
## URIs
Toast treats URIs generally as opaque strings, meaning that it only uses complete URLs and has no concept of "URL templates" for processing. Such templates may only appear in the documentation.
The canonical form of a URI for a model/resource is: `https://<HOST>/<PATH>/<RESOURCE>/<ID>?<PARAMS>`, where
* `https://<HOST>` is FQDN.
* `<PATH>` is an optional path segment,
* `<RESOURCE>` is name of the resource/model
* `<ID>` is a string of digits: `[0-9]+`,
* `<PARAMS>` is an optional list of query parameters
Association URIs composed like: `<CANONICAL>/<ASSOCIATION>?<PARAMS>`, where
* `<CANONICAL>` is as defined above
* `<ASSOCIATION>` is the name a models association (`has_many`, `belongs_to`, ...)
Root collection URIs are also provided: `https://<HOST>/<PATH>/<RESOURCES>?<PARAMS>`. The string `<RESOURCES>` is named after a class method of a model that returns a relation to a collection of instances of the same model.
## Association Treatment
Model instances link each other and construct a web of model instances/resources. The web is conveyed by URIs that can be traversed by GET request. All model association that are exposed appear in the JSON response as a URL, nothing else (embedding can be achieved through regular data properties).
Association properties never change when associations change, because they don't use the canonical URI form.
They can be used to issue a
* a POST request to create a new resource + linking to the base resource,
* a DELETE request to delete a model instance/resource,
* a LINK request in order to link existing model instances/resources using a second canonical URI or
* a UNLINK request in order to remove a association/link between model instances/resources without deleting a model instance/resource.
All these actions are directly mapped to the corresponding ActiveRecord calls on associations.
| Java |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TestProjectFromCsv.ValidationSteps;
namespace TestProjectFromCsv
{
public class Program
{
public static void Main(string[] args)
{
try
{
var options = new Options();
if (CommandLine.Parser.Default.ParseArguments(args, options))
{
var validation = new Validation(
new ValidationStep[] {
new CsvFileExists(options),
new TemplateFilesExist(options)
});
if (!validation.IsValid())
{
foreach (string issue in validation.Issues)
{
Console.WriteLine(issue);
}
}
else
{
Directory.CreateDirectory(Path.Combine(options.ProjectPath, options.ProjectName));
CsvFile csvFile = new CsvFile(options.CsvFile);
IList<CsvRecord> testRecords = csvFile.Parse();
StringBuilder allTestProjects = new StringBuilder(100 + testRecords.Count * 100);
TemplateFileGenerator testTemplateGen = new TemplateFileGenerator(Path.Combine(options.TemplatePath, "Test.tmp"));
foreach (CsvRecord record in testRecords)
{
string filename = Path.Combine(
options.ProjectPath,
options.ProjectName,
string.Format("{0}.GenericTest", record.TestName));
try
{
allTestProjects.AppendLine(string.Format("\t<None Include=\"{0}.GenericTest\">", record.TestName));
allTestProjects.AppendLine("\t\t<CopyToOutputDirectory>Always</CopyToOutputDirectory>");
allTestProjects.AppendLine("\t</None>");
testTemplateGen.GenerateFile(filename, new Dictionary<string, string>()
{
{ "[[TestName]]" , record.TestName } ,
{ "[[FullFilePath]]", filename } ,
{ "[[TestGuid]]", Guid.NewGuid().ToString("D") } ,
{ "[[CommandFullFilePath]]", Path.Combine(options.CommandPath, record.BatchFile)}
});
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Error building file '{0}' : {1}", filename, ex.Message));
}
}
string assemblyInfoFilename = Path.Combine(options.ProjectPath, options.ProjectName, "Properties", "AssemblyInfo.cs");
try
{
Directory.CreateDirectory(Path.Combine(options.ProjectPath, options.ProjectName, "Properties"));
TemplateFileGenerator assemblyInfoGen = new TemplateFileGenerator(Path.Combine(options.TemplatePath, "AssemblyInfo.cs.tmp"));
assemblyInfoGen.GenerateFile(assemblyInfoFilename, new Dictionary<string, string>()
{
{ "[[ProjectName]]" , options.ProjectName } ,
{ "[[AssemblyGuid]]", Guid.NewGuid().ToString("D") }
});
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Error building file '{0}' : {1}", assemblyInfoFilename, ex.Message));
}
string projectFileName = Path.Combine(options.ProjectPath, options.ProjectName, string.Format("{0}.csproj", options.ProjectName));
try
{
TemplateFileGenerator projectFileGen = new TemplateFileGenerator(Path.Combine(options.TemplatePath, "ProjectTemplate.proj.tmp"));
projectFileGen.GenerateFile(projectFileName, new Dictionary<string, string>()
{
{ "[[ProjectGuid]]", Guid.NewGuid().ToString("B") } ,
{ "[[ProjectName]]" , options.ProjectName } ,
{ "[[Tests]]" , allTestProjects.ToString() }
});
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Error building file '{0}' : {1}", projectFileName, ex.Message));
}
Console.WriteLine("Done.");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
| Java |
class AlbumsController < ApplicationController
respond_to :html, :xml, :json
attr_reader :current_album_type, :author_name
load_and_authorize_resource
def index
@albums = Album.by_type params[:album_type]
respond_with(@albums)
end
def show
get_current_album_type
get_author_name
if @current_album_type.name.singularize == 'Picture'
@album_pictures = @album.pictures.paginate(:page => params[:page], :per_page => 12)
elsif @current_album_type.name.singularize == 'Video'
@album_videos = @album.videos.paginate(:page => params[:page], :per_page => 12)
end
respond_with(@album)
end
def new
@album.album_type_id = params[:album_type]
get_current_album_type
respond_with(@album)
end
def edit
get_current_album_type
respond_with(@album)
end
def create
@album.user_id = user_signed_in? ? current_user.id : 0
flash[:notice] = 'Album was successfully created.' if @album.save
get_current_album_type
respond_with(@album)
end
def update
@album.update_attributes(params[:album])
respond_with(@album)
end
def destroy
@album.destroy
flash[:notice] = 'Successfully destroyed album.'
redirect_to albums_path(:album_type => @album.album_type_id)
end
private
def get_current_album_type
@current_album_type = AlbumType.all.find { |album_type| album_type.id == @album.album_type_id }
end
def get_author_name
@author_name = (@album.user_id > 0) \
? User.find { |user| user.id == @album.user_id }.name \
: 'Anonymous'
end
end
| Java |
// フォーマット
var koyomi = require('../..').create();
var format = koyomi.format.bind(koyomi);
var eq = require('assert').equal;
koyomi.startMonth = 1;
// 序数 (CC:経過日数)
eq(format(20150101, 'CC'), '1');
eq(format(20150101, 'CC>0'), '1st');
eq(format(20150102, 'CC>0'), '2nd');
eq(format(20150103, 'CC>0'), '3rd');
eq(format(20150104, 'CC>0'), '4th');
eq(format(20150105, 'CC>0'), '5th');
eq(format(20150106, 'CC>0'), '6th');
eq(format(20150107, 'CC>0'), '7th');
eq(format(20150108, 'CC>0'), '8th');
eq(format(20150109, 'CC>0'), '9th');
eq(format(20150110, 'CC>0'), '10th');
eq(format(20150111, 'CC>0'), '11th');
eq(format(20150112, 'CC>0'), '12th');
eq(format(20150113, 'CC>0'), '13th');
eq(format(20150114, 'CC>0'), '14th');
eq(format(20150115, 'CC>0'), '15th');
eq(format(20150116, 'CC>0'), '16th');
eq(format(20150117, 'CC>0'), '17th');
eq(format(20150118, 'CC>0'), '18th');
eq(format(20150119, 'CC>0'), '19th');
eq(format(20150120, 'CC>0'), '20th');
eq(format(20150121, 'CC>0'), '21st');
eq(format(20150122, 'CC>0'), '22nd');
eq(format(20150123, 'CC>0'), '23rd');
eq(format(20150124, 'CC>0'), '24th');
eq(format(20150125, 'CC>0'), '25th');
eq(format(20150126, 'CC>0'), '26th');
eq(format(20150127, 'CC>0'), '27th');
eq(format(20150128, 'CC>0'), '28th');
eq(format(20150129, 'CC>0'), '29th');
eq(format(20150130, 'CC>0'), '30th');
eq(format(20150131, 'CC>0'), '31st');
eq(format(20150201, 'CC>0'), '32nd');
eq(format(20150202, 'CC>0'), '33rd');
eq(format(20150203, 'CC>0'), '34th');
eq(format(20150204, 'CC>0'), '35th');
eq(format(20150205, 'CC>0'), '36th');
eq(format(20150206, 'CC>0'), '37th');
eq(format(20150207, 'CC>0'), '38th');
eq(format(20150208, 'CC>0'), '39th');
eq(format(20150209, 'CC>0'), '40th');
eq(format(20150210, 'CC>0'), '41st');
eq(format(20150211, 'CC>0'), '42nd');
eq(format(20150212, 'CC>0'), '43rd');
eq(format(20150213, 'CC>0'), '44th');
eq(format(20150214, 'CC>0'), '45th');
eq(format(20150215, 'CC>0'), '46th');
eq(format(20150216, 'CC>0'), '47th');
eq(format(20150217, 'CC>0'), '48th');
eq(format(20150218, 'CC>0'), '49th');
eq(format(20150219, 'CC>0'), '50th');
eq(format(20150220, 'CC>0'), '51st');
eq(format(20150221, 'CC>0'), '52nd');
eq(format(20150222, 'CC>0'), '53rd');
eq(format(20150223, 'CC>0'), '54th');
eq(format(20150224, 'CC>0'), '55th');
eq(format(20150225, 'CC>0'), '56th');
eq(format(20150226, 'CC>0'), '57th');
eq(format(20150227, 'CC>0'), '58th');
eq(format(20150228, 'CC>0'), '59th');
eq(format(20150301, 'CC>0'), '60th');
eq(format(20150302, 'CC>0'), '61st');
eq(format(20150303, 'CC>0'), '62nd');
eq(format(20150304, 'CC>0'), '63rd');
eq(format(20150305, 'CC>0'), '64th');
eq(format(20150306, 'CC>0'), '65th');
eq(format(20150307, 'CC>0'), '66th');
eq(format(20150308, 'CC>0'), '67th');
eq(format(20150309, 'CC>0'), '68th');
eq(format(20150310, 'CC>0'), '69th');
eq(format(20150311, 'CC>0'), '70th');
eq(format(20150312, 'CC>0'), '71st');
eq(format(20150313, 'CC>0'), '72nd');
eq(format(20150314, 'CC>0'), '73rd');
eq(format(20150315, 'CC>0'), '74th');
eq(format(20150316, 'CC>0'), '75th');
eq(format(20150317, 'CC>0'), '76th');
eq(format(20150318, 'CC>0'), '77th');
eq(format(20150319, 'CC>0'), '78th');
eq(format(20150320, 'CC>0'), '79th');
eq(format(20150321, 'CC>0'), '80th');
eq(format(20150322, 'CC>0'), '81st');
eq(format(20150323, 'CC>0'), '82nd');
eq(format(20150324, 'CC>0'), '83rd');
eq(format(20150325, 'CC>0'), '84th');
eq(format(20150326, 'CC>0'), '85th');
eq(format(20150327, 'CC>0'), '86th');
eq(format(20150328, 'CC>0'), '87th');
eq(format(20150329, 'CC>0'), '88th');
eq(format(20150330, 'CC>0'), '89th');
eq(format(20150331, 'CC>0'), '90th');
eq(format(20150401, 'CC>0'), '91st');
eq(format(20150402, 'CC>0'), '92nd');
eq(format(20150403, 'CC>0'), '93rd');
eq(format(20150404, 'CC>0'), '94th');
eq(format(20150405, 'CC>0'), '95th');
eq(format(20150406, 'CC>0'), '96th');
eq(format(20150407, 'CC>0'), '97th');
eq(format(20150408, 'CC>0'), '98th');
eq(format(20150409, 'CC>0'), '99th');
eq(format(20150410, 'CC>0'), '100th');
eq(format(20150411, 'CC>0'), '101st');
eq(format(20150412, 'CC>0'), '102nd');
eq(format(20150413, 'CC>0'), '103rd');
eq(format(20150414, 'CC>0'), '104th');
eq(format(20150415, 'CC>0'), '105th');
eq(format(20150416, 'CC>0'), '106th');
eq(format(20150417, 'CC>0'), '107th');
eq(format(20150418, 'CC>0'), '108th');
eq(format(20150419, 'CC>0'), '109th');
eq(format(20150420, 'CC>0'), '110th');
eq(format(20150421, 'CC>0'), '111th');
eq(format(20150422, 'CC>0'), '112th');
eq(format(20150423, 'CC>0'), '113th');
eq(format(20150424, 'CC>0'), '114th');
eq(format(20150425, 'CC>0'), '115th');
eq(format(20150426, 'CC>0'), '116th');
eq(format(20150427, 'CC>0'), '117th');
eq(format(20150428, 'CC>0'), '118th');
eq(format(20150429, 'CC>0'), '119th');
eq(format(20150430, 'CC>0'), '120th');
eq(format(20150501, 'CC>0'), '121st');
eq(format(20150502, 'CC>0'), '122nd');
eq(format(20150503, 'CC>0'), '123rd');
eq(format(20150504, 'CC>0'), '124th');
eq(format(20150505, 'CC>0'), '125th');
eq(format(20150506, 'CC>0'), '126th');
eq(format(20150507, 'CC>0'), '127th');
eq(format(20150508, 'CC>0'), '128th');
eq(format(20150509, 'CC>0'), '129th');
eq(format(20150510, 'CC>0'), '130th');
eq(format(20150511, 'CC>0'), '131st');
eq(format(20150512, 'CC>0'), '132nd');
eq(format(20150513, 'CC>0'), '133rd');
eq(format(20150514, 'CC>0'), '134th');
eq(format(20150515, 'CC>0'), '135th');
eq(format(20150516, 'CC>0'), '136th');
eq(format(20150517, 'CC>0'), '137th');
eq(format(20150518, 'CC>0'), '138th');
eq(format(20150519, 'CC>0'), '139th');
eq(format(20150520, 'CC>0'), '140th');
eq(format(20150521, 'CC>0'), '141st');
eq(format(20150522, 'CC>0'), '142nd');
eq(format(20150523, 'CC>0'), '143rd');
eq(format(20150524, 'CC>0'), '144th');
eq(format(20150525, 'CC>0'), '145th');
eq(format(20150526, 'CC>0'), '146th');
eq(format(20150527, 'CC>0'), '147th');
eq(format(20150528, 'CC>0'), '148th');
eq(format(20150529, 'CC>0'), '149th');
eq(format(20150530, 'CC>0'), '150th');
eq(format(20150531, 'CC>0'), '151st');
eq(format(20150601, 'CC>0'), '152nd');
eq(format(20150602, 'CC>0'), '153rd');
eq(format(20150603, 'CC>0'), '154th');
eq(format(20150604, 'CC>0'), '155th');
eq(format(20150605, 'CC>0'), '156th');
eq(format(20150606, 'CC>0'), '157th');
eq(format(20150607, 'CC>0'), '158th');
eq(format(20150608, 'CC>0'), '159th');
eq(format(20150609, 'CC>0'), '160th');
eq(format(20150610, 'CC>0'), '161st');
eq(format(20150611, 'CC>0'), '162nd');
eq(format(20150612, 'CC>0'), '163rd');
eq(format(20150613, 'CC>0'), '164th');
eq(format(20150614, 'CC>0'), '165th');
eq(format(20150615, 'CC>0'), '166th');
eq(format(20150616, 'CC>0'), '167th');
eq(format(20150617, 'CC>0'), '168th');
eq(format(20150618, 'CC>0'), '169th');
eq(format(20150619, 'CC>0'), '170th');
eq(format(20150620, 'CC>0'), '171st');
eq(format(20150621, 'CC>0'), '172nd');
eq(format(20150622, 'CC>0'), '173rd');
eq(format(20150623, 'CC>0'), '174th');
eq(format(20150624, 'CC>0'), '175th');
eq(format(20150625, 'CC>0'), '176th');
eq(format(20150626, 'CC>0'), '177th');
eq(format(20150627, 'CC>0'), '178th');
eq(format(20150628, 'CC>0'), '179th');
eq(format(20150629, 'CC>0'), '180th');
eq(format(20150630, 'CC>0'), '181st');
eq(format(20150701, 'CC>0'), '182nd');
eq(format(20150702, 'CC>0'), '183rd');
eq(format(20150703, 'CC>0'), '184th');
eq(format(20150704, 'CC>0'), '185th');
eq(format(20150705, 'CC>0'), '186th');
eq(format(20150706, 'CC>0'), '187th');
eq(format(20150707, 'CC>0'), '188th');
eq(format(20150708, 'CC>0'), '189th');
eq(format(20150709, 'CC>0'), '190th');
eq(format(20150710, 'CC>0'), '191st');
eq(format(20150711, 'CC>0'), '192nd');
eq(format(20150712, 'CC>0'), '193rd');
eq(format(20150713, 'CC>0'), '194th');
eq(format(20150714, 'CC>0'), '195th');
eq(format(20150715, 'CC>0'), '196th');
eq(format(20150716, 'CC>0'), '197th');
eq(format(20150717, 'CC>0'), '198th');
eq(format(20150718, 'CC>0'), '199th');
eq(format(20150719, 'CC>0'), '200th');
eq(format(20150720, 'CC>0'), '201st');
eq(format(20150721, 'CC>0'), '202nd');
eq(format(20150722, 'CC>0'), '203rd');
eq(format(20150723, 'CC>0'), '204th');
eq(format(20150724, 'CC>0'), '205th');
eq(format(20150725, 'CC>0'), '206th');
eq(format(20150726, 'CC>0'), '207th');
eq(format(20150727, 'CC>0'), '208th');
eq(format(20150728, 'CC>0'), '209th');
eq(format(20150729, 'CC>0'), '210th');
eq(format(20150730, 'CC>0'), '211th');
eq(format(20150731, 'CC>0'), '212th');
eq(format(20150801, 'CC>0'), '213th');
eq(format(20150802, 'CC>0'), '214th');
eq(format(20150803, 'CC>0'), '215th');
eq(format(20150804, 'CC>0'), '216th');
eq(format(20150805, 'CC>0'), '217th');
eq(format(20150806, 'CC>0'), '218th');
eq(format(20150807, 'CC>0'), '219th');
eq(format(20150808, 'CC>0'), '220th');
eq(format(20150809, 'CC>0'), '221st');
eq(format(20150810, 'CC>0'), '222nd');
eq(format(20150811, 'CC>0'), '223rd');
eq(format(20150812, 'CC>0'), '224th');
eq(format(20150813, 'CC>0'), '225th');
eq(format(20150814, 'CC>0'), '226th');
eq(format(20150815, 'CC>0'), '227th');
eq(format(20150816, 'CC>0'), '228th');
eq(format(20150817, 'CC>0'), '229th');
eq(format(20150818, 'CC>0'), '230th');
eq(format(20150819, 'CC>0'), '231st');
eq(format(20150820, 'CC>0'), '232nd');
eq(format(20150821, 'CC>0'), '233rd');
eq(format(20150822, 'CC>0'), '234th');
eq(format(20150823, 'CC>0'), '235th');
eq(format(20150824, 'CC>0'), '236th');
eq(format(20150825, 'CC>0'), '237th');
eq(format(20150826, 'CC>0'), '238th');
eq(format(20150827, 'CC>0'), '239th');
eq(format(20150828, 'CC>0'), '240th');
eq(format(20150829, 'CC>0'), '241st');
eq(format(20150830, 'CC>0'), '242nd');
eq(format(20150831, 'CC>0'), '243rd');
eq(format(20150901, 'CC>0'), '244th');
eq(format(20150902, 'CC>0'), '245th');
eq(format(20150903, 'CC>0'), '246th');
eq(format(20150904, 'CC>0'), '247th');
eq(format(20150905, 'CC>0'), '248th');
eq(format(20150906, 'CC>0'), '249th');
eq(format(20150907, 'CC>0'), '250th');
eq(format(20150908, 'CC>0'), '251st');
eq(format(20150909, 'CC>0'), '252nd');
eq(format(20150910, 'CC>0'), '253rd');
eq(format(20150911, 'CC>0'), '254th');
eq(format(20150912, 'CC>0'), '255th');
eq(format(20150913, 'CC>0'), '256th');
eq(format(20150914, 'CC>0'), '257th');
eq(format(20150915, 'CC>0'), '258th');
eq(format(20150916, 'CC>0'), '259th');
eq(format(20150917, 'CC>0'), '260th');
eq(format(20150918, 'CC>0'), '261st');
eq(format(20150919, 'CC>0'), '262nd');
eq(format(20150920, 'CC>0'), '263rd');
eq(format(20150921, 'CC>0'), '264th');
eq(format(20150922, 'CC>0'), '265th');
eq(format(20150923, 'CC>0'), '266th');
eq(format(20150924, 'CC>0'), '267th');
eq(format(20150925, 'CC>0'), '268th');
eq(format(20150926, 'CC>0'), '269th');
eq(format(20150927, 'CC>0'), '270th');
eq(format(20150928, 'CC>0'), '271st');
eq(format(20150929, 'CC>0'), '272nd');
eq(format(20150930, 'CC>0'), '273rd');
eq(format(20151001, 'CC>0'), '274th');
eq(format(20151002, 'CC>0'), '275th');
eq(format(20151003, 'CC>0'), '276th');
eq(format(20151004, 'CC>0'), '277th');
eq(format(20151005, 'CC>0'), '278th');
eq(format(20151006, 'CC>0'), '279th');
eq(format(20151007, 'CC>0'), '280th');
eq(format(20151008, 'CC>0'), '281st');
eq(format(20151009, 'CC>0'), '282nd');
eq(format(20151010, 'CC>0'), '283rd');
eq(format(20151011, 'CC>0'), '284th');
eq(format(20151012, 'CC>0'), '285th');
eq(format(20151013, 'CC>0'), '286th');
eq(format(20151014, 'CC>0'), '287th');
eq(format(20151015, 'CC>0'), '288th');
eq(format(20151016, 'CC>0'), '289th');
eq(format(20151017, 'CC>0'), '290th');
eq(format(20151018, 'CC>0'), '291st');
eq(format(20151019, 'CC>0'), '292nd');
eq(format(20151020, 'CC>0'), '293rd');
eq(format(20151021, 'CC>0'), '294th');
eq(format(20151022, 'CC>0'), '295th');
eq(format(20151023, 'CC>0'), '296th');
eq(format(20151024, 'CC>0'), '297th');
eq(format(20151025, 'CC>0'), '298th');
eq(format(20151026, 'CC>0'), '299th');
eq(format(20151027, 'CC>0'), '300th');
eq(format(20151028, 'CC>0'), '301st');
eq(format(20151029, 'CC>0'), '302nd');
eq(format(20151030, 'CC>0'), '303rd');
eq(format(20151031, 'CC>0'), '304th');
eq(format(20151101, 'CC>0'), '305th');
eq(format(20151102, 'CC>0'), '306th');
eq(format(20151103, 'CC>0'), '307th');
eq(format(20151104, 'CC>0'), '308th');
eq(format(20151105, 'CC>0'), '309th');
eq(format(20151106, 'CC>0'), '310th');
eq(format(20151107, 'CC>0'), '311th');
eq(format(20151108, 'CC>0'), '312th');
eq(format(20151109, 'CC>0'), '313th');
eq(format(20151110, 'CC>0'), '314th');
eq(format(20151111, 'CC>0'), '315th');
eq(format(20151112, 'CC>0'), '316th');
eq(format(20151113, 'CC>0'), '317th');
eq(format(20151114, 'CC>0'), '318th');
eq(format(20151115, 'CC>0'), '319th');
eq(format(20151116, 'CC>0'), '320th');
eq(format(20151117, 'CC>0'), '321st');
eq(format(20151118, 'CC>0'), '322nd');
eq(format(20151119, 'CC>0'), '323rd');
eq(format(20151120, 'CC>0'), '324th');
eq(format(20151121, 'CC>0'), '325th');
eq(format(20151122, 'CC>0'), '326th');
eq(format(20151123, 'CC>0'), '327th');
eq(format(20151124, 'CC>0'), '328th');
eq(format(20151125, 'CC>0'), '329th');
eq(format(20151126, 'CC>0'), '330th');
eq(format(20151127, 'CC>0'), '331st');
eq(format(20151128, 'CC>0'), '332nd');
eq(format(20151129, 'CC>0'), '333rd');
eq(format(20151130, 'CC>0'), '334th');
eq(format(20151201, 'CC>0'), '335th');
eq(format(20151202, 'CC>0'), '336th');
eq(format(20151203, 'CC>0'), '337th');
eq(format(20151204, 'CC>0'), '338th');
eq(format(20151205, 'CC>0'), '339th');
eq(format(20151206, 'CC>0'), '340th');
eq(format(20151207, 'CC>0'), '341st');
eq(format(20151208, 'CC>0'), '342nd');
eq(format(20151209, 'CC>0'), '343rd');
eq(format(20151210, 'CC>0'), '344th');
eq(format(20151211, 'CC>0'), '345th');
eq(format(20151212, 'CC>0'), '346th');
eq(format(20151213, 'CC>0'), '347th');
eq(format(20151214, 'CC>0'), '348th');
eq(format(20151215, 'CC>0'), '349th');
eq(format(20151216, 'CC>0'), '350th');
eq(format(20151217, 'CC>0'), '351st');
eq(format(20151218, 'CC>0'), '352nd');
eq(format(20151219, 'CC>0'), '353rd');
eq(format(20151220, 'CC>0'), '354th');
eq(format(20151221, 'CC>0'), '355th');
eq(format(20151222, 'CC>0'), '356th');
eq(format(20151223, 'CC>0'), '357th');
eq(format(20151224, 'CC>0'), '358th');
eq(format(20151225, 'CC>0'), '359th');
eq(format(20151226, 'CC>0'), '360th');
eq(format(20151227, 'CC>0'), '361st');
eq(format(20151228, 'CC>0'), '362nd');
eq(format(20151229, 'CC>0'), '363rd');
eq(format(20151230, 'CC>0'), '364th');
eq(format(20151231, 'CC>0'), '365th');
// 文字列の序数
eq(format(20150101, 'GG>0'), '平成');
eq(format(20000101, 'y>0'), '00th');
eq(format(20010101, 'y>0'), '01st');
| Java |
# ImageHelper
[](http://cocoapods.org/pods/AFImageHelper)
[](http://cocoapods.org/pods/AFImageHelper)
[](http://cocoapods.org/pods/AFImageHelper)
[](https://github.com/Carthage/Carthage)
Image Extensions for Swift 3.0

## Usage
To run the example project, clone or download the repo, and run.
## UIImageView Extension
### Image from a URL
```Swift
// Fetches an image from a URL. If caching is set, it will be cached by NSCache for future queries. The cached image is returned if available, otherise the placeholder is set. When the image is returned, the closure gets called.
func imageFromURL(url: String, placeholder: UIImage, fadeIn: Bool = true, closure: ((image: UIImage?)
```
## UIImage Extension
### Colors
```Swift
// Creates an image from a solid color
UIImage(color:UIColor, size:CGSize)
// Creates an image from a gradient color
UIImage(gradientColors:[UIColor], size:CGSize)
// Applies a gradient overlay to an image
func applyGradientColors(gradientColors: [UIColor], blendMode: CGBlendMode) -> UIImage
// Creates an image from a radial gradient
UIImage(startColor: UIColor, endColor: UIColor, radialGradientCenter: CGPoint, radius:Float, size:CGSize)
```
### Text
```Swift
// Creates an image with a string of text
UIImage(text: String, font: UIFont, color: UIColor, backgroundColor: UIColor, size:CGSize, offset: CGPoint)
```
### Screenshot
```Swift
// Creates an image from a UIView
UIImage(fromView view: UIView)
```
### Alpha and Padding
```Swift
// Returns true if the image has an alpha layer
func hasAlpha() -> Bool
// Returns a copy(if needed) of the image with alpha layer
func applyAlpha() -> UIImage?
// Returns a copy of the image with a transparent border of the given size added around its edges
func applyPadding(padding: CGFloat) -> UIImage?
```
### Crop and Resize
```Swift
// Crops an image to a new rect
func crop(bounds: CGRect) -> UIImage?
// Crops an image to a centered square
func cropToSquare() -> UIImage? {
// Resizes an image
func resize(size:CGSize, contentMode: UIImageContentMode = .ScaleToFill) -> UIImage?
```
### Circle and Rounded Corners
```Swift
// Rounds corners of an image
func roundCorners(cornerRadius:CGFloat) -> UIImage?
// Rounds corners of an image with border
func roundCorners(cornerRadius:CGFloat, border:CGFloat, color:UIColor) -> UIImage?
// Rounds corners to a circle
func roundCornersToCircle() -> UIImage?
// Rounds corners to a circle with border
func roundCornersToCircle(border border:CGFloat, color:UIColor) -> UIImage?
```
### Border
```Swift
// Adds a border
func applyBorder(border:CGFloat, color:UIColor) -> UIImage?
```
### Image Effects
```Swift
// Applies a light blur effect to the image
func applyLightEffect() -> UIImage?
// Applies a extra light blur effect to the image
func applyExtraLightEffect() -> UIImage?
// Applies a dark blur effect to the image
func applyDarkEffect() -> UIImage?
// Applies a color tint to an image
func applyTintEffect(tintColor: UIColor) -> UIImage?
// Applies a blur to an image based on the specified radius, tint color saturation and mask image
func applyBlur(blurRadius:CGFloat, tintColor:UIColor?, saturationDeltaFactor:CGFloat, maskImage:UIImage? = nil) -> UIImage?
```
### Screen Density
```Swift
// To create an image that is Retina aware, use the screen scale as a multiplier for your size. You should also use this technique for padding or borders.
let width = 140 * UIScreen.mainScreen().scale
let height = 140 * UIScreen.mainScreen().scale
let image = UIImage(named: "myImage")?.resize(CGSize(width: width, height: height))
```
| Java |
import { apiGet, apiPut, apiDelete } from 'utils/api'
import { flashError, flashSuccess } from 'utils/flash'
import { takeLatest, takeEvery, call, put, select } from 'redux-saga/effects'
import { filter, find, without, omit } from 'lodash'
import { filesUrlSelector } from 'ducks/app'
import { makeUploadsSelector } from 'ducks/uploads'
import { makeFiltersQuerySelector } from 'ducks/filters'
import { makeSelectedFileIdsSelector } from 'ducks/filePlacements'
// Constants
const GET_FILES = 'files/GET_FILES'
const GET_FILES_SUCCESS = 'files/GET_FILES_SUCCESS'
const UPLOADED_FILE = 'files/UPLOADED_FILE'
const THUMBNAIL_GENERATED = 'files/THUMBNAIL_GENERATED'
const DELETE_FILE = 'files/DELETE_FILE'
const DELETE_FILE_FAILURE = 'files/DELETE_FILE_FAILURE'
const UPDATE_FILE = 'files/UPDATE_FILE'
export const UPDATE_FILE_SUCCESS = 'files/UPDATE_FILE_SUCCESS'
export const UPDATE_FILE_FAILURE = 'files/UPDATE_FILE_FAILURE'
const UPDATED_FILES = 'files/UPDATED_FILES'
const REMOVED_FILES = 'files/REMOVED_FILES'
const CHANGE_FILES_PAGE = 'files/CHANGE_FILES_PAGE'
const MASS_SELECT = 'files/MASS_SELECT'
const MASS_DELETE = 'files/MASS_DELETE'
const MASS_CANCEL = 'files/MASS_CANCEL'
// Actions
export function getFiles (fileType, filesUrl, query = '') {
return { type: GET_FILES, fileType, filesUrl, query }
}
export function getFilesSuccess (fileType, records, meta) {
return { type: GET_FILES_SUCCESS, fileType, records, meta }
}
export function uploadedFile (fileType, file) {
return { type: UPLOADED_FILE, fileType, file }
}
export function thumbnailGenerated (fileType, temporaryUrl, url) {
return { type: THUMBNAIL_GENERATED, fileType, temporaryUrl, url }
}
export function updatedFiles (fileType, files) {
return { type: UPDATED_FILES, fileType, files }
}
export function updateFile (fileType, filesUrl, file, attributes) {
return { type: UPDATE_FILE, fileType, filesUrl, file, attributes }
}
export function deleteFile (fileType, filesUrl, file) {
return { type: DELETE_FILE, fileType, filesUrl, file }
}
export function deleteFileFailure (fileType, file) {
return { type: DELETE_FILE_FAILURE, fileType, file }
}
export function removedFiles (fileType, ids) {
return { type: REMOVED_FILES, fileType, ids }
}
export function updateFileSuccess (fileType, file, response) {
return { type: UPDATE_FILE_SUCCESS, fileType, file, response }
}
export function updateFileFailure (fileType, file) {
return { type: UPDATE_FILE_FAILURE, fileType, file }
}
export function changeFilesPage (fileType, filesUrl, page) {
return { type: CHANGE_FILES_PAGE, fileType, filesUrl, page }
}
export function massSelect (fileType, file, select) {
return { type: MASS_SELECT, fileType, file, select }
}
export function massDelete (fileType) {
return { type: MASS_DELETE, fileType }
}
export function massCancel (fileType) {
return { type: MASS_CANCEL, fileType }
}
// Sagas
function * getFilesPerform (action) {
try {
const filesUrl = `${action.filesUrl}?${action.query}`
const response = yield call(apiGet, filesUrl)
yield put(getFilesSuccess(action.fileType, response.data, response.meta))
} catch (e) {
flashError(e.message)
}
}
function * getFilesSaga () {
// takeLatest automatically cancels any saga task started previously if it's still running
yield takeLatest(GET_FILES, getFilesPerform)
}
function * updateFilePerform (action) {
try {
const { file, filesUrl, attributes } = action
const fullUrl = `${filesUrl}/${file.id}`
const data = {
file: {
id: file.id,
attributes
}
}
const response = yield call(apiPut, fullUrl, data)
yield put(updateFileSuccess(action.fileType, action.file, response.data))
} catch (e) {
flashError(e.message)
yield put(updateFileFailure(action.fileType, action.file))
}
}
function * updateFileSaga () {
yield takeEvery(UPDATE_FILE, updateFilePerform)
}
function * changeFilesPagePerform (action) {
try {
const filtersQuery = yield select(makeFiltersQuerySelector(action.fileType))
let query = `page=${action.page}`
if (filtersQuery) {
query = `${query}&${filtersQuery}`
}
yield put(getFiles(action.fileType, action.filesUrl, query))
} catch (e) {
flashError(e.message)
}
}
function * changeFilesPageSaga () {
yield takeLatest(CHANGE_FILES_PAGE, changeFilesPagePerform)
}
function * massDeletePerform (action) {
try {
const { massSelectedIds } = yield select(makeMassSelectedIdsSelector(action.fileType))
const filesUrl = yield select(filesUrlSelector)
const fullUrl = `${filesUrl}/mass_destroy?ids=${massSelectedIds.join(',')}`
const res = yield call(apiDelete, fullUrl)
if (res.error) {
flashError(res.error)
} else {
flashSuccess(res.data.message)
yield put(removedFiles(action.fileType, massSelectedIds))
yield put(massCancel(action.fileType))
}
} catch (e) {
flashError(e.message)
}
}
function * massDeleteSaga () {
yield takeLatest(MASS_DELETE, massDeletePerform)
}
function * deleteFilePerform (action) {
try {
const res = yield call(apiDelete, `${action.filesUrl}/${action.file.id}`)
if (res.error) {
flashError(res.error)
} else {
yield put(removedFiles(action.fileType, [action.file.id]))
}
} catch (e) {
flashError(e.message)
}
}
function * deleteFileSaga () {
yield takeLatest(DELETE_FILE, deleteFilePerform)
}
export const filesSagas = [
getFilesSaga,
updateFileSaga,
changeFilesPageSaga,
massDeleteSaga,
deleteFileSaga
]
// Selectors
export const makeFilesStatusSelector = (fileType) => (state) => {
return {
loading: state.files[fileType] && state.files[fileType].loading,
loaded: state.files[fileType] && state.files[fileType].loaded,
massSelecting: state.files[fileType].massSelectedIds.length > 0
}
}
export const makeFilesLoadedSelector = (fileType) => (state) => {
return state.files[fileType] && state.files[fileType].loaded
}
export const makeMassSelectedIdsSelector = (fileType) => (state) => {
const base = state.files[fileType] || defaultFilesKeyState
return {
massSelectedIds: base.massSelectedIds,
massSelectedIndestructibleIds: base.massSelectedIndestructibleIds
}
}
export const makeFilesSelector = (fileType) => (state) => {
const base = state.files[fileType] || defaultFilesKeyState
const selected = base.massSelectedIds
return base.records.map((file) => {
if (file.id && selected.indexOf(file.id) !== -1) {
return { ...file, massSelected: true }
} else {
return file
}
})
}
export const makeFilesForListSelector = (fileType) => (state) => {
const uploads = makeUploadsSelector(fileType)(state)
let files
if (uploads.uploadedIds.length) {
files = makeFilesSelector(fileType)(state).map((file) => {
if (uploads.uploadedIds.indexOf(file.id) === -1) {
return file
} else {
return { ...file, attributes: { ...file.attributes, freshlyUploaded: true } }
}
})
} else {
files = makeFilesSelector(fileType)(state)
}
return [
...Object.values(uploads.records).map((upload) => ({ ...upload, attributes: { ...upload.attributes, uploading: true } })),
...files
]
}
export const makeRawUnselectedFilesForListSelector = (fileType, selectedIds) => (state) => {
const all = makeFilesForListSelector(fileType)(state)
return filter(all, (file) => selectedIds.indexOf(String(file.id)) === -1)
}
export const makeUnselectedFilesForListSelector = (fileType) => (state) => {
const all = makeFilesForListSelector(fileType)(state)
const selectedIds = makeSelectedFileIdsSelector(fileType)(state)
return filter(all, (file) => selectedIds.indexOf(String(file.id)) === -1)
}
export const makeFilesPaginationSelector = (fileType) => (state) => {
const base = state.files[fileType] || defaultFilesKeyState
return base.pagination
}
export const makeFilesReactTypeSelector = (fileType) => (state) => {
const base = state.files[fileType] || defaultFilesKeyState
return base.reactType
}
export const makeFilesReactTypeIsImageSelector = (fileType) => (state) => {
return makeFilesReactTypeSelector(fileType)(state) === 'image'
}
// State
const defaultFilesKeyState = {
loading: false,
loaded: false,
records: [],
massSelectedIds: [],
massSelectedIndestructibleIds: [],
reactType: 'document',
pagination: {
page: null,
pages: null
}
}
const initialState = {}
// Reducer
function filesReducer (rawState = initialState, action) {
const state = rawState
if (action.fileType && !state[action.fileType]) {
state[action.fileType] = { ...defaultFilesKeyState }
}
switch (action.type) {
case GET_FILES:
return {
...state,
[action.fileType]: {
...state[action.fileType],
loading: true
}
}
case GET_FILES_SUCCESS:
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: action.records,
loading: false,
loaded: true,
pagination: omit(action.meta, ['react_type']),
reactType: action.meta.react_type
}
}
case UPLOADED_FILE:
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: [action.file, ...state[action.fileType].records]
}
}
case THUMBNAIL_GENERATED: {
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: state[action.fileType].records.map((record) => {
if (record.attributes.thumb !== action.temporaryUrl) return record
return {
...record,
attributes: {
...record.attributes,
thumb: action.url
}
}
})
}
}
}
case UPDATE_FILE:
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: state[action.fileType].records.map((record) => {
if (record.id === action.file.id) {
return {
...record,
attributes: {
...record.attributes,
...action.attributes,
updating: true
}
}
} else {
return record
}
})
}
}
case UPDATE_FILE_SUCCESS:
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: state[action.fileType].records.map((record) => {
if (record.id === action.response.id) {
return action.response
} else {
return record
}
})
}
}
case UPDATE_FILE_FAILURE:
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: state[action.fileType].records.map((record) => {
if (record.id === action.file.id) {
return { ...action.file }
} else {
return record
}
})
}
}
case UPDATED_FILES:
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: state[action.fileType].records.map((record) => {
const found = find(action.files, { id: record.id })
return found || record
})
}
}
case MASS_SELECT: {
if (!action.file.id) return state
let massSelectedIds = state[action.fileType].massSelectedIds
let massSelectedIndestructibleIds = state[action.fileType].massSelectedIndestructibleIds
if (action.select) {
massSelectedIds = [...massSelectedIds, action.file.id]
if (action.file.attributes.file_placements_size) {
massSelectedIndestructibleIds = [...massSelectedIndestructibleIds, action.file.id]
}
} else {
massSelectedIds = without(massSelectedIds, action.file.id)
if (action.file.attributes.file_placements_size) {
massSelectedIndestructibleIds = without(massSelectedIndestructibleIds, action.file.id)
}
}
return {
...state,
[action.fileType]: {
...state[action.fileType],
massSelectedIds,
massSelectedIndestructibleIds
}
}
}
case MASS_CANCEL:
return {
...state,
[action.fileType]: {
...state[action.fileType],
massSelectedIds: []
}
}
case REMOVED_FILES: {
const originalLength = state[action.fileType].records.length
const records = state[action.fileType].records.filter((record) => action.ids.indexOf(record.id) === -1)
return {
...state,
[action.fileType]: {
...state[action.fileType],
records,
pagination: {
...state[action.fileType].pagination,
to: records.length,
count: state[action.fileType].pagination.count - (originalLength - records.length)
}
}
}
}
case DELETE_FILE:
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: state[action.fileType].records.map((record) => {
if (record.id === action.file.id) {
return {
...record,
_destroying: true
}
} else {
return record
}
})
}
}
case DELETE_FILE_FAILURE:
return {
...state,
[action.fileType]: {
...state[action.fileType],
records: state[action.fileType].records.map((record) => {
if (record.id === action.file.id) {
return { ...action.file }
} else {
return record
}
})
}
}
default:
return state
}
}
export default filesReducer
| Java |
using ShiftCaptain.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
namespace ShiftCaptain.Infrastructure
{
public static class Authentication
{
public static Boolean Login(EmailNPass user, ref String errorMessage)
{
errorMessage = "";
var db = new ShiftCaptainEntities();
var validUser = db.Users.FirstOrDefault(u => u.EmailAddress == user.EmailAddress);
if (validUser != null)
{
if (validUser.Locked && validUser.LastLogin.HasValue && (validUser.LastLogin.Value <= DateTime.Now.AddMinutes(-30)))
{
validUser.Locked = false;
validUser.NumTries = 0;
}
int numTries = 4;
Int32.TryParse(ConfigurationManager.AppSettings["NumTries"], out numTries);
if (validUser.NumTries++ > numTries)
{
validUser.Locked = true;
}
if (!validUser.Locked && validUser.Pass == user.Pass)
{
validUser.NumTries = 0;
if (validUser.IsActive)
{
var ticket = new FormsAuthenticationTicket(String.Format("{0}|{1}", validUser.Id, validUser.EmailAddress), true, 30);
var encr = FormsAuthentication.Encrypt(ticket);
//FormsAuthentication.SetAuthCookie("authCk", false);
SessionManager.UserId = validUser.Id;
SessionManager.token = encr;
SessionManager.GetVersion();
return true;
}
}
validUser.LastLogin = DateTime.Now;
db.Entry(validUser).State = EntityState.Modified;
db.SaveChanges();
if (validUser.Locked)
{
errorMessage = "Your account is locked. Please wait 30 minutes or contact the system administrator.";
return false;
}
}
errorMessage = "Email Address or Password is invalid.";
return false;
}
public static void LogOff()
{
SessionManager.Clear();
}
public static bool Authenticate(HttpContextBase ctx)
{
if (SessionManager.token != null)
{
var ticket = FormsAuthentication.Decrypt(SessionManager.token);
if (ticket != null && !ticket.Expired)
{
ctx.User = new GenericPrincipal(new FormsIdentity(ticket), new string[] { });
var nTicket = new FormsAuthenticationTicket(ticket.Name, true, 30);//Everytime you click a new page, clock restarts
SessionManager.token = FormsAuthentication.Encrypt(nTicket);
}
}
return ctx.User.Identity.IsAuthenticated;
}
}
} | Java |
# Angular.js Enterprise Edition Lazy Load Boilerplate
> **TODO:** review and update
This boilerplate (seed project, starting project) helps you build large scale [Angular.js](https://angularjs.org/) applications with [Require.js](http://requirejs.org/)
--
<!-- toc -->
* [Overview](#overview)
* [Installation Guide](#installation-guide)
* [Prerequisites](#prerequisites)
* [Use Guide](#use-guide)
* [Tools for Development Workflow](#tools-for-development-workflow)
* [Build](#build)
* [Code Generation](#code-generation)
* [Development](#development)
* [Distribuction Preview](#distribuction-preview)
* [Tests](#tests)
* [Tools Configuration](#tools-configuration)
* [Tips](#tips)
* [Known Issues](#known-issues)
* [Publishing tool for GitHub gh-pages](#publishing-tool-for-github-gh-pages)
* [Directories Structure](#directories-structure)
* [Development](#development)
* [Publishing](#publishing)
* [Project](#project)
<!-- toc stop -->
## Overview
FrontEnd Boilerplate project with development and publishing tools (for GitHub gh-pages)
* **Important**: to define a better communication between frontend and backend (server), please consider follow the given proposal [REST URL Design](rest_url_design.md)
## Installation Guide
Enter the following commands in the terminal
```bash
$ git clone https://github.com/erkobridee/angularjs-ee-ll-boilerplate.git
$ cd angularjs-ee-ll-boilerplate
$ cd tools
$ npm run setup
$ cd ..
$ cd publisher
$ npm install
```
### Prerequisites
* Must have [Git](http://git-scm.com/) installed
* Must have [node.js (at least v0.10.0)](http://nodejs.org/) installed with npm (Node Package Manager)
* Must have [Grunt](https://github.com/gruntjs/grunt) node package installed globally
## Use Guide
> `./` means root directoy
### Tools for Development Workflow
> Inside `./tools` directory, available grunt.js commands
* `grunt` >> (default task) that will execute lintspaces, jshint to verify and ensure js code quality and cleanup build and dist directories
> **Attention:** the following task **lintspaces** will verify the patterns insides files according rules inside `.editorconfig` in the root directory
#### Build
* `grunt build:dev` >> prepare files for development, inside `./tools/.temp` directory
* `grunt build:prod` >> cleanup build directories, execute test's and then prepare files for distribution / production, inside `./dist` directory
#### Code Generation
* `grunt generate` >> ask for which code generate option you want, values for the chosen and finally output destination
#### Development
* `grunt dev:livereload` >> first will execute `build:dev` task, after that start web server with livereload support and watch changes on files *.html, .css and .js*, that will update all browsers and devices connect to server
* `grunt dev:livereload:proxy` >> beyond the `dev:livereload` tasks, this task create a proxy to route requests to other server based on given context, for example `/rest`
* `grunt dev:sync` >> first will execute `build:dev` task, after that start web server with browser-sync support and watch changes on files *.html, .css and .js*, that will update all browsers and devices connect to server and sync data and navigation
* `grunt dev:sync:proxy` >> beyond the `dev:sync` tasks, this task create a proxy to route requests to other server based on given context, for example `/rest`
##### alias
* `grunt dev` >> alias to `grunt dev:livereload`
* `grunt dev:proxy` >> alias to `grunt dev:livereload:proxy`
#### Distribuction Preview
* `grunt dist` >> first will execute `build:prod` task, after that start web server with generated files
* `grunt dist:proxy` >> first will execute `build:prod` task, after that start web server with generated files + proxy to route requests to other server based on given context, for example `/rest`
* `grunt dist:sync` >> first will execute `build:prod` task, after that start web server with generated files + browser-sync to synchronize data and navigation
* `grunt dist:sync:proxy` >> first will execute `build:prod` task, after that start web server with generated files + browser-sync to synchronize data and navigation + proxy to route requests to other server based on given context, for example `/rest`
#### Tests
##### Unit Tests
* `grunt ci` - cleanup build directories and then execute `karma:ci` grunt task that run test's
* `grunt reports` - cleanup build directories, execute `karma:reports` grunt task that generate coverage and jasmine html reports and then open reports output directory
* `grunt specs` - first generate coverage and jasmine html reports, start karma with watch process and webserver with livereload watching reports html's
> **Attention:** if you want to run with dev flow, run first dev task (ex.: `grunt dev`) in one terminal and in other terminal run `grunt specs`
##### e2e (end-to-end) - Selenium Tests
* `grunt e2e` - execute `build:prod`, start web server with proxy support and then run e2e test's with Protractor
* `grunt protractor` - run only e2e test's
> **Attention:** need to run with dev flow, run first (ex.: `grunt dev`) in one terminal and in other terminal run `grunt protractor` or specific test's suite `grunt protractor --suite bookmarks` (Protractor configs: `./tools/config.protractor.js`)
#### Tools Configuration
* Tools global configs: `./tools/config.js` which is used on `./tools/helpers/grunt/config/project.js`
* Proxy routing configuration ( see: `var backend = { ...` )
* Proxy Grunt.js Plugin : [grunt-connect-proxy](https://github.com/drewzboto/grunt-connect-proxy) | [Using grunt-connect-proxy](http://www.fettblog.eu/blog/2013/09/20/using-grunt-connect-proxy/)
* To center and make more easy to manage Grunt.js tasks configurations was defined the file `./tools/helpers/grunt/config/project.js`
#### Tips
* If you use Sublime Text, check this out:
* [[GitHub] the-front / sublime-angularjs-ee-snippets](https://github.com/the-front/sublime-angularjs-ee-snippets) - Sublime Text 2 / 3 Snippets and Completions for Angular.js, Angular UI Router and Require.js (focused to the angularjs-ee-boilerplate code)
* [[GitHub] caiogondim / jasmine-sublime-snippets](https://github.com/caiogondim/jasmine-sublime-snippets) - Snippets for Jasmine, the BDD framework for testing JavaScript, in Sublime Text
#### Known Issues
##### Mac OSX
* [How do I fix the error EMFILE: Too many opened files? | grunt-contrib-watch - GitHub](https://github.com/gruntjs/grunt-contrib-watch#how-do-i-fix-the-error-emfile-too-many-opened-files)
* [[SuperUser] How to change default ulimit values in Mac OS X 10.6?](https://superuser.com/questions/261023/how-to-change-default-ulimit-values-in-mac-os-x-10-6)
This is because of your system's max opened file limit.
For OSX the default is very low (256).
Temporarily increase your limit with `ulimit -n 2048`,
the number being the new max limit.
In some versions of OSX the above solution doesn't work.
In that case try `launchctl limit maxfiles 2048 2048` and restart your terminal.
##### Windows
* Behind a NTLM proxy
* run `npm install` two times, to install all dependencies
##### Protracto & Selenium - Firefox dos not work
* When you uptade to last Firefox version and Selenium stop to work with
* **Solution:** `keep selenium server jar always up to date`
### Publishing tool for GitHub gh-pages
> Inside `./publisher` directory, available grunt.js commands
* `grunt init` >> do project clone from GitHub inside `./publisher/local/gh-pages` directory and checkout `gh-pages` branch, which is used to update remote `gh-pages` branch on GitHub
> Execute this command at once, before the following commands
--
* `grunt publish` >> this task will invoke `grunt build:prod` command inside `./tools` directory, then copy generated files from `./dist` to `./publisher/local/gh-pages`, commit files and finally push to `gh-pages` branch on GitHub
* `grunt publish:dev` - this task will copy files from `./src` to `./publisher/local/gh-pages`, commit files and finally push to `gh-pages` branch on GitHub
## Directories Structure
```
./
/src >> project source
/tools >> development tools
/publisher >> publisher tool
```
### Development
```
/tools
/helpers
/lib >> auxiliary processing
/scripts >> automation processing
/html_report_template
jasmine.html >> jasmine html report template
/grunt
/config >> configuration files to grunt.js tasks
/tasks >> custom grunt.js tasks
/tests
require.config.js >> load application files and test's specs for Karma Runner
/templates >> templates files for grunt.js generate task
config.js >> global configs for grunt.js tasks
config.karma.js >> referenced on config.js
config.protractor.js >> config for Protractor
Gruntfile.js >> main grunt.js configuration file
package.json >> node.js 'tools' project and dependencies configuration
```
### Publishing
```
/publisher
/helpers
/grunt
/config >> configuration files to grunt.js tasks
/tasks >> custom grunt.js tasks
Gruntfile.js >> main grunt.js configuration file
package.json >> node.js 'publisher' project and dependencies configuration
```
### Project
> The directories structure of the project is organized following the BDD (Behavior Driven Development [wikipedia](https://en.wikipedia.org/wiki/Behavior-driven_development)) concept, where all one "use case" (behavior) is inside the same directory, which this allow code and behavior reuse
```
/src
/app
/bookmarks >> CRUD example with mock
>> package.js map all js files in the directory
this file is referenced as a dependency on /app/main/module.js
/mock
>> package.js map all js files in the directory
this file is referenced as a dependency on /require.mock.load.js
/tests/unit
>> package.js map all js files in the directory
this file is referenced as a dependency on /require.unit.load.js
/tests/e2e
>> files loaded from Protractor config specs regexp
/about
>> module referenced as a dependency on /app/main/module.js
/help
>> module referenced as a dependency on /app/main/module.js
/home
>> module referenced as a dependency on /app/main/module.js
/main
>> main application module where other modules are charged on /module.js
>> package.js map all js files in the directory
this file is referenced as a dependency on /ng.app.js
/shared
/fallback
>> scripts for Internet Explorer
/fend
>> set of commons and useful reusable modules across projects and other modules
/mock
>> module that enables emulate the backend
/less
/bootstrap
default.less >> default theme and configuration for Bootstrap,
which is imported in /less/app.less
>> other configurations and components
/less
app.less >> map .less files that generate /styles/app.css
/styles
app.css
/vendor
>> third party libraries (ex.: twitter bootstrap, jquery, angular.js, ...)
require.mock.load.js >> list and reference all mocks to be loaded
this file is referenced as a dependency on /ng.app.js
require.unit.load.js >> list and reference all tests unit to be loaded
this file is referenced as dependency on
./tools/helpers/tests/require.config.js
ng.app.js >> where start Angular.js application
require.config.js >> main configuration file to load all needed JavaScripts
files to execute /ng.app.js
index.html
```
| Java |
;;; keydown-counter.asm -- Count keydown form P3.2 and outputs in P1 using LED
;; Author: Zeno Zeng <zenoofzeng@gmail.com>
;; Time-stamp: <2014-12-25 21:56:36 Zeno Zeng>
;;; Commentary:
;; Count keydown from P3.2 then ouputs using 8bit P1 (in LED)
;;; Code:
ORG 0000H
AJMP INIT
ORG 0003H
AJMP ONKEYDOWN
INIT:
CLR A
MOV TCON, #01H ; 设置触发方式为脉冲,下降沿有效(IT0 = 1)
MOV IE, #81H ; 中断总允许,允许 EX0(P3.2 引入) 外中断 (EA = 1, EX0 = 1)
LISTENING:
SJMP LISTENING
ONKEYDOWN:
INC A
MOV P1, A
RETI
EXIT:
END
| Java |
var self = module.exports;
self = (function(){
self.debug = true;
self.prefix = '/kaskade';
self.ssl = false;
/*{
key: {PEM},
cert: {PEM}
}*/
self.port = 80;
self.host = '0.0.0.0';
self.onConnectionClose = new Function();
self.redis = false;
/*{
host: {String},
port: {Number},
options: {Object}
}*/
self.init = function(cfg){
for(var c in cfg){
if(c in this)
this[c] = cfg[c];
}
};
})(); | Java |
# encoding: utf-8
require_relative "qipowl/version"
require_relative "qipowl/constants"
require_relative "qipowl/core/mapper"
require_relative "qipowl/core/ruler"
require_relative "qipowl/core/bowler"
require_relative "qipowl/bowlers/html"
require_relative "qipowl/bowlers/i_sp_ru"
#require_relative "qipowl/bowlers/cmd"
#require_relative "qipowl/bowlers/yaml"
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8
module Qipowl
extend self
# A wrapper for the configuration block
def configure &block
instance_eval(&block)
end
def [](key)
config[key.to_sym]
end
private
def set(key, value)
config[key.to_sym] = value
end
def add(key, value)
config[key.to_sym] = [*config[key.to_sym]] << value
end
def config
@config ||= Hash.new
end
def method_missing(sym, *args)
if sym.to_s =~ /(.+)=$/
config[$1.to_sym] = args.first
else
config[sym.to_sym]
end
end
end
Qipowl::configure do
set :bowlers, File.expand_path(File.join(__dir__, '..', 'config', 'bowlers'))
end
class Qipowl::Html
attr_reader :bowler
def self.parse s
(@bowler ||= Qipowl::Ruler.new_bowler "html").execute s
end
end
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Retina</title>
<link rel="stylesheet" href="http://pic.lvmama.com/min/index.php?f=/styles/v6/header_new.css">
<link rel="stylesheet" href="css/monokai-sublime.css">
<link rel="stylesheet" href="css/docs.css">
<link rel="stylesheet" href="css/retina.css">
</head>
<body>
<header id="header">
<div id="logo">
NOVA
</div>
</header>
<menu id="nav">
<li><a href="./">首页</a></li>
</menu>
<div id="everything">
<h1>Retina</h1>
<h2>建议</h2>
<blockquote>
Ctrl + = 放大屏幕显示比例到200%或使用高分屏显示器以查看效果
</blockquote>
<h3>普通图片</h3>
<section>
<div class="lvmama-logo"></div>
</section>
<h3>高分屏适配图片</h3>
<section>
<div class="lvmama-logo lvmama-logo-retina"></div>
</section>
<pre>
<code>
.lvmama-logo {
background-image: url(../img/logo-61.png);
width: 330px;
height: 70px;
}
@media only screen and (-webkit-min-device-pixel-ratio: 1.5),
only screen and (min--moz-device-pixel-ratio: 1.5),
only screen and (min-device-pixel-ratio: 1.5) {
/* 当设备像素比不小于1.5的时候... */
.lvmama-logo-retina {
background-image: url(../img/logo-61@2x.png);
background-size: 100%;
}
}
</code>
</pre>
<h2>评论</h2>
<!-- 多说评论框 start -->
<div class="ds-thread" data-thread-key="retina" data-title="NOVA"
data-url="http://www.em2046.com/nova/docs/retina.html"></div>
<!-- 多说评论框 end -->
</div>
<script src="js/jquery-1.12.1.js"></script>
<script src="js/highlight.pack.js"></script>
<script src="js/navigation.js"></script>
</body>
</html>
| Java |
//
// AppDelegate.h
// testspinner
//
// Created by Christian Menschel on 29/09/15.
// Copyright © 2015 TAPWORK. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| Java |
<html><body>
<h4>Windows 10 x64 (19041.264)</h4><br>
<h2>_PPM_IDLE_STATES</h2>
<font face="arial"> +0x000 InterfaceVersion : UChar<br>
+0x001 IdleOverride : UChar<br>
+0x002 EstimateIdleDuration : UChar<br>
+0x003 ExitLatencyTraceEnabled : UChar<br>
+0x004 NonInterruptibleTransition : UChar<br>
+0x005 UnaccountedTransition : UChar<br>
+0x006 IdleDurationLimited : UChar<br>
+0x007 IdleCheckLimited : UChar<br>
+0x008 StrictVetoBias : UChar<br>
+0x00c ExitLatencyCountdown : Uint4B<br>
+0x010 TargetState : Uint4B<br>
+0x014 ActualState : Uint4B<br>
+0x018 OldState : Uint4B<br>
+0x01c OverrideIndex : Uint4B<br>
+0x020 ProcessorIdleCount : Uint4B<br>
+0x024 Type : Uint4B<br>
+0x028 LevelId : Uint8B<br>
+0x030 ReasonFlags : Uint2B<br>
+0x038 InitiateWakeStamp : Uint8B<br>
+0x040 PreviousStatus : Int4B<br>
+0x044 PreviousCancelReason : Uint4B<br>
+0x048 PrimaryProcessorMask : <a href="./_KAFFINITY_EX.html">_KAFFINITY_EX</a><br>
+0x0f0 SecondaryProcessorMask : <a href="./_KAFFINITY_EX.html">_KAFFINITY_EX</a><br>
+0x198 IdlePrepare : Ptr64 void <br>
+0x1a0 IdlePreExecute : Ptr64 long <br>
+0x1a8 IdleExecute : Ptr64 long <br>
+0x1b0 IdlePreselect : Ptr64 unsigned long <br>
+0x1b8 IdleTest : Ptr64 unsigned long <br>
+0x1c0 IdleAvailabilityCheck : Ptr64 unsigned long <br>
+0x1c8 IdleComplete : Ptr64 void <br>
+0x1d0 IdleCancel : Ptr64 void <br>
+0x1d8 IdleIsHalted : Ptr64 unsigned char <br>
+0x1e0 IdleInitiateWake : Ptr64 unsigned char <br>
+0x1e8 PrepareInfo : <a href="./_PROCESSOR_IDLE_PREPARE_INFO.html">_PROCESSOR_IDLE_PREPARE_INFO</a><br>
+0x240 DeepIdleSnapshot : <a href="./_KAFFINITY_EX.html">_KAFFINITY_EX</a><br>
+0x2e8 Tracing : Ptr64 <a href="./_PERFINFO_PPM_STATE_SELECTION.html">_PERFINFO_PPM_STATE_SELECTION</a><br>
+0x2f0 CoordinatedTracing : Ptr64 <a href="./_PERFINFO_PPM_STATE_SELECTION.html">_PERFINFO_PPM_STATE_SELECTION</a><br>
+0x2f8 ProcessorMenu : <a href="./_PPM_SELECTION_MENU.html">_PPM_SELECTION_MENU</a><br>
+0x308 CoordinatedMenu : <a href="./_PPM_SELECTION_MENU.html">_PPM_SELECTION_MENU</a><br>
+0x318 CoordinatedSelection : <a href="./_PPM_COORDINATED_SELECTION.html">_PPM_COORDINATED_SELECTION</a><br>
+0x330 State : [1] <a href="./_PPM_IDLE_STATE.html">_PPM_IDLE_STATE</a><br>
</font></body></html> | Java |
# coding=utf-8
from setuptools import setup
from Cython.Build import cythonize
setup(
name="cyfib",
ext_modules=cythonize('cyfib.pyx', compiler_directives={'embedsignature': True}),
)
| Java |
package org.eggermont.hm.cluster;
import cern.colt.matrix.DoubleFactory1D;
import cern.colt.matrix.DoubleMatrix1D;
import cern.colt.matrix.DoubleMatrix2D;
public class ClusterFactory {
private final DoubleMatrix2D x;
private final DoubleMatrix1D blocks;
private final DoubleMatrix1D vMin;
private final DoubleMatrix1D vMax;
private final int ndof;
public ClusterFactory(int d, int nidx, int ndof) {
this.ndof = ndof;
this.blocks = DoubleFactory1D.dense.make(d * nidx);
this.x = blocks.like2D(nidx, d);
this.vMin = DoubleFactory1D.dense.make(d);
this.vMax = DoubleFactory1D.dense.make(d);
}
}
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using SharpDeflate;
using vtortola.WebSockets;
using vtortola.WebSockets.Rfc6455;
namespace RohBot
{
public sealed class WebSocketServer<TClient> : IDisposable
where TClient : WebSocketClient, new()
{
private class ClientHandle : IDisposable
{
private Action _dispose;
public ClientHandle(Action dispose)
{
if (dispose == null)
throw new ArgumentNullException(nameof(dispose));
_dispose = dispose;
}
public void Dispose()
{
_dispose?.Invoke();
_dispose = null;
}
}
private CancellationTokenSource _cts;
private WebSocketListener _listener;
private object _clientsSync;
private List<TClient> _clients;
private IReadOnlyList<TClient> _clientsCache;
public WebSocketServer(IPEndPoint endpoint)
{
var options = new WebSocketListenerOptions
{
PingTimeout = TimeSpan.FromSeconds(30)
};
_cts = new CancellationTokenSource();
_listener = new WebSocketListener(endpoint, options);
_clientsSync = new object();
_clients = new List<TClient>();
var rfc6455 = new WebSocketFactoryRfc6455(_listener);
rfc6455.MessageExtensions.RegisterExtension(new WebSocketSharpDeflateExtension());
_listener.Standards.RegisterStandard(rfc6455);
_listener.Start();
ListenAsync();
}
public void Dispose()
{
_cts.Cancel();
_listener.Dispose();
}
public IReadOnlyList<TClient> Clients
{
get
{
lock (_clientsSync)
{
return _clientsCache ?? (_clientsCache = _clients.ToList().AsReadOnly());
}
}
}
private async void ListenAsync()
{
while (_listener.IsStarted)
{
WebSocket websocket;
try
{
websocket = await _listener.AcceptWebSocketAsync(_cts.Token).ConfigureAwait(false);
if (websocket == null)
continue;
}
catch (Exception e)
{
Program.Logger.Error("Failed to accept websocket connection", e);
continue;
}
var client = new TClient();
var clientHandle = new ClientHandle(() =>
{
lock (_clientsSync)
{
_clients.Remove(client);
_clientsCache = null;
}
});
client.Open(clientHandle, websocket, _cts.Token);
lock (_clientsSync)
{
_clients.Add(client);
_clientsCache = null;
}
}
}
}
}
| Java |
/* eslint-disable no-undef */
const cukeBtnSubmit = '//button[@data-cuke="save-item"]';
const cukeInpSize = '//input[@data-cuke="size"]';
const cukeInpTitle = '//input[@data-cuke="title"]';
const cukeInpContent = '//textarea[@data-cuke="content"]';
const cukeSize = '//x-cuke[@id="size"]';
const cukeTitle = '//x-cuke[@id="title"]';
const cukeContent = '//x-cuke[@id="content"]';
/*
const cukeHrefEdit = '//a[@data-cuke="edit-ite"]';
const cukeHrefDelete = '//a[@data-cuke="delete-item"]';
*/
const cukeInvalidSize = '//span[@class="help-block error-block"]';
let size = '';
let title = '';
let content = '';
module.exports = function () {
// Scenario: Create a new widget
// ------------------------------------------------------------------------
this.Given(/^I have opened the 'add widgets' page : "([^"]*)"$/, function (_url) {
browser.setViewportSize({ width: 1024, height: 480 });
browser.timeouts('implicit', 60000);
browser.timeouts('page load', 60000);
browser.url(_url);
server.call('_widgets.wipe');
});
this.When(/^I create a "([^"]*)" millimetre "([^"]*)" item with text "([^"]*)",$/,
function (_size, _title, _content) {
size = _size;
title = _title;
content = _content;
browser.waitForEnabled( cukeBtnSubmit );
browser.setValue(cukeInpTitle, title);
browser.setValue(cukeInpSize, size);
browser.setValue(cukeInpContent, content);
browser.click(cukeBtnSubmit);
});
this.Then(/^I see a new record with the same title, size and contents\.$/, function () {
expect(browser.getText(cukeSize)).toEqual(size + ' millimetres.');
expect(browser.getText(cukeTitle)).toEqual(title);
expect(browser.getText(cukeContent)).toEqual(content);
});
// =======================================================================
// Scenario: Verify field validation
// ------------------------------------------------------------------------
this.Given(/^I have opened the widgets list page : "([^"]*)"$/, function (_url) {
browser.setViewportSize({ width: 1024, height: 480 });
browser.timeoutsImplicitWait(1000);
browser.url(_url);
});
/*
let link = '';
this.Given(/^I choose to edit the "([^"]*)" item,$/, function (_widget) {
link = '//a[@data-cuke="' + _widget + '"]';
browser.waitForExist( link );
browser.click(link);
browser.waitForEnabled( cukeHrefEdit );
browser.click(cukeHrefEdit);
});
*/
this.When(/^I set 'Size' to "([^"]*)"$/, function (_size) {
browser.setValue(cukeInpSize, _size);
});
this.Then(/^I see the size validation hint "([^"]*)"\.$/, function (_message) {
expect(browser.getText(cukeInvalidSize)).toEqual(_message);
});
// =======================================================================
// Scenario: Fail to delete widget
// ------------------------------------------------------------------------
let widget = '';
this.Given(/^I choose to view the "([^"]*)" item,$/, function (_widget) {
widget = _widget;
const cukeHrefWidget = `//a[@data-cuke="${widget}"]`;
browser.waitForEnabled( cukeHrefWidget );
browser.click( cukeHrefWidget );
});
/*
let href = null;
this.When(/^I decide to delete the item,$/, function () {
href = cukeHrefDelete;
browser.waitForExist( href );
});
this.Then(/^I see it is disabled\.$/, function () {
expect(browser.isEnabled( href )).toBe(true);
});
*/
// =======================================================================
// Scenario: Unable to update widget
// ------------------------------------------------------------------------
/*
this.When(/^I attempt to edit the item,$/, function () {
href = cukeHrefEdit;
browser.waitForExist( href );
});
*/
// =======================================================================
// Scenario: Prohibited from add and from update
// ------------------------------------------------------------------------
this.Given(/^I have opened the widgets editor page : "([^"]*)"$/, function (_url) {
browser.setViewportSize({ width: 1024, height: 480 });
browser.timeouts('implicit', 60000);
browser.timeouts('page load', 60000);
browser.url(_url);
});
/*
this.Then(/^I see the warning "([^"]*)"$/, function (_warning) {
expect(_warning).toEqual(browser.getText(cukeWarning));
});
*/
// =======================================================================
// Scenario: Hide widget
// ------------------------------------------------------------------------
/*
this.Given(/^I have elected to "([^"]*)" the "([^"]*)" item\.$/, function (_cmd, _widget) {
link = '//a[@data-cuke="' + _widget + '"]';
browser.waitForEnabled( link );
browser.click(link);
let cukeHrefCmd = '//a[@data-cuke="' + _cmd + '-widget"]';
browser.waitForEnabled( cukeHrefCmd );
browser.click( cukeHrefCmd );
});
*/
/*
this.Then(/^I no longer see that widget record\.$/, function () {
browser.waitForEnabled( cukeWidgetsList );
let item = browser.elements(link);
expect(item.value.length).toEqual(0);
});
*/
};
| Java |
<!DOCTYPE html>
<?php
include("initial-header.php");
include("config.php");
include('swift/lib/swift_required.php');
$error = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT email_id, Password, salt FROM login WHERE email_id='$myusername' ";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
// If email ID exists in the login table
if($count == 1) {
$salt = $row["salt"];
$password_hash = $row["Password"];
$myhash = hash('sha512', $mypassword . $salt);
//If the password is correct
if($password_hash == $myhash){
$_SESSION['login_user'] = $myusername;
$random = rand(100000,999999);
$sql2 = "UPDATE login SET otp=". $random ." WHERE User_id='". $myusername. "'";
$querry = mysqli_query($db,$sql2);
$to = $myusername;
$subject = 'Dual Authentication for Gamify';
$body = 'Greetings. Your one time password is: '.$random;
$headers = 'From: Gamify <gamify101@gmail.com>' . "\r\n" .
'Reply-To: Gamify <gamify101@gmail.com>' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$result = mail($to, $subject, $body, $headers);
header('Location: duo_auth.php');
}
else{
$error = "Your Login Name or Password is invalid";
}
}else {
$error = "Your Login Name or Password is invalid";
}
}
?>
<div class="page-content container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-wrapper">
<div class="box">
<div class="content-wrap">
<h6>Sign In</h6>
<form action = "" method = "post">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input class="form-control" type="text" name = "username" placeholder="User Name" autofocus required>
</div>
<br>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-key"></i></span>
<input class="form-control" type="password" name = "password" placeholder="Password" required>
</div>
<div class="already">
<span><?php if (isset($error)) echo $error ?></span>
</div>
<div class="action">
<input type = "submit" class="btn btn-primary btn-block signup" value = " Login "/>
</div>
</form>
<br><br>
<p><h4><a href="fg_pwd.php">Forgot Password?</a></h4></p><br>
<h4><p>Don't have an account?<a href="email_id_verification.php"> Register now!</a></p></h4>
</div>
</div>
</div>
</div>
<?php include('initial-footer.php'); ?>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="js/custom.js"></script>
</body>
</html> | Java |
package net.spy.digg.parsers;
import java.io.IOException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import net.spy.digg.Story;
/**
* Parse a stories response.
*/
public class StoriesParser extends TimePagedItemParser<Story> {
@Override
protected String getRootElementName() {
return "stories";
}
@Override
protected void handleDocument(Document doc)
throws SAXException, IOException {
parseCommonFields(doc);
final NodeList nl=doc.getElementsByTagName("story");
for(int i=0; i<nl.getLength(); i++) {
addItem(new StoryImpl(nl.item(i)));
}
}
}
| Java |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OptimalizationFun")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OptimalizationFun")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8497300e-6541-4c7b-a1cd-592c2f61773d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Java |
require "../test_helper"
require "rorschart/data/rorschart_data"
module Rorschart
class TestPivotSeries < Minitest::Unit::TestCase
def test_pivot
# Given
data = [
{"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "A", "count"=> 1},
{"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "B", "count"=> 2},
{"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "C", "count"=> 3},
{"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "D", "count"=> 4},
{"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "A", "count"=> 5},
{"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "B", "count"=> 6},
{"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "D", "count"=> 7}
]
# When
pivot_series = PivotSeries.new(data)
# assert
expected_cols = [
{:type=>"date", :label=>"collector_tstamp"},
{:type=>"number", :label=>"A"},
{:type=>"number", :label=>"B"},
{:type=>"number", :label=>"C"},
{:type=>"number", :label=>"D"}
]
expected_rows = [
[Date.parse("2013-11-02"), 1, 2, 3, 4],
[Date.parse("2013-12-01"), 5, 6, nil, 7]
]
assert_equal expected_cols, pivot_series.cols
assert_equal expected_rows, pivot_series.rows
end
def test_pivot_with_sum_column
# Given
data = [
{"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "A", "count"=> 1},
{"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "B", "count"=> 2},
{"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "C", "count"=> 3},
{"collector_tstamp"=> Date.parse("2013-11-02"), "series" => "D", "count"=> 4},
{"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "A", "count"=> nil},
{"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "B", "count"=> 6},
{"collector_tstamp"=> Date.parse("2013-12-01"), "series" => "D", "count"=> 7}
]
# When
pivot_series = PivotSeries.new(data, add_total_column: true)
# assert
expected_cols = [
{:type=>"date", :label=>"collector_tstamp"},
{:type=>"number", :label=>"Total"},
{:type=>"number", :label=>"A"},
{:type=>"number", :label=>"B"},
{:type=>"number", :label=>"C"},
{:type=>"number", :label=>"D"}
]
expected_rows = [
[Date.parse("2013-11-02"), 10, 1, 2, 3, 4],
[Date.parse("2013-12-01"), 13, nil, 6, nil, 7]
]
assert_equal expected_cols, pivot_series.cols
assert_equal expected_rows, pivot_series.rows
end
def test_pivot_with_empty_data
# Given
data = []
# When
pivot_series = PivotSeries.new(data)
# assert
expected_cols = []
expected_rows = []
assert_equal expected_cols, pivot_series.cols
assert_equal expected_rows, pivot_series.rows
end
end
end | Java |
/*
* The MIT License (MIT): http://opensource.org/licenses/mit-license.php
*
* Copyright (c) 2013-2014, Chris Behrens
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#define __FIL_BUILDING_LOCKING__
#include "core/filament.h"
#include "locking/fil_lock.h"
typedef struct _pyfil_lock {
PyObject_HEAD
int locked;
FilWaiterList waiters;
} PyFilLock;
typedef struct _pyfil_rlock {
PyFilLock lock; /* must remain first. */
uint64_t owner;
uint64_t count;
} PyFilRLock;
static PyFilLock *_lock_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
PyFilLock *self = (PyFilLock *)type->tp_alloc(type, 0);
if (self != NULL)
{
fil_waiterlist_init(self->waiters);
}
return self;
}
static int _lock_init(PyFilLock *self, PyObject *args, PyObject *kwargs)
{
return 0;
}
static void _lock_dealloc(PyFilLock *self)
{
assert(fil_waiterlist_empty(self->waiters));
PyObject_Del(self);
}
static int __lock_acquire(PyFilLock *lock, int blocking, struct timespec *ts)
{
if (!lock->locked && fil_waiterlist_empty(lock->waiters))
{
lock->locked = 1;
return 0;
}
if (!blocking)
{
return 1;
}
int err = fil_waiterlist_wait(lock->waiters, ts, NULL);
if (err < 0)
{
return err;
}
assert(lock->locked == 1);
return 0;
}
static int __lock_release(PyFilLock *lock)
{
if (!lock->locked)
{
PyErr_SetString(PyExc_RuntimeError, "release without acquire");
return -1;
}
if (fil_waiterlist_empty(lock->waiters))
{
lock->locked = 0;
return 0;
}
/* leave 'locked' set because a different thread is just
* going to grab it anyway. This prevents some races without
* additional work to resolve them.
*/
fil_waiterlist_signal_first(lock->waiters);
return 0;
}
static int __rlock_acquire(PyFilRLock *lock, int blocking, struct timespec *ts)
{
uint64_t owner;
owner = fil_get_ident();
if (!lock->lock.locked && fil_waiterlist_empty(lock->lock.waiters))
{
lock->lock.locked = 1;
lock->owner = owner;
lock->count = 1;
return 0;
}
if (owner == lock->owner)
{
lock->count++;
return 0;
}
if (!blocking)
{
return 1;
}
int err = fil_waiterlist_wait(lock->lock.waiters, ts, NULL);
if (err)
{
return err;
}
assert(lock->lock.locked == 1);
lock->owner = owner;
lock->count = 1;
return 0;
}
static int __rlock_release(PyFilRLock *lock)
{
if (!lock->lock.locked || (fil_get_ident() != lock->owner))
{
PyErr_SetString(PyExc_RuntimeError, "cannot release un-acquired lock");
return -1;
}
if (--lock->count > 0)
{
return 0;
}
lock->owner = 0;
if (fil_waiterlist_empty(lock->lock.waiters))
{
lock->lock.locked = 0;
return 0;
}
/* leave 'locked' set because a different thread is just
* going to grab it anyway. This prevents some races without
* additional work to resolve them.
*/
fil_waiterlist_signal_first(lock->lock.waiters);
return 0;
}
PyDoc_STRVAR(_lock_acquire_doc, "Acquire the lock.");
static PyObject *_lock_acquire(PyFilLock *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {"blocking", "timeout", NULL};
PyObject *blockingobj = NULL;
PyObject *timeout = NULL;
struct timespec tsbuf;
struct timespec *ts;
int blocking;
int err;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O!O",
keywords,
&PyBool_Type,
&blockingobj, &timeout))
{
return NULL;
}
if (fil_timespec_from_pyobj_interval(timeout, &tsbuf, &ts) < 0)
{
return NULL;
}
blocking = (blockingobj == NULL || blockingobj == Py_True);
err = __lock_acquire(self, blocking, ts);
if (err < 0 && err != -ETIMEDOUT)
{
return NULL;
}
if (err == 0)
{
Py_INCREF(Py_True);
return Py_True;
}
Py_INCREF(Py_False);
return Py_False;
}
PyDoc_STRVAR(_lock_locked_doc, "Is the lock locked?");
static PyObject *_lock_locked(PyFilLock *self)
{
PyObject *res = (self->locked || !fil_waiterlist_empty(self->waiters)) ? Py_True : Py_False;
Py_INCREF(res);
return res;
}
PyDoc_STRVAR(_lock_release_doc, "Release the lock.");
static PyObject *_lock_release(PyFilLock *self)
{
if (__lock_release(self) < 0)
{
return NULL;
}
Py_RETURN_NONE;
}
static PyObject *_lock_enter(PyFilLock *self)
{
int err = __lock_acquire(self, 1, NULL);
if (err)
{
if (!PyErr_Occurred())
{
PyErr_Format(PyExc_RuntimeError, "unexpected failure in Lock.__enter__: %d", err);
}
return NULL;
}
Py_INCREF(self);
return (PyObject *)self;
}
static PyObject *_lock_exit(PyFilLock *self, PyObject *args)
{
return _lock_release(self);
}
PyDoc_STRVAR(_rlock_acquire_doc, "Acquire the lock.");
static PyObject *_rlock_acquire(PyFilRLock *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[] = {"blocking", "timeout", NULL};
PyObject *blockingobj = NULL;
PyObject *timeout = NULL;
struct timespec tsbuf;
struct timespec *ts;
int blocking;
int err;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O!O",
keywords,
&PyBool_Type,
&blockingobj, &timeout))
{
return NULL;
}
if (fil_timespec_from_pyobj_interval(timeout, &tsbuf, &ts) < 0)
{
return NULL;
}
blocking = (blockingobj == NULL || blockingobj == Py_True);
err = __rlock_acquire(self, blocking, ts);
if (err < 0 && err != -ETIMEDOUT)
{
return NULL;
}
if (err == 0)
{
Py_INCREF(Py_True);
return Py_True;
}
Py_INCREF(Py_False);
return Py_False;
}
PyDoc_STRVAR(_rlock_locked_doc, "Is the lock locked (by someone else)?");
static PyObject *_rlock_locked(PyFilRLock *self)
{
uint64_t owner = fil_get_ident();
PyObject *res = ((self->lock.locked && self->owner != owner) ||
!fil_waiterlist_empty(self->lock.waiters)) ? Py_True : Py_False;
Py_INCREF(res);
return res;
}
PyDoc_STRVAR(_rlock_release_doc, "Release the lock.");
static PyObject *_rlock_release(PyFilRLock *self)
{
if (__rlock_release(self) < 0)
{
return NULL;
}
Py_RETURN_NONE;
}
static PyObject *_rlock_enter(PyFilRLock *self)
{
int err = __rlock_acquire(self, 1, NULL);
if (err)
{
if (!PyErr_Occurred())
{
PyErr_Format(PyExc_RuntimeError, "unexpected failure in RLock.__enter__: %d", err);
}
return NULL;
}
Py_INCREF(self);
return (PyObject *)self;
}
static PyObject *_rlock_exit(PyFilRLock *self, PyObject *args)
{
return _rlock_release(self);
}
static PyMethodDef _lock_methods[] = {
{ "acquire", (PyCFunction)_lock_acquire, METH_VARARGS|METH_KEYWORDS, _lock_acquire_doc },
{ "release", (PyCFunction)_lock_release, METH_NOARGS, _lock_release_doc },
{ "locked", (PyCFunction)_lock_locked, METH_NOARGS, _lock_locked_doc },
{ "__enter__", (PyCFunction)_lock_enter, METH_NOARGS, NULL },
{ "__exit__", (PyCFunction)_lock_exit, METH_VARARGS, NULL },
{ NULL, NULL }
};
static PyMethodDef _rlock_methods[] = {
{ "acquire", (PyCFunction)_rlock_acquire, METH_VARARGS|METH_KEYWORDS, _rlock_acquire_doc },
{ "release", (PyCFunction)_rlock_release, METH_NOARGS, _rlock_release_doc },
{ "locked", (PyCFunction)_rlock_locked, METH_NOARGS, _rlock_locked_doc },
{ "__enter__", (PyCFunction)_rlock_enter, METH_NOARGS, NULL },
{ "__exit__", (PyCFunction)_rlock_exit, METH_VARARGS, NULL },
{ NULL, NULL }
};
static PyTypeObject _lock_type = {
PyVarObject_HEAD_INIT(0, 0)
"_filament.locking.Lock", /* tp_name */
sizeof(PyFilLock), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)_lock_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
FIL_DEFAULT_TPFLAGS, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
_lock_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)_lock_init, /* tp_init */
PyType_GenericAlloc, /* tp_alloc */
(newfunc)_lock_new, /* tp_new */
PyObject_Del, /* tp_free */
0, /* tp_is_gc */
0, /* tp_bases */
0, /* tp_mro */
0, /* tp_cache */
0, /* tp_subclasses */
0, /* tp_weaklist */
0, /* tp_del */
0, /* tp_version_tag */
};
/* Re-entrant lock. We can use the same calls here */
static PyTypeObject _rlock_type = {
PyVarObject_HEAD_INIT(0, 0)
"_filament.locking.RLock", /* tp_name */
sizeof(PyFilRLock), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)_lock_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
FIL_DEFAULT_TPFLAGS, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
_rlock_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)_lock_init, /* tp_init */
PyType_GenericAlloc, /* tp_alloc */
(newfunc)_lock_new, /* tp_new */
PyObject_Del, /* tp_free */
0, /* tp_is_gc */
0, /* tp_bases */
0, /* tp_mro */
0, /* tp_cache */
0, /* tp_subclasses */
0, /* tp_weaklist */
0, /* tp_del */
0, /* tp_version_tag */
};
/****************/
PyFilLock *fil_lock_alloc(void)
{
return _lock_new(&_lock_type, NULL, NULL);
}
PyFilRLock *fil_rlock_alloc(void)
{
return (PyFilRLock *)_lock_new(&_rlock_type, NULL, NULL);
}
int fil_lock_acquire(PyFilLock *lock, int blocking, struct timespec *ts)
{
return __lock_acquire(lock, blocking, ts);
}
int fil_rlock_acquire(PyFilRLock *rlock, int blocking, struct timespec *ts)
{
return __rlock_acquire(rlock, blocking, ts);
}
int fil_lock_release(PyFilLock *lock)
{
return __lock_release(lock);
}
int fil_rlock_release(PyFilRLock *rlock)
{
return __rlock_release(rlock);
}
int fil_lock_type_init(PyObject *module)
{
PyFilCore_Import();
if (PyType_Ready(&_lock_type) < 0)
{
return -1;
}
if (PyType_Ready(&_rlock_type) < 0)
{
return -1;
}
Py_INCREF((PyObject *)&_lock_type);
if (PyModule_AddObject(module, "Lock", (PyObject *)&_lock_type) != 0)
{
Py_DECREF((PyObject *)&_lock_type);
return -1;
}
Py_INCREF((PyObject *)&_rlock_type);
if (PyModule_AddObject(module, "RLock", (PyObject *)&_rlock_type) != 0)
{
Py_DECREF((PyObject *)&_rlock_type);
return -1;
}
return 0;
}
| Java |
package de.thomas.dreja.ec.musicquiz.gui.dialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import de.thomas.dreja.ec.musicquiz.R;
import de.thomas.dreja.ec.musicquiz.ctrl.PlaylistResolver.SortOrder;
public class SortOrderSelectionDialog extends DialogFragment {
private SortOrderSelectionListener listener;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String[] items = new String[SortOrder.values().length];
for(int i=0; i<items.length; i++) {
items[i] = SortOrder.values()[i].getName(getResources());
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.sort_by)
.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listener.onSortOrderSelected(SortOrder.values()[which]);
}
});
return builder.create();
}
public interface SortOrderSelectionListener {
public void onSortOrderSelected(SortOrder order);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
listener = (SortOrderSelectionListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement SortOrderSelectionListener");
}
}
}
| Java |
/*
* Panel
*/
.panel {
margin: 5rem auto;
max-width: 64rem;
background: $white;
border: 0.4rem solid $black;
box-shadow: 5px 5px 0px $black;
&:first-child {
margin-top: 0;
}
&:last-child {
margin-bottom: 0;
}
}
.panel-header {
padding: 2rem;
background: $secondary;
border-bottom: 0.4rem solid $black;
}
.panel-title {
color: $white;
}
.panel-content {
padding: 3rem 2rem;
} | Java |
angular-multi-select-tree
=============================
A native Angular multi select tree. No JQuery.

#### Demo Page:
[Demo] (http://htmlpreview.github.io/?https://github.com/kjvelarde/angular-multiselectsearchtree/blob/master/demo/index.html)
#### Features:
Very Easy to Use:
- Plug and Play component
- Tree List
- Databind
- Filter/NoFilter by search textbox
- Checkbox
- Select one only or Multiselect
- NO JQuery
#### Design details:
Custom element using Angular Directive and Templating
#### Callbacks:
This is your onchange :)
##### Usage:
Get this awesome component to your project by:
```sh
bower install kjvelarde-angular-multiselectsearchtree --save
# bower install long name ehhfsaduasdu lol . just kidding use the first one :)
```
Make sure to load the scripts in your html.
```html
<link rel="stylesheet" href="../dist/kjvelarde-multiselect-searchtree.min.css">
<script type="text/javascript" src="../dist/angular-multi-select-tree.min.js"></script>
<script type="text/javascript" src="../dist/angular-multi-select-tree.tpl.js"></script>
```
And Inject the module as dependency to your angular app.
```
angular.module('[YOURAPPNAMEHERE!]', ['multiselect-searchtree', '....']);
```
###### Html Structure:
```html
<multiselect-searchtree
multi-select="true"
data-input-model="data"
data-output-model="selectedItem2"
data-callback="CustomCallback(item, selectedItems)"
data-select-only-leafs="true">
</multiselect-searchtree>
```
That's what all you have to do.
##### License
MIT, see [LICENSE.md](./LICENSE.md).
| Java |
//
// DNTag.h
// DNTagView
//
// Created by dawnnnnn on 16/9/1.
// Copyright © 2016年 dawnnnnn. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface DNTag : NSObject
@property (nonatomic, copy) NSString *text;
@property (nonatomic, copy) NSAttributedString *attributedText;
@property (nonatomic, strong) UIColor *textColor;
@property (nonatomic, strong) UIColor *bgColor;
@property (nonatomic, strong) UIColor *highlightedBgColor;
@property (nonatomic, strong) UIColor *borderColor;
@property (nonatomic, strong) UIImage *bgImg;
@property (nonatomic, strong) UIFont *font;
@property (nonatomic, assign) CGFloat cornerRadius;
@property (nonatomic, assign) CGFloat borderWidth;
///like padding in css
@property (nonatomic, assign) UIEdgeInsets padding;
///if no font is specified, system font with fontSize is used
@property (nonatomic, assign) CGFloat fontSize;
///default:YES
@property (nonatomic, assign) BOOL enable;
- (nonnull instancetype)initWithText: (nonnull NSString *)text;
+ (nonnull instancetype)tagWithText: (nonnull NSString *)text;
@end
NS_ASSUME_NONNULL_END
| Java |
---
seo:
title: Scheduling Parameters
description: Scheduling an email with SMTP
keywords: SMTP, send email, scheduling
title: Scheduling Parameters
weight: 10
layout: page
navigation:
show: true
---
With scheduling, you can send large volumes of email in queued batches or target individual recipients by specifying a custom UNIX timestamp parameter.
Using the parameters defined below, you can queue batches of emails targeting individual recipients.
{% info %}
**Emails can be scheduled up to 72 hours in advance.** However, this scheduling constraint does not apply to campaigns sent via [Marketing Campaigns]({{root_url}}/User_Guide/Marketing_Campaigns/index.html).
{% endinfo%}
This parameter allows SendGrid to begin processing a customer’s email requests before sending. SendGrid queues the messages and releases them when the timestamp indicates. This technique allows for a more efficient way to distribute large email requests and can **improve overall mail delivery time** performance. This functionality:
* Improves efficiency of processing and distributing large volumes of email.
* Reduces email pre-processing time.
* Enables you to time email arrival to increase open rates.
* Is available for free to all SendGrid customers.
{% info %}
Cancel Scheduled sends by including a batch ID with your send. For more information, check out [Cancel Scheduled Sends]({{root_url}}/API_Reference/Web_API_v3/cancel_schedule_send.html)!
{% endinfo %}
{% warning %}
Using both `send_at` and `send_each_at` is not valid. Setting both causes your request to be dropped.
{% endwarning %}
{% anchor h2 %}
Send At
{% endanchor %}
To schedule a send request for a large batch of emails, use the `send_at` parameter which will send all emails at approximately the same time. `send_at` is a [UNIX timestamp](https://en.wikipedia.org/wiki/Unix_time).
<h4>Example of send_at email header</h4>
{% codeblock lang:json %}
{
"send_at": 1409348513
}
{% endcodeblock %}
{% anchor h2 %}
Send Each At
{% endanchor %}
To schedule a send request for individual recipients; use `send_each_at` to send emails to each recipient at the specified time. `send_each_at` is a sequence of UNIX timestamps, provided as an array. There must be one timestamp per email you wish to send.
<h4>Example of send_each_at email header</h4>
{% codeblock lang:json %}
{
"to": [
"<ben@example.com>",
"john@example.com",
"mikeexampexample@example.com",
"<example@example.com>",
"example@example.com",
"example@example.com"
],
"send_each_at": [
1409348513,
1409348514,
1409348515
]
}
{% endcodeblock %}
To allow for the cancellation of a scheduled send, you must include a `batch_id` with your send. To generate a valid `batch_id`, use the [batch id generation endpoint]({{root_url}}/API_Reference/Web_API_v3/cancel_scheduled_send.html#Cancel-Scheduled-Sends). A `batch_id` is valid for 10 days (864,000 seconds) after generation.
<h4>Example of including a batch_id</h4>
{% codeblock lang:json %}
{
"to": [
"<ben@example.com>",
"john@example.com",
"mikeexampexample@example.com",
"<example@example.com>",
"example@example.com",
"example@example.com"
],
"send_at": 1409348513,
"batch_id": "MWQxZmIyODYtNjE1Ni0xMWU1LWI3ZTUtMDgwMDI3OGJkMmY2LWEzMmViMjYxMw"
}
{% endcodeblock %}
{% anchor h2 %}
Additional Resources
{% endanchor h2 %}
- [SMTP Service Crash Course](https://sendgrid.com/blog/smtp-service-crash-course/)
- [Getting Started with the SMTP API]({{root_url}}/API_Reference/SMTP_API/getting_started_smtp.html)
- [Integrating with SMTP]({{root_url}}/API_Reference/SMTP_API/integrating_with_the_smtp_api.html)
- [Building an SMTP Email]({{root_url}}/API_Reference/SMTP_API/building_an_smtp_email.html)
| Java |
#pragma once
#include "FtInclude.h"
#include <string>
namespace ft {
class Library
{
public:
Library();
~Library();
FT_Library library = nullptr;
Library(const Library&) = delete;
Library(Library&&) = delete;
Library& operator = (const Library&) = delete;
Library& operator=(Library&&) = delete;
std::string getVersionString() const;
private:
static int initialized;
};
}
| Java |
package com.github.fhtw.swp.tutorium.guice;
import com.github.fhtw.swp.tutorium.composite.Leaf;
import com.github.fhtw.swp.tutorium.composite.LeafTypeProvider;
import com.github.fhtw.swp.tutorium.reflection.AnnotatedTypeFinder;
import org.reflections.Configuration;
import javax.inject.Inject;
import java.util.Set;
public class LeafTypeProviderImpl implements LeafTypeProvider {
private final Configuration configuration;
@Inject
public LeafTypeProviderImpl(Configuration configuration) {
this.configuration = configuration;
}
@Override
public Set<Class<?>> getLeafTypes() {
return new AnnotatedTypeFinder(configuration, Leaf.class).getAnnotatedTypes();
}
}
| Java |
#!/bin/sh
tokenizer()
{
STRNG="${1}"
DELIM="${2}"
while :
do
NEW="${STRNG%${DELIM}}"
while case "$NEW" in
*${DELIM}*);;
*)break;;
esac
do NEW="${NEW%${DELIM}*}"
done
TOKEN="${NEW%${DELIM}*}"
STRNG="${STRNG#${TOKEN}${DELIM}}"
printf "%s\n" "$TOKEN"
case "$STRNG" in
*${DELIM}*) ;;
*) [ -n "$d" ] && break || d="1" ;;
esac
done
}
which(){
for i in $(tokenizer $PATH ":" )
do
#echo "${i}" # test directory walk
[ -d "${i}/${1}" ] && break
[ -x "${i}/${1}" ] && echo "${i}/${1}" && exit
done
}
which $@
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.