code stringlengths 4 1.01M |
|---|
using System;
namespace Oragon.Architecture.MessageQueuing
{
public interface IQueueConsumerWorker : IDisposable
{
bool ModelIsClosed { get; }
void DoConsume();
void Ack(ulong deliveryTag);
void Nack(ulong deliveryTag, bool requeue = false);
}
} |
{% extends "app_layout.html" %}
{% set active_page = "users" %}
{% block content %}
<h3>Hello! {{ g.user.full_name() }}</h3>
{% endblock %}
|
<?php
class Input {
public static $is_parsed = false;
public static $params = [];
/**
* Парсит и сохраняет все параметры в переменной self::$params
*
* @access protected
* @return $this
*/
protected static function parse() {
if (filter_input(INPUT_SERVER, 'argc')) {
$argv = filter_input(INPUT_SERVER, 'argv');
array_shift($argv); // file
static::$params['ACTION'] = array_shift($argv);
static::$params += $argv;
} elseif ((0 === strpos(filter_input(INPUT_SERVER, 'CONTENT_TYPE'), 'application/json'))) {
static::$params = (array) filter_input_array(INPUT_GET) + (array) json_decode(file_get_contents('php://input'), true);
} else {
static::$params = (array) filter_input_array(INPUT_POST) + (array) filter_input_array(INPUT_GET);
}
static::$is_parsed = true;
}
public static function set(string $key, $value) {
static::$is_parsed || static::parse();
static::$params[$key] = $value;
}
/**
* Получение переменной запроса
*
* <code>
* $test = Input::get('test');
*
* $params = Input::get(['test:int=1']);
* </code>
*/
public static function get(...$args) {
static::$is_parsed || static::parse();
if (!isset($args[0])) {
return static::$params;
}
// String key?
if (is_string($args[0])) {
return isset(static::$params[$args[0]])
? static::$params[$args[0]]
: (isset($args[1]) ? $args[1] : null);
}
if (is_array($args[0])) {
return static::extractTypified($args[0], function ($key, $default = null) {
return static::get($key, $default);
});
}
// Exctract typifie var by mnemonic rules as array
trigger_error('Error while fetch key from input');
}
/**
* Извлекает и типизирует параметры из массива args с помощью функции $fetcher, которая
* принимает на вход ключ из массива args и значение по умолчанию, если его там нет
*
* @param array $args
* @param Closure $fetcher ($key, $default)
*/
public static function extractTypified(array $args, Closure $fetcher) {
$params = [];
foreach ($args as $arg) {
preg_match('#^([a-zA-Z0-9_]+)(?:\:([a-z]+))?(?:\=(.+))?$#', $arg, $m);
$params[$m[1]] = $fetcher($m[1], isset($m[3]) ? $m[3] : '');
// Нужно ли типизировать
if (isset($m[2])) {
typify($params[$m[1]], $m[2]);
}
}
return $params;
}
}
|
#include "pch.hpp"
#include "default_log.hpp"
#include "service_log.hpp"
#include "service_helpers.hpp"
namespace be {
///////////////////////////////////////////////////////////////////////////////
bool default_log_available() {
return check_service<Log>();
}
///////////////////////////////////////////////////////////////////////////////
Log& default_log() {
return service<Log>();
}
} // be
|
/**
* This code was auto-generated by a Codezu.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.api.clients.commerce.orders;
import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import com.mozu.api.security.AuthTicket;
import org.apache.commons.lang3.StringUtils;
/** <summary>
* Use the Fulfillment resource to manage shipments or pickups of collections of packages for an order.
* </summary>
*/
public class FulfillmentActionClient {
/**
* Sets the fulfillment action to "Ship" or "PickUp". To ship an order or prepare it for in-store pickup, the order must have a customer name, the "Open" or "OpenAndProcessing" status. To ship the order, it must also have the full shipping address and shipping method. Shipping all packages or picking up all pickups for an order will complete a paid order.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> mozuClient=PerformFulfillmentActionClient( action, orderId);
* client.setBaseAddress(url);
* client.executeRequest();
* Order order = client.Result();
* </code></pre></p>
* @param orderId Unique identifier of the order for which to perform the fulfillment action.
* @param action The action to perform for the order fulfillment.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.orders.Order>
* @see com.mozu.api.contracts.commerceruntime.orders.Order
* @see com.mozu.api.contracts.commerceruntime.fulfillment.FulfillmentAction
*/
public static MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> performFulfillmentActionClient(com.mozu.api.contracts.commerceruntime.fulfillment.FulfillmentAction action, String orderId) throws Exception
{
return performFulfillmentActionClient( action, orderId, null);
}
/**
* Sets the fulfillment action to "Ship" or "PickUp". To ship an order or prepare it for in-store pickup, the order must have a customer name, the "Open" or "OpenAndProcessing" status. To ship the order, it must also have the full shipping address and shipping method. Shipping all packages or picking up all pickups for an order will complete a paid order.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> mozuClient=PerformFulfillmentActionClient( action, orderId, responseFields);
* client.setBaseAddress(url);
* client.executeRequest();
* Order order = client.Result();
* </code></pre></p>
* @param orderId Unique identifier of the order for which to perform the fulfillment action.
* @param responseFields Updated order with a new fulfillment status resulting from the action supplied in the request.
* @param action The action to perform for the order fulfillment.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.orders.Order>
* @see com.mozu.api.contracts.commerceruntime.orders.Order
* @see com.mozu.api.contracts.commerceruntime.fulfillment.FulfillmentAction
*/
public static MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> performFulfillmentActionClient(com.mozu.api.contracts.commerceruntime.fulfillment.FulfillmentAction action, String orderId, String responseFields) throws Exception
{
MozuUrl url = com.mozu.api.urls.commerce.orders.FulfillmentActionUrl.performFulfillmentActionUrl(orderId, responseFields);
String verb = "POST";
Class<?> clz = com.mozu.api.contracts.commerceruntime.orders.Order.class;
MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> mozuClient = new MozuClient(clz);
mozuClient.setVerb(verb);
mozuClient.setResourceUrl(url);
mozuClient.setBody(action);
return mozuClient;
}
}
|
//
// VariableValueReference.cs
//
// Author:
// Lluis Sanchez Gual <lluis@novell.com>
//
// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Mono.Debugging.Evaluation;
using Mono.Debugging.Client;
using Mono.Debugger.Soft;
namespace Mono.Debugging.Soft
{
public class VariableValueReference : ValueReference
{
readonly LocalVariable variable;
LocalVariableBatch batch;
Value value;
string name;
public VariableValueReference (EvaluationContext ctx, string name, LocalVariable variable, LocalVariableBatch batch) : base (ctx)
{
this.variable = variable;
this.batch = batch;
this.name = name;
}
public VariableValueReference (EvaluationContext ctx, string name, LocalVariable variable, Value value) : base (ctx)
{
this.variable = variable;
this.value = value;
this.name = name;
}
public VariableValueReference (EvaluationContext ctx, string name, LocalVariable variable) : base (ctx)
{
this.variable = variable;
this.name = name;
}
public override ObjectValueFlags Flags {
get {
return ObjectValueFlags.Variable;
}
}
public override string Name {
get {
return name;
}
}
public override object Type {
get {
return variable.Type;
}
}
Value NormalizeValue (EvaluationContext ctx, Value value)
{
if (variable.Type.IsPointer) {
long addr = (long) ((PrimitiveValue) value).Value;
return new PointerValue (value.VirtualMachine, variable.Type, addr);
}
return ctx.Adapter.IsNull (ctx, value) ? null : value;
}
public override object Value {
get {
var ctx = (SoftEvaluationContext) Context;
try {
if (value == null)
value = batch != null ? batch.GetValue (variable) : ctx.Frame.GetValue (variable);
return NormalizeValue (ctx, value);
} catch (AbsentInformationException) {
throw new EvaluatorException ("Value not available");
} catch (ArgumentException ex) {
throw new EvaluatorException (ex.Message);
}
}
set {
((SoftEvaluationContext) Context).Frame.SetValue (variable, (Value) value);
this.value = (Value) value;
}
}
}
}
|
{% load cobweb_look %}
{% load jargon %}
{% load i18n %}
{% if link_url %}
<a href="{{ link_url }}" class="btn btn-primary">
+ Add a {% term "nomination" %}
</a>
{% endif %} |
---
title: 'txt2re: Regular Expression Generator'
date: '2011-10-10T03:56:00.000-07:00'
tags:
- Regex
- Utilities
modified_time: '2011-10-10T05:14:47.941-07:00'
blogger_id: tag:blogger.com,1999:blog-3456458686961244994.post-7064012350422304264
blogger_orig_url: http://blog.kieranties.com/2011/10/txt2re-regular-expression-generator.html
redirect_from: "/2011/10/txt2re-regular-expression-generator.html"
---
<a href="http://txt2re.com/">[Link]</a><br />A pretty awesome page to help when creating regular expressions. Type in the string you want to match, then use the selectors to create a snippet of code with the regex and validation process pre-populated, allowing you to drop the code straight into your application. (full credit to <a href="https://twitter.com/zoe_nolan">Zoe Nolan</a> for the link!)<br /><br />This is a cracking starting point for some simple regex work (or when your head just isn't wrapping itself around the joys of regex), but for more detailed help, pointers and tips I'd suggest taking a look at the following: <br /><ul><li><a href="http://regexlib.com/">Regex Library</a></li><li><a href="http://www.regular-expressions.info/">Regular Expressions Info</a></li></ul> |
//
// MenuViewController.h
// MBXMapKit
//
// Created by Gevorg Ghukasyan on 2/9/15.
// Copyright (c) 2015 MapBox. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface MenuViewController : UIViewController
@end
|
<?php
return array(
/*
|--------------------------------------------------------------------------
| Module Language Lines
|--------------------------------------------------------------------------
|
| This file keeps the language lines of the related module.
|
*/
'receiver' => 'Destinataire',
'message_sent' => 'Votre message a été envoyé.',
're' => 'Re: ',
'system_info' => 'Ce message a été créé automatiquement.',
);
|
/**
* Copyright 2015 aixigo AG
* Released under the MIT license.
* http://laxarjs.org/license
*/
require( [
'laxar',
'laxar-application/var/flows/embed/dependencies',
'json!laxar-application/var/flows/embed/resources.json'
], function( ax, mainDependencies, mainResources ) {
'use strict';
window.laxar.fileListings = {
application: mainResources,
bower_components: mainResources,
includes: mainResources
};
ax.bootstrap( mainDependencies );
} );
|
// Langevin.h -- The Velocity Verlet molecular dynamics algorithm.
// -*- c++ -*-
//
// Copyright (C) 2001-2011 Jakob Schiotz and Center for Individual
// Nanoparticle Functionality, Department of Physics, Technical
// University of Denmark. Email: schiotz@fysik.dtu.dk
//
// This file is part of Asap version 3.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// version 3 as published by the Free Software Foundation. Permission
// to use other versions of the GNU Lesser General Public License may
// granted by Jakob Schiotz or the head of department of the
// Department of Physics, Technical University of Denmark, as
// described in section 14 of the GNU General Public License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// and the GNU Lesser Public License along with this program. If not,
// see <http://www.gnu.org/licenses/>.
#ifndef _LANGEVIN_H
#define _LANGEVIN_H
#include "AsapPython.h"
#include "Asap.h"
#include "AsapObject.h"
#include "Vec.h"
#include "MolecularDynamics.h"
#include <vector>
namespace ASAPSPACE {
class Potential;
class DynamicAtoms;
class AsapRandomThread;
class Langevin : public MolecularDynamics
{
public:
Langevin(PyObject *py_atoms, Potential *calc, double timestep,
PyObject *sdpos_name, PyObject *sdmom_name, PyObject *c1_name,
PyObject *c2_name, bool fixcm, unsigned int seed);
virtual ~Langevin();
virtual string GetName() const {return "Langevin";}
// Constants are scalars and given here.
void SetScalarConstants(double act0, double c3, double c4, double pmcor,
double cnst);
// Constants are vectors on the atoms.
void SetVectorConstants(PyObject *act0_name, PyObject *c3_name,
PyObject *c4_name, PyObject *pmcor_name,
PyObject *cnst_name);
// Get the random numbers
void GetRandom(std::vector<Vec> &x1, std::vector<Vec> &x2, bool gaussian=true);
protected:
// Run the dynamics. nsteps is the number of steps, observers is a Python
// list of observers, each observer described by a tuple
// (function, interval, args, kwargs) and function(*args, **kwargs) is
// called for each interval time steps.
//virtual void Run(int nsteps);
virtual void Run2(int nsteps, PyObject *observers, PyObject *self);
void ClearPyNames(); // Release Python variable names.
private:
bool fixcm;
bool vectorconstants; // Constants are vectors
double act0;
double c3;
double c4;
double pmcor;
double cnst;
PyObject *sdpos_name;
PyObject *sdmom_name;
PyObject *c1_name;
PyObject *c2_name;
PyObject *act0_name;
PyObject *c3_name;
PyObject *c4_name;
PyObject *pmcor_name;
PyObject *cnst_name;
AsapRandomThread *random;
};
} // end namespace
#endif // _LANGEVIN_H
|
package com.tommytao.a5steak.glocation;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} |
#include <check.h>
#include "check_ace_string.h"
#include "../src/ace_string.h"
// unit tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
START_TEST (join_two_strings)
{
char *result = ace_str_join_2 ("hello", " world");
ck_assert_str_eq (result, "hello world");
}
END_TEST
START_TEST (join_three_strings)
{
char *result = ace_str_join_3 ("whiskey", " tango", " foxtrot");
ck_assert_str_eq (result, "whiskey tango foxtrot");
}
END_TEST
START_TEST (string_ending)
{
ck_assert (ace_str_ends_with ("", ""));
ck_assert (ace_str_ends_with ("a", "a"));
ck_assert (ace_str_ends_with ("aa", "a"));
ck_assert (ace_str_ends_with ("hello world", "world"));
ck_assert (!ace_str_ends_with ("a", "b"));
ck_assert (!ace_str_ends_with ("a", "aa"));
ck_assert (!ace_str_ends_with ("hello world", "hello"));
}
END_TEST
// test case ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TCase *create_ace_string_testcase (void)
{
TCase *testcase = tcase_create ("String utils");
tcase_add_test (testcase, join_two_strings);
tcase_add_test (testcase, join_three_strings);
tcase_add_test (testcase, string_ending);
return testcase;
}
|
=begin
#The Plaid API
#The Plaid REST API. Please see https://plaid.com/docs/api for more details.
The version of the OpenAPI document: 2020-09-14_1.79.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.1.0
=end
require 'date'
require 'time'
module Plaid
# An object containing liability accounts
class LiabilitiesObject
# The credit accounts returned.
attr_accessor :credit
# The mortgage accounts returned.
attr_accessor :mortgage
# The student loan accounts returned.
attr_accessor :student
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'credit' => :'credit',
:'mortgage' => :'mortgage',
:'student' => :'student'
}
end
# Returns all the JSON keys this model knows about
def self.acceptable_attributes
attribute_map.values
end
# Attribute type mapping.
def self.openapi_types
{
:'credit' => :'Array<CreditCardLiability>',
:'mortgage' => :'Array<MortgageLiability>',
:'student' => :'Array<StudentLoan>'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
:'credit',
:'mortgage',
:'student'
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `Plaid::LiabilitiesObject` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `Plaid::LiabilitiesObject`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'credit')
if (value = attributes[:'credit']).is_a?(Array)
self.credit = value
end
end
if attributes.key?(:'mortgage')
if (value = attributes[:'mortgage']).is_a?(Array)
self.mortgage = value
end
end
if attributes.key?(:'student')
if (value = attributes[:'student']).is_a?(Array)
self.student = value
end
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
credit == o.credit &&
mortgage == o.mortgage &&
student == o.student
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[credit, mortgage, student].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
elsif type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :Time
Time.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
# models (e.g. Pet) or oneOf
klass = Plaid.const_get(type)
klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
|
<?php
namespace Delr3ves\RestApiBundle\Tests\Unit\Unmarshalling;
use Delr3ves\RestApiBundle\Unmarshalling\ContentTypeUtils;
use Delr3ves\RestApiBundle\Unmarshalling\FormatNotSupportedException;
class ContentTypeUtilsTest extends \PHPUnit_Framework_TestCase {
/**
* @var ContentTypeUtils
*/
protected $contentTypeUtils;
public function setUp() {
$this->contentTypeUtils = new ContentTypeUtils();
}
/**
* @dataProvider getValidNormalizedContentTypeProvider
*/
public function testNormalizeContentTypeShouldReturnType($providedContentType, $expectedType) {
$normalizedFormat = $this->contentTypeUtils->normalize($providedContentType);
$this->assertThat($normalizedFormat, $this->equalTo($expectedType));
}
/**
* @expectedException Delr3ves\RestApiBundle\Unmarshalling\FormatNotSupportedException
*/
public function testNormalizeContentTypeShouldThrowException() {
$this->contentTypeUtils->normalize('invalidContentType');
}
/**
* @dataProvider getValidAcceptContentTypeProvider
*/
public function testGetAcceptContentTypeShouldReturnType($providedContentType, $expectedType) {
$normalizedFormat = $this->contentTypeUtils->findAcceptType($providedContentType);
$this->assertThat($normalizedFormat, $this->equalTo($expectedType));
}
public static function getValidNormalizedContentTypeProvider() {
return array(
array(ContentTypeUtils::SIMPLE_JSON_FORMAT, ContentTypeUtils::JSON_FORMAT),
array(ContentTypeUtils::JSON_FORMAT, ContentTypeUtils::JSON_FORMAT),
array(ContentTypeUtils::SIMPLE_XML_FORMAT, ContentTypeUtils::XML_FORMAT),
array(ContentTypeUtils::XML_FORMAT, ContentTypeUtils::XML_FORMAT),
);
}
public static function getValidAcceptContentTypeProvider() {
return array(
array("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "application/xml"),
array(ContentTypeUtils::SIMPLE_JSON_FORMAT, ContentTypeUtils::JSON_FORMAT),
array(ContentTypeUtils::JSON_FORMAT, ContentTypeUtils::JSON_FORMAT),
array(ContentTypeUtils::SIMPLE_XML_FORMAT, ContentTypeUtils::XML_FORMAT),
array(ContentTypeUtils::XML_FORMAT, ContentTypeUtils::XML_FORMAT),
);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace dona.Forms.Dependencies
{
public interface INetworkInformation
{
string GetNetworkOperatorName();
}
}
|
<!DOCTYPE html>
<!--[if IE 6]> <html id="ie ie67 ie6" dir="ltr" lang="en-US"> <![endif]-->
<!--[if IE 7]> <html id="ie ie67 ie7" dir="ltr" lang="en-US"> <![endif]-->
<!--[if IE 8]> <html id="ie ie678 ie8" dir="ltr" lang="en-US"> <![endif]-->
<!--[if !(IE 6) | !(IE 7) | !(IE 8) ]><!--> <html dir="ltr" lang="en-US"> <!--<![endif]-->
<head>
<title>Crossings Community Church</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="css/screen.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/print.css" type="text/css" media="print" />
</head>
<body>
<div id="container">
<div id="header">
<!-- <h1><a href="http://crossingscommunity.com/"><span class="hide">Crossings Community Church</span></a></h1> -->
</div>
<div id="nav">
<ul>
<li id="about"><a href="/about.php">About Crossings</a></li>
<li id="sermons"><a href="sermons/">Sermons</a></li>
<li id="sermons"><a href="songs.php">Songs</a></li>
<li id="critter"><a href="critter-crossings.php">Critter Crossings</a></li>
<li id="members"><a href="members.php">Members</a></li>
<li id="week"><a href="restofweek.php">Rest of Week</a></li>
<li id="contact"><a href="contact.php">Contact Us</a></li>
</ul>
</div>
<div id="content">
<div id="content-contain">
<object type="text/html" data="ccc-rss.html">
<div id="right-col" class="column">
<h2>What's Happening</h2>
<div class="block">
<p class="quiet">Meeting Wednesdays and Fridays</p>
<h4>Bible Study</h4>
<p>Watch your email for which group you'll be in.</p>
</div>
<div class="block">
<p class="quiet">October 23-26, 2008</p>
<h4>Annual Crossings Retreat</h4>
<p>Stay tuned for details!</p>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
1 West Campbell Avenue, Campbell, CA 95008 - Sundays @ 10am. Join us for set-up and fellowship @ 9am
</div>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-2468518-1");
pageTracker._trackPageview();
} catch(err) {}</script>
</body>
</html>
|
# roadie-rails
[](https://github.com/Mange/roadie-rails/actions/workflows/main.yml)
[](https://codeclimate.com/github/Mange/roadie-rails)
[](https://codecov.io/github/Mange/roadie-rails?branch=master)
[](https://rubygems.org/gems/roadie-rails)
[][passive]
|||
|---|---|
| :warning: | This gem is now in [passive maintenance mode][passive] together with `roadie`. [(more)][passive] |
> Making HTML emails comfortable for the Rails rockstars.
This gem hooks up your Rails application with Roadie to help you generate HTML emails.
## Installation ##
[Add this gem to your Gemfile as recommended by Rubygems][gem] and run `bundle install`.
```ruby
gem 'roadie-rails', '~> 3.0'
```
## Usage ##
`roadie-rails` have two primary means of usage. The first on is the "Automatic usage", which does almost everything automatically. It's the easiest way to hit the ground running in order to see if `roadie` would be a good fit for your application.
As soon as you require some more "advanced" features (congratulations!), you should migrate to the "Manual usage" which entails that you do some things by yourself.
### Automatic usage ###
Include the `Roadie::Rails::Automatic` module inside your mailer. Roadie will do its magic when you try to deliver the message:
```ruby
class NewsletterMailer < ActionMailer::Base
include Roadie::Rails::Automatic
def user_newsletter(user)
mail to: user.email, subject: subject_for_user(user)
end
private
def subject_for_user(user)
I18n.translate 'emails.user_newsletter.subject', name: user.name
end
end
# email has the original body; Roadie has not been invoked yet
email = NewsletterMailer.user_newsletter(User.first)
# This triggers Roadie inlining and will deliver the email with inlined styles
email.deliver
```
By overriding the `#roadie_options` method in the mailer you can disable inlining in certain cases:
```ruby
class NewsletterMailer < ActionMailer::Base
include Roadie::Rails::Automatic
private
def roadie_options
super unless Rails.env.test?
end
end
```
Another way:
```ruby
describe YourMailer do
describe "email contents" do
before do
# Disable inlining
YourMailer.any_instance.stub(:roadie_options).and_return(nil)
end
# ...
end
describe "inlined email contents" do
# ...
end
end
```
If you need the extra flexibility, look at the "Manual usage" below.
### Manual usage ###
Include the `Roadie::Rails::Mailer` module inside your `ActionMailer` and call `roadie_mail` with the same options that you would pass to `mail`.
```ruby
class NewsletterMailer < ActionMailer::Base
include Roadie::Rails::Mailer
def user_newsletter(user)
roadie_mail to: user.email, subject: subject_for_user(user)
end
private
def subject_for_user(user)
I18n.translate 'emails.user_newsletter.subject', name: user.name
end
end
```
This will inline the stylesheets right away, which sadly decreases performance for your tests where you might only want to inline in one of them. The upside is that you can selectively inline yourself.
```ruby
class NewsletterMailer < ActionMailer::Base
include Roadie::Rails::Mailer
def subscriber_newsletter(subscriber, options = {})
use_roadie = options.fetch :use_roadie, true
mail_factory(use_roadie, normal_mail_options)
end
private
def mail_factory(use_roadie, options)
if use_roadie
roadie_mail options
else
mail options
end
end
end
# tests
describe NewsletterMailer do
it "is emailed to the subscriber's email" do
email = NewsletterMailer.subscriber_newsletter(subscriber, use_roadie: false)
email.to.should == subscriber.email
end
it "inlines the emails by default" do
email = NewsletterMailer.subscriber_newsletter(subscriber)
email.should be_good_and_cool_and_all_that_jazz
end
end
```
Or, perhaps by doing this:
```ruby
describe YourMailer do
describe "email contents" do
before do
# Redirect all roadie mail calls to the normal mail method
YourMailer.any_instance.stub(:roadie_mail) { |*args, &block| YourMailer.mail(*args, &block) }
end
# ...
end
describe "inlined email contents" do
# ...
end
end
```
### Configuration ###
Roadie can be configured in three places, depending on how specific you want to be:
1. `Rails.application.config.roadie` (global, static).
2. `YourMailer#roadie_options` (mailer, dynamic).
3. Second argument to the `roadie_mail` (mail, specific and custom).
You can override at any level in the chain, depending on how specific you need to be.
Only the first two methods are available to you if you use the `Automatic` module.
```ruby
# config/environments/production.rb
config.roadie.url_options = {host: "my-app.com", scheme: "https"}
# app/mailer/my_mailer.rb
class MyMailer
include Roadie::Rails::Mailer
protected
def roadie_options
super.merge(url_options: {host: Product.current.host})
end
end
# app/mailer/my_other_mailer.rb
class MyOtherMailer
include Roadie::Rails::Mailer
def some_mail(user)
roadie_mail {to: "foo@example.com"}, roadie_options_for(user)
end
private
def roadie_options_for(user)
roadie_options.combine({
asset_providers: [MyCustomProvider.new(user)],
url_options: {host: user.subdomain_with_host},
})
end
end
```
If you `#merge` you will replace the older value outright:
```ruby
def roadie_options
original = super
original.url_options # => {protocol: "https", host: "foo.com"}
new = original.merge(url_options: {host: "bar.com"})
new.url_options # => {host: "bar.com"}
new
end
```
If you want to combine two values, use `#combine`. `#combine` is closer to `Hash#deep_merge`:
```ruby
def roadie_options
original = super
original.url_options # => {protocol: "https", host: "foo.com"}
new = original.combine(url_options: {host: "bar.com"})
new.url_options # => {protocol: "https", host: "bar.com"}
new
end
```
`#combine` is smarter than `Hash#deep_merge`, though. It can combine callback `proc`s (so both get called) and `Roadie::ProviderList`s as well.
If you want to see the available configuration options, see the [Roadie gem][roadie].
### Templates ###
Use normal `stylesheet_link_tag` and `foo_path` methods when generating your email and Roadie will look for the precompiled files on your filesystem, or by asking the asset pipeline to compile the files for you if it cannot be found.
### Previewing ###
You can create a controller that gets the email and then renders the body from it.
```ruby
class Admin::EmailsController < AdminController
def user_newsletter
render_email NewsletterMailer.user_newsletter(current_user)
end
def subscriber_newsletter
render_email NewsletterMailer.subscriber_newsletter(Subscriber.first || Subscriber.new)
end
private
def render_email(email)
respond_to do |format|
format.html { render html: email.html_part.decoded.html_safe }
format.text { render text: email.text_part.decoded }
end
end
end
```
## Known issues ##
Roadie will not be able to find your stylesheets if you have an `asset_host` configured and will ignore those lines when inlining.
A workaround for this is to not use `asset_host` in your mailers:
```ruby
config.action_controller.asset_host = # ...
config.action_mailer.asset_host = nil
# or
class MyMailer < ActionMailer::Base
self.asset_host = nil
end
```
## Build status ##
Tested with Github Actions on multiple Ruby and Rails versions:
* Ruby:
* MRI 2.6
* MRI 2.7
* MRI 3.0
* MRI 3.1
* Rails
* 5.1
* 5.2
* 6.0
* 6.1
* 7.0
Please note that [all Rails-versions are not compatible with all Ruby-versions](https://www.fastruby.io/blog/ruby/rails/versions/compatibility-table.html).
Let me know if you want any other combination supported officially.
### Versioning ###
This project follows [Semantic Versioning][semver].
## Documentation ##
* [Online documentation for gem](https://www.omniref.com/ruby/gems/roadie-rails)
* [Online documentation for master](https://www.omniref.com/github/Mange/roadie-rails)
* [Changelog](https://github.com/Mange/roadie-rails/blob/master/Changelog.md)
## Running specs ##
The default `rake` task will take care of the setup for you.
```bash
rake
```
After running `rake` for the first time and you want to keep running tests without having to install all dependencies, you may run `guard`, `rspec` or `rake spec` depending on what you prefer.
## License ##
(The MIT License)
Copyright © 2013-2022 [Magnus Bergmark](https://github.com/Mange) <magnus.bergmark@gmail.com>, et. al.
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.
[roadie]: http://rubygems.org/gems/roadie
[semver]: http://semver.org/
[gem]: http://rubygems.org/gems/roadie-rails
[passive]: https://github.com/Mange/roadie/issues/155
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>module Taxcalendario::Client::Entities - RDoc Documentation</title>
<link href="../../fonts.css" rel="stylesheet">
<link href="../../rdoc.css" rel="stylesheet">
<script type="text/javascript">
var rdoc_rel_prefix = "../../";
</script>
<script src="../../js/jquery.js"></script>
<script src="../../js/navigation.js"></script>
<script src="../../js/search_index.js"></script>
<script src="../../js/search.js"></script>
<script src="../../js/searcher.js"></script>
<script src="../../js/darkfish.js"></script>
<body id="top" role="document" class="module">
<nav role="navigation">
<div id="project-navigation">
<div id="home-section" role="region" title="Quick navigation" class="nav-section">
<h2>
<a href="../../index.html" rel="home">Home</a>
</h2>
<div id="table-of-contents-navigation">
<a href="../../table_of_contents.html#pages">Pages</a>
<a href="../../table_of_contents.html#classes">Classes</a>
<a href="../../table_of_contents.html#methods">Methods</a>
</div>
</div>
<div id="search-section" role="search" class="project-section initially-hidden">
<form action="#" method="get" accept-charset="utf-8">
<div id="search-field-wrapper">
<input id="search-field" role="combobox" aria-label="Search"
aria-autocomplete="list" aria-controls="search-results"
type="text" name="search" placeholder="Search" spellcheck="false"
title="Type to search, Up and Down to navigate, Enter to load">
</div>
<ul id="search-results" aria-label="Search Results"
aria-busy="false" aria-expanded="false"
aria-atomic="false" class="initially-hidden"></ul>
</form>
</div>
</div>
<div id="class-metadata">
</div>
</nav>
<main role="main" aria-labelledby="module-Taxcalendario::Client::Entities">
<h1 id="module-Taxcalendario::Client::Entities" class="module">
module Taxcalendario::Client::Entities
</h1>
<section class="description">
</section>
<section id="5Buntitled-5D" class="documentation-section">
</section>
</main>
<footer id="validator-badges" role="contentinfo">
<p><a href="http://validator.w3.org/check/referer">Validate</a>
<p>Generated by <a href="http://rdoc.rubyforge.org">RDoc</a> 4.1.2.
<p>Based on <a href="http://deveiate.org/projects/Darkfish-Rdoc/">Darkfish</a> by <a href="http://deveiate.org">Michael Granger</a>.
</footer>
|
# Nginx Log Tools
Every time something crops up I find myself writing a tool to chop up the log files and
find out what was happening. These are the more general of the tools that I have created
over the years so I know where to find them in the future
## What data is reported
The application can report three things:
1. **`response`** The minimum, average and maximum response times for a request. Shown here by hour
$ ngxl --report response --by hour <log files>
| date_and_hour | count | min | avg | max |
+---------------+----------+----------+----------+----------+
| 2019-09-24 06 | 11623 | 0.006 | 0.616 | 8.219 |
| 2019-09-24 07 | 102476 | 0.011 | 0.610 | 8.744 |
| 2019-09-24 08 | 103262 | 0.000 | 0.609 | 8.537 |
| 2019-09-24 09 | 103537 | 0.000 | 0.608 | 8.594 |
| 2019-09-24 10 | 103746 | 0.000 | 0.608 | 8.969 |
| 2019-09-24 11 | 103653 | 0.010 | 0.611 | 8.630 |
| 2019-09-24 12 | 103392 | 0.012 | 0.612 | 9.005 |
| 2019-09-24 13 | 103423 | 0.007 | 0.616 | 9.182 |
| 2019-09-24 14 | 102568 | 0.000 | 0.614 | 8.781 |
| 2019-09-24 15 | 92875 | 0.012 | 0.608 | 8.946 |
2. **`status`** A count of the status codes by class
$ ngxl --report status --by hour <log files>
| date_and_hour | count | 2xx | 3xx | 4xx | 5xx |
+---------------+----------+--------+--------+--------+--------+
| 2019-09-24 06 | 11623 | 11622 | 0 | 1 | 0 |
| 2019-09-24 07 | 102476 | 102476 | 0 | 0 | 0 |
| 2019-09-24 08 | 103262 | 103253 | 1 | 8 | 0 |
| 2019-09-24 09 | 103537 | 103533 | 3 | 1 | 0 |
| 2019-09-24 10 | 103746 | 103650 | 8 | 88 | 0 |
| 2019-09-24 11 | 103653 | 103644 | 2 | 6 | 1 |
| 2019-09-24 12 | 103392 | 103374 | 0 | 18 | 0 |
| 2019-09-24 13 | 103423 | 103422 | 1 | 0 | 0 |
| 2019-09-24 14 | 102568 | 102559 | 1 | 8 | 0 |
| 2019-09-24 15 | 92875 | 92875 | 0 | 0 | 0 |
3. **`size`** Reports the total size of all the responses along with their minimum. average and maximum
$ ngxl --report size --by hour <log files>
| date_and_hour | count | total | min | avg | max |
+---------------+----------+-----------------+-----------------+-----------------+-----------------+
| 2019-09-24 06 | 11623 | 58270082 | 439 | 5013 | 1149910 |
| 2019-09-24 07 | 102476 | 499856710 | 533 | 4877 | 1150518 |
| 2019-09-24 08 | 103262 | 504666038 | 245 | 4887 | 1150006 |
| 2019-09-24 09 | 103537 | 503025428 | 0 | 4858 | 1150701 |
| 2019-09-24 10 | 103746 | 504595496 | 245 | 4863 | 1149950 |
| 2019-09-24 11 | 103653 | 507222040 | 531 | 4893 | 1150091 |
| 2019-09-24 12 | 103392 | 496561788 | 520 | 4802 | 1150187 |
| 2019-09-24 13 | 103423 | 492099937 | 245 | 4758 | 1150099 |
| 2019-09-24 14 | 102568 | 496671806 | 245 | 4842 | 1150315 |
| 2019-09-24 15 | 92875 | 445168906 | 638 | 4793 | 1150115 |
## How the data is reported
As you can see above the data can be reported by hour. It can also be reported by ip. For example
$ ngxl.rb --report status --by ip <log files>
| ip_address | count | 2xx | 3xx | 4xx | 5xx |
+-----------------+----------+--------+--------+--------+--------+
| 10.181.201.246 | 2690 | 2690 | 0 | 0 | 0 |
| 134.213.150.114 | 126 | 126 | 0 | 0 | 0 |
| 134.213.56.245 | 126 | 126 | 0 | 0 | 0 |
| 134.213.58.233 | 32935 | 32935 | 0 | 0 | 0 |
| 141.138.130.1 | 1012 | 1012 | 0 | 0 | 0 |
| 141.138.134.1 | 3048 | 3048 | 0 | 0 | 0 |
| 176.58.124.134 | 1 | 0 | 0 | 1 | 0 |
| 185.119.152.38 | 1012 | 1012 | 0 | 0 | 0 |
| 212.22.234.47 | 24614 | 24614 | 0 | 0 | 0 |
| 213.187.236.32 | 63553 | 63553 | 0 | 0 | 0 |
| 220.238.156.239 | 36 | 9 | 3 | 24 | 0 |
| 31.222.58.6 | 162026 | 162026 | 0 | 0 | 0 |
| 34.253.163.217 | 105523 | 105523 | 0 | 0 | 0 |
| 52.212.44.165 | 3040 | 3040 | 0 | 0 | 0 |
| 52.215.78.102 | 648 | 648 | 0 | 0 | 0 |
| 52.232.67.76 | 2 | 1 | 1 | 0 | 0 |
| 52.31.67.157 | 9891 | 9891 | 0 | 0 | 0 |
| 52.51.101.91 | 480 | 480 | 0 | 0 | 0 |
| 54.37.17.195 | 96 | 96 | 0 | 0 | 0 |
| 54.37.18.96 | 76 | 76 | 0 | 0 | 0 |
| 54.37.19.80 | 70 | 70 | 0 | 0 | 0 |
| 54.72.171.131 | 10516 | 10516 | 0 | 0 | 0 |
| 63.34.213.250 | 125 | 21 | 0 | 104 | 0 |
| 81.132.110.249 | 161 | 158 | 3 | 0 | 0 |
| 85.199.212.121 | 19 | 19 | 0 | 0 | 0 |
| 85.199.212.122 | 12 | 12 | 0 | 0 | 0 |
| 85.199.212.123 | 18 | 18 | 0 | 0 | 0 |
| 85.199.212.124 | 11 | 11 | 0 | 0 | 0 |
| 85.199.212.125 | 14 | 14 | 0 | 0 | 0 |
| 85.199.212.126 | 14 | 14 | 0 | 0 | 0 |
| 88.151.157.235 | 151 | 140 | 9 | 1 | 1 |
| 91.211.96.165 | 154347 | 154347 | 0 | 0 | 0 |
| 91.211.99.90 | 161993 | 161993 | 0 | 0 | 0 |
| 91.230.243.134 | 2 | 2 | 0 | 0 | 0 |
| 91.230.243.135 | 1 | 1 | 0 | 0 | 0 |
| 91.230.243.136 | 9 | 9 | 0 | 0 | 0 |
| 91.230.243.137 | 5 | 5 | 0 | 0 | 0 |
| 91.230.243.138 | 2 | 2 | 0 | 0 | 0 |
| 91.230.243.139 | 2 | 2 | 0 | 0 | 0 |
| 93.191.194.10 | 162005 | 162005 | 0 | 0 | 0 |
| 94.125.56.56 | 30137 | 30137 | 0 | 0 | 0 |
| 94.14.154.19 | 6 | 6 | 0 | 0 | 0 |
## Output format
By default the output is formatted as a nicely formatted text suitable from monospaced printing. If you use the `--csv` flag on the command line then the output will be formatted as csv data suitable for spreadsheets and other such tools
## Other tools
Other than the marvellous `ngxtop` (to be found at `https://github.com/lebinh/ngxtop.git`) which you should be using
if you are running Nginx there is also my other tool `https://github.com/PeterHickman/StarGraph.git` which performs
a similar task to `nginx_summary_by_hour.rb` but is written in C++ (so it's a whole lot faster) and creates a graph
which can be easier to read
|
package parser_test
import (
"fmt"
"testing"
"github.com/ngdinhtoan/hari/parser"
)
func TestParse(t *testing.T) {
data := []byte(`
{
"name": "Toan",
"age": 30,
"active": true,
"children": [{
"name": "Hachi",
"age": 3
},
{
"name": "Yuri",
"age": 2
}],
"group": ["family", "work"],
"contact": {
"phone": "9282882822",
"email": "mail@gmail.com"
}
}
`)
rs := make(chan *parser.Struct)
errs := make(chan error)
done := make(chan bool)
go parser.Parse("Person", data, rs, errs, done)
for {
select {
case <-done:
close(rs)
close(errs)
close(done)
return
case s := <-rs:
w := &stringWriter{}
s.WriteTo(w)
fmt.Println(w.Data)
}
}
}
type stringWriter struct {
Data string
}
func (sw *stringWriter) Write(p []byte) (n int, err error) {
sw.Data += string(p)
return len(p), nil
}
|
#!/usr/bin/php -q
<?php
/*
The MIT License (MIT)
Copyright (c) 2015 Gary Smart www.smart-itc.com.au
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.
Parts of this script were inspired from jared@osTicket.com / ntozier@osTicket / tmib.net (http://tmib.net/using-osticket-1812-api)
*/
$settings = array(
'dbHost' => 'localhost',
'dbTable' => 'ost.ost_faq', // Database.Table where FAQs are stored.
'dbUser' => 'root',
'dbPass' => '',
'categoryId' => 16, // The Category ID where Automator tickete FAQs are kept
'topicId' => 8, // Created tickets are assigned to this topic.
'subjectPrefix' => '[',
'subjectSuffix' => ']',
'reporterEmail' => 'automator@domain.com',
'reporterName' => 'Automator',
'apiURL' => 'http://ost.domain.com/api/http.php/tickets.json',
'apiKey' => 'your-api-key'
);
if (!isset($settings)) {
die ('$settings is not set. Aborting.');
}
$period = isset($argv[1]) ? $argv[1] : "daily";
$tks = findTicketsToCreate($period);
foreach($tks as $t) {
createTicket($t->subject, $t->message);
}
// $period to match FAQ Question field.
function findTicketsToCreate($period = "daily") {
global $settings;
$link = mysql_connect($settings['dbHost'], $settings['dbUser'], $settings['dbPass']);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$sql_query = "select faq_id, answer from " . $settings['dbTable'] . " WHERE category_id=" . $settings['categoryId'] . " AND UPPER(question) LIKE UPPER('%$period%')";
$sql_result = mysql_query($sql_query, $link);
$rowsFound = false;
$results = array();
while ($row = mysql_fetch_array($sql_result,MYSQL_ASSOC)) {
$rowsFound = true;
$lines = explode("\n", trim(br2nl($row['answer']))) ;
foreach($lines as $line) {
$line = trim($line);
// Skip empty lines or lines starting with a comment (-- or #)
if (empty($line) || (strpos($line, "--") === 0) || (strpos($line, "#") === 0)) {
continue;
}
$subject = $line;
$message = null;
if (strpos($line, "|") !== FALSE) {
list($subject, $message) = explode("|", $line);
}
$subject = decode($subject);
$message = decode($message);
if (empty($message)) {
$message = $subject;
}
$tmp = new stdClass();
$tmp->faqId = $row['faq_id'];
$tmp->subject = $subject;
$tmp->message = $message . "\n\nPeriod: $period";
$results[] = $tmp;
}
}
mysql_free_result($sql_result);
mysql_close($link);
if (!$rowsFound) {
$msg = "Automator called for Period '$period' but found no tickets to create";
echo $msg . "\n";
createTicket($msg);
}
return $results;
} // findTicketsToCreate()
function createTicket($subject, $message = null) {
global $settings;
$topicId = $settings['topicId'];
$reporterEmail = $settings['reporterEmail'];
$reporterName = $settings['reporterName'];
$reporterIP = gethostbyname(gethostname());
if (empty($subject)) {
echo ("No Subject provided. Not creating ticket.\n");
return false;
};
if (empty($message)) {
$message = $subject;
}
$subject = $settings['subjectPrefix'] . $subject . $settings['subjectSuffix'];
$data = array(
'name' => $reporterName,
'email' => $reporterEmail,
'phone' => '',
'subject' => $subject,
'message' => $message,
'ip' => $reporterIP,
'topicId' => $topicId
);
function_exists('curl_version') or die('CURL support required');
function_exists('json_encode') or die('JSON support required');
set_time_limit(30);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $settings['apiURL']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_USERAGENT, 'osTicket API Client v1.8');
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Expect:', 'X-API-Key: '.$settings['apiKey']));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result=curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code != 201) {
echo "Unable to create ticket with subject $subject: " .$result . "\n";
return false;
}
$ticketId = (int)$result;
echo "Ticket '$subject' created with id $ticketId\n";
return $ticketId;
} // createTicket()
function br2nl($string) {
return preg_replace('/\<br(\s*)?\/?\>/i', PHP_EOL, $string);
}
function decode($s) {
if (empty($s)) {
return $s;
}
$s = str_ireplace(" ", " ", $s);
return trim($s);
}
|
<?php
namespace Recurrence\Validator;
use Recurrence\Model\Frequency;
use Recurrence\Model\Recurrence;
use Recurrence\Constraint\ProviderConstraint\EndOfMonthConstraint;
use Recurrence\Model\Exception\InvalidRecurrenceException;
/**
* Class RecurrenceValidator
* @package Recurrence\Validator
*/
class RecurrenceValidator
{
/**
* @param Recurrence $recurrence
* @throws InvalidRecurrenceException
* @return bool
*/
public static function validate(Recurrence $recurrence)
{
if (!$recurrence->getFrequency()) {
throw new InvalidRecurrenceException('Frequency is required');
}
if ($recurrence->hasCount() && $recurrence->getPeriodEndAt()) {
throw new InvalidRecurrenceException('Recurrence cannot have [COUNT] and [UNTIL] option at the same time');
}
if (!$recurrence->hasCount() && !$recurrence->getPeriodEndAt()) {
throw new InvalidRecurrenceException('Recurrence required [COUNT] or [UNTIL] option');
}
if ($recurrence->hasConstraint(EndOfMonthConstraint::class) && (string) $recurrence->getFrequency() != Frequency::FREQUENCY_MONTHLY) {
throw new InvalidRecurrenceException('End of month constraint can be applied only with monthly frequency');
}
return true;
}
}
|
#!/bin/bash -u
set -e
#
# Copyright (c) 2012 Tresys Technology LLC, Columbia, Maryland, USA
#
# This software was developed by Tresys Technology LLC
# with U.S. Government sponsorship.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# bootloader_nousb_argument
#
FILE=/etc/grub.conf
[ -f $FILE ] || exit 1
/sbin/grubby --update-kernel=ALL --args=nousb
|
import React from 'react';
import Tap from '../hahoo/Tap';
class BtnUpLevel extends React.Component {
static propTypes = {
onItemClick: React.PropTypes.func
}
state = {}
render() {
const { onItemClick, ...rest } = this.props;
return (<Tap
onTap={onItemClick}
className="btn btn-default"
{...rest}
><i className="fa fa-arrow-circle-up fa-fw" /> 上级</Tap>);
}
}
export default BtnUpLevel;
|
#ifndef QMLTAB_H
#define QMLTAB_H
#include <QWidget>
#include <QLayout>
#include <QQuickView>
#include <QQmlEngine>
#include <QQuickItem>
#include <QQmlComponent>
#include <QVariantList>
#include <QApplication>
#include <memory>
#include "dbi/dbi.h"
class QmlTab : public QWidget
{
Q_OBJECT
public:
explicit QmlTab(QString qmlfile, QWidget *parent = 0);
~QmlTab();
std::unique_ptr<QQuickItem> root;
std::unique_ptr<QQmlEngine> engine;
};
struct AlbumItem {
enum AlbumRoles {
NameRole = Qt::UserRole +1,
CoverRole,
TracksRole
};
};
#endif // QMLTAB_H
|
package org.openforis.collect.web.manager;
import java.util.HashMap;
import java.util.Map;
import org.openforis.collect.manager.CachedRecordProvider;
import org.openforis.collect.model.CollectRecord;
import org.openforis.collect.model.CollectRecord.Step;
import org.openforis.collect.model.CollectSurvey;
public class SessionRecordProvider extends CachedRecordProvider {
private CachedRecordProvider delegate;
private Map<Integer, CollectRecord> recordsPreviewBySurvey = new HashMap<Integer, CollectRecord>();
public SessionRecordProvider(CachedRecordProvider cachedRecordProvider) {
super(null);
this.delegate = cachedRecordProvider;
}
@Override
public CollectRecord provide(CollectSurvey survey, Integer recordId, Step recordStep) {
if (recordId == null) {
// Preview record
return this.recordsPreviewBySurvey.get(survey.getId());
} else {
return delegate.provide(survey, recordId, recordStep);
}
}
public void putRecord(CollectRecord record) {
if (record.isPreview()) {
this.recordsPreviewBySurvey.put(record.getSurvey().getId(), record);
} else {
delegate.putRecord(record);
}
}
@Override
public void clearRecords(int surveyId) {
delegate.clearRecords(surveyId);
this.recordsPreviewBySurvey.remove(surveyId);
}
}
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.default = void 0;
var _graphqlRelay = require("graphql-relay");
var _EnsayoType = _interopRequireDefault(require("./EnsayoType"));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}var _default =
(0, _graphqlRelay.connectionDefinitions)({
name: 'Ensayos',
nodeType: _EnsayoType.default });exports.default = _default;
//# sourceMappingURL=EnsayosConnection.js.map |
<?php
class Controller
{
private $project;
private $request;
private $response;
private $user;
private $template_engine;
public function __construct(BaseProject $project, Request $request=null)
{
$this->project = $project;
$this->request = $request;
}
public function getActionName($action)
{
return $action . 'Action';
}
public function action($action, $parameters=null)
{
$method = $this->getActionName($action);
if (!method_exists($this, $method))
throw new NotFoundException('Action not found: ' . $method);
$response = $this->getResponse();
if ($this->preExecute()===false) return $response;
$actionResult = $this->$method($parameters);
if ($actionResult) $response->setContent($actionResult);
$this->postExecute();
return $response;
}
public function preExecute(){}
public function postExecute(){}
public function getRequest()
{
if (!$this->request)
$this->request = new Request();
return $this->request;
}
public function getRequestParameter($parameter)
{
return $this->getRequest()->getParameter($parameter);
}
public function getResponse()
{
if (!$this->response)
$this->response = new Response();
return $this->response;
}
public function getTemplateDirectories()
{
return $this->getProject()->getTemplateDirectories();
}
public function prepareTemplateEngine()
{
$loader = new sfTemplateLoaderFilesystem($this->getTemplateDirectories());
$template_engine = new TemplateEngine($loader);
$helperSet = new sfTemplateHelperSet(array(new sfTemplateHelperAssets(), new sfTemplateHelperJavascripts(), new sfTemplateHelperStylesheets(), new ProjectHelper($this->getProject()), new RoutingHelper($this->getRequest()), new UserHelper($this->getUser())));
$template_engine->setHelperSet($helperSet);
return $template_engine;
}
public function getTemplateEngine()
{
if (!$this->template_engine){
$this->template_engine = $this->prepareTemplateEngine();
}
return $this->template_engine;
}
public function getTemplateVariables()
{
return array();
}
public function getProject()
{
return $this->project;
}
public function getUser()
{
if (!$this->user){
$this->user = new User();
}
return $this->user;
}
public function isAuthenticated()
{
return $this->getUser()->isAuthenticated();
}
public function getProjectName()
{
return $this->getProject()->getName();
}
public function render($template, $vars=array())
{
//TODO: check:
$vars = array_merge($vars, $this->getTemplateVariables());
$this->getTemplateEngine()->setParameters($vars);
return $this->getTemplateEngine()->render($template, $vars);
}
public function forward($controller_name, $action_name)
{
$current_controller = get_class($this);
if ($current_controller == $controller_name.'Controller'){
$action = $action_name . 'Action';
return $this->$action();
}
//TODO: needs fixing - since the new controller works in its own domain and doesn't effect the current User or Response.
return $this->getProject()->loadAction($controller_name, $action_name, $this->request);
}
public function redirect($url, $status=302)
{
$response = $this->getResponse();
$response->setStatusCode($status);
$response->setHeader('Location', $this->getRequest()->getScriptName() .$url);
}
public function getPagesCacheManager()
{
return $this->getProject()->getPagesCacheManager();
}
public function getSiteConfiguration()
{
return $this->getProject()->getSiteConfiguration();
}
}
?> |
---
layout: post
title: 后缀数组总结
tags: [about, Jekyll, theme, responsive]
comments: true
image:
feature: 4.jpg
---
最近接触到了后缀数组,可以说是我至今为止遇到的最复杂的数据结构了,从查资料到把他搞懂花了两天的时间,现把它做一个小小的总结。后缀数组是一种非常强大的处理字符串问题的数据结构,目前有两种方法构造后缀数组,一种是倍增算法,时间复杂度为O(NlogN)。优点是实现简单,内存较少。另一种是DC3算法,时间复杂度为O(N),但是常数较大而且所占内存较大。实际上,由于倍增算法便于实现,时间复杂度也并不比DC3算法差多少,所以其使用的频率要高于DC3算法。现将倍增算法总结如下。
####倍增算法构造后缀数组
{% highlight c %}
const int maxn = 500;
int wa[maxn] ,wb[maxn], wv[maxn],ws[maxn],sa[maxn];
int cmp(int *r, int a, int b, int l){
return r[a] == r[b] && r[a+l] == r[b+l];
}
/*****************************************************
功能:倍增法求排序后的后缀数组
参数:int *r,int *sa,int n,int m
r 指向原字符串数组
sa 结果后缀数组
n 字符串的长度+1 添加最后一个字符 区别比较
m 字符串包含不同字符的个数,一般128可以满足
*****************************************************/
void da(int *r,int *sa,int n,int m)//倍增法实现后缀数组
{
int i,j,p,*x=wa,*y=wb;
// 基数排序 ,确定字符串长度为1时的顺序
for(i = 0;i < m;i++) ws[i] = 0; //先对ws清零
for(i = 0;i < n;i++) ws[x[i] = r[i]]++;//将原串从左到右入桶
for(i = 1;i < m;i++) ws[i] += ws[i-1]; //求部分和序列,以便出桶时确定下标
for(i=n-1;i >=0;i--) sa[--ws[x[i]]] = i;//从右到左出桶
//多次基数排序,先按照第二关键字排序,在按照第一关键字排序
for(j = 1,p = 1;p<n; j *= 2,m = p){
//对第二关键字排序
for(p = 0,i=n-j;i<n;i++) y[p++]=i; //最开始求长度2的字符串的第二关键字,末尾不足j+1的后缀,排序在最前面,因为默认原串后面的字符最小
for(i = 0;i<n;i++) if(sa[i] >= j) y[p++] = sa[i] - j;//优化:按照上次排序后的结果,sa
for(i = 0;i<n;i++) wv[i] = x[y[i]];//排序后的字符存在wv中
//对第一关键字排序
for(i = 0;i < m;i++) ws[i] = 0;
for(i = 0;i < n;i++) ws[wv[i]]++; //是上面排序结果,要对它进行基数排序
for(i = 1;i < m;i++) ws[i] += ws[i-1];
for(i=n-1;i >=0;i--) sa[--ws[wv[i]]] = y[i];//y[i]是按第二关键字排名的‘sa’数组
//判断有没有相同的长度为j+1的字符串,若没有,则已得到后缀数组
swap(x,y); //交换x,y指向,因为下一此循环,y数组的计算要利用x数组,而现在的y数组是下一次的x数组应有的内容
for(p=1,x[sa[0]] = 0,i=1;i < n;i++) //x[sa[0]] = 0
x[sa[i]] = cmp(y,sa[i-1],sa[i],j) ? p-1:p++;//比较相邻的后缀数组有没有相同的字符,没有的话p=n,退出循环
}
return;
}
{% endhighlight %}
####计算height数组
{% highlight c %}
/*****************************************************
功能:计算height数组
参数:int *r,int *sa,int n
r 指向原字符串数组
sa 后缀数组
n 字符串的长度
*****************************************************/
int Rank[maxn],height[maxn];
void calheight(int *r,int *sa,int n){
int i, j, k = 0;
for(i = 1;i<=n;i++)
Rank[sa[i]] =i; //根据sa求rank
for(i = 0;i < n;height[Rank[i++]] = k) //h[i] = height[rank[i]]
for(k?k--:0,j = sa[Rank[i]-1];r[i+k] == r[j+k];k++);//h[i] >=h[i-1]-1;可以优化此计算
}
{% endhighlight %}
---
####应用:求最长回文子串
{% highlight c %}
/*****************************************************
功能: 求字符串的最长回文子串。方法是将原字符串逆序放在
后面,中间用一个较小字符隔开比如'$'str中保存
*****************************************************/
char str[maxn];
void longestPalindrome(void){
int n = strlen(str);
int i,j,r[maxn];
str[n] = '$';
for(i = n-1,j=n+1;i >= 0;i--,j++)
str[j] = str[i];
for(i = 0;i<2*n+1;i++)
r[i] = str[i];
r[2*n+1] = 0;
da(r,sa,2*n+2,128);
calheight(r,sa,2*n+1);
int max = 0,start = 0;
for(i = 1;i < 2*n+2;i++)
if(height[i] > max && (sa[i-1] < n) ^ (sa[i] < n)){
max = height[i];
start = sa[i];
}
for(i = start;i<start+max;i++) printf("%c",str[i]);
}
{% endhighlight %}
####测试
{% highlight c %}
int main()
{
scanf("%s",str); //输入 abaaabcaa
longestPalindrome(); //输出 baaab
return 0;
}
{% endhighlight %}
####参考资料
关于后缀数组的更多内容,请参考
<div markdown="0"><a href="http://files.cnblogs.com/newpanderking/%E5%90%8E%E7%BC%80%E6%95%B0%E7%BB%84%E2%80%94%E2%80%94%E5%A4%84%E7%90%86%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9A%84%E6%9C%89%E5%8A%9B%E5%B7%A5%E5%85%B7.pdf" class="btn btn-danger">后缀数组</a></div>
<section id="table-of-contents" class="toc">
<header>
<h3>Overview</h3>
</header>
<div id="drawer" markdown="1">
* Auto generated table of contents
{:toc}
</div>
</section><!-- /#table-of-contents -->
|
<!DOCTYPE html>
<html>
<head>
<title>Type Magic</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<style type="text/css">
body { font-family: 'Palatino'; line-height: 2.5em; }
h1, h2, h3 {
font-family: 'Palatino';
font-weight: normal;
}
img { height: 400px; }
li, p { font-size: 26px; }
code { font-size: 24px; line-height: 1.2em; }
em { color: #630; }
a { color: #360; }
.remark-inline-code { color: #036; }
.remark-code, .remark-inline-code { font-family: 'Inconsolata LGC'; }
.remark-slide-number { display: none; }
td { border: 1px solid #999; padding: 0.5em 1em; }
table { border-collapse: collapse; }
blockquote { background: #eee; }
</style>
</head>
<body onload="var slideshow = remark.create();">
<textarea id="source">
|
/**
* @author Phuluong
* Feb 13, 2016
*/
/** Exports **/
module.exports = new Config();
/** Imports **/
var fs = require("fs");
var util = require(__dir + '/core/app/util');
/** Modules **/
function Config() {
var configContainer = {};
/**
* Get config value by key
* @param {String} key
* @param {} defaultValue
* @returns {}
*/
this.get = function (key, defaultValue) {
var retval = defaultValue;
if (configContainer[key] != null) {
retval = configContainer[key];
} else {
key = key.replaceAll(".", "/");
var path = __dir + "/config/" + key;
var parentPath = path.substring(0, path.lastIndexOf("/"));
try {
var property = path.substring(path.lastIndexOf("/") + 1, path.length);
if (fs.existsSync(path + ".js")) {
retval = require(path);
} else if (fs.existsSync(parentPath + ".js")) {
if ((require(parentPath))[property] != null) {
retval = (require(parentPath))[property];
}
} else if (key.indexOf("package") == 0) {
retval = (require(__dir + "/package.json"))[property];
}
configContainer[key] = retval;
} catch (exc) {
}
}
if (retval == null) {
}
return retval;
};
/**
* Set config value
* @param {String} key
* @param {} value
*/
this.set = function (key, value) {
configContainer[key] = value;
};
}
|
class AddObserveIdFromPeriods < ActiveRecord::Migration
def change
add_reference :periods, :user, index: true
end
end
|
<?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
/**
* @return array
*/
public function registerBundles()
{
return array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new Actinoids\ApiSuiteBundle\ActinoidsApiSuiteBundle()
);
}
/**
* @return null
*/
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
/**
* @return string
*/
public function getCacheDir()
{
return sys_get_temp_dir().'/ActinoidsApiSuiteBundle/cache';
}
/**
* @return string
*/
public function getLogDir()
{
return sys_get_temp_dir().'/ActinoidsApiSuiteBundle/logs';
}
}
|
<!DOCTYPE html>
<!--[if lt IE 9]><html class="no-js lt-ie9" lang="en" dir="ltr"><![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="en" dir="ltr">
<!--<![endif]-->
<!-- Usage: /eic/site/ccc-rec.nsf/tpl-eng/template-1col.html?Open&id=3 (optional: ?Open&page=filename.html&id=x) -->
<!-- Created: ; Product Code: 536; Server: stratnotes2.ic.gc.ca -->
<head>
<!-- Title begins / Début du titre -->
<title>
Insured Creativity -
Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada
</title>
<!-- Title ends / Fin du titre -->
<!-- Meta-data begins / Début des métadonnées -->
<meta charset="utf-8" />
<meta name="dcterms.language" title="ISO639-2" content="eng" />
<meta name="dcterms.title" content="" />
<meta name="description" content="" />
<meta name="dcterms.description" content="" />
<meta name="dcterms.type" content="report, data set" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.issued" title="W3CDTF" content="" />
<meta name="dcterms.modified" title="W3CDTF" content="" />
<meta name="keywords" content="" />
<meta name="dcterms.creator" content="" />
<meta name="author" content="" />
<meta name="dcterms.created" title="W3CDTF" content="" />
<meta name="dcterms.publisher" content="" />
<meta name="dcterms.audience" title="icaudience" content="" />
<meta name="dcterms.spatial" title="ISO3166-1" content="" />
<meta name="dcterms.spatial" title="gcgeonames" content="" />
<meta name="dcterms.format" content="HTML" />
<meta name="dcterms.identifier" title="ICsiteProduct" content="536" />
<!-- EPI-11240 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- MCG-202 -->
<meta content="width=device-width,initial-scale=1" name="viewport">
<!-- EPI-11567 -->
<meta name = "format-detection" content = "telephone=no">
<!-- EPI-12603 -->
<meta name="robots" content="noarchive">
<!-- EPI-11190 - Webtrends -->
<script>
var startTime = new Date();
startTime = startTime.getTime();
</script>
<!--[if gte IE 9 | !IE ]><!-->
<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="icon" type="image/x-icon">
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/wet-boew.min.css">
<!--<![endif]-->
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/theme.min.css">
<!--[if lt IE 9]>
<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="shortcut icon" />
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/ie8-wet-boew.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew.min.js"></script>
<![endif]-->
<!--[if lte IE 9]>
<![endif]-->
<noscript><link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/noscript.min.css" /></noscript>
<!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER -->
<script>dataLayer1 = [];</script>
<!-- End Google Tag Manager -->
<!-- EPI-11235 -->
<link rel="stylesheet" href="/eic/home.nsf/css/add_WET_4-0_Canada_Apps.css">
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="/app/ccc/srch/css/print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body class="home" vocab="http://schema.org/" typeof="WebPage">
<!-- EPIC HEADER BEGIN -->
<!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER -->
<noscript><iframe title="Google Tag Manager" src="//www.googletagmanager.com/ns.html?id=GTM-TLGQ9K" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer1'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer1','GTM-TLGQ9K');</script>
<!-- End Google Tag Manager -->
<!-- EPI-12801 -->
<span typeof="Organization"><meta property="legalName" content="Department_of_Industry"></span>
<ul id="wb-tphp">
<li class="wb-slc">
<a class="wb-sl" href="#wb-cont">Skip to main content</a>
</li>
<li class="wb-slc visible-sm visible-md visible-lg">
<a class="wb-sl" href="#wb-info">Skip to "About this site"</a>
</li>
</ul>
<header role="banner">
<div id="wb-bnr" class="container">
<section id="wb-lng" class="visible-md visible-lg text-right">
<h2 class="wb-inv">Language selection</h2>
<div class="row">
<div class="col-md-12">
<ul class="list-inline mrgn-bttm-0">
<li><a href="nvgt.do?V_TOKEN=1492294053849&V_SEARCH.docsCount=3&V_DOCUMENT.docRank=23379&V_SEARCH.docsStart=23378&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=/prfl.do&lang=fra&redirectUrl=/app/scr/imbs/ccc/rgstrtn/rgstr.sec?_flId?_flxKy=e1s1&estblmntNo=234567041301&profileId=61&_evId=bck&lang=eng&V_SEARCH.showStricts=false&prtl=1&_flId?_flId?_flxKy=e1s1" title="Français" lang="fr">Français</a></li>
</ul>
</div>
</div>
</section>
<div class="row">
<div class="brand col-xs-8 col-sm-9 col-md-6">
<a href="http://www.canada.ca/en/index.html"><object type="image/svg+xml" tabindex="-1" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/sig-blk-en.svg"></object><span class="wb-inv"> Government of Canada</span></a>
</div>
<section class="wb-mb-links col-xs-4 col-sm-3 visible-sm visible-xs" id="wb-glb-mn">
<h2>Search and menus</h2>
<ul class="list-inline text-right chvrn">
<li><a href="#mb-pnl" title="Search and menus" aria-controls="mb-pnl" class="overlay-lnk" role="button"><span class="glyphicon glyphicon-search"><span class="glyphicon glyphicon-th-list"><span class="wb-inv">Search and menus</span></span></span></a></li>
</ul>
<div id="mb-pnl"></div>
</section>
<!-- Site Search Removed -->
</div>
</div>
<nav role="navigation" id="wb-sm" class="wb-menu visible-md visible-lg" data-trgt="mb-pnl" data-ajax-fetch="//cdn.canada.ca/gcweb-cdn-dev/sitemenu/sitemenu-en.html" typeof="SiteNavigationElement">
<h2 class="wb-inv">Topics menu</h2>
<div class="container nvbar">
<div class="row">
<ul class="list-inline menu">
<li><a href="https://www.canada.ca/en/services/jobs.html">Jobs</a></li>
<li><a href="http://www.cic.gc.ca/english/index.asp">Immigration</a></li>
<li><a href="https://travel.gc.ca/">Travel</a></li>
<li><a href="https://www.canada.ca/en/services/business.html">Business</a></li>
<li><a href="https://www.canada.ca/en/services/benefits.html">Benefits</a></li>
<li><a href="http://healthycanadians.gc.ca/index-eng.php">Health</a></li>
<li><a href="https://www.canada.ca/en/services/taxes.html">Taxes</a></li>
<li><a href="https://www.canada.ca/en/services.html">More services</a></li>
</ul>
</div>
</div>
</nav>
<!-- EPIC BODY BEGIN -->
<nav role="navigation" id="wb-bc" class="" property="breadcrumb">
<h2 class="wb-inv">You are here:</h2>
<div class="container">
<div class="row">
<ol class="breadcrumb">
<li><a href="/eic/site/icgc.nsf/eng/home" title="Home">Home</a></li>
<li><a href="/eic/site/icgc.nsf/eng/h_07063.html" title="Industries and Business">Industries and Business</a></li>
<li><a href="/eic/site/ccc-rec.nsf/tpl-eng/../eng/home" >Canadian Company Capabilities</a></li>
</ol>
</div>
</div>
</nav>
</header>
<main id="wb-cont" role="main" property="mainContentOfPage" class="container">
<!-- End Header -->
<!-- Begin Body -->
<!-- Begin Body Title -->
<!-- End Body Title -->
<!-- Begin Body Head -->
<!-- End Body Head -->
<!-- Begin Body Content -->
<br>
<!-- Complete Profile -->
<!-- Company Information above tabbed area-->
<input id="showMore" type="hidden" value='more'/>
<input id="showLess" type="hidden" value='less'/>
<h1 id="wb-cont">
Company profile - Canadian Company Capabilities
</h1>
<div class="profileInfo hidden-print">
<ul class="list-inline">
<li><a href="cccSrch.do?lang=eng&profileId=&prtl=1&key.hitsPerPage=25&searchPage=%252Fapp%252Fccc%252Fsrch%252FcccBscSrch.do%253Flang%253Deng%2526amp%253Bprtl%253D1%2526amp%253Btagid%253D&V_SEARCH.scopeCategory=CCC.Root&V_SEARCH.depth=1&V_SEARCH.showStricts=false&V_SEARCH.sortSpec=title+asc&rstBtn.x=" class="btn btn-link">New Search</a> |</li>
<li><form name="searchForm" method="post" action="/app/ccc/srch/bscSrch.do">
<input type="hidden" name="lang" value="eng" />
<input type="hidden" name="profileId" value="" />
<input type="hidden" name="prtl" value="1" />
<input type="hidden" name="searchPage" value="%2Fapp%2Fccc%2Fsrch%2FcccBscSrch.do%3Flang%3Deng%26amp%3Bprtl%3D1%26amp%3Btagid%3D" />
<input type="hidden" name="V_SEARCH.scopeCategory" value="CCC.Root" />
<input type="hidden" name="V_SEARCH.depth" value="1" />
<input type="hidden" name="V_SEARCH.showStricts" value="false" />
<input id="repeatSearchBtn" class="btn btn-link" type="submit" value="Return to search results" />
</form></li>
<li>| <a href="nvgt.do?V_SEARCH.docsStart=23377&V_DOCUMENT.docRank=23378&V_SEARCH.docsCount=3&lang=eng&prtl=1&sbPrtl=&profile=cmpltPrfl&V_TOKEN=1492294061099&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=%2fprfl.do&estblmntNo=234567088623&profileId=&key.newSearchLabel=">Previous Company</a></li>
<li>| <a href="nvgt.do?V_SEARCH.docsStart=23379&V_DOCUMENT.docRank=23380&V_SEARCH.docsCount=3&lang=eng&prtl=1&sbPrtl=&profile=cmpltPrfl&V_TOKEN=1492294061099&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=%2fprfl.do&estblmntNo=234567160801&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>
ICSB LP
</h2>
<div class="row">
<div class="col-md-5">
<h2 class="h5 mrgn-bttm-0">Legal Name:</h2>
<p>ICSB LP</p>
<h2 class="h5 mrgn-bttm-0">Operating Name:</h2>
<p>Insured Creativity</p>
<div class="mrgn-tp-md"></div>
<p class="mrgn-bttm-0" ><a href="http://www.insuredcreativity.com"
target="_blank" title="Website URL">http://www.insuredcreativity.com</a></p>
<p><a href="mailto:info@insuredcreativity.com" title="info@insuredcreativity.com">info@insuredcreativity.com</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">
300-251 North Service Rd<br/>
OAKVILLE,
Ontario<br/>
L6M 3E7
<br/>
</address>
<h2 class="h5 mrgn-bttm-0">Location Address:</h2>
<address class="mrgn-bttm-md">
300-251 North Service Rd<br/>
OAKVILLE,
Ontario<br/>
L6M 3E7
<br/>
</address>
<p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>:
(905) 608-1999
</p>
<p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>:
(800) 575-5590</p>
<p class="mrgn-bttm-lg"><abbr title="Facsimile">Fax</abbr>:
</p>
</div>
<div class="col-md-3 mrgn-tp-md">
<h2 class="wb-inv">Logo</h2>
<img class="img-responsive text-left" src="https://www.ic.gc.ca/app/ccc/srch/media?estblmntNo=234567166026&graphFileName=ICSB-Logo-White-72dp&applicationCode=AP&lang=eng" alt="Logo" />
</div>
</div>
<div class="row mrgn-tp-md mrgn-bttm-md">
<div class="col-md-12">
<h2 class="wb-inv">Company Profile</h2>
<br> Insured Creativity designs and executes rewards and incentive solutions for brand and agency marketers around the world. Specializing in shopper marketing, sponsorship activation and promotional offers, Insured Creativity develops turn-key and custom programs designed to influence and engage consumers with award winning programs.<br>
</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>
Dylan
MacTavish
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
Business Development Manager<br>
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Area of Responsibility:
</strong>
</div>
<div class="col-md-7">
Domestic Sales & Marketing.
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(905) 844-7408
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
dylan.mactavish@insuredcreativity.com
</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>
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">
541899 - All Other Services Related to Advertising
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Business Activity:
</strong>
</div>
<div class="col-md-7">
Services
</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>
Service Name:
</strong>
</div>
<div class="col-md-9">
Instant Win Games<br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-12">
Instant Win Games are a fun and exciting way of encouraging consumers to purchase a product, with a chance to win a lucrative prize for doing so.<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 -->
<h3 class="page-header">
Market profile
</h3>
<section class="container-fluid">
<h4>
Industry sector market interests:
</h4>
<ul>
<li>Consumer Products</li>
<li>Food and Beverage Manufacturing</li>
</ul>
<h4>
Geographic markets:
</h4>
<h5>
Export experience:
</h5>
<ul>
<li>Germany</li>
<li>United Kingdom</li>
<li>United States</li>
</ul>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- 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>
Dylan
MacTavish
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
Business Development Manager<br>
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Area of Responsibility:
</strong>
</div>
<div class="col-md-7">
Domestic Sales & Marketing.
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(905) 844-7408
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
dylan.mactavish@insuredcreativity.com
</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>
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">
541899 - All Other Services Related to Advertising
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Business Activity:
</strong>
</div>
<div class="col-md-7">
Services
</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>
Service Name:
</strong>
</div>
<div class="col-md-9">
Instant Win Games<br>
</div>
</div>
<div class="row mrgn-bttm-md">
<div class="col-md-12">
Instant Win Games are a fun and exciting way of encouraging consumers to purchase a product, with a chance to win a lucrative prize for doing so.<br>
<br>
</div>
</div>
</section>
</details>
<details id="details-panel6">
<summary>
Market
</summary>
<h2 class="wb-invisible">
Market profile
</h2>
<section class="container-fluid">
<h4>
Industry sector market interests:
</h4>
<ul>
<li>Consumer Products</li>
<li>Food and Beverage Manufacturing</li>
</ul>
<h4>
Geographic markets:
</h4>
<h5>
Export experience:
</h5>
<ul>
<li>Germany</li>
<li>United Kingdom</li>
<li>United States</li>
</ul>
</section>
</details>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
Last Update Date 2016-12-16
</div>
</div>
<!--
- Artifact ID: CBW - IMBS - CCC Search WAR
- Group ID: ca.gc.ic.strategis.imbs.ccc.search
- Version: 3.26
- Built-By: bamboo
- Build Timestamp: 2017-03-02T21:29:28Z
-->
<!-- End Body Content -->
<!-- Begin Body Foot -->
<!-- End Body Foot -->
<!-- END MAIN TABLE -->
<!-- End body -->
<!-- Begin footer -->
<div class="row pagedetails">
<div class="col-sm-5 col-xs-12 datemod">
<dl id="wb-dtmd">
<dt class=" hidden-print">Date Modified:</dt>
<dd class=" hidden-print">
<span><time>2017-03-02</time></span>
</dd>
</dl>
</div>
<div class="clear visible-xs"></div>
<div class="col-sm-4 col-xs-6">
</div>
<div class="col-sm-3 col-xs-6 text-right">
</div>
<div class="clear visible-xs"></div>
</div>
</main>
<footer role="contentinfo" id="wb-info">
<nav role="navigation" class="container wb-navcurr">
<h2 class="wb-inv">About government</h2>
<!-- EPIC FOOTER BEGIN -->
<!-- EPI-11638 Contact us -->
<ul class="list-unstyled colcount-sm-2 colcount-md-3">
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07026.html#pageid=E048-H00000&from=Industries">Contact us</a></li>
<li><a href="https://www.canada.ca/en/government/dept.html">Departments and agencies</a></li>
<li><a href="https://www.canada.ca/en/government/publicservice.html">Public service and military</a></li>
<li><a href="https://www.canada.ca/en/news.html">News</a></li>
<li><a href="https://www.canada.ca/en/government/system/laws.html">Treaties, laws and regulations</a></li>
<li><a href="https://www.canada.ca/en/transparency/reporting.html">Government-wide reporting</a></li>
<li><a href="http://pm.gc.ca/eng">Prime Minister</a></li>
<li><a href="https://www.canada.ca/en/government/system.html">How government works</a></li>
<li><a href="http://open.canada.ca/en/">Open government</a></li>
</ul>
</nav>
<div class="brand">
<div class="container">
<div class="row">
<nav class="col-md-10 ftr-urlt-lnk">
<h2 class="wb-inv">About this site</h2>
<ul>
<li><a href="https://www.canada.ca/en/social.html">Social media</a></li>
<li><a href="https://www.canada.ca/en/mobile.html">Mobile applications</a></li>
<li><a href="http://www1.canada.ca/en/newsite.html">About Canada.ca</a></li>
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html">Terms and conditions</a></li>
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html#p1">Privacy</a></li>
</ul>
</nav>
<div class="col-xs-6 visible-sm visible-xs tofpg">
<a href="#wb-cont">Top of Page <span class="glyphicon glyphicon-chevron-up"></span></a>
</div>
<div class="col-xs-6 col-md-2 text-right">
<object type="image/svg+xml" tabindex="-1" role="img" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object>
</div>
</div>
</div>
</div>
</footer>
<!--[if gte IE 9 | !IE ]><!-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/wet-boew.min.js"></script>
<!--<![endif]-->
<!--[if lt IE 9]>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew2.min.js"></script>
<![endif]-->
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/theme.min.js"></script>
<!-- EPI-10519 -->
<span class="wb-sessto"
data-wb-sessto='{"inactivity": 1800000, "reactionTime": 180000, "sessionalive": 1800000, "logouturl": "/app/ccc/srch/cccSrch.do?lang=eng&prtl=1"}'></span>
<script src="/eic/home.nsf/js/jQuery.externalOpensInNewWindow.js"></script>
<!-- EPI-11190 - Webtrends -->
<script src="/eic/home.nsf/js/webtrends.js"></script>
<script>var endTime = new Date();</script>
<noscript>
<div><img alt="" id="DCSIMG" width="1" height="1" src="//wt-sdc.ic.gc.ca/dcs6v67hwe0ei7wsv8g9fv50d_3k6i/njs.gif?dcsuri=/nojavascript&WT.js=No&WT.tv=9.4.0&dcssip=www.ic.gc.ca"/></div>
</noscript>
<!-- /Webtrends -->
<!-- JS deps -->
<script src="/eic/home.nsf/js/jquery.imagesloaded.js"></script>
<!-- EPI-11262 - Util JS -->
<script src="/eic/home.nsf/js/_WET_4-0_utils_canada.min.js"></script>
<!-- EPI-11383 -->
<script src="/eic/home.nsf/js/jQuery.icValidationErrors.js"></script>
<span style="display:none;" id='app-info' data-project-groupid='' data-project-artifactid='' data-project-version='' data-project-build-timestamp='' data-issue-tracking='' data-scm-sha1='' data-scm-sha1-abbrev='' data-scm-branch='' data-scm-commit-date=''></span>
</body></html>
<!-- End Footer -->
<!--
- Artifact ID: CBW - IMBS - CCC Search WAR
- Group ID: ca.gc.ic.strategis.imbs.ccc.search
- Version: 3.26
- Built-By: bamboo
- Build Timestamp: 2017-03-02T21:29:28Z
-->
|
namespace GridCity.Fields.Buildings {
using System;
using System.Collections.Generic;
using People;
internal class WorkBuilding : OccupationalBuilding {
//---------------------------------------------------------------------
// Constructors
//---------------------------------------------------------------------
public WorkBuilding(string name, Utility.GlobalCoordinate pos, Pathfinding.BaseNodeLayout layout, Orientation_CW orientation, Dictionary<Resident.Type, uint> jobs, Tuple<uint, uint> size) : base(name, pos, layout, orientation, jobs, size) {
}
}
}
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'addressbook-app',
environment: environment,
baseURL: '/',
locationType: 'auto',
emberPouch: {
localDb: 'dentone-addressbook',
remoteDb: 'https://wasilleptichandfurningio:6c01f93f266bb3cf6dfd579de0e8e51354ee3bf3@dentone.cloudant.com/addressbook/'
},
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
contentSecurityPolicy:{
'default-src': "'none'",
'script-src': "'self' 'unsafe-inline'",
'style-src': "'self' 'unsafe-inline' https://fonts.googleapis.com",
'font-src': "'self' fonts.gstatic.com",
'connect-src': "'self' https://dentone.cloudant.com/",
'img-src': "'self' data:",
'media-src': "'self'"
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
<?php use_stylesheets_for_form($form) ?>
<?php use_javascripts_for_form($form) ?>
<div class="sf_admin_form">
<?php echo form_tag_for($form, '@jt_users') ?>
<?php echo $form->renderHiddenFields(false) ?>
<?php if ($form->hasGlobalErrors()): ?>
<?php echo $form->renderGlobalErrors() ?>
<?php endif; ?>
<?php foreach ($configuration->getFormFields($form, $form->isNew() ? 'new' : 'edit') as $fieldset => $fields): ?>
<?php include_partial('jt_users/form_fieldset', array('jtusers' => $jtusers, 'form' => $form, 'fields' => $fields, 'fieldset' => $fieldset)) ?>
<?php endforeach; ?>
<?php include_partial('jt_users/form_actions', array('jtusers' => $jtusers, 'form' => $form, 'configuration' => $configuration, 'helper' => $helper)) ?>
</form>
</div>
|
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def rssToEstimatedDistance(rss):
freq = 2462 # freq of WiFi channel 6
origDBm = -20 # estimate this value
loss = abs(origDBm - rss)
dist = 10 ** ( ( loss + 27.55 - 20 * math.log10(freq) ) / 20 )
return dist
def trilaterate(inSources, rss):
distances = []
distances.append( rssToEstimatedDistance(rss[0]) )
distances.append( rssToEstimatedDistance(rss[1]) )
distances.append( rssToEstimatedDistance(rss[2]) )
# find the three intersection points
tp1 = _findEqualPerp(inSources[0], inSources[1], distances[0], distances[1])
tp2 = _findEqualPerp(inSources[0], inSources[2], distances[0], distances[2])
tp3 = _findEqualPerp(inSources[1], inSources[2], distances[1], distances[2])
p = Point( (tp1.x + tp2.x + tp3.x) / 3, (tp1.y + tp2.y + tp3.y) / 3 )
return p
def _findEqualPerp(p1, p2, r1, r2):
# swap points if p2 is behind p2
if p2.x < p1.x:
temp = p2
p2 = p1
p1 = temp
# compute the equation for the line
deltaX = p2.x - p1.x
deltaY = p2.y - p1.y
if deltaX == 0:
slope = 999999999
else:
slope = deltaY / deltaX
intercept = p2.y - slope * p2.x
# compute the constant multiplier
lineLen = math.sqrt((p2.x - p1.x)**2 + (p2.y - p1.y)**2)
c = lineLen / (r1 + r2)
posOnLine = c * r1
angle = math.atan(slope)
touchingPoint = Point(math.cos(angle) * posOnLine + p1.x, math.sin(angle) * posOnLine + p1.y)
return touchingPoint
# test program
def main():
a = Point(1, 6)
b = Point(2, 3)
c = Point(5, 7)
t = trilaterate([a,b,c], [2,3,5])
print(t.x)
print(t.y)
if __name__ == '__main__':
main()
|
---
layout: single
title: "2020-09-03 - Orchestration in Event Driven architecture"
date: 2020-09-03 17:00:00 +0000
comments: true
published: true
categories: ["events"]
tags: ["Events"]
author: Maarten Balliauw
---
Service Bus, Event Hub and Event Grid - all can be used in Event Driven Architecture. Let's look at the fundamentals
underpinning Event Driven architecture, and which patterns can be used on Azure!
## Agenda
### Orchestration in Event Driven architecture
Event Driven architecture (EDA) becomes more and more popular and Azure comes with many services which you can use in
your solutions design to build EDA. However, choosing between Service Bus, Event Hub and Event Grid is not always easy.
On top of that, while you want to leverage parallelism, elasticity and all the goodness of the Cloud, you usually need
to reconciliate all the operations at the end of the day, and that is called orchestration.
In this session, I'll come back to the fundamental differences between ESB-like architectures and EDA and I'll demo
different orchestration patterns one can use to build resilient and robust EDA, mostly using Azure Durable Functions.
As usual, the session is inspired from real-world applications!
<img src="/assets/media/speakers/stephane-eyskens.jpg" alt="Stephane Eyskens" align="left" height="100" style="margin-right: 20px;">**Speaker:** **Stephane Eyskens** is a Cloud Architect and Digital Transformation advocate, blogger, author and speaker.
He has a particular interest for Hybrid Architectures, Modern Authentication & Security in general as well as Artificial Intelligence.
He is a DevSecOps practitioner, always trying to have a Lean approach while understanding what Service and Application Management are all about.
Stephane on Twitter: [@stephaneeyskens](https://twitter.com/stephaneeyskens)
## Practical details
**Event date:** September 03, 2020 - you are welcome to [<img src="/assets/media/icon-slack.png" width="16" height="16" /> hang out in our Slack team](https://join.slack.com/t/azugbe/shared_invite/MjE4MzI5NDM3OTM5LTE1MDExNDgyMzUtMzgwNjM2YmU0Zg) or on the YouTube Live chat from 16:30, sessions start at 17:00
**Event location:**<br />
Online at [www.azug.be/live](https://www.azug.be/live), details will be e-mailed closer to the event.
## Register via Pretix
<link rel="stylesheet" type="text/css" href="https://pretix.eu/azug/20200903/widget/v1.css">
<script type="text/javascript" src="https://pretix.eu/widget/v1.en.js" async></script>
<pretix-widget event="https://pretix.eu/azug/20200903/"></pretix-widget>
<noscript>
<div class="pretix-widget">
<div class="pretix-widget-info-message">
JavaScript is disabled in your browser. To access our ticket shop without JavaScript, please <a target="_blank" rel="noopener" href="https://pretix.eu/azug/20200903/">click here</a>.
</div>
</div>
</noscript> |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Web 2.0</title>
<meta name="author" content="raesene">
<!-- Enable responsive viewport -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Le styles -->
<link href="https://raesene.github.io/assets/resources/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="https://raesene.github.io/assets/resources/font-awesome/css/font-awesome.min.css" rel="stylesheet">
<link href="https://raesene.github.io/assets/resources/syntax/syntax.css" rel="stylesheet">
<link href="https://raesene.github.io/assets/css/style.css" rel="stylesheet">
<!-- Le fav and touch icons -->
<!-- Update these with your own images
<link rel="shortcut icon" href="images/favicon.ico">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png">
-->
<link rel="alternate" type="application/rss+xml" title="" href="https://raesene.github.io/feed.xml">
</head>
<body>
<nav class="navbar navbar-default visible-xs" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a type="button" class="navbar-toggle nav-link" href="https://github.com/raesene">
<i class="fa fa-github"></i>
</a>
<a type="button" class="navbar-toggle nav-link" href="https://twitter.com/raesene">
<i class="fa fa-twitter"></i>
</a>
<a type="button" class="navbar-toggle nav-link" href="mailto:raesene@gmail.com">
<i class="fa fa-envelope"></i>
</a>
<a class="navbar-brand" href="https://raesene.github.io/">
<img src="https://www.gravatar.com/avatar/8c189c784a607c4b5d52b0c7ee69b036?s=35" class="img-circle" />
Raesene's Ramblings
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="https://raesene.github.io/">Home</a></li>
<li><a href="https://raesene.github.io/categories/index.html">Categories</a></li>
<li><a href="https://raesene.github.io/tags/index.html">Tags</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</nav>
<!-- nav-menu-dropdown -->
<div class="btn-group hidden-xs" id="nav-menu">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-bars"></i>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="https://raesene.github.io/"><i class="fa fa-home"></i>Home</a></li>
<li><a href="https://raesene.github.io/categories/index.html"><i class="fa fa-folder"></i>Categories</a></li>
<li><a href="https://raesene.github.io/tags/index.html"><i class="fa fa-tags"></i>Tags</a></li>
<li class="divider"></li>
<li><a href="#"><i class="fa fa-arrow-up"></i>Top of Page</a></li>
</ul>
</div>
<div class="col-sm-3 sidebar hidden-xs">
<!-- sidebar.html -->
<header class="sidebar-header" role="banner">
<a href="https://raesene.github.io/">
<img src="https://www.gravatar.com/avatar/8c189c784a607c4b5d52b0c7ee69b036?s=150" class="img-circle" />
</a>
<h3 class="title">
<a href="https://raesene.github.io/">Raesene's Ramblings</a>
</h3>
</header>
<div id="bio" class="text-center">
Security Geek, Penetration Testing, Docker, Ruby, Hillwalking
</div>
<div id="contact-list" class="text-center">
<ul class="list-unstyled list-inline">
<li>
<a class="btn btn-default btn-sm" href="https://github.com/raesene">
<i class="fa fa-github-alt fa-lg"></i>
</a>
</li>
<li>
<a class="btn btn-default btn-sm" href="https://twitter.com/raesene">
<i class="fa fa-twitter fa-lg"></i>
</a>
</li>
<li>
<a class="btn btn-default btn-sm" href="mailto:raesene@gmail.com">
<i class="fa fa-envelope fa-lg"></i>
</a>
</li>
</ul>
<ul id="contact-list-secondary" class="list-unstyled list-inline">
<li>
<a class="btn btn-default btn-sm" href="https://linkedin.com/in/rorym">
<i class="fa fa-linkedin fa-lg"></i>
</a>
</li>
<li>
<a class="btn btn-default btn-sm" href="https://raesene.github.io/feed.xml">
<i class="fa fa-rss fa-lg"></i>
</a>
</li>
</ul>
</div>
<!-- sidebar.html end -->
</div>
<div class="col-sm-9 col-sm-offset-3">
<div class="page-header">
<h1>Web 2.0 </h1>
</div>
<article>
<div class="col-sm-10">
<span class="post-date">
January
20th,
2006
</span>
<div class="article_body">
<p><a title="The Best Web 2.0 Software of 2005 (web2.wsj2.com)" href="http://web2.wsj2.com/the_best_web_20_software_of_2005.htm">The Best Web 2.0 Software of 2005 (web2.wsj2.com)</a><br />
Some interesting information on web 2.0 sites.</p>
</div>
<ul class="tag_box list-unstyled list-inline">
<li><i class="fa fa-folder-open"></i></li>
<li><a href="https://raesene.github.io/categories/index.html#Web Security-ref">
Web Security <span>(39)</span>
</a></li>
</ul>
<hr>
<div>
<section class="share col-sm-6">
<h4 class="section-title">Share Post</h4>
<a class="btn btn-default btn-sm twitter" href="https://twitter.com/share?text=Web 2.0&via=raesene"
onclick="window.open(this.href, 'twitter-share', 'width=550,height=235');return false;">
<i class="fa fa-twitter fa-lg"></i>
Twitter
</a>
<a class="btn btn-default btn-sm facebook" href="https://www.facebook.com/sharer/sharer.php"
onclick="window.open(this.href, 'facebook-share','width=580,height=296');return false;">
<i class="fa fa-facebook fa-lg"></i>
Facebook
</a>
<a class="btn btn-default btn-sm gplus"
onclick="window.open('https://plus.google.com/share?url='+window.location.href, 'google-plus-share', 'width=490,height=530');return false;">
<i class="fa fa-google-plus fa-lg"></i>
Google+
</a>
</section>
<section class="col-sm-6 author">
<img src="https://www.gravatar.com/avatar/8c189c784a607c4b5d52b0c7ee69b036" class="img-rounded author-image" />
<h4 class="section-title author-name">raesene</h4>
<p class="author-bio">Security Geek, Penetration Testing, Docker, Ruby, Hillwalking</p>
</section>
</div>
<div class="clearfix"></div>
<ul class="pager">
<li class="previous"><a href="https://raesene.github.io/blog/2006/01/19/good_guide_for/" title="Good Guide for Home user Internet Security">← Previous</a></li>
<li class="next"><a href="https://raesene.github.io/blog/2006/01/26/blog_worm_1/" title="Blog Worm....">Next →</a></li>
</ul>
<hr>
</div>
<div class="col-sm-2 sidebar-2">
</div>
</article>
<div class="clearfix"></div>
<footer>
<hr/>
<p>
© 2022 raesene with Jekyll. Theme: <a href="https://github.com/dbtek/dbyll">dbyll</a> by dbtek.
</p>
</footer>
</div>
<script type="text/javascript" src="https://raesene.github.io/assets/resources/jquery/jquery.min.js"></script>
<script type="text/javascript" src="https://raesene.github.io/assets/resources/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://raesene.github.io/assets/js/app.js"></script>
</body>
</html>
|
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInitfbfcde531df662d1e2394a96c22298b7::getLoader();
|
package _04MordorsCrueltyPlan;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Wizard {
private static final Map<String, Integer> FOODS = new HashMap<String, Integer>() {{
put("cram", 2);
put("lembas", 3);
put("apple", 1);
put("melon", 1);
put("honeycake", 5);
put("mushrooms", -10);
}};
public int getHappinessIndex() {
return this.happinessIndex;
}
private int happinessIndex;
public void setHappinessIndex(List<String> foods) {
foods.forEach(this::eatFood);
}
public String getMood() {
if (this.happinessIndex < -5) {
return "Angry";
} else if (this.happinessIndex <= 0) {
return "Sad";
} else if (this.happinessIndex <= 15) {
return "Happy";
} else {
return "JavaScript";
}
}
private void eatFood(String food) {
String foodLowerName = food.toLowerCase();
if (FOODS.containsKey(foodLowerName)) {
this.happinessIndex += FOODS.get(foodLowerName);
} else {
this.happinessIndex -= 1;
}
}
}
|
red = gr.material({0.8, 0.1, 0.1}, {0.5, 0.5, 0.5}, 25)
blue = gr.material({0.0, 0.0, 1.0}, {0.5, 0.5, 0.5}, 25)
rblue = gr.smaterial({0, 0, 0}, {1, 1, 1}, 50, 1, 1.65, 0)
blue = gr.material({0.0, 0.1, 1}, {0.5, 0.5, 0.5}, 25)
green = gr.material({0.0, 1.0, 0.0}, {0.5, 0.5, 0.5}, 25)
rgreen = gr.material({0.0, 0.1, 0.0}, {0.5, 0.5, 0.5}, 25)
rwhite = gr.material({1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}, 25)
fwhite = gr.material({1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}, 50, 1, 200, 10000)
root = gr.node('root')
-- floor
wall1 = gr.cube('wall1')
root:add_child(wall1)
wall1:set_material(fwhite)
wall1:translate(-15, -1, -15)
wall1:scale(30,1,30)
--roof
wall1 = gr.cube('wall1')
root:add_child(wall1)
wall1:set_material(rwhite)
wall1:translate(-15, 30, -15)
wall1:scale(30,1,30)
--Left wall
wall1 = gr.cube('wall1')
root:add_child(wall1)
wall1:set_material(red)
wall1:translate(-15, 0, -15)
wall1:rotate('z', 90)
wall1:scale(30,1,30)
-- right wall
wall1 = gr.cube('wall1')
root:add_child(wall1)
wall1:set_material(blue)
wall1:translate(15, 0, -15)
wall1:scale(1,30,30)
-- back wall
wall1 = gr.cube('wall1')
root:add_child(wall1)
wall1:set_material(rwhite)
wall1:translate(-15, 0, -15)
wall1:rotate('x', 90)
wall1:translate(0, 0, -30)
wall1:scale(30,1,30)
BALL = gr.cylinder('BALL')
BALL:translate(-4, 5, -7)
BALL:rotate('x', 90)
BALL:scale(4, 4, 5)
BALL:set_material(green)
root:add_child(BALL)
BALL = gr.cone('BALL')
BALL:translate(4, 15, 0)
BALL:rotate('x', 40)
BALL:rotate('y', 40)
BALL:scale(4, 4, 7)
BALL:set_material(red)
root:add_child(BALL)
white_light = gr.light(12000, {0.0, 29.0, 0.0}, {1, 1, 1}, {1, 0, 0})
camera = gr.pcamera({0, 15, 40}, {0, 0, -1}, {0, 1, 0}, 50, 0.1, 40)
gr.render(root, './img/conecyl.png', 1024, 1024,
camera,
{0.3, 0.3, 0.3}, {white_light}, {}, 0, 0, 1) |
/* global describe, before, it */
require('mocha')
require('should')
var async = require('async')
var testUtils = require('./testUtils')
var errorMessage = require('../errorMessages/errorMessages')
var mongo_dcms_core = require('../index')
describe('should get file Content by file id', function () {
var filepath = './test/testAsset/testTextFile.txt'
var savedFileId
var document = {
filePath: filepath,
fileName: 'testTextFile.txt',
contentType: 'binary/octet-stream',
identityMetaData: {
projectId: 10
}
}
before(function (done) {
this.timeout(5000)
async.series([
function (callback) {
testUtils.clearDb(callback)
},
function (callback) {
mongo_dcms_core.connect(testUtils.dbUrl)
mongo_dcms_core.uploadFile(document, {}, function (err, sucess) {
if (err) {
callback(err)
} else {
savedFileId = sucess.fileId
callback(null)
}
})
}
], done)
})
it('should get file Content by file id', function (done) {
mongo_dcms_core.getFileContentByFileId(savedFileId, function (err, sucess) {
if (err) {
err.should.equal(null)
done()
} else {
sucess.fileData.should.not.equal(null)
sucess.contentType.should.equal('binary/octet-stream')
sucess.fileName.should.equal('testTextFile.txt')
sucess.fileMetaData.should.not.equal(null)
sucess.fileMetaData.should.not.equal(undefined)
done()
}
})
})
it('should return message file not found', function (done) {
mongo_dcms_core.getFileContentByFileId('56f0dc0ca80f6cc01929cd1e', function (err, sucess) {
if (err) {
err.should.equal(errorMessage.fileNotFoundForSpecifiedFileId)
done()
} else {
sucess.should.equal(null)
done()
}
})
})
})
|
<section>
<h2>About</h2>
<p>
This is an Angular version of an Ember blog app with a Rails API.
</p>
</section>
|
import { Behavior } from '@aelea/core'
import { $text, component, style } from '@aelea/dom'
import { $card, $column, $row, $seperator, $TextField, $VirtualScroll, layoutSheet, ScrollRequest, ScrollResponse } from '@aelea/ui-components'
import { pallete } from '@aelea/ui-components-theme'
import { at, debounce, empty, join, map, merge, now, snapshot, startWith, switchLatest } from '@most/core'
import { Stream } from '@most/types'
function filterArrayByText(array: string[], filter: string) {
const filterLowercase = filter.toLocaleLowerCase()
return array.filter(id =>
id.indexOf(filterLowercase) > -1
)
}
const $label = (label: string, value: Stream<string> | string) => $row(layoutSheet.spacingSmall)(
$text(style({ color: pallete.foreground }))(label),
$text(value)
)
export const $VirtualScrollExample = component((
[scrollRequest, scrollRequestTether]: Behavior<ScrollRequest, ScrollRequest>,
[delayResponse, delayResponseTether]: Behavior<string, number>,
[filter, filterTether]: Behavior<string, string>,
) => {
const PAGE_SIZE = 25
const TOTAL_ITEMS = 1000
const formatNumber = Intl.NumberFormat().format
const initialDelayResponse = now(1600)
const delayWithInitial = merge(initialDelayResponse, delayResponse)
let i = 0
const $item = $text(style({ padding: '3px 10px' }))
const stubbedData = Array(TOTAL_ITEMS).fill(null).map(() =>
`item: ${Math.random().toString(36).substring(7)} ${formatNumber(++i)}`
)
const dataSourceFilter = (filter: string) => join(
snapshot((delay, requestNumber): Stream<ScrollResponse> => {
const pageStart = requestNumber * PAGE_SIZE
const pageEnd = pageStart + PAGE_SIZE
const filteredItems = filterArrayByText(stubbedData, filter)
const $items = filteredItems.slice(pageStart, pageEnd).map(id => {
return $item(id)
})
return at(delay, { $items: $items, offset: 0, pageSize: PAGE_SIZE })
}, delayWithInitial, scrollRequest)
)
const filterText = startWith('', filter)
const debouncedFilterText = debounce(300, filterText)
return [
$column(layoutSheet.spacingBig)(
$text(`High performance dynamically loaded list based on Intersection Observer Web API. this example shows a very common pagination and REST like fetching asynchnously more pages`),
$row(layoutSheet.spacingBig)(
$label('Page: ', map(l => String(l), scrollRequest)),
$label(`Page Size:`, String(PAGE_SIZE)),
$label(`Total Items:`, String(TOTAL_ITEMS)),
),
$row(layoutSheet.spacingBig)(
$TextField({
label: 'Filter',
value: empty(),
hint: 'Remove any items that does not match filter and debounce changes by 300ms to prevert spamming',
containerOp: layoutSheet.flex
})({
change: filterTether()
}),
$TextField({
label: 'Delay Response(ms)',
value: initialDelayResponse,
hint: 'Emulate the duration of a datasource response, show a stubbed $node instead',
containerOp: layoutSheet.flex
})({
change: delayResponseTether(
map(Number)
)
}),
),
$seperator,
$card(style({ padding: 0 }))(
switchLatest(
map(searchText =>
$VirtualScroll({
dataSource: dataSourceFilter(searchText),
containerOps: style({ padding: '8px', maxHeight: '400px' })
})({
scrollIndex: scrollRequestTether(),
})
, debouncedFilterText)
)
)
)
]
})
|
/* Definitions of target machine for GNU compiler. MIPS version.
Copyright (C) 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998
1999, 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009
Free Software Foundation, Inc.
Contributed by J. Grosbach, james.grosbach@microchip.com
Changes by J. Kajita, jason.kajita@microchip.com and
G. Loegel, george.loegel@microchip.com
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
GCC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
/* Macro for conditional compilation of PIC32 only stuff */
#ifndef MCHP_H
#define MCHP_H
#include <safe-ctype.h>
#include "config/mips/mips-machine-function.h"
#include "config/mchp-cci/cci-backend.h"
#undef TARGET_MCHP_PIC32MX
#define TARGET_MCHP_PIC32MX 1
#undef _BUILD_MCHP_
#define _BUILD_MCHP_ 1
#undef _BUILD_C32_
#define _BUILD_C32_ 1
#if 0
#define MCHP_DEBUG
#endif
extern int mchp_io_size_val;
extern HOST_WIDE_INT mchp_pic32_license_valid;
extern const char *pic32_text_scn;
extern int mchp_profile_option;
extern const char *mchp_resource_file;
enum pic32_isa_mode
{
pic32_isa_mips32r2 = 0,
pic32_isa_mips16e = 1,
pic32_isa_micromips = 2,
pic32_isa_unknown = 255
} ;
#undef DEFAULT_SIGNED_CHAR
#define DEFAULT_SIGNED_CHAR 1
/* Default to short double rather than long double */
/* chipKIT */
#undef TARGET_SHORT_DOUBLE
#define TARGET_SHORT_DOUBLE 0
#define MCHP_CONFIGURATION_DATA_FILENAME "configuration.data"
#define MCHP_CONFIGURATION_HEADER_MARKER \
"Daytona Configuration Word Definitions: "
#define MCHP_CONFIGURATION_HEADER_VERSION "0001"
#define MCHP_CONFIGURATION_HEADER_SIZE \
(sizeof (MCHP_CONFIGURATION_HEADER_MARKER) + 5)
/*
** This is how to output a reference to a user-level label named NAME.
** `assemble_name_raw' uses this.
*/
#undef ASM_OUTPUT_LABELREF
#define ASM_OUTPUT_LABELREF(FILE, NAME) \
do { \
const char * real_name; \
real_name = mchp_strip_name_encoding ((NAME)); \
asm_fprintf (FILE, "%U%s", real_name); \
} while (0)
/* Put at the end of the command given to the linker if -nodefaultlibs or
* -nostdlib is not specified on the command line. This includes all the
* standard libraries, the peripheral libraries if the -mno-peripheral-libs
* option is not specified on the command line, and the processor-specific
* peripheral library if -mno-peripheral-libs option is not specified, but
* the -mprocessor option is specified.
*/
/* chipKIT */
#undef LIB_SPEC
#define LIB_SPEC "--start-group -lc -lsupc++ -lpic32 -lgcc \
%{!mno-peripheral-libs:-lmchp_peripheral \
%{mprocessor=*:-lmchp_peripheral_%*}} \
--end-group"
#define LIBSTDCXX "-lsupc++"
#define LIBSTDCXX_STATIC "-lsupc++"
#define XC32CPPLIB_OPTION "-mxc32cpp-lib"
#if 1 /* TODO: Work in progress, investigating alternate designs */
# undef STARTFILE_SPEC
# define STARTFILE_SPEC " %{mmicromips: %s%{mprocessor=*:./proc/%*} %J%{mprocessor=*:/crt0_micromips%O};\
: %s%{mprocessor=*:./proc/%*} %J%{mprocessor=*:/crt0_mips32r2%O} } \
%{!mprocessor=* : crt0%O%s} \
"
# undef STARTFILECXX_SPEC
# define STARTFILECXX_SPEC " %{mmicromips: %s%{mprocessor=*:./proc/%*} %J%{mprocessor=*:/cpprt0_micromips%O} ;\
: %s%{mprocessor=*:./proc/%*} %J%{mprocessor=*:/cpprt0_mips32r2%O} } \
%{!mprocessor=* : cpprt0%O%s} \
crti%O%s crtbegin%O%s "
#else
# undef STARTFILE_SPEC
# define STARTFILE_SPEC " crt0%O%s \
"
# undef STARTFILECXX_SPEC
# define STARTFILECXX_SPEC " cpprt0%O%s \
crti%O%s crtbegin%O%s "
#endif
#undef ENDFILE_SPEC
#define ENDFILE_SPEC ""
#undef ENDFILECXX_SPEC
#define ENDFILECXX_SPEC " crtend%O%s crtn%O%s "
#undef LINK_COMMAND_SPEC
/* Add the PIC32 default linker script with the -T option */
/* When compiling with -mprocessor=32MX* or without the -mprocessor option,
use the ./ldscripts/elf32pic32mx.x file. When compiling for a newer device,
Use ./proc/<procname>/p<procname>.ld. */
#define LINK_COMMAND_SPEC "\
%{!fsyntax-only:%{!c:%{!M:%{!MM:%{!E:%{!S:\
%(linker) \
%{fuse-linker-plugin: \
-plugin %(linker_plugin_file) \
-plugin-opt=%(lto_wrapper) \
-plugin-opt=%(lto_gcc) \
%{static|static-libgcc:-plugin-opt=-pass-through=%(lto_libgcc)} \
%{static:-plugin-opt=-pass-through=-lc} \
%{O*:-plugin-opt=-O%*} \
%{w:-plugin-opt=-w} \
%{f*:-plugin-opt=-f%*} \
%{m*:-plugin-opt=-m%*} \
%{v:-plugin-opt=-v} \
} \
%{flto} %{fwhopr} %l " LINK_PIE_SPEC \
"%X %{o*} %{A} %{d} %{e*} %{m} %{N} %{n} %{r}\
%{s} %{t} %{u*} %{x} %{z} %{Z} %{!A:%{!nostdlib:%{!nostartfiles:%S} }}\
%{Wno-poison-system-directories:--no-poison-system-directories}\
%{Werror=poison-system-directories:--error-poison-system-directories}\
%{static:} %{L*} %(mfwrap) %(link_libgcc) %o\
%{fopenmp|ftree-parallelize-loops=*:%:include(libgomp.spec)%(link_gomp)} %(mflib)\
%{fprofile-arcs|fprofile-generate*|coverage:-lgcov}\
%{!A:%{!nostdlib:%{!mno-default-isr-vectors: -l:default_isr_vectors.o} }}\
%{T:%{T*};!T:-T %s%{mprocessor=32MX*:./ldscripts/elf32pic32mx.x; \
:%{mprocessor=32mx*:./ldscripts/elf32pic32mx.x; \
:%{!mprocessor=*:./ldscripts/elf32pic32mx.x; \
:%{mprocessor=*:./proc/%*} %J%{mprocessor=*:/p%*} %J%{mprocessor=*:.ld} }}}} \
%{!nostdlib:%{!nodefaultlibs:%(link_ssp) %(link_gcc_c_sequence)}}\
%{!A:%{!nostdlib:%{!nostartfiles:%E} }} \
%{mprocessor=*:-p%*} \
%{mdebugger : -l:software-debug-break.o} \
%{!mdebugger : %{mmicromips : -l:debug-exception-return-mm.o; !mmicromips: -l:debug-exception-return.o}} \
}}}}}}"
#undef LINK_COMMAND_SPEC_SUPPRESS_DEFAULT_SCRIPT
#define LINK_COMMAND_SPEC_SUPPRESS_DEFAULT_SCRIPT "\
%{!fsyntax-only:%{!c:%{!M:%{!MM:%{!E:%{!S:\
%(linker) \
%{fuse-linker-plugin: \
-plugin %(linker_plugin_file) \
-plugin-opt=%(lto_wrapper) \
-plugin-opt=%(lto_gcc) \
%{static|static-libgcc:-plugin-opt=-pass-through=%(lto_libgcc)} \
%{static:-plugin-opt=-pass-through=-lc} \
%{O*:-plugin-opt=-O%*} \
%{w:-plugin-opt=-w} \
%{f*:-plugin-opt=-f%*} \
%{m*:-plugin-opt=-m%*} \
%{v:-plugin-opt=-v} \
} \
%{flto} %{fwhopr} %l " LINK_PIE_SPEC \
"%X %{o*} %{A} %{d} %{e*} %{m} %{N} %{n} %{r}\
%{s} %{t} %{u*} %{x} %{z} %{Z} %{!A:%{!nostdlib:%{!nostartfiles:%S} }}\
%{Wno-poison-system-directories:--no-poison-system-directories}\
%{Werror=poison-system-directories:--error-poison-system-directories}\
%{static:} %{L*} %(mfwrap) %(link_libgcc) %o\
%{fopenmp|ftree-parallelize-loops=*:%:include(libgomp.spec)%(link_gomp)} %(mflib)\
%{fprofile-arcs|fprofile-generate*|coverage:-lgcov}\
%{!A:%{!nostdlib:%{mdefault-isr-vectors:-l:default_isr_vectors.o} }}\
%{T*} \
%{!nostdlib:%{!nodefaultlibs:%(link_ssp) %(link_gcc_c_sequence)}}\
%{!A:%{!nostdlib:%{!nostartfiles:%E} }} \
%{mprocessor=*:-p%*} \
%{mdebugger : -l:software-debug-break.o} \
%{!mdebugger : %{mmicromips : -l:debug-exception-return-mm.o; !mmicromips: -l:debug-exception-return.o}} \
}}}}}}"
/* Added on the linker command line after all user-specified -L options are
* included. This will add all the standard -L search paths, the
* processor-specific library search path, and define _DEBUGGER if the
* -mdebugger command-line option was specified.
*/
#define LINK_LIBGCC_SPEC " \
%D -L %s%{mprocessor=*:./proc/%*; :./proc/32MXGENERIC} %{mdebugger:--defsym _DEBUGGER=1}"
/* define PATH to be used if C_INCLUDE_PATH is not declared
(and CPLUS_INCLUDE_PATH for C++, &c). The directories are all relative
to the current executable's directory */
#if 0 /* TODO */
extern char * pic32_default_include_path(void) __attribute__((weak));
#define DEFAULT_INCLUDE_PATH (pic32_default_include_path ? \
pic32_default_include_path() : \
MPLABC32_COMMON_INCLUDE_PATH )
#endif
#if 0 /* chipKIT */
#ifndef TARGET_EXTRA_PRE_INCLUDES
extern void pic32_system_include_paths(const char *root, const char *system,
int nostdinc);
#define TARGET_EXTRA_PRE_INCLUDES pic32_system_include_paths
#endif
#endif
#if 0 /* TODO */
#ifdef PATH_SEPARATOR
#if PATH_SEPARATOR == ';'
#define PATH_SEPARATOR_STR ";"
#else
#define PATH_SEPARATOR_STR ":"
#endif
#endif
#endif
#ifdef DIR_SEPARATOR
#if DIR_SEPARATOR == '\\'
#define DIR_SEPARATOR_STR "\\"
#else
#define DIR_SEPARATOR_STR "/"
#endif
#endif
#ifndef MPLABC32_COMMON_INCLUDE_PATH
#define MPLABC32_COMMON_INCLUDE_PATH ""
#endif
#ifndef MPLABC32_LEGACY_COMMON_INCLUDE_PATH
#define MPLABC32_LEGACY_COMMON_INCLUDE_PATH DIR_SEPARATOR_STR \
"lega-c"
#endif
#if 0 /* TODO */
#define DEFAULT_LIB_PATH \
MPLABC32_COMMON_LIB_PATH PATH_SEPARATOR_STR
#endif
/* These are MIPS-specific specs that we do not utilize. Undefine them
* and define them as an empty string.
*/
#undef ENDIAN_SPEC
#define ENDIAN_SPEC ""
#undef ASM_ABI_DEFAULT_SPEC
#define ASM_ABI_DEFAULT_SPEC ""
/* Supports configure-time default options (i.e., '--with' options) in the
* driver. We don't have any options that are configurable at this time.
*/
#undef OPTION_DEFAULT_SPECS
/* The default MIPS CPU is pic32mx. */
#undef MIPS_CPU_STRING_DEFAULT
#define MIPS_CPU_STRING_DEFAULT "pic32mx"
/* Override the LINK_SPEC specified in mips.h since we removed a number
* of the options utilized in that spec.
*/
#undef LINK_SPEC
#define LINK_SPEC "\
%{G*} %{bestGnum} %{shared} %{non_shared} \
%{mno-smart-io:--no-smart-io} %{msmart-io=0:--no-smart-io}"
/* Override the GAS_ASM_SPEC specified in mips.h since we removed the mtune
* option utilized in that spec.
*/
#undef GAS_ASM_SPEC
#define GAS_ASM_SPEC "%{v}"
/* Override the ASM_SPEC specified in mips.h since we removed a number
* of the options utilized in that spec.
*/
#undef ASM_SPEC
#define ASM_SPEC "\
%{G*} \
%{mips16:%{!mno-mips16:-mips16}} %{mno-mips16:-no-mips16} \
%{mips16e} \
%{mmicromips} %{mno-micromips} \
%{mmcu} %{mno-mcu} \
%{mdsp} %{mno-dsp} \
%{mdspr2} %{mno-dspr2} \
%(subtarget_asm_optimizing_spec) \
%(subtarget_asm_debugging_spec) \
%{mxgot:-xgot} \
%{mtune=*} %{v} \
%{!mpdr:-mno-pdr} \
%{mprocessor=*:-p%*} \
%(target_asm_spec) \
%(subtarget_asm_spec)"
/* SUBTARGET_CC1_SPEC is passed to the compiler proper. It may be
overridden by subtargets. */
#ifndef SUBTARGET_CC1_SPEC
#define SUBTARGET_CC1_SPEC ""
#endif
#ifndef MCHP_CCI_CC1_SPEC
#error MCHP_CCI_CC1_SPEC not defined
#endif
/* A spec that infers the -mdsp setting from an -march argument. */
#undef BASE_DRIVER_SELF_SPECS
#define BASE_DRIVER_SELF_SPECS \
"%{!mno-dsp: \
%{march=24ke*|march=34kc*|march=34kf*|march=34kx*|march=1004k*: -mdsp} \
%{march=74k*|march=m14ke*: %{!mno-dspr2: -mdspr2 -mdsp}}} \
%{mprocessor=32MX* : %{msmall-isa:-mips16} %{!msmall-isa: %{mips16: -msmall-isa}} -mpic32mxlibs } \
%{mprocessor=32mx* : %{msmall-isa:-mips16} %{!msmall-isa: %{mips16: -msmall-isa}} -mpic32mxlibs} \
%{mprocessor=32MZ* : %{msmall-isa:-mmicromips} %{!msmall-isa: %{mmicromips: -msmall-isa}} -mpic32mzlibs} \
%{mprocessor=32mz* : %{msmall-isa:-mmicromips} %{!msmall-isa: %{mmicromips: -msmall-isa}} -mpic32mzlibs} \
%{mpic32mxlibs : %{msmall-isa: -mips16}} \
%{mpic32mzlibs : %{msmall-isa: -mmicromips}} \
%{D__DEBUG : -mdebugger} \
"
/* CC1_SPEC is the set of arguments to pass to the compiler proper. This
* was copied from the one in mips.h, but that one had some problems and
* contained the endian-selection options.
*/
#undef CC1_SPEC
#define CC1_SPEC " \
%{gline:%{!g:%{!g0:%{!g1:%{!g2: -g1}}}}} \
%{G*} \
%{minterlink-mips16: -minterlink-compressed} \
%{minterlink-compressed: -mno-jals} \
%{mmicromips : %{!minterlink-compressed : %{!mno-jals : -mjals } }} \
%{msmall-isa : %{!minterlink-compressed : %{!mno-jals : -mjals } }} \
%{mprocessor=32MX* : %{msmall-isa:-mips16} %{!msmall-isa: %{mips16: -msmall-isa}} -mpic32mxlibs } \
%{mprocessor=32mx* : %{msmall-isa:-mips16} %{!msmall-isa: %{mips16: -msmall-isa}} -mpic32mxlibs} \
%{mprocessor=32MZ* : %{msmall-isa:-mmicromips} %{!msmall-isa: %{mmicromips: -msmall-isa}} -mpic32mzlibs} \
%{mprocessor=32mz* : %{msmall-isa:-mmicromips} %{!msmall-isa: %{mmicromips: -msmall-isa}} -mpic32mzlibs} \
%{-mpic32mxlibs : %{msmall-isa: -mips16}} \
%{-mpic32mzlibs : %{msmall-isa: -mmicromips}} \
-mconfig-data-dir= %J%s%{ mprocessor=* :./proc/%*; :./proc/32MXGENERIC} \
%{mno-float:-fno-builtin-fabs -fno-builtin-fabsf} \
%{mlong-calls:-msmart-io=0} \
%{msmart-io:%{msmart-io=*:%emay not use both -msmart-io and -msmart-io=LEVEL}} \
%{mno-smart-io:%{msmart-io=*:%emay not use both -mno-smart-io and -msmart-io=LEVEL}} \
%{mlegacy-libc:%{!mno-legacy-libc:-fno-short-double -msmart-io=0}} \
%{legacy-libc:%{!mno-legacy-libc:-fno-short-double -msmart-io=0}} \
%{mno-smart-io:-msmart-io=0} \
%{msmart-io:-msmart-io=1} \
%{save-temps: -fverbose-asm} \
%{O2:%{!fno-remove-local-statics: -fremove-local-statics}} \
%{O*:%{O|O0|O1|O2|Os:;:%{!fno-remove-local-statics: -fremove-local-statics}}} \
%{mips16e:-mips16} \
%{mxc32cpp-lib:%{!mno-xc32cpp-lib: -msmart-io=0 }} \
%{mips16: %{fexceptions: %{!mmips16-exceptions: %e-fexceptions with -mips16 not yet supported}}} \
%{mips16: %{!mmips16-exceptions: -fno-exceptions}} \
%{O2|Os|O3:%{!mtune:-mtune=4kec}} \
%{D__DEBUG : -mdebugger} \
%{-mit=profile : -fno-inline} \
%(mchp_cci_cc1_spec) \
%(subtarget_cc1_spec) \
"
#define CC1PLUS_SPEC " \
%{!fenforce-eh-specs:-fno-enforce-eh-specs} \
%{mxc32cpp-lib:%{!mno-xc32cpp-lib: -msmart-io=0 }} \
%(subtarget_cc1plus_spec) \
"
/* Preprocessor specs. */
/* SUBTARGET_CPP_SPEC is passed to the preprocessor. It may be
overridden by subtargets. */
#ifndef SUBTARGET_CPP_SPEC
#define SUBTARGET_CPP_SPEC ""
#endif
#undef CPP_SPEC
#define CPP_SPEC "%(subtarget_cpp_spec)\
%{mappio-debug:-D__APPIO_DEBUG} \
"
/* This macro defines names of additional specifications to put in the specs
that can be used in various specifications like CC1_SPEC. Its definition
is an initializer with a subgrouping for each command option.
Each subgrouping contains a string constant, that defines the
specification name, and a string constant that used by the GCC driver
program.
Do not define this macro if it does not need to do anything. */
#undef EXTRA_SPECS
#define EXTRA_SPECS \
{ "subtarget_cc1_spec", SUBTARGET_CC1_SPEC }, \
{ "subtarget_cpp_spec", SUBTARGET_CPP_SPEC }, \
{ "subtarget_asm_optimizing_spec", SUBTARGET_ASM_OPTIMIZING_SPEC }, \
{ "subtarget_asm_debugging_spec", SUBTARGET_ASM_DEBUGGING_SPEC }, \
{ "subtarget_asm_spec", SUBTARGET_ASM_SPEC }, \
{ "asm_abi_default_spec", "-" MULTILIB_ABI_DEFAULT }, \
{ "endian_spec", ENDIAN_SPEC }, \
{ "mchp_cci_cc1_spec", MCHP_CCI_CC1_SPEC }, \
SUBTARGET_EXTRA_SPECS
#ifndef SUBTARGET_EXTRA_SPECS
#define SUBTARGET_EXTRA_SPECS
#endif
#undef SUBTARGET_SELF_SPECS
#define SUBTARGET_SELF_SPECS \
/* Make sure a -mips option is present. This helps us to pick \
the right multilib, and also makes the later specs easier \
to write. */ \
MIPS_ISA_LEVEL_SPEC, \
\
/* Infer the default float setting from -march. */ \
MIPS_ARCH_FLOAT_SPEC, \
\
/* Infer the default dsp setting from -march. */ \
MIPS_ARCH_DSP_SPEC, \
\
/* If no ABI option is specified, infer one from the ISA level \
or -mgp setting. */ \
"%{!mabi=*: %{" MIPS_32BIT_OPTION_SPEC ": -mabi=32;: -mabi=n32}}", \
\
/* Remove a redundant -mfp64 for -mabi=n32; we want the !mfp64 \
multilibs. There's no need to check whether the architecture \
is 64-bit; cc1 will complain if it isn't. */ \
"%{mabi=n32: %<mfp64}", \
\
/* -mcode-xonly is a traditional alias for -mcode-readable=pcrel and \
-mno-data-in-code is a traditional alias for -mcode-readable=no. \
The latter trumps the former. */ \
"%{mno-data-in-code: -mcode-readable=no}", \
"%{!mcode-readable=no: %{mcode-xonly: -mcode-readable=pcrel}}", \
"%<mno-data-in-code %<mcode-xonly"
/* We won't ever support SDB or MIPS debugging info. */
#undef SDB_DEBUGGING_INFO
#undef MIPS_DEBUGGING_INFO
#undef DWARF2_DEBUGGING_INFO
#define DWARF2_DEBUGGING_INFO 1 /* dwarf2 debugging info */
#ifndef PREFERRED_DEBUGGING_TYPE
#define PREFERRED_DEBUGGING_TYPE DWARF2_DEBUG
#endif
/* By default, the GCC_EXEC_PREFIX_ENV prefix is "GCC_EXEC_PREFIX", however
in a cross compiler, another environment variable might want to be used
to avoid conflicts with the host any host GCC_EXEC_PREFIX */
#ifndef GCC_EXEC_PREFIX_ENV
#define GCC_EXEC_PREFIX_ENV "XC32_EXEC_PREFIX"
#endif
/* By default, the COMPILER_PATH_ENV is "COMPILER_PATH", however
in a cross compiler, another environment variable might want to be used
to avoid conflicts with the host any host COMPILER_PATH */
#ifndef COMPILER_PATH_ENV
#define COMPILER_PATH_ENV "XC32_COMPILER_PATH"
#endif
/* By default, the C_INCLUDE_PATH_ENV is "C_INCLUDE_PATH", however
in a cross compiler, another environment variable might want to be used
to avoid conflicts with the host any host C_INCLUDE_PATH */
#ifndef C_INCLUDE_PATH_ENV
#define C_INCLUDE_PATH_ENV "XC32_C_INCLUDE_PATH"
#endif
/* By default, the CPLUS_INCLUDE_PATH_ENV is "CPLUS_INCLUDE_PATH", however
in a cross compiler, another environment variable might want to be used
to avoid conflicts with the host any host CPLUS_INCLUDE_PATH */
#ifndef CPLUS_INCLUDE_PATH_ENV
#define CPLUS_INCLUDE_PATH_ENV "XC32_CPLUS_INCLUDE_PATH"
#endif
/* By default, the LIBRARY_PATH_ENV is "LIBRARY_PATH", however
in a cross compiler, another environment variable might want to be used
to avoid conflicts with the host any host LIBRARY_PATH */
#ifndef LIBRARY_PATH_ENV
#define LIBRARY_PATH_ENV "XC32_LIBRARY_PATH"
#endif
/* None of the OPTIONS specified in MULTILIB_OPTIONS are set by default. */
#undef MULTILIB_DEFAULTS
/* Describe how we implement __builtin_eh_return. */
/* At the moment, nothing appears to use more than 2 EH data registers.
The chosen registers must not clash with the return register ($2),
EH_RETURN_STACKADJ ($3), or MIPS_EPILOGUE_TEMP ($5), and they must
be general MIPS16 registers. Pick $6 and $7. */
#undef EH_RETURN_DATA_REGNO
#define EH_RETURN_DATA_REGNO(N) \
((N) < 2 ? 7 - (N) : INVALID_REGNUM)
/* Use $5 as a temporary for both MIPS16 and non-MIPS16. */
#undef MIPS_EPILOGUE_TEMP_REGNUM
#define MIPS_EPILOGUE_TEMP_REGNUM (GP_REG_FIRST + 5)
/* Using long will always be right for size_t and ptrdiff_t, since
sizeof(long) must equal sizeof(void *), following from the setting
of the -mlong64 option. */
#undef SIZE_TYPE
#define SIZE_TYPE "long unsigned int"
#undef PTRDIFF_TYPE
#define PTRDIFF_TYPE "long int"
/* Enable parsing of #pragma pack(push,<n>) and #pragma pack(pop). */
#define HANDLE_PRAGMA_PACK_PUSH_POP 1
/* Use standard ELF-style local labels (not '$' as on early Irix). */
#undef LOCAL_LABEL_PREFIX
#define LOCAL_LABEL_PREFIX "."
/* Use periods rather than dollar signs in special g++ assembler names. */
#define NO_DOLLAR_IN_LABEL
/* Attach a special .ident directive to the end of the file to identify
the version of GCC which compiled this code. */
#undef IDENT_ASM_OP
#define IDENT_ASM_OP "\t.ident\t"
/* Output #ident string into the ELF .comment section, so it doesn't
form part of the load image, and so that it can be stripped. */
#undef ASM_OUTPUT_IDENT
#define ASM_OUTPUT_IDENT(STREAM, STRING) \
fprintf (STREAM, "%s\"%s\"\n", IDENT_ASM_OP, STRING);
/* Currently we don't support 128bit long doubles, so for now we force
n32 to be 64bit. */
#undef LONG_DOUBLE_TYPE_SIZE
#define LONG_DOUBLE_TYPE_SIZE 64
#ifdef IN_LIBGCC2
#undef LIBGCC2_LONG_DOUBLE_TYPE_SIZE
#define LIBGCC2_LONG_DOUBLE_TYPE_SIZE 64
#endif
/* Force all .init and .fini entries to be 32-bit, not mips16, so that
in a mixed environment they are all the same mode. The crti.asm and
crtn.asm files will also be compiled as 32-bit due to the
-no-mips16 flag in SUBTARGET_ASM_SPEC above. */
#undef CRT_CALL_STATIC_FUNCTION
#define CRT_CALL_STATIC_FUNCTION(SECTION_OP, FUNC) \
asm (SECTION_OP "\n\
.set push\n\
.set nomips16\n\
jal " USER_LABEL_PREFIX #FUNC "\n\
.set pop\n\
" TEXT_SECTION_ASM_OP);
/* Used for option processing */
extern const char *mchp_processor_string;
extern const char *mchp_config_data_dir;
/* Since these switches are only used by the specs, do not need to assign a
* unique mask
*/
#define MASK_LINK_PERIPHERAL_LIBS 0
#define MASK_DEBUG_EXEC 0
#define MASK_APPIO_DEBUG 0
/* Put small constants in .rodata, not .sdata. */
#undef TARGET_DEFAULT
/* TODO */
#define TARGET_DEFAULT \
(TARGET_CPU_DEFAULT \
| TARGET_ENDIAN_DEFAULT \
| TARGET_FP_EXCEPTIONS_DEFAULT \
| MASK_CHECK_ZERO_DIV \
| MASK_FUSED_MADD \
| MASK_SOFT_FLOAT_ABI )
#undef TARGET_ENDIAN_DEFAULT
#define TARGET_ENDIAN_DEFAULT 0
#undef TARGET_FP_EXCEPTIONS_DEFAULT
#define TARGET_FP_EXCEPTIONS_DEFAULT 0
/* We want to change the default pre-defined macros. Many of these
are the same as presented in sde.h, but not all */
/* TODO: ADD all PIC32MZ macros */
#undef TARGET_OS_CPP_BUILTINS
#define TARGET_OS_CPP_BUILTINS() \
do { \
if (TARGET_ABICALLS || flag_pic) \
{ \
builtin_define ("__PIC__"); \
builtin_define ("__pic__"); \
} \
\
if (mips_abi != ABI_32) \
fatal_error ("internal error: mips_abi != ABI_32"); \
builtin_define ("_ABIO32=1"); \
builtin_define ("_MIPS_SIM=_ABIO32"); \
\
builtin_define_with_int_value ("_MIPS_SZINT", INT_TYPE_SIZE); \
builtin_define_with_int_value ("_MCHP_SZINT", INT_TYPE_SIZE); \
builtin_define_with_int_value ("_MIPS_SZLONG", LONG_TYPE_SIZE); \
builtin_define_with_int_value ("_MCHP_SZLONG", LONG_TYPE_SIZE); \
builtin_define_with_int_value ("_MIPS_SZPTR", POINTER_SIZE); \
builtin_define_with_int_value ("_MCHP_SZPTR", POINTER_SIZE); \
builtin_define_with_int_value ("_MIPS_FPSET", \
32 / MAX_FPRS_PER_FMT); \
builtin_define_with_int_value ("_MCHP_FPSET", \
32 / MAX_FPRS_PER_FMT); \
\
/* These defines reflect the ABI in use, not whether the \
FPU is directly accessible. */ \
if (TARGET_NO_FLOAT) \
{ \
builtin_define ("__NO_FLOAT"); \
builtin_define ("__mips_no_float"); \
builtin_define ("__mchp_no_float"); \
} \
else if (!TARGET_HARD_FLOAT_ABI) \
{ \
builtin_define ("__SOFT_FLOAT"); \
builtin_define ("__mips_soft_float"); \
} \
if (TARGET_SINGLE_FLOAT) \
{ \
builtin_define ("__SINGLE_FLOAT"); \
} \
\
builtin_define_std ("PIC32"); \
builtin_define ("__C32__"); \
builtin_define ("__CHIPKIT"); \
builtin_define ("__CHIPKIT__"); \
builtin_define ("__XC"); \
builtin_define ("__XC__"); \
if ((mchp_processor_string != NULL) && *mchp_processor_string) \
{ \
if (strncmp (mchp_processor_string, "32MX", 4) == 0) { \
char *proc, *p; \
int setnum, memsize; \
char *pinset; \
pinset = (char*)alloca(2); \
pinset[1] = 0; \
gcc_assert(strlen(mchp_processor_string) < 20); \
for (p = mchp_processor_string ; *p ; p++) \
*p = TOUPPER (*p); \
builtin_define_std ("PIC32MX"); \
proc = (char*)alloca (strlen (mchp_processor_string) + 6); \
gcc_assert (proc!=NULL); \
sprintf (proc, "__%s__", mchp_processor_string); \
gcc_assert (strlen(proc)>0); \
builtin_define (proc); \
\
if (strchr(proc,'F') != NULL) { \
sscanf (proc, "__32MX%6dF%6d%1c__", &setnum, \
&memsize, &pinset[0]); \
builtin_define_with_int_value \
("__PIC32_FEATURE_SET__", \
setnum); \
builtin_define_with_int_value \
("__PIC32_FEATURE_SET", \
setnum); \
builtin_define_with_int_value \
("__PIC32_MEMORY_SIZE__", \
memsize); \
builtin_define_with_int_value \
("__PIC32_MEMORY_SIZE", \
memsize); \
builtin_define_with_value \
("__PIC32_PIN_SET__", \
&pinset[0], 1); \
builtin_define_with_value \
("__PIC32_PIN_SET", \
&pinset[0], 1); \
} \
} \
else if (strncmp (mchp_processor_string, "32MZ", 4) == 0) { \
char *proc=NULL, *p=NULL; \
int pincount, flashsize; \
char *featureset=NULL; \
char *productgroup=NULL; \
char *macroname=NULL; \
int index = 0; \
gcc_assert(strlen(mchp_processor_string) < 20); \
featureset = (char*)alloca(4); \
featureset[2] = featureset[3] = '\0'; \
productgroup = (char*)alloca(3); \
productgroup[1] = productgroup[2] = '\0'; \
for (p = mchp_processor_string ; *p ; p++) \
*p = TOUPPER (*p); \
macroname = (char*)alloca ( \
strlen("__PIC32_FEATURE_SETnnnn__")+1); \
builtin_define_std ("PIC32MZ"); \
proc = (char*)alloca ( \
strlen (mchp_processor_string) + 6); \
gcc_assert(proc!=NULL); \
gcc_assert(featureset!=NULL); \
gcc_assert(productgroup!=NULL); \
gcc_assert(macroname!=NULL); \
sprintf (proc, "__%s__", mchp_processor_string); \
gcc_assert (strlen(proc)>0); \
builtin_define (proc); \
sscanf (proc, "__32MZ%4d%2c%1c%4d__", \
&flashsize, &featureset[0], \
&productgroup[0], &pincount); \
builtin_define_with_int_value \
("__PIC32_FLASH_SIZE__", \
flashsize); \
builtin_define_with_int_value \
("__PIC32_FLASH_SIZE", \
flashsize); \
builtin_define_with_value \
("__PIC32_FEATURE_SET__", \
&featureset[0], 1); \
builtin_define_with_value \
("__PIC32_FEATURE_SET", \
&featureset[0], 1); \
index = strlen(featureset); \
gcc_assert(index<3); \
while (index--) { \
snprintf(macroname, \
strlen("__PIC32_FEATURE_SETnn__")+1, \
"__PIC32_FEATURE_SET%d__", index); \
builtin_define_with_int_value \
(macroname, \
featureset[index]); \
}; \
index = strlen(featureset); \
while (index--) { \
snprintf(macroname, \
strlen("__PIC32_FEATURE_SETnn")+1, \
"__PIC32_FEATURE_SET%d", index); \
builtin_define_with_int_value \
(macroname, \
featureset[index]); \
}; \
builtin_define_with_int_value \
("__PIC32_PRODUCT_GROUP__", \
productgroup[0]); \
builtin_define_with_int_value \
("__PIC32_PRODUCT_GROUP", \
productgroup[0]); \
builtin_define_with_int_value \
("__PIC32_PIN_COUNT__", \
pincount); \
builtin_define_with_int_value \
("__PIC32_PIN_COUNT", \
pincount); \
} \
} \
else \
{ \
builtin_define ("__32MXGENERIC__"); \
} \
if ((version_string != NULL) && *version_string) \
{ \
char *Microchip; \
int pic32_compiler_version; \
gcc_assert(strlen(version_string) < 80); \
Microchip = strrchr (version_string, 'v'); \
if (Microchip) \
{ \
int major =0, minor=0; \
while ((*Microchip) && \
((*Microchip < '0') || \
(*Microchip > '9'))) \
{ Microchip++; } \
if (*Microchip) \
{ \
major = strtol (Microchip, &Microchip, 0); \
} \
if ((*Microchip) && \
((*Microchip=='_') || (*Microchip=='.'))) \
{ \
Microchip++; \
minor = strtol(Microchip, &Microchip, 0); \
} \
pic32_compiler_version = (major*1000) + (minor*10); \
} \
else \
{ \
fatal_error ("internal error: version_string == NULL"); \
builtin_define_with_int_value ("__C32_VERSION__", -1); \
builtin_define_with_int_value ("__XC32_VERSION__", -1); \
builtin_define_with_int_value ("__XC32_VERSION", -1); \
builtin_define_with_int_value ("__XC_VERSION__", -1); \
builtin_define_with_int_value ("__XC_VERSION", -1); \
} \
builtin_define_with_int_value ("__C32_VERSION__", pic32_compiler_version); \
builtin_define_with_int_value ("__XC32_VERSION__", pic32_compiler_version); \
builtin_define_with_int_value ("__XC32_VERSION", pic32_compiler_version); \
builtin_define_with_int_value ("__XC_VERSION__", pic32_compiler_version); \
builtin_define_with_int_value ("__XC_VERSION", pic32_compiler_version); \
} \
\
mchp_init_cci(pfile); \
} while (0);
/*
** Easy access check for function beginning
**/
#define NOTE_INSN_FUNCTION_BEG_P(INSN) \
((GET_CODE(INSN) == NOTE) && \
(NOTE_KIND (INSN) == NOTE_INSN_FUNCTION_BEG))
/* The Microchip port has a few pragmas to define as well */
#undef REGISTER_TARGET_PRAGMAS
#define REGISTER_TARGET_PRAGMAS() { \
c_register_pragma(0, "vector", mchp_handle_vector_pragma); \
c_register_pragma(0, "interrupt", mchp_handle_interrupt_pragma); \
c_register_pragma(0, "config", mchp_handle_config_pragma); \
c_register_pragma(0, "config_alt", mchp_handle_config_alt_pragma); \
c_register_pragma(0, "config_bf1", mchp_handle_config_bf1_pragma); \
c_register_pragma(0, "config_abf1", mchp_handle_config_abf1_pragma); \
c_register_pragma(0, "config_bf2", mchp_handle_config_bf2_pragma); \
c_register_pragma(0, "config_abf2", mchp_handle_config_abf2_pragma); \
c_register_pragma(0, "align", mchp_handle_align_pragma); \
c_register_pragma(0, "section", mchp_handle_section_pragma); \
c_register_pragma(0, "printf_args", mchp_handle_printf_args_pragma); \
c_register_pragma(0, "scanf_args", mchp_handle_scanf_args_pragma); \
c_register_pragma(0, "keep", mchp_handle_keep_pragma); \
c_register_pragma(0, "coherent", mchp_handle_coherent_pragma); \
c_register_pragma(0, "optimize", mchp_handle_optimize_pragma); \
mchp_init_cci_pragmas(); \
}
/* There are no additional prefixes to try after STANDARD_EXEC_PREFIX. */
#undef MD_EXEC_PREFIX
/* There are no additional prefixes to try after STANDARD_STARTFILE_PREFIX. */
#undef MD_STARTFILE_PREFIX
/* Disallow big endian even when the command-line option is passed */
#undef TARGET_BIG_ENDIAN
#define TARGET_BIG_ENDIAN 0
#if 1
#undef TARGET_STRIP_NAME_ENCODING
#define TARGET_STRIP_NAME_ENCODING mchp_strip_name_encoding
#endif
/* Disable options not supported by PIC32 */
#undef MASK_PAIRED_SINGLE_FLOAT
#define MASK_PAIRED_SINGLE_FLOAT 0
#undef TARGET_PAIRED_SINGLE_FLOAT
#define TARGET_PAIRED_SINGLE_FLOAT ((target_flags & MASK_PAIRED_SINGLE_FLOAT) != 0)
#undef MASK_SINGLE_FLOAT
#define MASK_SINGLE_FLOAT 0
#undef TARGET_SINGLE_FLOAT
#define TARGET_SINGLE_FLOAT ((target_flags & MASK_SINGLE_FLOAT) != 0)
#undef TARGET_DOUBLE_FLOAT
#define TARGET_DOUBLE_FLOAT ((target_flags & MASK_SINGLE_FLOAT) == 0)
#undef TARGET_HARD_FLOAT_ABI
#define TARGET_HARD_FLOAT_ABI 0
#undef MASK_64BIT
#define MASK_64BIT 0
#undef TARGET_64BIT
#define TARGET_64BIT ((target_flags & MASK_64BIT) != 0)
#undef MASK_MIPS3D
#define MASK_MIPS3D 0
#undef TARGET_MIPS3D
#define TARGET_MIPS3D ((target_flags & MASK_MIPS3D) != 0)
#undef MASK_64BIT
#define MASK_64BIT 0
#undef TARGET_64BIT
#define TARGET_64BIT ((target_flags & MASK_64BIT) != 0)
#undef MASK_FLOAT64
#define MASK_FLOAT64 0
#undef TARGET_FLOAT64
#define TARGET_FLOAT64 ((target_flags & MASK_FLOAT64) != 0)
#undef MASK_OCTEON_UNALIGNED
#define MASK_OCTEON_UNALIGNED 0
#undef TARGET_OCTEON_UNALIGNED
#define TARGET_OCTEON_UNALIGNED ((target_flags & MASK_OCTEON_UNALIGNED) != 0)
#undef MASK_SMARTMIPS
#define MASK_SMARTMIPS 0
#undef TARGET_SMARTMIPS
#define TARGET_SMARTMIPS ((target_flags & MASK_SMARTMIPS) != 0)
#undef MASK_VR4130_ALIGN
#define MASK_VR4130_ALIGN 0
#undef TARGET_VR4130_ALIGN
#define TARGET_VR4130_ALIGN ((target_flags & MASK_VR4130_ALIGN) != 0)
static const int TARGET_MAD = 0;
static const int TARGET_MDMX = 0;
/* */
#undef SECTION_FLAGS_INT
#define SECTION_FLAGS_INT uint64_t
/* the flags may be any length if surrounded by | */
#define MCHP_EXTENDED_FLAG "|"
#define MCHP_PROG_FLAG MCHP_EXTENDED_FLAG "pm" MCHP_EXTENDED_FLAG
#define MCHP_DATA_FLAG MCHP_EXTENDED_FLAG "dm" MCHP_EXTENDED_FLAG
#define MCHP_CONST_FLAG MCHP_EXTENDED_FLAG "rd" MCHP_EXTENDED_FLAG
#define MCHP_RAMFUNC_FLAG MCHP_EXTENDED_FLAG "rf" MCHP_EXTENDED_FLAG
#define MCHP_PRST_FLAG MCHP_EXTENDED_FLAG "persist" MCHP_EXTENDED_FLAG
#define MCHP_BSS_FLAG MCHP_EXTENDED_FLAG "bss" MCHP_EXTENDED_FLAG
#define MCHP_MERGE_FLAG MCHP_EXTENDED_FLAG "mrg" MCHP_EXTENDED_FLAG
#define MCHP_NOLOAD_FLAG MCHP_EXTENDED_FLAG "nl" MCHP_EXTENDED_FLAG
#define MCHP_ALGN_FLAG MCHP_EXTENDED_FLAG "a" MCHP_EXTENDED_FLAG
#define MCHP_RALGN_FLAG MCHP_EXTENDED_FLAG "ra" MCHP_EXTENDED_FLAG
#define MCHP_ADDR_FLAG MCHP_EXTENDED_FLAG "addr" MCHP_EXTENDED_FLAG
#define MCHP_FCNN_FLAG MCHP_EXTENDED_FLAG "Nf" MCHP_EXTENDED_FLAG
#define MCHP_FCNS_FLAG MCHP_EXTENDED_FLAG "Sf" MCHP_EXTENDED_FLAG
#define MCHP_SFR_FLAG MCHP_EXTENDED_FLAG "sfr" MCHP_EXTENDED_FLAG
#define MCHP_NEAR_FLAG MCHP_EXTENDED_FLAG "near" MCHP_EXTENDED_FLAG
#define MCHP_KEEP_FLAG MCHP_EXTENDED_FLAG "keep" MCHP_EXTENDED_FLAG
#define MCHP_COHERENT_FLAG MCHP_EXTENDED_FLAG "coherent" MCHP_EXTENDED_FLAG
#define MCHP_IS_NAME_P(NAME,IS) (strncmp(NAME, IS, sizeof(IS)-1) == 0)
#define MCHP_HAS_NAME_P(NAME,HAS) (strstr(NAME, HAS))
#define ENCODED_NAME_P(SYMBOL_NAME) \
((SYMBOL_NAME[0] == MCHP_EXTENDED_FLAG[0]) ? \
(strrchr(SYMBOL_NAME,MCHP_EXTENDED_FLAG[0]) - SYMBOL_NAME) + 1 : 0)
/*
** Output before program text section
*/
#undef TEXT_SECTION_ASM_OP
#define TEXT_SECTION_ASM_OP mchp_text_section_asm_op()
#undef READONLY_DATA_SECTION_ASM_OP
#define READONLY_DATA_SECTION_ASM_OP mchp_rdata_section_asm_op() /* read-only data */
#undef TARGET_ASM_SELECT_SECTION
#define TARGET_ASM_SELECT_SECTION mchp_select_section
/* CHANGE TO NAMED SECTION */
#undef TARGET_ASM_NAMED_SECTION
#define TARGET_ASM_NAMED_SECTION mchp_asm_named_section
/*
** Output before writable data.
*/
#undef DATA_SECTION_ASM_OP
#define DATA_SECTION_ASM_OP mchp_data_section_asm_op()
#undef BSS_SECTION_ASM_OP
#define BSS_SECTION_ASM_OP mchp_bss_section_asm_op()
#undef SBSS_SECTION_ASM_OP
#define SBSS_SECTION_ASM_OP mchp_sbss_section_asm_op()
#undef SDATA_SECTION_ASM_OP
#define SDATA_SECTION_ASM_OP mchp_sdata_section_asm_op()
#if 1
#define HAS_INIT_SECTION 1
#undef INIT_SECTION_ASM_OP
#define INIT_SECTION_ASM_OP "\t.section .init, code"
#undef FINI_SECTION_ASM_OP
#define FINI_SECTION_ASM_OP "\t.section .fini, code"
#endif
#if 1
#undef CTORS_SECTION_ASM_OP
#define CTORS_SECTION_ASM_OP "\t.section .ctors, code"
#undef DTORS_SECTION_ASM_OP
#define DTORS_SECTION_ASM_OP "\t.section .dtors, code"
#endif
#undef TARGET_ASM_FILE_END
#define TARGET_ASM_FILE_END mchp_file_end
/* GET SECTION TYPE FLAGS */
#undef TARGET_SECTION_TYPE_FLAGS
#define TARGET_SECTION_TYPE_FLAGS mchp_section_type_flags
#undef MIPS_SUBTARGET_FUNCTION_END_PROLOGUE
#undef MIPS_SUBTARGET_SET_CURRENT_FUNCTION
#undef MIPS_SUBTARGET_PREPARE_FUNCTION_START
#define MIPS_SUBTARGET_PREPARE_FUNCTION_START(fndecl) \
mchp_prepare_function_start(fndecl)
#undef MIPS_SUBTARGET_SUPPRESS_PROLOGUE
#define MIPS_SUBTARGET_SUPPRESS_PROLOGUE() mchp_suppress_prologue()
#undef MIPS_SUBTARGET_FUNCTION_PROFILING_EPILOGUE
#define MIPS_SUBTARGET_FUNCTION_PROFILING_EPILOGUE(sibcall_p) mchp_function_profiling_epilogue(sibcall_p)
#undef MIPS_SUBTARGET_SUPPRESS_EPILOGUE
#define MIPS_SUBTARGET_SUPPRESS_EPILOGUE() mchp_suppress_epilogue()
#undef MIPS_SUBTARGET_EXPAND_PROLOGUE_AFTER_SAVE
#undef MIPS_SUBTARGET_EXPAND_PROLOGUE_END
#define MIPS_SUBTARGET_EXPAND_PROLOGUE_END(frame) \
mchp_expand_prologue_end(frame)
#undef MIPS_SUBTARGET_EXPAND_EPILOGUE_RESTOREREGS
#define MIPS_SUBTARGET_EXPAND_EPILOGUE_RESTOREREGS(step1,step2) \
mchp_expand_epilogue_restoreregs(step1,step2)
#undef MIPS_SUBTARGET_EXPAND_EPILOGUE_RETURN
#undef MIPS_SUBTARGET_OUTPUT_FUNCTION_BEGIN_EPILOGUE
#undef MIPS_SUBTARGET_OUTPUT_FUNCTION_EPILOGUE
#define MIPS_SUBTARGET_OUTPUT_FUNCTION_EPILOGUE(file,size) \
mchp_output_function_epilogue(file,size)
#undef MIPS_SUBTARGET_COMPUTE_FRAME_INFO
#define MIPS_SUBTARGET_COMPUTE_FRAME_INFO() mchp_compute_frame_info()
#undef MIPS_SUBTARGET_ATTRIBUTE_TABLE
#define MIPS_SUBTARGET_ATTRIBUTE_TABLE \
/* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */ \
/* Microchip: allow functions to be specified as interrupt handlers */ \
{ "interrupt", 0, 1, false, true, true, mchp_interrupt_attribute }, \
{ "vector", 1, 256, true, false, false, mchp_vector_attribute }, \
{ "at_vector", 1, 1, true, false, false, mchp_at_vector_attribute }, \
/* also allow functions to be created without prologue/epilogue code */ \
{ "naked", 0, 0, true, false, false, mchp_naked_attribute }, \
{ "address", 1, 1, false, false, false, mchp_address_attribute }, \
{ "space", 1, 1, false, false, false, mchp_space_attribute }, \
{ "persistent", 0, 0, false, false, false, mchp_persistent_attribute }, \
{ "ramfunc", 0, 0, false, true, true, mchp_ramfunc_attribute }, \
{ "unsupported", 0, 1, false, false, false, mchp_unsupported_attribute }, \
{ "target_error", 1, 1, false, false, false, mchp_target_error_attribute }, \
{ "keep", 0, 0, false, false, false, mchp_keep_attribute }, \
{ "coherent", 0, 0, false, false, false, mchp_coherent_attribute }, \
{ "crypto", 0, 0, false, false, false, mchp_crypto_attribute },
#undef MIPS_DISABLE_INTERRUPT_ATTRIBUTE
#define MIPS_DISABLE_INTERRUPT_ATTRIBUTE
extern enum mips_function_type_tag current_function_type;
#undef MIPS_SUBTARGET_SAVE_REG_P
#define MIPS_SUBTARGET_SAVE_REG_P(regno) \
mchp_subtarget_save_reg_p(regno)
#undef MIPS_SUBTARGET_OUTPUT_FUNCTION_PROLOGUE
#define MIPS_SUBTARGET_OUTPUT_FUNCTION_PROLOGUE(file,tsize,size) \
mchp_output_function_prologue(file,tsize,size)
#undef MIPS_SUBTARGET_EXPAND_PROLOGUE_SAVEREGS
#define MIPS_SUBTARGET_EXPAND_PROLOGUE_SAVEREGS(size,step1) \
mchp_expand_prologue_saveregs(size,step1)
#undef MIPS_SUBTARGET_INSERT_ATTRIBUTES
#define MIPS_SUBTARGET_INSERT_ATTRIBUTES(decl,attr_ptr) \
mchp_target_insert_attributes (decl,attr_ptr)
#undef MIPS_SUBTARGET_FUNCTION_OK_FOR_SIBCALL
#undef MIPS_SUBTARGET_OVERRIDE_OPTIONS
#define MIPS_SUBTARGET_OVERRIDE_OPTIONS() \
mchp_subtarget_override_options()
#undef MIPS_SUBTARGET_OVERRIDE_OPTIONS1
#define MIPS_SUBTARGET_OVERRIDE_OPTIONS1() \
mchp_subtarget_override_options1()
#undef MIPS_SUBTARGET_OVERRIDE_OPTIONS2
#define MIPS_SUBTARGET_OVERRIDE_OPTIONS2() \
mchp_subtarget_override_options2()
#if 0 /* chipKIT */
#undef OPTIMIZATION_OPTIONS
#define OPTIMIZATION_OPTIONS(LEVEL,SIZE) \
pic32_optimization_options ((LEVEL), (SIZE))
#endif
#undef MIPS_SUBTARGET_MIPS16_ENABLED
#define MIPS_SUBTARGET_MIPS16_ENABLED(decl) \
mchp_subtarget_mips16_enabled(decl)
#undef MIPS_SUBTARGET_MICROMIPS_ENABLED
#define MIPS_SUBTARGET_MICROMIPS_ENABLED(decl) \
mchp_subtarget_micromips_enabled(decl)
#undef MIPS_SUBTARGET_ENCODE_SECTION_INFO
#define MIPS_SUBTARGET_ENCODE_SECTION_INFO(decl,rtl,first) \
mchp_subtarget_encode_section_info(decl,rtl,first)
#define USE_SELECT_SECTION_FOR_FUNCTIONS 1
#undef JUMP_TABLES_IN_TEXT_SECTION
#define JUMP_TABLES_IN_TEXT_SECTION 1
#undef SUPPORTS_DISCRIMINATOR
#define SUPPORTS_DISCRIMINATOR 0
/* A few bitfield locations for the coprocessor registers */
#define CAUSE_IPL 10
#define SR_IPL 10
#define SR_IE 0
#define SR_EXL 1
#define SR_ERL 2
#undef TARGET_ASM_CONSTRUCTOR
#define TARGET_ASM_CONSTRUCTOR default_named_section_asm_out_constructor
#undef TARGET_ASM_DESTRUCTOR
#define TARGET_ASM_DESTRUCTOR default_named_section_asm_out_destructor
#undef TARGET_USE_JCR_SECTION
#define TARGET_USE_JCR_SECTION 0
#undef JCR_SECTION_NAME
#undef TARGET_APPLY_PRAGMA
#define TARGET_APPLY_PRAGMA mchp_apply_pragmas
/* Initialize the GCC target structure. */
#if 0 /* chipKIT */
#undef TARGET_OVERRIDE_OPTIONS_AFTER_CHANGE
#define TARGET_OVERRIDE_OPTIONS_AFTER_CHANGE mchp_override_options_after_change
#endif
/* True if we can optimize sibling calls. For simplicity, we only
handle cases in which call_insn_operand will reject invalid
sibcall addresses. There are two cases in which this isn't true:
- TARGET_MIPS16. call_insn_operand accepts constant addresses
but there is no direct jump instruction. It isn't worth
using sibling calls in this case anyway; they would usually
be longer than normal calls.
- TARGET_USE_GOT && !TARGET_EXPLICIT_RELOCS. call_insn_operand
accepts global constants, but all sibcalls must be indirect. */
#undef TARGET_SIBCALLS
#define TARGET_SIBCALLS \
(!TARGET_MIPS16 && (!TARGET_USE_GOT || TARGET_EXPLICIT_RELOCS) && !mchp_profile_option)
#define PIC32_SUPPORT_CRYPTO_ATTRIBUTE 1
#endif /* MCHP_H */
|
package loki_test
import (
"bytes"
"encoding/json"
"fmt"
"testing"
"time"
"github.com/andviro/goldie"
"github.com/andviro/grayproxy/pkg/loki"
"github.com/prometheus/common/model"
)
type testHandler bytes.Buffer
func (t *testHandler) Handle(ls model.LabelSet, ts time.Time, s string) error {
buf := (*bytes.Buffer)(t)
jd, _ := json.Marshal(ts)
fmt.Fprintf(buf, "%s\n", jd)
jd, _ = json.MarshalIndent(ls, "", "\t")
fmt.Fprintf(buf, "%s\n", jd)
fmt.Fprintf(buf, "%s\n", s)
return nil
}
func TestSender_Send(t *testing.T) {
buf := new(bytes.Buffer)
s := loki.Sender{Handler: (*testHandler)(buf), Job: "test"}
err := s.Send([]byte(`{
"version": "1.1",
"host": "example.org",
"short_message": "A short message that helps you identify what is going on",
"full_message": "Backtrace here\n\nmore stuff",
"timestamp": 1385053862.3072,
"level": 1,
"_user_id": 9001,
"_some_info": "foo",
"_some_env_var": "bar"
}`))
if err != nil {
t.Fatal(err)
}
goldie.Assert(t, "sender-send", buf.Bytes())
}
|
* Ask about a timeline
* Start thining about the timeline - calculate backwards starting from the launch date.
* What ressources do you have / do you need to acquire?
** Project Managers, Designer, Web Developer, UX Experts, Testers, Content People, Createive Agencies, Specialised E-Commerce Agencies
* Benchmarking the most important competitors for new features
* Make a list of existing features categorized by page type in a mindmap.
* Create Epics with general requirements based on page types, break down those epics into smaller user stories (Extra Post)
* How to write a user story (Extra Post)
## Next - Idea: Create a Framework for Relaunches.
|
/**
* Lawnchair!
* ---
* clientside json store
*
*/
var Lawnchair = function () {
// lawnchair requires json
if (!JSON) throw 'JSON unavailable! Include http://www.json.org/json2.js to fix.'
// options are optional; callback is not
if (arguments.length <= 2 && arguments.length > 0) {
var callback = (typeof arguments[0] === 'function') ? arguments[0] : arguments[1]
, options = (typeof arguments[0] === 'function') ? {} : arguments[0]
} else {
throw 'Incorrect # of ctor args!'
}
if (typeof callback !== 'function') throw 'No callback was provided';
// default configuration
this.record = options.record || 'record' // default for records
this.name = options.name || 'records' // default name for underlying store
// mixin first valid adapter
var adapter
// if the adapter is passed in we try to load that only
if (options.adapter) {
adapter = Lawnchair.adapters[Lawnchair.adapters.indexOf(options.adapter)]
adapter = adapter.valid() ? adapter : undefined
// otherwise find the first valid adapter for this env
} else {
for (var i = 0, l = Lawnchair.adapters.length; i < l; i++) {
adapter = Lawnchair.adapters[i].valid() ? Lawnchair.adapters[i] : undefined
if (adapter) break
}
}
// we have failed
if (!adapter) throw 'No valid adapter.'
// yay! mixin the adapter
for (var j in adapter) {
this[j] = adapter[j]
}
// call init for each mixed in plugin
for (var i = 0, l = Lawnchair.plugins.length; i < l; i++)
Lawnchair.plugins[i].call(this)
// init the adapter
this.init(options, callback)
}
Lawnchair.adapters = []
/**
* queues an adapter for mixin
* ===
* - ensures an adapter conforms to a specific interface
*
*/
Lawnchair.adapter = function (id, obj) {
// add the adapter id to the adapter obj
// ugly here for a cleaner dsl for implementing adapters
obj['adapter'] = id
// methods required to implement a lawnchair adapter
var implementing = 'adapter valid init keys save batch get exists all remove nuke'.split(' ')
// mix in the adapter
for (var i in obj) if (implementing.indexOf(i) === -1) throw 'Invalid adapter! Nonstandard method: ' + i
// if we made it this far the adapter interface is valid
Lawnchair.adapters.push(obj)
}
Lawnchair.plugins = []
/**
* generic shallow extension for plugins
* ===
* - if an init method is found it registers it to be called when the lawnchair is inited
* - yes we could use hasOwnProp but nobody here is an asshole
*/
Lawnchair.plugin = function (obj) {
for (var i in obj)
i === 'init' ? Lawnchair.plugins.push(obj[i]) : this.prototype[i] = obj[i]
}
/**
* helpers
*
*/
Lawnchair.prototype = {
isArray: Array.isArray || function(o) { return Object.prototype.toString.call(o) === '[object Array]' },
// awesome shorthand callbacks as strings. this is shameless theft from dojo.
lambda: function (callback) {
return this.fn(this.record, callback)
},
// first stab at named parameters for terse callbacks; dojo: first != best // ;D
fn: function (name, callback) {
return typeof callback == 'string' ? new Function(name, callback) : callback
},
// returns a unique identifier (by way of Backbone.localStorage.js)
// TODO investigate smaller UUIDs to cut on storage cost
uuid: function () {
var S4 = function () {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
},
// a classic iterator
each: function (callback) {
var cb = this.lambda(callback)
// iterate from chain
if (this.__results) {
for (var i = 0, l = this.__results.length; i < l; i++) cb.call(this, this.__results[i], i)
}
// otherwise iterate the entire collection
else {
this.all(function(r) {
for (var i = 0, l = r.length; i < l; i++) cb.call(this, r[i], i)
})
}
return this
}
// --
};
Lawnchair.adapter('webkit-sqlite', (function () {
// private methods
var fail = function (e, i) { console.log('error in sqlite adaptor!', e, i) }
, now = function () { return new Date() } // FIXME need to use better date fn
// not entirely sure if this is needed...
if (!Function.prototype.bind) {
Function.prototype.bind = function( obj ) {
var slice = [].slice
, args = slice.call(arguments, 1)
, self = this
, nop = function () {}
, bound = function () {
return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments)))
}
nop.prototype = self.prototype
bound.prototype = new nop()
return bound
}
}
// public methods
return {
valid: function() { return !!(window.openDatabase) },
init: function (options, callback) {
var that = this
, cb = that.fn(that.name, callback)
, create = "CREATE TABLE IF NOT EXISTS " + this.name + " (id NVARCHAR(32) UNIQUE PRIMARY KEY, value TEXT, timestamp REAL)"
, win = cb.bind(this)
// open a connection and create the db if it doesn't exist
this.db = openDatabase(this.name, '1.0.0', this.name, 65536)
this.db.transaction(function (t) {
t.executeSql(create, [], win, fail)
})
},
keys: function (callback) {
var cb = this.lambda(callback)
, that = this
, keys = "SELECT id FROM " + this.name + " ORDER BY timestamp DESC"
this.db.transaction(function(t) {
var win = function (xxx, results) {
if (results.rows.length == 0 ) {
cb.call(that, [])
} else {
var r = [];
for (var i = 0, l = results.rows.length; i < l; i++) {
r.push(results.rows.item(i).id);
}
cb.call(that, r)
}
}
t.executeSql(keys, [], win, fail)
})
return this
},
// you think thats air you're breathing now?
save: function (obj, callback) {
var that = this
, id = obj.key || that.uuid()
, ins = "INSERT INTO " + this.name + " (value, timestamp, id) VALUES (?,?,?)"
, up = "UPDATE " + this.name + " SET value=?, timestamp=? WHERE id=?"
, win = function () { if (callback) { obj.key = id; that.lambda(callback).call(that, obj) }}
, val = [now(), id]
// existential
that.exists(obj.key, function(exists) {
// transactions are like condoms
that.db.transaction(function(t) {
// TODO move timestamp to a plugin
var insert = function (obj) {
val.unshift(JSON.stringify(obj))
t.executeSql(ins, val, win, fail)
}
// TODO move timestamp to a plugin
var update = function (obj) {
delete(obj.key)
val.unshift(JSON.stringify(obj))
t.executeSql(up, val, win, fail)
}
// pretty
exists ? update(obj) : insert(obj)
})
});
return this
},
// FIXME this should be a batch insert / just getting the test to pass...
batch: function (objs, cb) {
var results = []
, done = false
, that = this
var updateProgress = function(obj) {
results.push(obj)
done = results.length === objs.length
}
var checkProgress = setInterval(function() {
if (done) {
if (cb) that.lambda(cb).call(that, results)
clearInterval(checkProgress)
}
}, 200)
for (var i = 0, l = objs.length; i < l; i++)
this.save(objs[i], updateProgress)
return this
},
get: function (keyOrArray, cb) {
var that = this
, sql = ''
// batch selects support
if (this.isArray(keyOrArray)) {
sql = 'SELECT id, value FROM ' + this.name + " WHERE id IN ('" + keyOrArray.join("','") + "')"
} else {
sql = 'SELECT id, value FROM ' + this.name + " WHERE id = '" + keyOrArray + "'"
}
// FIXME
// will always loop the results but cleans it up if not a batch return at the end..
// in other words, this could be faster
var win = function (xxx, results) {
var o = null
, r = []
if (results.rows.length) {
for (var i = 0, l = results.rows.length; i < l; i++) {
o = JSON.parse(results.rows.item(i).value)
o.key = results.rows.item(i).id
r.push(o)
}
}
if (!that.isArray(keyOrArray)) r = r.length ? r[0] : null
if (cb) that.lambda(cb).call(that, r)
}
this.db.transaction(function(t){ t.executeSql(sql, [], win, fail) })
return this
},
exists: function (key, cb) {
var is = "SELECT * FROM " + this.name + " WHERE id = ?"
, that = this
, win = function(xxx, results) { if (cb) that.fn('exists', cb).call(that, (results.rows.length > 0)) }
this.db.transaction(function(t){ t.executeSql(is, [key], win, fail) })
return this
},
all: function (callback) {
var that = this
, all = "SELECT * FROM " + this.name
, r = []
, cb = this.fn(this.name, callback) || undefined
, win = function (xxx, results) {
if (results.rows.length != 0) {
for (var i = 0, l = results.rows.length; i < l; i++) {
var obj = JSON.parse(results.rows.item(i).value)
obj.key = results.rows.item(i).id
r.push(obj)
}
}
if (cb) cb.call(that, r)
}
this.db.transaction(function (t) {
t.executeSql(all, [], win, fail)
})
return this
},
remove: function (keyOrObj, cb) {
var that = this
, key = typeof keyOrObj === 'string' ? keyOrObj : keyOrObj.key
, del = "DELETE FROM " + this.name + " WHERE id = ?"
, win = function () { if (cb) that.lambda(cb).call(that) }
this.db.transaction( function (t) {
t.executeSql(del, [key], win, fail);
});
return this;
},
nuke: function (cb) {
var nuke = "DELETE FROM " + this.name
, that = this
, win = cb ? function() { that.lambda(cb).call(that) } : function(){}
this.db.transaction(function (t) {
t.executeSql(nuke, [], win, fail)
})
return this
}
//////
}})())
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("HealthMonitoring.AcceptanceTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HealthMonitoring.AcceptanceTests")]
[assembly: AssemblyCopyright("Copyright © Wonga")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("8d2cfa8a-f44f-4de2-98bc-b19eb496f003")]
[assembly: AssemblyVersion("3.9.0.0")]
[assembly: AssemblyFileVersion("3.9.0.0")]
|
require 'test_helper'
class EmailsControllerTest < ActionDispatch::IntegrationTest
# test "the truth" do
# assert true
# end
end
|
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20150715020048) do
create_table "categories", force: :cascade do |t|
t.string "name", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "item_types", force: :cascade do |t|
t.string "name", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "items", force: :cascade do |t|
t.string "name", null: false
t.string "description", null: false
t.integer "item_type_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "people", force: :cascade do |t|
t.string "name", null: false
t.boolean "living", default: true
t.integer "age", default: -1
t.string "description", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "relationships", force: :cascade do |t|
t.string "name", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "tags", force: :cascade do |t|
t.integer "taggable_id"
t.string "taggable_type"
t.integer "category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
|
(function(){function h(a){return function(){return this[a]}}var k=this;function n(a){return"string"==typeof a}function p(a,c){var b=a.split("."),d=k;!(b[0]in d)&&d.execScript&&d.execScript("var "+b[0]);for(var e;b.length&&(e=b.shift());)!b.length&&void 0!==c?d[e]=c:d=d[e]?d[e]:d[e]={}};var q="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function s(a){var c=Number(a);return 0==c&&/^[\s\xa0]*$/.test(a)?NaN:c};function t(a,c){this.b=a|0;this.a=c|0}var v={};function w(a){if(-128<=a&&128>a){var c=v[a];if(c)return c}c=new t(a|0,0>a?-1:0);-128<=a&&128>a&&(v[a]=c);return c}function x(a){return isNaN(a)||!isFinite(a)?y:a<=-z?A:a+1>=z?aa:0>a?B(x(-a)):new t(a%C|0,a/C|0)}
function D(a,c){if(0==a.length)throw Error("number format error: empty string");var b=c||10;if(2>b||36<b)throw Error("radix out of range: "+b);if("-"==a.charAt(0))return B(D(a.substring(1),b));if(0<=a.indexOf("-"))throw Error('number format error: interior "-" character: '+a);for(var d=x(Math.pow(b,8)),e=y,f=0;f<a.length;f+=8){var g=Math.min(8,a.length-f),m=parseInt(a.substring(f,f+g),b);8>g?(g=x(Math.pow(b,g)),e=e.multiply(g).add(x(m))):(e=e.multiply(d),e=e.add(x(m)))}return e}
var C=4294967296,z=C*C/2,y=w(0),E=w(1),F=w(-1),aa=new t(-1,2147483647),A=new t(0,-2147483648),G=w(16777216);
t.prototype.toString=function(a){a=a||10;if(2>a||36<a)throw Error("radix out of range: "+a);if(H(this))return"0";if(0>this.a){if(I(this,A)){var c=x(a),b=J(this,c),c=L(b.multiply(c),this);return b.toString(a)+c.b.toString(a)}return"-"+B(this).toString(a)}for(var b=x(Math.pow(a,6)),c=this,d="";;){var e=J(c,b),f=L(c,e.multiply(b)).b.toString(a),c=e;if(H(c))return f+d;for(;6>f.length;)f="0"+f;d=""+f+d}};function M(a){return 0<=a.b?a.b:C+a.b}function H(a){return 0==a.a&&0==a.b}
function I(a,c){return a.a==c.a&&a.b==c.b}function N(a,c){if(I(a,c))return 0;var b=0>a.a,d=0>c.a;return b&&!d?-1:!b&&d?1:0>L(a,c).a?-1:1}function B(a){return I(a,A)?A:(new t(~a.b,~a.a)).add(E)}t.prototype.add=function(a){var c=this.a>>>16,b=this.a&65535,d=this.b>>>16,e=a.a>>>16,f=a.a&65535,g=a.b>>>16,m;m=0+((this.b&65535)+(a.b&65535));a=0+(m>>>16);a+=d+g;d=0+(a>>>16);d+=b+f;b=0+(d>>>16);b=b+(c+e)&65535;return new t((a&65535)<<16|m&65535,b<<16|d&65535)};function L(a,c){return a.add(B(c))}
t.prototype.multiply=function(a){if(H(this)||H(a))return y;if(I(this,A))return 1==(a.b&1)?A:y;if(I(a,A))return 1==(this.b&1)?A:y;if(0>this.a)return 0>a.a?B(this).multiply(B(a)):B(B(this).multiply(a));if(0>a.a)return B(this.multiply(B(a)));if(0>N(this,G)&&0>N(a,G))return x((this.a*C+M(this))*(a.a*C+M(a)));var c=this.a>>>16,b=this.a&65535,d=this.b>>>16,e=this.b&65535,f=a.a>>>16,g=a.a&65535,m=a.b>>>16;a=a.b&65535;var u,l,r,K;K=0+e*a;r=0+(K>>>16);r+=d*a;l=0+(r>>>16);r=(r&65535)+e*m;l+=r>>>16;r&=65535;
l+=b*a;u=0+(l>>>16);l=(l&65535)+d*m;u+=l>>>16;l&=65535;l+=e*g;u+=l>>>16;l&=65535;u=u+(c*a+b*m+d*g+e*f)&65535;return new t(r<<16|K&65535,u<<16|l)};
function J(a,c){if(H(c))throw Error("division by zero");if(H(a))return y;if(I(a,A)){if(I(c,E)||I(c,F))return A;if(I(c,A))return E;var b;b=1;if(0==b)b=a;else{var d=a.a;b=32>b?new t(a.b>>>b|d<<32-b,d>>b):new t(d>>b-32,0<=d?0:-1)}b=J(b,c).shiftLeft(1);if(I(b,y))return 0>c.a?E:F;d=L(a,c.multiply(b));return b.add(J(d,c))}if(I(c,A))return y;if(0>a.a)return 0>c.a?J(B(a),B(c)):B(J(B(a),c));if(0>c.a)return B(J(a,B(c)));for(var e=y,d=a;0<=N(d,c);){b=Math.max(1,Math.floor((d.a*C+M(d))/(c.a*C+M(c))));for(var f=
Math.ceil(Math.log(b)/Math.LN2),f=48>=f?1:Math.pow(2,f-48),g=x(b),m=g.multiply(c);0>m.a||0<N(m,d);)b-=f,g=x(b),m=g.multiply(c);H(g)&&(g=E);e=e.add(g);d=L(d,m)}return e}t.prototype.shiftLeft=function(a){a&=63;if(0==a)return this;var c=this.b;return 32>a?new t(c<<a,this.a<<a|c>>>32-a):new t(0,c<<a-32)};var O=Array.prototype,P=O.forEach?function(a,c,b){O.forEach.call(a,c,b)}:function(a,c,b){for(var d=a.length,e=n(a)?a.split(""):a,f=0;f<d;f++)f in e&&c.call(b,e[f],f,a)},Q=O.map?function(a,c,b){return O.map.call(a,c,b)}:function(a,c,b){for(var d=a.length,e=Array(d),f=n(a)?a.split(""):a,g=0;g<d;g++)g in f&&(e[g]=c.call(b,f[g],g,a));return e};function R(a,c,b){if(a.reduce)return a.reduce(c,b);var d=b;P(a,function(b,f){d=c.call(void 0,d,b,f,a)});return d}
function S(a,c,b){return 2>=arguments.length?O.slice.call(a,c):O.slice.call(a,c,b)};function T(a){return U(1,arguments,function(a,b){return a.add(b)})}function V(a,c){var b=W(2,[a,c]).d;return X(b[0]/b[1])}function Y(a){return U(3,arguments,function(a,b){return L(a,b)})}function Z(a){return U(4,arguments,function(a,b){return a.multiply(b)})}
function $(a){if("number"==typeof a)return a;var c=a.toString(),b=a.c;if(0!=b){var d;a=!1;"-"==c.charAt(0)&&(a=!0,c=c.replace(/^\-/,""));c.length<=b?(c=String(s(c)),d=c.indexOf("."),-1==d&&(d=c.length),b=Math.max(0,b-d),d=Array(b+1).join("0")+c,b="0"):(d=c.slice(-b),b=c.slice(0,-b));c=(a?"-":"")+b+"."+d}return s(c)}function U(a,c,b){c=W(a,c);b=R(S(c.d,1),b,c.d[0]);b.k(a,c.d.length,c.i);return b}
function X(a){if(!n(a)&&"number"!=typeof a)throw Error('Invalid value: "'+a+'"');a=s(String(a));var c=String(a),b,d;if(d=c.match(/\.(\d+)$/)){b=D;var e=RegExp,f;f=".".replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08");e=e(f,"");c=c.replace(e,"");b=b(c);b.e(a,d[1].length)}else b=D(c),b.e(a);return b}
function W(a,c){c=Q(c,function(a){return a instanceof t?a:X(a)});if(4==a){var b=R(c,function(a,b){return a+b.c},0);return{d:c,i:b}}var d=Math.max.apply(null,Q(c,function(a){return a.c}));if(0!=d){var e,f;c=Q(c,function(a){e=d-a.c;return 0!=e?(f=a.multiply(x(Math.pow(10,e))),f.j(a),f):a})}return{d:c,i:d}}
(function(a,c){for(var b,d,e=1;e<arguments.length;e++){d=arguments[e];for(b in d)a[b]=d[b];for(var f=0;f<q.length;f++)b=q[f],Object.prototype.hasOwnProperty.call(d,b)&&(a[b]=d[b])}})(t.prototype,{f:void 0,c:0,h:null,g:0,k:function(a,c,b){this.h=a;this.g=c;this.c=b},n:h("h"),m:h("g"),e:function(a,c){a&&(this.f=a);this.c=c||0},j:function(a){this.e(a.f,a.c)},p:h("f"),o:h("c"),l:function(){return 0!=this.c}});
p("sao.calc",function(a){var c,b=[],d=[];P(arguments,function(a){n(a)&&/^\+|\-|\*|\/$/.test(a)?b[b.length]=a:d[d.length]=a});c=R(S(d,1),function(a,c){switch(b.shift()){case "+":return T(a,c);case "-":return Y(a,c);case "/":return V(a,c);case "*":return Z(a,c)}},d[0]);return $(c)});p("sao.add",T);p("sao.div",V);p("sao.sub",Y);p("sao.mul",Z);p("sao.finalize",$);
p("sao.round",function(a,c){var b="number"==typeof a?X(a):a,d=b.toString().replace(/^\-/,""),e=c||0;if(b.l()&&!(b.c<=e)){var f=b.c,d=d.charAt(d.length-f+e),b=X(b.toString().slice(0,-(f-e)));b.e(void 0,e);4<s(d)?(e=x(1),e=0>b.a?B(e):e,e=b.add(e),e.j(b)):e=b;return $(e)}return $(b)});})()
|
module Hanami
module Utils
# HTML escape utilities
#
# Based on OWASP research and OWASP ESAPI code
#
# @since 0.4.0
#
# @see https://www.owasp.org
# @see https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29
# @see https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
# @see https://www.owasp.org/index.php/ESAPI
# @see https://github.com/ESAPI/esapi-java-legacy
module Escape
# Hex base for base 10 integer conversion
#
# @since 0.4.0
# @api private
#
# @see http://www.ruby-doc.org/core/Fixnum.html#method-i-to_s
HEX_BASE = 16
# Limit for non printable chars
#
# @since 0.4.0
# @api private
LOW_HEX_CODE_LIMIT = 0xff
# Replacement hex for non printable characters
#
# @since 0.4.0
# @api private
REPLACEMENT_HEX = "fffd".freeze
# Low hex codes lookup table
#
# @since 0.4.0
# @api private
HEX_CODES = (0..255).each_with_object({}) do |c, codes|
if (c >= 0x30 && c <= 0x39) || (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A)
codes[c] = nil
else
codes[c] = c.to_s(HEX_BASE)
end
end.freeze
# Non printable chars
#
# This is a Hash instead of a Set, to make lookup faster.
#
# @since 0.4.0
# @api private
#
# @see https://gist.github.com/jodosha/ac5dd54416de744b9600
NON_PRINTABLE_CHARS = {
0x0 => true, 0x1 => true, 0x2 => true, 0x3 => true, 0x4 => true,
0x5 => true, 0x6 => true, 0x7 => true, 0x8 => true, 0x11 => true,
0x12 => true, 0x14 => true, 0x15 => true, 0x16 => true, 0x17 => true,
0x18 => true, 0x19 => true, 0x1a => true, 0x1b => true, 0x1c => true,
0x1d => true, 0x1e => true, 0x1f => true, 0x7f => true, 0x80 => true,
0x81 => true, 0x82 => true, 0x83 => true, 0x84 => true, 0x85 => true,
0x86 => true, 0x87 => true, 0x88 => true, 0x89 => true, 0x8a => true,
0x8b => true, 0x8c => true, 0x8d => true, 0x8e => true, 0x8f => true,
0x90 => true, 0x91 => true, 0x92 => true, 0x93 => true, 0x94 => true,
0x95 => true, 0x96 => true, 0x97 => true, 0x98 => true, 0x99 => true,
0x9a => true, 0x9b => true, 0x9c => true, 0x9d => true, 0x9e => true,
0x9f => true
}.freeze
# Lookup table for HTML escape
#
# @since 0.4.0
# @api private
#
# @see Hanami::Utils::Escape.html
HTML_CHARS = {
'&' => '&',
'<' => '<',
'>' => '>',
'"' => '"',
"'" => ''',
'/' => '/'
}.freeze
# Lookup table for safe chars for HTML attributes.
#
# This is a Hash instead of a Set, to make lookup faster.
#
# @since 0.4.0
# @api private
#
# @see Lookup::Utils::Escape.html_attribute
# @see https://gist.github.com/jodosha/ac5dd54416de744b9600
HTML_ATTRIBUTE_SAFE_CHARS = {
',' => true, '.' => true, '-' => true, '_' => true
}.freeze
# Lookup table for HTML attribute escape
#
# @since 0.4.0
# @api private
#
# @see Hanami::Utils::Escape.html_attribute
HTML_ENTITIES = {
34 => 'quot', # quotation mark
38 => 'amp', # ampersand
60 => 'lt', # less-than sign
62 => 'gt', # greater-than sign
160 => 'nbsp', # no-break space
161 => 'iexcl', # inverted exclamation mark
162 => 'cent', # cent sign
163 => 'pound', # pound sign
164 => 'curren', # currency sign
165 => 'yen', # yen sign
166 => 'brvbar', # broken bar
167 => 'sect', # section sign
168 => 'uml', # diaeresis
169 => 'copy', # copyright sign
170 => 'ordf', # feminine ordinal indicator
171 => 'laquo', # left-pointing double angle quotation mark
172 => 'not', # not sign
173 => 'shy', # soft hyphen
174 => 'reg', # registered sign
175 => 'macr', # macron
176 => 'deg', # degree sign
177 => 'plusmn', # plus-minus sign
178 => 'sup2', # superscript two
179 => 'sup3', # superscript three
180 => 'acute', # acute accent
181 => 'micro', # micro sign
182 => 'para', # pilcrow sign
183 => 'middot', # middle dot
184 => 'cedil', # cedilla
185 => 'sup1', # superscript one
186 => 'ordm', # masculine ordinal indicator
187 => 'raquo', # right-pointing double angle quotation mark
188 => 'frac14', # vulgar fraction one quarter
189 => 'frac12', # vulgar fraction one half
190 => 'frac34', # vulgar fraction three quarters
191 => 'iquest', # inverted question mark
192 => 'Agrave', # Latin capital letter a with grave
193 => 'Aacute', # Latin capital letter a with acute
194 => 'Acirc', # Latin capital letter a with circumflex
195 => 'Atilde', # Latin capital letter a with tilde
196 => 'Auml', # Latin capital letter a with diaeresis
197 => 'Aring', # Latin capital letter a with ring above
198 => 'AElig', # Latin capital letter ae
199 => 'Ccedil', # Latin capital letter c with cedilla
200 => 'Egrave', # Latin capital letter e with grave
201 => 'Eacute', # Latin capital letter e with acute
202 => 'Ecirc', # Latin capital letter e with circumflex
203 => 'Euml', # Latin capital letter e with diaeresis
204 => 'Igrave', # Latin capital letter i with grave
205 => 'Iacute', # Latin capital letter i with acute
206 => 'Icirc', # Latin capital letter i with circumflex
207 => 'Iuml', # Latin capital letter i with diaeresis
208 => 'ETH', # Latin capital letter eth
209 => 'Ntilde', # Latin capital letter n with tilde
210 => 'Ograve', # Latin capital letter o with grave
211 => 'Oacute', # Latin capital letter o with acute
212 => 'Ocirc', # Latin capital letter o with circumflex
213 => 'Otilde', # Latin capital letter o with tilde
214 => 'Ouml', # Latin capital letter o with diaeresis
215 => 'times', # multiplication sign
216 => 'Oslash', # Latin capital letter o with stroke
217 => 'Ugrave', # Latin capital letter u with grave
218 => 'Uacute', # Latin capital letter u with acute
219 => 'Ucirc', # Latin capital letter u with circumflex
220 => 'Uuml', # Latin capital letter u with diaeresis
221 => 'Yacute', # Latin capital letter y with acute
222 => 'THORN', # Latin capital letter thorn
223 => 'szlig', # Latin small letter sharp sXCOMMAX German Eszett
224 => 'agrave', # Latin small letter a with grave
225 => 'aacute', # Latin small letter a with acute
226 => 'acirc', # Latin small letter a with circumflex
227 => 'atilde', # Latin small letter a with tilde
228 => 'auml', # Latin small letter a with diaeresis
229 => 'aring', # Latin small letter a with ring above
230 => 'aelig', # Latin lowercase ligature ae
231 => 'ccedil', # Latin small letter c with cedilla
232 => 'egrave', # Latin small letter e with grave
233 => 'eacute', # Latin small letter e with acute
234 => 'ecirc', # Latin small letter e with circumflex
235 => 'euml', # Latin small letter e with diaeresis
236 => 'igrave', # Latin small letter i with grave
237 => 'iacute', # Latin small letter i with acute
238 => 'icirc', # Latin small letter i with circumflex
239 => 'iuml', # Latin small letter i with diaeresis
240 => 'eth', # Latin small letter eth
241 => 'ntilde', # Latin small letter n with tilde
242 => 'ograve', # Latin small letter o with grave
243 => 'oacute', # Latin small letter o with acute
244 => 'ocirc', # Latin small letter o with circumflex
245 => 'otilde', # Latin small letter o with tilde
246 => 'ouml', # Latin small letter o with diaeresis
247 => 'divide', # division sign
248 => 'oslash', # Latin small letter o with stroke
249 => 'ugrave', # Latin small letter u with grave
250 => 'uacute', # Latin small letter u with acute
251 => 'ucirc', # Latin small letter u with circumflex
252 => 'uuml', # Latin small letter u with diaeresis
253 => 'yacute', # Latin small letter y with acute
254 => 'thorn', # Latin small letter thorn
255 => 'yuml', # Latin small letter y with diaeresis
338 => 'OElig', # Latin capital ligature oe
339 => 'oelig', # Latin small ligature oe
352 => 'Scaron', # Latin capital letter s with caron
353 => 'scaron', # Latin small letter s with caron
376 => 'Yuml', # Latin capital letter y with diaeresis
402 => 'fnof', # Latin small letter f with hook
710 => 'circ', # modifier letter circumflex accent
732 => 'tilde', # small tilde
913 => 'Alpha', # Greek capital letter alpha
914 => 'Beta', # Greek capital letter beta
915 => 'Gamma', # Greek capital letter gamma
916 => 'Delta', # Greek capital letter delta
917 => 'Epsilon', # Greek capital letter epsilon
918 => 'Zeta', # Greek capital letter zeta
919 => 'Eta', # Greek capital letter eta
920 => 'Theta', # Greek capital letter theta
921 => 'Iota', # Greek capital letter iota
922 => 'Kappa', # Greek capital letter kappa
923 => 'Lambda', # Greek capital letter lambda
924 => 'Mu', # Greek capital letter mu
925 => 'Nu', # Greek capital letter nu
926 => 'Xi', # Greek capital letter xi
927 => 'Omicron', # Greek capital letter omicron
928 => 'Pi', # Greek capital letter pi
929 => 'Rho', # Greek capital letter rho
931 => 'Sigma', # Greek capital letter sigma
932 => 'Tau', # Greek capital letter tau
933 => 'Upsilon', # Greek capital letter upsilon
934 => 'Phi', # Greek capital letter phi
935 => 'Chi', # Greek capital letter chi
936 => 'Psi', # Greek capital letter psi
937 => 'Omega', # Greek capital letter omega
945 => 'alpha', # Greek small letter alpha
946 => 'beta', # Greek small letter beta
947 => 'gamma', # Greek small letter gamma
948 => 'delta', # Greek small letter delta
949 => 'epsilon', # Greek small letter epsilon
950 => 'zeta', # Greek small letter zeta
951 => 'eta', # Greek small letter eta
952 => 'theta', # Greek small letter theta
953 => 'iota', # Greek small letter iota
954 => 'kappa', # Greek small letter kappa
955 => 'lambda', # Greek small letter lambda
956 => 'mu', # Greek small letter mu
957 => 'nu', # Greek small letter nu
958 => 'xi', # Greek small letter xi
959 => 'omicron', # Greek small letter omicron
960 => 'pi', # Greek small letter pi
961 => 'rho', # Greek small letter rho
962 => 'sigmaf', # Greek small letter final sigma
963 => 'sigma', # Greek small letter sigma
964 => 'tau', # Greek small letter tau
965 => 'upsilon', # Greek small letter upsilon
966 => 'phi', # Greek small letter phi
967 => 'chi', # Greek small letter chi
968 => 'psi', # Greek small letter psi
969 => 'omega', # Greek small letter omega
977 => 'thetasym', # Greek theta symbol
978 => 'upsih', # Greek upsilon with hook symbol
982 => 'piv', # Greek pi symbol
8194 => 'ensp', # en space
8195 => 'emsp', # em space
8201 => 'thinsp', # thin space
8204 => 'zwnj', # zero width non-joiner
8205 => 'zwj', # zero width joiner
8206 => 'lrm', # left-to-right mark
8207 => 'rlm', # right-to-left mark
8211 => 'ndash', # en dash
8212 => 'mdash', # em dash
8216 => 'lsquo', # left single quotation mark
8217 => 'rsquo', # right single quotation mark
8218 => 'sbquo', # single low-9 quotation mark
8220 => 'ldquo', # left double quotation mark
8221 => 'rdquo', # right double quotation mark
8222 => 'bdquo', # double low-9 quotation mark
8224 => 'dagger', # dagger
8225 => 'Dagger', # double dagger
8226 => 'bull', # bullet
8230 => 'hellip', # horizontal ellipsis
8240 => 'permil', # per mille sign
8242 => 'prime', # prime
8243 => 'Prime', # double prime
8249 => 'lsaquo', # single left-pointing angle quotation mark
8250 => 'rsaquo', # single right-pointing angle quotation mark
8254 => 'oline', # overline
8260 => 'frasl', # fraction slash
8364 => 'euro', # euro sign
8465 => 'image', # black-letter capital i
8472 => 'weierp', # script capital pXCOMMAX Weierstrass p
8476 => 'real', # black-letter capital r
8482 => 'trade', # trademark sign
8501 => 'alefsym', # alef symbol
8592 => 'larr', # leftwards arrow
8593 => 'uarr', # upwards arrow
8594 => 'rarr', # rightwards arrow
8595 => 'darr', # downwards arrow
8596 => 'harr', # left right arrow
8629 => 'crarr', # downwards arrow with corner leftwards
8656 => 'lArr', # leftwards double arrow
8657 => 'uArr', # upwards double arrow
8658 => 'rArr', # rightwards double arrow
8659 => 'dArr', # downwards double arrow
8660 => 'hArr', # left right double arrow
8704 => 'forall', # for all
8706 => 'part', # partial differential
8707 => 'exist', # there exists
8709 => 'empty', # empty set
8711 => 'nabla', # nabla
8712 => 'isin', # element of
8713 => 'notin', # not an element of
8715 => 'ni', # contains as member
8719 => 'prod', # n-ary product
8721 => 'sum', # n-ary summation
8722 => 'minus', # minus sign
8727 => 'lowast', # asterisk operator
8730 => 'radic', # square root
8733 => 'prop', # proportional to
8734 => 'infin', # infinity
8736 => 'ang', # angle
8743 => 'and', # logical and
8744 => 'or', # logical or
8745 => 'cap', # intersection
8746 => 'cup', # union
8747 => 'int', # integral
8756 => 'there4', # therefore
8764 => 'sim', # tilde operator
8773 => 'cong', # congruent to
8776 => 'asymp', # almost equal to
8800 => 'ne', # not equal to
8801 => 'equiv', # identical toXCOMMAX equivalent to
8804 => 'le', # less-than or equal to
8805 => 'ge', # greater-than or equal to
8834 => 'sub', # subset of
8835 => 'sup', # superset of
8836 => 'nsub', # not a subset of
8838 => 'sube', # subset of or equal to
8839 => 'supe', # superset of or equal to
8853 => 'oplus', # circled plus
8855 => 'otimes', # circled times
8869 => 'perp', # up tack
8901 => 'sdot', # dot operator
8968 => 'lceil', # left ceiling
8969 => 'rceil', # right ceiling
8970 => 'lfloor', # left floor
8971 => 'rfloor', # right floor
9001 => 'lang', # left-pointing angle bracket
9002 => 'rang', # right-pointing angle bracket
9674 => 'loz', # lozenge
9824 => 'spades', # black spade suit
9827 => 'clubs', # black club suit
9829 => 'hearts', # black heart suit
9830 => 'diams', # black diamond suit
}.freeze
# Allowed URL schemes
#
# @since 0.4.0
# @api private
#
# @see Hanami::Utils::Escape.url
DEFAULT_URL_SCHEMES = ['http', 'https', 'mailto'].freeze
# The output of an escape.
#
# It's marked with this special class for two reasons:
#
# * Don't double escape the same string (this is for `Hanami::Helpers` compatibility)
# * Leave open the possibility to developers to mark a string as safe with an higher API (eg. `#raw` in `Hanami::View` or `Hanami::Helpers`)
#
# @since 0.4.0
# @api private
class SafeString < ::String
# @return [SafeString] the duped string
#
# @since 0.4.0
# @api private
#
# @see http://www.ruby-doc.org/core/String.html#method-i-to_s
def to_s
dup
end
# Encode the string the given encoding
#
# @return [SafeString] an encoded SafeString
#
# @since 0.4.0
# @api private
#
# @see http://www.ruby-doc.org/core/String.html#method-i-encode
def encode(*args)
self.class.new super
end
end
# Escape HTML contents
#
# This MUST be used only for tag contents.
# Please use `html_attribute` for escaping HTML attributes.
#
# @param input [String] the input
#
# @return [String] the escaped string
#
# @since 0.4.0
#
# @see https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet OWASP XSS Cheat Sheet Rule #1
#
# @example Good practice
# <div><%= Hanami::Utils::Escape.html('<script>alert(1);</script>') %></div>
# <div><script>alert(1);</script></div>
#
# @example Bad practice
# # WRONG Use Escape.html_attribute
# <a title="<%= Hanami::Utils::Escape.html('...') %>">link</a>
def self.html(input)
input = encode(input)
return input if input.is_a?(SafeString)
result = SafeString.new
input.each_char do |chr|
result << HTML_CHARS.fetch(chr, chr)
end
result
end
# Escape HTML attributes
#
# This can be used both for HTML attributes and contents.
# Please note that this is more computational expensive.
# If you need to escape only HTML contents, please use `.html`.
#
# @param input [String] the input
#
# @return [String] the escaped string
#
# @since 0.4.0
#
# @see https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet OWASP XSS Cheat Sheet Rule #2
#
# @example Good practice
# <a title="<%= Hanami::Utils::Escape.html_attribute('...') %>">link</a>
#
# @example Good but expensive practice
# # Alternatively you can use Escape.html
# <p><%= Hanami::Utils::Escape.html_attribute('...') %></p>
def self.html_attribute(input)
input = encode(input)
return input if input.is_a?(SafeString)
result = SafeString.new
input.each_char do |chr|
result << encode_char(chr, HTML_ATTRIBUTE_SAFE_CHARS)
end
result
end
# Escape URL for HTML attributes (href, src, etc..).
#
# It extracts from the given input the first valid URL that matches the
# whitelisted schemes (default: http, https and mailto).
#
# It's possible to pass a second optional argument to specify different
# schemes.
#
# @param input [String] the input
# @param schemes [Array<String>] an array of whitelisted schemes
#
# @return [String] the escaped string
#
# @since 0.4.0
#
# @see Hanami::Utils::Escape::DEFAULT_URL_SCHEMES
# @see http://www.ruby-doc.org/stdlib/libdoc/uri/rdoc/URI.html#method-c-extract
#
# @example Basic usage
# <%
# good_input = "http://hanamirb.org"
# evil_input = "javascript:alert('xss')"
#
# escaped_good_input = Hanami::Utils::Escape.url(good_input) # => "http://hanamirb.org"
# escaped_evil_input = Hanami::Utils::Escape.url(evil_input) # => ""
# %>
#
# <a href="<%= escaped_good_input %>">personal website</a>
# <a href="<%= escaped_evil_input %>">personal website</a>
#
# @example Custom scheme
# <%
# schemes = ['ftp', 'ftps']
#
# accepted = "ftps://ftp.example.org"
# rejected = "http://www.example.org"
#
# escaped_accepted = Hanami::Utils::Escape.url(accepted) # => "ftps://ftp.example.org"
# escaped_rejected = Hanami::Utils::Escape.url(rejected) # => ""
# %>
#
# <a href="<%= escaped_accepted %>">FTP</a>
# <a href="<%= escaped_rejected %>">FTP</a>
def self.url(input, schemes = DEFAULT_URL_SCHEMES)
input = encode(input)
return input if input.is_a?(SafeString)
SafeString.new(
URI::Parser.new.extract(
URI.decode_www_form_component(input),
schemes
).first.to_s
)
end
private
# Encode the given string into UTF-8
#
# @param input [String] the input
#
# @return [String] an UTF-8 encoded string
#
# @since 0.4.0
# @api private
def self.encode(input)
return '' if input.nil?
input.to_s.encode(Encoding::UTF_8)
rescue Encoding::UndefinedConversionError
input.dup.force_encoding(Encoding::UTF_8)
end
# Encode the given UTF-8 char.
#
# @param char [String] an UTF-8 char
# @param safe_chars [Hash] a table of safe chars
#
# @return [String] an HTML encoded string
#
# @since 0.4.0
# @api private
def self.encode_char(char, safe_chars = {})
return char if safe_chars[char]
code = char.ord
hex = hex_for_non_alphanumeric_code(code)
return char if hex.nil?
if NON_PRINTABLE_CHARS[code]
hex = REPLACEMENT_HEX
end
if entity = HTML_ENTITIES[code]
"&#{ entity };"
else
"&#x#{ hex };"
end
end
# Transforms the given char code
#
# @since 0.4.0
# @api private
def self.hex_for_non_alphanumeric_code(input)
if input < LOW_HEX_CODE_LIMIT
HEX_CODES[input]
else
input.to_s(HEX_BASE)
end
end
end
end
end
|
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#define AWS_UTIL_EXPORT __declspec(dllexport)
///#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <algorithm>
#include <ctime>
#include <iomanip>
#include <sstream>
#include "hmac_sha2.h"
#include "BinaryUtils.h"
#include "URIUtils.h"
// TODO: reference additional headers your program requires here
|
package org.distributedproficiency.dojo.dto;
import org.distributedproficiency.dojo.domain.KataContent;
public class KataSaveRequest {
private KataContent newContent;
public KataSaveRequest() {
super();
}
public KataSaveRequest(KataContent c) {
super();
this.newContent = c;
}
public KataContent getNewContent() {
return newContent;
}
public void setNewContent(KataContent newContent) {
this.newContent = newContent;
}
}
|
/**
* drcProcess
* Created by dcorns on 1/2/15.
*/
'use strict';
var RunApp = require('./runApp');
var Server = require('./server');
var parseInput = require('./parseInput');
var CommandList = require('./commandList');
var runApp = new RunApp();
var cmds = new CommandList();
cmds.add(['ls', 'pwd', 'service', 'ps']);
var firstServer = new Server('firstServer');
firstServer.start(3000, function(err, cnn){
cnn.on('data', function(data){
parseInput(data, function(err, obj){
if(err) cnn.write(err);
else {
if(obj.cmd.substr(0, 6) === 'login:'){
cnn.loginID = obj.cmd.substr(6);
cnn.write('Welcome ' + cnn.loginID + '\r\n');
cnn.write('Valid Commands: ' + cmds.listCommands() + '\r\n');
cnn.write('Use # to add parameters: example: ls#/\r\n');
cnn.write('Use - to add options: example: ls#/ -al or ls#-al\r\n');
console.log(cnn.loginID + ' connected');
}
else {
if(cmds.validate(obj.cmd) > -1){
runApp.run(obj.params, cnn, obj.cmd);
}
else{
cnn.write('Valid commands: ' + cmds.listCommands());
}
}
}
});
});
});
|
/*****************************************************************************
The following code is derived, directly or indirectly, from the SystemC
source code Copyright (c) 1996-2006 by all Contributors.
All Rights reserved.
The contents of this file are subject to the restrictions and limitations
set forth in the SystemC Open Source License Version 2.4 (the "License");
You may not use this file except in compliance with such restrictions and
limitations. You may obtain instructions on how to receive a copy of the
License at http://www.systemc.org/. Software distributed by Contributors
under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
ANY KIND, either express or implied. See the License for the specific
language governing rights and limitations under the License.
*****************************************************************************/
/*****************************************************************************
simple_bus_request.h : The bus interface request form.
Original Author: Ric Hilderink, Synopsys, Inc., 2001-10-11
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
#ifndef __simple_bus_request_h
#define __simple_bus_request_h
enum simple_bus_lock_status { SIMPLE_BUS_LOCK_NO = 0
, SIMPLE_BUS_LOCK_SET
, SIMPLE_BUS_LOCK_GRANTED
};
struct simple_bus_request
{
// parameters
unsigned int priority;
// request parameters
bool do_write;
unsigned int address;
unsigned int end_address;
int *data;
simple_bus_lock_status lock;
// request status
sc_event transfer_done;
simple_bus_status status;
// default constructor
simple_bus_request();
};
inline simple_bus_request::simple_bus_request()
: priority(0)
, do_write(false)
, address(0)
, end_address(0)
, data((int *)0)
, lock(SIMPLE_BUS_LOCK_NO)
, status(SIMPLE_BUS_OK)
{}
#endif
|
"use strict";
const tester = require("./framework");
const repeatAsyncUntil = require("../source/regularly");
module.exports = tester.run([
tester.make("repeatAsyncUntil() should repeat calls to λ while predicate returns false", async () => {
let executionsCount = 0;
const λ = async () => ++executionsCount;
const predicate = async () => executionsCount === 2;
await repeatAsyncUntil(λ, predicate);
return executionsCount === 2;
})
]);
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebGL Tutorial Series</title>
<script src="webgl4j_tutorial_series/webgl4j_tutorial_series.nocache.js" type="text/javascript"></script>
</head>
<body>
</body>
</html> |
import {ATTACHMENTS} from "../constants";
export default (...args) => {
// Use one or the other
const attachments = args.length ? args : ATTACHMENTS;
return {
props: {
attach: {
type: String,
validator: value => value === "" || attachments.includes(value)
}
},
computed: {
getAttach() {
if(typeof this.attach === "string") {
return this.attach ? `${this.attach} attached` : "attached";
}
}
}
};
}; |
#!/bin/bash
cd /Users/chester_huang/Documents/HTC/htc-prototype/wip/estore-event
grunt prod
|
require 'rails_helper'
describe "Describing Model", model: true do
context "Data Validation" do
end
context "Associations" do
before :each do
@describing = build(:describing)
end
it "has a description" do
expect(@describing).to respond_to :description
end
it "has a describable" do
expect(@describing).to respond_to :describable
end
end
end |
<!-- Homework Assingment: Basic Portfolio Page Contact Page-->
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>Contact Melissa Wolowicz</title>
<meta charset="utf-8">
<!-- Linking the normalize.css FIRST, and then my own CSS -->
<link rel="stylesheet" type="text/css" href="assets/css/normalize.css">
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
<!-- Linking Google Font Lobster for MW's logo -->
<link href="https://fonts.googleapis.com/css?family=Lobster|Raleway:400,500,700" rel="stylesheet">
</head>
<body>
<!-- Site Header -->
<header id="masthead">
<div class="container">
<!-- Logo -->
<a href="index.html" id="logo">Melissa Wolowicz</a>
<!-- Navigation Links -->
<nav>
<a href="index.html">About</a>
<a href="portfolio.html">Portfolio</a>
<a href="contact.html">Contact</a>
</nav>
</div>
</header>
<!-- Contact Page Content -->
<div id="main-container" class="container">
<!-- Contact Form -->
<section class="main-section">
<h1>Contact</h1>
<form id="contact-form">
<ul>
<li>
<label for="name">Name</label>
<input type="text" name="name" id="name" placeholder="Jane Doe" required="required">
</li>
<li>
<label for="email">Email</label>
<input type="text" name="email" id="email" placeholder="example@gmail.com" required="required">
</li>
<li>
<label for="message">Message</label>
<textarea id="message" name="message" placeholder="Tell me what you think of my portfolio page!" required="required"></textarea>
</li>
</ul>
<input type="submit" name="submit">
</form>
</section>
<!-- Connect With Me Section -->
<section class="sidebar">
<div id="connect">
<h2>Connect With Me</h2>
<a href="https://github.com/m-wolowicz" target="_blank"><img src="assets/images/github.svg" class="social" id="git" alt="GitHub"></a>
<a href="https://www.linkedin.com/in/mwolowicz/" target="_blank"><img src="assets/images/linkedin.svg" class="social" id="linked" alt="LinkedIn"></a>
<a href="https://stackoverflow.com/users/8768790/mwolowicz" target="_blank"><img src="assets/images/stackoverflow.svg" class="social" id="stack" alt="Stack Overflow"></a>
</div>
</section>
</div>
<!-- Footer -->
<footer>
<div>
© Copyright 2017 Melissa Wolowicz
</div>
</footer>
</body>
</html> |
#import "MOBProjection.h"
@interface MOBProjectionEPSG4966 : MOBProjection
@end
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using gView.Framework.Data;
using gView.Framework.Offline;
namespace gView.Framework.Offline.UI
{
public partial class FormAddReplicationID : Form,IFeatureClassDialog
{
private IFeatureClass _fc;
private IFeatureDatabaseReplication _fdb;
private BackgroundWorker _worker;
public FormAddReplicationID()
{
InitializeComponent();
}
private void btnCreate_Click(object sender, EventArgs e)
{
btnCreate.Enabled = btnCancel.Enabled = false;
progressDisk1.Visible = lblCounter.Visible = true;
progressDisk1.Start(90);
_worker = new BackgroundWorker();
_worker.DoWork += new DoWorkEventHandler(_worker_DoWork);
_worker.RunWorkerAsync(txtFieldname.Text);
Cursor = Cursors.WaitCursor;
}
void _worker_DoWork(object sender, DoWorkEventArgs e)
{
string errMsg;
Replication repl = new Replication();
repl.ReplicationGuidsAppended += new Replication.ReplicationGuidsAppendedEventHandler(Replication_ReplicationGuidsAppended);
if (!repl.AppendReplicationIDField(_fdb, _fc, e.Argument.ToString(), out errMsg))
{
MessageBox.Show("Error: " + errMsg);
}
_worker = null;
CloseWindow();
}
private delegate void CloseWindowCallback();
private void CloseWindow()
{
if (this.InvokeRequired)
{
CloseWindowCallback callback = new CloseWindowCallback(CloseWindow);
this.Invoke(callback);
}
else
{
this.Close();
}
}
void Replication_ReplicationGuidsAppended(Replication sender, int count_appended)
{
if (this.InvokeRequired)
{
Replication.ReplicationGuidsAppendedEventHandler callback = new Replication.ReplicationGuidsAppendedEventHandler(Replication_ReplicationGuidsAppended);
this.Invoke(callback, new object[] { sender, count_appended });
}
else
{
lblCounter.Text = count_appended.ToString() + " Features updated...";
}
}
private void FormAddReplicationID_Load(object sender, EventArgs e)
{
if (_fc == null || _fdb == null) this.Close();
}
private void FormAddReplicationID_FormClosing(object sender, FormClosingEventArgs e)
{
if (_worker != null)
e.Cancel = true;
}
#region IFeatureClassDialog Member
public void ShowDialog(IFeatureClass fc)
{
_fc = fc;
if (_fc != null && fc.Dataset != null)
{
_fdb = _fc.Dataset.Database as IFeatureDatabaseReplication;
this.ShowDialog();
}
}
#endregion
}
} |
/**\file
*
* \copyright
* Copyright (c) 2008-2014, Kyuba Project Members
* \copyright
* 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:
* \copyright
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* \copyright
* 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.
*
* \see Project Documentation: http://ef.gy/documentation/curie
* \see Project Source Code: http://git.becquerel.org/kyuba/curie.git
*/
#include <curie/main.h>
#include <curie/sexpr.h>
#include <curie/time.h>
int cmain()
{
int_date date = dt_get_kin ();
return date < UNIX_EPOCH;
}
|
# Overview
Application start-up helper to initialize things like an IoC container, register mapping information or run a task.
[](https://ci.appveyor.com/project/LoreSoft/kickstart)
| Package | Version |
| :--- | :--- |
| [KickStart](https://www.nuget.org/packages/KickStart/) | [](https://www.nuget.org/packages/KickStart/) |
| [KickStart.Autofac](https://www.nuget.org/packages/KickStart.Autofac/) | [](https://www.nuget.org/packages/KickStart.Autofac/) |
| [KickStart.AutoMapper](https://www.nuget.org/packages/KickStart.AutoMapper/) | [](https://www.nuget.org/packages/KickStart.AutoMapper/) |
| [KickStart.DependencyInjection](https://www.nuget.org/packages/KickStart.DependencyInjection/) | [](https://www.nuget.org/packages/KickStart.DependencyInjection/) |
| [KickStart.MongoDB](https://www.nuget.org/packages/KickStart.MongoDB/) | [](https://www.nuget.org/packages/KickStart.MongoDB/) |
| [KickStart.Ninject](https://www.nuget.org/packages/KickStart.Ninject/) | [](https://www.nuget.org/packages/KickStart.Ninject/) |
| [KickStart.SimpleInjector](https://www.nuget.org/packages/KickStart.SimpleInjector/) | [](https://www.nuget.org/packages/KickStart.SimpleInjector/) |
| [KickStart.Unity](https://www.nuget.org/packages/KickStart.Unity/) | [](https://www.nuget.org/packages/KickStart.Unity/) |
## Download
The KickStart library is available on nuget.org via package name `KickStart`.
To install KickStart, run the following command in the Package Manager Console
PM> Install-Package KickStart
More information about NuGet package available at
<https://nuget.org/packages/KickStart>
## Development Builds
Development builds are available on the myget.org feed. A development build is promoted to the main NuGet feed when it's determined to be stable.
In your Package Manager settings add the following package source for development builds:
<http://www.myget.org/F/loresoft/>
## Features
- Run tasks on application start-up
- Extension model to add library specific start up tasks
- Common IoC container adaptor based on `IServiceProvider`
- Singleton instance of an application level IoC container `Kick.ServiceProvider`
|
<?php
$this->load->view("header");
$this->load->view($view_name);
$this->load->view("footer");
?> |
'use strict';
module.exports = Source;
const inherits = require('util').inherits;
const Stream = require('../stream');
const Chunk = require('../chunk');
const Compose = require('../through/compose');
const Break = require('../through/break');
const Filter = require('../through/filter');
const Map = require('../through/map');
const Take = require('../through/take');
const Each = require('../feed/each');
const Value = require('../feed/value');
module.exports = Source;
inherits(Source, Stream);
function Source(){
Stream.call(this);
this.async = false;
}
Source.prototype.iterator = function iterator() {
return new this.constructor.Iterator(this);
};
Source.prototype.pipe = function pipe(feed) {
return feed.feed([this]);
};
Source.prototype.break = function breake(fn, async){
return this.pipe(new Break(fn, async));
};
Source.prototype.filter = function filter(fn, async){
return this.pipe(new Filter(fn, async));
};
Source.prototype.map = function map(fn, async){
return this.pipe(new Map(fn, async));
};
Source.prototype.take = function take(max){
return this.pipe(new Take(max));
};
Source.prototype.each = function each(fn){
return this.pipe(new Each(fn));
};
Source.prototype.value = function value(async){
return this.pipe(new Value(async));
};
|
# Thyme
## An Evergreen Labs Concoction
|
{
"posts": [
{
"url": "/chat/gossiping/2018/01/02/GossipingM.1514855667.A.579.html",
"title": "「大家覺得五月天能紅過其他台灣樂團的秘訣」?鄉民這樣說。",
"image": "http://img5.cna.com.tw/www/WebPhotos/800/20170329/46790509.jpg",
"push": "77",
"boo": "24",
"date": "2018-01-02 09:14:25 +0800",
"boardName": "八卦",
"boardLink": "/category/gossiping"
} ,
{
"url": "/chat/gay/2017/12/31/gayM.1514708001.A.CB2.html",
"title": "終於結束的起點",
"image": "https://i.imgur.com/fYErH0W.jpg",
"push": "22",
"boo": "0",
"date": "2017-12-31 16:13:18 +0800",
"boardName": "甲 (gay)",
"boardLink": "/category/gay"
} ,
{
"url": "/chat/wanted/2017/12/31/WantedM.1514692270.A.158.html",
"title": "ppp最愛發廢文了",
"image": "https://i.imgur.com/n4guqc3.jpg",
"push": "21",
"boo": "0",
"date": "2017-12-31 11:51:08 +0800",
"boardName": "汪踢 (Wanted)",
"boardLink": "/category/wanted"
}
]
}
|
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Models;
namespace Services
{
public interface IArticlesService
{
Task<Section[]> GetSections();
Task<Section> GetSection(string sectionRef);
Task<Article[]> GetArticles(string sectionRef);
Task<Article[]> GetAllArticlesInTree(string sectionRef);
Task<Article> GetArticle(string sectionRef, string articleRef);
}
public class ArticlesService : IArticlesService
{
private ArticleGroup[] articleData = null;
private Section[] sectionData = null;
private readonly HttpClient httpClient;
private readonly ILogger logger;
public ArticlesService(HttpClient httpClient, ILogger<ArticlesService> logger)
{
this.httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<Section[]> GetSections()
{
await EnsureDataLoaded();
return sectionData;
}
public async Task<Section> GetSection(string sectionRef)
{
await EnsureDataLoaded();
var section = Section.Flatten(sectionData).FirstOrDefault(s => s.Reference == sectionRef);
return section;
}
public async Task<Article[]> GetArticles(string sectionRef)
{
await EnsureDataLoaded();
var section = await GetSection(sectionRef);
var sectionArticles = articleData.FirstOrDefault(s => s.Reference == section.Reference).Articles;
return sectionArticles;
}
public async Task<Article[]> GetAllArticlesInTree(string sectionRef)
{
await EnsureDataLoaded();
var section = await GetSection(sectionRef);
var sectionArticles = articleData.FirstOrDefault(s => s.Reference == section.Reference).Articles;
var allArticles = Article.Flatten(sectionArticles);
return allArticles.ToArray();
}
public async Task<Article> GetArticle(string sectionRef, string articleRef)
{
await EnsureDataLoaded();
var allArticles = await GetAllArticlesInTree(sectionRef);
var article = allArticles.FirstOrDefault(a => a.Reference == articleRef);
return article;
}
private async Task EnsureDataLoaded()
{
// load the section data from `data/sections.json`
if (sectionData == null)
{
var loadedData = await httpClient.GetFromJsonAsync<Section[]>("data/sections.json");
lock(this)
{
sectionData = loadedData;
foreach (var section in sectionData)
{
PopulateParentage(section.Children, null);
}
}
}
if (articleData == null)
{
var loadedData = await httpClient.GetFromJsonAsync<ArticleGroup[]>("data/articles.json");
lock(this)
{
articleData = loadedData;
foreach(var section in articleData)
{
PopulateParentage(section.Articles, null);
}
}
}
}
private void PopulateParentage<T>(IHeirarchicalItem<T>[] items, T parent)
where T : IHeirarchicalItem<T>
{
foreach (var item in items.OfType<T>())
{
if (item.Parent == null)
{
item.Parent = parent;
}
var children = item.Children.OfType<IHeirarchicalItem<T>>().ToArray();
if (children.Any())
{
PopulateParentage<T>(children, item);
}
}
}
}
}
|
<?php
class itemModel extends CI_Model
{
public function insertItem()
{
$itemName = $this->input->post('itemName');
$this->db->where('item_name',$itemName);
$result=$this->db->get('shop_item');
if($result->num_rows()>0) {
$this->session->set_flashdata('Error','Item you entered is already exists.!');
redirect('itemController/addItem');
}
else {
$data = array(
'item_name' => $this->input->post('itemName'),
'item_category' => $this->input->post('itemCategory'),
'quantity' => ($this->input->post('quantity')),
'measuring_unit' => $this->input->post('measuring_unit'),
'unit_price' => $this->input->post('price'),
'item_description' => $this->input->post('description'),
'shop_shop_id'=>$_SESSION['shop_id'],
);
$this->db->insert('shop_item', $data);
}
}
public function viewItems() {
$this->db->select('*');
$this->db->from('shop_item');
$this->db->order_by('shop_item_id');
$this->db->where('shop_shop_id',$_SESSION['shop_id']);
$query = $this->db->get();
return $query->result();
}
// return the row that want to be edited
public function edit($id) {
$this->db->where('shop_item_id',$id);
$query = $this->db->get_where('shop_item', array('shop_item_id' => $id));
return $query->row();
}
//update the selected with the given data
public function update($id) {
$data = array(
'item_category' => $this->input->post('itemCategory'),
'item_name' => $this->input->post('itemName'),
'quantity' => ($this->input->post('quantity')),
'measuring_unit' => ($this->input->post('measuring_unit')),
'unit_price' => $this->input->post('price'),
'item_description' => $this->input->post('description'),
'shop_shop_id'=>$_SESSION['shop_id'],
);
$this->db->where('shop_item_id',$id);
$this->db->update('shop_item',$data);
return $id;
}
public function delete($id) {
$this->db->where('shop_item_id',$id);
$this->db->delete('shop_item');
}
function Search($searchkey){
$this->db->select('*');
$this->db->where('shop_shop_id',$_SESSION['shop_id']);
$this->db->from('shop_item');
$this->db->like('item_name', $searchkey);
$this->db->or_like('shop_item_id', $searchkey);
$this->db->or_like('item_category', $searchkey);
$this->db->or_like('quantity', $searchkey);
$this->db->or_like('measuring_unit', $searchkey);
$this->db->or_like('unit_price', $searchkey);
$this->db->or_like('item_description', $searchkey);
$query = $this->db->get();
return $query->result();
}
public function getCategory()
{
$this->db->select('shop_category');
$this->db->from('shop');
$this->db->where('shop_id',$_SESSION['shop_id']);
$query = $this->db->get();
$result=$query->result_array();
return $result;
}
}
?> |
public class ASTStringLiteral extends SimpleNode
{
String val;
public ASTStringLiteral(int id)
{
super(id);
}
public ASTStringLiteral(ParfA p, int id)
{
super(p, id);
}
public void interpret()
{
ParfANode.stack[++ParfANode.p] = new String(val);
}
} |
require 'one_gadget/gadget'
# https://gitlab.com/david942j/libcdb/blob/master/libc/libc0.1-2.21-9/lib/i386-kfreebsd-gnu/libc-2.21.so
#
# Intel 80386
#
# GNU C Library (Debian GLIBC 2.21-9) stable release version 2.21, by Roland McGrath et al.
# Copyright (C) 2015 Free Software Foundation, Inc.
# This is free software; see the source for copying conditions.
# There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
# Compiled by GNU CC version 4.9.3.
# Available extensions:
# crypt add-on version 2.1 by Michael Glad and others
# Native POSIX Threads Library by Ulrich Drepper et al
# GNU Libidn by Simon Josefsson
# BIND-8.2.3-T5B
# libc ABIs: UNIQUE
# For bug reporting instructions, please see:
# <http://www.debian.org/Bugs/>.
build_id = File.basename(__FILE__, '.rb').split('-').last
OneGadget::Gadget.add(build_id, 233829,
constraints: ["ebx is the GOT address of libc", "[esp+0x2c] == NULL"],
effect: "execve(\"/bin/sh\", esp+0x2c, environ)")
OneGadget::Gadget.add(build_id, 233831,
constraints: ["ebx is the GOT address of libc", "[esp+0x30] == NULL"],
effect: "execve(\"/bin/sh\", esp+0x30, environ)")
OneGadget::Gadget.add(build_id, 233835,
constraints: ["ebx is the GOT address of libc", "[esp+0x34] == NULL"],
effect: "execve(\"/bin/sh\", esp+0x34, environ)")
OneGadget::Gadget.add(build_id, 233842,
constraints: ["ebx is the GOT address of libc", "[esp+0x38] == NULL"],
effect: "execve(\"/bin/sh\", esp+0x38, environ)")
OneGadget::Gadget.add(build_id, 233877,
constraints: ["ebx is the GOT address of libc", "[eax] == NULL || eax == NULL", "[[esp]] == NULL || [esp] == NULL"],
effect: "execve(\"/bin/sh\", eax, [esp])")
OneGadget::Gadget.add(build_id, 233878,
constraints: ["ebx is the GOT address of libc", "[[esp]] == NULL || [esp] == NULL", "[[esp+0x4]] == NULL || [esp+0x4] == NULL"],
effect: "execve(\"/bin/sh\", [esp], [esp+0x4])")
OneGadget::Gadget.add(build_id, 395455,
constraints: ["ebx is the GOT address of libc", "eax == NULL"],
effect: "execl(\"/bin/sh\", eax)")
OneGadget::Gadget.add(build_id, 395456,
constraints: ["ebx is the GOT address of libc", "[esp] == NULL"],
effect: "execl(\"/bin/sh\", [esp])")
|
using System.Windows.Controls;
namespace mze9412.ScriptCompiler.Views
{
/// <summary>
/// Interaction logic for SettingsView.xaml
/// </summary>
public partial class SettingsView : UserControl
{
public SettingsView()
{
InitializeComponent();
}
}
}
|
import pytest
from swimlane.exceptions import ValidationError
def test_getattr_fallback(mock_record):
"""Verify cursor __getattr__ falls back to AttributeError for unknown cursor + list methods"""
with pytest.raises(AttributeError):
getattr(mock_record['Text List'], 'unknown_method')
def test_set_validation(mock_record):
"""Test directly setting a ListField value for validation"""
mock_record['Text List'] = ['text']
with pytest.raises(ValidationError):
mock_record['Text List'] = [123]
with pytest.raises(ValidationError):
mock_record['Text List'] = 123
with pytest.raises(ValidationError):
mock_record['Text List'] = 'text'
def test_modification_validation(mock_record):
"""Test calling list methods on cursor respects validation"""
mock_record['Text List'].append('text')
with pytest.raises(ValidationError):
mock_record['Text List'].append(123)
def test_numeric_range(mock_record):
"""Test item numeric range restrictions"""
key = 'Numeric List Range Limit'
mock_record[key] = [5]
with pytest.raises(ValidationError):
mock_record[key] = [3]
with pytest.raises(ValidationError):
mock_record[key] = [12]
def test_list_length_validation(mock_record):
"""List length validation check"""
key = 'Numeric List Range Limit'
mock_record[key] = [5, 6, 7]
with pytest.raises(ValidationError):
mock_record[key].append(8)
with pytest.raises(ValidationError):
mock_record[key] = []
def test_item_type_validation(mock_record):
"""Validate correct item type for text/numeric values"""
key = 'Numeric List Range Limit'
with pytest.raises(ValidationError):
mock_record[key] = ['text']
def test_min_max_word_validation(mock_record):
"""Validate against min/max word restrictions"""
key = 'Text List Word Limit'
with pytest.raises(ValidationError):
mock_record[key] = ['word ' * 10]
with pytest.raises(ValidationError):
mock_record[key] = ['word']
def test_min_max_char_validation(mock_record):
"""Min/max characters restriction validation"""
key = 'Text List Char Limit'
with pytest.raises(ValidationError):
mock_record[key] = ['defg', 'hijkl', 'mno pqr']
with pytest.raises(ValidationError):
mock_record[key] = ['']
def test_list_field_bulk_modify_value(mock_record):
"""Pass-through bulk_modify value"""
value = ['Test', 'Value']
assert mock_record.get_field('Text List').get_bulk_modify(value) == value
|
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Checkout
* @copyright Copyright (c) 2006-2019 Magento, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Shopping cart model
*
* @category Mage
* @package Mage_Checkout
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_Checkout_Model_Cart_Api_V2 extends Mage_Checkout_Model_Cart_Api
{
}
|
Rails.application.routes.draw do
# Mount the physiqual engine
mount Physiqual::Engine => '/physiqual'
get 'welcome/index'
get 'welcome/example'
get 'welcome/example_data'
root 'welcome#index'
# Omniauth
get '/auth/:provider/callback', :to => 'sessions#create'
get '/auth/failure', :to => 'sessions#failure'
delete '/logout', :to => 'sessions#destroy'
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
|
// Idea and initial code from https://github.com/aomra015/ember-cli-chart
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'canvas',
attributeBindings: ['width', 'height'],
onlyValues: false,
chartData: {},
didInsertElement: function(){
var context = this.get('element').getContext('2d');
var type = Ember.String.classify(this.get('type'));
var options = {
responsive: true,
showTooltips: true,
pointDot: true,
pointDotRadius: 3,
pointHitDetectionRadius: 8,
bezierCurve: false,
barValueSpacing: 1,
datasetStrokeWidth: 3
};
// animation is very sexy, but it hogs browser. Waiting for chart.js 2.0
// https://github.com/nnnick/Chart.js/issues/653
options.animation = false;
if (this.get("onlyValues")) {
options.showScale = false;
}
var data = {labels: [], datasets: []};
this.get("chartData.labels").forEach((l) => {
data.labels.push(l);
});
this.get("chartData.datasets").forEach((ds) => {
var dataSet = this._chartColors(ds.label);
dataSet.data = ds.data.map((v) => { return v; });
data.datasets.push(dataSet);
});
var chart = new Chart(context)[type](data, options);
this.set('chart', chart);
},
willDestroyElement: function(){
this.get('chart').destroy();
},
updateChart: function() {
//// redraw
// this.willDestroyElement();
// this.didInsertElement();
var chart = this.get("chart");
while (chart.scale.xLabels.length && chart.scale.xLabels[0] !== this.get("chartData.labels")[0]) {
chart.removeData();
}
this.get("chartData.labels").forEach((label, i) => {
if (i < chart.scale.xLabels.length) {
this.get("chartData.datasets").forEach((ds, j) => {
if (this.get("type") === "Line") {
chart.datasets[j].points[i].value = ds.data[i];
} else {
chart.datasets[j].bars[i].value = ds.data[i];
}
});
} else {
var values = [];
this.get("chartData.datasets").forEach((ds) => {
values.push(ds.data[i]);
});
chart.addData(values, label);
}
});
chart.update();
}.observes("chartData", "chartData.[]"),
_chartColors: function(label) {
if (label === "count") {
return {
fillColor: "rgba(151,187,205,1)",
strokeColor: "rgba(151,187,205,1)"
};
} else {
var base = {
max: "203,46,255",
up: "46,255,203",
avg: "46,203,255",
min: "46,98,255",
sum: "98,56,255",
}[label] || "151,187,205";
return {
fillColor: "rgba(" + base + ",0.03)",
strokeColor: "rgba(" + base + ",0.5)",
pointColor: "rgba(" + base + ",0.5)",
// pointStrokeColor: "red", //"rgba(" + base + ")",
// pointHighlightFill: "green", //"rgba(" + base + ")",
// pointHighlightStroke: "blue",// "rgba(" + base + ")",
// pointStrokeColor: "#fff",
// pointHighlightFill: "#fff",
// pointHighlightStroke: "rgba(220,220,220,1)",
};
}
}
});
|
/**
* This module defines the `tslint-json` project task.
*
* @module project-tasks/tslint-json
* @internal
*/
/** (Placeholder comment, see TypeStrong/typedoc#603) */
import { Furi, join as furiJoin } from "furi";
import Undertaker from "undertaker";
import { DEFAULT_UNTYPED_TSLINT_CONFIG } from "../options/tslint";
import { ResolvedProject } from "../project";
import { writeJsonFile } from "../utils/project";
export function generateTask(project: ResolvedProject): Undertaker.TaskFunction {
let relativePath: string;
if (project.tslint !== undefined && project.tslint.tslintJson !== undefined) {
relativePath = project.tslint.tslintJson;
} else {
relativePath = "tslint.json";
}
const absolutePath: Furi = furiJoin(project.absRoot, [relativePath]);
return async function () {
return writeJsonFile(absolutePath, DEFAULT_UNTYPED_TSLINT_CONFIG);
};
}
export function getTaskName(): string {
return "tslint.json";
}
export function registerTask(taker: Undertaker, project: ResolvedProject): Undertaker.TaskFunction {
const taskName: string = getTaskName();
const task: Undertaker.TaskFunction = generateTask(project);
taker.task(taskName, task);
return task;
}
|
require 'spec'
require 'rr'
require File.join(File.dirname(__FILE__), '/../lib/chawan')
require File.join(File.dirname(__FILE__), '/provide_helper')
def data(key)
path = File.join(File.dirname(__FILE__) + "/fixtures/#{key}")
File.read(path){}
end
|
#include "ParticleData.h"
#include <algorithm>
#include <cassert>
namespace {
template<typename T>
void ResizeVector(T& obj, size_t size) {
obj.clear();
obj.resize(size);
obj.shrink_to_fit();
}
template<typename T>
size_t STLMemory(T& obj) {
using Type = typename T::value_type;
return obj.capacity() * sizeof(Type);
}
}
ParticleData::ParticleData()
: size(0)
, count(0) {
}
void ParticleData::Generate(size_t size) {
this->size = size;
count = 0;
ResizeVector(position, size);
ResizeVector(velocity, size);
ResizeVector(acceleration, size);
ResizeVector(color, size);
ResizeVector(alive, size);
}
size_t ParticleData::Wake(size_t count) {
size_t start = 0;
size_t end = std::min(std::max(this->count + count, start), size);
for (size_t i = start; i < end; ++i) {
alive[i] = true;
}
this->count = end;
return end;
}
void ParticleData::Kill(size_t id) {
assert(id < size && id >= 0);
if (alive[id]) {
count--;
alive[id] = false;
Swap(id, count);
}
}
void ParticleData::Swap(size_t left, size_t right) {
std::swap(position[left], position[right]);
std::swap(velocity[left], velocity[right]);
std::swap(acceleration[left], acceleration[right]);
std::swap(color[left], color[right]);
std::swap(alive[left], alive[right]);
}
size_t ParticleData::GetMemory(const ParticleData& system) {
size_t size = sizeof(system);
size += STLMemory(system.position);
size += STLMemory(system.velocity);
size += STLMemory(system.acceleration);
size += STLMemory(system.color);
size += STLMemory(system.alive);
return size;
}
|
package commandParsing.drawableObectGenerationInterfaces;
import gui.factories.ShapePaletteEntryFactory;
import java.util.HashMap;
import java.util.Map;
import workspaceState.Shape;
import drawableobject.DrawableObject;
/**
* This class generates the actual ShapePaletteUpdate drawableObjects to give to the GUI.
*
* @author Stanley Yuan, Steve Kuznetsov
*
*/
public interface ShapePaletteUpdateGenerator {
default public DrawableObject generateDrawableObjectRepresentingShapePaletteUpdate (int index,
Shape shape) {
String parent = ShapePaletteEntryFactory.PARENT;
String type = ShapePaletteEntryFactory.TYPE;
Map<String, String> parameters = new HashMap<String, String>();
parameters.put(ShapePaletteEntryFactory.INDEX, Integer.toString(index));
parameters.put(ShapePaletteEntryFactory.IMAGE_PATH, shape.getPath());
return new DrawableObject(parent, type, parameters);
}
}
|
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* 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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, CodeMirror, window */
/**
* Editor is a 1-to-1 wrapper for a CodeMirror editor instance. It layers on Brackets-specific
* functionality and provides APIs that cleanly pass through the bits of CodeMirror that the rest
* of our codebase may want to interact with. An Editor is always backed by a Document, and stays
* in sync with its content; because Editor keeps the Document alive, it's important to always
* destroy() an Editor that's going away so it can release its Document ref.
*
* For now, there's a distinction between the "master" Editor for a Document - which secretly acts
* as the Document's internal model of the text state - and the multitude of "slave" secondary Editors
* which, via Document, sync their changes to and from that master.
*
* For now, direct access to the underlying CodeMirror object is still possible via _codeMirror --
* but this is considered deprecated and may go away.
*
* The Editor object dispatches the following events:
* - keyEvent -- When any key event happens in the editor (whether it changes the text or not).
* Event handlers are passed ({Editor}, {KeyboardEvent}). The 2nd arg is the raw DOM event.
* Note: most listeners will only want to respond when event.type === "keypress".
* - cursorActivity -- When the user moves the cursor or changes the selection, or an edit occurs.
* Note: do not listen to this in order to be generally informed of edits--listen to the
* "change" event on Document instead.
* - scroll -- When the editor is scrolled, either by user action or programmatically.
* - lostContent -- When the backing Document changes in such a way that this Editor is no longer
* able to display accurate text. This occurs if the Document's file is deleted, or in certain
* Document->editor syncing edge cases that we do not yet support (the latter cause will
* eventually go away).
*
* The Editor also dispatches "change" events internally, but you should listen for those on
* Documents, not Editors.
*
* These are jQuery events, so to listen for them you do something like this:
* $(editorInstance).on("eventname", handler);
*/
define(function (require, exports, module) {
"use strict";
var EditorManager = require("editor/EditorManager"),
CodeHintManager = require("editor/CodeHintManager"),
Commands = require("command/Commands"),
CommandManager = require("command/CommandManager"),
Menus = require("command/Menus"),
PerfUtils = require("utils/PerfUtils"),
PreferencesManager = require("preferences/PreferencesManager"),
Strings = require("strings"),
TextRange = require("document/TextRange").TextRange,
ViewUtils = require("utils/ViewUtils");
var PREFERENCES_CLIENT_ID = "com.adobe.brackets.Editor",
defaultPrefs = { useTabChar: false, tabSize: 4, indentUnit: 4 };
/** Editor preferences */
var _prefs = PreferencesManager.getPreferenceStorage(PREFERENCES_CLIENT_ID, defaultPrefs);
/** @type {boolean} Global setting: When inserting new text, use tab characters? (instead of spaces) */
var _useTabChar = _prefs.getValue("useTabChar");
/** @type {boolean} Global setting: Tab size */
var _tabSize = _prefs.getValue("tabSize");
/** @type {boolean} Global setting: Indent unit (i.e. number of spaces when indenting) */
var _indentUnit = _prefs.getValue("indentUnit");
/**
* @private
* Handle Tab key press.
* @param {!CodeMirror} instance CodeMirror instance.
*/
function _handleTabKey(instance) {
// Tab key handling is done as follows:
// 1. If the selection is before any text and the indentation is to the left of
// the proper indentation then indent it to the proper place. Otherwise,
// add another tab. In either case, move the insertion point to the
// beginning of the text.
// 2. If the selection is after the first non-space character, and is not an
// insertion point, indent the entire line(s).
// 3. If the selection is after the first non-space character, and is an
// insertion point, insert a tab character or the appropriate number
// of spaces to pad to the nearest tab boundary.
var from = instance.getCursor(true),
to = instance.getCursor(false),
line = instance.getLine(from.line),
indentAuto = false,
insertTab = false;
if (from.line === to.line) {
if (line.search(/\S/) > to.ch || to.ch === 0) {
indentAuto = true;
}
}
if (indentAuto) {
var currentLength = line.length;
CodeMirror.commands.indentAuto(instance);
// If the amount of whitespace didn't change, insert another tab
if (instance.getLine(from.line).length === currentLength) {
insertTab = true;
to.ch = 0;
}
} else if (instance.somethingSelected()) {
CodeMirror.commands.indentMore(instance);
} else {
insertTab = true;
}
if (insertTab) {
if (instance.getOption("indentWithTabs")) {
CodeMirror.commands.insertTab(instance);
} else {
var i, ins = "", numSpaces = _indentUnit;
numSpaces -= to.ch % numSpaces;
for (i = 0; i < numSpaces; i++) {
ins += " ";
}
instance.replaceSelection(ins, "end");
}
}
}
/**
* @private
* Handle left arrow, right arrow, backspace and delete keys when soft tabs are used.
* @param {!CodeMirror} instance CodeMirror instance
* @param {number} direction Direction of movement: 1 for forward, -1 for backward
* @param {function} functionName name of the CodeMirror function to call
* @return {boolean} true if key was handled
*/
function _handleSoftTabNavigation(instance, direction, functionName) {
var handled = false;
if (!instance.getOption("indentWithTabs")) {
var cursor = instance.getCursor(),
jump = cursor.ch % _indentUnit,
line = instance.getLine(cursor.line);
if (direction === 1) {
jump = _indentUnit - jump;
if (cursor.ch + jump > line.length) { // Jump would go beyond current line
return false;
}
if (line.substr(cursor.ch, jump).search(/\S/) === -1) {
instance[functionName](jump, "char");
handled = true;
}
} else {
// Quick exit if we are at the beginning of the line
if (cursor.ch === 0) {
return false;
}
// If we are on the tab boundary, jump by the full amount,
// but not beyond the start of the line.
if (jump === 0) {
jump = _indentUnit;
}
// Search backwards to the first non-space character
var offset = line.substr(cursor.ch - jump, jump).search(/\s*$/g);
if (offset !== -1) { // Adjust to jump to first non-space character
jump -= offset;
}
if (jump > 0) {
instance[functionName](-jump, "char");
handled = true;
}
}
}
return handled;
}
/**
* Checks if the user just typed a closing brace/bracket/paren, and considers automatically
* back-indenting it if so.
*/
function _checkElectricChars(jqEvent, editor, event) {
var instance = editor._codeMirror;
if (event.type === "keypress") {
var keyStr = String.fromCharCode(event.which || event.keyCode);
if (/[\]\{\}\)]/.test(keyStr)) {
// If all text before the cursor is whitespace, auto-indent it
var cursor = instance.getCursor();
var lineStr = instance.getLine(cursor.line);
var nonWS = lineStr.search(/\S/);
if (nonWS === -1 || nonWS >= cursor.ch) {
// Need to do the auto-indent on a timeout to ensure
// the keypress is handled before auto-indenting.
// This is the same timeout value used by the
// electricChars feature in CodeMirror.
window.setTimeout(function () {
instance.indentLine(cursor.line);
}, 75);
}
}
}
}
function _handleKeyEvents(jqEvent, editor, event) {
_checkElectricChars(jqEvent, editor, event);
// Pass the key event to the code hint manager. It may call preventDefault() on the event.
CodeHintManager.handleKeyEvent(editor, event);
}
function _handleSelectAll() {
var editor = EditorManager.getFocusedEditor();
if (editor) {
editor._selectAllVisible();
}
}
/**
* List of all current (non-destroy()ed) Editor instances. Needed when changing global preferences
* that affect all editors, e.g. tabbing or color scheme settings.
* @type {Array.<Editor>}
*/
var _instances = [];
/**
* @constructor
*
* Creates a new CodeMirror editor instance bound to the given Document. The Document need not have
* a "master" Editor realized yet, even if makeMasterEditor is false; in that case, the first time
* an edit occurs we will automatically ask EditorManager to create a "master" editor to render the
* Document modifiable.
*
* ALWAYS call destroy() when you are done with an Editor - otherwise it will leak a Document ref.
*
* @param {!Document} document
* @param {!boolean} makeMasterEditor If true, this Editor will set itself as the (secret) "master"
* Editor for the Document. If false, this Editor will attach to the Document as a "slave"/
* secondary editor.
* @param {!string} mode Syntax-highlighting language mode; "" means plain-text mode.
* See {@link EditorUtils#getModeFromFileExtension()}.
* @param {!jQueryObject} container Container to add the editor to.
* @param {!Object<string, function(Editor)>} additionalKeys Mapping of keyboard shortcuts to
* custom handler functions. Mapping is in CodeMirror format
* @param {{startLine: number, endLine: number}=} range If specified, range of lines within the document
* to display in this editor. Inclusive.
*/
function Editor(document, makeMasterEditor, mode, container, additionalKeys, range) {
var self = this;
_instances.push(this);
// Attach to document: add ref & handlers
this.document = document;
document.addRef();
if (range) { // attach this first: want range updated before we process a change
this._visibleRange = new TextRange(document, range.startLine, range.endLine);
}
// store this-bound version of listeners so we can remove them later
this._handleDocumentChange = this._handleDocumentChange.bind(this);
this._handleDocumentDeleted = this._handleDocumentDeleted.bind(this);
$(document).on("change", this._handleDocumentChange);
$(document).on("deleted", this._handleDocumentDeleted);
// (if makeMasterEditor, we attach the Doc back to ourselves below once we're fully initialized)
this._inlineWidgets = [];
// Editor supplies some standard keyboard behavior extensions of its own
var codeMirrorKeyMap = {
"Tab": _handleTabKey,
"Shift-Tab": "indentLess",
"Left": function (instance) {
if (!_handleSoftTabNavigation(instance, -1, "moveH")) {
CodeMirror.commands.goCharLeft(instance);
}
},
"Right": function (instance) {
if (!_handleSoftTabNavigation(instance, 1, "moveH")) {
CodeMirror.commands.goCharRight(instance);
}
},
"Backspace": function (instance) {
if (!_handleSoftTabNavigation(instance, -1, "deleteH")) {
CodeMirror.commands.delCharLeft(instance);
}
},
"Delete": function (instance) {
if (!_handleSoftTabNavigation(instance, 1, "deleteH")) {
CodeMirror.commands.delCharRight(instance);
}
},
"Esc": function (instance) {
self.removeAllInlineWidgets();
},
"'>'": function (cm) { cm.closeTag(cm, '>'); },
"'/'": function (cm) { cm.closeTag(cm, '/'); }
};
EditorManager.mergeExtraKeys(self, codeMirrorKeyMap, additionalKeys);
// We'd like null/"" to mean plain text mode. CodeMirror defaults to plaintext for any
// unrecognized mode, but it complains on the console in that fallback case: so, convert
// here so we're always explicit, avoiding console noise.
if (!mode) {
mode = "text/plain";
}
// Create the CodeMirror instance
// (note: CodeMirror doesn't actually require using 'new', but jslint complains without it)
this._codeMirror = new CodeMirror(container, {
electricChars: false, // we use our own impl of this to avoid CodeMirror bugs; see _checkElectricChars()
indentWithTabs: _useTabChar,
tabSize: _tabSize,
indentUnit: _indentUnit,
lineNumbers: true,
matchBrackets: true,
dragDrop: false, // work around issue #1123
extraKeys: codeMirrorKeyMap
});
// Can't get CodeMirror's focused state without searching for
// CodeMirror-focused. Instead, track focus via onFocus and onBlur
// options and track state with this._focused
this._focused = false;
this._installEditorListeners();
$(this)
.on("keyEvent", _handleKeyEvents)
.on("change", this._handleEditorChange.bind(this));
// Set code-coloring mode BEFORE populating with text, to avoid a flash of uncolored text
this._codeMirror.setOption("mode", mode);
// Initially populate with text. This will send a spurious change event, so need to make
// sure this is understood as a 'sync from document' case, not a genuine edit
this._duringSync = true;
this._resetText(document.getText());
this._duringSync = false;
if (range) {
// Hide all lines other than those we want to show. We do this rather than trimming the
// text itself so that the editor still shows accurate line numbers.
this._codeMirror.operation(function () {
var i;
for (i = 0; i < range.startLine; i++) {
self._hideLine(i);
}
var lineCount = self.lineCount();
for (i = range.endLine + 1; i < lineCount; i++) {
self._hideLine(i);
}
});
this.setCursorPos(range.startLine, 0);
}
// Now that we're fully initialized, we can point the document back at us if needed
if (makeMasterEditor) {
document._makeEditable(this);
}
// Add scrollTop property to this object for the scroll shadow code to use
Object.defineProperty(this, "scrollTop", {
get: function () {
return this._codeMirror.getScrollInfo().y;
}
});
}
/**
* Removes this editor from the DOM and detaches from the Document. If this is the "master"
* Editor that is secretly providing the Document's backing state, then the Document reverts to
* a read-only string-backed mode.
*/
Editor.prototype.destroy = function () {
// CodeMirror docs for getWrapperElement() say all you have to do is "Remove this from your
// tree to delete an editor instance."
$(this.getRootElement()).remove();
_instances.splice(_instances.indexOf(this), 1);
// Disconnect from Document
this.document.releaseRef();
$(this.document).off("change", this._handleDocumentChange);
$(this.document).off("deleted", this._handleDocumentDeleted);
if (this._visibleRange) { // TextRange also refs the Document
this._visibleRange.dispose();
}
// If we're the Document's master editor, disconnecting from it has special meaning
if (this.document._masterEditor === this) {
this.document._makeNonEditable();
}
// Destroying us destroys any inline widgets we're hosting. Make sure their closeCallbacks
// run, at least, since they may also need to release Document refs
this._inlineWidgets.forEach(function (inlineWidget) {
inlineWidget.onClosed();
});
};
/**
* Handles Select All specially when we have a visible range in order to work around
* bugs in CodeMirror when lines are hidden.
*/
Editor.prototype._selectAllVisible = function () {
var startLine = this.getFirstVisibleLine(),
endLine = this.getLastVisibleLine();
this.setSelection({line: startLine, ch: 0},
{line: endLine, ch: this.document.getLine(endLine).length});
};
/**
* Ensures that the lines that are actually hidden in the inline editor correspond to
* the desired visible range.
*/
Editor.prototype._updateHiddenLines = function () {
if (this._visibleRange) {
var cm = this._codeMirror,
self = this;
cm.operation(function () {
// TODO: could make this more efficient by only iterating across the min-max line
// range of the union of all changes
var i;
for (i = 0; i < cm.lineCount(); i++) {
if (i < self._visibleRange.startLine || i > self._visibleRange.endLine) {
self._hideLine(i);
} else {
// Double-check that the set of NON-hidden lines matches our range too
console.assert(!cm.getLineHandle(i).hidden);
}
}
});
}
};
Editor.prototype._applyChanges = function (changeList) {
// _visibleRange has already updated via its own Document listener. See if this change caused
// it to lose sync. If so, our whole view is stale - signal our owner to close us.
if (this._visibleRange) {
if (this._visibleRange.startLine === null || this._visibleRange.endLine === null) {
$(this).triggerHandler("lostContent");
return;
}
}
// Apply text changes to CodeMirror editor
var cm = this._codeMirror;
cm.operation(function () {
var change, newText;
for (change = changeList; change; change = change.next) {
newText = change.text.join('\n');
if (!change.from || !change.to) {
if (change.from || change.to) {
console.assert(false, "Change record received with only one end undefined--replacing entire text");
}
cm.setValue(newText);
} else {
cm.replaceRange(newText, change.from, change.to);
}
}
});
// The update above may have inserted new lines - must hide any that fall outside our range
this._updateHiddenLines();
};
/**
* Responds to changes in the CodeMirror editor's text, syncing the changes to the Document.
* There are several cases where we want to ignore a CodeMirror change:
* - if we're the master editor, editor changes can be ignored because Document is already listening
* for our changes
* - if we're a secondary editor, editor changes should be ignored if they were caused by us reacting
* to a Document change
*/
Editor.prototype._handleEditorChange = function (event, editor, changeList) {
// we're currently syncing from the Document, so don't echo back TO the Document
if (this._duringSync) {
return;
}
// Secondary editor: force creation of "master" editor backing the model, if doesn't exist yet
this.document._ensureMasterEditor();
if (this.document._masterEditor !== this) {
// Secondary editor:
// we're not the ground truth; if we got here, this was a real editor change (not a
// sync from the real ground truth), so we need to sync from us into the document
// (which will directly push the change into the master editor).
// FUTURE: Technically we should add a replaceRange() method to Document and go through
// that instead of talking to its master editor directly. It's not clear yet exactly
// what the right Document API would be, though.
this._duringSync = true;
this.document._masterEditor._applyChanges(changeList);
this._duringSync = false;
// Update which lines are hidden inside our editor, since we're not going to go through
// _applyChanges() in our own editor.
this._updateHiddenLines();
}
// Else, Master editor:
// we're the ground truth; nothing else to do, since Document listens directly to us
// note: this change might have been a real edit made by the user, OR this might have
// been a change synced from another editor
CodeHintManager.handleChange(this);
};
/**
* Responds to changes in the Document's text, syncing the changes into our CodeMirror instance.
* There are several cases where we want to ignore a Document change:
* - if we're the master editor, Document changes should be ignored becuase we already have the right
* text (either the change originated with us, or it has already been set into us by Document)
* - if we're a secondary editor, Document changes should be ignored if they were caused by us sending
* the document an editor change that originated with us
*/
Editor.prototype._handleDocumentChange = function (event, doc, changeList) {
var change;
// we're currently syncing to the Document, so don't echo back FROM the Document
if (this._duringSync) {
return;
}
if (this.document._masterEditor !== this) {
// Secondary editor:
// we're not the ground truth; and if we got here, this was a Document change that
// didn't come from us (e.g. a sync from another editor, a direct programmatic change
// to the document, or a sync from external disk changes)... so sync from the Document
this._duringSync = true;
this._applyChanges(changeList);
this._duringSync = false;
}
// Else, Master editor:
// we're the ground truth; nothing to do since Document change is just echoing our
// editor changes
};
/**
* Responds to the Document's underlying file being deleted. The Document is now basically dead,
* so we must close.
*/
Editor.prototype._handleDocumentDeleted = function (event) {
// Pass the delete event along as the cause (needed in MultiRangeInlineEditor)
$(this).triggerHandler("lostContent", [event]);
};
/**
* Install singleton event handlers on the CodeMirror instance, translating them into multi-
* listener-capable jQuery events on the Editor instance.
*/
Editor.prototype._installEditorListeners = function () {
var self = this;
// FUTURE: if this list grows longer, consider making this a more generic mapping
// NOTE: change is a "private" event--others shouldn't listen to it on Editor, only on
// Document
this._codeMirror.setOption("onChange", function (instance, changeList) {
$(self).triggerHandler("change", [self, changeList]);
});
this._codeMirror.setOption("onKeyEvent", function (instance, event) {
$(self).triggerHandler("keyEvent", [self, event]);
return event.defaultPrevented; // false tells CodeMirror we didn't eat the event
});
this._codeMirror.setOption("onCursorActivity", function (instance) {
$(self).triggerHandler("cursorActivity", [self]);
});
this._codeMirror.setOption("onScroll", function (instance) {
// If this editor is visible, close all dropdowns on scroll.
// (We don't want to do this if we're just scrolling in a non-visible editor
// in response to some document change event.)
if (self.isFullyVisible()) {
Menus.closeAll();
}
$(self).triggerHandler("scroll", [self]);
// notify all inline widgets of a position change
self._fireWidgetOffsetTopChanged(self.getFirstVisibleLine() - 1);
});
// Convert CodeMirror onFocus events to EditorManager activeEditorChanged
this._codeMirror.setOption("onFocus", function () {
self._focused = true;
EditorManager._notifyActiveEditorChanged(self);
});
this._codeMirror.setOption("onBlur", function () {
self._focused = false;
// EditorManager only cares about other Editors gaining focus, so we don't notify it of anything here
});
};
/**
* Sets the contents of the editor and clears the undo/redo history. Dispatches a change event.
* Semi-private: only Document should call this.
* @param {!string} text
*/
Editor.prototype._resetText = function (text) {
var perfTimerName = PerfUtils.markStart("Edtitor._resetText()\t" + (!this.document || this.document.file.fullPath));
var cursorPos = this.getCursorPos(),
scrollPos = this.getScrollPos();
// This *will* fire a change event, but we clear the undo immediately afterward
this._codeMirror.setValue(text);
// Make sure we can't undo back to the empty state before setValue()
this._codeMirror.clearHistory();
// restore cursor and scroll positions
this.setCursorPos(cursorPos);
this.setScrollPos(scrollPos.x, scrollPos.y);
PerfUtils.addMeasurement(perfTimerName);
};
/**
* Gets the current cursor position within the editor. If there is a selection, returns whichever
* end of the range the cursor lies at.
* @param {boolean} expandTabs If true, return the actual visual column number instead of the character offset in
* the "ch" property.
* @return !{line:number, ch:number}
*/
Editor.prototype.getCursorPos = function (expandTabs) {
var cursor = this._codeMirror.getCursor();
if (expandTabs) {
var line = this._codeMirror.getRange({line: cursor.line, ch: 0}, cursor),
tabSize = Editor.getTabSize(),
column = 0,
i;
for (i = 0; i < line.length; i++) {
if (line[i] === '\t') {
column += (tabSize - (column % tabSize));
} else {
column++;
}
}
cursor.ch = column;
}
return cursor;
};
/**
* Sets the cursor position within the editor. Removes any selection.
* @param {number} line The 0 based line number.
* @param {number=} ch The 0 based character position; treated as 0 if unspecified.
*/
Editor.prototype.setCursorPos = function (line, ch) {
this._codeMirror.setCursor(line, ch);
};
/**
* Given a position, returns its index within the text (assuming \n newlines)
* @param {!{line:number, ch:number}}
* @return {number}
*/
Editor.prototype.indexFromPos = function (coords) {
return this._codeMirror.indexFromPos(coords);
};
/**
* Returns true if pos is between start and end (inclusive at both ends)
* @param {{line:number, ch:number}} pos
* @param {{line:number, ch:number}} start
* @param {{line:number, ch:number}} end
*
*/
Editor.prototype.posWithinRange = function (pos, start, end) {
var startIndex = this.indexFromPos(start),
endIndex = this.indexFromPos(end),
posIndex = this.indexFromPos(pos);
return posIndex >= startIndex && posIndex <= endIndex;
};
/**
* @return {boolean} True if there's a text selection; false if there's just an insertion point
*/
Editor.prototype.hasSelection = function () {
return this._codeMirror.somethingSelected();
};
/**
* Gets the current selection. Start is inclusive, end is exclusive. If there is no selection,
* returns the current cursor position as both the start and end of the range (i.e. a selection
* of length zero).
* @return {!{start:{line:number, ch:number}, end:{line:number, ch:number}}}
*/
Editor.prototype.getSelection = function () {
var selStart = this._codeMirror.getCursor(true),
selEnd = this._codeMirror.getCursor(false);
return { start: selStart, end: selEnd };
};
/**
* @return {!string} The currently selected text, or "" if no selection. Includes \n if the
* selection spans multiple lines (does NOT reflect the Document's line-endings style).
*/
Editor.prototype.getSelectedText = function () {
return this._codeMirror.getSelection();
};
/**
* Sets the current selection. Start is inclusive, end is exclusive. Places the cursor at the
* end of the selection range.
* @param {!{line:number, ch:number}} start
* @param {!{line:number, ch:number}} end
*/
Editor.prototype.setSelection = function (start, end) {
this._codeMirror.setSelection(start, end);
};
/**
* Selects word that the given pos lies within or adjacent to. If pos isn't touching a word
* (e.g. within a token like "//"), moves the cursor to pos without selecting a range.
* Adapted from selectWordAt() in CodeMirror v2.
* @param {!{line:number, ch:number}}
*/
Editor.prototype.selectWordAt = function (pos) {
var line = this.document.getLine(pos.line),
start = pos.ch,
end = pos.ch;
function isWordChar(ch) {
return (/\w/).test(ch) || ch.toUpperCase() !== ch.toLowerCase();
}
while (start > 0 && isWordChar(line.charAt(start - 1))) {
--start;
}
while (end < line.length && isWordChar(line.charAt(end))) {
++end;
}
this.setSelection({line: pos.line, ch: start}, {line: pos.line, ch: end});
};
/**
* Gets the total number of lines in the the document (includes lines not visible in the viewport)
* @returns {!number}
*/
Editor.prototype.lineCount = function () {
return this._codeMirror.lineCount();
};
/**
* Gets the number of the first visible line in the editor.
* @returns {number} The 0-based index of the first visible line.
*/
Editor.prototype.getFirstVisibleLine = function () {
return (this._visibleRange ? this._visibleRange.startLine : 0);
};
/**
* Gets the number of the last visible line in the editor.
* @returns {number} The 0-based index of the last visible line.
*/
Editor.prototype.getLastVisibleLine = function () {
return (this._visibleRange ? this._visibleRange.endLine : this.lineCount() - 1);
};
// FUTURE change to "hideLines()" API that hides a range of lines at once in a single operation, then fires offsetTopChanged afterwards.
/* Hides the specified line number in the editor
* @param {!number}
*/
Editor.prototype._hideLine = function (lineNumber) {
var value = this._codeMirror.hideLine(lineNumber);
// when this line is hidden, notify all following inline widgets of a position change
this._fireWidgetOffsetTopChanged(lineNumber);
return value;
};
/**
* Gets the total height of the document in pixels (not the viewport)
* @param {!boolean} includePadding
* @returns {!number} height in pixels
*/
Editor.prototype.totalHeight = function (includePadding) {
return this._codeMirror.totalHeight(includePadding);
};
/**
* Gets the scroller element from the editor.
* @returns {!HTMLDivElement} scroller
*/
Editor.prototype.getScrollerElement = function () {
return this._codeMirror.getScrollerElement();
};
/**
* Gets the root DOM node of the editor.
* @returns {Object} The editor's root DOM node.
*/
Editor.prototype.getRootElement = function () {
return this._codeMirror.getWrapperElement();
};
/**
* Gets the lineSpace element within the editor (the container around the individual lines of code).
* FUTURE: This is fairly CodeMirror-specific. Logic that depends on this may break if we switch
* editors.
* @returns {Object} The editor's lineSpace element.
*/
Editor.prototype._getLineSpaceElement = function () {
return $(".CodeMirror-lines", this.getScrollerElement()).children().get(0);
};
/**
* Returns the current scroll position of the editor.
* @returns {{x:number, y:number}} The x,y scroll position in pixels
*/
Editor.prototype.getScrollPos = function () {
return this._codeMirror.getScrollInfo();
};
/**
* Sets the current scroll position of the editor.
* @param {number} x scrollLeft position in pixels
* @param {number} y scrollTop position in pixels
*/
Editor.prototype.setScrollPos = function (x, y) {
this._codeMirror.scrollTo(x, y);
};
/**
* Adds an inline widget below the given line. If any inline widget was already open for that
* line, it is closed without warning.
* @param {!{line:number, ch:number}} pos Position in text to anchor the inline.
* @param {!InlineWidget} inlineWidget The widget to add.
*/
Editor.prototype.addInlineWidget = function (pos, inlineWidget) {
var self = this;
inlineWidget.id = this._codeMirror.addInlineWidget(pos, inlineWidget.htmlContent, inlineWidget.height, function (id) {
self._removeInlineWidgetInternal(id);
inlineWidget.onClosed();
});
this._inlineWidgets.push(inlineWidget);
inlineWidget.onAdded();
// once this widget is added, notify all following inline widgets of a position change
this._fireWidgetOffsetTopChanged(pos.line);
};
/**
* Removes all inline widgets
*/
Editor.prototype.removeAllInlineWidgets = function () {
// copy the array because _removeInlineWidgetInternal will modifying the original
var widgets = [].concat(this.getInlineWidgets());
widgets.forEach(function (widget) {
this.removeInlineWidget(widget);
}, this);
};
/**
* Removes the given inline widget.
* @param {number} inlineWidget The widget to remove.
*/
Editor.prototype.removeInlineWidget = function (inlineWidget) {
var lineNum = this._getInlineWidgetLineNumber(inlineWidget);
// _removeInlineWidgetInternal will get called from the destroy callback in CodeMirror.
this._codeMirror.removeInlineWidget(inlineWidget.id);
// once this widget is removed, notify all following inline widgets of a position change
this._fireWidgetOffsetTopChanged(lineNum);
};
/**
* Cleans up the given inline widget from our internal list of widgets.
* @param {number} inlineId id returned by addInlineWidget().
*/
Editor.prototype._removeInlineWidgetInternal = function (inlineId) {
var i;
var l = this._inlineWidgets.length;
for (i = 0; i < l; i++) {
if (this._inlineWidgets[i].id === inlineId) {
this._inlineWidgets.splice(i, 1);
break;
}
}
};
/**
* Returns a list of all inline widgets currently open in this editor. Each entry contains the
* inline's id, and the data parameter that was passed to addInlineWidget().
* @return {!Array.<{id:number, data:Object}>}
*/
Editor.prototype.getInlineWidgets = function () {
return this._inlineWidgets;
};
/**
* Sets the height of an inline widget in this editor.
* @param {!InlineWidget} inlineWidget The widget whose height should be set.
* @param {!number} height The height of the widget.
* @param {boolean} ensureVisible Whether to scroll the entire widget into view.
*/
Editor.prototype.setInlineWidgetHeight = function (inlineWidget, height, ensureVisible) {
var info = this._codeMirror.getInlineWidgetInfo(inlineWidget.id),
oldHeight = (info && info.height) || 0;
this._codeMirror.setInlineWidgetHeight(inlineWidget.id, height, ensureVisible);
// update position for all following inline editors
if (oldHeight !== height) {
var lineNum = this._getInlineWidgetLineNumber(inlineWidget);
this._fireWidgetOffsetTopChanged(lineNum);
}
};
/**
* @private
* Get the starting line number for an inline widget.
* @param {!InlineWidget} inlineWidget
* @return {number} The line number of the widget or -1 if not found.
*/
Editor.prototype._getInlineWidgetLineNumber = function (inlineWidget) {
var info = this._codeMirror.getInlineWidgetInfo(inlineWidget.id);
return (info && info.line) || -1;
};
/**
* @private
* Fire "offsetTopChanged" events when inline editor positions change due to
* height changes of other inline editors.
* @param {!InlineWidget} inlineWidget
*/
Editor.prototype._fireWidgetOffsetTopChanged = function (lineNum) {
var self = this,
otherLineNum;
this.getInlineWidgets().forEach(function (other) {
otherLineNum = self._getInlineWidgetLineNumber(other);
if (otherLineNum > lineNum) {
$(other).triggerHandler("offsetTopChanged");
}
});
};
/** Gives focus to the editor control */
Editor.prototype.focus = function () {
this._codeMirror.focus();
};
/** Returns true if the editor has focus */
Editor.prototype.hasFocus = function () {
return this._focused;
};
/**
* Re-renders the editor UI
*/
Editor.prototype.refresh = function () {
this._codeMirror.refresh();
};
/**
* Re-renders the editor, and all children inline editors.
*/
Editor.prototype.refreshAll = function () {
this.refresh();
this.getInlineWidgets().forEach(function (multilineEditor, i, arr) {
multilineEditor.sizeInlineWidgetToContents(true);
multilineEditor._updateRelatedContainer();
multilineEditor.editors.forEach(function (editor, j, arr) {
editor.refresh();
});
});
};
/**
* Shows or hides the editor within its parent. Does not force its ancestors to
* become visible.
* @param {boolean} show true to show the editor, false to hide it
*/
Editor.prototype.setVisible = function (show) {
$(this.getRootElement()).css("display", (show ? "" : "none"));
this._codeMirror.refresh();
if (show) {
this._inlineWidgets.forEach(function (inlineWidget) {
inlineWidget.onParentShown();
});
}
};
/**
* Returns true if the editor is fully visible--i.e., is in the DOM, all ancestors are
* visible, and has a non-zero width/height.
*/
Editor.prototype.isFullyVisible = function () {
return $(this.getRootElement()).is(":visible");
};
/**
* Gets the syntax-highlighting mode for the current selection or cursor position. (The mode may
* vary within one file due to embedded languages, e.g. JS embedded in an HTML script block).
*
* Returns null if the mode at the start of the selection differs from the mode at the end -
* an *approximation* of whether the mode is consistent across the whole range (a pattern like
* A-B-A would return A as the mode, not null).
*
* @return {?(Object|String)} Object or Name of syntax-highlighting mode; see {@link EditorUtils#getModeFromFileExtension()}.
*/
Editor.prototype.getModeForSelection = function () {
var sel = this.getSelection();
// Check for mixed mode info (meaning mode varies depending on position)
// TODO (#921): this only works for certain mixed modes; some do not expose this info
var startState = this._codeMirror.getTokenAt(sel.start).state;
if (startState.mode) {
var startMode = startState.mode;
// If mixed mode, check that mode is the same at start & end of selection
if (sel.start.line !== sel.end.line || sel.start.ch !== sel.end.ch) {
var endState = this._codeMirror.getTokenAt(sel.end).state;
var endMode = endState.mode;
if (startMode !== endMode) {
return null;
}
}
return startMode;
} else {
// Mode does not vary: just use the editor-wide mode
return this._codeMirror.getOption("mode");
}
};
/**
* Gets the syntax-highlighting mode for the document.
*
* @return {Object|String} Object or Name of syntax-highlighting mode; see {@link EditorUtils#getModeFromFileExtension()}.
*/
Editor.prototype.getModeForDocument = function () {
return this._codeMirror.getOption("mode");
};
/**
* Sets the syntax-highlighting mode for the document.
*
* @param {string} mode Name of syntax highlighting mode.
*/
Editor.prototype.setModeForDocument = function (mode) {
this._codeMirror.setOption("mode", mode);
};
/**
* The Document we're bound to
* @type {!Document}
*/
Editor.prototype.document = null;
/**
* If true, we're in the middle of syncing to/from the Document. Used to ignore spurious change
* events caused by us (vs. change events caused by others, which we need to pay attention to).
* @type {!boolean}
*/
Editor.prototype._duringSync = false;
/**
* @private
* NOTE: this is actually "semi-private": EditorManager also accesses this field... as well as
* a few other modules. However, we should try to gradually move most code away from talking to
* CodeMirror directly.
* @type {!CodeMirror}
*/
Editor.prototype._codeMirror = null;
/**
* @private
* @type {!Array.<{id:number, data:Object}>}
*/
Editor.prototype._inlineWidgets = null;
/**
* @private
* @type {?TextRange}
*/
Editor.prototype._visibleRange = null;
// Global settings that affect all Editor instances (both currently open Editors as well as those created
// in the future)
/**
* Sets whether to use tab characters (vs. spaces) when inserting new text. Affects all Editors.
* @param {boolean} value
*/
Editor.setUseTabChar = function (value) {
_useTabChar = value;
_instances.forEach(function (editor) {
editor._codeMirror.setOption("indentWithTabs", _useTabChar);
});
_prefs.setValue("useTabChar", Boolean(_useTabChar));
};
/** @type {boolean} Gets whether all Editors use tab characters (vs. spaces) when inserting new text */
Editor.getUseTabChar = function (value) {
return _useTabChar;
};
/**
* Sets tab character width. Affects all Editors.
* @param {number} value
*/
Editor.setTabSize = function (value) {
_tabSize = value;
_instances.forEach(function (editor) {
editor._codeMirror.setOption("tabSize", _tabSize);
});
_prefs.setValue("tabSize", _tabSize);
};
/** @type {number} Get indent unit */
Editor.getTabSize = function (value) {
return _tabSize;
};
/**
* Sets indentation width. Affects all Editors.
* @param {number} value
*/
Editor.setIndentUnit = function (value) {
_indentUnit = value;
_instances.forEach(function (editor) {
editor._codeMirror.setOption("indentUnit", _indentUnit);
});
_prefs.setValue("indentUnit", _indentUnit);
};
/** @type {number} Get indentation width */
Editor.getIndentUnit = function (value) {
return _indentUnit;
};
// Global commands that affect the currently focused Editor instance, wherever it may be
CommandManager.register(Strings.CMD_SELECT_ALL, Commands.EDIT_SELECT_ALL, _handleSelectAll);
// Define public API
exports.Editor = Editor;
});
|
using System;
using System.Collections.Generic;
using System.Text;
namespace WilliamWsy.RegexGenerator
{
public abstract class RegexLookaroundAssertionNode
: RegexNode
{
public RegexLookaroundAssertionNode(string pattern, int? min = null, int? max = null, RegexQuantifierOption quantifierOption = RegexQuantifierOption.Greedy)
: base(pattern, min, max, quantifierOption)
{
}
public RegexLookaroundAssertionNode(RegexNode innerNode, int? min = null, int? max = null, RegexQuantifierOption quantifierOption = RegexQuantifierOption.Greedy)
: base(innerNode, min, max, quantifierOption)
{
}
}
}
|
<?php
namespace Franklin\test\Soundcloud\TrackInfo\test;
use
Franklin\test\Soundcloud\TrackInfo\TrackInfo,
Franklin\test\Soundcloud\TrackInfo\Config
;
/**
* @group Tests
* @group Soundcloud
*/
class TrackInfoTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
$config = new Config(array(
'id' => 291,
'key' => 'playback',
));
$this->fixture = new TrackInfo($config);
}
public function testRun()
{
$result = $this->fixture->run();
$this->assertGreaterThan(100, $result);
}
} |
import { autoBindMethodsForReact } from 'class-autobind-decorator';
import { HotKeyRegistry } from 'insomnia-common';
import React, { PureComponent } from 'react';
import { AUTOBIND_CFG, DEBOUNCE_MILLIS, SortOrder } from '../../../common/constants';
import { hotKeyRefs } from '../../../common/hotkeys';
import { executeHotKey } from '../../../common/hotkeys-listener';
import { KeydownBinder } from '../keydown-binder';
import { SidebarCreateDropdown } from './sidebar-create-dropdown';
import { SidebarSortDropdown } from './sidebar-sort-dropdown';
interface Props {
onChange: (value: string) => Promise<void>;
requestCreate: () => void;
requestGroupCreate: () => void;
sidebarSort: (sortOrder: SortOrder) => void;
filter: string;
hotKeyRegistry: HotKeyRegistry;
}
@autoBindMethodsForReact(AUTOBIND_CFG)
export class SidebarFilter extends PureComponent<Props> {
_input: HTMLInputElement | null = null;
_triggerTimeout: NodeJS.Timeout | null = null;
_setInputRef(n: HTMLInputElement) {
this._input = n;
}
_handleClearFilter() {
this.props.onChange('');
if (this._input) {
this._input.value = '';
this._input.focus();
}
}
_handleOnChange(e: React.SyntheticEvent<HTMLInputElement>) {
const value = e.currentTarget.value;
if (this._triggerTimeout) {
clearTimeout(this._triggerTimeout);
}
this._triggerTimeout = setTimeout(() => {
this.props.onChange(value);
}, DEBOUNCE_MILLIS);
}
_handleRequestGroupCreate() {
this.props.requestGroupCreate();
}
_handleRequestCreate() {
this.props.requestCreate();
}
_handleKeydown(event: KeyboardEvent) {
executeHotKey(event, hotKeyRefs.SIDEBAR_FOCUS_FILTER, () => {
this._input?.focus();
});
}
render() {
const { filter, hotKeyRegistry, sidebarSort } = this.props;
return (
<KeydownBinder onKeydown={this._handleKeydown}>
<div className="sidebar__filter">
<div className="form-control form-control--outlined form-control--btn-right">
<input
ref={this._setInputRef}
type="text"
placeholder="Filter"
defaultValue={filter}
onChange={this._handleOnChange}
/>
{filter && (
<button className="form-control__right" onClick={this._handleClearFilter}>
<i className="fa fa-times-circle" />
</button>
)}
</div>
<SidebarSortDropdown handleSort={sidebarSort} />
<SidebarCreateDropdown
handleCreateRequest={this._handleRequestCreate}
handleCreateRequestGroup={this._handleRequestGroupCreate}
hotKeyRegistry={hotKeyRegistry}
/>
</div>
</KeydownBinder>
);
}
}
|
package com.mansonheart.data;
import java.util.Objects;
/**
* Created by alexandr on 18.09.16.
*/
public class Repository {
public Object get() {
return new Object();
}
public void add(Object object) {
}
}
|
# Configure Botkit and Cisco Webex Teams
Setting up a bot for Cisco Webex Teams is one of the easiest experiences for bot developers! Follow these steps carefully to configure your bot.
### 1. Install Botkit
You will need to [install Botkit](../platforms/webex.md#get-started) and run it before your bot can be configured with Cisco Spark.
### 2. Create a new bot in the Cisco Developer portal
Follow the instructions to create a new bot in the [Cisco Webex Teams Developer Portal](https://developer.ciscospark.com/add-bot.html).

Take note of the bot username, you'll need it later.
**Note about your icon**: Cisco requires you host an avatar for your bot before you can create it in their portal. This bot needs to be a 512x512px image icon hosted anywhere on the web. This can be changed later.
You can copy and paste this URL for a Botkit icon you can use right away:
https://raw.githubusercontent.com/howdyai/botkit-starter-ciscospark/master/public/default_icon.png
### 3. Copy your access token
Cisco will provide you an `access token` that is specific to your bot. Write this down, you won't be able to see this later (but you will be able revoke it and create a new one).
### 4. Run your bot with variables set
[Follow these instructions](../platforms/webex.md#get-started) to run your bot locally, or by using a third-party service such as [Glitch](https://glitch.com) or [Heroku](https://heroku.com).
You will need the following environment variables when running your bot:
* `access_token` = Your token from Webex Teams (**required**)
* `secret` = User-defined string to validate payloads (**required**)
* `public_address`= URL of your bot server (**required**)
You should now be able to search your Webex Teams for the bot username you defined, and add it to your team!
### Additional resources
Read more about making bots for this platform in the [Webex Developer Portal](https://developer.webex.com/docs/bots).
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities.Editor;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input.Editor
{
[CustomEditor(typeof(SpeechInputHandler))]
public class SpeechInputHandlerInspector : BaseInputHandlerInspector
{
private static readonly GUIContent RemoveButtonContent = new GUIContent("-", "Remove keyword");
private static readonly GUIContent AddButtonContent = new GUIContent("+", "Add keyword");
private static readonly GUIContent KeywordContent = new GUIContent("Keyword", "Speech keyword item");
private static readonly GUILayoutOption MiniButtonWidth = GUILayout.Width(20.0f);
private string[] distinctRegisteredKeywords;
private SerializedProperty keywordsProperty;
private SerializedProperty persistentKeywordsProperty;
private SerializedProperty speechConfirmationTooltipPrefabProperty;
protected override void OnEnable()
{
base.OnEnable();
keywordsProperty = serializedObject.FindProperty("keywords");
persistentKeywordsProperty = serializedObject.FindProperty("persistentKeywords");
speechConfirmationTooltipPrefabProperty = serializedObject.FindProperty("speechConfirmationTooltipPrefab");
if (MixedRealityInspectorUtility.CheckMixedRealityConfigured(false))
{
distinctRegisteredKeywords = GetDistinctRegisteredKeywords();
}
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
bool enabled = CheckMixedRealityToolkit();
if (enabled)
{
if (!MixedRealityToolkit.Instance.ActiveProfile.IsInputSystemEnabled)
{
EditorGUILayout.HelpBox("No input system is enabled, or you need to specify the type in the main configuration profile.", MessageType.Warning);
}
if (MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile == null)
{
EditorGUILayout.HelpBox("No Input System Profile Found, be sure to specify a profile in the main configuration profile.", MessageType.Error);
enabled = false;
}
else if (MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.SpeechCommandsProfile == null)
{
EditorGUILayout.HelpBox("No Speech Commands profile Found, be sure to specify a profile in the Input System's configuration profile.", MessageType.Error);
enabled = false;
}
}
bool validKeywords = distinctRegisteredKeywords != null && distinctRegisteredKeywords.Length != 0;
// If we should be enabled but there are no valid keywords, alert developer
if (enabled && !validKeywords)
{
distinctRegisteredKeywords = GetDistinctRegisteredKeywords();
EditorGUILayout.HelpBox("No keywords registered. Some properties may not be editable.\n\nKeywords can be registered via Speech Commands Profile on the Mixed Reality Toolkit's Configuration Profile.", MessageType.Error);
}
enabled = enabled && validKeywords;
serializedObject.Update();
EditorGUILayout.PropertyField(persistentKeywordsProperty);
EditorGUILayout.PropertyField(speechConfirmationTooltipPrefabProperty);
bool wasGUIEnabled = GUI.enabled;
GUI.enabled = enabled;
ShowList(keywordsProperty);
GUI.enabled = wasGUIEnabled;
serializedObject.ApplyModifiedProperties();
// error and warning messages
if (keywordsProperty.arraySize == 0)
{
EditorGUILayout.HelpBox("No keywords have been assigned!", MessageType.Warning);
}
else
{
var handler = (SpeechInputHandler)target;
string duplicateKeyword = handler.Keywords
.GroupBy(keyword => keyword.Keyword.ToLower())
.Where(group => group.Count() > 1)
.Select(group => group.Key).FirstOrDefault();
if (duplicateKeyword != null)
{
EditorGUILayout.HelpBox($"Keyword \'{duplicateKeyword}\' is assigned more than once!", MessageType.Warning);
}
}
}
private void ShowList(SerializedProperty list)
{
using (new EditorGUI.IndentLevelScope())
{
// remove the keywords already assigned from the registered list
var handler = (SpeechInputHandler)target;
var availableKeywords = System.Array.Empty<string>();
if (handler.Keywords != null && distinctRegisteredKeywords != null)
{
availableKeywords = distinctRegisteredKeywords.Except(handler.Keywords.Select(keywordAndResponse => keywordAndResponse.Keyword)).ToArray();
}
// keyword rows
for (int index = 0; index < list.arraySize; index++)
{
// the element
SerializedProperty speechCommandProperty = list.GetArrayElementAtIndex(index);
GUILayout.BeginHorizontal();
bool elementExpanded = EditorGUILayout.PropertyField(speechCommandProperty);
GUILayout.FlexibleSpace();
// the remove element button
bool elementRemoved = GUILayout.Button(RemoveButtonContent, EditorStyles.miniButton, MiniButtonWidth);
GUILayout.EndHorizontal();
if (elementRemoved)
{
list.DeleteArrayElementAtIndex(index);
if (index == list.arraySize)
{
EditorGUI.indentLevel--;
return;
}
}
SerializedProperty keywordProperty = speechCommandProperty.FindPropertyRelative("keyword");
bool invalidKeyword = true;
if (distinctRegisteredKeywords != null)
{
foreach (string keyword in distinctRegisteredKeywords)
{
if (keyword == keywordProperty.stringValue)
{
invalidKeyword = false;
break;
}
}
}
if (invalidKeyword)
{
EditorGUILayout.HelpBox("Registered keyword is not recognized in the speech command profile!", MessageType.Error);
}
if (!elementRemoved && elementExpanded)
{
Rect position = EditorGUILayout.GetControlRect();
using (new EditorGUI.PropertyScope(position, KeywordContent, keywordProperty))
{
string[] keywords = availableKeywords.Concat(new[] { keywordProperty.stringValue }).OrderBy(keyword => keyword).ToArray();
int previousSelection = ArrayUtility.IndexOf(keywords, keywordProperty.stringValue);
int currentSelection = EditorGUILayout.Popup(KeywordContent, previousSelection, keywords);
if (currentSelection != previousSelection)
{
keywordProperty.stringValue = keywords[currentSelection];
}
}
SerializedProperty responseProperty = speechCommandProperty.FindPropertyRelative("response");
EditorGUILayout.PropertyField(responseProperty, true);
}
}
// add button row
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
// the add element button
if (GUILayout.Button(AddButtonContent, EditorStyles.miniButton, MiniButtonWidth))
{
var index = list.arraySize;
list.InsertArrayElementAtIndex(index);
var elementProperty = list.GetArrayElementAtIndex(index);
SerializedProperty keywordProperty = elementProperty.FindPropertyRelative("keyword");
keywordProperty.stringValue = string.Empty;
}
}
}
}
private static string[] GetDistinctRegisteredKeywords()
{
if (!MixedRealityToolkit.IsInitialized ||
!MixedRealityToolkit.Instance.HasActiveProfile ||
!MixedRealityToolkit.Instance.ActiveProfile.IsInputSystemEnabled ||
MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.SpeechCommandsProfile == null ||
MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.SpeechCommandsProfile.SpeechCommands.Length == 0)
{
return null;
}
List<string> keywords = new List<string>();
var speechCommands = MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.SpeechCommandsProfile.SpeechCommands;
for (var i = 0; i < speechCommands.Length; i++)
{
keywords.Add(speechCommands[i].Keyword);
}
return keywords.Distinct().ToArray();
}
}
} |
<?php
namespace AppBundle\Service\OAuth\UserResponseHandler;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Interface ResponseHandlerInterface
* @package AppBundle\Service\OAuth\UserResponseHandler
*/
interface ResponseHandlerInterface
{
/**
* @param UserResponseInterface $response
*
* @return UserInterface
*/
public function processOauthUserResponse(UserResponseInterface $response): UserInterface;
} |
/*!
@file stddebug_windows_ntddk.c
@abstract Common debugging utilities
@copyright (c) 1997-2017 by Matt Slot <mattslot@gmail.com>.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
@discussion
Debug implementations safe for use in Windows kernel drivers.
*/
#include "stddebug.h"
#include <ntddk.h>
#include <Ntstrsafe.h>
#pragma comment (lib, "NtosKrnl.lib")
#pragma comment (lib, "Ntstrsafe.lib")
static bool gDebugEnabled = 1;
static int gDebugLevel = 1;
static int gDebugMask = 0;
static bool _IsSafeFormat(const char *string)
{
bool isSafe = true;
for( ; isSafe && *string; string++)
{
char c0 = string[0];
if (c0 == '%')
{
char c1 = string[1];
char c2 = c1 ? string[2] : 0;
if ((c1 == 'C') || (c1 == 'S'))
isSafe = FALSE;
else if ((c1 == 'l') && ((c2 == 'c') || (c2 == 's')))
isSafe = FALSE;
else if ((c1 == 'w') && ((c2 == 'c') || (c2 == 's') || (c2 == 'Z')))
isSafe = FALSE;
if ((c1 == 'f') || (c1 == 'e') || (c1 == 'E') ||
(c1 == 'g') || (c1 == 'G') || (c1 == 'a') || (c1 == 'A'))
return FALSE; // Not supported at all
}
}
return (isSafe) ? TRUE : ((KeGetCurrentIrql() == PASSIVE_LEVEL) ? TRUE : FALSE);
}
static DWORD _GetFilterLevel(int debugLevel)
{
switch(debugLevel)
{
case DEBUG_LEVEL_NONE:
return DPFLTR_INFO_LEVEL;
case DEBUG_LEVEL_FATAL:
case DEBUG_LEVEL_FAILURE:
case DEBUG_LEVEL_ERROR:
return DPFLTR_ERROR_LEVEL;
case DEBUG_LEVEL_WARN:
return DPFLTR_WARNING_LEVEL;
case DEBUG_LEVEL_DEBUG:
case DEBUG_LEVEL_INFO:
return DPFLTR_TRACE_LEVEL;
case DEBUG_LEVEL_SPAM:
// Lowest priority
return DPFLTR_INFO_LEVEL;
}
return DPFLTR_ERROR_LEVEL;
}
void DebugPreflight(const char *logname, bool redirect, int level, int perms)
{
(void)logname;
(void)redirect;
(void)perms;
if (gDebugLevel == 1)
SetDebugLevel(level);
DebugLevel();
}
void DebugPostflight()
{
}
void DebugSwitchLogFile(const char *newFileName)
{
(void)newFileName;
}
void DebugRotateLogFile(const char *newFileName)
{
(void)newFileName;
}
char * CopyDebugHistory()
{
return NULL;
}
#if 0
#pragma mark -
#endif
void DebugMessage(int level, const char *format, ...)
{
if (gDebugEnabled)
{
// Print the requested message into a buffer
if (_IsSafeFormat(format))
{
va_list args;
va_start(args, format);
vDbgPrintExWithPrefix(__PREFIX__, DPFLTR_DEFAULT_ID, _GetFilterLevel(level), format, args);
va_end(args);
}
else
// Ignore the parameters, just output the raw format string
DbgPrintEx(DPFLTR_DEFAULT_ID, _GetFilterLevel(level), "%s%s", __PREFIX__, format);
}
}
void DebugData(const char *label, const void *data, size_t length)
{
unsigned char * bytes = (unsigned char *)data;
char table[] = "0123456789ABCDEF";
char hex[37], ascii[18];
char * buffer = NULL;
size_t bufferLength;
size_t i, j, k, x, y;
if (gDebugEnabled)
{
// Allocate a scratch buffer for the output
bufferLength = (length + 15) * 80 / 16;
buffer = (char *) ExAllocatePoolWithTag(NonPagedPool, bufferLength, 'GBDs');
// Loop over the data, marking the end of our progress after each loop
if (buffer) for(i=k=0; i<length; )
{
char line[120] = "";
// Iterate the data block, processing 16 bytes of data on each line
for(j=0, x=y=0; j<16; i++, j++)
{
if (i < length)
{
hex[x++] = table[bytes[i] >> 4];
hex[x++] = table[bytes[i] & 0x0F];
ascii[y++] = ((bytes[i] < 0x20) || (bytes[i] > 0x7E)) ? '*' : bytes[i];
}
else
{
hex[x++] = ':';
hex[x++] = ':';
ascii[y++] = ':';
}
if ((x+1)%9 == 0) hex[x++] = ' ';
}
// Now format the string nicely into our buffer, and advance our mark
hex[x] = 0;
ascii[y] = 0;
#if _WIN64
RtlStringCbPrintfA(line, sizeof(line), " 0x%.16llX | %s| %s\n", (unsigned long long)(bytes + i), hex, ascii);
#else
RtlStringCbPrintfA(line, sizeof(line), " 0x%.8lX | %s| %s\n", (unsigned long)(bytes + i), hex, ascii);
#endif // _WIN64
RtlStringCbCatNA(buffer, bufferLength, line, sizeof(line));
}
// Now that we have the data, print out the label and our buffer
DbgPrintEx(DPFLTR_DEFAULT_ID, DPFLTR_ERROR_LEVEL,
"%s (%zu bytes):\n%s", label, length,
(buffer) ? buffer : " -- out of memory --\n");
if (buffer)
ExFreePool(buffer);
}
}
void SetDebugEnabled(int enable)
{
gDebugEnabled = (enable) ? true : false;
}
void SetDebugTimestamp(unsigned showTimestamp)
{
(void)showTimestamp; // Ignored
}
unsigned DebugTimestamp()
{
return 0;
}
void SetDebugLevel(int level)
{
if (level > DEBUG_LEVEL_NONE)
level = DEBUG_LEVEL_NONE;
gDebugLevel = level;
}
int DebugLevel(void)
{
return gDebugLevel;
}
void SetDebugMask(int mask)
{
if (mask < 0)
mask = 0;
gDebugMask = mask;
}
int DebugMask(void)
{
return gDebugMask;
}
bool DebugShouldLog(int value)
{
bool shouldLog = true;
if (value < 0)
shouldLog = (DebugLevel() <= value) ? true : false;
else
shouldLog = (DebugMask() & value) ? true : false;
return shouldLog;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#if NETFX_CORE
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI;
using Windows.UI.Xaml.Media;
#else
using System.Windows;
using System.Windows.Data;
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Media;
#endif
namespace TestApplication.Shared
{
public class StringToBrushConverter : IValueConverter
{
#if NETFX_CORE
public object Convert(object value, Type targetType, object parameter, string language)
{
return InternalConvert(value, targetType, parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
#else
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return InternalConvert(value, targetType, parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endif
public object InternalConvert(object value, Type targetType, object parameter)
{
if (value == null)
{
return null;
}
string colorName = value.ToString();
SolidColorBrush scb = new SolidColorBrush();
switch (colorName as string)
{
case "Magenta":
scb.Color = Colors.Magenta;
return scb;
case "Purple":
scb.Color = Colors.Purple;
return scb;
case "Brown":
scb.Color = Colors.Brown;
return scb;
case "Orange":
scb.Color = Colors.Orange;
return scb;
case "Blue":
scb.Color = Colors.Blue;
return scb;
case "Red":
scb.Color = Colors.Red;
return scb;
case "Yellow":
scb.Color = Colors.Yellow;
return scb;
case "Green":
scb.Color = Colors.Green;
return scb;
default:
return null;
}
}
}
}
|
{% extends "base.html" %}
{% set active_page = "admin" %}
{% block title %}Edit Schedules - BearStatus{{title}} {% endblock %}
{% block head %}
{{ super() }}
{% endblock %}
{% block content %}
<div id="content">
<div class="container">
{% if is_special == True %}
<div class="alert alert-danger" role="alert">
<strong>WARNING:</strong> This day already has a special schedule stored. Doing anything on this page will overwrite any existing special schedule for {{edit_date}}</div>
{% endif %}
<h1>Edit Schedules <small>{{edit_date}}</small>
</h1>
</div>
</div>
<div id="center">
<table class="table table-striped">
<thead>
<tr>
<td><h5>Block</h5></td>
<td><h5>Start Time</h5></td>
<td><h5>End Time</h5></td>
<td><h5>Tooltip (opt.)</h5></td>
</tr>
</thead>
<form class="form-horizontal" role="form" method="post">
<tbody>
{% for i in range(0, blocks) %}
<tr>
<td><input type="text" class="form control" placeholder="Block Name" name="name{{i}}"></td>
<td><input type="time" class="form control" placeholder="Start Time" name="start{{i}}"></td>
<td><input type="time" class="form control" placeholder="End Time" name="end{{i}}"></td>
<td><input type="text" class="form control" placeholder="Tooltip" name="tooltip{{i}}"></td>
</tr>
{% endfor %}
<div class="row">
</div>
<div class="col-md-3 col-md-offset-9">
<a class="btn btn-default" href="/admin" role="button">Cancel</a>
{% if is_special == True %}
<button type="submit" class="btn btn-danger">Save and Overwrite</button>
{% else %}
<button type="submit" class="btn btn-primary">Save</button>
{% endif %}
</div>
</tbody>
</form>
</table>
</div>
{% endblock %} |
<!doctype html>
<!--#if expr="$HTTP_COOKIE=/fonts\-loaded\=true/" -->
<html lang="en-GB" class="fonts-loaded">
<!--#else -->
<html lang="en-GB">
<!--#endif -->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1"/>
<meta name="format-detection" content="telephone=no">
<meta name="author" content="Jaywing"/>
<title>Base | Atomic: Core</title>
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<link rel="stylesheet" href="https://jaywing.github.io/atomic-framework/css/app.css">
<script>if(document.documentElement){document.documentElement.classList.add('js');}</script>
</head>
<body id="top" class="o-site u-scroll-y">
<a href="#content" class="c-skip-link">Skip to content</a>
<header class="o-site__header t-global-header">
<a href="#content" class="c-skip-link c-button ">
<span class='o-icon o-icon--arrow-down '>
<svg viewBox="0 0 1 1"><use xlink:href='https://jaywing.github.io/atomic-framework/images/icons.svg#arrow-down'></use></svg>
</span>
Skip to content</a>
<nav class="o-container o-container--centered o-container--fluid c-nav-responsive c-nav-responsive@md">
<button class="c-toggle-button c-toggle-button--hideText" data-module="Toggle" data-options='{"target":"parent"}'>
<div class="c-toggle-button__init">
<span class='o-icon o-icon--navicon c-toggle-button-icon--init'>
<svg viewBox="0 0 1 1"><use xlink:href='https://jaywing.github.io/atomic-framework/images/icons.svg#navicon'></use></svg>
</span>
<span class="c-toggle-button__text">Menu</span>
</div>
<div class="c-toggle-button__close">
<span class='o-icon o-icon--close c-toggle-button-icon--close'>
<svg viewBox="0 0 1 1"><use xlink:href='https://jaywing.github.io/atomic-framework/images/icons.svg#close'></use></svg>
</span>
<span class="c-toggle-button__text">Close</span>
</div>
</button>
<ul class="c-menu c-menu--vertical c-menu@md">
<li class="c-menu__item c-menu__item--left w-logo">
<a href="https://jaywing.github.io/atomic-framework/">
<img src="https://jaywing.github.io/atomic-framework/images/jaywing-logo.svg" alt="Jaywing">
</a>
</li>
<li class="c-menu__item is-active">
<a href="https://jaywing.github.io/atomic-framework/docs/core" class="c-menu__link">Core</a>
</li>
<li class="c-menu__item">
<a href="https://jaywing.github.io/atomic-framework/docs/extended" class="c-menu__link">Extended</a>
</li>
<li class="c-menu__item">
<a class="c-menu__link is-disabled" disabled>Roadmap</a>
</li>
</ul>
</nav>
</header>
<main id="content" class="o-site__content">
<div class="o-container o-container--centered o-container--fluid">
<div class="o-flex-grid o-flex-grid@md--gutters o-flex-grid@xl--gutters@xl" data-module="Sticky" data-sticky-container>
<section class="o-flex-grid__cell o-size--full o-size@md--3 c-sidebar">
<nav id="t-page-nav" class="c-sidenav c-Sticky__item@md c-nav-responsive c-nav-responsive@md" data-margin-top="20">
<button class="c-toggle-button c-toggle-button--hideText" data-module="Toggle" data-options='{"target":"parent"}'>
<div class="c-toggle-button__init">
<span class='o-icon o-icon--navicon c-toggle-button-icon--init'>
<svg viewBox="0 0 1 1"><use xlink:href='https://jaywing.github.io/atomic-framework/images/icons.svg#navicon'></use></svg>
</span>
<span class="c-toggle-button__text">Menu</span>
</div>
<div class="c-toggle-button__close">
<span class='o-icon o-icon--close c-toggle-button-icon--close'>
<svg viewBox="0 0 1 1"><use xlink:href='https://jaywing.github.io/atomic-framework/images/icons.svg#close'></use></svg>
</span>
<span class="c-toggle-button__text">Close</span>
</div>
</button>
<ul class="c-menu c-menu--flush c-menu--vertical">
<li class="c-menu__item c-sidenav__title">
<strong class="c-menu__link c-menu__title">What's inside</strong>
</li>
<li class="c-menu__item">
<strong class="c-menu__title">Defaults</strong>
<ul class="c-menu c-menu--vertical c-menu--flush">
<li class="c-menu__item is-active">
<a href="base.html" class="c-menu__link">Base</a>
</li>
<li class="c-menu__item">
<a href="breakpoints.html" class="c-menu__link">Breakpoints</a>
</li>
<li class="c-menu__item">
<a href="font-sizes.html" class="c-menu__link">Font sizes</a>
</li>
<li class="c-menu__item">
<a href="print.html" class="c-menu__link">Print</a>
</li>
</ul>
</li>
<li class="c-menu__item">
<strong class="c-menu__title">Objects</strong>
<ul class="c-menu c-menu--vertical c-menu--flush">
<li class="c-menu__item">
<a href="site.html" class="c-menu__link">Site</a>
</li>
<li class="c-menu__item">
<a href="container.html" class="c-menu__link">Container</a>
</li>
<li class="c-menu__item">
<a href="flex-grid.html" class="c-menu__link">Flexbox Grid</a>
</li>
<li class="c-menu__item">
<a class="c-menu__link c-text--disabled">Grid</a>
</li>
<li class="c-menu__item">
<a href="size.html" class="c-menu__link">Size</a>
</li>
<li class="c-menu__item">
<a href="section.html" class="c-menu__link">Section</a>
</li>
<li class="c-menu__item">
<a href="media.html" class="c-menu__link">Media</a>
</li>
<li class="c-menu__item">
<a href="cover.html" class="c-menu__link">Cover</a>
</li>
</ul>
</li>
<li class="c-menu__item">
<strong class="c-menu__title">Components</strong>
<ul class="c-menu c-menu--vertical c-menu--flush">
<li class="c-menu__item">
<a href="accordion-menu.html" class="c-menu__link">Accordion Menu</a>
</li>
<li class="c-menu__item">
<a href="back-to-top.html" class="c-menu__link">Back to top</a>
</li>
<li class="c-menu__item">
<a href="badge.html" class="c-menu__link">Badge</a>
</li>
<li class="c-menu__item">
<a href="breadcrumbs.html" class="c-menu__link">Breadcrumbs</a>
</li>
<li class="c-menu__item">
<a href="button.html" class="c-menu__link">Button</a>
</li>
<li class="c-menu__item">
<a href="close.html" class="c-menu__link">Close</a>
</li>
<li class="c-menu__item">
<a href="definition.html" class="c-menu__link">Definition</a>
</li>
<li class="c-menu__item">
<a href="dropdown-menu.html" class="c-menu__link">Dropdown Menu</a>
</li>
<li class="c-menu__item">
<a href="form.html" class="c-menu__link">Form</a>
</li>
<li class="c-menu__item">
<a href="hamburger.html" class="c-menu__link">Hamburger</a>
</li>
<li class="c-menu__item">
<a href="icon.html" class="c-menu__link">Icon</a>
</li>
<li class="c-menu__item">
<a href="list.html" class="c-menu__link">List</a>
</li>
<li class="c-menu__item">
<a href="overlay.html" class="c-menu__link">Overlay</a>
</li>
<li class="c-menu__item">
<a href="panel.html" class="c-menu__link">Panel</a>
</li>
<li class="c-menu__item">
<a href="skip-link.html" class="c-menu__link">Skip link</a>
</li>
<li class="c-menu__item">
<a href="table.html" class="c-menu__link">Table</a>
</li>
<li class="c-menu__item">
<a href="text.html" class="c-menu__link">Text</a>
</li>
<li class="c-menu__item">
<a href="tooltip.html" class="c-menu__link">Tooltip</a>
</li>
<li class="c-menu__item">
<a href="menu.html" class="c-menu__link">Menu</a>
</li>
</ul>
</li>
<li class="c-menu__item">
<strong class="c-menu__title">Modules</strong>
<ul class="c-menu c-menu--vertical c-menu--flush">
<li class="c-menu__item">
<a href="anchor.html" class="c-menu__link">Anchor</a>
</li>
<li class="c-menu__item">
<a href="breakpoint-mod.html" class="c-menu__link">Breakpoint</a>
</li>
<li class="c-menu__item">
<a href="helpers.html" class="c-menu__link">Helpers</a>
</li>
<li class="c-menu__item">
<a class="c-menu__link c-text--disabled">Load Image</a>
</li>
<li class="c-menu__item">
<a href="slider.html" class="c-menu__link">Slider</a>
</li>
<li class="c-menu__item">
<a href="switcher.html" class="c-menu__link">Switcher</a>
</li>
<li class="c-menu__item">
<a href="toggle.html" class="c-menu__link">Toggle</a>
</li>
<li class="c-menu__item">
<a class="c-menu__link c-text--disabled">Validate</a>
</li>
</ul>
</li>
</ul>
</nav>
</section>
<article class="o-flex-grid__cell o-size@md--9 o-size@xl--8 c-content">
<h1 class="Article-title">Base</h1>
<p class="c-text--lead">Provides the default style for all HTML elements.</p>
<p><strong>Version:</strong> </p>
<p>This component defines the base look of your page. It offers great typography by setting the default colors, margins, font-sizes and more for each HTML element. This page is a short guide on how to use basic HTML elements and how Atomic styles them.</p>
<hr class="Article-divider">
<h2 id="section:headings"><a href="#section:headings" class="c-text--resetLink">Headings</a></h2>
<p>Use the <code><h1></code> to <code><h6></code> elements to define your headings.</p>
<div class="c-example">
<h1>h1 Trafalgar</h1>
<h2>h2 Double pica</h2>
<h3>h3 Great primer</h3>
<h4>h4 Pica</h4>
<h5>h5 Brevier bold</h5>
<h6>h6 Brevier</h6>
</div>
<h3>Small header segments</h3>
<p>By inserting a <code><small></code> element into a header Foundation will scale the header font size down for an inline element, allowing you to use this for subtitles or other secondary header text.</p>
<div class="c-example">
<h1>Atomic by Jaywing <small>- Version 3.0.0</small></h1>
</div>
<hr class="Article-divider">
<h2 id="section:paragraphs"><a href="#section:paragraphs" class="c-text--resetLink">Paragraphs</a></h2>
<div class="c-example">
<p>The global font-size, line-height and regular margins between elements are set through variables, which can be customized. Paragraphs and other block elements stick to these values.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus corporis cupiditate deleniti illo incidunt iste molestiae quam quia, quidem sapiente sit voluptate! Aut ipsa iste nesciunt praesentium quisquam repudiandae tenetur.</p>
</div>
<hr class="Article-divider">
<h2 id="section:text-level-semantics"><a href="#section:text-level-semantics" class="c-text--resetLink">c-text Level Semantics</a></h2>
<p>The following list gives you a short overview of the most commonly used text-level semantics and how to utilize them.</p>
<div class="c-example">
<div class="o-container o-container--fluid o-container--collapse o-container--overflow">
<table class="c-table c-table--hover c-table--condensed textNoWrap">
<thead>
<tr>
<th class="width--1-4">Element</th>
<th class="width--3-4">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code><a></code></td>
<td>Turn text into hypertext using the <a href="#">a element</a>.</td>
</tr>
<tr>
<td><code><em></code></td>
<td>Emphasize text using the <em>em element</em>.</td>
</tr>
<tr>
<td><code><strong></code></td>
<td>Imply any extra importance using the <strong>strong element</strong>.</td>
</tr>
<tr>
<td><code><code></code></td>
<td>Define inline code snippets using the <code>code element</code>.</td>
</tr>
<tr>
<td><code><del></code></td>
<td>Mark document changes as deleted text using the <del>del element</del>.</td>
</tr>
<tr>
<td><code><ins></code></td>
<td>Mark document changes as inserted text using the <ins>ins element</ins>.</td>
</tr>
<tr>
<td><code><mark></code></td>
<td>Highlight text with no semantic meaning using the <mark>mark element</mark>.</td>
</tr>
<tr>
<td><code><q></code></td>
<td>Define inline quotations using <q>q element <q>inside</q> a q element</q>.</td>
</tr>
<tr>
<td><code><abbr></code></td>
<td>Define an abbreviation using the <abbr title="Abbreviation Element">abbr element</abbr> with a title.</td>
</tr>
<tr>
<td><code><dfn></code></td>
<td>Define a definition term using the <dfn title="Defines a definition term">dfn element</dfn> with a title.</td>
</tr>
<tr>
<td><code><small></code></td>
<td>De-emphasize text for small print using the <small>small element</small>.</td>
</tr>
</tbody>
</table>
</div>
</div>
<hr class="Article-divider">
<h2 id="section:horizontal-rule"><a href="#section:horizontal-rule" class="c-text--resetLink">Horizontal rule</a></h2>
<p>Create a horizontal rule by using the <code><hr></code> element.</p>
<div class="c-example">
<hr>
</div>
<hr class="Article-divider">
<h2 id="section:blockquotes"><a href="#section:blockquotes" class="c-text--resetLink">Blockquotes</a></h2>
<p>For quoting multiple lines of content from another source within your document, use the <code><blockquote></code> element.</p>
<div class="c-example">
<blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p>
<cite>Someone famous</cite>
</blockquote>
</div>
<hr class="Article-divider">
<h2 id="section:lists"><a href="#section:lists" class="c-text--resetLink">Lists</a></h2>
<p>Create an unordered list using the <code><ul></code> element and the <code><ol></code> element for ordered lists. The <code><li></code> element defines the list item.</p>
<div class="c-example">
<ul>
<li>Item 1</li>
<li>Item 2
<ul>
<li>Item 1</li>
<li>Item 2
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</li>
</ul>
</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
<ol>
<li>Item 1</li>
<li>Item 2
<ol>
<li>Item 1</li>
<li>Item 2
<ol>
<li>Item 1</li>
<li>Item 2</li>
</ol>
</li>
</ol>
</li>
<li>Item 3</li>
<li>Item 4</li>
</ol>
</div>
<hr class="Article-divider">
<h2 id="section:definition-lists"><a href="#section:definition-lists" class="c-text--resetLink">Definition lists</a></h2>
<p>Create a description list using the <code><dl></code> element. Use <code><dt></code> to define the term and <code><dd></code> for the description.</p>
<div class="c-example">
<dl>
<dt>Description lists</dt>
<dd>A description list defines terms and their corresponding descriptions.</dd>
<dt>This is a term</dt>
<dd>This is a description.</dd>
<dt>This is a term</dt>
<dd>This is a description.</dd>
</dl>
</div>
<hr class="Article-divider">
<h2 id="section:fluid-images"><a href="#section:fluid-images" class="c-text--resetLink">Fluid images</a></h2>
<p>All images are fluid by default. If the layout is narrowed, images adjust their size and keep their proportions. Images shouldn't stretch to bigger than their natural size.</p>
<div class="c-example">
<img src="/images/placeholder/img_480x260.svg" alt="">
</div>
<hr class="Article-divider">
<h2 id="section:code-blocks"><a href="#section:code-blocks" class="c-text--resetLink">Code blocks</a></h2>
<p>For multiple lines of code, use the <code><pre></code> element which defines preformatTed text. It creates a new text block that preserves spaces, tabs and line breaks. Nest a <code><code></code> element inside to define the code block.</p>
<p><span class="c-badge">IMPORTANT</span> Be sure to escape any angle brackets in the code for proper rendering.</p>
<div class="c-example">
<pre><code class="xml"><pre>
<code>...</code>
</pre></code></pre>
</div>
</article>
</div>
</div>
</main>
<footer class="o-site__footer t-footer">
<div class="o-container o-container--centered o-container--fluid">
<p>© Made with ♥ at <a href="http://jaywing.com">Jaywing</a>. <small>v3.0.0</small></p>
</div>
</footer>
<script src="https://jaywing.github.io/atomic-framework/js/app.js" async></script>
</body>
</html>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.