answer
stringlengths 15
1.25M
|
|---|
/* Accordion directive */
app.directive('<API key>', ['$compile', function($compile) {
return {
restrict: 'EA',
scope: {
type: '@',
headers: '=',
accData: '=',
selAcc: '=',
customClass:'='
},
link: function(scope, elem, attrs) {
var template;
if(scope.type === '1') {
template = '<table class="<API key>"><thead class="<API key>"><tr><td class="col1"></td>';
var count = 1;
angular.forEach(scope.headers, function(item) {
// template += '<td colspan="2">' + item + '</td>';
// else {
template += '<td class="col' + (count + 1) +'">' + item + '</td>';
count += 1;
});
template += '</tr></thead><tbody class="<API key>">';
scope.accordionIndex = 0;
angular.forEach(scope.accData, function(item) {
template += '<tr class="<API key>" ng-click="toggleAccordion(' + scope.accordionIndex + ')"><td ><span class="vmf-arrow"></span></td><td colspan="3">' + item.header + '</td></tr>';
angular.forEach(item.contents, function(content) {
template += '<tr class="vmf-accordion-row" ng-show="activeIndex =='+ scope.accordionIndex + '"><td colspan="1"></td>';
angular.forEach(content, function(cellData) {
template += '<td colspan="1">' + cellData + '</td>';
});
template += '</tr>';
});
scope.accordionIndex += 1;
});
template += '</tbody></table>';
elem.append(template);
// console.log(template);
$compile(elem.contents())(scope);
// for IE7
elem.find('.vmf-accordion-row').hide();
}
else if(scope.type === '2') {
template = '<table class="<API key>"><thead class="<API key>" style="background-color: lightgray;"><tr><td class="col1"></td>';
var headerCount = 0;
angular.forEach(scope.headers, function(item) {
if(headerCount !== scope.headers.length - 1) {
template += '<td class="col' + (headerCount + 1 + 1)+ '">' + item + '</td>';
}
else {
template += '<td colspan="2" class="col' + (headerCount + 1 + 1)+ '">' + item + '</td>';
}
headerCount += 1;
});
template += '</tr></thead><tbody class="<API key>">';
scope.accordionIndex = 0;
angular.forEach(scope.accData, function(item) {
template += '<tr class="<API key>" ng-click="toggleAccordion(' + scope.accordionIndex + ')"><td><span class="vmf-arrow"></span></td>';
var accHeadersCount = 1;
angular.forEach(item.headers, function(header) {
if(accHeadersCount !== item.headers.length) {
template += '<td>' + header + '</td>';
}
else {
template += '<td class="<API key>">' + header + '</td>';
}
accHeadersCount += 1;
});
template += '</tr><tr class="vmf-accordion-row2"><td></td><td class="<API key>" colspan="' + item.headers.length + '"><table class="<API key>" ng-show="activeIndex =='+ scope.accordionIndex + '">';
var count = 0;
angular.forEach(item.contents, function(content) {
if(count !== 0) {
template += '<tr class="<API key>">';
angular.forEach(content, function(cellData) {
template += '<td>' + cellData + '</td>';
});
template += '</tr>';
}
else {
template += '<thead class="<API key>"><tr>';
var subHeaderCount = 1;
angular.forEach(content, function(cellData) {
template += '<td class="col' + subHeaderCount + '">' + cellData + '</td>';
subHeaderCount += 1;
});
template += '</tr></thead><tbody class="<API key>">';
}
count += 1;
});
template += '</tbody></table></td></tr>';
scope.accordionIndex += 1;
});
template += '</tbody></table>';
elem.append(template);
// console.log(template);
if(scope.customClass){
angular.forEach(scope.customClass, function(item) {
elem.find(item.selector).addClass(item.cusclass);
});
}
$compile(elem.contents())(scope);
// for IE7
elem.find('.vmf-accordion-row2').hide();
// elem.find('.vmf-accordion-row2').hide();
}
scope.toggleAccordion = function(index) {
scope.activeIndex = scope.activeIndex === index ? -1 : index;
var accordions, accordionRows;
if(scope.type === '1') {
elem.find('.vmf-accordion-row').hide();
accordions = elem.find('.<API key>');
accordions.removeClass('vmf-active-row');
// for IE7
if(scope.activeIndex !== -1) {
// accordions = elem.find('.<API key>');
// console.log(accordions[index]);
$(accordions[index]).addClass('vmf-active-row');
accordionRows = $(accordions[index]).nextUntil('.<API key>');
$(accordionRows).show();
}
}
else if(scope.type === '2') {
elem.find('.vmf-accordion-row2').hide();
accordions = elem.find('.<API key>');
accordions.removeClass('vmf-active-row');
// for IE7
if(scope.activeIndex !== -1) {
$(accordions[index]).addClass('vmf-active-row');
accordionRows = $(accordions[index]).nextUntil('.<API key>');
$(accordionRows).show();
}
}
};
scope.buttonClick = function($event, index) {
$event.stopPropagation();
scope.selAcc = index;
};
}
};
}]);
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.comci.bigbib;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.bson.types.ObjectId;
import org.codehaus.jackson.annotate.JsonProperty;
import org.jbibtex.BibTeXEntry;
import org.jbibtex.Key;
import org.jbibtex.StringValue;
import org.jbibtex.Value;
/**
*
* @author Sebastian
*/
@XmlRootElement()
@XmlAccessorType(XmlAccessType.NONE)
public class <API key> extends BibTeXEntry {
private ObjectId id;
public <API key>(Key type, Key key) {
super(type, key);
}
static Map<String, Key> keyMapping = new HashMap<String, Key>();
static {
keyMapping.put("address", BibTeXEntry.KEY_ADDRESS);
keyMapping.put("annote", BibTeXEntry.KEY_ANNOTE);
keyMapping.put("author", BibTeXEntry.KEY_AUTHOR);
keyMapping.put("booktitle", BibTeXEntry.KEY_BOOKTITLE);
keyMapping.put("chapter", BibTeXEntry.KEY_CHAPTER);
keyMapping.put("crossref", BibTeXEntry.KEY_CROSSREF);
keyMapping.put("doi", BibTeXEntry.KEY_DOI);
keyMapping.put("edition", BibTeXEntry.KEY_EDITION);
keyMapping.put("editor", BibTeXEntry.KEY_EDITOR);
keyMapping.put("eprint", BibTeXEntry.KEY_EPRINT);
keyMapping.put("howpublished", BibTeXEntry.KEY_HOWPUBLISHED);
keyMapping.put("institution", BibTeXEntry.KEY_INSTITUTION);
keyMapping.put("journal", BibTeXEntry.KEY_JOURNAL);
keyMapping.put("key", BibTeXEntry.KEY_KEY);
keyMapping.put("month", BibTeXEntry.KEY_MONTH);
keyMapping.put("note", BibTeXEntry.KEY_NOTE);
keyMapping.put("number", BibTeXEntry.KEY_NUMBER);
keyMapping.put("organization", BibTeXEntry.KEY_ORGANIZATION);
keyMapping.put("pages", BibTeXEntry.KEY_PAGES);
keyMapping.put("publisher", BibTeXEntry.KEY_PUBLISHER);
keyMapping.put("school", BibTeXEntry.KEY_SCHOOL);
keyMapping.put("series", BibTeXEntry.KEY_SERIES);
keyMapping.put("title", BibTeXEntry.KEY_TITLE);
keyMapping.put("type", BibTeXEntry.KEY_TYPE);
keyMapping.put("url", BibTeXEntry.KEY_URL);
keyMapping.put("volume", BibTeXEntry.KEY_VOLUME);
keyMapping.put("year", BibTeXEntry.KEY_YEAR);
}
public <API key>(DBObject persistentObject) {
super(
new Key((String) persistentObject.get("type")),
new Key((String) persistentObject.get("key"))
);
BasicDBObject fields = (BasicDBObject) persistentObject.get("fields");
id = (ObjectId) persistentObject.get("_id");
for (String key : fields.keySet()) {
if (keyMapping.containsKey(key)) {
this.addField(keyMapping.get(key), new StringValue(fields.getString(key), StringValue.Style.BRACED));
} else {
this.addField(new Key(key), new StringValue(fields.getString(key), StringValue.Style.BRACED));
}
}
}
@JsonProperty("id")
@XmlElement(name="id")
public String getStringId() {
return id.toString();
}
@JsonProperty("key")
@XmlElement(name="key")
public String getStringKey() {
return super.getKey().getValue();
}
@JsonProperty("type")
@XmlElement(name="type")
public String getStringType() {
return super.getType().getValue();
}
@JsonProperty("fields")
@XmlElement(name="fields")
public Map<String, String> getStringFields() {
Map<String, String> fields = new HashMap<String, String>();
for (Entry<Key,Value> e : getFields().entrySet()) {
if (e.getKey() != null && e.getValue() != null) {
fields.put(e.getKey().getValue(), e.getValue().toUserString());
}
}
return fields;
}
@Override
public String toString() {
return String.format("[%s:%s] %s: %s (%s)",
this.getType(),
this.getKey(),
this.getField(KEY_AUTHOR).toUserString(),
this.getField(KEY_TITLE).toUserString(),
this.getField(KEY_YEAR).toUserString());
}
}
|
module Admin::BaseHelper
include ActionView::Helpers::DateHelper
def subtabs_for(current_module)
output = []
AccessControl.project_module(current_user.profile.label, current_module).submenus.each_with_index do |m,i|
current = (m.url[:controller] == params[:controller] && m.url[:action] == params[:action]) ? "current" : ""
output << subtab(_(m.name), current, m.url)
end
content_for(:tasks) { output.join("\n") }
end
def subtab(label, style, options = {})
content_tag :li, link_to(label, options, { "class"=> style })
end
def show_page_heading
content_tag(:h2, @page_heading, :class => 'mb20') unless @page_heading.blank?
end
def cancel(url = {:action => 'index'})
link_to _("Cancel"), url
end
def save(val = _("Store"))
'<input type="submit" value="' + val + '" class="save" />'
end
def confirm_delete(val = _("Delete"))
'<input type="submit" value="' + val + '" />'
end
def link_to_show(record, controller = @controller.controller_name)
if record.published?
link_to image_tag('admin/show.png', :alt => _("show"), :title => _("Show content")),
{:controller => controller, :action => 'show', :id => record.id},
{:class => "lbOn"}
end
end
def link_to_edit(label, record, controller = @controller.controller_name)
link_to label, :controller => controller, :action => 'edit', :id => record.id
end
def <API key>(label, record, controller = @controller.controller_name)
if current_user.admin? || current_user.id == record.user_id
link_to label, :controller => controller, :action => 'edit', :id => record.id
end
end
def link_to_destroy(record, controller = @controller.controller_name)
link_to image_tag('admin/delete.png', :alt => _("delete"), :title => _("Delete content")),
:controller => controller, :action => 'destroy', :id => record.id
end
def <API key>(record, controller = @controller.controller_name)
if current_user.admin? || current_user.id == record.user_id
link_to(_("delete"),
{ :controller => controller, :action => 'destroy', :id => record.id }, :confirm => _("Are you sure?"), :method => :post, :title => _("Delete content"))
end
end
def text_filter_options
TextFilter.find(:all).collect do |filter|
[ filter.description, filter ]
end
end
def <API key>
TextFilter.find(:all).collect do |filter|
[ filter.description, filter.id ]
end
end
def alternate_class
@class = @class != '' ? '' : 'class="shade"'
end
def reset_alternation
@class = nil
end
def task_quickpost(title)
link_to_function(title, toggle_effect('quick-post', 'Effect.BlindUp', "duration:0.4", "Effect.BlindDown", "duration:0.4"))
end
def task_overview
content_tag :li, link_to(_('Back to overview'), :action => 'index')
end
def <API key>(title,id)
link_to_function(title, toggle_effect('<API key>-' + id.to_s, 'Effect.BlindUp', "duration:0.4", "Effect.BlindDown", "duration:0.4"))
end
def <API key>(title,id)
link_to_function(title, toggle_effect('<API key>-' + id.to_s, 'Effect.BlindUp', "duration:0.4", "Effect.BlindDown", "duration:0.4"))
end
def <API key>(title,id)
link_to_function(title, toggle_effect('edit-resource-mime-' + id.to_s, 'Effect.BlindUp', "duration:0.4", "Effect.BlindDown", "duration:0.4"))
end
def class_write
if controller.controller_name == "content" or controller.controller_name == "pages"
"current" if controller.action_name == "new"
end
end
def class_content
if controller.controller_name =~ /content|pages|categories|resources|feedback/
"current" if controller.action_name =~ /list|index|show/
end
end
def class_themes
"current" if controller.controller_name =~ /themes|sidebar/
end
def class_users
controller.controller_name =~ /users/ ? "current right" : "right"
end
def class_dashboard
controller.controller_name =~ /dashboard/ ? "current right" : "right"
end
def class_settings
controller.controller_name =~ /settings|textfilter/ ? "current right" : "right"
end
def class_profile
controller.controller_name =~ /profiles/ ? "current right" : "right"
end
def alternate_editor
return 'visual' if current_user.editor == 'simple'
return 'simple'
end
def <API key>(object, method, collection, value_method, text_method, current_value, prompt=false)
result = "<select name='#{object}[#{method}]'>\n"
if prompt == true
result << "<option value=''>" << _("Please select") << "</option>"
end
for element in collection
if current_value and current_value == element.send(value_method)
result << "<option value='#{element.send(value_method)}' selected='selected'>#{element.send(text_method)}</option>\n"
else
result << "<option value='#{element.send(value_method)}'>#{element.send(text_method)}</option>\n"
end
end
result << "</select>\n"
return result
end
def render_void_table(size, cols)
if size == 0
"<tr>\n<td colspan=#{cols}>" + _("There are no %s yet. Why don't you start and create one?", _(controller.controller_name)) + "</td>\n</tr>\n"
end
end
def cancel_or_save
result = '<p class="right">'
result << cancel
result << " "
result << _("or")
result << " "
result << save( _("Save") + " »")
result << '</p>'
return result
end
def link_to_published(item)
item.published? ? link_to_permalink(item, _("published"), '', 'published') : "<span class='unpublished'>#{_("unpublished")}</span>"
end
def macro_help_popup(macro, text)
unless current_user.editor == 'visual'
"<a rel='lightbox' href=\"#{url_for :controller => 'textfilters', :action => 'macro_help', :id => macro.short_name}\" onclick=\"return popup(this, 'Typo Macro Help')\">#{text}</a>"
end
end
def render_macros(macros)
result = link_to_function _("Show help on Typo macros") + " (+/-)",update_page { |page| page.visual_effect(:toggle_blind, "macros", :duration => 0.2) }
result << "<table id='macros' style='display: none;'>"
result << "<tr>"
result << "<th>#{_('Name')}</th>"
result << "<th>#{_('Description')}</th>"
result << "<th>#{_('Tag')}</th>"
result << "</tr>"
for macro in macros.sort_by { |f| f.short_name }
result << "<tr #{alternate_class}>"
result << "<td>#{macro_help_popup macro, macro.display_name}</td>"
result << "<td>#{h macro.description}</td>"
result << "<td><code><typo:#{h macro.short_name}></code></td>"
result << "</tr>"
end
result << "</table>"
end
def build_editor_link(label, action, id, update, editor)
link = link_to_remote(label,
:url => { :action => action, 'editor' => editor},
:loading => "new Element.show('update_spinner_
:success => "new Element.toggle('update_spinner_
:update => "#{update}")
link << image_tag("spinner-blue.gif", :id => "update_spinner_#{id}", :style => 'display:none;')
end
def display_pagination(collection, cols)
if WillPaginate::ViewHelpers.<API key>(collection) > 1
return "<tr><td colspan=#{cols} class='paginate'>#{will_paginate(collection)}</td></tr>"
end
end
def <API key>(image)
thumb = "#{RAILS_ROOT}/public/files/thumb_#{image.filename}"
picture = "#{this_blog.base_url}/files/#{image.filename}"
image.create_thumbnail unless File.exists? thumb
# If something went wrong with thumbnail generation, we just display a place holder
thumbnail = (File.exists? thumb) ? "#{this_blog.base_url}/files/thumb_#{image.filename}" : "#{this_blog.base_url}/images/thumb_blank.jpg"
picture = "<img class='tumb' src='#{thumbnail}' "
picture << "alt='#{this_blog.base_url}/files/#{image.filename}' "
picture << " onclick=\"<API key>('<API key>', '#{this_blog.base_url}/files/#{image.filename}');\" />"
return picture
end
end
|
<?php
namespace Editionista\WebsiteBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\<API key>\Configuration\Template;
use Sensio\Bundle\<API key>\Configuration\Route;
use Sensio\Bundle\<API key>\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller as Controller;
use Editionista\WebsiteBundle\Entity\Tag;
/**
* Edition controller.
*
* @Route("/tags")
*/
class TagController extends Controller
{
/**
* @Route("/", name="tags")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$tags = $em->getRepository('<API key>:Tag')->findAll();
return array('tags' => $tags);
}
/**
* @Route("/{tag}", name="show_tag")
* @Template()
*/
public function showAction($tag)
{
$em = $this->getDoctrine()->getManager();
$tag = $em->getRepository('<API key>:Tag')->findOneByName($tag);
$editions = $tag->getEditions();
return array('tag' => $tag, 'editions' => $editions);
}
/**
* @Route("/push", name="push_tags")
* @Method({"POST"})
*/
public function pushAction(Request $request)
{
$pushedTag = $request->request->get('tag');
$em = $this->getDoctrine()->getManager();
$storedTag = $em->getRepository('<API key>:Tag')->findOneByName($pushedTag);
if($storedTag == null) {
$tag = new Tag();
$tag->setName($pushedTag);
$em = $this->getDoctrine()->getManager();
$em->persist($tag);
$em->flush();
}
$response = new Response(json_encode(array('tag' => $pushedTag)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/pull", name="pull_tags")
*/
public function pullAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('<API key>:Tag')->findAll();
$tags = array();
foreach($entities as $entity) {
$tags['tags'][] = array('tag' => $entity->getName());
}
$response = new Response(json_encode($tags));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
|
package io.questions.model.questionnaire
import io.questions.model.questionnaire.Element.{ Parent, Primitive }
trait ElementValues {
implicit class ElementValuesSyntax(e: Element) {
def parent: Element.Parent = e match {
case p: Parent => p
case x => throw new <API key>(s"Expected a Parent. Got $x")
}
def primitive: Element.Primitive = e match {
case p: Primitive => p
case x => throw new <API key>(s"Expected a Primitive. Got $x")
}
}
}
|
using System;
using System.Reflection;
namespace Light.DataCore
{
abstract class DynamicFieldMapping : FieldMapping
{
public static DynamicFieldMapping <API key> (PropertyInfo property, <API key> mapping)
{
DynamicFieldMapping fieldMapping;
Type type = property.PropertyType;
TypeInfo typeInfo = type.GetTypeInfo();
string fieldName = property.Name;
if (typeInfo.IsGenericType) {
Type frameType = type.<API key> ();
if (frameType.FullName == "System.Nullable`1") {
Type [] arguments = type.GetGenericArguments ();
type = arguments [0];
typeInfo = type.GetTypeInfo();
}
}
if (type.IsArray) {
throw new LightDataException(string.Format(SR.<API key>, property.DeclaringType, property.Name, type));
}
else if (type.IsGenericParameter || typeInfo.<API key>) {
throw new LightDataException(string.Format(SR.<API key>, property.DeclaringType, property.Name, type));
}
else if (typeInfo.IsEnum) {
<API key> enumFieldMapping = new <API key> (type, fieldName, mapping);
fieldMapping = enumFieldMapping;
}
else {
TypeCode code = Type.GetTypeCode (type);
switch (code) {
case TypeCode.Empty:
case TypeCode.Object:
throw new LightDataException(string.Format(SR.<API key>, property.DeclaringType, property.Name, type));
default:
<API key> <API key> = new <API key> (type, fieldName, mapping);
fieldMapping = <API key>;
break;
}
}
return fieldMapping;
}
protected DynamicFieldMapping (Type type, string fieldName, <API key> mapping, bool isNullable)
: base (type, fieldName, fieldName, mapping, isNullable, null)
{
}
}
}
|
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;
}
};
|
<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>
|
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'),
)
|
/*
* 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(<API key>)}.
* <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 <API key> implements IndexedRecord {
private static final Schema schema$ = SchemaBuilder
.record("<API key>")
.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.<API key>.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 <API key> object with default parameters.
*/
public <API key>() {
tableName = "";
viewName = "";
valueStr = "";
columnName = "";
options = new LinkedHashMap<>();
}
/**
* Constructs a <API key> 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/#<API key>"
* 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/#<API key>"
* target="_top">name resolution rules</a> and meeting <a
* href="../../../../../../concepts/tables/#<API key>"
* 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.<API key>.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 <API key>(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/#<API key>"
* 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/#<API key>"
* target="_top">name resolution rules</a>.
*
* @return {@code this} to mimic the builder pattern.
*
*/
public <API key> 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/#<API key>"
* target="_top">name resolution rules</a> and meeting <a
* href="../../../../../../concepts/tables/#<API key>"
* 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/#<API key>"
* target="_top">name resolution rules</a> and meeting <a
* href="../../../../../../concepts/tables/#<API key>"
* 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 <API key> 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 <API key> 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 <API key> 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 <API key> 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 <API key> setColumnName(String columnName) {
this.columnName = (columnName == null) ? "" : columnName;
return this;
}
/**
*
* @return Optional parameters.
* <ul>
* <li> {@link
* com.gpudb.protocol.<API key>.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.<API key>.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 <API key> 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 <API key>
*
*/
@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 <API key>("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 <API key>
*
*/
@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 <API key>("Invalid index specified.");
}
}
@Override
public boolean equals(Object obj) {
if( obj == this ) {
return true;
}
if( (obj == null) || (obj.getClass() != this.getClass()) ) {
return false;
}
<API key> that = (<API key>)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;
}
}
|
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
|
// <auto-generated>
// This code was generated by a tool.
// 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 <API key>
// 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.<API key>("System.Resources.Tools.<API key>", "4.0.0.0")]
[global::System.Diagnostics.<API key>()]
[global::System.Runtime.CompilerServices.<API key>()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.<API key>("Microsoft.Performance", "CA1811:<API key>")]
internal Resources() {
}
<summary>
Returns the cached ResourceManager instance used by this class.
</summary>
[global::System.ComponentModel.<API key>(global::System.ComponentModel.<API key>.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.<API key>(global::System.ComponentModel.<API key>.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
|
<!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
<API key> 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") }
"<API key>" { (>= "1.12.0" & < "1.13~") }
"<API key>" { (>= "1.12.0" & < "1.13~") }
"<API key>" { (>= "1.12.0" & < "1.13~") }
"<API key>" { (>= "1.12.0" & < "1.13~") }
"coq-mathcomp-field" { (>= "1.12.0" & < "1.13~") }
"<API key>" { (>= "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 -> <API key> < 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 -> <API key> < 0.3.8 -> coq-mathcomp-finmap < 1.4~ -> <API key> < 1.8~ -> coq < 8.10~ -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
- coq-infotheo -> <API key> < 0.3.8 -> <API key> (< 1.1.0 | >= dev) -> coq < 8.12.0~ -> ocaml < 4.12
base of this switch (use `--unlock-base' to force)
- coq-infotheo -> <API key> < 0.3.8 -> <API key> (< 1.1.0 | >= dev) -> coq-elpi -> ocaml < 4.12~
base of this switch (use `--unlock-base' to force)
- coq-infotheo -> <API key> < 0.3.8 -> <API key> (< 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 -> <API key> < 0.3.8 -> <API key> (< 1.1.0 | >= dev) -> coq-elpi -> elpi < 1.14.0~ -> <API key> < 2.0.0 -> ocaml < 4.13
base of this switch (use `--unlock-base' to force)
- coq-infotheo -> <API key> < 0.3.8 -> <API key> (< 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 -> <API key> < 0.3.8 -> <API key> (< 1.1.0 | >= dev) -> coq-elpi -> coq < 8.13~ -> ocaml < 4.12
base of this switch (use `--unlock-base' to force)
- coq-infotheo -> <API key> < 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:
</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>
|
<?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('<API key>', '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);
}
}
|
'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;
|
package com.highstock.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code><API key></code>
*/
@js.annotation.ScalaJSDefined
class <API key> extends com.highcharts.<API key> {
/**
* <p>CSS class name of the guide box in this state. Defaults to
* <code><API key></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 <API key> {
/**
* @param className <p>CSS class name of the guide box in this state. Defaults to. <code><API key></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): <API key> = {
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.<API key>.toCleanObject(new <API key> {
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
})
}
}
|
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);
}
}
}
}
|
<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>
|
import sys
import pytest
from opentracing.ext import tags
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from <API key>.client_hooks import mysqldb as mysqldb_hooks
from <API key>.request_context import span_in_context
from .sql_common import metadata, User
<API key> = 'MySQLdb is not compatible with Python 3'
<API key> = 'MySQL is not running or cannot connect'
<API key> = 'mysql://root@127.0.0.1/test'
@pytest.fixture
def session():
Session = sessionmaker()
engine = create_engine(<API key>)
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.<API key>
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=<API key>)
@pytest.mark.skipif(sys.version_info.major == 3, reason=<API key>)
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)
|
// 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()
{
int v = 8;
int p = 3;
// => 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);
}
}
}
|
<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="<API key>" 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="<API key>"><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>
|
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.<API key>;
import com.example.lit.exception.<API key>;
import com.example.lit.saving.Saveable;
import com.example.lit.exception.<API key>;
import io.searchbox.annotations.JestId;
import java.io.<API key>;
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 <API key> {
this.setTitle(title);
this.setDate(new Date());
}
public Habit(String title, Date date) throws <API key>{
this.setTitle(title);
this.setDate(date);
}
public Habit(String title, Date date, String reason) throws <API key> {
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 <API key> 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 <API key> {
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 <API key>, <API key>{
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 <API key> {
if (title.length() > this.titleLength){
throw new <API key>();
}
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 <API key> {
if (reason.length() < this.reasonLength) {
this.reason = reason;
}
else {
throw new <API key>();
}
}
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 <API key>
*/
public void setImage(Bitmap image) throws <API key> {
if (image == null){
this.image = null;
}
else if (image.getByteCount() > 65536){
throw new <API key>();
}
else {
this.image = image;
<API key> baos = new <API key>();
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());
}
}
|
<!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:
<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>
|
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" />
, '<API key>');
|
# 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 <API key>
include MsRestAzure
# @return [<API key>] 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 <API key> class as Ruby Hash.
# This will be used for serialization/deserialization.
def self.mapper()
{
<API key>: true,
required: false,
serialized_name: '<API key>',
type: {
name: 'Composite',
class_name: '<API key>',
model_properties: {
query_results: {
<API key>: true,
required: false,
serialized_name: 'queryResults',
type: {
name: 'Composite',
class_name: '<API key>'
}
},
validation_errors: {
<API key>: true,
required: false,
serialized_name: 'validationErrors',
type: {
name: 'Composite',
class_name: 'ValidationError'
}
}
}
}
}
end
end
end
end
|
import {MdSnackBar} from '@angular/material';
export abstract class CommonCrudService {
constructor(private snackBar: MdSnackBar) {
}
// todo refactor crud operations to here (use metadata?)
<API key>(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
});
};
}
}
|
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.<API key>();
}
/**
* 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.<API key>();
}
/**
* 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;
}
}
|
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;
}
}
}
|
#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* <API key>(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
|
# Jrails-ui
module ActionView
module Helpers
module JavaScriptHelper
def hash_to_jquery(hash)
'{'+hash.map { |k,v|
[k,
case v.class.name
when 'String'
"'
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
|
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.<API key>);
private TankExceptionCodes exceptionCode;
TankMessageCodes() {
exceptionCode = null;
}
TankMessageCodes(TankExceptionCodes pExceptionCode) {
exceptionCode = pExceptionCode;
}
@Override
public ExceptionCode getExceptionCode() {
return exceptionCode;
}
}
|
package okeanos.data.services.entities;
import javax.measure.quantity.Power;
import org.jscience.physics.amount.Amount;
public interface Price {
double <API key>(Amount<Power> consumption);
}
|
<?php
namespace Shop\MainBundle\Data;
use Doctrine\Common\Persistence\ObjectRepository;
use Shop\MainBundle\Entity\Settings;
/**
* Class <API key>
* @package Shop\MainBundle\Data
*/
class <API key> {
/**
* @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);
}
}
|
<!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>
Bayview Propeller -
Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada
</title>
<!-- Title ends / Fin du titre -->
<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/<API key>.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="
<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.<API key>(s)[0], j=d.createElement(s),dl=l!='dataLayer1'?'&l='+l:'';j.async=true;j.src='
<!-- End Google Tag Manager -->
<!-- EPI-12801 -->
<span typeof="Organization"><meta property="legalName" content="<API key>"></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:
</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="<API key>">
<h2 class="wb-inv">Topics menu</h2>
<div class="container nvbar">
<div class="row">
<ul class="list-inline menu">
<li><a href="https:
<li><a href="http:
<li><a href="https://travel.gc.ca/">Travel</a></li>
<li><a href="https:
<li><a href="https:
<li><a href="http://healthycanadians.gc.ca/index-eng.php">Health</a></li>
<li><a href="https:
<li><a href="https:
</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 <API key><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 <API key><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:
<li><a href="https:
<li><a href="https:
<li><a href="https:
<li><a href="https:
<li><a href="http://pm.gc.ca/eng">Prime Minister</a></li>
<li><a href="https:
<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:
<li><a href="https:
<li><a href="http://www1.canada.ca/en/newsite.html">About Canada.ca</a></li>
<li><a href="http:
<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 <API key>"></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.<API key>.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="
</noscript>
<!-- /Webtrends -->
<!-- JS deps -->
<script src="/eic/home.nsf/js/jquery.imagesloaded.js"></script>
<!-- EPI-11262 - Util JS -->
<script src="/eic/home.nsf/js/<API key>.min.js"></script>
<!-- EPI-11383 -->
<script src="/eic/home.nsf/js/jQuery.icValidationErrors.js"></script>
<span style="display:none;" id='app-info' <API key>='' <API key>='' <API key>='' <API key>='' data-issue-tracking='' data-scm-sha1='' <API key>='' data-scm-branch='' <API key>=''></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
|
var builder = require("botbuilder");
var botbuilder_azure = require("botbuilder-azure");
const notUtils = require('./notifications-utils.js');
module.exports = [
function (session) {
session.beginDialog('<API key>');
},
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);
});
}
];
|
#ifndef _PSW_H_INCLUDED_
#define _PSW_H_INCLUDED_
#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_ */
|
#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() : <API key>(0) {}
/** Copy constructor. @param d a duration to copy. */
VDuration(const VDuration& d) : <API key>(d.<API key>) {}
/** 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 <API key>(const VString& s);
/** Assignment operator. @param d a duration to assign from */
VDuration& operator=(const VDuration& d) { if (this != &d) <API key> = d.<API key>(); 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 <API key>() const { return <API key>; }
/** Returns the duration in whole seconds, using simple truncating division of milliseconds. @return obvious */
int getDurationSeconds() const { return static_cast<int>(<API key> / <API key>); }
/** Returns the duration in whole minutes, using simple truncating division of milliseconds. @return obvious */
int getDurationMinutes() const { return static_cast<int>(<API key> / <API key>); }
/** Returns the duration in whole hours, using simple truncating division of milliseconds. @return obvious */
int getDurationHours() const { return static_cast<int>(<API key> / <API key>); }
/** Returns the duration in whole days, using simple truncating division of milliseconds. @return obvious */
int getDurationDays() const { return static_cast<int>(<API key> / 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 <API key>() const;
/** Sets the duration in milliseconds. @param <API key> the duration to set, in milliseconds */
void <API key>(Vs64 <API key>) { <API key> = <API key>; }
/** Sets the duration in seconds. @param durationSeconds the duration to set, in seconds */
void setDurationSeconds(int durationSeconds) { <API key> = <API key> * static_cast<Vs64>(durationSeconds); }
/** Sets the duration in minutes. @param durationMinutes the duration to set, in minutes */
void setDurationMinutes(int durationMinutes) { <API key> = <API key> * static_cast<Vs64>(durationMinutes); }
/** Sets the duration in hours. @param durationHours the duration to set, in hours */
void setDurationHours(int durationHours) { <API key> = <API key> * 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) { <API key> = 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 <API key>) : <API key>(<API key>) {}
Vs64 <API key>; ///< The duration in milliseconds. The values for UNSPECIFIED, NEGATIVE_INFINITY, and POSITIVE_INFINITY are special.
// These are used internally for conversion.
static const Vs64 <API key> = CONST_S64(1000);
static const Vs64 <API key> = CONST_S64(60000);
static const Vs64 <API key> = 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.<API key> == rhs.<API key>; }
inline bool operator!=(const VDuration& lhs, const VDuration& rhs) { return !operator==(lhs, rhs); }
inline bool operator< (const VDuration& lhs, const VDuration& rhs) { return lhs.<API key> < rhs.<API key>; }
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.<API key> + d2.<API key>); else return VDuration::_complexAdd(d1, d2); }
inline VDuration operator-(const VDuration& d1, const VDuration& d2) { if (VDuration::areValuesSpecific(d1, d2)) return VDuration(d1.<API key> - d2.<API key>); else return VDuration::_complexSubtract(d1, d2); }
inline VDuration operator*(Vs64 multiplier, const VDuration& d) { if (d.isSpecific()) return VDuration(d.<API key> * multiplier); else return VDuration::_complexMultiply(d, multiplier); }
inline VDuration operator*(const VDuration& d, Vs64 multiplier) { if (d.isSpecific()) return VDuration(d.<API key> * 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.<API key> < 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 <API key>() 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 <API key>() 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 <API key>(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 <API key>(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 <API key>(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 <API key>(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 <API key>(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 <API key>(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::<API key>(). 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 <API key> {
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:
<API key>() {}
virtual ~<API key>() {}
};
/**
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 <API key>(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 <API key> the duration offset in milliseconds to apply;
positive values move the instant forward in time;
negative values move it backward
*/
VInstant& operator+=(const VDuration& <API key>);
/**
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 <API key> the offset in milliseconds to apply;
positive values move the instant backward in time;
negative values move it forward
*/
VInstant& operator-=(const VDuration& <API key>);
/**
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 <API key>() 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 <API key>() 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 <API key>(<API key>* 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 <API key>* <API key>();
// 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 <API key>(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 <API key>(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 <API key> the simulated time from which to calculate the offset
*/
static void <API key>(const VInstant& <API key>);
/**
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 <API key>();
/**
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 <API key>) : mValue(<API key>) {}
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 <API key>; ///< 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 <API key>* <API key>; ///< 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;
class VDate {
public:
static VDate <API key>(const VString& dateString, const VCodePoint& delimiter);
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); }
/**
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 <API key> {
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 <API key>& 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.)
*/
<API key>();
~<API key>() {}
// 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"
};
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 <API key>& 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 <API key>& 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 <API key>(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 <API key>) const;
void <API key>(const VInstantStruct& when, int <API key>, VString& fieldSpecifier/*will be set to empty on return*/, VString& resultToAppendTo) const;
void <API key>(const VString& value, VString& resultToAppendTo) const;
void <API key>(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 <API key>(int dayOfWeek/*0=sun ... 6=sat*/, int fieldLength, VString& resultToAppendTo) const;
void _flushTimeZoneValue(int <API key>, const VString& fieldSpecifier, VString& resultToAppendTo) const;
VString mFormatSpecifier;
// Pseudo-constants: Potentially localized values, not static, because we allow setting per VInstantFormatter.
const <API key>& mLocaleInfo;
};
#endif /* vinstant_h */
|
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; }
}
}
|
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;
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;
}
}
|
<?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\<API key>;
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 <API key>( $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";
$<API key> = $service->singlePurchase( $purchaseOrderId, $storageToken, '100', null );
// optional array dump of response params
// print_r($receipt->params);
if ( $<API key>->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;
$<API key> = $service->updateStorage($storageToken, $paymentProfile);
if ( $<API key>->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";
}
|
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.<API key>;
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.<API key>(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 = <API key>.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;
}
}
}
|
<?php
namespace SunCat\<API key>\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 <API key> extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this-><API key>($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']);
}
}
|
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, <API key>) {
if (!data) {
data = {};
}
if (!targetOrigin) {
targetOrigin = this.config.siteUrl;
}
if (!targetOrigin) {
targetOrigin = "*";
}
data.command = command;
data.postMessageId = `SP.RequestExecutor_${this.messageCounter++}`;
let <API key> = undefined;
if (<API key>) {
<API key> = _.get(data, <API key>);
}
if (<API key>)
this._contentWindow.postMessage(data, targetOrigin, [<API key>]);
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, <API key>) {
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.<API key>.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 <API key> = undefined;
if (<API key>) {
<API key> = _.get(data, <API key>);
}
if (<API key>)
this._contentWindow.postMessage(data, targetOrigin, [<API key>]);
else
this._contentWindow.postMessage(data, targetOrigin);
return promise;
}
}
module.exports = Channel;
|
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`, () => {
});
|
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";
}
|
# 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#<API key>)
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
|
#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
|
// config/database.js
module.exports = {
'secret': 'puneetvashisht',
'url' : 'mongodb://localhost/userdb' // looks like mongodb://<user>:<pass>@mongo.onmodulus.net:27017/Mikha4ot
};
|
import {
<API key>,
<API key>,
} from 'actions/search';
import { <API key> } from 'utils/reducer/actions-handlers';
const actionHandlers = {};
export function <API key>(state, searchResultsList) {
return searchResultsList.reduce((acc, result) => {
return {
acc,
[result.id]: result,
};
}, {});
}
export function clearSearchResult() {
return {};
}
actionHandlers[<API key>] = <API key>;
actionHandlers[<API key>] = clearSearchResult;
export default <API key>(actionHandlers);
|
/**
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
firstSing(X) :-
X <> [sing, first].
second(X) :-
person@X
third(X) :-
person@X
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.
|
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);
}
}
|
# Chokidar CLI
[, 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:
> [socketstream](http:
> [derby](http://derbyjs.com/),
> and [many others](https:
> 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]
--<API key> 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 "***.less" output changes of .js and .less
files
MIT
|
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.
|
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.<API key>(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.<API key>(node.getLevel() - 1))
html.push('<i class="glyphicon <API key> js-folder"></i>')
}
else {
html.push('<li><a href="#"><span>')
html.push(this.<API key>(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.<API key>(level - 1))
html.push('<i class="glyphicon ',
node.isOpen ? '<API key>' : 'glyphicon-plus-sign',
' js-folder"></i>')
}
else {
html.push(this.<API key>(level))
}
html.push(this.itemToLabel(node.data))
html.push('</span>')
return html.join('')
},
<API key>: 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('<API key>')
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('<API key>').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)
|
#!/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
|
# 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/<API key>.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/<API key>.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).
|
#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;
}
|
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');
}
}
|
#!/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);
});
|
// <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; }
}
}
|
const path = require('path');
require('dotenv').config();
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('<API key>');
const { AureliaPlugin } = require('<API key>');
const { optimize: { CommonsChunkPlugin }, ProvidePlugin } = require('webpack')
const { TsConfigPathsPlugin, CheckerPlugin } = require('<API key>');
var <API key> = require('<API key>').<API key>;
const UglifyJSPlugin = require('<API key>')
var BrowserSyncPlugin = require('<API key>');
// 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: '<API key>', 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: '<API key>',
include: srcDir, exclude: [/\.{spec,test}\.[jt]s$/i],
enforce: 'post', options: { esModules: true },
})
]
},
plugins: [
new BrowserSyncPlugin({
// ./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 <API key>({
// // 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'
],
})
|
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" %}
|
<!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="<API key> 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="<API key>">
<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>
|
# 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: `<API key>.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
MIT (see [LICENSE](LICENSE))
|
#!/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 <API key>
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."
<API key> = 20
"Default value for the logger configuration."
<API key> = 5
"Default value for the logger configuration."
<API key> = 0
"Default value for the logger configuration."
<API key> = 500
"Default value for the logger configuration."
default_level = logging.INFO
"Default value for the logger configuration."
<API key> = 500
"Default value for the logger configuration."
<API key> = '%d %B %Y %H:%M:%S'
"Default value for the logger configuration."
<API key> = '{T} [{L}]'
"Default value for the logger configuration."
<API key> = []
"Default value for the logger configuration. Filled in constructor."
def __init__(self,
message_number=<API key>,
exception_number=<API key>,
<API key>=<API key>,
<API key>=<API key>,
console_level=default_level,
<API key>=<API key>,
<API key>=<API key>,
console_format=<API key>,
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 <API key>: [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 <API key>: [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 <API key>: [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 <API key>: [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.<API key>))
self.<API key>.append(handler)
file_handlers = self.<API key>
if not self.queue:
self.queue = Queue()
self.process = <API key>(queue=self.queue,
console_level=console_level,
message_number=message_number,
exception_number=exception_number,
<API key>=<API key>,
<API key>=<API key>,
<API key>=<API key>,
<API key>=<API key>,
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=<API key>,
exception_number=<API key>,
<API key>=<API key>,
<API key>=<API key>,
console_level=default_level,
<API key>=<API key>,
<API key>=<API key>,
console_format=<API key>,
file_handlers=<API key>):
"""
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 <API key>: [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 <API key>: [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 <API key>: [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 <API key>: [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(<API key>(<API key>=<API key>,
console_level=console_level,
<API key>=<API key>,
message_number=message_number,
exception_number=exception_number,
<API key>=<API key>,
<API key>=<API key>,
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,
<API key>):
"""
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 <API key>: TaskProgress object holding the progress bar information.
"""
self.set_task(task_id=task_id,
total=<API key>.total,
prefix=<API key>.prefix,
suffix=<API key>.suffix,
decimals=<API key>.decimals,
bar_length=<API key>.bar_length,
keep_alive=<API key>.keep_alive,
display_time=<API key>.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(<API key>(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,
<API key>=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 <API key>: [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 <API key>:
# Force total attribute
<API key>.total = self.list_length
else:
<API key> = TaskProgress(total=self.list_length,
display_time=True,
prefix='Progress')
# Create a task progress
self.set_task_object(task_id=self.task_id,
<API key>=<API key>)
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]
|
<html><body>
<h4>Windows 10 x64 (18362.329)</h4><br>
<h2><API key></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>
|
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.<API key>;
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 <API key>()
{
when(clientMock.<API key>(Mockito.any())).thenReturn(null);
service.register();
Mockito.verify(clientMock).<API key>(serviceMock);
}
@Test
public void <API key>()
{
service.unregister();
Mockito.verify(clientMock).<API key>("42", true);
}
@Test(expected = <API key>.class)
public void <API key>()
{
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 <API key>()
{
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 <API key>()
{
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 <API key>()
{
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));
}
}
|
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;
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.
}
}
}
|
<?php
namespace LeadCommerce\Shopware\SDK\Query;
use LeadCommerce\Shopware\SDK\Util\Constants;
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';
}
}
|
**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.
|
/*
* 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 <API key> {
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();
System.out.println(list);
} catch (final <API key> ex) {
Logger.getLogger(<API key>.class.getName()).log(Level.SEVERE, null, ex);
future.cancel(true);
} catch (final ExecutionException ex) {
Logger.getLogger(<API key>.class.getName()).log(Level.SEVERE, null, ex);
throw new ExecutionException(ex);
} finally {
executor.shutdown();
}
}
public static void main(final String args[]) {
try {
new <API key>().start();
} catch (final Exception ex) {
Logger.getLogger(<API key>.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
// **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 <API key>.
</summary>
public partial interface <API key>
{
<summary>
Builds the request.
</summary>
<param name="options">The query and header options for the request.</param>
<returns>The built request.</returns>
<API key> Request(IEnumerable<Option> options = null);
}
}
|
// 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 <API key> {
/*
* x-ms-original-file: specification/eventhub/resource-manager/Microsoft.EventHub/stable/2021-11-01/examples/ConsumerGroup/<API key>.json
*/
/**
* Sample code: <API key>.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void <API key>(com.azure.resourcemanager.<API key> azure) {
azure
.eventHubs()
.manager()
.serviceClient()
.getConsumerGroups()
.listByEventHub("ArunMonocle", "sdk-Namespace-2661", "sdk-EventHub-6681", null, null, Context.NONE);
}
}
|
/** @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 => {
// <API key> no-param-reassign
vnode.state.href = '/';
// <API key> 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);
// <API key> 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;
|
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 <API key>(force, key, value):
for i in range(force.<API key>()):
if force.<API key>(i)==key:
print('setting force parameter', key, '=', value)
force.<API key>(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 <API key>(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)
<API key>(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)
|
namespace InControl
{
using System;
// @cond nodoc
[AutoDiscover]
public class <API key> : <API key>
{
public <API key>()
{
Name = "8Bitdo SNES30 Controller";
Meta = "8Bitdo SNES30 Controller on Android";
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
}
|
#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 <API key>(double dt);
void Update(double dt);
double speed;
private:
Transform* transform_;
CubeMesh* sprite_;
};
|
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.<API key>)
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
}
|
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';
}
});
});
|
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;
}
|
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;
}
};
|
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
}
|
'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'));
|
/**
* @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 <API key>$ref: FragmentReference;
declare export opaque type <API key>$fragmentType: <API key>$ref;
export type <API key> = {|
+id: string,
+reactionGroups: ?$ReadOnlyArray<{|
+content: ReactionContent,
+viewerHasReacted: boolean,
+users: {|
+totalCount: number
|},
|}>,
+viewerCanReact: boolean,
+$refType: <API key>$ref,
|};
export type <API key>$data = <API key>;
export type <API key>$key = {
+$data?: <API key>$data,
+$fragmentRefs: <API key>$ref,
};
*/
const node/*: ReaderFragment*/ = {
"kind": "Fragment",
"name": "<API key>",
"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": "<API key>",
"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 = '<API key>';
module.exports = node;
|
require 'bio-ucsc'
describe "Bio::Ucsc::Hg19::<API key>" 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::<API key>.<API key>(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::<API key>.find_by_interval(i)
r.chrom.should == "chr1"
end
end
end
end
|
# 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
|
<!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 .<API key>, div.coverage-summary .<API key> {
height: 10px;
width: 7px;
display: inline-block;
margin-left: 0.5em;
}
div.coverage-summary .<API key> {
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 .<API key> .<API key> {
background-position: 0 -20px;
}
div.coverage-summary .<API key> .<API key> {
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>
|
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
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateList extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('modelList', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('modelList');
}
}
|
type: docs
order: 10
title: "Transloadit"
module: "@uppy/transloadit"
permalink: docs/transloadit/
category: "File Processing"
tagline: "manipulate and transcode uploaded files using the <a href='https://transloadit.com'>transloadit.com</a> service"
The `@uppy/transloadit` plugin can be used to upload files to [Transloadit](https:
> If you’re okay to trade some flexibility for ergonomics, consider using
> the [Robodog](/docs/robodog/) Plugin instead, which is a higher-level abstraction for
> encoding files with Uppy and Transloadit.
<a class="TryButton" href="/examples/transloadit/">Try it live</a>
js
import Transloadit from '@uppy/transloadit'
uppy.use(Transloadit, {
service: 'https://api2.transloadit.com',
params: null,
waitForEncoding: false,
waitForMetadata: false,
<API key>: false,
alwaysRunAssembly: false,
signature: null,
fields: {},
limit: 0,
})
As of Uppy version 0.24, the Transloadit plugin includes the [Tus](/docs/tus) plugin to handle the uploading, so you no longer have to add it manually.
## Installation
This plugin is published as the `@uppy/transloadit` package.
Install from NPM:
shell
npm install @uppy/transloadit
In the [CDN package](/docs/#With-a-script-tag), the plugin class is available on the `Uppy` global object:
js
const { Transloadit } = Uppy
## Hosted Companion Service
You can use this plugin together with Transloadit’s hosted Companion service to let your users import files from third party sources across the web.
To do so each provider plugin must be configured with Transloadit’s Companion URLs:
js
uppy.use(Dropbox, {
companionUrl: Transloadit.COMPANION,
<API key>: Transloadit.COMPANION_PATTERN,
})
This will already work. Transloadit’s OAuth applications are used to authenticate your users by default. Your users will be asked to provide Transloadit access to their files. Since your users are probably not aware of Transloadit, this may be confusing or decrease trust. You may also hit rate limits, because the OAuth application is shared between everyone using Transloadit.
To solve that, you can use your own OAuth keys with Transloadit’s hosted Companion servers by using Transloadit Template Credentials. [Create a Template Credential][<API key>] on the Transloadit site. Select “Companion OAuth” for the service, and enter the key and secret for the provider you want to use. Then you can pass the name of the new credentials to that provider:
js
uppy.use(Dropbox, {
companionUrl: Transloadit.COMPANION,
<API key>: Transloadit.COMPANION_PATTERN,
companionKeysParams: {
key: '<API key>',
credentialsName: '<API key>',
},
})
## Properties
`Transloadit.COMPANION`
The main endpoint for Transloadit’s hosted companions. You can use this constant in remote provider options, like so:
js
import Dropbox from '@uppy/dropbox'
import Transloadit from '@uppy/transloadit'
uppy.use(Dropbox, {
companionUrl: Transloadit.COMPANION,
<API key>: Transloadit.COMPANION_PATTERN,
})
When using `Transloadit.COMPANION`, you should also configure [`<API key>: Transloadit.COMPANION_PATTERN`](#<API key>).
The value of this constant is `https://api2.transloadit.com/companion`. If you are using a custom [`service`](#service) option, you should also set a custom host option in your provider plugins, by taking a Transloadit API url and appending `/companion`:
js
uppy.use(Dropbox, {
companionUrl: 'https://api2-us-east-1.transloadit.com/companion',
})
`Transloadit.COMPANION_PATTERN`
A RegExp pattern matching Transloadit’s hosted companion endpoints. The pattern is used in remote provider `<API key>` options, to make sure that third party authentication messages cannot be faked by an attacker’s page, but can only originate from Transloadit’s servers.
Use it whenever you use `companionUrl: Transloadit.COMPANION`, like so:
js
import Dropbox from '@uppy/dropbox'
import Transloadit from '@uppy/transloadit'
uppy.use(Dropbox, {
companionUrl: Transloadit.COMPANION,
<API key>: Transloadit.COMPANION_PATTERN,
})
The value of this constant covers _all_ Transloadit’s Companion servers, so it does not need to be changed if you are using a custom [`service`](#service) option. But, if you are not using the Transloadit Companion servers at `*.transloadit.com`, make sure to set the `<API key>` option to something that matches what you do use.
## Options
The `@uppy/transloadit` plugin has the following configurable options:
`id: 'Transloadit'`
A unique identifier for this plugin. It defaults to `'Transloadit'`.
`service`
The Transloadit API URL to use. It defaults to `https:
`params`
The Assembly parameters to use for the upload. See the Transloadit documentation on [Assembly Instructions](https://transloadit.com/docs/#<API key>) for further information. `params` should be a plain JavaScript object, or a JSON string if you are using the [`signature`](#signature) option.
The `auth.key` Assembly parameter is required. You can also use the `steps` or `template_id` options here as described in the Transloadit documentation.
js
uppy.use(Transloadit, {
params: {
auth: { key: '<API key>' },
steps: {
encode: {
robot: '/video/encode',
use: {
steps: [':original'],
fields: ['file_input_field2'],
},
preset: 'iphone',
},
},
},
})
<a id="waitForEncoding"></a>
`waitForEncoding: false`
By default, the Transloadit plugin uploads files to Assemblies and then marks the files as complete in Uppy. The Assemblies will complete (or error) in the background but Uppy won’t know or care about it.
When `waitForEncoding` is set to true, the Transloadit plugin waits for Assemblies to complete before the files are marked as completed. This means users have to wait for a potentially long time, depending on how complicated your Assembly instructions are. But, you can receive transcoding results on the client side, and have a fully client-side experience this way.
When this is enabled, you can listen for the [`transloadit:result`](#transloadit-result) and [`transloadit:complete`](#<API key>) events.
<a id="waitForMetadata"></a>
`waitForMetadata: false`
By default, the Transloadit plugin uploads files to Assemblies and then marks the files as complete in Uppy. The Assemblies will complete (or error) in the background but Uppy won’t know or care about it.
When `waitForMetadata` is set to true, the Transloadit plugin waits for Transloadit’s backend to extract metadata from all the uploaded files. This is mostly handy if you want to have a quick user experience (so your users don’t necessarily need to wait for all the encoding to complete), but you do want to let users know about some types of errors that can be caught early on, like file format issues.
When this is enabled, you can listen for the [`transloadit:upload`](#transloadit-upload) event.
`<API key>`
Instead of uploading to Transloadit’s servers directly, allow another plugin to upload files, and then import those files into the Transloadit Assembly. This is set to `false` by default.
When enabling this option, Transloadit will _not_ configure the Tus plugin to upload to Transloadit. Instead, a separate upload plugin must be used. Once the upload completes, the Transloadit plugin adds the uploaded file to the Assembly.
For example, to upload files to an S3 bucket and then transcode them:
js
uppy.use(AwsS3, {
getUploadParameters (file) {
return { /* upload parameters */ }
},
})
uppy.use(Transloadit, {
<API key>: true,
params: {
auth: { key: 'YOUR_API_KEY' },
template_id: 'YOUR_TEMPLATE_ID',
},
})
For this to work, the upload plugin must assign a publically accessible `uploadURL` property to the uploaded file object. The Tus and S3 plugins both do this automatically. For the XHRUpload plugin, you may have to specify a custom `getResponseData` function.
`alwaysRunAssembly`
When set to true, always create and run an Assembly when `uppy.upload()` is called, even if no files were selected. This allows running Assemblies that do not receive files, but instead use a robot like [`/s3/import`](https://transloadit.com/docs/transcoding/#s3-import) to download the files from elsewhere, for example, for a bulk transcoding job.
`signature`
An optional signature for the Assembly parameters. See the Transloadit documentation on [Signature Authentication](https://transloadit.com/docs/#<API key>) for further information.
If a `signature` is provided, `params` should be a JSON string instead of a JavaScript object, as otherwise the generated JSON in the browser may be different from the JSON string that was used to generate the signature.
`fields`
An object of form fields to send along to the Assembly. Keys are field names, and values are field values. See also the Transloadit documentation on [Form Fields In Instructions](https://transloadit.com/docs/#<API key>).
js
uppy.use(Transloadit, {
fields: {
message: 'This is a form field',
},
})
You can also pass an array of field names to send global or file metadata along to the Assembly. Global metadata is set using the [`meta` option](/docs/uppy/#meta) in the Uppy constructor, or using the [`setMeta` method](/docs/uppy/#uppy-setMeta-data). File metadata is set using the [`setFileMeta`](/docs/uppy/#<API key>) method. The [Form](/docs/form) plugin also sets global metadata based on the values of `<input />`s in the form, providing a handy way to use values from HTML form fields:
js
uppy.use(Form, { target: 'form#upload-form', getMetaFromForm: true })
uppy.use(Transloadit, {
fields: ['field_name', 'other_field_name'],
params: { },
})
Form fields can also be computed dynamically using custom logic, by using the [`getAssemblyOptions(file)`](/docs/transloadit/#<API key>) option.
`getAssemblyOptions(file)`
While `params`, `signature`, and `fields` must be determined ahead of time, the `getAssemblyOptions` allows using dynamically generated values for these options. This way, it’s possible to use different Assembly parameters for different files, or to use some user input in an Assembly.
A custom `getAssemblyOptions()` option should return an object or a Promise for an object with properties `{ params, signature, fields }`. For example, to add a field with some user-provided data from the `MetaData` plugin:
js
uppy.use(MetaData, {
fields: [
{ id: 'caption' },
],
})
uppy.use(Transloadit, {
getAssemblyOptions (file) {
return {
params: {
auth: { key: '<API key>' },
template_id: 'xyz',
},
fields: {
caption: file.meta.caption,
},
}
},
})
Now, the `${fields.caption}` variable will be available in the Assembly template.
Combine the `getAssemblyOptions()` option with the [Form](/docs/form) plugin to pass user input from a `<form>` to a Transloadit Assembly:
js
// This will add form field values to each file's `.meta` object:
uppy.use(Form, { getMetaFromForm: true })
uppy.use(Transloadit, {
getAssemblyOptions (file) {
return {
params: { },
// Pass through the fields you need:
fields: {
message: file.meta.message,
},
}
},
})
`getAssemblyOptions()` may also return a Promise, so it could retrieve signed Assembly parameters from a server. For example, assuming an endpoint `/transloadit-params` that responds with a JSON object with `{ params, signature }` properties:
js
uppy.use(Transloadit, {
getAssemblyOptions (file) {
return fetch('/transloadit-params').then((response) => {
return response.json()
})
},
})
`limit: 0`
Limit the amount of uploads going on at the same time. Setting this to `0` means no limit on concurrent uploads. This option is passed through to the [`@uppy/tus`](/docs/tus) plugin that Transloadit plugin uses internally.
`locale: {}`
<!-- eslint-disable <API key>, <API key> -->
js
module.exports = {
strings: {
// Shown while Assemblies are being created for an upload.
creatingAssembly: 'Preparing upload...',
// Shown if an Assembly could not be created.
<API key>: 'Transloadit: Could not create Assembly',
// Shown after uploads have succeeded, but when the Assembly is still executing.
// This only shows if `waitForMetadata` or `waitForEncoding` was enabled.
encoding: 'Encoding...',
},
}
## Errors
If an error occurs when an Assembly has already started, you can find the Assembly Status on the error object’s `assembly` property.
js
uppy.on('error', (error) => {
if (error.assembly) {
console.log(`Assembly ID ${error.assembly.assembly_id} failed!`)
console.log(error.assembly)
}
})
## Events
`transloadit:assembly-created`
Fired when an Assembly is created.
**Parameters**
* `assembly` - The initial [Assembly Status][assembly-status].
* `fileIDs` - The IDs of the files that will be uploaded to this Assembly.
js
uppy.on('transloadit:assembly-created', (assembly, fileIDs) => {
console.group('Created', assembly.assembly_id, 'for files:')
for (const id of fileIDs) {
console.log(uppy.getFile(id).name)
}
console.groupEnd()
})
`transloadit:upload`
Fired when Transloadit has received an upload.
**Parameters**
* `file` - The Transloadit file object that was uploaded.
* `assembly` - The [Assembly Status][assembly-status] of the Assembly to which the file was uploaded.
`transloadit:assembly-executing`
Fired when Transloadit has received all uploads, and is executing the Assembly.
**Parameters**
* `assembly` - The [Assembly Status](https://transloadit.com/docs/api/#<API key>) of the Assembly that is executing.
`transloadit:result`
Fired when a result came in from an Assembly.
**Parameters**
* `stepName` - The name of the Assembly step that generated this result.
* `result` - The result object from Transloadit.
This result object has one more property, namely `localId`.
This is the ID of the file in Uppy’s local state, and can be used with `uppy.getFile(id)`.
* `assembly` - The [Assembly Status][assembly-status] of the Assembly that generated this result.
js
uppy.on('transloadit:result', (stepName, result) => {
const file = uppy.getFile(result.localId)
document.body.appendChild(html`
<div>
<h2>From ${file.name}</h2>
<a href=${result.ssl_url}> View </a>
</div>
`)
})
`transloadit:complete`
Fired when an Assembly completed.
**Parameters**
* `assembly` - The final [Assembly Status][assembly-status] of the completed Assembly.
js
uppy.on('transloadit:complete', (assembly) => {
// Could do something fun with this!
console.log(assembly.results)
})
[assembly-status]: https://transloadit.com/docs/api/#<API key>
[<API key>]: https://transloadit.com/docs/#<API key>
|
module Tire
module Model
module Persistence
# Provides infrastructure for storing records in _Elasticsearch_.
module Storage
def self.included(base)
base.class_eval do
extend ClassMethods
include InstanceMethods
end
end
module ClassMethods
def create(args={})
document = new(args)
return false unless document.valid?
if result = document.save
document
else
result
end
end
end
module InstanceMethods
def update_attribute(name, value)
__update_attributes name => value
save
end
def update_attributes(attributes={})
__update_attributes attributes
save
end
def update_index
run_callbacks :<API key> do
if destroyed?
response = index.remove self
else
if response = index.store( self, {:percolate => percolator} )
self.id ||= response['_id']
self._index = response['_index']
self._type = response['_type']
self._version = response['_version']
self.matches = response['matches']
end
end
response
end
end
def save
return false unless valid?
run_callbacks :save do
response = update_index
!! response['ok']
end
end
def destroy
run_callbacks :destroy do
@destroyed = true
response = update_index
! response.nil?
end
end
def destroyed? ; !!@destroyed; end
def persisted? ; !!id && !!_version; end
def new_record? ; !persisted?; end
end
end
end
end
end
|
class ItemsController < <API key>
def create
item = Item.new(item_params)
item.user_id = @user.id
if item.save
render json: item, status: 201
else
render json: item.errors, status: 422
end
end
def destroy
item = find_item
item.destroy
head 204
end
def index
render json: @user.items.as_json, status: 200
end
def show
item = find_item
render json: item.as_json, status: 200
end
def update
item = find_item
if item.update(item_params)
render json: item.as_json, status: 200
end
end
def find_item
Item.find(params[:id])
end
private
def item_params
params.require(:item).permit(:type, :brand, :size, :color, :description)
end
end
|
#ifndef QHTTPMULTIPART_H
#define QHTTPMULTIPART_H
#include <QtCore/QSharedDataPointer>
#include <QtCore/QByteArray>
#include <QtCore/QIODevice>
#include <QtNetwork/QNetworkRequest>
QT_BEGIN_NAMESPACE
class QHttpPartPrivate;
class QHttpMultiPart;
class Q_NETWORK_EXPORT QHttpPart
{
public:
QHttpPart();
QHttpPart(const QHttpPart &other);
~QHttpPart();
#ifdef <API key>
QHttpPart &operator=(QHttpPart &&other) Q_DECL_NOTHROW { swap(other); return *this; }
#endif
QHttpPart &operator=(const QHttpPart &other);
void swap(QHttpPart &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
bool operator==(const QHttpPart &other) const;
inline bool operator!=(const QHttpPart &other) const
{ return !operator==(other); }
void setHeader(QNetworkRequest::KnownHeaders header, const QVariant &value);
void setRawHeader(const QByteArray &headerName, const QByteArray &headerValue);
void setBody(const QByteArray &body);
void setBodyDevice(QIODevice *device);
private:
QSharedDataPointer<QHttpPartPrivate> d;
friend class <API key>;
};
Q_DECLARE_SHARED(QHttpPart)
class <API key>;
class Q_NETWORK_EXPORT QHttpMultiPart : public QObject
{
Q_OBJECT
public:
enum ContentType {
MixedType,
RelatedType,
FormDataType,
AlternativeType
};
explicit QHttpMultiPart(QObject *parent = Q_NULLPTR);
explicit QHttpMultiPart(ContentType contentType, QObject *parent = Q_NULLPTR);
~QHttpMultiPart();
void append(const QHttpPart &httpPart);
void setContentType(ContentType contentType);
QByteArray boundary() const;
void setBoundary(const QByteArray &boundary);
private:
Q_DECLARE_PRIVATE(QHttpMultiPart)
Q_DISABLE_COPY(QHttpMultiPart)
friend class <API key>;
friend class <API key>;
};
QT_END_NAMESPACE
#endif // QHTTPMULTIPART_H
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Killer : MonoBehaviour {
public Transform RobotPlayer;
public GameObject Robot;
public Text GameOVER;
// Use this for initialization
void Start() {
RobotPlayer = GetComponent<Transform>();
}
void FixedUpdate()
{
if(RobotPlayer.gameObject.transform.position.y < -2)
{
GameOVER.gameObject.SetActive(true);
}
}
}
|
module Linter
class Base
def self.can_lint?(filename)
self::FILE_REGEXP === filename
end
def initialize(hound_config:, build:, <API key>:)
@hound_config = hound_config
@build = build
@<API key> = <API key>
end
def file_review(commit_file)
attributes = <API key>(commit_file)
file_review = FileReview.create!(
build: build,
filename: commit_file.filename,
)
enqueue_job(attributes)
file_review
end
def enabled?
config.linter_names.any? do |linter_name|
hound_config.enabled_for?(linter_name)
end
end
def file_included?(*)
true
end
def name
self.class.name.demodulize.underscore
end
private
attr_reader :hound_config, :build, :<API key>
def <API key>(commit_file)
{
commit_sha: build.commit_sha,
config: config.content,
content: commit_file.content,
filename: commit_file.filename,
patch: commit_file.patch,
pull_request_number: build.pull_request_number,
}
end
def enqueue_job(attributes)
Resque.enqueue(job_class, attributes)
end
def job_class
"#{name.classify}ReviewJob".constantize
end
def config
@config ||= ConfigBuilder.for(hound_config, name)
end
end
end
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Lighthouse: lapack/dsprfs.f File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="tabs.css" rel="stylesheet" type="text/css" />
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<!--<div id="titlearea">
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="<API key>.html">lapack</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#func-members">Functions/Subroutines</a> </div>
<div class="headertitle">
<div class="title">dsprfs.f File Reference</div> </div>
</div><!--header
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions/Subroutines</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">subroutine </td><td class="memItemRight" valign="bottom"><a class="el" href="dsprfs_8f.html#<API key>">dsprfs</a> (UPLO, N, NRHS, AP, AFP, IPIV, B, LDB, X, LDX, FERR, BERR, WORK, IWORK, INFO)</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight"><b>DSPRFS</b> <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Function/Subroutine Documentation</h2>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">subroutine dsprfs </td>
<td>(</td>
<td class="paramtype">character </td>
<td class="paramname"><em>UPLO</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>N</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>NRHS</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension( * ) </td>
<td class="paramname"><em>AP</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension( * ) </td>
<td class="paramname"><em>AFP</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer, dimension( * ) </td>
<td class="paramname"><em>IPIV</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension( ldb, * ) </td>
<td class="paramname"><em>B</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>LDB</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension( ldx, * ) </td>
<td class="paramname"><em>X</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>LDX</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension( * ) </td>
<td class="paramname"><em>FERR</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension( * ) </td>
<td class="paramname"><em>BERR</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension( * ) </td>
<td class="paramname"><em>WORK</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer, dimension( * ) </td>
<td class="paramname"><em>IWORK</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>INFO</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p><b>DSPRFS</b> </p>
<p>
Download DSPRFS + dependencies
<a href="http:
[TGZ]</a>
<a href="http:
[ZIP]</a>
<a href="http:
[TXT]</a>
</p><dl class="section user"><dt>Purpose: </dt><dd><pre class="fragment"> DSPRFS improves the computed solution to a system of linear
equations when the coefficient matrix is symmetric indefinite
and packed, and provides error bounds and backward error estimates
for the solution.</pre> </dd></dl>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramdir">[in]</td><td class="paramname">UPLO</td><td><pre class="fragment"> UPLO is CHARACTER*1
= 'U': Upper triangle of A is stored;
= 'L': Lower triangle of A is stored.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">N</td><td><pre class="fragment"> N is INTEGER
The order of the matrix A. N >= 0.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">NRHS</td><td><pre class="fragment"> NRHS is INTEGER
The number of right hand sides, i.e., the number of columns
of the matrices B and X. NRHS >= 0.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">AP</td><td><pre class="fragment"> AP is DOUBLE PRECISION array, dimension (N*(N+1)/2)
The upper or lower triangle of the symmetric matrix A, packed
columnwise in a linear array. The j-th column of A is stored
in the array AP as follows:
if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1<=i<=j;
if UPLO = 'L', AP(i + (j-1)*(2*n-j)/2) = A(i,j) for j<=i<=n.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">AFP</td><td><pre class="fragment"> AFP is DOUBLE PRECISION array, dimension (N*(N+1)/2)
The factored form of the matrix A. AFP contains the block
diagonal matrix D and the multipliers used to obtain the
factor U or L from the factorization A = U*D*U**T or
A = L*D*L**T as computed by DSPTRF, stored as a packed
triangular matrix.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">IPIV</td><td><pre class="fragment"> IPIV is INTEGER array, dimension (N)
Details of the interchanges and the block structure of D
as determined by DSPTRF.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">B</td><td><pre class="fragment"> B is DOUBLE PRECISION array, dimension (LDB,NRHS)
The right hand side matrix B.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">LDB</td><td><pre class="fragment"> LDB is INTEGER
The leading dimension of the array B. LDB >= max(1,N).</pre></td></tr>
<tr><td class="paramdir">[in,out]</td><td class="paramname">X</td><td><pre class="fragment"> X is DOUBLE PRECISION array, dimension (LDX,NRHS)
On entry, the solution matrix X, as computed by DSPTRS.
On exit, the improved solution matrix X.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">LDX</td><td><pre class="fragment"> LDX is INTEGER
The leading dimension of the array X. LDX >= max(1,N).</pre></td></tr>
<tr><td class="paramdir">[out]</td><td class="paramname">FERR</td><td><pre class="fragment"> FERR is DOUBLE PRECISION array, dimension (NRHS)
The estimated forward error bound for each solution vector
X(j) (the j-th column of the solution matrix X).
If XTRUE is the true solution corresponding to X(j), FERR(j)
is an estimated upper bound for the magnitude of the largest
element in (X(j) - XTRUE) divided by the magnitude of the
largest element in X(j). The estimate is as reliable as
the estimate for RCOND, and is almost always a slight
overestimate of the true error.</pre></td></tr>
<tr><td class="paramdir">[out]</td><td class="paramname">BERR</td><td><pre class="fragment"> BERR is DOUBLE PRECISION array, dimension (NRHS)
The componentwise relative backward error of each solution
vector X(j) (i.e., the smallest relative change in
any element of A or B that makes X(j) an exact solution).</pre></td></tr>
<tr><td class="paramdir">[out]</td><td class="paramname">WORK</td><td><pre class="fragment"> WORK is DOUBLE PRECISION array, dimension (3*N)</pre></td></tr>
<tr><td class="paramdir">[out]</td><td class="paramname">IWORK</td><td><pre class="fragment"> IWORK is INTEGER array, dimension (N)</pre></td></tr>
<tr><td class="paramdir">[out]</td><td class="paramname">INFO</td><td><pre class="fragment"> INFO is INTEGER
= 0: successful exit
< 0: if INFO = -i, the i-th argument had an illegal value</pre> </td></tr>
</table>
</dd>
</dl>
<dl class="section user"><dt>Internal Parameters: </dt><dd><pre class="fragment"> ITMAX is the maximum number of steps of iterative refinement.</pre> </dd></dl>
<dl class="section author"><dt>Author</dt><dd>Univ. of Tennessee </dd>
<dd>
Univ. of California Berkeley </dd>
<dd>
Univ. of Colorado Denver </dd>
<dd>
NAG Ltd. </dd></dl>
<dl class="section date"><dt>Date</dt><dd>November 2011 </dd></dl>
</div>
</div>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Wed Apr 1 2015 16:27:43 for Lighthouse by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
|
<?php
namespace FluentDOM\Query {
use FluentDOM\Query;
use FluentDOM\TestCase;
require_once __DIR__.'/../../TestCase.php';
class <API key> extends TestCase {
protected $_directory = __DIR__;
/**
* @group Traversing
* @group TraversingFind
* @covers \FluentDOM\Query::parents
*/
public function testParents(): void {
$fd = $this-><API key>(__FUNCTION__);
$this->assertInstanceOf(Query::class, $fd);
$parents = $fd
->find('
->parents()
->map(
function($node) {
return $node->tagName;
}
);
$this->assertTrue(is_array($parents));
$this->assertContains('span', $parents);
$this->assertContains('p', $parents);
$this->assertContains('div', $parents);
$this->assertContains('body', $parents);
$this->assertContains('html', $parents);
$parents = implode(', ', $parents);
$doc = $fd
->find('
->append('<strong>'.htmlspecialchars($parents).'</strong>');
$this->assertInstanceOf(Query::class, $doc);
$this-><API key>(__FUNCTION__, $doc);
}
}
}
|
(function() {
'use strict';
angular
.module('app.match')
.run(appRun);
appRun.$inject = ['routerHelper'];
/* @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return [{
state: 'match',
config: {
url: '/match/:id',
templateUrl: 'app/match/match.html',
controller: 'MatchController',
controllerAs: 'vm',
title: 'Match',
settings: {
nav: 2,
content: '<i class="fa fa-lock"></i> Match'
}
}
}];
}
})();
|
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-docu',
templateUrl: './docu.component.html',
styleUrls: ['./docu.component.scss']
})
export class DocuComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
|
using System;
using System.Linq;
using Cresce.Datasources.Sql;
using Cresce.Models;
using NUnit.Framework;
namespace Cresce.Business.Tests.Integration.Sql
{
[TestFixture]
internal class <API key> : SqlTests
{
private <API key> _repository;
private Patient _patient;
public <API key>()
{
_repository = new <API key>(this);
}
[SetUp]
public void CreateResources()
{
_patient = Utils.SavePatient();
}
[Test]
public void <API key>()
{
// Arrange
var invoice = Utils.SaveInvoice(_patient);
// Act
_repository.Delete(invoice.Id);
// Assert
var invoiceById = _repository.GetById(invoice.Id);
Assert.That(invoiceById, Is.Null);
}
[Test]
public void When_deleting_an_invoice_linked_with_an_appointment_it_should_be_removed_from_the_database()
{
// Arrange
var invoice = Utils.SaveInvoice(_patient);
Utils.SaveAppointment(Utils.SaveUser(), _patient, Utils.SaveService(), new DateTime(), invoiceId: invoice.Id);
// Act
_repository.Delete(invoice.Id);
// Assert
var invoiceById = _repository.GetById(invoice.Id);
Assert.That(invoiceById, Is.Null);
}
[Test]
public void <API key>()
{
// Arrange
var invoice = Utils.SaveInvoice(_patient);
// Act
var result = _repository.GetById(invoice.Id);
// Assert
Assert.That(result, Is.Not.Null);
}
[Test]
public void <API key>()
{
// Arrange
var invoice = Utils.SaveInvoice(
_patient,
date: new DateTime(2017, 10, 23)
);
// Act
var result = _repository.GetById(invoice.Id);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.PatientId, Is.EqualTo(_patient.Id));
Assert.That(result.Date, Is.EqualTo(new DateTime(2017, 10, 23)));
Assert.That(result.Description, Is.EqualTo("some description"));
Assert.That(result.Value, Is.EqualTo(23.4));
}
[Test]
public void <API key>()
{
// Arrange
var invoiceId = "-1";
// Act
var result = _repository.GetById(invoiceId);
// Assert
Assert.That(result, Is.Null);
}
[Test]
public void When_getting_an_invoices_for_patient_id_it_should_return_only_invoices_of_that_patient()
{
// Arrange
Utils.SaveInvoice(_patient, date: new DateTime(2017, 10, 23));
Utils.SaveInvoice(Utils.SavePatient("2"), date: new DateTime(2017, 10, 23));
// Act
var result = _repository.GetInvoices(_patient.Id).ToList();
// Assert
Assert.That(result.Count, Is.EqualTo(1));
}
[Test]
public void <API key>()
{
// Arrange
Utils.SaveInvoice(_patient, date: new DateTime(2017, 10, 23));
Utils.SaveInvoice(Utils.SavePatient("2"), date: new DateTime(2017, 10, 23));
// Act
var result = _repository.GetInvoices().ToList();
// Assert
Assert.That(result.Count, Is.EqualTo(2));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.