answer
stringlengths 15
1.25M
|
|---|
'use strict';
const util = require('util');
const colors = require('colors/safe');
Object.entries({
info: colors.blue,
warn: colors.yellow,
error: colors.red
}).map(([method, color]) => {
const _ = global.console[method];
global.console[method] = (...args) => {
if (args.length) {
let msg = args.shift();
if ('string' == typeof msg) {
msg = color(msg);
}
args.unshift(msg);
}
_(...args);
};
});
|
<!DOCTYPE html>
<html lang="english">
<head>
<link href='//fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,400italic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="../theme/stylesheet/style.min.css">
<link rel="stylesheet" type="text/css" href="../theme/pygments/github.min.css">
<link rel="stylesheet" type="text/css" href="../theme/font-awesome/css/font-awesome.min.css">
<link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon">
<link rel="icon" href="/images/favicon.ico" type="image/x-icon">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="HandheldFriendly" content="True" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="robots" content="" />
<meta name="author" content="Rishabh Chakrabarti" />
<meta name="description" content="Learning about Bluemix and its features." />
<meta name="keywords" content="Bluemix, IBM">
<meta property="og:site_name" content="Bassdeveloper's Blog"/>
<meta property="og:title" content="In the Blues"/>
<meta property="og:description" content="Learning about Bluemix and its features."/>
<meta property="og:locale" content="en_US"/>
<meta property="og:url" content="../drafts/ibm-bluemix.html"/>
<meta property="og:type" content="article"/>
<meta property="article:published_time" content="2017-01-17 11:28:00+01:00"/>
<meta property="article:modified_time" content="2017-01-17 11:40:00+01:00"/>
<meta property="article:author" content="../author/rishabh-chakrabarti.html">
<meta property="article:section" content="Learning"/>
<meta property="article:tag" content="Bluemix"/>
<meta property="article:tag" content="IBM"/>
<meta property="og:image" content="/images/RC.jpg">
<title>Bassdeveloper's Blog – In the Blues</title>
</head>
<body>
<aside>
<div>
<a href="..">
<img src="/images/RC.jpg" alt="Rishabh Chakrabarti" title="Rishabh Chakrabarti">
</a>
<h1><a href="..">Rishabh Chakrabarti</a></h1>
<p>Learning about Data</p>
<nav>
<ul class="list">
<li><a href="https://bassdeveloper.github.io/category/learning.html" target="_blank">Learning</a></li>
<li><a href="https://bassdeveloper.github.io/category/data-science.html" target="_blank">Data-Science</a></li>
<li><a href="https://bassdeveloper.github.io/category/business.html" target="_blank">Business</a></li>
</ul>
</nav>
<ul class="social">
<li><a class="sc-facebook" href="https:
<li><a class="sc-github" href="https://github.com/bassdeveloper/" target="_blank"><i class="fa fa-github"></i></a></li>
<li><a class="sc-google-plus" href="https://plus.google.com/<API key>" target="_blank"><i class="fa fa-google-plus"></i></a></li>
</ul>
</div>
</aside>
<main>
<article class="single">
<header>
<h1 id="ibm-bluemix">In the Blues</h1>
<p>
Posted on Tue 17 January 2017 in <a href="../category/learning.html">Learning</a>
</p>
</header>
<div>
<h1>IBM® Bluemix®</h1>
<p>A cloud computing platform that <strong>combines platform as a service (PaaS) with infrastructure as a service (IaaS)</strong>.</p>
<ul>
<li>
<p>Polyglot (using several languages) programming approaches.</p>
</li>
<li>
<p>No investment in Hardware Models, all is handled.</p>
</li>
</ul>
<p>You can take an idea from</p>
<p><em>inception, to development sandbox, to a globally distributed production environment</em> </p>
<ul>
<li>
<p>IBM® Bluemix® also provides flexible deployment.</p>
</li>
<li>
<p>Provision IBM® Bluemix® resources on-premises, in dedicated private cloud environments, or in the public cloud, and manage the resources from all three types of environments in a single dashboard.</p>
</li>
<li>
<p>All IBM cloud resources that are deployed in public and dedicated environments are hosted from your choice of IBM® Cloud Data Center locations around the world.</p>
</li>
<li>
<p>IBM Cloud Data Centers provide regional redundancy, a global network backbone connecting all data centers and points of presence, and stringent security controls and reporting.</p>
</li>
</ul>
<p>IBM enables you to:</p>
<ul>
<li>
<p>Secure Data Centers</p>
</li>
<li>
<p>Test and adopt to a broad range of services.</p>
</li>
<li>
<p>Connect to all of your legacy systems and apps from a single, scalable, cloud platform through private network and API capabilities.</p>
</li>
</ul>
<p>App Dashboard has everything.</p>
<h2>Boiler Plates :</h2>
<p>Bluemix provides various boilerplates and runtimes:</p>
<blockquote>
<p>A boilerplate is a template for an application and its associated runtime environment and predefined services for a specific domain.</p>
<p>A runtime is the set of resources that is used to run an app, provided as containers for different types of apps.</p>
</blockquote>
<h2>Methods :</h2>
<p>Bluemix provides various ways for you to run your apps, for example :</p>
<ul>
<li>Cloud Foundry and IBM® Bluemix® Container Service. (run Docker containers on cloud)</li>
</ul>
<blockquote>
<p>Docker containers wrap a piece of software in a complete filesystem that contains everything needed to run: code, runtime, system tools, system libraries – anything that can be installed on a server. This guarantees that the software will always run the same, regardless of its environment.</p>
</blockquote>
<ul>
<li>You can use IBM® Bluemix® OpenWhisk for distributed, event-driven computing.</li>
</ul>
<p>OpenWhisk runs application logic in response to events or direct invocations from web or mobile apps over HTTP.</p>
<ul>
<li>Use Mobile Services</li>
</ul>
<p>Services</p>
<p>The Services dashboard provides access to the Bluemix services :</p>
<ul>
<li>
<p>Fast + Cheap Apps from IBM DevOps services and the Bluemix Garage Method.</p>
</li>
<li>
<p>Blockchain is a peer-to-peer distributed ledger technology for a new generation of transactional applications that establishes trust, accountability, and transparency while streamlining business processes.</p>
</li>
<li>
<p>Watson gives your apps the power of cognitive computing with a full suite of speech, vision, and data APIs.</p>
</li>
<li>
<p>IBM enables you to do more with rich, integrated cloud databases and Data & Analytics services.</p>
</li>
<li>
<p>The IBM Internet of Things service lets your apps communicate with, and consume data that is collected by, your connected devices, sensors, and gateways. Our recipes make it easy to get devices connected to our Internet of Things cloud. Your apps can then use our real-time and REST APIs to communicate with your devices and consume the data you've set them up to collect.</p>
</li>
</ul>
<p>IBM offers a mobile backend infrastructure where you can build multiplatform, native, or hybrid apps while also being able to monitor and test them. You can also enhance your app with analytics, security, user insight, and continuous delivery.
Bluemix also provides experimental services that you can try out. To learn about service types and availability, see Bluemix services.</p>
<p>Infrastructure</p>
<p>The Infrastructure dashboard provides various services to fit your cloud infrastructure needs.</p>
</div>
<div class="tag-cloud">
<p>
<a href="../tag/bluemix.html">Bluemix</a>
<a href="../tag/ibm.html">IBM</a>
</p>
</div>
</article>
<footer>
<p>© Rishabh Chakrabarti </p>
<p> Powered by <a href="http:
</p> </footer>
</main>
<script type="application/ld+json">
{
"@context" : "http://schema.org",
"@type" : "Blog",
"name": " Bassdeveloper's Blog ",
"url" : "..",
"image": "/images/RC.jpg",
"description": "Rishabh Chakrabarti's Notes and Highlights"
}
</script>
</body>
</html>
|
require.ensure([], function(require) {
require("./73.async.js");
require("./147.async.js");
require("./294.async.js");
require("./588.async.js");
});
module.exports = 589;
|
<html>
<head>
<meta charset="utf-8">
<title>Resources - git init</title>
<link
href='https://fonts.googleapis.com/css?family=Open+Sans'
rel='stylesheet'
type='text/css'
>
<link rel="stylesheet" href="octicons/octicons.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="header">
<h1 class="header-title">git init</h1>
<ul class="header-menu">
<li class="header-menu_item">
<a href="index.html">Tutorial</a>
</li>
<li class="header-menu_item">
<a href="cheatsheet.html">Cheatsheet</a>
</li>
<li class="header-menu_item <API key>">
Resources
</li>
<li class="header-menu_item">
<a
class="header-github mega-octicon octicon-mark-github"
href="https://github.com/pel-daniel/git-init"
></a>
</li>
</ul>
</div>
<div id="resources">
<h2 class="area-title">Resources</h2>
<h3>Intermediate</h3>
<ul>
<li>
<a href="http://chris.beams.io/posts/git-commit/">
How to write a Git Commit Message
</a>
</li>
<li>
<a href="http://gitimmersion.com/lab_01.html">
Git immersion:
</a>
A more in depth (and long) tutorial explaining: basics, branching, remote
repositories, git internals, aliases, and more.
</li>
<li>
<a href="http://justinhileman.info/article/git-pretty/git-pretty.png">
Justin Hileman's chart to solve a git mess
</a>
</li>
<li>
<a href="https://services.github.com/kit/downloads/<API key>.pdf">
Github's Git Cheat Sheet
</a>
</li>
</ul>
<h3>Advanced</h3>
<ul>
<li>
<a href="http://learngitbranching.js.org/">
Learn Git Branching:
</a>
Visual explanation of Git Commit Trees. Includes a really good explanation
of the differences between merge & rebase.
</li>
<li>
<a href="https:
Scott Chacon explaining how Git works internally
</a>
</li>
</ul>
</div>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/<API key>="
crossorigin="anonymous">
</script>
<script
src="https://code.jquery.com/color/jquery.color-2.1.2.min.js"
type="text/javascript">
</script>
</body>
</html>
|
<rtl code>
var m = function (){
function T(){
this.a = [];
}
var r = new T();
var a = RTL$.makeArray(3, 0);
var dynamicInt = [];
var dynamicString = [];
var dynamicChar = [];
var dynamicByte = [];
var dynamicRecord = [];
var <API key> = [];
var i = 0;
var s = '';
var byte = 0;
function <API key>(){
var static$ = RTL$.makeArray(3, 0);
var dynamic = [];
Array.prototype.splice.apply(dynamic, [0, Number.MAX_VALUE].concat(static$));
}
function returnOuterArray(){
return a.slice();
}
function passArrayBeRef(a/*VAR ARRAY * OF INTEGER*/){
var static$ = RTL$.makeArray(3, 0);
a[0] = 1;
a[0] = a[1];
Array.prototype.splice.apply(a, [0, Number.MAX_VALUE].concat(static$));
Array.prototype.splice.apply(a, [0, Number.MAX_VALUE].concat(dynamicInt));
}
function <API key>(a/*VAR ARRAY * OF T*/){
var result = [];
RTL$.copy(result, a, {array: {record: {a: {array: null}}}});
}
function <API key>(a/*VAR ARRAY *, 3 OF INTEGER*/){
var result = [];
RTL$.copy(result, a, {array: {array: null}});
}
function arrayOfRecords(){
var $scope1 = $scope + ".arrayOfRecords";
function T(){
}
var a = [];
a.push(new T());
}
function arrayOfArrays(){
var aa = [];
function f(){
var a = [];
return a;
}
aa.push(f());
}
function <API key>(){
function f(){
var a = [];
return a;
}
return f();
}
function <API key>(){
var a = [];
return a;
}
function <API key>(){
var a = RTL$.makeArray(3, 0);
return a;
}
function <API key>(a/*ARRAY OF INTEGER*/){
return a.slice();
}
function <API key>(a/*VAR ARRAY OF INTEGER*/){
return a.slice();
}
function <API key>(a/*VAR ARRAY * OF INTEGER*/){
return a.slice();
}
function arrayOfMaps(){
var aa = [];
function f(){
var a = {};
return a;
}
aa.push(f());
}
dynamicInt.push(3);
dynamicInt.push(i);
dynamicInt.push(byte);
dynamicString.push("abc");
dynamicString.push("\"");
dynamicString.push(s);
dynamicChar.push(34);
dynamicByte.push(byte);
dynamicByte.push(i & 0xFF);
dynamicRecord.push(RTL$.clone(r, {record: {a: {array: null}}}, T));
<API key>.push(a.slice());
RTL$.assert(dynamicInt.indexOf(i) != -1);
RTL$.assert(dynamicChar.indexOf(34) != -1);
dynamicInt.splice(i, 1);
dynamicInt.splice(0, Number.MAX_VALUE);
passArrayBeRef(dynamicInt);
<API key>(dynamicRecord);
<API key>(<API key>);
}();
|
# npmup [![NPM version][npm-image]][npm-url]
> Cli tool to overview dependencies in package.json
This is scope reduction result of my `update-my-deps` project. At the end I found out, that I wrote small part of [`david`](https://github.com/alanshaw/david) functionality. Oops.

## Installation
bash
$ npm i npmup -g
## Usage
bash
$ npmup
Dependency Required Stable Latest
! express ~3.4.4 3.4.8 3.5.0
lodash ~2.4.1 2.4.1 2.4.1
mkdirp ~0.3.5 0.3.5 0.3.5
! npmlog 0.0.2 0.0.2 0.0.6
recluster ~0.3.4 0.3.6 0.3.6
[npm-url]: https://npmjs.org/package/npmup
[npm-image]: https://badge.fury.io/js/npmup.png
MIT (c) Vsevolod Strukchinsky
|
var expect = require('chai').expect;
var assert = require('chai').assert;
var sinon = require('sinon');
var Config = require('../lib/config');
describe('config', function() {
describe('#constructor', function() {
it('creates a new object with the config defaults', function() {
sinon.spy(Config.prototype, 'set');
var options = {};
var config = new Config(options);
assert(Config.prototype.set.calledWith(options));
Config.prototype.set.restore();
});
it('call .set with any passed options', function() {
var config = new Config();
expect(config.source).to.equal('.');
expect(config.destination).to.equal('_site');
});
});
describe('#set', function() {
it('merges the passed options with the config defaults', function() {
var config = new Config();
config.set({
source: './foo',
destination: './bar',
fizz: 'buzz'
});
expect(config.source).to.equal('./foo');
expect(config.destination).to.equal('./bar');
// a default
expect(config.env).to.equal('production');
// a new value
expect(config.fizz).to.equal('buzz');
});
it('always includes certain default, even if overridden', function() {
var config = new Config();
config.set({
excludeFiles: ['foo'],
watchExcludes: ['bar']
});
expect(config.excludeFiles).to.deep.equal([
'foo',
'.*',
'_*',
'_**',
'package.json',
'bower_components',
'node_modules'
]);
expect(config.watchExcludes).to.deep.equal([
'bar',
'node_modules',
config.destination
]);
});
});
});
|
def burrows_wheeler(text):
"""Calculates the burrows wheeler transform of <text>.
returns the burrows wheeler string and the suffix array indices
The text is assumed to not contain the character $"""
text += "$"
all_permutations = []
for i in range(len(text)):
all_permutations.append((text[i:] + text[:i],i))
all_permutations.sort()
bw_l = [] # burrows wheeler as list
sa_i = [] # suffix array indices
for w,j in all_permutations:
bw_l.append(w[-1])
sa_i.append(j)
return "".join(bw_l), sa_i
|
local M = {}
function M:init()
print("test contract transfer caller")
local <API key> = import_contract '<API key>'
local res = <API key>:start()
pprint("transfer demo start response is ", res)
end
function M:start()
end
return M
|
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Microsoft.Deployment.Common.ActionModel;
using Microsoft.Deployment.Common.Actions;
using Microsoft.Deployment.Common.Enums;
using Microsoft.Deployment.Common.ErrorCode;
using Microsoft.Deployment.Common.Helpers;
using Microsoft.Deployment.Common.Model;
using Newtonsoft.Json.Linq;
namespace Microsoft.Deployment.Actions.AzureCustom.HCL
{
[Export(typeof(IAction))]
public class <API key> : BaseAction
{
public override async Task<ActionResponse> ExecuteActionAsync(ActionRequest request)
{
var azureToken = request.DataStore.GetJson("AzureToken")["access_token"].ToString();
var subscription = request.DataStore.GetJson("<API key>")["SubscriptionId"].ToString();
var resourceGroup = request.DataStore.GetValue("<API key>");
var location = request.DataStore.GetJson("SelectedLocation")["Name"].ToString();
var deploymentName = request.DataStore.GetValue("DeploymentName");
var mlWorkspaceName = request.DataStore.GetValue("mlWorkspaceName");
//var storageAccountName = request.DataStore.GetValue("storageAccountName");
var <API key> = request.DataStore.GetValue("<API key>");
var storageAccountName = request.DataStore.GetValue("storageAccountName");
var storageAccountType = request.DataStore.GetValue("storageAccountType");
var encryptionEnabled = request.DataStore.GetValue("<API key>");
var <API key> = request.DataStore.GetValue("<API key>");
foreach (var item in ListDeployedItems)
{
if (item.ToString() == deploymentName)
return new ActionResponse(ActionStatus.Success);
}
<API key> creds = new <API key>(subscription, azureToken);
<API key> client = new <API key>(creds);
var param = new <API key>();
param.AddStringParam("mlWorkspaceName", mlWorkspaceName);
param.AddStringParam("storageAccountName", storageAccountName);
param.AddStringParam("subscription", subscription);
param.AddStringParam("resourceGroup", resourceGroup);
param.AddStringParam("encryptionEnabled", encryptionEnabled);
param.AddStringParam("location", location);
param.AddStringParam("storageAccountType", storageAccountType);
var armTemplate = JsonUtility.<API key>(System.IO.File.ReadAllText(Path.Combine(request.Info.App.AppFilePath, "Service/AzureML/MLWorkspace.json")));
var armParamTemplate = JsonUtility.<API key>(param.GetDynamicObject());
armTemplate.Remove("parameters");
armTemplate.Add("parameters", armParamTemplate["parameters"]);
var deployment = new Azure.Management.Resources.Models.Deployment()
{
Properties = new <API key>()
{
Template = armTemplate.ToString(),
Parameters = JsonUtility.GetEmptyJObject().ToString()
}
};
var validate = await client.Deployments.ValidateAsync(resourceGroup, deploymentName, deployment, new CancellationToken());
if (!validate.IsValid)
{
return new ActionResponse(ActionStatus.Failure, JsonUtility.<API key>(validate), null,
DefaultErrorCodes.DefaultErrorCode, $"Azure:{validate.Error.Message} Details:{validate.Error.Details}");
}
var deploymentItem = await client.Deployments.CreateOrUpdateAsync(resourceGroup, deploymentName, deployment, new CancellationToken());
request.DataStore.AddToDataStore(<API key>, mlWorkspaceName);
request.DataStore.AddToDataStore(<API key>, storageAccountName);
ListDeployedItems.Add(deploymentName);
return new ActionResponse(ActionStatus.Success, deploymentItem);
}
}
}
|
package com.example.dao;
import com.example.model.Publisher;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface PublisherMapper {
@Select("SELECT *, PHONE as phoneNumber from PUBLISHERS") //SQL
List<Publisher> findAll();
// CREATE TABLE IF NOT EXISTS PUBLISHERS (
// ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY
// ,NAME VARCHAR(255) NOT NULL CONSTRAINT PUBLISHERS_NAME_UC UNIQUE
// ,PHONE VARCHAR(30));
// public class Publisher {
// private Integer id ;
// private String name;
// private String phoneNumber;
}
|
<?php while (have_posts()) : the_post(); ?>
<article <?php post_class(); ?>>
<div class="entry-content <API key>">
<header class="menu-med-prep text-center">
<ul class="list-inline">
<?php $loop = new WP_Query( array( 'post_type' => 'aps', 'order' => 'ASC', 'category_name'=> 'link'));?>
<?php while ( $loop->have_posts() ) : $loop->the_post();
$slug = get_post_field( 'post_name', get_post() );
?>
<li class="boton-aps"><a href="<?php the_permalink();?>"><span class="aps-title-menu text-uppercase texto<?php echo $slug; ?>"><?php the_title(); ?></span></a></li>
<?php endwhile; wp_reset_query(); ?>
</ul>
</header>
<?php $slug = get_post_field( 'post_name', get_post() ); ?>
<div class="row">
<div class="col-sm-12">
<div class="title-big-aps">
<div class="row">
<div class="col-sm-6">
<div class="aps-text-big">
<h2><span class="titulo-plan-big titulo-aps-big">Plan </span><span class="text-uppercase titulo-plan titulo-aps fondo<?php echo $slug; ?>"><?php the_title(); ?></span></h2>
</div>
</div>
<div class="col-sm-6">
<img src="<?php <API key>('full'); ?>" class="img-responsive">
</div>
</div>
</div>
<div class="wrapper-aps"><?php the_content(); ?></div>
<div class="wrapper-botones">
<?php $id_empresarial=<API key>( 'empresarial' );
$category=get_the_category();
if ($category[0]->name === 'empresarial') {
if( get_adjacent_post(true, '', true, 'category') ) {
$post_previo=get_adjacent_post(true, '', true, 'category');
if((in_category('empresarial', $post_previo))){
$post_previo_slug=get_post_field( 'post_name', $post_previo );
$post_previo_slug=str_replace("-", " ", $post_previo_slug);
echo '<div class="texto-azul pull-left boton-nav">';
previous_post_link('%link', '<span class="glyphicon <API key>"></span>'.$post_previo_slug);
echo "</div>";
}
else {
$first = new WP_Query( array( 'post_type' => 'aps', 'order' => 'DESC', 'category__in'=> $id_empresarial->term_id)); $first->the_post();
$post_previo_slug=get_post_field( 'post_name' );
$post_previo_slug=str_replace("-", " ", $post_previo_slug);
echo '<div class="texto-azul pull-left boton-nav"><a href="' . get_permalink() . '"><span class="glyphicon <API key>"></span>'.$post_previo_slug.'</a></div>';
wp_reset_query();
};
};
if( get_adjacent_post(true, '', false, 'category') ) {
$post_sig=get_adjacent_post(true, '', false, 'category');
$post_sig_slug=get_post_field( 'post_name', $post_sig );
echo '<div class="texto-azul pull-right boton-nav">';
next_post_link('%link', $post_sig_slug.'<span class="glyphicon <API key>"></span></div>');
}
else {
$last = new WP_Query( array( 'post_type' => 'aps', 'order' => 'ASC', 'category__in'=> $id_empresarial->term_id)); $last->the_post();
$post_sig_slug=get_post_field( 'post_name' );
$post_sig_slug=str_replace("-", " ", $post_sig_slug);
// $post_sig_slug=get_post_field( 'post_name', $post_sig );
echo '<div class="texto-azul pull-right boton-nav"><a href="' . get_permalink() . '"><span class="textobotonnav">'.$post_sig_slug.'</span><span class="glyphicon <API key>"></span></a></div>';
wp_reset_query();
};
}
else{?>
<div class="wrapper-botones text-center">
<a href="
<a href="#" class="boton-med-prep">Cotizar Empresa</a>
</div>
<?php }?>
</div>
</div>
</div>
</div>
</div>
</article>
<?php endwhile; ?>
|
<!DOCTYPE html>
<html lang="en-us">
{% include head.html %}
<body class="theme-base-08 layout-reverse sidebar-overlay">
<!-- Enable Google Analytics -->
{% include googleanalytics.html %}
{% include sidebar.html %}
<!-- Wrap is the content to shift when toggling the sidebar. We wrap the
content to avoid any CSS collisions with our real content.
<div class="wrap">
<div class="masthead">
<div class="container">
<h3 class="masthead-title">
<a href="{{ site.baseurl }}/" title="Home">{{ site.title }}</a>
<small>{{ site.tagline }}</small>
</h3>
</div>
</div>
<div class="container content">
{{ content }}
</div>
</div>
<label for="sidebar-checkbox" class="sidebar-toggle"></label>
<script>
(function(document) {
var toggle = document.querySelector('.sidebar-toggle');
var sidebar = document.querySelector('#sidebar');
var checkbox = document.querySelector('#sidebar-checkbox');
document.addEventListener('click', function(e) {
var target = e.target;
if(!checkbox.checked ||
sidebar.contains(target) ||
(target === checkbox || target === toggle)) return;
checkbox.checked = false;
}, false);
})(document);
</script>
</body>
</html>
|
package wikimediaparser
import (
"fmt"
"github.com/golang/glog"
"strings"
)
// Node as it is emitted by the parser
// - contains a NodeType for clear identification
// - a string val Val
// - a list of named parameters which are actually Node Lists
// -a list of anonymous parameters, a Node list again
type Node struct {
Typ nodeType
Val string
NamedParams map[string]Nodes
Params []Nodes
}
// Return the Node text content, without any decoration
func (n *Node) <API key>() string {
glog.V(7).Infof("<API key> for %+v", n)
switch n.Typ {
case NodeText, NodeInvalid:
return n.Val
case NodeLink, NodeELink:
if len(n.Params) > 0 {
return n.Params[0].<API key>()
} else {
return n.StringParamOrEmpty("link")
}
case NodeTemplate:
if len(n.Params) > 0 {
return n.Params[0].<API key>()
} else {
return ""
}
default:
return ""
}
}
func (n *Node) String() string {
switch n.Typ {
case NodeText, NodeInvalid:
return fmt.Sprintf("%q", n.Val)
}
o := fmt.Sprintf("%s: %s", n.Typ.String(), n.Val)
for ix, p := range n.Params {
o += fmt.Sprintf("\t%d: %s\n", ix, p.String())
}
for k, v := range n.NamedParams {
o += fmt.Sprintf("\t%s: %s\n", k, v.String())
}
return o
}
// StringParam returns the string value of a given named parameter
func (n *Node) StringParam(k string) string {
param, ok := n.NamedParams[k]
if !ok {
glog.V(2).Infof("Unable to extract parameter \"%s\" for node %s", k, n.String())
} else {
return param.<API key>()
}
return ""
}
func (n *Node) StringParamOrEmpty(k string) string {
glog.V(2).Infof("StringParamOrEmpty for %s", k)
v, ok := n.NamedParams[k]
if ok {
ret := v.<API key>()
return strings.Trim(ret, " \n")
}
return ""
}
func EmptyNode() Node {
return Node{Typ: NodeEmpty}
}
type nodeType int
const (
NodeInvalid = nodeType(iota)
NodeText
NodeTitle
NodeLink
NodeELink
NodeTemplate
NodePlaceholder
NodeEq
NodeUnknown
NodeEmpty
)
func (n nodeType) String() string {
switch n {
case NodeText:
return "Text"
case NodeLink:
return "Link"
case NodeELink:
return "ELink"
case NodeTemplate:
return "Template"
case NodeEq:
return " EQ "
case NodeTitle:
return " Title "
case NodePlaceholder:
return " Placeholder "
case NodeUnknown:
return "UNK"
case NodeInvalid:
return " INV "
default:
return "????"
}
}
|
# domBareMetal
Xen 4.6. bare metal domain for Odroid XU-3
Tested on Odroid XU3, for toggling GPA2.4 GPIO. Toggling is done directly by changing the register in memory.
On this link you can find XU3 expansion header: http://odroid.com/dokuwiki/doku.php?id=en:xu3_hardware_gpio
Xen devel thread on enabling emergency console: https://lists.xenproject.org/archives/html/xen-devel/2016-05/msg02524.html
Next step is enabling MMU.
|
import Vue from 'vue';
import VueForm from 'vue-form';
Vue.use(VueForm, {
validators: {
'step': function(value, stepValue) {
return stepValue === `any` || Number(value) % Number(stepValue) === 0;
},
'<API key>': function(value, exclusiveMinimum) {
return Number(value) > Number(exclusiveMinimum);
},
'<API key>': function(value, exclusiveMaximum) {
return Number(value) < Number(exclusiveMaximum);
},
'complete-range': function(range) {
return range === null || (range[0] !== null && range[1] !== null);
},
'valid-range': function(range) {
if (range === null) {
// allowed range
return true;
}
if (range[0] === null || range[1] === null) {
// let complete-range validator handle this
return true;
}
if (Number.isNaN(range[0]) || Number.isNaN(range[1])) {
// let number validator handle this
return true;
}
return range[0] <= range[1];
},
'<API key>': function(categories) {
return categories.length > 0;
},
'complete-dimensions': function(dimensions) {
return dimensions === null || (dimensions[0] !== null && dimensions[1] !== null && dimensions[2] !== null);
},
'<API key>': function(value) {
return /^[\dA-Z]/.test(value);
},
'no-mode-name': function(value) {
return !/\bmode\b/i.test(value);
},
'<API key>': function(value) {
if (/\bfine\b|\d+[\s_-]*bit/i.test(value)) {
return false;
}
return !/\bLSB\b|\bMSB\b/.test(value);
},
'entity-complete': function(value, attributeValue, vnode) {
const component = vnode.componentInstance;
if (component.hasNumber) {
return component.selectedNumber !== `` && component.selectedNumber !== null;
}
return true;
},
'<API key>': function(value, attributeValue, vnode) {
return vnode.componentInstance.hasSameUnit;
},
'<API key>': function(value) {
return /^\s*#[\da-f]{6}(?:\s*,\s*#[\da-f]{6})*\s*$/i.test(value);
},
'max-file-size': function(file, attributeValue) {
if (typeof file === `object`) {
let maxSize = Number.parseInt(attributeValue, 10);
if (attributeValue.includes(`M`)) {
maxSize *= 1000 * 1000;
}
else if (attributeValue.includes(`k`)) {
maxSize *= 1000;
}
return file.size <= maxSize;
}
return true;
},
},
});
|
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Post extends Application {
public function index()
{
$this->data['pagetitle'] = 'News title - Zerotype Website Template';
$this->data['pagebody'] = 'post';
$this->render();
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
|
layout: post
title: How To Order Bitcoin Debit Card With SpectroCoin?
description: How To Order Bitcoin Debit Card With SpectroCoin?
author: Melvin Draupnir
authorurl: /melvin-draupnir/
published: true
<p><a href="/spectrocoin/">SpectroCoin</a> now offers Bitcoin prepaid cards which could be a virtual one or a plastic one. You can.This card can be immediately funded All you need to do is click “Order card” on your <a href="http://geni.us/spectrocoin">SpectroCoin account</a>.</p>
<center><iframe width="700" height="394" src="https:
<h2>TRANSCRIPT</h2>
|
var resources = require('jest'),
util = require('util'),
models = require('../../models'),
async = require('async'),
common = require('./../common'),
calc_thresh = require('../../tools/calc_thresh.js'),
<API key> = require('./<API key>.js'),
ActionSuggestion = require('./<API key>.js'),
og_action = require('../../og/og.js').doAction;
//Authorization
var Authoriztion = function() {};
util.inherits(Authoriztion,resources.Authorization);
//Authorization.prototype.edit_object = function(req,object,callback){
// //check if user already grade this action
// var flag = false;
// models.GradeAction.find({"action_id": object.action_id}, function(err, objects){
// if (err){
// callback(err, null);
// }else{
// for (var i = 0; i < objects.length; i++){
// if(req.session.user_id == objects[i].user_id){
// flag = true;
// break;
// if (flag){
// callback({message:"user already grade this action",code:401}, null);
// }else{
// callback(null, object);
var GradeActionResource = module.exports = common.<API key>.extend({
init:function(){
this._super(models.GradeAction,'grade_action', null);
// GradeResource.super_.call(this,models.Grade);
this.allowed_methods = ["get", "put", "post"];
this.authorization = new Authoriztion();
this.authentication = new common.<API key>();
this.filtering = {action_id: {
exact:null,
in:null
}};
},
create_obj:function(req,fields,callback)
{
var self = this;
var g_grade_obj;
var new_grade = null;
var counter = 0;
var threshold;
var admin_threshold;
var action_thresh;
var action_obj;
var proxy_power = req.user.<API key> ? 1 + req.user.<API key> * 1/9 : 1;
var base = self._super;
fields.proxy_power = proxy_power;
fields.user_id = req.user._id;
async.waterfall([
function(cbk){
base.call(self, req, fields, cbk);
},
//find actions
function(grade_obj, cbk){
g_grade_obj = grade_obj;
models.Action.findById(grade_obj.action_id, cbk);
},
// 2) calculate action grade + set notifications for all users of proxy
function(action, cbk){
action_obj = action;
async.parallel([
//2.1 set notifications for all users of proxy
function(cbk1){
cbk1(null, null);
},
// 2.2 calculate action grade
function(cbk1){
//cant grade your own action
action_thresh = Number(action.<API key>) || action.<API key>
admin_threshold = action.<API key>;
<API key>(g_grade_obj.action_id, function(err, _new_grade, evaluate_counter, _threshold){
new_grade = _new_grade;
counter = evaluate_counter;
threshold = _threshold
cbk1(err, threshold);
});
},
//2.3 add user to be part of the action
function(cbk1){
if (! _.any(action.users, function(user){ return user.user_id + "" == req.user.id})){
var new_user = {user_id: req.user._id, join_date: Date.now()};
models.Action.update({_id: action._id}, {$addToSet:{users: new_user}}, function(err, num){cbk1(err, num)});
}else{
cbk1(null, null);
}
}
],function(err, args){
cbk(err, args[1]);
})
},
// 3) find suggestion object
//calculate all change suggestion all over again and check if they approved
function(threshold, cbk){
models.ActionSuggestion.find({action_id: g_grade_obj.action_id}, {"_id":1}, function(err, results)
{
cbk(err, results);
});
},
// 4) calculate suggestion grades
function(suggestions, cbk){
var real_threshold
async.forEach(suggestions, function(suggestion, itr_cbk){
<API key>.<API key>(suggestion._id, g_grade_obj.action_id, null, null, action_thresh, null, null,function(err, obj){
//check if suggestion is over the threshold
real_threshold = Number(suggestion.<API key>) || suggestion.<API key>;
if(suggestion.agrees && suggestion.agrees.length > real_threshold){
//approveSuggestion.exec()
ActionSuggestion.approveSuggestion(suggestion._id, function(err, obj1){
itr_cbk(err, obj1);
})
}else
itr_cbk(err, obj);
});}
, function(err){
cbk(err);
});
},
// 5) publish to facebook
function (cbk) {
og_action({
action: 'rank',
object_name:'action',
object_url : '/actions/' + action_obj.id,
fid : req.user.facebook_id,
access_token:req.user.access_token,
user:req.user
});
cbk();
},
// update actions done by user
function(cbk){
models.User.update({_id:user._id},{$set: {"<API key>.grade_object": true}}, function(err){
cbk(err);
});
}
],
// Final) set gamification details, return object
function(err, args){
req.gamification_type = "grade_action";
req.token_price = common.<API key>('grade_action') > -1 ? common.<API key>('grade_action') : 0;
callback(err, {new_grade: new_grade, evaluate_counter: counter, grade_id: g_grade_obj._id || 0});
})
},
update_obj: function(req, object, callback){
var g_grade;
var self = this;
var suggestions = [];
var action_thresh;
var proxy_power = req.user.<API key> ? 1 + req.user.<API key> * 1/9 : 1;
var iterator = function(suggestion, itr_cbk){
<API key>.<API key>(suggestion._id, object.action_id, null, null, action_thresh, null, null,function(err, sugg_new_grade, sugg_total_counter){
if(!err){
suggestions.push({
_id: suggestion._id,
grade: sugg_new_grade,
evaluators_counter: sugg_total_counter
})
}
itr_cbk(err, 0);
});
}
object.proxy_power = proxy_power;
self._super(req, object, function(err, grade_object){
if(err){
callback(err, null);
}else{
var new_grade, evaluate_counter;
async.waterfall([
function(cbk){
g_grade = grade_object;
<API key>(object.action_id, function(err, _new_grade, _evaluate_counter){
new_grade = _new_grade;
evaluate_counter = _evaluate_counter;
cbk(err, 0);
});
},
//get action threshold so i can update every suggestion threshold
function(obj, cbk){
models.Action.findById(object.action_id, function(err, result){
cbk(err, result)
});
},
function(action_obj,cbk){
async.parallel([
//set notifications for all users of proxy
function(cbk1){
//Todo - set notifications
// models.User.find({"proxy.user_id": req.user._id}, function(err, slaves_users){
// async.forEach(slaves_users, function(slave, itr_cbk){
// notifications.<API key>("<API key>",
// discussion_obj._id, slave._id, req.user._id,
// null, null, g_grade.evaluation_grade,
// function(err){
// itr_cbk(err);
// }, function(err){
// cbk1(err);
cbk1(null);
},
//calculate all change suggestion all over again
function(cbk1){
action_thresh = Number(action_obj.<API key>) || action_obj.<API key>;
models.ActionSuggestion.find({action_id: grade_object.action_id}, {"_id":1}, function(err, results)
{
cbk1(err, results);
});
}
],
function(err, args){
cbk(err, args[1]);
}
)
},
function(suggestions, cbk){
async.forEach(suggestions, iterator, cbk);
}
], function(err){
callback(err, {new_grade: new_grade, evaluate_counter: evaluate_counter, suggestions: suggestions,grade_id: g_grade._id || 0})
})
}
});
}
});
function <API key>(action_id, callback){
var count;
var grade_sum;
var new_grade;
var threshold;
async.waterfall([
function(cbk){
models.GradeAction.find({action_id: action_id}, {"evaluation_grade":1, "proxy_power":1}, cbk);
},
function(grades, cbk){
count = grades.length;
if(count){
//calculate grade_sum with take proxy power in consideration
grade_sum = _.reduce(grades, function(memo, grade){return memo + Number(grade.evaluation_grade * (grade.proxy_power || 1)); }, 0);
//calculate count with take proxy power in consideration
count = _.reduce(grades, function(memo, grade){return memo + Number(grade.proxy_power || 1)}, 0);
new_grade = grade_sum / count;
//calculate threshhold here
threshold = calc_thresh.calculating_thresh(count, new_grade) || 50;
models.Action.update({_id: action_id}, {$set: {grade: new_grade, evaluate_counter: count, <API key>: threshold}}, cbk);
}else{
cbk({message: "you have to grade before changing the grade" , code: 401});
}
}
],function(err, args){
callback(err, new_grade, count, threshold);
})
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace CameraModifications
{
public class LookButton : MonoBehaviour
{
public bool isHead;
public H_Scene h_scene;
public H_EditsUIControl controls;
private GameObject buttonPrefab;
public KocchiMitePlugin watchDog;
private Toggle m_toggle;
private UI_ShowCanvasGroup group;
private int currentValue = -1;
private Dictionary<LookAtRotator.TYPE, Toggle> toggles;
private bool initialShutup = true;
private void Start()
{
// Make buttons
m_toggle = GetComponent<Toggle>();
m_toggle.onValueChanged.AddListener(HandleClick);
controls.GetComponent<ToggleGroup>().RegisterToggle(m_toggle);
try
{
MakeGroup();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public int CurrentMode
{
get
{
return isHead ? watchDog.currentHeadType : watchDog.currentType;
}
}
private void Update()
{
if (CurrentMode != currentValue)
{
currentValue = CurrentMode;
toggles[(LookAtRotator.TYPE)currentValue].isOn = true;
}
initialShutup = false;
}
private void HandleClick(bool isOn)
{
try
{
if (isOn)
{
m_toggle.image.color = Color.blue;
// Show
h_scene.GC.SystemSE.Play_Click();
}
else
{
m_toggle.image.color = Color.white;
// Hide
h_scene.GC.SystemSE.Play_Cancel();
}
group.Show(isOn);
Console.WriteLine(isOn);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private void MakeGroup()
{
var container = controls.transform.FindChild("EditStep2");
Console.WriteLine("C {0}", container);
var exampleGroup = container.GetChild(0);
Console.WriteLine("E {0}", exampleGroup);
buttonPrefab = GameObject.Instantiate(container.<API key><Toggle>().gameObject) as GameObject;
buttonPrefab.SetActive(false);
group = new GameObject().AddComponent<CanvasGroup>().gameObject.AddComponent<UI_ShowCanvasGroup>();
group.gameObject.layer = LayerMask.NameToLayer("UI");
group.gameObject.AddComponent<ToggleGroup>().allowSwitchOff = false;
group.gameObject.AddComponent<RectTransform>(exampleGroup.GetComponent<RectTransform>());
group.gameObject.AddComponent<VerticalLayoutGroup>(exampleGroup.GetComponent<VerticalLayoutGroup>()).<API key> = false;
group.transform.SetParent(container, false);
//group.GetComponent<RectTransform>().GetCopyOf(exampleGroup.GetComponent<RectTransform>());
// Make buttons
toggles = new Dictionary<LookAtRotator.TYPE, Toggle>() {
{ LookAtRotator.TYPE.NO, MakeButton(watchDog.useEnglish ? "None" : "", LookAtRotator.TYPE.NO) },
{ LookAtRotator.TYPE.AWAY, MakeButton(watchDog.useEnglish ? "Away" : "", LookAtRotator.TYPE.AWAY)},
{ LookAtRotator.TYPE.FORWARD, MakeButton(watchDog.useEnglish ? "Forward" : "", LookAtRotator.TYPE.FORWARD)},
{ LookAtRotator.TYPE.TARGET, MakeButton(watchDog.useEnglish ? "Camera" : "", LookAtRotator.TYPE.TARGET)}
};
foreach (var button in toggles.Values)
{
button.transform.SetParent(group.transform, false);
}
//group.gameObject.AddComponent<Image>().color = Color.red;
}
private Toggle MakeButton(string text, LookAtRotator.TYPE type)
{
var buttonObj = Instantiate(buttonPrefab) as GameObject;
buttonObj.SetActive(true);
GameObject.DestroyImmediate(buttonObj.GetComponent<global::UI_ShowCanvasGroup>());
buttonObj.AddComponent<UI_ShowCanvasGroup>();
var buttonEl = buttonObj.GetComponent<Toggle>();
Console.WriteLine(buttonEl.group);
buttonEl.onValueChanged = new Toggle.ToggleEvent();
buttonEl.group = group.GetComponent<ToggleGroup>();
// set text
Console.WriteLine(buttonPrefab.name);
buttonEl.<API key><Text>().text = text;
//buttonEl.<API key><Text>().<API key> = true;
//buttonEl.<API key><Text>().resizeTextMinSize = 1;
buttonEl.onValueChanged.AddListener((state) =>
{
if (state)
{
if(!initialShutup)
h_scene.GC.SystemSE.Play_Click();
if (isHead)
{
watchDog.currentHeadType = (int)type;
if(!initialShutup) watchDog.oldHeadLook.IsChecked = false;
}
else
{
watchDog.currentType = (int)type;
if (!initialShutup) watchDog.oldEyeLook.IsChecked = false;
}
currentValue = (int)type;
buttonEl.image.color = Color.blue;
}
else
{
buttonEl.image.color = Color.white;
}
});
return buttonEl;
}
}
}
|
/**
* This Control enables to render a Scene with a Screen Space Ambient Occlusion (SSAO) effect.
*
* @namespace GIScene
* @class Control.SSAO
* @constructor
* @extends GIScene.Control
*/
GIScene.Control.SSAO = function() {
//inherit
GIScene.Control.call(this);
var scenePass;
var ssaoEffect;
var fxaaEffect;
var depthTarget;
var depthShader;
var depthUniforms;
var depthMaterial;
var depthCam;
var activeCam;
var updateDepthCam = function() {
// if(depthCam !== undefined && depthCam.parent !== undefined){
// this.scene.camera.remove(depthCam);
//depthCam
activeCam = (this.scene.camera instanceof THREE.CombinedCamera)?
( (this.scene.camera.inPerspectiveMode)? this.scene.camera.cameraP : this.scene.camera.cameraO )
:
this.scene.camera;
depthCam = activeCam.clone();
this.scene.camera.add(depthCam);
// depthCam = new THREE.PerspectiveCamera();
// //POSITION
// depthCam.fov = activeCam.fov;
// depthCam.aspect = activeCam.aspect;
depthCam.near = 0.1;
depthCam.far = 1000;
depthCam.<API key>();
//console.log(depthCam);
//updateSsaoUniforms();//mca
}.bind(this);
var updateSsaoUniforms = function() {
ssaoEffect.uniforms[ 'tDepth' ].value = depthTarget;
ssaoEffect.uniforms[ 'size' ].value.x = this.scene.canvas.width;
ssaoEffect.uniforms[ 'size' ].value.y = this.scene.canvas.height;
ssaoEffect.uniforms[ 'cameraNear' ].value = depthCam.near;
ssaoEffect.uniforms[ 'cameraFar' ].value = depthCam.far;
}.bind(this);
var onBeforeRender = function() {
// activeCam = (this.scene.camera instanceof THREE.CombinedCamera)?
// ( (this.scene.camera.inPerspectiveMode)? this.scene.camera.cameraP : this.scene.camera.cameraO )
// this.scene.camera;
// activeCam = this.scene.camera.cameraP.clone();
this.scene.root.overrideMaterial = depthMaterial;//new THREE.MeshDepthMaterial({blending: THREE.NoBlending});
// activeCam.near = 0.1;
// activeCam.far = 1500;
// activeCam.<API key>();
this.scene.renderer.clearTarget(depthTarget,true, true, false); //color, depth, stencil
this.scene.renderer.render(this.scene.root, depthCam, depthTarget);
// activeCam.near = this.scene.config.near;
// activeCam.far = this.scene.config.far;
// activeCam.<API key>();
this.scene.root.overrideMaterial = null;
// this.scene.root.overrideMaterial = null;
}.bind(this);
var onChangedProjection = function(event) {
console.log("chPrj2",activeCam);
updateDepthCam();
};
var onResize = function() {
updateDepthCam();
depthTarget = new THREE.WebGLRenderTarget( this.scene.canvas.width, this.scene.canvas.height, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat } );
updateSsaoUniforms();
fxaaEffect.uniforms[ 'resolution' ].value.set( 1 / this.scene.canvas.width, 1 / this.scene.canvas.height );
}.bind(this);
this.activate_ = function() {
if(!this.isActive){
scenePass = new THREE.RenderPass( this.scene.root, this.scene.camera );
ssaoEffect = new THREE.ShaderPass( THREE.SSAOShader );
depthTarget = new THREE.WebGLRenderTarget( this.scene.canvas.width, this.scene.canvas.height, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat } );
depthShader = THREE.ShaderLib[ "depthRGBA" ];
depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
depthMaterial.blending = THREE.NoBlending;
this.scene.addEventListener('beforeRender', onBeforeRender);
// function(){
// this.scene.root.overrideMaterial = depthMaterial;//new THREE.MeshDepthMaterial({blending: THREE.NoBlending});
// this.scene.camera.cameraP.near = 0.1;
// this.scene.camera.cameraP.far = 1500;
// this.scene.camera.cameraP.<API key>();
// this.scene.renderer.clearTarget(depthTarget,true, true, true);
// this.scene.renderer.render(this.scene.root, this.scene.camera, depthTarget);
// this.scene.camera.cameraP.near = this.scene.config.near;
// this.scene.camera.cameraP.far = this.scene.config.far;
// this.scene.camera.cameraP.<API key>();
// this.scene.root.overrideMaterial = null;
// }.bind(this)
ssaoEffect.uniforms[ 'tDepth' ].value = depthTarget;
ssaoEffect.uniforms[ 'size' ].value.x = this.scene.canvas.width;
ssaoEffect.uniforms[ 'size' ].value.y = this.scene.canvas.height;
ssaoEffect.uniforms[ 'cameraNear' ].value = this.scene.camera.near;
ssaoEffect.uniforms[ 'cameraFar' ].value = this.scene.camera.far;
ssaoEffect.uniforms[ 'onlyAO' ].value = 1;
ssaoEffect.renderToScreen = true;
this.scene.effectComposer.addPass(scenePass);
this.scene.effectComposer.addPass(ssaoEffect);
}
//call super class method
GIScene.Control.prototype.activate.call(this);
};
this.activate = function() {
if(!this.isActive){
//depth map
depthTarget = new THREE.WebGLRenderTarget( this.scene.canvas.width, this.scene.canvas.height, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat } );
depthShader = THREE.ShaderLib[ "depthRGBA" ];
depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
depthMaterial.blending = THREE.NoBlending;
//depthCam
updateDepthCam();
//define passes
scenePass = new THREE.RenderPass( this.scene.root, this.scene.camera );
ssaoEffect = new THREE.ShaderPass( THREE.SSAOShader );
fxaaEffect = new THREE.ShaderPass( THREE.FXAAShader );
updateSsaoUniforms();
ssaoEffect.renderToScreen = true;
fxaaEffect.uniforms[ 'resolution' ].value.set( 1 / this.scene.canvas.width, 1 / this.scene.canvas.height );
fxaaEffect.renderToScreen = false;
//add beforeRender Event
this.scene.addEventListener('beforeRender2', onBeforeRender);
//be sure, there are no other passes active
//add passes
this.scene.effectComposer.passes = [scenePass, fxaaEffect, ssaoEffect];
// this.scene.effectComposer.addPass(scenePass);
// this.scene.effectComposer.addPass(ssaoEffect);
//add other events
window.addEventListener('resize', onResize, false);
this.scene.camera.addEventListener('changedProjection', onChangedProjection);
//call super class method
GIScene.Control.prototype.activate.call(this);
}
};
this.deactivate = function() {
if(this.isActive){
//remove passes
this.scene.effectComposer.passes = [];
//remove depthCam
this.scene.camera.remove(depthCam);
//remove Events
this.scene.removeEventListener('beforeRender2', onBeforeRender);
window.removeEventListener('resize', onResize, false);
this.scene.camera.removeEventListener('changedProjection', onChangedProjection);
//call super class method
GIScene.Control.prototype.deactivate.call(this);
}
};
};
GIScene.Control.SSAO.prototype = Object.create(GIScene.Control.prototype);
|
div.CodeMirror-wrapping {
float:left;
width:275px;
height:303px;
border-width:2px;
border-style:solid;
background:#fff;
}
#canvas {
width:470px;
height:303px;
}
|
package com.cnpc.framework.utils;
import com.cnpc.framework.base.pojo.GenerateSetting;
import freemarker.template.Configuration;
import freemarker.template.<API key>;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.<API key>;
import org.springframework.core.io.support.<API key>;
import java.io.*;
public class FreeMarkerUtil {
/**
*
*
* @param templateName
*
* @return
* @throws IOException
*/
public static String getTemplatePath(String templateName) throws IOException {
Resource res = FreeMarkerUtil.getResource(templateName);
return res.getFile().getPath();
}
/**
*
*
* @param templateName
*
* @return Resource
*/
public static Resource getResource(String templateName) {
<API key> resolver = new <API key>();
Resource res = resolver.getResource("/template/" + templateName);
return res;
}
/**
*
*
* @param templateName
*
* @return Template
* @throws IOException
*/
public static Template getTemplate(String templateName) throws IOException {
Configuration cfg = new Configuration();
Template temp = null;
File tmpRootFile = getResource(templateName).getFile().getParentFile();
if (tmpRootFile == null) {
throw new RuntimeException("");
}
try {
cfg.setDefaultEncoding("utf-8");
cfg.setOutputEncoding("utf-8");
cfg.<API key>(tmpRootFile);
/* cfg.<API key>(getResourceURL()); */
cfg.setObjectWrapper(new <API key>());
temp = cfg.getTemplate(templateName);
} catch (IOException e) {
e.printStackTrace();
}
return temp;
}
/**
* freemark
*
* @param templateName
*
* @param filePath
*
* @param setting
*
*/
public static void generateFile(String templateName, String filePath, GenerateSetting setting)
throws TemplateException, IOException {
Writer writer = null;
Template template = getTemplate(templateName);
// Windows/Linux
// String dir = filePath.substring(0, filePath.lastIndexOf("\\"));
String dir = filePath.substring(0, filePath.lastIndexOf("/"));
File fdir = new File(dir);
if (!fdir.exists()) {
if (!fdir.mkdirs()) {
System.out.println("" + fdir.getAbsolutePath() + "");
return;
}
}
File file = new File(filePath);
if(file.exists())
file.delete();
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
template.setEncoding("utf-8");
template.process(setting, writer);
writer.flush();
writer.close();
}
}
|
<?php
/* @SRVDVServer/Registration/checkEmail.html.twig */
class <API key> extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
$this->parent = $this->loadTemplate("FOSUserBundle::layout.html.twig", "@SRVDVServer/Registration/checkEmail.html.twig", 1);
$this->blocks = array(
'fos_user_content' => array($this, '<API key>'),
);
}
protected function doGetParent(array $context)
{
return "FOSUserBundle::layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 6
public function <API key>($context, array $blocks = array())
{
// line 7
echo " <p>";
echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\<API key>')->trans("registration.check_email", array("%email%" => $this->getAttribute((isset($context["user"]) ? $context["user"] : null), "email", array())), "FOSUserBundle"), "html", null, true);
echo "</p>
";
}
public function getTemplateName()
{
return "@SRVDVServer/Registration/checkEmail.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 31 => 7, 28 => 6, 11 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("", "@SRVDVServer/Registration/checkEmail.html.twig", "C:\\wamp64\\www\\serveurDeVoeuxOmar\\src\\SRVDV\\ServerBundle\\Resources\\views\\Registration\\checkEmail.html.twig");
}
}
|
import * as b from "bobril";
import { <API key> } from "../../../../common/routing";
import { Anchor } from "../../../../common/Anchor";
import { Example } from "../../../../common/Example";
import { Col, Form, margin, Row } from "../../../../../index";
import { Code } from "../../../../common/Code";
import { Lead } from "../../../../common/Lead";
export const formControlsRoute: <API key> = {
url: "form-controls",
name: "form-controls",
label: "Form controls",
handler: () => <FormsDoc />,
subs: [
{
url: "example",
name: "<API key>",
label: "Example",
subs: [],
},
{
url: "sizing",
name: "<API key>",
label: "Sizing",
subs: [],
},
{
url: "readonly",
name: "<API key>",
label: "Readonly",
subs: [],
},
{
url: "readonly-plain-text",
name: "<API key>",
label: "Readonly plain text",
subs: [],
},
{
url: "file-input",
name: "<API key>",
label: "File input",
subs: [],
},
{
url: "color",
name: "form-controls-color",
label: "Color",
subs: [],
},
{
url: "datalist",
name: "<API key>",
label: "Datalist",
subs: [],
},
],
};
export function FormsDoc(): b.IBobrilNode {
return (
<>
<Anchor name="form-controls">
<h1>Form controls</h1>
</Anchor>
<Lead>
Give textual form controls like <code>{`<Form.Input>`}</code>s, <code>{`<Form.Select>`}</code>s, and{" "}
<code>{`<Form.Textarea>`}</code>s an upgrade with custom styles, sizing, focus states, and more.
</Lead>
<Anchor name="<API key>">
<h2>Form controls</h2>
</Anchor>
<Example>
<Form>
<div style={margin("b", 3)}>
<Form.Label for="<API key>">Email address</Form.Label>
<Form.Input type="email" id="<API key>" placeholder="name@example.com" />
</div>
<div style={margin("b", 3)}>
<Form.Label for="<API key>">Example textarea</Form.Label>
<Form.Textarea id="<API key>" rows="3" />
</div>
</Form>
</Example>
<Code language="tsx">{` <Form>
<div style={margin("b", 3)}>
<Form.Label for="<API key>">Email address</Form.Label>
<Form.Input type="email" id="<API key>" placeholder="name@example.com" />
</div>
<div style={margin("b", 3)}>
<Form.Label for="<API key>">Example textarea</Form.Label>
<Form.Textarea id="<API key>" rows="3" />
</div>
</Form>`}</Code>
<Anchor name="<API key>">
<h3>Sizing</h3>
</Anchor>
<p>
Set <code>size</code> prop.
</p>
<Example>
<Form.Input type="text" size="lg" placeholder="lg" />
<Form.Input type="text" placeholder="Default input" />
<Form.Input type="text" size="sm" placeholder="sm" />
</Example>
<Code language="tsx">{`<Form.Input type="text" size="lg" placeholder="lg" />
<Form.Input type="text" placeholder="Default input" />
<Form.Input type="text" size="sm" placeholder="sm" />`}</Code>
<Anchor name="<API key>">
<h3>Readonly</h3>
</Anchor>
<p>
Add the <code>readonly</code> boolean prop on an input to prevent modification of the input’s value. Read-only inputs appear
lighter (just like disabled inputs), but retain the standard cursor.
</p>
<Example>
<Form.Input type="text" placeholder="Readonly input here..." readonly />
</Example>
<Code language="tsx">{`<Form.Input type="text" placeholder="Readonly input here..." readonly />`}</Code>
<Anchor name="<API key>">
<h3>Readonly plain text</h3>
</Anchor>
<p>
If you want to have <code>readonly</code> elements in your form styled as plain text, use the <code>plain-text</code> prop
to remove the default form field styling and preserve the correct margin and padding.
</p>
<Example>
<Form>
<Row style={margin("b", 3)}>
<Form.Label col sm={2} for="staticEmail">
Email
</Form.Label>
<Col sm={10}>
<Form.Input type="text" readonly plain-text id="staticEmail" value="email@example.com" />
</Col>
</Row>
<Row style={margin("b", 3)}>
<Form.Label col sm={2} for="inputPassword">
Password
</Form.Label>
<Col sm={10}>
<Form.Input type="password" id="inputPassword" />
</Col>
</Row>
</Form>
</Example>
<Code language="tsx">{`<Form>
<Row style={margin("b", 3)}>
<Form.Label col sm={2} for="staticEmail">
Email
</Form.Label>
<Col sm={10}>
<Form.Input type="text" readonly plain-text id="staticEmail" value="email@example.com" />
</Col>
</Row>
<Row style={margin("b", 3)}>
<Form.Label col sm={2} for="inputPassword">
Password
</Form.Label>
<Col sm={10}>
<Form.Input type="password" id="inputPassword" />
</Col>
</Row>
</Form>`}</Code>
<Anchor name="<API key>">
<h3>File input</h3>
</Anchor>
<Example>
<div style={margin("b", 3)}>
<Form.Label for="formFile">Default file input example</Form.Label>
<Form.Input type="file" id="formFile" />
</div>
<div style={margin("b", 3)}>
<Form.Label for="formFileMultiple">Multiple files input example</Form.Label>
<Form.Input type="file" id="formFileMultiple" multiple />
</div>
<div style={margin("b", 3)}>
<Form.Label for="formFileDisabled">Disabled file input example</Form.Label>
<Form.Input type="file" id="formFileDisabled" disabled />
</div>
<div style={margin("b", 3)}>
<Form.Label for="formFileSm">Small file input example</Form.Label>
<Form.Input size="sm" id="formFileSm" type="file" />
</div>
<div>
<Form.Label for="formFileLg">Large file input example</Form.Label>
<Form.Input size="lg" id="formFileLg" type="file" />
</div>
</Example>
<Code language="tsx">{`<div style={margin("b", 3)}>
<Form.Label for="formFile">Default file input example</Form.Label>
<Form.Input type="file" id="formFile" />
</div>
<div style={margin("b", 3)}>
<Form.Label for="formFileMultiple">Multiple files input example</Form.Label>
<Form.Input type="file" id="formFileMultiple" multiple />
</div>
<div style={margin("b", 3)}>
<Form.Label for="formFileDisabled">Disabled file input example</Form.Label>
<Form.Input type="file" id="formFileDisabled" disabled />
</div>
<div style={margin("b", 3)}>
<Form.Label for="formFileSm">
Small file input example
</Form.Label>
<Form.Input size="sm" id="formFileSm" type="file" />
</div>
<div>
<Form.Label for="formFileLg">Large file input example</Form.Label>
<Form.Input size="lg" id="formFileLg" type="file" />
</div>`}</Code>
<Anchor name="form-controls-color">
<h3>Color</h3>
</Anchor>
<Example>
<Form.Label for="exampleColorInput">Color picker</Form.Label>
<Form.Input type="color" id="exampleColorInput" value="#563d7c" title="Choose your color" />
</Example>
<Code language="tsx">{`<Form.Label for="exampleColorInput">Color picker</Form.Label>
<Form.Input type="color" id="exampleColorInput" value="#563d7c" title="Choose your color" />`}</Code>
<Anchor name="<API key>">
<h3>Datalist</h3>
</Anchor>
<p>
Datalists allow you to create a group of <code>{`<Form.Option>`}</code>s that can be accessed (and autocompleted) from
within an <code>{`<Form.Input>`}</code>. These are similar to <code>{`<Form.Select>`}</code>s, but come with more menu
styling limitations and differences. While most browsers and operating systems include some support for{" "}
<code>{`<Form.Datalist>`}</code>s, their styling is inconsistent at best.
</p>
<Example>
<Form.Label for="exampleDataList">Datalist example</Form.Label>
<Form.Input type="datalist" list="datalistOptions" id="exampleDataList" placeholder="Type to search..." />
<Form.Datalist id="datalistOptions">
<Form.Option value="San Francisco" />
<Form.Option value="New York" />
<Form.Option value="Seattle" />
<Form.Option value="Los Angeles" />
<Form.Option value="Chicago" />
</Form.Datalist>
</Example>
<Code language="tsx">{`<Form.Label for="exampleDataList">Datalist example</Form.Label>
<Form.Input type="datalist" list="datalistOptions" id="exampleDataList" placeholder="Type to search..." />
<Form.Datalist id="datalistOptions">
<Form.Option value="San Francisco" />
<Form.Option value="New York" />
<Form.Option value="Seattle" />
<Form.Option value="Los Angeles" />
<Form.Option value="Chicago" />
</Form.Datalist>`}</Code>
</>
);
}
|
package easyauth
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"html/template"
"log"
"net/http"
"strings"
"time"
"github.com/gorilla/mux"
)
//Specific roles will be defined by the host application.
//It is intended to be a bitmask.
type Role uint32
type User struct {
Username string
Access Role
Method string
Data interface{}
}
//AuthProvider is any source of user authentication. These core methods must be implemented by all providers.
type AuthProvider interface {
//Retreive a user from the current http request if present.
GetUser(r *http.Request) (*User, error)
}
//FormProvider is a provider that accepts login info from an html form.
type FormProvider interface {
AuthProvider
GetRequiredFields() []string
HandlePost(http.ResponseWriter, *http.Request)
}
//HTTPProvider is a provider that provides an http handler form managing its own login endpoints, for example oauth.
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M20 15H4c-.55 0-1 .45-1 1s.45 1 1 1h16c.55 0 1-.45 1-1s-.45-1-1-1zm0-5H4c-.55 0-1 .45-1 1v1c0 .55.45 1 1 1h16c.55 0 1-.45 1-1v-1c0-.55-.45-1-1-1zm0-6H4c-.55 0-1 .45-1 1v2c0 .55.45 1 1 1h16c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zm.5 15h-17c-.28 0-.5.22-.5.5s.22.5.5.5h17c.28 0 .5-.22.5-.5s-.22-.5-.5-.5z"
}), 'LineWeightRounded');
|
FROM python:3
WORKDIR /root
# install any Python packages this app depends on
COPY requirements.txt /root/requirements.txt
RUN pip install -r requirements.txt
ENV FLASK_APP /root/main.py
# copy sources
COPY main.py /root/main.py
COPY templates /root/templates
CMD ["flask", "run", "--host=0.0.0.0", "--port=80"]
|
package test.unit.hu.interconnect.hr.module.personaldata.vacations;
import static com.google.common.collect.Lists.newArrayList;
import static hu.interconnect.hr.backend.api.enumeration.KivetelnapTipus.MUNKANAP;
import static hu.interconnect.hr.backend.api.enumeration.KivetelnapTipus.PIHENONAP;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import hu.interconnect.hr.backend.api.dto.<API key>;
import hu.interconnect.hr.domain.Kivetelnap;
import hu.interconnect.hr.domain.Szabadsag;
import hu.interconnect.hr.module.exceptiondays.KivetelnapokHelper;
import hu.interconnect.hr.module.personaldata.vacations.<API key>;
import test.builder.KivetelnapBuilder;
import test.builder.SzabadsagBuilder;
import test.builder.<API key>;
import test.matcher.<API key>;
import test.unit.<API key>;
public class <API key> extends <API key> {
private <API key> konvertalo = new <API key>(new KivetelnapokHelper(new ArrayList<Kivetelnap>()));
@Test
public void <API key>() {
try {
konvertalo.konvertal(null);
fail();
} catch (<API key> e) {
assertEquals(e.getLocalizedMessage(), "A bemeno parameter null!");
}
}
@Test
public void <API key>() {
List<<API key>> kapottReszletek = konvertalo.konvertal(new ArrayList<Szabadsag>());
assertThat(kapottReszletek, hasSize(0));
}
@Test
public void <API key>() {
List<<API key>> kapottReszletek = konvertalo.konvertal(newArrayList(
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.03").letrehoz()));
<API key> elvartReszletek = new <API key>()
.tsz(1)
.kezdet("2012.12.03")
.veg("2012.12.03")
.munkanapokSzama(1);
assertThat(kapottReszletek, contains(elvartReszletek));
}
@Test
public void <API key>() {
List<<API key>> kapottReszletek = konvertalo.konvertal(newArrayList(
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.03").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.04").letrehoz()));
<API key> elvartReszletek = new <API key>()
.tsz(1)
.kezdet("2012.12.03")
.veg("2012.12.04")
.munkanapokSzama(2);
assertThat(kapottReszletek, contains(elvartReszletek));
}
@Test
public void <API key>() {
List<<API key>> kapottReszletek = konvertalo.konvertal(newArrayList(
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.07").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.10").letrehoz()));
<API key> elvartReszletek = new <API key>()
.tsz(1)
.kezdet("2012.12.07")
.veg("2012.12.10")
.munkanapokSzama(2);
assertThat(kapottReszletek, contains(elvartReszletek));
}
@Test
public void <API key>() {
List<<API key>> kapottReszletek = konvertalo.konvertal(newArrayList(
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.06").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.07").letrehoz()));
<API key> elvartReszletek = new <API key>()
.tsz(1)
.kezdet("2012.12.06")
.veg("2012.12.07")
.munkanapokSzama(2);
assertThat(kapottReszletek, contains(elvartReszletek));
}
@Test
public void <API key>() {
List<<API key>> kapottReszletek = konvertalo.konvertal(newArrayList(
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.03").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.04").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.05").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.06").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.07").letrehoz()));
<API key> elvartReszletek = new <API key>()
.tsz(1)
.kezdet("2012.12.03")
.veg("2012.12.07")
.munkanapokSzama(5);
assertThat(kapottReszletek, contains(elvartReszletek));
}
@Test
public void <API key>() {
List<<API key>> kapottReszletek = konvertalo.konvertal(newArrayList(
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.07").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.11").letrehoz()));
<API key> elvartReszletek1 = new <API key>()
.tsz(1)
.kezdet("2012.12.07")
.veg("2012.12.07")
.munkanapokSzama(1);
<API key> elvartReszletek2 = new <API key>()
.tsz(1)
.kezdet("2012.12.11")
.veg("2012.12.11")
.munkanapokSzama(1);
assertThat(kapottReszletek, contains(asList(elvartReszletek1, elvartReszletek2)));
}
@Test
public void <API key>() {
KivetelnapokHelper kivetelnapok = new KivetelnapokHelper(newArrayList(new KivetelnapBuilder()
.datum("2012.12.10")
.tipus(PIHENONAP)
.letrehoz()));
konvertalo = new <API key>(kivetelnapok);
List<<API key>> kapottReszletek = konvertalo.konvertal(newArrayList(
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.07").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.11").letrehoz()));
<API key> elvartReszletek = new <API key>()
.tsz(1)
.kezdet("2012.12.07")
.veg("2012.12.11")
.munkanapokSzama(2);
assertThat(kapottReszletek, contains(elvartReszletek));
}
@Test
public void bugfix() {
KivetelnapokHelper kivetelnapok = new KivetelnapokHelper(newArrayList(new KivetelnapBuilder()
.datum("2012.03.16")
.tipus(PIHENONAP)
.letrehoz()));
konvertalo = new <API key>(kivetelnapok);
List<<API key>> kapottReszletek = konvertalo.konvertal(newArrayList(
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.01").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.02").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.05").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.06").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.07").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.08").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.15").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.19").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.20").letrehoz()));
<API key> elvartReszletek1 = new <API key>()
.tsz(1)
.kezdet("2012.03.01")
.veg("2012.03.08")
.munkanapokSzama(6);
<API key> elvartReszletek2 = new <API key>()
.tsz(1)
.kezdet("2012.03.15")
.veg("2012.03.20")
.munkanapokSzama(3);
assertThat(kapottReszletek, contains(asList(elvartReszletek1, elvartReszletek2)));
}
@Test
public void <API key>() {
KivetelnapokHelper kivetelnapok = new KivetelnapokHelper(newArrayList(new KivetelnapBuilder()
.datum("2012.12.23")
.tipus(MUNKANAP)
.letrehoz()));
konvertalo = new <API key>(kivetelnapok);
List<<API key>> kapottReszletek = konvertalo.konvertal(newArrayList(
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.12.23").letrehoz()));
<API key> elvartReszletek = new <API key>()
.tsz(1)
.kezdet("2012.12.23")
.veg("2012.12.23")
.munkanapokSzama(1);
assertThat(kapottReszletek, contains(asList(elvartReszletek)));
}
@Test
public void bugfix2() {
List<<API key>> eredmeny = konvertalo.konvertal(newArrayList(
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2013.01.15").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2013.01.16").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2013.01.17").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2013.01.18").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2013.01.21").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2013.01.22").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2013.01.23").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2013.01.28").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2013.01.29").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2013.01.30").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2013.01.31").letrehoz()));
<API key> elvartReszletek1 = new <API key>()
.tsz(1)
.kezdet("2013.01.15")
.veg("2013.01.23")
.munkanapokSzama(7);
<API key> elvartReszletek2 = new <API key>()
.tsz(1)
.kezdet("2013.01.28")
.veg("2013.01.31")
.munkanapokSzama(4);
assertThat(eredmeny, contains(asList(elvartReszletek1, elvartReszletek2)));
}
@Test
public void bugfix3() {
KivetelnapokHelper kivetelnapok = new KivetelnapokHelper(newArrayList(new KivetelnapBuilder()
.datum("2012.03.16")
.tipus(PIHENONAP)
.letrehoz(),
new KivetelnapBuilder()
.datum("2012.03.24")
.tipus(MUNKANAP)
.letrehoz())
);
konvertalo = new <API key>(kivetelnapok);
List<<API key>> eredmeny = konvertalo.konvertal(newArrayList(
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.01").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.02").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.05").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.06").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.07").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.08").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.09").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.12").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.13").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.14").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.15").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.19").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.20").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.21").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.22").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.23").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.24").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.26").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.27").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.28").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.29").letrehoz(),
new SzabadsagBuilder().szemelyitorzs(new <API key>().tsz(1).letrehoz()).nap("2012.03.30").letrehoz()));
<API key> elvartReszletek = new <API key>()
.tsz(1)
.kezdet("2012.03.01")
.veg("2012.03.30")
.munkanapokSzama(22);
assertThat(eredmeny, contains(elvartReszletek));
}
}
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>JsDoc Reference - Index</title>
<meta name="generator" content="JsDoc Toolkit" />
<link href="css/default.css" type="text/css" rel="stylesheet" media="all" />
</head>
<body>
<div id="header">
</div>
<div class="index">
<div class="menu">
<div align="center"><a href="index.html">Class Index</a> | <a href="files.html">File Index</a></div>
<h2 class="heading1">Classes</h2>
<ul class="classList">
<li><a href="symbols/_global_.html">_global_</a></li>
<li><a href="symbols/dom.html">dom</a></li>
<li><a href="symbols/dom.clone.html">dom.clone</a></li>
<li><a href="symbols/s.html">s</a></li>
</ul>
</div>
<div class="fineprint" style="clear:both">
Generated by <a href="http://code.google.com/p/jsdoc-toolkit/" target="_blank">JsDoc Toolkit</a> 2.4.0 on Wed Dec 15 2010 21:56:33 GMT-0000 (GMT)<br />
HTML template: <a href="http:
</div>
</div>
<div class="content">
<div class="innerContent">
<h1 class="classTitle">Class Index</h1>
<ul>
<li>
<h2 class="classname"><a href="symbols/_global_.html">_global_</a></h2>
<p></p>
</li>
<li>
<h2 class="classname"><a href="symbols/dom.html">dom</a></h2>
<p>Common and useful DOM elements for the class instance</p>
</li>
<li>
<h2 class="classname"><a href="symbols/dom.clone.html">dom.clone</a></h2>
<p>Cloned table nodes</p>
</li>
<li>
<h2 class="classname"><a href="symbols/s.html">s</a></h2>
<p>Settings object which contains customisable information for FixedColumns instance</p>
</li>
</ul>
</div>
</div>
</body>
</html>
|
using ENode.EQueue;
using ENode.Eventing;
namespace ENode.Tests
{
public class EventTopicProvider : <API key><IDomainEvent>
{
public override string GetTopic(IDomainEvent source)
{
return "EventTopic";
}
}
}
|
public class Grid {
public Tile array[][] = new Tile[10][8];
public Grid() {
for(int y = 0; y < getHeight(); y++) {
for(int x = 0; x < getWidth(); x++) {
array[x][y] = new Tile();
}
}
}
public int getWidth() { return 9; }
public int getHeight() { return 7; }
public Tile getTile(int x, int y) {
Tile mytile = new Tile();
try {
//System.out.println("Actual tile returned");
mytile = array[x][y];
}
catch(<API key> e) {
//System.out.println("Out of bounds tile");
}
finally {
//System.out.println("Returning false tile");
return mytile;
}
}
public void makeHole() {
for(int y = 0; y < getHeight(); y++) {
for(int x = 0; x < getWidth(); x++) {
if(((y == 1) || (y == 5)) && (x>=3) && (x<=6)) {
array[x][y].visible = false;
}
if(((y == 2) || (y == 4)) && (x>=2) && (x<=6)) {
array[x][y].visible = false;
}
if((y == 3) && (x>=2) && (x<=7)) {
array[x][y].visible = false;
}
}
}
}
public void makeHolierHole() {
for(int y = 0; y < getHeight(); y++) {
for(int x = 0; x < getWidth(); x++) {
if((x >= 1+y%2) && (x <= 5+y%2)) {
array[x][y].visible = false;
}
}
}
}
}
|
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FootComponent } from './foot.component';
describe('FootComponent', () => {
let component: FootComponent;
let fixture: ComponentFixture<FootComponent>;
beforeEach(async(() => {
TestBed.<API key>({
declarations: [ FootComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(FootComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
|
# path
Create a 2d path using SVG syntax.
* `d` is the path descriptor
{% craftml %}
<!-- rectangle -->
<path d="M10 10 h 10 v 10 h -10 z"/>
<!-- triangle -->
<path d="M30 10 l 10 10 l 10 -10 z"/>
{% endcraftml %}
Typically, you would use another drawing program to draw a path and export
it as an SVG tag to use in CraftML, because it is quite difficult to write
out a path descriptor manually.
{% craftml %}
<path d="M425.714,298.795c-3.315-25.56-31.224-50.174-59.725-52.675c-1.32-0.116-2.678-0.175-4.035-0.175
c-7.841,0-15.145,1.899-22.876,3.909c-8.474,2.204-17.236,4.482-27.593,4.482c-24.627,0-51.939-13.673-85.951-43.03
c-15.99-13.803-37.649-30.563-60.579-48.309c-35.625-27.57-72.464-56.078-92.513-76.923c-0.966-1.005-2.134-2.422-3.485-4.063
c-5.524-6.71-13.871-16.849-23.975-16.849c-7.007,0-13.556,4.88-19.463,14.506c-17.969,29.272-40.64,92.412-11.632,143.381
c22.454,39.516,27.952,104.224,29.102,123.114c0.583,9.583,7.556,12.261,11.214,12.338h33.836c6.576,0,10.445-4.408,10.615-12.095
c0.141-6.393,0.801-30.128,3.351-67.172c2.102-30.806,8.488-34.369,13.109-34.369c10.056,0,27.157,16.668,50.825,39.738
c15.363,14.975,34.483,33.61,56.618,52.296c19.095,16.12,42.025,23.956,70.1,23.956c36.682,0,74.746-13.709,105.331-24.725
l2.09-0.752C418.524,328.739,427.869,315.404,425.714,298.795z"/>
{% endcraftml %}
|
import {normalize, resolve} from "path";
import {existsSync, readFileSync} from "fs";
import {sys, ScriptSnapshot, resolveModuleName, <API key>} from "typescript";
export function createServiceHost(options, filenames, cwd) {
const normalizePath = (path) => resolve(normalize(path));
const <API key> = <API key>();
const files = {}; // normalized filename => {version, snap, text}
filenames.forEach(filename => files[normalizePath(filename)] = null);
return {
getDirectories: sys.getDirectories,
directoryExists: sys.directoryExists,
readDirectory: sys.readDirectory,
<API key>: <API key>,
fileExists(filename) {
filename = normalizePath(filename);
return filename in files || sys.fileExists(filename);
},
readFile(filename) {
return readFileSync(normalizePath(filename), "utf-8");
},
<API key>() {
return options;
},
getCurrentDirectory() {
return cwd;
},
getScriptFileNames() {
return Object.keys(files);
},
getScriptVersion(filename) {
const f = files[normalizePath(filename)];
return f ? f.version.toString() : "";
},
getScriptSnapshot(filename) {
let f = files[normalizePath(filename)];
if(!f) {
f = this.addFile(filename, this.readFile(filename));
}
return f.snap;
},
resolveModuleNames(moduleNames, containingFile) {
return moduleNames.map(name => this.resolveModuleName(name, containingFile));
},
getNewLine() {
return options.newLine || sys.newLine;
},
// additional methods
containsFile(filename) {
return normalizePath(filename) in files;
},
resolveModuleName(moduleName, containingFile) {
const {resolvedModule} = resolveModuleName(moduleName, containingFile, options, <API key>);
if(resolvedModule) {
resolvedModule.resolvedFileName = normalizePath(resolvedModule.resolvedFileName);
resolvedModule.originalFileName = resolvedModule.resolvedFileName;
}
return resolvedModule;
},
addFile(filename, text) {
filename = normalizePath(filename);
const snap = ScriptSnapshot.fromString(text);
snap.getChangeRange = () => {};
let file = files[filename];
if(!file) {
file = {version: 0};
files[filename] = file;
}
++file.version;
file.snap = snap;
file.text = text;
return file;
},
};
}
function <API key>() {
return {
fileExists(filename) {
return existsSync(filename);
},
readFile(filename) {
return readFileSync(filename, "utf-8")
},
};
}
|
package main
import (
"fmt"
"log"
)
type ListCommand struct {
All bool `short:"a" long:"available" description:"also prints all available version for installation"`
}
type InitCommand struct{}
type InstallCommand struct {
Use bool `short:"u" long:"use" description:"force use of this new version after installation"`
}
type UseCommand struct{}
type Interactor struct {
archive WebotsArchive
manager <API key>
templates TemplateManager
}
func NewInteractor() (*Interactor, error) {
res := &Interactor{}
var err error
res.archive, err = <API key>("http:
if err != nil {
return nil, err
}
manager, err := NewSymlinkManager(res.archive)
if err != nil {
return nil, err
}
res.manager = manager
res.templates = manager.templates
return res, nil
}
func (x *ListCommand) Execute(args []string) error {
xx, err := NewInteractor()
if err != nil {
return err
}
installed := xx.manager.Installed()
if len(installed) == 0 {
fmt.Printf("No webots version installed.\n")
} else {
for _, v := range installed {
if xx.manager.IsUsed(v) == true {
fmt.Printf(" -* %s\n", v)
} else {
fmt.Printf(" - %s\n", v)
}
}
}
if x.All {
fmt.Println("List of all available versions:")
for _, v := range xx.archive.AvailableVersions() {
fmt.Printf(" - %s\n", v)
}
} else {
vers := xx.archive.AvailableVersions()
if len(vers) == 0 {
return fmt.Errorf("No version are available")
}
fmt.Printf("Last available version is %s\n",
vers[len(vers)-1])
}
return nil
}
func (x *InitCommand) Execute(args []string) error {
return <API key>()
}
func (x *InstallCommand) Execute(args []string) error {
if len(args) != 1 {
return fmt.Errorf("Missing version to install")
}
v, err := ParseWebotsVersion(args[0])
if err != nil {
return err
}
xx, err := NewInteractor()
if err != nil {
return err
}
err = xx.manager.Install(v)
if err != nil {
return err
}
notUsed := true
for _, vv := range xx.manager.Installed() {
if xx.manager.IsUsed(vv) {
notUsed = false
break
}
}
if notUsed || x.Use {
err = xx.manager.Use(v)
if err != nil {
return err
}
log.Printf("Using now version %s", v)
}
return nil
}
func (x *UseCommand) Execute(args []string) error {
if len(args) != 1 {
return fmt.Errorf("Missing version to use")
}
v, err := ParseWebotsVersion(args[0])
if err != nil {
return err
}
xx, err := NewInteractor()
if err != nil {
return err
}
return xx.manager.Use(v)
}
type AddTemplateCommand struct {
Only []string `short:"o" long:"only" description:"apply template only for these versions"`
Except []string `short:"e" long:"except" description:"do not apply template on these versions"`
}
func (x *AddTemplateCommand) Execute(args []string) error {
if len(args) != 2 {
return fmt.Errorf("Need file to read and where to install")
}
var white, black []WebotsVersion
for _, w := range x.Only {
v, err := ParseWebotsVersion(w)
if err != nil {
return err
}
white = append(white, v)
}
for _, w := range x.Except {
v, err := ParseWebotsVersion(w)
if err != nil {
return err
}
black = append(black, v)
}
xx, err := NewInteractor()
if err != nil {
return err
}
err = xx.templates.RegisterTemplate(args[0], args[1])
if err != nil {
return err
}
err = xx.templates.WhiteList(args[1], white)
if err != nil {
return err
}
err = xx.templates.BlackList(args[1], black)
if err != nil {
return err
}
return xx.manager.ApplyAllTemplates()
}
type <API key> struct{}
func (x *<API key>) Execute(args []string) error {
if len(args) != 1 {
return fmt.Errorf("Need install path to remove template from")
}
xx, err := NewInteractor()
if err != nil {
return err
}
err = xx.templates.RemoveTemplate(args[0])
if err != nil {
return err
}
return xx.manager.ApplyAllTemplates()
}
func init() {
parser.AddCommand("list",
"Prints all the available version of webots",
"Prints all installed version, and current version in use. Can also prinst all available version for installation",
&ListCommand{})
parser.AddCommand("init",
"Initialiaze the system for webots_manager",
"Initialiaze the system with all requirement for webots_manager",
&InitCommand{})
parser.AddCommand("install",
"Install a new webots version on the system",
"Installs a new webots version on the system",
&InstallCommand{})
parser.AddCommand("use",
"Use a webots version on the system",
"Use a webots version on the system. If it is not installed, it will first install it",
&UseCommand{})
parser.AddCommand("add-template",
"Adds a template file to all version",
"Install a file to all version of webots. -o and -e can be used to explicitely whitelist or blacklist a version",
&AddTemplateCommand{})
parser.AddCommand("remove-template",
"Removes a template file from all version",
"Removes a previously installed template from all version of webots.",
&<API key>{})
}
|
package org.apache.oro.text.regex;
import java.util.Stack;
/**
* The Perl5Matcher class is used to match regular expressions (conforming to
* the Perl5 regular expression syntax) generated by Perl5Compiler.
* <p>
* Perl5Compiler and Perl5Matcher are designed with the intent that you use a
* separate instance of each per thread to avoid the overhead of both
* synchronization and concurrent access (e.g., a match that takes a long time
* in one thread will block the progress of another thread with a shorter
* match). If you want to use a single instance of each in a concurrent program,
* you must appropriately protect access to the instances with critical
* sections. If you want to share Perl5Pattern instances between concurrently
* executing instances of Perl5Matcher, you must compile the patterns with
* {@link Perl5Compiler#READ_ONLY_MASK}.
*
* @since 1.0
* @see PatternMatcher
* @see Perl5Compiler
*/
public final class Perl5Matcher implements PatternMatcher {
private static final char __EOS = Character.MAX_VALUE;
private static final int <API key> = 20;
private final boolean __multiline = false;
private boolean __lastSuccess = false;
private boolean __caseInsensitive = false;
private char __previousChar, __input[], __originalInput[];
private Perl5Repetition __currentRep;
private int __numParentheses, __bol, __eol, __currentOffset, __endOffset;
private char[] __program;
private int __expSize, __inputOffset, __lastParen;
private int[] __beginMatchOffsets, __endMatchOffsets;
private final Stack<int[]> __stack = new Stack<int[]>();
private Perl5MatchResult __lastMatchResult = null;
private static boolean __compare(final char[] s1, final int s1off,
final char[] s2, final int s2off, final int n) {
int s2Offs = s2off;
int s1Offs = s1off;
int cnt;
for (cnt = 0; cnt < n; cnt++, s1Offs++, s2Offs++) {
if (s1Offs >= s1.length) {
return false;
}
if (s2Offs >= s2.length) {
return false;
}
if (s1[s1Offs] != s2[s2Offs]) {
return false;
}
}
return true;
}
private static int __findFirst(final char[] input, final int curr,
final int endOffset, final char[] mustString) {
int current = curr;
int count, saveCurrent;
char ch;
if (input.length == 0) {
return endOffset;
}
ch = mustString[0];
// Find the offset of the first character of the must string
while (current < endOffset) {
if (ch == input[current]) {
saveCurrent = current;
count = 0;
while (current < endOffset && count < mustString.length) {
if (mustString[count] != input[current]) {
break;
}
++count;
++current;
}
current = saveCurrent;
if (count >= mustString.length) {
break;
}
}
++current;
}
return current;
}
private void __pushState(final int parenFloor) {
int[] state;
int stateEntries, paren;
stateEntries = 3 * (this.__expSize - parenFloor);
if (stateEntries <= 0) {
state = new int[3];
} else {
state = new int[stateEntries + 3];
}
state[0] = this.__expSize;
state[1] = this.__lastParen;
state[2] = this.__inputOffset;
for (paren = this.__expSize; paren > parenFloor; --paren, stateEntries -= 3) {
state[stateEntries] = this.__endMatchOffsets[paren];
state[stateEntries + 1] = this.__beginMatchOffsets[paren];
state[stateEntries + 2] = paren;
}
this.__stack.push(state);
}
private void __popState() {
int[] state;
int entry, paren;
state = this.__stack.pop();
this.__expSize = state[0];
this.__lastParen = state[1];
this.__inputOffset = state[2];
for (entry = 3; entry < state.length; entry += 3) {
paren = state[entry + 2];
this.__beginMatchOffsets[paren] = state[entry + 1];
if (paren <= this.__lastParen) {
this.__endMatchOffsets[paren] = state[entry];
}
}
for (paren = this.__lastParen + 1; paren <= this.__numParentheses; paren++) {
if (paren > this.__expSize) {
this.__beginMatchOffsets[paren] = OpCode._NULL_OFFSET;
}
this.__endMatchOffsets[paren] = OpCode._NULL_OFFSET;
}
}
// Initialize globals needed before calling __tryExpression for first time
private void <API key>(final Perl5Pattern expression,
final char[] input, final int beginOffset, final int endOff,
final int currentOffset) {
int endOffset = endOff;
// Remove this hack after more efficient case-folding and unicode
// character classes are implemented
this.__caseInsensitive = expression._isCaseInsensitive;
this.__input = input;
this.__endOffset = endOffset;
this.__currentRep = new Perl5Repetition();
this.__currentRep._numInstances = 0;
this.__currentRep._lastRepetition = null;
this.__program = expression._program;
this.__stack.setSize(0);
// currentOffset should always be >= beginOffset and should
// always be equal to zero when beginOffset equals 0, but we
// make a weak attempt to protect against a violation of this
// precondition
if (currentOffset == beginOffset || currentOffset <= 0) {
this.__previousChar = '\n';
} else {
this.__previousChar = input[currentOffset - 1];
if (!this.__multiline && this.__previousChar == '\n') {
this.__previousChar = '\0';
}
}
this.__numParentheses = expression._numParentheses;
this.__currentOffset = currentOffset;
this.__bol = beginOffset;
this.__eol = endOffset;
// Ok, here we're using endOffset as a temporary variable.
endOffset = this.__numParentheses + 1;
if (this.__beginMatchOffsets == null
|| endOffset > this.__beginMatchOffsets.length) {
if (endOffset < <API key>) {
endOffset = <API key>;
}
this.__beginMatchOffsets = new int[endOffset];
this.__endMatchOffsets = new int[endOffset];
}
}
// Set the match result information. Only call this if we successfully
// matched.
private void <API key>() {
int offs, maxEndOffs = 0;
// endOffset+=dontTry;
this.__lastMatchResult = new Perl5MatchResult(this.__numParentheses + 1);
// This can happen when using Perl5StreamInput
if (this.__endMatchOffsets[0] > this.__originalInput.length) {
throw new <API key>();
}
this.__lastMatchResult._matchBeginOffset = this.__beginMatchOffsets[0];
while (this.__numParentheses >= 0) {
offs = this.__beginMatchOffsets[this.__numParentheses];
if (offs >= 0) {
this.__lastMatchResult._beginGroupOffset[this.__numParentheses] = offs
- this.__lastMatchResult._matchBeginOffset;
} else {
this.__lastMatchResult._beginGroupOffset[this.__numParentheses] = OpCode._NULL_OFFSET;
}
offs = this.__endMatchOffsets[this.__numParentheses];
if (offs >= 0) {
this.__lastMatchResult._endGroupOffset[this.__numParentheses] = offs
- this.__lastMatchResult._matchBeginOffset;
if (offs > maxEndOffs && offs <= this.__originalInput.length) {
maxEndOffs = offs;
}
} else {
this.__lastMatchResult._endGroupOffset[this.__numParentheses] = OpCode._NULL_OFFSET;
}
--this.__numParentheses;
}
this.__lastMatchResult._match = new String(this.__originalInput,
this.__beginMatchOffsets[0], maxEndOffs
- this.__beginMatchOffsets[0]);
// Free up for garbage collection
this.__originalInput = null;
}
// Expects to receive a valid regular expression program. No checking
// is done to ensure validity.
// __originalInput must be set before calling this method for
// __lastMatchResult to be set correctly.
// beginOffset marks the beginning of the string
// currentOffset marks where to start the pattern search
private boolean __interpret(final Perl5Pattern expression,
final char[] input, final int beginOffset, final int endOff,
final int currentOffset) {
int endOffset = endOff;
boolean success;
int minLength = 0, dontTry = 0, offset;
char ch, mustString[];
<API key>(expression, input, beginOffset, endOffset,
currentOffset);
success = false;
mustString = expression._mustString;
_mainLoop: while (true) {
if (mustString != null
&& ((expression._anchor & Perl5Pattern._OPT_ANCH) == 0 || (this.__multiline || (expression._anchor & Perl5Pattern._OPT_ANCH_MBOL) != 0)
&& expression._back >= 0)) {
this.__currentOffset = __findFirst(this.__input,
this.__currentOffset, endOffset, mustString);
if (this.__currentOffset >= endOffset) {
if ((expression._options & Perl5Compiler.READ_ONLY_MASK) == 0) {
expression._mustUtility++;
}
success = false;
break _mainLoop;
} else if (expression._back >= 0) {
this.__currentOffset -= expression._back;
if (this.__currentOffset < currentOffset) {
this.__currentOffset = currentOffset;
}
minLength = expression._back + mustString.length;
} else if (!expression._isExpensive
&& (expression._options & Perl5Compiler.READ_ONLY_MASK) == 0
&& --expression._mustUtility < 0) {
// Be careful! The preceding logical expression is
// constructed
// so that mustUtility is only decremented if the expression
// compiled without READ_ONLY_MASK.
mustString = expression._mustString = null;
this.__currentOffset = currentOffset;
} else {
this.__currentOffset = currentOffset;
minLength = mustString.length;
}
}
if ((expression._anchor & Perl5Pattern._OPT_ANCH) != 0) {
if (this.__currentOffset == beginOffset
&& __tryExpression(beginOffset)) {
success = true;
break _mainLoop;
} else if (this.__multiline
|| (expression._anchor & Perl5Pattern._OPT_ANCH_MBOL) != 0
|| (expression._anchor & Perl5Pattern._OPT_IMPLICIT) != 0) {
if (minLength > 0) {
dontTry = minLength - 1;
}
endOffset -= dontTry;
if (this.__currentOffset > currentOffset) {
--this.__currentOffset;
}
while (this.__currentOffset < endOffset) {
if (this.__input[this.__currentOffset++] == '\n') {
if (this.__currentOffset < endOffset
&& __tryExpression(this.__currentOffset)) {
success = true;
break _mainLoop;
}
}
}
}
break _mainLoop;
}
if (expression._startString != null) {
mustString = expression._startString;
if ((expression._anchor & Perl5Pattern._OPT_SKIP) != 0) {
ch = mustString[0];
while (this.__currentOffset < endOffset) {
if (ch == this.__input[this.__currentOffset]) {
if (__tryExpression(this.__currentOffset)) {
success = true;
break _mainLoop;
}
++this.__currentOffset;
while (this.__currentOffset < endOffset
&& this.__input[this.__currentOffset] == ch) {
++this.__currentOffset;
}
}
++this.__currentOffset;
}
} else {
while ((this.__currentOffset = __findFirst(this.__input,
this.__currentOffset, endOffset, mustString)) < endOffset) {
if (__tryExpression(this.__currentOffset)) {
success = true;
break _mainLoop;
}
++this.__currentOffset;
}
}
break _mainLoop;
}
if ((offset = expression._startClassOffset) != OpCode._NULL_OFFSET) {
boolean doEvery, tmp;
char op;
doEvery = (expression._anchor & Perl5Pattern._OPT_SKIP) == 0;
if (minLength > 0) {
dontTry = minLength - 1;
}
endOffset -= dontTry;
tmp = true;
switch (op = this.__program[offset]) {
case OpCode._ANYOF:
offset = OpCode._getOperand(offset);
while (this.__currentOffset < endOffset) {
ch = this.__input[this.__currentOffset];
if (ch < 256
&& (this.__program[offset + (ch >> 4)] & 1 << (ch & 0xf)) == 0) {
if (tmp && __tryExpression(this.__currentOffset)) {
success = true;
break _mainLoop;
}
tmp = doEvery;
} else {
tmp = true;
}
++this.__currentOffset;
}
break;
case OpCode._ANYOFUN:
case OpCode._NANYOFUN:
offset = OpCode._getOperand(offset);
while (this.__currentOffset < endOffset) {
ch = this.__input[this.__currentOffset];
if (__matchUnicodeClass(ch, this.__program, offset, op)) {
if (tmp && __tryExpression(this.__currentOffset)) {
success = true;
break _mainLoop;
}
tmp = doEvery;
} else {
tmp = true;
}
++this.__currentOffset;
}
break;
case OpCode._BOUND:
if (minLength > 0) {
++dontTry;
--endOffset;
}
if (this.__currentOffset != beginOffset) {
ch = this.__input[this.__currentOffset - 1];
tmp = OpCode._isWordCharacter(ch);
} else {
tmp = OpCode._isWordCharacter(this.__previousChar);
}
while (this.__currentOffset < endOffset) {
ch = this.__input[this.__currentOffset];
if (tmp != OpCode._isWordCharacter(ch)) {
tmp = !tmp;
if (__tryExpression(this.__currentOffset)) {
success = true;
break _mainLoop;
}
}
++this.__currentOffset;
}
if ((minLength > 0 || tmp)
&& __tryExpression(this.__currentOffset)) {
success = true;
break _mainLoop;
}
break;
case OpCode._NBOUND:
if (minLength > 0) {
++dontTry;
--endOffset;
}
if (this.__currentOffset != beginOffset) {
ch = this.__input[this.__currentOffset - 1];
tmp = OpCode._isWordCharacter(ch);
} else {
tmp = OpCode._isWordCharacter(this.__previousChar);
}
while (this.__currentOffset < endOffset) {
ch = this.__input[this.__currentOffset];
if (tmp != OpCode._isWordCharacter(ch)) {
tmp = !tmp;
} else if (__tryExpression(this.__currentOffset)) {
success = true;
break _mainLoop;
}
++this.__currentOffset;
}
if ((minLength > 0 || !tmp)
&& __tryExpression(this.__currentOffset)) {
success = true;
break _mainLoop;
}
break;
case OpCode._ALNUM:
while (this.__currentOffset < endOffset) {
ch = this.__input[this.__currentOffset];
if (OpCode._isWordCharacter(ch)) {
if (tmp && __tryExpression(this.__currentOffset)) {
success = true;
break _mainLoop;
}
tmp = doEvery;
} else {
tmp = true;
}
++this.__currentOffset;
}
break;
case OpCode._NALNUM:
while (this.__currentOffset < endOffset) {
ch = this.__input[this.__currentOffset];
if (!OpCode._isWordCharacter(ch)) {
if (tmp && __tryExpression(this.__currentOffset)) {
success = true;
break _mainLoop;
}
tmp = doEvery;
} else {
tmp = true;
}
++this.__currentOffset;
}
break;
case OpCode._SPACE:
while (this.__currentOffset < endOffset) {
if (Character
.isWhitespace(this.__input[this.__currentOffset])) {
if (tmp && __tryExpression(this.__currentOffset)) {
success = true;
break _mainLoop;
}
tmp = doEvery;
} else {
tmp = true;
}
++this.__currentOffset;
}
break;
case OpCode._NSPACE:
while (this.__currentOffset < endOffset) {
if (!Character
.isWhitespace(this.__input[this.__currentOffset])) {
if (tmp && __tryExpression(this.__currentOffset)) {
success = true;
break _mainLoop;
}
tmp = doEvery;
} else {
tmp = true;
}
++this.__currentOffset;
}
break;
case OpCode._DIGIT:
while (this.__currentOffset < endOffset) {
if (Character
.isDigit(this.__input[this.__currentOffset])) {
if (tmp && __tryExpression(this.__currentOffset)) {
success = true;
break _mainLoop;
}
tmp = doEvery;
} else {
tmp = true;
}
++this.__currentOffset;
}
break;
case OpCode._NDIGIT:
while (this.__currentOffset < endOffset) {
if (!Character
.isDigit(this.__input[this.__currentOffset])) {
if (tmp && __tryExpression(this.__currentOffset)) {
success = true;
break _mainLoop;
}
tmp = doEvery;
} else {
tmp = true;
}
++this.__currentOffset;
}
break;
default:
break;
} // end switch
} else {
if (minLength > 0) {
dontTry = minLength - 1;
}
endOffset -= dontTry;
do {
if (__tryExpression(this.__currentOffset)) {
success = true;
break _mainLoop;
}
} while (this.__currentOffset++ < endOffset);
}
break _mainLoop;
} // end while
this.__lastSuccess = success;
this.__lastMatchResult = null;
return success;
}
private boolean __matchUnicodeClass(final char code,
final char __program1[], final int off, final char opcode) {
int offset = off;
boolean isANYOF = opcode == OpCode._ANYOFUN;
while (__program1[offset] != OpCode._END) {
if (__program1[offset] == OpCode._RANGE) {
offset++;
if (code >= __program1[offset]
&& code <= __program1[offset + 1]) {
return isANYOF;
}
offset += 2;
} else if (__program1[offset] == OpCode._ONECHAR) {
offset++;
if (__program1[offset++] == code) {
return isANYOF;
}
} else {
isANYOF = __program1[offset] == OpCode._OPCODE ? isANYOF
: !isANYOF;
offset++;
switch (__program1[offset++]) {
case OpCode._ALNUM:
if (OpCode._isWordCharacter(code)) {
return isANYOF;
}
break;
case OpCode._NALNUM:
if (!OpCode._isWordCharacter(code)) {
return isANYOF;
}
break;
case OpCode._SPACE:
if (Character.isWhitespace(code)) {
return isANYOF;
}
break;
case OpCode._NSPACE:
if (!Character.isWhitespace(code)) {
return isANYOF;
}
break;
case OpCode._DIGIT:
if (Character.isDigit(code)) {
return isANYOF;
}
break;
case OpCode._NDIGIT:
if (!Character.isDigit(code)) {
return isANYOF;
}
break;
case OpCode._ALNUMC:
if (Character.isLetterOrDigit(code)) {
return isANYOF;
}
break;
case OpCode._ALPHA:
if (Character.isLetter(code)) {
return isANYOF;
}
break;
case OpCode._BLANK:
if (Character.isSpaceChar(code)) {
return isANYOF;
}
break;
case OpCode._CNTRL:
if (Character.isISOControl(code)) {
return isANYOF;
}
break;
case OpCode._LOWER:
if (Character.isLowerCase(code)) {
return isANYOF;
}
// Remove this hack after more efficient case-folding and
// unicode
// character classes are implemented
if (this.__caseInsensitive && Character.isUpperCase(code)) {
return isANYOF;
}
break;
case OpCode._UPPER:
if (Character.isUpperCase(code)) {
return isANYOF;
}
// Remove this hack after more efficient case-folding and
// unicode
// character classes are implemented
if (this.__caseInsensitive && Character.isLowerCase(code)) {
return isANYOF;
}
break;
case OpCode._PRINT:
if (Character.isSpaceChar(code)) {
return isANYOF;
}
// Fall through to check if the character is alphanumeric,
// or a punctuation mark. Printable characters are either
// alphanumeric, punctuation marks, or spaces.
//$FALL-THROUGH$
case OpCode._GRAPH:
if (Character.isLetterOrDigit(code)) {
return isANYOF;
}
// Fall through to check if the character is a punctuation
// mark.
// Graph characters are either alphanumeric or punctuation.
//$FALL-THROUGH$
case OpCode._PUNCT:
switch (Character.getType(code)) {
case Character.DASH_PUNCTUATION:
case Character.START_PUNCTUATION:
case Character.END_PUNCTUATION:
case Character.<API key>:
case Character.OTHER_PUNCTUATION:
case Character.MATH_SYMBOL:
case Character.CURRENCY_SYMBOL:
case Character.MODIFIER_SYMBOL:
return isANYOF;
default:
break;
}
break;
case OpCode._XDIGIT:
if (code >= '0' && code <= '9' || code >= 'a'
&& code <= 'f' || code >= 'A' && code <= 'F') {
return isANYOF;
}
break;
case OpCode._ASCII:
if (code < 0x80) {
return isANYOF;
}
break;
default:
return !isANYOF;
}
}
}
return !isANYOF;
}
private boolean __tryExpression(final int offset) {
int count;
this.__inputOffset = offset;
this.__lastParen = 0;
this.__expSize = 0;
if (this.__numParentheses > 0) {
for (count = 0; count <= this.__numParentheses; count++) {
this.__beginMatchOffsets[count] = OpCode._NULL_OFFSET;
this.__endMatchOffsets[count] = OpCode._NULL_OFFSET;
}
}
if (__match(1)) {
this.__beginMatchOffsets[0] = offset;
this.__endMatchOffsets[0] = this.__inputOffset;
return true;
}
return false;
}
private int __repeat(final int offset, final int max) {
int scan, eol, operand, ret;
char ch;
char op;
scan = this.__inputOffset;
eol = this.__eol;
if (max != Character.MAX_VALUE && max < eol - scan) {
eol = scan + max;
}
operand = OpCode._getOperand(offset);
switch (op = this.__program[offset]) {
case OpCode._ANY:
while (scan < eol && this.__input[scan] != '\n') {
++scan;
}
break;
case OpCode._SANY:
scan = eol;
break;
case OpCode._EXACTLY:
++operand;
while (scan < eol && this.__program[operand] == this.__input[scan]) {
++scan;
}
break;
case OpCode._ANYOF:
if (scan < eol && (ch = this.__input[scan]) < 256) {
while (ch < 256
&& (this.__program[operand + (ch >> 4)] & 1 << (ch & 0xf)) == 0) {
if (++scan < eol) {
ch = this.__input[scan];
} else {
break;
}
}
}
break;
case OpCode._ANYOFUN:
case OpCode._NANYOFUN:
if (scan < eol) {
ch = this.__input[scan];
while (__matchUnicodeClass(ch, this.__program, operand, op)) {
if (++scan < eol) {
ch = this.__input[scan];
} else {
break;
}
}
}
break;
case OpCode._ALNUM:
while (scan < eol && OpCode._isWordCharacter(this.__input[scan])) {
++scan;
}
break;
case OpCode._NALNUM:
while (scan < eol && !OpCode._isWordCharacter(this.__input[scan])) {
++scan;
}
break;
case OpCode._SPACE:
while (scan < eol && Character.isWhitespace(this.__input[scan])) {
++scan;
}
break;
case OpCode._NSPACE:
while (scan < eol && !Character.isWhitespace(this.__input[scan])) {
++scan;
}
break;
case OpCode._DIGIT:
while (scan < eol && Character.isDigit(this.__input[scan])) {
++scan;
}
break;
case OpCode._NDIGIT:
while (scan < eol && !Character.isDigit(this.__input[scan])) {
++scan;
}
break;
default:
break;
}
ret = scan - this.__inputOffset;
this.__inputOffset = scan;
return ret;
}
private boolean __match(final int offset) {
char nextChar, op;
int scan, next, input, maxScan, current, line, arg;
boolean inputRemains = true, minMod = false;
Perl5Repetition rep;
input = this.__inputOffset;
inputRemains = input < this.__endOffset;
nextChar = inputRemains ? this.__input[input] : __EOS;
scan = offset;
maxScan = this.__program.length;
while (scan < maxScan /* && scan > 0 */) {
next = OpCode._getNext(this.__program, scan);
switch (op = this.__program[scan]) {
case OpCode._BOL:
if (input == this.__bol ? this.__previousChar == '\n'
: this.__multiline) {
break;
}
return false;
case OpCode._MBOL:
if (input == this.__bol ? this.__previousChar == '\n'
: (inputRemains || input < this.__eol)
&& this.__input[input - 1] == '\n') {
break;
}
return false;
case OpCode._SBOL:
if (input == this.__bol && this.__previousChar == '\n') {
break;
}
return false;
case OpCode._GBOL:
if (input == this.__bol) {
break;
}
return true;
case OpCode._EOL:
if ((inputRemains || input < this.__eol) && nextChar != '\n') {
return false;
}
if (!this.__multiline && this.__eol - input > 1) {
return false;
}
break;
case OpCode._MEOL:
if ((inputRemains || input < this.__eol) && nextChar != '\n') {
return false;
}
break;
case OpCode._SEOL:
if ((inputRemains || input < this.__eol) && nextChar != '\n') {
return false;
}
if (this.__eol - input > 1) {
return false;
}
break;
case OpCode._SANY:
if (!inputRemains && input >= this.__eol) {
return false;
}
inputRemains = ++input < this.__endOffset;
nextChar = inputRemains ? this.__input[input] : __EOS;
break;
case OpCode._ANY:
if (!inputRemains && input >= this.__eol || nextChar == '\n') {
return false;
}
inputRemains = ++input < this.__endOffset;
nextChar = inputRemains ? this.__input[input] : __EOS;
break;
case OpCode._EXACTLY:
current = OpCode._getOperand(scan);
line = this.__program[current++];
if (this.__program[current] != nextChar) {
return false;
}
if (this.__eol - input < line) {
return false;
}
if (line > 1
&& !__compare(this.__program, current, this.__input,
input, line)) {
return false;
}
input += line;
inputRemains = input < this.__endOffset;
nextChar = inputRemains ? this.__input[input] : __EOS;
break;
case OpCode._ANYOF:
current = OpCode._getOperand(scan);
if (nextChar == __EOS && inputRemains) {
nextChar = this.__input[input];
}
if (nextChar >= 256
|| (this.__program[current + (nextChar >> 4)] & 1 << (nextChar & 0xf)) != 0) {
return false;
}
if (!inputRemains && input >= this.__eol) {
return false;
}
inputRemains = ++input < this.__endOffset;
nextChar = inputRemains ? this.__input[input] : __EOS;
break;
case OpCode._ANYOFUN:
case OpCode._NANYOFUN:
current = OpCode._getOperand(scan);
if (nextChar == __EOS && inputRemains) {
nextChar = this.__input[input];
}
if (!__matchUnicodeClass(nextChar, this.__program, current, op)) {
return false;
}
if (!inputRemains && input >= this.__eol) {
return false;
}
inputRemains = ++input < this.__endOffset;
nextChar = inputRemains ? this.__input[input] : __EOS;
break;
case OpCode._ALNUM:
if (!inputRemains) {
return false;
}
if (!OpCode._isWordCharacter(nextChar)) {
return false;
}
inputRemains = ++input < this.__endOffset;
nextChar = inputRemains ? this.__input[input] : __EOS;
break;
case OpCode._NALNUM:
if (!inputRemains && input >= this.__eol) {
return false;
}
if (OpCode._isWordCharacter(nextChar)) {
return false;
}
inputRemains = ++input < this.__endOffset;
nextChar = inputRemains ? this.__input[input] : __EOS;
break;
case OpCode._NBOUND:
case OpCode._BOUND:
boolean a,
b;
if (input == this.__bol) {
a = OpCode._isWordCharacter(this.__previousChar);
} else {
a = OpCode._isWordCharacter(this.__input[input - 1]);
}
b = OpCode._isWordCharacter(nextChar);
if (a == b == (this.__program[scan] == OpCode._BOUND)) {
return false;
}
break;
case OpCode._SPACE:
if (!inputRemains && input >= this.__eol) {
return false;
}
if (!Character.isWhitespace(nextChar)) {
return false;
}
inputRemains = ++input < this.__endOffset;
nextChar = inputRemains ? this.__input[input] : __EOS;
break;
case OpCode._NSPACE:
if (!inputRemains) {
return false;
}
if (Character.isWhitespace(nextChar)) {
return false;
}
inputRemains = ++input < this.__endOffset;
nextChar = inputRemains ? this.__input[input] : __EOS;
break;
case OpCode._DIGIT:
if (!Character.isDigit(nextChar)) {
return false;
}
inputRemains = ++input < this.__endOffset;
nextChar = inputRemains ? this.__input[input] : __EOS;
break;
case OpCode._NDIGIT:
if (!inputRemains && input >= this.__eol) {
return false;
}
if (Character.isDigit(nextChar)) {
return false;
}
inputRemains = ++input < this.__endOffset;
nextChar = inputRemains ? this.__input[input] : __EOS;
break;
case OpCode._REF:
arg = OpCode._getArg1(this.__program, scan);
current = this.__beginMatchOffsets[arg];
if (current == OpCode._NULL_OFFSET) {
return false;
}
if (this.__endMatchOffsets[arg] == OpCode._NULL_OFFSET) {
return false;
}
if (current == this.__endMatchOffsets[arg]) {
break;
}
if (this.__input[current] != nextChar) {
return false;
}
line = this.__endMatchOffsets[arg] - current;
if (input + line > this.__eol) {
return false;
}
if (line > 1
&& !__compare(this.__input, current, this.__input,
input, line)) {
return false;
}
input += line;
inputRemains = input < this.__endOffset;
nextChar = inputRemains ? this.__input[input] : __EOS;
break;
case OpCode._NOTHING:
break;
case OpCode._BACK:
break;
case OpCode._OPEN:
arg = OpCode._getArg1(this.__program, scan);
this.__beginMatchOffsets[arg] = input;
if (arg > this.__expSize) {
this.__expSize = arg;
}
break;
case OpCode._CLOSE:
arg = OpCode._getArg1(this.__program, scan);
this.__endMatchOffsets[arg] = input;
if (arg > this.__lastParen) {
this.__lastParen = arg;
}
break;
case OpCode._CURLYX:
rep = new Perl5Repetition();
rep._lastRepetition = this.__currentRep;
this.__currentRep = rep;
rep._parenFloor = this.__lastParen;
rep._numInstances = -1;
rep._min = OpCode._getArg1(this.__program, scan);
rep._max = OpCode._getArg2(this.__program, scan);
rep._scan = OpCode._getNextOperator(scan) + 2;
rep._next = next;
rep._minMod = minMod;
// Must initialize to -1 because if we initialize to 0 and are
// at the beginning of the input the OpCode._WHILEM case will
// not work right.
rep._lastLocation = -1;
this.__inputOffset = input;
// use minMod as temporary
minMod = __match(OpCode._getPrevOperator(next));
// leave scope call not pertinent?
this.__currentRep = rep._lastRepetition;
return minMod;
case OpCode._WHILEM:
rep = this.__currentRep;
arg = rep._numInstances + 1;
this.__inputOffset = input;
if (input == rep._lastLocation) {
this.__currentRep = rep._lastRepetition;
line = this.__currentRep._numInstances;
if (__match(rep._next)) {
return true;
}
this.__currentRep._numInstances = line;
this.__currentRep = rep;
return false;
}
if (arg < rep._min) {
rep._numInstances = arg;
rep._lastLocation = input;
if (__match(rep._scan)) {
return true;
}
rep._numInstances = arg - 1;
return false;
}
if (rep._minMod) {
this.__currentRep = rep._lastRepetition;
line = this.__currentRep._numInstances;
if (__match(rep._next)) {
return true;
}
this.__currentRep._numInstances = line;
this.__currentRep = rep;
if (arg >= rep._max) {
return false;
}
this.__inputOffset = input;
rep._numInstances = arg;
rep._lastLocation = input;
if (__match(rep._scan)) {
return true;
}
rep._numInstances = arg - 1;
return false;
}
if (arg < rep._max) {
__pushState(rep._parenFloor);
rep._numInstances = arg;
rep._lastLocation = input;
if (__match(rep._scan)) {
return true;
}
__popState();
this.__inputOffset = input;
}
this.__currentRep = rep._lastRepetition;
line = this.__currentRep._numInstances;
if (__match(rep._next)) {
return true;
}
rep._numInstances = line;
this.__currentRep = rep;
rep._numInstances = arg - 1;
return false;
case OpCode._BRANCH:
if (this.__program[next] != OpCode._BRANCH) {
next = OpCode._getNextOperator(scan);
} else {
int lastParen;
lastParen = this.__lastParen;
do {
this.__inputOffset = input;
if (__match(OpCode._getNextOperator(scan))) {
return true;
}
for (arg = this.__lastParen; arg > lastParen; --arg) {
// __endMatchOffsets[arg] = 0;
this.__endMatchOffsets[arg] = OpCode._NULL_OFFSET;
}
this.__lastParen = arg;
scan = OpCode._getNext(this.__program, scan);
} while (scan != OpCode._NULL_OFFSET
&& this.__program[scan] == OpCode._BRANCH);
return false;
}
break;
case OpCode._MINMOD:
minMod = true;
break;
case OpCode._CURLY:
case OpCode._STAR:
case OpCode._PLUS:
if (op == OpCode._CURLY) {
line = OpCode._getArg1(this.__program, scan);
arg = OpCode._getArg2(this.__program, scan);
scan = OpCode._getNextOperator(scan) + 2;
} else if (op == OpCode._STAR) {
line = 0;
arg = Character.MAX_VALUE;
scan = OpCode._getNextOperator(scan);
} else {
line = 1;
arg = Character.MAX_VALUE;
scan = OpCode._getNextOperator(scan);
}
if (this.__program[next] == OpCode._EXACTLY) {
nextChar = this.__program[OpCode._getOperand(next) + 1];
current = 0;
} else {
nextChar = __EOS;
current = -1000;
}
this.__inputOffset = input;
if (minMod) {
minMod = false;
if (line > 0 && __repeat(scan, line) < line) {
return false;
}
while (arg >= line || arg == Character.MAX_VALUE
&& line > 0) {
// there may be a bug here with respect to
// __inputOffset >= __endOffset, but it seems to be
// right for
// now. the issue is with __inputOffset being reset
// later.
// is this test really supposed to happen here?
if (current == -1000
|| this.__inputOffset >= this.__endOffset
|| this.__input[this.__inputOffset] == nextChar) {
if (__match(next)) {
return true;
}
}
this.__inputOffset = input + line;
if (__repeat(scan, 1) != 0) {
++line;
this.__inputOffset = input + line;
} else {
return false;
}
}
} else {
arg = __repeat(scan, arg);
if (line < arg
&& OpCode._opType[this.__program[next]] == OpCode._EOL
&& (!this.__multiline
&& this.__program[next] != OpCode._MEOL || this.__program[next] == OpCode._SEOL)) {
line = arg;
}
while (arg >= line) {
// there may be a bug here with respect to
// __inputOffset >= __endOffset, but it seems to be
// right for
// now. the issue is with __inputOffset being reset
// later.
// is this test really supposed to happen here?
if (current == -1000
|| this.__inputOffset >= this.__endOffset
|| this.__input[this.__inputOffset] == nextChar) {
if (__match(next)) {
return true;
}
}
--arg;
this.__inputOffset = input + arg;
}
}
return false;
case OpCode._SUCCEED:
case OpCode._END:
this.__inputOffset = input;
// This enforces the rule that two consecutive matches cannot
// have
// the same end offset.
if (this.__inputOffset == this.<API key>) {
return false;
}
return true;
case OpCode._IFMATCH:
this.__inputOffset = input;
scan = OpCode._getNextOperator(scan);
if (!__match(scan)) {
return false;
}
break;
case OpCode._UNLESSM:
this.__inputOffset = input;
scan = OpCode._getNextOperator(scan);
if (__match(scan)) {
return false;
}
break;
default:
// todo: Need to throw an exception here.
} // end switch
// scan = (next > 0 ? next : 0);
scan = next;
} // end while scan
return false;
}
static char[] _toLower(final char[] in) {
char[] input = in.clone();
int current;
char[] inp;
// todo:
// Certainly not the best way to do case insensitive matching.
// Must definitely change this in some way, but for now we
// do what Perl does and make a copy of the input, converting
// it all to lowercase. This is truly better handled in the
// compilation phase.
inp = new char[input.length];
System.arraycopy(input, 0, inp, 0, input.length);
input = inp;
// todo: Need to inline toLowerCase()
for (current = 0; current < input.length; current++) {
if (Character.isUpperCase(input[current])) {
input[current] = Character.toLowerCase(input[current]);
}
}
return input;
}
/**
* Determines if a prefix of a string (represented as a char[]) matches a
* given pattern, starting from a given offset into the string. If a prefix
* of the string matches the pattern, a MatchResult instance representing
* the match is made accesible via {@link #getMatch()}.
* <p>
* This method is useful for certain common token identification tasks that
* are made more difficult without this functionality.
* <p>
*
* @param in
* The char[] to test for a prefix match.
* @param pattern
* The Pattern to be matched.
* @param offset
* The offset at which to start searching for the prefix.
* @return True if input matches pattern, false otherwise.
*/
@Override
public boolean matchesPrefix(final char[] in, final Pattern pattern,
final int offset) {
char[] input = in.clone();
final Perl5Pattern expression = (Perl5Pattern) pattern;
this.__originalInput = input;
if (expression._isCaseInsensitive) {
input = _toLower(input);
}
<API key>(expression, input, 0, input.length, offset);
this.__lastSuccess = __tryExpression(offset);
this.__lastMatchResult = null;
return this.__lastSuccess;
}
/**
* Determines if a prefix of a string (represented as a char[]) matches a
* given pattern. If a prefix of the string matches the pattern, a
* MatchResult instance representing the match is made accesible via
* {@link #getMatch()}.
* <p>
* This method is useful for certain common token identification tasks that
* are made more difficult without this functionality.
* <p>
*
* @param input
* The char[] to test for a prefix match.
* @param pattern
* The Pattern to be matched.
* @return True if input matches pattern, false otherwise.
*/
@Override
public boolean matchesPrefix(final char[] input, final Pattern pattern) {
return matchesPrefix(input, pattern, 0);
}
/**
* Determines if a prefix of a string matches a given pattern. If a prefix
* of the string matches the pattern, a MatchResult instance representing
* the match is made accesible via {@link #getMatch()}.
* <p>
* This method is useful for certain common token identification tasks that
* are made more difficult without this functionality.
* <p>
*
* @param input
* The String to test for a prefix match.
* @param pattern
* The Pattern to be matched.
* @return True if input matches pattern, false otherwise.
*/
@Override
public boolean matchesPrefix(final String input, final Pattern pattern) {
return matchesPrefix(input.toCharArray(), pattern, 0);
}
/**
* Determines if a prefix of a PatternMatcherInput instance matches a given
* pattern. If there is a match, a MatchResult instance representing the
* match is made accesible via {@link #getMatch()}. Unlike the
* {@link #contains(PatternMatcherInput, Pattern)} method, the current
* offset of the PatternMatcherInput argument is not updated. However,
* unlike the {@link #matches matches(PatternMatcherInput, Pattern)} method,
* matchesPrefix() will start its search from the current offset rather than
* the begin offset of the PatternMatcherInput.
* <p>
* This method is useful for certain common token identification tasks that
* are made more difficult without this functionality.
* <p>
*
* @param input
* The PatternMatcherInput to test for a prefix match.
* @param pattern
* The Pattern to be matched.
* @return True if input matches pattern, false otherwise.
*/
@Override
public boolean matchesPrefix(final PatternMatcherInput input,
final Pattern pattern) {
char[] inp;
Perl5Pattern expression;
expression = (Perl5Pattern) pattern;
this.__originalInput = input._originalBuffer;
if (expression._isCaseInsensitive) {
if (input._toLowerBuffer == null) {
input._toLowerBuffer = _toLower(this.__originalInput);
}
inp = input._toLowerBuffer;
} else {
inp = this.__originalInput;
}
<API key>(expression, inp, input._beginOffset,
input._endOffset, input._currentOffset);
this.__lastSuccess = __tryExpression(input._currentOffset);
this.__lastMatchResult = null;
return this.__lastSuccess;
}
/**
* Determines if a string (represented as a char[]) exactly matches a given
* pattern. If there is an exact match, a MatchResult instance representing
* the match is made accesible via {@link #getMatch()}. The pattern must be
* a Perl5Pattern instance, otherwise a ClassCastException will be thrown.
* You are not required to, and indeed should NOT try to (for performance
* reasons), catch a ClassCastException because it will never be thrown as
* long as you use a Perl5Pattern as the pattern parameter.
* <p>
* <b>Note:</b> matches() is not the same as sticking a ^ in front of your
* expression and a $ at the end of your expression in Perl5 and using the
* =~ operator, even though in many cases it will be equivalent. matches()
* literally looks for an exact match according to the rules of Perl5
* expression matching. Therefore, if you have a pattern <em>foo|foot</em>
* and are matching the input <em>foot</em> it will not produce an exact
* match. But <em>foot|foo</em> will produce an exact match for either
* <em>foot</em> or <em>foo</em>. Remember, Perl5 regular expressions do not
* match the longest possible match. From the perlre manpage: <blockquote>
* Alternatives are tried from left to right, so the first alternative found
* for which the entire expression matches, is the one that is chosen. This
* means that alternatives are not necessarily greedy. For example: when
* matching foo|foot against "barefoot", only the "foo" part will match, as
* that is the first alternative tried, and it successfully matches the
* target string. </blockquote>
* <p>
*
* @param in
* The char[] to test for an exact match.
* @param pattern
* The Perl5Pattern to be matched.
* @return True if input matches pattern, false otherwise.
* @exception ClassCastException
* If a Pattern instance other than a Perl5Pattern is passed
* as the pattern parameter.
*/
@Override
public boolean matches(final char[] in, final Pattern pattern) {
char[] input = in.clone();
final Perl5Pattern expression = (Perl5Pattern) pattern;
this.__originalInput = input;
if (expression._isCaseInsensitive) {
input = _toLower(input);
}
<API key>(expression, input, 0, input.length, 0);
this.__lastSuccess = __tryExpression(0)
&& this.__endMatchOffsets[0] == input.length;
this.__lastMatchResult = null;
return this.__lastSuccess;
}
/**
* Determines if a string exactly matches a given pattern. If there is an
* exact match, a MatchResult instance representing the match is made
* accesible via {@link #getMatch()}. The pattern must be a Perl5Pattern
* instance, otherwise a ClassCastException will be thrown. You are not
* required to, and indeed should NOT try to (for performance reasons),
* catch a ClassCastException because it will never be thrown as long as you
* use a Perl5Pattern as the pattern parameter.
* <p>
* <b>Note:</b> matches() is not the same as sticking a ^ in front of your
* expression and a $ at the end of your expression in Perl5 and using the
* =~ operator, even though in many cases it will be equivalent. matches()
* literally looks for an exact match according to the rules of Perl5
* expression matching. Therefore, if you have a pattern <em>foo|foot</em>
* and are matching the input <em>foot</em> it will not produce an exact
* match. But <em>foot|foo</em> will produce an exact match for either
* <em>foot</em> or <em>foo</em>. Remember, Perl5 regular expressions do not
* match the longest possible match. From the perlre manpage: <blockquote>
* Alternatives are tried from left to right, so the first alternative found
* for which the entire expression matches, is the one that is chosen. This
* means that alternatives are not necessarily greedy. For example: when
* matching foo|foot against "barefoot", only the "foo" part will match, as
* that is the first alternative tried, and it successfully matches the
* target string. </blockquote>
* <p>
*
* @param input
* The String to test for an exact match.
* @param pattern
* The Perl5Pattern to be matched.
* @return True if input matches pattern, false otherwise.
* @exception ClassCastException
* If a Pattern instance other than a Perl5Pattern is passed
* as the pattern parameter.
*/
@Override
public boolean matches(final String input, final Pattern pattern) {
return matches(input.toCharArray(), pattern);
}
/**
* Determines if the contents of a PatternMatcherInput instance exactly
* matches a given pattern. If there is an exact match, a MatchResult
* instance representing the match is made accesible via {@link #getMatch()}
* . Unlike the {@link #contains(PatternMatcherInput, Pattern)} method, the
* current offset of the PatternMatcherInput argument is not updated. You
* should remember that the region between the begin (NOT the current) and
* end offsets of the PatternMatcherInput will be tested for an exact match.
* <p>
* The pattern must be a Perl5Pattern instance, otherwise a
* ClassCastException will be thrown. You are not required to, and indeed
* should NOT try to (for performance reasons), catch a ClassCastException
* because it will never be thrown as long as you use a Perl5Pattern as the
* pattern parameter.
* <p>
* <b>Note:</b> matches() is not the same as sticking a ^ in front of your
* expression and a $ at the end of your expression in Perl5 and using the
* =~ operator, even though in many cases it will be equivalent. matches()
* literally looks for an exact match according to the rules of Perl5
* expression matching. Therefore, if you have a pattern <em>foo|foot</em>
* and are matching the input <em>foot</em> it will not produce an exact
* match. But <em>foot|foo</em> will produce an exact match for either
* <em>foot</em> or <em>foo</em>. Remember, Perl5 regular expressions do not
* match the longest possible match. From the perlre manpage: <blockquote>
* Alternatives are tried from left to right, so the first alternative found
* for which the entire expression matches, is the one that is chosen. This
* means that alternatives are not necessarily greedy. For example: when
* matching foo|foot against "barefoot", only the "foo" part will match, as
* that is the first alternative tried, and it successfully matches the
* target string. </blockquote>
* <p>
*
* @param input
* The PatternMatcherInput to test for a match.
* @param pattern
* The Perl5Pattern to be matched.
* @return True if input matches pattern, false otherwise.
* @exception ClassCastException
* If a Pattern instance other than a Perl5Pattern is passed
* as the pattern parameter.
*/
@Override
public boolean matches(final PatternMatcherInput input,
final Pattern pattern) {
char[] inp;
Perl5Pattern expression;
expression = (Perl5Pattern) pattern;
this.__originalInput = input._originalBuffer;
if (expression._isCaseInsensitive) {
if (input._toLowerBuffer == null) {
input._toLowerBuffer = _toLower(this.__originalInput);
}
inp = input._toLowerBuffer;
} else {
inp = this.__originalInput;
}
<API key>(expression, inp, input._beginOffset,
input._endOffset, input._beginOffset);
this.__lastMatchResult = null;
if (__tryExpression(input._beginOffset)) {
if (this.__endMatchOffsets[0] == input._endOffset
|| input.length() == 0
|| input._beginOffset == input._endOffset) {
this.__lastSuccess = true;
return true;
}
}
this.__lastSuccess = false;
return false;
}
/**
* Determines if a string contains a pattern. If the pattern is matched by
* some substring of the input, a MatchResult instance representing the <b>
* first </b> such match is made acessible via {@link #getMatch()}. If you
* want to access subsequent matches you should either use a
* PatternMatcherInput object or use the offset information in the
* MatchResult to create a substring representing the remaining input. Using
* the MatchResult offset information is the recommended method of obtaining
* the parts of the string preceeding the match and following the match.
* <p>
* The pattern must be a Perl5Pattern instance, otherwise a
* ClassCastException will be thrown. You are not required to, and indeed
* should NOT try to (for performance reasons), catch a ClassCastException
* because it will never be thrown as long as you use a Perl5Pattern as the
* pattern parameter.
* <p>
*
* @param input
* The String to test for a match.
* @param pattern
* The Perl5Pattern to be matched.
* @return True if the input contains a pattern match, false otherwise.
* @exception ClassCastException
* If a Pattern instance other than a Perl5Pattern is passed
* as the pattern parameter.
*/
@Override
public boolean contains(final String input, final Pattern pattern) {
return contains(input.toCharArray(), pattern);
}
/**
* Determines if a string (represented as a char[]) contains a pattern. If
* the pattern is matched by some substring of the input, a MatchResult
* instance representing the <b> first </b> such match is made acessible via
* {@link #getMatch()}. If you want to access subsequent matches you should
* either use a PatternMatcherInput object or use the offset information in
* the MatchResult to create a substring representing the remaining input.
* Using the MatchResult offset information is the recommended method of
* obtaining the parts of the string preceeding the match and following the
* match.
* <p>
* The pattern must be a Perl5Pattern instance, otherwise a
* ClassCastException will be thrown. You are not required to, and indeed
* should NOT try to (for performance reasons), catch a ClassCastException
* because it will never be thrown as long as you use a Perl5Pattern as the
* pattern parameter.
* <p>
*
* @param in
* The char[] to test for a match.
* @param pattern
* The Perl5Pattern to be matched.
* @return True if the input contains a pattern match, false otherwise.
* @exception ClassCastException
* If a Pattern instance other than a Perl5Pattern is passed
* as the pattern parameter.
*/
@Override
public boolean contains(final char[] in, final Pattern pattern) {
char[] input = in.clone();
final Perl5Pattern expression = (Perl5Pattern) pattern;
this.__originalInput = input;
if (expression._isCaseInsensitive) {
input = _toLower(input);
}
return __interpret(expression, input, 0, input.length, 0);
}
private static final int <API key> = -100;
private int <API key> = <API key>;
/**
* Determines if the contents of a PatternMatcherInput, starting from the
* current offset of the input contains a pattern. If a pattern match is
* found, a MatchResult instance representing the <b>first</b> such match is
* made acessible via {@link #getMatch()}. The current offset of the
* PatternMatcherInput is set to the offset corresponding to the end of the
* match, so that a subsequent call to this method will continue searching
* where the last call left off. You should remember that the region between
* the begin and end offsets of the PatternMatcherInput are considered the
* input to be searched, and that the current offset of the
* PatternMatcherInput reflects where a search will start from. Matches
* extending beyond the end offset of the PatternMatcherInput will not be
* matched. In other words, a match must occur entirely between the begin
* and end offsets of the input. See <code>PatternMatcherInput</code> for
* more details.
* <p>
* As a side effect, if a match is found, the PatternMatcherInput match
* offset information is updated. See the
* <code>PatternMatcherInput.setMatchOffsets(int, int)</code> method for
* more details.
* <p>
* The pattern must be a Perl5Pattern instance, otherwise a
* ClassCastException will be thrown. You are not required to, and indeed
* should NOT try to (for performance reasons), catch a ClassCastException
* because it will never be thrown as long as you use a Perl5Pattern as the
* pattern parameter.
* <p>
* This method is usually used in a loop as follows: <blockquote>
*
* <pre>
* PatternMatcher matcher;
* PatternCompiler compiler;
* Pattern pattern;
* PatternMatcherInput input;
* MatchResult result;
*
* compiler = new Perl5Compiler();
* matcher = new Perl5Matcher();
*
* try {
* pattern = compiler.compile(somePatternString);
* } catch (<API key> e) {
* System.err.println("Bad pattern.");
* System.err.println(e.getMessage());
* return;
* }
*
* input = new PatternMatcherInput(someStringInput);
*
* while (matcher.contains(input, pattern)) {
* result = matcher.getMatch();
* // Perform whatever processing on the result you want.
* }
*
* </pre>
*
* </blockquote>
* <p>
*
* @param input
* The PatternMatcherInput to test for a match.
* @param pattern
* The Pattern to be matched.
* @return True if the input contains a pattern match, false otherwise.
* @exception ClassCastException
* If a Pattern instance other than a Perl5Pattern is passed
* as the pattern parameter.
*/
@Override
public boolean contains(final PatternMatcherInput input,
final Pattern pattern) {
char[] inp;
Perl5Pattern expression;
boolean matchFound;
// if(input.length() > 0) {
// We want to allow a null string to match at the end of the input
// which is why we don't check endOfInput. Not sure if this is a
// safe thing to do or not.
if (input._currentOffset > input._endOffset) {
return false;
}
/*
* else if(input._endOfInput()) return false;
*/
expression = (Perl5Pattern) pattern;
this.__originalInput = input._originalBuffer;
// Todo:
// Really should only reduce to lowercase that part of the
// input that is necessary, instead of the whole thing.
// Adjust MatchResult offsets accordingly. Actually, pass an adjustment
// value to __interpret.
this.__originalInput = input._originalBuffer;
if (expression._isCaseInsensitive) {
if (input._toLowerBuffer == null) {
input._toLowerBuffer = _toLower(this.__originalInput);
}
inp = input._toLowerBuffer;
} else {
inp = this.__originalInput;
}
this.<API key> = input.getMatchEndOffset();
matchFound = __interpret(expression, inp, input._beginOffset,
input._endOffset, input._currentOffset);
if (matchFound) {
input.setCurrentOffset(this.__endMatchOffsets[0]);
input.setMatchOffsets(this.__beginMatchOffsets[0],
this.__endMatchOffsets[0]);
} else {
input.setCurrentOffset(input._endOffset + 1);
}
// Restore so it doesn't interfere with other unrelated matches.
this.<API key> = <API key>;
return matchFound;
}
/**
* Fetches the last match found by a call to a matches() or contains()
* method. If you plan on modifying the original search input, you must call
* this method BEFORE you modify the original search input, as a lazy
* evaluation technique is used to create the MatchResult. This reduces the
* cost of pattern matching when you don't care about the actual match and
* only care if the pattern occurs in the input. Otherwise, a MatchResult
* would be created for every match found, whether or not the MatchResult
* was later used by a call to getMatch().
* <p>
*
* @return A MatchResult instance containing the pattern match found by the
* last call to any one of the matches() or contains() methods. If
* no match was found by the last call, returns null.
*/
@Override
public MatchResult getMatch() {
if (!this.__lastSuccess) {
return null;
}
if (this.__lastMatchResult == null) {
<API key>();
}
return this.__lastMatchResult;
}
}
|
layout: post
title: "Sourdough Cinnamon Rolls"
date: 2014-07-21 07:30:37 -0600
comments: true
categories:
- buddy
image: http://anthonyrotio.com/rotiofood/2014-07-21/rolls_1.jpg
alt-image: http%3A%2F%2Fanthonyrotio.com%2Frotiofood%2F2014-07-21%2Frolls_1.jpg
author: rotio
keywords: sourdough, cinnamon rolls, buns, cinnamon, budweiser, breakfast
description: Sourdough cinnamon rolls made with Budweiser sourdough starter
external-url: http%3A%2F%2Frotiofood.com%2Fblog%2F2014%2F07%2F21%<API key>%2F
twitter-text: Sourdough%20cinnamon%20rolls%20made%20with%20Budweiser%20sourdough%20starter
buddy: 1
<!-- more -->
<img src="http://anthonyrotio.com/rotiofood/2014-07-21/rolls_1.jpg" />
<a href="https://plus.google.com/<API key>?rel=author" style="display:none">{{page.author }}</a>
<h4>Story</b> </h4>
<div>
<p>
<img src="http:
</p>
</div>
<h4>Recipe</b> </h4>
<div itemscope itemtype="http://schema.org/Recipe" >
<h4 itemprop="name">Sourdough Cinnamon Rolls</h4>
<br />
July 21, 2014
<center>
<img itemprop="image" width="200px" src="http://anthonyrotio.com/rotiofood/2014-07-21/rolls_1.jpg" />
<br /><span itemprop="description">{{page.description }}</span><br />
<br />Prep time: <time datetime="PT2H10M" itemprop="prepTime">2h10m</time>
<br />Cook time: <time datetime="PT0H25M" itemprop="cookTime">25m</time>
<br />Total time: <time datetime="PT2H35M" itemprop="totalTime">2h35m</time>
<br />Yield: <span itemprop="recipeYield">about 12 rolls</span>
<br/>
<h5>Ingredients:</h5>
<span itemprop="ingredients" itemscope itemtype="http://schema.org/ingredients">
<span itemprop="name"><a href="http:
<span itemprop="amount">1/2 batch</span>, prepared through the first rise
</span><br />
<span itemprop="ingredients" itemscope itemtype="http://schema.org/ingredients">
<span itemprop="name">Butter</span>:
<span itemprop="amount">6 tbl</span>, softened
</span><br />
<span itemprop="ingredients" itemscope itemtype="http://schema.org/ingredients">
<span itemprop="name">Sugar</span>:
<span itemprop="amount">1/2 c</span>
</span><br />
<span itemprop="ingredients" itemscope itemtype="http://schema.org/ingredients">
<span itemprop="name">Cinnamon</span>:
<span itemprop="amount">1/4 c</span>
</span><br />
<span itemprop="ingredients" itemscope itemtype="http://schema.org/ingredients">
<span itemprop="name">Powdered Sugar</span>:
<span itemprop="amount">1/4 c</span>
</span><br />
<span itemprop="ingredients" itemscope itemtype="http://schema.org/ingredients">
<span itemprop="name">Milk</span>:
<span itemprop="amount">splash</span>
</span><br />
<span itemprop="ingredients" itemscope itemtype="http://schema.org/ingredients">
<span itemprop="name">Vanilla</span>:
<span itemprop="amount">1 tsp</span>
</span><br />
<br /><h5>Directions:</h5>
<div itemprop="recipeInstructions">
1. Roll out dough to a rectangular shape between 1/2 and 1 inch thick.<br/>
2. Spread butter all over dough.<br/>
3. Sprinkle with sugar and cinnamon.<br/>
4. Roll dough as shown in photo. Cut into 1" slices. Place in greased pan with 1/4 inch in between each roll.<br/>
5. Allow to rise until doubled, about an hour. Tip: Heat a bowl of water in the microwave for 2 minutes. Remove bowl from microwave. Place dough in microwave and shut door to rise in warm humid environment.<br/>
6. Preheat oven to 350 F. <br/>
7. Toss a few ice cubes into bottom of oven. Bake rolls for 25 minutes or until risen and golden brown. Remove from oven.<br/>
8. Mix last three ingredients, adding milk a splash at a time to achieve an icing consistency.<br/>
9. Top hot rolls with icing, serve immediately.<br/></div>
<br/>
<br />
<center><div><img src="http://anthonyrotio.com/rotiofood/2014-07-21/rolls_rolling.jpg" /> <em style="text-align:center;font-size:.8em">Dough being rolled up with butter, cinnamon, and sugar already added.</em> <br/><br/><br/>
<img src="http://anthonyrotio.com/rotiofood/2014-07-21/rolls_raw.jpg" /> <em style="text-align:center;font-size:.8em">Rolls cut and spaced, before the rise.</em> <br/><br/><br/>
<img src="http://anthonyrotio.com/rotiofood/2014-07-21/rolls_baked.jpg"/> <em style="text-align:center;font-size:.8em">Rolls baked and ready to be iced.</em> <br/><br/><br/>
<img src="http://anthonyrotio.com/rotiofood/2014-07-21/rolls_1.jpg" /> <em style="text-align:center;font-size:.8em">The final product - Budweiser Sourdough Cinnamon Rolls.</em> <br/><br/><br/>
</div></center>
</div>
|
import path from 'path';
import {runScheduler} from './scheduler';
import logger from '../util/logger';
import dotenv from 'dotenv';
import {loadConfig} from '../../config';
import {initQueue} from './pipeline.queue';
logger.info(" _____ _ _ _ _ _ _ _ _ ");
logger.info("| | |_|___| | | |_| |_|_|");
logger.info("|
logger.info("|_____|_|_|_|_|_____|_|_,_|_|");
logger.info('ClinWiki data pipeline starting...');
const envPath = path.resolve(process.cwd()+'/../', '.env');
logger.info('Loading .env from '+envPath);
dotenv.config({
path: envPath
});
loadConfig();
logger.info('Initializing pipeline queue');
initQueue();
logger.info('Running...');
runScheduler();
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc -->
<title>org.robolectric.util.reflector Class Hierarchy</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
<script type="text/javascript" src="../../../../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]
<script type="text/javascript" src="../../../../jquery/jquery-1.10.2.js"></script>
<script type="text/javascript" src="../../../../jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.robolectric.util.reflector Class Hierarchy";
}
}
catch(err) {
}
var pathtoroot = "../../../../";loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="fixedNav">
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><ul class="navList" style="font-size: 1.5em;"><li>Robolectric 4.4 | <a href="/" target="_top"><img src="http://robolectric.org/images/<API key>.png" style="max-height: 18pt; vertical-align: sub;"/></a></li></ul></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/robolectric/util/inject/package-tree.html">Prev</a></li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/robolectric/util/reflector/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<ul class="navListSearch">
<li><span>SEARCH: </span>
<input type="text" id="search" value=" " disabled="disabled">
<input type="reset" id="reset" value=" " disabled="disabled">
</li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a name="skip.navbar.top">
</a></div>
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
</script>
<div class="header">
<h1 class="title">Hierarchy For Package org.robolectric.util.reflector</h1>
<span class="<API key>">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li class="circle">java.lang.<a href="https://developer.android.com/reference/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a>
<ul>
<li class="circle">org.robolectric.util.reflector.<a href="../../../../org/robolectric/util/reflector/Reflector.html" title="class in org.robolectric.util.reflector"><span class="typeNameLink">Reflector</span></a></li>
<li class="circle">org.robolectric.util.reflector.<a href="../../../../org/robolectric/util/reflector/UnsafeAccess.html" title="class in org.robolectric.util.reflector"><span class="typeNameLink">UnsafeAccess</span></a></li>
</ul>
</li>
</ul>
<h2 title="Annotation Type Hierarchy">Annotation Type Hierarchy</h2>
<ul>
<li class="circle">org.robolectric.util.reflector.<a href="../../../../org/robolectric/util/reflector/Accessor.html" title="annotation in org.robolectric.util.reflector"><span class="typeNameLink">Accessor</span></a> (implements java.lang.annotation.<a href="https://developer.android.com/reference/java/lang/annotation/Annotation.html?is-external=true" title="class or interface in java.lang.annotation">Annotation</a>)</li>
<li class="circle">org.robolectric.util.reflector.<a href="../../../../org/robolectric/util/reflector/ForType.html" title="annotation in org.robolectric.util.reflector"><span class="typeNameLink">ForType</span></a> (implements java.lang.annotation.<a href="https://developer.android.com/reference/java/lang/annotation/Annotation.html?is-external=true" title="class or interface in java.lang.annotation">Annotation</a>)</li>
<li class="circle">org.robolectric.util.reflector.<a href="../../../../org/robolectric/util/reflector/Static.html" title="annotation in org.robolectric.util.reflector"><span class="typeNameLink">Static</span></a> (implements java.lang.annotation.<a href="https://developer.android.com/reference/java/lang/annotation/Annotation.html?is-external=true" title="class or interface in java.lang.annotation">Annotation</a>)</li>
<li class="circle">org.robolectric.util.reflector.<a href="../../../../org/robolectric/util/reflector/WithType.html" title="annotation in org.robolectric.util.reflector"><span class="typeNameLink">WithType</span></a> (implements java.lang.annotation.<a href="https://developer.android.com/reference/java/lang/annotation/Annotation.html?is-external=true" title="class or interface in java.lang.annotation">Annotation</a>)</li>
</ul>
</div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><ul class="navList" style="font-size: 1.5em;"><li>Robolectric 4.4 | <a href="/" target="_top"><img src="http://robolectric.org/images/<API key>.png" style="max-height: 18pt; vertical-align: sub;"/></a></li></ul></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/robolectric/util/inject/package-tree.html">Prev</a></li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/robolectric/util/reflector/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a name="skip.navbar.bottom">
</a></div>
</body>
</html>
|
<!DOCTYPE html>
<html xmlns:msxsl="urn:<API key>:xslt">
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-16" http-equiv="Content-Type" />
<title _locid="<API key>">.NET Portability Report</title>
<style>
/* Body style, for the entire document */
body {
background: #F3F3F4;
color: #1E1E1F;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
padding: 0;
margin: 0;
}
/* Header1 style, used for the main title */
h1 {
padding: 10px 0px 10px 10px;
font-size: 21pt;
background-color: #E2E2E2;
border-bottom: 1px #C1C1C2 solid;
color: #201F20;
margin: 0;
font-weight: normal;
}
/* Header2 style, used for "Overview" and other sections */
h2 {
font-size: 18pt;
font-weight: normal;
padding: 15px 0 5px 0;
margin: 0;
}
/* Header3 style, used for sub-sections, such as project name */
h3 {
font-weight: normal;
font-size: 15pt;
margin: 0;
padding: 15px 0 5px 0;
background-color: transparent;
}
h4 {
font-weight: normal;
font-size: 12pt;
margin: 0;
padding: 0 0 0 0;
background-color: transparent;
}
/* Color all hyperlinks one color */
a {
color: #1382CE;
}
/* Paragraph text (for longer informational messages) */
p {
font-size: 10pt;
}
/* Table styles */
table {
border-spacing: 0 0;
border-collapse: collapse;
font-size: 10pt;
}
table th {
background: #E7E7E8;
text-align: left;
text-decoration: none;
font-weight: normal;
padding: 3px 6px 3px 6px;
}
table td {
vertical-align: top;
padding: 3px 6px 5px 5px;
margin: 0px;
border: 1px solid #E7E7E8;
background: #F7F7F8;
}
.NoBreakingChanges {
color: darkgreen;
font-weight:bold;
}
.FewBreakingChanges {
color: orange;
font-weight:bold;
}
.ManyBreakingChanges {
color: red;
font-weight:bold;
}
.BreakDetails {
margin-left: 30px;
}
.CompatMessage {
font-style: italic;
font-size: 10pt;
}
.GoodMessage {
color: darkgreen;
}
/* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */
.localLink {
color: #1E1E1F;
background: #EEEEED;
text-decoration: none;
}
.localLink:hover {
color: #1382CE;
background: #FFFF99;
text-decoration: none;
}
/* Center text, used in the over views cells that contain message level counts */
.textCentered {
text-align: center;
}
/* The message cells in message tables should take up all avaliable space */
.messageCell {
width: 100%;
}
/* Padding around the content after the h1 */
#content {
padding: 0px 12px 12px 12px;
}
/* The overview table expands to width, with a max width of 97% */
#overview table {
width: auto;
max-width: 75%;
}
/* The messages tables are always 97% width */
#messages table {
width: 97%;
}
/* All Icons */
.IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded {
min-width: 18px;
min-height: 18px;
background-repeat: no-repeat;
background-position: center;
}
/* Success icon encoded */
.IconSuccessEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
background-image: url(data:image/png;base64,<API key>/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+<API key>/H5+sHpZwYfxyRjTs+<API key>/13u3Fjrs/EdhsdDFHGB/<API key>+m3tVe/t97D52CB/ziG0nIgD/<API key>/<API key>/<API key>+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==);
}
/* Information icon encoded */
.IconInfoEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
background-image: url(data:image/png;base64,<API key>/<API key>+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/<API key>/HF1RsMXq+<API key>/<API key>+<API key>/<API key>=);
}
/* Warning icon encoded */
.IconWarningEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
background-image: url(data:image/png;base64,<API key>/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/<API key>+wVDSyyzFoJjfz9NB+pAF+<API key>/<API key>/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/<API key>==);
}
/* Error icon encoded */
.IconErrorEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
background-image: url(data:image/png;base64,<API key>/<API key>/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+<API key>/<API key>/<API key>=);
}
</style>
</head>
<body>
<h1 _locid="PortabilityReport">.NET Portability Report</h1>
<div id="content">
<div id="submissionId" style="font-size:8pt;">
<p>
<i>
Submission Id
<API key>
</i>
</p>
</div>
<h2 _locid="SummaryTitle">
<a name="Portability Summary"></a>Portability Summary
</h2>
<div id="summary">
<table>
<tbody>
<tr>
<th>Assembly</th>
<th>ASP.NET 5,Version=v1.0</th>
<th>Windows,Version=v8.1</th>
<th>.NET Framework,Version=v4.6</th>
<th>Windows Phone,Version=v8.1</th>
</tr>
<tr>
<td><strong><a href="#iso-relax">iso-relax</a></strong></td>
<td class="text-center">99.48 %</td>
<td class="text-center">99.48 %</td>
<td class="text-center">100.00 %</td>
<td class="text-center">99.48 %</td>
</tr>
</tbody>
</table>
</div>
<div id="details">
<a name="iso-relax"><h3>iso-relax</h3></a>
<table>
<tbody>
<tr>
<th>Target type</th>
<th>ASP.NET 5,Version=v1.0</th>
<th>Windows,Version=v8.1</th>
<th>.NET Framework,Version=v4.6</th>
<th>Windows Phone,Version=v8.1</th>
<th>Recommended changes</th>
</tr>
<tr>
<td>System.Diagnostics.DebuggableAttribute</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">#ctor(System.Boolean,System.Boolean)</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>System.Runtime.Serialization.SerializationInfo</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Remove serialization constructors on custom Exception types</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
<p>
<a href="#Portability Summary">Back to Summary</a>
</p>
</div>
</div>
</body>
</html>
|
<?php
/*
Unsafe sample
input : get the field userData from the variable $_GET via an object
Uses a <API key> via filter_var function
construction : use of sprintf via a %s with simple quote
*/
class Input{
private $input;
public function getInput(){
return $this->input;
}
public function __construct(){
$this->input = $_GET['UserData'] ;
}
}
$temp = new Input();
$tainted = $temp->getInput();
$sanitized = filter_var($tainted, <API key>);
$tainted = $sanitized ;
$query = sprintf("cat '%s'", $tainted);
//flaw
$ret = system($query);
?>
|
describe VagrantHyperV do
it 'should have a version number' do
VagrantHyperV::VERSION.should_not be_nil
end
it 'should do something useful' do
false.should be_true
end
end
|
import primes as py
def lcm(a, b):
return a * b / gcd(a, b)
def gcd(a, b):
while b != 0:
(a, b) = (b, a % b)
return a
# Returns two integers x, y such that gcd(a, b) = ax + by
def egcd(a, b):
if a == 0:
return (0, 1)
else:
y, x = egcd(b % a, a)
return (x - (b // a) * y, y)
# Returns an integer x such that ax = 1(mod m)
def modInverse(a, m):
x, y = egcd(a, m)
if gcd(a, m) == 1:
return x % m
# Reduces linear congruence to form x = b(mod m)
def reduceCongr(a, b, m):
gcdAB = gcd(a, b)
a /= gcdAB
b /= gcdAB
m /= gcd(gcdAB, m)
modinv = modInverse(a, m)
b *= modinv
return (1, b, m)
# Returns the incongruent solutions to the linear congruence ax = b(mod m)
def linCongr(a, b, m):
solutions = set()
if (b % gcd(a, m) == 0):
numSols = gcd(a, m)
sol = (b * egcd(a, m)[0] / numSols) % m
for i in xrange(0, numSols):
solutions.add((sol + m * i / numSols) % m)
return solutions
# Uses the Chinese Remainder Theorem to solve a system of linear congruences
def crt(congruences):
x = 0
M = 1
for i in xrange(len(congruences)):
M *= congruences[i][2]
congruences[i] = reduceCongr(congruences[i][0], congruences[i][1], congruences[i][2])
for j in xrange(len(congruences)):
m = congruences[j][2]
if gcd(m, M/m) != 1:
return None
x += congruences[j][1] * modInverse(M/m, m) * M / m
return x % M
# Returns the incongruent solution to any system of linear congruences
def linCongrSystem(congruences):
newCongruences = []
for i in xrange(len(congruences)):
congruences[i] = reduceCongr(congruences[i][0], congruences[i][1], congruences[i][2])
# Tests to see whether the system is solvable
for j in xrange(len(congruences)):
if congruences[i] != congruences[j]:
if (congruences[i][1] - congruences[j][1]) % gcd(congruences[i][2], congruences[j][2]) != 0:
return None
# Splits moduli into prime powers
pFactor = py.primeFactorization(congruences[i][2])
for term in pFactor:
newCongruences.append((1, congruences[i][1], term[0] ** term[1]))
# Discards redundant congruences
newCongruences = sorted(newCongruences, key=lambda x: x[2], reverse = True)
finalCongruences = []
for k in xrange(len(newCongruences)):
isRedundant = False
for l in xrange(0, k):
if newCongruences[l][2] % newCongruences[k][2] == 0:
isRedundant = True
if not isRedundant:
finalCongruences.append(newCongruences[k])
return crt(finalCongruences)
# Returns incongruents solutions to a polynomial congruence
def polyCongr(coefficients, m):
solutions = []
for i in xrange(m):
value = 0
for degree in xrange(len(coefficients)):
value += coefficients[degree] * (i ** (len(coefficients) - degree - 1))
if value % m == 0:
solutions.append(i)
return solutions
|
package com.aokyu.service;
import android.app.Application;
import android.test.ApplicationTestCase;
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using PowerLib.System;
using PowerLib.System.Collections;
using PowerLib.System.IO;
using PowerLib.System.IO.Streamed.Typed;
using PowerLib.System.Numerics;
using PowerLib.System.Data.SqlTypes.Numerics;
namespace PowerLib.System.Data.SqlTypes.Collections
{
[SqlUserDefinedType(Format.UserDefined, Name = "GradAngleCollection", IsByteOrdered = true, IsFixedLength = false, MaxByteSize = -1)]
public sealed class <API key> : INullable, IBinarySerialize
{
private List<GradAngle?> _list;
#region Contructors
public <API key>()
{
_list = null;
}
public <API key>(IEnumerable<GradAngle?> coll)
{
_list = coll != null ? new List<GradAngle?>(coll) : null;
}
private <API key>(List<GradAngle?> list)
{
_list = list;
}
#endregion
#region Properties
public List<GradAngle?> List
{
get { return _list; }
set { _list = value; }
}
public static <API key> Null
{
get { return new <API key>(); }
}
public bool IsNull
{
get { return _list == null; }
}
public SqlInt32 Count
{
get { return _list != null ? _list.Count : SqlInt32.Null; }
}
#endregion
#region Methods
public static <API key> Parse(SqlString s)
{
if (s.IsNull)
return Null;
return new <API key>(SqlFormatting.ParseCollection<GradAngle?>(s.Value,
t => !t.Equals(SqlFormatting.NullText, StringComparison.<API key>) ? SqlGradAngle.Parse(t).Value : default(GradAngle?)));
}
public override String ToString()
{
return SqlFormatting.Format(_list, t => (t.HasValue ? new SqlGradAngle(t.Value) : SqlGradAngle.Null).ToString());
}
[SqlMethod(IsMutator = true)]
public void Clear()
{
_list.Clear();
}
[SqlMethod(IsMutator = true)]
public void AddItem(SqlGradAngle value)
{
_list.Add(value.IsNull ? default(GradAngle?) : value.Value);
}
[SqlMethod(IsMutator = true)]
public void InsertItem(SqlInt32 index, SqlGradAngle value)
{
_list.Insert(index.IsNull ? _list.Count : index.Value, value.IsNull ? default(GradAngle?) : value.Value);
}
[SqlMethod(IsMutator = true)]
public void RemoveItem(SqlGradAngle value)
{
_list.Remove(value.IsNull ? default(GradAngle?) : value.Value);
}
[SqlMethod(IsMutator = true)]
public void RemoveAt(SqlInt32 index)
{
if (index.IsNull)
return;
_list.RemoveAt(index.Value);
}
[SqlMethod(IsMutator = true)]
public void SetItem(SqlInt32 index, SqlGradAngle value)
{
if (index.IsNull)
return;
_list[index.Value] = value.IsNull ? default(GradAngle?) : value.Value;
}
[SqlMethod(IsMutator = true)]
public void AddRange(<API key> coll)
{
if (coll.IsNull)
return;
_list.AddRange(coll._list);
}
[SqlMethod(IsMutator = true)]
public void AddRepeat(SqlGradAngle value, SqlInt32 count)
{
if (count.IsNull)
return;
_list.AddRepeat(value.IsNull ? default(GradAngle?) : value.Value, count.Value);
}
[SqlMethod(IsMutator = true)]
public void InsertRange(SqlInt32 index, <API key> coll)
{
if (coll.IsNull)
return;
int indexValue = !index.IsNull ? index.Value : _list.Count;
_list.InsertRange(indexValue, coll._list);
}
[SqlMethod(IsMutator = true)]
public void InsertRepeat(SqlInt32 index, SqlGradAngle value, SqlInt32 count)
{
if (count.IsNull)
return;
int indexValue = !index.IsNull ? index.Value : _list.Count;
_list.InsertRepeat(indexValue, value.IsNull ? default(GradAngle?) : value.Value, count.Value);
}
[SqlMethod(IsMutator = true)]
public void SetRange(SqlInt32 index, <API key> range)
{
if (range.IsNull)
return;
int indexValue = index.IsNull ? _list.Count - Comparable.Min(_list.Count, range._list.Count) : index.Value;
_list.SetRange(indexValue, range.List);
}
[SqlMethod(IsMutator = true)]
public void SetRepeat(SqlInt32 index, SqlGradAngle value, SqlInt32 count)
{
int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _list.Count - count.Value;
int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _list.Count - index.Value;
_list.SetRepeat(indexValue, value.IsNull ? default(GradAngle?) : value.Value, countValue);
}
[SqlMethod(IsMutator = true)]
public void RemoveRange(SqlInt32 index, SqlInt32 count)
{
int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _list.Count - count.Value;
int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _list.Count - index.Value;
_list.RemoveRange(indexValue, countValue);
}
[SqlMethod]
public SqlGradAngle GetItem(SqlInt32 index)
{
return !index.IsNull && _list[index.Value].HasValue ? _list[index.Value].Value : SqlGradAngle.Null;
}
[SqlMethod]
public <API key> GetRange(SqlInt32 index, SqlInt32 count)
{
int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _list.Count - count.Value;
int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _list.Count - index.Value;
return new <API key>(_list.GetRange(indexValue, countValue));
}
[SqlMethod]
public SqlGradAngleArray ToArray()
{
return new SqlGradAngleArray(_list);
}
#endregion
#region Operators
public static implicit operator byte[] (<API key> coll)
{
using (var ms = new MemoryStream())
using (new <API key>(ms, SizeEncoding.B4, true, coll._list.Select(t => t.HasValue ? t.Value.Units : default(Int32?)).Counted(coll._list.Count), true, false))
return ms.ToArray();
}
public static explicit operator <API key>(byte[] buffer)
{
using (var ms = new MemoryStream(buffer))
using (var sa = new <API key>(ms, true, false))
return new <API key>(sa.Select(t => t.HasValue ? new GradAngle(t.Value) : default(GradAngle?)).ToList());
}
#endregion
#region IBinarySerialize implementation
public void Read(BinaryReader rd)
{
using (var sa = new <API key>(rd.BaseStream, true, false))
_list = sa.Select(t => !t.HasValue ? default(GradAngle?) : new GradAngle(t.Value)).ToList();
}
public void Write(BinaryWriter wr)
{
using (var ms = new MemoryStream())
using (var sa = new <API key>(ms, SizeEncoding.B4, true, _list.Select(t => t.HasValue ? t.Value.Units : default(Int32?)).Counted(_list.Count), true, false))
wr.Write(ms.GetBuffer(), 0, (int)ms.Length);
}
#endregion
}
}
|
require 'spec_helper'
describe Pagerage::IncidentsParser do
before(:each) do
Pagerage::Incident.delete
end
let(:incidents_json) { File.read(File.dirname(__FILE__) + '/incidents_sample.json') }
let(:incidents_data) { JSON.parse(incidents_json) }
let(:parser) { Pagerage::IncidentsParser.new(incidents_json) }
it 'should set data attr when created' do
parser.data.should eq(incidents_data)
end
it 'should generate two incidents from the sample data' do
parser.run!
Pagerage::Incident.count.should eq(2)
end
end
|
a = a # e 4
a = 1 # 0 int
l = [a] # 0 [int]
d = {a:l} # 0 {int:[int]}
s = "abc"
c = ord(s[2].lower()[0]) # 0 int # 4 (str) -> int
l2 = [range(i) for i in d] # 0 [[int]]
y = [(a,b) for a,b in {1:'2'}.iteritems()] # 0 [(int,str)]
b = 1 # 0 int
if 0:
b = '' # 4 str
else:
b = str(b) # 4 str # 12 int
r = 0 # 0 int
if r: # 3 int
r = str(r) # 4 str # 12 int
r # 0 <int|str>
l = range(5) # 0 [int]
l2 = l[2:3] # 0 [int]
x = l2[1] # 0 int
k = 1() # 0 <unknown> # e 4
del k
k # e 0
l = [] # 0 [int]
x = 1 # 0 int
while x: # 6 int
l = [] # 4 [int]
l.append(1) # 0 [int] # 2 (int) -> None
l = [1, 2] # 0 [int]
l2 = [x for x in l] # 0 [<int|str>]
l2.append('') # 0 [<int|str>]
s = str() # 0 str
s2 = str(s) # 0 str
s3 = repr() # e 5 # 0 str
s4 = repr(s) # 0 str
x = 1 if [] else '' # 0 <int|str>
l = [1] # 0 [<int|str>]
l2 = [''] # 0 [str]
l[:] = l2 # 0 [<int|str>]
b = 1 < 2 < 3 # 0 bool
l = sorted(range(5), key=lambda x:-x) # 0 [int]
d = {} # 0 {<bool|int>:<int|str>}
d1 = {1:''} # 0 {int:str}
d.update(d1)
d[True] = 1
d # 0 {<bool|int>:<int|str>}
l = [] # 0 [int]
l1 = [] # 0 [<unknown>]
l.extend(l1)
l.append(2)
l = [] # 0 [<[str]|int>]
l1 = [[]] # 0 [[str]]
l.extend(l1)
l[0].append('') # e 0
l.append(1)
l = [] # 0 [[<int|str>]]
l2 = [1] # 0 [int]
l3 = [''] # 0 [str]
l.append(l2)
l.append(l3)
for i, s in enumerate("aoeu"): # 4 int # 7 str
pass
x = 1 # 0 int
y = x + 1.0 # 0 float
y << 1 # e 0
l = [1, 1.0] # 0 [float]
1.0 in [1] # e 0
x = `1` # 0 str
def f():
x = `1` # 4 str
d = dict(a=1) # 0 {str:int}
l = list() # 0 [<unknown>]
i = int(1) # 0 int
i = int(1.2) # 0 int
i = abs(1) # 0 int
i = abs(1.0) # 0 float
d = dict() # 0 {int:int}
d[1] = 2
d2 = dict(d) # 0 {<int|str>:<int|str>}
d2[''] = ''
d3 = dict([(1,2)]) # 0 {int:int}
d4 = dict(a=1) # 0 {str:int}
|
<?php //var_dump($games) ?>
<?php $this->load->view('includes/tables-head') ?>
<body class="fixed-header" ng-app="app" ng-controller="gameCtrl">
<?php $this->load->view('admin/admin-nav') ?>
<div class="page-container">
<?php $this->load->view('admin/admin-header') ?>
<div class="<API key> ">
<div class="content ">
<div class="jumbotron" data-pages="parallax">
<div class="container-fluid container-fixed-lg sm-p-l-20 sm-p-r-20">
<div class="inner">
<ul class="breadcrumb">
<li><p>Dashboard</p></li>
<li><a href="#" class="active">Game</a></li>
<li><a href="#" class="active">New</a></li>
</ul>
</div>
</div>
</div>
<div class="container-fluid container-fixed-lg">
<div class="panel">
<ul class="nav nav-tabs <API key>" <API key>="dropdownfx">
<li class="active">
<a data-toggle="tab" href="#new"><span>New Game</span></a>
</li>
<li>
<a data-toggle="tab" href="#game"><span>This Week Game</span></a>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane slide-left active" id="new">
<!-- View Branches Table start -->
<div class="conatiner">
<div class="row">
<div class="col-lg-12 col-md-12">
<div class="clearfix"></div>
<?php echo validation_errors(); ?>
<table class="table">
<thead>
<tr>
<td>NUMBER</td>
<td>HOME</td>
<td>AWAY</td>
<td>DEADLINE <small>format: (2016-04-18 11:24:00)</small></td>
</tr>
</thead>
<tbody>
<form role="form" method="post" action="<?=site_url('admin/game/create') ?>">
<?php for($i = 1; $i<=49; $i++){ ?>
<tr>
<td>
<?=$i; ?>
<input type="hidden" name="data[<?=$i; ?>][number]" value="<?=$i; ?>" />
</td>
<td>
<input id="home" type="text" name="data[<?=$i ?>][home]" class="form-control" required />
</td>
<td>
<input id="away" type="text" name="data[<?=$i ?>][away]" class="form-control" required />
</td>
<td>
<input type="date" class="input-sm form-control" name="data[<?=$i ?>][deadline]" placeholder="2016-04-18 11:24:00" required/>
</td>
</tr>
<?php } ?>
<?php $csrf = array(
'name' => $this->security->get_csrf_token_name(),
'hash' => $this->security->get_csrf_hash());
?>
<input type="hidden" name="<?=$csrf['name'];?>" value="<?=$csrf['hash'];?>" />
<tr>
<td>
<label for="number">Week Number <small>e.g. 34</small></label>
<input type="number" name="week_number" class="form-control" required placeholder="0">
</td>
<td>
<label for="week_start_date">Week Start Date (<small>format: 2016-04-18</small>)</label>
<input type="date" name="week_start_date" class="form-control" required placeholder="2016-04-18">
</td>
<td>
<label for="week_start_date">Week End Date (<small>format: 2016-04-18</small>)</label>
<input type="date" name="week_end_date" class="form-control" required placeholder="2016-04-18">
</td>
<td>
<label for="submit">Submit All Entries</label><br />
<input id="sumbit" type="submit" name="submit" value="Submit" class="btn btn-sm btn-primary">
</td>
</tr>
</form>
</tbody>
</table>
<br />
</div>
</div>
</div>
<!-- Veiw Branches Table end -->
</div>
<div class="tab-pane slide-left" id="game">
<!-- View Branches Table start -->
<div class="conatiner">
<div class="row">
<div class="col-lg-12 col-md-12">
<div class="clearfix"></div>
<table class="table table-responsive">
<thead>
<tr>
<td>NUMBER</td>
<td >DEADLINE</td>
<td>TOGGLE</td>
</tr>
</thead>
<?php if($games): ?>
<tbody>
<?php foreach ($games as $row): ?>
<tr>
<td><?=$row->number; ?></td>
<td><?=$row->deadline ?></td>
<td>
<?php if ($row->status == 'active'){ ?>
<input type="checkbox" ng-click="toggleGame(<?=$row->number; ?>, <?=$row->week_number ?>)" id="<?=$row->number ?>"checked/>
<?php }else{ ?>
<input type="checkbox" disabled id="<?=$row->number ?>" />
<?php } ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
<?php endif; ?>
</table>
</div>
</div>
</div>
<!-- Veiw Branches Table end -->
</div>
</div>
</div>
</div>
<?php $this->load->view('includes/footer-note') ?>
</div>
</div>
<?php $this->load->view('includes/tables-footer') ?>
|
define(['js/util'], function (util) {
"use strict";
var sf2 = {};
sf2.<API key> = function(ab) {
var that = {
riffHeader: null,
sfbk: {}
};
var ar = util.ArrayReader(ab);
var sfGenerator = [
"startAddrsOffset",
"endAddrsOffset",
"<API key>",
"endloopAddrsOffset",
"<API key>",
"modLfoToPitch",
"vibLfoToPitch",
"modEnvToPitch",
"initialFilterFc",
"initialFilterQ",
"modLfoToFilterFc",
"modEnvToFilterFc",
"<API key>",
"modLfoToVolume",
"unused1",
"chorusEffectsSend",
"reverbEffectsSend",
"pan",
"unused2",
"unused3",
"unused4",
"delayModLFO",
"freqModLFO",
"delayVibLFO",
"freqVibLFO",
"delayModEnv",
"attackModEnv",
"holdModEnv",
"decayModEnv",
"sustainModEnv",
"releaseModEnv",
"keynumToModEnvHold",
"keynumToModEnvDecay",
"delayVolEnv",
"attackVolEnv",
"holdVolEnv",
"decayVolEnv",
"sustainVolEnv",
"releaseVolEnv",
"keynumToVolEnvHold",
"keynumToVolEnvDecay",
"instrument", // 41: PGEN Terminator
"reserved1",
"keyRange",
"velRange",
"<API key>",
"keynum",
"velocity",
"initialAttenuation",
"reserved2",
"<API key>",
"coarseTune",
"fineTune",
"sampleID", // 53: IGEN Terminator
"sampleModes",
"reserved3",
"scaleTuning",
"exclusiveClass",
"overridingRootKey",
"unused5",
"endOper"
];
that.parseHeader = function () {
// read RIFF header
that.riffHeader = parseHeader();
that.size = that.riffHeader.length + 8;
// read level1 header
ar.seek(that.riffHeader.headPosition);
that.sfbk = {};
that.sfbk.ID = ar.readStringF(4);
// read level2 header
that.sfbk.INFO = parseHeader();
// read level3 header
// 3.1 INFO
ar.seek(that.sfbk.INFO.headPosition);
that.sfbk.INFO.ID = ar.readStringF(4);
that.sfbk.INFO.child = {};
while(ar.position() < that.sfbk.INFO.headPosition + that.sfbk.INFO.length) {
var head = parseHeader();
that.sfbk.INFO.child[head.ID] = head;
}
// 3.2 sdta
ar.seek(that.sfbk.INFO.headPosition + that.sfbk.INFO.padLength);
that.sfbk.sdta = parseHeader();
ar.seek(that.sfbk.sdta.headPosition);
that.sfbk.sdta.ID = ar.readStringF(4);
that.sfbk.sdta.child = {};
while(ar.position() < that.sfbk.sdta.headPosition + that.sfbk.sdta.length) {
head = parseHeader();
that.sfbk.sdta.child[head.ID] = head;
}
// 3.3 pdta
ar.seek(that.sfbk.sdta.headPosition + that.sfbk.sdta.padLength);
that.sfbk.pdta = parseHeader();
ar.seek(that.sfbk.pdta.headPosition);
that.sfbk.pdta.ID = ar.readStringF(4);
that.sfbk.pdta.child = {};
while(ar.position() < that.sfbk.pdta.headPosition + that.sfbk.pdta.length) {
head = parseHeader();
that.sfbk.pdta.child[head.ID] = head;
}
// read level4 data
// 4.1 PHDR data
var phdr = that.sfbk.pdta.child.phdr;
phdr.data = [];
ar.seek(phdr.headPosition);
while(ar.position() < phdr.headPosition + phdr.length) {
var data = {};
data.presetName = ar.readStringF(20);
data.preset = ar.readUInt16();
data.bank = ar.readUInt16();
data.presetBagNdx = ar.readUInt16();
data.library = ar.readUInt32();
data.genre = ar.readUInt32();
data.morphology = ar.readUInt32();
phdr.data.push(data);
}
// set placeholder
that.sfbk.pdta.child.pbag.data = [];
that.sfbk.pdta.child.pgen.data = [];
that.sfbk.pdta.child.pmod.data = [];
that.sfbk.pdta.child.inst.data = [];
that.sfbk.pdta.child.ibag.data = [];
that.sfbk.pdta.child.igen.data = [];
that.sfbk.pdta.child.imod.data = [];
that.sfbk.pdta.child.shdr.data = [];
};
that.readPreset = function(n) {
var phdr = that.sfbk.pdta.child.phdr;
var pbag = that.sfbk.pdta.child.pbag;
var r = {
presetName: phdr.data[n].presetName,
preset: phdr.data[n].preset,
bank: phdr.data[n].bank,
gen: [],
mod: []
}
// PBAGs
var pgen_global = {
keyRange: { lo: 0, hi: 127 },
velRange: { lo: 1, hi: 127 }
};
var pmod_global = [];
for(var i = phdr.data[n].presetBagNdx; i < phdr.data[n + 1].presetBagNdx; i++) {
var pbag0 = parsePBAG1(ar, pbag, i);
var pbag1 = parsePBAG1(ar, pbag, i + 1);
var pmod = readPMOD1(pbag0.modNdx, pbag1.modNdx, pmod_global);
var pmod_local = Array.prototype.concat(pmod_global, pmod);
var pgen = readPGEN1(pbag0.genNdx, pbag1.genNdx, pgen_global, pmod_local);
if(pgen["instrument"] === undefined) {
pgen_global = pgen;
pmod_global = pmod;
} else {
r.gen = Array.prototype.concat(r.gen, pgen.instrument.ibag.igen);
r.mod = Array.prototype.concat(r.mod, pgen.instrument.ibag.imod);
}
// r.mod.push(readPMOD1(pbag0.modNdx, pbag1.modNdx));
}
return r;
};
that.enumPresets = function() {
var p = [];
var phdr = that.sfbk.pdta.child.phdr;
phdr.data.forEach(function(ph) { p.push(ph.presetName); });
return p;
};
that.readSDTA = function(pos) {
ar.seek(that.sfbk.sdta.child.smpl.headPosition + pos * 2);
return ar.readInt16() / 32768;
}
that.readSDTAChunk = function(b, e) {
return new Int16Array(new Uint8Array(ar.subarray(
that.sfbk.sdta.child.smpl.headPosition + b * 2,
that.sfbk.sdta.child.smpl.headPosition + e * 2
)).buffer);
}
var readPGEN1 = function(b, e, g, gm) {
var pgen = that.sfbk.pdta.child.pgen;
var global = _.O(g, true);
var global_m = _.O(gm, true);
var result = _.O(g, true);
if(b != e) {
for(var i = b; i < e; i++) {
var r = parsePGEN1(ar, pgen, i);
if(r.inst == "instrument") {
global = _.O(result, true);
result[r.inst] = readINST1(r.genAmount, global, global_m);
} else {
result[r.inst] = r.genAmount;
}
}
}
return result;
};
var readPMOD1 = function(b, e, g) {
var pmod = that.sfbk.pdta.child.pmod;
var result = _.O(g, true);
if(b != e) {
for(var i = b; i < e; i++) {
result.push(parseMOD1(ar, pmod, i));
}
}
return result;
};
var readINST1 = function(i, g, gm) {
var inst = that.sfbk.pdta.child.inst;
var ibag = that.sfbk.pdta.child.ibag;
var inst0 = parseINST1(ar, inst, i);
var inst1 = parseINST1(ar, inst, i + 1);
var r = {
"instName": inst0.instName
};
var global = _.O(g, true);
var global_m = _.O(gm, true);
// IBAGs
r.ibag = {
igen: [],
imod: []
};
for(var i = inst0.instBagNdx; i < inst1.instBagNdx; i++) {
var ibag0 = parseIBAG1(ar, ibag, i);
var ibag1 = parseIBAG1(ar, ibag, i + 1);
var igen = readIGEN1(ibag0.instGenNdx, ibag1.instGenNdx, global);
var imod = readIMOD1(ibag0.instModNdx, ibag1.instModNdx, global_m);
if(igen["sampleID"] === undefined) { // global parameter
global = igen;
global_m = imod;
} else {
r.ibag.igen.push(igen);
r.ibag.imod.push(imod);
}
}
return r;
}
var readIGEN1 = function(b, e, g) {
var igen = that.sfbk.pdta.child.igen;
var result = _.O(g, true);
for(var i = b; i < e; i++) {
var r = parseIGEN1(ar, igen, i);
result[r.inst] = r.genAmount;
if(r.inst == "sampleID") {
result.shdr = readSHDR1(r.genAmount);
}
}
return result;
};
var readIMOD1 = function(b, e, g) {
var imod = that.sfbk.pdta.child.imod;
var result = _.O(g, true);
if(b != e) {
for(var i = b; i < e; i++) {
result.push(parseMOD1(ar, imod, i));
}
}
return result;
};
var readSHDR1 = function(i) {
var shdr = that.sfbk.pdta.child.shdr;
var r = parseSHDR1(ar, shdr, i);
r.end -= r.start;
r.startloop -= r.start;
r.endloop -= r.start;
r.sample = new Float32Array(r.end);
ar.seek(that.sfbk.sdta.child.smpl.headPosition + r.start * 2)
for(var j = 0; j < r.end; j++) {
r.sample[j] = ar.readInt16() / 32768;
}
r.start = 0;
return r;
};
var parseHeader = function(){
var h = {};
h.ID = ar.readStringF(4);
h.length = ar.readUInt32();
h.padLength = h.length % 2 == 1 ? h.length + 1 : h.length;
h.headPosition = ar.position();
ar.seek(ar.position() + h.padLength);
return h;
};
var parsePBAG1 = function(ar, root, i) {
ar.seek(root.headPosition + i * 4);
var data = {};
data.genNdx = ar.readUInt16();
data.modNdx = ar.readUInt16();
root.data[i] = data;
return data;
};
var parsePGEN1 = function(ar, root, i) {
ar.seek(root.headPosition + i * 4);
var data = {};
data.genOper = ar.readUInt16();
data.inst = sfGenerator[data.genOper];
if(data.inst == 'keyRange' ||
data.inst == 'velRange' ||
data.inst == 'keynum' ||
data.inst == 'velocity') {
data.genAmount = {};
data.genAmount.lo = ar.readUInt8();
data.genAmount.hi = ar.readUInt8();
} else {
data.genAmount = ar.readInt16();
}
root.data[i] = data;
return data;
};
var parseMOD1 = function(ar, root, i) {
ar.seek(root.headPosition + i * 10);
var data = {};
data.modSrcOper = { };
data.modSrcOper.index = ar.readUInt8();
data.modSrcOper.type = ar.readUInt8();
data.modDestOper = ar.readUInt16();
data.modDestInst = sfGenerator[data.modDestOper];
data.modAmount = ar.readInt16();
data.modAmtSrcOper = {};
data.modAmtSrcOper.index = ar.readUInt8();
data.modAmtSrcOper.type = ar.readUInt8();
data.modTransOper = ar.readUInt16();
root.data[i] = data;
return data;
};
var parseINST1 = function(ar, root, i) {
ar.seek(root.headPosition + i * 22);
var data = {};
data.instName = ar.readStringF(20);
data.instBagNdx = ar.readUInt16();
root.data.push(data);
return data;
};
var parseIBAG1 = function(ar, root, i) {
ar.seek(root.headPosition + i * 4);
var data = {};
data.instGenNdx = ar.readUInt16();
data.instModNdx = ar.readUInt16();
root.data.push(data);
return data;
};
var parseIGEN1 = function(ar, root, i) {
ar.seek(root.headPosition + i * 4);
var data = {};
data.genOper = ar.readUInt16();
data.inst = sfGenerator[data.genOper];
if(data.inst == 'keyRange' ||
data.inst == 'velRange' ||
data.inst == 'keynum' ||
data.inst == 'velocity') {
data.genAmount = {};
data.genAmount.lo = ar.readUInt8();
data.genAmount.hi = ar.readUInt8();
} else {
data.genAmount = ar.readInt16();
}
root.data.push(data);
return data;
};
var parseSHDR1 = function(ar, root, i) {
ar.seek(root.headPosition + i * 46);
var data = {};
data.sampleName = ar.readStringF(20);
data.start = ar.readUInt32();
data.end = ar.readUInt32();
data.startloop = ar.readUInt32();
data.endloop = ar.readUInt32();
data.sampleRate = ar.readUInt32();
data.originalPitch = ar.readUInt8();
data.pitchCorrection = ar.readInt8();
data.sampleLink = ar.readUInt16();
data.sampleType = ar.readUInt16();
root.data.push(data);
return data;
};
return that;
}
return sf2;
});
|
=begin
<recording pid=""
cookie=""
stamp=""
agent="">
<record id=""
stamp=""
status=""
method=""
url=""
request-time="">
<header name="" value=""/>
<body><![CDATA[HTML OR WHATEVER HERE]]></body>
<param name="" value=""/>
<multipart-reference name="" file-path=""/>
</record>
</recording>
=end
module DejaVuNS
class Recording
def self.find_by_identifier(ident)
DejaVuNS.root.recording.each do |rec|
return rec if rec.cookie == ident
end
nil
end
def self.find_by_pid(pid)
rec = nil
DejaVuNS.transaction do
rec = DejaVuNS.root.recording[pid]
end
rec
end
def self.all_recordings
recordings = []
DejaVuNS.transaction do
DejaVuNS.root.recording.each do |rec|
recordings << rec
end
end
recordings
end
end
end
|
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
public class IdParserTest {
@Test
public void testListParser() {
String testMedList = "{1;3;9}";
List<Integer> ids = IdParser.parse(testMedList);
assertEquals(3, ids.size());
assertEquals(new Integer(1), ids.get(0));
assertEquals(new Integer(3), ids.get(1));
assertEquals(new Integer(9), ids.get(2));
}
@Test
public void testEmptyListParser() {
String testMedList = "{}";
List<Integer> ids = IdParser.parse(testMedList);
assertEquals(0, ids.size());
}
@Test
public void <API key>() {
String testMedList = "{1}";
List<Integer> ids = IdParser.parse(testMedList);
assertEquals(1, ids.size());
assertEquals(new Integer(1), ids.get(0));
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>User agent detail - Mozilla/5.0 (Linux; U; Android 1.1.20; En-au; A101C Build/ECLAIR) AppleWebKit/530.17 (KHTML, Like Gecko) Version/4.0 Mobile Safari/530.17</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="../circle.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="section">
<h1 class="header center orange-text">User agent detail</h1>
<div class="row center">
<h5 class="header light">
Mozilla/5.0 (Linux; U; Android 1.1.20; En-au; A101C Build/ECLAIR) AppleWebKit/530.17 (KHTML, Like Gecko) Version/4.0 Mobile Safari/530.17
</h5>
</div>
</div>
<div class="section">
<table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Test suite</th></tr><tr><td>UAParser<br /><small>v0.5.0.2</small><br /><small>vendor/thadafinser/uap-core/tests/test_device.yaml</small></td><td> </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">Archos</td><td>A101C</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#<API key>">Detail</a>
<!-- Modal Structure -->
<div id="<API key>" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>UAParser result detail</h4>
<p><pre><code class="php">Array
(
[user_agent_string] => Mozilla/5.0 (Linux; U; Android 1.1.20; En-au; A101C Build/ECLAIR) AppleWebKit/530.17 (KHTML, Like Gecko) Version/4.0 Mobile Safari/530.17
[family] => Archos A101C
[brand] => Archos
[model] => A101C
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapFull<br /><small>6014</small><br /></td><td>Android 4.0</td><td>WebKit </td><td>Android 1.1</td><td style="border-left: 1px solid #555"></td><td></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.023</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#<API key>">Detail</a>
<!-- Modal Structure -->
<div id="<API key>" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>BrowscapFull result detail</h4>
<p><pre><code class="php">stdClass Object
(
[browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.1\.1.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/
|
javascript
/**
* @param {string} s
* @return {boolean}
*
* Maximum length is 50000
* s is not empty
* s only contains a-z
*/
var validPalindrome = function(s) {
return validHelper(s, 0, s.length - 1, 0);
};
var validHelper = function(s, startIndex, endIndex, deleteCount) {
let left = startIndex,
right = endIndex,
lc, rc;
while (left < right) {
lc = s[left], rc = s[right];
if (lc === rc) {
left++;
right
} else {
if (deleteCount > 0) {
return false;
} else {
// we got two choices, (1) delete left character, (2) delete right charecter
return validHelper(s, left + 1, right, 1) || validHelper(s, left, right - 1, 1);
}
}
}
return true;
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// @ignoreDep @angular/compiler-cli
const ts = require("typescript");
const path = require("path");
const fs = require("fs");
const { <API key>, VERSION } = require('@angular/compiler-cli');
const resource_loader_1 = require("./resource_loader");
class ExtractI18nPlugin {
constructor(options) {
this._compiler = null;
this._compilation = null;
this._compilerOptions = null;
this.<API key> = null;
this._setupOptions(options);
}
_setupOptions(options) {
if (!options.hasOwnProperty('tsConfigPath')) {
throw new Error('Must specify "tsConfigPath" in the configuration of @ngtools/webpack.');
}
// TS represents paths internally with '/' and expects the tsconfig path to be in this format
this._tsConfigPath = options.tsConfigPath.replace(/\\/g, '/');
// Check the base path.
const maybeBasePath = path.resolve(process.cwd(), this._tsConfigPath);
let basePath = maybeBasePath;
if (fs.statSync(maybeBasePath).isFile()) {
basePath = path.dirname(basePath);
}
if (options.hasOwnProperty('basePath')) {
basePath = path.resolve(process.cwd(), options.basePath);
}
let tsConfigJson = null;
try {
tsConfigJson = JSON.parse(fs.readFileSync(this._tsConfigPath, 'utf8'));
}
catch (err) {
throw new Error(`An error happened while parsing ${this._tsConfigPath} JSON: ${err}.`);
}
const tsConfig = ts.<API key>(tsConfigJson, ts.sys, basePath, null, this._tsConfigPath);
let fileNames = tsConfig.fileNames;
if (options.hasOwnProperty('exclude')) {
let exclude = typeof options.exclude == 'string'
? [options.exclude] : options.exclude;
exclude.forEach((pattern) => {
const basePathPattern = '(' + basePath.replace(/\\/g, '/')
.replace(/[\-\[\]\/{}()+?.\\^$|*]/g, '\\$&') + ')?';
pattern = pattern
.replace(/\\/g, '/')
.replace(/[\-\[\]{}()+?.\\^$|]/g, '\\$&')
.replace(/\*\*/g, '(?:.*)')
.replace(/\*/g, '(?:[^/]*)')
.replace(/^/, basePathPattern);
const re = new RegExp('^' + pattern + '$');
fileNames = fileNames.filter(x => !x.replace(/\\/g, '/').match(re));
});
}
else {
fileNames = fileNames.filter(fileName => !/\.spec\.ts$/.test(fileName));
}
this._rootFilePath = fileNames;
// By default messages will be generated in basePath
let genDir = basePath;
if (options.hasOwnProperty('genDir')) {
genDir = path.resolve(process.cwd(), options.genDir);
}
this._compilerOptions = tsConfig.options;
this.<API key> = Object.assign({ genDir }, this._compilerOptions, tsConfig.raw['<API key>'], { basePath });
this._basePath = basePath;
this._genDir = genDir;
// this._compilerHost = new WebpackCompilerHost(this._compilerOptions, this._basePath);
this._compilerHost = ts.createCompilerHost(this._compilerOptions, true);
this._program = ts.createProgram(this._rootFilePath, this._compilerOptions, this._compilerHost);
if (options.hasOwnProperty('i18nFormat')) {
this._i18nFormat = options.i18nFormat;
}
if (options.hasOwnProperty('locale')) {
if (VERSION.major === '2') {
console.warn("The option '--locale' is only available on the xi18n command"
+ ' starting from Angular v4, please update to a newer version.', '\n\n');
}
this._locale = options.locale;
}
if (options.hasOwnProperty('outFile')) {
if (VERSION.major === '2') {
console.warn("The option '--out-file' is only available on the xi18n command"
+ ' starting from Angular v4, please update to a newer version.', '\n\n');
}
this._outFile = options.outFile;
}
}
apply(compiler) {
this._compiler = compiler;
compiler.plugin('make', (compilation, cb) => this._make(compilation, cb));
compiler.plugin('after-emit', (compilation, cb) => {
this._donePromise = null;
this._compilation = null;
compilation.<API key> = null;
cb();
});
}
_make(compilation, cb) {
this._compilation = compilation;
if (this._compilation.<API key>) {
return cb(new Error('An @ngtools/webpack xi18n plugin already exist for ' +
'this compilation.'));
}
if (!this._compilation.<API key>) {
return cb(new Error('An @ngtools/webpack aot plugin does not exists ' +
'for this compilation'));
}
this._compilation.<API key> = this;
this._resourceLoader = new resource_loader_1.<API key>(compilation);
this._donePromise = Promise.resolve()
.then(() => {
return <API key>.extractI18n({
basePath: this._basePath,
compilerOptions: this._compilerOptions,
program: this._program,
host: this._compilerHost,
<API key>: this.<API key>,
i18nFormat: this._i18nFormat,
locale: this._locale,
outFile: this._outFile,
readResource: (path) => this._resourceLoader.get(path)
});
})
.then(() => cb(), (err) => {
this._compilation.errors.push(err);
cb(err);
});
}
}
exports.ExtractI18nPlugin = ExtractI18nPlugin;
//# sourceMappingURL=/users/mikkeldamm/forked-repos/angular-cli/src/extract_i18n_plugin.js.map
|
package org.softlang.service.company;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
/**
* A department has a name, a manager, employees, and subdepartments.
*/
public class Department implements Serializable {
private static final long serialVersionUID = -<API key>;
private String name;
private Employee manager;
private List<Department> subdepts = new LinkedList<Department>();
private List<Employee> employees = new LinkedList<Employee>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Employee getManager() {
return manager;
}
public void setManager(Employee manager) {
this.manager = manager;
}
public List<Department> getSubdepts() {
return subdepts;
}
public List<Employee> getEmployees() {
return employees;
}
public double total() {
double total = 0;
total += getManager().getSalary();
for (Department s : getSubdepts())
total += s.total();
for (Employee e : getEmployees())
total += e.getSalary();
return total;
}
public void cut() {
getManager().cut();
for (Department s : getSubdepts())
s.cut();
for (Employee e : getEmployees())
e.cut();
}
}
|
/**
* Contains methods for extracting/selecting final multiword candidates.
* @author Valeria Quochi @author Francesca Frontini @author Francesco Rubino
* Istituto di linguistica Computazionale "A. Zampolli" - CNR Pisa - Italy
*
*/
package multiword;
|
layout: post
title: "IO"
category: Linux
tags: [net]
  IOselectepollLinux IOIOread
IO
1.
2.
* **IO**
  readIOreadIOIO
* **IO**
  readreadreadreadIOreadIOIOIO
* **IO**
  IOIOIOIOIOIO
* **IO**
  IO
>   IOIOIOIOIO
* **selectepoll**
  selectepollIOsocketselectepollselectO(n)epollepollO(1)
>   
* **:**
  [http:
  [http:
|
_<sup><sup>[www.codever.land/bookmarks/t/ngrx](https:
_<sup>https:
This month at the St. Lewis Angular Lunch, Kyle spoke about managing state in Angular 2 applications. The crying baby thumbnail accurately reflects how many developers have come to experience state ma...
* :calendar: **published on**: 2016-10-20
* **tags**: [angular](../tagged/angular.md), [state-management](../tagged/state-management.md), [ngrx](../tagged/ngrx.md), [redux](../tagged/redux.md)
_<sup>https://blog.angular-university.io/<API key>/</sup>_
Using a store architecture represents a big architectural shift: with the arrival of single page applications, we moved the Model to View transformation from the server to the client.
Store architect...
* **tags**: [angular](../tagged/angular.md), [flux](../tagged/flux.md), [ngrx](../tagged/ngrx.md), [architecture](../tagged/architecture.md)
_<sup>https://medium.com/<API key>/<API key></sup>_
Angular follows a two-way data flow pattern, meaning you can send data up and down the component tree. As everything in the Angular is a component, understanding communication between components is cr...
* :calendar: **published on**: 2019-05-30
* **tags**: [angular](../tagged/angular.md), [ngrx](../tagged/ngrx.md)
* :octocat: **[source code](https://github.com/bbachi/<API key>)**
_<sup>https:
NGXS is a state management pattern + library for Angular. It acts as a single source of truth for your application's state, providing simple rules for predictable state mutations.
NGXS is modeled aft...
* **tags**: [angular](../tagged/angular.md), [rxjs](../tagged/rxjs.md), [redux](../tagged/redux.md), [ngrx](../tagged/ngrx.md), [cqrs](../tagged/cqrs.md)
* :octocat: **[source code](https://github.com/ngxs/store)**
_<sup>https://github.com/johnpapa/angular-ngrx-data</sup>_
Angular with ngRx and experimental ngrx-data helper
* **tags**: [angular](../tagged/angular.md), [ngrx](../tagged/ngrx.md)
* :octocat: **[source code](https://github.com/johnpapa/angular-ngrx-data)**
_<sup>https://github.com/ngrx/platform</sup>_
Monorepo for ngrx codebase
* **tags**: [angular](../tagged/angular.md), [ngrx](../tagged/ngrx.md), [redux](../tagged/redux.md)
* :octocat: **[source code](https://github.com/ngrx/platform)**
|
#include "<API key>.h"
enum {
kMaxNodes = 50000,
kNodesIncrease = 250,
TEST_COUNT = 7,
};
enum {
kTagInfoLayer = 1,
kTagMainLayer = 2,
kTagMenuLayer = (kMaxNodes + 1000),
};
static int s_nSpriteCurCase = 0;
// SubTest
SubTest::~SubTest()
{
if (batchNode)
{
batchNode->release();
batchNode = NULL;
}
}
void SubTest::initWithSubTest(int nSubTest, CCNode* p)
{
subtestNumber = nSubTest;
parent = p;
batchNode = NULL;
/*
* Tests:
* 1: 1 (32-bit) PNG sprite of 52 x 139
* 2: 1 (32-bit) PNG Batch Node using 1 sprite of 52 x 139
* 3: 1 (16-bit) PNG Batch Node using 1 sprite of 52 x 139
* 4: 1 (4-bit) PVRTC Batch Node using 1 sprite of 52 x 139
* 5: 14 (32-bit) PNG sprites of 85 x 121 each
* 6: 14 (32-bit) PNG Batch Node of 85 x 121 each
* 7: 14 (16-bit) PNG Batch Node of 85 x 121 each
* 8: 14 (4-bit) PVRTC Batch Node of 85 x 121 each
* 9: 64 (32-bit) sprites of 32 x 32 each
*10: 64 (32-bit) PNG Batch Node of 32 x 32 each
*11: 64 (16-bit) PNG Batch Node of 32 x 32 each
*12: 64 (4-bit) PVRTC Batch Node of 32 x 32 each
*/
// purge textures
CCTextureCache *mgr = CCTextureCache::sharedTextureCache();
// [mgr removeAllTextures];
mgr->removeTexture(mgr->addImage("Images/grossinis_sister1.png"));
mgr->removeTexture(mgr->addImage("Images/<API key>.png"));
mgr->removeTexture(mgr->addImage("Images/spritesheet1.png"));
switch ( subtestNumber)
{
case 1:
case 4:
case 7:
break;
case 2:
CCTexture2D::<API key>(<API key>);
batchNode = CCSpriteBatchNode::create("Images/grossinis_sister1.png", 100);
p->addChild(batchNode, 0);
break;
case 3:
CCTexture2D::<API key>(<API key>);
batchNode = CCSpriteBatchNode::create("Images/grossinis_sister1.png", 100);
p->addChild(batchNode, 0);
break;
case 5:
CCTexture2D::<API key>(<API key>);
batchNode = CCSpriteBatchNode::create("Images/<API key>.png", 100);
p->addChild(batchNode, 0);
break;
case 6:
CCTexture2D::<API key>(<API key>);
batchNode = CCSpriteBatchNode::create("Images/<API key>.png", 100);
p->addChild(batchNode, 0);
break;
case 8:
CCTexture2D::<API key>(<API key>);
batchNode = CCSpriteBatchNode::create("Images/spritesheet1.png", 100);
p->addChild(batchNode, 0);
break;
case 9:
CCTexture2D::<API key>(<API key>);
batchNode = CCSpriteBatchNode::create("Images/spritesheet1.png", 100);
p->addChild(batchNode, 0);
break;
default:
break;
}
if (batchNode)
{
batchNode->retain();
}
CCTexture2D::<API key>(<API key>);
}
CCSprite* SubTest::createSpriteWithTag(int tag)
{
// create
CCTexture2D::<API key>(<API key>);
CCSprite* sprite = NULL;
switch (subtestNumber)
{
case 1:
{
sprite = CCSprite::create("Images/grossinis_sister1.png");
parent->addChild(sprite, 0, tag+100);
break;
}
case 2:
case 3:
{
sprite = CCSprite::createWithTexture(batchNode->getTexture(), CCRectMake(0, 0, 52, 139));
batchNode->addChild(sprite, 0, tag+100);
break;
}
case 4:
{
int idx = (CCRAScutOM_0_1() * 1400 / 100) + 1;
char str[32] = {0};
sprintf(str, "Images/grossini_dance_%02d.png", idx);
sprite = CCSprite::create(str);
parent->addChild(sprite, 0, tag+100);
break;
}
case 5:
case 6:
{
int y,x;
int r = (CCRAScutOM_0_1() * 1400 / 100);
y = r / 5;
x = r % 5;
x *= 85;
y *= 121;
sprite = CCSprite::createWithTexture(batchNode->getTexture(), CCRectMake(x,y,85,121));
batchNode->addChild(sprite, 0, tag+100);
break;
}
case 7:
{
int y,x;
int r = (CCRAScutOM_0_1() * 6400 / 100);
y = r / 8;
x = r % 8;
char str[40] = {0};
sprintf(str, "Images/sprites_test/sprite-%d-%d.png", x, y);
sprite = CCSprite::create(str);
parent->addChild(sprite, 0, tag+100);
break;
}
case 8:
case 9:
{
int y,x;
int r = (CCRAScutOM_0_1() * 6400 / 100);
y = r / 8;
x = r % 8;
x *= 32;
y *= 32;
sprite = CCSprite::createWithTexture(batchNode->getTexture(), CCRectMake(x,y,32,32));
batchNode->addChild(sprite, 0, tag+100);
break;
}
default:
break;
}
CCTexture2D::<API key>(<API key>);
return sprite;
}
void SubTest::removeByTag(int tag)
{
switch (subtestNumber)
{
case 1:
case 4:
case 7:
parent->removeChildByTag(tag+100, true);
break;
case 2:
case 3:
case 5:
case 6:
case 8:
case 9:
batchNode-><API key>(tag, true);
// [batchNode removeChildByTag:tag+100 cleanup:YES];
break;
default:
break;
}
}
// SpriteMenuLayer
void SpriteMenuLayer::showCurrentTest()
{
SpriteMainScene* pScene = NULL;
SpriteMainScene* pPreScene = (SpriteMainScene*) getParent();
int nSubTest = pPreScene->getSubTestNum();
int nNodes = pPreScene->getNodesNum();
switch (m_nCurCase)
{
case 0:
pScene = new SpritePerformTest1;
break;
case 1:
pScene = new SpritePerformTest2;
break;
case 2:
pScene = new SpritePerformTest3;
break;
case 3:
pScene = new SpritePerformTest4;
break;
case 4:
pScene = new SpritePerformTest5;
break;
case 5:
pScene = new SpritePerformTest6;
break;
case 6:
pScene = new SpritePerformTest7;
break;
}
s_nSpriteCurCase = m_nCurCase;
if (pScene)
{
pScene->initWithSubTest(nSubTest, nNodes);
CCDirector::sharedDirector()->replaceScene(pScene);
pScene->release();
}
}
// SpriteMainScene
void SpriteMainScene::initWithSubTest(int asubtest, int nNodes)
{
//sraScutom(0);
subtestNumber = asubtest;
m_pSubTest = new SubTest;
m_pSubTest->initWithSubTest(asubtest, this);
CCSize s = CCDirector::sharedDirector()->getWinSize();
lastRenderedCount = 0;
quantityNodes = 0;
CCMenuItemFont::setFontSize(65);
CCMenuItemFont *decrease = CCMenuItemFont::create(" - ", this, menu_selector(SpriteMainScene::oScutecrease));
decrease->setColor(ccc3(0,200,20));
CCMenuItemFont *increase = CCMenuItemFont::create(" + ", this, menu_selector(SpriteMainScene::onIncrease));
increase->setColor(ccc3(0,200,20));
CCMenu *menu = CCMenu::create(decrease, increase, NULL);
menu-><API key>();
menu->setPosition(ccp(s.width/2, s.height-65));
addChild(menu, 1);
CCLabelTTF *infoLabel = CCLabelTTF::create("0 nodes", "Marker Felt", 30);
infoLabel->setColor(ccc3(0,200,20));
infoLabel->setPosition(ccp(s.width/2, s.height-90));
addChild(infoLabel, 1, kTagInfoLayer);
// add menu
SpriteMenuLayer* pMenu = new SpriteMenuLayer(true, TEST_COUNT, s_nSpriteCurCase);
addChild(pMenu, 1, kTagMenuLayer);
pMenu->release();
// Sub Tests
CCMenuItemFont::setFontSize(32);
CCMenu* pSubMenu = CCMenu::create();
for (int i = 1; i <= 9; ++i)
{
char str[10] = {0};
sprintf(str, "%d ", i);
CCMenuItemFont* itemFont = CCMenuItemFont::create(str, this, menu_selector(SpriteMainScene::testNCallback));
itemFont->setTag(i);
pSubMenu->addChild(itemFont, 10);
if( i<= 3)
itemFont->setColor(ccc3(200,20,20));
else if(i <= 6)
itemFont->setColor(ccc3(0,200,20));
else
itemFont->setColor(ccc3(0,20,200));
}
pSubMenu-><API key>();
pSubMenu->setPosition(ccp(s.width/2, 80));
addChild(pSubMenu, 2);
// add title label
CCLabelTTF *label = CCLabelTTF::create(title().c_str(), "Arial", 40);
addChild(label, 1);
label->setPosition(ccp(s.width/2, s.height-32));
label->setColor(ccc3(255,255,40));
while(quantityNodes < nNodes)
onIncrease(this);
}
std::string SpriteMainScene::title()
{
return "No title";
}
SpriteMainScene::~SpriteMainScene()
{
if (m_pSubTest)
{
delete m_pSubTest;
m_pSubTest = NULL;
}
}
void SpriteMainScene::testNCallback(CCObject* pSender)
{
subtestNumber = ((CCMenuItemFont*) pSender)->getTag();
SpriteMenuLayer* pMenu = (SpriteMenuLayer*)getChildByTag(kTagMenuLayer);
pMenu->restartCallback(pSender);
}
void SpriteMainScene::updateNodes()
{
if( quantityNodes != lastRenderedCount )
{
CCLabelTTF *infoLabel = (CCLabelTTF *) getChildByTag(kTagInfoLayer);
char str[16] = {0};
sprintf(str, "%u nodes", quantityNodes);
infoLabel->setString(str);
lastRenderedCount = quantityNodes;
}
}
void SpriteMainScene::onIncrease(CCObject* pSender)
{
if( quantityNodes >= kMaxNodes)
return;
for( int i=0;i< kNodesIncrease;i++)
{
CCSprite *sprite = m_pSubTest->createSpriteWithTag(quantityNodes);
doTest(sprite);
quantityNodes++;
}
updateNodes();
}
void SpriteMainScene::oScutecrease(CCObject* pSender)
{
if( quantityNodes <= 0 )
return;
for( int i=0;i < kNodesIncrease;i++)
{
quantityNodes
m_pSubTest->removeByTag(quantityNodes);
}
updateNodes();
}
// For test functions
void performanceActions(CCSprite* pSprite)
{
CCSize size = CCDirector::sharedDirector()->getWinSize();
pSprite->setPosition(ccp((raScut() % (int)size.width), (raScut() % (int)size.height)));
float period = 0.5f + (raScut() % 1000) / 500.0f;
CCRotateBy* rot = CCRotateBy::create(period, 360.0f * CCRAScutOM_0_1());
CCActionInterval* rot_back = rot->reverse();
CCAction *permanentRotation = CCRepeatForever::create(CCSequence::create(rot, rot_back, NULL));
pSprite->runAction(permanentRotation);
float growDuration = 0.5f + (raScut() % 1000) / 500.0f;
CCActionInterval *grow = CCScaleBy::create(growDuration, 0.5f, 0.5f);
CCAction *permanentScaleLoop = CCRepeatForever::create(CCSequence::create(grow, grow->reverse(), NULL));
pSprite->runAction(permanentScaleLoop);
}
void <API key>(CCSprite* pSprite)
{
CCSize size = CCDirector::sharedDirector()->getWinSize();
if( CCRAScutOM_0_1() < 0.2f )
pSprite->setPosition(ccp((raScut() % (int)size.width), (raScut() % (int)size.height)));
else
pSprite->setPosition(ccp( -1000, -1000));
float period = 0.5f + (raScut() % 1000) / 500.0f;
CCRotateBy* rot = CCRotateBy::create(period, 360.0f * CCRAScutOM_0_1());
CCActionInterval* rot_back = rot->reverse();
CCAction *permanentRotation = CCRepeatForever::create(CCSequence::create(rot, rot_back, NULL));
pSprite->runAction(permanentRotation);
float growDuration = 0.5f + (raScut() % 1000) / 500.0f;
CCActionInterval *grow = CCScaleBy::create(growDuration, 0.5f, 0.5f);
CCAction *permanentScaleLoop = CCRepeatForever::create(CCSequence::<API key>(grow, grow->reverse()));
pSprite->runAction(permanentScaleLoop);
}
void <API key>(CCSprite* pSprite)
{
CCSize size = CCDirector::sharedDirector()->getWinSize();
pSprite->setPosition(ccp((raScut() % (int)size.width), (raScut() % (int)size.height)));
pSprite->setRotation(CCRAScutOM_0_1() * 360);
pSprite->setScale(CCRAScutOM_0_1() * 2);
}
void performancePosition(CCSprite* pSprite)
{
CCSize size = CCDirector::sharedDirector()->getWinSize();
pSprite->setPosition(ccp((raScut() % (int)size.width), (raScut() % (int)size.height)));
}
void performanceout20(CCSprite* pSprite)
{
CCSize size = CCDirector::sharedDirector()->getWinSize();
if( CCRAScutOM_0_1() < 0.2f )
pSprite->setPosition(ccp((raScut() % (int)size.width), (raScut() % (int)size.height)));
else
pSprite->setPosition(ccp( -1000, -1000));
}
void performanceOut100(CCSprite* pSprite)
{
pSprite->setPosition(ccp( -1000, -1000));
}
void performanceScale(CCSprite* pSprite)
{
CCSize size = CCDirector::sharedDirector()->getWinSize();
pSprite->setPosition(ccp((raScut() % (int)size.width), (raScut() % (int)size.height)));
pSprite->setScale(CCRAScutOM_0_1() * 100 / 50);
}
// SpritePerformTest1
std::string SpritePerformTest1::title()
{
char str[32] = {0};
sprintf(str, "A (%d) position", subtestNumber);
std::string strRet = str;
return strRet;
}
void SpritePerformTest1::doTest(CCSprite* sprite)
{
performancePosition(sprite);
}
// SpritePerformTest2
std::string SpritePerformTest2::title()
{
char str[32] = {0};
sprintf(str, "B (%d) scale", subtestNumber);
std::string strRet = str;
return strRet;
}
void SpritePerformTest2::doTest(CCSprite* sprite)
{
performanceScale(sprite);
}
// SpritePerformTest3
std::string SpritePerformTest3::title()
{
char str[32] = {0};
sprintf(str, "C (%d) scale + rot", subtestNumber);
std::string strRet = str;
return strRet;
}
void SpritePerformTest3::doTest(CCSprite* sprite)
{
<API key>(sprite);
}
// SpritePerformTest4
std::string SpritePerformTest4::title()
{
char str[32] = {0};
sprintf(str, "D (%d) 100%% out", subtestNumber);
std::string strRet = str;
return strRet;
}
void SpritePerformTest4::doTest(CCSprite* sprite)
{
performanceOut100(sprite);
}
// SpritePerformTest5
std::string SpritePerformTest5::title()
{
char str[32] = {0};
sprintf(str, "E (%d) 80%% out", subtestNumber);
std::string strRet = str;
return strRet;
}
void SpritePerformTest5::doTest(CCSprite* sprite)
{
performanceout20(sprite);
}
// SpritePerformTest6
std::string SpritePerformTest6::title()
{
char str[32] = {0};
sprintf(str, "F (%d) actions", subtestNumber);
std::string strRet = str;
return strRet;
}
void SpritePerformTest6::doTest(CCSprite* sprite)
{
performanceActions(sprite);
}
// SpritePerformTest7
std::string SpritePerformTest7::title()
{
char str[32] = {0};
sprintf(str, "G (%d) actions 80%% out", subtestNumber);
std::string strRet = str;
return strRet;
}
void SpritePerformTest7::doTest(CCSprite* sprite)
{
<API key>(sprite);
}
void runSpriteTest()
{
SpriteMainScene* pScene = new SpritePerformTest1;
pScene->initWithSubTest(1, 50);
CCDirector::sharedDirector()->replaceScene(pScene);
pScene->release();
}
|
class SparseVector {
unordered_map<int, int> repr;
int size = 0;
public:
SparseVector(vector<int> &nums) {
size = nums.size();
for (int i=0; i<nums.size(); i++) {
if (nums[i] == 0) { continue; }
repr[i] = nums[i];
}
}
// Return the dotProduct of two sparse vectors
int dotProduct(SparseVector& vec) {
if (size != vec.size) {return 0;} // incompatible
int dp=0;
for (const auto& kv : vec.repr) {
if (repr.find(kv.first) == repr.end()) continue;
dp += kv.second * repr[kv.first];
}
return dp;
}
};
// Your SparseVector object will be instantiated and called as such:
// SparseVector v1(nums1);
// SparseVector v2(nums2);
// int ans = v1.dotProduct(v2);
|
# 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,
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# included in all copies or substantial portions of the Software.
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# 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.
"""Application configuration"""
from django.apps import AppConfig
class ShowcaseConfig(AppConfig):
name = 'mystartupmanager.showcase'
|
<?php
namespace Algolia\SearchBundle;
use Algolia\SearchBundle\TestApp\Entity\Comment;
use Algolia\SearchBundle\TestApp\Entity\Image;
use Algolia\SearchBundle\TestApp\Entity\Post;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\ConsoleOutput;
class BaseTest extends KernelTestCase
{
public function setUp(): void
{
self::bootKernel();
}
protected function createPost($id = null): Post
{
$post = new Post();
$post->setTitle('Test');
$post->setContent('Test content');
if (!is_null($id)) {
$post->setId($id);
}
return $post;
}
protected function <API key>(): SearchableEntity
{
$post = $this->createPost(random_int(100, 300));
return new SearchableEntity(
$this->getPrefix() . 'posts',
$post,
$this->get('doctrine')->getManager()->getClassMetadata(Post::class),
$this->get('serializer')
);
}
protected function createComment($id = null): Comment
{
$comment = new Comment();
$comment->setContent('Comment content');
$comment->setPost(new Post(['title' => 'What a post!', 'content' => 'my content']));
if (!is_null($id)) {
$comment->setId($id);
}
return $comment;
}
protected function createImage($id = null): Image
{
$image = new Image();
if (!is_null($id)) {
$image->setId($id);
}
return $image;
}
protected function <API key>(): SearchableEntity
{
$image = $this->createImage(random_int(100, 300));
return new SearchableEntity(
$this->getPrefix() . 'image',
$image,
$this->get('doctrine')->getManager()->getClassMetadata(Image::class),
null
);
}
protected function getPrefix(): ?string
{
return $this->get('search.service')->getConfiguration()['prefix'];
}
protected function get($id): ?object
{
return self::$kernel->getContainer()->get($id);
}
protected function refreshDb($application): void
{
$inputs = [
new ArrayInput([
'command' => 'doctrine:schema:drop',
'--full-database' => true,
'--force' => true,
'--quiet' => true,
]),
new ArrayInput([
'command' => 'doctrine:schema:create',
'--quiet' => true,
]),
];
$application->setAutoExit(false);
foreach ($inputs as $input) {
$application->run($input, new ConsoleOutput());
}
}
protected function getFileName($indexName, $type): string
{
return sprintf(
'%s/%s-%s.json',
$this->get('search.service')->getConfiguration()['settingsDirectory'],
$indexName,
$type
);
}
protected function getDefaultConfig(): array
{
return [
'hitsPerPage' => 20,
'maxValuesPerFacet' => 100,
];
}
}
|
module PrintSquare
class CommandRunner
class << self
def run(args)
validate_args(args)
print_square(args[0].to_i)
end
def print_square(number)
size = Math.sqrt(number).to_i
n = number
x = PrintSquare::Vector.new size.even? ? 1 : -1, size, size.even? ? 1 : 0
y = PrintSquare::Vector.new 0, size
print = PrintSquare::Printer.new size
x.turn = proc do
y.offset += 1 if x.direction == 1
y.direction = x.direction
x.direction = 0
end
y.turn = proc do
if y.direction == -1
x.size -= 1
y.size -= 1
x.offset += 1
end
x.direction = y.direction * -1
y.direction = 0
end
until n == 0
print.set x, y, n
y.direction == 0 ? x.next : y.next
n -= 1
end
print.out
end
def validate_args(args)
usage(:no_args) if args.count == 0
usage(:too_many_args) if args.count > 1
usage(:invalid_arg) unless (Integer(args[0]) rescue false)
usage(:not_square) unless is_square?(args[0].to_i)
end
def is_square?(number)
return true if number == 1
position = 2
spread = 1
until spread == 0
current_square = position*position
return true if current_square == number
if number < current_square
spread >>= 1
position -= spread
else
spread <<= 1
position += spread
end
end
false
end
def usage(error_type)
error = case error_type
when :no_args then 'Missing argument'
when :invalid_arg then 'Argument must be a number'
when :too_many_args then 'Too many arguments'
when :not_square then "Argument is not a square number"
end
puts <<-USAGE
#{error}
print_square [square_number]
USAGE
exit(-1)
end
end
end
end
|
package com.ripplargames.meshio.meshformats.ply;
import com.ripplargames.meshio.vertices.VertexType;
public class PlyVertexDataType {
private final VertexType vertexType;
private final PlyDataType plyDataType;
public PlyVertexDataType(VertexType vertexType, PlyDataType plyDataType) {
this.vertexType = vertexType;
this.plyDataType = plyDataType;
}
public VertexType vertexType() {
return vertexType;
}
public PlyDataType plyDataType() {
return plyDataType;
}
}
|
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- Begin Jekyll SEO tag v2.5.0 -->
<title>Jalil Butrón | Shanghai-based cinematographer</title>
<meta name="generator" content="Jekyll v3.7.4" />
<meta property="og:title" content="Jalil Butrón" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="Shanghai-based cinematographer" />
<meta property="og:description" content="Shanghai-based cinematographer" />
<link rel="canonical" href="http://localhost:4000/404.html" />
<meta property="og:url" content="http://localhost:4000/404.html" />
<meta property="og:site_name" content="Jalil Butrón" />
<script type="application/ld+json">
{"description":"Shanghai-based cinematographer","@type":"WebPage","url":"http:
<!-- End Jekyll SEO tag -->
<link rel="stylesheet" href="/assets/main.css"><link type="application/atom+xml" rel="alternate" href="http:
<link rel="shortcut icon" type="image/png" href="/assets/favicon.png">
<link rel="shortcut icon" sizes="196x196" href="/assets/favicon.png">
<link rel="apple-touch-icon" href="/assets/favicon.png">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="<API key>" crossorigin="anonymous">
</head>
<body>
<div class="body-container"><header class="site-header" role="banner">
<div class="wrapper"><div class="site-title">
<a rel="author" href="/">
<strong>Jalil Butrón</strong> <span>Cinematographer</span>
</a>
</div><nav class="site-nav">
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger">
<span class="menu-icon">
<svg viewBox="0 0 18 15" width="18px" height="15px">
<path d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0 h15.032C17.335,0,18,0.665,18,1.484L18,1.484z M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0 c0-0.82,0.665-1.484,1.484-1.484h15.032C17.335,6.031,18,6.696,18,7.516L18,7.516z M18,13.516C18,14.335,17.335,15,16.516,15H1.484 C0.665,15,0,14.335,0,13.516l0,0c0-0.82,0.665-1.483,1.484-1.483h15.032C17.335,12.031,18,12.695,18,13.516L18,13.516z"/>
</svg>
</span>
</label>
<div class="trigger"><a class="page-link" href="/stills/">Stills</a><a class="page-link" href="/contact">Contact</a></div>
</nav></div>
</header>
<main class="page-wrapper" aria-label="Content">
<div class="wrapper">
<style type="text/css" media="screen">
.container {
margin: 10px auto;
max-width: 600px;
text-align: center;
}
h1 {
margin: 30px 0;
font-size: 4em;
line-height: 1;
letter-spacing: -1px;
}
</style>
<div class="container">
<h1>404</h1>
<p><strong>Page not found :(</strong></p>
<p>The requested page could not be found.</p>
</div>
</div>
</main><footer class="site-footer h-card">
<data class="u-url" href="/"></data>
<div class="wrapper"><div class="footer-social">
<a class="no-underline" href="https://instagram.com/jalilbutron" target="_blank"><i class="fab fa-instagram fa-lg"></i></a>
<a class="no-underline" href="https://vimeo.com/jalilbutron" target="_blank"><i class="fab fa-vimeo-v fa-lg"></i></a>
</div><h5>
© Jalil Butrón. All rights reserved. 2020
</h5>
</div>
</footer>
</div>
<script>
</script>
</body>
</html>
|
require 'multi_xml'
require 'ostruct'
require 'roxml'
module WxHelper
module XmlHelper
class Message
def initialize(xml)
hash = parse_xml xml
@source = OpenStruct.new(hash['xml'])
end
def method_missing(method, *args, &block)
@source.send(method.to_s.classify, *args, &block)
end
def parse_xml xml
MultiXml.parse(xml)
end
end
# <xml>
# <AppId><![CDATA[wwwwb4f85f3a797777]]></AppId>
# <TimeStamp> 1369745073</TimeStamp>
# <NonceStr><![CDATA[<API key>]]></NonceStr>
# <RetCode>0</RetCode>
# <RetErrMsg><![CDATA[ok]]></ RetErrMsg>
# <AppSignature><![CDATA[<SHA1-like>]]>
# </AppSignature>
# <SignMethod><![CDATA[sha1]]></ SignMethod >
# </xml>
PackageMessage = Class.new(Message)
# <xml>
# <OpenId><![CDATA[111222]]></OpenId>
# <AppId><![CDATA[wwwwb4f85f3a797777]]></AppId>
# <IsSubscribe>1</IsSubscribe>
# <TimeStamp> 1369743511</TimeStamp>
# <NonceStr><![CDATA[jALldRTHAFd5Tgs5]]></NonceStr>
# <AppSignature><![CDATA[<SHA1-like>]]>
# </AppSignature>
# <SignMethod><![CDATA[sha1]]></ SignMethod >
# </xml>
NotifyMessage = Class.new(Message)
# <xml>
# <OpenId><![CDATA[111222]]></OpenId>
# <AppId><![CDATA[wwwwb4f85f3a797777]]></AppId>
# <TimeStamp> 1369743511</TimeStamp>
# <MsgType><![CDATA[request]]></MsgType>
# <FeedBackId><![CDATA[5883726847655944563]]></FeedBackId>
# <TransId><![CDATA[<API key>]]></TransId>
# <Reason><![CDATA[]]></Reason>
# <Solution><![CDATA[]]></Solution>
# <ExtInfo><![CDATA[ 18610847266]]></ExtInfo>
# <AppSignature><![CDATA[<SHA1-like>]]>
# </AppSignature>
# <SignMethod><![CDATA[sha1]]></ SignMethod >
# </xml>
# <xml>
# <OpenId><![CDATA[111222]]></OpenId>
# <AppId><![CDATA[wwwwb4f85f3a797777]]></AppId>
# <TimeStamp> 1369743511</TimeStamp>
# <MsgType><![CDATA[confirm/reject]]></MsgType>
# <FeedBackId><![CDATA[5883726847655944563]]></FeedBackId>
# <Reason><![CDATA[]]></Reason>
# <AppSignature><![CDATA[<SHA1-like>]]>
# </AppSignature>
# <SignMethod><![CDATA[sha1]]></ SignMethod >
# </xml>
PayFeedbackMessage = Class.new(Message)
# <xml>
# <AppId><![CDATA[wxf8b4f85f3a794e77]]></AppId>
# <ErrorType>1001</ErrorType>
# <Description><![CDATA[]]></Description>
# <AlarmContent><![CDATA[]]></AlarmContent>
# <TimeStamp>1393860740</TimeStamp>
# <AppSignature><![CDATA[<SHA1-like>]]></AppSignature>
# <SignMethod><![CDATA[sha1]]></SignMethod>
# </xml>
WarningMessage = Class.new(Message)
class ResponseMessage
include ROXML
xml_name :xml
xml_convention :camelcase
xml_accessor :app_id, :cdata => true
xml_accessor :package, :cdata => true
xml_accessor :nonce_str, :cdata => true
xml_accessor :ret_err_msg, :cdata => true
xml_accessor :app_signature, :cdata => true
xml_accessor :sign_method, :cdata => true
xml_accessor :time_stamp, :as => Integer
xml_accessor :ret_code, :as => Integer
def initialize
@sign_method = "sha1"
end
def to_xml
super.to_xml(:encoding => 'UTF-8', :indent => 0, :save_with => 0)
end
end
end
end
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>qarith: Not compatible </title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.5.0 / qarith - 8.9.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
qarith
<small>
8.9.0
<span class="label label-info">Not compatible </span>
</small>
</h1>
<p> <em><script>document.write(moment("2022-01-13 20:16:59 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-13 20:16:59 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 <API key> of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 1 Virtual package relying on perl
coq 8.5.0 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.03.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.03.0 Official 4.03.0 release
ocaml-config 1 OCaml Switch Configuration
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/qarith"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/QArith"]
depends: [
"ocaml"
"coq" {>= "8.9" & < "8.10~"}
]
tags: [
"keyword: Q"
"keyword: arithmetic"
"keyword: rational numbers"
"keyword: setoid"
"keyword: ring"
"category: Mathematics/Arithmetic and Number Theory/Rational numbers"
"category: Miscellaneous/Extracted Programs/Arithmetic"
]
authors: [
"Pierre Letouzey"
]
bug-reports: "https://github.com/coq-contribs/qarith/issues"
dev-repo: "git+https://github.com/coq-contribs/qarith.git"
synopsis: "A Library for Rational Numbers (QArith)"
description: """
This contribution is a proposition of a library formalizing
rational number in Coq."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/qarith/archive/v8.9.0.tar.gz"
checksum: "md5=<API key>"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install </h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-qarith.8.9.0 coq.8.5.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.5.0).
The following dependencies couldn't be met:
- coq-qarith -> coq >= 8.9 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-qarith.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install </h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https:
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mathcomp-finmap: Not compatible </title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / extra-dev</a></li>
<li class="active"><a href="">dev / mathcomp-finmap - 1.3.1</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
mathcomp-finmap
<small>
1.3.1
<span class="label label-info">Not compatible </span>
</small>
</h1>
<p> <em><script>document.write(moment("2022-01-20 06:05:22 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-20 06:05:22 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 3 Virtual package relying on a GMP lib system installation
coq dev Formal proof management system
dune 2.9.1 Fast, portable, and opinionated build system
ocaml 4.10.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.10.2 Official release 4.10.2
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.1 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Cyril Cohen <cyril.cohen@inria.fr>"
homepage: "https://github.com/math-comp/finmap"
bug-reports: "https://github.com/math-comp/finmap/issues"
dev-repo: "git+https://github.com/math-comp/finmap.git"
license: "CeCILL-B"
build: [ make "-j" "%{jobs}%" ]
install: [ make "install" ]
depends: [
"coq" { (>= "8.7" & < "8.11~") }
"<API key>" { (>= "1.8.0" & < "1.10~") }
"<API key>" { (>= "1.0.0" & < "1.1~") }
]
tags: [ "keyword:finmap" "keyword:finset" "keyword:multiset" "keyword:order" "date:2019-06-13" "logpath:mathcomp.finmap"]
authors: [ "Cyril Cohen <cyril.cohen@inria.fr>" "Kazuhiko Sakaguchi <sakaguchi@coins.tsukuba.ac.jp>" ]
synopsis: "Finite sets, finite maps, finitely supported functions, orders"
description: """
This library is an extension of mathematical component in order to
support finite sets and finite maps on choicetypes (rather that finite
types). This includes support for functions with finite support and
multisets. The library also contains a generic order and set libary,
which will be used to subsume notations for finite sets, eventually."""
url {
src: "https://github.com/math-comp/finmap/archive/1.3.1.tar.gz"
checksum: "sha256=<SHA256-like>"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install </h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-mathcomp-finmap.1.3.1 coq.dev</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is dev).
The following dependencies couldn't be met:
- coq-mathcomp-finmap -> coq < 8.11~ -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-finmap.1.3.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install </h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https:
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using P03_FootballBetting.Data.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace P03_FootballBetting.Data.<API key>
{
public class PositionConfig : <API key><Position>
{
public void Configure(EntityTypeBuilder<Position> builder)
{
builder.Property(x => x.Name)
.IsRequired()
.IsUnicode();
builder.HasMany(x => x.Players)
.WithOne(x => x.Position)
.HasForeignKey(x => x.PositionId);
}
}
}
|
#ifndef <API key>
#define <API key>
#include <string>
#include <vector>
namespace CoreLib {
class Compression;
}
class CoreLib::Compression
{
public:
typedef std::vector<char> Buffer;
public:
enum class Algorithm : unsigned char {
Zlib,
Gzip,
Bzip2
};
public:
static void Compress(const char *data, const size_t size,
Buffer &<API key>,
const Algorithm &algorithm);
static void Compress(const std::string &dataString,
Buffer &<API key>,
const Algorithm &algorithm);
static void Compress(const Buffer &dataBuffer,
Buffer &<API key>,
const Algorithm &algorithm);
static void Decompress(const Buffer &dataBuffer,
std::string &<API key>,
const Algorithm &algorithm);
static void Decompress(const Buffer &dataBuffer,
Buffer &<API key>,
const Algorithm &algorithm);
};
#endif /* <API key> */
|
# v0.6.10
* Original: [Release atom-shell v0.6.10 - electron/electron](https://github.com/electron/electron/releases/tag/v0.6.10)
Changelog:
* Build binary for Mac on OS X 10.8.5.
* OS X 10.8.5 Mac
* Mountain Lion
* Fix a possible dead lock when quitting.
*
*
* Enable setting window icons when creating window.
*
* Electron v0.6.9
|
import asyncio
import email.utils
import json
import sys
from cgi import parse_header
from collections import namedtuple
from http.cookies import SimpleCookie
from urllib.parse import parse_qs, unquote, urlunparse
from httptools import parse_url
from sanic.exceptions import InvalidUsage
from sanic.log import error_logger, logger
try:
from ujson import loads as json_loads
except ImportError:
if sys.version_info[:2] == (3, 5):
def json_loads(data):
# on Python 3.5 json.loads only supports str not bytes
return json.loads(data.decode())
else:
json_loads = json.loads
<API key> = "application/octet-stream"
# > If the media type remains unknown, the recipient SHOULD treat it
# > as type "application/octet-stream"
class RequestParameters(dict):
"""Hosts a dict with lists as values where get returns the first
value of the list and getlist returns the whole shebang
"""
def get(self, name, default=None):
"""Return the first value, either the default or actual"""
return super().get(name, [default])[0]
def getlist(self, name, default=None):
"""Return the entire list"""
return super().get(name, default)
class StreamBuffer:
def __init__(self, buffer_size=100):
self._queue = asyncio.Queue(buffer_size)
async def read(self):
""" Stop reading when gets None """
payload = await self._queue.get()
self._queue.task_done()
return payload
async def put(self, payload):
await self._queue.put(payload)
def is_full(self):
return self._queue.full()
class Request(dict):
"""Properties of an HTTP request such as URL, headers, etc."""
__slots__ = (
"__weakref__",
"_cookies",
"_ip",
"_parsed_url",
"_port",
"_remote_addr",
"_socket",
"app",
"body",
"endpoint",
"headers",
"method",
"parsed_args",
"parsed_files",
"parsed_form",
"parsed_json",
"raw_url",
"stream",
"transport",
"uri_template",
"version",
)
def __init__(self, url_bytes, headers, version, method, transport):
self.raw_url = url_bytes
# TODO: Content-Encoding detection
self._parsed_url = parse_url(url_bytes)
self.app = None
self.headers = headers
self.version = version
self.method = method
self.transport = transport
# Init but do not inhale
self.body_init()
self.parsed_json = None
self.parsed_form = None
self.parsed_files = None
self.parsed_args = None
self.uri_template = None
self._cookies = None
self.stream = None
self.endpoint = None
def __repr__(self):
return "<{0}: {1} {2}>".format(
self.__class__.__name__, self.method, self.path
)
def __bool__(self):
if self.transport:
return True
return False
def body_init(self):
self.body = []
def body_push(self, data):
self.body.append(data)
def body_finish(self):
self.body = b"".join(self.body)
@property
def json(self):
if self.parsed_json is None:
self.load_json()
return self.parsed_json
def load_json(self, loads=json_loads):
try:
self.parsed_json = loads(self.body)
except Exception:
if not self.body:
return None
raise InvalidUsage("Failed when parsing body as json")
return self.parsed_json
@property
def token(self):
"""Attempt to return the auth header token.
:return: token related to request
"""
prefixes = ("Bearer", "Token")
auth_header = self.headers.get("Authorization")
if auth_header is not None:
for prefix in prefixes:
if prefix in auth_header:
return auth_header.partition(prefix)[-1].strip()
return auth_header
@property
def form(self):
if self.parsed_form is None:
self.parsed_form = RequestParameters()
self.parsed_files = RequestParameters()
content_type = self.headers.get(
"Content-Type", <API key>
)
content_type, parameters = parse_header(content_type)
try:
if content_type == "application/<API key>":
self.parsed_form = RequestParameters(
parse_qs(self.body.decode("utf-8"))
)
elif content_type == "multipart/form-data":
# TODO: Stream this instead of reading to/from memory
boundary = parameters["boundary"].encode("utf-8")
self.parsed_form, self.parsed_files = <API key>(
self.body, boundary
)
except Exception:
error_logger.exception("Failed when parsing form")
return self.parsed_form
@property
def files(self):
if self.parsed_files is None:
self.form # compute form to get files
return self.parsed_files
@property
def args(self):
if self.parsed_args is None:
if self.query_string:
self.parsed_args = RequestParameters(
parse_qs(self.query_string)
)
else:
self.parsed_args = RequestParameters()
return self.parsed_args
@property
def raw_args(self):
return {k: v[0] for k, v in self.args.items()}
@property
def cookies(self):
if self._cookies is None:
cookie = self.headers.get("Cookie")
if cookie is not None:
cookies = SimpleCookie()
cookies.load(cookie)
self._cookies = {
name: cookie.value for name, cookie in cookies.items()
}
else:
self._cookies = {}
return self._cookies
@property
def ip(self):
if not hasattr(self, "_socket"):
self._get_address()
return self._ip
@property
def port(self):
if not hasattr(self, "_socket"):
self._get_address()
return self._port
@property
def socket(self):
if not hasattr(self, "_socket"):
self._get_address()
return self._socket
def _get_address(self):
self._socket = self.transport.get_extra_info("peername") or (
None,
None,
)
self._ip = self._socket[0]
self._port = self._socket[1]
@property
def remote_addr(self):
"""Attempt to return the original client ip based on X-Forwarded-For.
:return: original client ip.
"""
if not hasattr(self, "_remote_addr"):
forwarded_for = self.headers.get("X-Forwarded-For", "").split(",")
remote_addrs = [
addr
for addr in [addr.strip() for addr in forwarded_for]
if addr
]
if len(remote_addrs) > 0:
self._remote_addr = remote_addrs[0]
else:
self._remote_addr = ""
return self._remote_addr
@property
def scheme(self):
if (
self.app.websocket_enabled
and self.headers.get("upgrade") == "websocket"
):
scheme = "ws"
else:
scheme = "http"
if self.transport.get_extra_info("sslcontext"):
scheme += "s"
return scheme
@property
def host(self):
# it appears that httptools doesn't return the host
# so pull it from the headers
return self.headers.get("Host", "")
@property
def content_type(self):
return self.headers.get("Content-Type", <API key>)
@property
def match_info(self):
"""return matched info after resolving route"""
return self.app.router.get(self)[2]
@property
def path(self):
return self._parsed_url.path.decode("utf-8")
@property
def query_string(self):
if self._parsed_url.query:
return self._parsed_url.query.decode("utf-8")
else:
return ""
@property
def url(self):
return urlunparse(
(self.scheme, self.host, self.path, None, self.query_string, None)
)
File = namedtuple("File", ["type", "body", "name"])
def <API key>(body, boundary):
"""Parse a request body and returns fields and files
:param body: bytes request body
:param boundary: bytes multipart boundary
:return: fields (RequestParameters), files (RequestParameters)
"""
files = RequestParameters()
fields = RequestParameters()
form_parts = body.split(boundary)
for form_part in form_parts[1:-1]:
file_name = None
content_type = "text/plain"
content_charset = "utf-8"
field_name = None
line_index = 2
line_end_index = 0
while not line_end_index == -1:
line_end_index = form_part.find(b"\r\n", line_index)
form_line = form_part[line_index:line_end_index].decode("utf-8")
line_index = line_end_index + 2
if not form_line:
break
colon_index = form_line.index(":")
form_header_field = form_line[0:colon_index].lower()
form_header_value, form_parameters = parse_header(
form_line[colon_index + 2 :]
)
if form_header_field == "content-disposition":
field_name = form_parameters.get("name")
file_name = form_parameters.get("filename")
# non-ASCII filenames in RFC2231, "filename*" format
if file_name is None and form_parameters.get("filename*"):
encoding, _, value = email.utils.decode_rfc2231(
form_parameters["filename*"]
)
file_name = unquote(value, encoding=encoding)
elif form_header_field == "content-type":
content_type = form_header_value
content_charset = form_parameters.get("charset", "utf-8")
if field_name:
post_data = form_part[line_index:-4]
if file_name is None:
value = post_data.decode(content_charset)
if field_name in fields:
fields[field_name].append(value)
else:
fields[field_name] = [value]
else:
form_file = File(
type=content_type, name=file_name, body=post_data
)
if field_name in files:
files[field_name].append(form_file)
else:
files[field_name] = [form_file]
else:
logger.debug(
"Form-data field does not have a 'name' parameter "
"in the Content-Disposition header"
)
return fields, files
|
require 'stringio'
require 'highline/import'
module RailsZen
class ChosenAttr
attr_accessor :name, :type, :validator, :<API key>, :scope_attr
def initialize(name, type)
@name = name
@type = type
@scope_attr = []
end
def get_user_inputs
get_presence_req
<API key>
end
def get_presence_req
say "\n\nShould :#{name} be present always in your record?\n"
say"
inp = agree("Reply with y or n")
if inp
@validator = "<API key>"
#say "What should be the default value? If there is no default value enter n"
#val = $stdin.gets.strip
#if val != 'n'
#@default_value = val
#end
get_uniqueness_req
else
@validator = nil
end
end
def get_uniqueness_req
say "Should :#{name} be an unique column?\n"
say "
say "Reply with \n
0 if it is not unique \n
1 if it is just unique \n
2 if it is unique with respect to another attr \n\n"
inp = ask("Please enter", Integer) { |q| q.in = 0..2 }
if inp == 2
#say "Setting presence true in your models and migrations"
say "\n#{name} is unique along with ?\n Reply with attr name\n "
if is_relation?
@scope_attr << "#{name}_id" unless name.end_with? "_id"
end
say("if it is a relation reply along with id: eg: user_id \n\n $->")
@scope_attr << ask("Enter (comma sep list) ", lambda { |str| str.split(/,\s*/) })
@scope_attr = @scope_attr.flatten.map(&:to_sym)
@validator = "<API key>"
elsif inp == 1
@validator = "<API key>"
end
end
def <API key>
if(type == "integer" || type == "decimal")
@validator_line = "#@validator_line, numericality: true"
say "#{name} is an integer do you want to check \n
1 just the numericality? \n
2 check if it is only integer\n\n $->
"
input = ask("Please enter", Integer) { |q| q.in = 1..2}
map_input = {
1 => "<API key>", 2 => "validate_integer"
#"3" => "<API key>", "4" => "<API key>"
}
@<API key> = map_input[input]
elsif(is_relation?)
@<API key> = "validate_belongs_to"
end
end
def is_relation?
type =="belongs_to" || type == "references" || (type.end_with? "_id")
end
end
end
|
# <API key>: true
RSpec::Matchers.define :<API key> do
expected_error =
{ 'error' => 'User is not authorized to access this resource.' }
match do |actual|
expect(actual).to have_http_status(403)
expect(JSON.parse(actual.body)).to eq(expected_error)
end
failure_message do |actual|
"expected to receive 403 status code (forbidden) and '#{expected_error}' " \
"as the response body. Received #{actual.status} status and "\
"'#{JSON.parse(actual.body)}' response body instead."
end
<API key> do
"expected not to receive 403 status (forbidden) or '#{expected_error}' "\
'in the response body, but it did.'
end
description do
'enforce authorization policies when accessing API resources.'
end
end
|
from .tile import Split, Stack, TileStack
class Tile(Split):
class left(Stack):
weight = 3
priority = 0
limit = 1
class right(TileStack):
pass
class Max(Split):
class main(Stack):
tile = False
class InstantMsg(Split):
class left(TileStack): # or maybe not tiled ?
weight = 3
class roster(Stack):
limit = 1
priority = 0 # probably roster created first
class Gimp(Split):
class toolbox(Stack):
limit = 1
size = 184
class main(Stack):
weight = 4
priority = 0
class dock(Stack):
limit = 1
size = 324
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BookReviews.UI.Saga
{
public class <API key> :
SagaStateMachine<<API key>>, ISaga
{
static <API key>()
{
Define(Saga);
}
private static void Saga()
{
Correlate(RequestReceived)
.By((saga, message) => saga.CustomerId == message.CustomerId &&
saga.OrderId == message.OrderId &&
saga.CurrentState == WaitingForResponse);
Correlate(ResponseReceived)
.By((saga, message) => saga.CustomerId == message.CustomerId &&
saga.OrderId == message.OrderId &&
saga.CurrentState == WaitingForResponse);
public static State Initial { get; set; }
public static State WaitingForResponse { get; set; }
public static State Completed { get; set; }
public static Event<<API key>> RequestReceived { get; set; }
public static Event<<API key>> ResponseReceived { get; set; }
public static Event<<API key>> RequestFailed { get; set; }
Initially(
When(RequestReceived)
.Then((saga, request) =>
{
saga.OrderId = request.OrderId;
saga.CustomerId = request.CustomerId;
})
.Publish((saga, request) => new <API key>
{
RequestId = saga.CorrelationId,
CustomerId = saga.CustomerId,
OrderId = saga.OrderId,
})
.TransitionTo(WaitingForResponse));
During(WaitingForResponse,
When(ResponseReceived)
.Then((saga, response) =>
{
saga.OrderCreated = response.Created;
saga.OrderStatus = response.Status;
})
.Publish((saga, request) => new OrderDetails
{
CustomerId = saga.CustomerId,
OrderId = saga.OrderId,
Created = saga.OrderCreated.Value,
Status = saga.OrderStatus,
})
.TransitionTo(Completed));
}
public <API key>(Guid correlationId)
{
CorrelationId = correlationId;
}
protected <API key>()
{
}
public virtual string CustomerId { get; set; }
public virtual string OrderId { get; set; }
public virtual OrderStatus OrderStatus { get; set; }
public virtual DateTime? OrderCreated { get; set; }
public virtual Guid CorrelationId { get; set; }
public virtual IServiceBus Bus { get; set; }
}
//The rest of the saga class is shown above for completeness.
//The properties are part of the saga and get saved when the saga is persisted
//(using the NHibernate saga persister, or in the case of the sample the in-memory implementation).
//The constructor with the Guid is used to initialize the saga when a new one is created,
//the protected one is there for NHibernate to be able to persist the saga.
}
}
|
ActiveRecord::Schema.define(:version => 1) do
create_table :notes, :force => true do |t|
t.string :title
t.text :body
end
end
|
var coords;
var directionsDisplay;
var map;
var travelMode;
var travelModeElement = $('#mode_travel');
// Order of operations for the trip planner (each function will have detailed notes):
// 1) Calculate a user's route, with directions.
// 2) Run a query using the route's max and min bounds to narrow potential results.
// 3) Just because a marker is in the area of the route, it doesn't mean that it's on the route.
// Use RouteBoxer to map sections of the route to markers, if applicable. Display only those markers on the map.
// 4) The directions panel also isn't linked to a section of the route.
// Use RouteBoxer to map a direction (turn left, right, etc) to part of the route.
// 5) Build the custom directions panel by looping though each leg of the trip, finding the corresponding RouteBoxer
// section, and use that to get markers for that section only.
$(document).ready(function () {
$('.active').toggleClass('active');
$('#trip-planner').toggleClass('active');
});
// Run these functions after setting geolocation. All except setFormDateTime() are dependent on geolocation to run.
initGeolocation().then(function (coords) {
map = mapGenerator(coords);
<API key>(map);
formListener();
});
// Instantiate directions methods on map.
function <API key>(map) {
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
}
// Listener for if the mode of travel is changed from an empty default to either bicycling or walking.
function formListener() {
travelModeElement.change(function(){
// Launch route calculation, markers, and directions panel.
calcRoute();
});
}
// Once the mode of travel is selected, start calculating routes and get marker data.
function calcRoute() {
var directionsService = new google.maps.DirectionsService();
var start = $('#start').val();
var end = $('#end').val();
travelMode = travelModeElement.val();
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode[travelMode]
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
// Remove existing markers from the map and map object.
removeMarkers(true);
queryResults = getMarkers(response);
// Check if results are along the route.
if (queryResults.objects.length > 0) {
// Filter the query results further by comparing coords with each route section.
narrowResults(queryResults.objects, response);
// If no query results, set the marker count to 0 and generate the directions panel.
} else {
response.routes[0].legs[0]['marker_count'] = 0;
<API key>(response);
}
}
});
}
// Get markers near a route. This is done by getting the boundaries for the route as a whole and using those
// as query params.
function getMarkers(response){
var userType;
if (travelMode == "BICYCLING") {
userType = 1;
} else {
userType = 2;
}
// Build the query string, limiting the results for cyclists and pedestrians.
var queryString = '/api/v1/hazard/?format=json&?user_type=' + userType;
// Get the maximum and minimum lat/lon bounds for the route.
// This will narrow the query to a box around the route as a whole.
var routeBounds = getBounds(response.routes[0].bounds);
// TODO(zemadi): Look up alternatives for building the querystring.
//Build the querystring. Negative numbers require different greater/less than logic,
// so testing for that here.
if (routeBounds.lat1 >= 0 && routeBounds.lat2 >= 0) {
queryString += '&lat__gte=' + routeBounds.lat1 + '&lat__lte=' + routeBounds.lat2;
} else {
queryString += '&lat__gte=' + routeBounds.lat2 + '&lat__lte=' + routeBounds.lat1;
}
if (routeBounds.lon1 >= 0 && routeBounds.lon2 >= 0) {
queryString += '&lon__gte=' + routeBounds.lon1 + '&lon__lte=' + routeBounds.lon2;
} else {
queryString += '&lon__gte=' + routeBounds.lon2 + '&lon__lte=' + routeBounds.lon1;
}
return httpGet(queryString);
}
// Function to get coordinate boundaries from the Directions route callback.
function getBounds(data) {
var coordinateBounds = {};
var keyByIndex = Object.keys(data);
coordinateBounds['lat1'] = data[keyByIndex[0]]['k'];
coordinateBounds['lat2'] = data[keyByIndex[0]]['j'];
coordinateBounds['lon1'] = data[keyByIndex[1]]['k'];
coordinateBounds['lon2'] = data[keyByIndex[1]]['j'];
return coordinateBounds;
}
// Reduce the query results further by checking if they're actually along a route.
// In order for a data point to be on the route, the coordinates need to be between the values of a box in routeBoxer.
// RouteBoxer chops up a route into sections and returns the upper and lower boundaries for that section of the route.
function narrowResults(queryResults, directionsResponse) {
// Variables needed for routeBoxer.
var path = directionsResponse.routes[0].overview_path;
var rboxer = new RouteBoxer();
var boxes = rboxer.box(path, .03); // Second param is a boundary in km from the route path.
//Variables to hold mapData and match a marker to a specific section of the route.
var mapData = {'objects': []};
// Object to hold routeBoxer index to markers map.
var mapBoxesAndMarkers = {};
// For each section of the route, look through markers to see if any fit in the section's boundaries.
// Using a for loop here because routeBoxer returns an array.
for (var j = 0, b=boxes.length; j < b; j++) {
// For each section of the route, record the index as a key and create an empty array to hold marker values.
mapBoxesAndMarkers[j] = [];
queryResults.forEach(function(result) {
// If a marker is between the latitude and longitude bounds of the route, add it to the map and
// the route-marker dict.
var currentResult = new google.maps.LatLng(result.lat, result.lon);
if (boxes[j].contains(currentResult)) {
mapData.objects.push(result);
mapBoxesAndMarkers[j].push(result);
}
});
}
if (mapData.objects.length > 0) {
// Add new markers to the map.
markerGenerator(map, mapData);
// Add the count of valid markers to the directionsResponse object, which is used to generate
// the directions panel. If there are no markers, add 'None'.
directionsResponse.routes[0].legs[0]['marker_count'] = mapData.objects.length;
} else {
directionsResponse.routes[0].legs[0]['marker_count'] = 'None';
}
<API key>(boxes, directionsResponse, mapBoxesAndMarkers);
}
// Directions information also needs to be mapped to a section of the route.
function <API key>(boxes, directionsResponse, mapBoxesAndMarkers){
var directions = directionsResponse.routes[0].legs[0].steps;
// go through each step and set of lat lngs per step.
directions.forEach(function(direction) {
var <API key> = [];
for (var l = 0, b=boxes.length; l < b; l++) {
direction.lat_lngs.forEach(function(lat_lng) {
// If the index isn't already in the array and the box contains the current route's lat and long, add the
// index.
if (<API key>.indexOf(l) === -1 && boxes[l].contains(lat_lng)) {
<API key>.push(l);
}
});
}
// Once we're done looping over route boxes for the current direction, lookup markers that have the same bounds.
// A direction can have multiple route boxes so a list is being used here.
direction['markers'] = [];
<API key>.forEach(function(box) {
if (mapBoxesAndMarkers[box].length > 0) {
// Use the route box to look up arrays of markers to add to the directions object.
direction['markers'].push.apply(direction['markers'], mapBoxesAndMarkers[box]);
}
});
});
<API key>(directionsResponse);
}
function <API key>(directionsResponse) {
var directionsPanel = $('#directions-panel');
var directionsPanelHtml = $('#<API key>').html();
var newSearchTrigger = $('#new-search-trigger');
var template = Handlebars.compile(directionsPanelHtml);
var <API key> = template(directionsResponse.routes[0].legs[0]);
if (directionsPanel[0].children.length > 0) {
directionsPanel[0].innerHTML = <API key>;
} else {
directionsPanel.append(<API key>);
}
// Close the trip planner form and display the directions panel.
$('#trip-planner-form').addClass('closed');
directionsPanel.removeClass('closed');
newSearchTrigger.removeClass('hidden');
// Listen for a new search event, which shows the form and closes the directions panel.
newSearchTrigger.click(function(){
directionsPanel.addClass('closed');
newSearchTrigger.addClass('hidden');
$('#trip-planner-form').removeClass('closed');
});
}
|
define(['backbone', 'marionette', 'mustache', 'jquery', 'text!templates/ctrldialog.html'],
function(Backbone, Marionette, Mustache, $, template) {
return Marionette.ItemView.extend({
initialize: function(options) {
if (!options.icon_name) {
options.icon_name = 'bird';
}
this.model = new Backbone.Model( options );
this.render();
},
template: function(serialized_model) {
return Mustache.render(template, serialized_model);
},
ui: {
'ok': '.btn-ok',
'cancel': '.btn-cancel',
'dialog': '.dialog',
'close': '.dialog-close'
},
events: {
'tap @ui.ok': 'onOk',
'tap @ui.cancel': 'onCancel',
'tap @ui.close': 'onCancel'
},
onOk: function(ev) {
this.trigger('ok');
this.destroy();
},
onCancel: function(ev) {
this.trigger('cancel');
this.destroy();
},
onRender: function() {
$('body').append(this.$el);
this.ui.dialog.css({
'marginTop': 0 - this.ui.dialog.height()/2
});
this.ui.dialog.addClass('bounceInDown animated');
},
onDestory: function() {
this.$el.remove();
this.model.destroy();
},
className: 'dialogContainer'
});
});
|
export * from './alert.service';
export * from './authentication.service';
export * from './user.service';
export * from './serviceRequest.service';
|
title: play on playa (part deux)
date: 2007-01-14 00:00:00 Z
permalink: "/2007/01/14/<API key>/"
categories:
- Baby E
- Uncategorized
author: Jennifer
layout: post
Yes, we had a fun filled [play date](http:
<img id="image115" alt="pod_011207.jpg" src="http://static.squarespace.com/static/<API key>/<API key>/<API key>/1168806613000/?format=original" />
|
import { <API key> } from '../errors/<API key>';
import { NotImplementedError } from '../errors/NotImplementedError';
import mustache from 'mustache';
import '../utils/Function';
// The base class for a control
export class Control {
// The constructor of a control
// id: The id of the control
// template: The template used for rendering the control
// localCSS: An object whose properties are CSS class names and whose values are the localized CSS class names
// The control will change the matching CSS class names in the templates.
constructor(id, template, localCSS) {
if (typeof id !== 'string' || !isNaN(id)) {
throw new <API key>('Cannot create the control because the id is not a string');
}
if (id.length < 1) {
throw new <API key>('Cannot create the control because the id is not a non-empty string');
}
if (null === template || undefined === template) {
throw new <API key>('Cannot create the control because the template cannot be null or undefined');
}
if (typeof template !== 'string') {
throw new <API key>('Cannot create the control because the template is not a string');
}
this.id = id;
this.template = template;
if (template && localCSS) {
// localize the CSS class names in the templates
for (const oCN in localCSS) {
const nCN = localCSS[oCN];
this.template = this.template
.replace(new RegExp(`class="${oCN}"`, 'gi'), `class="${nCN}"`)
.replace(new RegExp(`class='${oCN}'`, 'gi'), `class='${nCN}'`);
}
}
this.controls = {};
}
// Adds a child control to the control
// control: The Control instance
addControl(control) {
if (!(control instanceof Control)) {
throw new <API key>('Cannot add sub-control because it is invalid');
}
this.controls[control.id] = control;
}
// Removes a child control from the control
// val: Either a controlId or a Control instance
removeControl(val) {
if (val instanceof Control) {
delete this.controls[val.id];
} else {
delete this.controls[val];
}
}
// Renders the control (and all its contained controls)
// data: The object that contains the data to substitute into the template
// eventObj: Event related data for the event that caused the control to render
render(data, eventObj) {
if (this.controls) {
const controlData = {};
for (let controlId in this.controls) {
const control = this.controls[controlId];
controlData[control.constructor.getConstructorName()] = {};
controlData[control.constructor.getConstructorName()][control.id] = control.render(data, eventObj);
}
for (let key in controlData) {
data[key] = controlData[key];
}
}
return mustache.render(this.template, data);
}
// This method is invoked so the control can bind events after the DOM has been updated
// domContainerElement: The DOM container element into which the control was rendered
// eventObj: Event related data for the event that caused the control to render
onDOMUpdated(domContainerElement, eventObj) {
if (this.<API key>) {
this.<API key>(domContainerElement, eventObj);
}
if (this.controls) {
for (let controlId in this.controls) {
const control = this.controls[controlId];
control.onDOMUpdated(domContainerElement, eventObj);
}
}
}
// The Control classes that extend this type can add custom logic here to be executed after the domContainerElement
// has been updated
// domContainerElement: The DOM container element into which the control was rendered
// eventObj: Event related data for the event that caused the control to render
<API key>(domContainerElement, eventObj) {
}
};
|
<html><img border=0 src=70786-65-1.txt alt=70786-65-1.txt></img><body>
"x"
"1" "KAZIUS, J, MCGUIRE, R AND BURSI, R. DERIVATION AND VALIDATION OF TOXICOPHORES FOR MUTAGENICITY PREDICTION. J. MED. CHEM. 48: 312-320, 2005"
</body></html>
|
// MultibandBank.c
// FxDSP
#include "MultibandBank.h"
#include "LinkwitzRileyFilter.h"
#include "RBJFilter.h"
#include "FilterTypes.h"
#include <stdlib.h>
// Sqrt(2)/2
#define FILT_Q (0.70710681186548)
/*******************************************************************************
MultibandFilter */
struct MultibandFilter
{
LRFilter* LPA;
LRFilter* HPA;
LRFilter* LPB;
LRFilter* HPB;
RBJFilter* APF;
float lowCutoff;
float highCutoff;
float sampleRate;
};
struct MultibandFilterD
{
LRFilterD* LPA;
LRFilterD* HPA;
LRFilterD* LPB;
LRFilterD* HPB;
RBJFilterD* APF;
double lowCutoff;
double highCutoff;
double sampleRate;
};
/*******************************************************************************
MultibandFilterInit */
MultibandFilter*
MultibandFilterInit(float lowCutoff,
float highCutoff,
float sampleRate)
{
MultibandFilter* filter = (MultibandFilter*) malloc(sizeof(MultibandFilter));
filter->lowCutoff = lowCutoff;
filter->highCutoff = highCutoff;
filter->sampleRate = sampleRate;
filter->LPA = LRFilterInit(LOWPASS, filter->lowCutoff, FILT_Q, filter->sampleRate);
filter->HPA = LRFilterInit(HIGHPASS, filter->lowCutoff, FILT_Q, filter->sampleRate);
filter->LPB = LRFilterInit(LOWPASS, filter->highCutoff, FILT_Q, filter->sampleRate);
filter->HPB = LRFilterInit(HIGHPASS, filter->highCutoff, FILT_Q, filter->sampleRate);
filter->APF = RBJFilterInit(ALLPASS, filter->sampleRate/2.0, filter->sampleRate);
RBJFilterSetQ(filter->APF, 0.5);
return filter;
}
MultibandFilterD*
<API key>(double lowCutoff,
double highCutoff,
double sampleRate)
{
MultibandFilterD* filter = (MultibandFilterD*) malloc(sizeof(MultibandFilterD));
filter->lowCutoff = lowCutoff;
filter->highCutoff = highCutoff;
filter->sampleRate = sampleRate;
filter->LPA = LRFilterInitD(LOWPASS, filter->lowCutoff, FILT_Q, filter->sampleRate);
filter->HPA = LRFilterInitD(HIGHPASS, filter->lowCutoff, FILT_Q, filter->sampleRate);
filter->LPB = LRFilterInitD(LOWPASS, filter->highCutoff, FILT_Q, filter->sampleRate);
filter->HPB = LRFilterInitD(HIGHPASS, filter->highCutoff, FILT_Q, filter->sampleRate);
filter->APF = RBJFilterInitD(ALLPASS, filter->sampleRate/2.0, filter->sampleRate);
RBJFilterSetQD(filter->APF, 0.5);
return filter;
}
/*******************************************************************************
MultibandFilterFree */
Error_t
MultibandFilterFree(MultibandFilter* filter)
{
LRFilterFree(filter->LPA);
LRFilterFree(filter->LPB);
LRFilterFree(filter->HPA);
LRFilterFree(filter->HPB);
RBJFilterFree(filter->APF);
if (filter)
{
free(filter);
filter = NULL;
}
return NOERR;
}
Error_t
<API key>(MultibandFilterD* filter)
{
LRFilterFreeD(filter->LPA);
LRFilterFreeD(filter->LPB);
LRFilterFreeD(filter->HPA);
LRFilterFreeD(filter->HPB);
RBJFilterFreeD(filter->APF);
if (filter)
{
free(filter);
filter = NULL;
}
return NOERR;
}
/*******************************************************************************
<API key> */
Error_t
<API key>(MultibandFilter* filter)
{
LRFilterFlush(filter->LPA);
LRFilterFlush(filter->LPB);
LRFilterFlush(filter->HPA);
LRFilterFlush(filter->HPB);
RBJFilterFlush(filter->APF);
return NOERR;
}
Error_t
<API key>(MultibandFilterD* filter)
{
LRFilterFlushD(filter->LPA);
LRFilterFlushD(filter->LPB);
LRFilterFlushD(filter->HPA);
LRFilterFlushD(filter->HPB);
RBJFilterFlushD(filter->APF);
return NOERR;
}
/*******************************************************************************
<API key> */
Error_t
<API key>(MultibandFilter* filter, float lowCutoff)
{
filter->lowCutoff = lowCutoff;
LRFilterSetParams(filter->LPA, LOWPASS, lowCutoff, FILT_Q);
LRFilterSetParams(filter->HPA, HIGHPASS, lowCutoff, FILT_Q);
return NOERR;
}
Error_t
<API key>(MultibandFilterD* filter, double lowCutoff)
{
filter->lowCutoff = lowCutoff;
LRFilterSetParamsD(filter->LPA, LOWPASS, lowCutoff, FILT_Q);
LRFilterSetParamsD(filter->HPA, HIGHPASS, lowCutoff, FILT_Q);
return NOERR;
}
/*******************************************************************************
<API key> */
Error_t
<API key>(MultibandFilter* filter, float highCutoff)
{
filter->highCutoff = highCutoff;
LRFilterSetParams(filter->LPB, LOWPASS, highCutoff, FILT_Q);
LRFilterSetParams(filter->HPB, HIGHPASS, highCutoff, FILT_Q);
return NOERR;
}
Error_t
<API key>(MultibandFilterD* filter, double highCutoff)
{
filter->highCutoff = highCutoff;
LRFilterSetParamsD(filter->LPB, LOWPASS, highCutoff, FILT_Q);
LRFilterSetParamsD(filter->HPB, HIGHPASS, highCutoff, FILT_Q);
return NOERR;
}
/*******************************************************************************
<API key> */
Error_t
<API key>(MultibandFilter* filter,
float lowCutoff,
float highCutoff)
{
filter->lowCutoff = lowCutoff;
filter->highCutoff = highCutoff;
LRFilterSetParams(filter->LPA, LOWPASS, lowCutoff, FILT_Q);
LRFilterSetParams(filter->HPA, HIGHPASS, lowCutoff, FILT_Q);
LRFilterSetParams(filter->LPB, LOWPASS, highCutoff, FILT_Q);
LRFilterSetParams(filter->HPB, HIGHPASS, highCutoff, FILT_Q);
return NOERR;
}
Error_t
<API key>(MultibandFilterD* filter,
double lowCutoff,
double highCutoff)
{
filter->lowCutoff = lowCutoff;
filter->highCutoff = highCutoff;
LRFilterSetParamsD(filter->LPA, LOWPASS, lowCutoff, FILT_Q);
LRFilterSetParamsD(filter->HPA, HIGHPASS, lowCutoff, FILT_Q);
LRFilterSetParamsD(filter->LPB, LOWPASS, highCutoff, FILT_Q);
LRFilterSetParamsD(filter->HPB, HIGHPASS, highCutoff, FILT_Q);
return NOERR;
}
/*******************************************************************************
<API key> */
Error_t
<API key>(MultibandFilter* filter,
float* lowOut,
float* midOut,
float* highOut,
const float* inBuffer,
unsigned n_samples)
{
float tempLow[n_samples];
float tempHi[n_samples];
LRFilterProcess(filter->LPA, tempLow, inBuffer, n_samples);
LRFilterProcess(filter->HPA, tempHi, inBuffer, n_samples);
RBJFilterProcess(filter->APF, lowOut, tempLow, n_samples);
LRFilterProcess(filter->LPB, midOut, tempHi, n_samples);
LRFilterProcess(filter->HPB, highOut, tempHi, n_samples);
return NOERR;
}
Error_t
<API key>(MultibandFilterD* filter,
double* lowOut,
double* midOut,
double* highOut,
const double* inBuffer,
unsigned n_samples)
{
double tempLow[n_samples];
double tempHi[n_samples];
LRFilterProcessD(filter->LPA, tempLow, inBuffer, n_samples);
LRFilterProcessD(filter->HPA, tempHi, inBuffer, n_samples);
RBJFilterProcessD(filter->APF, lowOut, tempLow, n_samples);
LRFilterProcessD(filter->LPB, midOut, tempHi, n_samples);
LRFilterProcessD(filter->HPB, highOut, tempHi, n_samples);
return NOERR;
}
|
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.Serialization;
namespace AutoHelp.domain.Models
{
[DebuggerDisplay("{Fullname}")]
[DataContract]
public class Method : CodeCommentBase
{
[DataMember]
public string ReturnType { get; set; }
[DataMember]
public string ReturnTypeFullName { get; set; }
public Method()
{
Parameters = new List<Parameter>();
}
}
}
|
'use strict';
/* jasmine specs for filters go here */
describe('filter', function() {
});
|
<div id="contenido">
<div class="bloque">
<h2 class="titulo"><strong>Contacto</strong></h2>
<p>Rellene el siguiente formulario si desea ponerse en contacto.</p>
<?php
if(!empty($estado)){
echo $estado;
}
?>
<form action="contacto/" method="post">
<fieldset>
<legend>Datos</legend>
<p>
<label for="nombre" title="Nombre"><strong>Nombre </strong></label>
<input id="nombre" name="nombre" type="text" value="<?php echo $nombre; ?>" size="50" maxlength="40" /> <em>Ejemplo: Pepe</em>
</p>
<p>
<label for="email" title="Email"><strong>Email </strong></label>
<input id="email" name="email" type="text" value="<?php echo $email; ?>" size="50" maxlength="320" /> <em>Ejemplo: ejemplo@ejemplo.es</em>
</p>
<p>
<label for="asunto" title="Asunto"><strong>Asunto </strong></label>
<input id="asunto" name="asunto" type="text" value="<?php echo $asunto; ?>" size="50" maxlength="50" />
</p>
<p>
<label for="mensaje" title="Mensaje"><strong>Mensaje </strong></label>
<textarea id="mensaje" name="mensaje" rows="7" cols="40"><?php echo $mensaje; ?></textarea>
</p>
<p>
<label for="humano" title="Humano ó Maquina"><strong>¿Eres humano? </strong></label>
<input id="humano" name="humano" type="text" value="0" size="5" maxlength="5" /> <?php echo $captcha["pregunta"]; ?>
</p>
<p><input id="enviar" name="enviar" type="submit" value="Enviar" /></p>
</fieldset>
</form>
</div>
</div>
|
!function(n){}(jQuery);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5iYWRyYWZ0LnNjcmlwdC5qcyJdLCJuYW1lcyI6WyIkIiwialF1ZXJ5Il0sIm1hcHBpbmdzIjoiQ0FJQSxTQUFBQSxLQUVBQyIsImZpbGUiOiJuYmFkcmFmdC5zY3JpcHQuanMiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIEBmaWxlXG4gKiBDdXN0b20gc2NyaXB0cyBmb3IgdGhlbWUuXG4gKi9cbihmdW5jdGlvbiAoJCkge1xuICBcbn0pKGpRdWVyeSk7XG4iXSwic291cmNlUm9vdCI6Ii9zb3VyY2UvIn0=
|
#include <graphene/chain/account_object.hpp>
#include <graphene/chain/asset_object.hpp>
#include <graphene/chain/market_object.hpp>
#include <graphene/chain/market_evaluator.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/chain/exceptions.hpp>
#include <graphene/chain/hardfork.hpp>
#include <graphene/chain/is_authorized_asset.hpp>
#include <graphene/chain/protocol/market.hpp>
#include <fc/uint128.hpp>
namespace graphene { namespace chain {
void_result <API key>::do_evaluate(const <API key>& op)
{ try {
// Disable Operation Temporary
FC_ASSERT( false, "Limit order create operation is not supported for now.");
const database& d = db();
FC_ASSERT( d.head_block_time() < HARDFORK_1_TIME );
FC_ASSERT( op.expiration >= d.head_block_time() );
_seller = this->fee_paying_account;
_sell_asset = &op.amount_to_sell.asset_id(d);
_receive_asset = &op.min_to_receive.asset_id(d);
if( _sell_asset->options.whitelist_markets.size() )
FC_ASSERT( _sell_asset->options.whitelist_markets.find(_receive_asset->id) != _sell_asset->options.whitelist_markets.end() );
if( _sell_asset->options.blacklist_markets.size() )
FC_ASSERT( _sell_asset->options.blacklist_markets.find(_receive_asset->id) == _sell_asset->options.blacklist_markets.end() );
FC_ASSERT( is_authorized_asset( d, *_seller, *_sell_asset ) );
FC_ASSERT( is_authorized_asset( d, *_seller, *_receive_asset ) );
FC_ASSERT( d.get_balance( *_seller, *_sell_asset ) >= op.amount_to_sell, "insufficient balance",
("balance",d.get_balance(*_seller,*_sell_asset))("amount_to_sell",op.amount_to_sell) );
return void_result();
} <API key>( (op) ) }
void <API key>::pay_fee()
{
_deferred_fee = core_fee_paid;
}
object_id_type <API key>::do_apply(const <API key>& op)
{ try {
const auto& seller_stats = _seller->statistics(db());
db().modify(seller_stats, [&](<API key>& bal) {
if( op.amount_to_sell.asset_id == asset_id_type() )
{
bal.<API key> += op.amount_to_sell.amount;
}
});
db().adjust_balance(op.seller, -op.amount_to_sell);
const auto& new_order_object = db().create<limit_order_object>([&](limit_order_object& obj){
obj.seller = _seller->id;
obj.for_sale = op.amount_to_sell.amount;
obj.sell_price = op.get_price();
obj.expiration = op.expiration;
obj.deferred_fee = _deferred_fee;
});
limit_order_id_type order_id = new_order_object.id; // save this because we may remove the object by filling it
bool filled = db().apply_order(new_order_object);
FC_ASSERT( !op.fill_or_kill || filled );
return order_id;
} <API key>( (op) ) }
void_result <API key>::do_evaluate(const <API key>& o)
{ try {
database& d = db();
FC_ASSERT( d.head_block_time() < HARDFORK_1_TIME );
_order = &o.order(d);
FC_ASSERT( _order->seller == o.fee_paying_account );
return void_result();
} <API key>( (o) ) }
asset <API key>::do_apply(const <API key>& o)
{ try {
database& d = db();
auto base_asset = _order->sell_price.base.asset_id;
auto quote_asset = _order->sell_price.quote.asset_id;
auto refunded = _order->amount_for_sale();
d.cancel_order(*_order, false /* don't create a virtual op*/);
// Possible optimization: order can be called by canceling a limit order iff the canceled order was at the top of the book.
// Do I need to check calls in both assets?
d.check_call_orders(base_asset(d));
d.check_call_orders(quote_asset(d));
return refunded;
} <API key>( (o) ) }
void_result <API key>::do_evaluate(const <API key>& o)
{ try {
database& d = db();
FC_ASSERT( d.head_block_time() < HARDFORK_1_TIME );
_paying_account = &o.funding_account(d);
_debt_asset = &o.delta_debt.asset_id(d);
FC_ASSERT( _debt_asset->is_market_issued(), "Unable to cover ${sym} as it is not a collateralized asset.",
("sym", _debt_asset->symbol) );
_bitasset_data = &_debt_asset->bitasset_data(d);
if there is a settlement for this asset, then no further margin positions may be taken and
all existing margin positions should have been closed va database::<API key>
FC_ASSERT( !_bitasset_data->has_settlement() );
FC_ASSERT( o.delta_collateral.asset_id == _bitasset_data->options.short_backing_asset );
if( _bitasset_data-><API key> )
FC_ASSERT( o.delta_collateral.amount == o.delta_debt.amount );
else if( _bitasset_data->current_feed.settlement_price.is_null() )
FC_THROW_EXCEPTION(insufficient_feeds, "Cannot borrow asset with no price feed.");
if( o.delta_debt.amount < 0 )
{
FC_ASSERT( d.get_balance(*_paying_account, *_debt_asset) >= o.delta_debt,
"Cannot cover by ${c} when payer only has ${b}",
("c", o.delta_debt.amount)("b", d.get_balance(*_paying_account, *_debt_asset).amount) );
}
if( o.delta_collateral.amount > 0 )
{
FC_ASSERT( d.get_balance(*_paying_account, _bitasset_data->options.short_backing_asset(d)) >= o.delta_collateral,
"Cannot increase collateral by ${c} when payer only has ${b}", ("c", o.delta_collateral.amount)
("b", d.get_balance(*_paying_account, o.delta_collateral.asset_id(d)).amount) );
}
return void_result();
} <API key>( (o) ) }
void_result <API key>::do_apply(const <API key>& o)
{ try {
FC_ASSERT( false, "Call order update operation is not supported for now.");
database& d = db();
if( o.delta_debt.amount != 0 )
{
d.adjust_balance( o.funding_account, o.delta_debt );
// Deduct the debt paid from the total supply of the debt asset.
d.modify(_debt_asset-><API key>(d), [&](<API key>& dynamic_asset) {
dynamic_asset.current_supply += o.delta_debt.amount;
assert(dynamic_asset.current_supply >= 0);
});
}
if( o.delta_collateral.amount != 0 )
{
d.adjust_balance( o.funding_account, -o.delta_collateral );
// Adjust the total core in orders accodingly
if( o.delta_collateral.asset_id == asset_id_type() )
{
d.modify(_paying_account->statistics(d), [&](<API key>& stats) {
stats.<API key> += o.delta_collateral.amount;
});
}
}
auto& call_idx = d.get_index_type<call_order_index>().indices().get<by_account>();
auto itr = call_idx.find( boost::make_tuple(o.funding_account, o.delta_debt.asset_id) );
const call_order_object* call_obj = nullptr;
if( itr == call_idx.end() )
{
FC_ASSERT( o.delta_collateral.amount > 0 );
FC_ASSERT( o.delta_debt.amount > 0 );
call_obj = &d.create<call_order_object>( [&](call_order_object& call ){
call.borrower = o.funding_account;
call.collateral = o.delta_collateral.amount;
call.debt = o.delta_debt.amount;
call.call_price = price::call_price(o.delta_debt, o.delta_collateral,
_bitasset_data->current_feed.<API key>);
});
}
else
{
call_obj = &*itr;
d.modify( *call_obj, [&]( call_order_object& call ){
call.collateral += o.delta_collateral.amount;
call.debt += o.delta_debt.amount;
if( call.debt > 0 )
{
call.call_price = price::call_price(call.get_debt(), call.get_collateral(),
_bitasset_data->current_feed.<API key>);
}
});
}
auto debt = call_obj->get_debt();
if( debt.amount == 0 )
{
FC_ASSERT( call_obj->collateral == 0 );
d.remove( *call_obj );
return void_result();
}
FC_ASSERT(call_obj->collateral > 0 && call_obj->debt > 0);
// then we must check for margin calls and other issues
if( !_bitasset_data-><API key> )
{
call_order_id_type call_order_id = call_obj->id;
// check to see if the order needs to be margin called now, but don't allow black swans and require there to be
// limit orders available that could be used to fill the order.
if( d.check_call_orders( *_debt_asset, false ) )
{
const auto call_obj = d.find(call_order_id);
// if we filled at least one call order, we are OK if we totally filled.
GRAPHENE_ASSERT(
!call_obj,
<API key>,
"Updating call order would trigger a margin call that cannot be fully filled",
("a", ~call_obj->call_price )("b", _bitasset_data->current_feed.settlement_price)
);
}
else
{
const auto call_obj = d.find(call_order_id);
FC_ASSERT( call_obj, "no margin call was executed and yet the call object was deleted" );
//edump( (~call_obj->call_price) ("<")( _bitasset_data->current_feed.settlement_price) );
// We didn't fill any call orders. This may be because we
// aren't in margin call territory, or it may be because there
// were no matching orders. In the latter case, we throw.
GRAPHENE_ASSERT(
~call_obj->call_price < _bitasset_data->current_feed.settlement_price,
<API key>,
"Updating call order would trigger a margin call that cannot be fully filled",
("a", ~call_obj->call_price )("b", _bitasset_data->current_feed.settlement_price)
);
}
}
return void_result();
} <API key>( (o) ) }
} } // graphene::chain
|
require "fog"
module <API key>
module AttachmentPatch
def self.included(base) # :nodoc:
base.extend(ClassMethods)
base.send(:include, InstanceMethods)
base.class_eval do
unloadable
cattr_accessor :context_obj, :<API key>, :<API key>
after_validation :<API key>
before_destroy :<API key>
def readable?
!!Attachment.<API key>.get(self.objectstorage_path) rescue false
end
end
end
module ClassMethods
def set_context(context)
@@context_obj = context
end
def get_context
@@context_obj
end
def <API key>
unless Attachment.<API key>
yaml = ERB.new(File.read(Rails.root.join("config", "objectstorage.yml"))).result
@@<API key> = YAML.load(yaml).fetch(Rails.env)
end
return @@<API key>
end
def <API key>
unless Attachment.<API key>
config = Attachment.<API key>
@@<API key> = Fog::Storage.new(
provider: :aws,
aws_access_key_id: config["access_key_id"],
<API key>: config["secret_access_key"],
host: config["endpoint"],
<API key>: config["signature_version"]
).directories.get(config["bucket"])
end
@@<API key>
end
def <API key>(filename, project_id)
ts = DateTime.now.strftime("%y%m%d%H%M%S")
[project_id, ts, filename].compact.join("/")
end
end
module InstanceMethods
def <API key>
if self.new_record?
timestamp = DateTime.now.strftime("%y%m%d%H%M%S")
self.disk_filename = [timestamp, filename].join("/")
end
self.disk_filename.blank? ? filename : self.disk_filename
end
# path on objectstorage to the file, defaulting the instance's disk_filename
def objectstorage_path(fn = <API key>)#, ctx = nil, pid = nil)
context = self.container || self.class.get_context
project = context.is_a?(Hash) ? Project.find(context[:project]) : context.project
ctx = context.is_a?(Hash) ? context[:class] : context.class.name
# XXX s/WikiPage/Wiki
ctx = "Wiki" if ctx == "WikiPage"
pid = project.identifier
[pid, fn].compact.join("/")
end
def <API key>
if @temp_file && !@temp_file.empty?
logger.debug "[<API key>] Uploading #{<API key>}"
file = Attachment.<API key>.files.create(
key: objectstorage_path,
body: @temp_file.is_a?(String) ? @temp_file : @temp_file.read
)
self.digest = file.etag
end
# set the temp file to nil so the model's original after_save block
# skips writing to the filesystem
@temp_file = nil
end
def <API key>
logger.debug "[<API key>] Deleting #{<API key>}"
Attachment.<API key>.files.get(objectstorage_path(<API key>)).destroy
end
end
end
end
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Chromamboo.Contracts;
using Newtonsoft.Json.Linq;
namespace Chromamboo.Providers.Notification
{
public class <API key> : <API key><string>
{
private readonly IBitbucketApi bitbucketApi;
private readonly IBambooApi bambooApi;
private readonly <API key> presentationService;
public <API key>(IBitbucketApi bitbucketApi, IBambooApi bambooApi, <API key> presentationService)
{
this.bitbucketApi = bitbucketApi;
this.bambooApi = bambooApi;
this.presentationService = presentationService;
}
public enum NotificationType
{
Build,
PullRequest
}
public void Register(string planKey)
{
Observable
.Timer(DateTimeOffset.MinValue, TimeSpan.FromSeconds(5))
.Subscribe(async l =>
{
await this.<API key>(planKey);
});
}
private async Task <API key>(string planKey)
{
List<BuildDetail> buildsDetails;
try
{
var latestHistoryBuild = this.bambooApi.<API key>(planKey);
var branchesListing = this.bambooApi.<API key>(planKey);
var isDevelopSuccessful = JObject.Parse(latestHistoryBuild.Result)["results"]["result"].First()["state"].Value<string>() == "Successful";
var lastBuiltBranches = JObject.Parse(branchesListing.Result);
buildsDetails = lastBuiltBranches["branches"]["branch"].Where(b => b["enabled"].Value<bool>()).Select(this.GetBuildDetails).ToList();
if (!isDevelopSuccessful)
{
var developDetails = this.bambooApi.<API key>(JObject.Parse(latestHistoryBuild.Result)["results"]["result"].First()["planResultKey"]["key"].Value<string>());
var developBuildDetails = this.<API key>(developDetails.Result);
buildsDetails.Add(developBuildDetails);
}
}
catch (Exception e)
{
this.presentationService.MarkAsInconclusive(NotificationType.Build);
Console.WriteLine(e.GetType() + ": " + e.Message);
return;
}
this.presentationService.Update(buildsDetails);
}
private BuildDetail GetBuildDetails(JToken jsonToken)
{
var key = jsonToken["key"].Value<string>();
var <API key> = JObject.Parse(this.bambooApi.<API key>(key).Result)["results"]["result"].First()["buildResultKey"].Value<string>();
var buildDetailsString = this.bambooApi.<API key>(<API key>).Result;
var buildDetails = this.<API key>(buildDetailsString);
buildDetails.BranchName = jsonToken["shortName"].Value<string>();
return buildDetails;
}
private BuildDetail <API key>(string buildDetailsString)
{
var details = JObject.Parse(buildDetailsString);
var buildDetails = new BuildDetail();
buildDetails.CommitHash = details["vcsRevisionKey"].Value<string>();
buildDetails.Successful = details["successful"].Value<bool>();
buildDetails.BuildResultKey = details["buildResultKey"].Value<string>();
buildDetails.PlanResultKey = details["planResultKey"]["key"].Value<string>();
var commitDetails = JObject.Parse(this.bitbucketApi.GetCommitDetails(buildDetails.CommitHash).Result);
buildDetails.JiraIssue = commitDetails["properties"]?["jira-key"].Values<string>().Aggregate((s1, s2) => s1 + ", " + s2);
buildDetails.AuthorEmailAddress = commitDetails["author"]["emailAddress"].Value<string>();
buildDetails.AuthorName = commitDetails["author"]["name"].Value<string>();
buildDetails.AuthorDisplayName = commitDetails["author"]["displayName"]?.Value<string>() ?? buildDetails.AuthorName;
return buildDetails;
}
}
}
|
namespace SupermarketsChainDB.Data.Migrations
{
using System;
using System.Collections.Generic;
using System.Linq;
using Oracle.DataAccess.Client;
using SupermarketsChainDB.Data;
using SupermarketsChainDB.Models;
public static class OracleToSqlDb
{
private static string ConnectionString = Connection.<API key>();
private static OracleConnection con;
public static void MigrateToSql()
{
MigrateMeasures();
MigrateVendors();
MigrateProducts();
}
private static void Connect()
{
var con = new OracleConnection();
if (OracleConnection.IsAvailable)
{
con.ConnectionString = "context connection=true";
}
else
{
con = new OracleConnection { ConnectionString = ConnectionString };
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
}
}
private static void MigrateMeasures()
{
<API key> data = new <API key>();
con = new OracleConnection { ConnectionString = ConnectionString };
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT M_ID, MEASURE_NAME FROM MEASURE_UNITS";
using (OracleDataReader reader = cmd.ExecuteReader())
{
var lastMeasure = data.Measures.All().OrderByDescending(v => v.Id).FirstOrDefault();
int dataId = 0;
if (lastMeasure != null)
{
dataId = lastMeasure.Id;
}
while (reader.Read())
{
int measureId = int.Parse(reader["M_ID"].ToString());
if (dataId < measureId)
{
Measure measure = new Measure();
measure.Id = measureId;
measure.MeasureName = (string)reader["MEASURE_NAME"];
data.Measures.Add(measure);
}
}
data.SaveChanges();
}
Close();
}
private static void MigrateVendors()
{
<API key> data = new <API key>();
con = new OracleConnection { ConnectionString = ConnectionString };
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT V_ID,VENDOR_NAME FROM VENDORS";
using (OracleDataReader reader = cmd.ExecuteReader())
{
var lastVendor = data.Vendors.All().OrderByDescending(v => v.Id).FirstOrDefault();
int dataId = 0;
if (lastVendor != null)
{
dataId = lastVendor.Id;
}
while (reader.Read())
{
int vendorId = int.Parse(reader["V_ID"].ToString());
if (dataId < vendorId)
{
Vendor vendor = new Vendor();
vendor.Id = vendorId;
vendor.VendorName = (string)reader["VENDOR_NAME"];
data.Vendors.Add(vendor);
}
}
data.SaveChanges();
}
Close();
}
private static void MigrateProducts()
{
<API key> data = new <API key>();
con = new OracleConnection { ConnectionString = ConnectionString };
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT P_ID, " +
"VENDOR_ID," +
"PRODUCT_NAME, " +
"MEASURE_ID, " +
"PRICE, " +
"PRODUCT_TYPE " +
"FROM PRODUCTS";
using (OracleDataReader reader = cmd.ExecuteReader())
{
var lastProduct = data.Products.All().OrderByDescending(p => p.Id).FirstOrDefault();
int dataId = 0;
if (lastProduct != null)
{
dataId = lastProduct.Id;
}
while (reader.Read())
{
int productId = int.Parse(reader["P_ID"].ToString());
if (dataId < productId)
{
Product product = new Product();
// for debugging
product.Id = productId;
product.VendorId = int.Parse(reader["VENDOR_ID"].ToString());
product.ProductName = reader["PRODUCT_NAME"].ToString();
product.MeasureId = int.Parse(reader["MEASURE_ID"].ToString());
product.Price = decimal.Parse(reader["PRICE"].ToString());
product.ProductType = (ProductType)Enum.Parse(typeof(ProductType), reader["PRODUCT_TYPE"].ToString());
data.Products.Add(product);
}
}
data.SaveChanges();
}
Close();
}
private static void Close()
{
con.Close();
con.Dispose();
}
}
}
|
# ts3
TeamSpeak 3 ServerQuery API implementation for Node.js
|
^^^^^^^^^^^^^CS171 2015 Homework Assignments
Homework assignments for Harvard's [CS171](http:
git pull homework master
For details on how to submit your work, take a look at [Section 1](https://github.com/CS171/2015-cs171-homework/tree/master/section1).
**Name**:Yi Mao
**Email**:yim833@mail.harvard.edu
|
class <API key> < ActionController::Base
<API key> with: :exception
helper_method :current_user
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def require_login
render_404 unless current_user
end
private
def render_404
raise ActionController::RoutingError.new('Not Found')
end
end
|
import { Injectable } from '@angular/core';
import { SyncResult } from 'app/model/syncResult'
import { Log } from 'app/model/log'
import { LogItem } from 'app/model/logItem'
@Injectable()
export class SyncResultService
{
syncResultService : any;
constructor()
{
this.syncResultService = (window as any).syncResultService;
}
// TODO cache
// TODO should be ab
// TODO shouldnt be needed, drop
isSuccess() : boolean
{
var success;
var syncResults = this.syncResultService.getResults();
if (syncResults.length > 0)
{
success = true;
for (var i = 0; i < syncResults.length; i++)
{
var syncResult = syncResults[i];
success &= syncResult.success;
}
}
else
{
success = false;
}
return success;
}
// TODO cache
// TODO move translation into shared service
getResults() : SyncResult[]
{
var results = [];
var syncResults = this.syncResultService.getResults();
// Translate each result
for (var i = 0; i < syncResults.length; i++)
{
var syncResult = syncResults[i];
var result = new SyncResult();
result.profileId = syncResult.getProfileId();
result.hostName = syncResult.getHostName();
// Translate merge log
var log = syncResult.getLog();
if (log != null)
{
var logItems = log.getLogItems();
// Translate log items of each result
var jsonLog = new Log();
var items = [];
for (var j = 0; j < logItems.length; j++)
{
var logItem = logItems[j];
var item = new LogItem();
item.level = logItem.getLevel().toString();
item.local = logItem.isLocal();
item.text = logItem.getText();
items.push(item);
}
jsonLog.items = items;
result.log = jsonLog;
}
results.push(result);
}
return results;
}
clear()
{
this.syncResultService.clear();
}
getResultsAsText()
{
return this.syncResultService.getResultsAsText();
}
}
|
import * as React from 'react';
import { StandardProps } from '..';
export interface TableProps extends StandardProps<TableBaseProps, TableClassKey> {
component?: React.ReactType<TableBaseProps>;
}
export type TableBaseProps = React.TableHTMLAttributes<HTMLTableElement>;
export type TableClassKey = 'root';
declare const Table: React.ComponentType<TableProps>;
export default Table;
|
import React from 'react';
import ReactDOM from 'react-dom';
import EventStack from './EventStack';
import PropTypes from 'prop-types';
const ESCAPE = 27;
/**
* Get the keycode from an event
* @param {Event} event The browser event from which we want the keycode from
* @returns {Number} The number of the keycode
*/
const getKeyCodeFromEvent = event =>
event.which || event.keyCode || event.charCode;
// Render into subtree is necessary for parent contexts to transfer over
// For example, for react-router
const <API key> = ReactDOM.<API key>;
export class ModalContent extends React.Component {
constructor(props) {
super(props);
this.handleGlobalClick = this.handleGlobalClick.bind(this);
this.handleGlobalKeydown = this.handleGlobalKeydown.bind(this);
}
componentWillMount() {
/**
* This is done in the componentWillMount instead of the componentDidMount
* because this way, a modal that is a child of another will have register
* for events after its parent
*/
this.eventToken = EventStack.addListenable([
['click', this.handleGlobalClick],
['keydown', this.handleGlobalKeydown]
]);
}
<API key>() {
EventStack.removeListenable(this.eventToken);
}
shouldClickDismiss(event) {
const { target } = event;
// This piece of code isolates targets which are fake clicked by things
// like file-drop handlers
if (target.tagName === 'INPUT' && target.type === 'file') {
return false;
}
if (!this.props.<API key>) {
if (target !== this.refs.self || this.refs.self.contains(target)) {
return false;
}
} else {
if (target === this.refs.self || this.refs.self.contains(target)) {
return false;
}
}
return true;
}
handleGlobalClick(event) {
if (this.shouldClickDismiss(event)) {
if (typeof this.props.onClose === 'function') {
this.props.onClose(event);
}
}
}
handleGlobalKeydown(event) {
if (getKeyCodeFromEvent(event) === ESCAPE) {
if (typeof this.props.onClose === 'function') {
this.props.onClose(event);
}
}
}
render() {
return (
<div ref="self" className={'liq_modal-content'}>
{this.props.showButton && this.props.onClose ? (
<button
onClick={this.props.onClose}
className={'liq_modal-close'}
data-test="close_modal_button">
<span aria-hidden="true">{'×'}</span>
</button>
) : null}
{this.props.children}
</div>
);
}
}
ModalContent.propTypes = {
showButton: PropTypes.bool,
onClose: PropTypes.func, // required for the close button
className: PropTypes.string,
children: PropTypes.node,
<API key>: PropTypes.bool
};
ModalContent.defaultProps = {
<API key>: true,
showButton: true
};
export class ModalPortal extends React.Component {
componentDidMount() {
// disable scrolling on body
document.body.classList.add('liq_modal-open');
// Create a div and append it to the body
this._target = document.body.appendChild(document.createElement('div'));
// Mount a component on that div
this._component = <API key>(
this,
this.props.children,
this._target
);
// A handler call in case you want to do something when a modal opens, like add a class to the body or something
if (typeof this.props.onModalDidMount === 'function') {
this.props.onModalDidMount();
}
}
componentDidUpdate() {
// When the child component updates, we have to make sure the content rendered to the DOM is updated to
this._component = <API key>(
this,
this.props.children,
this._target
);
}
<API key>() {
/**
* Let this be some discussion about fading out the components on unmount.
* Right now, there is the issue that if a stack of components are layered
* on top of each other, and you programmatically dismiss the bottom one,
* it actually takes some time for the animation to catch up to the top one,
* because each modal doesn't send a dismiss signal to its children until
* it itself is totally gone...
*/
// TODO: REMOVE THIS - THINK OUT OF THE BOX
const done = () => {
// Modal will unmount now
// Call a handler, like onModalDidMount
if (typeof this.props.onModalWillUnmount === 'function') {
this.props.onModalWillUnmount();
}
// Remove the node and clean up after the target
ReactDOM.<API key>(this._target);
document.body.removeChild(this._target);
document.body.classList.remove('liq_modal-open');
};
// A similar API to <API key>
if (
this._component &&
typeof this._component.componentWillLeave === 'function'
) {
// Pass the callback to be called on completion
this._component.componentWillLeave(done);
} else {
// Call completion immediately
done();
}
}
render() {
return null;
} // This doesn't actually return anything to render
}
ModalPortal.propTypes = {
onClose: PropTypes.func, // This is called when the dialog should close
children: PropTypes.node,
onModalDidMount: PropTypes.func, // optional, called on mount
onModalWillUnmount: PropTypes.func // optional, called on unmount
};
export class ModalBackground extends React.Component {
constructor(props) {
super(props);
this.state = {
// This is set to false as soon as the component has mounted
// This allows the component to change its css and animate in
transparent: true
};
}
componentDidMount() {
// Create a delay so CSS will animate
<API key>(() => this.setState({ transparent: false }));
}
componentWillLeave(callback) {
this.setState({
transparent: true,
componentIsLeaving: true
});
// There isn't a good way to figure out what the duration is exactly,
// because parts of the animation are carried out in CSS...
setTimeout(() => {
callback();
}, this.props.duration);
}
render() {
const { transparent } = this.state;
const overlayStyle = {
opacity: transparent ? 0 : 0.6
};
const containerStyle = {
opacity: transparent ? 0 : 1
};
return (
<div
className={'<API key>'}
style={{ zIndex: this.props.zIndex }}>
<div
style={overlayStyle}
className={'<API key>'}
/>
<div
style={containerStyle}
className={'<API key>'}>
{this.props.children}
</div>
</div>
);
}
}
ModalBackground.defaultProps = {
duration: 300,
zIndex: 1100 // to lay above tooltips and the website header
};
ModalBackground.propTypes = {
onClose: PropTypes.func,
duration: PropTypes.number.isRequired,
zIndex: PropTypes.number.isRequired,
children: PropTypes.node
};
export default {
ModalPortal,
ModalBackground,
ModalContent
};
|
#include "pch.h"
#include "ActalogicApp.h"
TCHAR ActalogicApp::m_szWindowClass[] = _T("Actalogic");
TCHAR ActalogicApp::m_szTitle[] = _T("Actalogic");
ActalogicApp::ActalogicApp():
m_hWnd(NULL),
m_hInstance(NULL),
m_d2d1Manager(),
m_entityFPS(),
<API key>(),
<API key>(this),
m_inputHelper()
{
<API key>.SetApp(this);
}
ActalogicApp::~ActalogicApp()
{
}
HRESULT ActalogicApp::Initialize(HINSTANCE hInstance, int nCmdShow)
{
HRESULT hresult;
hresult = m_d2d1Manager.<API key>();
if (FAILED(hresult)) {return hresult;}
hresult = <API key>.<API key>(&m_d2d1Manager);
if (FAILED(hresult)) { return hresult; }
hresult = m_entityFPS.<API key>(&m_d2d1Manager);
if (FAILED(hresult)) { return hresult; }
hresult = <API key>.<API key>(&m_d2d1Manager);
if (FAILED(hresult)) { return hresult; }
m_hInstance = hInstance;
m_hWnd = InitializeWindow(hInstance, nCmdShow, 800.0F, 600.0F);
return m_hWnd==NULL ? E_FAIL : S_OK;
}
HWND ActalogicApp::InitializeWindow(HINSTANCE hInstance, int nCmdShow, FLOAT width, FLOAT height)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = ActalogicApp::WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = m_szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
if (!RegisterClassEx(&wcex))
{
MessageBox(NULL,
_T("Call to RegisterClassEx failed!"),
m_szTitle,
NULL);
return NULL;
}
FLOAT dpiX, dpiY;
m_d2d1Manager.GetDesktopDpi(&dpiX, &dpiY);
UINT desktopWidth = static_cast<UINT>(ceil(width * dpiX / 96.f));
UINT desktopHeight = static_cast<UINT>(ceil(height * dpiY / 96.f));
HWND hWnd = CreateWindow(
m_szWindowClass,
m_szTitle,
WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX & ~WS_SIZEBOX,
CW_USEDEFAULT, CW_USEDEFAULT,
desktopWidth, desktopHeight,
NULL,
NULL,
hInstance,
this
);
if (!hWnd)
{
MessageBox(NULL,
_T("Call to CreateWindow failed!"),
m_szTitle,
NULL);
return NULL;
}
SetClientSize(hWnd, desktopWidth, desktopHeight);
if (nCmdShow == SW_MAXIMIZE)
{
ShowWindow(hWnd, SW_RESTORE);
}
else
{
ShowWindow(hWnd, nCmdShow);
}
UpdateWindow(hWnd);
return hWnd;
}
int ActalogicApp::Run()
{
MSG msg;
for (;;)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
if (!GetMessage(&msg, NULL, 0, 0))
{
return msg.wParam;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
if (m_isActive)
{
OnTick();
}
else
{
Sleep(1);
}
}
}
}
void ActalogicApp::Dispose()
{
<API key>.<API key>();
<API key>.<API key>();
m_d2d1Manager.DiscardAllResources();
}
void ActalogicApp::Exit()
{
PostMessage(m_hWnd, WM_DESTROY, 0, 0);
}
void ActalogicApp::OnTick()
{
m_inputHelper.OnTick();
OnPreRender();
OnRender();
OnPostRender();
}
void ActalogicApp::OnPreRender()
{
<API key>.OnPreRender(&m_inputHelper);
m_entityFPS.OnPreRender(&m_inputHelper);
<API key>.OnPreRender(&m_inputHelper);
}
void ActalogicApp::OnRender()
{
HRESULT hresult = S_OK;
hresult = m_d2d1Manager.<API key>(m_hWnd);
if (SUCCEEDED(hresult)){ <API key>.<API key>(&m_d2d1Manager); }
if (SUCCEEDED(hresult)){ <API key>.<API key>(&m_d2d1Manager); }
if (SUCCEEDED(hresult))
{
m_d2d1Manager.BeginDraw();
<API key>.OnRender(&m_d2d1Manager);
<API key>.OnRender(&m_d2d1Manager);
hresult = m_d2d1Manager.EndDraw();
}
if (FAILED(hresult))
{
<API key>.<API key>();
<API key>.<API key>();
m_d2d1Manager.<API key>();
}
}
void ActalogicApp::OnPostRender()
{
<API key>.OnPostRender();
<API key>.OnPostRender();
}
void ActalogicApp::OnResize(WORD width, WORD height, BOOL isActive)
{
m_isActive = isActive;
}
LRESULT CALLBACK ActalogicApp::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (message == WM_CREATE)
{
LPCREATESTRUCT pcs = (LPCREATESTRUCT)lParam;
ActalogicApp *pApp = (ActalogicApp *)pcs->lpCreateParams;
SetWindowLongPtrW(hWnd, GWLP_USERDATA, PtrToUlong(pApp));
}
else
{
ActalogicApp *pApp = reinterpret_cast<ActalogicApp *>(static_cast<LONG_PTR>(
::GetWindowLongPtrW(hWnd, GWLP_USERDATA)));
switch (message)
{
case WM_DISPLAYCHANGE:
InvalidateRect(hWnd, NULL, FALSE);
case WM_PAINT:
pApp->OnRender();
ValidateRect(hWnd, NULL);
break;
case WM_SIZE:
{
BOOL isActive = wParam == SIZE_MINIMIZED ? FALSE : TRUE;
WORD width = lParam & 0xFFFF;
WORD height = (lParam >> 16) & 0xFFFF;
pApp->OnResize(width, height, isActive);
break;
}
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
break;
}
}
return S_OK;
}
VOID ActalogicApp::SetClientSize(HWND hWnd, LONG sx, LONG sy)
{
RECT rc1;
RECT rc2;
GetWindowRect(hWnd, &rc1);
GetClientRect(hWnd, &rc2);
sx += ((rc1.right - rc1.left) - (rc2.right - rc2.left));
sy += ((rc1.bottom - rc1.top) - (rc2.bottom - rc2.top));
SetWindowPos(hWnd, NULL, 0, 0, sx, sy, (SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOMOVE));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.