code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
class Solution {
public:
int findRadius(vector<int>& houses, vector<int>& heaters) {
sort(houses.begin(), houses.end());
sort(heaters.begin(), heaters.end());
auto radius = 0;
auto idx = 0;
for (auto house : houses) {
auto current = abs(house - heaters[idx]);
if (current <= radius) continue;
for (auto n = idx + 1; n < heaters.size(); ++n) {
if (abs(house - heaters[n]) <= current) {
current = abs(house - heaters[n]);
idx = n;
} else {
break;
}
}
radius = max(radius, current);
}
return radius;
}
}; | Java |
<div *ngIf="user">
<div class="page-header">
<h2>{{user.name}}</h2>
</div>
<ul class="list-group">
<li class="list-group-item">Username: {{user.username}}</li>
<li class="list-group-item">Email: {{user.email}}</li>
</ul>
</div> | Java |
from django.conf.urls import patterns, include, url
import views
urlpatterns = patterns('',
url(r'^logout', views.logout, name='logout'),
url(r'^newUser', views.newUser, name='newUser'),
url(r'^appHandler', views.appHandler, name='appHandler'),
url(r'^passToLogin', views.loginByPassword, name='passToLogin'),
url(r'^signToLogin', views.loginBySignature, name='signToLogin'),
url(r'^authUserHandler', views.authUserHandler, name='authUserHandler'),
)
| Java |
/*
* This file was autogenerated by the GPUdb schema processor.
*
* DO NOT EDIT DIRECTLY.
*/
package com.gpudb.protocol;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.avro.Schema;
import org.apache.avro.SchemaBuilder;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.IndexedRecord;
/**
* A set of parameters for {@link
* com.gpudb.GPUdb#filterByValue(FilterByValueRequest)}.
* <p>
* Calculates which objects from a table has a particular value for a
* particular column. The input parameters provide a way to specify either a
* String
* or a Double valued column and a desired value for the column on which the
* filter
* is performed. The operation is synchronous, meaning that a response will not
* be
* returned until all the objects are fully available. The response payload
* provides the count of the resulting set. A new result view which satisfies
* the
* input filter restriction specification is also created with a view name
* passed
* in as part of the input payload. Although this functionality can also be
* accomplished with the standard filter function, it is more efficient.
*/
public class FilterByValueRequest implements IndexedRecord {
private static final Schema schema$ = SchemaBuilder
.record("FilterByValueRequest")
.namespace("com.gpudb")
.fields()
.name("tableName").type().stringType().noDefault()
.name("viewName").type().stringType().noDefault()
.name("isString").type().booleanType().noDefault()
.name("value").type().doubleType().noDefault()
.name("valueStr").type().stringType().noDefault()
.name("columnName").type().stringType().noDefault()
.name("options").type().map().values().stringType().noDefault()
.endRecord();
/**
* This method supports the Avro framework and is not intended to be called
* directly by the user.
*
* @return the schema for the class.
*
*/
public static Schema getClassSchema() {
return schema$;
}
/**
* Optional parameters.
* <ul>
* <li> {@link
* com.gpudb.protocol.FilterByValueRequest.Options#COLLECTION_NAME
* COLLECTION_NAME}: [DEPRECATED--please specify the containing schema for
* the view as part of {@code viewName} and use {@link
* com.gpudb.GPUdb#createSchema(CreateSchemaRequest)} to create the schema
* if non-existent] Name of a schema for the newly created view. If the
* schema is non-existent, it will be automatically created.
* </ul>
* The default value is an empty {@link Map}.
* A set of string constants for the parameter {@code options}.
*/
public static final class Options {
/**
* [DEPRECATED--please specify the containing schema for the view as
* part of {@code viewName} and use {@link
* com.gpudb.GPUdb#createSchema(CreateSchemaRequest)} to create the
* schema if non-existent] Name of a schema for the newly created
* view. If the schema is non-existent, it will be automatically
* created.
*/
public static final String COLLECTION_NAME = "collection_name";
private Options() { }
}
private String tableName;
private String viewName;
private boolean isString;
private double value;
private String valueStr;
private String columnName;
private Map<String, String> options;
/**
* Constructs a FilterByValueRequest object with default parameters.
*/
public FilterByValueRequest() {
tableName = "";
viewName = "";
valueStr = "";
columnName = "";
options = new LinkedHashMap<>();
}
/**
* Constructs a FilterByValueRequest object with the specified parameters.
*
* @param tableName Name of an existing table on which to perform the
* calculation, in [schema_name.]table_name format, using
* standard <a
* href="../../../../../../concepts/tables/#table-name-resolution"
* target="_top">name resolution rules</a>.
* @param viewName If provided, then this will be the name of the view
* containing the results, in [schema_name.]view_name
* format, using standard <a
* href="../../../../../../concepts/tables/#table-name-resolution"
* target="_top">name resolution rules</a> and meeting <a
* href="../../../../../../concepts/tables/#table-naming-criteria"
* target="_top">table naming criteria</a>. Must not be
* an already existing table or view. The default value
* is ''.
* @param isString Indicates whether the value being searched for is
* string or numeric.
* @param value The value to search for. The default value is 0.
* @param valueStr The string value to search for. The default value is
* ''.
* @param columnName Name of a column on which the filter by value would
* be applied.
* @param options Optional parameters.
* <ul>
* <li> {@link
* com.gpudb.protocol.FilterByValueRequest.Options#COLLECTION_NAME
* COLLECTION_NAME}: [DEPRECATED--please specify the
* containing schema for the view as part of {@code
* viewName} and use {@link
* com.gpudb.GPUdb#createSchema(CreateSchemaRequest)} to
* create the schema if non-existent] Name of a schema for
* the newly created view. If the schema is non-existent,
* it will be automatically created.
* </ul>
* The default value is an empty {@link Map}.
*
*/
public FilterByValueRequest(String tableName, String viewName, boolean isString, double value, String valueStr, String columnName, Map<String, String> options) {
this.tableName = (tableName == null) ? "" : tableName;
this.viewName = (viewName == null) ? "" : viewName;
this.isString = isString;
this.value = value;
this.valueStr = (valueStr == null) ? "" : valueStr;
this.columnName = (columnName == null) ? "" : columnName;
this.options = (options == null) ? new LinkedHashMap<String, String>() : options;
}
/**
*
* @return Name of an existing table on which to perform the calculation,
* in [schema_name.]table_name format, using standard <a
* href="../../../../../../concepts/tables/#table-name-resolution"
* target="_top">name resolution rules</a>.
*
*/
public String getTableName() {
return tableName;
}
/**
*
* @param tableName Name of an existing table on which to perform the
* calculation, in [schema_name.]table_name format, using
* standard <a
* href="../../../../../../concepts/tables/#table-name-resolution"
* target="_top">name resolution rules</a>.
*
* @return {@code this} to mimic the builder pattern.
*
*/
public FilterByValueRequest setTableName(String tableName) {
this.tableName = (tableName == null) ? "" : tableName;
return this;
}
/**
*
* @return If provided, then this will be the name of the view containing
* the results, in [schema_name.]view_name format, using standard
* <a
* href="../../../../../../concepts/tables/#table-name-resolution"
* target="_top">name resolution rules</a> and meeting <a
* href="../../../../../../concepts/tables/#table-naming-criteria"
* target="_top">table naming criteria</a>. Must not be an already
* existing table or view. The default value is ''.
*
*/
public String getViewName() {
return viewName;
}
/**
*
* @param viewName If provided, then this will be the name of the view
* containing the results, in [schema_name.]view_name
* format, using standard <a
* href="../../../../../../concepts/tables/#table-name-resolution"
* target="_top">name resolution rules</a> and meeting <a
* href="../../../../../../concepts/tables/#table-naming-criteria"
* target="_top">table naming criteria</a>. Must not be
* an already existing table or view. The default value
* is ''.
*
* @return {@code this} to mimic the builder pattern.
*
*/
public FilterByValueRequest setViewName(String viewName) {
this.viewName = (viewName == null) ? "" : viewName;
return this;
}
/**
*
* @return Indicates whether the value being searched for is string or
* numeric.
*
*/
public boolean getIsString() {
return isString;
}
/**
*
* @param isString Indicates whether the value being searched for is
* string or numeric.
*
* @return {@code this} to mimic the builder pattern.
*
*/
public FilterByValueRequest setIsString(boolean isString) {
this.isString = isString;
return this;
}
/**
*
* @return The value to search for. The default value is 0.
*
*/
public double getValue() {
return value;
}
/**
*
* @param value The value to search for. The default value is 0.
*
* @return {@code this} to mimic the builder pattern.
*
*/
public FilterByValueRequest setValue(double value) {
this.value = value;
return this;
}
/**
*
* @return The string value to search for. The default value is ''.
*
*/
public String getValueStr() {
return valueStr;
}
/**
*
* @param valueStr The string value to search for. The default value is
* ''.
*
* @return {@code this} to mimic the builder pattern.
*
*/
public FilterByValueRequest setValueStr(String valueStr) {
this.valueStr = (valueStr == null) ? "" : valueStr;
return this;
}
/**
*
* @return Name of a column on which the filter by value would be applied.
*
*/
public String getColumnName() {
return columnName;
}
/**
*
* @param columnName Name of a column on which the filter by value would
* be applied.
*
* @return {@code this} to mimic the builder pattern.
*
*/
public FilterByValueRequest setColumnName(String columnName) {
this.columnName = (columnName == null) ? "" : columnName;
return this;
}
/**
*
* @return Optional parameters.
* <ul>
* <li> {@link
* com.gpudb.protocol.FilterByValueRequest.Options#COLLECTION_NAME
* COLLECTION_NAME}: [DEPRECATED--please specify the containing
* schema for the view as part of {@code viewName} and use {@link
* com.gpudb.GPUdb#createSchema(CreateSchemaRequest)} to create the
* schema if non-existent] Name of a schema for the newly created
* view. If the schema is non-existent, it will be automatically
* created.
* </ul>
* The default value is an empty {@link Map}.
*
*/
public Map<String, String> getOptions() {
return options;
}
/**
*
* @param options Optional parameters.
* <ul>
* <li> {@link
* com.gpudb.protocol.FilterByValueRequest.Options#COLLECTION_NAME
* COLLECTION_NAME}: [DEPRECATED--please specify the
* containing schema for the view as part of {@code
* viewName} and use {@link
* com.gpudb.GPUdb#createSchema(CreateSchemaRequest)} to
* create the schema if non-existent] Name of a schema for
* the newly created view. If the schema is non-existent,
* it will be automatically created.
* </ul>
* The default value is an empty {@link Map}.
*
* @return {@code this} to mimic the builder pattern.
*
*/
public FilterByValueRequest setOptions(Map<String, String> options) {
this.options = (options == null) ? new LinkedHashMap<String, String>() : options;
return this;
}
/**
* This method supports the Avro framework and is not intended to be called
* directly by the user.
*
* @return the schema object describing this class.
*
*/
@Override
public Schema getSchema() {
return schema$;
}
/**
* This method supports the Avro framework and is not intended to be called
* directly by the user.
*
* @param index the position of the field to get
*
* @return value of the field with the given index.
*
* @throws IndexOutOfBoundsException
*
*/
@Override
public Object get(int index) {
switch (index) {
case 0:
return this.tableName;
case 1:
return this.viewName;
case 2:
return this.isString;
case 3:
return this.value;
case 4:
return this.valueStr;
case 5:
return this.columnName;
case 6:
return this.options;
default:
throw new IndexOutOfBoundsException("Invalid index specified.");
}
}
/**
* This method supports the Avro framework and is not intended to be called
* directly by the user.
*
* @param index the position of the field to set
* @param value the value to set
*
* @throws IndexOutOfBoundsException
*
*/
@Override
@SuppressWarnings("unchecked")
public void put(int index, Object value) {
switch (index) {
case 0:
this.tableName = (String)value;
break;
case 1:
this.viewName = (String)value;
break;
case 2:
this.isString = (Boolean)value;
break;
case 3:
this.value = (Double)value;
break;
case 4:
this.valueStr = (String)value;
break;
case 5:
this.columnName = (String)value;
break;
case 6:
this.options = (Map<String, String>)value;
break;
default:
throw new IndexOutOfBoundsException("Invalid index specified.");
}
}
@Override
public boolean equals(Object obj) {
if( obj == this ) {
return true;
}
if( (obj == null) || (obj.getClass() != this.getClass()) ) {
return false;
}
FilterByValueRequest that = (FilterByValueRequest)obj;
return ( this.tableName.equals( that.tableName )
&& this.viewName.equals( that.viewName )
&& ( this.isString == that.isString )
&& ( (Double)this.value ).equals( (Double)that.value )
&& this.valueStr.equals( that.valueStr )
&& this.columnName.equals( that.columnName )
&& this.options.equals( that.options ) );
}
@Override
public String toString() {
GenericData gd = GenericData.get();
StringBuilder builder = new StringBuilder();
builder.append( "{" );
builder.append( gd.toString( "tableName" ) );
builder.append( ": " );
builder.append( gd.toString( this.tableName ) );
builder.append( ", " );
builder.append( gd.toString( "viewName" ) );
builder.append( ": " );
builder.append( gd.toString( this.viewName ) );
builder.append( ", " );
builder.append( gd.toString( "isString" ) );
builder.append( ": " );
builder.append( gd.toString( this.isString ) );
builder.append( ", " );
builder.append( gd.toString( "value" ) );
builder.append( ": " );
builder.append( gd.toString( this.value ) );
builder.append( ", " );
builder.append( gd.toString( "valueStr" ) );
builder.append( ": " );
builder.append( gd.toString( this.valueStr ) );
builder.append( ", " );
builder.append( gd.toString( "columnName" ) );
builder.append( ": " );
builder.append( gd.toString( this.columnName ) );
builder.append( ", " );
builder.append( gd.toString( "options" ) );
builder.append( ": " );
builder.append( gd.toString( this.options ) );
builder.append( "}" );
return builder.toString();
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = (31 * hashCode) + this.tableName.hashCode();
hashCode = (31 * hashCode) + this.viewName.hashCode();
hashCode = (31 * hashCode) + ((Boolean)this.isString).hashCode();
hashCode = (31 * hashCode) + ((Double)this.value).hashCode();
hashCode = (31 * hashCode) + this.valueStr.hashCode();
hashCode = (31 * hashCode) + this.columnName.hashCode();
hashCode = (31 * hashCode) + this.options.hashCode();
return hashCode;
}
}
| Java |
module Dragoman
module Mapper
def localize
locales = I18n.available_locales
unscoped_locales = [I18n.default_locale]
scoped_locales = locales - unscoped_locales
scope ':locale', shallow_path: ':locale', defaults: {dragoman_options: {locales: scoped_locales}} do
yield
end
defaults dragoman_options: {locales: unscoped_locales} do
yield
end
@locales = nil
end
end
end | Java |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NugetCompare.UI.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NugetCompare.UI.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>infotheo: 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.13.0 / infotheo - 0.3.2</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
infotheo
<small>
0.3.2
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-02-11 02:59:41 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-11 02:59:41 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 4 Virtual package relying on a GMP lib system installation
coq 8.13.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.13.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.13.1 Official release 4.13.1
ocaml-config 2 OCaml Switch Configuration
ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Reynald Affeldt <reynald.affeldt@aist.go.jp>"
homepage: "https://github.com/affeldt-aist/infotheo"
dev-repo: "git+https://github.com/affeldt-aist/infotheo.git"
bug-reports: "https://github.com/affeldt-aist/infotheo/issues"
license: "LGPL-2.1-or-later"
synopsis: "Discrete probabilities and information theory for Coq"
description: """
Infotheo is a Coq library for reasoning about discrete probabilities,
information theory, and linear error-correcting codes."""
build: [
[make "-j%{jobs}%" ]
[make "-C" "extraction" "tests"] {with-test}
]
install: [make "install"]
depends: [
"coq" { (>= "8.13" & < "8.14~") | (= "dev") }
"coq-mathcomp-ssreflect" { (>= "1.12.0" & < "1.13~") }
"coq-mathcomp-fingroup" { (>= "1.12.0" & < "1.13~") }
"coq-mathcomp-algebra" { (>= "1.12.0" & < "1.13~") }
"coq-mathcomp-solvable" { (>= "1.12.0" & < "1.13~") }
"coq-mathcomp-field" { (>= "1.12.0" & < "1.13~") }
"coq-mathcomp-analysis" { (>= "0.3.6" & < "0.3.8") }
]
tags: [
"keyword:information theory"
"keyword:probability"
"keyword:error-correcting codes"
"keyword:convexity"
"logpath:infotheo"
"date:2021-03-23"
]
authors: [
"Reynald Affeldt, AIST"
"Manabu Hagiwara, Chiba U. (previously AIST)"
"Jonas Senizergues, ENS Cachan (internship at AIST)"
"Jacques Garrigue, Nagoya U."
"Kazuhiko Sakaguchi, Tsukuba U."
"Taku Asai, Nagoya U. (M2)"
"Takafumi Saikawa, Nagoya U."
"Naruomi Obata, Titech (M2)"
]
url {
http: "https://github.com/affeldt-aist/infotheo/archive/0.3.2.tar.gz"
checksum: "sha512=ab3a82c343eb3b1fc164e95cc963612310f06a400e3fb9781c28b4afb37356a57a99d236cd788d925ae5f2c8ce8f96850ad40d5a79306daca69db652c268d5f8"
}
</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-infotheo.0.3.2 coq.8.13.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.13.0).
The following dependencies couldn't be met:
- coq-infotheo -> coq-mathcomp-analysis < 0.3.8 -> coq-mathcomp-finmap < 1.4~ -> coq < 8.11.1 -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
- coq-infotheo -> coq-mathcomp-analysis < 0.3.8 -> coq-mathcomp-finmap < 1.4~ -> coq-mathcomp-ssreflect < 1.8~ -> coq < 8.10~ -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
- coq-infotheo -> coq-mathcomp-analysis < 0.3.8 -> coq-hierarchy-builder (< 1.1.0 | >= dev) -> coq < 8.12.0~ -> ocaml < 4.12
base of this switch (use `--unlock-base' to force)
- coq-infotheo -> coq-mathcomp-analysis < 0.3.8 -> coq-hierarchy-builder (< 1.1.0 | >= dev) -> coq-elpi -> ocaml < 4.12~
base of this switch (use `--unlock-base' to force)
- coq-infotheo -> coq-mathcomp-analysis < 0.3.8 -> coq-hierarchy-builder (< 1.1.0 | >= dev) -> coq-elpi -> elpi < 1.14.0~ -> camlp5 < 8.00~alpha01 -> ocaml < 4.13.0
base of this switch (use `--unlock-base' to force)
- coq-infotheo -> coq-mathcomp-analysis < 0.3.8 -> coq-hierarchy-builder (< 1.1.0 | >= dev) -> coq-elpi -> elpi < 1.14.0~ -> ocaml-migrate-parsetree < 2.0.0 -> ocaml < 4.13
base of this switch (use `--unlock-base' to force)
- coq-infotheo -> coq-mathcomp-analysis < 0.3.8 -> coq-hierarchy-builder (< 1.1.0 | >= dev) -> coq-elpi -> elpi < 1.14.0~ -> ppx_tools_versioned < 5.2.1 -> ocaml < 4.08.0
base of this switch (use `--unlock-base' to force)
- coq-infotheo -> coq-mathcomp-analysis < 0.3.8 -> coq-hierarchy-builder (< 1.1.0 | >= dev) -> coq-elpi -> coq < 8.13~ -> ocaml < 4.12
base of this switch (use `--unlock-base' to force)
- coq-infotheo -> coq-mathcomp-analysis < 0.3.8 -> coq < 8.9~ -> ocaml < 4.12
base of this switch (use `--unlock-base' to force)
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-infotheo.0.3.2</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://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</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>
| Java |
<?php
if(!defined('BASEPATH'))
die;
class MY_Controller extends CI_Controller
{
public $session;
public $user;
function __construct(){
parent::__construct();
$this->output->set_header('X-Powered-By: ' . config_item('system_vendor'));
$this->output->set_header('X-Deadpool: ' . config_item('header_message'));
$this->load->library('SiteEnum', '', 'enum');
$this->load->library('SiteParams', '', 'setting');
$this->load->library('SiteTheme', '', 'theme');
$this->load->library('SiteMenu', '', 'menu');
$this->load->library('SiteForm', '', 'form');
$this->load->library('SiteMeta', '', 'meta');
$this->load->library('ObjectMeta', '', 'ometa');
$this->load->library('ActionEvent', '', 'event');
$cookie_name = config_item('sess_cookie_name');
$hash = $this->input->cookie($cookie_name);
if($hash){
$this->load->model('Usersession_model', 'USession');
$session = $this->USession->getBy('hash', $hash);
$this->session = $session;
if($session){
$this->load->model('User_model', 'User');
$user = $this->User->get($session->user);
// TODO
// Increase session expiration if it's almost expired
if($user && $user->status > 1){
$this->user = $user;
$this->user->perms = [];
if($user){
if($user->id == 1){
$this->load->model('Perms_model', 'Perms');
$user_perms = $this->Perms->getByCond([], true, false);
$this->user->perms = prop_values($user_perms, 'name');
}else{
$this->load->model('Userperms_model', 'UPerms');
$user_perms = $this->UPerms->getBy('user', $user->id, true);
if($user_perms)
$this->user->perms = prop_values($user_perms, 'perms');
}
$this->user->perms[] = 'logged_in';
}
}
}
}
if($this->theme->current() == 'admin/')
$this->lang->load('admin', config_item('language'));
}
/**
* Return to client as ajax respond.
* @param mixed data The data to return.
* @param mixed error The error data.
* @param mixed append Additional data to append to result.
*/
public function ajax($data, $error=false, $append=null){
$result = array(
'data' => $data,
'error'=> $error
);
if($append)
$result = array_merge($result, $append);
$cb = $this->input->get('cb');
if(!$cb)
$cb = $this->input->get('callback');
$json = json_encode($result);
$cset = config_item('charset');
if($cb){
$json = "$cb($json);";
$this->output
->set_status_header(200)
->set_content_type('application/javascript', $cset)
->set_output($json)
->_display();
exit;
}else{
$this->output
->set_status_header(200)
->set_content_type('application/json', $cset)
->set_output($json)
->_display();
exit;
}
}
/**
* Check if current admin user can do something
* @param string perms The perms to check.
* @return boolean true on allowed, false otherwise.
*/
public function can_i($perms){
if(!$this->user)
return false;
return in_array($perms, $this->user->perms);
}
/**
* Redirect to some URL.
* @param string next Target URL.
* @param integer status Redirect status.
*/
public function redirect($next='/', $status=NULL){
if(substr($next, 0, 4) != 'http')
$next = base_url($next);
redirect($next, 'auto', $status);
}
/**
* Print page.
* @param string view The view to load.
* @param array params The parameters to send to view.
*/
public function respond($view, $params=array()){
$page_title = '';
if(array_key_exists('title', $params))
$page_title = $params['title'] . ' - ';
$page_title.= $this->setting->item('site_name');
$params['page_title'] = $page_title;
if(!$this->theme->exists($view) && !is_dev())
return $this->show_404();
$this->theme->load($view, $params);
}
/**
* Print 404 page
*/
public function show_404(){
$this->load->model('Urlredirection_model', 'Redirection');
$next = $this->Redirection->getBy('source', uri_string());
if($next)
return $this->redirect($next->target, 301);
$this->output->set_status_header('404');
$params = array(
'title' => _l('Page not found')
);
$this->respond('404', $params);
}
} | Java |
/* ================================================================
* startserver by xdf(xudafeng[at]126.com)
*
* first created at : Mon Jun 02 2014 20:15:51 GMT+0800 (CST)
*
* ================================================================
* Copyright 2013 xdf
*
* Licensed under the MIT License
* You may not use this file except in compliance with the License.
*
* ================================================================ */
'use strict';
var logx = require('logx');
function *logger() {
var log = 'Method: '.gray + this.req.method.red;
log += ' Url: '.gray + this.req.url.red;
logx.info(log);
yield this.next();
}
module.exports = logger;
| Java |
/**
* Default admin
*/
new User({
firstName: 'Admin',
lastName: 'Admin',
username: 'admin',
type: 'admin',
password: 'admin',
email: 'admin@admin.com',
subscribed: false,
}).save((u) => {
})
/**
* Test users
*/
new User({
firstName: 'Jonathan',
lastName: 'Santos',
username: 'santojon',
type: 'user',
password: 'test',
email: 'santojon5@gmail.com',
gender: 'Male',
subscribed: true,
image: 'https://avatars1.githubusercontent.com/u/4976482'
}).save((u) => {
UserController.updateUser(u)
})
new User({
firstName: 'Raphael',
lastName: 'Tulyo',
username: 'crazybird',
type: 'user',
password: 'test',
email: 'rtsd@cin.ufpe.br',
gender: 'Male',
subscribed: true
}).save((u) => {
UserController.updateUser(u)
})
new User({
firstName: 'Vinícius',
lastName: 'Emanuel',
username: 'vems',
type: 'user',
password: 'test',
email: 'vems@cin.ufpe.br',
gender: 'Male',
subscribed: true
}).save((u) => {
UserController.updateUser(u)
})
/**
* More test users
*/
for (i = 0; i < 5; i++) {
new User({
firstName: 'Test' + i,
lastName: '' + i,
username: 'testuser' + i,
type: 'user',
password: 'test',
email: 'test' + i + '@test.br',
gender: (i % 2 === 0) ? 'Male' : 'Female',
subscribed: true
}).save((u) => {
UserController.updateUser(u)
})
}
Subscription.findAll().forEach((s) => {
s.status = true
s.update(s)
}) | Java |
---
layout: page
title: Mcclain Family Reunion
date: 2016-05-24
author: Roger Moss
tags: weekly links, java
status: published
summary: Nullam hendrerit elit lectus. Vestibulum in purus efficitur.
banner: images/banner/leisure-04.jpg
booking:
startDate: 02/07/2019
endDate: 02/11/2019
ctyhocn: PRIWVHX
groupCode: MFR
published: true
---
Donec interdum pulvinar ex id pharetra. Morbi accumsan, ligula non dignissim pellentesque, arcu est semper massa, in congue lectus metus vitae purus. Vestibulum sit amet elementum ante. Sed efficitur maximus pulvinar. Praesent laoreet justo in dui consequat, dictum elementum mauris maximus. Morbi ultrices tortor nec porta tincidunt. Donec et lectus tortor. Vestibulum porttitor venenatis odio id tincidunt.
In pellentesque tortor a metus fringilla, eu tincidunt lorem feugiat. Praesent pulvinar metus ac quam mattis, nec maximus eros pretium. Nullam et nulla a mauris semper venenatis. Fusce lacus mauris, vehicula vel diam quis, auctor venenatis mi. Vivamus ac urna dui. Duis porttitor tincidunt metus quis lobortis. Donec ut velit felis. Vivamus justo ex, suscipit non turpis sed, lacinia commodo dui. Vivamus tristique finibus arcu ac condimentum. Sed vel risus quis urna fringilla hendrerit et id tellus. Nam suscipit massa a dignissim scelerisque. Nullam nisl felis, imperdiet eu dui non, iaculis rutrum orci.
1 Nullam vehicula orci sit amet felis euismod varius
1 Morbi feugiat ex vel lectus pharetra, sed gravida metus facilisis.
Cras nec lobortis augue. Vestibulum enim massa, dapibus sagittis ornare vitae, feugiat nec arcu. Sed id augue leo. In hac habitasse platea dictumst. Donec ullamcorper sapien a egestas commodo. Praesent non elit mollis mi sodales egestas sit amet nec elit. Suspendisse eget efficitur enim. Quisque libero quam, volutpat sed commodo sed, gravida et purus. Nam bibendum ipsum quis justo convallis, vel porttitor purus ullamcorper. Mauris id gravida velit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Fusce sed gravida urna, sed mattis arcu. Aenean facilisis at ex at porta. Nullam semper eget est eget dapibus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce efficitur arcu in erat vestibulum tempus. Cras aliquet, sapien feugiat scelerisque lobortis, tellus ex mollis ipsum, a convallis quam ipsum id ligula. Mauris porta tristique turpis, eget feugiat sapien sollicitudin sed. Nullam porttitor sagittis mi, vitae pharetra enim efficitur et. Etiam hendrerit ac metus sed viverra. Ut ipsum nisi, luctus eget ex ac, volutpat maximus justo. Fusce vulputate iaculis dignissim. Duis placerat facilisis purus ut tristique.
| Java |
---
layout: page
title: Purple Systems Seminar
date: 2016-05-24
author: Martha Chandler
tags: weekly links, java
status: published
summary: Fusce risus orci, porttitor id molestie sit amet, mollis.
banner: images/banner/meeting-01.jpg
booking:
startDate: 10/13/2016
endDate: 10/14/2016
ctyhocn: FTWMFHX
groupCode: PSS
published: true
---
Phasellus pretium nulla id risus congue maximus. Fusce elementum elementum facilisis. Suspendisse ut venenatis nunc. Nulla euismod, elit non semper aliquam, odio leo pellentesque turpis, vitae feugiat lorem purus in purus. Vestibulum accumsan bibendum felis, vitae volutpat nunc fringilla et. Quisque eros nunc, congue in pharetra ut, lacinia quis urna. Praesent a enim vitae turpis fringilla tristique. Mauris euismod elit id nunc mollis porttitor. In ultricies est libero, non porttitor ante eleifend pharetra. Quisque tincidunt sapien sollicitudin urna viverra rutrum. Quisque molestie leo libero, nec porttitor tortor vestibulum tempor. Nullam vel ullamcorper quam, at euismod nunc. Etiam faucibus nisl eros, id tempor enim pellentesque vel.
* Pellentesque porttitor eros a diam faucibus commodo.
In sit amet leo diam. Phasellus sollicitudin porta mi, in venenatis lectus ultricies sit amet. Aliquam eu porta nisl. Maecenas nec est eget enim elementum elementum vel ac justo. Ut aliquam tellus non commodo pulvinar. Curabitur pharetra ligula vel orci maximus viverra. Duis a blandit dolor. Vestibulum sit amet venenatis nulla. Mauris lectus eros, pellentesque vitae urna in, vulputate blandit augue. Suspendisse potenti. Fusce a euismod nisl, eu imperdiet sem. Aliquam nec finibus elit. Praesent odio velit, bibendum et leo et, rhoncus ornare odio.
| Java |
---
title: "Suriname"
published: true
featured_image_path:
featured_image_attribution:
geocode: SUR
iso_code: SR
territory:
state_party: true
signed_but_not_ratified: false
signed_date:
ratified_or_acceded_date: 2008-07-15T00:00:00.000Z
entry_into_force_date: 2008-10-01T00:00:00.000Z
ratified_apic_date:
genocide:
crimes_against_humanity:
aggression:
war_crimes:
note:
slug: suriname
---
| Java |
/**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highstock]]
*/
package com.highstock.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>plotOptions-solidgauge-dragDrop-guideBox-default</code>
*/
@js.annotation.ScalaJSDefined
class PlotOptionsSolidgaugeDragDropGuideBoxDefault extends com.highcharts.HighchartsGenericObject {
/**
* <p>CSS class name of the guide box in this state. Defaults to
* <code>highcharts-drag-box-default</code>.</p>
* @since 6.2.0
*/
val className: js.UndefOr[String] = js.undefined
/**
* <p>Width of the line around the guide box.</p>
* @since 6.2.0
*/
val lineWidth: js.UndefOr[Double] = js.undefined
/**
* <p>Color of the border around the guide box.</p>
* @since 6.2.0
*/
val lineColor: js.UndefOr[String | js.Object] = js.undefined
/**
* <p>Guide box fill color.</p>
* @since 6.2.0
*/
val color: js.UndefOr[String | js.Object] = js.undefined
/**
* <p>Guide box cursor.</p>
* @since 6.2.0
*/
val cursor: js.UndefOr[String] = js.undefined
/**
* <p>Guide box zIndex.</p>
* @since 6.2.0
*/
val zIndex: js.UndefOr[Double] = js.undefined
}
object PlotOptionsSolidgaugeDragDropGuideBoxDefault {
/**
* @param className <p>CSS class name of the guide box in this state. Defaults to. <code>highcharts-drag-box-default</code>.</p>
* @param lineWidth <p>Width of the line around the guide box.</p>
* @param lineColor <p>Color of the border around the guide box.</p>
* @param color <p>Guide box fill color.</p>
* @param cursor <p>Guide box cursor.</p>
* @param zIndex <p>Guide box zIndex.</p>
*/
def apply(className: js.UndefOr[String] = js.undefined, lineWidth: js.UndefOr[Double] = js.undefined, lineColor: js.UndefOr[String | js.Object] = js.undefined, color: js.UndefOr[String | js.Object] = js.undefined, cursor: js.UndefOr[String] = js.undefined, zIndex: js.UndefOr[Double] = js.undefined): PlotOptionsSolidgaugeDragDropGuideBoxDefault = {
val classNameOuter: js.UndefOr[String] = className
val lineWidthOuter: js.UndefOr[Double] = lineWidth
val lineColorOuter: js.UndefOr[String | js.Object] = lineColor
val colorOuter: js.UndefOr[String | js.Object] = color
val cursorOuter: js.UndefOr[String] = cursor
val zIndexOuter: js.UndefOr[Double] = zIndex
com.highcharts.HighchartsGenericObject.toCleanObject(new PlotOptionsSolidgaugeDragDropGuideBoxDefault {
override val className: js.UndefOr[String] = classNameOuter
override val lineWidth: js.UndefOr[Double] = lineWidthOuter
override val lineColor: js.UndefOr[String | js.Object] = lineColorOuter
override val color: js.UndefOr[String | js.Object] = colorOuter
override val cursor: js.UndefOr[String] = cursorOuter
override val zIndex: js.UndefOr[Double] = zIndexOuter
})
}
}
| Java |
---
layout: home
title: Borislav Stanimirov
stylesheet: homepage
---
| Java |
using UnityEngine;
using System.Collections;
public class GravitySwitch : MonoBehaviour
{
public float GravityStrength;
float momentum;
float click;
public bool GameState;
bool GravityState;
public GameObject Explosion;
public GameObject[] Jets;
public GameObject[] CharacterPieces;
public Vector3 hitposition;
public GameObject EndScreen;
public UILabel BestScore;
void Start()
{
GravityStrength = 0;
BestScore.text = "Best:" + PlayerPrefs.GetFloat("BestScore").ToString();
GameState = true;
}
void Update ()
{
Gravity();
Controls();
if (GameState == false)
{
transform.position = hitposition;
EndScreen.SetActive(true);
}
}
void Gravity()
{
//transform.Translate(new Vector3(3,0) * Time.deltaTime);
switch (GravityState)
{
case true: Physics2D.gravity = new Vector2(momentum,GravityStrength); /*transform.localEulerAngles = new Vector2(-180, 0);*/ break;
case false: Physics2D.gravity = new Vector2(momentum,-GravityStrength); /*transform.localEulerAngles = new Vector2(0, 0);*/ break;
}
if (GravityStrength == 0)
{
transform.position = new Vector3(0,-5.5f,0);
}
}
void Controls()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GravityState = !GravityState;
}
if (Input.GetMouseButtonDown(0))
{
GravityState = !GravityState;
if (click == 0)
{
momentum = 2;
GravityStrength = 27;
foreach(GameObject jet in Jets)
{
jet.SetActive(true);
}
}
click+=1;
}
}
void OnCollisionEnter2D(Collision2D other)
{
//Application.LoadLevel(Application.loadedLevel);
if (GameState == true)
{
foreach (ContactPoint2D contact in other.contacts)
{
GameObject Hit = Instantiate (Explosion, contact.point, Quaternion.identity) as GameObject;
hitposition = Hit.transform.position;
GameState = false;
}
foreach (GameObject self in CharacterPieces)
{
self.SetActive(false);
}
}
}
}
| Java |
<h1>Most Viewed</h1>
<table class="table table-hover">
<thead>
<tr>
<th>Tool ID</th>
<th>Tool Name</th>
<th>Tool Description</th>
<th>Extent</th>
<th>Rating</th>
<th>Views</th>
</tr>
</thead>
<tbody>
<tr>
<td>#1</td>
<td>Test Pro</td>
<td>This tool creates auto testing scripts</td>
<td>Enterprise</td>
<td>3/5</td>
<td>4589</td>
</tr>
<tr>
<td>#2</td>
<td>Script Builder</td>
<td>This tool auto builds the scripts</td>
<td>Application</td>
<td>4/5</td>
<td>9768</td>
</tr>
<tr>
<td>#3</td>
<td>Bootstrap Builder</td>
<td>Auto build responsive websites</td>
<td>Technology</td>
<td>5/5</td>
<td>759</td>
</tr>
</tbody>
</table> | Java |
import sys
import pytest
from opentracing.ext import tags
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import mysqldb as mysqldb_hooks
from opentracing_instrumentation.request_context import span_in_context
from .sql_common import metadata, User
SKIP_REASON_PYTHON_3 = 'MySQLdb is not compatible with Python 3'
SKIP_REASON_CONNECTION = 'MySQL is not running or cannot connect'
MYSQL_CONNECTION_STRING = 'mysql://root@127.0.0.1/test'
@pytest.fixture
def session():
Session = sessionmaker()
engine = create_engine(MYSQL_CONNECTION_STRING)
Session.configure(bind=engine)
metadata.create_all(engine)
try:
yield Session()
except:
pass
@pytest.fixture(autouse=True, scope='module')
def patch_sqlalchemy():
mysqldb_hooks.install_patches()
try:
yield
finally:
mysqldb_hooks.reset_patches()
def is_mysql_running():
try:
import MySQLdb
with MySQLdb.connect(host='127.0.0.1', user='root'):
pass
return True
except:
return False
def assert_span(span, operation, parent=None):
assert span.operation_name == 'MySQLdb:' + operation
assert span.tags.get(tags.SPAN_KIND) == tags.SPAN_KIND_RPC_CLIENT
if parent:
assert span.parent_id == parent.context.span_id
assert span.context.trace_id == parent.context.trace_id
else:
assert span.parent_id is None
@pytest.mark.skipif(not is_mysql_running(), reason=SKIP_REASON_CONNECTION)
@pytest.mark.skipif(sys.version_info.major == 3, reason=SKIP_REASON_PYTHON_3)
def test_db(tracer, session):
root_span = tracer.start_span('root-span')
# span recording works for regular operations within a context only
with span_in_context(root_span):
user = User(name='user', fullname='User', password='password')
session.add(user)
session.commit()
spans = tracer.recorder.get_spans()
assert len(spans) == 4
connect_span, insert_span, commit_span, rollback_span = spans
assert_span(connect_span, 'Connect')
assert_span(insert_span, 'INSERT', root_span)
assert_span(commit_span, 'commit', root_span)
assert_span(rollback_span, 'rollback', root_span)
| Java |
// Write a boolean expression that returns if the bit at position p (counting from 0)
// in a given integer number v has value of 1. Example: v=5; p=1 -> false.
using System;
class BitInIntegerCheck
{
static void Main()
{
// декларираме променливи за числото (v) и позицията (p), за която ще проверяваме
int v = 8;
int p = 3;
// израза е прекалено лесен и не мисля, че си заслужава декларацията на 2 допълнителни променливи...
// умножаваме "v" с 1 предварително отместено "p" пъти наляво, след което резултатът бива отместен "p" пъти надясно
// със същият успех може и да се премести единицата от дясната страна на израза "p" пъти наляво,
// като по този начин си спестяваме връщането "p" пъти надясно от другата страна на равенството и е по-лесно за разбиране/четене
// => if( v & ( 1 << p ) == 1 << p )
if( ( v & ( 1 << p ) ) >> p == 1 )
{
Console.WriteLine("The value {0} has a 1 at bit number {1}", v, p);
}
else
{
Console.WriteLine("The value {0} has a 0 at bit number {1}", v, p);
}
}
} | Java |
<header role="banner" id="top">
<div class="mdj-header">
<div style="flex-grow: 2;">
<div class="mdj-card">
<div class="mdj-card--photo">
<a href="{{ site.baseurl }}/"><img class="mdj-card--photo__rainbow" src="/assets/mdjablonski-white.jpg"></a>
</div>
<div class="mdj-card--desc">
<h2 class="mdj-header--title"><a href="{{ site.baseurl }}/">Marcin Dominik Jabłoński</a></h2>
<p class="mdj-header--subtitle"><a href="{{ site.baseurl }}/">Product & UX designer</a></p>
</div>
</div>
<div class="mdj-dialog">
<span class="mdj-dialog--arrow"></span>
<span class="mdj-dialog--bubble">Hello!<span class="hello"></span>Welcome to my website.</span>
</div>
</div>
<nav role="navigation">
<ul class="mdj-menu">
<li><a class="mdj-menu__about" href="{{ site.baseurl }}/"><span></span>About me</a></li>
<li><a class="mdj-menu__portfolio" href="{{ site.baseurl }}/ux-portfolio/"><span></span>UX portfolio</a></li>
<li><a class="mdj-menu__articles" href="{{ site.baseurl }}/articles/"><span></span>Articles</a></li>
</ul>
</nav>
</div>
</header> | Java |
/*
* Copyright 2017 Max Schafer, Ammar Mahdi, Riley Dixon, Steven Weikai Lu, Jiaxiong Yang
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.example.lit.habit;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Base64;
import android.util.Log;
import com.example.lit.exception.BitmapTooLargeException;
import com.example.lit.exception.HabitFormatException;
import com.example.lit.saving.Saveable;
import com.example.lit.exception.HabitFormatException;
import io.searchbox.annotations.JestId;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* This class is an abstract habit class
* @author Steven Weikai Lu
*/
public abstract class Habit implements Habitable , Parcelable, Saveable {
private String title;
private SimpleDateFormat format;
private Date date;
public abstract String habitType();
private String user;
private String reason;
private int titleLength = 20;
private int reasonLength = 30;
private List<Calendar> calendars;
private List<Date> dates;
private String encodedImage;
@JestId
private String id;
private Bitmap image;
public String getID(){ return id ;}
public void setID(String id){ this.id = id ;}
public Habit(String title) throws HabitFormatException {
this.setTitle(title);
this.setDate(new Date());
}
public Habit(String title, Date date) throws HabitFormatException{
this.setTitle(title);
this.setDate(date);
}
public Habit(String title, Date date, String reason) throws HabitFormatException {
this.setTitle(title);
this.setDate(date);
this.setReason(reason);
}
/**
* This is the main constructor we are using in AddHabitActivity
*
* @see com.example.lit.activity.AddHabitActivity
* @param title Habit name, should be at most 20 char long.
* @param reason Habit Comment, should be at most 30 char long.
* @param date Set by GPS when creating the habit
* @param calendarList Set by user when creating the habit
* @throws HabitFormatException thrown when title longer than 20 char or reason longer than 30 char
* */
public Habit(String title, Date date, String reason, List<Calendar> calendarList) throws HabitFormatException {
this.setTitle(title);
this.setDate(date);
this.setReason(reason);
this.setCalendars(calendarList);
}
public Habit(String title, Date date, String reason, List<Calendar> calendars, Bitmap image)throws HabitFormatException, BitmapTooLargeException{
this.setTitle(title);
this.setDate(date);
this.setReason(reason);
this.setCalendars(calendars);
this.setImage(image);
}
// TODO: Constructor with JestID
public String getTitle() {
return title;
}
public void setTitle(String title) throws HabitFormatException {
if (title.length() > this.titleLength){
throw new HabitFormatException();
}
this.title = title;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public Date getDate() {
return date;
}
/**
* Function takes in a Date object and formats it to dd-MM-yyyy
* @param date
*/
public void setDate(Date date) {
// Format the current time.
SimpleDateFormat format = new SimpleDateFormat ("dd-MM-yyyy");
String dateString = format.format(date);
// Parse the previous string back into a Date.
ParsePosition pos = new ParsePosition(0);
this.date = format.parse(dateString, pos);
}
public String getReason() {
return reason;
}
public void setReason(String reason) throws HabitFormatException {
if (reason.length() < this.reasonLength) {
this.reason = reason;
}
else {
throw new HabitFormatException();
}
}
public List<Calendar> getCalendars() {
return calendars;
}
public void setCalendars(List<Calendar> calendars) {
this.calendars = calendars;
}
public Bitmap getImage() {
if(encodedImage != null) {
byte[] decodedString = Base64.decode(this.encodedImage, Base64.DEFAULT);
this.image = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
}
return this.image;
}
/**
* Function takes in a Bitmap object and decodes it to a 64Base string
* @param image
* @throws BitmapTooLargeException
*/
public void setImage(Bitmap image) throws BitmapTooLargeException {
if (image == null){
this.image = null;
}
else if (image.getByteCount() > 65536){
throw new BitmapTooLargeException();
}
else {
this.image = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] byteArray = baos.toByteArray();
this.encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
//Log.i("encoded",this.encodedImage);
}
}
@Override
public String toString() {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
return "Habit Name: " + this.getTitle() + '\n' +
"Started From: " + format.format(this.getDate());
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.title);
dest.writeSerializable(this.format);
dest.writeLong(this.date != null ? this.date.getTime() : -1);
dest.writeString(this.user);
dest.writeString(this.reason);
dest.writeInt(this.titleLength);
dest.writeInt(this.reasonLength);
dest.writeList(this.calendars);
dest.writeList(this.dates);
dest.writeString(this.encodedImage);
dest.writeString(this.id);
dest.writeParcelable(this.image, flags);
}
protected Habit(Parcel in) {
this.title = in.readString();
this.format = (SimpleDateFormat) in.readSerializable();
long tmpDate = in.readLong();
this.date = tmpDate == -1 ? null : new Date(tmpDate);
this.user = in.readString();
this.reason = in.readString();
this.titleLength = in.readInt();
this.reasonLength = in.readInt();
this.calendars = new ArrayList<Calendar>();
in.readList(this.calendars, Calendar.class.getClassLoader());
this.dates = new ArrayList<Date>();
in.readList(this.dates, Date.class.getClassLoader());
this.encodedImage = in.readString();
this.id = in.readString();
this.image = in.readParcelable(Bitmap.class.getClassLoader());
}
}
| Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Privacy Policy</title>
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
padding: 1em;
}
</style>
</head>
<body>
<h2>Privacy Policy</h2>
<p> Bobgoo SLU built the Bobzon for Amazon app as an Ad Supported app. This SERVICE is provided by Bobgoo SLU at no cost and is intended for use as is.
</p>
<p>This page is used to inform website visitors regarding our policies with the collection, use, and disclosure of Personal Information if anyone decided to use our Service.
</p>
<p>If you choose to use our Service, then you agree to the collection and use of information in relation to this policy. The Personal Information that we collect is used for providing and improving the Service. We will not use or share your information with anyone except as described in this Privacy Policy.
</p>
<p>The terms used in this Privacy Policy have the same meanings as in our Terms and Conditions, which is accessible at Bobzon for Amazon unless otherwise defined in this Privacy Policy.
</p>
<p><strong>Information Collection and Use</strong></p>
<p>For a better experience, while using our Service, we may require you to provide us with certain personally identifiable information. The information that we request is retained on your device and is not collected by us in any way.
</p>
<p>The app does use third party services that may collect information used to identify you.</p>
<div>
<p>Link to privacy policy of third party service providers used by the app </p>
<ul>
<!---->
<li><a href="https://www.google.com/policies/privacy/" target="_blank">Google Play Services</a></li>
<li><a href="https://support.google.com/admob/answer/6128543?hl=en" target="_blank">AdMob</a></li>
<li><a href="https://firebase.google.com/policies/analytics" target="_blank">Firebase Analytics</a></li>
<li><a href="https://fabric.io/privacy" target="_blank">Fabric</a></li>
<li><a href="http://try.crashlytics.com/terms/privacy-policy.pdf" target="_blank">Crashlytics</a></li>
<!---->
</ul>
</div>
<p><strong>Log Data</strong></p>
<p> We want to inform you that whenever you use our Service, in a case of an error in the app we collect data and information (through third party products) on your phone called Log Data. This Log Data may include information such as your device Internet Protocol (“IP”) address, device name, operating system version, the configuration of the app when utilizing our Service, the time and date of your use of the Service, and other statistics.
</p>
<p><strong>Cookies</strong></p>
<p>Cookies are files with small amount of data that is commonly used an anonymous unique identifier. These are sent to your browser from the website that you visit and are stored on your device internal memory.
</p>
<p>This Service does not use these “cookies” explicitly. However, the app may use third party code and libraries that use “cookies” to collection information and to improve their services. You have the option to either accept or refuse these cookies and know when a cookie is being sent to your device. If you choose to refuse our cookies, you may not be able to use some portions of this Service.
</p>
<p><strong>Service Providers</strong></p>
<p> We may employ third-party companies and individuals due to the following reasons:</p>
<ul>
<li>To facilitate our Service;</li>
<li>To provide the Service on our behalf;</li>
<li>To perform Service-related services; or</li>
<li>To assist us in analyzing how our Service is used.</li>
</ul>
<p> We want to inform users of this Service that these third parties have access to your Personal Information. The reason is to perform the tasks assigned to them on our behalf. However, they are obligated not to disclose or use the information for any other purpose.
</p>
<p><strong>Security</strong></p>
<p> We value your trust in providing us your Personal Information, thus we are striving to use commercially acceptable means of protecting it. But remember that no method of transmission over the internet, or method of electronic storage is 100% secure and reliable, and we cannot guarantee its absolute security.
</p>
<p><strong>Links to Other Sites</strong></p>
<p>This Service may contain links to other sites. If you click on a third-party link, you will be directed to that site. Note that these external sites are not operated by us. Therefore, we strongly advise you to review the Privacy Policy of these websites. We have no control over and assume no responsibility for the content, privacy policies, or practices of any third-party sites or services.
</p>
<p><strong>Children’s Privacy</strong></p>
<p>These Services do not address anyone under the age of 13. We do not knowingly collect personally identifiable information from children under 13. In the case we discover that a child under 13 has provided us with personal information, we immediately delete this from our servers. If you are a parent or guardian and you are aware that your child has provided us with personal information, please contact us so that we will be able to do necessary actions.
</p>
<p><strong>Changes to This Privacy Policy</strong></p>
<p> We may update our Privacy Policy from time to time. Thus, you are advised to review this page periodically for any changes. We will notify you of any changes by posting the new Privacy Policy on this page. These changes are effective immediately after they are posted on this page.
</p>
<p><strong>Contact Us</strong></p>
<p>If you have any questions or suggestions about our Privacy Policy, do not hesitate to contact us.
</p>
<br>
<p>Last Edited on 2019-02-19</p>
</body>
</html> | Java |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M2 21.5c0 .28.22.5.49.5h13.02c.27 0 .49-.22.49-.5V20H2v1.5zM15.5 16H11v-2H7v2H2.5c-.28 0-.5.22-.5.5V18h14v-1.5c0-.28-.22-.5-.5-.5zm4.97-.55c.99-1.07 1.53-2.48 1.53-3.94V2h-6v9.47c0 1.48.58 2.92 1.6 4l.4.42V22h4v-2h-2v-4.03l.47-.52zM18 4h2v4h-2V4zm1.03 10.07c-.65-.71-1.03-1.65-1.03-2.6V10h2v1.51c0 .95-.34 1.85-.97 2.56z" />
, 'BrunchDiningOutlined');
| Java |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::DataMigration::Mgmt::V2018_07_15_preview
module Models
#
# Results for query analysis comparison between the source and target
#
class QueryAnalysisValidationResult
include MsRestAzure
# @return [QueryExecutionResult] List of queries executed and it's
# execution results in source and target
attr_accessor :query_results
# @return [ValidationError] Errors that are part of the execution
attr_accessor :validation_errors
#
# Mapper for QueryAnalysisValidationResult class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'QueryAnalysisValidationResult',
type: {
name: 'Composite',
class_name: 'QueryAnalysisValidationResult',
model_properties: {
query_results: {
client_side_validation: true,
required: false,
serialized_name: 'queryResults',
type: {
name: 'Composite',
class_name: 'QueryExecutionResult'
}
},
validation_errors: {
client_side_validation: true,
required: false,
serialized_name: 'validationErrors',
type: {
name: 'Composite',
class_name: 'ValidationError'
}
}
}
}
}
end
end
end
end
| Java |
import {MdSnackBar} from '@angular/material';
export abstract class CommonCrudService {
constructor(private snackBar: MdSnackBar) {
}
// todo refactor crud operations to here (use metadata?)
onOperationPerformedNotify(opName: string): (res: boolean) => void {
return (res) => {
let text;
if (res) {
text = `Successful ${opName}!`;
} else {
text = `Failed to ${opName}!`;
}
this.snackBar.open(text, null, {
duration: 1000
});
};
}
}
| Java |
---
layout: post
author: Christoph Broschinski
author_lnk: https://github.com/cbroschinski
title: TU Clausthal reports its 2016 and 2017 APC expenditures
date: 2018-02-05 08:00:00
summary:
categories: [general, openAPC]
comments: true
---
The [TU Clausthal](http://www.tu-clausthal.de/Welcome.php.en) has updated its APC expenditures. The latest contribution provides data for the 2016 and 2017 periods.
The [Library of Clausthal University of Technology](http://www.ub.tu-clausthal.de/en/) is in charge of the [University's Open Access Publishing Fund](http://www.ub.tu-clausthal.de/en/angebote-fuer-wissenschaftlerinnen/elektronisches-publizieren/publikationsfonds/), which is supported by the DFG under its [Open-Access Publishing Programme](http://www.dfg.de/en/research_funding/programmes/infrastructure/lis/funding_opportunities/open_access/).
Contact person is [Silke Frank](mailto:silke.frank@tu-clausthal.de)
## Cost data
The new dataset covers publication fees for 7 articles. Total expenditure amounts to 11 106€ and the average fee is 1 587€.
The following table shows the payments the library of Clausthal University of Technology has made to publishers in 2016 and 2017.
| | Articles| Fees paid in EURO| Mean Fee paid|
|:------------------------------------|--------:|-----------------:|-------------:|
|Scientific Research Publishing, Inc, | 2| 921| 461|
|Carl Hanser Verlag | 1| 2099| 2099|
|Elsevier BV | 1| 1964| 1964|
|MDPI AG | 1| 1004| 1004|
|Springer Nature | 1| 2618| 2618|
|Wiley-Blackwell | 1| 2500| 2500|
## Overview
With the recent contribution included, the overall APC data for TU Clausthal now looks as follows:
### Fees paid per publisher (in EURO)

### Average costs per year (in EURO)

| Java |
package org.vitrivr.cineast.core.util.audio.pitch.tracking;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import org.vitrivr.cineast.core.util.audio.pitch.Pitch;
/**
* This is a helper class for pitch tracking. It represents a pitch contour, that is, a candidate for a melody fragment. The contour has a fixed length and each slot in the sequence represents a specific timeframe (e.g. belonging to a FFT bin in the underlying STFT).
* <p>
* The intention behind this class is the simplification of comparison between different pitch contours, either on a frame-by-frame basis but also as an entity. In addition to the actual pitch information, the pitch contour class also provides access to pitch contour statistics related to salience and pitch frequency.
*
* @see PitchTracker
*/
public class PitchContour {
/**
* The minimum frequency in Hz on the (artifical) cent-scale.
*/
private static final float CENT_SCALE_MINIMUM = 55.0f;
/**
* Entity that keeps track of salience related contour statistics.
*/
private SummaryStatistics salienceStatistics = new SummaryStatistics();
/**
* Entity that keeps track of frequency related contour statistics.
*/
private SummaryStatistics frequencyStatistics = new SummaryStatistics();
/**
* Sequence of pitches that form the PitchContour.
*/
private final List<Pitch> contour = new LinkedList<>();
/**
* Indicates that the PitchContour statistics require recalculation.
*/
private boolean dirty = true;
/**
* The start frame-index of the pitch-contour. Marks beginning in time.
*/
private int start;
/**
* The end frame-index of the pitch-contour. Marks ending in time.
*/
private int end;
/**
* Constructor for PitchContour.
*
* @param start Start-index of the contour.
* @param pitch Pitch that belongs to the start-index.
*/
public PitchContour(int start, Pitch pitch) {
this.start = start;
this.end = start;
this.contour.add(pitch);
}
/**
* Sets the pitch at the given index if the index is within the bounds of the PitchContour.
*
* @param p Pitch to append.
*/
public void append(Pitch p) {
this.contour.add(p);
this.end += 1;
this.dirty = true;
}
/**
* Sets the pitch at the given index if the index is within the bounds of the PitchContour.
*
* @param p Pitch to append.
*/
public void prepend(Pitch p) {
this.contour.add(0, p);
this.start -= 1;
this.dirty = true;
}
/**
* Returns the pitch at the given index or null, if the index is out of bounds. Note that even if the index is within bounds, the Pitch can still be null.
*
* @param i Index for which to return a pitch.
*/
public Pitch getPitch(int i) {
if (i >= this.start && i <= this.end) {
return this.contour.get(i - this.start);
} else {
return null;
}
}
/**
* Getter for start.
*
* @return Start frame-index.
*/
public final int getStart() {
return start;
}
/**
* Getter for end.
*
* @return End frame-index.
*/
public final int getEnd() {
return end;
}
/**
* Size of the pitch-contour. This number also includes empty slots.
*
* @return Size of the contour.
*/
public final int size() {
return this.contour.size();
}
/**
* Returns the mean of all pitches in the melody.
*
* @return Pitch mean
*/
public final double pitchMean() {
if (this.dirty) {
this.calculate();
}
return this.frequencyStatistics.getMean();
}
/**
* Returns the standard-deviation of all pitches in the melody.
*
* @return Pitch standard deviation
*/
public final double pitchDeviation() {
if (this.dirty) {
this.calculate();
}
return this.frequencyStatistics.getStandardDeviation();
}
/**
* Returns the mean-salience of all pitches in the contour.
*
* @return Salience mean
*/
public final double salienceMean() {
if (this.dirty) {
this.calculate();
}
return this.salienceStatistics.getMean();
}
/**
* Returns the salience standard deviation of all pitches in the contour.
*
* @return Salience standard deviation.
*/
public final double salienceDeviation() {
if (this.dirty) {
this.calculate();
}
return this.salienceStatistics.getStandardDeviation();
}
/**
* Returns the sum of all salience values in the pitch contour.
*/
public final double salienceSum() {
if (this.dirty) {
this.calculate();
}
return this.salienceStatistics.getSum();
}
/**
* Calculates the overlap between the given pitch-contours.
*
* @return Size of the overlap between two pitch-contours.
*/
public final int overlap(PitchContour contour) {
return Math.max(0, Math.min(this.end, contour.end) - Math.max(this.start, contour.start));
}
/**
* Determines if two PitchContours overlap and returns true of false.
*
* @return true, if two PitchContours overlap and falseotherwise.
*/
public final boolean overlaps(PitchContour contour) {
return this.overlap(contour) > 0;
}
/**
* Re-calculates the PitchContour statistics.
*/
private void calculate() {
this.salienceStatistics.clear();
this.frequencyStatistics.clear();
for (Pitch pitch : this.contour) {
if (pitch != null) {
this.salienceStatistics.addValue(pitch.getSalience());
this.frequencyStatistics.addValue(pitch.distanceCents(CENT_SCALE_MINIMUM));
}
}
this.dirty = false;
}
}
| Java |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RapidPliant.App.EarleyDebugger")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RapidPliant.App.EarleyDebugger")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly:ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "RapidPliant.App.EarleyDebugger.Views")]
| Java |
package com.company;
import java.util.Scanner;
public class EvenPowersOf2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int num = 1;
for (int i = 0; i <= n ; i+=2) {
System.out.println(num);
num *= 4;
}
}
}
| Java |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'Participant'
db.delete_table(u'pa_participant')
# Removing M2M table for field user on 'Participant'
db.delete_table('pa_participant_user')
# Adding M2M table for field user on 'ReportingPeriod'
db.create_table(u'pa_reportingperiod_user', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('reportingperiod', models.ForeignKey(orm[u'pa.reportingperiod'], null=False)),
('user', models.ForeignKey(orm[u'pa.user'], null=False))
))
db.create_unique(u'pa_reportingperiod_user', ['reportingperiod_id', 'user_id'])
def backwards(self, orm):
# Adding model 'Participant'
db.create_table(u'pa_participant', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('reporting_period', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['pa.ReportingPeriod'])),
))
db.send_create_signal(u'pa', ['Participant'])
# Adding M2M table for field user on 'Participant'
db.create_table(u'pa_participant_user', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('participant', models.ForeignKey(orm[u'pa.participant'], null=False)),
('user', models.ForeignKey(orm[u'pa.user'], null=False))
))
db.create_unique(u'pa_participant_user', ['participant_id', 'user_id'])
# Removing M2M table for field user on 'ReportingPeriod'
db.delete_table('pa_reportingperiod_user')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'pa.activity': {
'Meta': {'object_name': 'Activity'},
'category': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['pa.Category']"}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'pa.activityentry': {
'Meta': {'object_name': 'ActivityEntry'},
'activity': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['pa.Activity']"}),
'day': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'hour': ('django.db.models.fields.IntegerField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'slot': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['pa.User']"})
},
u'pa.category': {
'Meta': {'object_name': 'Category'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'grouping': ('django.db.models.fields.CharField', [], {'default': "'d'", 'max_length': '15'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'reporting_period': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['pa.ReportingPeriod']"})
},
u'pa.profession': {
'Meta': {'object_name': 'Profession'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '60'})
},
u'pa.reportingperiod': {
'Meta': {'object_name': 'ReportingPeriod'},
'end_date': ('django.db.models.fields.DateTimeField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '120'}),
'slots_per_hour': ('django.db.models.fields.IntegerField', [], {}),
'start_date': ('django.db.models.fields.DateTimeField', [], {}),
'user': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['pa.User']", 'symmetrical': 'False'})
},
u'pa.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'profession': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['pa.Profession']", 'null': 'True', 'blank': 'True'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
}
}
complete_apps = ['pa'] | Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>美艺空间手工饰品 2017-03-18-2 - 美艺空间</title>
<meta name="description" content="美艺空间手工饰品">
<link rel="shortcut icon" href="/assets/images/favicon.ico">
<link href="https://fonts.googleapis.com/css?family=Fascinate+Inline" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,700" rel="stylesheet">
<link rel="stylesheet" href="/assets/fonts/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="/assets/css/main.css">
</head>
<body>
<header class="site-header">
<button class="toggle_menu">
<span class="sandwich">
<span class="sw-topper"></span>
<span class="sw-bottom"></span>
<span class="sw-footer"></span>
</span>
</button>
<nav class="top_menu">
<ul>
<li class="main-items"><a href="/">首页</a></li>
<li class="main-items"><a href="">建设中</a></li>
</ul>
</nav>
<div class="header-content">
<div class="logo">
<a href="/" class="logo-link">美艺空间</a>
</div>
</div>
</header>
<div class="page-wrap">
<main role="main">
<div class="page-container">
<img class="page-img" src=http://imglf0.nosdn.127.net/img/R2s3QnZjM0lqWFRtYUZGNDU2VUlOOURkcGJxc0JzOVh4M1B4bHFoUE5kNUpHTEZKUmdBWmhRPT0.jpg?imageView&thumbnail=1800y1350&type=jpg&quality=96&stripmeta=0&type=jpg alt="美艺空间手工饰品 2017-03-18-2">
<div class="page-content">
<article>
<h1 class="page-title">美艺空间手工饰品 2017-03-18-2</h1>
<div class="date-byline"><span><i class="fa fa-calendar-o" aria-hidden="true"></i> 2017, Mar 18 </span><span><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Xiaomeng</span></div>
</article>
<!-- <div class="comment">
<button class="show-comments"><i class="fa fa-comments" aria-hidden="true"> Load/Add comments</i></button>
<div id="disqus_thread"></div>
</div>
<script src=/assets/js/vendor/jquery-3.1.1.min.js></script>
<script>
$(document).ready(function() {
$('.show-comments').on('click', function(){
var disqus_shortname = '';
$.ajax({
type: "GET",
url: "http://" + disqus_shortname + "mr-brown.disqus.com/embed.js",
dataType: "script",
cache: true
});
$(this).fadeOut();
});
});
</script> -->
<div id="disqus_thread" class="article-comments"></div>
<script>
(function() {
var d = document, s = d.createElement('script');
s.src = '//mr-brown.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
</div>
</main>
</div>
<footer class="footer">
<div class="footer-social">
<ul class="social-icons">
</ul>
<ul class="copyright">
<li>2017 @ 美艺空间</li>
</ul>
</div>
<div class="footer-newsletter"></div>
</footer>
<!-- Jquery -->
<script src="/assets/js/vendor/jquery-3.1.1.min.js"></script>
<!-- Main Js -->
<script src="/assets/js/main.js"></script>
</body>
</html>
| Java |
/************************************************************************
The MIT License(MIT)
Copyright(c) 2014 Lingjijian [B-y]
342854406@qq.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
************************************************************************/
#ifndef __TUI_UTIL_H__
#define __TUI_UTIL_H__
#include "cocos2d.h"
#include "TuiMacros.h"
NS_TUI_BEGIN
using namespace std;
/**
* @brief the tool
*
*/
class TuiUtil{
public:
/**
* @brief use name to create the animation
*
* @param name
* @param delay
* @param iLoops Whether loop
* @return Animation
*/
static Animation* createAnimWithName(const char* name,float delay,unsigned int iLoops);
/**
* @brief use name and Play frames to create the animation
*
* @param name
* @param iNum frame number
* @param delay
* @param iLoops Whether loop
* @return Animation
*/
static Animation* createAnimWithNameAndNum(const char* name,int iNum, float delay,unsigned int iLoops);
/*
* @brief replace all string in actual ,such as => replace_all(string("12212"),"12","21") => 22211
*
* @param str text
* @param old_value
* @param new_value
* @return string
*/
static string replace_all_actual(string str, const string& old_value, const string& new_value);
/*
* @brief replace all string ,such as => replace_all(string("12212"),"12","21") => 21221
*
* @param str text
* @param old_value
* @param new_value
* @return string
*/
static string replace_all(string str, const string& old_value, const string& new_value);
/*
* @brief split string ,such as => split(string("ff_a"),"_") => ["ff","a"]
*
* @param str text
* @param delim
* @return string
*/
static vector< string > split(const string& s,const string& delim);
static vector< string > separateUtf8(const std::string& inStr);
static bool isChinese(const std::string& s);
protected:
private:
};
NS_TUI_END
#endif | Java |
# Jrails-ui
module ActionView
module Helpers
module JavaScriptHelper
def hash_to_jquery(hash)
'{'+hash.map { |k,v|
[k,
case v.class.name
when 'String'
"'#{v}'"
when 'Hash'
hash_to_jquery(v)
else
v.to_s
end
].join(':')
}.join(',')+'}'
end
def flash_messages
content_tag(:div, :class => "ui-widget flash") do
flash.map { |type,message|
state = case type
when :notice; 'highlight'
when :error; 'error'
end
icon = case type
when :notice; 'info'
when :error; 'alert'
end
content_tag(:div, content_tag(:span, "", :class => "ui-icon ui-icon-#{icon}", :style => "float: left; margin-right: 0.3em;")+message, :class => "ui-state-#{state} ui-corner-all #{type}", :style => "margin-top: 5px; padding: 0.7em;")
}.join
end
end
def link_to_dialog(*args, &block)
div_id = "dialog#{args[1].gsub(/\//,'_')}"
dialog = {
:modal => true,
:draggable => false,
:resizable => false,
:width => 600
}.merge(args[2][:dialog] || {})
args[2].merge!(
:onclick => "$('##{div_id}').dialog(#{hash_to_jquery(dialog)});return false;"
)
args[2].delete(:dialog)
if block_given?
dialog_html = capture(&block)
else
render_options = args[2][:render] || {}
dialog_html = render(render_options)
end
link_html = link_to(*args)+content_tag(:div, dialog_html, :style => 'display:none;', :id => div_id, :title => args.first)
return block_given? ? concat(link_html) : link_html
end
end
end
end
| Java |
/*
* Copyright (c) 2020 by Stefan Schubert under the MIT License (MIT).
* See project LICENSE file for the detailed terms and conditions.
*/
package de.bluewhale.sabi.webclient.rest.exceptions;
import de.bluewhale.sabi.exception.ExceptionCode;
import de.bluewhale.sabi.exception.MessageCode;
import de.bluewhale.sabi.exception.TankExceptionCodes;
/**
* MessageCodes that may arise by using the Tank Restservice
*
* @author schubert
*/
public enum TankMessageCodes implements MessageCode {
NO_SUCH_TANK(TankExceptionCodes.TANK_NOT_FOUND_OR_DOES_NOT_BELONG_TO_USER);
// ------------------------------ FIELDS ------------------------------
private TankExceptionCodes exceptionCode;
// --------------------------- CONSTRUCTORS ---------------------------
TankMessageCodes() {
exceptionCode = null;
}
TankMessageCodes(TankExceptionCodes pExceptionCode) {
exceptionCode = pExceptionCode;
}
// --------------------- GETTER / SETTER METHODS ---------------------
@Override
public ExceptionCode getExceptionCode() {
return exceptionCode;
}
}
| Java |
package okeanos.data.services.entities;
import javax.measure.quantity.Power;
import org.jscience.physics.amount.Amount;
public interface Price {
double getCostAtConsumption(Amount<Power> consumption);
}
| Java |
<?php
namespace Shop\MainBundle\Data;
use Doctrine\Common\Persistence\ObjectRepository;
use Shop\MainBundle\Entity\Settings;
/**
* Class ShopSettingsResource
* @package Shop\MainBundle\Data
*/
class ShopSettingsResource {
/**
* @var ObjectRepository
*/
protected $settingsRepository;
/**
* @var Settings|null
*/
protected $settings;
function __construct(ObjectRepository $settingsRepository)
{
$this->settingsRepository = $settingsRepository;
}
/**
* @return null|Settings
*/
public function getSettings()
{
if($this->settings === null){
$this->settings = $this->settingsRepository->findOneBy(array());
if (!$this->settings) {
$this->settings = new Settings();
}
}
return $this->settings;
}
/**
* @param $key
* @return mixed
*/
public function get($key){
return $this->getSettings()->offsetGet($key);
}
} | Java |
<!DOCTYPE html>
<!--[if lt IE 9]><html class="no-js lt-ie9" lang="en" dir="ltr"><![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="en" dir="ltr">
<!--<![endif]-->
<!-- Usage: /eic/site/ccc-rec.nsf/tpl-eng/template-1col.html?Open&id=3 (optional: ?Open&page=filename.html&id=x) -->
<!-- Created: ; Product Code: 536; Server: stratnotes2.ic.gc.ca -->
<head>
<!-- Title begins / Début du titre -->
<title>
Bayview Propeller -
Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada
</title>
<!-- Title ends / Fin du titre -->
<!-- Meta-data begins / Début des métadonnées -->
<meta charset="utf-8" />
<meta name="dcterms.language" title="ISO639-2" content="eng" />
<meta name="dcterms.title" content="" />
<meta name="description" content="" />
<meta name="dcterms.description" content="" />
<meta name="dcterms.type" content="report, data set" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.issued" title="W3CDTF" content="" />
<meta name="dcterms.modified" title="W3CDTF" content="" />
<meta name="keywords" content="" />
<meta name="dcterms.creator" content="" />
<meta name="author" content="" />
<meta name="dcterms.created" title="W3CDTF" content="" />
<meta name="dcterms.publisher" content="" />
<meta name="dcterms.audience" title="icaudience" content="" />
<meta name="dcterms.spatial" title="ISO3166-1" content="" />
<meta name="dcterms.spatial" title="gcgeonames" content="" />
<meta name="dcterms.format" content="HTML" />
<meta name="dcterms.identifier" title="ICsiteProduct" content="536" />
<!-- EPI-11240 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- MCG-202 -->
<meta content="width=device-width,initial-scale=1" name="viewport">
<!-- EPI-11567 -->
<meta name = "format-detection" content = "telephone=no">
<!-- EPI-12603 -->
<meta name="robots" content="noarchive">
<!-- EPI-11190 - Webtrends -->
<script>
var startTime = new Date();
startTime = startTime.getTime();
</script>
<!--[if gte IE 9 | !IE ]><!-->
<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="icon" type="image/x-icon">
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/wet-boew.min.css">
<!--<![endif]-->
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/theme.min.css">
<!--[if lt IE 9]>
<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="shortcut icon" />
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/ie8-wet-boew.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew.min.js"></script>
<![endif]-->
<!--[if lte IE 9]>
<![endif]-->
<noscript><link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/noscript.min.css" /></noscript>
<!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER -->
<script>dataLayer1 = [];</script>
<!-- End Google Tag Manager -->
<!-- EPI-11235 -->
<link rel="stylesheet" href="/eic/home.nsf/css/add_WET_4-0_Canada_Apps.css">
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="/app/ccc/srch/css/print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body class="home" vocab="http://schema.org/" typeof="WebPage">
<!-- EPIC HEADER BEGIN -->
<!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER -->
<noscript><iframe title="Google Tag Manager" src="//www.googletagmanager.com/ns.html?id=GTM-TLGQ9K" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer1'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer1','GTM-TLGQ9K');</script>
<!-- End Google Tag Manager -->
<!-- EPI-12801 -->
<span typeof="Organization"><meta property="legalName" content="Department_of_Industry"></span>
<ul id="wb-tphp">
<li class="wb-slc">
<a class="wb-sl" href="#wb-cont">Skip to main content</a>
</li>
<li class="wb-slc visible-sm visible-md visible-lg">
<a class="wb-sl" href="#wb-info">Skip to "About this site"</a>
</li>
</ul>
<header role="banner">
<div id="wb-bnr" class="container">
<section id="wb-lng" class="visible-md visible-lg text-right">
<h2 class="wb-inv">Language selection</h2>
<div class="row">
<div class="col-md-12">
<ul class="list-inline mrgn-bttm-0">
<li><a href="nvgt.do?V_TOKEN=1492268651023&V_SEARCH.docsCount=3&V_DOCUMENT.docRank=5279&V_SEARCH.docsStart=5278&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=/prfl.do&lang=fra&redirectUrl=/app/scr/imbs/ccc/rgstrtn/rgstr.sec?_flId?_flxKy=e1s1&estblmntNo=234567041301&profileId=61&_evId=bck&lang=eng&V_SEARCH.showStricts=false&prtl=1&_flId?_flId?_flxKy=e1s1" title="Français" lang="fr">Français</a></li>
</ul>
</div>
</div>
</section>
<div class="row">
<div class="brand col-xs-8 col-sm-9 col-md-6">
<a href="http://www.canada.ca/en/index.html"><object type="image/svg+xml" tabindex="-1" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/sig-blk-en.svg"></object><span class="wb-inv"> Government of Canada</span></a>
</div>
<section class="wb-mb-links col-xs-4 col-sm-3 visible-sm visible-xs" id="wb-glb-mn">
<h2>Search and menus</h2>
<ul class="list-inline text-right chvrn">
<li><a href="#mb-pnl" title="Search and menus" aria-controls="mb-pnl" class="overlay-lnk" role="button"><span class="glyphicon glyphicon-search"><span class="glyphicon glyphicon-th-list"><span class="wb-inv">Search and menus</span></span></span></a></li>
</ul>
<div id="mb-pnl"></div>
</section>
<!-- Site Search Removed -->
</div>
</div>
<nav role="navigation" id="wb-sm" class="wb-menu visible-md visible-lg" data-trgt="mb-pnl" data-ajax-fetch="//cdn.canada.ca/gcweb-cdn-dev/sitemenu/sitemenu-en.html" typeof="SiteNavigationElement">
<h2 class="wb-inv">Topics menu</h2>
<div class="container nvbar">
<div class="row">
<ul class="list-inline menu">
<li><a href="https://www.canada.ca/en/services/jobs.html">Jobs</a></li>
<li><a href="http://www.cic.gc.ca/english/index.asp">Immigration</a></li>
<li><a href="https://travel.gc.ca/">Travel</a></li>
<li><a href="https://www.canada.ca/en/services/business.html">Business</a></li>
<li><a href="https://www.canada.ca/en/services/benefits.html">Benefits</a></li>
<li><a href="http://healthycanadians.gc.ca/index-eng.php">Health</a></li>
<li><a href="https://www.canada.ca/en/services/taxes.html">Taxes</a></li>
<li><a href="https://www.canada.ca/en/services.html">More services</a></li>
</ul>
</div>
</div>
</nav>
<!-- EPIC BODY BEGIN -->
<nav role="navigation" id="wb-bc" class="" property="breadcrumb">
<h2 class="wb-inv">You are here:</h2>
<div class="container">
<div class="row">
<ol class="breadcrumb">
<li><a href="/eic/site/icgc.nsf/eng/home" title="Home">Home</a></li>
<li><a href="/eic/site/icgc.nsf/eng/h_07063.html" title="Industries and Business">Industries and Business</a></li>
<li><a href="/eic/site/ccc-rec.nsf/tpl-eng/../eng/home" >Canadian Company Capabilities</a></li>
</ol>
</div>
</div>
</nav>
</header>
<main id="wb-cont" role="main" property="mainContentOfPage" class="container">
<!-- End Header -->
<!-- Begin Body -->
<!-- Begin Body Title -->
<!-- End Body Title -->
<!-- Begin Body Head -->
<!-- End Body Head -->
<!-- Begin Body Content -->
<br>
<!-- Complete Profile -->
<!-- Company Information above tabbed area-->
<input id="showMore" type="hidden" value='more'/>
<input id="showLess" type="hidden" value='less'/>
<h1 id="wb-cont">
Company profile - Canadian Company Capabilities
</h1>
<div class="profileInfo hidden-print">
<ul class="list-inline">
<li><a href="cccSrch.do?lang=eng&profileId=&prtl=1&key.hitsPerPage=25&searchPage=%252Fapp%252Fccc%252Fsrch%252FcccBscSrch.do%253Flang%253Deng%2526amp%253Bprtl%253D1%2526amp%253Btagid%253D&V_SEARCH.scopeCategory=CCC.Root&V_SEARCH.depth=1&V_SEARCH.showStricts=false&V_SEARCH.sortSpec=title+asc&rstBtn.x=" class="btn btn-link">New Search</a> |</li>
<li><form name="searchForm" method="post" action="/app/ccc/srch/bscSrch.do">
<input type="hidden" name="lang" value="eng" />
<input type="hidden" name="profileId" value="" />
<input type="hidden" name="prtl" value="1" />
<input type="hidden" name="searchPage" value="%2Fapp%2Fccc%2Fsrch%2FcccBscSrch.do%3Flang%3Deng%26amp%3Bprtl%3D1%26amp%3Btagid%3D" />
<input type="hidden" name="V_SEARCH.scopeCategory" value="CCC.Root" />
<input type="hidden" name="V_SEARCH.depth" value="1" />
<input type="hidden" name="V_SEARCH.showStricts" value="false" />
<input id="repeatSearchBtn" class="btn btn-link" type="submit" value="Return to search results" />
</form></li>
<li>| <a href="nvgt.do?V_SEARCH.docsStart=5277&V_DOCUMENT.docRank=5278&V_SEARCH.docsCount=3&lang=eng&prtl=1&sbPrtl=&profile=cmpltPrfl&V_TOKEN=1492268658485&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=%2fprfl.do&estblmntNo=234567162180&profileId=&key.newSearchLabel=">Previous Company</a></li>
<li>| <a href="nvgt.do?V_SEARCH.docsStart=5279&V_DOCUMENT.docRank=5280&V_SEARCH.docsCount=3&lang=eng&prtl=1&sbPrtl=&profile=cmpltPrfl&V_TOKEN=1492268658485&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=%2fprfl.do&estblmntNo=234567068940&profileId=&key.newSearchLabel=">Next Company</a></li>
</ul>
</div>
<details>
<summary>Third-Party Information Liability Disclaimer</summary>
<p>Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.</p>
</details>
<h2>
Bayview Propeller Div. of Artanus Inc.
</h2>
<div class="row">
<div class="col-md-5">
<h2 class="h5 mrgn-bttm-0">Legal Name:</h2>
<p>Bayview Propeller Div. of Artanus Inc.</p>
<h2 class="h5 mrgn-bttm-0">Operating Name:</h2>
<p>Bayview Propeller</p>
<h2 class="h5 mrgn-bttm-0">Alternate Name:</h2>
<p class="mrgn-bttm-0">Bayview Marina</p>
<p class="mrgn-bttm-0">Bayview Propeller</p>
<p><a href="mailto:bayview.propeller@sympatico.ca" title="bayview.propeller@sympatico.ca">bayview.propeller@sympatico.ca</a></p>
</div>
<div class="col-md-4 mrgn-sm-sm">
<h2 class="h5 mrgn-bttm-0">Mailing Address:</h2>
<address class="mrgn-bttm-md">
832 Northey's Bay Rd<br/>
WOODVIEW,
Ontario<br/>
K0L 3E0
<br/>
</address>
<h2 class="h5 mrgn-bttm-0">Location Address:</h2>
<address class="mrgn-bttm-md">
832 Northey's Bay Rd<br/>
WOODVIEW,
Ontario<br/>
K0L 3E0
<br/>
</address>
<p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>:
(705) 654-4409
</p>
<p class="mrgn-bttm-lg"><abbr title="Facsimile">Fax</abbr>:
(705) 654-4611</p>
</div>
<div class="col-md-3 mrgn-tp-md">
</div>
</div>
<div class="row mrgn-tp-md mrgn-bttm-md">
<div class="col-md-12">
</div>
</div>
<!-- <div class="wb-tabs ignore-session update-hash wb-eqht-off print-active"> -->
<div class="wb-tabs ignore-session">
<div class="tabpanels">
<details id="details-panel1">
<summary>
Full profile
</summary>
<!-- Tab 1 -->
<h2 class="wb-invisible">
Full profile
</h2>
<!-- Contact Information -->
<h3 class="page-header">
Contact information
</h3>
<section class="container-fluid">
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Dennis
Johnson
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
<!--if client gender is not null or empty we use gender based job title-->
Manager
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Area of Responsibility:
</strong>
</div>
<div class="col-md-7">
Manufacturing/Production/Operations.
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(705) 654-3545
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(705) 654-4611
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
bayview.propeller@sympatico.ca
</div>
</div>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- Company Description -->
<h3 class="page-header">
Company description
</h3>
<section class="container-fluid">
<div class="row">
<div class="col-md-5">
<strong>
Country of Ownership:
</strong>
</div>
<div class="col-md-7">
Canada
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Year Established:
</strong>
</div>
<div class="col-md-7">
1964
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Exporting:
</strong>
</div>
<div class="col-md-7">
No
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Industry (NAICS):
</strong>
</div>
<div class="col-md-7">
336611 - Ship Building and Repairing
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Alternate Industries (NAICS):
</strong>
</div>
<div class="col-md-7">
332999 - All Other Miscellaneous Fabricated Metal Product Manufacturing<br>
417990 - All Other Machinery, Equipment and Supplies Wholesaler-Distributors<br>
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Business Activity:
</strong>
</div>
<div class="col-md-7">
Services
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Number of Employees:
</strong>
</div>
<div class="col-md-7">
6
</div>
</div>
</section>
<!-- Products / Services / Licensing -->
<h3 class="page-header">
Product / Service / Licensing
</h3>
<section class="container-fluid">
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
Propellers<br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-12">
MANUFACTURER OF MARINE PROPELLERS<br>
<br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Service Name:
</strong>
</div>
<div class="col-md-9">
Yacht Service Company <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Service Name:
</strong>
</div>
<div class="col-md-9">
Boat Parts and Accessories Distributor <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-12">
Lines Distributed:
<br>
Arco Electrical Products, Bayview Propeller repair services,
<br>
Bayview shafts and marine hardward, Buck Algonquin Marine
<br>
couplings, Federal Propellers, Martec Propellers, Michigan
<br>
Propellers Strong Seal by Tides Marine.<br>
<br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Service Name:
</strong>
</div>
<div class="col-md-9">
Propeller Repair<br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-12">
Repairs to all types of marine propellers up to ten feet in diameter<br>
<br>
</div>
</div>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- Technology Profile -->
<!-- Market Profile -->
<!-- Sector Information -->
<details class="mrgn-tp-md mrgn-bttm-md">
<summary>
Third-Party Information Liability Disclaimer
</summary>
<p>
Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.
</p>
</details>
</details>
<details id="details-panel2">
<summary>
Contacts
</summary>
<h2 class="wb-invisible">
Contact information
</h2>
<!-- Contact Information -->
<section class="container-fluid">
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Dennis
Johnson
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
<!--if client gender is not null or empty we use gender based job title-->
Manager
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Area of Responsibility:
</strong>
</div>
<div class="col-md-7">
Manufacturing/Production/Operations.
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(705) 654-3545
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(705) 654-4611
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
bayview.propeller@sympatico.ca
</div>
</div>
</section>
</details>
<details id="details-panel3">
<summary>
Description
</summary>
<h2 class="wb-invisible">
Company description
</h2>
<section class="container-fluid">
<div class="row">
<div class="col-md-5">
<strong>
Country of Ownership:
</strong>
</div>
<div class="col-md-7">
Canada
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Year Established:
</strong>
</div>
<div class="col-md-7">
1964
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Exporting:
</strong>
</div>
<div class="col-md-7">
No
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Industry (NAICS):
</strong>
</div>
<div class="col-md-7">
336611 - Ship Building and Repairing
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Alternate Industries (NAICS):
</strong>
</div>
<div class="col-md-7">
332999 - All Other Miscellaneous Fabricated Metal Product Manufacturing<br>
417990 - All Other Machinery, Equipment and Supplies Wholesaler-Distributors<br>
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Business Activity:
</strong>
</div>
<div class="col-md-7">
Services
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Number of Employees:
</strong>
</div>
<div class="col-md-7">
6
</div>
</div>
</section>
</details>
<details id="details-panel4">
<summary>
Products, services and licensing
</summary>
<h2 class="wb-invisible">
Product / Service / Licensing
</h2>
<section class="container-fluid">
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
Propellers<br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-12">
MANUFACTURER OF MARINE PROPELLERS<br>
<br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Service Name:
</strong>
</div>
<div class="col-md-9">
Yacht Service Company <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Service Name:
</strong>
</div>
<div class="col-md-9">
Boat Parts and Accessories Distributor <br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-12">
Lines Distributed:
<br>
Arco Electrical Products, Bayview Propeller repair services,
<br>
Bayview shafts and marine hardward, Buck Algonquin Marine
<br>
couplings, Federal Propellers, Martec Propellers, Michigan
<br>
Propellers Strong Seal by Tides Marine.<br>
<br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Service Name:
</strong>
</div>
<div class="col-md-9">
Propeller Repair<br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-12">
Repairs to all types of marine propellers up to ten feet in diameter<br>
<br>
</div>
</div>
</section>
</details>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
Last Update Date 2014-11-26
</div>
</div>
<!--
- Artifact ID: CBW - IMBS - CCC Search WAR
- Group ID: ca.gc.ic.strategis.imbs.ccc.search
- Version: 3.26
- Built-By: bamboo
- Build Timestamp: 2017-03-02T21:29:28Z
-->
<!-- End Body Content -->
<!-- Begin Body Foot -->
<!-- End Body Foot -->
<!-- END MAIN TABLE -->
<!-- End body -->
<!-- Begin footer -->
<div class="row pagedetails">
<div class="col-sm-5 col-xs-12 datemod">
<dl id="wb-dtmd">
<dt class=" hidden-print">Date Modified:</dt>
<dd class=" hidden-print">
<span><time>2017-03-02</time></span>
</dd>
</dl>
</div>
<div class="clear visible-xs"></div>
<div class="col-sm-4 col-xs-6">
</div>
<div class="col-sm-3 col-xs-6 text-right">
</div>
<div class="clear visible-xs"></div>
</div>
</main>
<footer role="contentinfo" id="wb-info">
<nav role="navigation" class="container wb-navcurr">
<h2 class="wb-inv">About government</h2>
<!-- EPIC FOOTER BEGIN -->
<!-- EPI-11638 Contact us -->
<ul class="list-unstyled colcount-sm-2 colcount-md-3">
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07026.html#pageid=E048-H00000&from=Industries">Contact us</a></li>
<li><a href="https://www.canada.ca/en/government/dept.html">Departments and agencies</a></li>
<li><a href="https://www.canada.ca/en/government/publicservice.html">Public service and military</a></li>
<li><a href="https://www.canada.ca/en/news.html">News</a></li>
<li><a href="https://www.canada.ca/en/government/system/laws.html">Treaties, laws and regulations</a></li>
<li><a href="https://www.canada.ca/en/transparency/reporting.html">Government-wide reporting</a></li>
<li><a href="http://pm.gc.ca/eng">Prime Minister</a></li>
<li><a href="https://www.canada.ca/en/government/system.html">How government works</a></li>
<li><a href="http://open.canada.ca/en/">Open government</a></li>
</ul>
</nav>
<div class="brand">
<div class="container">
<div class="row">
<nav class="col-md-10 ftr-urlt-lnk">
<h2 class="wb-inv">About this site</h2>
<ul>
<li><a href="https://www.canada.ca/en/social.html">Social media</a></li>
<li><a href="https://www.canada.ca/en/mobile.html">Mobile applications</a></li>
<li><a href="http://www1.canada.ca/en/newsite.html">About Canada.ca</a></li>
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html">Terms and conditions</a></li>
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html#p1">Privacy</a></li>
</ul>
</nav>
<div class="col-xs-6 visible-sm visible-xs tofpg">
<a href="#wb-cont">Top of Page <span class="glyphicon glyphicon-chevron-up"></span></a>
</div>
<div class="col-xs-6 col-md-2 text-right">
<object type="image/svg+xml" tabindex="-1" role="img" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object>
</div>
</div>
</div>
</div>
</footer>
<!--[if gte IE 9 | !IE ]><!-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/wet-boew.min.js"></script>
<!--<![endif]-->
<!--[if lt IE 9]>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew2.min.js"></script>
<![endif]-->
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/theme.min.js"></script>
<!-- EPI-10519 -->
<span class="wb-sessto"
data-wb-sessto='{"inactivity": 1800000, "reactionTime": 180000, "sessionalive": 1800000, "logouturl": "/app/ccc/srch/cccSrch.do?lang=eng&prtl=1"}'></span>
<script src="/eic/home.nsf/js/jQuery.externalOpensInNewWindow.js"></script>
<!-- EPI-11190 - Webtrends -->
<script src="/eic/home.nsf/js/webtrends.js"></script>
<script>var endTime = new Date();</script>
<noscript>
<div><img alt="" id="DCSIMG" width="1" height="1" src="//wt-sdc.ic.gc.ca/dcs6v67hwe0ei7wsv8g9fv50d_3k6i/njs.gif?dcsuri=/nojavascript&WT.js=No&WT.tv=9.4.0&dcssip=www.ic.gc.ca"/></div>
</noscript>
<!-- /Webtrends -->
<!-- JS deps -->
<script src="/eic/home.nsf/js/jquery.imagesloaded.js"></script>
<!-- EPI-11262 - Util JS -->
<script src="/eic/home.nsf/js/_WET_4-0_utils_canada.min.js"></script>
<!-- EPI-11383 -->
<script src="/eic/home.nsf/js/jQuery.icValidationErrors.js"></script>
<span style="display:none;" id='app-info' data-project-groupid='' data-project-artifactid='' data-project-version='' data-project-build-timestamp='' data-issue-tracking='' data-scm-sha1='' data-scm-sha1-abbrev='' data-scm-branch='' data-scm-commit-date=''></span>
</body></html>
<!-- End Footer -->
<!--
- Artifact ID: CBW - IMBS - CCC Search WAR
- Group ID: ca.gc.ic.strategis.imbs.ccc.search
- Version: 3.26
- Built-By: bamboo
- Build Timestamp: 2017-03-02T21:29:28Z
-->
| Java |
var builder = require("botbuilder");
var botbuilder_azure = require("botbuilder-azure");
const notUtils = require('./notifications-utils.js');
module.exports = [
function (session) {
session.beginDialog('notifications-common-symbol');
},
function (session, results) {
var pair = results.response;
session.dialogData.symbol = pair;
builder.Prompts.number(session, 'How big should the interval be?');
},
function (session, results) {
session.dialogData.interval = results.response;
builder.Prompts.text(session, "What name would you like to give to this notification?");
},
function (session, results) {
var sub = notUtils.getBaseNotification('interval', session.message.address);
sub.symbol = session.dialogData.symbol;
sub.interval = session.dialogData.interval;
sub.previousprice = 0;
sub.isfirstun = true;
sub.name = results.response;
notUtils.createNotification(sub).then((r) => {
session.endDialog('Notification created!');
}).catch((e) => {
session.endDialog('Couldn\'t create notification: ' + e);
});
}
]; | Java |
#ifndef _PSW_H_INCLUDED_
#define _PSW_H_INCLUDED_
/*
* (補足) プロセッサステータスレジスタ(PSW):
* -------+----------+----------------------------------------
* b16 | I | 割り込み許可ビット(0:禁止/1:許可)
* b17 | U | スタックポインタ指定ビット(0:ISP/1:USP)
* b20 | PM | プロセッサモード設定ビット(0:S/1:U)
* b27-24 | IPL[3:0] | プロセッサ割り込み優先レベル(0(最低)-15(最高)
* -------+----------+----------------------------------------
*/
#define PSW_I_DISABLE 0x00000000
#define PSW_I_ENABLE 0x00010000
#define PSW_U_ISP 0x00000000
#define PSW_U_USP 0x00020000
#define PSW_PM_SUPER 0x00000000
#define PSW_PM_USER 0x00100000
#define PSW_IPL_MIN 0x00000000
#define PSW_IPL_MAX 0x0f000000
#endif /* _PSW_H_INCLUDED_ */
| Java |
/*
Copyright c1997-2014 Trygve Isaacson. All rights reserved.
This file is part of the Code Vault version 4.1
http://www.bombaydigital.com/
License: MIT. See LICENSE.md in the Vault top level directory.
*/
#ifndef vinstant_h
#define vinstant_h
/** @file */
#include "vtypes.h"
#include "vstring.h"
class VCodePoint;
class VInstant;
class VDate;
class VTimeOfDay;
class VDateAndTime;
class VInstantFormatter;
/**
A VDuration is a length of time. It is most useful in conjunction with VInstant
as the proper type to use when adding or subtracting an amount of time to a
VInstant, or when subtracting two VInstants to find out the length of time
between them.
Several constant values are defined, and by applying the multiplication
operator, you can create your own values describing particular lengths of
time. For example, to declare a constant for the duration of 1.5 hours, you
could do any of the following:
<code>
VDuration d1 = 90 * VDuration::MINUTE();
VDuration d2 = VDuration::HOUR() + (30 * VDuration::MINUTE());
assert(d1 == d2);
</code>
To get a VInstant describing a point in time 15 minutes in the future, you
could do the following:
<code>
VInstant x; // constructs to the current time
x += (15 * VDuration::MINUTE());
</code>
The only unusual behavior within VDuration is the existence of the UNSPECIFIED
duration constant. This is provided for cases where, due to backward compatibility,
you need to initialize a duration to a special value that a normal value will
never equal. It's a much better practice to let durations initialize to ZERO by
default. Some behavior is not meaningful if you perform operations on an UNSPECIFIED
duration. You should only test them for equality.
Negative durations are perfectly OK. They behave just as you'd expect; for example,
if you subtract a later VInstant from an earlier VInstant, the resulting VDuration
will be negative.
The NEGATIVE_INFINITY and POSITIVE_INFINITY constants are provided primarily so
that the VInstant math operations can provide reasonable results when the instant
values are INFINITE_PAST or INFINITE_FUTURE. In addition, VDuration's own math
operations provide logical results when using these infinity values.
Strict Weak Ordering:
Sorting functions require a strict weak ordering to be defined. This is implemented
by the comparision operators. It is defined as follows:
NEGATIVE_INFINITY < negative durations < ZERO < positive durations < POSITIVE_INFINITY < UNSPECIFIED
*/
class VDuration {
public:
static const VDuration& ZERO(); ///< Duration constant of zero milliseconds.
static const VDuration& MILLISECOND(); ///< Duration constant of 1 millisecond.
static const VDuration& SECOND(); ///< Duration constant of 1 second (1000 milliseconds).
static const VDuration& MINUTE(); ///< Duration constant of 1 minute (60 seconds).
static const VDuration& HOUR(); ///< Duration constant of 1 hour (60 minutes).
static const VDuration& DAY(); ///< Duration constant of 1 day (24 hours).
static const VDuration& UNSPECIFIED(); ///< Special duration constant that is unequal to any other duration value.
static const VDuration& NEGATIVE_INFINITY(); ///< Special duration constant that is "less than" all specific durations.
static const VDuration& POSITIVE_INFINITY(); ///< Special duration constant that is "greater than" all specific durations.
/** Constructs a duration equal to ZERO, or zero milliseconds. */
VDuration() : mDurationMilliseconds(0) {}
/** Copy constructor. @param d a duration to copy. */
VDuration(const VDuration& d) : mDurationMilliseconds(d.mDurationMilliseconds) {}
/** Constructs a duration that is the difference from the specified instant to now. @param sinceWhen the start time to measure from */
VDuration(const VInstant& sinceWhen);
/** Non-virtual destructor. This class is not intended to be subclassed. */
~VDuration() {}
/**
Rather than have a constructor that takes a string, and risk unintended overloading,
we define a static helper if you want to construct a VDuration from a duration string.
It uses setDurationString internally to do the work.
@see setDurationString
@param s the string indicating the duration
@return the VDuration
*/
static VDuration createFromDurationString(const VString& s);
/** Assignment operator. @param d a duration to assign from */
VDuration& operator=(const VDuration& d) { if (this != &d) mDurationMilliseconds = d.getDurationMilliseconds(); return *this; }
/** Increment operator. @param forwardOffset a duration to add */
VDuration& operator+=(const VDuration& forwardOffset);
/** Decrement operator. @param backwardOffset a duration to subtract */
VDuration& operator-=(const VDuration& backwardOffset);
/** In-place multiplication operator. @param multiplier a number to multiply the duration by */
VDuration& operator*=(Vs64 multiplier);
/** In-place division operator. @param divisor a number to divide the duration by @throws does nothing if the divisor is zero */
VDuration& operator/=(int divisor);
/** In-place modulo operator. @param divisor a duration to modulo the duration by @throws does nothing if the divisor is zero or not specific */
VDuration& operator%=(const VDuration& divisor);
/** Unary negation operator. @return the negative of this duration */
VDuration operator-() const;
/** Returns the duration in milliseconds. @return obvious */
Vs64 getDurationMilliseconds() const { return mDurationMilliseconds; }
/** Returns the duration in whole seconds, using simple truncating division of milliseconds. @return obvious */
int getDurationSeconds() const { return static_cast<int>(mDurationMilliseconds / kMillisecondsPerSecond); }
/** Returns the duration in whole minutes, using simple truncating division of milliseconds. @return obvious */
int getDurationMinutes() const { return static_cast<int>(mDurationMilliseconds / kMillisecondsPerMinute); }
/** Returns the duration in whole hours, using simple truncating division of milliseconds. @return obvious */
int getDurationHours() const { return static_cast<int>(mDurationMilliseconds / kMillisecondsPerHour); }
/** Returns the duration in whole days, using simple truncating division of milliseconds. @return obvious */
int getDurationDays() const { return static_cast<int>(mDurationMilliseconds / kMillisecondsPerDay); }
/** Returns a string formatted as in the simplest integer+suffix possible as described in setDurationString() docs below. @return obvious */
VString getDurationString() const;
/** Returns a string formatted as s.uuu, the number of seconds and milliseconds. @return obvious */
VString getDurationStringFractionalSeconds() const;
/** Sets the duration in milliseconds. @param durationMilliseconds the duration to set, in milliseconds */
void setDurationMilliseconds(Vs64 durationMilliseconds) { mDurationMilliseconds = durationMilliseconds; }
/** Sets the duration in seconds. @param durationSeconds the duration to set, in seconds */
void setDurationSeconds(int durationSeconds) { mDurationMilliseconds = kMillisecondsPerSecond * static_cast<Vs64>(durationSeconds); }
/** Sets the duration in minutes. @param durationMinutes the duration to set, in minutes */
void setDurationMinutes(int durationMinutes) { mDurationMilliseconds = kMillisecondsPerMinute * static_cast<Vs64>(durationMinutes); }
/** Sets the duration in hours. @param durationHours the duration to set, in hours */
void setDurationHours(int durationHours) { mDurationMilliseconds = kMillisecondsPerHour * static_cast<Vs64>(durationHours); }
/** Sets the duration in 24-hour days (no DST calculations are done). @param durationDays the duration to set, in 24-hour days */
void setDurationDays(int durationDays) { mDurationMilliseconds = kMillisecondsPerDay * static_cast<Vs64>(durationDays); }
/**
Sets the duration via a simple human-readable format that indicates value and magnitude.
Please note that because this requires string parsing, it is less efficient than using
VDuration constants and multiplication.
If present, the suffix of s must be one of: ms | s | m | h | d
The prefix is an integer (leading minus sign allowed).
If the suffix is omitted the string must be in the form s.mmm just like what
getDurationString() returns. This is to allow get/set symmetry.
Whitespace between the prefix and suffix is allowed but not preferred.
Here are examples with each allowed suffix and the (obvious) meaning:
27ms
23472ms (meaning 23.472 seconds)
5s
107s (meaning 1 minute 47 seconds)
8m
152m (meaning 2 hours 32 minutes)
3h
7d
5.273 (meaning 5.273 seconds)
The prefix value is simply multiplied out to get the raw number of milliseconds to store in
the object. No calendar-like operations are done, which is why "weeks", "months", etc. are
not supported.
For symmetry of getDurationString/setDurationString, the following strings are used for the
special durations. (They are case-insensitive on input, and written as upper case on output.)
"INFINITY" <-> VDuration::POSITIVE_INFINITY()
"-INFINITY" <-> VDuration::NEGATIVE_INFINITY()
"UNSPECIFIED" <-> VDuration::UNSPECIFIED()
@param s the string indicating the duration
@throws VRangeException if the string is malformed
*/
void setDurationString(const VString& s);
friend inline bool operator==(const VDuration& lhs, const VDuration& rhs); ///< Compares durations for equality in milliseconds using ==.
friend inline bool operator!=(const VDuration& lhs, const VDuration& rhs); ///< Compares durations for equality in milliseconds using !=.
friend inline bool operator< (const VDuration& lhs, const VDuration& rhs); ///< Compares durations for equality in milliseconds using <.
friend inline bool operator<=(const VDuration& lhs, const VDuration& rhs); ///< Compares durations for equality in milliseconds using <=.
friend inline bool operator>=(const VDuration& lhs, const VDuration& rhs); ///< Compares durations for equality in milliseconds using >=.
friend inline bool operator> (const VDuration& lhs, const VDuration& rhs); ///< Compares durations for equality in milliseconds using >.
friend inline VDuration operator+(const VDuration& d1, const VDuration& d2);///< Adds d1 + d2 and returns their total duration.
friend inline VDuration operator-(const VDuration& d1, const VDuration& d2);///< Subtracts d2 from d1 and returns the difference in duration.
friend inline VDuration operator*(Vs64 multiplier, const VDuration& d1); ///< Multiplies d1 by a number and returns the resulting duration; uses Vs64 for VInstant delta compatibility.
friend inline VDuration operator*(const VDuration& d1, Vs64 multiplier); ///< Multiplies d1 by a number and returns the resulting duration; uses Vs64 for VInstant delta compatibility.
friend VDuration operator/(const VDuration& d, int divisor); ///< Divides d1 by a number and returns the resulting duration. @throws VException if the divisor is zero
friend VDuration operator%(const VDuration& d, const VDuration& divisor); ///< Returns d modulo the divisor. Does nothing if the divisor is zero or not specific.
static inline VDuration min(const VDuration& d1, const VDuration& d2); ///< Returns a duration that is the lesser of d1 and d2.
static inline VDuration max(const VDuration& d1, const VDuration& d2); ///< Returns a duration that is the greater of d1 and d2.
static inline VDuration abs(const VDuration& d); ///< Returns a duration that is equal to d if d is > ZERO, and -d if d is < ZERO.
/**
Returns true if the duration can be legitimately compared using comparison
operators such as <, <=, >, >=. This is the case for specific durations as
well as the infinite durations. It is not the case for unspecified durations.
*/
bool isComparable() const { return (*this != VDuration::UNSPECIFIED()); }
/**
Returns true if the duration has a specific value (not infinite) and therefore
its internal duration value can be tested and used in simple math calculations.
*/
bool isSpecific() const { return (*this != VDuration::UNSPECIFIED()) && (*this != VDuration::NEGATIVE_INFINITY()) && (*this != VDuration::POSITIVE_INFINITY()); }
/**
Returns true if d1 and d2 can be compared using simple value comparison.
In other words, both d1 and d2 have specific values. It's false if either
one is not specific.
*/
static bool areValuesSpecific(const VDuration& d1, const VDuration& d2) { return d1.isSpecific() && d2.isSpecific(); }
private:
// These are called by the friend inline comparison operators for comparing non-simple durations.
static VDuration _complexAdd(const VDuration& d1, const VDuration& d2);
static VDuration _complexSubtract(const VDuration& d1, const VDuration& d2);
static VDuration _complexMultiply(const VDuration& d, Vs64 multiplier);
static VDuration _complexMin(const VDuration& d1, const VDuration& d2);
static VDuration _complexMax(const VDuration& d1, const VDuration& d2);
static VDuration _complexAbs(const VDuration& d);
// This is the private constructor used internally.
explicit VDuration(Vs64 durationMilliseconds) : mDurationMilliseconds(durationMilliseconds) {}
Vs64 mDurationMilliseconds; ///< The duration in milliseconds. The values for UNSPECIFIED, NEGATIVE_INFINITY, and POSITIVE_INFINITY are special.
// These are used internally for conversion.
static const Vs64 kMillisecondsPerSecond = CONST_S64(1000);
static const Vs64 kMillisecondsPerMinute = CONST_S64(60000);
static const Vs64 kMillisecondsPerHour = CONST_S64(3600000);
static const Vs64 kMillisecondsPerDay = CONST_S64(86400000);
};
// Inline implementations of some of the above VDuration operators.
// For non-specific values, some operators need to call more complicated functions to provide
// sensible values.
inline bool operator==(const VDuration& lhs, const VDuration& rhs) { return lhs.mDurationMilliseconds == rhs.mDurationMilliseconds; }
inline bool operator!=(const VDuration& lhs, const VDuration& rhs) { return !operator==(lhs, rhs); }
inline bool operator< (const VDuration& lhs, const VDuration& rhs) { return lhs.mDurationMilliseconds < rhs.mDurationMilliseconds; }
inline bool operator<=(const VDuration& lhs, const VDuration& rhs) { return !operator>(lhs, rhs); }
inline bool operator>=(const VDuration& lhs, const VDuration& rhs) { return !operator<(lhs, rhs); }
inline bool operator> (const VDuration& lhs, const VDuration& rhs) { return operator<(rhs, lhs); }
inline VDuration operator+(const VDuration& d1, const VDuration& d2) { if (VDuration::areValuesSpecific(d1, d2)) return VDuration(d1.mDurationMilliseconds + d2.mDurationMilliseconds); else return VDuration::_complexAdd(d1, d2); }
inline VDuration operator-(const VDuration& d1, const VDuration& d2) { if (VDuration::areValuesSpecific(d1, d2)) return VDuration(d1.mDurationMilliseconds - d2.mDurationMilliseconds); else return VDuration::_complexSubtract(d1, d2); }
inline VDuration operator*(Vs64 multiplier, const VDuration& d) { if (d.isSpecific()) return VDuration(d.mDurationMilliseconds * multiplier); else return VDuration::_complexMultiply(d, multiplier); }
inline VDuration operator*(const VDuration& d, Vs64 multiplier) { if (d.isSpecific()) return VDuration(d.mDurationMilliseconds * multiplier); else return VDuration::_complexMultiply(d, multiplier); }
inline VDuration VDuration::min(const VDuration& d1, const VDuration& d2) { if (VDuration::areValuesSpecific(d1, d2)) return (d1 < d2) ? d1 : d2; else return VDuration::_complexMin(d1, d2); }
inline VDuration VDuration::max(const VDuration& d1, const VDuration& d2) { if (VDuration::areValuesSpecific(d1, d2)) return (d1 > d2) ? d1 : d2; else return VDuration::_complexMax(d1, d2); }
inline VDuration VDuration::abs(const VDuration& d) { if (d.isSpecific()) return (d.mDurationMilliseconds < CONST_S64(0)) ? -d : d; else return VDuration::_complexAbs(d); }
/**
VDurationVector is simply a vector of VDuration objects. Note that the vector
elements are objects, not pointers to objects.
*/
typedef std::vector<VDuration> VDurationVector;
/**
This structure is passed to or returned by the core functions to
describe a calendar structured instant in some implied time zone.
*/
class VInstantStruct {
public:
VInstantStruct() : mYear(0), mMonth(1), mDay(1), mHour(0), mMinute(0), mSecond(0), mMillisecond(0), mDayOfWeek(0) {}
VInstantStruct(const VDate& date, const VTimeOfDay& timeOfDay);
/**
Returns the UTC Epoch Offset of this Time Struct, treating the Time
Struct as an instant in the UTC time zone. The mDayOfWeek field is ignored.
@return the UTC Epoch Offset of this UTC time struct
*/
Vs64 getOffsetFromUTCStruct() const;
/**
Returns the UTC Epoch Offset of this Time Struct, treating the Time
Struct as an instant in the machine's local time zone. The mDayOfWeek field
is ignored.
@return the UTC Epoch Offset of this local time struct
*/
Vs64 getOffsetFromLocalStruct() const;
/**
Fills in a Time Struct to represent the specified UTC Epoch Offset in the
UTC time zone.
@param offset a UTC Epoch Offset
*/
void setUTCStructFromOffset(Vs64 offset);
/**
Fills in this Time Struct to represent the specified UTC Epoch Offset in the
machine's local time zone.
@param offset a UTC Epoch Offset
*/
void setLocalStructFromOffset(Vs64 offset);
/**
Copies this Time Struct into a "struct tm" POSIX structure.
@param fields the tm struct to initialize
*/
void getTmStruct(struct tm& fields) const;
/**
Sets up this Time Struct from a "struct tm" POSIX structure.
@param fields the tm struct to copy
@param millisecond the ms value to use, since tm only has second resolution; normally zero except for some conversions
*/
void setFromTmStruct(const struct tm& fields, int millisecond);
int mYear; ///< The year.
int mMonth; ///< The month (1 to 12).
int mDay; ///< The day of the month (1 to 31).
int mHour; ///< The hour of day (0 to 23).
int mMinute; ///< The minute of the hour (0 to 59).
int mSecond; ///< The second of the minute (0 to 59).
int mMillisecond; ///< The millisecond within the second (0 to 999).
int mDayOfWeek; ///< See enum in VInstant: kSunday=0..kSaturday=6.
private:
// These are the 3 platform-defined helper functions for converting between
// offsets and UTC or local broken-down time struct. There isn't one for
// "from UTC struct" because it is not per-platform; if timegm is available
// we call it, otherwise we implement it directly.
/**
Returns the UTC Epoch Offset of the specified Time Struct, treating the Time
Struct as an instant in the machine's local time zone. The mDayOfWeek field
is ignored.
@return the UTC Epoch Offset of the specified local time struct
*/
static Vs64 _platform_offsetFromLocalStruct(const VInstantStruct& when);
/**
Fills in a Time Struct to represent the specified UTC Epoch Offset in the
machine's local time zone.
@param offset a UTC Epoch Offset
@param when the Time Struct to fill in with the local time zone
representation of the offset
*/
static void _platform_offsetToLocalStruct(Vs64 offset, VInstantStruct& when);
/**
Fills in a Time Struct to represent the specified UTC Epoch Offset in the
UTC time zone.
@param offset a UTC Epoch Offset
@param when the Time Struct to fill in with the UTC time zone
representation of the offset
*/
static void _platform_offsetToUTCStruct(Vs64 offset, VInstantStruct& when);
/**
Provides a robust interface to localtime without the thread safety pitfalls,
using the re-entrant version if available. Throws an exception if the date
specified is out of range for the platform's time implementation.
(Specifically, Win32 does not support dates prior to 1970!)
The result structure contains the broken-down time corresponding to the
supplied offset, in local time.
@param epochOffset number of seconds since 1/1/1970 UTC
@param resultStorage pointer to tm struct to be filled out in local time
*/
static void _threadsafe_localtime(const time_t epochOffset, struct tm* resultStorage);
/**
Provides a robust interface to gmtime without the thread safety pitfalls,
using the re-entrant version if available. Throws an exception if the date
specified is out of range for the platform's time implementation.
(Specifically, Win32 does not support dates prior to 1970!)
The result structure contains the broken-down time corresponding to the
supplied offset, in GMT time.
@param epochOffset number of seconds since 1/1/1970 UTC
@param resultStorage pointer to tm struct to be filled out in GMT time
*/
static void _threadsafe_gmtime(const time_t epochOffset, struct tm* resultStorage);
};
/**
You can provide a callback interface for VInstant to allow for converting
to and from "remote time zones" (RTZ). Currently the built-in code of VInstant
(using OS-provided functions) can only convert between UTC and the local
time zone.
To implement remote time zone conversion, implement this interface, and
call VInstant::setRemoteTimeZoneConverter(). Then you can pass RTZ specifiers
to the VInstant APIs that allow them, and VInstant will call back to
the installed RTZ converter interface.
*/
class IVRemoteTimeZoneConverter {
public:
/**
Converts an offset (ms from 1970 UTC, same as VInstant "value") to
a broken-down calendar time in the specified time zone. This function
should throw a VException if the time zone ID is invalid.
@param offset a number milliseconds since UTC 1970 00:00:00.000
@param timeZoneID a time zone ID string (e.g., PST, EST, etc.) from
the set of strings supported by the converter
@param when a structure that will be filled to contain the
y/m/d/h/m/s for the specified UTC offset as seen in
the specified time zone
*/
virtual void offsetToRTZStruct(Vs64 offset, const VString& timeZoneID, VInstantStruct& when) = 0;
/**
Converts a broken-down calendar time, interpreted in the specified
time zone, to an offset (ms from 1970 UTC, same as VInstant "value").
This function should throw a VException if the time zone ID is invalid.
@param timeZoneID a time zone ID string (e.g., PST, EST, etc.) from
the set of strings supported by the converter
@param when a structure containing y/m/d/h/m/s values in the
specified time zone
@return the number milliseconds since UTC 1970 00:00:00.000 that the
time represents as interpreted in the specified
time zone
*/
virtual Vs64 offsetFromRTZStruct(const VString& timeZoneID, const VInstantStruct& when) = 0;
protected:
IVRemoteTimeZoneConverter() {}
virtual ~IVRemoteTimeZoneConverter() {}
};
/**
A VInstant is an object that represents an instant in time regardless of the
location (and time zone) of where code is running.
A key purpose of VInstant is to abstract the OS time-related APIs while
retaining the ability to easily compare two instants that originated in
code running in different time zones--internally, the value is stored in
UTC time.
You can create a VInstant to represent the current instant in time, and you
can convert to and from string representations in UTC or the current locale.
A VInstant can also be created to represent instants infinitely far in the
past or future, to indicate events that have not yet happened or should
never happen.
*/
class VInstant {
public:
/** Constant VInstant representing the kInfinitePast value. */
static const VInstant& INFINITE_PAST();
/** Constant VInstant representing the kInfiniteFuture value. */
static const VInstant& INFINITE_FUTURE();
/** Constant VInstant representing the kNeverOccurred value. */
static const VInstant& NEVER_OCCURRED();
/** Constant for use with functions that take a timeZoneID parameter,
indicating the time conversion is for UTC. */
static const VString& UTC_TIME_ZONE_ID();
/** Constant for use with functions that take a timeZoneID parameter,
indicating the time conversion is for the local time zone. */
static const VString& LOCAL_TIME_ZONE_ID();
/**
Returns an instant created from a raw 64-bit millisecond UTC epoch offset,
of the same form as is returned by getValue() and can be passed to setValue().
@param value the time value in ms since UTC 1970 00:00:00.000 (negative values
represent earlier instants in time)
@return an instant representing the specified time
*/
static VInstant instantFromRawValue(Vs64 value) { return VInstant(value); }
/**
Returns an instant created from a POSIX time_t value, which is defined as the
number of seconds since UTC 1970 00:00:00.000.
@param value the POSIX time value (seconds since UTC 1970 00:00:00.000) (negative values
represent earlier instants in time)
@return an instant representing the specified time
*/
static VInstant instantFromPosixTime(time_t value) { return VInstant(CONST_S64(1000) * static_cast<Vs64>(value)); }
/**
Creates an instant to represent the current time.
*/
VInstant();
/**
Creates an instant by copying an existing instant.
*/
VInstant(const VInstant& i) : mValue(i.mValue) {}
/**
Destructor.
*/
~VInstant() {}
/**
Copy constructor.
@param i the instant to copy
*/
VInstant& operator=(const VInstant& i);
/**
Increments (or decrements) the instant in time from its current value
by the specified VDuration if the kind is kActualValue.
If the kind is not kActualValue, this function has no effect.
@param forwardOffsetDuration the duration offset in milliseconds to apply;
positive values move the instant forward in time;
negative values move it backward
*/
VInstant& operator+=(const VDuration& forwardOffsetDuration);
/**
Decrements (or increments) the instant in time from its current value
by the specified VDuration if the kind is kActualValue.
If the kind is not kActualValue, this function has no effect.
@param backwardOffsetDuration the offset in milliseconds to apply;
positive values move the instant backward in time;
negative values move it forward
*/
VInstant& operator-=(const VDuration& backwardOffsetDuration);
/**
Sets the instant to the current time. The time is affected by any simulated
or frozen time state that has been set.
*/
void setNow();
/**
Sets the instant to the actual current time not offset by simulation or frozen time.
*/
void setTrueNow();
/**
Returns an object holding the broken-down fields that this instant represents
in UTC. This is primarily for use by VInstantFormatter when formatting a string.
@return the UTC y/m/d/h/m/s etc. values for this instant
*/
VInstantStruct getUTCInstantFields() const;
/**
Returns an object holding the broken-down fields that this instant represents
in the current time zone. This is primarily for use by VInstantFormatter when formatting a string.
@return the current time zone y/m/d/h/m/s etc. values for this instant
*/
VInstantStruct getLocalInstantFields() const;
/*
There are two flavors of string conversion -- UTC and local -- and each one has
a modern form and a legacy form.
The modern form returns the string, and is supplied a VInstantFormatter to control
the format; there are several preset formatters available in VInstantFormatter.
If you omit the formatter you get the same format that the legacy API provided
prior to Vault 4.0, for backward compatibility.
The legacy form puts the string into a read-write parameter and has optional
parameters to control whether milliseconds are included and whether punctuation
is stripped out to make the string safe to use as a file system node name.
*/
// Modern APIs starting with Vault 4.0:
/**
Returns a string for this instant in UTC time in the format "y-MM-dd HH:mm:ss.SSS UTC",
or one of the special time value strings "PAST", "FUTURE", or "NEVER".
@return obvious
*/
VString getUTCString() const;
/**
Returns a string for this instant in UTC time in the specified format,
or one of the special time value strings "PAST", "FUTURE", or "NEVER".
@param formatter the formatter to use
@return obvious
*/
VString getUTCString(const VInstantFormatter& formatter) const;
/**
Returns a string for this instant in local time in the format "y-MM-dd HH:mm:ss.SSS",
or one of the special time value strings "PAST", "FUTURE", or "NEVER".
@return obvious
*/
VString getLocalString() const;
/**
Returns a string for this instant in local time in the specified format,
or one of the special time value strings "PAST", "FUTURE", or "NEVER".
@param formatter the formatter to use
@return obvious
*/
VString getLocalString(const VInstantFormatter& formatter) const;
// Legacy APIs:
/**
Returns a string for this instant in UTC time, or one of the special time value
strings "PAST", "FUTURE", or "NEVER". You can specify whether to use a format that
is safe for use in a file system node name (no punctuation), and whether to include
the milliseconds.
@param s the string for format for return
@param fileNameSafe if true, the format omits punctuation and the " UTC" suffix so it can be safely used in a file system node name
@param wantMilliseconds if true, the milliseconds suffix is included; otherwise not
*/
void getUTCString(VString& s, bool fileNameSafe = false, bool wantMilliseconds = true) const;
/**
Returns a string for this instant in local time, or one of the special time value
strings "PAST", "FUTURE", or "NEVER". You can specify whether to use a format that
is safe for use in a file system node name (no punctuation), and whether to include
the milliseconds.
@param s the string for format for return
@param fileNameSafe if true, the format omits punctuation so it can be safely used in a file system node name
@param wantMilliseconds if true, the milliseconds suffix is included; otherwise not
*/
void getLocalString(VString& s, bool fileNameSafe = false, bool wantMilliseconds = true) const;
/**
Sets the instant from a UTC string representation.
You must use the same string format as returned by getUTCString(), that is "y-MM-dd HH:mm:ss.SSS UTC",
or one of the special time value strings "PAST", "FUTURE", or "NEVER", or the special string "NOW".
@param s the UTC string representation of the instant
@see VInstant::getUTCString()
*/
void setUTCString(const VString& s);
/**
Sets the instant from a local string representation.
You must use the same string format as returned by getLocalString(), that is "y-MM-dd HH:mm:ss.SSS",
or one of the special time value strings "PAST", "FUTURE", or "NEVER", or the special string "NOW".
@param s the local string representation of the instant
@see VInstant::getLocalString()
*/
void setLocalString(const VString& s);
/**
Returns true if the instance has a specific time value, indicating that it
is not one of the special time constants NEVER_OCCURRED, INFINITE_PAST, or
INFINITE_FUTURE.
*/
bool isSpecific() const { return (*this != VInstant::NEVER_OCCURRED()) && (*this != VInstant::INFINITE_PAST()) && (*this != VInstant::INFINITE_FUTURE()); }
/**
Returns true if the instance kind is comparable, indicating that it
can be compared against another time along the timeline; in particular,
instants with kind kNeverOccurred are not comparable.
*/
bool isComparable() const { return (*this != VInstant::NEVER_OCCURRED()); }
/**
Returns the raw time value of the instant, defined as milliseconds since
UTC 1970 00:00:00.000. Actual resolution may only be seconds, depending on OS.
You should generally avoid accessing this value since it is not abstract;
you can use other functions and operators to shift forward and backward
in time, to get streamable values, etc. You can use the value returned
by this function to set into another VInstant using setValue(), but you
must also synchronize the "kind" as well (see getKind(), setKind()) if
you are using any kinds other than kActualValue.
@return the time value in ms since UTC 1970 00:00:00.000 (negative values
represent earlier instants in time)
*/
Vs64 getValue() const { return mValue; }
/**
Sets the raw time value of the instant, defined as milliseconds since
UTC 1970 00:00:00.000. Actual resolution may only be seconds, depending on OS.
You should generally avoid accessing this value since it is not abstract;
you can use other functions and operators to shift forward and backward
in time, to set from streamed values, etc. You can use the value returned
by getValue() to supply to this function, but you must also synchronize
the "kind" as well (see getKind(), setKind()) if
you are using any kinds other than kActualValue.
@param value the time value in ms since UTC 1970 00:00:00.000 (negative values
represent earlier instants in time)
*/
void setValue(Vs64 value) { mValue = value; }
/**
Returns a VDate to represent the instant's date, just as would be returned
in the date value returned by getValues() if you specified the local time zone.
@return the date of the instant in the local time zone
*/
VDate getLocalDate() const;
/**
Returns a VDate to represent the instant's date, just as would be returned
in the date value returned by getValues(). The difference is that this function
only returns the date, as a convenience. If you need both date and time, it is
more efficient to call getValues() than getDate() followed by getTimeOfDay(),
because the underlying conversion must happen on each of those calls. Throws an
exception if you specify RTZ conversion and there is no converter installed.
@param timeZoneID specifies which time zone the result should be given in
@return the date of the instant in the specified time zone
*/
VDate getDate(const VString& timeZoneID) const;
/**
Returns a VTimeOfDay to represent the instant's time, just as would be returned
in the timeOfDay value returned by getValues() if you specified the local time
zone.
@return the time of day of the instant in the local time zone
*/
VTimeOfDay getLocalTimeOfDay() const;
/**
Returns a VTimeOfDay to represent the instant's time, just as would be returned
in the timeOfDay value returned by getValues(). The difference is that this function
only returns the time of day, as a convenience. If you need both date and time, it is
more efficient to call getValues() than getDate() followed by getTimeOfDay(),
because the underlying conversion must happen on each of those calls. Throws an
exception if you specify RTZ conversion and there is no converter installed.
@param timeZoneID specifies which time zone the result should be given in
@return the time of day of the instant in the specified time zone
*/
VTimeOfDay getTimeOfDay(const VString& timeZoneID) const;
/**
Returns a VDateAndTime to represent the instant's time, just as would be returned
in the values returned by getValues(), using the local time zone.
@return the date and time of day of the instant in the local time zone
*/
VDateAndTime getLocalDateAndTime() const;
/**
Returns a VDateAndTime to represent the instant's time, just as would be returned
in the values returned by getValues(). Throws an
exception if you specify RTZ conversion and there is no converter installed.
@param timeZoneID specifies which time zone the result should be given in
@return the date and time of day of the instant in the specified time zone
*/
VDateAndTime getDateAndTime(const VString& timeZoneID) const;
/**
Sets the instant to represent the specified time, just as would be done
by setValues(), using the local time zone.
@param dt the date and time of day to use
*/
void setLocalDateAndTime(const VDateAndTime& dt);
/**
Sets the instant to represent the specified time, just as would be done
by setValues(), using the specified time zone. Throws an
exception if you specify RTZ conversion and there is no converter installed.
@param dt the date and time of day to use
@param timeZoneID specifies which time zone the date and time is given in
*/
void setDateAndTime(const VDateAndTime& dt, const VString& timeZoneID);
/**
Returns a VDate and VTimeOfDay to represent the instant, either in
UTC or local time, or in a remote time zone (if an RTZ converter has
been installed). Throws an exception if you specify RTZ conversion
and there is no converter installed.
@param date the VDate to set
@param timeOfDay the VTimeOfDay to set
@param timeZoneID specifies which time zone the result should be given in
*/
void getValues(VDate& date, VTimeOfDay& timeOfDay, const VString& timeZoneID) const;
/**
Sets the instant from a VDate and VTimeOfDay, either in UTC or local time,
or in a remote time zone (if an RTZ converter has been installed). Throws an
exception if you specify RTZ conversion and there is no converter installed.
@param date the date to use
@param timeOfDay the time of day to use
@param timeZoneID specifies which time zone in which the supplied date and
time are given in
*/
void setValues(const VDate& date, const VTimeOfDay& timeOfDay, const VString& timeZoneID);
/**
Returns the local offset in milliseconds, of the local time zone, at the instant
in time represented by this VInstant. For locales west of GMT, this value is
negative (e.g., -8 hours or -7 hours in California, depending on daylight time),
and for locales east of GMT, this value is positive.
*/
Vs64 getLocalOffsetMilliseconds() const;
friend inline bool operator==(const VInstant& lhs, const VInstant& rhs); ///< Compares two instants.
friend inline bool operator!=(const VInstant& lhs, const VInstant& rhs); ///< Compares two instants.
friend inline bool operator< (const VInstant& lhs, const VInstant& rhs); ///< Compares two instants.
friend inline bool operator<=(const VInstant& lhs, const VInstant& rhs); ///< Compares two instants.
friend inline bool operator>=(const VInstant& lhs, const VInstant& rhs); ///< Compares two instants.
friend inline bool operator> (const VInstant& lhs, const VInstant& rhs); ///< Compares two instants.
friend inline VDuration operator-(const VInstant& i1, const VInstant& i2); ///< Returns the time duration between i1 and i2. @param i1 an instant @param i2 an instant @return i1 - i2 as a VDuration
friend inline VInstant operator+(const VInstant& i1, const VDuration& forwardDuration); ///< Returns an instant incremented by a delta. @param i1 an instant @param forwardDuration the duration to add @return the result of i1+forwardDuration
friend inline VInstant operator-(const VInstant& i1, const VDuration& backwardDuration);///< Returns an instant decremented by a delta. @param i1 an instant @param backwardDuration the duration to subtract to add @return the result of i1-backwardDuration
static inline VInstant min(const VInstant& i1, const VInstant& i2); ///< Returns the earlier of i1 and i2. @param i1 an instant @param i2 an instant @return i1 if i1 < i2
static inline VInstant max(const VInstant& i1, const VInstant& i2); ///< Returns the later of i1 and i2. @param i1 an instant @param i2 an instant @return i1 if i1 > i2
/**
Returns a relatively high-resolution snapshot of the current time, for
use with a subsequent call to VInstant::snapshotDelta(). You should
not assume that the snapshot value remains valid across system starts;
if you need to get the difference in times across reboots, use normal
VInstant operator minus.
@return the current system clock snapshot
*/
static Vs64 snapshot();
/**
Returns the delta between the current time and the supplied
origin snapshot value. As noted in the VInstant::snapshot() docs, the
delta may not work across reboots.
@param snapshotValue a snapshot value from VInstant::snapshot()
@return the time delta from the snapshot to now
*/
static VDuration snapshotDelta(Vs64 snapshotValue);
/**
Installs a Remote Time Zone Converter, that VInstant will use for functions
that take a timeZoneID, if that parameter is not UTC or the local time zone.
The caller still owns the converter; VInstant will not delete it. You can
pass NULL to disable use of RTZ conversion (by default, no converter is
installed).
*/
static void setRemoteTimeZoneConverter(IVRemoteTimeZoneConverter* converter);
/**
Returns the currently installed Remote Time Zone Converter, which may be
NULL. You might use this to delete the old converter if you are installing
a new one. VInstant uses whatever converter is installed (if it's not NULL)
at the time it needs it.
*/
static IVRemoteTimeZoneConverter* getRemoteTimeZoneConverter();
// Time simulation features. Note that if "frozen time" is in effect, the
// "clock offset" information is not used.
/**
Adjusts the simulated clock offset. The simulated clock offset is applied
by _platform_now() and _platform_snapshot() to the values they return. This
can be used to simulate a faster passing of time, by adjusting the clock
forward. It may be impractical to adjust the clock backwards, because some
code constructs may behave badly if time flows backwards. However, you may
be able to apply an initial backwards offset if you wish to start your
program running in a simulated time in the past.
@param delta the amount of offset to add/delete
*/
static void incrementSimulatedClockOffset(const VDuration& delta);
/**
Sets the simulated clock offset. The simulated clock offset is applied
by setNow() and snapshot() to the values they return. This
can be used to simulate a faster passing of time, by adjusting the clock
forward. It may be impractical to adjust the clock backwards, because some
code constructs may behave badly if time flows backwards. However, you may
be able to apply an initial backwards offset if you wish to start your
program running in a simulated time in the past.
@param offset the simulated clock offset
*/
static void setSimulatedClockOffset(const VDuration& offset);
/**
Sets the simulated clock offset implied by the specified absolute time value.
The simulated clock offset is applied
by setNow() and snapshot() to the values they return. This
can be used to simulate a faster passing of time, by adjusting the clock
forward. It may be impractical to adjust the clock backwards, because some
code constructs may behave badly if time flows backwards. However, you may
be able to apply an initial backwards offset if you wish to start your
program running in a simulated time in the past.
@param simulatedCurrentTime the simulated time from which to calculate the offset
*/
static void setSimulatedClockValue(const VInstant& simulatedCurrentTime);
/**
Returns the simulated clock offset. The simulated clock offset is applied
by _platform_now() and _platform_snapshot() to the values they return. This
can be used to simulate a faster passing of time, by adjusting the clock
forward. It may be impractical to adjust the clock backwards, because some
code constructs may behave badly if time flows backwards. However, you may
be able to apply an initial backwards offset if you wish to start your
program running in a simulated time in the past.
*/
static VDuration getSimulatedClockOffset();
/**
Freezes the flow of time by specifying an absolute time that will be returned
by any call to setNow(), as well as any use of snapshot() to track time deltas.
@param frozenTimeValue the time value that is frozen
*/
static void freezeTime(const VInstant& frozenTimeValue);
/**
Shifts the frozen time value by the specified amount. This can be used to freeze
time and then cause it to flow slowly or quickly by manually rolling time forward at
the desired rate.
@param delta the duration by which to offset the frozen time; negative values
may have strange effects
*/
static void shiftFrozenTime(const VDuration& delta);
/**
Unfreezes time and resumes real-time operation. If you previously used a future
time for freezing, you should probably install a clock offset value before
unfreezing, to ensure that time proceeds forward; otherwise you will unfreeze
and end up in an earlier time (now).
*/
static void unfreezeTime();
/**
Returns true if time is currently frozen.
@return true if time is frozen
*/
static bool isTimeFrozen();
private:
// This is the private constructor used internally.
explicit VInstant(Vs64 utcOffsetMilliseconds) : mValue(utcOffsetMilliseconds) {}
Vs64 mValue; ///< Milliseconds since: UTC 1970 00:00:00.000. Actual resolution may only be seconds, depending on OS. Using {64-bit,ms} means our definition does not have painful range limits like {32-bit,sec}.
/**
Returns true if i1 and i2 can be compared using simple value comparison.
(It's false if either one has mKind != kActualValue.)
*/
static bool canCompareValues(const VInstant& i1, const VInstant& i2) { return i1.isSpecific() && i2.isSpecific(); }
/**
Returns true if i1 > i2, considering the complexity of mKind != kActualValue.
*/
static bool _complexGT(const VInstant& i1, const VInstant& i2);
/**
Returns true if i1 >= i2, considering the complexity of mKind != kActualValue.
*/
static bool _complexGTE(const VInstant& i1, const VInstant& i2);
/**
Returns true if i1 < i2, considering the complexity of mKind != kActualValue.
*/
static bool _complexLT(const VInstant& i1, const VInstant& i2);
/**
Returns true if i1 <= i2, considering the complexity of mKind != kActualValue.
*/
static bool _complexLTE(const VInstant& i1, const VInstant& i2);
/*
These are the core function interfaces that must be implemented on a
per-platform basis. That is, they are platform-specific and are
implemented in the vinstant_platform.* files. All other time
conversion is performed via these calls. This allows us to isolate
the platform and library quirks in those files rather than conditionally
compile code in vinstant.cpp.
There are only two types used here.
- The 64-bit millisecond "offset" from UTC 1970. This is also what VInstant
uses an offset. We'll just refer to this as a UTC Epoch Offset.
- The y/m/d/h/m/s "struct" in some time zone. We'll just refer to this
as a "Time Struct".
It's all about converting between them.
There is one additional function, _platform_snapshot(), which is not about
time conversion, but just about measuring short time durations with
millisecond resolution.
*/
/**
Returns the current UTC Epoch Offset in milliseconds. Actual resolution may
only be seconds, depending on OS.
@return the current UTC Epoch Offset in milliseconds
*/
static Vs64 _platform_now();
/**
Returns a current time value with millisecond resolution; the base value
is unspecified, and this is only to be used to count time deltas between
two snapshot values.
@return a clock value representing "now" in milliseconds, base undefined
*/
static Vs64 _platform_snapshot();
static Vs64 gSimulatedClockOffset; ///< Value applied by _platform_now() and _platform_snapshot() to simulate non-real-time flow.
static Vs64 gFrozenClockValue; ///< If non-zero, the "current time" returned is always this value; time is effectively frozen.
static IVRemoteTimeZoneConverter* gRemoteTimeZoneConverter; ///< The converter for RTZ conversion, or NULL.
// Let VDate call the getTimeValue() bottleneck for getting the day of
// week, but don't make it a public API since it's exposing the tm
// structure which is dependent on time.h functionality.
friend class VDate;
friend class VInstantUnit; // Let unit test validate our internal APIs.
};
// Inline implementations of some of the above VInstant operators.
inline bool operator==(const VInstant& lhs, const VInstant& rhs) { return lhs.mValue == rhs.mValue; }
inline bool operator!=(const VInstant& lhs, const VInstant& rhs) { return !operator==(lhs, rhs); }
inline bool operator< (const VInstant& lhs, const VInstant& rhs) { if (VInstant::canCompareValues(lhs, rhs)) return lhs.mValue < rhs.mValue; else return VInstant::_complexLT(lhs, rhs); }
inline bool operator<=(const VInstant& lhs, const VInstant& rhs) { if (VInstant::canCompareValues(lhs, rhs)) return lhs.mValue <= rhs.mValue; else return VInstant::_complexLTE(lhs, rhs); }
inline bool operator>=(const VInstant& lhs, const VInstant& rhs) { if (VInstant::canCompareValues(lhs, rhs)) return lhs.mValue >= rhs.mValue; else return VInstant::_complexGTE(lhs, rhs); }
inline bool operator> (const VInstant& lhs, const VInstant& rhs) { if (VInstant::canCompareValues(lhs, rhs)) return lhs.mValue > rhs.mValue; else return VInstant::_complexGT(lhs, rhs); }
inline VDuration operator-(const VInstant& i1, const VInstant& i2) { if (VInstant::canCompareValues(i1, i2)) return VDuration::MILLISECOND() * (i1.mValue - i2.mValue); else return VDuration(); }
inline VInstant operator+(const VInstant& i1, const VDuration& forwardDuration) { VInstant result = i1; result += forwardDuration; return result; }
inline VInstant operator-(const VInstant& i1, const VDuration& backwardDuration) { VInstant result = i1; result -= backwardDuration; return result; }
inline VInstant VInstant::min(const VInstant& i1, const VInstant& i2) { return (i1 < i2) ? i1 : i2; }
inline VInstant VInstant::max(const VInstant& i1, const VInstant& i2) { return (i1 > i2) ? i1 : i2; }
/**
VInstantVector is simply a vector of VInstant objects. Note that the vector
elements are objects, not pointers to objects.
*/
typedef std::vector<VInstant> VInstantVector;
/**
VDate represents a calendar date: a year/month/day.
Per (*) below, the "day" field is actually allowed to be in the range 1 to 32,
for purposes of allowing the caller to increment the day and then convert to
a VInstant.
*/
class VDate {
public:
static VDate createFromDateString(const VString& dateString, const VCodePoint& delimiter);
/**
Constructs a date with values set to 0000-01-01 (useless but legal state
for a VDate object). Your first use of such a date object should be to
assign it a useful value.
*/
VDate();
/**
Constructs a date from the current instant.
Throws an exception if you
specify RTZ conversion and there is no converter installed.
@param timeZoneID specifies which time zone the y/m/d should be given in
*/
VDate(const VString& timeZoneID);
/**
Constructs a date from specified values.
@param year the year
@param month the month (1 to 12)
@param day the day of the month (1 to 31*)
*/
VDate(int year, int month, int day);
/**
Destructor.
*/
virtual ~VDate() {}
/**
Returns the year of the date.
@return the year
*/
int getYear() const;
/**
Returns the month of the date.
@return the month (1 to 12)
*/
int getMonth() const;
/**
Returns the day of the month of the date.
@return the day of the month (1 to 31*)
*/
int getDay() const;
/**
Returns the day of the week of the date.
@return the day of the week (0=kSunday to 6=kSaturday, as in time.h
and defined in the enum below)
*/
int getDayOfWeek() const;
/**
Sets the date from specified values.
@param year the year
@param month the month of the year (1 to 12)
@param day the day of the month (1 to 31*)
*/
void set(int year, int month, int day);
/**
Sets the year of the date.
@param year the year
*/
void setYear(int year);
/**
Sets the month of the date.
@param month the month of the year (1 to 12)
*/
void setMonth(int month);
/**
Sets the day of the month.
@param day the day of the month (1 to 31*)
*/
void setDay(int day);
/**
Returns a string for this date in the format "y-MM-dd".
@return obvious
*/
VString getDateString() const;
/**
Returns a string for this date in the specified format.
@param formatter the formatter to use
@return obvious
*/
VString getDateString(const VInstantFormatter& formatter) const;
/**
Returns an object holding the broken-down fields that this date represents.
This is primarily for use by VInstantFormatter when formatting a string.
@return the y/m/d values for this date, with other fields default constructed from VTimeOfDay()
*/
VInstantStruct getDateFields() const;
// Values returned by getDayOfWeek().
enum {
kSunday = 0,
kMonday,
kTuesday,
kWednesday,
kThursday,
kFriday,
kSaturday
};
friend inline bool operator==(const VDate& lhs, const VDate& rhs); ///< Compares two dates.
friend inline bool operator!=(const VDate& lhs, const VDate& rhs); ///< Compares two dates.
friend inline bool operator< (const VDate& lhs, const VDate& rhs); ///< Compares two dates.
friend inline bool operator<=(const VDate& lhs, const VDate& rhs); ///< Compares two dates.
friend inline bool operator>=(const VDate& lhs, const VDate& rhs); ///< Compares two dates.
friend inline bool operator> (const VDate& lhs, const VDate& rhs); ///< Compares two dates.
private:
/** Asserts if any invariant is broken. */
void _assertInvariant() const;
int mYear; ///< The year.
int mMonth; ///< The month (1 to 12).
int mDay; ///< The day of the month (1 to 31*).
};
inline bool operator==(const VDate& lhs, const VDate& rhs) { return (lhs.mYear == rhs.mYear) && (lhs.mMonth == rhs.mMonth) && (lhs.mDay == rhs.mDay); }
inline bool operator!=(const VDate& lhs, const VDate& rhs) { return !operator==(lhs, rhs); }
inline bool operator< (const VDate& lhs, const VDate& rhs) {
if (lhs.mYear < rhs.mYear) return true;
if (lhs.mYear > rhs.mYear) return false;
if (lhs.mMonth < rhs.mMonth) return true;
if (lhs.mMonth > rhs.mMonth) return false;
return (lhs.mDay < rhs.mDay);
}
inline bool operator<=(const VDate& lhs, const VDate& rhs) { return !operator>(lhs, rhs); }
inline bool operator>=(const VDate& lhs, const VDate& rhs) { return !operator<(lhs, rhs); }
inline bool operator> (const VDate& lhs, const VDate& rhs) { return operator<(rhs, lhs); }
/**
VTimeOfDay represents a time of day without understanding about
calendars or time zones; it is simply an hour/minute/second container.
*/
class VTimeOfDay {
public:
/**
Constructs a time of day with all values set to zero, which is valid
and means midnight (start of a day).
*/
VTimeOfDay();
/**
Constructs a time of day from the current instant.
Throws an exception if you
specify RTZ conversion and there is no converter installed.
@param timeZoneID specifies which time zone the h/m/s should be given in
*/
VTimeOfDay(const VString& timeZoneID);
/**
Constructs a time of day from specified values.
@param hour the hour of day (0 to 23)
@param minute the minute of the hour (0 to 59)
@param second the second of the minute (0 to 59)
@param millisecond the millisecond of the second (0 to 999)
*/
VTimeOfDay(int hour, int minute, int second, int millisecond);
/**
Destructor.
*/
virtual ~VTimeOfDay() {}
/**
Returns the hour of day.
@return the hour (0 to 23)
*/
int getHour() const;
/**
Returns the minute of the hour.
@return the minute (0 to 59)
*/
int getMinute() const;
/**
Returns the second of the minute.
@return the second (0 to 59)
*/
int getSecond() const;
/**
Returns the millisecond of the second.
@return the second (0 to 999)
*/
int getMillisecond() const;
/**
Sets the time of day from specified values.
@param hour the hour of day (0 to 23)
@param minute the minute of the hour (0 to 59)
@param second the second of the minute (1 to 59)
@param millisecond the millisecond of the second (0 to 999)
*/
void set(int hour, int minute, int second, int millisecond);
/**
Sets the hour of the day.
@param hour the hour of day (0 to 23)
*/
void setHour(int hour);
/**
Sets the minute of the hour.
@param minute the minute of the hour (0 to 59)
*/
void setMinute(int minute);
/**
Sets the second of the minute.
@param second the second of the minute (1 to 59)
*/
void setSecond(int second);
/**
Sets the millisecond of the second.
@param millisecond the millisecond of the second (0 to 999)
*/
void setMillisecond(int millisecond);
/**
Sets the hour, minute, second, and millisecond to zero.
*/
void setToStartOfDay();
/**
Returns a string for this time of day in the format "HH:mm:ss.SSS".
@return obvious
*/
VString getTimeOfDayString() const;
/**
Returns a string for this time of day in the specified format.
@param formatter the formatter to use
@return obvious
*/
VString getTimeOfDayString(const VInstantFormatter& formatter) const;
/**
Returns an object holding the broken-down fields that this time of day represents.
This is primarily for use by VInstantFormatter when formatting a string.
@return the h/m/s/ms values for this time of day, with other fields defaulted from VDate()
*/
VInstantStruct getTimeOfDayFields() const;
friend inline bool operator==(const VTimeOfDay& t1, const VTimeOfDay& t2);
private:
/** Asserts if any invariant is broken. */
void _assertInvariant() const;
int mHour; ///< The hour of day (0 to 23).
int mMinute; ///< The minute of the hour (0 to 59).
int mSecond; ///< The second of the minute (0 to 59).
int mMillisecond; ///< The millisecond of the second (0 to 999).
};
inline bool operator==(const VTimeOfDay& t1, const VTimeOfDay& t2) { return (t1.mHour == t2.mHour) && (t1.mMinute == t2.mMinute) && (t1.mSecond == t2.mSecond) && (t1.mMillisecond == t2.mMillisecond); }
/**
VDateAndTime simply aggregates a VDate and a VTimeOfDay into one convenient object.
*/
class VDateAndTime {
public:
VDateAndTime() : mDate(), mTimeOfDay() {}
VDateAndTime(const VString& timeZoneID);
VDateAndTime(int inYear, int inMonth, int inDay, int inHour, int inMinute, int inSecond, int inMillisecond) :
mDate(inYear, inMonth, inDay), mTimeOfDay(inHour, inMinute, inSecond, inMillisecond) {}
~VDateAndTime() {}
// Use these accessors to call the date and time of day sub-objects directly.
const VDate& getDate() const { return mDate; }
const VTimeOfDay& getTimeOfDay() const { return mTimeOfDay; }
int getYear() const { return mDate.getYear(); }
int getMonth() const { return mDate.getMonth(); }
int getDay() const { return mDate.getDay(); }
int getDayOfWeek() const { return mDate.getDayOfWeek(); }
int getHour() const { return mTimeOfDay.getHour(); }
int getMinute() const { return mTimeOfDay.getMinute(); }
int getSecond() const { return mTimeOfDay.getSecond(); }
int getMillisecond() const { return mTimeOfDay.getMillisecond(); }
void set(int inYear, int inMonth, int inDay, int inHour, int inMinute, int inSecond, int inMillisecond) {
mDate.set(inYear, inMonth, inDay); mTimeOfDay.set(inHour, inMinute, inSecond, inMillisecond);
}
void setYear(int year) { mDate.setYear(year); }
void setMonth(int month) { mDate.setMonth(month); }
void setDay(int day) { mDate.setDay(day); }
void setHour(int hour) { mTimeOfDay.setHour(hour); }
void setMinute(int minute) { mTimeOfDay.setMinute(minute); }
void setSecond(int second) { mTimeOfDay.setSecond(second); }
void setMillisecond(int millisecond) { mTimeOfDay.setMillisecond(millisecond); }
void setToStartOfDay() { mTimeOfDay.setToStartOfDay(); }
friend inline bool operator==(const VDateAndTime& dt1, const VDateAndTime& dt2);
private:
VDate mDate;
VTimeOfDay mTimeOfDay;
};
inline bool operator==(const VDateAndTime& dt1, const VDateAndTime& dt2) { return (dt1.mDate == dt2.mDate) && (dt1.mTimeOfDay == dt2.mTimeOfDay); }
// VInstantFormatterLocaleInfo -----------------------------------------------
/**
This class holds a set of locale-specific text and other information used when
formatting VInstant time stamp strings. The purpose is to decouple the text and
rules specific to a locale from the formatting directive logic of VInstantFormatter
itself. You can supply one of these when constructing a VInstantFormatter to
control the format. Currently I have the default constructor creating US English
strings and that's all, but you can build one for another locale and use it when
appropriate.
*/
class VInstantFormatterLocaleInfo {
public:
/**
Returns a reference to a global locale info object for a specific locale.
Currently I do not actually track and return objects for different locales,
so this is a future-proofing API. It always returns the US English info.
@param localeName the local name string (e.g. "en-us")
@return the info for the specified locale, to use when formatting
*/
static const VInstantFormatterLocaleInfo& getLocaleInfo(const VString& localeName);
/**
Constructs an empty locale info that you can modify.
(In reality, the default constructor currently fills in "en-us" locale info.)
*/
VInstantFormatterLocaleInfo();
~VInstantFormatterLocaleInfo() {}
// The instance variables are public since they are just data, which you can
// build if you are setting up your own locale object.
VString CE_MARKER; ///< The marker for the common era name, e.g. "CE" or "AD"
VString AM_MARKER; ///< The marker for times before noon, e.g. "AM"
VString PM_MARKER; ///< The marker for time after noon, e.g. "PM"
VStringVector MONTH_NAMES_SHORT; ///< Short-form abbreviated month names, e.g. [0] = "Jan" ... [11] = "Dec"
VStringVector MONTH_NAMES_LONG; ///< Long-form full month names, e.g. [0] = "January" ... [11] = "December"
VStringVector DAY_NAMES_SHORT; ///< Short-form abbreviated day-of-week names, e.g. [0] = "Sun" ... [6] = "Sat"
VStringVector DAY_NAMES_LONG; ///< Long-form full day-of-week names, e.g. [0] = "Sunday" ... [6] = "Saturday"
};
// VInstantFormatter ---------------------------------------------------------
/**
This class describes how a VInstant should be formatted as a string.
You construct it with a format specifier string, whose contents lay out the
fields that you want in the string, and their form.
The format specifier implements as closely as possible the same directives as
the Java SimpleDateFormat documentation describes:
<http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html>
You can also supply a locale info object to indicate the language of non-numeric
parts of the string. In the future this may also include some aspects of formatting
that differ per locale rather than per format specifier.
Because there is nothing mutable in this class, and because there is no transient
internal state in the object, the format() method can be called freely by multiple
threads at the same time.
*/
class VInstantFormatter {
public:
/**
Constructs a formatter for the default locale with a default format specifier.
*/
VInstantFormatter();
/**
Constructs a formatter for a specified locale with a default format specifier.
@param localeInfo the locale to use
*/
VInstantFormatter(const VInstantFormatterLocaleInfo& localeInfo);
/**
Constructs a formatter for the default locale with a specified format specifier.
@param formatSpecifier the format to apply
*/
VInstantFormatter(const VString& formatSpecifier);
/**
Constructs a formatter for a specified locale and format specifier.
@param formatSpecifier the format to apply
@param localeInfo the locale to use
*/
VInstantFormatter(const VString& formatSpecifier, const VInstantFormatterLocaleInfo& localeInfo);
~VInstantFormatter() {}
/**
Builds and returns a local time zone time stamp string for the specified instant,
according to the locale and format specifier supplied to the constructor
of this formatter. Assuming that the local time zone is non-UTC, if the format
specifier includes time zone, it will be non-zero such as "-07:00" depending on
the particular specifier.
*/
VString formatLocalString(const VInstant& when) const;
/**
Builds and returns a UTC time zone time stamp string for the specified instant,
according to the locale and format specifier supplied to the constructor
of this formatter. If the format specifier includes the time zone, it will
indicate UTC in a form such as "Z" or "+0:00" depending on the particular specifier.
*/
VString formatUTCString(const VInstant& when) const;
/**
Builds and returns a date string for the specified date, according to the locale
and format specifier supplied to the constructor of this formatter. It is important
to use the correct formatter: don't simply re-use one that has field specifiers for time
components within a day, because it would cause values to be included for those components.
*/
VString formatDateString(const VDate& date) const;
/**
Builds and returns a time string for the specified time of day, according to the locale
and format specifier supplied to the constructor of this formatter. It is important
to use the correct formatter: don't simply re-use one that has field specifiers for date
components, because it would cause values to be included for those components.
*/
VString formatTimeOfDayString(const VTimeOfDay& timeOfDay) const;
// Getter, for debugging use.
VString getFormatSpecifier() const { return mFormatSpecifier; }
private:
/**
This is what we call internally to format the instant after converting it to
a broken-down set of information. If it's a UTC time, the offset is zero;
otherwise it's the offset in milliseconds.
*/
VString _format(const VInstantStruct& when, int utcOffsetMilliseconds) const;
void _flushPendingFieldSpecifier(const VInstantStruct& when, int utcOffsetMilliseconds, VString& fieldSpecifier/*will be set to empty on return*/, VString& resultToAppendTo) const;
void _flushFixedLengthTextValue(const VString& value, VString& resultToAppendTo) const;
void _flushVariableLengthTextValue(const VString& shortValue, const VString& longValue, int fieldLength, VString& resultToAppendTo) const;
void _flushNumberValue(int value, int fieldLength, VString& resultToAppendTo) const;
void _flushYearValue(int year, int fieldLength, VString& resultToAppendTo) const;
void _flushMonthValue(int month, int fieldLength, VString& resultToAppendTo) const;
void _flushDayNameValue(int dayOfWeek/*0=sun ... 6=sat*/, int fieldLength, VString& resultToAppendTo) const;
void _flushDayNumberValue(int dayOfWeek/*0=sun ... 6=sat*/, int fieldLength, VString& resultToAppendTo) const;
void _flushTimeZoneValue(int utcOffsetMilliseconds, const VString& fieldSpecifier, VString& resultToAppendTo) const;
VString mFormatSpecifier;
// Pseudo-constants: Potentially localized values, not static, because we allow setting per VInstantFormatter.
const VInstantFormatterLocaleInfo& mLocaleInfo;
};
#endif /* vinstant_h */
| Java |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Terra.WebUI.Models.AccountViewModels
{
public class LoginViewModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
}
| Java |
version https://git-lfs.github.com/spec/v1
oid sha256:a396601eca15b0c281513d01941cfd37300b927b32a1bb9bb6e708a9910f1b49
size 2712
| Java |
package com.ruenzuo.weatherapp.adapters;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.ruenzuo.weatherapp.R;
import com.ruenzuo.weatherapp.models.City;
/**
* Created by ruenzuo on 08/05/14.
*/
public class CitiesAdapter extends ArrayAdapter<City> {
private int resourceId;
public CitiesAdapter(Context context, int resource) {
super(context, resource);
resourceId = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = ((Activity)getContext()).getLayoutInflater();
convertView = inflater.inflate(resourceId, null);
}
City country = getItem(position);
TextView txtViewCityName = (TextView) convertView.findViewById(R.id.txtViewCityName);
txtViewCityName.setText(country.getName());
return convertView;
}
} | Java |
module SelecaoAdmin
class Engine < ::Rails::Engine
isolate_namespace SelecaoAdmin
end
end
| Java |
<?php
include __DIR__.'/../lib/SALT.php';
/** An example of using the SALT Secure Storage API to store then use a stored Credit Card */
use \SALT\Merchant;
use \SALT\HttpsCreditCardService;
use \SALT\CreditCard;
use \SALT\PaymentProfile;
// connection parameters to the gateway
$url = 'https://test.salt.com/gateway/creditcard/processor.do';
//$merchant = new Merchant ('Your Merchant ID', 'Your API Token');
$merchant = new Merchant ( VALID_MERCHANT_ID, VALID_API_TOKEN );
$service = new HttpsCreditCardService( $merchant, $url );
// credit card info from customer - to be stored
$creditCard = new CreditCard( '4242424242424242', '1010', null, '123 Street', 'A1B23C' );
// payment profile to be stored (just using the card component in this example)
$paymentProfile = new PaymentProfile( $creditCard, null );
// store data under the token 'my-token-001'
//$storageToken = 'my-token-'.date('Ymd');
$storageToken = uniqid();
$storageReceipt = $service->addToStorage( $storageToken, $paymentProfile );
if ( $storageReceipt->approved ) {
echo "Credit card storage approved.\n";
$purchaseOrderId = uniqid();
echo "Creating Single purchase with Order ID $purchaseOrderId\n";
$singlePurchaseReceipt = $service->singlePurchase( $purchaseOrderId, $storageToken, '100', null );
// optional array dump of response params
// print_r($receipt->params);
if ( $singlePurchaseReceipt->approved ) {
//Store the transaction id.
echo "Single Purchase Receipt approved\n";
} else {
echo "Single purchase receipt not approved\n";
}
} else {
echo "Credit card storage not approved.\n";
}
//Update the credit card stored
$updatedCreditCard = new CreditCard ( '4012888888881881', '1010', null, '1 Market St.', '94105' );
$paymentProfile->creditCard = $updatedCreditCard;
$updatedStorageReceipt = $service->updateStorage($storageToken, $paymentProfile);
if ( $updatedStorageReceipt->approved ) {
echo "Updated credit card storage approved.\n";
} else {
echo "Updated credit card storage not approved.\n";
}
//Query the credit card stored
$queryStorageReceipt = $service->queryStorage($storageToken);
if ( $queryStorageReceipt->approved ) {
echo "Secure storage query successful.\n";
echo "Response: \n";
print_r($queryStorageReceipt->params);
} else {
echo "Secure storage query failed.\n";
}
| Java |
package tehnut.resourceful.crops.compat;
import mcp.mobius.waila.api.*;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.items.ItemHandlerHelper;
import tehnut.resourceful.crops.block.tile.TileSeedContainer;
import tehnut.resourceful.crops.core.RegistrarResourcefulCrops;
import tehnut.resourceful.crops.core.data.Seed;
import javax.annotation.Nonnull;
import java.util.List;
@WailaPlugin
public class CompatibilityWaila implements IWailaPlugin {
@Override
public void register(IWailaRegistrar registrar) {
final CropProvider cropProvider = new CropProvider();
registrar.registerStackProvider(cropProvider, TileSeedContainer.class);
registrar.registerNBTProvider(cropProvider, TileSeedContainer.class);
}
public static class CropProvider implements IWailaDataProvider {
@Nonnull
@Override
public ItemStack getWailaStack(IWailaDataAccessor accessor, IWailaConfigHandler config) {
Seed seed = RegistrarResourcefulCrops.SEEDS.getValue(new ResourceLocation(accessor.getNBTData().getString("seed")));
if (seed == null)
return accessor.getStack();
if (seed.isNull())
return accessor.getStack();
if (seed.getOutputs().length == 0)
return accessor.getStack();
return ItemHandlerHelper.copyStackWithSize(seed.getOutputs()[0].getItem(), 1);
}
@Nonnull
@Override
public List<String> getWailaHead(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
return currenttip;
}
@Nonnull
@Override
public List<String> getWailaBody(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
return currenttip;
}
@Nonnull
@Override
public List<String> getWailaTail(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
return currenttip;
}
@Nonnull
@Override
public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, BlockPos pos) {
tag.setString("seed", ((TileSeedContainer) te).getSeedKey().toString());
return tag;
}
}
}
| Java |
<?php
/*
* This file is part of the WeatherUndergroundBundle.
*
* (c) Nikolay Ivlev <nikolay.kotovsky@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SunCat\WeatherUndergroundBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* DI extension
*
* @author suncat2000 <nikolay.kotovsky@gmail.com>
*/
class WeatherUndergroundExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
$container->setParameter('weather_underground.apikey', $config['apikey']);
$container->setParameter('weather_underground.format', $config['format']);
$container->setParameter('weather_underground.host_data_features', $config['host_data_features']);
$container->setParameter('weather_underground.host_autocomlete', $config['host_autocomlete']);
}
}
| Java |
import _ from 'lodash';
/**
* Represents a channel with which commands can be invoked.
*
* Channels are one-per-origin (protocol/domain/port).
*/
class Channel {
constructor(config, $rootScope, $timeout, contentWindow) {
this.config = config;
this.$rootScope = $rootScope;
this.$timeout = $timeout;
this._contentWindow = contentWindow;
this.messageCounter = 0;
}
ab2str(buffer) {
let result = "";
let bytes = new Uint8Array(buffer);
let len = bytes.byteLength;
for (let i = 0; i < len; i++) {
result += String.fromCharCode(bytes[i]);
}
return result;
};
/**
* Fire and forget pattern that sends the command to the target without waiting for a response.
*/
invokeDirect(command, data, targetOrigin, transferrablePropertyPath) {
if (!data) {
data = {};
}
if (!targetOrigin) {
targetOrigin = this.config.siteUrl;
}
if (!targetOrigin) {
targetOrigin = "*";
}
data.command = command;
data.postMessageId = `SP.RequestExecutor_${this.messageCounter++}`;
let transferrableProperty = undefined;
if (transferrablePropertyPath) {
transferrableProperty = _.get(data, transferrablePropertyPath);
}
if (transferrableProperty)
this._contentWindow.postMessage(data, targetOrigin, [transferrableProperty]);
else
this._contentWindow.postMessage(data, targetOrigin);
}
/**
* Invokes the specified command on the channel with the specified data, constrained to the specified domain awaiting for max ms specified in timeout
*/
async invoke(command, data, targetOrigin, timeout, transferrablePropertyPath) {
if (!data) {
data = {};
}
if (!targetOrigin) {
targetOrigin = this.config.siteUrl;
}
if (!targetOrigin) {
targetOrigin = "*";
}
if (!timeout) {
timeout = 0;
}
data.command = command;
data.postMessageId = `SP.RequestExecutor_${this.messageCounter++}`;
let resolve, reject;
let promise = new Promise((innerResolve, innerReject) => {
resolve = innerResolve;
reject = innerReject;
});
let timeoutPromise;
if (timeout > 0) {
timeoutPromise = this.$timeout(() => {
reject(new Error(`invoke() timed out while waiting for a response while executing ${data.command}`));
}, timeout);
}
let removeMonitor = this.$rootScope.$on(this.config.crossDomainMessageSink.incomingMessageName, (event, response) => {
if (response.postMessageId !== data.postMessageId)
return;
if (response.result === "error") {
reject(response);
}
else {
if (response.data) {
let contentType = response.headers["content-type"] || response.headers["Content-Type"];
if (contentType.startsWith("application/json")) {
let str = this.ab2str(response.data);
if (str.length > 0) {
try
{
response.data = JSON.parse(str);
}
catch(ex) {
}
}
} else if (contentType.startsWith("text")) {
response.data = this.ab2str(response.data);
}
}
resolve(response);
}
removeMonitor();
if (timeoutPromise)
this.$timeout.cancel(timeoutPromise);
});
let transferrableProperty = undefined;
if (transferrablePropertyPath) {
transferrableProperty = _.get(data, transferrablePropertyPath);
}
if (transferrableProperty)
this._contentWindow.postMessage(data, targetOrigin, [transferrableProperty]);
else
this._contentWindow.postMessage(data, targetOrigin);
return promise;
}
}
module.exports = Channel; | Java |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
include __DIR__.'/../../../application/config/config.php';
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| If this is not set then CodeIgniter will guess the protocol, domain and
| path to your installation.
|
*/
$config['base_url'] = $config['gi_base_url'].'/api/';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'AUTO' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'AUTO' Default - auto detects
| 'PATH_INFO' Uses the PATH_INFO
| 'QUERY_STRING' Uses the QUERY_STRING
| 'REQUEST_URI' Uses the REQUEST_URI
| 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO
|
*/
$config['uri_protocol'] = 'AUTO';
if( defined('__CLI_MODE') && __CLI_MODE === TRUE ) {
$config['uri_protocol'] = 'AUTO';
}
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/core_classes.html
| http://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'GI_';
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify with a regular expression which characters are permitted
| within your URLs. When someone tries to submit a URL with disallowed
| characters they will get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd'; // experimental not currently in use
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| If you have enabled error logging, you can set an error threshold to
| determine what gets logged. Threshold options are:
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ folder. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| system/cache/ folder. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class or the Session class you
| MUST set an encryption key. See the user guide for info.
|
*/
$config['encryption_key'] = 'dfsa09302qdflaskf0-2iq';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_cookie_name' = the name you want for the cookie
| 'sess_expiration' = the number of SECONDS you want the session to last.
| by default sessions last 7200 seconds (two hours). Set to zero for no expiration.
| 'sess_expire_on_close' = Whether to cause the session to expire automatically
| when the browser window is closed
| 'sess_encrypt_cookie' = Whether to encrypt the cookie
| 'sess_use_database' = Whether to save the session data to a database
| 'sess_table_name' = The name of the session database table
| 'sess_match_ip' = Whether to match the user's IP address when reading the session data
| 'sess_match_useragent' = Whether to match the User Agent when reading the session data
| 'sess_time_to_update' = how many seconds between CI refreshing Session Information
|
*/
$config['sess_cookie_name'] = 'gi_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = FALSE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookies will only be set if a secure HTTPS connection exists.
|
*/
$config['cookie_prefix'] = "";
$config['cookie_domain'] = "";
$config['cookie_path'] = "/";
$config['cookie_secure'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
*/
$config['global_xss_filtering'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or 'gmt'. This pref tells the system whether to use
| your server's local time as the master 'now' reference, or convert it to
| GMT. See the 'date helper' page of the user guide for information
| regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
*/
$config['rewrite_short_tags'] = FALSE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy IP
| addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR
| header in order to properly identify the visitor's IP address.
| Comma-delimited, e.g. '10.0.1.200,10.0.1.201'
|
*/
$config['proxy_ips'] = '';
/* End of file config.php */
/* Location: ./application/config/config.php */
| Java |
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
inject,
async,
TestBed,
ComponentFixture
} from '@angular/core/testing';
// Load the implementations that should be tested
import { AppComponent } from './app.component';
import { AppState } from './app.service';
describe(`App`, () => {
});
| Java |
export function getName(value) {
if (value == 0) {
return "上班";
}
if (value == 1) {
return "下班";
}
throw "invalid route direction";
}
export function getValue(name) {
if (name == "上班") {
return 0;
}
if (name == "下班") {
return 1;
}
throw "invalid route direction";
} | Java |
# reactjs-program
A collection of ReactJS examples.
### Requirements
1) NodeJS & npm
2) python (optional, used for serving up HTTP)
### Getting Started
You can view the examples through any HTTP server. The following assumes use of [Python's SimpleHTTPServer] (https://docs.python.org/2/library/simplehttpserver.html#module-SimpleHTTPServer)
1) Clone repo and cd into it.
2) Install dependencies: `npm install`
2) Start HTTP server: `python -m SimpleHTTPServer 8000`. You may need to install Python if not already installed.
3) Navigate to desired example, e.g., http://localhost:8000/todo/
### Create An Example
At the moment I'm enjoying using [browserify](http://browserify.org/) to organize and bundle dependencies within the browser. To get start, try the following:
1) `mkdir my_new_app && cd my_new_app`
2) `touch index.html && mkdir src && mkdir build`
2) `npm init`
3) `npm install --save react react-dom`
4) `npm install --save-dev babelify babel-preset-react`
5) `npm install -g browserify`
6) Bundle all dependencies: `browserify -t [ babelify --presets [ react ] ] src/main.js -o build/app.js` (assumes your final render takes place in `src/main.js`)
7) Include the following script tag in your index.html: `<script src="build/app.js"></script>`
8) Fire up your example on http://localhost:8000/my_new_app
| Java |
#ifndef VIEWER_H
#define VIEWER_H
#include "common.h"
#include "drawable.h"
#include "controller.h"
class Viewer
{
public:
bool glfw_is_up;
GLFWwindow* window;
GLuint VertexArrayID;
int width;
int height;
Controller controls;
std::vector<Drawable *> drawables;
Viewer();
void add( Drawable *d)
{
drawables.push_back( d);
}
void fatal( std::string msg)
{
fprintf( stderr, "%s\n", msg.c_str());
getchar();
throw Exc(msg);
}
// Various inits
void init();
int init_window();
int init_glew();
int init_vao();
void run();
virtual ~Viewer();
};
#endif
| Java |
// config/database.js
module.exports = {
'secret': 'puneetvashisht',
'url' : 'mongodb://localhost/userdb' // looks like mongodb://<user>:<pass>@mongo.onmodulus.net:27017/Mikha4ot
};
| Java |
import {
LOAD_SEARCH_RESULT_SUCCESS,
CLEAR_SEARCH_RESULTS,
} from 'actions/search';
import { createActionHandlers } from 'utils/reducer/actions-handlers';
const actionHandlers = {};
export function loadSearchResultSuccess(state, searchResultsList) {
return searchResultsList.reduce((acc, result) => {
return {
...acc,
[result.id]: result,
};
}, {});
}
export function clearSearchResult() {
return {};
}
actionHandlers[LOAD_SEARCH_RESULT_SUCCESS] = loadSearchResultSuccess;
actionHandlers[CLEAR_SEARCH_RESULTS] = clearSearchResult;
export default createActionHandlers(actionHandlers);
| Java |
/**
specified=*(N): you have had a specifier added to you (internal). 0 = no, new ones have to score higher than old
specifier=[_]: you are capable of being used in situation where we need to know what to do with you (external).
bare noun: has no specifier added, but if it *were* to be used as an NP then the value of specifier would be *mass
plural noun: has no specifier added, but if it *were* to be used as an NP then the value of specifier would be *count
det+NP: we record values for both specified (a number) and specifier (a property).
**/
specifier(X, SPEC) :-
specifier@X -- SPEC.
specified(X) :-
X <> [specifier(*(_))].
unspecified(X) :-
-specifier@X.
casemarked(X, case@X).
subjcase(X) :-
case@X -- *subj.
objcase(X) :-
case@X -- *obj.
standardcase(X, CASE) :-
case@X -- *CASE.
standardcase(X) :-
X <> [standardcase(_)].
sing(X) :-
number@X -- sing.
plural(X) :-
number@X -- plural.
first(X) :-
person@X -- 1.
firstSing(X) :-
X <> [sing, first].
second(X) :-
person@X -- 2.
third(X) :-
person@X -- 3.
thirdSing(X) :-
X <> [sing, third].
thirdPlural(X) :-
X <> [plural, third].
notThirdSing(X) :-
when((nonvar(person@X), nonvar(number@X)),
\+ thirdSing(X)).
masculine(X) :-
gender@X -- masculine.
feminine(X) :-
gender@X -- feminine. | Java |
import { autoinject } from 'aurelia-framework';
import { Customers } from './customers';
import { Router } from 'aurelia-router';
@autoinject()
export class List {
heading = 'Customer management';
customerList = [];
customers: Customers;
router: Router;
constructor(customers: Customers, router: Router) {
this.customers = customers;
this.router = router;
}
gotoCustomer(customer: any) {
this.router.navigateToRoute('edit', {id: customer.id});
}
new() {
this.router.navigateToRoute('create');
}
activate() {
return this.customers.getAll()
.then(customerList => this.customerList = customerList);
}
}
| Java |
# Chokidar CLI
[](https://travis-ci.org/kimmobrunfeldt/chokidar-cli)
Fast cross-platform command line utility to watch file system changes.
The underlying watch library is [Chokidar](https://github.com/paulmillr/chokidar), which is one of the best watch utilities for Node. Chokidar is battle-tested:
> It is used in
> [brunch](http://brunch.io),
> [gulp](https://github.com/gulpjs/gulp/),
> [karma](http://karma-runner.github.io),
> [PM2](https://github.com/Unitech/PM2),
> [browserify](http://browserify.org/),
> [webpack](http://webpack.github.io/),
> [BrowserSync](http://www.browsersync.io/),
> [socketstream](http://www.socketstream.org),
> [derby](http://derbyjs.com/),
> and [many others](https://www.npmjs.org/browse/depended/chokidar/).
> It has proven itself in production environments.
## Install
If you need it only with NPM scripts:
```bash
npm install chokidar-cli
```
Or globally
```bash
npm install -g chokidar-cli
```
## Usage
By default `chokidar` streams changes for all patterns to stdout:
```bash
$ chokidar '**/.js' '**/*.less'
change:test/dir/a.js
change:test/dir/a.less
add:test/b.js
unlink:test/b.js
```
Each change is represented with format `event:relativepath`. Possible events: `add`, `unlink`, `addDir`, `unlinkDir`, `change`.
**Output only relative paths on each change**
```bash
$ chokidar '**/.js' '**/*.less' | cut -d ':' -f 2-
test/dir/a.js
test/dir/a.less
test/b.js
test/b.js
```
**Run *npm run build-js* whenever any .js file changes in the current work directory tree**
```chokidar '**/*.js' -c 'npm run build-js'```
**Watching in network directories must use polling**
```chokidar '**/*.less' -c 'npm run build-less' --polling```
**Pass the path and event details in to your custom command
```chokidar '**/*.less' -c 'if [ "{event}" = "change" ]; then npm run build-less -- {path}; fi;'```
**Detailed help**
```
Usage: chokidar <pattern> [<pattern>...] [options]
<pattern>:
Glob pattern to specify files to be watched.
Multiple patterns can be watched by separating patterns with spaces.
To prevent shell globbing, write pattern inside quotes.
Guide to globs: https://github.com/isaacs/node-glob#glob-primer
Options:
-c, --command Command to run after each change. Needs to be
surrounded with quotes when command contains spaces.
Instances of `{path}` or `{event}` within the command
will be replaced by the corresponding values from the
chokidar event.
-d, --debounce Debounce timeout in ms for executing command
[default: 400]
-t, --throttle Throttle timeout in ms for executing command
[default: 0]
-s, --follow-symlinks When not set, only the symlinks themselves will be
watched for changes instead of following the link
references and bubbling events through the links path
[boolean] [default: false]
-i, --ignore Pattern for files which should be ignored. Needs to be
surrounded with quotes to prevent shell globbing. The
whole relative or absolute path is tested, not just
filename. Supports glob patters or regexes using
format: /yourmatch/i
--initial When set, command is initially run once
[boolean] [default: false]
-p, --polling Whether to use fs.watchFile(backed by polling) instead
of fs.watch. This might lead to high CPU utilization.
It is typically necessary to set this to true to
successfully watch files over a network, and it may be
necessary to successfully watch files in other non-
standard situations [boolean] [default: false]
--poll-interval Interval of file system polling. Effective when --
polling is set [default: 100]
--poll-interval-binary Interval of file system polling for binary files.
Effective when --polling is set [default: 300]
--verbose When set, output is more verbose and human readable.
[boolean] [default: false]
--silent When set, internal messages of chokidar-cli won't be
written. [boolean] [default: false]
-h, --help Show help [boolean]
-v, --version Show version number [boolean]
Examples:
chokidar "**/*.js" -c "npm run build-js" build when any .js file changes
chokidar "**/*.js" "**/*.less" output changes of .js and .less
files
```
## License
MIT
| Java |
The MIT License (MIT)
Copyright (c) 2014 Christophe Van Neste
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. | Java |
/**
* Created by huangxinghui on 2016/1/20.
*/
var $ = require('jquery')
var Widget = require('../../widget')
var plugin = require('../../plugin')
var TreeNode = require('./treenode')
var Tree = Widget.extend({
options: {
'labelField': null,
'labelFunction': null,
'childrenField': 'children',
'autoOpen': true
},
events: {
'click li': '_onSelect',
'click i': '_onExpand'
},
_create: function() {
this.$element.addClass('tree')
var that = this
var $ul = $('<ul></ul>')
this._loadFromDataSource()
this.nodes.forEach(function(node) {
that._createNode(node)
$ul.append(node.element)
})
this.$element.append($ul)
},
_onSelect: function(e) {
var $li = $(e.currentTarget),
node = $li.data('node')
e.preventDefault()
if (!$li.hasClass('active')) {
this._setSelectedNode(node)
this._trigger('itemClick', node.data)
}
},
_onExpand: function(e) {
var $li = $(e.currentTarget).closest('li'),
node = $li.data('node')
e.preventDefault()
if (node.isOpen) {
this.collapseNode(node)
}
else {
this.expandNode(node)
}
},
_setSelectedNode: function(node) {
var $active = this.$element.find('.active')
$active.removeClass('active')
var $li = node.element
$li.addClass('active')
this._trigger('change', node.data)
},
_createNode: function(node) {
if (node.isBranch()) {
this._createFolder(node)
}
else {
this._createLeaf(node)
}
},
_createLeaf: function(node) {
var html = ['<li><a href="#"><span>']
html.push(this._createIndentationHtml(node.getLevel()))
html.push(this.itemToLabel(node.data))
html.push('</span></a></li>')
var $li = $(html.join(''))
$li.data('node', node)
node.element = $li
return $li
},
_createFolder: function(node) {
var that = this
var html = []
if (node.isOpen) {
html.push('<li class="open"><a href="#"><span>')
html.push(this._createIndentationHtml(node.getLevel() - 1))
html.push('<i class="glyphicon glyphicon-minus-sign js-folder"></i>')
}
else {
html.push('<li><a href="#"><span>')
html.push(this._createIndentationHtml(node.getLevel() - 1))
html.push('<i class="glyphicon glyphicon-plus-sign js-folder"></i>')
}
html.push(this.itemToLabel(node.data))
html.push('</span></a></li>')
var $li = $(html.join(''))
var $ul = $('<ul class="children-list"></ul>')
node.children.forEach(function(childNode) {
that._createNode(childNode)
$ul.append(childNode.element)
})
$li.append($ul)
$li.data('node', node)
node.element = $li
return $li
},
_createLabel: function(node) {
var html = ['<span>']
var level = node.getLevel()
if (node.isBranch()) {
html.push(this._createIndentationHtml(level - 1))
html.push('<i class="glyphicon ',
node.isOpen ? 'glyphicon-minus-sign' : 'glyphicon-plus-sign',
' js-folder"></i>')
}
else {
html.push(this._createIndentationHtml(level))
}
html.push(this.itemToLabel(node.data))
html.push('</span>')
return html.join('')
},
_createIndentationHtml: function(count) {
var html = []
for (var i = 0; i < count; i++) {
html.push('<i class="glyphicon tree-indentation"></i>')
}
return html.join('')
},
_loadFromDataSource: function() {
var node, children, nodes = [], that = this
if (this.options.dataSource) {
this.options.dataSource.forEach(function(item) {
node = new TreeNode(item)
children = item[that.options.childrenField]
if (children) {
node.isOpen = that.options.autoOpen
that._loadFromArray(children, node)
}
nodes.push(node)
})
}
this.nodes = nodes
},
_loadFromArray: function(array, parentNode) {
var node, children, that = this
array.forEach(function(item) {
node = new TreeNode(item)
parentNode.addChild(node)
children = item[that.childrenField]
if (children) {
node.isOpen = that.autoOpen
that._loadFromArray(children, node)
}
})
},
expandNode: function(node) {
if (!node.isBranch()) {
return
}
var $li = node.element
var $disclosureIcon = $li.children('a').find('.js-folder')
if (!node.isOpen) {
node.isOpen = true
$li.addClass('open')
$disclosureIcon.removeClass('glyphicon-plus-sign').addClass('glyphicon-minus-sign')
this._trigger('itemOpen')
}
},
collapseNode: function(node) {
if (!node.isBranch()) {
return
}
var $li = node.element
var $disclosureIcon = $li.children('a').find('.js-folder')
if (node.isOpen) {
node.isOpen = false
$li.removeClass('open')
$disclosureIcon.removeClass('glyphicon-minus-sign').addClass('glyphicon-plus-sign')
this._trigger('itemClose')
}
},
expandAll: function() {
var that = this
this.nodes.forEach(function(node) {
that.expandNode(node)
})
},
collapseAll: function() {
var that = this
this.nodes.forEach(function(node) {
that.collapseNode(node)
})
},
append: function(item, parentNode) {
var $ul, $li, $prev, node = new TreeNode(item)
if (parentNode.isBranch()) {
parentNode.addChild(node)
$ul = parentNode.element.children('ul')
this._createNode(node)
$li = node.element
$ul.append($li)
}
else {
parentNode.addChild(node)
$li = parentNode.element
$prev = $li.prev()
$ul = $li.parent()
parentNode.element = null
$li.remove()
$li = this._createFolder(parentNode)
if ($prev.length) {
$prev.after($li)
}
else {
$ul.append($li)
}
}
this.expandNode(parentNode)
this._setSelectedNode(node)
},
remove: function(node) {
var parentNode = node.parent
node.element.remove()
node.destroy()
this._setSelectedNode(parentNode)
},
update: function(node) {
var $li = node.element
$li.children('a').html(this._createLabel(node))
},
getSelectedNode: function() {
var $li = this.$element.find('.active')
return $li.data('node')
},
getSelectedItem: function() {
var node = this.getSelectedNode()
return node.data
},
itemToLabel: function(data) {
if (!data) {
return ''
}
if (this.options.labelFunction != null) {
return this.options.labelFunction(data)
}
else if (this.options.labelField != null) {
return data[this.options.labelField]
}
else {
return data
}
}
})
plugin('tree', Tree)
| Java |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Advent of Code 2015 from http://adventofcode.com/2015/day/5
Author: James Walker
Copyrighted 2017 under the MIT license:
http://www.opensource.org/licenses/mit-license.php
Execution:
python advent_of_code_2015_day_05.py
--- Day 5: Doesn't He Have Intern-Elves For This? ---
Santa needs help figuring out which strings in his text file are naughty or
nice.
A nice string is one with all of the following properties:
It contains at least three vowels (aeiou only), like aei, xazegov, or
aeiouaeiouaeiou.
It contains at least one letter that appears twice in a row, like xx,
abcdde (dd), or aabbccdd (aa, bb, cc, or dd).
It does not contain the strings ab, cd, pq, or xy, even if they are part of
one of the other requirements.
For example:
ugknbfddgicrmopn is nice because it has at least three vowels
(u...i...o...), a double letter (...dd...), and none of the disallowed
substrings.
aaa is nice because it has at least three vowels and a double letter, even
though the letters used by different rules overlap.
jchzalrnumimnmhp is naughty because it has no double letter.
haegwjzuvuyypxyu is naughty because it contains the string xy.
dvszwmarrgswjxmb is naughty because it contains only one vowel.
How many strings are nice?
Answer: 258
--- Day 5: Part Two ---
Realizing the error of his ways, Santa has switched to a better model of
determining whether a string is naughty or nice. None of the old rules apply,
as they are all clearly ridiculous. Now, a nice string is one with all of the
following properties:
It contains a pair of any two letters that appears at least twice in the
string without overlapping, like xyxy (xy) or aabcdefgaa (aa), but not
like aaa (aa, but it overlaps).
It contains at least one letter which repeats with exactly one letter
between them, like xyx, abcdefeghi (efe), or even aaa.
For example:
qjhvhtzxzqqjkmpb is nice because is has a pair that appears twice (qj) and
a letter that repeats with exactly one letter between them (zxz).
xxyxx is nice because it has a pair that appears twice and a letter that
repeats with one between, even though the letters used by each rule
overlap.
uurcxstgmygtbstg is naughty because it has a pair (tg) but no repeat with a
single letter between them.
ieodomkazucvgmuy is naughty because it has a repeating letter with one
between (odo), but no pair that appears twice.
How many strings are nice under these new rules?
Answer: 53
"""
import collections
import os
import re
import sys
TestCase = collections.namedtuple('TestCase', 'input expected1 expected2')
class Advent_Of_Code_2015_Solver_Day05(object):
"""Advent of Code 2015 Day 5: Doesn't He Have Intern-Elves For This?"""
def __init__(self, file_name=None):
self._file_name = file_name
self._puzzle_input = None
self._solved_output = (
"The text file had {0} nice strings using the original rules\n"
"and it had {1} nice strings using the new rules."
)
self.__regex_vowels = re.compile('[aeiou]')
self.__regex_double_char = re.compile('(\w)\\1+')
self.__regex_naughty = re.compile('ab|cd|pq|xy')
self.__regex_double_pair = re.compile('(\w{2})\w*\\1')
self.__regex_triplet = re.compile('(\w)\w\\1')
def _load_puzzle_file(self):
filePath = "{dir}/{f}".format(dir=os.getcwd(), f=self._file_name)
try:
with open(filePath, mode='r') as puzzle_file:
self._puzzle_input = puzzle_file.readlines()
except IOError as err:
errorMsg = (
"ERROR: Failed to read the puzzle input from file '{file}'\n"
"{error}"
)
print(errorMsg.format(file=self._file_name, error=err))
exit(1)
def __is_nice_string_using_old_rules(self, string):
return (self.__regex_naughty.search(string) is None
and len(self.__regex_vowels.findall(string)) > 2
and self.__regex_double_char.search(string))
def __is_nice_string_using_new_rules(self, string):
return (self.__regex_double_pair.search(string)
and self.__regex_triplet.search(string))
def _solve_puzzle_parts(self):
old_nice_count = 0
new_nice_count = 0
for string in self._puzzle_input:
if not string:
continue
if self.__is_nice_string_using_old_rules(string):
old_nice_count += 1
if self.__is_nice_string_using_new_rules(string):
new_nice_count += 1
return (old_nice_count, new_nice_count)
def get_puzzle_solution(self, alt_input=None):
if alt_input is None:
self._load_puzzle_file()
else:
self._puzzle_input = alt_input
old_nice_count, new_nice_count = self._solve_puzzle_parts()
return self._solved_output.format(old_nice_count, new_nice_count)
def _run_test_case(self, test_case):
correct_output = self._solved_output.format(
test_case.expected1,
test_case.expected2
)
test_output = self.get_puzzle_solution(test_case.input)
if correct_output == test_output:
print("Test passed for input '{0}'".format(test_case.input))
else:
print("Test failed for input '{0}'".format(test_case.input))
print(test_output)
def run_test_cases(self):
print("No Puzzle Input for {puzzle}".format(puzzle=self.__doc__))
print("Running Test Cases...")
self._run_test_case(TestCase(['ugknbfddgicrmopn'], 1, 0))
self._run_test_case(TestCase(['aaa'], 1, 0))
self._run_test_case(TestCase(['jchzalrnumimnmhp'], 0, 0))
self._run_test_case(TestCase(['haegwjzuvuyypxyu'], 0, 0))
self._run_test_case(TestCase(['dvszwmarrgswjxmb'], 0, 0))
self._run_test_case(TestCase(['xyxy'], 0, 1))
self._run_test_case(TestCase(['aabcdefgaa'], 0, 0))
self._run_test_case(TestCase(['qjhvhtzxzqqjkmpb'], 0, 1))
self._run_test_case(TestCase(['xxyxx'], 0, 1))
self._run_test_case(TestCase(['uurcxstgmygtbstg'], 0, 0))
self._run_test_case(TestCase(['ieodomkazucvgmuy'], 0, 0))
self._run_test_case(TestCase(['aaccacc'], 1, 1))
if __name__ == '__main__':
try:
day05_solver = Advent_Of_Code_2015_Solver_Day05(sys.argv[1])
print(day05_solver.__doc__)
print(day05_solver.get_puzzle_solution())
except IndexError:
Advent_Of_Code_2015_Solver_Day05().run_test_cases()
| Java |
#!/bin/sh
_now=$(date +"%m_%d_%Y_%H_%M_%S")
PATH=$PATH:/usr/local/bin
export PATH
cd $HOME/Code/newspost/crawlers/crawlers && $HOME/Installs/envs/newspost/bin/scrapy runspider spiders/huffingtonpost.py -o feeds/huffingtonpost-$_now.json
wait
cd $HOME/Code/newspost/crawlers/crawlers && $HOME/Installs/envs/newspost/bin/scrapy runspider spiders/iamwire.py -o feeds/iamwire-$_now.json
wait
cd $HOME/Code/newspost/crawlers/crawlers && $HOME/Installs/envs/newspost/bin/scrapy runspider spiders/vccircle.py -o feeds/vccircle-$_now.json
wait
cd $HOME/Code/newspost/crawlers/crawlers && $HOME/Installs/envs/newspost/bin/scrapy runspider spiders/moneycontrol.py -o feeds/moneycontrol-$_now.json | Java |
# Image Widget
?> GitPitch widgets greatly enhance traditional markdown rendering capabilities for slide decks.
The image widget extends traditional markdown image syntax with support for positioning, sizing, transformations, and filters.
### Widget Paths
All paths to image files specified within [PITCHME.md](/conventions/pitchme-md.md) markdown must be relative to the *root directory* of your local working directory or Git repository.
### Widget Syntax
The following markdown snippet demonstrates image widget syntax:
```markdown

```
?> The `properties...` list expects a comma-separated list of property `key=value` pairs.
### Image Properties
The image widget supports the following image specific properties:
[Image Widget Properties](../_snippets/image-widget-properties.md ':include')
### Grid Native Props
The *Image Widget* is a [grid native widget](/grid-layouts/native-widgets.md) meaning it also directly supports [grid layouts](/grid-layouts/) properties:
[Grid Widget Properties](../_snippets/grid-widget-properties.md ':include')
### Sample Slide
The following slide demonstrates an image rendered using image widget syntax. The markdown snippet used to create this slide takes advantage of numerous *grid native properties* to position, size, and transform the image on the slide:

> This sample slide uses additional grid layouts blocks to set a custom [slide background color](/grid-layouts/backgrounds.md) and to render text alongside the sample image.
For details of the current image size limits policy see the [next guide](/images/size-limits-policy.md).
| Java |
/**
* Test program.
*
* Copyright (c) 2015 Alex Jin (toalexjin@hotmail.com)
*/
#include "test/test.h"
#include <iostream>
namespace {
void help() {
std::cout << "Usage: testalgo -a" << std::endl;
std::cout << " testalgo <test-case-name>" << std::endl;
std::cout << std::endl;
std::cout << "Options:" << std::endl;
std::cout << " -a Run all test cases" << std::endl;
std::cout << std::endl;
std::cout << "Test Case Names:" << std::endl;
const auto names = test_manager_t::instance().get_names();
for (auto it = names.begin(); it != names.end(); ++it) {
std::cout << " " << *it << std::endl;
}
std::cout << std::endl;
}
} // unnamed namespace
int main(int argc, char* argv[]) {
if (argc != 2) {
help();
exit(1);
}
bool result = false;
std::string arg1 = argv[1];
if (arg1 == "-a") {
result = test_manager_t::instance().run();
}
else {
result = test_manager_t::instance().run(arg1);
}
return result ? 0 : 2;
}
| Java |
function solve(args) {
function biSearch(array, searchedNumber, start, end) {
for (var i = start; i <= end; i += 1) {
if (+array[i] === searchedNumber) {
return i;
}
}
return -1;
}
var data = args[0].split('\n'),
numberN = +data.shift(),
numberX = +data.pop();
var firstIndex = 0;
var lastIndex = data.length - 1;
var resultIndex = 0;
var middle = 0;
for (var j = firstIndex; j < lastIndex; j += 1) {
middle = (lastIndex / 2) | 0;
if (+data[middle] === numberX) {
resultIndex = middle;
break;
}
if (+data[middle] < numberX) {
firstIndex = middle;
resultIndex = biSearch(data, numberX, firstIndex, lastIndex);
}
if (+data[middle] > numberX) {
lastIndex = middle;
resultIndex = biSearch(data, numberX, firstIndex, lastIndex);
}
}
if (resultIndex >= 0 && resultIndex < data.length) {
console.log(resultIndex);
} else {
console.log('-1');
}
} | Java |
#!/usr/bin/env node
var pluginlist = [
];
var exec = require('child_process').exec;
function puts(error, stdout, stderr) {
console.log(stdout);
}
pluginlist.forEach(function(plug) {
exec("cordova plugin add " + plug, puts);
});
| Java |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.text;
import java.util.Map;
public abstract class StrLookup<V> {
public static StrLookup<?> noneLookup() {
return null;
}
public static StrLookup<String> systemPropertiesLookup() {
return null;
}
public static <V> StrLookup<V> mapLookup(final Map<String, V> map) {
return null;
}
public abstract String lookup(String key);
}
| Java |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DynThings.Data.Models
{
using System;
using System.Collections.Generic;
public partial class UserNotification
{
public long ID { get; set; }
public string UserID { get; set; }
public Nullable<long> IsRead { get; set; }
public string Txt { get; set; }
public Nullable<long> NotificationTypeID { get; set; }
public Nullable<long> RefID { get; set; }
public Nullable<System.DateTime> AlertTimeStamp { get; set; }
public Nullable<bool> IsEmailSent { get; set; }
public virtual AspNetUser AspNetUser { get; set; }
}
}
| Java |
const path = require('path');
require('dotenv').config();
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const { AureliaPlugin } = require('aurelia-webpack-plugin');
const { optimize: { CommonsChunkPlugin }, ProvidePlugin } = require('webpack')
const { TsConfigPathsPlugin, CheckerPlugin } = require('awesome-typescript-loader');
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
// config helpers:
const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || []
const when = (condition, config, negativeConfig) =>
condition ? ensureArray(config) : ensureArray(negativeConfig)
// primary config:
const title = 'TechRadar';
const outDir = path.resolve(__dirname, 'dist');
const srcDir = path.resolve(__dirname, 'src');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const baseUrl = '/';
const cssRules = [
{ loader: 'css-loader' },
{
loader: 'postcss-loader',
options: { plugins: () => [require('autoprefixer')({ browsers: ['last 2 versions'] })] }
}
]
module.exports = ({ production, server, extractCss, coverage } = {}) => ({
resolve: {
extensions: ['.ts', '.js'],
modules: [srcDir, 'node_modules'],
alias: {
'aurelia-binding$': path.resolve(__dirname, 'node_modules/aurelia-binding/dist/amd/aurelia-binding.js')
}
},
entry: {
app: ['./src/main']
},
output: {
path: outDir,
publicPath: baseUrl,
filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js',
sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map',
chunkFilename: production ? '[chunkhash].chunk.js' : '[hash].chunk.js',
},
devServer: {
contentBase: baseUrl,
},
module: {
rules: [
// CSS required in JS/TS files should use the style-loader that auto-injects it into the website
// only when the issuer is a .js/.ts file, so the loaders are not applied inside html templates
{
test: /\.css$/i,
issuer: [{ not: [{ test: /\.html$/i }] }],
use: extractCss ? ExtractTextPlugin.extract({
fallback: 'style-loader',
use: cssRules,
}) : ['style-loader', ...cssRules],
},
{
test: /\.css$/i,
issuer: [{ test: /\.html$/i }],
// CSS required in templates cannot be extracted safely
// because Aurelia would try to require it again in runtime
use: cssRules,
},
{ test: /\.html$/i, loader: 'html-loader' },
{ test: /\.ts$/i, loader: 'awesome-typescript-loader', exclude: nodeModulesDir },
{ test: /\.json$/i, loader: 'json-loader' },
// use Bluebird as the global Promise implementation:
{ test: /[\/\\]node_modules[\/\\]bluebird[\/\\].+\.js$/, loader: 'expose-loader?Promise' },
// exposes jQuery globally as $ and as jQuery:
{ test: require.resolve('jquery'), loader: 'expose-loader?$!expose-loader?jQuery' },
// embed small images and fonts as Data Urls and larger ones as files:
{ test: /\.(png|gif|jpg|cur)$/i, loader: 'url-loader', options: { limit: 8192 } },
{ test: /\.woff2(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff2' } },
{ test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } },
// load these fonts normally, as files:
{ test: /\.(ttf|eot|svg|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'file-loader' },
...when(coverage, {
test: /\.[jt]s$/i, loader: 'istanbul-instrumenter-loader',
include: srcDir, exclude: [/\.{spec,test}\.[jt]s$/i],
enforce: 'post', options: { esModules: true },
})
]
},
plugins: [
new BrowserSyncPlugin({
// browse to http://localhost:3000/ during development,
// ./public directory is being served
host: 'localhost',
port: 3000,
server: { baseDir: ['dist'] }
}),
new AureliaPlugin(),
new ProvidePlugin({
'Promise': 'bluebird',
'$': 'jquery',
'jQuery': 'jquery',
'window.jQuery': 'jquery',
}),
new TsConfigPathsPlugin(),
new CheckerPlugin(),
new HtmlWebpackPlugin({
template: 'index.ejs',
minify: production ? {
removeComments: true,
collapseWhitespace: true
} : undefined,
metadata: {
// available in index.ejs //
title, server, baseUrl
},
}),
// new UglifyJSPlugin(),
new CopyWebpackPlugin([
{ from: 'static/favicon.ico', to: 'favicon.ico' }
,{ from: './../tr-host/projects', to: 'projects' }
,{ from: 'img', to: 'img' }
]),
...when(extractCss, new ExtractTextPlugin({
filename: production ? '[contenthash].css' : '[id].css',
allChunks: true,
})),
...when(production, new CommonsChunkPlugin({
name: ['vendor']
})),
...when(production, new CopyWebpackPlugin([
{ from: 'static/favicon.ico', to: 'favicon.ico' }
]))
// ,
// new BundleAnalyzerPlugin({
// // Can be `server`, `static` or `disabled`.
// // In `server` mode analyzer will start HTTP server to show bundle report.
// // In `static` mode single HTML file with bundle report will be generated.
// // In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting `generateStatsFile` to `true`.
// analyzerMode: 'static',
// // Host that will be used in `server` mode to start HTTP server.
// analyzerHost: '127.0.0.1',
// // Port that will be used in `server` mode to start HTTP server.
// analyzerPort: 8888,
// // Path to bundle report file that will be generated in `static` mode.
// // Relative to bundles output directory.
// reportFilename: 'report.html',
// // Module sizes to show in report by default.
// // Should be one of `stat`, `parsed` or `gzip`.
// // See "Definitions" section for more information.
// defaultSizes: 'parsed',
// // Automatically open report in default browser
// openAnalyzer: false,
// // If `true`, Webpack Stats JSON file will be generated in bundles output directory
// generateStatsFile: false,
// // Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
// // Relative to bundles output directory.
// statsFilename: 'stats.json',
// // Options for `stats.toJson()` method.
// // For example you can exclude sources of your modules from stats file with `source: false` option.
// // See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
// statsOptions: null,
// // Log level. Can be 'info', 'warn', 'error' or 'silent'.
// logLevel: 'info'
// })
],
})
| Java |
---
title: The Coliseum
author: rami
layout: lifestream
categories: [Lifestream]
tags: [oakland, california, usa, instagram]
image: the-coliseum.jpg
---
{% include image.html url="/assets/images/content/lifestream/the-coliseum.jpg" description="The Coliseum Oakland Athletics" %}
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Enjoying The New</title>
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:300,300i,600">
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href="/custom.css">
<link rel="shortcut icon" href="https://micro.blog/joeduvall4/favicon.png" type="image/x-icon" />
<link rel="alternate" type="application/rss+xml" title="Joe Duvall" href="http://micro.blog.joe.duvall.me/feed.xml" />
<link rel="alternate" type="application/json" title="Joe Duvall" href="http://micro.blog.joe.duvall.me/feed.json" />
<link rel="EditURI" type="application/rsd+xml" href="/rsd.xml" />
<link rel="me" href="https://micro.blog/joeduvall4" />
<link rel="authorization_endpoint" href="https://indieauth.com/auth" />
<link rel="token_endpoint" href="https://tokens.indieauth.com/token" />
<link rel="micropub" href="https://micro.blog/micropub" />
<link rel="webmention" href="https://micro.blog/webmention" />
<link rel="subscribe" href="https://micro.blog/users/follow" />
</head>
<body>
<div class="container">
<header class="masthead">
<h1 class="masthead-title--small">
<a href="/">Joe Duvall</a>
</h1>
</header>
<div class="content post h-entry">
<div class="post-date">
<time class="dt-published" datetime="2018-04-25 15:05:59 -0700">25 Apr 2018</time>
</div>
<div class="e-content">
<p>Enjoying the new Gmail redesign! It’s mostly solid, with a few rough edges, but it’s not labeled beta. Amusing that the original Gmail carried a “beta” tag for 5 years, but this redesign does not!</p>
</div>
</div>
</div>
</body>
</html>
| Java |
<!-- Begin Footer -->
<footer id="footer" class="footer">
<div class="row">
<div class="pull-left col-md-6 col-xs-6">
<div class="g-plusone" data-size="medium" data-annotation="inline" data-width="300" data-href="{{ site.url }}"></div>
</div>
<div class="logo logo-footer logo-gray pull-right"></div>
</div>
<div class="row">
{% for block in site.footerBlocks %}
{% assign colWidth = 12 | divided_by: forloop.length %}
<div class="col-md-{{ colWidth }} col-xs-6">
<h5>{{ block.title }}</h5>
<ul>
{% for linkElement in block.links %}
<li><a href="{% if linkElement.permalink != null %} {{ linkElement.permalink | prepend: site.baseurl }} {% else %} {{ linkElement.link }} {% endif %}" {% if linkElement.link != null %}target="_blank"{% endif %}>{{ linkElement.text }}</a></li>
{% endfor %}
</ul>
</div>
{% endfor %}
</div>
<div class="row">
<div class="col-md-6 col-xs-12">
<ul class="social-links">
{% for social in site.socialLinks %}
<li>
<a href="{% if social.permalink != null %} {{ social.permalink | prepend: site.baseurl }} {% else %} {{ social.link }} {% endif %}" target="_blank">
<svg class="icon icon-{{ social.icon }}" viewBox="0 0 30 32">
<use xlink:href="{{ site.baseurl }}/img/sprites/sprites.svg#icon-{{ social.icon }}"></use>
</svg>
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
<div class="row">
<!-- Please don't delete this line-->
<div class="col-md-6">
<p class="copyright">
© 2014 Based on <a href="https://github.com/gdg-x/zeppelin" target="_blank">Project Zeppelin</a>. Designed and created by <a href="https://github.com/ozasadnyy" target="_blank">Oleh Zasadnyy</a> · <a href="https://gdg.org.ua" target="_blank">GDG Lviv</a>
</p>
</div>
</div>
</footer>
<!-- End Footer -->
| Java |
# rustual-boy-www
A basic landing page/blog for [Rustual Boy](https://github.com/emu-rs/rustual-boy).
## running locally
1. Update/install dependencies by running: `npm install` from the repo directory (safe to only do this once per pull)
2. Run the site: `node app`
The site will be available on [localhost:3000](http://localhost:3000). To use another port, you can specify a just-in-time environment variable like so: `httpPort=[port] node app`.
## running in deployment
Start the site: `sudo httpPort=80 useHttps=true pm2 start app.js`
Note that `pm2` is used to spawn the app in a separate process so that the ssh terminal isn't blocked while it's running. To monitor the process, use `sudo pm2 list`. It can be restarted using `sudo pm2 restart app`, and if absolutely necessary, all node processes can be killed using `sudo pm2 kill`.
## blog
The blog is built with [poet](http://jsantell.github.io/poet/), which means a couple things:
- Posts are stored as .md files in the `posts/` directory. We've configured poet to watch the posts dir, but its watcher isn't recursive by default, so we can't use subdirectories. Therefore, all posts follow a simple naming convention: `category-number-postname.md`. This way they can stay cleanly organized within this single folder.
- Post slugs are generated using the title of the post, so these can't be changed without also invalidating the post url.
- Post dates use the nonintuitive American format (M-D-Y)
## demo reel
Just in case I lose them later, here's the encoding settings used for the demo reel video:
```
ffmpeg.exe -i reel.mkv -c:v libvpx -qmin 0 -qmax 50 -crf 5 -b:v 1M -an -r 25 reel.webm
ffmpeg.exe -i reel.mkv -c:v libx264 -pix_fmt yuv420p -profile:v baseline -b:v 600k -pass 1 -level 3 -movflags +faststart -an -r 25 -f mp4 /dev/null && \
ffmpeg.exe -i reel.mkv -c:v libx264 -pix_fmt yuv420p -profile:v baseline -b:v 600k -pass 2 -level 3 -movflags +faststart -an -r 25 reel.mp4
```
## license
MIT (see [LICENSE](LICENSE))
| Java |
#!/bin/env/python
# coding: utf-8
import logging
import os
import time
import uuid
from logging import Formatter
from logging.handlers import RotatingFileHandler
from multiprocessing import Queue
from time import strftime
import dill
from .commands import *
from .processing import MultiprocessingLogger
class TaskProgress(object):
"""
Holds both data and graphics-related information for a task's progress bar.
The logger will iterate over TaskProgress objects to draw progress bars on screen.
"""
def __init__(self,
total,
prefix='',
suffix='',
decimals=0,
bar_length=60,
keep_alive=False,
display_time=False):
"""
Creates a new progress bar using the given information.
:param total: The total number of iteration for this progress bar.
:param prefix: [Optional] The text that should be displayed at the left side of the
progress bar. Note that progress bars will always stay left-aligned at the
shortest possible.
:param suffix: [Optional] The text that should be displayed at the very right side of the
progress bar.
:param decimals: [Optional] The number of decimals to display for the percentage.
:param bar_length: [Optional] The graphical bar size displayed on screen. Unit is character.
:param keep_alive: [Optional] Specify whether the progress bar should stay displayed forever
once completed or if it should vanish.
:param display_time: [Optional] Specify whether the duration since the progress has begun should
be displayed. Running time will be displayed between parenthesis, whereas it
will be displayed between brackets when the progress has completed.
"""
super(TaskProgress, self).__init__()
self.progress = 0
# Minimum number of seconds at maximum completion before a progress bar is removed from display
# The progress bar may vanish at a further time as the redraw rate depends upon chrono AND method calls
self.timeout_chrono = None
self.begin_time = None
self.end_time = None
self.elapsed_time_at_end = None
# Graphics related information
self.keep_alive = keep_alive
self.display_time = display_time
self.total = total
self.prefix = prefix
self.suffix = suffix
self.decimals = decimals
self.bar_length = bar_length
def set_progress(self, progress):
"""
Defines the current progress for this progress bar in iteration units (not percent).
:param progress: Current progress in iteration units regarding its total (not percent).
:return: True if the progress has changed. If the given progress is higher than the total or lower
than 0 then it will be ignored.
"""
_progress = progress
if _progress > self.total:
_progress = self.total
elif _progress < 0:
_progress = 0
# Stop task chrono if needed
if _progress == self.total and self.display_time:
self.end_time = time.time() * 1000
# If the task has completed instantly then define its begin_time too
if not self.begin_time:
self.begin_time = self.end_time
has_changed = self.progress != _progress
if has_changed:
self.progress = _progress
return has_changed
class FancyLogger(object):
"""
Defines a multiprocess logger object. Logger uses a redraw rate because of console flickering. That means it will
not draw new messages or progress at the very time they are being logged but their timestamp will be captured at the
right time. Logger will redraw at a given time period AND when new messages or progress are logged.
If you still want to force redraw immediately (may produce flickering) then call 'flush' method.
Logger uses one file handler and then uses standard output (stdout) to draw on screen.
"""
queue = None
"Handles all messages and progress to be sent to the logger process."
default_message_number = 20
"Default value for the logger configuration."
default_exception_number = 5
"Default value for the logger configuration."
default_permanent_progressbar_slots = 0
"Default value for the logger configuration."
default_redraw_frequency_millis = 500
"Default value for the logger configuration."
default_level = logging.INFO
"Default value for the logger configuration."
default_task_millis_to_removal = 500
"Default value for the logger configuration."
default_console_format_strftime = '%d %B %Y %H:%M:%S'
"Default value for the logger configuration."
default_console_format = '{T} [{L}]'
"Default value for the logger configuration."
default_file_handlers = []
"Default value for the logger configuration. Filled in constructor."
def __init__(self,
message_number=default_message_number,
exception_number=default_exception_number,
permanent_progressbar_slots=default_permanent_progressbar_slots,
redraw_frequency_millis=default_redraw_frequency_millis,
console_level=default_level,
task_millis_to_removal=default_task_millis_to_removal,
console_format_strftime=default_console_format_strftime,
console_format=default_console_format,
file_handlers=None,
application_name=None):
"""
Initializes a new logger and starts its process immediately using given configuration.
:param message_number: [Optional] Number of simultaneously displayed messages below progress bars.
:param exception_number: [Optional] Number of simultaneously displayed exceptions below messages.
:param permanent_progressbar_slots: [Optional] The amount of vertical space (bar slots) to keep at all times,
so the message logger will not move anymore if the bar number is equal or
lower than this parameter.
:param redraw_frequency_millis: [Optional] Minimum time lapse in milliseconds between two redraws. It may be
more because the redraw rate depends upon time AND method calls.
:param console_level: [Optional] The logging level (from standard logging module).
:param task_millis_to_removal: [Optional] Minimum time lapse in milliseconds at maximum completion before
a progress bar is removed from display. The progress bar may vanish at a
further time as the redraw rate depends upon time AND method calls.
:param console_format_strftime: [Optional] Specify the time format for console log lines using python
strftime format. Defaults to format: '29 november 2016 21:52:12'.
:param console_format: [Optional] Specify the format of the console log lines. There are two
variables available: {T} for timestamp, {L} for level. Will then add some
tabulations in order to align text beginning for all levels.
Defaults to format: '{T} [{L}]'
Which will produce: '29 november 2016 21:52:12 [INFO] my log text'
'29 november 2016 21:52:13 [WARNING] my log text'
'29 november 2016 21:52:14 [DEBUG] my log text'
:param file_handlers: [Optional] Specify the file handlers to use. Each file handler will use its
own regular formatter and level. Console logging is distinct from file
logging. Console logging uses custom stdout formatting, while file logging
uses regular python logging rules. All handlers are permitted except
StreamHandler if used with stdout or stderr which are reserved by this
library for custom console output.
:param application_name: [Optional] Used only if 'file_handlers' parameter is ignored. Specifies the
application name to use to format the default file logger using format:
application_%Y-%m-%d_%H-%M-%S.log
"""
super(FancyLogger, self).__init__()
# Define default file handlers
if not file_handlers:
if not application_name:
app_name = 'application'
else:
app_name = application_name
handler = RotatingFileHandler(filename=os.path.join(os.getcwd(), '{}_{}.log'
.format(app_name, strftime('%Y-%m-%d_%H-%M-%S'))),
encoding='utf8',
maxBytes=5242880, # 5 MB
backupCount=10,
delay=True)
handler.setLevel(logging.INFO)
handler.setFormatter(fmt=Formatter(fmt='%(asctime)s [%(levelname)s]\t%(message)s',
datefmt=self.default_console_format_strftime))
self.default_file_handlers.append(handler)
file_handlers = self.default_file_handlers
if not self.queue:
self.queue = Queue()
self.process = MultiprocessingLogger(queue=self.queue,
console_level=console_level,
message_number=message_number,
exception_number=exception_number,
permanent_progressbar_slots=permanent_progressbar_slots,
redraw_frequency_millis=redraw_frequency_millis,
task_millis_to_removal=task_millis_to_removal,
console_format_strftime=console_format_strftime,
console_format=console_format,
file_handlers=file_handlers)
self.process.start()
def flush(self):
"""
Flushes the remaining messages and progress bars state by forcing redraw. Can be useful if you want to be sure
that a message or progress has been updated in display at a given moment in code, like when you are exiting an
application or doing some kind of synchronized operations.
"""
self.queue.put(dill.dumps(FlushCommand()))
def terminate(self):
"""
Tells the logger process to exit immediately. If you do not call 'flush' method before, you may lose some
messages of progresses that have not been displayed yet. This method blocks until logger process has stopped.
"""
self.queue.put(dill.dumps(ExitCommand()))
if self.process:
self.process.join()
def set_configuration(self,
message_number=default_message_number,
exception_number=default_exception_number,
permanent_progressbar_slots=default_permanent_progressbar_slots,
redraw_frequency_millis=default_redraw_frequency_millis,
console_level=default_level,
task_millis_to_removal=default_task_millis_to_removal,
console_format_strftime=default_console_format_strftime,
console_format=default_console_format,
file_handlers=default_file_handlers):
"""
Defines the current configuration of the logger. Can be used at any moment during runtime to modify the logger
behavior.
:param message_number: [Optional] Number of simultaneously displayed messages below progress bars.
:param exception_number: [Optional] Number of simultaneously displayed exceptions below messages.
:param permanent_progressbar_slots: [Optional] The amount of vertical space (bar slots) to keep at all times,
so the message logger will not move anymore if the bar number is equal or
lower than this parameter.
:param redraw_frequency_millis: [Optional] Minimum time lapse in milliseconds between two redraws. It may be
more because the redraw rate depends upon time AND method calls.
:param console_level: [Optional] The logging level (from standard logging module).
:param task_millis_to_removal: [Optional] Minimum time lapse in milliseconds at maximum completion before
a progress bar is removed from display. The progress bar may vanish at a
further time as the redraw rate depends upon time AND method calls.
:param console_format_strftime: [Optional] Specify the time format for console log lines using python
strftime format. Defaults to format: '29 november 2016 21:52:12'.
:param console_format: [Optional] Specify the format of the console log lines. There are two
variables available: {T} for timestamp, {L} for level. Will then add some
tabulations in order to align text beginning for all levels.
Defaults to format: '{T} [{L}]'
Which will produce: '29 november 2016 21:52:12 [INFO] my log text'
'29 november 2016 21:52:13 [WARNING] my log text'
'29 november 2016 21:52:14 [DEBUG] my log text'
:param file_handlers: [Optional] Specify the file handlers to use. Each file handler will use its
own regular formatter and level. Console logging is distinct from file
logging. Console logging uses custom stdout formatting, while file logging
uses regular python logging rules. All handlers are permitted except
StreamHandler if used with stdout or stderr which are reserved by this
library for custom console output.
"""
self.queue.put(dill.dumps(SetConfigurationCommand(task_millis_to_removal=task_millis_to_removal,
console_level=console_level,
permanent_progressbar_slots=permanent_progressbar_slots,
message_number=message_number,
exception_number=exception_number,
redraw_frequency_millis=redraw_frequency_millis,
console_format_strftime=console_format_strftime,
console_format=console_format,
file_handlers=file_handlers)))
def set_level(self,
level,
console_only=False):
"""
Defines the logging level (from standard logging module) for log messages.
:param level: Level of logging for the file logger.
:param console_only: [Optional] If True then the file logger will not be affected.
"""
self.queue.put(dill.dumps(SetLevelCommand(level=level,
console_only=console_only)))
def set_task_object(self,
task_id,
task_progress_object):
"""
Defines a new progress bar with the given information using a TaskProgress object.
:param task_id: Unique identifier for this progress bar. Will erase if already existing.
:param task_progress_object: TaskProgress object holding the progress bar information.
"""
self.set_task(task_id=task_id,
total=task_progress_object.total,
prefix=task_progress_object.prefix,
suffix=task_progress_object.suffix,
decimals=task_progress_object.decimals,
bar_length=task_progress_object.bar_length,
keep_alive=task_progress_object.keep_alive,
display_time=task_progress_object.display_time)
def set_task(self,
task_id,
total,
prefix,
suffix='',
decimals=0,
bar_length=60,
keep_alive=False,
display_time=False):
"""
Defines a new progress bar with the given information.
:param task_id: Unique identifier for this progress bar. Will erase if already existing.
:param total: The total number of iteration for this progress bar.
:param prefix: The text that should be displayed at the left side of the progress bar. Note that
progress bars will always stay left-aligned at the shortest possible.
:param suffix: [Optional] The text that should be displayed at the very right side of the progress bar.
:param decimals: [Optional] The number of decimals to display for the percentage.
:param bar_length: [Optional] The graphical bar size displayed on screen. Unit is character.
:param keep_alive: [Optional] Specify whether the progress bar should stay displayed forever once completed
or if it should vanish.
:param display_time: [Optional] Specify whether the duration since the progress has begun should be
displayed. Running time will be displayed between parenthesis, whereas it will be
displayed between brackets when the progress has completed.
"""
self.queue.put(dill.dumps(NewTaskCommand(task_id=task_id,
task=TaskProgress(total,
prefix,
suffix,
decimals,
bar_length,
keep_alive,
display_time))))
def update(self,
task_id,
progress):
"""
Defines the current progress for this progress bar id in iteration units (not percent).
If the given id does not exist or the given progress is identical to the current, then does nothing.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param task_id: Unique identifier for this progress bar. Will erase if already existing.
:param progress: Current progress in iteration units regarding its total (not percent).
"""
self.queue.put(dill.dumps(UpdateProgressCommand(task_id=task_id,
progress=progress)))
def debug(self, text):
"""
Posts a debug message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param text: The text to log into file and console.
"""
self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.DEBUG)))
def info(self, text):
"""
Posts an info message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param text: The text to log into file and console.
"""
self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.INFO)))
def warning(self, text):
"""
Posts a warning message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param text: The text to log into file and console.
"""
self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.WARNING)))
def error(self, text):
"""
Posts an error message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param text: The text to log into file and console.
"""
self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.ERROR)))
def critical(self, text):
"""
Posts a critical message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time. Logger will
redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw
immediately (may produce flickering) then call 'flush' method.
:param text: The text to log into file and console.
"""
self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.CRITICAL)))
def throw(self, stacktrace, process_title=None):
"""
Sends an exception to the logger so it can display it as a special message. Prevents console refresh cycles from
hiding exceptions that could be thrown by processes.
:param stacktrace: Stacktrace string as returned by 'traceback.format_exc()' in an 'except' block.
:param process_title: [Optional] Define the current process title to display into the logger for this
exception.
"""
self.queue.put(dill.dumps(StacktraceCommand(pid=os.getpid(),
stacktrace=stacktrace,
process_title=process_title)))
# --------------------------------------------------------------------
# Iterator implementation
def progress(self,
enumerable,
task_progress_object=None):
"""
Enables the object to be used as an iterator. Each iteration will produce a progress update in the logger.
:param enumerable: Collection to iterate over.
:param task_progress_object: [Optional] TaskProgress object holding the progress bar information.
:return: The logger instance.
"""
self.list = enumerable
self.list_length = len(enumerable)
self.task_id = uuid.uuid4()
self.index = 0
if task_progress_object:
# Force total attribute
task_progress_object.total = self.list_length
else:
task_progress_object = TaskProgress(total=self.list_length,
display_time=True,
prefix='Progress')
# Create a task progress
self.set_task_object(task_id=self.task_id,
task_progress_object=task_progress_object)
return self
def __iter__(self):
"""
Enables the object to be used as an iterator. Each iteration will produce a progress update in the logger.
:return: The logger instance.
"""
return self
def __next__(self):
"""
Enables the object to be used as an iterator. Each iteration will produce a progress update in the logger.
:return: The current object of the iterator.
"""
if self.index >= self.list_length:
raise StopIteration
else:
self.index += 1
self.update(task_id=self.task_id,
progress=self.index)
return self.list[self.index - 1]
# ---------------------------------------------------------------------
| Java |
<html><body>
<h4>Windows 10 x64 (18362.329)</h4><br>
<h2>_DEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT</h2>
<font face="arial"> +0x000 Size : Uint4B<br>
+0x004 Action : Uint4B<br>
+0x008 Flags : Uint4B<br>
+0x00c OperationStatus : Uint4B<br>
+0x010 ExtendedError : Uint4B<br>
+0x014 TargetDetailedError : Uint4B<br>
+0x018 ReservedStatus : Uint4B<br>
+0x01c OutputBlockOffset : Uint4B<br>
+0x020 OutputBlockLength : Uint4B<br>
</font></body></html> | Java |
package com.rebuy.consul;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.NewService;
import com.ecwid.consul.v1.catalog.model.CatalogService;
import com.rebuy.consul.exceptions.NoServiceFoundException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ConsulServiceTest
{
private ConsulClient clientMock;
private ConsulService service;
private NewService serviceMock;
@Before
public void before()
{
clientMock = mock(ConsulClient.class);
serviceMock = mock(NewService.class);
when(serviceMock.getId()).thenReturn("42");
service = new ConsulService(clientMock, serviceMock);
}
@Test
public void register_should_invoke_client()
{
when(clientMock.agentServiceRegister(Mockito.any())).thenReturn(null);
service.register();
Mockito.verify(clientMock).agentServiceRegister(serviceMock);
}
@Test
public void unregister_should_invoke_client()
{
service.unregister();
Mockito.verify(clientMock).agentServiceSetMaintenance("42", true);
}
@Test(expected = NoServiceFoundException.class)
public void findService_should_throw_exception_if_no_services_are_found()
{
Response<List<CatalogService>> response = new Response<>(new ArrayList<>(), 1L, true, 1L);
when(clientMock.getCatalogService(Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response);
service.getRandomService("service");
Mockito.verify(clientMock).getCatalogService("service", Mockito.any(QueryParams.class));
}
@Test
public void findService_should_invoke_client()
{
List<CatalogService> services = new ArrayList<>();
services.add(mock(CatalogService.class));
Response<List<CatalogService>> response = new Response<>(services, 1L, true, 1L);
when(clientMock.getCatalogService(Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response);
service.getRandomService("service");
Mockito.verify(clientMock).getCatalogService(Mockito.eq("service"), Mockito.any(QueryParams.class));
}
@Test
public void findService_should_return_one_service()
{
List<CatalogService> services = new ArrayList<>();
CatalogService service1 = mock(CatalogService.class);
when(service1.getAddress()).thenReturn("192.168.0.1");
services.add(service1);
CatalogService service2 = mock(CatalogService.class);
when(service2.getAddress()).thenReturn("192.168.0.2");
services.add(service2);
CatalogService service3 = mock(CatalogService.class);
when(service3.getAddress()).thenReturn("192.168.0.3");
services.add(service3);
Response<List<CatalogService>> response = new Response<>(services, 1L, true, 1L);
when(clientMock.getCatalogService(Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response);
Service catalogService = service.getRandomService("service");
boolean foundMatch = false;
for (CatalogService service : services) {
if (service.getAddress().equals(catalogService.getHostname()) && service.getServicePort() == catalogService.getPort()) {
foundMatch = true;
}
}
assertTrue(foundMatch);
Mockito.verify(clientMock).getCatalogService(Mockito.eq("service"), Mockito.any(QueryParams.class));
}
@Test
public void findService_should_return_one_service_with_tag()
{
List<CatalogService> services = new ArrayList<>();
CatalogService service1 = mock(CatalogService.class);
when(service1.getAddress()).thenReturn("192.168.0.1");
services.add(service1);
CatalogService service2 = mock(CatalogService.class);
when(service2.getAddress()).thenReturn("192.168.0.2");
services.add(service2);
CatalogService service3 = mock(CatalogService.class);
when(service3.getAddress()).thenReturn("192.168.0.3");
services.add(service3);
Response<List<CatalogService>> response = new Response<>(services, 1L, true, 1L);
when(clientMock.getCatalogService(Mockito.anyString(), Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response);
Service catalogService = service.getRandomService("service", "my-tag");
boolean foundMatch = false;
for (CatalogService service : services) {
if (service.getAddress().equals(catalogService.getHostname()) && service.getServicePort() == catalogService.getPort()) {
foundMatch = true;
}
}
assertTrue(foundMatch);
Mockito.verify(clientMock).getCatalogService(Mockito.eq("service"), Mockito.eq("my-tag"), Mockito.any(QueryParams.class));
}
}
| Java |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace XamarinFormsHello.WinPhone
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
LoadApplication(new XamarinFormsHello.App());
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
}
}
| Java |
<?php
namespace LeadCommerce\Shopware\SDK\Query;
use LeadCommerce\Shopware\SDK\Util\Constants;
/**
* Class CustomerQuery
*
* @author Alexander Mahrt <amahrt@leadcommerce.de>
* @copyright 2016 LeadCommerce <amahrt@leadcommerce.de>
*/
class CustomerQuery extends Base
{
/**
* @var array
*/
protected $methodsAllowed = [
Constants::METHOD_CREATE,
Constants::METHOD_GET,
Constants::METHOD_GET_BATCH,
Constants::METHOD_UPDATE,
Constants::METHOD_DELETE,
];
/**
* @return mixed
*/
protected function getClass()
{
return 'LeadCommerce\\Shopware\\SDK\\Entity\\Customer';
}
/**
* Gets the query path to look for entities.
* E.G: 'variants' or 'articles'
*
* @return string
*/
protected function getQueryPath()
{
return 'customers';
}
}
| Java |
--- @module vline
local BASE = (...):match("(.-)[^%.]+$")
local core = require( BASE .. "core" )
local style = require( BASE .. "style" )
local group = {}
-------------------------------------------------------------------------------
-- vertically allign all elements
-------------------------------------------------------------------------------
function group.v_align( elements, align, x )
x = x or style.getCenterX()
if align == "left" then
for _, rect in ipairs( elements ) do
rect.x = x
end
elseif align == "right" then
for _, rect in ipairs( elements ) do
rect.x = x - rect.w
end
elseif align == "center" then
for _, rect in ipairs( elements ) do
rect.x = x - rect.w / 2
end
else
error( "group.v_align invalid align: " .. tostring( align ) )
end
end
-------------------------------------------------------------------------------
-- horizontally allign all elements
-------------------------------------------------------------------------------
function group.h_align( elements, align, y )
y = y or style.getCenterY()
if align == "top" then
for _, rect in ipairs( elements ) do
rect.y = y
end
elseif align == "bottom" then
for _, rect in ipairs( elements ) do
rect.y = y - rect.h
end
elseif align == "center" then
for _, rect in ipairs( elements ) do
rect.y = y - rect.h / 2
end
else
error( "group.h_align invalid align: " .. tostring( align ) )
end
end
-------------------------------------------------------------------------------
-- arrange elements from top to bottom with vertical spacing in between
-------------------------------------------------------------------------------
function group.v_distribute( elements, spacing )
if spacing and elements[ 1 ] then
local y = elements[ 1 ].y
for _, rect in ipairs( elements ) do
rect.y = y
y = y + rect.h + spacing
end
end
end
-------------------------------------------------------------------------------
-- make all elements have same width
-------------------------------------------------------------------------------
function group.stretch_w( elements )
local w = 0
for _, rect in ipairs( elements ) do
w = math.max( w, rect.w )
end
for _, rect in ipairs( elements ) do
rect.w = w
end
end
-------------------------------------------------------------------------------
-- returns the arithmetic center of group
-------------------------------------------------------------------------------
function group.get_center( elements )
local cx = 0
local cy = 0
local n = 0
for _, rect in ipairs( elements ) do
cx = cx + rect.x + rect.w / 2
cy = cy + rect.y + rect.h / 2
n = n + 1
end
if n == 0 then
return style.getCenterX(), style.getCenterY()
else
return math.floor( cx / n ), math.floor( cy / n )
end
end
-------------------------------------------------------------------------------
-- centers whole group on screen; preserves element distances
-------------------------------------------------------------------------------
function group.center_on_screen( elements )
local sx, sy = style.getCenterX(), style.getCenterY()
local dx, dy = group.get_center( elements )
for _, rect in ipairs( elements ) do
local rx = rect.x + rect.w / 2
local ry = rect.y + rect.h / 2
rect.x = math.floor( rect.x + sx - dx )
rect.y = math.floor( rect.y + sy - dy )
end
end
-------------------------------------------------------------------------------
return group
| Java |
**Blight**
**School** necromancy; **Level** druid 4, sorcerer/wizard 5
**Casting Time** 1 standard action
**Components** V, S, DF
**Range** touch
**Target** plant touched
**Duration** instantaneous
**Saving Throw** [Fortitude](../combat#_fortitude) half; see text; **[Spell Resistance](../glossary#_spell-resistance)** yes
This spell withers a single plant of any size. An affected plant creature takes 1d6 points of damage per level (maximum 15d6) and may attempt a [Fortitude](../combat#_fortitude) saving throw for half damage. A plant that isn't a creature doesn't receive a save and immediately withers and dies.
This spell has no effect on the soil or surrounding plant life.
| Java |
<?php
namespace GFire\InvoiceBundle\Entity\Interfaces;
interface InvoiceInterface{
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package test.thread;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Administrator
*/
public class CallableAndFutureTest {
private final ExecutorService executor = Executors.newFixedThreadPool(2);
void start() throws Exception {
final Callable<List<Integer>> task = new Callable<List<Integer>>() {
public List<Integer> call() throws Exception {
// get obj
final List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 100; i++) {
Thread.sleep(50);
list.add(i);
}
return list;
}
};
final Future<List<Integer>> future = executor.submit(task);
//do sthing others..
//example: due to show some data..
try {
final List<Integer> list = future.get(); //这个函数还可以接受超时检测http://www.javaeye.com/topic/671314
System.out.println(list);
} catch (final InterruptedException ex) {
Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex);
future.cancel(true);
} catch (final ExecutionException ex) {
Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex);
throw new ExecutionException(ex);
} finally {
executor.shutdown();
}
}
public static void main(final String args[]) {
try {
new CallableAndFutureTest().start();
} catch (final Exception ex) {
Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| Java |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The interface IWorkbookFunctionsCumPrincRequestBuilder.
/// </summary>
public partial interface IWorkbookFunctionsCumPrincRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
IWorkbookFunctionsCumPrincRequest Request(IEnumerable<Option> options = null);
}
}
| Java |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.eventhubs.generated;
import com.azure.core.util.Context;
/** Samples for ConsumerGroups ListByEventHub. */
public final class ConsumerGroupsListByEventHubSamples {
/*
* x-ms-original-file: specification/eventhub/resource-manager/Microsoft.EventHub/stable/2021-11-01/examples/ConsumerGroup/EHConsumerGroupListByEventHub.json
*/
/**
* Sample code: ConsumerGroupsListAll.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void consumerGroupsListAll(com.azure.resourcemanager.AzureResourceManager azure) {
azure
.eventHubs()
.manager()
.serviceClient()
.getConsumerGroups()
.listByEventHub("ArunMonocle", "sdk-Namespace-2661", "sdk-EventHub-6681", null, null, Context.NONE);
}
}
| Java |
/** @jsx m */
import m from 'mithril';
import { linkTo, hrefTo } from '@storybook/addon-links';
const Main = {
view: vnode => (
<article
style={{
padding: 15,
lineHeight: 1.4,
fontFamily: '"Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif',
backgroundColor: '#ffffff',
}}
>
{vnode.children}
</article>
),
};
const Title = {
view: vnode => <h1>{vnode.children}</h1>,
};
const Note = {
view: vnode => (
<p
style={{
opacity: 0.5,
}}
>
{vnode.children}
</p>
),
};
const InlineCode = {
view: vnode => (
<code
style={{
fontSize: 15,
fontWeight: 600,
padding: '2px 5px',
border: '1px solid #eae9e9',
borderRadius: 4,
backgroundColor: '#f3f2f2',
color: '#3a3a3a',
}}
>
{vnode.children}
</code>
),
};
const Link = {
view: vnode => (
<a
style={{
color: '#1474f3',
textDecoration: 'none',
borderBottom: '1px solid #1474f3',
paddingBottom: 2,
}}
{...vnode.attrs}
>
{vnode.children}
</a>
),
};
const NavButton = {
view: vnode => (
<button
type="button"
style={{
borderTop: 'none',
borderRight: 'none',
borderLeft: 'none',
backgroundColor: 'transparent',
padding: 0,
cursor: 'pointer',
font: 'inherit',
}}
{...vnode.attrs}
>
{vnode.children}
</button>
),
};
const StoryLink = {
oninit: vnode => {
// eslint-disable-next-line no-param-reassign
vnode.state.href = '/';
// eslint-disable-next-line no-param-reassign
vnode.state.onclick = () => {
linkTo(vnode.attrs.kind, vnode.attrs.story)();
return false;
};
StoryLink.updateHref(vnode);
},
updateHref: async vnode => {
const href = await hrefTo(vnode.attrs.kind, vnode.attrs.story);
// eslint-disable-next-line no-param-reassign
vnode.state.href = href;
m.redraw();
},
view: vnode => (
<a
href={vnode.state.href}
style={{
color: '#1474f3',
textDecoration: 'none',
borderBottom: '1px solid #1474f3',
paddingBottom: 2,
}}
onClick={vnode.state.onclick}
>
{vnode.children}
</a>
),
};
const Welcome = {
view: vnode => (
<Main>
<Title>Welcome to storybook</Title>
<p>This is a UI component dev environment for your app.</p>
<p>
We've added some basic stories inside the <InlineCode>src/stories</InlineCode> directory.
<br />A story is a single state of one or more UI components. You can have as many stories
as you want.
<br />
(Basically a story is like a visual test case.)
</p>
<p>
See these sample
{vnode.attrs.showApp ? (
<NavButton onclick={vnode.attrs.showApp}>stories</NavButton>
) : (
<StoryLink kind={vnode.attrs.showKind} story={vnode.attrs.showStory}>
stories
</StoryLink>
)}
for a component called <InlineCode>Button</InlineCode>.
</p>
<p>
Just like that, you can add your own components as stories.
<br />
You can also edit those components and see changes right away.
<br />
(Try editing the <InlineCode>Button</InlineCode> stories located at
<InlineCode>src/stories/1-Button.stories.js</InlineCode>
.)
</p>
<p>
Usually we create stories with smaller UI components in the app.
<br />
Have a look at the
<Link
href="https://storybook.js.org/basics/writing-stories"
target="_blank"
rel="noopener noreferrer"
>
Writing Stories
</Link>
section in our documentation.
</p>
<Note>
<b>NOTE:</b>
<br />
Have a look at the <InlineCode>.storybook/webpack.config.js</InlineCode> to add webpack
loaders and plugins you are using in this project.
</Note>
</Main>
),
};
export default Welcome;
| Java |
from simtk.openmm import app
import simtk.openmm as mm
from simtk import unit
def findForce(system, forcetype, add=True):
""" Finds a specific force in the system force list - added if not found."""
for force in system.getForces():
if isinstance(force, forcetype):
return force
if add==True:
system.addForce(forcetype())
return findForce(system, forcetype)
return None
def setGlobalForceParameter(force, key, value):
for i in range(force.getNumGlobalParameters()):
if force.getGlobalParameterName(i)==key:
print('setting force parameter', key, '=', value)
force.setGlobalParameterDefaultValue(i, value);
def atomIndexInResidue(residue):
""" list of atom index in residue """
index=[]
for a in list(residue.atoms()):
index.append(a.index)
return index
def getResiduePositions(residue, positions):
""" Returns array w. atomic positions of residue """
ndx = atomIndexInResidue(residue)
return np.array(positions)[ndx]
def uniquePairs(index):
""" list of unique, internal pairs """
return list(combinations( range(index[0],index[-1]+1),2 ) )
def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k):
""" add harmonic bonds between pairs if distance is smaller than threshold """
print('Constraint force constant =', k)
for i,j in pairlist:
distance = unit.norm( positions[i]-positions[j] )
if distance<threshold:
harmonicforce.addBond( i,j,
distance.value_in_unit(unit.nanometer),
k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole ))
print("added harmonic bond between", i, j, 'with distance',distance)
def addExclusions(nonbondedforce, pairlist):
""" add nonbonded exclusions between pairs """
for i,j in pairlist:
nonbondedforce.addExclusion(i,j)
def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None,
threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole):
""" make residue rigid by adding constraints and nonbonded exclusions """
index = atomIndexInResidue(residue)
pairlist = uniquePairs(index)
addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k)
if nonbondedforce is not None:
for i,j in pairlist:
print('added nonbonded exclusion between', i, j)
nonbonded.addExclusion(i,j)
| Java |
namespace InControl
{
using System;
// @cond nodoc
[AutoDiscover]
public class EightBitdoSNES30AndroidProfile : UnityInputDeviceProfile
{
public EightBitdoSNES30AndroidProfile()
{
Name = "8Bitdo SNES30 Controller";
Meta = "8Bitdo SNES30 Controller on Android";
// Link = "https://www.amazon.com/Wireless-Bluetooth-Controller-Classic-Joystick/dp/B014QP2H1E";
DeviceClass = InputDeviceClass.Controller;
DeviceStyle = InputDeviceStyle.NintendoSNES;
IncludePlatforms = new[] {
"Android"
};
JoystickNames = new[] {
"8Bitdo SNES30 GamePad",
};
ButtonMappings = new[] {
new InputControlMapping {
Handle = "A",
Target = InputControlType.Action2,
Source = Button( 0 ),
},
new InputControlMapping {
Handle = "B",
Target = InputControlType.Action1,
Source = Button( 1 ),
},
new InputControlMapping {
Handle = "X",
Target = InputControlType.Action4,
Source = Button( 2 ),
},
new InputControlMapping {
Handle = "Y",
Target = InputControlType.Action3,
Source = Button( 3 ),
},
new InputControlMapping {
Handle = "L",
Target = InputControlType.LeftBumper,
Source = Button( 4 ),
},
new InputControlMapping {
Handle = "R",
Target = InputControlType.RightBumper,
Source = Button( 5 ),
},
new InputControlMapping {
Handle = "Select",
Target = InputControlType.Select,
Source = Button( 11 ),
},
new InputControlMapping {
Handle = "Start",
Target = InputControlType.Start,
Source = Button( 10 ),
},
};
AnalogMappings = new[] {
new InputControlMapping {
Handle = "DPad Left",
Target = InputControlType.DPadLeft,
Source = Analog( 0 ),
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "DPad Right",
Target = InputControlType.DPadRight,
Source = Analog( 0 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "DPad Up",
Target = InputControlType.DPadUp,
Source = Analog( 1 ),
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "DPad Down",
Target = InputControlType.DPadDown,
Source = Analog( 1 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
},
};
}
}
// @endcond
}
| Java |
#pragma once
#include "Component.h"
#include "Transform.h"
#include "CubeMesh.h"
using namespace Beans;
class PlayerController : public Component, public Utilities::AutoLister<PlayerController>
{
public:
PlayerController(GameObject* owner);
REFLECT_CLASS;
static void UpdatePlayerControllers(double dt);
void Update(double dt);
double speed;
private:
Transform* transform_;
CubeMesh* sprite_;
}; | Java |
package context
import (
"github.com/Everlane/evan/common"
"github.com/satori/go.uuid"
)
// Stores state relating to a deployment.
type Deployment struct {
uuid uuid.UUID
application common.Application
environment string
strategy common.Strategy
ref string
sha1 string
flags map[string]interface{}
store common.Store
// Internal state
currentState common.DeploymentState
currentPhase common.Phase
lastError error
}
// Create a deployment for the given application to an environment.
func NewDeployment(app common.Application, environment string, strategy common.Strategy, ref string, flags map[string]interface{}) *Deployment {
return &Deployment{
uuid: uuid.NewV1(),
application: app,
environment: environment,
strategy: strategy,
ref: ref,
flags: flags,
currentState: common.DEPLOYMENT_PENDING,
}
}
func NewBareDeployment() *Deployment {
return &Deployment{
flags: make(map[string]interface{}),
}
}
func (deployment *Deployment) UUID() uuid.UUID {
return deployment.uuid
}
func (deployment *Deployment) Application() common.Application {
return deployment.application
}
func (deployment *Deployment) Environment() string {
return deployment.environment
}
func (deployment *Deployment) Strategy() common.Strategy {
return deployment.strategy
}
func (deployment *Deployment) Ref() string {
return deployment.ref
}
func (deployment *Deployment) SHA1() string {
return deployment.sha1
}
func (deployment *Deployment) SetSHA1(sha1 string) {
deployment.sha1 = sha1
}
func (deployment *Deployment) MostPreciseRef() string {
if deployment.sha1 != "" {
return deployment.sha1
} else {
return deployment.ref
}
}
func (deployment *Deployment) SetStoreAndSave(store common.Store) error {
deployment.store = store
return store.SaveDeployment(deployment)
}
// Will panic if it is unable to save. This will be called *after*
// `SetStoreAndSave` should have been called, so we're assuming that if that
// worked then this should also work.
func (deployment *Deployment) setStateAndSave(state common.DeploymentState) {
deployment.currentState = state
err := deployment.store.SaveDeployment(deployment)
if err != nil {
panic(err)
}
}
func (deployment *Deployment) Flags() map[string]interface{} {
return deployment.flags
}
func (deployment *Deployment) HasFlag(key string) bool {
_, present := deployment.flags[key]
return present
}
func (deployment *Deployment) Flag(key string) interface{} {
return deployment.flags[key]
}
func (deployment *Deployment) SetFlag(key string, value interface{}) {
deployment.flags[key] = value
}
// Looks for the "force" boolean in the `flags`.
func (deployment *Deployment) IsForce() bool {
if force, ok := deployment.Flag("force").(bool); ok {
return force
} else {
return false
}
}
func (deployment *Deployment) Status() common.DeploymentStatus {
var phase common.Phase
if deployment.currentState == common.RUNNING_PHASE {
phase = deployment.currentPhase
}
return common.DeploymentStatus{
State: deployment.currentState,
Phase: phase,
Error: nil,
}
}
func (deployment *Deployment) CheckPreconditions() error {
deployment.setStateAndSave(common.RUNNING_PRECONDITIONS)
preconditions := deployment.strategy.Preconditions()
for _, precondition := range preconditions {
err := precondition.Status(deployment)
if err != nil {
return err
}
}
return nil
}
// Internal implementation of running phases. Manages setting
// `deployment.currentPhase` to the phase currently executing.
func (deployment *Deployment) runPhases(preloadResults PreloadResults) error {
phases := deployment.strategy.Phases()
for _, phase := range phases {
deployment.currentPhase = phase
preloadResult := preloadResults.Get(phase)
err := phase.Execute(deployment, preloadResult)
if err != nil {
return err
}
}
return nil
}
// Runs all the phases configured in the `Strategy`. Sets `currentState` and
// `currentPhase` fields as appropriate. If an error occurs it will also set
// the `lastError` field to that error.
func (deployment *Deployment) RunPhases() error {
results, err := deployment.RunPhasePreloads()
if err != nil {
deployment.lastError = err
deployment.setStateAndSave(common.DEPLOYMENT_ERROR)
return err
}
deployment.setStateAndSave(common.RUNNING_PHASE)
err = deployment.runPhases(results)
if err != nil {
deployment.lastError = err
deployment.setStateAndSave(common.DEPLOYMENT_ERROR)
return err
} else {
deployment.setStateAndSave(common.DEPLOYMENT_DONE)
return nil
}
}
type preloadResult struct {
data interface{}
err error
}
type PreloadResults map[common.Phase]interface{}
func (results PreloadResults) Get(phase common.Phase) interface{} {
return results[phase]
}
func (results PreloadResults) Set(phase common.Phase, data interface{}) {
results[phase] = data
}
// Phases can expose preloads to gather any additional information they may
// need before executing. This will run those preloads in parallel.
func (deployment *Deployment) RunPhasePreloads() (PreloadResults, error) {
preloadablePhases := make([]common.PreloadablePhase, 0)
for _, phase := range deployment.strategy.Phases() {
if phase.CanPreload() {
preloadablePhases = append(preloadablePhases, phase.(common.PreloadablePhase))
}
}
resultChan := make(chan preloadResult)
for _, phase := range preloadablePhases {
go func() {
data, err := phase.Preload(deployment)
resultChan <- preloadResult{data: data, err: err}
}()
}
results := make(PreloadResults)
for _, phase := range preloadablePhases {
result := <-resultChan
if result.err != nil {
return nil, result.err
} else {
results.Set(phase.(common.Phase), result.data)
}
}
return results, nil
}
| Java |
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Blue Project</title>
<meta name="description" content="Complete Site">
<meta name="author" content="Vassilis Sponis">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/lightbox.css">
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Trykker|Share+Tech' rel='stylesheet' type='text/css'>
</head>
<body>
<!--<div id="wrapper">-->
<header>
<div id="tophead">
<div class="wrapper">
<span id="sub">Subscribe to:</span>
<ul id="sub_list">
<li><a title="Posts" href="#">Posts</a></li>
<li><a title="Comments" href="#">Comments</a></li>
<li><a class="noborder" title="Email" href="#">Email</a></li>
</ul>
<div id="searchform">
<form name="search" action ="" method="">
<input type="text" name="searchvalue" placeholder=" Search Keywords">
<input class="magnglass" type="Submit" value="">
</form>
</div>
<div id="social">
<ul class="social_icons">
<li><a class="rss" title="RSS" href="#"></a></li>
<li><a class="fb" title="Facebook" href="#"></a></li>
<li><a class="tw" title="Twitter" href="#"></a></li>
</ul>
</div>
</div>
</div>
<div id="bothead">
<div class="wrapper">
<h1 id="logo">
<span class="main">Blue Masters</span>
<span class="sub">COMPLETELY UNIQUE WORDPRESS THEME</span>
</h1>
<nav>
<ul>
<li class="nav01"><a class="navi active" title="Home" href="/index.html">Home</a></li>
<li class="nav02"><a class="navi" title="About" href="#">About</a></li>
<li class="nav03"><a class="navi" title="Portfolio" href="#">Portfolio</a></li>
<li class="nav04"><a class="navi" title="Blog" href="OurBlogs.html">Blog</a></li>
<li class="nav05"><a class="navi" title="Contact" href="/contactpage.php">Contact</a></li>
</ul>
</nav>
</div>
</div>
</header>
<!--- END OF HEADER-->
<div id="content">
<div class="wrapper">
<div id="slideshow">
<img src="img/main.jpg" alt="mainpic">
<img src="img/main2.jpg" alt="alt1pic">
<img src="img/main3.jpg" alt="alt2pic">
<img src="img/main4.jpg" alt="alt3pic">
</div>
<div id="slidenav">
<a href="#"><span id="previousbutton"></span></a>
<ul id="pagenavi"></ul>
<a href="#"><span id="nextbutton"></span></a>
</div>
<div id="box">
<div id="boxA" class="mainbox">
<div class="boxhead">
<h3 class="boxhd boxAico">About iPadMasters</h3>
</div>
<div class="innerbox">
<img class="boxpic" src="img/boxApic.jpg" alt="picA">
<h4 class="subhead">All About iPadMasters</h4> <p id="boxAtext" class="textbox">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
<a id="buttonA" class="buttontext" title="Learn More" href="#">Learn More</a>
</div>
</div>
<div id="boxB" class="mainbox">
<div class="boxhead">
<h3 class="boxhd boxBico">Our Blog Updates</h3>
</div>
<div class="innerbox">
<img class="boxpic" src="img/boxBpic.jpg" alt="picB">
<h4 id="MyFirst">
<span class="subhead sechead">My First Website Creation</span>
<span class="textbox secsub">Posted in <a title="Web Design" href="#">Web Design</a> on April 13,2010</span>
</h4>
<p id="boxBtext" class="textbox">Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
<a id="buttonB" class="buttontext" title="Comments" href="#">23 Comments</a>
<a id="buttonC" class="buttontext" title="Read More" href="#">Read More</a>
</div>
</div>
<div id="boxC">
<div class="boxhead">
<h3 class="boxhd boxCico">Get In Touch</h3>
</div>
<div class="innerbox2">
<ul>
<li>
<h4 class="phoneico">
<span class="phoneinfo">
<span class="subhead phonehead">PHONE</span>
<span class="textbox phonetext">1+ (123)456.789</span>
</span>
</h4>
</li>
<li>
<h4 class="emailico">
<span class="phoneinfo">
<span class="subhead phonehead">EMAIL</span>
<span class="textbox phonetext">email@yourdomain.com</span>
</span>
</h4>
</li>
<li>
<h4 class="skypeico">
<span class="phoneinfo">
<span class="subhead phonehead">SKYPE</span>
<span class="textbox phonetext">yourskypename</span>
</span>
</h4>
</li>
<li>
<h4 class="skypeico">
<span class="phoneinfo">
<span class="subhead phonehead">OTHER REQUEST</span>
<span class="textbox phonetext">Try Our Contact Form</span>
</span>
</h4>
</li>
</ul>
</div>
</div>
<div id="boxD">
<ul>
<li>
<a class ="twitter_icon" title="twitter" href="#"></a>
</li>
<li>
<a class ="facebook_icon" title="facebook" href="#"></a>
</li>
<li>
<a class ="flickr_icon" title="flickr" href="#"></a>
</li>
<li>
<a class ="linkedin_icon" title="linkedin" href="#"></a>
</li>
<li>
<a class ="tumblr_icon" title="tumblr" href="#"></a>
</li>
<li>
<a class ="youtube_icon" title="youtube" href="#"></a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div id="info">
<div class="wrapper">
<div id="about">
<h4 class="head">About Us</h4>
<br>
<ul>
<li><a class="listlinks" href="#">Our Company</a></li>
<li><a class="listlinks" href="#">Our Blog</a></li>
<li><a class="listlinks" href="#">Submit A Site</a></li>
<li><a class="listlinks" href="#">Contact Us</a></li>
<li><a class="listlinks" href="#">Help & Terms</a></li>
<li><a class="listlinks" href="#">Read Our FAQ</a></li>
</ul>
</div>
<div id="Categories">
<h4 class="head">Categories</h4>
<br>
<ul>
<li><a class="listlinks" href="#">Trends & Technology</a></li>
<li><a class="listlinks" href="#">Desigh Companies</a></li>
<li><a class="listlinks" href="#">Design Freelancers</a></li>
<li><a class="listlinks" href="#">Web Portfolios</a></li>
<li><a class="listlinks" href="#">Web Development</a></li>
<li><a class="listlinks" href="#">General Icons</a></li>
</ul>
</div>
<div id="Gallery">
<h4 class="head">From The Gallery</h4>
<br>
<table id="photos">
<tr>
<td><a href="/img/gall01.jpg" data-lightbox="gallery" title="Image 01"><img src="img/gall01.jpg" alt="img01"></a></td>
<td><a href="/img/gall02.jpg" data-lightbox="gallery" title="Image 02"><img src="img/gall02.jpg" alt="img02"></a></td>
<td><a href="/img/gall03.jpg" data-lightbox="gallery" title="Image 03"><img src="img/gall03.jpg" alt="img03"></a></td>
<td><a href="/img/gall04.jpg" data-lightbox="gallery" title="Image 04"><img src="img/gall04.jpg" alt="img04"></a></td>
</tr>
<tr>
<td><a href="/img/gall05.jpg" data-lightbox="gallery" title="Image 05"><img src="img/gall05.jpg" alt="img05"></a></td>
<td><a href="/img/gall06.jpg" data-lightbox="gallery" title="Image 06"><img src="img/gall06.jpg" alt="img06"></a></td>
<td><a href="/img/gall07.jpg" data-lightbox="gallery" title="Image 07"><img src="img/gall07.jpg" alt="img07"></a></td>
<td><a href="/img/gall08.jpg" data-lightbox="gallery" title="Image 08"><img src="img/gall08.jpg" alt="img08"></a></td>
</tr>
</table>
</div>
<div id="twupdates">
<h4 class="head">Twitter Updates</h4>
<div id="example1"></div>
</div>
</div>
</div>
<footer>
<div class="wrapper">
<p id="copyright">© 2010 Copyright iPadMasters Theme. All Rights Reserved.</p>
<div id="links">
<ul>
<li><a href="#">Log In</a></li>
<li><a href="#">Privacy Policy</a></li>
<li><a href="#">Terms and Conditions</a></li>
<li><a href="#">Contact Us</a></li>
<li><a class="noborder" href="#">Back to Top</a></li>
</ul>
</div>
</div>
</footer>
<script src="js/vendor/jquery-1.10.2.min.js"></script>
<script src="js/vendor/lightbox-2.6.min.js"></script>
<script src="js/vendor/twitterFetcher_v10_min.js"></script>
<script src="js/vendor/jquery.cycle.all.js"></script>
<script src="js/main.js"></script>
</body>
</html>
| Java |
window.Lunchiatto.module('Transfer', function(Transfer, App, Backbone, Marionette, $, _) {
return Transfer.Layout = Marionette.LayoutView.extend({
template: 'transfers/layout',
ui: {
receivedTransfers: '.received-transfers',
submittedTransfers: '.submitted-transfers'
},
behaviors: {
Animateable: {
types: ['fadeIn']
},
Titleable: {}
},
regions: {
receivedTransfers: '@ui.receivedTransfers',
submittedTransfers: '@ui.submittedTransfers'
},
onRender() {
this._showTransfers('received');
this._showTransfers('submitted');
},
_showTransfers(type) {
const transfers = new App.Entities.Transfers([], {type});
transfers.optionedFetch({
success: transfers => {
App.getUsers().then(() => {
const view = new App.Transfer.List({
collection: transfers});
this[`${type}Transfers`].show(view);
});
}
});
},
_htmlTitle() {
return 'Transfers';
}
});
});
| Java |
body {
font-family: Arial, Verdana, "Times New Roman", Times, serif;
}
div.pages {
font-weight: bold;
}
a.page, span.page {
padding: 4px 6px;
}
a.page {
margin: 0 3px;
border: 1px solid #ddd;
text-decoration: none;
color: #0063dc;
}
a.page:hover {
border: 1px solid #003366;
background-color: #0063dc;
color: #fff;
}
span.disabled_page {
color: #b1aab1;
}
span.current_page {
color: #ff0084;
} | Java |
---
layout: post
title: "Leetcode (48, 64, 542) Matrix Series"
category: Leetcode
tags: Leetcode
---
* content
{:toc}
Leetcode Matrix Series
## Leetcode 48. Rotate Image
* [Leetcode 48. Rotate Image](https://leetcode.com/problems/rotate-image/#/description)
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
```cpp
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
if (matrix.empty()) return;
const int n = matrix.size();
for (int i=0; i<n; i++)
for (int j=0; j<i; j++)
swap(matrix[i][j], matrix[j][i]);
for (int j=0; j<n/2; j++)
for (int i=0; i<n; i++)
swap(matrix[i][j], matrix[i][n-1-j]);
}
};
```
## Leetcode 64. Minimum Path Sum
* [Leetcode 64. Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/#/description)
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
```cpp
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
for (int i=0; i<grid.size(); i++)
for (int j=0; j<grid[0].size(); j++) {
if (i==0 && j==0) continue;
else grid[i][j] = min((i-1>=0 ?grid[i-1][j]:INT_MAX), (j-1>=0?grid[i][j-1]:INT_MAX))+grid[i][j];
}
return grid.back().back();
}
};
```
## Leetcode 542. 01 Matrix
* [Leetcode 542. 01 Matrix](https://leetcode.com/problems/01-matrix/#/description)
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example 1:
Input:
```
0 0 0
0 1 0
0 0 0
```
Output:
```
0 0 0
0 1 0
0 0 0
```
Example 2:
Input:
```
0 0 0
0 1 0
1 1 1
```
Output:
```
0 0 0
0 1 0
1 2 1
```
Note:
* The number of elements of the given matrix will not exceed 10,000.
* There are at least one 0 in the given matrix.
* The cells are adjacent in only four directions: up, down, left and right.
```cpp
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
const int n = matrix.size();
const int m = matrix[0].size();
typedef pair<int, int> p;
queue<p> q;
vector<vector<int>> ans(n, vector<int>(m, 0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
if (matrix[i][j] == 1)
ans[i][j] = -1;
else
q.push(p(i, j));
}
p direct[4] = {p(-1, 0), p(1,0),p(0,1), p(0, -1)};
while (q.size() > 0) {
p temp = q.front();
for (int i = 0; i < 4; i++) {
int x = temp.first+direct[i].first;
int y = temp.second+direct[i].second;
if (x>=0 && x<n && y>=0 && y<m)
if (ans[x][y] == -1) {
ans[x][y] = ans[temp.first][temp.second]+1;
q.push(p(x, y));
}
}
q.pop();
}
return ans;
}
};
``` | Java |
package analytics
import (
"fmt"
elastic "gopkg.in/olivere/elastic.v3"
)
//Elasticsearch stores configuration related to the AWS elastic cache isntance.
type Elasticsearch struct {
URL string
IndexName string
DocType string
client *elastic.Client
}
//Initialize initializes the analytics engine.
func (e *Elasticsearch) Initialize() error {
client, err := elastic.NewSimpleClient(elastic.SetURL(e.URL))
if err != nil {
return err
}
e.client = client
s := e.client.IndexExists(e.IndexName)
exists, err := s.Do()
if err != nil {
return err
}
if !exists {
s := e.client.CreateIndex(e.IndexName)
_, err := s.Do()
if err != nil {
return err
}
}
return nil
}
//SendAnalytics is used to send the data to the analytics engine.
func (e *Elasticsearch) SendAnalytics(data string) error {
fmt.Println(data)
_, err := e.client.Index().Index(e.IndexName).Type(e.DocType).BodyJson(data).Do()
if err != nil {
return err
}
return nil
}
| Java |
'use strict';
var i18n = require('./i18n.js')
i18n.add_translation("pt-BR", {
test: 'OK',
greetings: {
hello: 'Olá',
welcome: 'Bem vindo'
}
});
i18n.locale = 'pt-BR';
console.log(i18n.t('greetings.hello'));
console.log(i18n.t('greetings.welcome'));
console.log("Hallo");
// Example 2
i18n.add_translation("pt-BR", {
greetings: {
hello: 'Olá',
welcome: 'Bem vindo'
}
});
console.log(i18n.t('greetings.hello'));
i18n.add_translation("pt-BR", {
test: 'OK',
greetings: {
hello: 'Oi',
bye: 'Tchau'
}
});
console.log(i18n.t('greetings.hello'));
console.log(i18n.t('test'));
| Java |
/**
* @flow
*/
/* eslint-disable */
'use strict';
/*::
import type { ReaderFragment } from 'relay-runtime';
export type ReactionContent = "CONFUSED" | "EYES" | "HEART" | "HOORAY" | "LAUGH" | "ROCKET" | "THUMBS_DOWN" | "THUMBS_UP" | "%future added value";
import type { FragmentReference } from "relay-runtime";
declare export opaque type emojiReactionsView_reactable$ref: FragmentReference;
declare export opaque type emojiReactionsView_reactable$fragmentType: emojiReactionsView_reactable$ref;
export type emojiReactionsView_reactable = {|
+id: string,
+reactionGroups: ?$ReadOnlyArray<{|
+content: ReactionContent,
+viewerHasReacted: boolean,
+users: {|
+totalCount: number
|},
|}>,
+viewerCanReact: boolean,
+$refType: emojiReactionsView_reactable$ref,
|};
export type emojiReactionsView_reactable$data = emojiReactionsView_reactable;
export type emojiReactionsView_reactable$key = {
+$data?: emojiReactionsView_reactable$data,
+$fragmentRefs: emojiReactionsView_reactable$ref,
};
*/
const node/*: ReaderFragment*/ = {
"kind": "Fragment",
"name": "emojiReactionsView_reactable",
"type": "Reactable",
"metadata": null,
"argumentDefinitions": [],
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "id",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "reactionGroups",
"storageKey": null,
"args": null,
"concreteType": "ReactionGroup",
"plural": true,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "content",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "viewerHasReacted",
"args": null,
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"name": "users",
"storageKey": null,
"args": null,
"concreteType": "ReactingUserConnection",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "totalCount",
"args": null,
"storageKey": null
}
]
}
]
},
{
"kind": "ScalarField",
"alias": null,
"name": "viewerCanReact",
"args": null,
"storageKey": null
}
]
};
// prettier-ignore
(node/*: any*/).hash = 'fde156007f42d841401632fce79875d5';
module.exports = node;
| Java |
require 'bio-ucsc'
describe "Bio::Ucsc::Hg19::WgEncodeAffyRnaChipFiltTransfragsKeratinocyteCytosolLongnonpolya" do
describe "#find_by_interval" do
context "given range chr1:1-100,000" do
it "returns an array of results" do
Bio::Ucsc::Hg19::DBConnection.default
Bio::Ucsc::Hg19::DBConnection.connect
i = Bio::GenomicInterval.parse("chr1:1-100,000")
r = Bio::Ucsc::Hg19::WgEncodeAffyRnaChipFiltTransfragsKeratinocyteCytosolLongnonpolya.find_all_by_interval(i)
r.should have(1).items
end
it "returns an array of results with column accessors" do
Bio::Ucsc::Hg19::DBConnection.default
Bio::Ucsc::Hg19::DBConnection.connect
i = Bio::GenomicInterval.parse("chr1:1-100,000")
r = Bio::Ucsc::Hg19::WgEncodeAffyRnaChipFiltTransfragsKeratinocyteCytosolLongnonpolya.find_by_interval(i)
r.chrom.should == "chr1"
end
end
end
end
| Java |
# EETetris
EETetris, a monogame application to play tetris in a style that looks like EE. Based off of an EE world ( PWNLqCFExbbUI )
# How to play
1) Download it from the releases
2) Know your hotkeys
To make the tetris piece move left/right,
<-- A | D --> (Arrow keys apply)
To rotate the piece left ( 90 degrees counterclockwise )
Q
To rotate the piece right ( 90 degrees clockwise )
E
To convert the board from BETA style to BASIC stlye,
L
To swap out the piece on the board for your held piece,
C
To instant drop
SPACE
To fastly drop
S | Java |
<!doctype html>
<html>
<head>
<title>Code coverage report for wizard/test/wizardSpecs.js</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="content-language" content="en-gb">
<link rel='stylesheet' href='../../prettify.css'>
<style type='text/css'>
body, html {
margin:0; padding: 0;
}
body {
font-family: "Helvetic Neue", Helvetica,Arial;
font-size: 10pt;
}
div.header, div.footer {
background: #eee;
padding: 1em;
}
div.header {
z-index: 100;
position: fixed;
top: 0;
border-bottom: 1px solid #666;
width: 100%;
}
div.footer {
border-top: 1px solid #666;
}
div.body {
margin-top: 10em;
}
div.meta {
font-size: 90%;
text-align: center;
}
h1, h2, h3 {
font-weight: normal;
}
h1 {
font-size: 12pt;
}
h2 {
font-size: 10pt;
}
pre {
font-family: consolas, menlo, monaco, monospace;
margin: 0;
padding: 0;
line-height: 14px;
font-size: 14px;
}
div.path { font-size: 110%; }
div.path a:link, div.path a:visited { color: #000; }
table.coverage { border-collapse: collapse; margin:0; padding: 0 }
table.coverage td {
margin: 0;
padding: 0;
color: #111;
vertical-align: top;
}
table.coverage td.line-count {
width: 50px;
text-align: right;
padding-right: 5px;
}
table.coverage td.line-coverage {
color: #777 !important;
text-align: right;
border-left: 1px solid #666;
border-right: 1px solid #666;
}
table.coverage td.text {
}
table.coverage td span.cline-any {
display: inline-block;
padding: 0 5px;
width: 40px;
}
table.coverage td span.cline-neutral {
background: #eee;
}
table.coverage td span.cline-yes {
background: #b5d592;
color: #999;
}
table.coverage td span.cline-no {
background: #fc8c84;
}
.cstat-yes { color: #111; }
.cstat-no { background: #fc8c84; color: #111; }
.fstat-no { background: #ffc520; color: #111 !important; }
.cbranch-no { background: yellow !important; color: #111; }
.missing-if-branch {
display: inline-block;
margin-right: 10px;
position: relative;
padding: 0 4px;
background: black;
color: yellow;
xtext-decoration: line-through;
}
.missing-if-branch .typ {
color: inherit !important;
}
.entity, .metric { font-weight: bold; }
.metric { display: inline-block; border: 1px solid #333; padding: 0.3em; background: white; }
.metric small { font-size: 80%; font-weight: normal; color: #666; }
div.coverage-summary table { border-collapse: collapse; margin: 3em; font-size: 110%; }
div.coverage-summary td, div.coverage-summary table th { margin: 0; padding: 0.25em 1em; border-top: 1px solid #666; border-bottom: 1px solid #666; }
div.coverage-summary th { text-align: left; border: 1px solid #666; background: #eee; font-weight: normal; }
div.coverage-summary th.file { border-right: none !important; }
div.coverage-summary th.pic { border-left: none !important; text-align: right; }
div.coverage-summary th.pct { border-right: none !important; }
div.coverage-summary th.abs { border-left: none !important; text-align: right; }
div.coverage-summary td.pct { text-align: right; border-left: 1px solid #666; }
div.coverage-summary td.abs { text-align: right; font-size: 90%; color: #444; border-right: 1px solid #666; }
div.coverage-summary td.file { text-align: right; border-left: 1px solid #666; white-space: nowrap; }
div.coverage-summary td.pic { min-width: 120px !important; }
div.coverage-summary a:link { text-decoration: none; color: #000; }
div.coverage-summary a:visited { text-decoration: none; color: #333; }
div.coverage-summary a:hover { text-decoration: underline; }
div.coverage-summary tfoot td { border-top: 1px solid #666; }
div.coverage-summary .yui3-datatable-sort-indicator, div.coverage-summary .dummy-sort-indicator {
height: 10px;
width: 7px;
display: inline-block;
margin-left: 0.5em;
}
div.coverage-summary .yui3-datatable-sort-indicator {
background: url("http://yui.yahooapis.com/3.6.0/build/datatable-sort/assets/skins/sam/sort-arrow-sprite.png") no-repeat scroll 0 0 transparent;
}
div.coverage-summary .yui3-datatable-sorted .yui3-datatable-sort-indicator {
background-position: 0 -20px;
}
div.coverage-summary .yui3-datatable-sorted-desc .yui3-datatable-sort-indicator {
background-position: 0 -10px;
}
.high { background: #b5d592 !important; }
.medium { background: #ffe87c !important; }
.low { background: #fc8c84 !important; }
span.cover-fill, span.cover-empty {
display:inline-block;
border:1px solid #444;
background: white;
height: 12px;
}
span.cover-fill {
background: #ccc;
border-right: 1px solid #444;
}
span.cover-empty {
background: white;
border-left: none;
}
span.cover-full {
border-right: none !important;
}
pre.prettyprint {
border: none !important;
padding: 0 !important;
margin: 0 !important;
}
.com { color: #999 !important; }
</style>
</head>
<body>
<div class='header high'>
<h1>Code coverage report for <span class='entity'>wizard/test/wizardSpecs.js</span></h1>
<h2>
Statements: <span class='metric'>100% <small>(91 / 91)</small></span>
Branches: <span class='metric'>100% <small>(0 / 0)</small></span>
Functions: <span class='metric'>100% <small>(22 / 22)</small></span>
Lines: <span class='metric'>100% <small>(91 / 91)</small></span>
</h2>
<div class="path"><a href="../../index.html">All files</a> » <a href="index.html">wizard/test/</a> » wizardSpecs.js</div>
</div>
<div class='body'>
<pre><table class="coverage">
<tr><td class="line-count">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159</td><td class="line-coverage"><span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">6</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">6</span>
<span class="cline-any cline-yes">6</span>
<span class="cline-any cline-yes">6</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">6</span>
<span class="cline-any cline-yes">6</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">4</span>
<span class="cline-any cline-yes">4</span>
<span class="cline-any cline-yes">4</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">5</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-yes">1</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span></td><td class="text"><pre class="prettyprint lang-js">describe('The Wizard Module', function(){
beforeEach(module('wizard'));
describe('The Wizard Directive', function(){
var elm, scope, headings, panes;
beforeEach(module('template/wizard/wizard.html'));
beforeEach(module('template/wizard/pane.html'));
beforeEach(module('wizard'));
beforeEach(inject(function($compile, $rootScope){
elm = angular.element(
'<wizard>' +
'<pane heading="Step 1">' +
'Content 1' +
'</pane>' +
'<pane heading="Step 2">' +
'Content 2' +
'</pane>' +
'</wizard>');
scope = $rootScope;
$compile(elm)(scope);
scope.$digest();
headings = elm.find('ul.steps li a')
panes = elm.find('div.panes .pane');
}));
it('should be a element with "wizard" class', function(){
expect(elm).toHaveClass('wizard');
});
it('should create clickable steps with their heading text in the navigation', function(){
expect(headings.length).toBe(2);
expect(headings.eq(0).text()).toBe('Step 1');
expect(headings.eq(1).text()).toBe('Step 2');
});
it('should bind the content', function() {
expect(panes.length).toBe(2);
expect(panes.eq(0).text()).toBe('Content 1');
expect(panes.eq(1).text()).toBe('Content 2');
});
it('shoud activate the first step', function() {
expect(headings.parent().eq(0)).toHaveClass('active');
expect(panes.eq(0)).toHaveClass('active');
expect(headings.parent().eq(1)).not.toHaveClass('active');
expect(panes.eq(1)).not.toHaveClass('active');
});
it('should activate the next step', function(){
elm.find('.btn-next').click();
expect(headings.parent().eq(1)).toHaveClass('active');
expect(panes.eq(1)).toHaveClass('active');
expect(headings.parent().eq(0)).toHaveClass('complete');
expect(panes.eq(0)).toHaveClass('complete');
});
it('should activate the prev step', function(){
elm.find('.btn-next').click();
elm.find('.btn-prev').click();
expect(headings.parent().eq(0)).toHaveClass('active');
expect(panes.eq(0)).toHaveClass('active');
expect(headings.parent().eq(1)).not.toHaveClass('active');
expect(panes.eq(1)).not.toHaveClass('active');
});
});
describe('The Wizard Controller', function(){
var ctrl, wizardScope, firstStep;
beforeEach(inject(function($controller, $rootScope, Step) {
ctrl = $controller('WizardCtrl', {$scope: wizardScope = $rootScope});
firstStep = new Step();
ctrl.addStep(firstStep);
}));
it('shoud add a child step scope to the wizardScope', inject(function($rootScope){
expect(wizardScope.steps).toBeDefined();
expect(wizardScope.steps.length).toBe(1);
}));
it('should set the first step as active', function(){
expect(firstStep.status).toBe('active');
});
it('should advance to next step', inject(function(Step){
var secondStep = new Step();
ctrl.addStep(secondStep);
ctrl.nextStep();
expect(firstStep.status).toBe('complete');
expect(secondStep.status).toBe('active');
}));
it('should back to previous step', inject(function(Step){
var secondStep = new Step(),
thirdStep = new Step();
ctrl.addStep(secondStep);
ctrl.addStep(thirdStep);
ctrl.nextStep();
ctrl.nextStep();
expect(secondStep.status).toBe('complete');
expect(thirdStep.status).toBe('active');
ctrl.prevStep();
expect(secondStep.status).toBe('active');
expect(thirdStep.status).toBeUndefined();
}));
});
describe('The Step Factory', function(){
var step;
beforeEach(inject(function(Step){
step = new Step('Heading One');
}));
it('should have a heading', function(){
expect(step.heading).toBe('Heading One');
});
it('should be initialized with undefined status', function(){
expect(step.status).toBeUndefined();
});
it('should became active', function(){
step.activate();
expect(step.status).toBe('active');
});
it('should became complete', function(){
step.complete();
expect(step.status).toBe('complete');
});
it('should revert his status', function(){
step.activate();
step.reset();
expect(step.status).toBeUndefined();
step.complete();
step.activate();
expect(step.status).toBe('active');
});
});
});</pre></td></tr>
</table></pre>
</div>
<div class='footer'>
<div class='meta'>Generated by <a href='http://istanbul-js.org' target='_blank'>istanbul</a> at Wed Mar 13 2013 08:34:08 GMT-0300 (BRT)</div>
</div>
</body>
<script src="../../prettify.js"></script>
<script src="http://yui.yahooapis.com/3.6.0/build/yui/yui-min.js"></script>
<script>
YUI().use('datatable', function (Y) {
var formatters = {
pct: function (o) {
o.className += o.record.get('classes')[o.column.key];
try {
return o.value.toFixed(2) + '%';
} catch (ex) { return o.value + '%'; }
},
html: function (o) {
o.className += o.record.get('classes')[o.column.key];
return o.record.get(o.column.key + '_html');
}
},
defaultFormatter = function (o) {
o.className += o.record.get('classes')[o.column.key];
return o.value;
};
function getColumns(theadNode) {
var colNodes = theadNode.all('tr th'),
cols = [],
col;
colNodes.each(function (colNode) {
col = {
key: colNode.getAttribute('data-col'),
label: colNode.get('innerHTML') || ' ',
sortable: !colNode.getAttribute('data-nosort'),
className: colNode.getAttribute('class'),
type: colNode.getAttribute('data-type'),
allowHTML: colNode.getAttribute('data-html') === 'true' || colNode.getAttribute('data-fmt') === 'html'
};
col.formatter = formatters[colNode.getAttribute('data-fmt')] || defaultFormatter;
cols.push(col);
});
return cols;
}
function getRowData(trNode, cols) {
var tdNodes = trNode.all('td'),
i,
row = { classes: {} },
node,
name;
for (i = 0; i < cols.length; i += 1) {
name = cols[i].key;
node = tdNodes.item(i);
row[name] = node.getAttribute('data-value') || node.get('innerHTML');
row[name + '_html'] = node.get('innerHTML');
row.classes[name] = node.getAttribute('class');
//Y.log('Name: ' + name + '; Value: ' + row[name]);
if (cols[i].type === 'number') { row[name] = row[name] * 1; }
}
//Y.log(row);
return row;
}
function getData(tbodyNode, cols) {
var data = [];
tbodyNode.all('tr').each(function (trNode) {
data.push(getRowData(trNode, cols));
});
return data;
}
function replaceTable(node) {
if (!node) { return; }
var cols = getColumns(node.one('thead')),
data = getData(node.one('tbody'), cols),
table,
parent = node.get('parentNode');
table = new Y.DataTable({
columns: cols,
data: data,
sortBy: 'file'
});
parent.set('innerHTML', '');
table.render(parent);
}
Y.on('domready', function () {
replaceTable(Y.one('div.coverage-summary table'));
if (typeof prettyPrint === 'function') {
prettyPrint();
}
});
});
</script>
</html>
| Java |
require File.expand_path("../../../test_helper", __FILE__)
describe Redcarpet::Render::HTMLAbbreviations do
before do
@renderer = Class.new do
include Redcarpet::Render::HTMLAbbreviations
end
end
describe "#preprocess" do
it "converts markdown abbrevations to HTML" do
markdown = <<-EOS.strip_heredoc
YOLO
*[YOLO]: You Only Live Once
EOS
@renderer.new.preprocess(markdown).must_equal <<-EOS.strip_heredoc.chomp
<abbr title="You Only Live Once">YOLO</abbr>
EOS
end
it "converts hyphenated abbrevations to HTML" do
markdown = <<-EOS.strip_heredoc
JSON-P
*[JSON-P]: JSON with Padding
EOS
@renderer.new.preprocess(markdown).must_equal <<-EOS.strip_heredoc.chomp
<abbr title="JSON with Padding">JSON-P</abbr>
EOS
end
it "converts abbrevations with numbers to HTML" do
markdown = <<-EOS.strip_heredoc
ES6
*[ES6]: ECMAScript 6
EOS
@renderer.new.preprocess(markdown).must_equal <<-EOS.strip_heredoc.chomp
<abbr title="ECMAScript 6">ES6</abbr>
EOS
end
end
describe "#acronym_regexp" do
it "matches an acronym at the beginning of a line" do
"FOO bar".must_match @renderer.new.acronym_regexp("FOO")
end
it "matches an acronym at the end of a line" do
"bar FOO".must_match @renderer.new.acronym_regexp("FOO")
end
it "matches an acronym next to punctuation" do
".FOO.".must_match @renderer.new.acronym_regexp("FOO")
end
it "matches an acronym with hyphens" do
"JSON-P".must_match @renderer.new.acronym_regexp("JSON-P")
end
it "doesn't match an acronym in the middle of a word" do
"YOLOFOOYOLO".wont_match @renderer.new.acronym_regexp("FOO")
end
it "matches numbers" do
"ES6".must_match @renderer.new.acronym_regexp("ES6")
end
end
end
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.