code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
class DefaultColor(object):
"""
This class should have the default colors for every segment.
Please test every new segment with this theme first.
"""
# RESET is not a real color code. It is used as in indicator
# within the code that any foreground / background color should
# be cleared
RESET = -1
USERNAME_FG = 250
USERNAME_BG = 240
USERNAME_ROOT_BG = 124
HOSTNAME_FG = 250
HOSTNAME_BG = 238
HOME_SPECIAL_DISPLAY = True
HOME_BG = 31 # blueish
HOME_FG = 15 # white
PATH_BG = 237 # dark grey
PATH_FG = 250 # light grey
CWD_FG = 254 # nearly-white grey
SEPARATOR_FG = 244
READONLY_BG = 124
READONLY_FG = 254
SSH_BG = 166 # medium orange
SSH_FG = 254
REPO_CLEAN_BG = 148 # a light green color
REPO_CLEAN_FG = 0 # black
REPO_DIRTY_BG = 161 # pink/red
REPO_DIRTY_FG = 15 # white
JOBS_FG = 39
JOBS_BG = 238
CMD_PASSED_BG = 236
CMD_PASSED_FG = 15
CMD_FAILED_BG = 161
CMD_FAILED_FG = 15
SVN_CHANGES_BG = 148
SVN_CHANGES_FG = 22 # dark green
GIT_AHEAD_BG = 240
GIT_AHEAD_FG = 250
GIT_BEHIND_BG = 240
GIT_BEHIND_FG = 250
GIT_STAGED_BG = 22
GIT_STAGED_FG = 15
GIT_NOTSTAGED_BG = 130
GIT_NOTSTAGED_FG = 15
GIT_UNTRACKED_BG = 52
GIT_UNTRACKED_FG = 15
GIT_CONFLICTED_BG = 9
GIT_CONFLICTED_FG = 15
GIT_STASH_BG = 221
GIT_STASH_FG = 0
VIRTUAL_ENV_BG = 35 # a mid-tone green
VIRTUAL_ENV_FG = 00
BATTERY_NORMAL_BG = 22
BATTERY_NORMAL_FG = 7
BATTERY_LOW_BG = 196
BATTERY_LOW_FG = 7
AWS_PROFILE_FG = 39
AWS_PROFILE_BG = 238
TIME_FG = 250
TIME_BG = 238
class Color(DefaultColor):
"""
This subclass is required when the user chooses to use 'default' theme.
Because the segments require a 'Color' class for every theme.
"""
pass
|
banga/powerline-shell
|
powerline_shell/themes/default.py
|
Python
|
mit
| 1,896 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const schematics_1 = require("@angular-devkit/schematics");
const ast_1 = require("../utils/ast");
const component_1 = require("../utils/devkit-utils/component");
/**
* Scaffolds a new navigation component.
* Internally it bootstraps the base component schematic
*/
function default_1(options) {
return schematics_1.chain([
component_1.buildComponent(Object.assign({}, options)),
options.skipImport ? schematics_1.noop() : addNavModulesToModule(options)
]);
}
exports.default = default_1;
/**
* Adds the required modules to the relative module.
*/
function addNavModulesToModule(options) {
return (host) => {
const modulePath = ast_1.findModuleFromOptions(host, options);
ast_1.addModuleImportToModule(host, modulePath, 'LayoutModule', '@angular/cdk/layout');
ast_1.addModuleImportToModule(host, modulePath, 'MatToolbarModule', '@angular/material');
ast_1.addModuleImportToModule(host, modulePath, 'MatButtonModule', '@angular/material');
ast_1.addModuleImportToModule(host, modulePath, 'MatSidenavModule', '@angular/material');
ast_1.addModuleImportToModule(host, modulePath, 'MatIconModule', '@angular/material');
ast_1.addModuleImportToModule(host, modulePath, 'MatListModule', '@angular/material');
return host;
};
}
//# sourceMappingURL=index.js.map
|
friendsofagape/mt2414ui
|
node_modules/@angular/material/schematics/nav/index.js
|
JavaScript
|
mit
| 1,432 |
import { RouteHandler } from './route_handler';
import { Type } from 'angular2/src/facade/lang';
export declare class AsyncRouteHandler implements RouteHandler {
private _loader;
_resolvedComponent: Promise<any>;
componentType: Type;
constructor(_loader: Function);
resolveComponentType(): Promise<any>;
}
|
anttisirkiafuturice/angular2todo
|
node_modules/angular2/src/router/async_route_handler.d.ts
|
TypeScript
|
mit
| 335 |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2000,2008 Oracle. All rights reserved.
*
* $Id: ShortBinding.java,v 12.7 2008/01/08 20:58:36 bostic Exp $
*/
package com.sleepycat.bind.tuple;
import com.sleepycat.db.DatabaseEntry;
/**
* A concrete <code>TupleBinding</code> for a <code>Short</code> primitive
* wrapper or a <code>short</code> primitive.
*
* <p>There are two ways to use this class:</p>
* <ol>
* <li>When using the {@link com.sleepycat.db} package directly, the static
* methods in this class can be used to convert between primitive values and
* {@link DatabaseEntry} objects.</li>
* <li>When using the {@link com.sleepycat.collections} package, an instance of
* this class can be used with any stored collection. The easiest way to
* obtain a binding instance is with the {@link
* TupleBinding#getPrimitiveBinding} method.</li>
* </ol>
*/
public class ShortBinding extends TupleBinding {
private static final int SHORT_SIZE = 2;
// javadoc is inherited
public Object entryToObject(TupleInput input) {
return new Short(input.readShort());
}
// javadoc is inherited
public void objectToEntry(Object object, TupleOutput output) {
output.writeShort(((Number) object).shortValue());
}
// javadoc is inherited
protected TupleOutput getTupleOutput(Object object) {
return sizedOutput();
}
/**
* Converts an entry buffer into a simple <code>short</code> value.
*
* @param entry is the source entry buffer.
*
* @return the resulting value.
*/
public static short entryToShort(DatabaseEntry entry) {
return entryToInput(entry).readShort();
}
/**
* Converts a simple <code>short</code> value into an entry buffer.
*
* @param val is the source value.
*
* @param entry is the destination entry buffer.
*/
public static void shortToEntry(short val, DatabaseEntry entry) {
outputToEntry(sizedOutput().writeShort(val), entry);
}
/**
* Returns a tuple output object of the exact size needed, to avoid
* wasting space when a single primitive is output.
*/
private static TupleOutput sizedOutput() {
return new TupleOutput(new byte[SHORT_SIZE]);
}
}
|
djsedulous/namecoind
|
libs/db-4.7.25.NC/java/src/com/sleepycat/bind/tuple/ShortBinding.java
|
Java
|
mit
| 2,314 |
# --- nitro-js
npmdir = $(shell npm bin)
whoami = $(shell whoami)
git_branch := $(shell git rev-parse --abbrev-ref HEAD)
# TASKS
install:
npm install
test:
@$(npmdir)/mocha tests
npm.publish:
git pull --tags
npm version patch
git push origin $(git_branch)
git push --tags
npm publish
@echo "published ${PKG_VERSION}"s
github.release: export PKG_NAME=$(shell node -e "console.log(require('./package.json').name);")
github.release: export PKG_VERSION=$(shell node -e "console.log('v'+require('./package.json').version);")
github.release: export RELEASE_URL=$(shell curl -s -X POST -H "Content-Type: application/json" -H "Authorization: Bearer ${GITHUB_TOKEN}" \
-d '{"tag_name": "${PKG_VERSION}", "target_commitish": "$(git_branch)", "name": "${PKG_VERSION}", "body": "", "draft": false, "prerelease": false}' \
-w '%{url_effective}' "https://api.github.com/repos/nitrojs/${PKG_NAME}/releases" )
github.release:
@echo ${RELEASE_URL}
@true
release: install test npm.publish github.release
# DEFAULT TASKS
.DEFAULT_GOAL := test
|
nitrojs/nitro
|
Makefile
|
Makefile
|
mit
| 1,046 |
<?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 [email protected] 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_Bundle
* @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
require_once 'Mage/Bundle/controllers/Adminhtml/Bundle/SelectionController.php';
/**
* Adminhtml selection grid controller
*
* @category Mage
* @package Mage_Bundle
* @author Magento Core Team <[email protected]>
* @deprecated after 1.4.2.0 Mage_Bundle_Adminhtml_Bundle_SelectionController is used
*/
class Mage_Bundle_SelectionController extends Mage_Bundle_Adminhtml_Bundle_SelectionController
{
}
|
fabiensebban/magento
|
app/code/core/Mage/Bundle/controllers/SelectionController.php
|
PHP
|
mit
| 1,390 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Type definition type_info</title>
<link rel="stylesheet" href="http://www.boost.org/doc/libs/1_53_0/doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.TypeIndex 4.0">
<link rel="up" href="../../boost_typeindex_header_reference.html#header.boost.type_index_hpp" title="Header <boost/type_index.hpp>">
<link rel="prev" href="type_index.html" title="Type definition type_index">
<link rel="next" href="type_id.html" title="Function template type_id">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="http://www.boost.org/doc/libs/1_53_0/boost.png"></td>
<td align="center"><a href="http://www.boost.org/doc/libs/1_53_0/index.html">Home</a></td>
<td align="center"><a href="http://www.boost.org/doc/libs/1_53_0/libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="http://www.boost.org/doc/libs/1_53_0/more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="type_index.html"><img src="http://www.boost.org/doc/libs/1_53_0/doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_typeindex_header_reference.html#header.boost.type_index_hpp"><img src="http://www.boost.org/doc/libs/1_53_0/doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="http://www.boost.org/doc/libs/1_53_0/doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="type_id.html"><img src="http://www.boost.org/doc/libs/1_53_0/doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.typeindex.type_info"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Type definition type_info</span></h2>
<p>type_info</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../boost_typeindex_header_reference.html#header.boost.type_index_hpp" title="Header <boost/type_index.hpp>">boost/type_index.hpp</a>>
</span>
<span class="keyword">typedef</span> <span class="identifier">type_index</span><span class="special">::</span><span class="identifier">type_info_t</span> <span class="identifier">type_info</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp5898736"></a><h2>Description</h2>
<p>Depending on a compiler flags, optimal implementation of type_info will be used as a default boost::typeindex::type_info.</p>
<p>Could be a std::type_info, boost::typeindex::detail::ctti_data or some user defined class.</p>
<p>type_info <span class="bold"><strong>is</strong></span> <span class="bold"><strong>not</strong></span> copyable or default constructible. It is <span class="bold"><strong>not</strong></span> assignable too! </p>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2012-2014 Antony Polukhin<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="type_index.html"><img src="http://www.boost.org/doc/libs/1_53_0/doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_typeindex_header_reference.html#header.boost.type_index_hpp"><img src="http://www.boost.org/doc/libs/1_53_0/doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="http://www.boost.org/doc/libs/1_53_0/doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="type_id.html"><img src="http://www.boost.org/doc/libs/1_53_0/doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
yinchunlong/abelkhan-1
|
ext/c++/thirdpart/c++/boost/libs/type_index/doc/html/boost/typeindex/type_info.html
|
HTML
|
mit
| 4,510 |
require File.dirname(__FILE__) + "/helper"
class NotStrictEqualNodeTest < NodeTestCase
def test_to_sexp
node = NotStrictEqualNode.new(NumberNode.new(5), NumberNode.new(10))
assert_sexp([:not_strict_equal, [:lit, 5], [:lit, 10]], node)
end
end
|
tobie/modulr
|
vendor/rkelly/test/test_not_strict_equal_node.rb
|
Ruby
|
mit
| 256 |
<div class="map-panel" ><pre class="language-javascript"><code class="language-javascript">
var map = new mapTools({
id: 'mymap',
lat: 41.3833,
lng: 2.1833,
type: 'ROADMAP',
on: {
zoom_changed: function() {
console.log('the zoom level has changed!', map.zoom())
}
}
}, function (err, map) {
console.log('Map Loaded!', map.instance);
});
</code></pre></div>
|
pjakobsen/map-tools
|
examples/code.snippet/simple.map.snippet.html
|
HTML
|
mit
| 387 |
<div class="tab-pane fade" id="tab-contact-numbers">
<h1>contact numbers</h1>
<p>lorem</p>
</div>
|
lohicasoft/KAWANI_CI
|
application/views/modals/employee/forms/edit/modal-contact-numbers.php
|
PHP
|
mit
| 106 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.Rule
{
#region Namespaces
using System;
using System.ComponentModel.Composition;
using System.Xml.Linq;
using Newtonsoft.Json.Linq;
using ODataValidator.Rule.Helper;
using ODataValidator.RuleEngine;
#endregion
/// <summary>
/// Class of entension rule for Rule #295
/// </summary>
[Export(typeof(ExtensionRule))]
public class PropertyCore2005 : ExtensionRule
{
/// <summary>
/// Gets Categpry property
/// </summary>
public override string Category
{
get
{
return "core";
}
}
/// <summary>
/// Gets rule name
/// </summary>
public override string Name
{
get
{
return "Property.Core.2005";
}
}
/// <summary>
/// Gets rule description
/// </summary>
public override string Description
{
get
{
return @"A collection of EDMSimpleType values MUST be represented as an array of JSON primitives.";
}
}
/// <summary>
/// Gets rule specification in OData document
/// </summary>
public override string SpecificationSection
{
get
{
return "2.2.6.3.7";
}
}
/// <summary>
/// Gets location of help information of the rule
/// </summary>
public override string HelpLink
{
get
{
return null;
}
}
/// <summary>
/// Gets the error message for validation failure
/// </summary>
public override string ErrorMessage
{
get
{
return this.Description;
}
}
/// <summary>
/// Gets the requriement level.
/// </summary>
public override RequirementLevel RequirementLevel
{
get
{
return RequirementLevel.Must;
}
}
/// <summary>
/// Gets the payload type to which the rule applies.
/// </summary>
public override PayloadType? PayloadType
{
get
{
return RuleEngine.PayloadType.Property;
}
}
/// <summary>
/// Gets the payload format to which the rule applies.
/// </summary>
public override PayloadFormat? PayloadFormat
{
get
{
return RuleEngine.PayloadFormat.Json;
}
}
/// <summary>
/// Gets the flag whether it requires metadata document or not
/// </summary>
public override bool? RequireMetadata
{
get
{
return true;
}
}
/// <summary>
/// Gets the flag whether this rule applies to offline context or not
/// </summary>
public override bool? IsOfflineContext
{
get
{
return false;
}
}
/// <summary>
/// Gets the flag whether this rule applies to projected query or not
/// </summary>
public override bool? Projection
{
get
{
return false;
}
}
/// <summary>
/// Verify the code rule
/// </summary>
/// <param name="context">Service context</param>
/// <param name="info">out paramater to return violation information when rule fail</param>
/// <returns>true if rule passes; false otherwise</returns>
public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
bool? passed = null;
info = null;
var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
var segments = ResourcePathHelper.GetPathSegments(context);
UriType uriType;
var target = edmxHelper.GetTargetType(segments, out uriType);
// to check this rule only when returned resource is collection of EdmSimpleType
if (uriType == UriType.URI13)
{
JObject jo = JObject.Parse(context.ResponsePayload);
var version = JsonParserHelper.GetPayloadODataVersion(jo);
string jSchema = JsonSchemaHelper.WrapJsonSchema(coreSchema, version);
TestResult testResult;
passed = JsonParserHelper.ValidateJson(jSchema, context.ResponsePayload, out testResult);
if (passed.HasValue && !passed.Value)
{
info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, testResult != null ? testResult.LineNumberInError : -1);
}
}
return passed;
}
private const string coreSchema = @"
{
""type"":""array""
,""required"" : true
,""items"" : {""type"" : [""string"", ""number"", ""integer"", ""boolean"", ""null""]}
}
";
}
}
|
OData/ValidationTool
|
src/CodeRules/Property/PropertyCore2005.cs
|
C#
|
mit
| 5,785 |
#ifndef __VXTHREAD_H__
#define __VXTHREAD_H__
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Project: omniORB
%% Filename: $Filename$
%% Author: Guillaume/Bill ARRECKX
%% Copyright Wavetek Wandel & Goltermann, Plymouth.
%% Description: OMNI thread implementation classes for VxWorks threads
%% Notes:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*/
///////////////////////////////////////////////////////////////////////////
// Includes
///////////////////////////////////////////////////////////////////////////
#include <vxWorks.h>
#include <semLib.h>
#include <taskLib.h>
///////////////////////////////////////////////////////////////////////////
// Externs prototypes
///////////////////////////////////////////////////////////////////////////
extern "C" void omni_thread_wrapper(void* ptr);
///////////////////////////////////////////////////////////////////////////
// Exported macros
// Note: These are added as private members in each class implementation.
///////////////////////////////////////////////////////////////////////////
#define OMNI_MUTEX_IMPLEMENTATION \
SEM_ID mutexID; \
bool m_bConstructed;
#define OMNI_CONDITION_IMPLEMENTATION \
SEM_ID sema_;
#define OMNI_SEMAPHORE_IMPLEMENTATION \
SEM_ID semID;
#define OMNI_MUTEX_LOCK_IMPLEMENTATION \
if(semTake(mutexID, WAIT_FOREVER) != OK) \
{ \
throw omni_thread_fatal(errno); \
}
#define OMNI_MUTEX_TRYLOCK_IMPLEMENTATION \
return semTake(mutexID, NO_WAIT) == OK;
#define OMNI_MUTEX_UNLOCK_IMPLEMENTATION \
if(semGive(mutexID) != OK) \
{ \
throw omni_thread_fatal(errno); \
}
#define OMNI_THREAD_IMPLEMENTATION \
friend void omni_thread_wrapper(void* ptr); \
static int vxworks_priority(priority_t); \
omni_condition *running_cond; \
void* return_val; \
int tid; \
public: \
static void attach(void); \
static void detach(void); \
static void show(void);
///////////////////////////////////////////////////////////////////////////
// Porting macros
///////////////////////////////////////////////////////////////////////////
// This is a wrapper function for the 'main' function which does not exists
// as such in VxWorks. The wrapper creates a launch function instead,
// which spawns the application wrapped in a omni_thread.
// Argc will always be null.
///////////////////////////////////////////////////////////////////////////
#define main( discarded_argc, discarded_argv ) \
omni_discard_retval() \
{ \
throw; \
} \
int omni_main( int argc, char **argv ); \
void launch( ) \
{ \
omni_thread* th = new omni_thread( (void(*)(void*))omni_main );\
th->start();\
}\
int omni_main( int argc, char **argv )
#endif // ndef __VXTHREAD_H__
|
amonmoce/corba_examples
|
omniORB-4.2.1/include/omnithread/VxThread.h
|
C
|
mit
| 2,920 |
.ORIG x3000
AND R1, R1, #0
ADD R2, R1, #1
ADD R2, R2, R2
ADD R2, R1, #1
ADD R2, R2, R2
ADD R2, R1, #1
ADD R2, R2, R2
ADD R2, R1, #1
ADD R2, R2, R2
ADD R2, R1, #1
ADD R2, R2, R2
ADD R2, R1, #1
ADD R2, R2, R2
ADD R2, R1, #1
ADD R2, R2, R2
ADD R2, R1, #1
ADD R2, R2, R2
ADD R2, R1, #1
ADD R3, R2, R2
AND R2, R2, #7
ADD R4, R3, R3
AND R4, R4, R2
HALT
.END
|
Zaydax/PipelineProcessor
|
lab3_test_harness/Lab1test/and.asm
|
Assembly
|
mit
| 376 |
# -*- coding: utf-8 -*-
#
# pyOlog documentation build configuration file, created by
# sphinx-quickstart on Sat Nov 29 06:14:28 2014.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('../'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.mathjax']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'pyOlog'
copyright = u'2014, Kunal Schroff, Stuart Wilkins'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.2'
# The full version, including alpha/beta/rc tags.
release = '0.2.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'agogo'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'pyOlogdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'pyOlog.tex', u'pyOlog Documentation',
u'Kunal Schroff, Stuart Wilkins', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'pyolog', u'pyOlog Documentation',
[u'Kunal Schroff, Stuart Wilkins'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'pyOlog', u'pyOlog Documentation',
u'Kunal Schroff, Stuart Wilkins', 'pyOlog', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
|
tacaswell/pyOlog
|
doc/conf.py
|
Python
|
mit
| 7,888 |
/*
win32 app data type
Created July 1994, Mark Hammond ([email protected])
Note that this source file contains embedded documentation.
This documentation consists of marked up text inside the
C comments, and is prefixed with an '@' symbol. The source
files are processed by a tool called "autoduck" which
generates Windows .hlp files.
@doc
*/
#include "stdafx.h"
#include "win32ui.h"
#include "win32doc.h"
#include "win32template.h"
extern CWnd *GetWndPtr(PyObject *self);
PyObject *PyCWinApp::pExistingAppObject = NULL;
char *errmsgAlreadyInit = "The application has already been initialised";
/////////////////////////////////////////////////////////////////////
//
// CProtectedWinApp Application helpers.
//
//////////////////////////////////////////////////////////////////////
int CProtectedWinApp::GetRecentCount()
{
return m_pRecentFileList->GetSize();
}
CString CProtectedWinApp::GetRecentFileName(int index)
{
if (index>=0 && index < _AFX_MRU_MAX_COUNT) {
return (*m_pRecentFileList)[index];
}
else {
ASSERT(0);
return CString();
}
}
void CProtectedWinApp::RemoveRecentFile(int index)
{
if (index>=0 && index < _AFX_MRU_MAX_COUNT) {
m_pRecentFileList->Remove(index);
}
}
PyObject *CProtectedWinApp::MakePyDocTemplateList()
{
PyObject *retList = PyList_New(0);
if (retList==NULL)
return NULL;
POSITION posTempl = m_pDocManager ? m_pDocManager->GetFirstDocTemplatePosition() : NULL;
while (posTempl) {
CDocTemplate* pTemplate = m_pDocManager->GetNextDocTemplate(posTempl);
ASSERT(pTemplate->IsKindOf(RUNTIME_CLASS(CDocTemplate)));
PyObject *newListItem = ui_assoc_object::make(PyCDocTemplate::type, pTemplate)->GetGoodRet();
if (newListItem==NULL) {
Py_DECREF(retList);
return NULL;
}
PyList_Append(retList, newListItem);
Py_DECREF(newListItem);
}
return retList;
}
// FindOpenDocument - if the C++ framework has a document with this name open,
// then return a pointer to it, else NULL.
CDocument *CProtectedWinApp::FindOpenDocument(const TCHAR *lpszFileName)
{
POSITION posTempl = m_pDocManager->GetFirstDocTemplatePosition();
CDocument* pOpenDocument = NULL;
TCHAR szPath[_MAX_PATH];
if (!AfxFullPath(szPath, lpszFileName))
_tcscpy(szPath, lpszFileName);
while (posTempl) {
CDocTemplate* pTemplate = m_pDocManager->GetNextDocTemplate(posTempl);
ASSERT(pTemplate->IsKindOf(RUNTIME_CLASS(CDocTemplate)));
// go through all documents
POSITION posDoc = pTemplate->GetFirstDocPosition();
while (posDoc) {
CDocument* pDoc = pTemplate->GetNextDoc(posDoc);
if (lstrcmpi(pDoc->GetPathName(), szPath) == 0)
return pDoc;
}
}
return NULL;
}
CProtectedDocManager *CProtectedWinApp::GetDocManager()
{
CProtectedDocManager *ret = (CProtectedDocManager *)m_pDocManager;
if (!ret->IsKindOf(RUNTIME_CLASS(CDocManager)))
RETURN_ERR("There is not a valid Document Manager");
return ret;
}
extern BOOL bDebuggerPumpStopRequested;
/////////////////////////////////////////////////////////////////////
//
// Application object
//
//////////////////////////////////////////////////////////////////////
PyCWinApp::PyCWinApp()
{
ASSERT(pExistingAppObject== NULL);
}
PyCWinApp::~PyCWinApp()
{
XDODECREF(pExistingAppObject);
pExistingAppObject = NULL;
}
// @pymethod |PyCWinApp|AddDocTemplate|Adds a template to the application list.
static PyObject *
ui_app_add_doc_template(PyObject *self, PyObject *args)
{
PyObject *obTemplate;
if (!PyArg_ParseTuple(args,"O:AddDocTemplate",
&obTemplate)) // @pyparm <o PyCDocTemplate>|template||The template to be added.
return NULL;
if (!ui_base_class::is_uiobject(obTemplate, &PyCDocTemplate::type))
RETURN_TYPE_ERR("The parameter must be a template object");
CDocTemplate *pTempl = PyCDocTemplate::GetTemplate(obTemplate);
if (pTempl==NULL)
return NULL;
CWinApp *pApp = GetApp();
if (!pApp) return NULL;
// walk all templates in the application looking for it.
CDocTemplate* pTemplate;
POSITION pos = pApp->m_pDocManager ? pApp->m_pDocManager->GetFirstDocTemplatePosition() : NULL;
while (pos != NULL) {
pTemplate = pApp->m_pDocManager->GetNextDocTemplate(pos);
if (pTemplate==pTempl)
RETURN_ERR("The template is already in the application list");
}
GUI_BGN_SAVE;
pApp->AddDocTemplate(pTempl);
GUI_END_SAVE;
RETURN_NONE;
}
// @pymethod |PyCWinApp|RemoveDocTemplate|Removes a template to the application list.
static PyObject *
ui_app_remove_doc_template(PyObject *self, PyObject *args)
{
// @comm Note that MFC does not provide an equivilent function.
PyObject *obTemplate;
if (!PyArg_ParseTuple(args,"O:RemoveDocTemplate",
&obTemplate)) // @pyparm <o PyCDocTemplate>|template||The template to be removed. Must have previously been added by <om PyCWinApp.AddDocTemplate>.
return NULL;
if (!ui_base_class::is_uiobject(obTemplate, &PyCDocTemplate::type))
RETURN_TYPE_ERR("The parameter must be a template object");
CDocTemplate *pTempl = PyCDocTemplate::GetTemplate(obTemplate);
if (pTempl==NULL)
return NULL;
GUI_BGN_SAVE;
BOOL ok = PyCDocTemplate::RemoveDocTemplateFromApp( pTempl );
GUI_END_SAVE;
if (!ok)
RETURN_ERR("The template is not in the application template list");
RETURN_NONE;
}
static PyObject *
ui_init_mdi_instance(PyObject *self, PyObject *args)
{
RETURN_NONE;
}
// @pymethod |PyCWinApp|OpenDocumentFile|Opens a document file by name.
static PyObject *
ui_open_document_file(PyObject *self, PyObject *args)
{
TCHAR *fileName;
PyObject *obfileName;
if (!PyArg_ParseTuple(args, "O:OpenDocumentFile",
&obfileName )) // @pyparm string|fileName||The name of the document to open.
return NULL;
if (!PyWinObject_AsTCHAR(obfileName, &fileName))
return NULL;
CWinApp *pApp = GetApp();
if (!pApp) return NULL;
if (((CProtectedWinApp *)pApp)->GetMainFrame()->GetSafeHwnd()==0)
RETURN_ERR("There is no main frame in which to create the document");
GUI_BGN_SAVE;
CDocument *pDoc = pApp->OpenDocumentFile(fileName);
GUI_END_SAVE;
PyWinObject_FreeTCHAR(fileName);
if (PyErr_Occurred())
return NULL;
if (pDoc==NULL)
RETURN_NONE;
return ui_assoc_object::make(PyCDocument::type, pDoc)->GetGoodRet();
}
// @pymethod <o PyCDocument>|PyCWinApp|FindOpenDocument|Returns an existing document with the specified file name.
static PyObject *
ui_find_open_document(PyObject *self, PyObject *args)
{
TCHAR *fileName;
PyObject *obfileName;
// @pyparm string|fileName||The fully qualified filename to search for.
if (!PyArg_ParseTuple(args,"O", &obfileName))
return NULL;
CProtectedWinApp *pApp = GetProtectedApp();
if (!pApp) return NULL;
if (!PyWinObject_AsTCHAR(obfileName, &fileName, FALSE))
return NULL;
// Let MFC framework search for a filename for us.
GUI_BGN_SAVE;
CDocument *pDoc=pApp->FindOpenDocument(fileName);
GUI_END_SAVE;
PyWinObject_FreeTCHAR(fileName);
if (pDoc==NULL)
RETURN_NONE;
return ui_assoc_object::make(PyCDocument::type, pDoc)->GetGoodRet();
}
// @pymethod <o PyCWinApp>|win32ui|GetApp|Retrieves the application object.
PyObject *
ui_get_app(PyObject *self, PyObject *args)
{
// @comm There will only ever be one application object per application.
CHECK_NO_ARGS2(args,GetApp);
CWinApp *pApp = GetApp();
if (pApp==NULL) return NULL;
return ui_assoc_object::make(PyCWinApp::type, pApp)->GetGoodRet();
}
// @pymethod |PyCWinApp|OnFileNew|Calls the underlying OnFileNew MFC method.
static PyObject *
ui_on_file_new(PyObject *self, PyObject *args)
{
CHECK_NO_ARGS2(args,OnFileNew);
CProtectedWinApp *pApp = GetProtectedApp();
if (!pApp) return NULL;
GUI_BGN_SAVE;
pApp->OnFileNew();
GUI_END_SAVE;
RETURN_NONE;
}
// @pymethod |PyCWinApp|OnFileOpen|Calls the underlying OnFileOpen MFC method.
static PyObject *
ui_on_file_open(PyObject *self, PyObject *args)
{
CHECK_NO_ARGS2(args,OnFileNew);
CProtectedWinApp *pApp = GetProtectedApp();
if (!pApp) return NULL;
GUI_BGN_SAVE;
pApp->OnFileOpen();
GUI_END_SAVE;
RETURN_NONE;
}
// @pymethod int|PyCWinApp|LoadCursor|Loads a cursor.
static PyObject *ui_load_cursor(PyObject *self, PyObject *args)
{
TCHAR *csid;
HCURSOR hc;
PyObject *obid;
if (!PyArg_ParseTuple(args, "O:LoadCursor",
&obid)) // @pyparm <o PyResourceId>|cursorId||The resource id or name of the cursor to load.
return NULL;
if (!PyWinObject_AsResourceId(obid, &csid, TRUE))
return NULL;
if (IS_INTRESOURCE(csid))
hc = GetApp()->LoadCursor((UINT)csid);
else
hc = GetApp()->LoadCursor(csid);
PyWinObject_FreeResourceId(csid);
if (hc==0)
RETURN_API_ERR("LoadCursor");
return PyWinLong_FromHANDLE(hc);
}
// @pymethod int|PyCWinApp|LoadStandardCursor|Loads a standard cursor.
static PyObject *ui_load_standard_cursor(PyObject *self, PyObject *args)
{
PyObject *obid;
TCHAR *csid;
HCURSOR hc;
if (!PyArg_ParseTuple(args, "O:LoadStandardCursor",
&obid)) // @pyparm <o PyResourceId>|cursorId||The resource ID or name of the cursor to load.
return NULL;
if (!PyWinObject_AsResourceId(obid, &csid, TRUE))
return NULL;
hc = GetApp()->LoadStandardCursor(csid);
PyWinObject_FreeResourceId(csid);
if (hc==0)
RETURN_API_ERR("LoadStandardCursor");
return PyWinLong_FromHANDLE(hc);
}
// @pymethod int|PyCWinApp|LoadOEMCursor|Loads an OEM cursor.
static PyObject *ui_load_oem_cursor(PyObject *self, PyObject *args)
{
UINT cid;
HCURSOR hc;
if ( !PyArg_ParseTuple(args, "i:LoadOEMCursor",
&cid)) // @pyparm int|cursorId||The ID of the cursor to load.
return NULL;
hc = GetApp()->LoadOEMCursor(cid);
if (hc==0)
RETURN_API_ERR("LoadOEMCursor");
return PyWinLong_FromHANDLE(hc);
}
// @pymethod int|PyCWinApp|LoadIcon|Loads an icon resource.
static PyObject *
ui_load_icon(PyObject *self, PyObject *args)
{
int idResource;
// @pyparm int|idResource||The ID of the icon to load.
if (!PyArg_ParseTuple(args,"i:LoadIcon", &idResource))
return NULL;
CWinApp *pApp = GetApp();
if (!pApp) return NULL;
return PyWinLong_FromHANDLE(pApp->LoadIcon(idResource));
}
// @pymethod int|PyCWinApp|LoadStandardIcon|Loads an icon resource.
static PyObject *
ui_load_standard_icon(PyObject *self, PyObject *args)
{
TCHAR *resName;
PyObject *obName;
// @pyparm <o PyResourceId>|resourceName||The resource name or id of the standard icon to load.
if (!PyArg_ParseTuple(args,"O:LoadStandardIcon", &obName))
return NULL;
CWinApp *pApp = GetApp();
if (!pApp) return NULL;
if (!PyWinObject_AsResourceId(obName, &resName, FALSE))
return NULL;
HICON hicon = pApp->LoadStandardIcon(resName);
PyWinObject_FreeResourceId(resName);
if (hicon==0)
RETURN_API_ERR("LoadStandardIcon");
return PyWinLong_FromHANDLE(hicon);
}
// @pymethod int|PyCWinApp|Run|Starts the message pump. Advanced users only
static PyObject *
ui_app_run(PyObject *self, PyObject *args)
{
CHECK_NO_ARGS2(args, "Run");
GUI_BGN_SAVE;
long rc = AfxGetApp()->CWinApp::Run();
GUI_END_SAVE;
return PyInt_FromLong(rc);
}
// @pymethod int|PyCWinApp|IsInproc|Returns a flag to indicate if the created CWinApp was in the DLL, or an external EXE.
static PyObject *
ui_app_isinproc(PyObject *self, PyObject *args)
{
extern BOOL PyWin_bHaveMFCHost;
CHECK_NO_ARGS2(args, IsInproc);
return PyInt_FromLong(!PyWin_bHaveMFCHost);
}
// @pymethod [<o PyCDocTemplate>,...]|PyCWinApp|GetDocTemplateList|Returns a list of all document templates.
static PyObject *
ui_app_get_doc_template_list(PyObject *self, PyObject *args)
{
CHECK_NO_ARGS2(args, GetDocTemplateList);
CProtectedWinApp *pApp = GetProtectedApp();
if (!pApp) return NULL;
return pApp->MakePyDocTemplateList();
}
extern PyObject *ui_init_dlg_instance(PyObject *self, PyObject *args);
// @object PyCWinApp|An application class. Encapsulates an MFC <c CWinApp> class
static struct PyMethodDef PyCWinApp_methods[] = {
{"AddDocTemplate", ui_app_add_doc_template, 1 }, // @pymeth AddDocTemplate|Adds a template to the application list.
{"FindOpenDocument", ui_find_open_document, 1}, // @pymeth FindOpenDocument|Returns an existing document with the specified file name.
{"GetDocTemplateList", ui_app_get_doc_template_list, 1}, // @pymeth GetDocTemplateList|Returns a list of all document templates in use.
{"InitMDIInstance", ui_init_mdi_instance, 1},
{"InitDlgInstance", ui_init_dlg_instance, 1}, // @pymeth InitDlgInstance|Calls critical InitInstance processing for a dialog based application.
{"LoadCursor", ui_load_cursor, 1}, //@pymeth LoadCursor|Loads a cursor.
{"LoadStandardCursor", ui_load_standard_cursor,1}, //@pymeth LoadStandardCursor|Loads a standard cursor.
{"LoadOEMCursor", ui_load_oem_cursor, 1}, //@pymeth LoadOEMCursor|Loads an OEM cursor.
{"LoadIcon", ui_load_icon, 1}, // @pymeth LoadIcon|Loads an icon resource.
{"LoadStandardIcon", ui_load_standard_icon, 1}, // @pymeth LoadStandardIcon|Loads an icon resource.
{"OpenDocumentFile", ui_open_document_file, 1}, // @pymeth OpenDocumentFile|Opens a document file by name.
{"OnFileNew", ui_on_file_new, 1}, // @pymeth OnFileNew|Calls the underlying OnFileNew MFC method.
{"OnFileOpen", ui_on_file_open, 1}, // @pymeth OnFileOpen|Calls the underlying OnFileOpen MFC method.
{"RemoveDocTemplate", ui_app_remove_doc_template, 1}, // @pymeth RemoveDocTemplate|Removes a template to the application list.
{"Run", ui_app_run, 1}, // @pymeth Run|Starts the main application message pump.
{"IsInproc", ui_app_isinproc, 1}, // @pymeth IsInproc|Returns a flag to indicate if the created CWinApp was in the DLL, or an external EXE.
{NULL, NULL}
};
ui_type_CObject PyCWinApp::type("PyCWinApp",
&PyCWinThread::type,
RUNTIME_CLASS(CWinApp),
sizeof(PyCWinApp),
PYOBJ_OFFSET(PyCWinApp),
PyCWinApp_methods,
GET_PY_CTOR(PyCWinApp) );
void PyCWinApp::cleanup()
{
PyCWinThread::cleanup();
// total hack!
while (pExistingAppObject)
DODECREF(pExistingAppObject); // this may delete it.
}
|
DavidGuben/rcbplayspokemon
|
app/pywin32-220/Pythonwin/win32app.cpp
|
C++
|
mit
| 13,966 |
import { expectFileToExist } from '../../utils/fs';
import { ng } from '../../utils/process';
import { updateJsonFile } from '../../utils/project';
import { expectToFail } from '../../utils/utils';
export default async function () {
await updateJsonFile('angular.json', workspaceJson => {
const appArchitect = workspaceJson.projects['test-project'].architect;
// These are the default options, that we'll overwrite in subsequent configs.
// extractCss defaults to false
// sourceMap defaults to true
appArchitect['options'] = {
outputPath: 'dist/latest-project',
index: 'src/index.html',
main: 'src/main.ts',
polyfills: 'src/polyfills.ts',
tsConfig: 'tsconfig.app.json',
assets: [
'src/favicon.ico',
'src/assets',
],
'styles': [
'src/styles.css',
],
'scripts': [],
};
const browserConfigs = appArchitect['build'].configurations;
browserConfigs['production'] = {
extractCss: true,
};
browserConfigs['one'] = {
assets: [],
};
browserConfigs['two'] = {
sourceMap: false,
};
browserConfigs['three'] = {
extractCss: false, // Defaults to false when not set.
};
});
// Test the base configuration.
await ng('build');
await expectFileToExist('dist/test-project/favicon.ico');
await expectFileToExist('dist/test-project/main-es2015.js.map');
await expectFileToExist('dist/test-project/styles-es2015.js');
await expectFileToExist('dist/test-project/vendor-es2015.js');
// Test that --prod extracts css.
await ng('build', '--prod');
await expectFileToExist('dist/test-project/styles.css');
// But using a config overrides prod.
await ng('build', '--prod', '--configuration=three');
await expectFileToExist('dist/test-project/styles-es2015.js');
await expectToFail(() => expectFileToExist('dist/test-project/styles.css'));
// Use two configurations.
await ng('build', '--configuration=one,two', '--vendor-chunk=false');
await expectToFail(() => expectFileToExist('dist/test-project/favicon.ico'));
await expectToFail(() => expectFileToExist('dist/test-project/main-es2015.js.map'));
// Use two configurations and two overrides, one of which overrides a config.
await ng('build', '--configuration=one,two', '--vendor-chunk=false', '--sourceMap=true');
await expectToFail(() => expectFileToExist('dist/test-project/favicon.ico'));
await expectFileToExist('dist/test-project/main-es2015.js.map');
await expectToFail(() => expectFileToExist('dist/test-project/vendor-es2015.js'));
// Use three configurations and a override, and prod at the end.
await ng('build', '--configuration=one,two,three', '--vendor-chunk=false', '--prod');
await expectToFail(() => expectFileToExist('dist/test-project/favicon.ico'));
await expectToFail(() => expectFileToExist('dist/test-project/main-es2015.js.map'));
await expectToFail(() => expectFileToExist('dist/test-project/vendor-es2015.js'));
await expectFileToExist('dist/test-project/styles-es2015.js');
await expectToFail(() => expectFileToExist('dist/test-project/styles.css'));
}
|
DevIntent/angular-cli
|
tests/legacy-cli/e2e/tests/build/multiple-configs.ts
|
TypeScript
|
mit
| 3,137 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="IE=edge" http-equiv="X-UA-Compatible">
<meta content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width" name="viewport">
<title>Icons - Material</title>
<!-- css -->
<link href="../css/base.min.css" rel="stylesheet">
<link href="../css/project.min.css" rel="stylesheet">
<!-- favicon -->
<!-- ... -->
</head>
<body class="page-brand">
<header class="header header-transparent header-waterfall ui-header">
<ul class="nav nav-list pull-left">
<li>
<a data-toggle="menu" href="#ui_menu">
<span class="icon icon-lg">menu</span>
</a>
</li>
</ul>
<a class="header-logo header-affix-hide margin-left-no margin-right-no" data-offset-top="213" data-spy="affix" href="index.html">Material</a>
<span class="header-logo header-affix margin-left-no margin-right-no" data-offset-top="213" data-spy="affix">Icons</span>
<ul class="nav nav-list pull-right">
<li class="dropdown margin-right">
<a class="dropdown-toggle padding-left-no padding-right-no" data-toggle="dropdown">
<span class="access-hide">John Smith</span>
<span class="avatar avatar-sm"><img alt="alt text for John Smith avatar" src="../images/users/avatar-001.jpg"></span>
</a>
<ul class="dropdown-menu dropdown-menu-right">
<li>
<a class="padding-right-lg waves-attach" href="javascript:void(0)"><span class="icon icon-lg margin-right">account_box</span>Profile Settings</a>
</li>
<li>
<a class="padding-right-lg waves-attach" href="javascript:void(0)"><span class="icon icon-lg margin-right">add_to_photos</span>Upload Photo</a>
</li>
<li>
<a class="padding-right-lg waves-attach" href="page-login.html"><span class="icon icon-lg margin-right">exit_to_app</span>Logout</a>
</li>
</ul>
</li>
</ul>
</header>
<nav aria-hidden="true" class="menu" id="ui_menu" tabindex="-1">
<div class="menu-scroll">
<div class="menu-content">
<a class="menu-logo" href="index.html">Material</a>
<ul class="nav">
<li>
<a class="collapsed waves-attach" data-toggle="collapse" href="#ui_menu_components">Components</a>
<ul class="menu-collapse collapse" id="ui_menu_components">
<li>
<a class="waves-attach" href="ui-button.html">Buttons</a>
</li>
<li>
<a class="waves-attach" href="ui-button-fab.html">Buttons<small class="margin-left-xs">(Floating Action Button)</small></a>
</li>
<li>
<a class="waves-attach" href="ui-card.html">Cards</a>
</li>
<li>
<a class="waves-attach" href="ui-data-table.html">Data Tables</a>
</li>
<li>
<a class="waves-attach" href="ui-dialog.html">Dialogs</a>
</li>
<li>
<a class="waves-attach" href="ui-dropdown-menu.html">Menus</a>
</li>
<li>
<a class="waves-attach" href="ui-nav-drawer.html">Navigation Drawers</a>
</li>
<li>
<a class="waves-attach" href="ui-picker.html">Pickers</a>
</li>
<li>
<a class="waves-attach" href="ui-progress.html">Progress</a>
</li>
<li>
<a class="waves-attach" href="ui-selection-control.html">Selection Controls</a>
</li>
<li>
<a class="waves-attach" href="ui-snackbar.html">Snackbars</a>
</li>
<li>
<a class="waves-attach" href="ui-tab.html">Tabs</a>
</li>
<li>
<a class="waves-attach" href="ui-text-field.html">Text Fields</a>
</li>
<li>
<a class="waves-attach" href="ui-toolbar.html">Toolbars</a>
</li>
</ul>
</li>
<li>
<a class="waves-attach" data-toggle="collapse" href="#ui_menu_extras">Extras</a>
<ul class="menu-collapse collapse in" id="ui_menu_extras">
<li>
<a class="waves-attach" href="ui-avatar.html">Avatars</a>
</li>
<li class="active">
<a class="waves-attach" href="ui-icon.html">Icons</a>
</li>
<li>
<a class="waves-attach" href="ui-label.html">Labels</a>
</li>
<li>
<a class="waves-attach" href="ui-nav.html">Navs</a>
</li>
<li>
<a class="waves-attach" href="ui-tile.html">Tiles</a>
</li>
</ul>
</li>
<li>
<a class="collapsed waves-attach" data-toggle="collapse" href="#ui_menu_javascript">Javascript</a>
<ul class="menu-collapse collapse" id="ui_menu_javascript">
<li>
<a class="waves-attach" href="ui-affix.html">Affix</a>
</li>
<li>
<a class="waves-attach" href="ui-collapse.html">Collapse</a>
</li>
<li>
<a class="waves-attach" href="ui-dropdown-menu.html">Dropdown</a>
</li>
<li>
<a class="waves-attach" href="ui-modal.html">Modals</a>
</li>
<li>
<a class="waves-attach" href="ui-tab.html">Togglable Tabs</a>
</li>
</ul>
</li>
<li>
<a class="collapsed waves-attach" data-toggle="collapse" href="#ui_menu_samples">Sample Pages</a>
<ul class="menu-collapse collapse" id="ui_menu_samples">
<li>
<a class="waves-attach" href="page-login.html">Login Page</a>
</li>
<li>
<a class="waves-attach" href="page-picker.html">Picker Page</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<main class="content">
<div class="content-header ui-content-header">
<div class="container">
<div class="row">
<div class="col-lg-6 col-lg-offset-3 col-md-8 col-md-offset-2">
<h1 class="content-heading">Material Design Icons</h1>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-6 col-lg-offset-3 col-md-8 col-md-offset-2">
<section class="content-inner margin-top-no">
<div class="card">
<div class="card-main">
<div class="card-inner">
<p>Material comes with Material Design Icons.</p>
<blockquote>Material design system icons are simple, modern, friendly, and sometimes quirky. Each icon is created using our design guidelines to depict in simple and minimal forms the universal concepts used commonly throughout a UI. Ensuring readability and clarity at both large and small sizes, these icons have been optimized for beautiful display on all common platforms and display resolutions.</blockquote>
</div>
<div class="card-action">
<div class="card-action-btn pull-left">
<a class="btn btn-flat waves-attach" href="http://www.google.com/design/icons/" target="_blank">View all Material Design Icons<span class="icon margin-left-sm">open_in_new</span></a>
</div>
</div>
</div>
</div>
<h2 class="content-sub-heading">Basic Icons</h2>
<div class="tile-wrap">
<div class="tile">
<div class="tile-side pull-left">
<span class="icon">face</span>
</div>
<div class="tile-inner">
<pre class="margin-bottom-no margin-top-no">
<span class="icon">face</span>
</pre>
</div>
</div>
</div>
<h2 class="content-sub-heading">Colours</h2>
<div class="tile-wrap">
<div class="tile">
<div class="tile-side pull-left">
<span class="icon text-brand">face</span>
</div>
<div class="tile-inner">
<code>.text-brand</code>
</div>
</div>
<div class="tile">
<div class="tile-side pull-left">
<span class="icon text-brand-accent">face</span>
</div>
<div class="tile-inner">
<code>.text-brand-accent</code>
</div>
</div>
<div class="tile">
<div class="tile-side pull-left">
<span class="icon text-green">face</span>
</div>
<div class="tile-inner">
<code>.text-green</code>
</div>
</div>
<div class="tile">
<div class="tile-side pull-left">
<span class="icon text-orange">face</span>
</div>
<div class="tile-inner">
<code>.text-orange</code>
</div>
</div>
<div class="tile">
<div class="tile-side pull-left">
<span class="icon text-red">face</span>
</div>
<div class="tile-inner">
<code>.text-red</code>
</div>
</div>
</div>
<h2 class="content-sub-heading">Sizes</h2>
<div class="tile-wrap">
<div class="tile">
<div class="tile-side pull-left">
<span class="icon icon-lg">face</span>
</div>
<div class="tile-inner">
<code>.icon-lg</code>
</div>
</div>
<div class="tile">
<div class="tile-side pull-left">
<span class="icon icon-2x">face</span>
</div>
<div class="tile-inner">
<code>.icon-2x</code>
</div>
</div>
<div class="tile">
<div class="tile-side pull-left">
<span class="icon icon-3x">face</span>
</div>
<div class="tile-inner">
<code>.icon-3x</code>
</div>
</div>
<div class="tile">
<div class="tile-side pull-left">
<span class="icon icon-4x">face</span>
</div>
<div class="tile-inner">
<code>.icon-4x</code>
</div>
</div>
<div class="tile">
<div class="tile-side pull-left">
<span class="icon icon-5x">face</span>
</div>
<div class="tile-inner">
<code>.icon-5x</code>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
</main>
<footer class="ui-footer">
<div class="container">
<p>Material</p>
</div>
</footer>
<div class="fbtn-container">
<div class="fbtn-inner">
<a class="fbtn fbtn-lg fbtn-brand-accent waves-attach waves-circle waves-light" data-toggle="dropdown"><span class="fbtn-text fbtn-text-left">Links</span><span class="fbtn-ori icon">apps</span><span class="fbtn-sub icon">close</span></a>
<div class="fbtn-dropup">
<a class="fbtn waves-attach waves-circle" href="https://github.com/Daemonite/material" target="_blank"><span class="fbtn-text fbtn-text-left">Fork me on GitHub</span><span class="icon">code</span></a>
<a class="fbtn fbtn-brand waves-attach waves-circle waves-light" href="https://twitter.com/daemonites" target="_blank"><span class="fbtn-text fbtn-text-left">Follow Daemon on Twitter</span><span class="icon">share</span></a>
<a class="fbtn fbtn-green waves-attach waves-circle" href="http://www.daemon.com.au/" target="_blank"><span class="fbtn-text fbtn-text-left">Visit Daemon Website</span><span class="icon">link</span></a>
</div>
</div>
</div>
<!-- js -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="../js/base.min.js"></script>
<script src="../js/project.min.js"></script>
</body>
</html>
|
Dafell/we-movil
|
views/pages/Templates/ui-icon.html
|
HTML
|
mit
| 11,004 |
'use strict';
const _ = require('lodash');
const path = require('path');
const fs = require('fs-extra');
const plugin = require('../index');
/**
* This module exports a function that enrich the interactive command line and return a promise
* @returns {Promise} - a promise that resolve when the operation is done
*/
module.exports = (icli) => {
// Build the lists of choices
const choicesLists = getChoices();
const config = {
section: 'Lambda plugin',
cmd: 'create-lambda',
description: 'create a new lambda',
parameters: [{
cmdSpec: '[identifier]',
type: 'input',
validate: input => { return /^[a-z0-9_-]+$/i.test(input); },
question: {
message: 'Choose a unique identifier for the Lambda (alphanumeric caracters, "_" and "-" accepted)'
}
}, {
cmdSpec: '-r, --runtime <nodejs4.3|nodejs6.10|nodejs8.10|python2.7|python3.6>',
description: 'select the runtime',
type: 'list',
choices: choicesLists.runtimes,
default: 'nodejs8.10',
question: {
message: 'Choose the runtime'
}
}, {
cmdSpec: '-t, --timeout <timeout>',
description: 'select the timeout (in seconds)',
type: 'integer',
default: 10,
question: {
message: 'Choose the timeout (in seconds)'
}
}, {
cmdSpec: '-m, --memory <memory>',
description: 'select the memory (in MB)',
type: 'list',
choices: choicesLists.memory,
default: '256',
question: {
message: 'Choose the memory'
}
}, {
cmdSpec: '-d --dependencies <modules-names>',
description: 'select the project modules that must be included in the Lambda (only for nodejs runtimes)',
type: 'checkbox',
choices: choicesLists.dependencies,
question: {
message: 'Choose the node packages that must be included in the Lambda',
when(answers, cmdParameterValues) {
const runtime = answers.runtime || cmdParameterValues.runtime;
if (cmdParameterValues.dependencies || !_.startsWith(runtime, 'nodejs')) { return false; }
return choicesLists.dependencies().then(dependencies => {
return dependencies.length > 0;
});
}
}
}, {
type: 'list',
choices: choicesLists.roleOrigins,
question: {
name: 'roleOrigin',
message: 'Where can we find the execution role of the Lambda?',
when: (answers, cmdParameterValues) => {
if (cmdParameterValues.role) { return false; }
return choicesLists.roleOrigins().length > 0;
}
}
}, {
cmdSpec: '--role <role>',
description: 'select the execution role' + (plugin.myrmex.isPluginRegistered('iam') ? '' : ' (enter the ARN)'),
type: 'list',
choices: choicesLists.roles,
// We desactivate validation because the value can be set manually
validate: input => { return true; },
question: {
message: 'Choose the execution role',
when(answers, cmdParameterValues) {
if (cmdParameterValues.role) { return false; }
return answers.roleOrigin === 'myrmex' || answers.roleOrigin === 'aws';
}
}
}, {
type: 'input',
question: {
name: 'roleManually',
message: 'Enter the IAM role that will be used to execute the Lambda function' + (plugin.myrmex.isPluginRegistered('iam') ? '' : ' (enter the ARN)'),
when(answers, cmdParameterValues) {
return !answers.role && !cmdParameterValues.role;
}
}
}],
execute: executeCommand
};
/**
* Create the command and the prompt
*/
return icli.createSubCommand(config);
/**
* Build the choices for "list" and "checkbox" parameters
* @param {Array} endpoints - the list o available endpoint specifications
* @returns {Object} - collection of lists of choices for "list" and "checkbox" parameters
*/
function getChoices() {
const memoryValues = [];
for (let i = 128; i <= 1536; i += 64) {
memoryValues.push({ value: i.toString(), name: _.padStart(i, 4) + ' MB' });
}
return {
memory: memoryValues,
runtimes: ['nodejs4.3', 'nodejs6.10', 'nodejs8.10', 'python2.7', 'python3.6'],
dependencies: () => {
return plugin.loadModules()
.then(modules => {
return _.map(modules, m => {
return {
value: m.getName(),
name: icli.format.info(m.getName())
};
});
});
},
roleOrigins: () => {
if (plugin.myrmex.isPluginRegistered('iam')) {
const choices = [];
choices.push({
value: 'myrmex',
name: 'Select a role managed by the plugin @myrmex/iam'
});
choices.push({
value: 'aws',
name: 'Select a role in your AWS account'
});
choices.push({
value: '',
name: 'Enter the value manually'
});
return choices;
}
return [];
},
roles: (answers) => {
if (answers && answers.roleOrigin === 'aws') {
return plugin.myrmex.call('iam:getAWSRoles', [])
.then(roles => {
const eligibleRoles = [];
_.forEach(roles, role => {
const trustRelationship = JSON.parse(decodeURIComponent(role.AssumeRolePolicyDocument))
if (_.find(trustRelationship.Statement, (o) => { return o.Principal.Service === 'lambda.amazonaws.com'; })) {
eligibleRoles.push({
value: role.RoleName,
name: icli.format.info(role.RoleName)
});
}
});
return eligibleRoles;
});
} else {
return plugin.myrmex.call('iam:getRoles', [])
.then(roles => {
const eligibleRoles = [];
_.forEach(roles, role => {
if (_.find(role.config['trust-relationship'].Statement, (o) => { return o.Principal.Service === 'lambda.amazonaws.com'; })) {
eligibleRoles.push({
value: role.getName(),
name: icli.format.info(role.getName())
});
}
});
return eligibleRoles;
});
}
}
};
}
/**
* Create the new lambda
* @param {Object} parameters - the parameters provided in the command and in the prompt
* @returns {Promise<null>} - The execution stops here
*/
function executeCommand(parameters) {
if (!parameters.role && parameters.roleManually) { parameters.role = parameters.roleManually; }
const configFilePath = path.join(process.cwd(), plugin.config.lambdasPath, parameters.identifier);
return fs.mkdirp(configFilePath)
.then(() => {
// We create the configuration file of the Lambda
const config = {
params: {
Timeout: parameters.timeout,
MemorySize: parameters.memory,
Role: parameters.role,
Runtime: parameters.runtime,
Handler: _.startsWith(parameters.runtime, 'nodejs') ? 'index.handler' : 'lambda_function.lambda_handler'
}
};
// We save the configuration in a json file
return fs.writeFile(configFilePath + path.sep + 'config.json', JSON.stringify(config, null, 2));
})
.then(() => {
return _.startsWith(parameters.runtime, 'nodejs')
? initNodeJs(parameters, configFilePath)
: initPython(parameters, configFilePath);
})
.then(() => {
// We create a test event file
const src = path.join(__dirname, 'templates', 'events');
const dest = path.join(configFilePath, 'events');
return fs.copy(src, dest);
})
.then(() => {
const msg = '\n The Lambda ' + icli.format.info(parameters.identifier) + ' has been created\n\n'
+ ' Its configuration and its handler function are available in ' + icli.format.info(configFilePath) + '\n';
icli.print(msg);
});
}
};
function initNodeJs(parameters, configFilePath) {
// We create the package.json file
const packageJson = {
'name': parameters.identifier,
'version': '0.0.0',
dependencies: {}
};
_.forEach(parameters.dependencies, moduleName => {
packageJson.dependencies[moduleName] = path.relative(configFilePath, path.join(process.cwd(), plugin.config.modulesPath, moduleName));
});
// We save the package.json file
return fs.writeFile(configFilePath + path.sep + 'package.json', JSON.stringify(packageJson, null, 2))
.then(() => {
// We create the lambda handler
const src = path.join(__dirname, 'templates', 'index.js');
const dest = path.join(configFilePath, 'index.js');
return fs.copy(src, dest);
});
}
function initPython(parameters, configFilePath) {
// We create the lambda handler
const src = path.join(__dirname, 'templates', 'setup.cfg');
const dest = path.join(configFilePath, 'setup.cfg');
return fs.copy(src, dest)
.then(() => {
// We create the lambda handler
const src = path.join(__dirname, 'templates', 'lambda_function.py');
const dest = path.join(configFilePath, 'lambda_function.py');
return fs.copy(src, dest);
})
.then(() => {
// We create a requirements.txt file
return fs.writeFile(path.join(configFilePath, 'requirements.txt'), '')
});
}
|
myrmex-org/myrmex
|
packages/lambda/src/cli/create-lambda.js
|
JavaScript
|
mit
| 9,431 |
/****************************************************************************
Copyright (c) 2012-2013 cocos2d-x.org
http://www.cocos2d-x.org
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.
****************************************************************************/
#include "HelloWorldScene.h"
#include "PluginManager.h"
#include "AppDelegate.h"
#include "MySocialManager.h"
using namespace cocos2d;
using namespace cocos2d::plugin;
enum {
TAG_SHARE_BY_TWWITER = 100,
TAG_SHARE_BY_WEIBO = 101,
};
typedef struct tagEventMenuItem {
std::string id;
int tag;
}EventMenuItem;
static EventMenuItem s_EventMenuItem[] = {
{"twitter.jpeg", TAG_SHARE_BY_TWWITER},
{"weibo.png", TAG_SHARE_BY_WEIBO}
};
CCScene* HelloWorld::scene()
{
// 'scene' is an autorelease object
CCScene *scene = CCScene::create();
// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !CCLayer::init() )
{
return false;
}
CCSize size = CCDirector::sharedDirector()->getVisibleSize();
CCSprite* pBackground = CCSprite::create("background.png");
pBackground->setPosition(ccp(size.width / 2, size.height / 2));
addChild(pBackground);
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();
CCPoint posBR = ccp(pEGLView->getVisibleOrigin().x + pEGLView->getVisibleSize().width, pEGLView->getVisibleOrigin().y);
CCPoint posBC = ccp(pEGLView->getVisibleOrigin().x + pEGLView->getVisibleSize().width/2, pEGLView->getVisibleOrigin().y);
CCPoint posTL = ccp(pEGLView->getVisibleOrigin().x, pEGLView->getVisibleOrigin().y + pEGLView->getVisibleSize().height);
// add a "close" icon to exit the progress. it's an autorelease object
CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
this,
menu_selector(HelloWorld::menuCloseCallback) );
pCloseItem->setPosition( ccp(posBR.x - 20, posBR.y + 20) );
// create menu, it's an autorelease object
CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
pMenu->setPosition( CCPointZero );
this->addChild(pMenu, 1);
CCPoint posStep = ccp(150, -150);
CCPoint beginPos = ccpAdd(posTL, ccpMult(posStep, 0.5f));
int line = 0;
int row = 0;
for (int i = 0; i < sizeof(s_EventMenuItem)/sizeof(s_EventMenuItem[0]); i++) {
CCMenuItemImage* pMenuItem = CCMenuItemImage::create(s_EventMenuItem[i].id.c_str(), s_EventMenuItem[i].id.c_str(),
this, menu_selector(HelloWorld::eventMenuCallback));
pMenu->addChild(pMenuItem, 0, s_EventMenuItem[i].tag);
CCPoint pos = ccpAdd(beginPos, ccp(posStep.x * row, posStep.y * line));
CCSize itemSize = pMenuItem->getContentSize();
if ((pos.x + itemSize.width / 2) > posBR.x)
{
line += 1;
row = 0;
pos = ccpAdd(beginPos, ccp(posStep.x * row, posStep.y * line));
}
row += 1;
pMenuItem->setPosition(pos);
}
CCLabelTTF* label = CCLabelTTF::create("Reload all plugins", "Arial", 24);
CCMenuItemLabel* pMenuItem = CCMenuItemLabel::create(label, this, menu_selector(HelloWorld::reloadPluginMenuCallback));
pMenuItem->setAnchorPoint(ccp(0.5f, 0));
pMenu->addChild(pMenuItem, 0);
pMenuItem->setPosition(posBC);
return true;
}
void HelloWorld::reloadPluginMenuCallback(CCObject* pSender)
{
MySocialManager::sharedSocialManager()->unloadSocialPlugin();
MySocialManager::sharedSocialManager()->loadSocialPlugin();
}
void HelloWorld::eventMenuCallback(CCObject* pSender)
{
CCMenuItemLabel* pMenuItem = (CCMenuItemLabel*)pSender;
TShareInfo pInfo;
pInfo["SharedText"] = "Share message : HelloSocial!";
// pInfo["SharedImagePath"] = "Full/path/to/image";
MySocialManager::MyShareMode mode = (MySocialManager::MyShareMode) (pMenuItem->getTag() - TAG_SHARE_BY_TWWITER + 1);
MySocialManager::sharedSocialManager()->shareByMode(pInfo, mode);
}
void HelloWorld::menuCloseCallback(CCObject* pSender)
{
MySocialManager::purgeManager();
CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
|
cnsuperx/Cocos2d-x-2.2.5
|
plugin/samples/HelloSocial/Classes/HelloWorldScene.cpp
|
C++
|
mit
| 5,625 |
package middleware
import (
"fmt"
"runtime"
echo "gopkg.in/labstack/echo.v1"
)
// Recover returns a middleware which recovers from panics anywhere in the chain
// and handles the control to the centralized HTTPErrorHandler.
func Recover() echo.MiddlewareFunc {
// TODO: Provide better stack trace `https://github.com/go-errors/errors` `https://github.com/docker/libcontainer/tree/master/stacktrace`
return func(h echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
defer func() {
if err := recover(); err != nil {
trace := make([]byte, 1<<16)
n := runtime.Stack(trace, true)
c.Error(fmt.Errorf("panic recover\n %v\n stack trace %d bytes\n %s",
err, n, trace[:n]))
}
}()
return h(c)
}
}
}
|
holys/initials-avatar
|
vendor/gopkg.in/labstack/echo.v1/middleware/recover.go
|
GO
|
mit
| 762 |
function toggleHelper(e){var a=e.parentElement.parentElement,n=a.getElementsByTagName("div")[1],s=a.getElementsByTagName("span")[0],l=a.getElementsByTagName("span")[1];"none"==n.style.display?(n.style.display="block",s.innerHTML="▼",l.className=a.getElementsByTagName("span")[1].className.replace(/\bclosed\b/,"open")):(n.style.display="none",s.innerHTML="►",l.className=a.getElementsByTagName("span")[1].className.replace(/\bopen\b/,"closed"))}function closeWhereToFind(e){var a=document.getElementById(e);a.getElementsByTagName("div")[1].style.display="none";var n=a.getElementsByTagName("span");n[0].innerHTML="►",n[1].className=n[1].className.replace(/\bopen\b/,"closed")}
//# sourceMappingURL=helpToggler.js.map
|
wayneddgu/view-driving-licence
|
app/assets/vdl/helpToggler.js
|
JavaScript
|
mit
| 722 |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateForumThreadsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('forum_threads', function (Blueprint $table)
{
$table->increments('id');
$table->string('title');
$table->text('body');
$table->integer('category_id');
$table->integer('subcategory_id');
$table->integer('author_id');
$table->bigInteger('views')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('forum_threads');
}
}
|
muntasirsyed/LaraBB
|
database/migrations/2015_07_07_124948_create_forum_threads_table.php
|
PHP
|
mit
| 712 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>The page you were looking for doesn't exist (404)</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/404.html -->
<div class="dialog">
<h1>The page you were looking for doesn't exist.</h1>
<p>You may have mistyped the address or the page may have moved.</p>
</div>
</body>
</html>
|
vena/sugar
|
public/404.html
|
HTML
|
mit
| 976 |
foolproof
=========
MVC Foolproof Validation aims to extend the Data Annotation validation provided in ASP.NET MVC.
The original repository is a clone of the MVC Foolproof Validation library from https://foolproof.codeplex.com/ with bug fixes.
This fork targets the issue that Foolproof doesn't not work with ```Validator.TryValidateObject(...)```. It doesn't validate the model, it just returns ture. This caused problems when a validation was triggerd from the server side (e.g. validation of a file based import).
Example:
```html
private class Model
{
public string Value1 { get; set; }
[NotEqualTo("Value1")]
public string Value2 { get; set; }
}
[TestMethod()]
public void IsValid()
{
var model = new Model() { Value1 = "hello", Value2 = "goodbye" };
var ctx = new ValidationContext(model, null, null);
var results = new List<ValidationResult>();
bool actual = Validator.TryValidateObject(model, ctx, results, true);
var expected = true;
Assert.AreEqual(actual, expected);
}
```
All Unit Tests have been rewritten to test this behaviour.
QUnit test are updated to a new MVC 5 project (2 missing (compilation error), 2 changed (test results where mixed)))
|
philiphendry/foolproof
|
README.md
|
Markdown
|
mit
| 1,180 |
/* Copyright (c) 2013-2020 Mahmoud Fayed <[email protected]> */
extern "C" {
#include "ring.h"
}
#include "gtexttospeech.h"
GTextToSpeech::GTextToSpeech(QObject *parent,VM *pVM) : QTextToSpeech(parent)
{
this->pVM = pVM;
this->pParaList = ring_list_new(0);
strcpy(this->clocaleChangedEvent,"");
strcpy(this->cpitchChangedEvent,"");
strcpy(this->crateChangedEvent,"");
strcpy(this->cstateChangedEvent,"");
strcpy(this->cvoiceChangedEvent,"");
strcpy(this->cvolumeChangedEvent,"");
QObject::connect(this, SIGNAL(localeChanged(const QLocale)),this, SLOT(localeChangedSlot()));
QObject::connect(this, SIGNAL(pitchChanged(double)),this, SLOT(pitchChangedSlot()));
QObject::connect(this, SIGNAL(rateChanged(double)),this, SLOT(rateChangedSlot()));
QObject::connect(this, SIGNAL(stateChanged(QTextToSpeech::State)),this, SLOT(stateChangedSlot()));
QObject::connect(this, SIGNAL(voiceChanged(const QVoice)),this, SLOT(voiceChangedSlot()));
QObject::connect(this, SIGNAL(volumeChanged(double)),this, SLOT(volumeChangedSlot()));
}
GTextToSpeech::~GTextToSpeech()
{
ring_list_delete(this->pParaList);
}
void GTextToSpeech::geteventparameters(void)
{
void *pPointer;
pPointer = this->pVM;
RING_API_RETLIST(this->pParaList);
}
void GTextToSpeech::setlocaleChangedEvent(const char *cStr)
{
if ( strlen(cStr) < RINGQT_EVENT_SIZE )
strcpy(this->clocaleChangedEvent,cStr);
else {
printf("\nEvent Code: %s\n",cStr);
ring_vm_error(this->pVM,RINGQT_EVENT_SIZE_ERROR);
}
}
void GTextToSpeech::setpitchChangedEvent(const char *cStr)
{
if ( strlen(cStr) < RINGQT_EVENT_SIZE )
strcpy(this->cpitchChangedEvent,cStr);
else {
printf("\nEvent Code: %s\n",cStr);
ring_vm_error(this->pVM,RINGQT_EVENT_SIZE_ERROR);
}
}
void GTextToSpeech::setrateChangedEvent(const char *cStr)
{
if ( strlen(cStr) < RINGQT_EVENT_SIZE )
strcpy(this->crateChangedEvent,cStr);
else {
printf("\nEvent Code: %s\n",cStr);
ring_vm_error(this->pVM,RINGQT_EVENT_SIZE_ERROR);
}
}
void GTextToSpeech::setstateChangedEvent(const char *cStr)
{
if ( strlen(cStr) < RINGQT_EVENT_SIZE )
strcpy(this->cstateChangedEvent,cStr);
else {
printf("\nEvent Code: %s\n",cStr);
ring_vm_error(this->pVM,RINGQT_EVENT_SIZE_ERROR);
}
}
void GTextToSpeech::setvoiceChangedEvent(const char *cStr)
{
if ( strlen(cStr) < RINGQT_EVENT_SIZE )
strcpy(this->cvoiceChangedEvent,cStr);
else {
printf("\nEvent Code: %s\n",cStr);
ring_vm_error(this->pVM,RINGQT_EVENT_SIZE_ERROR);
}
}
void GTextToSpeech::setvolumeChangedEvent(const char *cStr)
{
if ( strlen(cStr) < RINGQT_EVENT_SIZE )
strcpy(this->cvolumeChangedEvent,cStr);
else {
printf("\nEvent Code: %s\n",cStr);
ring_vm_error(this->pVM,RINGQT_EVENT_SIZE_ERROR);
}
}
const char *GTextToSpeech::getlocaleChangedEvent(void)
{
return this->clocaleChangedEvent;
}
const char *GTextToSpeech::getpitchChangedEvent(void)
{
return this->cpitchChangedEvent;
}
const char *GTextToSpeech::getrateChangedEvent(void)
{
return this->crateChangedEvent;
}
const char *GTextToSpeech::getstateChangedEvent(void)
{
return this->cstateChangedEvent;
}
const char *GTextToSpeech::getvoiceChangedEvent(void)
{
return this->cvoiceChangedEvent;
}
const char *GTextToSpeech::getvolumeChangedEvent(void)
{
return this->cvolumeChangedEvent;
}
void GTextToSpeech::localeChangedSlot()
{
if (strcmp(this->clocaleChangedEvent,"")==0)
return ;
ring_vm_runcode(this->pVM,this->clocaleChangedEvent);
}
void GTextToSpeech::pitchChangedSlot()
{
if (strcmp(this->cpitchChangedEvent,"")==0)
return ;
ring_vm_runcode(this->pVM,this->cpitchChangedEvent);
}
void GTextToSpeech::rateChangedSlot()
{
if (strcmp(this->crateChangedEvent,"")==0)
return ;
ring_vm_runcode(this->pVM,this->crateChangedEvent);
}
void GTextToSpeech::stateChangedSlot()
{
if (strcmp(this->cstateChangedEvent,"")==0)
return ;
ring_vm_runcode(this->pVM,this->cstateChangedEvent);
}
void GTextToSpeech::voiceChangedSlot()
{
if (strcmp(this->cvoiceChangedEvent,"")==0)
return ;
ring_vm_runcode(this->pVM,this->cvoiceChangedEvent);
}
void GTextToSpeech::volumeChangedSlot()
{
if (strcmp(this->cvolumeChangedEvent,"")==0)
return ;
ring_vm_runcode(this->pVM,this->cvolumeChangedEvent);
}
|
ring-lang/ring
|
extensions/webassembly/ringqt/project/ringqt/src/gtexttospeech.cpp
|
C++
|
mit
| 4,220 |
Rails.application.routes.draw do
devise_for :users
# TODO: use only in archive sidebar. See how made other system
get ':year/:month', to: 'articles#index', year: /\d{4}/, month: /\d{1,2}/, as: 'articles_by_month', format: false
get ':year/:month/page/:page', to: 'articles#index', year: /\d{4}/, month: /\d{1,2}/, as: 'articles_by_month_page', format: false
get ':year', to: 'articles#index', year: /\d{4}/, as: 'articles_by_year', format: false
get ':year/page/:page', to: 'articles#index', year: /\d{4}/, as: 'articles_by_year_page', format: false
get 'articles.:format', to: 'articles#index', constraints: {format: 'rss'}, as: 'rss'
get 'articles.:format', to: 'articles#index', constraints: {format: 'atom'}, as: 'atom'
scope controller: 'xml', path: 'xml' do
get 'articlerss/:id/feed.xml', action: 'articlerss', format: false
get 'commentrss/feed.xml', action: 'commentrss', format: false
get 'trackbackrss/feed.xml', action: 'trackbackrss', format: false
end
get 'xml/:format', to: 'xml#feed', type: 'feed', constraints: {format: 'rss'}, as: 'xml'
get 'sitemap.xml', to: 'xml#feed', format: 'googlesitemap', type: 'sitemap', as: 'sitemap_xml'
scope controller: 'xml', path: 'xml', as: 'xml' do
scope action: 'feed' do
get ':format/feed.xml', type: 'feed'
get ':format/:type/:id/feed.xml'
get ':format/:type/feed.xml'
end
end
get 'xml/rsd', to: 'xml#rsd', format: false
get 'xml/feed', to: 'xml#feed'
# CommentsController
resources :comments, as: 'admin_comments', only: [:index, :create] do
collection do
post :preview
end
end
resources :trackbacks
# I thinks it's useless. More investigating
post "trackbacks/:id/:day/:month/:year", to: 'trackbacks#create', format: false
# ArticlesController
get '/live_search/', to: 'articles#live_search', as: :live_search_articles, format: false
get '/search/:q(.:format)/page/:page', to: 'articles#search', as: 'search', defaults: {page: 1}
get '/search(/:q(.:format))', to: 'articles#search'
get '/search/', to: 'articles#search', as: 'search_base', format: false
get '/archives/', to: 'articles#archives', format: false
get '/page/:page', to: 'articles#index', page: /\d+/, format: false
get '/pages/*name', to: 'articles#view_page', format: false
get 'previews(/:id)', to: 'articles#preview', format: false
get 'previews_pages(/:id)', to: 'articles#preview_page', format: false
get 'check_password', to: 'articles#check_password', format: false
get 'articles/markup_help/:id', to: 'articles#markup_help', format: false
get 'articles/tag', to: 'articles#tag', format: false
# SetupController
match '/setup', to: 'setup#index', via: [:get, :post], format: false
# TagsController (imitate inflected_resource)
resources :tags, only: [:index, :create, :new]
resources :tags, path: 'tag', only: [:show, :edit, :update, :destroy]
get '/tag/:id/page/:page', to: 'tags#show', format: false
get '/tags/page/:page', to: 'tags#index', format: false
resources :authors, path: 'author', only: :show
# ThemeController
scope controller: 'theme', filename: /.*/ do
get 'stylesheets/theme/:filename', action: 'stylesheets', format: false
get 'javascripts/theme/:filename', action: 'javascript', format: false
get 'images/theme/:filename', action: 'images', format: false
get 'fonts/theme/:filename', action: 'fonts', format: false
end
# For the tests
get 'theme/static_view_test', format: false
# For the statuses
get '/notes', to: 'notes#index', format: false
get '/notes/page/:page', to: 'notes#index', format: false
get '/note/:permalink', to: 'notes#show', format: false
get '/humans', to: 'text#humans', format: 'txt'
get '/robots', to: 'text#robots', format: 'txt'
# TODO: Remove if possible
resources :accounts, only: [], format: false do
collection do
get 'confirm'
end
end
namespace :admin do
root 'dashboard#index', as: 'dashboard'
get 'cache', to: 'cache#show', format: false
delete 'cache', to: 'cache#destroy', format: false
resources :content, only: [:index, :new, :edit, :create, :update, :destroy], format: false do
collection do
get 'auto_complete_for_article_keywords'
post 'autosave'
end
end
resources :feedback, only: [:index, :edit, :create, :update, :destroy], format: false do
collection do
post 'bulkops'
end
member do
get 'article'
post 'change_state'
end
end
resources :notes, only: [:index, :show, :edit, :create, :update, :destroy], format: false
resources :pages, only: [:index, :new, :edit, :create, :update, :destroy], format: false
resources :post_types, only: [:index, :edit, :create, :update, :destroy], format: false
resources :profiles, only: [:index, :update], format: false
resources :redirects, only: [:index, :edit, :create, :update, :destroy], format: false
resources :resources, only: [:index, :destroy], format: false do
collection do
post 'upload'
end
end
resource :seo, controller: 'seo', only: [:show, :update], format: false
resource :migrations, only: [:show, :update]
# TODO: This should be a singular resource
resource :settings, only: [], format: false do
collection do
get 'index'
get 'display'
get 'feedback'
get 'write'
post 'migrate'
post 'update'
end
end
resources :sidebar, only: [:index, :update, :destroy] do
collection do
put :publish
post :sortable
end
end
resources :tags, only: [:index, :edit, :create, :update, :destroy], format: false
# TODO: Work out if post is actually used or not.
get 'textfilters/macro_help(/:id)', to: 'textfilters#macro_help', id: nil, format: false
post 'textfilters/macro_help(/:id)', to: 'textfilters#macro_help', id: nil, format: false
resources :themes, only: [:index], format: false do
collection do
get 'preview'
get 'switchto'
end
end
resources :users, only: [:index, :new, :edit, :create, :update, :destroy], format: false
end
root 'articles#index'
get '*from', to: 'articles#redirect', format: false
end
|
seyedrazavi/publify
|
config/routes.rb
|
Ruby
|
mit
| 6,297 |
html,
body,
.wrapper-table {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.wrapper-table-opacity {
color: white;
background-color: rgba(0, 0, 0, .68);
}
.wrapper-table {
display: table;
}
.wrapper-table-cell {
display: table-cell;
margin: 0;
padding: 0;
text-align: center;
vertical-align: middle;
}
.content-coming-soon {
width: 80%;
height: auto;
margin: auto;
}
.coming-soon-wrapper {
display: inline-block;
padding: 20px;
text-align: center;
background-color: #ecf0f1;
}
.coming-soon-wrapper-transparent {
display: inline-block;
padding: 20px;
text-align: center;
color: white;
background-color: rgba(0, 0, 0, .6);
}
.coming-soon-wrapper + .coming-soon-wrapper,
.coming-soon-wrapper-transparent + .coming-soon-wrapper-transparent {
margin-left: 16px;
}
.coming-soon-time {
font-size: 40px;
font-weight: 700;
}
.coming-soon-date {
font-size: 16px;
display: block;
}
@media (max-width: 767px) {
.coming-soon-wrapper,
.coming-soon-wrapper-transparent {
padding: 10px;
}
.coming-soon-wrapper + .coming-soon-wrapper,
.coming-soon-wrapper-transparent + .coming-soon-wrapper-transparent {
margin-left: 8px;
}
.coming-soon-time {
font-size: 22px;
font-weight: 700;
}
.coming-soon-date {
font-size: 13px;
display: block;
}
}
|
reeganaga/tokoonline
|
assets/front/assets/css/coming-soon-404.css
|
CSS
|
mit
| 1,441 |
#!/usr/bin/env python
"""
Downloads all data files from on-line storage using the URL and destination
folder specified in the comma-separated-varaiable './download_data_index.csv'
file, which should have the columns:
filename,URL,folder,MD5
Specified paths are assumed to be relative to the detected location of
this python script, i.e., the location of download_data_all.py
If the MD5 hash of the downloaded file matches, the function increments the
reported SUCCESS_COUNT otherwise it increments the reported FAIL_COUNT
If a file is already downloaded, only the MD5 checksum is performed.
Warning messages are generated when:
* file already exists locally
* file did not download
* file MD5 hash value does not match expected value
If the file storage service changes, the URLs in the index file
will be updated to reflect the new location.
"""
import os
import urllib2
import hashlib
import zipfile
# detect location of this script
pathstr_python_script = os.path.dirname(os.path.realpath(__file__))
print(pathstr_python_script)
# full path to download_data_index.csv
filename_index = os.path.join(pathstr_python_script, 'download_data_index.csv')
# initialize counts
success_count = 0
fail_count = 0
def md5_for_file(filename, block_size=2**27):
md5 = hashlib.md5()
f = open(filename, 'rb')
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
f.close()
return md5.hexdigest()
def file_is_verified(destination_filename_fullpath, md5_expected, should_print_output):
# Reports success if file exists on file-system and MD5 matches.
result = False
if os.path.isfile(destination_filename_fullpath):
if should_print_output:
print("%s exists" % (destination_filename_fullpath) )
# success only if MD5 checksum matches
md5_download = md5_for_file(destination_filename_fullpath)
if md5_expected==md5_download:
if should_print_output:
print("Success! MD5 checksum verified for %35s : %s (expected) == %s (downloaded)" % (filename_download, md5_expected, md5_download) )
result = True
else:
if should_print_output:
print("INVALID MD5 checksum for %35s: %s (expected) != %s (downloaded)" % (filename_download, md5_expected, md5_download) )
result = False
return result
with open(filename_index, 'r') as f:
lines = f.read().splitlines()
f.close()
# loop over files. Skip header row of CSV.
for line in lines[1:]:
print("")
# download details
filename_download, URL, folder_relative_path, md5_expected = line.strip().split(',')
destination_filename_fullpath = os.path.join(pathstr_python_script, folder_relative_path, filename_download)
success = 0
if file_is_verified(destination_filename_fullpath, md5_expected, True):
print("Skipping download of verified file: %s" % destination_filename_fullpath)
success = 1
success_count += 1
else:
# download file
print("Downloading file %s from %s" % (filename_download, URL) )
filehandle = urllib2.urlopen(URL)
# Open our local file for writing
with open(destination_filename_fullpath, "wb") as local_file:
local_file.write(filehandle.read())
local_file.close()
if file_is_verified(destination_filename_fullpath, md5_expected, True):
success = 1
success_count += 1
else:
fail_count += 1
print("%s did not successfully download" % (filename_download) )
if success:
# extract if zip file
if zipfile.is_zipfile(destination_filename_fullpath):
print("Extracting zip file %s" % destination_filename_fullpath)
z = zipfile.ZipFile(destination_filename_fullpath, "r")
z.extractall(os.path.dirname(destination_filename_fullpath))
else:
print("%s is not a zip file" % destination_filename_fullpath)
print("\nSuccessfully downloaded and verified %.2f%% : success_count = %d, fail_count = %d\n" % (100.0 * success_count/float(success_count+fail_count+0.0001), success_count, fail_count) )
|
senguptasaikat/MRM_Sengupta_Moving_Table_Fat-Water_MRI_with_Dynamic_B0_Shimming
|
code/download_data_all.py
|
Python
|
mit
| 4,371 |
#ifndef CODA_NET_SERVER_SYNC_LISTENER_H
#define CODA_NET_SERVER_SYNC_LISTENER_H
#include "../socket_server_listener.h"
namespace coda {
namespace net {
namespace sync {
class server;
class server_listener : public socket_server_listener {
typedef server *server_type;
public:
/*!
* called when the server has polled its connections
*/
virtual void on_poll(const server_type &server) = 0;
};
} // namespace sync
} // namespace net
} // namespace coda
#endif
|
ryjen/arg3net
|
src/sync/listener.h
|
C
|
mit
| 544 |
<?php
defined('_JEXEC') or die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );
/*
* Best selling Products module for VirtueMart
* @version $Id: mod_virtuemart_category.php 1160 2014-05-06 20:35:19Z milbo $
* @package VirtueMart
* @subpackage modules
*
* @copyright (C) 2011-2015 The Virtuemart Team
*
*
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* VirtueMart is Free Software.
* VirtueMart comes with absolute no warranty.
*
* @link https://virtuemart.net
*----------------------------------------------------------------------
* This code creates a list of the bestselling products
* and displays it wherever you want
*----------------------------------------------------------------------
*/
defined('DS') or define('DS', DIRECTORY_SEPARATOR);
if (!class_exists( 'VmConfig' )) require(JPATH_ROOT .'/administrator/components/com_virtuemart/helpers/config.php');
VmConfig::loadConfig();
vmLanguage::loadJLang('mod_virtuemart_category', true);
vmJsApi::jQuery();
vmJsApi::cssSite();
/* Setting */
$categoryModel = VmModel::getModel('Category');
$category_id = $params->get('Parent_Category_id', 0);
$class_sfx = $params->get('class_sfx', '');
$moduleclass_sfx = $params->get('moduleclass_sfx','');
$layout = $params->get('layout','default');
$active_category_id = vRequest::getInt('virtuemart_category_id', '0');
$vendorId = '1';
$categories = $categoryModel->getChildCategoryList($vendorId, $category_id);
// We dont use image here
//$categoryModel->addImages($categories);
if(empty($categories)) return false;
$level = $params->get('level','2');
if($level>1){
foreach ($categories as $i => $category) {
$categories[$i]->childs = $categoryModel->getChildCategoryList($vendorId, $category->virtuemart_category_id) ;
// No image used here
//$categoryModel->addImages($category->childs);
//Yehyeh, very cheap done.
if($level>2){
foreach ($categories[$i]->childs as $j => $cat) {
$categories[$i]->childs[$j]->childs = $categoryModel->getChildCategoryList( $vendorId, $cat->virtuemart_category_id );
}
}
}
}
//vmdebug('my categories',$categories);
$parentCategories = $categoryModel->getCategoryRecurse($active_category_id,0);
/* Load tmpl default */
require(JModuleHelper::getLayoutPath('mod_virtuemart_category',$layout));
?>
|
yaelduckwen/lo_imaginario
|
web2/modules/mod_virtuemart_category/mod_virtuemart_category.php
|
PHP
|
mit
| 2,285 |
<?php
/* FOSUserBundle:Profile:edit.html.twig */
class __TwigTemplate_c48a25ce544536c0c41549c69a40d735b23ca6e001c38969f328d817234843a5 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = $this->env->loadTemplate("FOSUserBundle::layout.html.twig");
$this->blocks = array(
'fos_user_content' => array($this, 'block_fos_user_content'),
);
}
protected function doGetParent(array $context)
{
return "FOSUserBundle::layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_fos_user_content($context, array $blocks = array())
{
// line 4
$this->env->loadTemplate("FOSUserBundle:Profile:edit_content.html.twig")->display($context);
}
public function getTemplateName()
{
return "FOSUserBundle:Profile:edit.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 31 => 4, 28 => 3,);
}
}
|
VPecquerie/ESV
|
app/cache/prod/twig/c4/8a/25ce544536c0c41549c69a40d735b23ca6e001c38969f328d817234843a5.php
|
PHP
|
mit
| 1,239 |
<div class="modal-header">
<h4 class="modal-title">Profile</h4>
</div>
<div class="modal-body">
<ul class="profile-info">
<li class="pull-left">
<?php
if ($this->cbconfig->item('use_member_photo') && element('mem_photo', element('member', $view))) {
?>
<img src="<?php echo member_photo_url(element('mem_photo', element('member', $view))); ?>" width="64" height="64" class="media-object" alt="<?php echo html_escape(element('mem_nickname', element('member', $view))); ?> 님의 사진" title="<?php echo html_escape(element('mem_nickname', element('member', $view))); ?> 님의 사진" />
<?php
} else {
?>
<span class="fa fa-user fa-3x"></span>
<?php
}
?>
</li>
<li class="like pull-right">
<a class="good" href="javascript:;" onClick="add_follow('<?php echo element('mem_userid', element('member', $view)); ?>', 'followed_number');" title="<?php echo html_escape(element('mem_nickname', element('member', $view))); ?> 님을 친구추가하기"><i class="fa fa-thumbs-o-up fa-lg"></i> <span class="followed_number"><?php echo number_format(element('mem_followed', element('member', $view))); ?></span></a>
</li>
</ul>
<table class="table mt20">
<tbody>
<tr>
<th>포인트</th>
<td><?php echo number_format(element('mem_point', element('member', $view))); ?></td>
</tr>
<?php
if ($data) {
foreach ($data as $key => $value) {
?>
<tr>
<th><?php echo html_escape(element('display_name', $value)); ?></th>
<td><?php echo nl2br(html_escape(element('value', $value))); ?> </td>
</tr>
<?php
}
}
?>
<tr>
<th>회원가입일</th>
<td><?php echo display_datetime(element('mem_register_datetime', element('member', $view)), 'full'); ?></td>
</tr>
<tr>
<th>최종접속일</th>
<td><?php echo display_datetime(element('mem_lastlogin_datetime', element('member', $view)), 'full'); ?></td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-black btn-sm" onClick="window.close();">닫기</button>
</div>
|
damanegi79/gaon
|
views/profile/mobile/profile.php
|
PHP
|
mit
| 2,511 |
namespace TortoiseVS.Tortoise
{
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Win32;
internal class TortoiseProc
{
private static readonly Lazy<TortoiseProc> InstanceValue = new Lazy<TortoiseProc>(() => new TortoiseProc());
private string path;
private TortoiseProc()
{
path = FindPath();
}
public static TortoiseProc Instance
{
get
{
return InstanceValue.Value;
}
}
internal void Blame(string file, int line)
{
Start($"/command:blame /line:{line}", file);
}
internal void Log(string file)
{
Start($"/command:log", file);
}
internal Task Update(string path)
{
return StartAsync($"/command:update /closeonend:2", path);
}
private string FindPath()
{
const string keyPath = @"Software\TortoiseSVN";
const string valueName = "ProcPath";
RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, Environment.MachineName, RegistryView.Registry64).OpenSubKey(keyPath);
string procPath = key.GetValue(valueName).ToString();
if (!string.IsNullOrEmpty(procPath) && File.Exists(procPath))
{
return procPath;
}
key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, Environment.MachineName, RegistryView.Registry32).OpenSubKey(keyPath);
procPath = key.GetValue(valueName).ToString();
if (!string.IsNullOrEmpty(procPath) && File.Exists(procPath))
{
return procPath;
}
else
{
return string.Empty;
}
}
private void Start(string command, string file)
{
command += string.Format(@" /path:""{0}""", file);
Start(command);
}
private Task StartAsync(string command, string file)
{
command += string.Format(@" /path:""{0}""", file);
return StartAsync(command);
}
private Process Start(string arguments)
{
if (arguments.Length > 32767)
{
throw new Exception("to many args");
}
Process process = new Process();
process.EnableRaisingEvents = true;
process.StartInfo.FileName = path;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = false;
process.Start();
return process;
}
private Task StartAsync(string arguments)
{
var tcs = new TaskCompletionSource<bool>();
Process process = Start(arguments);
if (!process.HasExited)
{
process.Exited += (sender, args) =>
{
tcs.SetResult(true);
process.Dispose();
};
}
else
{
tcs.SetResult(false);
process.Dispose();
}
return tcs.Task;
}
}
}
|
Jan-Magerl/VSExtensions
|
TortoiseVS2/Tortoise/TortoiseProc.cs
|
C#
|
mit
| 3,315 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.common;
import android.text.TextUtils;
import android.text.util.Rfc822Token;
import android.text.util.Rfc822Tokenizer;
import android.widget.AutoCompleteTextView;
import java.util.regex.Pattern;
/**
* This class works as a Validator for AutoCompleteTextView for
* email addresses. If a token does not appear to be a valid address,
* it is trimmed of characters that cannot legitimately appear in one
* and has the specified domain name added. It is meant for use with
* {@link Rfc822Token} and {@link Rfc822Tokenizer}.
*
* @deprecated In the future make sure we don't quietly alter the user's
* text in ways they did not intend. Meanwhile, hide this
* class from the public API because it does not even have
* a full understanding of the syntax it claims to correct.
* @hide
*/
@Deprecated
public class Rfc822Validator implements AutoCompleteTextView.Validator {
/*
* Regex.EMAIL_ADDRESS_PATTERN hardcodes the TLD that we accept, but we
* want to make sure we will keep accepting email addresses with TLD's
* that don't exist at the time of this writing, so this regexp relaxes
* that constraint by accepting any kind of top level domain, not just
* ".com", ".fr", etc...
*/
private static final Pattern EMAIL_ADDRESS_PATTERN =
Pattern.compile("[^\\s@]+@([^\\s@\\.]+\\.)+[a-zA-z][a-zA-Z][a-zA-Z]*");
private String mDomain;
private boolean mRemoveInvalid = false;
/**
* Constructs a new validator that uses the specified domain name as
* the default when none is specified.
*/
public Rfc822Validator(String domain) {
mDomain = domain;
}
/**
* {@inheritDoc}
*/
public boolean isValid(CharSequence text) {
Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(text);
return tokens.length == 1 &&
EMAIL_ADDRESS_PATTERN.
matcher(tokens[0].getAddress()).matches();
}
/**
* Specify if the validator should remove invalid tokens instead of trying
* to fix them. This can be used to strip results of incorrectly formatted
* tokens.
*
* @param remove true to remove tokens with the wrong format, false to
* attempt to fix them
*/
public void setRemoveInvalid(boolean remove) {
mRemoveInvalid = remove;
}
/**
* @return a string in which all the characters that are illegal for the username
* or the domain name part of the email address have been removed.
*/
private String removeIllegalCharacters(String s) {
StringBuilder result = new StringBuilder();
int length = s.length();
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
/*
* An RFC822 atom can contain any ASCII printing character
* except for periods and any of the following punctuation.
* A local-part can contain multiple atoms, concatenated by
* periods, so do allow periods here.
*/
if (c <= ' ' || c > '~') {
continue;
}
if (c == '(' || c == ')' || c == '<' || c == '>' ||
c == '@' || c == ',' || c == ';' || c == ':' ||
c == '\\' || c == '"' || c == '[' || c == ']') {
continue;
}
result.append(c);
}
return result.toString();
}
/**
* {@inheritDoc}
*/
public CharSequence fixText(CharSequence cs) {
// Return an empty string if the email address only contains spaces, \n or \t
if (TextUtils.getTrimmedLength(cs) == 0) return "";
Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(cs);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < tokens.length; i++) {
String text = tokens[i].getAddress();
if (mRemoveInvalid && !isValid(text)) {
continue;
}
int index = text.indexOf('@');
if (index < 0) {
// append the domain of the account if it exists
if (mDomain != null) {
tokens[i].setAddress(removeIllegalCharacters(text) + "@" + mDomain);
}
} else {
// Otherwise, remove the illegal characters on both sides of the '@'
String fix = removeIllegalCharacters(text.substring(0, index));
if (TextUtils.isEmpty(fix)) {
// if the address is empty after removing invalid chars
// don't use it
continue;
}
String domain = removeIllegalCharacters(text.substring(index + 1));
boolean emptyDomain = domain.length() == 0;
if (!emptyDomain || mDomain != null) {
tokens[i].setAddress(fix + "@" + (!emptyDomain ? domain : mDomain));
}
}
sb.append(tokens[i].toString());
if (i + 1 < tokens.length) {
sb.append(", ");
}
}
return sb;
}
}
|
x7hub/Calendar_lunar
|
src/com/android/common/Rfc822Validator.java
|
Java
|
mit
| 5,809 |
#ifndef BUILDING_NODE_EXTENSION
#define BUILDING_NODE_EXTENSION
#endif
#include "OneToManyTranscoder.h"
using v8::Local;
using v8::Value;
using v8::Function;
using v8::HandleScope;
Nan::Persistent<Function> OneToManyTranscoder::constructor;
// Async Delete OTM
// Classes for Async (not in node main thread) operations
class AsyncDeleter : public Nan::AsyncWorker {
public:
AsyncDeleter(erizo::OneToManyTranscoder* ott, Nan::Callback *callback) :
AsyncWorker(callback), ottToDelete_(ott) {
}
~AsyncDeleter() {}
void Execute() {
delete ottToDelete_;
}
void HandleOKCallback() {
HandleScope scope;
std::string msg("OK");
if (callback) {
Local<Value> argv[] = {
Nan::New(msg.c_str()).ToLocalChecked()
};
Nan::AsyncResource resource("erizo::addon.oneToManyTranscoder.deleter");
callback->Call(1, argv), &resource;
}
}
private:
erizo::OneToManyTranscoder* ottToDelete_;
Nan::Callback* callback_;
};
class AsyncRemoveSubscriber : public Nan::AsyncWorker{
public:
AsyncRemoveSubscriber(erizo::OneToManyTranscoder* ott, const std::string& peerId, Nan::Callback *callback):
AsyncWorker(callback), ott_(ott), peerId_(peerId), callback_(callback) {
}
~AsyncRemoveSubscriber() {}
void Execute() {
ott_->removeSubscriber(peerId_);
}
void HandleOKCallback() {
// We're not doing anything here ATM
}
private:
erizo::OneToManyTranscoder* ott_;
std::string peerId_;
Nan::Callback* callback_;
};
OneToManyTranscoder::OneToManyTranscoder() {}
OneToManyTranscoder::~OneToManyTranscoder() {}
NAN_MODULE_INIT(OneToManyTranscoder::Init) {
// Prepare constructor template
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
tpl->SetClassName(Nan::New("OneToManyTranscoder").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
Nan::SetPrototypeMethod(tpl, "close", close);
Nan::SetPrototypeMethod(tpl, "setPublisher", setPublisher);
Nan::SetPrototypeMethod(tpl, "hasPublisher", hasPublisher);
Nan::SetPrototypeMethod(tpl, "addSubscriber", addSubscriber);
Nan::SetPrototypeMethod(tpl, "removeSubscriber", removeSubscriber);
constructor.Reset(tpl->GetFunction());
Nan::Set(target, Nan::New("OneToManyTranscoder").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());
}
NAN_METHOD(OneToManyTranscoder::New) {
OneToManyTranscoder* obj = new OneToManyTranscoder();
obj->me = new erizo::OneToManyTranscoder();
obj->msink = obj->me;
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(OneToManyTranscoder::close) {
OneToManyTranscoder* obj = Nan::ObjectWrap::Unwrap<OneToManyTranscoder>(info.Holder());
erizo::OneToManyTranscoder *me = (erizo::OneToManyTranscoder*)obj->me;
Nan::Callback *callback;
if (info.Length() >= 1) {
callback = new Nan::Callback(info[0].As<Function>());
} else {
callback = NULL;
}
Nan::AsyncQueueWorker(new AsyncDeleter(me, callback));
}
NAN_METHOD(OneToManyTranscoder::setPublisher) {
OneToManyTranscoder* obj = Nan::ObjectWrap::Unwrap<OneToManyTranscoder>(info.Holder());
erizo::OneToManyTranscoder *me = (erizo::OneToManyTranscoder*)obj->me;
WebRtcConnection* param = Nan::ObjectWrap::Unwrap<WebRtcConnection>(Nan::To<v8::Object>(info[0]).ToLocalChecked());
erizo::WebRtcConnection* wr = (erizo::WebRtcConnection*)param->me;
erizo::MediaSource* ms = dynamic_cast<erizo::MediaSource*>(wr);
me->setPublisher(ms);
}
NAN_METHOD(OneToManyTranscoder::hasPublisher) {
OneToManyTranscoder* obj = Nan::ObjectWrap::Unwrap<OneToManyTranscoder>(info.Holder());
erizo::OneToManyTranscoder *me = (erizo::OneToManyTranscoder*)obj->me;
bool p = true;
if (me->publisher == NULL) {
p = false;
}
info.GetReturnValue().Set(Nan::New(p));
}
NAN_METHOD(OneToManyTranscoder::addSubscriber) {
OneToManyTranscoder* obj = Nan::ObjectWrap::Unwrap<OneToManyTranscoder>(info.Holder());
erizo::OneToManyTranscoder *me = (erizo::OneToManyTranscoder*)obj->me;
WebRtcConnection* param = Nan::ObjectWrap::Unwrap<WebRtcConnection>(Nan::To<v8::Object>(info[0]).ToLocalChecked());
erizo::WebRtcConnection* wr = (erizo::WebRtcConnection*)param->me;
erizo::MediaSink* ms = dynamic_cast<erizo::MediaSink*>(wr);
// get the param
v8::String::Utf8Value param1(Nan::To<v8::String>(info[1]).ToLocalChecked());
// convert it to string
std::string peerId = std::string(*param1);
me->addSubscriber(ms, peerId);
}
NAN_METHOD(OneToManyTranscoder::removeSubscriber) {
OneToManyTranscoder* obj = Nan::ObjectWrap::Unwrap<OneToManyTranscoder>(info.Holder());
erizo::OneToManyTranscoder *me = (erizo::OneToManyTranscoder*)obj->me;
// get the param
v8::String::Utf8Value param1(Nan::To<v8::String>(info[0]).ToLocalChecked());
// convert it to string
std::string peerId = std::string(*param1);
Nan::AsyncQueueWorker(new AsyncRemoveSubscriber(me, peerId, NULL));
}
|
lodoyun/licode
|
erizoAPI/OneToManyTranscoder.cc
|
C++
|
mit
| 4,938 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\Tests;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class ResponseTest extends ResponseTestCase
{
public function testCreate()
{
$response = Response::create('foo', 301, array('Foo' => 'bar'));
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
$this->assertEquals(301, $response->getStatusCode());
$this->assertEquals('bar', $response->headers->get('foo'));
}
public function testToString()
{
$response = new Response();
$response = explode("\r\n", $response);
$this->assertEquals("HTTP/1.0 200 OK", $response[0]);
$this->assertEquals("Cache-Control: no-cache", $response[1]);
}
public function testClone()
{
$response = new Response();
$responseClone = clone $response;
$this->assertEquals($response, $responseClone);
}
public function testSendHeaders()
{
$response = new Response();
$headers = $response->sendHeaders();
$this->assertObjectHasAttribute('headers', $headers);
$this->assertObjectHasAttribute('content', $headers);
$this->assertObjectHasAttribute('version', $headers);
$this->assertObjectHasAttribute('statusCode', $headers);
$this->assertObjectHasAttribute('statusText', $headers);
$this->assertObjectHasAttribute('charset', $headers);
}
public function testSend()
{
$response = new Response();
$responseSend = $response->send();
$this->assertObjectHasAttribute('headers', $responseSend);
$this->assertObjectHasAttribute('content', $responseSend);
$this->assertObjectHasAttribute('version', $responseSend);
$this->assertObjectHasAttribute('statusCode', $responseSend);
$this->assertObjectHasAttribute('statusText', $responseSend);
$this->assertObjectHasAttribute('charset', $responseSend);
}
public function testGetCharset()
{
$response = new Response();
$charsetOrigin = 'UTF-8';
$response->setCharset($charsetOrigin);
$charset = $response->getCharset();
$this->assertEquals($charsetOrigin, $charset);
}
public function testIsCacheable()
{
$response = new Response();
$this->assertFalse($response->isCacheable());
}
public function testIsCacheableWithErrorCode()
{
$response = new Response('', 500);
$this->assertFalse($response->isCacheable());
}
public function testIsCacheableWithNoStoreDirective()
{
$response = new Response();
$response->headers->set('cache-control', 'private');
$this->assertFalse($response->isCacheable());
}
public function testIsCacheableWithSetTtl()
{
$response = new Response();
$response->setTtl(10);
$this->assertTrue($response->isCacheable());
}
public function testMustRevalidate()
{
$response = new Response();
$this->assertFalse($response->mustRevalidate());
}
public function testSetNotModified()
{
$response = new Response();
$modified = $response->setNotModified();
$this->assertObjectHasAttribute('headers', $modified);
$this->assertObjectHasAttribute('content', $modified);
$this->assertObjectHasAttribute('version', $modified);
$this->assertObjectHasAttribute('statusCode', $modified);
$this->assertObjectHasAttribute('statusText', $modified);
$this->assertObjectHasAttribute('charset', $modified);
$this->assertEquals(304, $modified->getStatusCode());
}
public function testIsSuccessful()
{
$response = new Response();
$this->assertTrue($response->isSuccessful());
}
public function testIsNotModified()
{
$response = new Response();
$modified = $response->isNotModified(new Request());
$this->assertFalse($modified);
}
public function testIsNotModifiedNotSafe()
{
$request = Request::create('/homepage', 'POST');
$response = new Response();
$this->assertFalse($response->isNotModified($request));
}
public function testIsNotModifiedLastModified()
{
$modified = 'Sun, 25 Aug 2013 18:33:31 GMT';
$request = new Request();
$request->headers->set('If-Modified-Since', $modified);
$response = new Response();
$response->headers->set('Last-Modified', $modified);
$this->assertTrue($response->isNotModified($request));
$response->headers->set('Last-Modified', '');
$this->assertFalse($response->isNotModified($request));
}
public function testIsNotModifiedEtag()
{
$etagOne = 'randomly_generated_etag';
$etagTwo = 'randomly_generated_etag_2';
$request = new Request();
$request->headers->set('if_none_match', sprintf('%s, %s, %s', $etagOne, $etagTwo, 'etagThree'));
$response = new Response();
$response->headers->set('ETag', $etagOne);
$this->assertTrue($response->isNotModified($request));
$response->headers->set('ETag', $etagTwo);
$this->assertTrue($response->isNotModified($request));
$response->headers->set('ETag', '');
$this->assertFalse($response->isNotModified($request));
}
public function testIsValidateable()
{
$response = new Response('', 200, array('Last-Modified' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)));
$this->assertTrue($response->isValidateable(), '->isValidateable() returns true if Last-Modified is present');
$response = new Response('', 200, array('ETag' => '"12345"'));
$this->assertTrue($response->isValidateable(), '->isValidateable() returns true if ETag is present');
$response = new Response();
$this->assertFalse($response->isValidateable(), '->isValidateable() returns false when no validator is present');
}
public function testGetDate()
{
$response = new Response('', 200, array('Date' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)));
$this->assertEquals(0, $this->createDateTimeOneHourAgo()->diff($response->getDate())->format('%s'), '->getDate() returns the Date header if present');
$response = new Response();
$date = $response->getDate();
$this->assertLessThan(1, $date->diff(new \DateTime(), true)->format('%s'), '->getDate() returns the current Date if no Date header present');
$response = new Response('', 200, array('Date' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)));
$now = $this->createDateTimeNow();
$response->headers->set('Date', $now->format(DATE_RFC2822));
$this->assertEquals(0, $now->diff($response->getDate())->format('%s'), '->getDate() returns the date when the header has been modified');
$response = new Response('', 200);
$response->headers->remove('Date');
$this->assertInstanceOf('\DateTime', $response->getDate());
}
public function testGetMaxAge()
{
$response = new Response();
$response->headers->set('Cache-Control', 's-maxage=600, max-age=0');
$this->assertEquals(600, $response->getMaxAge(), '->getMaxAge() uses s-maxage cache control directive when present');
$response = new Response();
$response->headers->set('Cache-Control', 'max-age=600');
$this->assertEquals(600, $response->getMaxAge(), '->getMaxAge() falls back to max-age when no s-maxage directive present');
$response = new Response();
$response->headers->set('Cache-Control', 'must-revalidate');
$response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(DATE_RFC2822));
$this->assertEquals(3600, $response->getMaxAge(), '->getMaxAge() falls back to Expires when no max-age or s-maxage directive present');
$response = new Response();
$response->headers->set('Cache-Control', 'must-revalidate');
$response->headers->set('Expires', -1);
$this->assertEquals('Sat, 01 Jan 00 00:00:00 +0000', $response->getExpires()->format(DATE_RFC822));
$response = new Response();
$this->assertNull($response->getMaxAge(), '->getMaxAge() returns null if no freshness information available');
}
public function testSetSharedMaxAge()
{
$response = new Response();
$response->setSharedMaxAge(20);
$cacheControl = $response->headers->get('Cache-Control');
$this->assertEquals('public, s-maxage=20', $cacheControl);
}
public function testIsPrivate()
{
$response = new Response();
$response->headers->set('Cache-Control', 'max-age=100');
$response->setPrivate();
$this->assertEquals(100, $response->headers->getCacheControlDirective('max-age'), '->isPrivate() adds the private Cache-Control directive when set to true');
$this->assertTrue($response->headers->getCacheControlDirective('private'), '->isPrivate() adds the private Cache-Control directive when set to true');
$response = new Response();
$response->headers->set('Cache-Control', 'public, max-age=100');
$response->setPrivate();
$this->assertEquals(100, $response->headers->getCacheControlDirective('max-age'), '->isPrivate() adds the private Cache-Control directive when set to true');
$this->assertTrue($response->headers->getCacheControlDirective('private'), '->isPrivate() adds the private Cache-Control directive when set to true');
$this->assertFalse($response->headers->hasCacheControlDirective('public'), '->isPrivate() removes the public Cache-Control directive');
}
public function testExpire()
{
$response = new Response();
$response->headers->set('Cache-Control', 'max-age=100');
$response->expire();
$this->assertEquals(100, $response->headers->get('Age'), '->expire() sets the Age to max-age when present');
$response = new Response();
$response->headers->set('Cache-Control', 'max-age=100, s-maxage=500');
$response->expire();
$this->assertEquals(500, $response->headers->get('Age'), '->expire() sets the Age to s-maxage when both max-age and s-maxage are present');
$response = new Response();
$response->headers->set('Cache-Control', 'max-age=5, s-maxage=500');
$response->headers->set('Age', '1000');
$response->expire();
$this->assertEquals(1000, $response->headers->get('Age'), '->expire() does nothing when the response is already stale/expired');
$response = new Response();
$response->expire();
$this->assertFalse($response->headers->has('Age'), '->expire() does nothing when the response does not include freshness information');
$response = new Response();
$response->headers->set('Expires', -1);
$response->expire();
$this->assertNull($response->headers->get('Age'), '->expire() does not set the Age when the response is expired');
}
public function testGetTtl()
{
$response = new Response();
$this->assertNull($response->getTtl(), '->getTtl() returns null when no Expires or Cache-Control headers are present');
$response = new Response();
$response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(DATE_RFC2822));
$this->assertLessThan(1, 3600 - $response->getTtl(), '->getTtl() uses the Expires header when no max-age is present');
$response = new Response();
$response->headers->set('Expires', $this->createDateTimeOneHourAgo()->format(DATE_RFC2822));
$this->assertLessThan(0, $response->getTtl(), '->getTtl() returns negative values when Expires is in past');
$response = new Response();
$response->headers->set('Expires', $response->getDate()->format(DATE_RFC2822));
$response->headers->set('Age', 0);
$this->assertSame(0, $response->getTtl(), '->getTtl() correctly handles zero');
$response = new Response();
$response->headers->set('Cache-Control', 'max-age=60');
$this->assertLessThan(1, 60 - $response->getTtl(), '->getTtl() uses Cache-Control max-age when present');
}
public function testSetClientTtl()
{
$response = new Response();
$response->setClientTtl(10);
$this->assertEquals($response->getMaxAge(), $response->getAge() + 10);
}
public function testGetSetProtocolVersion()
{
$response = new Response();
$this->assertEquals('1.0', $response->getProtocolVersion());
$response->setProtocolVersion('1.1');
$this->assertEquals('1.1', $response->getProtocolVersion());
}
public function testGetVary()
{
$response = new Response();
$this->assertEquals(array(), $response->getVary(), '->getVary() returns an empty array if no Vary header is present');
$response = new Response();
$response->headers->set('Vary', 'Accept-Language');
$this->assertEquals(array('Accept-Language'), $response->getVary(), '->getVary() parses a single header name value');
$response = new Response();
$response->headers->set('Vary', 'Accept-Language User-Agent X-Foo');
$this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->getVary() parses multiple header name values separated by spaces');
$response = new Response();
$response->headers->set('Vary', 'Accept-Language,User-Agent, X-Foo');
$this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->getVary() parses multiple header name values separated by commas');
}
public function testSetVary()
{
$response = new Response();
$response->setVary('Accept-Language');
$this->assertEquals(array('Accept-Language'), $response->getVary());
$response->setVary('Accept-Language, User-Agent');
$this->assertEquals(array('Accept-Language', 'User-Agent'), $response->getVary(), '->setVary() replace the vary header by default');
$response->setVary('X-Foo', false);
$this->assertEquals(array('Accept-Language', 'User-Agent'), $response->getVary(), '->setVary() doesn\'t change the Vary header if replace is set to false');
}
public function testDefaultContentType()
{
$headerMock = $this->getMock('Symfony\Component\HttpFoundation\ResponseHeaderBag', array('set'));
$headerMock->expects($this->at(0))
->method('set')
->with('Content-Type', 'text/html');
$headerMock->expects($this->at(1))
->method('set')
->with('Content-Type', 'text/html; charset=UTF-8');
$response = new Response('foo');
$response->headers = $headerMock;
$response->prepare(new Request());
}
public function testContentTypeCharset()
{
$response = new Response();
$response->headers->set('Content-Type', 'text/css');
// force fixContentType() to be called
$response->prepare(new Request());
$this->assertEquals('text/css; charset=UTF-8', $response->headers->get('Content-Type'));
}
public function testPrepareDoesNothingIfContentTypeIsSet()
{
$response = new Response('foo');
$response->headers->set('Content-Type', 'text/plain');
$response->prepare(new Request());
$this->assertEquals('text/plain; charset=UTF-8', $response->headers->get('content-type'));
}
public function testPrepareDoesNothingIfRequestFormatIsNotDefined()
{
$response = new Response('foo');
$response->prepare(new Request());
$this->assertEquals('text/html; charset=UTF-8', $response->headers->get('content-type'));
}
public function testPrepareSetContentType()
{
$response = new Response('foo');
$request = Request::create('/');
$request->setRequestFormat('json');
$response->prepare($request);
$this->assertEquals('application/json', $response->headers->get('content-type'));
}
public function testPrepareRemovesContentForHeadRequests()
{
$response = new Response('foo');
$request = Request::create('/', 'HEAD');
$length = 12345;
$response->headers->set('Content-Length', $length);
$response->prepare($request);
$this->assertEquals('', $response->getContent());
$this->assertEquals($length, $response->headers->get('Content-Length'), 'Content-Length should be as if it was GET; see RFC2616 14.13');
}
public function testPrepareRemovesContentForInformationalResponse()
{
$response = new Response('foo');
$request = Request::create('/');
$response->setContent('content');
$response->setStatusCode(101);
$response->prepare($request);
$this->assertEquals('', $response->getContent());
$response->setContent('content');
$response->setStatusCode(304);
$response->prepare($request);
$this->assertEquals('', $response->getContent());
}
public function testPrepareRemovesContentLength()
{
$response = new Response('foo');
$request = Request::create('/');
$response->headers->set('Content-Length', 12345);
$response->prepare($request);
$this->assertEquals(12345, $response->headers->get('Content-Length'));
$response->headers->set('Transfer-Encoding', 'chunked');
$response->prepare($request);
$this->assertFalse($response->headers->has('Content-Length'));
}
public function testPrepareSetsPragmaOnHttp10Only()
{
$request = Request::create('/', 'GET');
$request->server->set('SERVER_PROTOCOL', 'HTTP/1.0');
$response = new Response('foo');
$response->prepare($request);
$this->assertEquals('no-cache', $response->headers->get('pragma'));
$this->assertEquals('-1', $response->headers->get('expires'));
$request->server->set('SERVER_PROTOCOL', 'HTTP/1.1');
$response = new Response('foo');
$response->prepare($request);
$this->assertFalse($response->headers->has('pragma'));
$this->assertFalse($response->headers->has('expires'));
}
public function testSetCache()
{
$response = new Response();
//array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public')
try {
$response->setCache(array("wrong option" => "value"));
$this->fail('->setCache() throws an InvalidArgumentException if an option is not supported');
} catch (\Exception $e) {
$this->assertInstanceOf('InvalidArgumentException', $e, '->setCache() throws an InvalidArgumentException if an option is not supported');
$this->assertContains('"wrong option"', $e->getMessage());
}
$options = array('etag' => '"whatever"');
$response->setCache($options);
$this->assertEquals($response->getEtag(), '"whatever"');
$now = new \DateTime();
$options = array('last_modified' => $now);
$response->setCache($options);
$this->assertEquals($response->getLastModified()->getTimestamp(), $now->getTimestamp());
$options = array('max_age' => 100);
$response->setCache($options);
$this->assertEquals($response->getMaxAge(), 100);
$options = array('s_maxage' => 200);
$response->setCache($options);
$this->assertEquals($response->getMaxAge(), 200);
$this->assertTrue($response->headers->hasCacheControlDirective('public'));
$this->assertFalse($response->headers->hasCacheControlDirective('private'));
$response->setCache(array('public' => true));
$this->assertTrue($response->headers->hasCacheControlDirective('public'));
$this->assertFalse($response->headers->hasCacheControlDirective('private'));
$response->setCache(array('public' => false));
$this->assertFalse($response->headers->hasCacheControlDirective('public'));
$this->assertTrue($response->headers->hasCacheControlDirective('private'));
$response->setCache(array('private' => true));
$this->assertFalse($response->headers->hasCacheControlDirective('public'));
$this->assertTrue($response->headers->hasCacheControlDirective('private'));
$response->setCache(array('private' => false));
$this->assertTrue($response->headers->hasCacheControlDirective('public'));
$this->assertFalse($response->headers->hasCacheControlDirective('private'));
}
public function testSendContent()
{
$response = new Response('test response rendering', 200);
ob_start();
$response->sendContent();
$string = ob_get_clean();
$this->assertContains('test response rendering', $string);
}
public function testSetPublic()
{
$response = new Response();
$response->setPublic();
$this->assertTrue($response->headers->hasCacheControlDirective('public'));
$this->assertFalse($response->headers->hasCacheControlDirective('private'));
}
public function testSetExpires()
{
$response = new Response();
$response->setExpires(null);
$this->assertNull($response->getExpires(), '->setExpires() remove the header when passed null');
$now = new \DateTime();
$response->setExpires($now);
$this->assertEquals($response->getExpires()->getTimestamp(), $now->getTimestamp());
}
public function testSetLastModified()
{
$response = new Response();
$response->setLastModified(new \DateTime());
$this->assertNotNull($response->getLastModified());
$response->setLastModified(null);
$this->assertNull($response->getLastModified());
}
public function testIsInvalid()
{
$response = new Response();
try {
$response->setStatusCode(99);
$this->fail();
} catch (\InvalidArgumentException $e) {
$this->assertTrue($response->isInvalid());
}
try {
$response->setStatusCode(650);
$this->fail();
} catch (\InvalidArgumentException $e) {
$this->assertTrue($response->isInvalid());
}
$response = new Response('', 200);
$this->assertFalse($response->isInvalid());
}
/**
* @dataProvider getStatusCodeFixtures
*/
public function testSetStatusCode($code, $text, $expectedText)
{
$response = new Response();
$response->setStatusCode($code, $text);
$statusText = new \ReflectionProperty($response, 'statusText');
$statusText->setAccessible(true);
$this->assertEquals($expectedText, $statusText->getValue($response));
}
public function getStatusCodeFixtures()
{
return array(
array('200', null, 'OK'),
array('200', false, ''),
array('200', 'foo', 'foo'),
array('199', null, ''),
array('199', false, ''),
array('199', 'foo', 'foo')
);
}
public function testIsInformational()
{
$response = new Response('', 100);
$this->assertTrue($response->isInformational());
$response = new Response('', 200);
$this->assertFalse($response->isInformational());
}
public function testIsRedirectRedirection()
{
foreach (array(301, 302, 303, 307) as $code) {
$response = new Response('', $code);
$this->assertTrue($response->isRedirection());
$this->assertTrue($response->isRedirect());
}
$response = new Response('', 304);
$this->assertTrue($response->isRedirection());
$this->assertFalse($response->isRedirect());
$response = new Response('', 200);
$this->assertFalse($response->isRedirection());
$this->assertFalse($response->isRedirect());
$response = new Response('', 404);
$this->assertFalse($response->isRedirection());
$this->assertFalse($response->isRedirect());
$response = new Response('', 301, array('Location' => '/good-uri'));
$this->assertFalse($response->isRedirect('/bad-uri'));
$this->assertTrue($response->isRedirect('/good-uri'));
}
public function testIsNotFound()
{
$response = new Response('', 404);
$this->assertTrue($response->isNotFound());
$response = new Response('', 200);
$this->assertFalse($response->isNotFound());
}
public function testIsEmpty()
{
foreach (array(201, 204, 304) as $code) {
$response = new Response('', $code);
$this->assertTrue($response->isEmpty());
}
$response = new Response('', 200);
$this->assertFalse($response->isEmpty());
}
public function testIsForbidden()
{
$response = new Response('', 403);
$this->assertTrue($response->isForbidden());
$response = new Response('', 200);
$this->assertFalse($response->isForbidden());
}
public function testIsOk()
{
$response = new Response('', 200);
$this->assertTrue($response->isOk());
$response = new Response('', 404);
$this->assertFalse($response->isOk());
}
public function testIsServerOrClientError()
{
$response = new Response('', 404);
$this->assertTrue($response->isClientError());
$this->assertFalse($response->isServerError());
$response = new Response('', 500);
$this->assertFalse($response->isClientError());
$this->assertTrue($response->isServerError());
}
public function testHasVary()
{
$response = new Response();
$this->assertFalse($response->hasVary());
$response->setVary('User-Agent');
$this->assertTrue($response->hasVary());
}
public function testSetEtag()
{
$response = new Response('', 200, array('ETag' => '"12345"'));
$response->setEtag();
$this->assertNull($response->headers->get('Etag'), '->setEtag() removes Etags when call with null');
}
/**
* @dataProvider validContentProvider
*/
public function testSetContent($content)
{
$response = new Response();
$response->setContent($content);
$this->assertEquals((string) $content, $response->getContent());
}
/**
* @expectedException UnexpectedValueException
* @dataProvider invalidContentProvider
*/
public function testSetContentInvalid($content)
{
$response = new Response();
$response->setContent($content);
}
public function testSettersAreChainable()
{
$response = new Response();
$setters = array(
'setProtocolVersion' => '1.0',
'setCharset' => 'UTF-8',
'setPublic' => null,
'setPrivate' => null,
'setDate' => new \DateTime,
'expire' => null,
'setMaxAge' => 1,
'setSharedMaxAge' => 1,
'setTtl' => 1,
'setClientTtl' => 1,
);
foreach ($setters as $setter => $arg) {
$this->assertEquals($response, $response->{$setter}($arg));
}
}
public function validContentProvider()
{
return array(
'obj' => array(new StringableObject),
'string' => array('Foo'),
'int' => array(2),
);
}
public function invalidContentProvider()
{
return array(
'obj' => array(new \stdClass),
'array' => array(array()),
'bool' => array(true, '1'),
);
}
protected function createDateTimeOneHourAgo()
{
$date = new \DateTime();
return $date->sub(new \DateInterval('PT1H'));
}
protected function createDateTimeOneHourLater()
{
$date = new \DateTime();
return $date->add(new \DateInterval('PT1H'));
}
protected function createDateTimeNow()
{
return new \DateTime();
}
protected function provideResponse()
{
return new Response();
}
}
class StringableObject
{
public function __toString()
{
return 'Foo';
}
}
|
samsonasik/symfony
|
src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php
|
PHP
|
mit
| 28,860 |
import {TestBed, ComponentFixture} from '@angular/core/testing';
import {Component} from '@angular/core';
import {createGenericTestComponent} from '../../test/util/helpers';
import {NglBreadcrumbsModule} from './module';
const createTestComponent = (html?: string, detectChanges?: boolean) =>
createGenericTestComponent(TestComponent, html, detectChanges) as ComponentFixture<TestComponent>;
function getBreadcrumbsLinks(element: HTMLElement): HTMLLinkElement[] {
return [].slice.call(element.querySelectorAll('a'));
}
function getAssistiveText(element: HTMLElement): string {
const el = <HTMLElement>element.querySelector('nav');
return el.getAttribute('aria-label');
}
describe('Breadcrumbs Component', () => {
beforeEach(() => TestBed.configureTestingModule({declarations: [TestComponent], imports: [NglBreadcrumbsModule]}));
it('should have the proper structure when rendered', () => {
const fixture = createTestComponent();
const anchors = getBreadcrumbsLinks(fixture.nativeElement);
anchors.map(el => el.parentElement).forEach(parentEl => {
expect(parentEl.tagName).toBe('LI');
expect(parentEl).toHaveCssClass('slds-breadcrumb__item');
expect(parentEl.parentElement.tagName).toBe('OL');
});
});
it('should have anchor across the path', () => {
const fixture = createTestComponent();
const anchors = getBreadcrumbsLinks(fixture.nativeElement);
expect(anchors.map(el => el.getAttribute('href'))).toEqual(['/here', '/there']);
expect(anchors.map(el => el.textContent)).toEqual(['Here I am!', 'There I was!']);
expect(anchors.map(el => el.classList.toString())).toEqual(['custom', '']);
});
it('should render assistive text correctly', () => {
const fixture = createTestComponent(`<ngl-breadcrumbs [assistiveText]="text"></ngl-breadcrumbs>`);
expect(getAssistiveText(fixture.nativeElement)).toEqual('Here you are:');
});
});
@Component({
template: `
<ngl-breadcrumbs [assistiveText]="text">
<a *nglBreadcrumb href="/here" class="custom">Here I am!</a>
<a *nglBreadcrumb href="/there">There I was!</a>
</ngl-breadcrumbs>`,
})
export class TestComponent {
text: string = 'Here you are:';
}
|
esarbanis/ng-lightning
|
src/breadcrumbs/breadcrumbs.spec.ts
|
TypeScript
|
mit
| 2,209 |
<div>Hi, this is a nested component: {{{nested}}}</div>
|
NapoleanReigns/oc
|
test/fixtures/components/container-with-nested/template.html
|
HTML
|
mit
| 55 |
#
#
#
# ------------------------------------------------------------------------
#
# Generel stuff
#
# Detect OS
OS = $(shell uname -s)
# Defaults
ECHO = echo
# Make adjustments based on OS
# http://stackoverflow.com/questions/3466166/how-to-check-if-running-in-cygwin-mac-or-linux/27776822#27776822
ifneq (, $(findstring CYGWIN, $(OS)))
ECHO = /bin/echo -e
endif
# Colors and helptext
NO_COLOR = \033[0m
ACTION = \033[32;01m
OK_COLOR = \033[32;01m
ERROR_COLOR = \033[31;01m
WARN_COLOR = \033[33;01m
# Which makefile am I in?
WHERE-AM-I = $(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
THIS_MAKEFILE := $(call WHERE-AM-I)
# Echo some nice helptext based on the target comment
HELPTEXT = $(ECHO) "$(ACTION)--->" `egrep "^\# target: $(1) " $(THIS_MAKEFILE) | sed "s/\# target: $(1)[ ]*-[ ]* / /g"` "$(NO_COLOR)"
# ------------------------------------------------------------------------
#
# Specifics
#
# Add local bin path for test tools
#PATH := "./.bin:./vendor/bin:./node_modules/.bin:$(PATH)"
#SHELL := env PATH=$(PATH) $(SHELL)
BIN := .bin
PHPUNIT := $(BIN)/phpunit
PHPLOC := $(BIN)/phploc
PHPCS := $(BIN)/phpcs
PHPCBF := $(BIN)/phpcbf
PHPMD := $(BIN)/phpmd
PHPDOC := $(BIN)/phpdoc
BEHAT := $(BIN)/behat
SHELLCHECK := $(BIN)/shellcheck
BATS := $(BIN)/bats
# target: help - Displays help.
.PHONY: help
help:
@$(call HELPTEXT,$@)
@$(ECHO) "Usage:"
@$(ECHO) " make [target] ..."
@$(ECHO) "target:"
@egrep "^# target:" $(THIS_MAKEFILE) | sed 's/# target: / /g'
# target: prepare - Prepare for tests and build
.PHONY: prepare
prepare:
@$(call HELPTEXT,$@)
[ -d .bin ] || mkdir .bin
[ -d build ] || mkdir build
rm -rf build/*
# target: clean - Removes generated files and directories.
.PHONY: clean
clean:
@$(call HELPTEXT,$@)
rm -rf build
# target: clean-cache - Clean the cache.
.PHONY: clean-cache
clean-cache:
@$(call HELPTEXT,$@)
rm -rf cache/*/*
# target: clean-all - Removes generated files and directories.
.PHONY: clean-all
clean-all:
@$(call HELPTEXT,$@)
rm -rf .bin build vendor
# target: check - Check version of installed tools.
.PHONY: check
check: check-tools-bash check-tools-php
@$(call HELPTEXT,$@)
# target: test - Run all tests.
.PHONY: test
test: bats phpunit phpcs phpmd phploc behat # shellcheck
@$(call HELPTEXT,$@)
composer validate
# target: doc - Generate documentation.
.PHONY: doc
doc: phpdoc
@$(call HELPTEXT,$@)
# target: build - Do all build
.PHONY: build
build: test doc #theme less-compile less-minify js-minify
@$(call HELPTEXT,$@)
# target: install - Install all tools
.PHONY: install
install: prepare install-tools-bash install-tools-php
@$(call HELPTEXT,$@)
# target: update - Update the codebase and tools.
.PHONY: update
update:
@$(call HELPTEXT,$@)
[ ! -d .git ] || git pull
composer update
# target: tag-prepare - Prepare to tag new version.
.PHONY: tag-prepare
tag-prepare:
@$(call HELPTEXT,$@)
# ------------------------------------------------------------------------
#
# PHP
#
# target: install-tools-php - Install PHP development tools.
.PHONY: install-tools-php
install-tools-php:
@$(call HELPTEXT,$@)
curl -Lso $(PHPDOC) https://www.phpdoc.org/phpDocumentor.phar && chmod 755 $(PHPDOC)
curl -Lso $(PHPCS) https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar && chmod 755 $(PHPCS)
curl -Lso $(PHPCBF) https://squizlabs.github.io/PHP_CodeSniffer/phpcbf.phar && chmod 755 $(PHPCBF)
curl -Lso $(PHPMD) http://static.phpmd.org/php/latest/phpmd.phar && chmod 755 $(PHPMD)
curl -Lso $(PHPUNIT) https://phar.phpunit.de/phpunit-5.7.9.phar && chmod 755 $(PHPUNIT)
curl -Lso $(PHPLOC) https://phar.phpunit.de/phploc.phar && chmod 755 $(PHPLOC)
curl -Lso $(BEHAT) https://github.com/Behat/Behat/releases/download/v3.3.0/behat.phar && chmod 755 $(BEHAT)
composer install
# target: check-tools-php - Check versions of PHP tools.
.PHONY: check-tools-php
check-tools-php:
@$(call HELPTEXT,$@)
which $(PHPUNIT) && $(PHPUNIT) --version
which $(PHPLOC) && $(PHPLOC) --version
which $(PHPCS) && $(PHPCS) --version && echo
which $(PHPMD) && $(PHPMD) --version && echo
which $(PHPCBF) && $(PHPCBF) --version && echo
which $(PHPDOC) && $(PHPDOC) --version && echo
which $(BEHAT) && $(BEHAT) --version && echo
# target: phpunit - Run unit tests for PHP.
.PHONY: phpunit
phpunit: prepare
@$(call HELPTEXT,$@)
[ ! -f .phpunit.xml ] || $(PHPUNIT) --configuration .phpunit.xml
# target: phpcs - Codestyle for PHP.
.PHONY: phpcs
phpcs: prepare
@$(call HELPTEXT,$@)
[ ! -f .phpcs.xml ] || $(PHPCS) --standard=.phpcs.xml | tee build/phpcs
# target: phpcbf - Fix codestyle for PHP.
.PHONY: phpcbf
phpcbf:
@$(call HELPTEXT,$@)
[ ! -f .phpcs.xml ] || $(PHPCBF) --standard=.phpcs.xml
# target: phpmd - Mess detector for PHP.
.PHONY: phpmd
phpmd: prepare
@$(call HELPTEXT,$@)
- [ ! -f .phpmd.xml ] || $(PHPMD) . text .phpmd.xml | tee build/phpmd
# target: phploc - Code statistics for PHP.
.PHONY: phploc
phploc: prepare
@$(call HELPTEXT,$@)
$(PHPLOC) src > build/phploc
# target: phpdoc - Create documentation for PHP.
.PHONY: phpdoc
phpdoc:
@$(call HELPTEXT,$@)
[ ! -f .phpdoc.xml ] || $(PHPDOC) --config=.phpdoc.xml
# target: behat - Run behat for feature tests.
.PHONY: behat
behat:
@$(call HELPTEXT,$@)
[ ! -d features ] || $(BEHAT)
# ------------------------------------------------------------------------
#
# Bash
#
# target: install-tools-bash - Install Bash development tools.
.PHONY: install-tools-bash
install-tools-bash:
@$(call HELPTEXT,$@)
# Shellcheck
curl -s https://storage.googleapis.com/shellcheck/shellcheck-latest.linux.x86_64.tar.xz | tar -xJ -C build/ && rm -f .bin/shellcheck && ln build/shellcheck-latest/shellcheck .bin/
# Bats
curl -Lso $(BIN)/bats-exec-suite https://raw.githubusercontent.com/sstephenson/bats/master/libexec/bats-exec-suite
curl -Lso $(BIN)/bats-exec-test https://raw.githubusercontent.com/sstephenson/bats/master/libexec/bats-exec-test
curl -Lso $(BIN)/bats-format-tap-stream https://raw.githubusercontent.com/sstephenson/bats/master/libexec/bats-format-tap-stream
curl -Lso $(BIN)/bats-preprocess https://raw.githubusercontent.com/sstephenson/bats/master/libexec/bats-preprocess
curl -Lso $(BATS) https://raw.githubusercontent.com/sstephenson/bats/master/libexec/bats
chmod 755 $(BIN)/bats*
# target: check-tools-bash - Check versions of Bash tools.
.PHONY: check-tools-bash
check-tools-bash:
@$(call HELPTEXT,$@)
which $(SHELLCHECK) && $(SHELLCHECK) --version
which $(BATS) && $(BATS) --version
# target: shellcheck - Run shellcheck for bash files.
.PHONY: shellcheck
shellcheck:
@$(call HELPTEXT,$@)
[ ! -d src ] || $(SHELLCHECK) --shell=bash src/*.bash
# target: bats - Run bats for unit testing bash files.
.PHONY: bats
bats:
@$(call HELPTEXT,$@)
[ ! -d test ] || $(BATS) test/
# ------------------------------------------------------------------------
#
# Theme
#
# target: theme - Do make build install in theme/ if available.
.PHONY: theme
theme:
@$(call HELPTEXT,$@)
[ ! -d theme ] || ( cd theme && make build install )
# ------------------------------------------------------------------------
#
# Cimage
#
define CIMAGE_CONFIG
<?php
return [
"mode" => "development",
"image_path" => __DIR__ . "/../img/",
"cache_path" => __DIR__ . "/../../cache/cimage/",
"autoloader" => __DIR__ . "/../../vendor/autoload.php",
];
endef
export CIMAGE_CONFIG
# target: cimage-update - Install/update Cimage to latest version.
.PHONY: cimage-update
cimage-update:
@$(call HELPTEXT,$@)
composer require mos/cimage
install -d htdocs/cimage cache/cimage
chmod 777 cache/cimage
cp vendor/mos/cimage/webroot/img.php htdocs/cimage
cp vendor/mos/cimage/webroot/img/car.png htdocs/img/
touch htdocs/cimage/img_config.php
# target: cimage-config-create - Create configfile for Cimage.
.PHONY: cimage-config-create
cimage-config-create:
@$(call HELPTEXT,$@)
$(ECHO) "$$CIMAGE_CONFIG" | bash -c 'cat > htdocs/cimage/img_config.php'
cat htdocs/cimage/img_config.php
|
mafd16/curious-george
|
Makefile
|
Makefile
|
mit
| 8,350 |
"""
Support for Nest thermostats.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/thermostat.nest/
"""
import voluptuous as vol
import homeassistant.components.nest as nest
from homeassistant.components.thermostat import (
STATE_COOL, STATE_HEAT, STATE_IDLE, ThermostatDevice)
from homeassistant.const import TEMP_CELSIUS, CONF_PLATFORM, CONF_SCAN_INTERVAL
DEPENDENCIES = ['nest']
PLATFORM_SCHEMA = vol.Schema({
vol.Required(CONF_PLATFORM): nest.DOMAIN,
vol.Optional(CONF_SCAN_INTERVAL):
vol.All(vol.Coerce(int), vol.Range(min=1)),
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Nest thermostat."""
add_devices([NestThermostat(structure, device)
for structure, device in nest.devices()])
class NestThermostat(ThermostatDevice):
"""Representation of a Nest thermostat."""
def __init__(self, structure, device):
"""Initialize the thermostat."""
self.structure = structure
self.device = device
@property
def name(self):
"""Return the name of the nest, if any."""
location = self.device.where
name = self.device.name
if location is None:
return name
else:
if name == '':
return location.capitalize()
else:
return location.capitalize() + '(' + name + ')'
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return TEMP_CELSIUS
@property
def device_state_attributes(self):
"""Return the device specific state attributes."""
# Move these to Thermostat Device and make them global
return {
"humidity": self.device.humidity,
"target_humidity": self.device.target_humidity,
"mode": self.device.mode
}
@property
def current_temperature(self):
"""Return the current temperature."""
return self.device.temperature
@property
def operation(self):
"""Return current operation ie. heat, cool, idle."""
if self.device.hvac_ac_state is True:
return STATE_COOL
elif self.device.hvac_heater_state is True:
return STATE_HEAT
else:
return STATE_IDLE
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
if self.device.mode == 'range':
low, high = self.target_temperature_low, \
self.target_temperature_high
if self.operation == STATE_COOL:
temp = high
elif self.operation == STATE_HEAT:
temp = low
else:
# If the outside temp is lower than the current temp, consider
# the 'low' temp to the target, otherwise use the high temp
if (self.device.structure.weather.current.temperature <
self.current_temperature):
temp = low
else:
temp = high
else:
if self.is_away_mode_on:
# away_temperature is a low, high tuple. Only one should be set
# if not in range mode, the other will be None
temp = self.device.away_temperature[0] or \
self.device.away_temperature[1]
else:
temp = self.device.target
return temp
@property
def target_temperature_low(self):
"""Return the lower bound temperature we try to reach."""
if self.is_away_mode_on and self.device.away_temperature[0]:
# away_temperature is always a low, high tuple
return self.device.away_temperature[0]
if self.device.mode == 'range':
return self.device.target[0]
return self.target_temperature
@property
def target_temperature_high(self):
"""Return the upper bound temperature we try to reach."""
if self.is_away_mode_on and self.device.away_temperature[1]:
# away_temperature is always a low, high tuple
return self.device.away_temperature[1]
if self.device.mode == 'range':
return self.device.target[1]
return self.target_temperature
@property
def is_away_mode_on(self):
"""Return if away mode is on."""
return self.structure.away
def set_temperature(self, temperature):
"""Set new target temperature."""
if self.device.mode == 'range':
if self.target_temperature == self.target_temperature_low:
temperature = (temperature, self.target_temperature_high)
elif self.target_temperature == self.target_temperature_high:
temperature = (self.target_temperature_low, temperature)
self.device.target = temperature
def turn_away_mode_on(self):
"""Turn away on."""
self.structure.away = True
def turn_away_mode_off(self):
"""Turn away off."""
self.structure.away = False
@property
def is_fan_on(self):
"""Return whether the fan is on."""
return self.device.fan
def turn_fan_on(self):
"""Turn fan on."""
self.device.fan = True
def turn_fan_off(self):
"""Turn fan off."""
self.device.fan = False
@property
def min_temp(self):
"""Identify min_temp in Nest API or defaults if not available."""
temp = self.device.away_temperature.low
if temp is None:
return super().min_temp
else:
return temp
@property
def max_temp(self):
"""Identify max_temp in Nest API or defaults if not available."""
temp = self.device.away_temperature.high
if temp is None:
return super().max_temp
else:
return temp
def update(self):
"""Python-nest has its own mechanism for staying up to date."""
pass
|
mikaelboman/home-assistant
|
homeassistant/components/thermostat/nest.py
|
Python
|
mit
| 6,067 |
using VkNet.Utils;
namespace VkNet.Model.Attachments
{
/// <summary>
/// Информация о документе.
/// См. описание <see href="http://vk.com/dev/doc"/>.
/// </summary>
public class Document : MediaAttachment
{
static Document()
{
RegisterType(typeof (Document), "doc");
}
/// <summary>
/// Название документа.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Размер документа в байтах.
/// </summary>
public long? Size { get; set; }
/// <summary>
/// Расширение документа.
/// </summary>
public string Ext { get; set; }
/// <summary>
/// Адрес документа, по которому его можно загрузить.
/// </summary>
public string Url { get; set; }
/// <summary>
/// Адрес изображения с размером 100x75px (если файл графический).
/// </summary>
public string Photo100 { get; set; }
/// <summary>
/// Адрес изображения с размером 130x100px (если файл графический).
/// </summary>
public string Photo130 { get; set; }
/// <summary>
/// Ключ доступа к закрытым ресурсам
/// </summary>
public string AccessKey { get; set; }
#region Методы
internal static Document FromJson(VkResponse response)
{
var document = new Document();
document.Id = response["did"] ?? response["id"];
document.OwnerId = response["owner_id"];
document.Title = response["title"];
document.Size = response["size"];
document.Ext = response["ext"];
document.Url = response["url"];
document.Photo100 = response["photo_100"];
document.Photo130 = response["photo_130"];
document.AccessKey = response["access_key"];
return document;
}
#endregion
}
}
|
J2GIS/vk
|
VkNet/Model/Attachments/Document.cs
|
C#
|
mit
| 2,275 |
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
#include <glm/glm.hpp>
#include <gl-platform/GLPlatform.hpp>
#include <entity-system/GenericSystem.hpp>
#include <es-systems/SystemCore.hpp>
#include <es-acorn/Acorn.hpp>
#include <es-general/comp/Transform.hpp>
#include <es-general/comp/StaticGlobalTime.hpp>
#include <es-general/comp/StaticCamera.hpp>
#include <es-render/comp/VBO.hpp>
#include <es-render/comp/IBO.hpp>
#include <es-render/comp/CommonUniforms.hpp>
#include <es-render/comp/Shader.hpp>
#include <es-render/comp/Texture.hpp>
#include <es-render/comp/GLState.hpp>
#include <es-render/comp/VecUniform.hpp>
#include <es-render/comp/MatUniform.hpp>
#include <es-render/comp/StaticGLState.hpp>
#include <es-render/comp/StaticVBOMan.hpp>
#include <es-render/comp/StaticTextureMan.hpp>
#include <bserialize/BSerialize.hpp>
#include "../comp/RenderBasicGeom.h"
#include "../comp/SRRenderState.h"
#include "../comp/RenderList.h"
#include "../comp/StaticWorldLight.h"
#include "../comp/StaticClippingPlanes.h"
#include "../comp/LightingUniforms.h"
#include "../comp/ClippingPlaneUniforms.h"
namespace es = spire;
namespace shaders = spire;
// Every component is self contained. It only accesses the systems and
// components that it specifies in it's component list.
namespace SCIRun {
namespace Render {
class RenderTransText :
public spire::GenericSystem<true,
RenderBasicGeom, // TAG class
SRRenderState,
RenderList,
LightingUniforms,
ClippingPlaneUniforms,
gen::Transform,
gen::StaticGlobalTime,
ren::VBO,
ren::IBO,
ren::Texture,
ren::CommonUniforms,
ren::VecUniform,
ren::MatUniform,
ren::Shader,
ren::GLState,
StaticWorldLight,
StaticClippingPlanes,
gen::StaticCamera,
ren::StaticGLState,
ren::StaticVBOMan,
ren::StaticTextureMan>
{
public:
static const char* getName() {return "RenderTransText";}
bool isComponentOptional(uint64_t type) override
{
return spire::OptionalComponents<RenderList,
ren::GLState,
ren::StaticGLState,
ren::CommonUniforms,
LightingUniforms,
ClippingPlaneUniforms,
ren::VecUniform,
ren::MatUniform,
ren::Texture,
ren::StaticTextureMan>(type);
}
void groupExecute(
spire::ESCoreBase&, uint64_t /* entityID */,
const spire::ComponentGroup<RenderBasicGeom>& geom,
const spire::ComponentGroup<SRRenderState>& srstate,
const spire::ComponentGroup<RenderList>& rlist,
const spire::ComponentGroup<LightingUniforms>& lightUniforms,
const spire::ComponentGroup<ClippingPlaneUniforms>& clippingPlaneUniforms,
const spire::ComponentGroup<gen::Transform>& trafo,
const spire::ComponentGroup<gen::StaticGlobalTime>& time,
const spire::ComponentGroup<ren::VBO>& vbo,
const spire::ComponentGroup<ren::IBO>& ibo,
const spire::ComponentGroup<ren::Texture>& textures,
const spire::ComponentGroup<ren::CommonUniforms>& commonUniforms,
const spire::ComponentGroup<ren::VecUniform>& vecUniforms,
const spire::ComponentGroup<ren::MatUniform>& matUniforms,
const spire::ComponentGroup<ren::Shader>& shader,
const spire::ComponentGroup<ren::GLState>& state,
const spire::ComponentGroup<StaticWorldLight>& worldLight,
const spire::ComponentGroup<StaticClippingPlanes>& clippingPlanes,
const spire::ComponentGroup<gen::StaticCamera>& camera,
const spire::ComponentGroup<ren::StaticGLState>& defaultGLState,
const spire::ComponentGroup<ren::StaticVBOMan>& vboMan,
const spire::ComponentGroup<ren::StaticTextureMan>& texMan) override
{
/// \todo This needs to be moved to pre-execute.
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
return;
}
if (!srstate.front().state.get(RenderState::IS_TEXT))
{
return;
}
GLuint iboID = ibo.front().glid;
// Setup *everything*. We don't want to enter multiple conditional
// statements if we can avoid it. So we assume everything has not been
// setup (including uniforms) if the simple geom hasn't been setup.
if (!geom.front().attribs.isSetup())
{
// We use const cast to get around a 'modify' call for 2 reasons:
// 1) This is populating system specific GL data. It has no bearing on the
// actual simulation state.
// 2) It is more correct than issuing a modify call. The data is used
// directly below to render geometry.
const_cast<RenderBasicGeom&>(geom.front()).attribs.setup(
vbo.front().glid, shader.front().glid, vboMan.front());
/// \todo Optimize by pulling uniforms only once.
if (commonUniforms.size() > 0)
{
const_cast<ren::CommonUniforms&>(commonUniforms.front()).checkUniformArray(
shader.front().glid);
}
if (vecUniforms.size() > 0)
{
for (const ren::VecUniform& unif : vecUniforms)
{
const_cast<ren::VecUniform&>(unif).checkUniform(shader.front().glid);
}
}
if (matUniforms.size() > 0)
{
for (const ren::MatUniform& unif : matUniforms)
{
const_cast<ren::MatUniform&>(unif).checkUniform(shader.front().glid);
}
}
if (lightUniforms.size() > 0)
const_cast<LightingUniforms&>(lightUniforms.front()).checkUniformArray(shader.front().glid);
if (clippingPlaneUniforms.size() > 0)
const_cast<ClippingPlaneUniforms&>(clippingPlaneUniforms.front()).checkUniformArray(shader.front().glid);
}
// Check to see if we have GLState. If so, apply it relative to the
// current state (I'm actually thinking GLState is a bad idea, and we
// should just program what we need manually in the system -- depending
// on type). State can be set in a pre-walk phase.
if (state.size() > 0 && defaultGLState.size() > 0)
{
// Apply GLState based on current GLState (the static state), if it is
// present. Otherwise, fully apply it (performance issue).
state.front().state.applyRelative(defaultGLState.front().state);
}
// Bind shader.
GL(glUseProgram(shader.front().glid));
// Bind VBO and IBO
GL(glBindBuffer(GL_ARRAY_BUFFER, vbo.front().glid));
GL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboID));
// Bind any common uniforms.
if (commonUniforms.size() > 0)
{
commonUniforms.front().applyCommonUniforms(
trafo.front().transform, camera.front().data, time.front().globalTime);
}
// Apply vector uniforms (if any).
for (const ren::VecUniform& unif : vecUniforms) {unif.applyUniform();}
if (lightUniforms.size() > 0)
{
std::vector<glm::vec3> lightDir(worldLight.front().lightDir,
worldLight.front().lightDir + LIGHT_NUM);
std::vector<glm::vec3> lightColor(worldLight.front().lightColor,
worldLight.front().lightColor + LIGHT_NUM);
lightUniforms.front().applyUniform(lightDir, lightColor);
}
if (clippingPlaneUniforms.size() > 0)
{
glm::mat4 transform = trafo.front().transform;
clippingPlaneUniforms.front().applyUniforms(transform, clippingPlanes.front().clippingPlanes,
clippingPlanes.front().clippingPlaneCtrls);
}
// Apply matrix uniforms (if any).
for (const ren::MatUniform& unif : matUniforms) {unif.applyUniform();}
// bind textures
for (const ren::Texture& tex : textures)
{
GL(glActiveTexture(GL_TEXTURE0 + tex.textureUnit));
GL(glBindTexture(tex.textureType, tex.glid));
}
geom.front().attribs.bind();
// Disable zwrite if we are rendering a transparent object.
bool depthMask = glIsEnabled(GL_DEPTH_WRITEMASK);
bool cullFace = glIsEnabled(GL_CULL_FACE);
bool blend = glIsEnabled(GL_BLEND);
GL(glEnable(GL_DEPTH_TEST));
GL(glDepthMask(GL_FALSE));
GL(glDisable(GL_CULL_FACE));
GL(glEnable(GL_BLEND));
GL(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
if (rlist.size() > 0)
{
glm::mat4 rlistTrafo = trafo.front().transform;
GLint uniformColorLoc = 0;
for (const ren::VecUniform& unif : vecUniforms)
{
if (std::string(unif.uniformName) == "uColor")
{
uniformColorLoc = unif.uniformLocation;
}
}
// Note: Some of this work can be done beforehand. But we elect not to
// since it is feasible that the data contained in the VBO can change
// fairly dramatically.
// Build BSerialize object.
spire::BSerialize posDeserialize(
rlist.front().data->getBuffer(), rlist.front().data->getBufferSize());
spire::BSerialize colorDeserialize(
rlist.front().data->getBuffer(), rlist.front().data->getBufferSize());
int64_t posSize = 0;
int64_t colorSize = 0;
int64_t stride = 0; // Stride of entire attributes buffer.
// Determine stride for our buffer. Also determine appropriate position
// and color information offsets, and set the offsets. Also determine
// attribute size in bytes.
for (const auto& attrib : rlist.front().attributes)
{
if (attrib.name == "aPos")
{
if (stride != 0) {posDeserialize.readBytes(stride);}
posSize = attrib.sizeInBytes;
}
else if (attrib.name == "aColor")
{
if (stride != 0) {colorDeserialize.readBytes(stride);}
colorSize = attrib.sizeInBytes;
}
stride += attrib.sizeInBytes;
}
int64_t posStride = stride - posSize;
int64_t colorStride = stride - colorSize;
// Render using a draw list. We will be using the VBO and IBO attached
// to this object as the basic rendering primitive.
for (int i = 0; i < rlist.front().numElements; ++i)
{
// Read position.
float x = posDeserialize.read<float>();
float y = posDeserialize.read<float>();
float z = posDeserialize.read<float>();
posDeserialize.readBytes(posStride);
// Read color if available.
if (colorSize > 0)
{
float r = static_cast<float>(colorDeserialize.read<uint8_t>()) / 255.0f;
float g = static_cast<float>(colorDeserialize.read<uint8_t>()) / 255.0f;
float b = static_cast<float>(colorDeserialize.read<uint8_t>()) / 255.0f;
float a = static_cast<float>(colorDeserialize.read<uint8_t>()) / 255.0f;
if (colorDeserialize.getBytesLeft() > colorStride)
{
colorDeserialize.readBytes(colorStride);
}
GL(glUniform4f(uniformColorLoc, r, g, b, a));
}
// Update transform.
rlistTrafo[3].x = x;
rlistTrafo[3].y = y;
rlistTrafo[3].z = z;
commonUniforms.front().applyCommonUniforms(
rlistTrafo, camera.front().data, time.front().globalTime);
GL(glDrawElements(ibo.front().primMode, ibo.front().numPrims,
ibo.front().primType, 0));
}
}
else
{
if (!srstate.front().state.get(RenderState::IS_DOUBLE_SIDED))
{
GL(glDrawElements(ibo.front().primMode, ibo.front().numPrims,
ibo.front().primType, 0));
}
else
{
GL(glEnable(GL_CULL_FACE));
// Double sided rendering. Mimic SCIRun4 and use GL_FRONT and GL_BACK
// to mimic forward facing and back facing polygons.
// Draw front facing polygons.
GLint fdToggleLoc = glGetUniformLocation(shader.front().glid, "uFDToggle");
GL(glUniform1f(fdToggleLoc, 1.0f));
glCullFace(GL_BACK);
GL(glDrawElements(ibo.front().primMode, ibo.front().numPrims,
ibo.front().primType, 0));
GL(glUniform1f(fdToggleLoc, 0.0f));
glCullFace(GL_FRONT);
GL(glDrawElements(ibo.front().primMode, ibo.front().numPrims,
ibo.front().primType, 0));
}
}
if (depthMask)
{
GL(glDepthMask(GL_TRUE));
}
if (cullFace)
{
GL(glEnable(GL_CULL_FACE));
}
if (!blend)
{
GL(glDisable(GL_BLEND));
}
// unbind textures
for (const ren::Texture& tex : textures)
{
GL(glActiveTexture(GL_TEXTURE0 + tex.textureUnit));
GL(glBindTexture(tex.textureType, 0));
}
geom.front().attribs.unbind();
// Reapply the default state here -- only do this if static state is
// present.
if (state.size() > 0 && defaultGLState.size() > 0)
{
defaultGLState.front().state.applyRelative(state.front().state);
}
}
};
void registerSystem_RenderTransTextGeom(spire::Acorn& core)
{
core.registerSystem<RenderTransText>();
}
const char* getSystemName_RenderTransTextGeom()
{
return RenderTransText::getName();
}
} // namespace Render
} // namespace SCIRun
|
ajanson/SCIRun
|
src/Interface/Modules/Render/ES/systems/RenderTransText.cc
|
C++
|
mit
| 14,834 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ar" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Duckduckcoin</source>
<translation>عن Duckduckcoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Duckduckcoin</b> version</source>
<translation>نسخة <b>Duckduckcoin</b></translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The Duckduckcoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>دفتر العناوين</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>أنقر على الماوس مرتين لتعديل عنوان</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>قم بعمل عنوان جديد</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>قم بنسخ القوانين المختارة لحافظة النظام</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Duckduckcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Duckduckcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Duckduckcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&أمسح</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Duckduckcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-56"/>
<source>Duckduckcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your duckduckcoins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>DuckduckcoinGUI</name>
<message>
<location filename="../duckduckcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Show information about Duckduckcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Duckduckcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Duckduckcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Duckduckcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Duckduckcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Duckduckcoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Duckduckcoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Duckduckcoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Duckduckcoin network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Duckduckcoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../duckduckcoin.cpp" line="+111"/>
<source>A fatal error occurred. Duckduckcoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Duckduckcoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Duckduckcoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start Duckduckcoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start Duckduckcoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Duckduckcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the Duckduckcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Duckduckcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show Duckduckcoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Duckduckcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Duckduckcoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start duckduckcoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Duckduckcoin-Qt help message to get a list with possible Duckduckcoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>Duckduckcoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Duckduckcoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Duckduckcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Duckduckcoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>123.456 DDC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Duckduckcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Duckduckcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Duckduckcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Duckduckcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Duckduckcoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Duckduckcoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>duckduckcoin-core</name>
<message>
<location filename="../duckduckcoinstrings.cpp" line="+94"/>
<source>Duckduckcoin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or duckduckcoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: duckduckcoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: duckduckcoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 34465 or testnet: 134465)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 34464 or testnet: 134464)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=duckduckcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Duckduckcoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Duckduckcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Duckduckcoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Duckduckcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Duckduckcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Duckduckcoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Duckduckcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS>
|
bankonme/duckduckcoin
|
src/qt/locale/bitcoin_ar.ts
|
TypeScript
|
mit
| 97,905 |
---
title: Export User Data To MailChimp
description: Learn how to export your Auth0 user data and import it into MailChimp.
toc: true
topics:
- marketing
- mailchimp
contentType: how-to
useCase: export-users-marketing
---
# Export User Data To MailChimp
In this article, you’ll learn how to export user data in Auth0 to a CSV file then import it into the [MailChimp dashboard](https://login.mailchimp.com/).
## Create a user data file
Start by navigating to the [Extensions](${manage_url}/#/extensions) section of the Dashboard and open the **User Import / Export Extension**. On the extension page, select **Export** from the menu.
Next, set the **Export Format** to the required file format. MailChimp accepts file imports in CSV format so choose the `Tab Separated Value file (*.csv)` option.

At the top in the **Fields** section, provide a **User Field** and **Column Name** for each user attribute to include in the export. For MailChimp, an email field with the column name `Email Address` is required, so make sure to include it. For example:
User Field | Column Name
-----------|------------
`email` | Email Address
`created_at` | Created At
`given_name` | First Name
`family_name` | Last Name

::: note
[MailChimp Knowledge Base: Format Guidelines for Your Import File](https://kb.mailchimp.com/lists/growth/format-guidelines-for-your-import-file)
:::
After adding the user fields, click on the **Export Users** button to start the export. Once the export is complete, download the CSV file to use in the following section.
## Import a user data file
::: note
[MailChimp Knowledge Base: Import Subscribers to a List](https://kb.mailchimp.com/lists/growth/import-subscribers-to-a-list)
:::
Log in to your MailChimp account and go to the **Lists** page. Select a list to import your Auth0 users into ([or create a new list](https://kb.mailchimp.com/lists/growth/create-a-new-list)). On your MailChimp List page, click on **Import Contacts** from the **Add Contacts** menu.

On the next page, select the `CSV or tab-delimited text file` option to import contacts from.

Next, upload the user data CSV file you exported from Auth0 in the previous section. MailChimp will interpret your user data on the following page.

Check that the column names and field types are correct, when you're ready to proceed click the **Next** button.

After reviewing your selections and setting the import category, click on the **Import** button to start the user import.
That's it! You successfully imported your Auth0 users into MailChimp.
|
yvonnewilson/docs
|
articles/integrations/marketing/mailchimp/index.md
|
Markdown
|
mit
| 3,177 |
# HTML5 History Test
This file cannot be tested automatically at the moment.
Safari (WebKit?) demands that the base href is set at this will change between the unit-testing server and
the manual server. HTML5 history tests must be run manually for now.
|
finnsson/pagerjs
|
test_html5/README.md
|
Markdown
|
mit
| 254 |
<?php
/**
* @package Grav.Common
*
* @copyright Copyright (C) 2014 - 2017 RocketTheme, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use DateTime;
use Grav\Common\Helpers\Truncator;
use RocketTheme\Toolbox\Event\Event;
abstract class Utils
{
protected static $nonces = [];
/**
* Check if the $haystack string starts with the substring $needle
*
* @param string $haystack
* @param string $needle
*
* @return bool
*/
public static function startsWith($haystack, $needle)
{
if (is_array($needle)) {
$status = false;
foreach ($needle as $each_needle) {
$status = $status || ($each_needle === '' || strpos($haystack, $each_needle) === 0);
if ($status) {
return $status;
}
}
return $status;
}
return $needle === '' || strpos($haystack, $needle) === 0;
}
/**
* Check if the $haystack string ends with the substring $needle
*
* @param string $haystack
* @param string $needle
*
* @return bool
*/
public static function endsWith($haystack, $needle)
{
if (is_array($needle)) {
$status = false;
foreach ($needle as $each_needle) {
$status = $status || ($each_needle === '' || substr($haystack, -strlen($each_needle)) === $each_needle);
if ($status) {
return $status;
}
}
return $status;
}
return $needle === '' || substr($haystack, -strlen($needle)) === $needle;
}
/**
* Check if the $haystack string contains the substring $needle
*
* @param string $haystack
* @param string $needle
*
* @return bool
*/
public static function contains($haystack, $needle)
{
return $needle === '' || strpos($haystack, $needle) !== false;
}
/**
* Returns the substring of a string up to a specified needle. if not found, return the whole haytack
*
* @param $haystack
* @param $needle
*
* @return string
*/
public static function substrToString($haystack, $needle)
{
if (static::contains($haystack, $needle)) {
return substr($haystack, 0, strpos($haystack, $needle));
}
return $haystack;
}
/**
* Merge two objects into one.
*
* @param object $obj1
* @param object $obj2
*
* @return object
*/
public static function mergeObjects($obj1, $obj2)
{
return (object)array_merge((array)$obj1, (array)$obj2);
}
/**
* Recursive Merge with uniqueness
*
* @param $array1
* @param $array2
* @return mixed
*/
public static function arrayMergeRecursiveUnique($array1, $array2)
{
if (empty($array1)) return $array2; //optimize the base case
foreach ($array2 as $key => $value) {
if (is_array($value) && is_array(@$array1[$key])) {
$value = static::arrayMergeRecursiveUnique($array1[$key], $value);
}
$array1[$key] = $value;
}
return $array1;
}
/**
* Return the Grav date formats allowed
*
* @return array
*/
public static function dateFormats()
{
$now = new DateTime();
$date_formats = [
'd-m-Y H:i' => 'd-m-Y H:i (e.g. '.$now->format('d-m-Y H:i').')',
'Y-m-d H:i' => 'Y-m-d H:i (e.g. '.$now->format('Y-m-d H:i').')',
'm/d/Y h:i a' => 'm/d/Y h:i a (e.g. '.$now->format('m/d/Y h:i a').')',
'H:i d-m-Y' => 'H:i d-m-Y (e.g. '.$now->format('H:i d-m-Y').')',
'h:i a m/d/Y' => 'h:i a m/d/Y (e.g. '.$now->format('h:i a m/d/Y').')',
];
$default_format = Grav::instance()['config']->get('system.pages.dateformat.default');
if ($default_format) {
$date_formats = array_merge([$default_format => $default_format.' (e.g. '.$now->format($default_format).')'], $date_formats);
}
return $date_formats;
}
/**
* Truncate text by number of characters but can cut off words.
*
* @param string $string
* @param int $limit Max number of characters.
* @param bool $up_to_break truncate up to breakpoint after char count
* @param string $break Break point.
* @param string $pad Appended padding to the end of the string.
*
* @return string
*/
public static function truncate($string, $limit = 150, $up_to_break = false, $break = " ", $pad = "…")
{
// return with no change if string is shorter than $limit
if (mb_strlen($string) <= $limit) {
return $string;
}
// is $break present between $limit and the end of the string?
if ($up_to_break && false !== ($breakpoint = mb_strpos($string, $break, $limit))) {
if ($breakpoint < mb_strlen($string) - 1) {
$string = mb_substr($string, 0, $breakpoint) . $break;
}
} else {
$string = mb_substr($string, 0, $limit) . $pad;
}
return $string;
}
/**
* Truncate text by number of characters in a "word-safe" manor.
*
* @param string $string
* @param int $limit
*
* @return string
*/
public static function safeTruncate($string, $limit = 150)
{
return static::truncate($string, $limit, true);
}
/**
* Truncate HTML by number of characters. not "word-safe"!
*
* @param string $text
* @param int $length in characters
* @param string $ellipsis
*
* @return string
*/
public static function truncateHtml($text, $length = 100, $ellipsis = '...')
{
if (mb_strlen($text) <= $length) {
return $text;
} else {
return Truncator::truncateLetters($text, $length, $ellipsis);
}
}
/**
* Truncate HTML by number of characters in a "word-safe" manor.
*
* @param string $text
* @param int $length in words
* @param string $ellipsis
*
* @return string
*/
public static function safeTruncateHtml($text, $length = 25, $ellipsis = '...')
{
return Truncator::truncateWords($text, $length, $ellipsis);
}
/**
* Generate a random string of a given length
*
* @param int $length
*
* @return string
*/
public static function generateRandomString($length = 5)
{
return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
}
/**
* Provides the ability to download a file to the browser
*
* @param string $file the full path to the file to be downloaded
* @param bool $force_download as opposed to letting browser choose if to download or render
* @param int $sec Throttling, try 0.1 for some speed throttling of downloads
* @param int $bytes Size of chunks to send in bytes. Default is 1024
* @throws \Exception
*/
public static function download($file, $force_download = true, $sec = 0, $bytes = 1024)
{
if (file_exists($file)) {
// fire download event
Grav::instance()->fireEvent('onBeforeDownload', new Event(['file' => $file]));
$file_parts = pathinfo($file);
$mimetype = Utils::getMimeByExtension($file_parts['extension']);
$size = filesize($file); // File size
// clean all buffers
while (ob_get_level()) {
ob_end_clean();
}
// required for IE, otherwise Content-Disposition may be ignored
if (ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
header("Content-Type: " . $mimetype);
header('Accept-Ranges: bytes');
if ($force_download) {
// output the regular HTTP headers
header('Content-Disposition: attachment; filename="' . $file_parts['basename'] . '"');
}
// multipart-download and download resuming support
if (isset($_SERVER['HTTP_RANGE'])) {
list($a, $range) = explode("=", $_SERVER['HTTP_RANGE'], 2);
list($range) = explode(",", $range, 2);
list($range, $range_end) = explode("-", $range);
$range = intval($range);
if (!$range_end) {
$range_end = $size - 1;
} else {
$range_end = intval($range_end);
}
$new_length = $range_end - $range + 1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: $new_length");
header("Content-Range: bytes $range-$range_end/$size");
} else {
$new_length = $size;
header("Content-Length: " . $size);
if (Grav::instance()['config']->get('system.cache.enabled')) {
$expires = Grav::instance()['config']->get('system.pages.expires');
if ($expires > 0) {
$expires_date = gmdate('D, d M Y H:i:s T', time() + $expires);
header('Cache-Control: max-age=' . $expires);
header('Expires: ' . $expires_date);
header('Pragma: cache');
}
header('Last-Modified: ' . gmdate("D, d M Y H:i:s T", filemtime($file)));
// Return 304 Not Modified if the file is already cached in the browser
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($file))
{
header('HTTP/1.1 304 Not Modified');
exit();
}
}
}
/* output the file itself */
$chunksize = $bytes * 8; //you may want to change this
$bytes_send = 0;
$fp = @fopen($file, 'r');
if ($fp) {
if (isset($_SERVER['HTTP_RANGE'])) {
fseek($fp, $range);
}
while (!feof($fp) && (!connection_aborted()) && ($bytes_send < $new_length) ) {
$buffer = fread($fp, $chunksize);
echo($buffer); //echo($buffer); // is also possible
flush();
usleep($sec * 1000000);
$bytes_send += strlen($buffer);
}
fclose($fp);
} else {
throw new \Exception('Error - can not open file.');
}
exit;
}
}
/**
* Return the mimetype based on filename extension
*
* @param string $extension Extension of file (eg "txt")
* @param string $default
*
* @return string
*/
public static function getMimeByExtension($extension, $default = 'application/octet-stream')
{
$extension = strtolower($extension);
// look for some standard types
switch ($extension) {
case null:
return $default;
case 'json':
return 'application/json';
case 'html':
return 'text/html';
case 'atom':
return 'application/atom+xml';
case 'rss':
return 'application/rss+xml';
case 'xml':
return 'application/xml';
}
$media_types = Grav::instance()['config']->get('media.types');
if (isset($media_types[$extension])) {
if (isset($media_types[$extension]['mime'])) {
return $media_types[$extension]['mime'];
}
}
return $default;
}
/**
* Return the mimetype based on filename extension
*
* @param string $mime mime type (eg "text/html")
* @param string $default default value
*
* @return string
*/
public static function getExtensionByMime($mime, $default = 'html')
{
$mime = strtolower($mime);
// look for some standard mime types
switch ($mime) {
case '*/*':
case 'text/*':
case 'text/html':
return 'html';
case 'application/json':
return 'json';
case 'application/atom+xml':
return 'atom';
case 'application/rss+xml':
return 'rss';
case 'application/xml':
return 'xml';
}
$media_types = Grav::instance()['config']->get('media.types');
foreach ($media_types as $extension => $type) {
if ($extension == 'defaults') {
continue;
}
if (isset($type['mime']) && $type['mime'] == $mime) {
return $extension;
}
}
return $default;
}
/**
* Normalize path by processing relative `.` and `..` syntax and merging path
*
* @param string $path
*
* @return string
*/
public static function normalizePath($path)
{
$root = ($path[0] === '/') ? '/' : '';
$segments = explode('/', trim($path, '/'));
$ret = [];
foreach ($segments as $segment) {
if (($segment == '.') || strlen($segment) == 0) {
continue;
}
if ($segment == '..') {
array_pop($ret);
} else {
array_push($ret, $segment);
}
}
return $root . implode('/', $ret);
}
/**
* Check whether a function is disabled in the PHP settings
*
* @param string $function the name of the function to check
*
* @return bool
*/
public static function isFunctionDisabled($function)
{
return in_array($function, explode(',', ini_get('disable_functions')));
}
/**
* Get the formatted timezones list
*
* @return array
*/
public static function timezones()
{
$timezones = \DateTimeZone::listIdentifiers(\DateTimeZone::ALL);
$offsets = [];
$testDate = new \DateTime;
foreach ($timezones as $zone) {
$tz = new \DateTimeZone($zone);
$offsets[$zone] = $tz->getOffset($testDate);
}
asort($offsets);
$timezone_list = [];
foreach ($offsets as $timezone => $offset) {
$offset_prefix = $offset < 0 ? '-' : '+';
$offset_formatted = gmdate('H:i', abs($offset));
$pretty_offset = "UTC${offset_prefix}${offset_formatted}";
$timezone_list[$timezone] = "(${pretty_offset}) ".str_replace('_', ' ', $timezone);
}
return $timezone_list;
}
/**
* Recursively filter an array, filtering values by processing them through the $fn function argument
*
* @param array $source the Array to filter
* @param callable $fn the function to pass through each array item
*
* @return array
*/
public static function arrayFilterRecursive(Array $source, $fn)
{
$result = [];
foreach ($source as $key => $value) {
if (is_array($value)) {
$result[$key] = static::arrayFilterRecursive($value, $fn);
continue;
}
if ($fn($key, $value)) {
$result[$key] = $value; // KEEP
continue;
}
}
return $result;
}
/**
* Flatten an array
*
* @param $array
* @return array
*/
public static function arrayFlatten($array)
{
$flatten = array();
foreach ($array as $key => $inner){
if (is_array($inner)) {
foreach ($inner as $inner_key => $value) {
$flatten[$inner_key] = $value;
}
} else {
$flatten[$key] = $inner;
}
}
return $flatten;
}
/**
* Checks if the passed path contains the language code prefix
*
* @param string $string The path
*
* @return bool
*/
public static function pathPrefixedByLangCode($string)
{
if (strlen($string) <= 3) {
return false;
}
$languages_enabled = Grav::instance()['config']->get('system.languages.supported', []);
if ($string[0] == '/' && $string[3] == '/' && in_array(substr($string, 1, 2), $languages_enabled)) {
return true;
}
return false;
}
/**
* Get the timestamp of a date
*
* @param string $date a String expressed in the system.pages.dateformat.default format, with fallback to a
* strtotime argument
* @param string $format a date format to use if possible
* @return int the timestamp
*/
public static function date2timestamp($date, $format = null)
{
$config = Grav::instance()['config'];
$dateformat = $format ?: $config->get('system.pages.dateformat.default');
// try to use DateTime and default format
if ($dateformat) {
$datetime = DateTime::createFromFormat($dateformat, $date);
} else {
$datetime = new DateTime($date);
}
// fallback to strtotime if DateTime approach failed
if ($datetime !== false) {
return $datetime->getTimestamp();
} else {
return strtotime($date);
}
}
/**
* @deprecated Use getDotNotation() method instead
*
*/
public static function resolve(array $array, $path, $default = null)
{
return static::getDotNotation($array, $path, $default);
}
/**
* Checks if a value is positive
*
* @param string $value
*
* @return boolean
*/
public static function isPositive($value)
{
return in_array($value, [true, 1, '1', 'yes', 'on', 'true'], true);
}
/**
* Generates a nonce string to be hashed. Called by self::getNonce()
* We removed the IP portion in this version because it causes too many inconsistencies
* with reverse proxy setups.
*
* @param string $action
* @param bool $plusOneTick if true, generates the token for the next tick (the next 12 hours)
*
* @return string the nonce string
*/
private static function generateNonceString($action, $plusOneTick = false)
{
$username = '';
if (isset(Grav::instance()['user'])) {
$user = Grav::instance()['user'];
$username = $user->username;
}
$token = session_id();
$i = self::nonceTick();
if ($plusOneTick) {
$i++;
}
return ($i . '|' . $action . '|' . $username . '|' . $token . '|' . Grav::instance()['config']->get('security.salt'));
}
//Added in version 1.0.8 to ensure that existing nonces are not broken.
private static function generateNonceStringOldStyle($action, $plusOneTick = false)
{
if (isset(Grav::instance()['user'])) {
$user = Grav::instance()['user'];
$username = $user->username;
if (isset($_SERVER['REMOTE_ADDR'])) {
$username .= $_SERVER['REMOTE_ADDR'];
}
} else {
$username = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
}
$token = session_id();
$i = self::nonceTick();
if ($plusOneTick) {
$i++;
}
return ($i . '|' . $action . '|' . $username . '|' . $token . '|' . Grav::instance()['config']->get('security.salt'));
}
/**
* Get the time-dependent variable for nonce creation.
*
* Now a tick lasts a day. Once the day is passed, the nonce is not valid any more. Find a better way
* to ensure nonces issued near the end of the day do not expire in that small amount of time
*
* @return int the time part of the nonce. Changes once every 24 hours
*/
private static function nonceTick()
{
$secondsInHalfADay = 60 * 60 * 12;
return (int)ceil(time() / ($secondsInHalfADay));
}
/**
* Creates a hashed nonce tied to the passed action. Tied to the current user and time. The nonce for a given
* action is the same for 12 hours.
*
* @param string $action the action the nonce is tied to (e.g. save-user-admin or move-page-homepage)
* @param bool $plusOneTick if true, generates the token for the next tick (the next 12 hours)
*
* @return string the nonce
*/
public static function getNonce($action, $plusOneTick = false)
{
// Don't regenerate this again if not needed
if (isset(static::$nonces[$action])) {
return static::$nonces[$action];
}
$nonce = md5(self::generateNonceString($action, $plusOneTick));
static::$nonces[$action] = $nonce;
return static::$nonces[$action];
}
//Added in version 1.0.8 to ensure that existing nonces are not broken.
public static function getNonceOldStyle($action, $plusOneTick = false)
{
// Don't regenerate this again if not needed
if (isset(static::$nonces[$action])) {
return static::$nonces[$action];
}
$nonce = md5(self::generateNonceStringOldStyle($action, $plusOneTick));
static::$nonces[$action] = $nonce;
return static::$nonces[$action];
}
/**
* Verify the passed nonce for the give action
*
* @param string $nonce the nonce to verify
* @param string $action the action to verify the nonce to
*
* @return boolean verified or not
*/
public static function verifyNonce($nonce, $action)
{
//Safety check for multiple nonces
if (is_array($nonce)) {
$nonce = array_shift($nonce);
}
//Nonce generated 0-12 hours ago
if ($nonce == self::getNonce($action)) {
return true;
}
//Nonce generated 12-24 hours ago
$plusOneTick = true;
if ($nonce == self::getNonce($action, $plusOneTick)) {
return true;
}
//Added in version 1.0.8 to ensure that existing nonces are not broken.
//Nonce generated 0-12 hours ago
if ($nonce == self::getNonceOldStyle($action)) {
return true;
}
//Nonce generated 12-24 hours ago
$plusOneTick = true;
if ($nonce == self::getNonceOldStyle($action, $plusOneTick)) {
return true;
}
//Invalid nonce
return false;
}
/**
* Simple helper method to get whether or not the admin plugin is active
*
* @return bool
*/
public static function isAdminPlugin()
{
if (isset(Grav::instance()['admin'])) {
return true;
}
return false;
}
/**
* Get a portion of an array (passed by reference) with dot-notation key
*
* @param $array
* @param $key
* @param null $default
* @return mixed
*/
public static function getDotNotation($array, $key, $default = null)
{
if (is_null($key)) return $array;
if (isset($array[$key])) return $array[$key];
foreach (explode('.', $key) as $segment)
{
if ( ! is_array($array) ||
! array_key_exists($segment, $array))
{
return $default;
}
$array = $array[$segment];
}
return $array;
}
/**
* Set portion of array (passed by reference) for a dot-notation key
* and set the value
*
* @param $array
* @param $key
* @param $value
* @param bool $merge
*
* @return mixed
*/
public static function setDotNotation(&$array, $key, $value, $merge = false)
{
if (is_null($key)) return $array = $value;
$keys = explode('.', $key);
while (count($keys) > 1)
{
$key = array_shift($keys);
if ( ! isset($array[$key]) || ! is_array($array[$key]))
{
$array[$key] = array();
}
$array =& $array[$key];
}
$key = array_shift($keys);
if (!$merge || !isset($array[$key])) {
$array[$key] = $value;
} else {
$array[$key] = array_merge($array[$key], $value);
}
return $array;
}
/**
* Utility method to determine if the current OS is Windows
*
* @return bool
*/
public static function isWindows() {
return strncasecmp(PHP_OS, 'WIN', 3) == 0;
}
/**
* Utility to determine if the server running PHP is Apache
*
* @return bool
*/
public static function isApache() {
return strpos($_SERVER["SERVER_SOFTWARE"], 'Apache') !== false;
}
/**
* Sort a multidimensional array by another array of ordered keys
*
* @param array $array
* @param array $orderArray
* @return array
*/
public static function sortArrayByArray(array $array, array $orderArray) {
$ordered = array();
foreach ($orderArray as $key) {
if (array_key_exists($key, $array)) {
$ordered[$key] = $array[$key];
unset($array[$key]);
}
}
return $ordered + $array;
}
/**
* Get's path based on a token
*
* @param $path
* @param null $page
* @return string
*/
public static function getPagePathFromToken($path, $page = null)
{
$path_parts = pathinfo($path);
$grav = Grav::instance();
$basename = '';
if (isset($path_parts['extension'])) {
$basename = '/' . $path_parts['basename'];
$path = rtrim($path_parts['dirname'], ':');
}
$regex = '/(@self|self@)|((?:@page|page@):(?:.*))|((?:@theme|theme@):(?:.*))/';
preg_match($regex, $path, $matches);
if ($matches) {
if ($matches[1]) {
if (is_null($page)) {
throw new \RuntimeException('Page not available for this self@ reference');
}
} elseif ($matches[2]) {
// page@
$parts = explode(':', $path);
$route = $parts[1];
$page = $grav['page']->find($route);
} elseif ($matches[3]) {
// theme@
$parts = explode(':', $path);
$route = $parts[1];
$theme = str_replace(ROOT_DIR, '', $grav['locator']->findResource("theme://"));
return $theme . $route . $basename;
}
} else {
return $path . $basename;
}
if (!$page) {
throw new \RuntimeException('Page route not found: ' . $path);
}
$path = str_replace($matches[0], rtrim($page->relativePagePath(), '/'), $path);
return $path . $basename;
}
public static function getUploadLimit()
{
static $max_size = -1;
if ($max_size < 0) {
$post_max_size = static::parseSize(ini_get('post_max_size'));
if ($post_max_size > 0) {
$max_size = $post_max_size;
}
$upload_max = static::parseSize(ini_get('upload_max_filesize'));
if ($upload_max > 0 && $upload_max < $max_size) {
$max_size = $upload_max;
}
}
return $max_size;
}
/**
* Parse a readable file size and return a value in bytes
*
* @param $size
* @return int
*/
public static function parseSize($size)
{
$unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
$size = preg_replace('/[^0-9\.]/', '', $size);
if ($unit) {
return intval($size * pow(1024, stripos('bkmgtpezy', $unit[0])));
} else {
return intval($size);
}
}
}
|
floede/freeplay-blog
|
system/src/Grav/Common/Utils.php
|
PHP
|
mit
| 28,551 |
% Copyright (C) 2002 Jörg Lehmann <[email protected]>
% Copyright (C) 2002 André Wobst <[email protected]>
%
% This file is part of PyX (http://pyx.sourceforge.net/).
%
% PyX 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 2 of the License, or
% (at your option) any later version.
%
% PyX 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 PyX; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\endlinechar=-1 % don't add tailing space while \read
\message{latex style name (e.g. 12ptex)? }
\read-1 to\latexstylename
\message{latex class name (e.g. article)? }
\read-1 to\latexclassname
\message{latex class options (e.g. 12pt)? }
\read-1 to\latexclassopt
\message{initial commands (e.g. \string\usepackage\string{exscale\string})? }
\read-1 to\latexinit
\endlinechar=13
\newwrite\myfile
\newbox\mybox
\documentclass[\latexclassopt]{\latexclassname}
\latexinit
\newcommand{\writefontsize}[1]{
\setbox\mybox=\hbox{#1
a $a$
\immediate\write\myfile{%
\string\def\string#1{%
\string\font\string\pyxfont=\fontname\font
\string\pyxfont
\string\font\string\pyxfonttfa=\fontname\textfont0
\string\textfont0=\string\pyxfonttfa
\string\font\string\pyxfontsfa=\fontname\scriptfont0
\string\scriptfont0=\string\pyxfontsfa
\string\font\string\pyxfontssfa=\fontname\scriptscriptfont0
\string\scriptscriptfont0=\string\pyxfontssfa
\string\font\string\pyxfonttfb=\fontname\textfont1
\string\textfont1=\string\pyxfonttfb
\string\font\string\pyxfontsfb=\fontname\scriptfont1
\string\scriptfont1=\string\pyxfontsfb
\string\font\string\pyxfontssfb=\fontname\scriptscriptfont1
\string\scriptscriptfont1=\string\pyxfontssfb
\string\font\string\pyxfonttfc=\fontname\textfont2
\string\textfont2=\string\pyxfonttfc
\string\font\string\pyxfontsfc=\fontname\scriptfont2
\string\scriptfont2=\string\pyxfontsfc
\string\font\string\pyxfontssfc=\fontname\scriptscriptfont2
\string\scriptscriptfont2=\string\pyxfontssfc
\string\font\string\pyxfonttfd=\fontname\textfont3
\string\textfont3=\string\pyxfonttfd
\string\font\string\pyxfontsfd=\fontname\scriptfont3
\string\scriptfont3=\string\pyxfontsfd
\string\font\string\pyxfontssfd=\fontname\scriptscriptfont3
\string\scriptscriptfont3=\string\pyxfontssfd
}%
}
}
}
\begin{document}
\immediate\openout\myfile=\latexstylename.lfs
{\catcode`\%=12\immediate\write\myfile{% This automatically generated file is part of PyX (http://pyx.sourceforge.net/).}}
{\catcode`\%=12\immediate\write\myfile{% \string\latexstylename="\expandafter\string\latexstylename"}}
{\catcode`\%=12\immediate\write\myfile{% \string\latexclassname="\expandafter\string\latexclassname"}}
{\catcode`\%=12\immediate\write\myfile{% \string\latexclassopt="\expandafter\string\latexclassopt"}}
{\catcode`\%=12\immediate\write\myfile{% \string\latexinit="\expandafter\string\latexinit"}}
\writefontsize{\tiny}
\writefontsize{\scriptsize}
\writefontsize{\footnotesize}
\writefontsize{\small}
\writefontsize{\normalsize}
\writefontsize{\large}
\writefontsize{\Large}
\writefontsize{\LARGE}
\writefontsize{\huge}
\writefontsize{\Huge}
\immediate\closeout\myfile
\end{document}
|
paradigmsort/MagicValidate
|
pyx/data/lfs/createlfs.tex
|
TeX
|
mit
| 3,773 |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2013 ecdsa@github
#
# 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.
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from electrum.i18n import _
from util import *
from qrtextedit import ShowQRTextEdit, ScanQRTextEdit
def seed_warning_msg(seed):
return ''.join([
"<p>",
_("Please save these %d words on paper (order is important). "),
_("This seed will allow you to recover your wallet in case "
"of computer failure."),
"</p>",
"<b>" + _("WARNING") + ":</b>",
"<ul>",
"<li>" + _("Never disclose your seed.") + "</li>",
"<li>" + _("Never type it on a website.") + "</li>",
"<li>" + _("Do not store it electronically.") + "</li>",
"</ul>"
]) % len(seed.split())
class SeedLayout(QVBoxLayout):
#options
is_bip39 = False
is_ext = False
def seed_options(self):
dialog = QDialog()
vbox = QVBoxLayout(dialog)
if 'ext' in self.options:
cb_ext = QCheckBox(_('Extend this seed with custom words'))
cb_ext.setChecked(self.is_ext)
vbox.addWidget(cb_ext)
if 'bip39' in self.options:
def f(b):
if b:
msg = ' '.join([
'<b>' + _('Warning') + '</b>' + ': ',
_('BIP39 seeds may not be supported in the future.'),
'<br/><br/>',
_('As technology matures, Bitcoin address generation may change.'),
_('However, BIP39 seeds do not include a version number.'),
_('As a result, it is not possible to infer your wallet type from a BIP39 seed.'),
'<br/><br/>',
_('We do not guarantee that BIP39 seeds will be supported in future versions of Electrum.'),
_('We recommend to use seeds generated by Electrum or compatible wallets.'),
])
#self.parent.show_warning(msg)
self.seed_type_label.setVisible(not b)
self.is_seed = (lambda x: bool(x)) if b else self.saved_is_seed
self.on_edit()
cb_bip39 = QCheckBox(_('BIP39 seed'))
cb_bip39.toggled.connect(f)
cb_bip39.setChecked(self.is_bip39)
vbox.addWidget(cb_bip39)
vbox.addLayout(Buttons(OkButton(dialog)))
if not dialog.exec_():
return None
self.is_ext = cb_ext.isChecked() if 'ext' in self.options else False
self.is_bip39 = cb_bip39.isChecked() if 'bip39' in self.options else False
def __init__(self, seed=None, title=None, icon=True, msg=None, options=None, is_seed=None, passphrase=None, parent=None):
QVBoxLayout.__init__(self)
self.parent = parent
self.options = options
if title:
self.addWidget(WWLabel(title))
if seed:
self.seed_e = ShowQRTextEdit()
self.seed_e.setText(seed)
else:
self.seed_e = ScanQRTextEdit()
self.seed_e.setTabChangesFocus(True)
self.is_seed = is_seed
self.saved_is_seed = self.is_seed
self.seed_e.textChanged.connect(self.on_edit)
self.seed_e.setMaximumHeight(75)
hbox = QHBoxLayout()
if icon:
logo = QLabel()
logo.setPixmap(QPixmap(":icons/seed.png").scaledToWidth(64))
logo.setMaximumWidth(60)
hbox.addWidget(logo)
hbox.addWidget(self.seed_e)
self.addLayout(hbox)
hbox = QHBoxLayout()
hbox.addStretch(1)
self.seed_type_label = QLabel('')
hbox.addWidget(self.seed_type_label)
if options:
opt_button = EnterButton(_('Options'), self.seed_options)
hbox.addWidget(opt_button)
self.addLayout(hbox)
if passphrase:
hbox = QHBoxLayout()
passphrase_e = QLineEdit()
passphrase_e.setText(passphrase)
passphrase_e.setReadOnly(True)
hbox.addWidget(QLabel(_("Your seed extension is") + ':'))
hbox.addWidget(passphrase_e)
self.addLayout(hbox)
self.addStretch(1)
if msg:
msg = seed_warning_msg(seed)
self.addWidget(WWLabel(msg))
def get_seed(self):
text = unicode(self.seed_e.text())
return ' '.join(text.split())
def on_edit(self):
from electrum.bitcoin import seed_type
s = self.get_seed()
b = self.is_seed(s)
t = seed_type(s)
label = _('Seed Type') + ': ' + t if t else ''
self.seed_type_label.setText(label)
self.parent.next_button.setEnabled(b)
class KeysLayout(QVBoxLayout):
def __init__(self, parent=None, title=None, is_valid=None):
QVBoxLayout.__init__(self)
self.parent = parent
self.is_valid = is_valid
self.text_e = ScanQRTextEdit()
self.text_e.textChanged.connect(self.on_edit)
self.addWidget(WWLabel(title))
self.addWidget(self.text_e)
def get_text(self):
return unicode(self.text_e.text())
def on_edit(self):
b = self.is_valid(self.get_text())
self.parent.next_button.setEnabled(b)
class SeedDialog(WindowModalDialog):
def __init__(self, parent, seed, passphrase):
WindowModalDialog.__init__(self, parent, ('Electrum - ' + _('Seed')))
self.setMinimumWidth(400)
vbox = QVBoxLayout(self)
title = _("Your wallet generation seed is:")
slayout = SeedLayout(title=title, seed=seed, msg=True, passphrase=passphrase)
vbox.addLayout(slayout)
vbox.addLayout(Buttons(CloseButton(self)))
|
fireduck64/electrum
|
gui/qt/seed_dialog.py
|
Python
|
mit
| 6,845 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel.Design;
using Microsoft.VisualStudio.Text.Formatting;
using System.ComponentModel.Composition;
using System.Windows.Forms;
using Microsoft.VisualStudio.Text;
using EnvDTE;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.Editor.EmacsEmulation.Commands
{
/// <summary>
/// If the region is active, this command kills the region, placing it on the Clipboard Ring;
/// otherwise, it signals an error and messages in the status bar that the region is not active.
///
/// Keys: Ctrl+W
/// </summary>
[EmacsCommand(VSConstants.VSStd97CmdID.Cut, UndoName="Delete")]
internal class CutCommand : EmacsCommand
{
internal override void Execute(EmacsCommandContext context)
{
ITextSelection textSelection = context.TextView.Selection;
if (!textSelection.IsEmpty)
{
// Don't support addition of box selection to the clipboard ring yet
if (textSelection.Mode == TextSelectionMode.Stream)
{
context.Manager.ClipboardRing.Add(textSelection.StreamSelectionSpan.GetText());
}
context.CommandRouter.ExecuteDTECommand("Edit.Cut");
}
else
{
context.Manager.UpdateStatus(Resources.OperationCannotBePerformedWithoutTextSelection);
}
}
}
}
|
ronniexue/EmacsKeys
|
Commands/Text/CutCommand.cs
|
C#
|
mit
| 1,565 |
<?php
require_once( dirname(__FILE__).'/Cache.php');
/**
* Class for parsing and compiling less files into css
*
* @package Less
* @subpackage parser
*
*/
class Less_Parser{
/**
* Default parser options
*/
public static $default_options = array(
'compress' => false, // option - whether to compress
'strictUnits' => false, // whether units need to evaluate correctly
'strictMath' => false, // whether math has to be within parenthesis
'relativeUrls' => true, // option - whether to adjust URL's to be relative
'urlArgs' => array(), // whether to add args into url tokens
'numPrecision' => 8,
'import_dirs' => array(),
'import_callback' => null,
'cache_dir' => null,
'cache_method' => 'php', // false, 'serialize', 'php', 'var_export', 'callback';
'cache_callback_get' => null,
'cache_callback_set' => null,
'sourceMap' => false, // whether to output a source map
'sourceMapBasepath' => null,
'sourceMapWriteTo' => null,
'sourceMapURL' => null,
'plugins' => array(),
);
public static $options = array();
private $input; // Less input string
private $input_len; // input string length
private $pos; // current index in `input`
private $saveStack = array(); // holds state for backtracking
private $furthest;
/**
* @var Less_Environment
*/
private $env;
private $rules = array();
private static $imports = array();
public static $has_extends = false;
public static $next_id = 0;
/**
* Filename to contents of all parsed the files
*
* @var array
*/
public static $contentsMap = array();
/**
* @param Less_Environment|array|null $env
*/
public function __construct( $env = null ){
// Top parser on an import tree must be sure there is one "env"
// which will then be passed around by reference.
if( $env instanceof Less_Environment ){
$this->env = $env;
}else{
$this->SetOptions(Less_Parser::$default_options);
$this->Reset( $env );
}
}
/**
* Reset the parser state completely
*
*/
public function Reset( $options = null ){
$this->rules = array();
self::$imports = array();
self::$has_extends = false;
self::$imports = array();
self::$contentsMap = array();
$this->env = new Less_Environment($options);
$this->env->Init();
//set new options
if( is_array($options) ){
$this->SetOptions(Less_Parser::$default_options);
$this->SetOptions($options);
}
}
/**
* Set one or more compiler options
* options: import_dirs, cache_dir, cache_method
*
*/
public function SetOptions( $options ){
foreach($options as $option => $value){
$this->SetOption($option,$value);
}
}
/**
* Set one compiler option
*
*/
public function SetOption($option,$value){
switch($option){
case 'import_dirs':
$this->SetImportDirs($value);
return;
case 'cache_dir':
if( is_string($value) ){
Less_Cache::SetCacheDir($value);
Less_Cache::CheckCacheDir();
}
return;
}
Less_Parser::$options[$option] = $value;
}
/**
* Registers a new custom function
*
* @param string $name function name
* @param callable $callback callback
*/
public function registerFunction($name, $callback) {
$this->env->functions[$name] = $callback;
}
/**
* Removed an already registered function
*
* @param string $name function name
*/
public function unregisterFunction($name) {
if( isset($this->env->functions[$name]) )
unset($this->env->functions[$name]);
}
/**
* Get the current css buffer
*
* @return string
*/
public function getCss(){
$precision = ini_get('precision');
@ini_set('precision',16);
$locale = setlocale(LC_NUMERIC, 0);
setlocale(LC_NUMERIC, "C");
try {
$root = new Less_Tree_Ruleset(array(), $this->rules );
$root->root = true;
$root->firstRoot = true;
$this->PreVisitors($root);
self::$has_extends = false;
$evaldRoot = $root->compile($this->env);
$this->PostVisitors($evaldRoot);
if( Less_Parser::$options['sourceMap'] ){
$generator = new Less_SourceMap_Generator($evaldRoot, Less_Parser::$contentsMap, Less_Parser::$options );
// will also save file
// FIXME: should happen somewhere else?
$css = $generator->generateCSS();
}else{
$css = $evaldRoot->toCSS();
}
if( Less_Parser::$options['compress'] ){
$css = preg_replace('/(^(\s)+)|((\s)+$)/', '', $css);
}
} catch (Exception $exc) {
// Intentional fall-through so we can reset environment
}
//reset php settings
@ini_set('precision',$precision);
setlocale(LC_NUMERIC, $locale);
// Rethrow exception after we handled resetting the environment
if (!empty($exc)) {
throw $exc;
}
return $css;
}
/**
* Run pre-compile visitors
*
*/
private function PreVisitors($root){
if( Less_Parser::$options['plugins'] ){
foreach(Less_Parser::$options['plugins'] as $plugin){
if( !empty($plugin->isPreEvalVisitor) ){
$plugin->run($root);
}
}
}
}
/**
* Run post-compile visitors
*
*/
private function PostVisitors($evaldRoot){
$visitors = array();
$visitors[] = new Less_Visitor_joinSelector();
if( self::$has_extends ){
$visitors[] = new Less_Visitor_processExtends();
}
$visitors[] = new Less_Visitor_toCSS();
if( Less_Parser::$options['plugins'] ){
foreach(Less_Parser::$options['plugins'] as $plugin){
if( property_exists($plugin,'isPreEvalVisitor') && $plugin->isPreEvalVisitor ){
continue;
}
if( property_exists($plugin,'isPreVisitor') && $plugin->isPreVisitor ){
array_unshift( $visitors, $plugin);
}else{
$visitors[] = $plugin;
}
}
}
for($i = 0; $i < count($visitors); $i++ ){
$visitors[$i]->run($evaldRoot);
}
}
/**
* Parse a Less string into css
*
* @param string $str The string to convert
* @param string $uri_root The url of the file
* @return Less_Tree_Ruleset|Less_Parser
*/
public function parse( $str, $file_uri = null ){
if( !$file_uri ){
$uri_root = '';
$filename = 'anonymous-file-'.Less_Parser::$next_id++.'.less';
}else{
$file_uri = self::WinPath($file_uri);
$filename = $file_uri;
$uri_root = dirname($file_uri);
}
$previousFileInfo = $this->env->currentFileInfo;
$uri_root = self::WinPath($uri_root);
$this->SetFileInfo($filename, $uri_root);
$this->input = $str;
$this->_parse();
if( $previousFileInfo ){
$this->env->currentFileInfo = $previousFileInfo;
}
return $this;
}
/**
* Parse a Less string from a given file
*
* @throws Less_Exception_Parser
* @param string $filename The file to parse
* @param string $uri_root The url of the file
* @param bool $returnRoot Indicates whether the return value should be a css string a root node
* @return Less_Tree_Ruleset|Less_Parser
*/
public function parseFile( $filename, $uri_root = '', $returnRoot = false){
if( !file_exists($filename) ){
$this->Error(sprintf('File `%s` not found.', $filename));
}
// fix uri_root?
// Instead of The mixture of file path for the first argument and directory path for the second argument has bee
if( !$returnRoot && !empty($uri_root) && basename($uri_root) == basename($filename) ){
$uri_root = dirname($uri_root);
}
$previousFileInfo = $this->env->currentFileInfo;
if( $filename ){
$filename = self::WinPath(realpath($filename));
}
$uri_root = self::WinPath($uri_root);
$this->SetFileInfo($filename, $uri_root);
self::AddParsedFile($filename);
if( $returnRoot ){
$rules = $this->GetRules( $filename );
$return = new Less_Tree_Ruleset(array(), $rules );
}else{
$this->_parse( $filename );
$return = $this;
}
if( $previousFileInfo ){
$this->env->currentFileInfo = $previousFileInfo;
}
return $return;
}
/**
* Allows a user to set variables values
* @param array $vars
* @return Less_Parser
*/
public function ModifyVars( $vars ){
$this->input = Less_Parser::serializeVars( $vars );
$this->_parse();
return $this;
}
/**
* @param string $filename
*/
public function SetFileInfo( $filename, $uri_root = ''){
$filename = Less_Environment::normalizePath($filename);
$dirname = preg_replace('/[^\/\\\\]*$/','',$filename);
if( !empty($uri_root) ){
$uri_root = rtrim($uri_root,'/').'/';
}
$currentFileInfo = array();
//entry info
if( isset($this->env->currentFileInfo) ){
$currentFileInfo['entryPath'] = $this->env->currentFileInfo['entryPath'];
$currentFileInfo['entryUri'] = $this->env->currentFileInfo['entryUri'];
$currentFileInfo['rootpath'] = $this->env->currentFileInfo['rootpath'];
}else{
$currentFileInfo['entryPath'] = $dirname;
$currentFileInfo['entryUri'] = $uri_root;
$currentFileInfo['rootpath'] = $dirname;
}
$currentFileInfo['currentDirectory'] = $dirname;
$currentFileInfo['currentUri'] = $uri_root.basename($filename);
$currentFileInfo['filename'] = $filename;
$currentFileInfo['uri_root'] = $uri_root;
//inherit reference
if( isset($this->env->currentFileInfo['reference']) && $this->env->currentFileInfo['reference'] ){
$currentFileInfo['reference'] = true;
}
$this->env->currentFileInfo = $currentFileInfo;
}
/**
* @deprecated 1.5.1.2
*
*/
public function SetCacheDir( $dir ){
if( !file_exists($dir) ){
if( mkdir($dir) ){
return true;
}
throw new Less_Exception_Parser('Less.php cache directory couldn\'t be created: '.$dir);
}elseif( !is_dir($dir) ){
throw new Less_Exception_Parser('Less.php cache directory doesn\'t exist: '.$dir);
}elseif( !is_writable($dir) ){
throw new Less_Exception_Parser('Less.php cache directory isn\'t writable: '.$dir);
}else{
$dir = self::WinPath($dir);
Less_Cache::$cache_dir = rtrim($dir,'/').'/';
return true;
}
}
/**
* Set a list of directories or callbacks the parser should use for determining import paths
*
* @param array $dirs
*/
public function SetImportDirs( $dirs ){
Less_Parser::$options['import_dirs'] = array();
foreach($dirs as $path => $uri_root){
$path = self::WinPath($path);
if( !empty($path) ){
$path = rtrim($path,'/').'/';
}
if ( !is_callable($uri_root) ){
$uri_root = self::WinPath($uri_root);
if( !empty($uri_root) ){
$uri_root = rtrim($uri_root,'/').'/';
}
}
Less_Parser::$options['import_dirs'][$path] = $uri_root;
}
}
/**
* @param string $file_path
*/
private function _parse( $file_path = null ){
if (ini_get("mbstring.func_overload")) {
$mb_internal_encoding = ini_get("mbstring.internal_encoding");
@ini_set("mbstring.internal_encoding", "ascii");
}
$this->rules = array_merge($this->rules, $this->GetRules( $file_path ));
//reset php settings
if (isset($mb_internal_encoding)) {
@ini_set("mbstring.internal_encoding", $mb_internal_encoding);
}
}
/**
* Return the results of parsePrimary for $file_path
* Use cache and save cached results if possible
*
* @param string|null $file_path
*/
private function GetRules( $file_path ){
$this->SetInput($file_path);
$cache_file = $this->CacheFile( $file_path );
if( $cache_file ){
if( Less_Parser::$options['cache_method'] == 'callback' ){
if( is_callable(Less_Parser::$options['cache_callback_get']) ){
$cache = call_user_func_array(
Less_Parser::$options['cache_callback_get'],
array($this, $file_path, $cache_file)
);
if( $cache ){
$this->UnsetInput();
return $cache;
}
}
}elseif( file_exists($cache_file) ){
switch(Less_Parser::$options['cache_method']){
// Using serialize
// Faster but uses more memory
case 'serialize':
$cache = unserialize(file_get_contents($cache_file));
if( $cache ){
touch($cache_file);
$this->UnsetInput();
return $cache;
}
break;
// Using generated php code
case 'var_export':
case 'php':
$this->UnsetInput();
return include($cache_file);
}
}
}
$rules = $this->parsePrimary();
if( $this->pos < $this->input_len ){
throw new Less_Exception_Chunk($this->input, null, $this->furthest, $this->env->currentFileInfo);
}
$this->UnsetInput();
//save the cache
if( $cache_file ){
if( Less_Parser::$options['cache_method'] == 'callback' ){
if( is_callable(Less_Parser::$options['cache_callback_set']) ){
call_user_func_array(
Less_Parser::$options['cache_callback_set'],
array($this, $file_path, $cache_file, $rules)
);
}
}else{
//msg('write cache file');
switch(Less_Parser::$options['cache_method']){
case 'serialize':
file_put_contents( $cache_file, serialize($rules) );
break;
case 'php':
file_put_contents( $cache_file, '<?php return '.self::ArgString($rules).'; ?>' );
break;
case 'var_export':
//Requires __set_state()
file_put_contents( $cache_file, '<?php return '.var_export($rules,true).'; ?>' );
break;
}
Less_Cache::CleanCache();
}
}
return $rules;
}
/**
* Set up the input buffer
*
*/
public function SetInput( $file_path ){
if( $file_path ){
$this->input = file_get_contents( $file_path );
}
$this->pos = $this->furthest = 0;
// Remove potential UTF Byte Order Mark
$this->input = preg_replace('/\\G\xEF\xBB\xBF/', '', $this->input);
$this->input_len = strlen($this->input);
if( Less_Parser::$options['sourceMap'] && $this->env->currentFileInfo ){
$uri = $this->env->currentFileInfo['currentUri'];
Less_Parser::$contentsMap[$uri] = $this->input;
}
}
/**
* Free up some memory
*
*/
public function UnsetInput(){
unset($this->input, $this->pos, $this->input_len, $this->furthest);
$this->saveStack = array();
}
public function CacheFile( $file_path ){
if( $file_path && $this->CacheEnabled() ){
$env = get_object_vars($this->env);
unset($env['frames']);
$parts = array();
$parts[] = $file_path;
$parts[] = filesize( $file_path );
$parts[] = filemtime( $file_path );
$parts[] = $env;
$parts[] = Less_Version::cache_version;
$parts[] = Less_Parser::$options['cache_method'];
return Less_Cache::$cache_dir . Less_Cache::$prefix . base_convert( sha1(json_encode($parts) ), 16, 36) . '.lesscache';
}
}
static function AddParsedFile($file){
self::$imports[] = $file;
}
static function AllParsedFiles(){
return self::$imports;
}
/**
* @param string $file
*/
static function FileParsed($file){
return in_array($file,self::$imports);
}
function save() {
$this->saveStack[] = $this->pos;
}
private function restore() {
$this->pos = array_pop($this->saveStack);
}
private function forget(){
array_pop($this->saveStack);
}
private function isWhitespace($offset = 0) {
return preg_match('/\s/',$this->input[ $this->pos + $offset]);
}
/**
* Parse from a token, regexp or string, and move forward if match
*
* @param array $toks
* @return array
*/
private function match($toks){
// The match is confirmed, add the match length to `this::pos`,
// and consume any extra white-space characters (' ' || '\n')
// which come after that. The reason for this is that LeSS's
// grammar is mostly white-space insensitive.
//
foreach($toks as $tok){
$char = $tok[0];
if( $char === '/' ){
$match = $this->MatchReg($tok);
if( $match ){
return count($match) === 1 ? $match[0] : $match;
}
}elseif( $char === '#' ){
$match = $this->MatchChar($tok[1]);
}else{
// Non-terminal, match using a function call
$match = $this->$tok();
}
if( $match ){
return $match;
}
}
}
/**
* @param string[] $toks
*
* @return string
*/
private function MatchFuncs($toks){
if( $this->pos < $this->input_len ){
foreach($toks as $tok){
$match = $this->$tok();
if( $match ){
return $match;
}
}
}
}
// Match a single character in the input,
private function MatchChar($tok){
if( ($this->pos < $this->input_len) && ($this->input[$this->pos] === $tok) ){
$this->skipWhitespace(1);
return $tok;
}
}
// Match a regexp from the current start point
private function MatchReg($tok){
if( preg_match($tok, $this->input, $match, 0, $this->pos) ){
$this->skipWhitespace(strlen($match[0]));
return $match;
}
}
/**
* Same as match(), but don't change the state of the parser,
* just return the match.
*
* @param string $tok
* @return integer
*/
public function PeekReg($tok){
return preg_match($tok, $this->input, $match, 0, $this->pos);
}
/**
* @param string $tok
*/
public function PeekChar($tok){
//return ($this->input[$this->pos] === $tok );
return ($this->pos < $this->input_len) && ($this->input[$this->pos] === $tok );
}
/**
* @param integer $length
*/
public function skipWhitespace($length){
$this->pos += $length;
for(; $this->pos < $this->input_len; $this->pos++ ){
$c = $this->input[$this->pos];
if( ($c !== "\n") && ($c !== "\r") && ($c !== "\t") && ($c !== ' ') ){
break;
}
}
}
/**
* @param string $tok
* @param string|null $msg
*/
public function expect($tok, $msg = NULL) {
$result = $this->match( array($tok) );
if (!$result) {
$this->Error( $msg ? "Expected '" . $tok . "' got '" . $this->input[$this->pos] . "'" : $msg );
} else {
return $result;
}
}
/**
* @param string $tok
*/
public function expectChar($tok, $msg = null ){
$result = $this->MatchChar($tok);
if( !$result ){
$this->Error( $msg ? "Expected '" . $tok . "' got '" . $this->input[$this->pos] . "'" : $msg );
}else{
return $result;
}
}
//
// Here in, the parsing rules/functions
//
// The basic structure of the syntax tree generated is as follows:
//
// Ruleset -> Rule -> Value -> Expression -> Entity
//
// Here's some LESS code:
//
// .class {
// color: #fff;
// border: 1px solid #000;
// width: @w + 4px;
// > .child {...}
// }
//
// And here's what the parse tree might look like:
//
// Ruleset (Selector '.class', [
// Rule ("color", Value ([Expression [Color #fff]]))
// Rule ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
// Rule ("width", Value ([Expression [Operation "+" [Variable "@w"][Dimension 4px]]]))
// Ruleset (Selector [Element '>', '.child'], [...])
// ])
//
// In general, most rules will try to parse a token with the `$()` function, and if the return
// value is truly, will return a new node, of the relevant type. Sometimes, we need to check
// first, before parsing, that's when we use `peek()`.
//
//
// The `primary` rule is the *entry* and *exit* point of the parser.
// The rules here can appear at any level of the parse tree.
//
// The recursive nature of the grammar is an interplay between the `block`
// rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
// as represented by this simplified grammar:
//
// primary → (ruleset | rule)+
// ruleset → selector+ block
// block → '{' primary '}'
//
// Only at one point is the primary rule not called from the
// block rule: at the root level.
//
private function parsePrimary(){
$root = array();
while( true ){
if( $this->pos >= $this->input_len ){
break;
}
$node = $this->parseExtend(true);
if( $node ){
$root = array_merge($root,$node);
continue;
}
//$node = $this->MatchFuncs( array( 'parseMixinDefinition', 'parseRule', 'parseRuleset', 'parseMixinCall', 'parseComment', 'parseDirective'));
$node = $this->MatchFuncs( array( 'parseMixinDefinition', 'parseNameValue', 'parseRule', 'parseRuleset', 'parseMixinCall', 'parseComment', 'parseRulesetCall', 'parseDirective'));
if( $node ){
$root[] = $node;
}elseif( !$this->MatchReg('/\\G[\s\n;]+/') ){
break;
}
if( $this->PeekChar('}') ){
break;
}
}
return $root;
}
// We create a Comment node for CSS comments `/* */`,
// but keep the LeSS comments `//` silent, by just skipping
// over them.
private function parseComment(){
if( $this->input[$this->pos] !== '/' ){
return;
}
if( $this->input[$this->pos+1] === '/' ){
$match = $this->MatchReg('/\\G\/\/.*/');
return $this->NewObj4('Less_Tree_Comment',array($match[0], true, $this->pos, $this->env->currentFileInfo));
}
//$comment = $this->MatchReg('/\\G\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/');
$comment = $this->MatchReg('/\\G\/\*(?s).*?\*+\/\n?/');//not the same as less.js to prevent fatal errors
if( $comment ){
return $this->NewObj4('Less_Tree_Comment',array($comment[0], false, $this->pos, $this->env->currentFileInfo));
}
}
private function parseComments(){
$comments = array();
while( $this->pos < $this->input_len ){
$comment = $this->parseComment();
if( !$comment ){
break;
}
$comments[] = $comment;
}
return $comments;
}
//
// A string, which supports escaping " and '
//
// "milky way" 'he\'s the one!'
//
private function parseEntitiesQuoted() {
$j = $this->pos;
$e = false;
$index = $this->pos;
if( $this->input[$this->pos] === '~' ){
$j++;
$e = true; // Escaped strings
}
if( $this->input[$j] != '"' && $this->input[$j] !== "'" ){
return;
}
if ($e) {
$this->MatchChar('~');
}
// Fix for #124: match escaped newlines
//$str = $this->MatchReg('/\\G"((?:[^"\\\\\r\n]|\\\\.)*)"|\'((?:[^\'\\\\\r\n]|\\\\.)*)\'/');
$str = $this->MatchReg('/\\G"((?:[^"\\\\\r\n]|\\\\.|\\\\\r\n|\\\\[\n\r\f])*)"|\'((?:[^\'\\\\\r\n]|\\\\.|\\\\\r\n|\\\\[\n\r\f])*)\'/');
if( $str ){
$result = $str[0][0] == '"' ? $str[1] : $str[2];
return $this->NewObj5('Less_Tree_Quoted',array($str[0], $result, $e, $index, $this->env->currentFileInfo) );
}
return;
}
//
// A catch-all word, such as:
//
// black border-collapse
//
private function parseEntitiesKeyword(){
//$k = $this->MatchReg('/\\G[_A-Za-z-][_A-Za-z0-9-]*/');
$k = $this->MatchReg('/\\G%|\\G[_A-Za-z-][_A-Za-z0-9-]*/');
if( $k ){
$k = $k[0];
$color = $this->fromKeyword($k);
if( $color ){
return $color;
}
return $this->NewObj1('Less_Tree_Keyword',$k);
}
}
// duplicate of Less_Tree_Color::FromKeyword
private function FromKeyword( $keyword ){
$keyword = strtolower($keyword);
if( Less_Colors::hasOwnProperty($keyword) ){
// detect named color
return $this->NewObj1('Less_Tree_Color',substr(Less_Colors::color($keyword), 1));
}
if( $keyword === 'transparent' ){
return $this->NewObj3('Less_Tree_Color', array( array(0, 0, 0), 0, true));
}
}
//
// A function call
//
// rgb(255, 0, 255)
//
// We also try to catch IE's `alpha()`, but let the `alpha` parser
// deal with the details.
//
// The arguments are parsed with the `entities.arguments` parser.
//
private function parseEntitiesCall(){
$index = $this->pos;
if( !preg_match('/\\G([\w-]+|%|progid:[\w\.]+)\(/', $this->input, $name,0,$this->pos) ){
return;
}
$name = $name[1];
$nameLC = strtolower($name);
if ($nameLC === 'url') {
return null;
}
$this->pos += strlen($name);
if( $nameLC === 'alpha' ){
$alpha_ret = $this->parseAlpha();
if( $alpha_ret ){
return $alpha_ret;
}
}
$this->MatchChar('('); // Parse the '(' and consume whitespace.
$args = $this->parseEntitiesArguments();
if( !$this->MatchChar(')') ){
return;
}
if ($name) {
return $this->NewObj4('Less_Tree_Call',array($name, $args, $index, $this->env->currentFileInfo) );
}
}
/**
* Parse a list of arguments
*
* @return array
*/
private function parseEntitiesArguments(){
$args = array();
while( true ){
$arg = $this->MatchFuncs( array('parseEntitiesAssignment','parseExpression') );
if( !$arg ){
break;
}
$args[] = $arg;
if( !$this->MatchChar(',') ){
break;
}
}
return $args;
}
private function parseEntitiesLiteral(){
return $this->MatchFuncs( array('parseEntitiesDimension','parseEntitiesColor','parseEntitiesQuoted','parseUnicodeDescriptor') );
}
// Assignments are argument entities for calls.
// They are present in ie filter properties as shown below.
//
// filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
//
private function parseEntitiesAssignment() {
$key = $this->MatchReg('/\\G\w+(?=\s?=)/');
if( !$key ){
return;
}
if( !$this->MatchChar('=') ){
return;
}
$value = $this->parseEntity();
if( $value ){
return $this->NewObj2('Less_Tree_Assignment',array($key[0], $value));
}
}
//
// Parse url() tokens
//
// We use a specific rule for urls, because they don't really behave like
// standard function calls. The difference is that the argument doesn't have
// to be enclosed within a string, so it can't be parsed as an Expression.
//
private function parseEntitiesUrl(){
if( $this->input[$this->pos] !== 'u' || !$this->matchReg('/\\Gurl\(/') ){
return;
}
$value = $this->match( array('parseEntitiesQuoted','parseEntitiesVariable','/\\Gdata\:.*?[^\)]+/','/\\G(?:(?:\\\\[\(\)\'"])|[^\(\)\'"])+/') );
if( !$value ){
$value = '';
}
$this->expectChar(')');
if( isset($value->value) || $value instanceof Less_Tree_Variable ){
return $this->NewObj2('Less_Tree_Url',array($value, $this->env->currentFileInfo));
}
return $this->NewObj2('Less_Tree_Url', array( $this->NewObj1('Less_Tree_Anonymous',$value), $this->env->currentFileInfo) );
}
//
// A Variable entity, such as `@fink`, in
//
// width: @fink + 2px
//
// We use a different parser for variable definitions,
// see `parsers.variable`.
//
private function parseEntitiesVariable(){
$index = $this->pos;
if ($this->PeekChar('@') && ($name = $this->MatchReg('/\\G@@?[\w-]+/'))) {
return $this->NewObj3('Less_Tree_Variable', array( $name[0], $index, $this->env->currentFileInfo));
}
}
// A variable entity useing the protective {} e.g. @{var}
private function parseEntitiesVariableCurly() {
$index = $this->pos;
if( $this->input_len > ($this->pos+1) && $this->input[$this->pos] === '@' && ($curly = $this->MatchReg('/\\G@\{([\w-]+)\}/')) ){
return $this->NewObj3('Less_Tree_Variable',array('@'.$curly[1], $index, $this->env->currentFileInfo));
}
}
//
// A Hexadecimal color
//
// #4F3C2F
//
// `rgb` and `hsl` colors are parsed through the `entities.call` parser.
//
private function parseEntitiesColor(){
if ($this->PeekChar('#') && ($rgb = $this->MatchReg('/\\G#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/'))) {
return $this->NewObj1('Less_Tree_Color',$rgb[1]);
}
}
//
// A Dimension, that is, a number and a unit
//
// 0.5em 95%
//
private function parseEntitiesDimension(){
$c = @ord($this->input[$this->pos]);
//Is the first char of the dimension 0-9, '.', '+' or '-'
if (($c > 57 || $c < 43) || $c === 47 || $c == 44){
return;
}
$value = $this->MatchReg('/\\G([+-]?\d*\.?\d+)(%|[a-z]+)?/');
if( $value ){
if( isset($value[2]) ){
return $this->NewObj2('Less_Tree_Dimension', array($value[1],$value[2]));
}
return $this->NewObj1('Less_Tree_Dimension',$value[1]);
}
}
//
// A unicode descriptor, as is used in unicode-range
//
// U+0?? or U+00A1-00A9
//
function parseUnicodeDescriptor() {
$ud = $this->MatchReg('/\\G(U\+[0-9a-fA-F?]+)(\-[0-9a-fA-F?]+)?/');
if( $ud ){
return $this->NewObj1('Less_Tree_UnicodeDescriptor', $ud[0]);
}
}
//
// JavaScript code to be evaluated
//
// `window.location.href`
//
private function parseEntitiesJavascript(){
$e = false;
$j = $this->pos;
if( $this->input[$j] === '~' ){
$j++;
$e = true;
}
if( $this->input[$j] !== '`' ){
return;
}
if( $e ){
$this->MatchChar('~');
}
$str = $this->MatchReg('/\\G`([^`]*)`/');
if( $str ){
return $this->NewObj3('Less_Tree_Javascript', array($str[1], $this->pos, $e));
}
}
//
// The variable part of a variable definition. Used in the `rule` parser
//
// @fink:
//
private function parseVariable(){
if ($this->PeekChar('@') && ($name = $this->MatchReg('/\\G(@[\w-]+)\s*:/'))) {
return $name[1];
}
}
//
// The variable part of a variable definition. Used in the `rule` parser
//
// @fink();
//
private function parseRulesetCall(){
if( $this->input[$this->pos] === '@' && ($name = $this->MatchReg('/\\G(@[\w-]+)\s*\(\s*\)\s*;/')) ){
return $this->NewObj1('Less_Tree_RulesetCall', $name[1] );
}
}
//
// extend syntax - used to extend selectors
//
function parseExtend($isRule = false){
$index = $this->pos;
$extendList = array();
if( !$this->MatchReg( $isRule ? '/\\G&:extend\(/' : '/\\G:extend\(/' ) ){ return; }
do{
$option = null;
$elements = array();
while( true ){
$option = $this->MatchReg('/\\G(all)(?=\s*(\)|,))/');
if( $option ){ break; }
$e = $this->parseElement();
if( !$e ){ break; }
$elements[] = $e;
}
if( $option ){
$option = $option[1];
}
$extendList[] = $this->NewObj3('Less_Tree_Extend', array( $this->NewObj1('Less_Tree_Selector',$elements), $option, $index ));
}while( $this->MatchChar(",") );
$this->expect('/\\G\)/');
if( $isRule ){
$this->expect('/\\G;/');
}
return $extendList;
}
//
// A Mixin call, with an optional argument list
//
// #mixins > .square(#fff);
// .rounded(4px, black);
// .button;
//
// The `while` loop is there because mixins can be
// namespaced, but we only support the child and descendant
// selector for now.
//
private function parseMixinCall(){
$char = $this->input[$this->pos];
if( $char !== '.' && $char !== '#' ){
return;
}
$index = $this->pos;
$this->save(); // stop us absorbing part of an invalid selector
$elements = $this->parseMixinCallElements();
if( $elements ){
if( $this->MatchChar('(') ){
$returned = $this->parseMixinArgs(true);
$args = $returned['args'];
$this->expectChar(')');
}else{
$args = array();
}
$important = $this->parseImportant();
if( $this->parseEnd() ){
$this->forget();
return $this->NewObj5('Less_Tree_Mixin_Call', array( $elements, $args, $index, $this->env->currentFileInfo, $important));
}
}
$this->restore();
}
private function parseMixinCallElements(){
$elements = array();
$c = null;
while( true ){
$elemIndex = $this->pos;
$e = $this->MatchReg('/\\G[#.](?:[\w-]|\\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/');
if( !$e ){
break;
}
$elements[] = $this->NewObj4('Less_Tree_Element', array($c, $e[0], $elemIndex, $this->env->currentFileInfo));
$c = $this->MatchChar('>');
}
return $elements;
}
/**
* @param boolean $isCall
*/
private function parseMixinArgs( $isCall ){
$expressions = array();
$argsSemiColon = array();
$isSemiColonSeperated = null;
$argsComma = array();
$expressionContainsNamed = null;
$name = null;
$returner = array('args'=>array(), 'variadic'=> false);
$this->save();
while( true ){
if( $isCall ){
$arg = $this->MatchFuncs( array( 'parseDetachedRuleset','parseExpression' ) );
} else {
$this->parseComments();
if( $this->input[ $this->pos ] === '.' && $this->MatchReg('/\\G\.{3}/') ){
$returner['variadic'] = true;
if( $this->MatchChar(";") && !$isSemiColonSeperated ){
$isSemiColonSeperated = true;
}
if( $isSemiColonSeperated ){
$argsSemiColon[] = array('variadic'=>true);
}else{
$argsComma[] = array('variadic'=>true);
}
break;
}
$arg = $this->MatchFuncs( array('parseEntitiesVariable','parseEntitiesLiteral','parseEntitiesKeyword') );
}
if( !$arg ){
break;
}
$nameLoop = null;
if( $arg instanceof Less_Tree_Expression ){
$arg->throwAwayComments();
}
$value = $arg;
$val = null;
if( $isCall ){
// Variable
if( property_exists($arg,'value') && count($arg->value) == 1 ){
$val = $arg->value[0];
}
} else {
$val = $arg;
}
if( $val instanceof Less_Tree_Variable ){
if( $this->MatchChar(':') ){
if( $expressions ){
if( $isSemiColonSeperated ){
$this->Error('Cannot mix ; and , as delimiter types');
}
$expressionContainsNamed = true;
}
// we do not support setting a ruleset as a default variable - it doesn't make sense
// However if we do want to add it, there is nothing blocking it, just don't error
// and remove isCall dependency below
$value = null;
if( $isCall ){
$value = $this->parseDetachedRuleset();
}
if( !$value ){
$value = $this->parseExpression();
}
if( !$value ){
if( $isCall ){
$this->Error('could not understand value for named argument');
} else {
$this->restore();
$returner['args'] = array();
return $returner;
}
}
$nameLoop = ($name = $val->name);
}elseif( !$isCall && $this->MatchReg('/\\G\.{3}/') ){
$returner['variadic'] = true;
if( $this->MatchChar(";") && !$isSemiColonSeperated ){
$isSemiColonSeperated = true;
}
if( $isSemiColonSeperated ){
$argsSemiColon[] = array('name'=> $arg->name, 'variadic' => true);
}else{
$argsComma[] = array('name'=> $arg->name, 'variadic' => true);
}
break;
}elseif( !$isCall ){
$name = $nameLoop = $val->name;
$value = null;
}
}
if( $value ){
$expressions[] = $value;
}
$argsComma[] = array('name'=>$nameLoop, 'value'=>$value );
if( $this->MatchChar(',') ){
continue;
}
if( $this->MatchChar(';') || $isSemiColonSeperated ){
if( $expressionContainsNamed ){
$this->Error('Cannot mix ; and , as delimiter types');
}
$isSemiColonSeperated = true;
if( count($expressions) > 1 ){
$value = $this->NewObj1('Less_Tree_Value', $expressions);
}
$argsSemiColon[] = array('name'=>$name, 'value'=>$value );
$name = null;
$expressions = array();
$expressionContainsNamed = false;
}
}
$this->forget();
$returner['args'] = ($isSemiColonSeperated ? $argsSemiColon : $argsComma);
return $returner;
}
//
// A Mixin definition, with a list of parameters
//
// .rounded (@radius: 2px, @color) {
// ...
// }
//
// Until we have a finer grained state-machine, we have to
// do a look-ahead, to make sure we don't have a mixin call.
// See the `rule` function for more information.
//
// We start by matching `.rounded (`, and then proceed on to
// the argument list, which has optional default values.
// We store the parameters in `params`, with a `value` key,
// if there is a value, such as in the case of `@radius`.
//
// Once we've got our params list, and a closing `)`, we parse
// the `{...}` block.
//
private function parseMixinDefinition(){
$cond = null;
$char = $this->input[$this->pos];
if( ($char !== '.' && $char !== '#') || ($char === '{' && $this->PeekReg('/\\G[^{]*\}/')) ){
return;
}
$this->save();
$match = $this->MatchReg('/\\G([#.](?:[\w-]|\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/');
if( $match ){
$name = $match[1];
$argInfo = $this->parseMixinArgs( false );
$params = $argInfo['args'];
$variadic = $argInfo['variadic'];
// .mixincall("@{a}");
// looks a bit like a mixin definition..
// also
// .mixincall(@a: {rule: set;});
// so we have to be nice and restore
if( !$this->MatchChar(')') ){
$this->furthest = $this->pos;
$this->restore();
return;
}
$this->parseComments();
if ($this->MatchReg('/\\Gwhen/')) { // Guard
$cond = $this->expect('parseConditions', 'Expected conditions');
}
$ruleset = $this->parseBlock();
if( is_array($ruleset) ){
$this->forget();
return $this->NewObj5('Less_Tree_Mixin_Definition', array( $name, $params, $ruleset, $cond, $variadic));
}
$this->restore();
}else{
$this->forget();
}
}
//
// Entities are the smallest recognized token,
// and can be found inside a rule's value.
//
private function parseEntity(){
return $this->MatchFuncs( array('parseEntitiesLiteral','parseEntitiesVariable','parseEntitiesUrl','parseEntitiesCall','parseEntitiesKeyword','parseEntitiesJavascript','parseComment') );
}
//
// A Rule terminator. Note that we use `peek()` to check for '}',
// because the `block` rule will be expecting it, but we still need to make sure
// it's there, if ';' was ommitted.
//
private function parseEnd(){
return $this->MatchChar(';') || $this->PeekChar('}');
}
//
// IE's alpha function
//
// alpha(opacity=88)
//
private function parseAlpha(){
if ( ! $this->MatchReg('/\\G\(opacity=/i')) {
return;
}
$value = $this->MatchReg('/\\G[0-9]+/');
if( $value ){
$value = $value[0];
}else{
$value = $this->parseEntitiesVariable();
if( !$value ){
return;
}
}
$this->expectChar(')');
return $this->NewObj1('Less_Tree_Alpha',$value);
}
//
// A Selector Element
//
// div
// + h1
// #socks
// input[type="text"]
//
// Elements are the building blocks for Selectors,
// they are made out of a `Combinator` (see combinator rule),
// and an element name, such as a tag a class, or `*`.
//
private function parseElement(){
$c = $this->parseCombinator();
$index = $this->pos;
$e = $this->match( array('/\\G(?:\d+\.\d+|\d+)%/', '/\\G(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/',
'#*', '#&', 'parseAttribute', '/\\G\([^()@]+\)/', '/\\G[\.#](?=@)/', 'parseEntitiesVariableCurly') );
if( is_null($e) ){
$this->save();
if( $this->MatchChar('(') ){
if( ($v = $this->parseSelector()) && $this->MatchChar(')') ){
$e = $this->NewObj1('Less_Tree_Paren',$v);
$this->forget();
}else{
$this->restore();
}
}else{
$this->forget();
}
}
if( !is_null($e) ){
return $this->NewObj4('Less_Tree_Element',array( $c, $e, $index, $this->env->currentFileInfo));
}
}
//
// Combinators combine elements together, in a Selector.
//
// Because our parser isn't white-space sensitive, special care
// has to be taken, when parsing the descendant combinator, ` `,
// as it's an empty space. We have to check the previous character
// in the input, to see if it's a ` ` character.
//
private function parseCombinator(){
if( $this->pos < $this->input_len ){
$c = $this->input[$this->pos];
if ($c === '>' || $c === '+' || $c === '~' || $c === '|' || $c === '^' ){
$this->pos++;
if( $this->input[$this->pos] === '^' ){
$c = '^^';
$this->pos++;
}
$this->skipWhitespace(0);
return $c;
}
if( $this->pos > 0 && $this->isWhitespace(-1) ){
return ' ';
}
}
}
//
// A CSS selector (see selector below)
// with less extensions e.g. the ability to extend and guard
//
private function parseLessSelector(){
return $this->parseSelector(true);
}
//
// A CSS Selector
//
// .class > div + h1
// li a:hover
//
// Selectors are made out of one or more Elements, see above.
//
private function parseSelector( $isLess = false ){
$elements = array();
$extendList = array();
$condition = null;
$when = false;
$extend = false;
$e = null;
$c = null;
$index = $this->pos;
while( ($isLess && ($extend = $this->parseExtend())) || ($isLess && ($when = $this->MatchReg('/\\Gwhen/') )) || ($e = $this->parseElement()) ){
if( $when ){
$condition = $this->expect('parseConditions', 'expected condition');
}elseif( $condition ){
//error("CSS guard can only be used at the end of selector");
}elseif( $extend ){
$extendList = array_merge($extendList,$extend);
}else{
//if( count($extendList) ){
//error("Extend can only be used at the end of selector");
//}
if( $this->pos < $this->input_len ){
$c = $this->input[ $this->pos ];
}
$elements[] = $e;
$e = null;
}
if( $c === '{' || $c === '}' || $c === ';' || $c === ',' || $c === ')') { break; }
}
if( $elements ){
return $this->NewObj5('Less_Tree_Selector',array($elements, $extendList, $condition, $index, $this->env->currentFileInfo));
}
if( $extendList ) {
$this->Error('Extend must be used to extend a selector, it cannot be used on its own');
}
}
private function parseTag(){
return ( $tag = $this->MatchReg('/\\G[A-Za-z][A-Za-z-]*[0-9]?/') ) ? $tag : $this->MatchChar('*');
}
private function parseAttribute(){
$val = null;
if( !$this->MatchChar('[') ){
return;
}
$key = $this->parseEntitiesVariableCurly();
if( !$key ){
$key = $this->expect('/\\G(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\\\.)+/');
}
$op = $this->MatchReg('/\\G[|~*$^]?=/');
if( $op ){
$val = $this->match( array('parseEntitiesQuoted','/\\G[0-9]+%/','/\\G[\w-]+/','parseEntitiesVariableCurly') );
}
$this->expectChar(']');
return $this->NewObj3('Less_Tree_Attribute',array( $key, $op[0], $val));
}
//
// The `block` rule is used by `ruleset` and `mixin.definition`.
// It's a wrapper around the `primary` rule, with added `{}`.
//
private function parseBlock(){
if( $this->MatchChar('{') ){
$content = $this->parsePrimary();
if( $this->MatchChar('}') ){
return $content;
}
}
}
private function parseBlockRuleset(){
$block = $this->parseBlock();
if( $block ){
$block = $this->NewObj2('Less_Tree_Ruleset',array( null, $block));
}
return $block;
}
private function parseDetachedRuleset(){
$blockRuleset = $this->parseBlockRuleset();
if( $blockRuleset ){
return $this->NewObj1('Less_Tree_DetachedRuleset',$blockRuleset);
}
}
//
// div, .class, body > p {...}
//
private function parseRuleset(){
$selectors = array();
$this->save();
while( true ){
$s = $this->parseLessSelector();
if( !$s ){
break;
}
$selectors[] = $s;
$this->parseComments();
if( $s->condition && count($selectors) > 1 ){
$this->Error('Guards are only currently allowed on a single selector.');
}
if( !$this->MatchChar(',') ){
break;
}
if( $s->condition ){
$this->Error('Guards are only currently allowed on a single selector.');
}
$this->parseComments();
}
if( $selectors ){
$rules = $this->parseBlock();
if( is_array($rules) ){
$this->forget();
return $this->NewObj2('Less_Tree_Ruleset',array( $selectors, $rules)); //Less_Environment::$strictImports
}
}
// Backtrack
$this->furthest = $this->pos;
$this->restore();
}
/**
* Custom less.php parse function for finding simple name-value css pairs
* ex: width:100px;
*
*/
private function parseNameValue(){
$index = $this->pos;
$this->save();
//$match = $this->MatchReg('/\\G([a-zA-Z\-]+)\s*:\s*((?:\'")?[a-zA-Z0-9\-% \.,!]+?(?:\'")?)\s*([;}])/');
$match = $this->MatchReg('/\\G([a-zA-Z\-]+)\s*:\s*([\'"]?[#a-zA-Z0-9\-%\.,]+?[\'"]?) *(! *important)?\s*([;}])/');
if( $match ){
if( $match[4] == '}' ){
$this->pos = $index + strlen($match[0])-1;
}
if( $match[3] ){
$match[2] .= ' !important';
}
return $this->NewObj4('Less_Tree_NameValue',array( $match[1], $match[2], $index, $this->env->currentFileInfo));
}
$this->restore();
}
private function parseRule( $tryAnonymous = null ){
$merge = false;
$startOfRule = $this->pos;
$c = $this->input[$this->pos];
if( $c === '.' || $c === '#' || $c === '&' ){
return;
}
$this->save();
$name = $this->MatchFuncs( array('parseVariable','parseRuleProperty'));
if( $name ){
$isVariable = is_string($name);
$value = null;
if( $isVariable ){
$value = $this->parseDetachedRuleset();
}
$important = null;
if( !$value ){
// prefer to try to parse first if its a variable or we are compressing
// but always fallback on the other one
//if( !$tryAnonymous && is_string($name) && $name[0] === '@' ){
if( !$tryAnonymous && (Less_Parser::$options['compress'] || $isVariable) ){
$value = $this->MatchFuncs( array('parseValue','parseAnonymousValue'));
}else{
$value = $this->MatchFuncs( array('parseAnonymousValue','parseValue'));
}
$important = $this->parseImportant();
// a name returned by this.ruleProperty() is always an array of the form:
// [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
// where each item is a tree.Keyword or tree.Variable
if( !$isVariable && is_array($name) ){
$nm = array_pop($name);
if( $nm->value ){
$merge = $nm->value;
}
}
}
if( $value && $this->parseEnd() ){
$this->forget();
return $this->NewObj6('Less_Tree_Rule',array( $name, $value, $important, $merge, $startOfRule, $this->env->currentFileInfo));
}else{
$this->furthest = $this->pos;
$this->restore();
if( $value && !$tryAnonymous ){
return $this->parseRule(true);
}
}
}else{
$this->forget();
}
}
function parseAnonymousValue(){
if( preg_match('/\\G([^@+\/\'"*`(;{}-]*);/',$this->input, $match, 0, $this->pos) ){
$this->pos += strlen($match[1]);
return $this->NewObj1('Less_Tree_Anonymous',$match[1]);
}
}
//
// An @import directive
//
// @import "lib";
//
// Depending on our environment, importing is done differently:
// In the browser, it's an XHR request, in Node, it would be a
// file-system operation. The function used for importing is
// stored in `import`, which we pass to the Import constructor.
//
private function parseImport(){
$this->save();
$dir = $this->MatchReg('/\\G@import?\s+/');
if( $dir ){
$options = $this->parseImportOptions();
$path = $this->MatchFuncs( array('parseEntitiesQuoted','parseEntitiesUrl'));
if( $path ){
$features = $this->parseMediaFeatures();
if( $this->MatchChar(';') ){
if( $features ){
$features = $this->NewObj1('Less_Tree_Value',$features);
}
$this->forget();
return $this->NewObj5('Less_Tree_Import',array( $path, $features, $options, $this->pos, $this->env->currentFileInfo));
}
}
}
$this->restore();
}
private function parseImportOptions(){
$options = array();
// list of options, surrounded by parens
if( !$this->MatchChar('(') ){
return $options;
}
do{
$optionName = $this->parseImportOption();
if( $optionName ){
$value = true;
switch( $optionName ){
case "css":
$optionName = "less";
$value = false;
break;
case "once":
$optionName = "multiple";
$value = false;
break;
}
$options[$optionName] = $value;
if( !$this->MatchChar(',') ){ break; }
}
}while( $optionName );
$this->expectChar(')');
return $options;
}
private function parseImportOption(){
$opt = $this->MatchReg('/\\G(less|css|multiple|once|inline|reference)/');
if( $opt ){
return $opt[1];
}
}
private function parseMediaFeature() {
$nodes = array();
do{
$e = $this->MatchFuncs(array('parseEntitiesKeyword','parseEntitiesVariable'));
if( $e ){
$nodes[] = $e;
} elseif ($this->MatchChar('(')) {
$p = $this->parseProperty();
$e = $this->parseValue();
if ($this->MatchChar(')')) {
if ($p && $e) {
$r = $this->NewObj7('Less_Tree_Rule', array( $p, $e, null, null, $this->pos, $this->env->currentFileInfo, true));
$nodes[] = $this->NewObj1('Less_Tree_Paren',$r);
} elseif ($e) {
$nodes[] = $this->NewObj1('Less_Tree_Paren',$e);
} else {
return null;
}
} else
return null;
}
} while ($e);
if ($nodes) {
return $this->NewObj1('Less_Tree_Expression',$nodes);
}
}
private function parseMediaFeatures() {
$features = array();
do{
$e = $this->parseMediaFeature();
if( $e ){
$features[] = $e;
if (!$this->MatchChar(',')) break;
}else{
$e = $this->parseEntitiesVariable();
if( $e ){
$features[] = $e;
if (!$this->MatchChar(',')) break;
}
}
} while ($e);
return $features ? $features : null;
}
private function parseMedia() {
if( $this->MatchReg('/\\G@media/') ){
$features = $this->parseMediaFeatures();
$rules = $this->parseBlock();
if( is_array($rules) ){
return $this->NewObj4('Less_Tree_Media',array( $rules, $features, $this->pos, $this->env->currentFileInfo));
}
}
}
//
// A CSS Directive
//
// @charset "utf-8";
//
private function parseDirective(){
if( !$this->PeekChar('@') ){
return;
}
$rules = null;
$index = $this->pos;
$hasBlock = true;
$hasIdentifier = false;
$hasExpression = false;
$hasUnknown = false;
$value = $this->MatchFuncs(array('parseImport','parseMedia'));
if( $value ){
return $value;
}
$this->save();
$name = $this->MatchReg('/\\G@[a-z-]+/');
if( !$name ) return;
$name = $name[0];
$nonVendorSpecificName = $name;
$pos = strpos($name,'-', 2);
if( $name[1] == '-' && $pos > 0 ){
$nonVendorSpecificName = "@" . substr($name, $pos + 1);
}
switch( $nonVendorSpecificName ){
/*
case "@font-face":
case "@viewport":
case "@top-left":
case "@top-left-corner":
case "@top-center":
case "@top-right":
case "@top-right-corner":
case "@bottom-left":
case "@bottom-left-corner":
case "@bottom-center":
case "@bottom-right":
case "@bottom-right-corner":
case "@left-top":
case "@left-middle":
case "@left-bottom":
case "@right-top":
case "@right-middle":
case "@right-bottom":
hasBlock = true;
break;
*/
case "@charset":
$hasIdentifier = true;
$hasBlock = false;
break;
case "@namespace":
$hasExpression = true;
$hasBlock = false;
break;
case "@keyframes":
$hasIdentifier = true;
break;
case "@host":
case "@page":
case "@document":
case "@supports":
$hasUnknown = true;
break;
}
if( $hasIdentifier ){
$value = $this->parseEntity();
if( !$value ){
$this->error("expected " . $name . " identifier");
}
} else if( $hasExpression ){
$value = $this->parseExpression();
if( !$value ){
$this->error("expected " . $name. " expression");
}
} else if ($hasUnknown) {
$value = $this->MatchReg('/\\G[^{;]+/');
if( $value ){
$value = $this->NewObj1('Less_Tree_Anonymous',trim($value[0]));
}
}
if( $hasBlock ){
$rules = $this->parseBlockRuleset();
}
if( $rules || (!$hasBlock && $value && $this->MatchChar(';'))) {
$this->forget();
return $this->NewObj5('Less_Tree_Directive',array($name, $value, $rules, $index, $this->env->currentFileInfo));
}
$this->restore();
}
//
// A Value is a comma-delimited list of Expressions
//
// font-family: Baskerville, Georgia, serif;
//
// In a Rule, a Value represents everything after the `:`,
// and before the `;`.
//
private function parseValue(){
$expressions = array();
do{
$e = $this->parseExpression();
if( $e ){
$expressions[] = $e;
if (! $this->MatchChar(',')) {
break;
}
}
}while($e);
if( $expressions ){
return $this->NewObj1('Less_Tree_Value',$expressions);
}
}
private function parseImportant (){
if( $this->PeekChar('!') && $this->MatchReg('/\\G! *important/') ){
return ' !important';
}
}
private function parseSub (){
if( $this->MatchChar('(') ){
$a = $this->parseAddition();
if( $a ){
$this->expectChar(')');
return $this->NewObj2('Less_Tree_Expression',array( array($a), true) ); //instead of $e->parens = true so the value is cached
}
}
}
/**
* Parses multiplication operation
*
* @return Less_Tree_Operation|null
*/
function parseMultiplication(){
$return = $m = $this->parseOperand();
if( $return ){
while( true ){
$isSpaced = $this->isWhitespace( -1 );
if( $this->PeekReg('/\\G\/[*\/]/') ){
break;
}
$op = $this->MatchChar('/');
if( !$op ){
$op = $this->MatchChar('*');
if( !$op ){
break;
}
}
$a = $this->parseOperand();
if(!$a) { break; }
$m->parensInOp = true;
$a->parensInOp = true;
$return = $this->NewObj3('Less_Tree_Operation',array( $op, array( $return, $a ), $isSpaced) );
}
}
return $return;
}
/**
* Parses an addition operation
*
* @return Less_Tree_Operation|null
*/
private function parseAddition (){
$return = $m = $this->parseMultiplication();
if( $return ){
while( true ){
$isSpaced = $this->isWhitespace( -1 );
$op = $this->MatchReg('/\\G[-+]\s+/');
if( $op ){
$op = $op[0];
}else{
if( !$isSpaced ){
$op = $this->match(array('#+','#-'));
}
if( !$op ){
break;
}
}
$a = $this->parseMultiplication();
if( !$a ){
break;
}
$m->parensInOp = true;
$a->parensInOp = true;
$return = $this->NewObj3('Less_Tree_Operation',array($op, array($return, $a), $isSpaced));
}
}
return $return;
}
/**
* Parses the conditions
*
* @return Less_Tree_Condition|null
*/
private function parseConditions() {
$index = $this->pos;
$return = $a = $this->parseCondition();
if( $a ){
while( true ){
if( !$this->PeekReg('/\\G,\s*(not\s*)?\(/') || !$this->MatchChar(',') ){
break;
}
$b = $this->parseCondition();
if( !$b ){
break;
}
$return = $this->NewObj4('Less_Tree_Condition',array('or', $return, $b, $index));
}
return $return;
}
}
private function parseCondition() {
$index = $this->pos;
$negate = false;
$c = null;
if ($this->MatchReg('/\\Gnot/')) $negate = true;
$this->expectChar('(');
$a = $this->MatchFuncs(array('parseAddition','parseEntitiesKeyword','parseEntitiesQuoted'));
if( $a ){
$op = $this->MatchReg('/\\G(?:>=|<=|=<|[<=>])/');
if( $op ){
$b = $this->MatchFuncs(array('parseAddition','parseEntitiesKeyword','parseEntitiesQuoted'));
if( $b ){
$c = $this->NewObj5('Less_Tree_Condition',array($op[0], $a, $b, $index, $negate));
} else {
$this->Error('Unexpected expression');
}
} else {
$k = $this->NewObj1('Less_Tree_Keyword','true');
$c = $this->NewObj5('Less_Tree_Condition',array('=', $a, $k, $index, $negate));
}
$this->expectChar(')');
return $this->MatchReg('/\\Gand/') ? $this->NewObj3('Less_Tree_Condition',array('and', $c, $this->parseCondition())) : $c;
}
}
/**
* An operand is anything that can be part of an operation,
* such as a Color, or a Variable
*
*/
private function parseOperand (){
$negate = false;
$offset = $this->pos+1;
if( $offset >= $this->input_len ){
return;
}
$char = $this->input[$offset];
if( $char === '@' || $char === '(' ){
$negate = $this->MatchChar('-');
}
$o = $this->MatchFuncs(array('parseSub','parseEntitiesDimension','parseEntitiesColor','parseEntitiesVariable','parseEntitiesCall'));
if( $negate ){
$o->parensInOp = true;
$o = $this->NewObj1('Less_Tree_Negative',$o);
}
return $o;
}
/**
* Expressions either represent mathematical operations,
* or white-space delimited Entities.
*
* 1px solid black
* @var * 2
*
* @return Less_Tree_Expression|null
*/
private function parseExpression (){
$entities = array();
do{
$e = $this->MatchFuncs(array('parseAddition','parseEntity'));
if( $e ){
$entities[] = $e;
// operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
if( !$this->PeekReg('/\\G\/[\/*]/') ){
$delim = $this->MatchChar('/');
if( $delim ){
$entities[] = $this->NewObj1('Less_Tree_Anonymous',$delim);
}
}
}
}while($e);
if( $entities ){
return $this->NewObj1('Less_Tree_Expression',$entities);
}
}
/**
* Parse a property
* eg: 'min-width', 'orientation', etc
*
* @return string
*/
private function parseProperty (){
$name = $this->MatchReg('/\\G(\*?-?[_a-zA-Z0-9-]+)\s*:/');
if( $name ){
return $name[1];
}
}
/**
* Parse a rule property
* eg: 'color', 'width', 'height', etc
*
* @return string
*/
private function parseRuleProperty(){
$offset = $this->pos;
$name = array();
$index = array();
$length = 0;
$this->rulePropertyMatch('/\\G(\*?)/', $offset, $length, $index, $name );
while( $this->rulePropertyMatch('/\\G((?:[\w-]+)|(?:@\{[\w-]+\}))/', $offset, $length, $index, $name )); // !
if( (count($name) > 1) && $this->rulePropertyMatch('/\\G\s*((?:\+_|\+)?)\s*:/', $offset, $length, $index, $name) ){
// at last, we have the complete match now. move forward,
// convert name particles to tree objects and return:
$this->skipWhitespace($length);
if( $name[0] === '' ){
array_shift($name);
array_shift($index);
}
foreach($name as $k => $s ){
if( !$s || $s[0] !== '@' ){
$name[$k] = $this->NewObj1('Less_Tree_Keyword',$s);
}else{
$name[$k] = $this->NewObj3('Less_Tree_Variable',array('@' . substr($s,2,-1), $index[$k], $this->env->currentFileInfo));
}
}
return $name;
}
}
private function rulePropertyMatch( $re, &$offset, &$length, &$index, &$name ){
preg_match($re, $this->input, $a, 0, $offset);
if( $a ){
$index[] = $this->pos + $length;
$length += strlen($a[0]);
$offset += strlen($a[0]);
$name[] = $a[1];
return true;
}
}
public static function serializeVars( $vars ){
$s = '';
foreach($vars as $name => $value){
$s .= (($name[0] === '@') ? '' : '@') . $name .': '. $value . ((substr($value,-1) === ';') ? '' : ';');
}
return $s;
}
/**
* Some versions of php have trouble with method_exists($a,$b) if $a is not an object
*
* @param string $b
*/
public static function is_method($a,$b){
return is_object($a) && method_exists($a,$b);
}
/**
* Round numbers similarly to javascript
* eg: 1.499999 to 1 instead of 2
*
*/
public static function round($i, $precision = 0){
$precision = pow(10,$precision);
$i = $i*$precision;
$ceil = ceil($i);
$floor = floor($i);
if( ($ceil - $i) <= ($i - $floor) ){
return $ceil/$precision;
}else{
return $floor/$precision;
}
}
/**
* Create Less_Tree_* objects and optionally generate a cache string
*
* @return mixed
*/
public function NewObj0($class){
$obj = new $class();
if( $this->CacheEnabled() ){
$obj->cache_string = ' new '.$class.'()';
}
return $obj;
}
public function NewObj1($class, $arg){
$obj = new $class( $arg );
if( $this->CacheEnabled() ){
$obj->cache_string = ' new '.$class.'('.Less_Parser::ArgString($arg).')';
}
return $obj;
}
public function NewObj2($class, $args){
$obj = new $class( $args[0], $args[1] );
if( $this->CacheEnabled() ){
$this->ObjCache( $obj, $class, $args);
}
return $obj;
}
public function NewObj3($class, $args){
$obj = new $class( $args[0], $args[1], $args[2] );
if( $this->CacheEnabled() ){
$this->ObjCache( $obj, $class, $args);
}
return $obj;
}
public function NewObj4($class, $args){
$obj = new $class( $args[0], $args[1], $args[2], $args[3] );
if( $this->CacheEnabled() ){
$this->ObjCache( $obj, $class, $args);
}
return $obj;
}
public function NewObj5($class, $args){
$obj = new $class( $args[0], $args[1], $args[2], $args[3], $args[4] );
if( $this->CacheEnabled() ){
$this->ObjCache( $obj, $class, $args);
}
return $obj;
}
public function NewObj6($class, $args){
$obj = new $class( $args[0], $args[1], $args[2], $args[3], $args[4], $args[5] );
if( $this->CacheEnabled() ){
$this->ObjCache( $obj, $class, $args);
}
return $obj;
}
public function NewObj7($class, $args){
$obj = new $class( $args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6] );
if( $this->CacheEnabled() ){
$this->ObjCache( $obj, $class, $args);
}
return $obj;
}
//caching
public function ObjCache($obj, $class, $args=array()){
$obj->cache_string = ' new '.$class.'('. self::ArgCache($args).')';
}
public function ArgCache($args){
return implode(',',array_map( array('Less_Parser','ArgString'),$args));
}
/**
* Convert an argument to a string for use in the parser cache
*
* @return string
*/
public static function ArgString($arg){
$type = gettype($arg);
if( $type === 'object'){
$string = $arg->cache_string;
unset($arg->cache_string);
return $string;
}elseif( $type === 'array' ){
$string = ' Array(';
foreach($arg as $k => $a){
$string .= var_export($k,true).' => '.self::ArgString($a).',';
}
return $string . ')';
}
return var_export($arg,true);
}
public function Error($msg){
throw new Less_Exception_Parser($msg, null, $this->furthest, $this->env->currentFileInfo);
}
public static function WinPath($path){
return str_replace('\\', '/', $path);
}
public function CacheEnabled(){
return (Less_Parser::$options['cache_method'] && (Less_Cache::$cache_dir || (Less_Parser::$options['cache_method'] == 'callback')));
}
}
/**
* Utility for css colors
*
* @package Less
* @subpackage color
*/
class Less_Colors {
public static $colors = array(
'aliceblue'=>'#f0f8ff',
'antiquewhite'=>'#faebd7',
'aqua'=>'#00ffff',
'aquamarine'=>'#7fffd4',
'azure'=>'#f0ffff',
'beige'=>'#f5f5dc',
'bisque'=>'#ffe4c4',
'black'=>'#000000',
'blanchedalmond'=>'#ffebcd',
'blue'=>'#0000ff',
'blueviolet'=>'#8a2be2',
'brown'=>'#a52a2a',
'burlywood'=>'#deb887',
'cadetblue'=>'#5f9ea0',
'chartreuse'=>'#7fff00',
'chocolate'=>'#d2691e',
'coral'=>'#ff7f50',
'cornflowerblue'=>'#6495ed',
'cornsilk'=>'#fff8dc',
'crimson'=>'#dc143c',
'cyan'=>'#00ffff',
'darkblue'=>'#00008b',
'darkcyan'=>'#008b8b',
'darkgoldenrod'=>'#b8860b',
'darkgray'=>'#a9a9a9',
'darkgrey'=>'#a9a9a9',
'darkgreen'=>'#006400',
'darkkhaki'=>'#bdb76b',
'darkmagenta'=>'#8b008b',
'darkolivegreen'=>'#556b2f',
'darkorange'=>'#ff8c00',
'darkorchid'=>'#9932cc',
'darkred'=>'#8b0000',
'darksalmon'=>'#e9967a',
'darkseagreen'=>'#8fbc8f',
'darkslateblue'=>'#483d8b',
'darkslategray'=>'#2f4f4f',
'darkslategrey'=>'#2f4f4f',
'darkturquoise'=>'#00ced1',
'darkviolet'=>'#9400d3',
'deeppink'=>'#ff1493',
'deepskyblue'=>'#00bfff',
'dimgray'=>'#696969',
'dimgrey'=>'#696969',
'dodgerblue'=>'#1e90ff',
'firebrick'=>'#b22222',
'floralwhite'=>'#fffaf0',
'forestgreen'=>'#228b22',
'fuchsia'=>'#ff00ff',
'gainsboro'=>'#dcdcdc',
'ghostwhite'=>'#f8f8ff',
'gold'=>'#ffd700',
'goldenrod'=>'#daa520',
'gray'=>'#808080',
'grey'=>'#808080',
'green'=>'#008000',
'greenyellow'=>'#adff2f',
'honeydew'=>'#f0fff0',
'hotpink'=>'#ff69b4',
'indianred'=>'#cd5c5c',
'indigo'=>'#4b0082',
'ivory'=>'#fffff0',
'khaki'=>'#f0e68c',
'lavender'=>'#e6e6fa',
'lavenderblush'=>'#fff0f5',
'lawngreen'=>'#7cfc00',
'lemonchiffon'=>'#fffacd',
'lightblue'=>'#add8e6',
'lightcoral'=>'#f08080',
'lightcyan'=>'#e0ffff',
'lightgoldenrodyellow'=>'#fafad2',
'lightgray'=>'#d3d3d3',
'lightgrey'=>'#d3d3d3',
'lightgreen'=>'#90ee90',
'lightpink'=>'#ffb6c1',
'lightsalmon'=>'#ffa07a',
'lightseagreen'=>'#20b2aa',
'lightskyblue'=>'#87cefa',
'lightslategray'=>'#778899',
'lightslategrey'=>'#778899',
'lightsteelblue'=>'#b0c4de',
'lightyellow'=>'#ffffe0',
'lime'=>'#00ff00',
'limegreen'=>'#32cd32',
'linen'=>'#faf0e6',
'magenta'=>'#ff00ff',
'maroon'=>'#800000',
'mediumaquamarine'=>'#66cdaa',
'mediumblue'=>'#0000cd',
'mediumorchid'=>'#ba55d3',
'mediumpurple'=>'#9370d8',
'mediumseagreen'=>'#3cb371',
'mediumslateblue'=>'#7b68ee',
'mediumspringgreen'=>'#00fa9a',
'mediumturquoise'=>'#48d1cc',
'mediumvioletred'=>'#c71585',
'midnightblue'=>'#191970',
'mintcream'=>'#f5fffa',
'mistyrose'=>'#ffe4e1',
'moccasin'=>'#ffe4b5',
'navajowhite'=>'#ffdead',
'navy'=>'#000080',
'oldlace'=>'#fdf5e6',
'olive'=>'#808000',
'olivedrab'=>'#6b8e23',
'orange'=>'#ffa500',
'orangered'=>'#ff4500',
'orchid'=>'#da70d6',
'palegoldenrod'=>'#eee8aa',
'palegreen'=>'#98fb98',
'paleturquoise'=>'#afeeee',
'palevioletred'=>'#d87093',
'papayawhip'=>'#ffefd5',
'peachpuff'=>'#ffdab9',
'peru'=>'#cd853f',
'pink'=>'#ffc0cb',
'plum'=>'#dda0dd',
'powderblue'=>'#b0e0e6',
'purple'=>'#800080',
'red'=>'#ff0000',
'rosybrown'=>'#bc8f8f',
'royalblue'=>'#4169e1',
'saddlebrown'=>'#8b4513',
'salmon'=>'#fa8072',
'sandybrown'=>'#f4a460',
'seagreen'=>'#2e8b57',
'seashell'=>'#fff5ee',
'sienna'=>'#a0522d',
'silver'=>'#c0c0c0',
'skyblue'=>'#87ceeb',
'slateblue'=>'#6a5acd',
'slategray'=>'#708090',
'slategrey'=>'#708090',
'snow'=>'#fffafa',
'springgreen'=>'#00ff7f',
'steelblue'=>'#4682b4',
'tan'=>'#d2b48c',
'teal'=>'#008080',
'thistle'=>'#d8bfd8',
'tomato'=>'#ff6347',
'turquoise'=>'#40e0d0',
'violet'=>'#ee82ee',
'wheat'=>'#f5deb3',
'white'=>'#ffffff',
'whitesmoke'=>'#f5f5f5',
'yellow'=>'#ffff00',
'yellowgreen'=>'#9acd32'
);
public static function hasOwnProperty($color) {
return isset(self::$colors[$color]);
}
public static function color($color) {
return self::$colors[$color];
}
}
/**
* Environment
*
* @package Less
* @subpackage environment
*/
class Less_Environment{
//public $paths = array(); // option - unmodified - paths to search for imports on
//public static $files = array(); // list of files that have been imported, used for import-once
//public $rootpath; // option - rootpath to append to URL's
//public static $strictImports = null; // option -
//public $insecure; // option - whether to allow imports from insecure ssl hosts
//public $processImports; // option - whether to process imports. if false then imports will not be imported
//public $javascriptEnabled; // option - whether JavaScript is enabled. if undefined, defaults to true
//public $useFileCache; // browser only - whether to use the per file session cache
public $currentFileInfo; // information about the current file - for error reporting and importing and making urls relative etc.
public $importMultiple = false; // whether we are currently importing multiple copies
/**
* @var array
*/
public $frames = array();
/**
* @var array
*/
public $mediaBlocks = array();
/**
* @var array
*/
public $mediaPath = array();
public static $parensStack = 0;
public static $tabLevel = 0;
public static $lastRule = false;
public static $_outputMap;
public static $mixin_stack = 0;
/**
* @var array
*/
public $functions = array();
public function Init(){
self::$parensStack = 0;
self::$tabLevel = 0;
self::$lastRule = false;
self::$mixin_stack = 0;
if( Less_Parser::$options['compress'] ){
Less_Environment::$_outputMap = array(
',' => ',',
': ' => ':',
'' => '',
' ' => ' ',
':' => ' :',
'+' => '+',
'~' => '~',
'>' => '>',
'|' => '|',
'^' => '^',
'^^' => '^^'
);
}else{
Less_Environment::$_outputMap = array(
',' => ', ',
': ' => ': ',
'' => '',
' ' => ' ',
':' => ' :',
'+' => ' + ',
'~' => ' ~ ',
'>' => ' > ',
'|' => '|',
'^' => ' ^ ',
'^^' => ' ^^ '
);
}
}
public function copyEvalEnv($frames = array() ){
$new_env = new Less_Environment();
$new_env->frames = $frames;
return $new_env;
}
public static function isMathOn(){
return !Less_Parser::$options['strictMath'] || Less_Environment::$parensStack;
}
public static function isPathRelative($path){
return !preg_match('/^(?:[a-z-]+:|\/)/',$path);
}
/**
* Canonicalize a path by resolving references to '/./', '/../'
* Does not remove leading "../"
* @param string path or url
* @return string Canonicalized path
*
*/
public static function normalizePath($path){
$segments = explode('/',$path);
$segments = array_reverse($segments);
$path = array();
$path_len = 0;
while( $segments ){
$segment = array_pop($segments);
switch( $segment ) {
case '.':
break;
case '..':
if( !$path_len || ( $path[$path_len-1] === '..') ){
$path[] = $segment;
$path_len++;
}else{
array_pop($path);
$path_len--;
}
break;
default:
$path[] = $segment;
$path_len++;
break;
}
}
return implode('/',$path);
}
public function unshiftFrame($frame){
array_unshift($this->frames, $frame);
}
public function shiftFrame(){
return array_shift($this->frames);
}
}
/**
* Builtin functions
*
* @package Less
* @subpackage function
* @see http://lesscss.org/functions/
*/
class Less_Functions{
public $env;
public $currentFileInfo;
function __construct($env, $currentFileInfo = null ){
$this->env = $env;
$this->currentFileInfo = $currentFileInfo;
}
/**
* @param string $op
*/
public static function operate( $op, $a, $b ){
switch ($op) {
case '+': return $a + $b;
case '-': return $a - $b;
case '*': return $a * $b;
case '/': return $a / $b;
}
}
public static function clamp($val, $max = 1){
return min( max($val, 0), $max);
}
public static function fround( $value ){
if( $value === 0 ){
return $value;
}
if( Less_Parser::$options['numPrecision'] ){
$p = pow(10, Less_Parser::$options['numPrecision']);
return round( $value * $p) / $p;
}
return $value;
}
public static function number($n){
if ($n instanceof Less_Tree_Dimension) {
return floatval( $n->unit->is('%') ? $n->value / 100 : $n->value);
} else if (is_numeric($n)) {
return $n;
} else {
throw new Less_Exception_Compiler("color functions take numbers as parameters");
}
}
public static function scaled($n, $size = 255 ){
if( $n instanceof Less_Tree_Dimension && $n->unit->is('%') ){
return (float)$n->value * $size / 100;
} else {
return Less_Functions::number($n);
}
}
public function rgb ($r = null, $g = null, $b = null){
if (is_null($r) || is_null($g) || is_null($b)) {
throw new Less_Exception_Compiler("rgb expects three parameters");
}
return $this->rgba($r, $g, $b, 1.0);
}
public function rgba($r = null, $g = null, $b = null, $a = null){
$rgb = array($r, $g, $b);
$rgb = array_map(array('Less_Functions','scaled'),$rgb);
$a = self::number($a);
return new Less_Tree_Color($rgb, $a);
}
public function hsl($h, $s, $l){
return $this->hsla($h, $s, $l, 1.0);
}
public function hsla($h, $s, $l, $a){
$h = fmod(self::number($h), 360) / 360; // Classic % operator will change float to int
$s = self::clamp(self::number($s));
$l = self::clamp(self::number($l));
$a = self::clamp(self::number($a));
$m2 = $l <= 0.5 ? $l * ($s + 1) : $l + $s - $l * $s;
$m1 = $l * 2 - $m2;
return $this->rgba( self::hsla_hue($h + 1/3, $m1, $m2) * 255,
self::hsla_hue($h, $m1, $m2) * 255,
self::hsla_hue($h - 1/3, $m1, $m2) * 255,
$a);
}
/**
* @param double $h
*/
public function hsla_hue($h, $m1, $m2){
$h = $h < 0 ? $h + 1 : ($h > 1 ? $h - 1 : $h);
if ($h * 6 < 1) return $m1 + ($m2 - $m1) * $h * 6;
else if ($h * 2 < 1) return $m2;
else if ($h * 3 < 2) return $m1 + ($m2 - $m1) * (2/3 - $h) * 6;
else return $m1;
}
public function hsv($h, $s, $v) {
return $this->hsva($h, $s, $v, 1.0);
}
/**
* @param double $a
*/
public function hsva($h, $s, $v, $a) {
$h = ((Less_Functions::number($h) % 360) / 360 ) * 360;
$s = Less_Functions::number($s);
$v = Less_Functions::number($v);
$a = Less_Functions::number($a);
$i = floor(($h / 60) % 6);
$f = ($h / 60) - $i;
$vs = array( $v,
$v * (1 - $s),
$v * (1 - $f * $s),
$v * (1 - (1 - $f) * $s));
$perm = array(array(0, 3, 1),
array(2, 0, 1),
array(1, 0, 3),
array(1, 2, 0),
array(3, 1, 0),
array(0, 1, 2));
return $this->rgba($vs[$perm[$i][0]] * 255,
$vs[$perm[$i][1]] * 255,
$vs[$perm[$i][2]] * 255,
$a);
}
public function hue($color = null){
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to hue must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$c = $color->toHSL();
return new Less_Tree_Dimension(Less_Parser::round($c['h']));
}
public function saturation($color = null){
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to saturation must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$c = $color->toHSL();
return new Less_Tree_Dimension(Less_Parser::round($c['s'] * 100), '%');
}
public function lightness($color = null){
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to lightness must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$c = $color->toHSL();
return new Less_Tree_Dimension(Less_Parser::round($c['l'] * 100), '%');
}
public function hsvhue( $color = null ){
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to hsvhue must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$hsv = $color->toHSV();
return new Less_Tree_Dimension( Less_Parser::round($hsv['h']) );
}
public function hsvsaturation( $color = null ){
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to hsvsaturation must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$hsv = $color->toHSV();
return new Less_Tree_Dimension( Less_Parser::round($hsv['s'] * 100), '%' );
}
public function hsvvalue( $color = null ){
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to hsvvalue must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$hsv = $color->toHSV();
return new Less_Tree_Dimension( Less_Parser::round($hsv['v'] * 100), '%' );
}
public function red($color = null) {
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to red must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
return new Less_Tree_Dimension( $color->rgb[0] );
}
public function green($color = null) {
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to green must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
return new Less_Tree_Dimension( $color->rgb[1] );
}
public function blue($color = null) {
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to blue must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
return new Less_Tree_Dimension( $color->rgb[2] );
}
public function alpha($color = null){
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to alpha must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$c = $color->toHSL();
return new Less_Tree_Dimension($c['a']);
}
public function luma ($color = null) {
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to luma must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
return new Less_Tree_Dimension(Less_Parser::round( $color->luma() * $color->alpha * 100), '%');
}
public function luminance( $color = null ){
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to luminance must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$luminance =
(0.2126 * $color->rgb[0] / 255)
+ (0.7152 * $color->rgb[1] / 255)
+ (0.0722 * $color->rgb[2] / 255);
return new Less_Tree_Dimension(Less_Parser::round( $luminance * $color->alpha * 100), '%');
}
public function saturate($color = null, $amount = null){
// filter: saturate(3.2);
// should be kept as is, so check for color
if ($color instanceof Less_Tree_Dimension) {
return null;
}
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to saturate must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$amount instanceof Less_Tree_Dimension) {
throw new Less_Exception_Compiler('The second argument to saturate must be a percentage' . ($amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$hsl = $color->toHSL();
$hsl['s'] += $amount->value / 100;
$hsl['s'] = self::clamp($hsl['s']);
return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
}
/**
* @param Less_Tree_Dimension $amount
*/
public function desaturate($color = null, $amount = null){
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to desaturate must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$amount instanceof Less_Tree_Dimension) {
throw new Less_Exception_Compiler('The second argument to desaturate must be a percentage' . ($amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$hsl = $color->toHSL();
$hsl['s'] -= $amount->value / 100;
$hsl['s'] = self::clamp($hsl['s']);
return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
}
public function lighten($color = null, $amount=null){
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to lighten must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$amount instanceof Less_Tree_Dimension) {
throw new Less_Exception_Compiler('The second argument to lighten must be a percentage' . ($amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$hsl = $color->toHSL();
$hsl['l'] += $amount->value / 100;
$hsl['l'] = self::clamp($hsl['l']);
return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
}
public function darken($color = null, $amount = null){
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to darken must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$amount instanceof Less_Tree_Dimension) {
throw new Less_Exception_Compiler('The second argument to darken must be a percentage' . ($amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$hsl = $color->toHSL();
$hsl['l'] -= $amount->value / 100;
$hsl['l'] = self::clamp($hsl['l']);
return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
}
public function fadein($color = null, $amount = null){
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to fadein must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$amount instanceof Less_Tree_Dimension) {
throw new Less_Exception_Compiler('The second argument to fadein must be a percentage' . ($amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$hsl = $color->toHSL();
$hsl['a'] += $amount->value / 100;
$hsl['a'] = self::clamp($hsl['a']);
return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
}
public function fadeout($color = null, $amount = null){
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to fadeout must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$amount instanceof Less_Tree_Dimension) {
throw new Less_Exception_Compiler('The second argument to fadeout must be a percentage' . ($amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$hsl = $color->toHSL();
$hsl['a'] -= $amount->value / 100;
$hsl['a'] = self::clamp($hsl['a']);
return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
}
public function fade($color = null, $amount = null){
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to fade must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$amount instanceof Less_Tree_Dimension) {
throw new Less_Exception_Compiler('The second argument to fade must be a percentage' . ($amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$hsl = $color->toHSL();
$hsl['a'] = $amount->value / 100;
$hsl['a'] = self::clamp($hsl['a']);
return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
}
public function spin($color = null, $amount = null){
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to spin must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$amount instanceof Less_Tree_Dimension) {
throw new Less_Exception_Compiler('The second argument to spin must be a number' . ($amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$hsl = $color->toHSL();
$hue = fmod($hsl['h'] + $amount->value, 360);
$hsl['h'] = $hue < 0 ? 360 + $hue : $hue;
return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
}
//
// Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein
// http://sass-lang.com
//
/**
* @param Less_Tree_Color $color1
*/
public function mix($color1 = null, $color2 = null, $weight = null){
if (!$color1 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to mix must be a color' . ($color1 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$color2 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The second argument to mix must be a color' . ($color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$weight) {
$weight = new Less_Tree_Dimension('50', '%');
}
if (!$weight instanceof Less_Tree_Dimension) {
throw new Less_Exception_Compiler('The third argument to contrast must be a percentage' . ($weight instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
$p = $weight->value / 100.0;
$w = $p * 2 - 1;
$hsl1 = $color1->toHSL();
$hsl2 = $color2->toHSL();
$a = $hsl1['a'] - $hsl2['a'];
$w1 = (((($w * $a) == -1) ? $w : ($w + $a) / (1 + $w * $a)) + 1) / 2;
$w2 = 1 - $w1;
$rgb = array($color1->rgb[0] * $w1 + $color2->rgb[0] * $w2,
$color1->rgb[1] * $w1 + $color2->rgb[1] * $w2,
$color1->rgb[2] * $w1 + $color2->rgb[2] * $w2);
$alpha = $color1->alpha * $p + $color2->alpha * (1 - $p);
return new Less_Tree_Color($rgb, $alpha);
}
public function greyscale($color){
return $this->desaturate($color, new Less_Tree_Dimension(100,'%'));
}
public function contrast( $color, $dark = null, $light = null, $threshold = null){
// filter: contrast(3.2);
// should be kept as is, so check for color
if (!$color instanceof Less_Tree_Color) {
return null;
}
if( !$light ){
$light = $this->rgba(255, 255, 255, 1.0);
}
if( !$dark ){
$dark = $this->rgba(0, 0, 0, 1.0);
}
if (!$dark instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The second argument to contrast must be a color' . ($dark instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$light instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The third argument to contrast must be a color' . ($light instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
//Figure out which is actually light and dark!
if( $dark->luma() > $light->luma() ){
$t = $light;
$light = $dark;
$dark = $t;
}
if( !$threshold ){
$threshold = 0.43;
} else {
$threshold = Less_Functions::number($threshold);
}
if( $color->luma() < $threshold ){
return $light;
} else {
return $dark;
}
}
public function e ($str){
if( is_string($str) ){
return new Less_Tree_Anonymous($str);
}
return new Less_Tree_Anonymous($str instanceof Less_Tree_JavaScript ? $str->expression : $str->value);
}
public function escape ($str){
$revert = array('%21'=>'!', '%2A'=>'*', '%27'=>"'",'%3F'=>'?','%26'=>'&','%2C'=>',','%2F'=>'/','%40'=>'@','%2B'=>'+','%24'=>'$');
return new Less_Tree_Anonymous(strtr(rawurlencode($str->value), $revert));
}
/**
* todo: This function will need some additional work to make it work the same as less.js
*
*/
public function replace( $string, $pattern, $replacement, $flags = null ){
$result = $string->value;
$expr = '/'.str_replace('/','\\/',$pattern->value).'/';
if( $flags && $flags->value){
$expr .= self::replace_flags($flags->value);
}
$result = preg_replace($expr,$replacement->value,$result);
if( property_exists($string,'quote') ){
return new Less_Tree_Quoted( $string->quote, $result, $string->escaped);
}
return new Less_Tree_Quoted( '', $result );
}
public static function replace_flags($flags){
$flags = str_split($flags,1);
$new_flags = '';
foreach($flags as $flag){
switch($flag){
case 'e':
case 'g':
break;
default:
$new_flags .= $flag;
break;
}
}
return $new_flags;
}
public function _percent(){
$string = func_get_arg(0);
$args = func_get_args();
array_shift($args);
$result = $string->value;
foreach($args as $arg){
if( preg_match('/%[sda]/i',$result, $token) ){
$token = $token[0];
$value = stristr($token, 's') ? $arg->value : $arg->toCSS();
$value = preg_match('/[A-Z]$/', $token) ? urlencode($value) : $value;
$result = preg_replace('/%[sda]/i',$value, $result, 1);
}
}
$result = str_replace('%%', '%', $result);
return new Less_Tree_Quoted( $string->quote , $result, $string->escaped);
}
public function unit( $val, $unit = null) {
if( !($val instanceof Less_Tree_Dimension) ){
throw new Less_Exception_Compiler('The first argument to unit must be a number' . ($val instanceof Less_Tree_Operation ? '. Have you forgotten parenthesis?' : '.') );
}
if( $unit ){
if( $unit instanceof Less_Tree_Keyword ){
$unit = $unit->value;
} else {
$unit = $unit->toCSS();
}
} else {
$unit = "";
}
return new Less_Tree_Dimension($val->value, $unit );
}
public function convert($val, $unit){
return $val->convertTo($unit->value);
}
public function round($n, $f = false) {
$fraction = 0;
if( $f !== false ){
$fraction = $f->value;
}
return $this->_math('Less_Parser::round',null, $n, $fraction);
}
public function pi(){
return new Less_Tree_Dimension(M_PI);
}
public function mod($a, $b) {
return new Less_Tree_Dimension( $a->value % $b->value, $a->unit);
}
public function pow($x, $y) {
if( is_numeric($x) && is_numeric($y) ){
$x = new Less_Tree_Dimension($x);
$y = new Less_Tree_Dimension($y);
}elseif( !($x instanceof Less_Tree_Dimension) || !($y instanceof Less_Tree_Dimension) ){
throw new Less_Exception_Compiler('Arguments must be numbers');
}
return new Less_Tree_Dimension( pow($x->value, $y->value), $x->unit );
}
// var mathFunctions = [{name:"ce ...
public function ceil( $n ){ return $this->_math('ceil', null, $n); }
public function floor( $n ){ return $this->_math('floor', null, $n); }
public function sqrt( $n ){ return $this->_math('sqrt', null, $n); }
public function abs( $n ){ return $this->_math('abs', null, $n); }
public function tan( $n ){ return $this->_math('tan', '', $n); }
public function sin( $n ){ return $this->_math('sin', '', $n); }
public function cos( $n ){ return $this->_math('cos', '', $n); }
public function atan( $n ){ return $this->_math('atan', 'rad', $n); }
public function asin( $n ){ return $this->_math('asin', 'rad', $n); }
public function acos( $n ){ return $this->_math('acos', 'rad', $n); }
private function _math() {
$args = func_get_args();
$fn = array_shift($args);
$unit = array_shift($args);
if ($args[0] instanceof Less_Tree_Dimension) {
if( $unit === null ){
$unit = $args[0]->unit;
}else{
$args[0] = $args[0]->unify();
}
$args[0] = (float)$args[0]->value;
return new Less_Tree_Dimension( call_user_func_array($fn, $args), $unit);
} else if (is_numeric($args[0])) {
return call_user_func_array($fn,$args);
} else {
throw new Less_Exception_Compiler("math functions take numbers as parameters");
}
}
/**
* @param boolean $isMin
*/
private function _minmax( $isMin, $args ){
$arg_count = count($args);
if( $arg_count < 1 ){
throw new Less_Exception_Compiler( 'one or more arguments required');
}
$j = null;
$unitClone = null;
$unitStatic = null;
$order = array(); // elems only contains original argument values.
$values = array(); // key is the unit.toString() for unified tree.Dimension values,
// value is the index into the order array.
for( $i = 0; $i < $arg_count; $i++ ){
$current = $args[$i];
if( !($current instanceof Less_Tree_Dimension) ){
if( is_array($args[$i]->value) ){
$args[] = $args[$i]->value;
}
continue;
}
if( $current->unit->toString() === '' && !$unitClone ){
$temp = new Less_Tree_Dimension($current->value, $unitClone);
$currentUnified = $temp->unify();
}else{
$currentUnified = $current->unify();
}
if( $currentUnified->unit->toString() === "" && !$unitStatic ){
$unit = $unitStatic;
}else{
$unit = $currentUnified->unit->toString();
}
if( $unit !== '' && !$unitStatic || $unit !== '' && $order[0]->unify()->unit->toString() === "" ){
$unitStatic = $unit;
}
if( $unit != '' && !$unitClone ){
$unitClone = $current->unit->toString();
}
if( isset($values['']) && $unit !== '' && $unit === $unitStatic ){
$j = $values[''];
}elseif( isset($values[$unit]) ){
$j = $values[$unit];
}else{
if( $unitStatic && $unit !== $unitStatic ){
throw new Less_Exception_Compiler( 'incompatible types');
}
$values[$unit] = count($order);
$order[] = $current;
continue;
}
if( $order[$j]->unit->toString() === "" && $unitClone ){
$temp = new Less_Tree_Dimension( $order[$j]->value, $unitClone);
$referenceUnified = $temp->unifiy();
}else{
$referenceUnified = $order[$j]->unify();
}
if( ($isMin && $currentUnified->value < $referenceUnified->value) || (!$isMin && $currentUnified->value > $referenceUnified->value) ){
$order[$j] = $current;
}
}
if( count($order) == 1 ){
return $order[0];
}
$args = array();
foreach($order as $a){
$args[] = $a->toCSS($this->env);
}
return new Less_Tree_Anonymous( ($isMin?'min(':'max(') . implode(Less_Environment::$_outputMap[','],$args).')');
}
public function min(){
$args = func_get_args();
return $this->_minmax( true, $args );
}
public function max(){
$args = func_get_args();
return $this->_minmax( false, $args );
}
public function getunit($n){
return new Less_Tree_Anonymous($n->unit);
}
public function argb($color) {
if (!$color instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to argb must be a color' . ($dark instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
return new Less_Tree_Anonymous($color->toARGB());
}
public function percentage($n) {
return new Less_Tree_Dimension($n->value * 100, '%');
}
public function color($n) {
if( $n instanceof Less_Tree_Quoted ){
$colorCandidate = $n->value;
$returnColor = Less_Tree_Color::fromKeyword($colorCandidate);
if( $returnColor ){
return $returnColor;
}
if( preg_match('/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/',$colorCandidate) ){
return new Less_Tree_Color(substr($colorCandidate, 1));
}
throw new Less_Exception_Compiler("argument must be a color keyword or 3/6 digit hex e.g. #FFF");
} else {
throw new Less_Exception_Compiler("argument must be a string");
}
}
public function iscolor($n) {
return $this->_isa($n, 'Less_Tree_Color');
}
public function isnumber($n) {
return $this->_isa($n, 'Less_Tree_Dimension');
}
public function isstring($n) {
return $this->_isa($n, 'Less_Tree_Quoted');
}
public function iskeyword($n) {
return $this->_isa($n, 'Less_Tree_Keyword');
}
public function isurl($n) {
return $this->_isa($n, 'Less_Tree_Url');
}
public function ispixel($n) {
return $this->isunit($n, 'px');
}
public function ispercentage($n) {
return $this->isunit($n, '%');
}
public function isem($n) {
return $this->isunit($n, 'em');
}
/**
* @param string $unit
*/
public function isunit( $n, $unit ){
return ($n instanceof Less_Tree_Dimension) && $n->unit->is( ( property_exists($unit,'value') ? $unit->value : $unit) ) ? new Less_Tree_Keyword('true') : new Less_Tree_Keyword('false');
}
/**
* @param string $type
*/
private function _isa($n, $type) {
return is_a($n, $type) ? new Less_Tree_Keyword('true') : new Less_Tree_Keyword('false');
}
public function tint($color, $amount) {
return $this->mix( $this->rgb(255,255,255), $color, $amount);
}
public function shade($color, $amount) {
return $this->mix($this->rgb(0, 0, 0), $color, $amount);
}
public function extract($values, $index ){
$index = (int)$index->value - 1; // (1-based index)
// handle non-array values as an array of length 1
// return 'undefined' if index is invalid
if( property_exists($values,'value') && is_array($values->value) ){
if( isset($values->value[$index]) ){
return $values->value[$index];
}
return null;
}elseif( (int)$index === 0 ){
return $values;
}
return null;
}
public function length($values){
$n = (property_exists($values,'value') && is_array($values->value)) ? count($values->value) : 1;
return new Less_Tree_Dimension($n);
}
public function datauri($mimetypeNode, $filePathNode = null ) {
$filePath = ( $filePathNode ? $filePathNode->value : null );
$mimetype = $mimetypeNode->value;
$args = 2;
if( !$filePath ){
$filePath = $mimetype;
$args = 1;
}
$filePath = str_replace('\\','/',$filePath);
if( Less_Environment::isPathRelative($filePath) ){
if( Less_Parser::$options['relativeUrls'] ){
$temp = $this->currentFileInfo['currentDirectory'];
} else {
$temp = $this->currentFileInfo['entryPath'];
}
if( !empty($temp) ){
$filePath = Less_Environment::normalizePath(rtrim($temp,'/').'/'.$filePath);
}
}
// detect the mimetype if not given
if( $args < 2 ){
/* incomplete
$mime = require('mime');
mimetype = mime.lookup(path);
// use base 64 unless it's an ASCII or UTF-8 format
var charset = mime.charsets.lookup(mimetype);
useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
if (useBase64) mimetype += ';base64';
*/
$mimetype = Less_Mime::lookup($filePath);
$charset = Less_Mime::charsets_lookup($mimetype);
$useBase64 = !in_array($charset,array('US-ASCII', 'UTF-8'));
if( $useBase64 ){ $mimetype .= ';base64'; }
}else{
$useBase64 = preg_match('/;base64$/',$mimetype);
}
if( file_exists($filePath) ){
$buf = @file_get_contents($filePath);
}else{
$buf = false;
}
// IE8 cannot handle a data-uri larger than 32KB. If this is exceeded
// and the --ieCompat flag is enabled, return a normal url() instead.
$DATA_URI_MAX_KB = 32;
$fileSizeInKB = round( strlen($buf) / 1024 );
if( $fileSizeInKB >= $DATA_URI_MAX_KB ){
$url = new Less_Tree_Url( ($filePathNode ? $filePathNode : $mimetypeNode), $this->currentFileInfo);
return $url->compile($this);
}
if( $buf ){
$buf = $useBase64 ? base64_encode($buf) : rawurlencode($buf);
$filePath = '"data:' . $mimetype . ',' . $buf . '"';
}
return new Less_Tree_Url( new Less_Tree_Anonymous($filePath) );
}
//svg-gradient
public function svggradient( $direction ){
$throw_message = 'svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position]';
$arguments = func_get_args();
if( count($arguments) < 3 ){
throw new Less_Exception_Compiler( $throw_message );
}
$stops = array_slice($arguments,1);
$gradientType = 'linear';
$rectangleDimension = 'x="0" y="0" width="1" height="1"';
$useBase64 = true;
$directionValue = $direction->toCSS();
switch( $directionValue ){
case "to bottom":
$gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
break;
case "to right":
$gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
break;
case "to bottom right":
$gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
break;
case "to top right":
$gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
break;
case "ellipse":
case "ellipse at center":
$gradientType = "radial";
$gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
$rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
break;
default:
throw new Less_Exception_Compiler( "svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'" );
}
$returner = '<?xml version="1.0" ?>' .
'<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">' .
'<' . $gradientType . 'Gradient id="gradient" gradientUnits="userSpaceOnUse" ' . $gradientDirectionSvg . '>';
for( $i = 0; $i < count($stops); $i++ ){
if( is_object($stops[$i]) && property_exists($stops[$i],'value') ){
$color = $stops[$i]->value[0];
$position = $stops[$i]->value[1];
}else{
$color = $stops[$i];
$position = null;
}
if( !($color instanceof Less_Tree_Color) || (!(($i === 0 || $i+1 === count($stops)) && $position === null) && !($position instanceof Less_Tree_Dimension)) ){
throw new Less_Exception_Compiler( $throw_message );
}
if( $position ){
$positionValue = $position->toCSS();
}elseif( $i === 0 ){
$positionValue = '0%';
}else{
$positionValue = '100%';
}
$alpha = $color->alpha;
$returner .= '<stop offset="' . $positionValue . '" stop-color="' . $color->toRGB() . '"' . ($alpha < 1 ? ' stop-opacity="' . $alpha . '"' : '') . '/>';
}
$returner .= '</' . $gradientType . 'Gradient><rect ' . $rectangleDimension . ' fill="url(#gradient)" /></svg>';
if( $useBase64 ){
$returner = "'data:image/svg+xml;base64,".base64_encode($returner)."'";
}else{
$returner = "'data:image/svg+xml,".$returner."'";
}
return new Less_Tree_URL( new Less_Tree_Anonymous( $returner ) );
}
/**
* Php version of javascript's `encodeURIComponent` function
*
* @param string $string The string to encode
* @return string The encoded string
*/
public static function encodeURIComponent($string){
$revert = array('%21' => '!', '%2A' => '*', '%27' => "'", '%28' => '(', '%29' => ')');
return strtr(rawurlencode($string), $revert);
}
// Color Blending
// ref: http://www.w3.org/TR/compositing-1
public function colorBlend( $mode, $color1, $color2 ){
$ab = $color1->alpha; // backdrop
$as = $color2->alpha; // source
$r = array(); // result
$ar = $as + $ab * (1 - $as);
for( $i = 0; $i < 3; $i++ ){
$cb = $color1->rgb[$i] / 255;
$cs = $color2->rgb[$i] / 255;
$cr = call_user_func( $mode, $cb, $cs );
if( $ar ){
$cr = ($as * $cs + $ab * ($cb - $as * ($cb + $cs - $cr))) / $ar;
}
$r[$i] = $cr * 255;
}
return new Less_Tree_Color($r, $ar);
}
public function multiply($color1 = null, $color2 = null ){
if (!$color1 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to multiply must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$color2 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The second argument to multiply must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
return $this->colorBlend( array($this,'colorBlendMultiply'), $color1, $color2 );
}
private function colorBlendMultiply($cb, $cs){
return $cb * $cs;
}
public function screen($color1 = null, $color2 = null ){
if (!$color1 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to screen must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$color2 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The second argument to screen must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
return $this->colorBlend( array($this,'colorBlendScreen'), $color1, $color2 );
}
private function colorBlendScreen( $cb, $cs){
return $cb + $cs - $cb * $cs;
}
public function overlay($color1 = null, $color2 = null){
if (!$color1 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to overlay must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$color2 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The second argument to overlay must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
return $this->colorBlend( array($this,'colorBlendOverlay'), $color1, $color2 );
}
private function colorBlendOverlay($cb, $cs ){
$cb *= 2;
return ($cb <= 1)
? $this->colorBlendMultiply($cb, $cs)
: $this->colorBlendScreen($cb - 1, $cs);
}
public function softlight($color1 = null, $color2 = null){
if (!$color1 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to softlight must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$color2 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The second argument to softlight must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
return $this->colorBlend( array($this,'colorBlendSoftlight'), $color1, $color2 );
}
private function colorBlendSoftlight($cb, $cs ){
$d = 1;
$e = $cb;
if( $cs > 0.5 ){
$e = 1;
$d = ($cb > 0.25) ? sqrt($cb)
: ((16 * $cb - 12) * $cb + 4) * $cb;
}
return $cb - (1 - 2 * $cs) * $e * ($d - $cb);
}
public function hardlight($color1 = null, $color2 = null){
if (!$color1 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to hardlight must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$color2 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The second argument to hardlight must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
return $this->colorBlend( array($this,'colorBlendHardlight'), $color1, $color2 );
}
private function colorBlendHardlight( $cb, $cs ){
return $this->colorBlendOverlay($cs, $cb);
}
public function difference($color1 = null, $color2 = null) {
if (!$color1 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to difference must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$color2 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The second argument to difference must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
return $this->colorBlend( array($this,'colorBlendDifference'), $color1, $color2 );
}
private function colorBlendDifference( $cb, $cs ){
return abs($cb - $cs);
}
public function exclusion( $color1 = null, $color2 = null ){
if (!$color1 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to exclusion must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$color2 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The second argument to exclusion must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
return $this->colorBlend( array($this,'colorBlendExclusion'), $color1, $color2 );
}
private function colorBlendExclusion( $cb, $cs ){
return $cb + $cs - 2 * $cb * $cs;
}
public function average($color1 = null, $color2 = null){
if (!$color1 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to average must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$color2 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The second argument to average must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
return $this->colorBlend( array($this,'colorBlendAverage'), $color1, $color2 );
}
// non-w3c functions:
public function colorBlendAverage($cb, $cs ){
return ($cb + $cs) / 2;
}
public function negation($color1 = null, $color2 = null ){
if (!$color1 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The first argument to negation must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
if (!$color2 instanceof Less_Tree_Color) {
throw new Less_Exception_Compiler('The second argument to negation must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
}
return $this->colorBlend( array($this,'colorBlendNegation'), $color1, $color2 );
}
public function colorBlendNegation($cb, $cs){
return 1 - abs($cb + $cs - 1);
}
// ~ End of Color Blending
}
/**
* Mime lookup
*
* @package Less
* @subpackage node
*/
class Less_Mime{
// this map is intentionally incomplete
// if you want more, install 'mime' dep
static $_types = array(
'.htm' => 'text/html',
'.html'=> 'text/html',
'.gif' => 'image/gif',
'.jpg' => 'image/jpeg',
'.jpeg'=> 'image/jpeg',
'.png' => 'image/png',
'.ttf' => 'application/x-font-ttf',
'.otf' => 'application/x-font-otf',
'.eot' => 'application/vnd.ms-fontobject',
'.woff' => 'application/x-font-woff',
'.svg' => 'image/svg+xml',
);
public static function lookup( $filepath ){
$parts = explode('.',$filepath);
$ext = '.'.strtolower(array_pop($parts));
if( !isset(self::$_types[$ext]) ){
return null;
}
return self::$_types[$ext];
}
public static function charsets_lookup( $type = null ){
// assumes all text types are UTF-8
return $type && preg_match('/^text\//',$type) ? 'UTF-8' : '';
}
}
/**
* Tree
*
* @package Less
* @subpackage tree
*/
class Less_Tree{
public $cache_string;
public function toCSS(){
$output = new Less_Output();
$this->genCSS($output);
return $output->toString();
}
/**
* Generate CSS by adding it to the output object
*
* @param Less_Output $output The output
* @return void
*/
public function genCSS($output){}
/**
* @param Less_Tree_Ruleset[] $rules
*/
public static function outputRuleset( $output, $rules ){
$ruleCnt = count($rules);
Less_Environment::$tabLevel++;
// Compressed
if( Less_Parser::$options['compress'] ){
$output->add('{');
for( $i = 0; $i < $ruleCnt; $i++ ){
$rules[$i]->genCSS( $output );
}
$output->add( '}' );
Less_Environment::$tabLevel--;
return;
}
// Non-compressed
$tabSetStr = "\n".str_repeat( ' ' , Less_Environment::$tabLevel-1 );
$tabRuleStr = $tabSetStr.' ';
$output->add( " {" );
for($i = 0; $i < $ruleCnt; $i++ ){
$output->add( $tabRuleStr );
$rules[$i]->genCSS( $output );
}
Less_Environment::$tabLevel--;
$output->add( $tabSetStr.'}' );
}
public function accept($visitor){}
public static function ReferencedArray($rules){
foreach($rules as $rule){
if( method_exists($rule, 'markReferenced') ){
$rule->markReferenced();
}
}
}
/**
* Requires php 5.3+
*/
public static function __set_state($args){
$class = get_called_class();
$obj = new $class(null,null,null,null);
foreach($args as $key => $val){
$obj->$key = $val;
}
return $obj;
}
}
/**
* Parser output
*
* @package Less
* @subpackage output
*/
class Less_Output{
/**
* Output holder
*
* @var string
*/
protected $strs = array();
/**
* Adds a chunk to the stack
*
* @param string $chunk The chunk to output
* @param Less_FileInfo $fileInfo The file information
* @param integer $index The index
* @param mixed $mapLines
*/
public function add($chunk, $fileInfo = null, $index = 0, $mapLines = null){
$this->strs[] = $chunk;
}
/**
* Is the output empty?
*
* @return boolean
*/
public function isEmpty(){
return count($this->strs) === 0;
}
/**
* Converts the output to string
*
* @return string
*/
public function toString(){
return implode('',$this->strs);
}
}
/**
* Visitor
*
* @package Less
* @subpackage visitor
*/
class Less_Visitor{
protected $methods = array();
protected $_visitFnCache = array();
public function __construct(){
$this->_visitFnCache = get_class_methods(get_class($this));
$this->_visitFnCache = array_flip($this->_visitFnCache);
}
public function visitObj( $node ){
$funcName = 'visit'.$node->type;
if( isset($this->_visitFnCache[$funcName]) ){
$visitDeeper = true;
$this->$funcName( $node, $visitDeeper );
if( $visitDeeper ){
$node->accept($this);
}
$funcName = $funcName . "Out";
if( isset($this->_visitFnCache[$funcName]) ){
$this->$funcName( $node );
}
}else{
$node->accept($this);
}
return $node;
}
public function visitArray( $nodes ){
array_map( array($this,'visitObj'), $nodes);
return $nodes;
}
}
/**
* Replacing Visitor
*
* @package Less
* @subpackage visitor
*/
class Less_VisitorReplacing extends Less_Visitor{
public function visitObj( $node ){
$funcName = 'visit'.$node->type;
if( isset($this->_visitFnCache[$funcName]) ){
$visitDeeper = true;
$node = $this->$funcName( $node, $visitDeeper );
if( $node ){
if( $visitDeeper && is_object($node) ){
$node->accept($this);
}
$funcName = $funcName . "Out";
if( isset($this->_visitFnCache[$funcName]) ){
$this->$funcName( $node );
}
}
}else{
$node->accept($this);
}
return $node;
}
public function visitArray( $nodes ){
$newNodes = array();
foreach($nodes as $node){
$evald = $this->visitObj($node);
if( $evald ){
if( is_array($evald) ){
self::flatten($evald,$newNodes);
}else{
$newNodes[] = $evald;
}
}
}
return $newNodes;
}
public function flatten( $arr, &$out ){
foreach($arr as $item){
if( !is_array($item) ){
$out[] = $item;
continue;
}
foreach($item as $nestedItem){
if( is_array($nestedItem) ){
self::flatten( $nestedItem, $out);
}else{
$out[] = $nestedItem;
}
}
}
return $out;
}
}
/**
* Configurable
*
* @package Less
* @subpackage Core
*/
abstract class Less_Configurable {
/**
* Array of options
*
* @var array
*/
protected $options = array();
/**
* Array of default options
*
* @var array
*/
protected $defaultOptions = array();
/**
* Set options
*
* If $options is an object it will be converted into an array by called
* it's toArray method.
*
* @throws Exception
* @param array|object $options
*
*/
public function setOptions($options){
$options = array_intersect_key($options,$this->defaultOptions);
$this->options = array_merge($this->defaultOptions, $this->options, $options);
}
/**
* Get an option value by name
*
* If the option is empty or not set a NULL value will be returned.
*
* @param string $name
* @param mixed $default Default value if confiuration of $name is not present
* @return mixed
*/
public function getOption($name, $default = null){
if(isset($this->options[$name])){
return $this->options[$name];
}
return $default;
}
/**
* Set an option
*
* @param string $name
* @param mixed $value
*/
public function setOption($name, $value){
$this->options[$name] = $value;
}
}
/**
* Alpha
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Alpha extends Less_Tree{
public $value;
public $type = 'Alpha';
public function __construct($val){
$this->value = $val;
}
//function accept( $visitor ){
// $this->value = $visitor->visit( $this->value );
//}
public function compile($env){
if( is_object($this->value) ){
$this->value = $this->value->compile($env);
}
return $this;
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
$output->add( "alpha(opacity=" );
if( is_string($this->value) ){
$output->add( $this->value );
}else{
$this->value->genCSS( $output);
}
$output->add( ')' );
}
public function toCSS(){
return "alpha(opacity=" . (is_string($this->value) ? $this->value : $this->value->toCSS()) . ")";
}
}
/**
* Anonymous
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Anonymous extends Less_Tree{
public $value;
public $quote;
public $index;
public $mapLines;
public $currentFileInfo;
public $type = 'Anonymous';
/**
* @param integer $index
* @param boolean $mapLines
*/
public function __construct($value, $index = null, $currentFileInfo = null, $mapLines = null ){
$this->value = $value;
$this->index = $index;
$this->mapLines = $mapLines;
$this->currentFileInfo = $currentFileInfo;
}
public function compile(){
return new Less_Tree_Anonymous($this->value, $this->index, $this->currentFileInfo, $this->mapLines);
}
public function compare($x){
if( !is_object($x) ){
return -1;
}
$left = $this->toCSS();
$right = $x->toCSS();
if( $left === $right ){
return 0;
}
return $left < $right ? -1 : 1;
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
$output->add( $this->value, $this->currentFileInfo, $this->index, $this->mapLines );
}
public function toCSS(){
return $this->value;
}
}
/**
* Assignment
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Assignment extends Less_Tree{
public $key;
public $value;
public $type = 'Assignment';
public function __construct($key, $val) {
$this->key = $key;
$this->value = $val;
}
public function accept( $visitor ){
$this->value = $visitor->visitObj( $this->value );
}
public function compile($env) {
return new Less_Tree_Assignment( $this->key, $this->value->compile($env));
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
$output->add( $this->key . '=' );
$this->value->genCSS( $output );
}
public function toCss(){
return $this->key . '=' . $this->value->toCSS();
}
}
/**
* Attribute
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Attribute extends Less_Tree{
public $key;
public $op;
public $value;
public $type = 'Attribute';
public function __construct($key, $op, $value){
$this->key = $key;
$this->op = $op;
$this->value = $value;
}
public function compile($env){
$key_obj = is_object($this->key);
$val_obj = is_object($this->value);
if( !$key_obj && !$val_obj ){
return $this;
}
return new Less_Tree_Attribute(
$key_obj ? $this->key->compile($env) : $this->key ,
$this->op,
$val_obj ? $this->value->compile($env) : $this->value);
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
$output->add( $this->toCSS() );
}
public function toCSS(){
$value = $this->key;
if( $this->op ){
$value .= $this->op;
$value .= (is_object($this->value) ? $this->value->toCSS() : $this->value);
}
return '[' . $value . ']';
}
}
/**
* Call
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Call extends Less_Tree{
public $value;
protected $name;
protected $args;
protected $index;
protected $currentFileInfo;
public $type = 'Call';
public function __construct($name, $args, $index, $currentFileInfo = null ){
$this->name = $name;
$this->args = $args;
$this->index = $index;
$this->currentFileInfo = $currentFileInfo;
}
public function accept( $visitor ){
$this->args = $visitor->visitArray( $this->args );
}
//
// When evaluating a function call,
// we either find the function in `tree.functions` [1],
// in which case we call it, passing the evaluated arguments,
// or we simply print it out as it appeared originally [2].
//
// The *functions.js* file contains the built-in functions.
//
// The reason why we evaluate the arguments, is in the case where
// we try to pass a variable to a function, like: `saturate(@color)`.
// The function should receive the value, not the variable.
//
public function compile($env=null){
$args = array();
foreach($this->args as $a){
$args[] = $a->compile($env);
}
$nameLC = strtolower($this->name);
switch($nameLC){
case '%':
$nameLC = '_percent';
break;
case 'get-unit':
$nameLC = 'getunit';
break;
case 'data-uri':
$nameLC = 'datauri';
break;
case 'svg-gradient':
$nameLC = 'svggradient';
break;
}
$result = null;
if( $nameLC === 'default' ){
$result = Less_Tree_DefaultFunc::compile();
}else{
if( method_exists('Less_Functions',$nameLC) ){ // 1.
try {
$func = new Less_Functions($env, $this->currentFileInfo);
$result = call_user_func_array( array($func,$nameLC),$args);
} catch (Exception $e) {
throw new Less_Exception_Compiler('error evaluating function `' . $this->name . '` '.$e->getMessage().' index: '. $this->index);
}
} elseif( isset( $env->functions[$nameLC] ) && is_callable( $env->functions[$nameLC] ) ) {
try {
$result = call_user_func_array( $env->functions[$nameLC], $args );
} catch (Exception $e) {
throw new Less_Exception_Compiler('error evaluating function `' . $this->name . '` '.$e->getMessage().' index: '. $this->index);
}
}
}
if( $result !== null ){
return $result;
}
return new Less_Tree_Call( $this->name, $args, $this->index, $this->currentFileInfo );
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
$output->add( $this->name . '(', $this->currentFileInfo, $this->index );
$args_len = count($this->args);
for($i = 0; $i < $args_len; $i++ ){
$this->args[$i]->genCSS( $output );
if( $i + 1 < $args_len ){
$output->add( ', ' );
}
}
$output->add( ')' );
}
//public function toCSS(){
// return $this->compile()->toCSS();
//}
}
/**
* Color
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Color extends Less_Tree{
public $rgb;
public $alpha;
public $isTransparentKeyword;
public $type = 'Color';
public function __construct($rgb, $a = 1, $isTransparentKeyword = null ){
if( $isTransparentKeyword ){
$this->rgb = $rgb;
$this->alpha = $a;
$this->isTransparentKeyword = true;
return;
}
$this->rgb = array();
if( is_array($rgb) ){
$this->rgb = $rgb;
}else if( strlen($rgb) == 6 ){
foreach(str_split($rgb, 2) as $c){
$this->rgb[] = hexdec($c);
}
}else{
foreach(str_split($rgb, 1) as $c){
$this->rgb[] = hexdec($c.$c);
}
}
$this->alpha = is_numeric($a) ? $a : 1;
}
public function compile(){
return $this;
}
public function luma(){
$r = $this->rgb[0] / 255;
$g = $this->rgb[1] / 255;
$b = $this->rgb[2] / 255;
$r = ($r <= 0.03928) ? $r / 12.92 : pow((($r + 0.055) / 1.055), 2.4);
$g = ($g <= 0.03928) ? $g / 12.92 : pow((($g + 0.055) / 1.055), 2.4);
$b = ($b <= 0.03928) ? $b / 12.92 : pow((($b + 0.055) / 1.055), 2.4);
return 0.2126 * $r + 0.7152 * $g + 0.0722 * $b;
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
$output->add( $this->toCSS() );
}
public function toCSS( $doNotCompress = false ){
$compress = Less_Parser::$options['compress'] && !$doNotCompress;
$alpha = Less_Functions::fround( $this->alpha );
//
// If we have some transparency, the only way to represent it
// is via `rgba`. Otherwise, we use the hex representation,
// which has better compatibility with older browsers.
// Values are capped between `0` and `255`, rounded and zero-padded.
//
if( $alpha < 1 ){
if( ( $alpha === 0 || $alpha === 0.0 ) && isset($this->isTransparentKeyword) && $this->isTransparentKeyword ){
return 'transparent';
}
$values = array();
foreach($this->rgb as $c){
$values[] = Less_Functions::clamp( round($c), 255);
}
$values[] = $alpha;
$glue = ($compress ? ',' : ', ');
return "rgba(" . implode($glue, $values) . ")";
}else{
$color = $this->toRGB();
if( $compress ){
// Convert color to short format
if( $color[1] === $color[2] && $color[3] === $color[4] && $color[5] === $color[6]) {
$color = '#'.$color[1] . $color[3] . $color[5];
}
}
return $color;
}
}
//
// Operations have to be done per-channel, if not,
// channels will spill onto each other. Once we have
// our result, in the form of an integer triplet,
// we create a new Color node to hold the result.
//
/**
* @param string $op
*/
public function operate( $op, $other) {
$rgb = array();
$alpha = $this->alpha * (1 - $other->alpha) + $other->alpha;
for ($c = 0; $c < 3; $c++) {
$rgb[$c] = Less_Functions::operate( $op, $this->rgb[$c], $other->rgb[$c]);
}
return new Less_Tree_Color($rgb, $alpha);
}
public function toRGB(){
return $this->toHex($this->rgb);
}
public function toHSL(){
$r = $this->rgb[0] / 255;
$g = $this->rgb[1] / 255;
$b = $this->rgb[2] / 255;
$a = $this->alpha;
$max = max($r, $g, $b);
$min = min($r, $g, $b);
$l = ($max + $min) / 2;
$d = $max - $min;
$h = $s = 0;
if( $max !== $min ){
$s = $l > 0.5 ? $d / (2 - $max - $min) : $d / ($max + $min);
switch ($max) {
case $r: $h = ($g - $b) / $d + ($g < $b ? 6 : 0); break;
case $g: $h = ($b - $r) / $d + 2; break;
case $b: $h = ($r - $g) / $d + 4; break;
}
$h /= 6;
}
return array('h' => $h * 360, 's' => $s, 'l' => $l, 'a' => $a );
}
//Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
public function toHSV() {
$r = $this->rgb[0] / 255;
$g = $this->rgb[1] / 255;
$b = $this->rgb[2] / 255;
$a = $this->alpha;
$max = max($r, $g, $b);
$min = min($r, $g, $b);
$v = $max;
$d = $max - $min;
if ($max === 0) {
$s = 0;
} else {
$s = $d / $max;
}
$h = 0;
if( $max !== $min ){
switch($max){
case $r: $h = ($g - $b) / $d + ($g < $b ? 6 : 0); break;
case $g: $h = ($b - $r) / $d + 2; break;
case $b: $h = ($r - $g) / $d + 4; break;
}
$h /= 6;
}
return array('h'=> $h * 360, 's'=> $s, 'v'=> $v, 'a' => $a );
}
public function toARGB(){
$argb = array_merge( (array) Less_Parser::round($this->alpha * 255), $this->rgb);
return $this->toHex( $argb );
}
public function compare($x){
if( !property_exists( $x, 'rgb' ) ){
return -1;
}
return ($x->rgb[0] === $this->rgb[0] &&
$x->rgb[1] === $this->rgb[1] &&
$x->rgb[2] === $this->rgb[2] &&
$x->alpha === $this->alpha) ? 0 : -1;
}
public function toHex( $v ){
$ret = '#';
foreach($v as $c){
$c = Less_Functions::clamp( Less_Parser::round($c), 255);
if( $c < 16 ){
$ret .= '0';
}
$ret .= dechex($c);
}
return $ret;
}
/**
* @param string $keyword
*/
public static function fromKeyword( $keyword ){
$keyword = strtolower($keyword);
if( Less_Colors::hasOwnProperty($keyword) ){
// detect named color
return new Less_Tree_Color(substr(Less_Colors::color($keyword), 1));
}
if( $keyword === 'transparent' ){
return new Less_Tree_Color( array(0, 0, 0), 0, true);
}
}
}
/**
* Comment
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Comment extends Less_Tree{
public $value;
public $silent;
public $isReferenced;
public $currentFileInfo;
public $type = 'Comment';
public function __construct($value, $silent, $index = null, $currentFileInfo = null ){
$this->value = $value;
$this->silent = !! $silent;
$this->currentFileInfo = $currentFileInfo;
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
//if( $this->debugInfo ){
//$output->add( tree.debugInfo($env, $this), $this->currentFileInfo, $this->index);
//}
$output->add( trim($this->value) );//TODO shouldn't need to trim, we shouldn't grab the \n
}
public function toCSS(){
return Less_Parser::$options['compress'] ? '' : $this->value;
}
public function isSilent(){
$isReference = ($this->currentFileInfo && isset($this->currentFileInfo['reference']) && (!isset($this->isReferenced) || !$this->isReferenced) );
$isCompressed = Less_Parser::$options['compress'] && !preg_match('/^\/\*!/', $this->value);
return $this->silent || $isReference || $isCompressed;
}
public function compile(){
return $this;
}
public function markReferenced(){
$this->isReferenced = true;
}
}
/**
* Condition
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Condition extends Less_Tree{
public $op;
public $lvalue;
public $rvalue;
public $index;
public $negate;
public $type = 'Condition';
public function __construct($op, $l, $r, $i = 0, $negate = false) {
$this->op = trim($op);
$this->lvalue = $l;
$this->rvalue = $r;
$this->index = $i;
$this->negate = $negate;
}
public function accept($visitor){
$this->lvalue = $visitor->visitObj( $this->lvalue );
$this->rvalue = $visitor->visitObj( $this->rvalue );
}
public function compile($env) {
$a = $this->lvalue->compile($env);
$b = $this->rvalue->compile($env);
switch( $this->op ){
case 'and':
$result = $a && $b;
break;
case 'or':
$result = $a || $b;
break;
default:
if( Less_Parser::is_method($a, 'compare') ){
$result = $a->compare($b);
}elseif( Less_Parser::is_method($b, 'compare') ){
$result = $b->compare($a);
}else{
throw new Less_Exception_Compiler('Unable to perform comparison', null, $this->index);
}
switch ($result) {
case -1:
$result = $this->op === '<' || $this->op === '=<' || $this->op === '<=';
break;
case 0:
$result = $this->op === '=' || $this->op === '>=' || $this->op === '=<' || $this->op === '<=';
break;
case 1:
$result = $this->op === '>' || $this->op === '>=';
break;
}
break;
}
return $this->negate ? !$result : $result;
}
}
/**
* DefaultFunc
*
* @package Less
* @subpackage tree
*/
class Less_Tree_DefaultFunc{
static $error_;
static $value_;
public static function compile(){
if( self::$error_ ){
throw new Exception(self::$error_);
}
if( self::$value_ !== null ){
return self::$value_ ? new Less_Tree_Keyword('true') : new Less_Tree_Keyword('false');
}
}
public static function value( $v ){
self::$value_ = $v;
}
public static function error( $e ){
self::$error_ = $e;
}
public static function reset(){
self::$value_ = self::$error_ = null;
}
}
/**
* DetachedRuleset
*
* @package Less
* @subpackage tree
*/
class Less_Tree_DetachedRuleset extends Less_Tree{
public $ruleset;
public $frames;
public $type = 'DetachedRuleset';
public function __construct( $ruleset, $frames = null ){
$this->ruleset = $ruleset;
$this->frames = $frames;
}
public function accept($visitor) {
$this->ruleset = $visitor->visitObj($this->ruleset);
}
public function compile($env){
if( $this->frames ){
$frames = $this->frames;
}else{
$frames = $env->frames;
}
return new Less_Tree_DetachedRuleset($this->ruleset, $frames);
}
public function callEval($env) {
if( $this->frames ){
return $this->ruleset->compile( $env->copyEvalEnv( array_merge($this->frames,$env->frames) ) );
}
return $this->ruleset->compile( $env );
}
}
/**
* Dimension
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Dimension extends Less_Tree{
public $value;
public $unit;
public $type = 'Dimension';
public function __construct($value, $unit = null){
$this->value = floatval($value);
if( $unit && ($unit instanceof Less_Tree_Unit) ){
$this->unit = $unit;
}elseif( $unit ){
$this->unit = new Less_Tree_Unit( array($unit) );
}else{
$this->unit = new Less_Tree_Unit( );
}
}
public function accept( $visitor ){
$this->unit = $visitor->visitObj( $this->unit );
}
public function compile(){
return $this;
}
public function toColor() {
return new Less_Tree_Color(array($this->value, $this->value, $this->value));
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
if( Less_Parser::$options['strictUnits'] && !$this->unit->isSingular() ){
throw new Less_Exception_Compiler("Multiple units in dimension. Correct the units or use the unit function. Bad unit: ".$this->unit->toString());
}
$value = Less_Functions::fround( $this->value );
$strValue = (string)$value;
if( $value !== 0 && $value < 0.000001 && $value > -0.000001 ){
// would be output 1e-6 etc.
$strValue = number_format($strValue,10);
$strValue = preg_replace('/\.?0+$/','', $strValue);
}
if( Less_Parser::$options['compress'] ){
// Zero values doesn't need a unit
if( $value === 0 && $this->unit->isLength() ){
$output->add( $strValue );
return $strValue;
}
// Float values doesn't need a leading zero
if( $value > 0 && $value < 1 && $strValue[0] === '0' ){
$strValue = substr($strValue,1);
}
}
$output->add( $strValue );
$this->unit->genCSS( $output );
}
public function __toString(){
return $this->toCSS();
}
// In an operation between two Dimensions,
// we default to the first Dimension's unit,
// so `1px + 2em` will yield `3px`.
/**
* @param string $op
*/
public function operate( $op, $other){
$value = Less_Functions::operate( $op, $this->value, $other->value);
$unit = clone $this->unit;
if( $op === '+' || $op === '-' ){
if( !$unit->numerator && !$unit->denominator ){
$unit->numerator = $other->unit->numerator;
$unit->denominator = $other->unit->denominator;
}elseif( !$other->unit->numerator && !$other->unit->denominator ){
// do nothing
}else{
$other = $other->convertTo( $this->unit->usedUnits());
if( Less_Parser::$options['strictUnits'] && $other->unit->toString() !== $unit->toCSS() ){
throw new Less_Exception_Compiler("Incompatible units. Change the units or use the unit function. Bad units: '".$unit->toString() . "' and ".$other->unit->toString()+"'.");
}
$value = Less_Functions::operate( $op, $this->value, $other->value);
}
}elseif( $op === '*' ){
$unit->numerator = array_merge($unit->numerator, $other->unit->numerator);
$unit->denominator = array_merge($unit->denominator, $other->unit->denominator);
sort($unit->numerator);
sort($unit->denominator);
$unit->cancel();
}elseif( $op === '/' ){
$unit->numerator = array_merge($unit->numerator, $other->unit->denominator);
$unit->denominator = array_merge($unit->denominator, $other->unit->numerator);
sort($unit->numerator);
sort($unit->denominator);
$unit->cancel();
}
return new Less_Tree_Dimension( $value, $unit);
}
public function compare($other) {
if ($other instanceof Less_Tree_Dimension) {
if( $this->unit->isEmpty() || $other->unit->isEmpty() ){
$a = $this;
$b = $other;
} else {
$a = $this->unify();
$b = $other->unify();
if( $a->unit->compare($b->unit) !== 0 ){
return -1;
}
}
$aValue = $a->value;
$bValue = $b->value;
if ($bValue > $aValue) {
return -1;
} elseif ($bValue < $aValue) {
return 1;
} else {
return 0;
}
} else {
return -1;
}
}
public function unify() {
return $this->convertTo(array('length'=> 'px', 'duration'=> 's', 'angle' => 'rad' ));
}
public function convertTo($conversions) {
$value = $this->value;
$unit = clone $this->unit;
if( is_string($conversions) ){
$derivedConversions = array();
foreach( Less_Tree_UnitConversions::$groups as $i ){
if( isset(Less_Tree_UnitConversions::${$i}[$conversions]) ){
$derivedConversions = array( $i => $conversions);
}
}
$conversions = $derivedConversions;
}
foreach($conversions as $groupName => $targetUnit){
$group = Less_Tree_UnitConversions::${$groupName};
//numerator
foreach($unit->numerator as $i => $atomicUnit){
$atomicUnit = $unit->numerator[$i];
if( !isset($group[$atomicUnit]) ){
continue;
}
$value = $value * ($group[$atomicUnit] / $group[$targetUnit]);
$unit->numerator[$i] = $targetUnit;
}
//denominator
foreach($unit->denominator as $i => $atomicUnit){
$atomicUnit = $unit->denominator[$i];
if( !isset($group[$atomicUnit]) ){
continue;
}
$value = $value / ($group[$atomicUnit] / $group[$targetUnit]);
$unit->denominator[$i] = $targetUnit;
}
}
$unit->cancel();
return new Less_Tree_Dimension( $value, $unit);
}
}
/**
* Directive
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Directive extends Less_Tree{
public $name;
public $value;
public $rules;
public $index;
public $isReferenced;
public $currentFileInfo;
public $debugInfo;
public $type = 'Directive';
public function __construct($name, $value = null, $rules, $index = null, $currentFileInfo = null, $debugInfo = null ){
$this->name = $name;
$this->value = $value;
if( $rules ){
$this->rules = $rules;
$this->rules->allowImports = true;
}
$this->index = $index;
$this->currentFileInfo = $currentFileInfo;
$this->debugInfo = $debugInfo;
}
public function accept( $visitor ){
if( $this->rules ){
$this->rules = $visitor->visitObj( $this->rules );
}
if( $this->value ){
$this->value = $visitor->visitObj( $this->value );
}
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
$value = $this->value;
$rules = $this->rules;
$output->add( $this->name, $this->currentFileInfo, $this->index );
if( $this->value ){
$output->add(' ');
$this->value->genCSS($output);
}
if( $this->rules ){
Less_Tree::outputRuleset( $output, array($this->rules));
} else {
$output->add(';');
}
}
public function compile($env){
$value = $this->value;
$rules = $this->rules;
if( $value ){
$value = $value->compile($env);
}
if( $rules ){
$rules = $rules->compile($env);
$rules->root = true;
}
return new Less_Tree_Directive( $this->name, $value, $rules, $this->index, $this->currentFileInfo, $this->debugInfo );
}
public function variable($name){
if( $this->rules ){
return $this->rules->variable($name);
}
}
public function find($selector){
if( $this->rules ){
return $this->rules->find($selector, $this);
}
}
//rulesets: function () { if (this.rules) return tree.Ruleset.prototype.rulesets.apply(this.rules); },
public function markReferenced(){
$this->isReferenced = true;
if( $this->rules ){
Less_Tree::ReferencedArray($this->rules->rules);
}
}
}
/**
* Element
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Element extends Less_Tree{
public $combinator = '';
public $value = '';
public $index;
public $currentFileInfo;
public $type = 'Element';
public $value_is_object = false;
public function __construct($combinator, $value, $index = null, $currentFileInfo = null ){
$this->value = $value;
$this->value_is_object = is_object($value);
if( $combinator ){
$this->combinator = $combinator;
}
$this->index = $index;
$this->currentFileInfo = $currentFileInfo;
}
public function accept( $visitor ){
if( $this->value_is_object ){ //object or string
$this->value = $visitor->visitObj( $this->value );
}
}
public function compile($env){
if( Less_Environment::$mixin_stack ){
return new Less_Tree_Element($this->combinator, ($this->value_is_object ? $this->value->compile($env) : $this->value), $this->index, $this->currentFileInfo );
}
if( $this->value_is_object ){
$this->value = $this->value->compile($env);
}
return $this;
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
$output->add( $this->toCSS(), $this->currentFileInfo, $this->index );
}
public function toCSS(){
if( $this->value_is_object ){
$value = $this->value->toCSS();
}else{
$value = $this->value;
}
if( $value === '' && $this->combinator && $this->combinator === '&' ){
return '';
}
return Less_Environment::$_outputMap[$this->combinator] . $value;
}
}
/**
* Expression
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Expression extends Less_Tree{
public $value = array();
public $parens = false;
public $parensInOp = false;
public $type = 'Expression';
public function __construct( $value, $parens = null ){
$this->value = $value;
$this->parens = $parens;
}
public function accept( $visitor ){
$this->value = $visitor->visitArray( $this->value );
}
public function compile($env) {
$doubleParen = false;
if( $this->parens && !$this->parensInOp ){
Less_Environment::$parensStack++;
}
$returnValue = null;
if( $this->value ){
$count = count($this->value);
if( $count > 1 ){
$ret = array();
foreach($this->value as $e){
$ret[] = $e->compile($env);
}
$returnValue = new Less_Tree_Expression($ret);
}else{
if( ($this->value[0] instanceof Less_Tree_Expression) && $this->value[0]->parens && !$this->value[0]->parensInOp ){
$doubleParen = true;
}
$returnValue = $this->value[0]->compile($env);
}
} else {
$returnValue = $this;
}
if( $this->parens ){
if( !$this->parensInOp ){
Less_Environment::$parensStack--;
}elseif( !Less_Environment::isMathOn() && !$doubleParen ){
$returnValue = new Less_Tree_Paren($returnValue);
}
}
return $returnValue;
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
$val_len = count($this->value);
for( $i = 0; $i < $val_len; $i++ ){
$this->value[$i]->genCSS( $output );
if( $i + 1 < $val_len ){
$output->add( ' ' );
}
}
}
public function throwAwayComments() {
if( is_array($this->value) ){
$new_value = array();
foreach($this->value as $v){
if( $v instanceof Less_Tree_Comment ){
continue;
}
$new_value[] = $v;
}
$this->value = $new_value;
}
}
}
/**
* Extend
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Extend extends Less_Tree{
public $selector;
public $option;
public $index;
public $selfSelectors = array();
public $allowBefore;
public $allowAfter;
public $firstExtendOnThisSelectorPath;
public $type = 'Extend';
public $ruleset;
public $object_id;
public $parent_ids = array();
/**
* @param integer $index
*/
public function __construct($selector, $option, $index){
static $i = 0;
$this->selector = $selector;
$this->option = $option;
$this->index = $index;
switch($option){
case "all":
$this->allowBefore = true;
$this->allowAfter = true;
break;
default:
$this->allowBefore = false;
$this->allowAfter = false;
break;
}
$this->object_id = $i++;
$this->parent_ids = array($this->object_id);
}
public function accept( $visitor ){
$this->selector = $visitor->visitObj( $this->selector );
}
public function compile( $env ){
Less_Parser::$has_extends = true;
$this->selector = $this->selector->compile($env);
return $this;
//return new Less_Tree_Extend( $this->selector->compile($env), $this->option, $this->index);
}
public function findSelfSelectors( $selectors ){
$selfElements = array();
for( $i = 0, $selectors_len = count($selectors); $i < $selectors_len; $i++ ){
$selectorElements = $selectors[$i]->elements;
// duplicate the logic in genCSS function inside the selector node.
// future TODO - move both logics into the selector joiner visitor
if( $i && $selectorElements && $selectorElements[0]->combinator === "") {
$selectorElements[0]->combinator = ' ';
}
$selfElements = array_merge( $selfElements, $selectors[$i]->elements );
}
$this->selfSelectors = array(new Less_Tree_Selector($selfElements));
}
}
/**
* CSS @import node
*
* The general strategy here is that we don't want to wait
* for the parsing to be completed, before we start importing
* the file. That's because in the context of a browser,
* most of the time will be spent waiting for the server to respond.
*
* On creation, we push the import path to our import queue, though
* `import,push`, we also pass it a callback, which it'll call once
* the file has been fetched, and parsed.
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Import extends Less_Tree{
public $options;
public $index;
public $path;
public $features;
public $currentFileInfo;
public $css;
public $skip;
public $root;
public $type = 'Import';
public function __construct($path, $features, $options, $index, $currentFileInfo = null ){
$this->options = $options;
$this->index = $index;
$this->path = $path;
$this->features = $features;
$this->currentFileInfo = $currentFileInfo;
if( is_array($options) ){
$this->options += array('inline'=>false);
if( isset($this->options['less']) || $this->options['inline'] ){
$this->css = !isset($this->options['less']) || !$this->options['less'] || $this->options['inline'];
} else {
$pathValue = $this->getPath();
if( $pathValue && preg_match('/css([\?;].*)?$/',$pathValue) ){
$this->css = true;
}
}
}
}
//
// The actual import node doesn't return anything, when converted to CSS.
// The reason is that it's used at the evaluation stage, so that the rules
// it imports can be treated like any other rules.
//
// In `eval`, we make sure all Import nodes get evaluated, recursively, so
// we end up with a flat structure, which can easily be imported in the parent
// ruleset.
//
public function accept($visitor){
if( $this->features ){
$this->features = $visitor->visitObj($this->features);
}
$this->path = $visitor->visitObj($this->path);
if( !$this->options['inline'] && $this->root ){
$this->root = $visitor->visit($this->root);
}
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
if( $this->css ){
$output->add( '@import ', $this->currentFileInfo, $this->index );
$this->path->genCSS( $output );
if( $this->features ){
$output->add( ' ' );
$this->features->genCSS( $output );
}
$output->add( ';' );
}
}
public function toCSS(){
$features = $this->features ? ' ' . $this->features->toCSS() : '';
if ($this->css) {
return "@import " . $this->path->toCSS() . $features . ";\n";
} else {
return "";
}
}
/**
* @return string
*/
public function getPath(){
if ($this->path instanceof Less_Tree_Quoted) {
$path = $this->path->value;
$path = ( isset($this->css) || preg_match('/(\.[a-z]*$)|([\?;].*)$/',$path)) ? $path : $path . '.less';
} else if ($this->path instanceof Less_Tree_URL) {
$path = $this->path->value->value;
}else{
return null;
}
//remove query string and fragment
return preg_replace('/[\?#][^\?]*$/','',$path);
}
public function compileForImport( $env ){
return new Less_Tree_Import( $this->path->compile($env), $this->features, $this->options, $this->index, $this->currentFileInfo);
}
public function compilePath($env) {
$path = $this->path->compile($env);
$rootpath = '';
if( $this->currentFileInfo && $this->currentFileInfo['rootpath'] ){
$rootpath = $this->currentFileInfo['rootpath'];
}
if( !($path instanceof Less_Tree_URL) ){
if( $rootpath ){
$pathValue = $path->value;
// Add the base path if the import is relative
if( $pathValue && Less_Environment::isPathRelative($pathValue) ){
$path->value = $this->currentFileInfo['uri_root'].$pathValue;
}
}
$path->value = Less_Environment::normalizePath($path->value);
}
return $path;
}
public function compile( $env ){
$evald = $this->compileForImport($env);
//get path & uri
$path_and_uri = null;
if( is_callable(Less_Parser::$options['import_callback']) ){
$path_and_uri = call_user_func(Less_Parser::$options['import_callback'],$evald);
}
if( !$path_and_uri ){
$path_and_uri = $evald->PathAndUri();
}
if( $path_and_uri ){
list($full_path, $uri) = $path_and_uri;
}else{
$full_path = $uri = $evald->getPath();
}
//import once
if( $evald->skip( $full_path, $env) ){
return array();
}
if( $this->options['inline'] ){
//todo needs to reference css file not import
//$contents = new Less_Tree_Anonymous($this->root, 0, array('filename'=>$this->importedFilename), true );
Less_Parser::AddParsedFile($full_path);
$contents = new Less_Tree_Anonymous( file_get_contents($full_path), 0, array(), true );
if( $this->features ){
return new Less_Tree_Media( array($contents), $this->features->value );
}
return array( $contents );
}
// css ?
if( $evald->css ){
$features = ( $evald->features ? $evald->features->compile($env) : null );
return new Less_Tree_Import( $this->compilePath( $env), $features, $this->options, $this->index);
}
return $this->ParseImport( $full_path, $uri, $env );
}
/**
* Using the import directories, get the full absolute path and uri of the import
*
* @param Less_Tree_Import $evald
*/
public function PathAndUri(){
$evald_path = $this->getPath();
if( $evald_path ){
$import_dirs = array();
if( Less_Environment::isPathRelative($evald_path) ){
//if the path is relative, the file should be in the current directory
$import_dirs[ $this->currentFileInfo['currentDirectory'] ] = $this->currentFileInfo['uri_root'];
}else{
//otherwise, the file should be relative to the server root
$import_dirs[ $this->currentFileInfo['entryPath'] ] = $this->currentFileInfo['entryUri'];
//if the user supplied entryPath isn't the actual root
$import_dirs[ $_SERVER['DOCUMENT_ROOT'] ] = '';
}
// always look in user supplied import directories
$import_dirs = array_merge( $import_dirs, Less_Parser::$options['import_dirs'] );
foreach( $import_dirs as $rootpath => $rooturi){
if( is_callable($rooturi) ){
list($path, $uri) = call_user_func($rooturi, $evald_path);
if( is_string($path) ){
$full_path = $path;
return array( $full_path, $uri );
}
}elseif( !empty($rootpath) ){
if( $rooturi ){
if( strpos($evald_path,$rooturi) === 0 ){
$evald_path = substr( $evald_path, strlen($rooturi) );
}
}
$path = rtrim($rootpath,'/\\').'/'.ltrim($evald_path,'/\\');
if( file_exists($path) ){
$full_path = Less_Environment::normalizePath($path);
$uri = Less_Environment::normalizePath(dirname($rooturi.$evald_path));
return array( $full_path, $uri );
} elseif( file_exists($path.'.less') ){
$full_path = Less_Environment::normalizePath($path.'.less');
$uri = Less_Environment::normalizePath(dirname($rooturi.$evald_path.'.less'));
return array( $full_path, $uri );
}
}
}
}
}
/**
* Parse the import url and return the rules
*
* @return Less_Tree_Media|array
*/
public function ParseImport( $full_path, $uri, $env ){
$import_env = clone $env;
if( (isset($this->options['reference']) && $this->options['reference']) || isset($this->currentFileInfo['reference']) ){
$import_env->currentFileInfo['reference'] = true;
}
if( (isset($this->options['multiple']) && $this->options['multiple']) ){
$import_env->importMultiple = true;
}
$parser = new Less_Parser($import_env);
$root = $parser->parseFile($full_path, $uri, true);
$ruleset = new Less_Tree_Ruleset(array(), $root->rules );
$ruleset->evalImports($import_env);
return $this->features ? new Less_Tree_Media($ruleset->rules, $this->features->value) : $ruleset->rules;
}
/**
* Should the import be skipped?
*
* @return boolean|null
*/
private function Skip($path, $env){
$path = Less_Parser::winPath(realpath($path));
if( $path && Less_Parser::FileParsed($path) ){
if( isset($this->currentFileInfo['reference']) ){
return true;
}
return !isset($this->options['multiple']) && !$env->importMultiple;
}
}
}
/**
* Javascript
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Javascript extends Less_Tree{
public $type = 'Javascript';
public $escaped;
public $expression;
public $index;
/**
* @param boolean $index
* @param boolean $escaped
*/
public function __construct($string, $index, $escaped){
$this->escaped = $escaped;
$this->expression = $string;
$this->index = $index;
}
public function compile(){
return new Less_Tree_Anonymous('/* Sorry, can not do JavaScript evaluation in PHP... :( */');
}
}
/**
* Keyword
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Keyword extends Less_Tree{
public $value;
public $type = 'Keyword';
/**
* @param string $value
*/
public function __construct($value){
$this->value = $value;
}
public function compile(){
return $this;
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
if( $this->value === '%') {
throw new Less_Exception_Compiler("Invalid % without number");
}
$output->add( $this->value );
}
public function compare($other) {
if ($other instanceof Less_Tree_Keyword) {
return $other->value === $this->value ? 0 : 1;
} else {
return -1;
}
}
}
/**
* Media
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Media extends Less_Tree{
public $features;
public $rules;
public $index;
public $currentFileInfo;
public $isReferenced;
public $type = 'Media';
public function __construct($value = array(), $features = array(), $index = null, $currentFileInfo = null ){
$this->index = $index;
$this->currentFileInfo = $currentFileInfo;
$selectors = $this->emptySelectors();
$this->features = new Less_Tree_Value($features);
$this->rules = array(new Less_Tree_Ruleset($selectors, $value));
$this->rules[0]->allowImports = true;
}
public function accept( $visitor ){
$this->features = $visitor->visitObj($this->features);
$this->rules = $visitor->visitArray($this->rules);
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
$output->add( '@media ', $this->currentFileInfo, $this->index );
$this->features->genCSS( $output );
Less_Tree::outputRuleset( $output, $this->rules);
}
public function compile($env) {
$media = new Less_Tree_Media(array(), array(), $this->index, $this->currentFileInfo );
$strictMathBypass = false;
if( Less_Parser::$options['strictMath'] === false) {
$strictMathBypass = true;
Less_Parser::$options['strictMath'] = true;
}
$media->features = $this->features->compile($env);
if( $strictMathBypass ){
Less_Parser::$options['strictMath'] = false;
}
$env->mediaPath[] = $media;
$env->mediaBlocks[] = $media;
array_unshift($env->frames, $this->rules[0]);
$media->rules = array($this->rules[0]->compile($env));
array_shift($env->frames);
array_pop($env->mediaPath);
return !$env->mediaPath ? $media->compileTop($env) : $media->compileNested($env);
}
public function variable($name) {
return $this->rules[0]->variable($name);
}
public function find($selector) {
return $this->rules[0]->find($selector, $this);
}
public function emptySelectors(){
$el = new Less_Tree_Element('','&', $this->index, $this->currentFileInfo );
$sels = array( new Less_Tree_Selector(array($el), array(), null, $this->index, $this->currentFileInfo) );
$sels[0]->mediaEmpty = true;
return $sels;
}
public function markReferenced(){
$this->rules[0]->markReferenced();
$this->isReferenced = true;
Less_Tree::ReferencedArray($this->rules[0]->rules);
}
// evaltop
public function compileTop($env) {
$result = $this;
if (count($env->mediaBlocks) > 1) {
$selectors = $this->emptySelectors();
$result = new Less_Tree_Ruleset($selectors, $env->mediaBlocks);
$result->multiMedia = true;
}
$env->mediaBlocks = array();
$env->mediaPath = array();
return $result;
}
public function compileNested($env) {
$path = array_merge($env->mediaPath, array($this));
// Extract the media-query conditions separated with `,` (OR).
foreach ($path as $key => $p) {
$value = $p->features instanceof Less_Tree_Value ? $p->features->value : $p->features;
$path[$key] = is_array($value) ? $value : array($value);
}
// Trace all permutations to generate the resulting media-query.
//
// (a, b and c) with nested (d, e) ->
// a and d
// a and e
// b and c and d
// b and c and e
$permuted = $this->permute($path);
$expressions = array();
foreach($permuted as $path){
for( $i=0, $len=count($path); $i < $len; $i++){
$path[$i] = Less_Parser::is_method($path[$i], 'toCSS') ? $path[$i] : new Less_Tree_Anonymous($path[$i]);
}
for( $i = count($path) - 1; $i > 0; $i-- ){
array_splice($path, $i, 0, array(new Less_Tree_Anonymous('and')));
}
$expressions[] = new Less_Tree_Expression($path);
}
$this->features = new Less_Tree_Value($expressions);
// Fake a tree-node that doesn't output anything.
return new Less_Tree_Ruleset(array(), array());
}
public function permute($arr) {
if (!$arr)
return array();
if (count($arr) == 1)
return $arr[0];
$result = array();
$rest = $this->permute(array_slice($arr, 1));
foreach ($rest as $r) {
foreach ($arr[0] as $a) {
$result[] = array_merge(
is_array($a) ? $a : array($a),
is_array($r) ? $r : array($r)
);
}
}
return $result;
}
public function bubbleSelectors($selectors) {
if( !$selectors) return;
$this->rules = array(new Less_Tree_Ruleset( $selectors, array($this->rules[0])));
}
}
/**
* A simple css name-value pair
* ex: width:100px;
*
* In bootstrap, there are about 600-1,000 simple name-value pairs (depending on how forgiving the match is) -vs- 6,020 dynamic rules (Less_Tree_Rule)
* Using the name-value object can speed up bootstrap compilation slightly, but it breaks color keyword interpretation: color:red -> color:#FF0000;
*
* @package Less
* @subpackage tree
*/
class Less_Tree_NameValue extends Less_Tree{
public $name;
public $value;
public $index;
public $currentFileInfo;
public $type = 'NameValue';
public function __construct($name, $value = null, $index = null, $currentFileInfo = null ){
$this->name = $name;
$this->value = $value;
$this->index = $index;
$this->currentFileInfo = $currentFileInfo;
}
public function genCSS( $output ){
$output->add(
$this->name
. Less_Environment::$_outputMap[': ']
. $this->value
. (((Less_Environment::$lastRule && Less_Parser::$options['compress'])) ? "" : ";")
, $this->currentFileInfo, $this->index);
}
public function compile ($env){
return $this;
}
}
/**
* Negative
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Negative extends Less_Tree{
public $value;
public $type = 'Negative';
public function __construct($node){
$this->value = $node;
}
//function accept($visitor) {
// $this->value = $visitor->visit($this->value);
//}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
$output->add( '-' );
$this->value->genCSS( $output );
}
public function compile($env) {
if( Less_Environment::isMathOn() ){
$ret = new Less_Tree_Operation('*', array( new Less_Tree_Dimension(-1), $this->value ) );
return $ret->compile($env);
}
return new Less_Tree_Negative( $this->value->compile($env) );
}
}
/**
* Operation
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Operation extends Less_Tree{
public $op;
public $operands;
public $isSpaced;
public $type = 'Operation';
/**
* @param string $op
*/
public function __construct($op, $operands, $isSpaced = false){
$this->op = trim($op);
$this->operands = $operands;
$this->isSpaced = $isSpaced;
}
public function accept($visitor) {
$this->operands = $visitor->visitArray($this->operands);
}
public function compile($env){
$a = $this->operands[0]->compile($env);
$b = $this->operands[1]->compile($env);
if( Less_Environment::isMathOn() ){
if( $a instanceof Less_Tree_Dimension && $b instanceof Less_Tree_Color ){
$a = $a->toColor();
}elseif( $b instanceof Less_Tree_Dimension && $a instanceof Less_Tree_Color ){
$b = $b->toColor();
}
if( !method_exists($a,'operate') ){
throw new Less_Exception_Compiler("Operation on an invalid type");
}
return $a->operate( $this->op, $b);
}
return new Less_Tree_Operation($this->op, array($a, $b), $this->isSpaced );
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
$this->operands[0]->genCSS( $output );
if( $this->isSpaced ){
$output->add( " " );
}
$output->add( $this->op );
if( $this->isSpaced ){
$output->add( ' ' );
}
$this->operands[1]->genCSS( $output );
}
}
/**
* Paren
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Paren extends Less_Tree{
public $value;
public $type = 'Paren';
public function __construct($value) {
$this->value = $value;
}
public function accept($visitor){
$this->value = $visitor->visitObj($this->value);
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
$output->add( '(' );
$this->value->genCSS( $output );
$output->add( ')' );
}
public function compile($env) {
return new Less_Tree_Paren($this->value->compile($env));
}
}
/**
* Quoted
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Quoted extends Less_Tree{
public $escaped;
public $value;
public $quote;
public $index;
public $currentFileInfo;
public $type = 'Quoted';
/**
* @param string $str
*/
public function __construct($str, $content = '', $escaped = false, $index = false, $currentFileInfo = null ){
$this->escaped = $escaped;
$this->value = $content;
if( $str ){
$this->quote = $str[0];
}
$this->index = $index;
$this->currentFileInfo = $currentFileInfo;
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
if( !$this->escaped ){
$output->add( $this->quote, $this->currentFileInfo, $this->index );
}
$output->add( $this->value );
if( !$this->escaped ){
$output->add( $this->quote );
}
}
public function compile($env){
$value = $this->value;
if( preg_match_all('/`([^`]+)`/', $this->value, $matches) ){
foreach($matches as $i => $match){
$js = new Less_Tree_JavaScript($matches[1], $this->index, true);
$js = $js->compile()->value;
$value = str_replace($matches[0][$i], $js, $value);
}
}
if( preg_match_all('/@\{([\w-]+)\}/',$value,$matches) ){
foreach($matches[1] as $i => $match){
$v = new Less_Tree_Variable('@' . $match, $this->index, $this->currentFileInfo );
$v = $v->compile($env);
$v = ($v instanceof Less_Tree_Quoted) ? $v->value : $v->toCSS();
$value = str_replace($matches[0][$i], $v, $value);
}
}
return new Less_Tree_Quoted($this->quote . $value . $this->quote, $value, $this->escaped, $this->index, $this->currentFileInfo);
}
public function compare($x) {
if( !Less_Parser::is_method($x, 'toCSS') ){
return -1;
}
$left = $this->toCSS();
$right = $x->toCSS();
if ($left === $right) {
return 0;
}
return $left < $right ? -1 : 1;
}
}
/**
* Rule
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Rule extends Less_Tree{
public $name;
public $value;
public $important;
public $merge;
public $index;
public $inline;
public $variable;
public $currentFileInfo;
public $type = 'Rule';
/**
* @param string $important
*/
public function __construct($name, $value = null, $important = null, $merge = null, $index = null, $currentFileInfo = null, $inline = false){
$this->name = $name;
$this->value = ($value instanceof Less_Tree_Value || $value instanceof Less_Tree_Ruleset) ? $value : new Less_Tree_Value(array($value));
$this->important = $important ? ' ' . trim($important) : '';
$this->merge = $merge;
$this->index = $index;
$this->currentFileInfo = $currentFileInfo;
$this->inline = $inline;
$this->variable = ( is_string($name) && $name[0] === '@');
}
public function accept($visitor) {
$this->value = $visitor->visitObj( $this->value );
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
$output->add( $this->name . Less_Environment::$_outputMap[': '], $this->currentFileInfo, $this->index);
try{
$this->value->genCSS( $output);
}catch( Less_Exception_Parser $e ){
$e->index = $this->index;
$e->currentFile = $this->currentFileInfo;
throw $e;
}
$output->add( $this->important . (($this->inline || (Less_Environment::$lastRule && Less_Parser::$options['compress'])) ? "" : ";"), $this->currentFileInfo, $this->index);
}
public function compile ($env){
$name = $this->name;
if( is_array($name) ){
// expand 'primitive' name directly to get
// things faster (~10% for benchmark.less):
if( count($name) === 1 && $name[0] instanceof Less_Tree_Keyword ){
$name = $name[0]->value;
}else{
$name = $this->CompileName($env,$name);
}
}
$strictMathBypass = Less_Parser::$options['strictMath'];
if( $name === "font" && !Less_Parser::$options['strictMath'] ){
Less_Parser::$options['strictMath'] = true;
}
try {
$evaldValue = $this->value->compile($env);
if( !$this->variable && $evaldValue->type === "DetachedRuleset") {
throw new Less_Exception_Compiler("Rulesets cannot be evaluated on a property.", null, $this->index, $this->currentFileInfo);
}
if( Less_Environment::$mixin_stack ){
$return = new Less_Tree_Rule($name, $evaldValue, $this->important, $this->merge, $this->index, $this->currentFileInfo, $this->inline);
}else{
$this->name = $name;
$this->value = $evaldValue;
$return = $this;
}
}catch( Less_Exception_Parser $e ){
if( !is_numeric($e->index) ){
$e->index = $this->index;
$e->currentFile = $this->currentFileInfo;
}
throw $e;
}
Less_Parser::$options['strictMath'] = $strictMathBypass;
return $return;
}
public function CompileName( $env, $name ){
$output = new Less_Output();
foreach($name as $n){
$n->compile($env)->genCSS($output);
}
return $output->toString();
}
public function makeImportant(){
return new Less_Tree_Rule($this->name, $this->value, '!important', $this->merge, $this->index, $this->currentFileInfo, $this->inline);
}
}
/**
* Ruleset
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Ruleset extends Less_Tree{
protected $lookups;
public $_variables;
public $_rulesets;
public $strictImports;
public $selectors;
public $rules;
public $root;
public $allowImports;
public $paths;
public $firstRoot;
public $type = 'Ruleset';
public $multiMedia;
public $allExtends;
public $ruleset_id;
public $originalRuleset;
public $first_oelements;
public function SetRulesetIndex(){
$this->ruleset_id = Less_Parser::$next_id++;
$this->originalRuleset = $this->ruleset_id;
if( $this->selectors ){
foreach($this->selectors as $sel){
if( $sel->_oelements ){
$this->first_oelements[$sel->_oelements[0]] = true;
}
}
}
}
public function __construct($selectors, $rules, $strictImports = null){
$this->selectors = $selectors;
$this->rules = $rules;
$this->lookups = array();
$this->strictImports = $strictImports;
$this->SetRulesetIndex();
}
public function accept( $visitor ){
if( $this->paths ){
$paths_len = count($this->paths);
for($i = 0,$paths_len; $i < $paths_len; $i++ ){
$this->paths[$i] = $visitor->visitArray($this->paths[$i]);
}
}elseif( $this->selectors ){
$this->selectors = $visitor->visitArray($this->selectors);
}
if( $this->rules ){
$this->rules = $visitor->visitArray($this->rules);
}
}
public function compile($env){
$ruleset = $this->PrepareRuleset($env);
// Store the frames around mixin definitions,
// so they can be evaluated like closures when the time comes.
$rsRuleCnt = count($ruleset->rules);
for( $i = 0; $i < $rsRuleCnt; $i++ ){
if( $ruleset->rules[$i] instanceof Less_Tree_Mixin_Definition || $ruleset->rules[$i] instanceof Less_Tree_DetachedRuleset ){
$ruleset->rules[$i] = $ruleset->rules[$i]->compile($env);
}
}
$mediaBlockCount = 0;
if( $env instanceof Less_Environment ){
$mediaBlockCount = count($env->mediaBlocks);
}
// Evaluate mixin calls.
$this->EvalMixinCalls( $ruleset, $env, $rsRuleCnt );
// Evaluate everything else
for( $i=0; $i<$rsRuleCnt; $i++ ){
if(! ($ruleset->rules[$i] instanceof Less_Tree_Mixin_Definition || $ruleset->rules[$i] instanceof Less_Tree_DetachedRuleset) ){
$ruleset->rules[$i] = $ruleset->rules[$i]->compile($env);
}
}
// Evaluate everything else
for( $i=0; $i<$rsRuleCnt; $i++ ){
$rule = $ruleset->rules[$i];
// for rulesets, check if it is a css guard and can be removed
if( $rule instanceof Less_Tree_Ruleset && $rule->selectors && count($rule->selectors) === 1 ){
// check if it can be folded in (e.g. & where)
if( $rule->selectors[0]->isJustParentSelector() ){
array_splice($ruleset->rules,$i--,1);
$rsRuleCnt--;
for($j = 0; $j < count($rule->rules); $j++ ){
$subRule = $rule->rules[$j];
if( !($subRule instanceof Less_Tree_Rule) || !$subRule->variable ){
array_splice($ruleset->rules, ++$i, 0, array($subRule));
$rsRuleCnt++;
}
}
}
}
}
// Pop the stack
$env->shiftFrame();
if ($mediaBlockCount) {
$len = count($env->mediaBlocks);
for($i = $mediaBlockCount; $i < $len; $i++ ){
$env->mediaBlocks[$i]->bubbleSelectors($ruleset->selectors);
}
}
return $ruleset;
}
/**
* Compile Less_Tree_Mixin_Call objects
*
* @param Less_Tree_Ruleset $ruleset
* @param integer $rsRuleCnt
*/
private function EvalMixinCalls( $ruleset, $env, &$rsRuleCnt ){
for($i=0; $i < $rsRuleCnt; $i++){
$rule = $ruleset->rules[$i];
if( $rule instanceof Less_Tree_Mixin_Call ){
$rule = $rule->compile($env);
$temp = array();
foreach($rule as $r){
if( ($r instanceof Less_Tree_Rule) && $r->variable ){
// do not pollute the scope if the variable is
// already there. consider returning false here
// but we need a way to "return" variable from mixins
if( !$ruleset->variable($r->name) ){
$temp[] = $r;
}
}else{
$temp[] = $r;
}
}
$temp_count = count($temp)-1;
array_splice($ruleset->rules, $i, 1, $temp);
$rsRuleCnt += $temp_count;
$i += $temp_count;
$ruleset->resetCache();
}elseif( $rule instanceof Less_Tree_RulesetCall ){
$rule = $rule->compile($env);
$rules = array();
foreach($rule->rules as $r){
if( ($r instanceof Less_Tree_Rule) && $r->variable ){
continue;
}
$rules[] = $r;
}
array_splice($ruleset->rules, $i, 1, $rules);
$temp_count = count($rules);
$rsRuleCnt += $temp_count - 1;
$i += $temp_count-1;
$ruleset->resetCache();
}
}
}
/**
* Compile the selectors and create a new ruleset object for the compile() method
*
*/
private function PrepareRuleset($env){
$hasOnePassingSelector = false;
$selectors = array();
if( $this->selectors ){
Less_Tree_DefaultFunc::error("it is currently only allowed in parametric mixin guards,");
foreach($this->selectors as $s){
$selector = $s->compile($env);
$selectors[] = $selector;
if( $selector->evaldCondition ){
$hasOnePassingSelector = true;
}
}
Less_Tree_DefaultFunc::reset();
} else {
$hasOnePassingSelector = true;
}
if( $this->rules && $hasOnePassingSelector ){
$rules = $this->rules;
}else{
$rules = array();
}
$ruleset = new Less_Tree_Ruleset($selectors, $rules, $this->strictImports);
$ruleset->originalRuleset = $this->ruleset_id;
$ruleset->root = $this->root;
$ruleset->firstRoot = $this->firstRoot;
$ruleset->allowImports = $this->allowImports;
// push the current ruleset to the frames stack
$env->unshiftFrame($ruleset);
// Evaluate imports
if( $ruleset->root || $ruleset->allowImports || !$ruleset->strictImports ){
$ruleset->evalImports($env);
}
return $ruleset;
}
function evalImports($env) {
$rules_len = count($this->rules);
for($i=0; $i < $rules_len; $i++){
$rule = $this->rules[$i];
if( $rule instanceof Less_Tree_Import ){
$rules = $rule->compile($env);
if( is_array($rules) ){
array_splice($this->rules, $i, 1, $rules);
$temp_count = count($rules)-1;
$i += $temp_count;
$rules_len += $temp_count;
}else{
array_splice($this->rules, $i, 1, array($rules));
}
$this->resetCache();
}
}
}
function makeImportant(){
$important_rules = array();
foreach($this->rules as $rule){
if( $rule instanceof Less_Tree_Rule || $rule instanceof Less_Tree_Ruleset ){
$important_rules[] = $rule->makeImportant();
}else{
$important_rules[] = $rule;
}
}
return new Less_Tree_Ruleset($this->selectors, $important_rules, $this->strictImports );
}
public function matchArgs($args){
return !$args;
}
// lets you call a css selector with a guard
public function matchCondition( $args, $env ){
$lastSelector = end($this->selectors);
if( !$lastSelector->evaldCondition ){
return false;
}
if( $lastSelector->condition && !$lastSelector->condition->compile( $env->copyEvalEnv( $env->frames ) ) ){
return false;
}
return true;
}
function resetCache(){
$this->_rulesets = null;
$this->_variables = null;
$this->lookups = array();
}
public function variables(){
$this->_variables = array();
foreach( $this->rules as $r){
if ($r instanceof Less_Tree_Rule && $r->variable === true) {
$this->_variables[$r->name] = $r;
}
}
}
public function variable($name){
if( is_null($this->_variables) ){
$this->variables();
}
return isset($this->_variables[$name]) ? $this->_variables[$name] : null;
}
public function find( $selector, $self = null ){
$key = implode(' ',$selector->_oelements);
if( !isset($this->lookups[$key]) ){
if( !$self ){
$self = $this->ruleset_id;
}
$this->lookups[$key] = array();
$first_oelement = $selector->_oelements[0];
foreach($this->rules as $rule){
if( $rule instanceof Less_Tree_Ruleset && $rule->ruleset_id != $self ){
if( isset($rule->first_oelements[$first_oelement]) ){
foreach( $rule->selectors as $ruleSelector ){
$match = $selector->match($ruleSelector);
if( $match ){
if( $selector->elements_len > $match ){
$this->lookups[$key] = array_merge($this->lookups[$key], $rule->find( new Less_Tree_Selector(array_slice($selector->elements, $match)), $self));
} else {
$this->lookups[$key][] = $rule;
}
break;
}
}
}
}
}
}
return $this->lookups[$key];
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
if( !$this->root ){
Less_Environment::$tabLevel++;
}
$tabRuleStr = $tabSetStr = '';
if( !Less_Parser::$options['compress'] ){
if( Less_Environment::$tabLevel ){
$tabRuleStr = "\n".str_repeat( ' ' , Less_Environment::$tabLevel );
$tabSetStr = "\n".str_repeat( ' ' , Less_Environment::$tabLevel-1 );
}else{
$tabSetStr = $tabRuleStr = "\n";
}
}
$ruleNodes = array();
$rulesetNodes = array();
foreach($this->rules as $rule){
$class = get_class($rule);
if( ($class === 'Less_Tree_Media') || ($class === 'Less_Tree_Directive') || ($this->root && $class === 'Less_Tree_Comment') || ($class === 'Less_Tree_Ruleset' && $rule->rules) ){
$rulesetNodes[] = $rule;
}else{
$ruleNodes[] = $rule;
}
}
// If this is the root node, we don't render
// a selector, or {}.
if( !$this->root ){
/*
debugInfo = tree.debugInfo(env, this, tabSetStr);
if (debugInfo) {
output.add(debugInfo);
output.add(tabSetStr);
}
*/
$paths_len = count($this->paths);
for( $i = 0; $i < $paths_len; $i++ ){
$path = $this->paths[$i];
$firstSelector = true;
foreach($path as $p){
$p->genCSS( $output, $firstSelector );
$firstSelector = false;
}
if( $i + 1 < $paths_len ){
$output->add( ',' . $tabSetStr );
}
}
$output->add( (Less_Parser::$options['compress'] ? '{' : " {") . $tabRuleStr );
}
// Compile rules and rulesets
$ruleNodes_len = count($ruleNodes);
$rulesetNodes_len = count($rulesetNodes);
for( $i = 0; $i < $ruleNodes_len; $i++ ){
$rule = $ruleNodes[$i];
// @page{ directive ends up with root elements inside it, a mix of rules and rulesets
// In this instance we do not know whether it is the last property
if( $i + 1 === $ruleNodes_len && (!$this->root || $rulesetNodes_len === 0 || $this->firstRoot ) ){
Less_Environment::$lastRule = true;
}
$rule->genCSS( $output );
if( !Less_Environment::$lastRule ){
$output->add( $tabRuleStr );
}else{
Less_Environment::$lastRule = false;
}
}
if( !$this->root ){
$output->add( $tabSetStr . '}' );
Less_Environment::$tabLevel--;
}
$firstRuleset = true;
$space = ($this->root ? $tabRuleStr : $tabSetStr);
for( $i = 0; $i < $rulesetNodes_len; $i++ ){
if( $ruleNodes_len && $firstRuleset ){
$output->add( $space );
}elseif( !$firstRuleset ){
$output->add( $space );
}
$firstRuleset = false;
$rulesetNodes[$i]->genCSS( $output);
}
if( !Less_Parser::$options['compress'] && $this->firstRoot ){
$output->add( "\n" );
}
}
function markReferenced(){
if( !$this->selectors ){
return;
}
foreach($this->selectors as $selector){
$selector->markReferenced();
}
}
public function joinSelectors( $context, $selectors ){
$paths = array();
if( is_array($selectors) ){
foreach($selectors as $selector) {
$this->joinSelector( $paths, $context, $selector);
}
}
return $paths;
}
public function joinSelector( &$paths, $context, $selector){
$hasParentSelector = false;
foreach($selector->elements as $el) {
if( $el->value === '&') {
$hasParentSelector = true;
}
}
if( !$hasParentSelector ){
if( $context ){
foreach($context as $context_el){
$paths[] = array_merge($context_el, array($selector) );
}
}else {
$paths[] = array($selector);
}
return;
}
// The paths are [[Selector]]
// The first list is a list of comma seperated selectors
// The inner list is a list of inheritance seperated selectors
// e.g.
// .a, .b {
// .c {
// }
// }
// == [[.a] [.c]] [[.b] [.c]]
//
// the elements from the current selector so far
$currentElements = array();
// the current list of new selectors to add to the path.
// We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
// by the parents
$newSelectors = array(array());
foreach( $selector->elements as $el){
// non parent reference elements just get added
if( $el->value !== '&' ){
$currentElements[] = $el;
} else {
// the new list of selectors to add
$selectorsMultiplied = array();
// merge the current list of non parent selector elements
// on to the current list of selectors to add
if( $currentElements ){
$this->mergeElementsOnToSelectors( $currentElements, $newSelectors);
}
// loop through our current selectors
foreach($newSelectors as $sel){
// if we don't have any parent paths, the & might be in a mixin so that it can be used
// whether there are parents or not
if( !$context ){
// the combinator used on el should now be applied to the next element instead so that
// it is not lost
if( $sel ){
$sel[0]->elements = array_slice($sel[0]->elements,0);
$sel[0]->elements[] = new Less_Tree_Element($el->combinator, '', $el->index, $el->currentFileInfo );
}
$selectorsMultiplied[] = $sel;
}else {
// and the parent selectors
foreach($context as $parentSel){
// We need to put the current selectors
// then join the last selector's elements on to the parents selectors
// our new selector path
$newSelectorPath = array();
// selectors from the parent after the join
$afterParentJoin = array();
$newJoinedSelectorEmpty = true;
//construct the joined selector - if & is the first thing this will be empty,
// if not newJoinedSelector will be the last set of elements in the selector
if( $sel ){
$newSelectorPath = $sel;
$lastSelector = array_pop($newSelectorPath);
$newJoinedSelector = $selector->createDerived( array_slice($lastSelector->elements,0) );
$newJoinedSelectorEmpty = false;
}
else {
$newJoinedSelector = $selector->createDerived(array());
}
//put together the parent selectors after the join
if ( count($parentSel) > 1) {
$afterParentJoin = array_merge($afterParentJoin, array_slice($parentSel,1) );
}
if ( $parentSel ){
$newJoinedSelectorEmpty = false;
// join the elements so far with the first part of the parent
$newJoinedSelector->elements[] = new Less_Tree_Element( $el->combinator, $parentSel[0]->elements[0]->value, $el->index, $el->currentFileInfo);
$newJoinedSelector->elements = array_merge( $newJoinedSelector->elements, array_slice($parentSel[0]->elements, 1) );
}
if (!$newJoinedSelectorEmpty) {
// now add the joined selector
$newSelectorPath[] = $newJoinedSelector;
}
// and the rest of the parent
$newSelectorPath = array_merge($newSelectorPath, $afterParentJoin);
// add that to our new set of selectors
$selectorsMultiplied[] = $newSelectorPath;
}
}
}
// our new selectors has been multiplied, so reset the state
$newSelectors = $selectorsMultiplied;
$currentElements = array();
}
}
// if we have any elements left over (e.g. .a& .b == .b)
// add them on to all the current selectors
if( $currentElements ){
$this->mergeElementsOnToSelectors($currentElements, $newSelectors);
}
foreach( $newSelectors as $new_sel){
if( $new_sel ){
$paths[] = $new_sel;
}
}
}
function mergeElementsOnToSelectors( $elements, &$selectors){
if( !$selectors ){
$selectors[] = array( new Less_Tree_Selector($elements) );
return;
}
foreach( $selectors as &$sel){
// if the previous thing in sel is a parent this needs to join on to it
if( $sel ){
$last = count($sel)-1;
$sel[$last] = $sel[$last]->createDerived( array_merge($sel[$last]->elements, $elements) );
}else{
$sel[] = new Less_Tree_Selector( $elements );
}
}
}
}
/**
* RulesetCall
*
* @package Less
* @subpackage tree
*/
class Less_Tree_RulesetCall extends Less_Tree{
public $variable;
public $type = "RulesetCall";
public function __construct($variable){
$this->variable = $variable;
}
public function accept($visitor) {}
public function compile( $env ){
$variable = new Less_Tree_Variable($this->variable);
$detachedRuleset = $variable->compile($env);
return $detachedRuleset->callEval($env);
}
}
/**
* Selector
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Selector extends Less_Tree{
public $elements;
public $condition;
public $extendList = array();
public $_css;
public $index;
public $evaldCondition = false;
public $type = 'Selector';
public $currentFileInfo = array();
public $isReferenced;
public $mediaEmpty;
public $elements_len = 0;
public $_oelements;
public $_oelements_len;
public $cacheable = true;
/**
* @param boolean $isReferenced
*/
public function __construct( $elements, $extendList = array() , $condition = null, $index=null, $currentFileInfo=null, $isReferenced=null ){
$this->elements = $elements;
$this->elements_len = count($elements);
$this->extendList = $extendList;
$this->condition = $condition;
if( $currentFileInfo ){
$this->currentFileInfo = $currentFileInfo;
}
$this->isReferenced = $isReferenced;
if( !$condition ){
$this->evaldCondition = true;
}
$this->CacheElements();
}
public function accept($visitor) {
$this->elements = $visitor->visitArray($this->elements);
$this->extendList = $visitor->visitArray($this->extendList);
if( $this->condition ){
$this->condition = $visitor->visitObj($this->condition);
}
if( $visitor instanceof Less_Visitor_extendFinder ){
$this->CacheElements();
}
}
public function createDerived( $elements, $extendList = null, $evaldCondition = null ){
$newSelector = new Less_Tree_Selector( $elements, ($extendList ? $extendList : $this->extendList), null, $this->index, $this->currentFileInfo, $this->isReferenced);
$newSelector->evaldCondition = $evaldCondition ? $evaldCondition : $this->evaldCondition;
return $newSelector;
}
public function match( $other ){
if( !$other->_oelements || ($this->elements_len < $other->_oelements_len) ){
return 0;
}
for( $i = 0; $i < $other->_oelements_len; $i++ ){
if( $this->elements[$i]->value !== $other->_oelements[$i]) {
return 0;
}
}
return $other->_oelements_len; // return number of matched elements
}
public function CacheElements(){
$this->_oelements = array();
$css = '';
foreach($this->elements as $v){
$css .= $v->combinator;
if( !$v->value_is_object ){
$css .= $v->value;
continue;
}
if( !property_exists($v->value,'value') || !is_string($v->value->value) ){
$this->cacheable = false;
return;
}
$css .= $v->value->value;
}
$this->_oelements_len = preg_match_all('/[,&#\.\w-](?:[\w-]|(?:\\\\.))*/', $css, $matches);
if( $this->_oelements_len ){
$this->_oelements = $matches[0];
if( $this->_oelements[0] === '&' ){
array_shift($this->_oelements);
$this->_oelements_len--;
}
}
}
public function isJustParentSelector(){
return !$this->mediaEmpty &&
count($this->elements) === 1 &&
$this->elements[0]->value === '&' &&
($this->elements[0]->combinator === ' ' || $this->elements[0]->combinator === '');
}
public function compile($env) {
$elements = array();
foreach($this->elements as $el){
$elements[] = $el->compile($env);
}
$extendList = array();
foreach($this->extendList as $el){
$extendList[] = $el->compile($el);
}
$evaldCondition = false;
if( $this->condition ){
$evaldCondition = $this->condition->compile($env);
}
return $this->createDerived( $elements, $extendList, $evaldCondition );
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output, $firstSelector = true ){
if( !$firstSelector && $this->elements[0]->combinator === "" ){
$output->add(' ', $this->currentFileInfo, $this->index);
}
foreach($this->elements as $element){
$element->genCSS( $output );
}
}
public function markReferenced(){
$this->isReferenced = true;
}
public function getIsReferenced(){
return !isset($this->currentFileInfo['reference']) || !$this->currentFileInfo['reference'] || $this->isReferenced;
}
public function getIsOutput(){
return $this->evaldCondition;
}
}
/**
* UnicodeDescriptor
*
* @package Less
* @subpackage tree
*/
class Less_Tree_UnicodeDescriptor extends Less_Tree{
public $value;
public $type = 'UnicodeDescriptor';
public function __construct($value){
$this->value = $value;
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
$output->add( $this->value );
}
public function compile(){
return $this;
}
}
/**
* Unit
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Unit extends Less_Tree{
var $numerator = array();
var $denominator = array();
public $backupUnit;
public $type = 'Unit';
public function __construct($numerator = array(), $denominator = array(), $backupUnit = null ){
$this->numerator = $numerator;
$this->denominator = $denominator;
$this->backupUnit = $backupUnit;
}
public function __clone(){
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
if( $this->numerator ){
$output->add( $this->numerator[0] );
}elseif( $this->denominator ){
$output->add( $this->denominator[0] );
}elseif( !Less_Parser::$options['strictUnits'] && $this->backupUnit ){
$output->add( $this->backupUnit );
return ;
}
}
public function toString(){
$returnStr = implode('*',$this->numerator);
foreach($this->denominator as $d){
$returnStr .= '/'.$d;
}
return $returnStr;
}
public function __toString(){
return $this->toString();
}
/**
* @param Less_Tree_Unit $other
*/
public function compare($other) {
return $this->is( $other->toString() ) ? 0 : -1;
}
public function is($unitString){
return $this->toString() === $unitString;
}
public function isLength(){
$css = $this->toCSS();
return !!preg_match('/px|em|%|in|cm|mm|pc|pt|ex/',$css);
}
public function isAngle() {
return isset( Less_Tree_UnitConversions::$angle[$this->toCSS()] );
}
public function isEmpty(){
return !$this->numerator && !$this->denominator;
}
public function isSingular() {
return count($this->numerator) <= 1 && !$this->denominator;
}
public function usedUnits(){
$result = array();
foreach(Less_Tree_UnitConversions::$groups as $groupName){
$group = Less_Tree_UnitConversions::${$groupName};
foreach($this->numerator as $atomicUnit){
if( isset($group[$atomicUnit]) && !isset($result[$groupName]) ){
$result[$groupName] = $atomicUnit;
}
}
foreach($this->denominator as $atomicUnit){
if( isset($group[$atomicUnit]) && !isset($result[$groupName]) ){
$result[$groupName] = $atomicUnit;
}
}
}
return $result;
}
public function cancel(){
$counter = array();
$backup = null;
foreach($this->numerator as $atomicUnit){
if( !$backup ){
$backup = $atomicUnit;
}
$counter[$atomicUnit] = ( isset($counter[$atomicUnit]) ? $counter[$atomicUnit] : 0) + 1;
}
foreach($this->denominator as $atomicUnit){
if( !$backup ){
$backup = $atomicUnit;
}
$counter[$atomicUnit] = ( isset($counter[$atomicUnit]) ? $counter[$atomicUnit] : 0) - 1;
}
$this->numerator = array();
$this->denominator = array();
foreach($counter as $atomicUnit => $count){
if( $count > 0 ){
for( $i = 0; $i < $count; $i++ ){
$this->numerator[] = $atomicUnit;
}
}elseif( $count < 0 ){
for( $i = 0; $i < -$count; $i++ ){
$this->denominator[] = $atomicUnit;
}
}
}
if( !$this->numerator && !$this->denominator && $backup ){
$this->backupUnit = $backup;
}
sort($this->numerator);
sort($this->denominator);
}
}
/**
* UnitConversions
*
* @package Less
* @subpackage tree
*/
class Less_Tree_UnitConversions{
public static $groups = array('length','duration','angle');
public static $length = array(
'm'=> 1,
'cm'=> 0.01,
'mm'=> 0.001,
'in'=> 0.0254,
'px'=> 0.000264583, // 0.0254 / 96,
'pt'=> 0.000352778, // 0.0254 / 72,
'pc'=> 0.004233333, // 0.0254 / 72 * 12
);
public static $duration = array(
's'=> 1,
'ms'=> 0.001
);
public static $angle = array(
'rad' => 0.1591549430919, // 1/(2*M_PI),
'deg' => 0.002777778, // 1/360,
'grad'=> 0.0025, // 1/400,
'turn'=> 1
);
}
/**
* Url
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Url extends Less_Tree{
public $attrs;
public $value;
public $currentFileInfo;
public $isEvald;
public $type = 'Url';
public function __construct($value, $currentFileInfo = null, $isEvald = null){
$this->value = $value;
$this->currentFileInfo = $currentFileInfo;
$this->isEvald = $isEvald;
}
public function accept( $visitor ){
$this->value = $visitor->visitObj($this->value);
}
/**
* @see Less_Tree::genCSS
*/
public function genCSS( $output ){
$output->add( 'url(' );
$this->value->genCSS( $output );
$output->add( ')' );
}
/**
* @param Less_Functions $ctx
*/
public function compile($ctx){
$val = $this->value->compile($ctx);
if( !$this->isEvald ){
// Add the base path if the URL is relative
if( Less_Parser::$options['relativeUrls']
&& $this->currentFileInfo
&& is_string($val->value)
&& Less_Environment::isPathRelative($val->value)
){
$rootpath = $this->currentFileInfo['uri_root'];
if ( !$val->quote ){
$rootpath = preg_replace('/[\(\)\'"\s]/', '\\$1', $rootpath );
}
$val->value = $rootpath . $val->value;
}
$val->value = Less_Environment::normalizePath( $val->value);
}
// Add cache buster if enabled
if( Less_Parser::$options['urlArgs'] ){
if( !preg_match('/^\s*data:/',$val->value) ){
$delimiter = strpos($val->value,'?') === false ? '?' : '&';
$urlArgs = $delimiter . Less_Parser::$options['urlArgs'];
$hash_pos = strpos($val->value,'#');
if( $hash_pos !== false ){
$val->value = substr_replace($val->value,$urlArgs, $hash_pos, 0);
} else {
$val->value .= $urlArgs;
}
}
}
return new Less_Tree_URL($val, $this->currentFileInfo, true);
}
}
/**
* Value
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Value extends Less_Tree{
public $type = 'Value';
public $value;
public function __construct($value){
$this->value = $value;
}
public function accept($visitor) {
$this->value = $visitor->visitArray($this->value);
}
public function compile($env){
$ret = array();
$i = 0;
foreach($this->value as $i => $v){
$ret[] = $v->compile($env);
}
if( $i > 0 ){
return new Less_Tree_Value($ret);
}
return $ret[0];
}
/**
* @see Less_Tree::genCSS
*/
function genCSS( $output ){
$len = count($this->value);
for($i = 0; $i < $len; $i++ ){
$this->value[$i]->genCSS( $output );
if( $i+1 < $len ){
$output->add( Less_Environment::$_outputMap[','] );
}
}
}
}
/**
* Variable
*
* @package Less
* @subpackage tree
*/
class Less_Tree_Variable extends Less_Tree{
public $name;
public $index;
public $currentFileInfo;
public $evaluating = false;
public $type = 'Variable';
/**
* @param string $name
*/
public function __construct($name, $index = null, $currentFileInfo = null) {
$this->name = $name;
$this->index = $index;
$this->currentFileInfo = $currentFileInfo;
}
public function compile($env) {
if( $this->name[1] === '@' ){
$v = new Less_Tree_Variable(substr($this->name, 1), $this->index + 1, $this->currentFileInfo);
$name = '@' . $v->compile($env)->value;
}else{
$name = $this->name;
}
if ($this->evaluating) {
throw new Less_Exception_Compiler("Recursive variable definition for " . $name, null, $this->index, $this->currentFileInfo);
}
$this->evaluating = true;
foreach($env->frames as $frame){
if( $v = $frame->variable($name) ){
$r = $v->value->compile($env);
$this->evaluating = false;
return $r;
}
}
throw new Less_Exception_Compiler("variable " . $name . " is undefined in file ".$this->currentFileInfo["filename"], null, $this->index, $this->currentFileInfo);
}
}
class Less_Tree_Mixin_Call extends Less_Tree{
public $selector;
public $arguments;
public $index;
public $currentFileInfo;
public $important;
public $type = 'MixinCall';
/**
* less.js: tree.mixin.Call
*
*/
public function __construct($elements, $args, $index, $currentFileInfo, $important = false){
$this->selector = new Less_Tree_Selector($elements);
$this->arguments = $args;
$this->index = $index;
$this->currentFileInfo = $currentFileInfo;
$this->important = $important;
}
//function accept($visitor){
// $this->selector = $visitor->visit($this->selector);
// $this->arguments = $visitor->visit($this->arguments);
//}
public function compile($env){
$rules = array();
$match = false;
$isOneFound = false;
$candidates = array();
$defaultUsed = false;
$conditionResult = array();
$args = array();
foreach($this->arguments as $a){
$args[] = array('name'=> $a['name'], 'value' => $a['value']->compile($env) );
}
foreach($env->frames as $frame){
$mixins = $frame->find($this->selector);
if( !$mixins ){
continue;
}
$isOneFound = true;
$defNone = 0;
$defTrue = 1;
$defFalse = 2;
// To make `default()` function independent of definition order we have two "subpasses" here.
// At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
// and build candidate list with corresponding flags. Then, when we know all possible matches,
// we make a final decision.
$mixins_len = count($mixins);
for( $m = 0; $m < $mixins_len; $m++ ){
$mixin = $mixins[$m];
if( $this->IsRecursive( $env, $mixin ) ){
continue;
}
if( $mixin->matchArgs($args, $env) ){
$candidate = array('mixin' => $mixin, 'group' => $defNone);
if( $mixin instanceof Less_Tree_Ruleset ){
for( $f = 0; $f < 2; $f++ ){
Less_Tree_DefaultFunc::value($f);
$conditionResult[$f] = $mixin->matchCondition( $args, $env);
}
if( $conditionResult[0] || $conditionResult[1] ){
if( $conditionResult[0] != $conditionResult[1] ){
$candidate['group'] = $conditionResult[1] ? $defTrue : $defFalse;
}
$candidates[] = $candidate;
}
}else{
$candidates[] = $candidate;
}
$match = true;
}
}
Less_Tree_DefaultFunc::reset();
$count = array(0, 0, 0);
for( $m = 0; $m < count($candidates); $m++ ){
$count[ $candidates[$m]['group'] ]++;
}
if( $count[$defNone] > 0 ){
$defaultResult = $defFalse;
} else {
$defaultResult = $defTrue;
if( ($count[$defTrue] + $count[$defFalse]) > 1 ){
throw new Exception( 'Ambiguous use of `default()` found when matching for `'. $this->format($args) + '`' );
}
}
$candidates_length = count($candidates);
$length_1 = ($candidates_length == 1);
for( $m = 0; $m < $candidates_length; $m++){
$candidate = $candidates[$m]['group'];
if( ($candidate === $defNone) || ($candidate === $defaultResult) ){
try{
$mixin = $candidates[$m]['mixin'];
if( !($mixin instanceof Less_Tree_Mixin_Definition) ){
$mixin = new Less_Tree_Mixin_Definition('', array(), $mixin->rules, null, false);
$mixin->originalRuleset = $mixins[$m]->originalRuleset;
}
$rules = array_merge($rules, $mixin->evalCall($env, $args, $this->important)->rules);
} catch (Exception $e) {
//throw new Less_Exception_Compiler($e->getMessage(), $e->index, null, $this->currentFileInfo['filename']);
throw new Less_Exception_Compiler($e->getMessage(), null, null, $this->currentFileInfo);
}
}
}
if( $match ){
if( !$this->currentFileInfo || !isset($this->currentFileInfo['reference']) || !$this->currentFileInfo['reference'] ){
Less_Tree::ReferencedArray($rules);
}
return $rules;
}
}
if( $isOneFound ){
throw new Less_Exception_Compiler('No matching definition was found for `'.$this->Format( $args ).'`', null, $this->index, $this->currentFileInfo);
}else{
throw new Less_Exception_Compiler(trim($this->selector->toCSS()) . " is undefined in ".$this->currentFileInfo['filename'], null, $this->index);
}
}
/**
* Format the args for use in exception messages
*
*/
private function Format($args){
$message = array();
if( $args ){
foreach($args as $a){
$argValue = '';
if( $a['name'] ){
$argValue += $a['name']+':';
}
if( is_object($a['value']) ){
$argValue += $a['value']->toCSS();
}else{
$argValue += '???';
}
$message[] = $argValue;
}
}
return implode(', ',$message);
}
/**
* Are we in a recursive mixin call?
*
* @return bool
*/
private function IsRecursive( $env, $mixin ){
foreach($env->frames as $recur_frame){
if( !($mixin instanceof Less_Tree_Mixin_Definition) ){
if( $mixin === $recur_frame ){
return true;
}
if( isset($recur_frame->originalRuleset) && $mixin->ruleset_id === $recur_frame->originalRuleset ){
return true;
}
}
}
return false;
}
}
class Less_Tree_Mixin_Definition extends Less_Tree_Ruleset{
public $name;
public $selectors;
public $params;
public $arity = 0;
public $rules;
public $lookups = array();
public $required = 0;
public $frames = array();
public $condition;
public $variadic;
public $type = 'MixinDefinition';
// less.js : /lib/less/tree/mixin.js : tree.mixin.Definition
public function __construct($name, $params, $rules, $condition, $variadic = false, $frames = array() ){
$this->name = $name;
$this->selectors = array(new Less_Tree_Selector(array( new Less_Tree_Element(null, $name))));
$this->params = $params;
$this->condition = $condition;
$this->variadic = $variadic;
$this->rules = $rules;
if( $params ){
$this->arity = count($params);
foreach( $params as $p ){
if (! isset($p['name']) || ($p['name'] && !isset($p['value']))) {
$this->required++;
}
}
}
$this->frames = $frames;
$this->SetRulesetIndex();
}
//function accept( $visitor ){
// $this->params = $visitor->visit($this->params);
// $this->rules = $visitor->visit($this->rules);
// $this->condition = $visitor->visit($this->condition);
//}
public function toCSS(){
return '';
}
// less.js : /lib/less/tree/mixin.js : tree.mixin.Definition.evalParams
public function compileParams($env, $mixinFrames, $args = array() , &$evaldArguments = array() ){
$frame = new Less_Tree_Ruleset(null, array());
$params = $this->params;
$mixinEnv = null;
$argsLength = 0;
if( $args ){
$argsLength = count($args);
for($i = 0; $i < $argsLength; $i++ ){
$arg = $args[$i];
if( $arg && $arg['name'] ){
$isNamedFound = false;
foreach($params as $j => $param){
if( !isset($evaldArguments[$j]) && $arg['name'] === $params[$j]['name']) {
$evaldArguments[$j] = $arg['value']->compile($env);
array_unshift($frame->rules, new Less_Tree_Rule( $arg['name'], $arg['value']->compile($env) ) );
$isNamedFound = true;
break;
}
}
if ($isNamedFound) {
array_splice($args, $i, 1);
$i--;
$argsLength--;
continue;
} else {
throw new Less_Exception_Compiler("Named argument for " . $this->name .' '.$args[$i]['name'] . ' not found');
}
}
}
}
$argIndex = 0;
foreach($params as $i => $param){
if ( isset($evaldArguments[$i]) ){ continue; }
$arg = null;
if( isset($args[$argIndex]) ){
$arg = $args[$argIndex];
}
if (isset($param['name']) && $param['name']) {
if( isset($param['variadic']) ){
$varargs = array();
for ($j = $argIndex; $j < $argsLength; $j++) {
$varargs[] = $args[$j]['value']->compile($env);
}
$expression = new Less_Tree_Expression($varargs);
array_unshift($frame->rules, new Less_Tree_Rule($param['name'], $expression->compile($env)));
}else{
$val = ($arg && $arg['value']) ? $arg['value'] : false;
if ($val) {
$val = $val->compile($env);
} else if ( isset($param['value']) ) {
if( !$mixinEnv ){
$mixinEnv = new Less_Environment();
$mixinEnv->frames = array_merge( array($frame), $mixinFrames);
}
$val = $param['value']->compile($mixinEnv);
$frame->resetCache();
} else {
throw new Less_Exception_Compiler("Wrong number of arguments for " . $this->name . " (" . $argsLength . ' for ' . $this->arity . ")");
}
array_unshift($frame->rules, new Less_Tree_Rule($param['name'], $val));
$evaldArguments[$i] = $val;
}
}
if ( isset($param['variadic']) && $args) {
for ($j = $argIndex; $j < $argsLength; $j++) {
$evaldArguments[$j] = $args[$j]['value']->compile($env);
}
}
$argIndex++;
}
ksort($evaldArguments);
$evaldArguments = array_values($evaldArguments);
return $frame;
}
public function compile($env) {
if( $this->frames ){
return new Less_Tree_Mixin_Definition($this->name, $this->params, $this->rules, $this->condition, $this->variadic, $this->frames );
}
return new Less_Tree_Mixin_Definition($this->name, $this->params, $this->rules, $this->condition, $this->variadic, $env->frames );
}
public function evalCall($env, $args = NULL, $important = NULL) {
Less_Environment::$mixin_stack++;
$_arguments = array();
if( $this->frames ){
$mixinFrames = array_merge($this->frames, $env->frames);
}else{
$mixinFrames = $env->frames;
}
$frame = $this->compileParams($env, $mixinFrames, $args, $_arguments);
$ex = new Less_Tree_Expression($_arguments);
array_unshift($frame->rules, new Less_Tree_Rule('@arguments', $ex->compile($env)));
$ruleset = new Less_Tree_Ruleset(null, $this->rules);
$ruleset->originalRuleset = $this->ruleset_id;
$ruleSetEnv = new Less_Environment();
$ruleSetEnv->frames = array_merge( array($this, $frame), $mixinFrames );
$ruleset = $ruleset->compile( $ruleSetEnv );
if( $important ){
$ruleset = $ruleset->makeImportant();
}
Less_Environment::$mixin_stack--;
return $ruleset;
}
public function matchCondition($args, $env) {
if( !$this->condition ){
return true;
}
// set array to prevent error on array_merge
if(!is_array($this->frames)) {
$this->frames = array();
}
$frame = $this->compileParams($env, array_merge($this->frames,$env->frames), $args );
$compile_env = new Less_Environment();
$compile_env->frames = array_merge(
array($frame) // the parameter variables
, $this->frames // the parent namespace/mixin frames
, $env->frames // the current environment frames
);
$compile_env->functions = $env->functions;
return (bool)$this->condition->compile($compile_env);
}
public function matchArgs($args, $env = NULL){
$argsLength = count($args);
if( !$this->variadic ){
if( $argsLength < $this->required ){
return false;
}
if( $argsLength > count($this->params) ){
return false;
}
}else{
if( $argsLength < ($this->required - 1)){
return false;
}
}
$len = min($argsLength, $this->arity);
for( $i = 0; $i < $len; $i++ ){
if( !isset($this->params[$i]['name']) && !isset($this->params[$i]['variadic']) ){
if( $args[$i]['value']->compile($env)->toCSS() != $this->params[$i]['value']->compile($env)->toCSS() ){
return false;
}
}
}
return true;
}
}
/**
* Extend Finder Visitor
*
* @package Less
* @subpackage visitor
*/
class Less_Visitor_extendFinder extends Less_Visitor{
public $contexts = array();
public $allExtendsStack;
public $foundExtends;
public function __construct(){
$this->contexts = array();
$this->allExtendsStack = array(array());
parent::__construct();
}
/**
* @param Less_Tree_Ruleset $root
*/
public function run($root){
$root = $this->visitObj($root);
$root->allExtends =& $this->allExtendsStack[0];
return $root;
}
public function visitRule($ruleNode, &$visitDeeper ){
$visitDeeper = false;
}
public function visitMixinDefinition( $mixinDefinitionNode, &$visitDeeper ){
$visitDeeper = false;
}
public function visitRuleset($rulesetNode){
if( $rulesetNode->root ){
return;
}
$allSelectorsExtendList = array();
// get &:extend(.a); rules which apply to all selectors in this ruleset
if( $rulesetNode->rules ){
foreach($rulesetNode->rules as $rule){
if( $rule instanceof Less_Tree_Extend ){
$allSelectorsExtendList[] = $rule;
$rulesetNode->extendOnEveryPath = true;
}
}
}
// now find every selector and apply the extends that apply to all extends
// and the ones which apply to an individual extend
foreach($rulesetNode->paths as $selectorPath){
$selector = end($selectorPath); //$selectorPath[ count($selectorPath)-1];
$j = 0;
foreach($selector->extendList as $extend){
$this->allExtendsStackPush($rulesetNode, $selectorPath, $extend, $j);
}
foreach($allSelectorsExtendList as $extend){
$this->allExtendsStackPush($rulesetNode, $selectorPath, $extend, $j);
}
}
$this->contexts[] = $rulesetNode->selectors;
}
public function allExtendsStackPush($rulesetNode, $selectorPath, $extend, &$j){
$this->foundExtends = true;
$extend = clone $extend;
$extend->findSelfSelectors( $selectorPath );
$extend->ruleset = $rulesetNode;
if( $j === 0 ){
$extend->firstExtendOnThisSelectorPath = true;
}
$end_key = count($this->allExtendsStack)-1;
$this->allExtendsStack[$end_key][] = $extend;
$j++;
}
public function visitRulesetOut( $rulesetNode ){
if( !is_object($rulesetNode) || !$rulesetNode->root ){
array_pop($this->contexts);
}
}
public function visitMedia( $mediaNode ){
$mediaNode->allExtends = array();
$this->allExtendsStack[] =& $mediaNode->allExtends;
}
public function visitMediaOut(){
array_pop($this->allExtendsStack);
}
public function visitDirective( $directiveNode ){
$directiveNode->allExtends = array();
$this->allExtendsStack[] =& $directiveNode->allExtends;
}
public function visitDirectiveOut(){
array_pop($this->allExtendsStack);
}
}
/*
class Less_Visitor_import extends Less_VisitorReplacing{
public $_visitor;
public $_importer;
public $importCount;
function __construct( $evalEnv ){
$this->env = $evalEnv;
$this->importCount = 0;
parent::__construct();
}
function run( $root ){
$root = $this->visitObj($root);
$this->isFinished = true;
//if( $this->importCount === 0) {
// $this->_finish();
//}
}
function visitImport($importNode, &$visitDeeper ){
$importVisitor = $this;
$inlineCSS = $importNode->options['inline'];
if( !$importNode->css || $inlineCSS ){
$evaldImportNode = $importNode->compileForImport($this->env);
if( $evaldImportNode && (!$evaldImportNode->css || $inlineCSS) ){
$importNode = $evaldImportNode;
$this->importCount++;
$env = clone $this->env;
if( (isset($importNode->options['multiple']) && $importNode->options['multiple']) ){
$env->importMultiple = true;
}
//get path & uri
$path_and_uri = null;
if( is_callable(Less_Parser::$options['import_callback']) ){
$path_and_uri = call_user_func(Less_Parser::$options['import_callback'],$importNode);
}
if( !$path_and_uri ){
$path_and_uri = $importNode->PathAndUri();
}
if( $path_and_uri ){
list($full_path, $uri) = $path_and_uri;
}else{
$full_path = $uri = $importNode->getPath();
}
//import once
if( $importNode->skip( $full_path, $env) ){
return array();
}
if( $importNode->options['inline'] ){
//todo needs to reference css file not import
//$contents = new Less_Tree_Anonymous($importNode->root, 0, array('filename'=>$importNode->importedFilename), true );
Less_Parser::AddParsedFile($full_path);
$contents = new Less_Tree_Anonymous( file_get_contents($full_path), 0, array(), true );
if( $importNode->features ){
return new Less_Tree_Media( array($contents), $importNode->features->value );
}
return array( $contents );
}
// css ?
if( $importNode->css ){
$features = ( $importNode->features ? $importNode->features->compile($env) : null );
return new Less_Tree_Import( $importNode->compilePath( $env), $features, $importNode->options, $this->index);
}
return $importNode->ParseImport( $full_path, $uri, $env );
}
}
$visitDeeper = false;
return $importNode;
}
function visitRule( $ruleNode, &$visitDeeper ){
$visitDeeper = false;
return $ruleNode;
}
function visitDirective($directiveNode, $visitArgs){
array_unshift($this->env->frames,$directiveNode);
return $directiveNode;
}
function visitDirectiveOut($directiveNode) {
array_shift($this->env->frames);
}
function visitMixinDefinition($mixinDefinitionNode, $visitArgs) {
array_unshift($this->env->frames,$mixinDefinitionNode);
return $mixinDefinitionNode;
}
function visitMixinDefinitionOut($mixinDefinitionNode) {
array_shift($this->env->frames);
}
function visitRuleset($rulesetNode, $visitArgs) {
array_unshift($this->env->frames,$rulesetNode);
return $rulesetNode;
}
function visitRulesetOut($rulesetNode) {
array_shift($this->env->frames);
}
function visitMedia($mediaNode, $visitArgs) {
array_unshift($this->env->frames, $mediaNode->ruleset);
return $mediaNode;
}
function visitMediaOut($mediaNode) {
array_shift($this->env->frames);
}
}
*/
/**
* Join Selector Visitor
*
* @package Less
* @subpackage visitor
*/
class Less_Visitor_joinSelector extends Less_Visitor{
public $contexts = array( array() );
/**
* @param Less_Tree_Ruleset $root
*/
public function run( $root ){
return $this->visitObj($root);
}
public function visitRule( $ruleNode, &$visitDeeper ){
$visitDeeper = false;
}
public function visitMixinDefinition( $mixinDefinitionNode, &$visitDeeper ){
$visitDeeper = false;
}
public function visitRuleset( $rulesetNode ){
$paths = array();
if( !$rulesetNode->root ){
$selectors = array();
if( $rulesetNode->selectors && $rulesetNode->selectors ){
foreach($rulesetNode->selectors as $selector){
if( $selector->getIsOutput() ){
$selectors[] = $selector;
}
}
}
if( !$selectors ){
$rulesetNode->selectors = null;
$rulesetNode->rules = null;
}else{
$context = end($this->contexts); //$context = $this->contexts[ count($this->contexts) - 1];
$paths = $rulesetNode->joinSelectors( $context, $selectors);
}
$rulesetNode->paths = $paths;
}
$this->contexts[] = $paths; //different from less.js. Placed after joinSelectors() so that $this->contexts will get correct $paths
}
public function visitRulesetOut(){
array_pop($this->contexts);
}
public function visitMedia($mediaNode) {
$context = end($this->contexts); //$context = $this->contexts[ count($this->contexts) - 1];
if( !count($context) || (is_object($context[0]) && $context[0]->multiMedia) ){
$mediaNode->rules[0]->root = true;
}
}
}
/**
* Process Extends Visitor
*
* @package Less
* @subpackage visitor
*/
class Less_Visitor_processExtends extends Less_Visitor{
public $allExtendsStack;
/**
* @param Less_Tree_Ruleset $root
*/
public function run( $root ){
$extendFinder = new Less_Visitor_extendFinder();
$extendFinder->run( $root );
if( !$extendFinder->foundExtends){
return $root;
}
$root->allExtends = $this->doExtendChaining( $root->allExtends, $root->allExtends);
$this->allExtendsStack = array();
$this->allExtendsStack[] = &$root->allExtends;
return $this->visitObj( $root );
}
private function doExtendChaining( $extendsList, $extendsListTarget, $iterationCount = 0){
//
// chaining is different from normal extension.. if we extend an extend then we are not just copying, altering and pasting
// the selector we would do normally, but we are also adding an extend with the same target selector
// this means this new extend can then go and alter other extends
//
// this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
// this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already processed if
// we look at each selector at a time, as is done in visitRuleset
$extendsToAdd = array();
//loop through comparing every extend with every target extend.
// a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
// e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one
// and the second is the target.
// the seperation into two lists allows us to process a subset of chains with a bigger set, as is the
// case when processing media queries
for( $extendIndex = 0, $extendsList_len = count($extendsList); $extendIndex < $extendsList_len; $extendIndex++ ){
for( $targetExtendIndex = 0; $targetExtendIndex < count($extendsListTarget); $targetExtendIndex++ ){
$extend = $extendsList[$extendIndex];
$targetExtend = $extendsListTarget[$targetExtendIndex];
// look for circular references
if( in_array($targetExtend->object_id, $extend->parent_ids,true) ){
continue;
}
// find a match in the target extends self selector (the bit before :extend)
$selectorPath = array( $targetExtend->selfSelectors[0] );
$matches = $this->findMatch( $extend, $selectorPath);
if( $matches ){
// we found a match, so for each self selector..
foreach($extend->selfSelectors as $selfSelector ){
// process the extend as usual
$newSelector = $this->extendSelector( $matches, $selectorPath, $selfSelector);
// but now we create a new extend from it
$newExtend = new Less_Tree_Extend( $targetExtend->selector, $targetExtend->option, 0);
$newExtend->selfSelectors = $newSelector;
// add the extend onto the list of extends for that selector
end($newSelector)->extendList = array($newExtend);
//$newSelector[ count($newSelector)-1]->extendList = array($newExtend);
// record that we need to add it.
$extendsToAdd[] = $newExtend;
$newExtend->ruleset = $targetExtend->ruleset;
//remember its parents for circular references
$newExtend->parent_ids = array_merge($newExtend->parent_ids,$targetExtend->parent_ids,$extend->parent_ids);
// only process the selector once.. if we have :extend(.a,.b) then multiple
// extends will look at the same selector path, so when extending
// we know that any others will be duplicates in terms of what is added to the css
if( $targetExtend->firstExtendOnThisSelectorPath ){
$newExtend->firstExtendOnThisSelectorPath = true;
$targetExtend->ruleset->paths[] = $newSelector;
}
}
}
}
}
if( $extendsToAdd ){
// try to detect circular references to stop a stack overflow.
// may no longer be needed. $this->extendChainCount++;
if( $iterationCount > 100) {
try{
$selectorOne = $extendsToAdd[0]->selfSelectors[0]->toCSS();
$selectorTwo = $extendsToAdd[0]->selector->toCSS();
}catch(Exception $e){
$selectorOne = "{unable to calculate}";
$selectorTwo = "{unable to calculate}";
}
throw new Less_Exception_Parser("extend circular reference detected. One of the circular extends is currently:"+$selectorOne+":extend(" + $selectorTwo+")");
}
// now process the new extends on the existing rules so that we can handle a extending b extending c ectending d extending e...
$extendsToAdd = $this->doExtendChaining( $extendsToAdd, $extendsListTarget, $iterationCount+1);
}
return array_merge($extendsList, $extendsToAdd);
}
protected function visitRule( $ruleNode, &$visitDeeper ){
$visitDeeper = false;
}
protected function visitMixinDefinition( $mixinDefinitionNode, &$visitDeeper ){
$visitDeeper = false;
}
protected function visitSelector( $selectorNode, &$visitDeeper ){
$visitDeeper = false;
}
protected function visitRuleset($rulesetNode){
if( $rulesetNode->root ){
return;
}
$allExtends = end($this->allExtendsStack);
$paths_len = count($rulesetNode->paths);
// look at each selector path in the ruleset, find any extend matches and then copy, find and replace
foreach($allExtends as $allExtend){
for($pathIndex = 0; $pathIndex < $paths_len; $pathIndex++ ){
// extending extends happens initially, before the main pass
if( isset($rulesetNode->extendOnEveryPath) && $rulesetNode->extendOnEveryPath ){
continue;
}
$selectorPath = $rulesetNode->paths[$pathIndex];
if( end($selectorPath)->extendList ){
continue;
}
$this->ExtendMatch( $rulesetNode, $allExtend, $selectorPath);
}
}
}
private function ExtendMatch( $rulesetNode, $extend, $selectorPath ){
$matches = $this->findMatch($extend, $selectorPath);
if( $matches ){
foreach($extend->selfSelectors as $selfSelector ){
$rulesetNode->paths[] = $this->extendSelector($matches, $selectorPath, $selfSelector);
}
}
}
private function findMatch($extend, $haystackSelectorPath ){
if( !$this->HasMatches($extend, $haystackSelectorPath) ){
return false;
}
//
// look through the haystack selector path to try and find the needle - extend.selector
// returns an array of selector matches that can then be replaced
//
$needleElements = $extend->selector->elements;
$potentialMatches = array();
$potentialMatches_len = 0;
$potentialMatch = null;
$matches = array();
// loop through the haystack elements
$haystack_path_len = count($haystackSelectorPath);
for($haystackSelectorIndex = 0; $haystackSelectorIndex < $haystack_path_len; $haystackSelectorIndex++ ){
$hackstackSelector = $haystackSelectorPath[$haystackSelectorIndex];
$haystack_elements_len = count($hackstackSelector->elements);
for($hackstackElementIndex = 0; $hackstackElementIndex < $haystack_elements_len; $hackstackElementIndex++ ){
$haystackElement = $hackstackSelector->elements[$hackstackElementIndex];
// if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
if( $extend->allowBefore || ($haystackSelectorIndex === 0 && $hackstackElementIndex === 0) ){
$potentialMatches[] = array('pathIndex'=> $haystackSelectorIndex, 'index'=> $hackstackElementIndex, 'matched'=> 0, 'initialCombinator'=> $haystackElement->combinator);
$potentialMatches_len++;
}
for($i = 0; $i < $potentialMatches_len; $i++ ){
$potentialMatch = &$potentialMatches[$i];
$potentialMatch = $this->PotentialMatch( $potentialMatch, $needleElements, $haystackElement, $hackstackElementIndex );
// if we are still valid and have finished, test whether we have elements after and whether these are allowed
if( $potentialMatch && $potentialMatch['matched'] === $extend->selector->elements_len ){
$potentialMatch['finished'] = true;
if( !$extend->allowAfter && ($hackstackElementIndex+1 < $haystack_elements_len || $haystackSelectorIndex+1 < $haystack_path_len) ){
$potentialMatch = null;
}
}
// if null we remove, if not, we are still valid, so either push as a valid match or continue
if( $potentialMatch ){
if( $potentialMatch['finished'] ){
$potentialMatch['length'] = $extend->selector->elements_len;
$potentialMatch['endPathIndex'] = $haystackSelectorIndex;
$potentialMatch['endPathElementIndex'] = $hackstackElementIndex + 1; // index after end of match
$potentialMatches = array(); // we don't allow matches to overlap, so start matching again
$potentialMatches_len = 0;
$matches[] = $potentialMatch;
}
continue;
}
array_splice($potentialMatches, $i, 1);
$potentialMatches_len--;
$i--;
}
}
}
return $matches;
}
// Before going through all the nested loops, lets check to see if a match is possible
// Reduces Bootstrap 3.1 compile time from ~6.5s to ~5.6s
private function HasMatches($extend, $haystackSelectorPath){
if( !$extend->selector->cacheable ){
return true;
}
$first_el = $extend->selector->_oelements[0];
foreach($haystackSelectorPath as $hackstackSelector){
if( !$hackstackSelector->cacheable ){
return true;
}
if( in_array($first_el, $hackstackSelector->_oelements) ){
return true;
}
}
return false;
}
/**
* @param integer $hackstackElementIndex
*/
private function PotentialMatch( $potentialMatch, $needleElements, $haystackElement, $hackstackElementIndex ){
if( $potentialMatch['matched'] > 0 ){
// selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
// then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to work out
// what the resulting combinator will be
$targetCombinator = $haystackElement->combinator;
if( $targetCombinator === '' && $hackstackElementIndex === 0 ){
$targetCombinator = ' ';
}
if( $needleElements[ $potentialMatch['matched'] ]->combinator !== $targetCombinator ){
return null;
}
}
// if we don't match, null our match to indicate failure
if( !$this->isElementValuesEqual( $needleElements[$potentialMatch['matched'] ]->value, $haystackElement->value) ){
return null;
}
$potentialMatch['finished'] = false;
$potentialMatch['matched']++;
return $potentialMatch;
}
private function isElementValuesEqual( $elementValue1, $elementValue2 ){
if( $elementValue1 === $elementValue2 ){
return true;
}
if( is_string($elementValue1) || is_string($elementValue2) ) {
return false;
}
if( $elementValue1 instanceof Less_Tree_Attribute ){
return $this->isAttributeValuesEqual( $elementValue1, $elementValue2 );
}
$elementValue1 = $elementValue1->value;
if( $elementValue1 instanceof Less_Tree_Selector ){
return $this->isSelectorValuesEqual( $elementValue1, $elementValue2 );
}
return false;
}
/**
* @param Less_Tree_Selector $elementValue1
*/
private function isSelectorValuesEqual( $elementValue1, $elementValue2 ){
$elementValue2 = $elementValue2->value;
if( !($elementValue2 instanceof Less_Tree_Selector) || $elementValue1->elements_len !== $elementValue2->elements_len ){
return false;
}
for( $i = 0; $i < $elementValue1->elements_len; $i++ ){
if( $elementValue1->elements[$i]->combinator !== $elementValue2->elements[$i]->combinator ){
if( $i !== 0 || ($elementValue1->elements[$i]->combinator || ' ') !== ($elementValue2->elements[$i]->combinator || ' ') ){
return false;
}
}
if( !$this->isElementValuesEqual($elementValue1->elements[$i]->value, $elementValue2->elements[$i]->value) ){
return false;
}
}
return true;
}
/**
* @param Less_Tree_Attribute $elementValue1
*/
private function isAttributeValuesEqual( $elementValue1, $elementValue2 ){
if( $elementValue1->op !== $elementValue2->op || $elementValue1->key !== $elementValue2->key ){
return false;
}
if( !$elementValue1->value || !$elementValue2->value ){
if( $elementValue1->value || $elementValue2->value ) {
return false;
}
return true;
}
$elementValue1 = ($elementValue1->value->value ? $elementValue1->value->value : $elementValue1->value );
$elementValue2 = ($elementValue2->value->value ? $elementValue2->value->value : $elementValue2->value );
return $elementValue1 === $elementValue2;
}
private function extendSelector($matches, $selectorPath, $replacementSelector){
//for a set of matches, replace each match with the replacement selector
$currentSelectorPathIndex = 0;
$currentSelectorPathElementIndex = 0;
$path = array();
$selectorPath_len = count($selectorPath);
for($matchIndex = 0, $matches_len = count($matches); $matchIndex < $matches_len; $matchIndex++ ){
$match = $matches[$matchIndex];
$selector = $selectorPath[ $match['pathIndex'] ];
$firstElement = new Less_Tree_Element(
$match['initialCombinator'],
$replacementSelector->elements[0]->value,
$replacementSelector->elements[0]->index,
$replacementSelector->elements[0]->currentFileInfo
);
if( $match['pathIndex'] > $currentSelectorPathIndex && $currentSelectorPathElementIndex > 0 ){
$last_path = end($path);
$last_path->elements = array_merge( $last_path->elements, array_slice( $selectorPath[$currentSelectorPathIndex]->elements, $currentSelectorPathElementIndex));
$currentSelectorPathElementIndex = 0;
$currentSelectorPathIndex++;
}
$newElements = array_merge(
array_slice($selector->elements, $currentSelectorPathElementIndex, ($match['index'] - $currentSelectorPathElementIndex) ) // last parameter of array_slice is different than the last parameter of javascript's slice
, array($firstElement)
, array_slice($replacementSelector->elements,1)
);
if( $currentSelectorPathIndex === $match['pathIndex'] && $matchIndex > 0 ){
$last_key = count($path)-1;
$path[$last_key]->elements = array_merge($path[$last_key]->elements,$newElements);
}else{
$path = array_merge( $path, array_slice( $selectorPath, $currentSelectorPathIndex, $match['pathIndex'] ));
$path[] = new Less_Tree_Selector( $newElements );
}
$currentSelectorPathIndex = $match['endPathIndex'];
$currentSelectorPathElementIndex = $match['endPathElementIndex'];
if( $currentSelectorPathElementIndex >= count($selectorPath[$currentSelectorPathIndex]->elements) ){
$currentSelectorPathElementIndex = 0;
$currentSelectorPathIndex++;
}
}
if( $currentSelectorPathIndex < $selectorPath_len && $currentSelectorPathElementIndex > 0 ){
$last_path = end($path);
$last_path->elements = array_merge( $last_path->elements, array_slice($selectorPath[$currentSelectorPathIndex]->elements, $currentSelectorPathElementIndex));
$currentSelectorPathIndex++;
}
$slice_len = $selectorPath_len - $currentSelectorPathIndex;
$path = array_merge($path, array_slice($selectorPath, $currentSelectorPathIndex, $slice_len));
return $path;
}
protected function visitMedia( $mediaNode ){
$newAllExtends = array_merge( $mediaNode->allExtends, end($this->allExtendsStack) );
$this->allExtendsStack[] = $this->doExtendChaining($newAllExtends, $mediaNode->allExtends);
}
protected function visitMediaOut(){
array_pop( $this->allExtendsStack );
}
protected function visitDirective( $directiveNode ){
$newAllExtends = array_merge( $directiveNode->allExtends, end($this->allExtendsStack) );
$this->allExtendsStack[] = $this->doExtendChaining($newAllExtends, $directiveNode->allExtends);
}
protected function visitDirectiveOut(){
array_pop($this->allExtendsStack);
}
}
/**
* toCSS Visitor
*
* @package Less
* @subpackage visitor
*/
class Less_Visitor_toCSS extends Less_VisitorReplacing{
private $charset;
public function __construct(){
parent::__construct();
}
/**
* @param Less_Tree_Ruleset $root
*/
public function run( $root ){
return $this->visitObj($root);
}
public function visitRule( $ruleNode ){
if( $ruleNode->variable ){
return array();
}
return $ruleNode;
}
public function visitMixinDefinition($mixinNode){
// mixin definitions do not get eval'd - this means they keep state
// so we have to clear that state here so it isn't used if toCSS is called twice
$mixinNode->frames = array();
return array();
}
public function visitExtend(){
return array();
}
public function visitComment( $commentNode ){
if( $commentNode->isSilent() ){
return array();
}
return $commentNode;
}
public function visitMedia( $mediaNode, &$visitDeeper ){
$mediaNode->accept($this);
$visitDeeper = false;
if( !$mediaNode->rules ){
return array();
}
return $mediaNode;
}
public function visitDirective( $directiveNode ){
if( isset($directiveNode->currentFileInfo['reference']) && (!property_exists($directiveNode,'isReferenced') || !$directiveNode->isReferenced) ){
return array();
}
if( $directiveNode->name === '@charset' ){
// Only output the debug info together with subsequent @charset definitions
// a comment (or @media statement) before the actual @charset directive would
// be considered illegal css as it has to be on the first line
if( isset($this->charset) && $this->charset ){
//if( $directiveNode->debugInfo ){
// $comment = new Less_Tree_Comment('/* ' . str_replace("\n",'',$directiveNode->toCSS())." */\n");
// $comment->debugInfo = $directiveNode->debugInfo;
// return $this->visit($comment);
//}
return array();
}
$this->charset = true;
}
return $directiveNode;
}
public function checkPropertiesInRoot( $rulesetNode ){
if( !$rulesetNode->firstRoot ){
return;
}
foreach($rulesetNode->rules as $ruleNode){
if( $ruleNode instanceof Less_Tree_Rule && !$ruleNode->variable ){
$msg = "properties must be inside selector blocks, they cannot be in the root. Index ".$ruleNode->index.($ruleNode->currentFileInfo ? (' Filename: '.$ruleNode->currentFileInfo['filename']) : null);
throw new Less_Exception_Compiler($msg);
}
}
}
public function visitRuleset( $rulesetNode, &$visitDeeper ){
$visitDeeper = false;
$this->checkPropertiesInRoot( $rulesetNode );
if( $rulesetNode->root ){
return $this->visitRulesetRoot( $rulesetNode );
}
$rulesets = array();
$rulesetNode->paths = $this->visitRulesetPaths($rulesetNode);
// Compile rules and rulesets
$nodeRuleCnt = count($rulesetNode->rules);
for( $i = 0; $i < $nodeRuleCnt; ){
$rule = $rulesetNode->rules[$i];
if( property_exists($rule,'rules') ){
// visit because we are moving them out from being a child
$rulesets[] = $this->visitObj($rule);
array_splice($rulesetNode->rules,$i,1);
$nodeRuleCnt--;
continue;
}
$i++;
}
// accept the visitor to remove rules and refactor itself
// then we can decide now whether we want it or not
if( $nodeRuleCnt > 0 ){
$rulesetNode->accept($this);
if( $rulesetNode->rules ){
if( count($rulesetNode->rules) > 1 ){
$this->_mergeRules( $rulesetNode->rules );
$this->_removeDuplicateRules( $rulesetNode->rules );
}
// now decide whether we keep the ruleset
if( $rulesetNode->paths ){
//array_unshift($rulesets, $rulesetNode);
array_splice($rulesets,0,0,array($rulesetNode));
}
}
}
if( count($rulesets) === 1 ){
return $rulesets[0];
}
return $rulesets;
}
/**
* Helper function for visitiRuleset
*
* return array|Less_Tree_Ruleset
*/
private function visitRulesetRoot( $rulesetNode ){
$rulesetNode->accept( $this );
if( $rulesetNode->firstRoot || $rulesetNode->rules ){
return $rulesetNode;
}
return array();
}
/**
* Helper function for visitRuleset()
*
* @return array
*/
private function visitRulesetPaths($rulesetNode){
$paths = array();
foreach($rulesetNode->paths as $p){
if( $p[0]->elements[0]->combinator === ' ' ){
$p[0]->elements[0]->combinator = '';
}
foreach($p as $pi){
if( $pi->getIsReferenced() && $pi->getIsOutput() ){
$paths[] = $p;
break;
}
}
}
return $paths;
}
protected function _removeDuplicateRules( &$rules ){
// remove duplicates
$ruleCache = array();
for( $i = count($rules)-1; $i >= 0 ; $i-- ){
$rule = $rules[$i];
if( $rule instanceof Less_Tree_Rule || $rule instanceof Less_Tree_NameValue ){
if( !isset($ruleCache[$rule->name]) ){
$ruleCache[$rule->name] = $rule;
}else{
$ruleList =& $ruleCache[$rule->name];
if( $ruleList instanceof Less_Tree_Rule || $ruleList instanceof Less_Tree_NameValue ){
$ruleList = $ruleCache[$rule->name] = array( $ruleCache[$rule->name]->toCSS() );
}
$ruleCSS = $rule->toCSS();
if( array_search($ruleCSS,$ruleList) !== false ){
array_splice($rules,$i,1);
}else{
$ruleList[] = $ruleCSS;
}
}
}
}
}
protected function _mergeRules( &$rules ){
$groups = array();
//obj($rules);
$rules_len = count($rules);
for( $i = 0; $i < $rules_len; $i++ ){
$rule = $rules[$i];
if( ($rule instanceof Less_Tree_Rule) && $rule->merge ){
$key = $rule->name;
if( $rule->important ){
$key .= ',!';
}
if( !isset($groups[$key]) ){
$groups[$key] = array();
}else{
array_splice($rules, $i--, 1);
$rules_len--;
}
$groups[$key][] = $rule;
}
}
foreach($groups as $parts){
if( count($parts) > 1 ){
$rule = $parts[0];
$spacedGroups = array();
$lastSpacedGroup = array();
$parts_mapped = array();
foreach($parts as $p){
if( $p->merge === '+' ){
if( $lastSpacedGroup ){
$spacedGroups[] = self::toExpression($lastSpacedGroup);
}
$lastSpacedGroup = array();
}
$lastSpacedGroup[] = $p;
}
$spacedGroups[] = self::toExpression($lastSpacedGroup);
$rule->value = self::toValue($spacedGroups);
}
}
}
public static function toExpression($values){
$mapped = array();
foreach($values as $p){
$mapped[] = $p->value;
}
return new Less_Tree_Expression( $mapped );
}
public static function toValue($values){
//return new Less_Tree_Value($values); ??
$mapped = array();
foreach($values as $p){
$mapped[] = $p;
}
return new Less_Tree_Value($mapped);
}
}
/**
* Parser Exception
*
* @package Less
* @subpackage exception
*/
class Less_Exception_Parser extends Exception{
/**
* The current file
*
* @var Less_ImportedFile
*/
public $currentFile;
/**
* The current parser index
*
* @var integer
*/
public $index;
protected $input;
protected $details = array();
/**
* Constructor
*
* @param string $message
* @param Exception $previous Previous exception
* @param integer $index The current parser index
* @param Less_FileInfo|string $currentFile The file
* @param integer $code The exception code
*/
public function __construct($message = null, Exception $previous = null, $index = null, $currentFile = null, $code = 0){
if (PHP_VERSION_ID < 50300) {
$this->previous = $previous;
parent::__construct($message, $code);
} else {
parent::__construct($message, $code, $previous);
}
$this->currentFile = $currentFile;
$this->index = $index;
$this->genMessage();
}
protected function getInput(){
if( !$this->input && $this->currentFile && $this->currentFile['filename'] && file_exists($this->currentFile['filename']) ){
$this->input = file_get_contents( $this->currentFile['filename'] );
}
}
/**
* Converts the exception to string
*
* @return string
*/
public function genMessage(){
if( $this->currentFile && $this->currentFile['filename'] ){
$this->message .= ' in '.basename($this->currentFile['filename']);
}
if( $this->index !== null ){
$this->getInput();
if( $this->input ){
$line = self::getLineNumber();
$this->message .= ' on line '.$line.', column '.self::getColumn();
$lines = explode("\n",$this->input);
$count = count($lines);
$start_line = max(0, $line-3);
$last_line = min($count, $start_line+6);
$num_len = strlen($last_line);
for( $i = $start_line; $i < $last_line; $i++ ){
$this->message .= "\n".str_pad($i+1,$num_len,'0',STR_PAD_LEFT).'| '.$lines[$i];
}
}
}
}
/**
* Returns the line number the error was encountered
*
* @return integer
*/
public function getLineNumber(){
if( $this->index ){
// https://bugs.php.net/bug.php?id=49790
if (ini_get("mbstring.func_overload")) {
return substr_count(substr($this->input, 0, $this->index), "\n") + 1;
} else {
return substr_count($this->input, "\n", 0, $this->index) + 1;
}
}
return 1;
}
/**
* Returns the column the error was encountered
*
* @return integer
*/
public function getColumn(){
$part = substr($this->input, 0, $this->index);
$pos = strrpos($part,"\n");
return $this->index - $pos;
}
}
/**
* Chunk Exception
*
* @package Less
* @subpackage exception
*/
class Less_Exception_Chunk extends Less_Exception_Parser{
protected $parserCurrentIndex = 0;
protected $emitFrom = 0;
protected $input_len;
/**
* Constructor
*
* @param string $input
* @param Exception $previous Previous exception
* @param integer $index The current parser index
* @param Less_FileInfo|string $currentFile The file
* @param integer $code The exception code
*/
public function __construct($input, Exception $previous = null, $index = null, $currentFile = null, $code = 0){
$this->message = 'ParseError: Unexpected input'; //default message
$this->index = $index;
$this->currentFile = $currentFile;
$this->input = $input;
$this->input_len = strlen($input);
$this->Chunks();
$this->genMessage();
}
/**
* See less.js chunks()
* We don't actually need the chunks
*
*/
protected function Chunks(){
$level = 0;
$parenLevel = 0;
$lastMultiCommentEndBrace = null;
$lastOpening = null;
$lastMultiComment = null;
$lastParen = null;
for( $this->parserCurrentIndex = 0; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++ ){
$cc = $this->CharCode($this->parserCurrentIndex);
if ((($cc >= 97) && ($cc <= 122)) || ($cc < 34)) {
// a-z or whitespace
continue;
}
switch ($cc) {
// (
case 40:
$parenLevel++;
$lastParen = $this->parserCurrentIndex;
continue;
// )
case 41:
$parenLevel--;
if( $parenLevel < 0 ){
return $this->fail("missing opening `(`");
}
continue;
// ;
case 59:
//if (!$parenLevel) { $this->emitChunk(); }
continue;
// {
case 123:
$level++;
$lastOpening = $this->parserCurrentIndex;
continue;
// }
case 125:
$level--;
if( $level < 0 ){
return $this->fail("missing opening `{`");
}
//if (!$level && !$parenLevel) { $this->emitChunk(); }
continue;
// \
case 92:
if ($this->parserCurrentIndex < $this->input_len - 1) { $this->parserCurrentIndex++; continue; }
return $this->fail("unescaped `\\`");
// ", ' and `
case 34:
case 39:
case 96:
$matched = 0;
$currentChunkStartIndex = $this->parserCurrentIndex;
for ($this->parserCurrentIndex = $this->parserCurrentIndex + 1; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++) {
$cc2 = $this->CharCode($this->parserCurrentIndex);
if ($cc2 > 96) { continue; }
if ($cc2 == $cc) { $matched = 1; break; }
if ($cc2 == 92) { // \
if ($this->parserCurrentIndex == $this->input_len - 1) {
return $this->fail("unescaped `\\`");
}
$this->parserCurrentIndex++;
}
}
if ($matched) { continue; }
return $this->fail("unmatched `" + chr($cc) + "`", $currentChunkStartIndex);
// /, check for comment
case 47:
if ($parenLevel || ($this->parserCurrentIndex == $this->input_len - 1)) { continue; }
$cc2 = $this->CharCode($this->parserCurrentIndex+1);
if ($cc2 == 47) {
// //, find lnfeed
for ($this->parserCurrentIndex = $this->parserCurrentIndex + 2; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++) {
$cc2 = $this->CharCode($this->parserCurrentIndex);
if (($cc2 <= 13) && (($cc2 == 10) || ($cc2 == 13))) { break; }
}
} else if ($cc2 == 42) {
// /*, find */
$lastMultiComment = $currentChunkStartIndex = $this->parserCurrentIndex;
for ($this->parserCurrentIndex = $this->parserCurrentIndex + 2; $this->parserCurrentIndex < $this->input_len - 1; $this->parserCurrentIndex++) {
$cc2 = $this->CharCode($this->parserCurrentIndex);
if ($cc2 == 125) { $lastMultiCommentEndBrace = $this->parserCurrentIndex; }
if ($cc2 != 42) { continue; }
if ($this->CharCode($this->parserCurrentIndex+1) == 47) { break; }
}
if ($this->parserCurrentIndex == $this->input_len - 1) {
return $this->fail("missing closing `*/`", $currentChunkStartIndex);
}
}
continue;
// *, check for unmatched */
case 42:
if (($this->parserCurrentIndex < $this->input_len - 1) && ($this->CharCode($this->parserCurrentIndex+1) == 47)) {
return $this->fail("unmatched `/*`");
}
continue;
}
}
if( $level !== 0 ){
if( ($lastMultiComment > $lastOpening) && ($lastMultiCommentEndBrace > $lastMultiComment) ){
return $this->fail("missing closing `}` or `*/`", $lastOpening);
} else {
return $this->fail("missing closing `}`", $lastOpening);
}
} else if ( $parenLevel !== 0 ){
return $this->fail("missing closing `)`", $lastParen);
}
//chunk didn't fail
//$this->emitChunk(true);
}
public function CharCode($pos){
return ord($this->input[$pos]);
}
public function fail( $msg, $index = null ){
if( !$index ){
$this->index = $this->parserCurrentIndex;
}else{
$this->index = $index;
}
$this->message = 'ParseError: '.$msg;
}
/*
function emitChunk( $force = false ){
$len = $this->parserCurrentIndex - $this->emitFrom;
if ((($len < 512) && !$force) || !$len) {
return;
}
$chunks[] = substr($this->input, $this->emitFrom, $this->parserCurrentIndex + 1 - $this->emitFrom );
$this->emitFrom = $this->parserCurrentIndex + 1;
}
*/
}
/**
* Compiler Exception
*
* @package Less
* @subpackage exception
*/
class Less_Exception_Compiler extends Less_Exception_Parser{
}
/**
* Parser output with source map
*
* @package Less
* @subpackage Output
*/
class Less_Output_Mapped extends Less_Output {
/**
* The source map generator
*
* @var Less_SourceMap_Generator
*/
protected $generator;
/**
* Current line
*
* @var integer
*/
protected $lineNumber = 0;
/**
* Current column
*
* @var integer
*/
protected $column = 0;
/**
* Array of contents map (file and its content)
*
* @var array
*/
protected $contentsMap = array();
/**
* Constructor
*
* @param array $contentsMap Array of filename to contents map
* @param Less_SourceMap_Generator $generator
*/
public function __construct(array $contentsMap, $generator){
$this->contentsMap = $contentsMap;
$this->generator = $generator;
}
/**
* Adds a chunk to the stack
* The $index for less.php may be different from less.js since less.php does not chunkify inputs
*
* @param string $chunk
* @param string $fileInfo
* @param integer $index
* @param mixed $mapLines
*/
public function add($chunk, $fileInfo = null, $index = 0, $mapLines = null){
//ignore adding empty strings
if( $chunk === '' ){
return;
}
$sourceLines = array();
$sourceColumns = ' ';
if( $fileInfo ){
$url = $fileInfo['currentUri'];
if( isset($this->contentsMap[$url]) ){
$inputSource = substr($this->contentsMap[$url], 0, $index);
$sourceLines = explode("\n", $inputSource);
$sourceColumns = end($sourceLines);
}else{
throw new Exception('Filename '.$url.' not in contentsMap');
}
}
$lines = explode("\n", $chunk);
$columns = end($lines);
if($fileInfo){
if(!$mapLines){
$this->generator->addMapping(
$this->lineNumber + 1, // generated_line
$this->column, // generated_column
count($sourceLines), // original_line
strlen($sourceColumns), // original_column
$fileInfo
);
}else{
for($i = 0, $count = count($lines); $i < $count; $i++){
$this->generator->addMapping(
$this->lineNumber + $i + 1, // generated_line
$i === 0 ? $this->column : 0, // generated_column
count($sourceLines) + $i, // original_line
$i === 0 ? strlen($sourceColumns) : 0, // original_column
$fileInfo
);
}
}
}
if(count($lines) === 1){
$this->column += strlen($columns);
}else{
$this->lineNumber += count($lines) - 1;
$this->column = strlen($columns);
}
// add only chunk
parent::add($chunk);
}
}
/**
* Encode / Decode Base64 VLQ.
*
* @package Less
* @subpackage SourceMap
*/
class Less_SourceMap_Base64VLQ {
/**
* Shift
*
* @var integer
*/
private $shift = 5;
/**
* Mask
*
* @var integer
*/
private $mask = 0x1F; // == (1 << shift) == 0b00011111
/**
* Continuation bit
*
* @var integer
*/
private $continuationBit = 0x20; // == (mask - 1 ) == 0b00100000
/**
* Char to integer map
*
* @var array
*/
private $charToIntMap = array(
'A' => 0, 'B' => 1, 'C' => 2, 'D' => 3, 'E' => 4, 'F' => 5, 'G' => 6,
'H' => 7,'I' => 8, 'J' => 9, 'K' => 10, 'L' => 11, 'M' => 12, 'N' => 13,
'O' => 14, 'P' => 15, 'Q' => 16, 'R' => 17, 'S' => 18, 'T' => 19, 'U' => 20,
'V' => 21, 'W' => 22, 'X' => 23, 'Y' => 24, 'Z' => 25, 'a' => 26, 'b' => 27,
'c' => 28, 'd' => 29, 'e' => 30, 'f' => 31, 'g' => 32, 'h' => 33, 'i' => 34,
'j' => 35, 'k' => 36, 'l' => 37, 'm' => 38, 'n' => 39, 'o' => 40, 'p' => 41,
'q' => 42, 'r' => 43, 's' => 44, 't' => 45, 'u' => 46, 'v' => 47, 'w' => 48,
'x' => 49, 'y' => 50, 'z' => 51, 0 => 52, 1 => 53, 2 => 54, 3 => 55, 4 => 56,
5 => 57, 6 => 58, 7 => 59, 8 => 60, 9 => 61, '+' => 62, '/' => 63,
);
/**
* Integer to char map
*
* @var array
*/
private $intToCharMap = array(
0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D', 4 => 'E', 5 => 'F', 6 => 'G',
7 => 'H', 8 => 'I', 9 => 'J', 10 => 'K', 11 => 'L', 12 => 'M', 13 => 'N',
14 => 'O', 15 => 'P', 16 => 'Q', 17 => 'R', 18 => 'S', 19 => 'T', 20 => 'U',
21 => 'V', 22 => 'W', 23 => 'X', 24 => 'Y', 25 => 'Z', 26 => 'a', 27 => 'b',
28 => 'c', 29 => 'd', 30 => 'e', 31 => 'f', 32 => 'g', 33 => 'h', 34 => 'i',
35 => 'j', 36 => 'k', 37 => 'l', 38 => 'm', 39 => 'n', 40 => 'o', 41 => 'p',
42 => 'q', 43 => 'r', 44 => 's', 45 => 't', 46 => 'u', 47 => 'v', 48 => 'w',
49 => 'x', 50 => 'y', 51 => 'z', 52 => '0', 53 => '1', 54 => '2', 55 => '3',
56 => '4', 57 => '5', 58 => '6', 59 => '7', 60 => '8', 61 => '9', 62 => '+',
63 => '/',
);
/**
* Constructor
*/
public function __construct(){
// I leave it here for future reference
// foreach(str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/') as $i => $char)
// {
// $this->charToIntMap[$char] = $i;
// $this->intToCharMap[$i] = $char;
// }
}
/**
* Convert from a two-complement value to a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
* We generate the value for 32 bit machines, hence -2147483648 becomes 1, not 4294967297,
* even on a 64 bit machine.
* @param string $aValue
*/
public function toVLQSigned($aValue){
return 0xffffffff & ($aValue < 0 ? ((-$aValue) << 1) + 1 : ($aValue << 1) + 0);
}
/**
* Convert to a two-complement value from a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
* We assume that the value was generated with a 32 bit machine in mind.
* Hence
* 1 becomes -2147483648
* even on a 64 bit machine.
* @param integer $aValue
*/
public function fromVLQSigned($aValue){
return $aValue & 1 ? $this->zeroFill(~$aValue + 2, 1) | (-1 - 0x7fffffff) : $this->zeroFill($aValue, 1);
}
/**
* Return the base 64 VLQ encoded value.
*
* @param string $aValue The value to encode
* @return string The encoded value
*/
public function encode($aValue){
$encoded = '';
$vlq = $this->toVLQSigned($aValue);
do
{
$digit = $vlq & $this->mask;
$vlq = $this->zeroFill($vlq, $this->shift);
if($vlq > 0){
$digit |= $this->continuationBit;
}
$encoded .= $this->base64Encode($digit);
} while($vlq > 0);
return $encoded;
}
/**
* Return the value decoded from base 64 VLQ.
*
* @param string $encoded The encoded value to decode
* @return integer The decoded value
*/
public function decode($encoded){
$vlq = 0;
$i = 0;
do
{
$digit = $this->base64Decode($encoded[$i]);
$vlq |= ($digit & $this->mask) << ($i * $this->shift);
$i++;
} while($digit & $this->continuationBit);
return $this->fromVLQSigned($vlq);
}
/**
* Right shift with zero fill.
*
* @param integer $a number to shift
* @param integer $b number of bits to shift
* @return integer
*/
public function zeroFill($a, $b){
return ($a >= 0) ? ($a >> $b) : ($a >> $b) & (PHP_INT_MAX >> ($b - 1));
}
/**
* Encode single 6-bit digit as base64.
*
* @param integer $number
* @return string
* @throws Exception If the number is invalid
*/
public function base64Encode($number){
if($number < 0 || $number > 63){
throw new Exception(sprintf('Invalid number "%s" given. Must be between 0 and 63.', $number));
}
return $this->intToCharMap[$number];
}
/**
* Decode single 6-bit digit from base64
*
* @param string $char
* @return number
* @throws Exception If the number is invalid
*/
public function base64Decode($char){
if(!array_key_exists($char, $this->charToIntMap)){
throw new Exception(sprintf('Invalid base 64 digit "%s" given.', $char));
}
return $this->charToIntMap[$char];
}
}
/**
* Source map generator
*
* @package Less
* @subpackage Output
*/
class Less_SourceMap_Generator extends Less_Configurable {
/**
* What version of source map does the generator generate?
*/
const VERSION = 3;
/**
* Array of default options
*
* @var array
*/
protected $defaultOptions = array(
// an optional source root, useful for relocating source files
// on a server or removing repeated values in the 'sources' entry.
// This value is prepended to the individual entries in the 'source' field.
'sourceRoot' => '',
// an optional name of the generated code that this source map is associated with.
'sourceMapFilename' => null,
// url of the map
'sourceMapURL' => null,
// absolute path to a file to write the map to
'sourceMapWriteTo' => null,
// output source contents?
'outputSourceFiles' => false,
// base path for filename normalization
'sourceMapRootpath' => '',
// base path for filename normalization
'sourceMapBasepath' => ''
);
/**
* The base64 VLQ encoder
*
* @var Less_SourceMap_Base64VLQ
*/
protected $encoder;
/**
* Array of mappings
*
* @var array
*/
protected $mappings = array();
/**
* The root node
*
* @var Less_Tree_Ruleset
*/
protected $root;
/**
* Array of contents map
*
* @var array
*/
protected $contentsMap = array();
/**
* File to content map
*
* @var array
*/
protected $sources = array();
protected $source_keys = array();
/**
* Constructor
*
* @param Less_Tree_Ruleset $root The root node
* @param array $options Array of options
*/
public function __construct(Less_Tree_Ruleset $root, $contentsMap, $options = array()){
$this->root = $root;
$this->contentsMap = $contentsMap;
$this->encoder = new Less_SourceMap_Base64VLQ();
$this->SetOptions($options);
// fix windows paths
if( !empty($this->options['sourceMapRootpath']) ){
$this->options['sourceMapRootpath'] = str_replace('\\', '/', $this->options['sourceMapRootpath']);
$this->options['sourceMapRootpath'] = rtrim($this->options['sourceMapRootpath'],'/').'/';
}
}
/**
* Generates the CSS
*
* @return string
*/
public function generateCSS(){
$output = new Less_Output_Mapped($this->contentsMap, $this);
// catch the output
$this->root->genCSS($output);
$sourceMapUrl = $this->getOption('sourceMapURL');
$sourceMapFilename = $this->getOption('sourceMapFilename');
$sourceMapContent = $this->generateJson();
$sourceMapWriteTo = $this->getOption('sourceMapWriteTo');
if( !$sourceMapUrl && $sourceMapFilename ){
$sourceMapUrl = $this->normalizeFilename($sourceMapFilename);
}
// write map to a file
if( $sourceMapWriteTo ){
$this->saveMap($sourceMapWriteTo, $sourceMapContent);
}
// inline the map
if( !$sourceMapUrl ){
$sourceMapUrl = sprintf('data:application/json,%s', Less_Functions::encodeURIComponent($sourceMapContent));
}
if( $sourceMapUrl ){
$output->add( sprintf('/*# sourceMappingURL=%s */', $sourceMapUrl) );
}
return $output->toString();
}
/**
* Saves the source map to a file
*
* @param string $file The absolute path to a file
* @param string $content The content to write
* @throws Exception If the file could not be saved
*/
protected function saveMap($file, $content){
$dir = dirname($file);
// directory does not exist
if( !is_dir($dir) ){
// FIXME: create the dir automatically?
throw new Exception(sprintf('The directory "%s" does not exist. Cannot save the source map.', $dir));
}
// FIXME: proper saving, with dir write check!
if(file_put_contents($file, $content) === false){
throw new Exception(sprintf('Cannot save the source map to "%s"', $file));
}
return true;
}
/**
* Normalizes the filename
*
* @param string $filename
* @return string
*/
protected function normalizeFilename($filename){
$filename = str_replace('\\', '/', $filename);
$rootpath = $this->getOption('sourceMapRootpath');
$basePath = $this->getOption('sourceMapBasepath');
// "Trim" the 'sourceMapBasepath' from the output filename.
if (strpos($filename, $basePath) === 0) {
$filename = substr($filename, strlen($basePath));
}
// Remove extra leading path separators.
if(strpos($filename, '\\') === 0 || strpos($filename, '/') === 0){
$filename = substr($filename, 1);
}
return $rootpath . $filename;
}
/**
* Adds a mapping
*
* @param integer $generatedLine The line number in generated file
* @param integer $generatedColumn The column number in generated file
* @param integer $originalLine The line number in original file
* @param integer $originalColumn The column number in original file
* @param string $sourceFile The original source file
*/
public function addMapping($generatedLine, $generatedColumn, $originalLine, $originalColumn, $fileInfo ){
$this->mappings[] = array(
'generated_line' => $generatedLine,
'generated_column' => $generatedColumn,
'original_line' => $originalLine,
'original_column' => $originalColumn,
'source_file' => $fileInfo['currentUri']
);
$this->sources[$fileInfo['currentUri']] = $fileInfo['filename'];
}
/**
* Generates the JSON source map
*
* @return string
* @see https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#
*/
protected function generateJson(){
$sourceMap = array();
$mappings = $this->generateMappings();
// File version (always the first entry in the object) and must be a positive integer.
$sourceMap['version'] = self::VERSION;
// An optional name of the generated code that this source map is associated with.
$file = $this->getOption('sourceMapFilename');
if( $file ){
$sourceMap['file'] = $file;
}
// An optional source root, useful for relocating source files on a server or removing repeated values in the 'sources' entry. This value is prepended to the individual entries in the 'source' field.
$root = $this->getOption('sourceRoot');
if( $root ){
$sourceMap['sourceRoot'] = $root;
}
// A list of original sources used by the 'mappings' entry.
$sourceMap['sources'] = array();
foreach($this->sources as $source_uri => $source_filename){
$sourceMap['sources'][] = $this->normalizeFilename($source_filename);
}
// A list of symbol names used by the 'mappings' entry.
$sourceMap['names'] = array();
// A string with the encoded mapping data.
$sourceMap['mappings'] = $mappings;
if( $this->getOption('outputSourceFiles') ){
// An optional list of source content, useful when the 'source' can't be hosted.
// The contents are listed in the same order as the sources above.
// 'null' may be used if some original sources should be retrieved by name.
$sourceMap['sourcesContent'] = $this->getSourcesContent();
}
// less.js compat fixes
if( count($sourceMap['sources']) && empty($sourceMap['sourceRoot']) ){
unset($sourceMap['sourceRoot']);
}
return json_encode($sourceMap);
}
/**
* Returns the sources contents
*
* @return array|null
*/
protected function getSourcesContent(){
if(empty($this->sources)){
return;
}
$content = array();
foreach($this->sources as $sourceFile){
$content[] = file_get_contents($sourceFile);
}
return $content;
}
/**
* Generates the mappings string
*
* @return string
*/
public function generateMappings(){
if( !count($this->mappings) ){
return '';
}
$this->source_keys = array_flip(array_keys($this->sources));
// group mappings by generated line number.
$groupedMap = $groupedMapEncoded = array();
foreach($this->mappings as $m){
$groupedMap[$m['generated_line']][] = $m;
}
ksort($groupedMap);
$lastGeneratedLine = $lastOriginalIndex = $lastOriginalLine = $lastOriginalColumn = 0;
foreach($groupedMap as $lineNumber => $line_map){
while(++$lastGeneratedLine < $lineNumber){
$groupedMapEncoded[] = ';';
}
$lineMapEncoded = array();
$lastGeneratedColumn = 0;
foreach($line_map as $m){
$mapEncoded = $this->encoder->encode($m['generated_column'] - $lastGeneratedColumn);
$lastGeneratedColumn = $m['generated_column'];
// find the index
if( $m['source_file'] ){
$index = $this->findFileIndex($m['source_file']);
if( $index !== false ){
$mapEncoded .= $this->encoder->encode($index - $lastOriginalIndex);
$lastOriginalIndex = $index;
// lines are stored 0-based in SourceMap spec version 3
$mapEncoded .= $this->encoder->encode($m['original_line'] - 1 - $lastOriginalLine);
$lastOriginalLine = $m['original_line'] - 1;
$mapEncoded .= $this->encoder->encode($m['original_column'] - $lastOriginalColumn);
$lastOriginalColumn = $m['original_column'];
}
}
$lineMapEncoded[] = $mapEncoded;
}
$groupedMapEncoded[] = implode(',', $lineMapEncoded) . ';';
}
return rtrim(implode($groupedMapEncoded), ';');
}
/**
* Finds the index for the filename
*
* @param string $filename
* @return integer|false
*/
protected function findFileIndex($filename){
return $this->source_keys[$filename];
}
}
|
netAction/foto-penz-theme
|
lib/less/Less.php
|
PHP
|
mit
| 260,105 |
require_relative 'concern/dereferenceable_shared'
require_relative 'concern/obligation_shared'
require_relative 'concern/observable_shared'
RSpec.shared_examples :ivar do
it_should_behave_like :obligation
it_should_behave_like :dereferenceable
it_should_behave_like :observable
context 'initialization' do
it 'sets the state to incomplete' do
expect(subject).to be_incomplete
end
end
context '#set' do
it 'sets the state to be fulfilled' do
subject.set(14)
expect(subject).to be_fulfilled
end
it 'sets the value' do
subject.set(14)
expect(subject.value).to eq 14
end
it 'raises an exception if set more than once' do
subject.set(14)
expect {subject.set(2)}.to raise_error(Concurrent::MultipleAssignmentError)
expect(subject.value).to eq 14
end
it 'returns self' do
expect(subject.set(42)).to eq subject
end
it 'fulfils when given a block which executes successfully' do
subject.set{ 42 }
expect(subject.value).to eq 42
end
it 'rejects when given a block which raises an exception' do
expected = ArgumentError.new
subject.set{ raise expected }
expect(subject.reason).to eq expected
end
it 'raises an exception when given a value and a block' do
expect {
subject.set(42){ :guide }
}.to raise_error(ArgumentError)
end
it 'raises an exception when given neither a value nor a block' do
expect {
subject.set
}.to raise_error(ArgumentError)
end
end
context '#fail' do
it 'sets the state to be rejected' do
subject.fail
expect(subject).to be_rejected
end
it 'sets the value to be nil' do
subject.fail
expect(subject.value).to be_nil
end
it 'sets the reason to the given exception' do
expected = ArgumentError.new
subject.fail(expected)
expect(subject.reason).to eq expected
end
it 'raises an exception if set more than once' do
subject.fail
expect {subject.fail}.to raise_error(Concurrent::MultipleAssignmentError)
expect(subject.value).to be_nil
end
it 'defaults the reason to a StandardError' do
subject.fail
expect(subject.reason).to be_a StandardError
end
it 'returns self' do
expect(subject.fail).to eq subject
end
end
describe '#try_set' do
context 'when unset' do
it 'assigns the value' do
subject.try_set(32)
expect(subject.value).to eq 32
end
it 'assigns the block result' do
subject.try_set{ 32 }
expect(subject.value).to eq 32
end
it 'returns true' do
expect(subject.try_set('hi')).to eq true
end
end
context 'when fulfilled' do
before(:each) { subject.set(27) }
it 'does not assign the value' do
subject.try_set(88)
expect(subject.value).to eq 27
end
it 'does not assign the block result' do
subject.try_set{ 88 }
expect(subject.value).to eq 27
end
it 'returns false' do
expect(subject.try_set('hello')).to eq false
end
end
context 'when rejected' do
before(:each) { subject.fail }
it 'does not assign the value' do
subject.try_set(88)
expect(subject).to be_rejected
end
it 'does not assign the block result' do
subject.try_set{ 88 }
expect(subject).to be_rejected
end
it 'has a nil value' do
expect(subject.value).to be_nil
end
it 'returns false' do
expect(subject.try_set('hello')).to eq false
end
end
end
end
|
lucasallan/concurrent-ruby
|
spec/concurrent/ivar_shared.rb
|
Ruby
|
mit
| 3,680 |
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
const common = require('../common');
const assert = require('assert');
const path = require('path');
const spawn = require('child_process').spawn;
const childPath = path.join(common.fixturesDir,
'parent-process-nonpersistent.js');
let persistentPid = -1;
const child = spawn(process.execPath, [ childPath ]);
child.stdout.on('data', function(data) {
persistentPid = parseInt(data, 10);
});
process.on('exit', function() {
assert.notStrictEqual(persistentPid, -1);
assert.throws(function() {
process.kill(child.pid);
}, /^Error: kill ESRCH$/);
assert.doesNotThrow(function() {
process.kill(persistentPid);
});
});
|
hoho/dosido
|
nodejs/test/parallel/test-child-process-detached.js
|
JavaScript
|
mit
| 1,813 |
require File.dirname(__FILE__) + '/helper'
describe "Middleware" do
before do
@app = mock_app(Sinatra::Default) {
get '/*' do
response.headers['X-Tests'] = env['test.ran'].
map { |n| n.split('::').last }.
join(', ')
env['PATH_INFO']
end
}
end
class MockMiddleware < Struct.new(:app)
def call(env)
(env['test.ran'] ||= []) << self.class.to_s
app.call(env)
end
end
class UpcaseMiddleware < MockMiddleware
def call(env)
env['PATH_INFO'] = env['PATH_INFO'].upcase
super
end
end
it "is added with Sinatra::Application.use" do
@app.use UpcaseMiddleware
get '/hello-world'
assert ok?
assert_equal '/HELLO-WORLD', body
end
class DowncaseMiddleware < MockMiddleware
def call(env)
env['PATH_INFO'] = env['PATH_INFO'].downcase
super
end
end
it "runs in the order defined" do
@app.use UpcaseMiddleware
@app.use DowncaseMiddleware
get '/Foo'
assert_equal "/foo", body
assert_equal "UpcaseMiddleware, DowncaseMiddleware", response['X-Tests']
end
it "resets the prebuilt pipeline when new middleware is added" do
@app.use UpcaseMiddleware
get '/Foo'
assert_equal "/FOO", body
@app.use DowncaseMiddleware
get '/Foo'
assert_equal '/foo', body
assert_equal "UpcaseMiddleware, DowncaseMiddleware", response['X-Tests']
end
it "works when app is used as middleware" do
@app.use UpcaseMiddleware
@app = @app.new
get '/Foo'
assert_equal "/FOO", body
assert_equal "UpcaseMiddleware", response['X-Tests']
end
end
|
mhawkins/wehaveengagedtheb.org
|
vendor/sinatra/test/middleware_test.rb
|
Ruby
|
mit
| 1,628 |
:host{background-color:#4E75E2;border:0;padding:6px 8px;margin:0;color:#fff;outline:0;font-size:16px;cursor:pointer}:host:hover{background-color:#2454d9}
|
manyvan2000/ptoc
|
src/client/app/modules/shared/components/button/button.component.css
|
CSS
|
mit
| 154 |
require File.dirname(__FILE__) + '/spec_helper'
describe YARD::Docstring do
before { YARD::Registry.clear }
describe '#initialize' do
it "should handle docstrings with empty newlines" do
Docstring.new("\n\n").should == ""
end
end
describe '#+' do
it "should add another Docstring" do
d = Docstring.new("FOO") + Docstring.new("BAR")
d.should == "FOO\nBAR"
end
it "should copy over tags" do
d1 = Docstring.new("FOO\n@api private\n")
d2 = Docstring.new("BAR\n@param foo descr")
d = (d1 + d2)
d.should have_tag(:api)
d.should have_tag(:param)
end
it "should add a String" do
d = Docstring.new("FOO") + "BAR"
d.should == "FOOBAR"
end
end
describe '#line' do
it "should return nil if #line_range is not set" do
Docstring.new('foo').line.should be_nil
end
it "should return line_range.first if #line_range is set" do
doc = Docstring.new('foo')
doc.line_range = (1..10)
doc.line.should == doc.line_range.first
end
end
describe '#summary' do
it "should handle empty docstrings" do
o1 = Docstring.new
o1.summary.should == ""
end
it "should handle multiple calls" do
o1 = Docstring.new("Hello. world")
5.times { o1.summary.should == "Hello." }
end
it "should return the first sentence" do
o = Docstring.new("DOCSTRING. Another sentence")
o.summary.should == "DOCSTRING."
end
it "should return the first paragraph" do
o = Docstring.new("DOCSTRING, and other stuff\n\nAnother sentence.")
o.summary.should == "DOCSTRING, and other stuff."
end
it "should return proper summary when docstring is changed" do
o = Docstring.new "DOCSTRING, and other stuff\n\nAnother sentence."
o.summary.should == "DOCSTRING, and other stuff."
o = Docstring.new "DOCSTRING."
o.summary.should == "DOCSTRING."
end
it "should not double the ending period" do
o = Docstring.new("Returns a list of tags specified by +name+ or all tags if +name+ is not specified.\n\nTest")
o.summary.should == "Returns a list of tags specified by +name+ or all tags if +name+ is not specified."
doc = Docstring.new(<<-eof)
Returns a list of tags specified by +name+ or all tags if +name+ is not specified.
@param name the tag name to return data for, or nil for all tags
@return [Array<Tags::Tag>] the list of tags by the specified tag name
eof
doc.summary.should == "Returns a list of tags specified by +name+ or all tags if +name+ is not specified."
end
it "should handle references embedded in summary" do
Docstring.new("Aliasing {Test.test}. Done.").summary.should == "Aliasing {Test.test}."
end
it "should only end first sentence when outside parentheses" do
Docstring.new("Hello (the best.) world. Foo bar.").summary.should == "Hello (the best.) world."
Docstring.new("A[b.]c.").summary.should == "A[b.]c."
end
it "should only see '.' as period if whitespace (or eof) follows" do
Docstring.new("hello 1.5 times.").summary.should == "hello 1.5 times."
Docstring.new("hello... me").summary.should == "hello..."
Docstring.new("hello.").summary.should == "hello."
end
end
describe '#ref_tags' do
it "should parse reference tag into ref_tags" do
doc = Docstring.new("@return (see Foo#bar)")
doc.ref_tags.size.should == 1
doc.ref_tags.first.owner.should == P("Foo#bar")
doc.ref_tags.first.tag_name.should == "return"
doc.ref_tags.first.name.should be_nil
end
it "should parse named reference tag into ref_tags" do
doc = Docstring.new("@param blah \n (see Foo#bar )")
doc.ref_tags.size.should == 1
doc.ref_tags.first.owner.should == P("Foo#bar")
doc.ref_tags.first.tag_name.should == "param"
doc.ref_tags.first.name.should == "blah"
end
it "should fail to parse named reference tag into ref_tags" do
doc = Docstring.new("@param blah THIS_BREAKS_REFTAG (see Foo#bar)")
doc.ref_tags.size.should == 0
end
it "should return all valid reference tags along with #tags" do
o = CodeObjects::MethodObject.new(:root, 'Foo#bar')
o.docstring.add_tag Tags::Tag.new('return', 'testing')
doc = Docstring.new("@return (see Foo#bar)")
tags = doc.tags
tags.size.should == 1
tags.first.text.should == 'testing'
tags.first.should be_kind_of(Tags::RefTag)
tags.first.owner.should == o
end
it "should return all valid named reference tags along with #tags(name)" do
o = CodeObjects::MethodObject.new(:root, 'Foo#bar')
o.docstring.add_tag Tags::Tag.new('param', 'testing', nil, '*args')
o.docstring.add_tag Tags::Tag.new('param', 'NOTtesting', nil, 'notargs')
doc = Docstring.new("@param *args (see Foo#bar)")
tags = doc.tags('param')
tags.size.should == 1
tags.first.text.should == 'testing'
tags.first.should be_kind_of(Tags::RefTag)
tags.first.owner.should == o
end
it "should ignore invalid reference tags" do
doc = Docstring.new("@param *args (see INVALID::TAG#tag)")
tags = doc.tags('param')
tags.size.should == 0
end
it "resolves references to methods in the same class with #methname" do
klass = CodeObjects::ClassObject.new(:root, "Foo")
o = CodeObjects::MethodObject.new(klass, "bar")
ref = CodeObjects::MethodObject.new(klass, "baz")
o.docstring.add_tag Tags::Tag.new('param', 'testing', nil, 'arg1')
ref.docstring = "@param (see #bar)"
tags = ref.docstring.tags("param")
tags.size.should == 1
tags.first.text.should == "testing"
tags.first.should be_kind_of(Tags::RefTag)
tags.first.owner.should == o
end
end
describe '#empty?/#blank?' do
before(:all) do
Tags::Library.define_tag "Invisible", :invisible_tag
end
it "should be blank and empty if it has no content and no tags" do
Docstring.new.should be_blank
Docstring.new.should be_empty
end
it "shouldn't be empty or blank if it has content" do
d = Docstring.new("foo bar")
d.should_not be_empty
d.should_not be_blank
end
it "should be empty but not blank if it has tags" do
d = Docstring.new("@param foo")
d.should be_empty
d.should_not be_blank
end
it "should be empty but not blank if it has ref tags" do
o = CodeObjects::MethodObject.new(:root, 'Foo#bar')
o.docstring.add_tag Tags::Tag.new('return', 'testing')
d = Docstring.new("@return (see Foo#bar)")
d.should be_empty
d.should_not be_blank
end
it "should be blank if it has no visible tags" do
d = Docstring.new("@invisible_tag value")
d.should be_blank
end
it "should not be blank if it has invisible tags and only_visible_tags = false" do
d = Docstring.new("@invisible_tag value")
d.add_tag Tags::Tag.new('invisible_tag', nil, nil)
d.blank?(false).should == false
end
end
describe '#add_tag' do
it "should only parse tags with charset [A-Za-z_]" do
doc = Docstring.new
valid = %w( @testing @valid @is_a @is_A @__ )
invalid = %w( @ @return@ @param, @x.y @x-y )
log.enter_level(Logger::FATAL) do
{valid => 1, invalid => 0}.each do |tags, size|
tags.each do |tag|
class << doc
def create_tag(tag_name, *args)
add_tag Tags::Tag.new(tag_name, *args)
end
end
doc.all = tag
doc.tags(tag[1..-1]).size.should == size
end
end
end
end
end
describe '#parse_comments' do
it "should parse comments into tags" do
doc = Docstring.new(<<-eof)
@param name Hello world
how are you?
@param name2
this is a new line
@param name3 and this
is a new paragraph:
right here.
eof
tags = doc.tags(:param)
tags[0].name.should == "name"
tags[0].text.should == "Hello world\nhow are you?"
tags[1].name.should == "name2"
tags[1].text.should == "this is a new line"
tags[2].name.should == "name3"
tags[2].text.should == "and this\nis a new paragraph:\n\nright here."
end
it "should end parsing a tag on de-dent" do
doc = Docstring.new(<<-eof)
@note test
one two three
rest of docstring
eof
doc.tag(:note).text.should == "test\none two three"
doc.should == "rest of docstring"
end
it "should parse examples embedded in doc" do
doc = Docstring.new(<<-eof)
test string here
@example code
def foo(x, y, z)
end
class A; end
more stuff
eof
doc.should == "test string here\nmore stuff"
doc.tag(:example).text.should == "\ndef foo(x, y, z)\nend\n\nclass A; end"
end
it "should remove only original indentation from beginning of line in tags" do
doc = Docstring.new(<<-eof)
@param name
some value
foo bar
baz
eof
doc.tag(:param).text.should == "some value\nfoo bar\n baz"
end
it "should allow numbers in tags" do
Tags::Library.define_tag(nil, :foo1)
Tags::Library.define_tag(nil, :foo2)
Tags::Library.define_tag(nil, :foo3)
doc = Docstring.new(<<-eof)
@foo1 bar1
@foo2 bar2
@foo3 bar3
eof
doc.tag(:foo1).text.should == "bar1"
doc.tag(:foo2).text.should == "bar2"
end
it "should end tag on newline if next line is not indented" do
doc = Docstring.new(<<-eof)
@author bar1
@api bar2
Hello world
eof
doc.tag(:author).text.should == "bar1"
doc.tag(:api).text.should == "bar2"
end
it "should warn about unknown tag" do
log.should_receive(:warn).with(/Unknown tag @hello$/)
Docstring.new("@hello world")
end
it "should not add trailing whitespace to freeform tags" do
doc = Docstring.new("@api private \t ")
doc.tag(:api).text.should == "private"
end
end
describe '#delete_tags' do
it "should delete tags by a given tag name" do
doc = Docstring.new("@param name x\n@param name2 y\n@return foo")
doc.delete_tags(:param)
doc.tags.size.should == 1
end
end
describe '#delete_tag_if' do
it "should delete tags for a given block" do
doc = Docstring.new("@param name x\n@param name2 y\n@return foo")
doc.delete_tag_if {|t| t.name == 'name2' }
doc.tags.size.should == 2
end
end
describe '#to_raw' do
it "should return a clean representation of tags" do
doc = Docstring.new("Hello world\n@return [String, X] foobar\n@param name<Array> the name\nBYE!")
doc.to_raw.should == "Hello world\nBYE!\n@param [Array] name\n the name\n@return [String, X] foobar"
end
it "should handle tags with newlines and indentation" do
doc = Docstring.new("@example TITLE\n the \n example\n @foo\n@param [X] name\n the name")
doc.to_raw.should == "@example TITLE\n the \n example\n @foo\n@param [X] name\n the name"
end
it "should handle deleted tags" do
doc = Docstring.new("@example TITLE\n the \n example\n @foo\n@param [X] name\n the name")
doc.delete_tags(:param)
doc.to_raw.should == "@example TITLE\n the \n example\n @foo"
end
it "should handle added tags" do
doc = Docstring.new("@example TITLE\n the \n example\n @foo")
doc.add_tag(Tags::Tag.new('foo', 'foo'))
doc.to_raw.should == "@example TITLE\n the \n example\n @foo\n@foo foo"
end
it "should be equal to .all if not modified" do
doc = Docstring.new("123\n@param")
doc.to_raw.should == doc.all
end
end
describe '#dup' do
it "should duplicate docstring text" do
doc = Docstring.new("foo")
doc.dup.should == doc
doc.dup.all.should == doc
end
it "should duplicate tags to new list" do
doc = Docstring.new("@param x\n@return y")
doc2 = doc.dup
doc2.delete_tags(:param)
doc.tags.size.should == 2
doc2.tags.size.should == 1
end
it "should preserve summary" do
doc = Docstring.new("foo. bar")
doc.dup.summary.should == doc.summary
end
it "should preserve hash_flag" do
doc = Docstring.new
doc.hash_flag = 'foo'
doc.dup.hash_flag.should == doc.hash_flag
end
it "should preserve line_range" do
doc = Docstring.new
doc.line_range = (1..2)
doc.dup.line_range.should == doc.line_range
end
end
end
|
sgerrand/yard
|
spec/docstring_spec.rb
|
Ruby
|
mit
| 12,681 |
package org.knowm.xchange.examples.dsx.marketdata;
import java.io.IOException;
import java.util.Map;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dsx.DSXExchange;
import org.knowm.xchange.dsx.dto.marketdata.DSXTrade;
import org.knowm.xchange.dsx.service.DSXMarketDataService;
import org.knowm.xchange.dto.marketdata.Trades;
import org.knowm.xchange.service.marketdata.MarketDataService;
/** @author Mikhail Wall */
public class DSXTradesDemo {
public static void main(String[] args) throws IOException {
Exchange dsx = ExchangeFactory.INSTANCE.createExchange(DSXExchange.class.getName());
generic(dsx);
raw(dsx);
}
private static void generic(Exchange exchange) throws IOException {
MarketDataService marketDataService = exchange.getMarketDataService();
Trades trades = marketDataService.getTrades(CurrencyPair.BTC_EUR);
System.out.println(trades.toString());
}
private static void raw(Exchange exchange) throws IOException {
DSXMarketDataService marketDataService = (DSXMarketDataService) exchange.getMarketDataService();
Map<String, DSXTrade[]> trades =
marketDataService.getDSXTrades("btcusd", 7, "LIVE").getTradesMap();
for (Map.Entry<String, DSXTrade[]> entry : trades.entrySet()) {
System.out.println("Pair: " + entry.getKey() + ", Trades:");
for (DSXTrade trade : entry.getValue()) {
System.out.println(trade.toString());
}
}
}
}
|
Panchen/XChange
|
xchange-examples/src/main/java/org/knowm/xchange/examples/dsx/marketdata/DSXTradesDemo.java
|
Java
|
mit
| 1,540 |
package org.robolectric.util;
import java.io.IOException;
import java.io.InputStream;
public class Strings {
public static String fromStream(InputStream inputStream) throws IOException {
int bufSize = 1028;
byte[] buffer = new byte[bufSize];
int inSize;
StringBuilder stringBuilder = new StringBuilder();
while ((inSize = inputStream.read(buffer)) > 0) {
stringBuilder.append(new String(buffer, 0, inSize));
}
return stringBuilder.toString();
}
public static boolean equals(String a, String b) {
if (a == null) {
return b == null;
}
return a.equals(b);
}
}
|
jeffreyzh/robolectric
|
src/main/java/org/robolectric/util/Strings.java
|
Java
|
mit
| 681 |
<?php
/**
* @package go\DB
*/
namespace go\DB\Exceptions;
/**
* Error: a pattern contain regular and named placeholders
*
* @author Oleg Grigoriev <[email protected]>
*/
final class MixedPlaceholder extends Placeholder
{
/**
* {@inheritdoc}
*/
protected $MESSAGE_PATTERN = 'Mixed placeholder "{{ placeholder }}"';
}
|
mundiir/kostylev
|
modules/goDB/Exceptions/MixedPlaceholder.php
|
PHP
|
mit
| 343 |
package router
import (
"github.com/micro/go-micro/registry"
router "github.com/micro/go-os/router/proto"
)
func values(v []*registry.Value) []*router.Value {
if len(v) == 0 {
return []*router.Value{}
}
var vs []*router.Value
for _, vi := range v {
vs = append(vs, &router.Value{
Name: vi.Name,
Type: vi.Type,
Values: values(vi.Values),
})
}
return vs
}
func toValues(v []*router.Value) []*registry.Value {
if len(v) == 0 {
return []*registry.Value{}
}
var vs []*registry.Value
for _, vi := range v {
vs = append(vs, ®istry.Value{
Name: vi.Name,
Type: vi.Type,
Values: toValues(vi.Values),
})
}
return vs
}
func serviceToProto(s *registry.Service) *router.Service {
if s == nil || len(s.Nodes) == 0 {
return nil
}
return &router.Service{
Name: s.Name,
Version: s.Version,
Metadata: s.Metadata,
Nodes: []*router.Node{&router.Node{
Id: s.Nodes[0].Id,
Address: s.Nodes[0].Address,
Port: int64(s.Nodes[0].Port),
Metadata: s.Nodes[0].Metadata,
}},
}
}
func protoToService(s *router.Service) *registry.Service {
var endpoints []*registry.Endpoint
for _, ep := range s.Endpoints {
var request, response *registry.Value
if ep.Request != nil {
request = ®istry.Value{
Name: ep.Request.Name,
Type: ep.Request.Type,
Values: toValues(ep.Request.Values),
}
}
if ep.Response != nil {
response = ®istry.Value{
Name: ep.Response.Name,
Type: ep.Response.Type,
Values: toValues(ep.Response.Values),
}
}
endpoints = append(endpoints, ®istry.Endpoint{
Name: ep.Name,
Request: request,
Response: response,
Metadata: ep.Metadata,
})
}
var nodes []*registry.Node
for _, node := range s.Nodes {
nodes = append(nodes, ®istry.Node{
Id: node.Id,
Address: node.Address,
Port: int(node.Port),
Metadata: node.Metadata,
})
}
return ®istry.Service{
Name: s.Name,
Version: s.Version,
Metadata: s.Metadata,
Endpoints: endpoints,
Nodes: nodes,
}
}
|
JermineHu/berk
|
vendor/github.com/micro/go-os/router/marshalling.go
|
GO
|
mit
| 2,071 |
import Template from '~/templates/Popmotion/LiveExamples/Template';
import {
Carousel,
Item,
AlignCenter
} from '~/templates/Popmotion/LiveExamples/styled';
import { styler, value, listen, pointer, decay, transform } from 'popmotion';
import posed from 'react-pose';
import styled from 'styled-components';
import { color } from '~/styles/vars';
const { interpolate } = transform;
const props = {
draggable: 'x',
passive: {
opacity: ['x', interpolate([-200, -100, 100, 200], [0, 1, 1, 0])]
}
};
const Box = styled(posed.div(props))`
width: 100px;
height: 100px;
background: ${color.blue};
border-radius: 50%;
transform: scaleX(0);
transform-origin: 50%;
color: white;
display: flex;
justify-content: center;
align-items: center;
font-weight: bold;
`;
const code = `// React, Vue & vanilla use Popmotion's functional pipelines
passive: {
opacity: ['x', interpolate(
[-200, -100, 100, 200],
[0, 1, 1, 0]
)]
}
// React Native uses React Animated's interpolate function
passive: {
opacity: ['x', {
inputRange: [-200, -100, 100, 200],
outputRange: [0, 1, 1, 0]
}]
}`;
class Example extends React.Component {
state = { isVisible: false };
componentDidMount() {
this.interval = setInterval(this.toggleVisibility, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
toggleVisibility = () => this.setState({ isVisible: !this.state.isVisible });
render() {
return <Box pose={this.state.isVisible ? 'open' : 'closed'}>Drag</Box>;
}
}
export default () => (
<Template code={code}>
<AlignCenter>
<Example />
</AlignCenter>
</Template>
);
|
InventingWithMonster/popmotion
|
packages/site/templates/Pose/USPs/PassiveExample.js
|
JavaScript
|
mit
| 1,656 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stop_Sign
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
// First Row
Console.WriteLine("{0}{1}{0}", new string('.', n + 1), new string('_', n * 2 + 1));
for (int i = 0, dots = n, downScores = n * 2 - 1; i < n; i++, dots--, downScores += 2)
{
Console.WriteLine("{0}//{1}\\\\{0}", new string('.', dots), new string('_', downScores));
}
// Middle
Console.WriteLine("//{0}STOP!{0}\\\\", new string('_', ((n * 2 - 1) + n * 2 - 5) / 2));
// Down Side
Console.WriteLine("\\\\{0}//", new string('_', (n * 2 - 1) + n * 2));
for (int i = 0, dots = 1, downScores = (n * 2 - 1) + n * 2 - 5 / 2; i < n - 1; dots++, downScores -= 2, i++)
{
Console.WriteLine("{0}\\\\{1}//{0}", new string('.', dots), new string('_', downScores));
}
// Last Row
}
}
}
|
Rusev12/Software-University-SoftUni
|
Programming Basics/Draw-with-Loops/Stop Sign/Program.cs
|
C#
|
mit
| 1,153 |
import INTERNAL_ATTRS from '../../../processing/dom/internal-attributes';
import nativeMethods from '../native-methods';
// NOTE: We should avoid using native object prototype methods,
// since they can be overriden by the client code. (GH-245)
var arraySlice = Array.prototype.slice;
function createInput (form) {
var hiddenInput = nativeMethods.createElement.call(document, 'input');
hiddenInput.type = 'hidden';
hiddenInput.name = INTERNAL_ATTRS.uploadInfoHiddenInputName;
hiddenInput.value = '[]';
nativeMethods.appendChild.call(form, hiddenInput);
return hiddenInput;
}
function getInput (form) {
var inputSelector = '[name="' + INTERNAL_ATTRS.uploadInfoHiddenInputName + '"]';
return nativeMethods.elementQuerySelector.call(form, inputSelector) || createInput(form);
}
function indexOf (info, input) {
for (var index = 0; index < info.length; index++) {
if (info[index].id === input.id || info[index].name === input.name)
return index;
}
return -1;
}
export function addInputInfo (input, fileList, value) {
var formInfo = getFormInfo(input);
if (formInfo) {
var files = [];
fileList = arraySlice.call(fileList);
for (var i = 0, len = fileList.length; i < len; i++) {
var file = fileList[i];
files.push({
name: file.name,
type: file.type,
data: file.base64
});
}
var inputInfoIndex = indexOf(formInfo, input);
var inputInfo = {
id: input.id,
name: input.name,
files: files,
value: value
};
if (inputInfoIndex === -1)
formInfo.push(inputInfo);
else
formInfo[inputInfoIndex] = inputInfo;
setFormInfo(input, formInfo);
}
}
export function getFormInfo (input) {
return input.form ? JSON.parse(getInput(input.form).value) : null;
}
export function setFormInfo (input, info) {
if (input.form) {
var hiddenInput = getInput(input.form);
hiddenInput.value = JSON.stringify(info);
}
}
export function removeInputInfo (input) {
var uploadInfo = getFormInfo(input);
if (uploadInfo) {
var inputInfoIndex = indexOf(uploadInfo, input);
if (inputInfoIndex !== -1) {
uploadInfo.splice(inputInfoIndex, 1);
setFormInfo(input, uploadInfo);
return true;
}
}
return false;
}
|
georgiy-abbasov/testcafe-hammerhead
|
src/client/sandbox/upload/hidden-info.js
|
JavaScript
|
mit
| 2,510 |
################################################################################
# Variables
################################################################################
slavedb = analytics-slave.eqiad.wmnet
enwiki = --defaults-file=~/.my.research.cnf -h s1-$(slavedb) -u research enwiki
dewiki = --defaults-file=~/.my.research.cnf -h s5-$(slavedb) -u research dewiki
eswiki = --defaults-file=~/.my.research.cnf -h s7-$(slavedb) -u research eswiki
ptwiki = --defaults-file=~/.my.research.cnf -h s2-$(slavedb) -u research ptwiki
plwiki = --defaults-file=~/.my.research.cnf -h s2-$(slavedb) -u research plwiki
frwiki = --defaults-file=~/.my.research.cnf -h s6-$(slavedb) -u research frwiki
ruwiki = --defaults-file=~/.my.research.cnf -h s6-$(slavedb) -u research ruwiki
staging = --defaults-file=~/.my.halfak.cnf -h db1047.eqiad.wmnet staging
.PHONY = datasets/monthly_user_counts.tsv \
datasets/sampled_newly_registered_users.tsv \
datasets/sampled_new_user_stats.tsv
################################################################################
########################### Aggregated datasets ################################
################################################################################
datasets/monthly_new_user_survival.tsv: sql/monthly_new_user_survival.sql \
datasets/staging/new_user_info.table \
datasets/staging/new_user_survival.table \
datasets/staging/new_user_revisions.table
cat sql/monthly_new_user_survival.sql | \
mysql $(staging) > \
datasets/monthly_new_user_survival.tsv
datasets/monthly_new_user_survival_groups.tsv: sql/monthly_new_user_survival_groups.sql \
datasets/staging/new_user_info.table \
datasets/staging/new_user_revisions.table \
datasets/staging/user_activity_months.table
cat sql/monthly_new_user_survival_groups.sql | \
mysql $(staging) > \
datasets/monthly_new_user_survival_groups.tsv
datasets/monthly_new_user_activity.tsv: sql/monthly_new_user_activity.sql \
datasets/staging/new_user_info.table \
datasets/staging/new_user_revisions.table
cat sql/monthly_new_user_activity.sql | \
mysql $(staging) > \
datasets/monthly_new_user_activity.tsv
datasets/sampled_newly_registered_users.tsv: datasets/staging/sampled_newly_registered_users.table
mysql $(staging) -e "SELECT * FROM sampled_newly_registered_users;" > \
datasets/sampled_newly_registered_users.tsv
datasets/sampled_new_user_stats.tsv: datasets/staging/sampled_new_user_stats.table
mysql $(staging) -e "SELECT * FROM sampled_new_user_stats;" > \
datasets/sampled_new_user_stats.tsv
################################################################################
############################# Create tables ####################################
################################################################################
datasets/staging/user_activity_months.table: sql/user_activity_months.create.sql
cat sql/user_activity_months.create.sql | \
mysql $(staging) > datasets/staging/user_activity_months.table
datasets/staging/new_user_survival.table: sql/new_user_survival.create.sql
cat sql/new_user_survival.create.sql | \
mysql $(staging) > datasets/staging/new_user_survival.table
datasets/staging/new_user_revisions.table: sql/new_user_revisions.create.sql
cat sql/new_user_revisions.create.sql | \
mysql $(staging) > datasets/staging/new_user_revisions.table
datasets/staging/new_user_info.table: sql/new_user_info.create.sql
cat sql/new_user_info.create.sql | \
mysql $(staging) > datasets/staging/new_user_info.table
datasets/staging/user_registration_type.table: sql/user_registration_type.create.sql
cat sql/user_registration_type.create.sql | \
mysql $(staging) > datasets/staging/user_registration_type.table
datasets/staging/user_registration_approx.table: sql/user_registration_approx.create.sql
cat sql/user_registration_approx.create.sql | \
mysql $(staging) > datasets/staging/user_registration_approx.table
datasets/staging/user_first_edit.table: sql/user_first_edit.create.sql
cat sql/user_first_edit.create.sql | \
mysql $(staging) > datasets/staging/user_first_edit.table
datasets/staging/sampled_newly_registered_users.table: sql/sampled_newly_registered_users.create.sql
cat sql/sampled_newly_registered_users.create.sql | \
mysql $(staging) > datasets/staging/sampled_newly_registered_users.table
datasets/staging/sampled_new_user_stats.table: sql/sampled_new_user_stats.create.sql
cat sql/sampled_new_user_stats.create.sql | \
mysql $(staging) > datasets/staging/sampled_new_user_stats.table
################################################################################
################################ Languages #####################################
################################################################################
#############
## English ##
################################################################################
####### user_activity_months
datasets/enwiki/user_activity_months.table: datasets/enwiki/user_activity_months.no_header.tsv \
datasets/staging/user_activity_months.table
mysql $(staging) -e "DELETE FROM user_activity_months WHERE wiki_db = 'enwiki';" && \
ln -s -f user_activity_months.no_header.tsv datasets/enwiki/user_activity_months && \
mysqlimport $(staging) --local datasets/enwiki/user_activity_months && \
rm -f datasets/enwiki/user_activity_months && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_activity_months WHERE wiki_db = 'enwiki';" > \
datasets/enwiki/user_activity_months.table
datasets/enwiki/user_activity_months.no_header.tsv: sql/user_activity_months.sql
cat sql/user_activity_months.sql | \
mysql $(enwiki) -N > \
datasets/enwiki/user_activity_months.no_header.tsv
####### new_user_survival
datasets/enwiki/new_user_survival.table: datasets/enwiki/new_user_survival.no_header.tsv \
datasets/staging/new_user_survival.table
mysql $(staging) -e "DELETE FROM new_user_survival WHERE wiki_db = 'enwiki';" && \
ln -s -f new_user_survival.no_header.tsv datasets/enwiki/new_user_survival && \
mysqlimport $(staging) --local datasets/enwiki/new_user_survival && \
rm -f datasets/enwiki/new_user_survival && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_survival WHERE wiki_db = 'enwiki';" > \
datasets/enwiki/new_user_survival.table
datasets/enwiki/new_user_survival.no_header.tsv: sql/new_user_survival.sql
cat sql/new_user_survival.sql | \
mysql $(enwiki) -N > \
datasets/enwiki/new_user_survival.no_header.tsv
####### new_user_revisions
datasets/enwiki/new_user_revisions.table: datasets/enwiki/new_user_revisions.no_header.tsv \
datasets/staging/new_user_revisions.table
mysql $(staging) -e "DELETE FROM new_user_revisions WHERE wiki_db = 'enwiki';" && \
ln -s -f new_user_revisions.no_header.tsv datasets/enwiki/new_user_revisions && \
mysqlimport $(staging) --local datasets/enwiki/new_user_revisions && \
rm -f datasets/enwiki/new_user_revisions && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_revisions WHERE wiki_db = 'enwiki';" > \
datasets/enwiki/new_user_revisions.table
datasets/enwiki/new_user_revisions.no_header.tsv: sql/new_user_revisions.sql
cat sql/new_user_revisions.sql | \
mysql $(enwiki) -N > \
datasets/enwiki/new_user_revisions.no_header.tsv
####### new_user_info
datasets/enwiki/new_user_info.table: datasets/enwiki/new_user_info.no_header.tsv \
datasets/staging/new_user_info.table
mysql $(staging) -e "DELETE FROM new_user_info WHERE wiki_db = 'enwiki';" && \
ln -s -f new_user_info.no_header.tsv datasets/enwiki/new_user_info && \
mysqlimport $(staging) --local datasets/enwiki/new_user_info && \
rm -f datasets/enwiki/new_user_info && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_info WHERE wiki_db = 'enwiki';" > \
datasets/enwiki/new_user_info.table
datasets/enwiki/new_user_info.no_header.tsv: sql/new_user_info.sql \
datasets/enwiki/user_registration_type.table \
datasets/enwiki/user_registration_approx.table
echo "SET @wiki_db = 'enwiki';" | \
cat - sql/new_user_info.sql | \
mysql $(staging) -N > \
datasets/enwiki/new_user_info.no_header.tsv
####### user_registration_type
datasets/enwiki/user_registration_type.table: datasets/enwiki/user_registration_type.no_header.tsv \
datasets/staging/user_registration_type.table
mysql $(staging) -e "DELETE FROM user_registration_type WHERE wiki_db = 'enwiki';" && \
ln -s -f user_registration_type.no_header.tsv datasets/enwiki/user_registration_type && \
mysqlimport $(staging) --local datasets/enwiki/user_registration_type && \
rm -f datasets/enwiki/user_registration_type && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_registration_type WHERE wiki_db = 'enwiki';" > \
datasets/enwiki/user_registration_type.table
datasets/enwiki/user_registration_type.no_header.tsv: sql/user_registration_type.sql
cat sql/user_registration_type.sql | \
mysql $(enwiki) -N > \
datasets/enwiki/user_registration_type.no_header.tsv
####### user_first_edit
datasets/enwiki/user_first_edit.table: datasets/enwiki/user_first_edit.no_header.tsv \
datasets/staging/user_first_edit.table
mysql $(staging) -e "DELETE FROM user_first_edit WHERE wiki_db = 'enwiki';" && \
ln -s -f user_first_edit.no_header.tsv datasets/enwiki/user_first_edit && \
mysqlimport $(staging) --local datasets/enwiki/user_first_edit && \
rm -f datasets/enwiki/user_first_edit && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_first_edit WHERE wiki_db = 'enwiki';" > \
datasets/enwiki/user_first_edit.table
datasets/enwiki/user_first_edit.no_header.tsv: sql/user_first_edit.sql
cat sql/user_first_edit.sql | \
mysql $(enwiki) -N > \
datasets/enwiki/user_first_edit.no_header.tsv
####### user_registration_approx
datasets/enwiki/user_registration_approx.table: datasets/enwiki/user_registration_approx.no_header.tsv \
datasets/enwiki/user_registration_type.table
mysql $(staging) -e "DELETE FROM user_registration_approx WHERE wiki_db = 'enwiki';" && \
ln -s -f user_registration_approx.no_header.tsv datasets/enwiki/user_registration_approx && \
mysqlimport $(staging) --local datasets/enwiki/user_registration_approx && \
rm -f datasets/enwiki/user_registration_approx && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_registration_approx WHERE wiki_db = 'enwiki';" > \
datasets/enwiki/user_registration_approx.table
datasets/enwiki/user_registration_approx.no_header.tsv: sql/old_user_registration_guess.sql \
datasets/enwiki/user_first_edit.table \
metrics/user_registration_approx.py
echo "SET @wiki_db = 'enwiki';" | \
cat - sql/old_user_registration_guess.sql | \
mysql $(staging) | \
./user_registration_approx --no-header > \
datasets/enwiki/user_registration_approx.no_header.tsv
####### sampled_newly_registered_users
datasets/enwiki/sampled_newly_registered_users.no_header.tsv: sql/sampled_newly_registered_users.sql \
datasets/enwiki/new_user_info.table
echo "SET @wiki_db = 'enwiki';" | \
cat - sql/sampled_newly_registered_users.sql | \
mysql $(staging) > \
datasets/enwiki/sampled_newly_registered_users.no_header.tsv
datasets/enwiki/sampled_newly_registered_users.table: datasets/enwiki/sampled_newly_registered_users.no_header.tsv \
datasets/staging/sampled_newly_registered_users.table
mysql $(staging) -e "DELETE FROM sampled_newly_registered_users WHERE wiki_db = 'enwiki';" && \
ln -s -f sampled_newly_registered_users.no_header.tsv datasets/enwiki/sampled_newly_registered_users && \
mysqlimport $(staging) --local datasets/enwiki/sampled_newly_registered_users && \
rm -f datasets/enwiki/sampled_newly_registered_users && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM sampled_newly_registered_users WHERE wiki_db = 'enwiki';" > \
datasets/enwiki/sampled_newly_registered_users.table
####### sampled_new_user_stats
datasets/enwiki/sampled_new_user_stats.no_header.tsv: datasets/enwiki/sampled_newly_registered_users.table \
metrics/new_user_stats.py
mysql $(staging) -e "SELECT * FROM sampled_newly_registered_users WHERE wiki_db = 'enwiki';" | \
./new_user_stats --no-headers > \
datasets/enwiki/sampled_new_user_stats.no_header.tsv
datasets/enwiki/sampled_new_user_stats.table: datasets/enwiki/sampled_new_user_stats.no_header.tsv \
datasets/staging/sampled_new_user_stats.table
mysql $(staging) -e "DELETE FROM sampled_new_user_stats WHERE wiki_db = 'enwiki';" && \
ln -s -f sampled_new_user_stats.no_header.tsv datasets/enwiki/sampled_new_user_stats && \
mysqlimport $(staging) --local datasets/enwiki/sampled_new_user_stats && \
rm -f datasets/enwiki/sampled_new_user_stats && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM sampled_new_user_stats WHERE wiki_db = 'enwiki';" > \
datasets/enwiki/sampled_new_user_stats.table
##########
## German ##
################################################################################
####### user_activity_months
datasets/dewiki/user_activity_months.table: datasets/dewiki/user_activity_months.no_header.tsv \
datasets/staging/user_activity_months.table
mysql $(staging) -e "DELETE FROM user_activity_months WHERE wiki_db = 'dewiki';" && \
ln -s -f user_activity_months.no_header.tsv datasets/dewiki/user_activity_months && \
mysqlimport $(staging) --local datasets/dewiki/user_activity_months && \
rm -f datasets/dewiki/user_activity_months && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_activity_months WHERE wiki_db = 'dewiki';" > \
datasets/dewiki/user_activity_months.table
datasets/dewiki/user_activity_months.no_header.tsv: sql/user_activity_months.sql
cat sql/user_activity_months.sql | \
mysql $(dewiki) -N > \
datasets/dewiki/user_activity_months.no_header.tsv
####### new_user_survival
datasets/dewiki/new_user_survival.table: datasets/dewiki/new_user_survival.no_header.tsv \
datasets/staging/new_user_survival.table
mysql $(staging) -e "DELETE FROM new_user_survival WHERE wiki_db = 'dewiki';" && \
ln -s -f new_user_survival.no_header.tsv datasets/dewiki/new_user_survival && \
mysqlimport $(staging) --local datasets/dewiki/new_user_survival && \
rm -f datasets/dewiki/new_user_survival && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_survival WHERE wiki_db = 'dewiki';" > \
datasets/dewiki/new_user_survival.table
datasets/dewiki/new_user_survival.no_header.tsv: sql/new_user_survival.sql
cat sql/new_user_survival.sql | \
mysql $(dewiki) -N > \
datasets/dewiki/new_user_survival.no_header.tsv
####### new_user_revisions
datasets/dewiki/new_user_revisions.table: datasets/dewiki/new_user_revisions.no_header.tsv \
datasets/staging/new_user_revisions.table
mysql $(staging) -e "DELETE FROM new_user_revisions WHERE wiki_db = 'dewiki';" && \
ln -s -f new_user_revisions.no_header.tsv datasets/dewiki/new_user_revisions && \
mysqlimport $(staging) --local datasets/dewiki/new_user_revisions && \
rm -f datasets/dewiki/new_user_revisions && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_revisions WHERE wiki_db = 'dewiki';" > \
datasets/dewiki/new_user_revisions.table
datasets/dewiki/new_user_revisions.no_header.tsv: sql/new_user_revisions.sql
cat sql/new_user_revisions.sql | \
mysql $(dewiki) -N > \
datasets/dewiki/new_user_revisions.no_header.tsv
####### new_user_info
datasets/dewiki/new_user_info.table: datasets/dewiki/new_user_info.no_header.tsv \
datasets/staging/new_user_info.table
mysql $(staging) -e "DELETE FROM new_user_info WHERE wiki_db = 'dewiki';" && \
ln -s -f new_user_info.no_header.tsv datasets/dewiki/new_user_info && \
mysqlimport $(staging) --local datasets/dewiki/new_user_info && \
rm -f datasets/dewiki/new_user_info && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_info WHERE wiki_db = 'dewiki';" > \
datasets/dewiki/new_user_info.table
datasets/dewiki/new_user_info.no_header.tsv: sql/new_user_info.sql \
datasets/dewiki/user_registration_type.table \
datasets/dewiki/user_registration_approx.table
echo "SET @wiki_db = 'dewiki';" | \
cat - sql/new_user_info.sql | \
mysql $(staging) -N > \
datasets/dewiki/new_user_info.no_header.tsv
####### user_registration_type
datasets/dewiki/user_registration_type.table: datasets/dewiki/user_registration_type.no_header.tsv \
datasets/staging/user_registration_type.table
mysql $(staging) -e "DELETE FROM user_registration_type WHERE wiki_db = 'dewiki';" && \
ln -s -f user_registration_type.no_header.tsv datasets/dewiki/user_registration_type && \
mysqlimport $(staging) --local datasets/dewiki/user_registration_type && \
rm -f datasets/dewiki/user_registration_type && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_registration_type WHERE wiki_db = 'dewiki';" > \
datasets/dewiki/user_registration_type.table
datasets/dewiki/user_registration_type.no_header.tsv: sql/user_registration_type.sql
cat sql/user_registration_type.sql | \
mysql $(dewiki) -N > \
datasets/dewiki/user_registration_type.no_header.tsv
####### user_first_edit
datasets/dewiki/user_first_edit.table: datasets/dewiki/user_first_edit.no_header.tsv \
datasets/staging/user_first_edit.table
mysql $(staging) -e "DELETE FROM user_first_edit WHERE wiki_db = 'dewiki';" && \
ln -s -f user_first_edit.no_header.tsv datasets/dewiki/user_first_edit && \
mysqlimport $(staging) --local datasets/dewiki/user_first_edit && \
rm -f datasets/dewiki/user_first_edit && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_first_edit WHERE wiki_db = 'dewiki';" > \
datasets/dewiki/user_first_edit.table
datasets/dewiki/user_first_edit.no_header.tsv: sql/user_first_edit.sql
cat sql/user_first_edit.sql | \
mysql $(dewiki) -N > \
datasets/dewiki/user_first_edit.no_header.tsv
####### user_registration_approx
datasets/dewiki/user_registration_approx.table: datasets/dewiki/user_registration_approx.no_header.tsv \
datasets/dewiki/user_registration_type.table
mysql $(staging) -e "DELETE FROM user_registration_approx WHERE wiki_db = 'dewiki';" && \
ln -s -f user_registration_approx.no_header.tsv datasets/dewiki/user_registration_approx && \
mysqlimport $(staging) --local datasets/dewiki/user_registration_approx && \
rm -f datasets/dewiki/user_registration_approx && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_registration_approx WHERE wiki_db = 'dewiki';" > \
datasets/dewiki/user_registration_approx.table
datasets/dewiki/user_registration_approx.no_header.tsv: sql/old_user_registration_guess.sql \
datasets/dewiki/user_first_edit.table
echo "SET @wiki_db = 'dewiki';" | \
cat - sql/old_user_registration_guess.sql | \
mysql $(staging) | \
./user_registration_approx --no-header > \
datasets/dewiki/user_registration_approx.no_header.tsv
####### sampled_newly_registered_users
datasets/dewiki/sampled_newly_registered_users.no_header.tsv: sql/sampled_newly_registered_users.sql \
datasets/dewiki/new_user_info.table
echo "SET @wiki_db = 'dewiki';" | \
cat - sql/sampled_newly_registered_users.sql | \
mysql $(staging) > \
datasets/dewiki/sampled_newly_registered_users.no_header.tsv
datasets/dewiki/sampled_newly_registered_users.table: datasets/dewiki/sampled_newly_registered_users.no_header.tsv \
datasets/staging/sampled_newly_registered_users.table
mysql $(staging) -e "DELETE FROM sampled_newly_registered_users WHERE wiki_db = 'dewiki';" && \
ln -s -f sampled_newly_registered_users.no_header.tsv datasets/dewiki/sampled_newly_registered_users && \
mysqlimport $(staging) --local datasets/dewiki/sampled_newly_registered_users && \
rm -f datasets/dewiki/sampled_newly_registered_users && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM sampled_newly_registered_users WHERE wiki_db = 'dewiki';" > \
datasets/dewiki/sampled_newly_registered_users.table
####### sampled_new_user_stats
datasets/dewiki/sampled_new_user_stats.no_header.tsv: datasets/dewiki/sampled_newly_registered_users.table \
metrics/new_user_stats.py
mysql $(staging) -e "SELECT * FROM sampled_newly_registered_users WHERE wiki_db = 'dewiki';" | \
./new_user_stats --no-headers -h s5-analytics-slave.eqiad.wmnet -d dewiki > \
datasets/dewiki/sampled_new_user_stats.no_header.tsv
datasets/dewiki/sampled_new_user_stats.table: datasets/dewiki/sampled_new_user_stats.no_header.tsv \
datasets/staging/sampled_new_user_stats.table
mysql $(staging) -e "DELETE FROM sampled_new_user_stats WHERE wiki_db = 'dewiki';" && \
ln -s -f sampled_new_user_stats.no_header.tsv datasets/dewiki/sampled_new_user_stats && \
mysqlimport $(staging) --local datasets/dewiki/sampled_new_user_stats && \
rm -f datasets/dewiki/sampled_new_user_stats && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM sampled_new_user_stats WHERE wiki_db = 'dewiki';" > \
datasets/dewiki/sampled_new_user_stats.table
##############
## Portuguese ##
################################################################################
####### user_activity_months
datasets/ptwiki/user_activity_months.table: datasets/ptwiki/user_activity_months.no_header.tsv \
datasets/staging/user_activity_months.table
mysql $(staging) -e "DELETE FROM user_activity_months WHERE wiki_db = 'ptwiki';" && \
ln -s -f user_activity_months.no_header.tsv datasets/ptwiki/user_activity_months && \
mysqlimport $(staging) --local datasets/ptwiki/user_activity_months && \
rm -f datasets/ptwiki/user_activity_months && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_activity_months WHERE wiki_db = 'ptwiki';" > \
datasets/ptwiki/user_activity_months.table
datasets/ptwiki/user_activity_months.no_header.tsv: sql/user_activity_months.sql
cat sql/user_activity_months.sql | \
mysql $(ptwiki) -N > \
datasets/ptwiki/user_activity_months.no_header.tsv
####### new_user_survival
datasets/ptwiki/new_user_survival.table: datasets/ptwiki/new_user_survival.no_header.tsv \
datasets/staging/new_user_survival.table
mysql $(staging) -e "DELETE FROM new_user_survival WHERE wiki_db = 'ptwiki';" && \
ln -s -f new_user_survival.no_header.tsv datasets/ptwiki/new_user_survival && \
mysqlimport $(staging) --local datasets/ptwiki/new_user_survival && \
rm -f datasets/ptwiki/new_user_survival && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_survival WHERE wiki_db = 'ptwiki';" > \
datasets/ptwiki/new_user_survival.table
datasets/ptwiki/new_user_survival.no_header.tsv: sql/new_user_survival.sql
cat sql/new_user_survival.sql | \
mysql $(ptwiki) -N > \
datasets/ptwiki/new_user_survival.no_header.tsv
####### new_user_revisions
datasets/ptwiki/new_user_revisions.table: datasets/ptwiki/new_user_revisions.no_header.tsv \
datasets/staging/new_user_revisions.table
mysql $(staging) -e "DELETE FROM new_user_revisions WHERE wiki_db = 'ptwiki';" && \
ln -s -f new_user_revisions.no_header.tsv datasets/ptwiki/new_user_revisions && \
mysqlimport $(staging) --local datasets/ptwiki/new_user_revisions && \
rm -f datasets/ptwiki/new_user_revisions && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_revisions WHERE wiki_db = 'ptwiki';" > \
datasets/ptwiki/new_user_revisions.table
datasets/ptwiki/new_user_revisions.no_header.tsv: sql/new_user_revisions.sql
cat sql/new_user_revisions.sql | \
mysql $(ptwiki) -N > \
datasets/ptwiki/new_user_revisions.no_header.tsv
####### new_user_info
datasets/ptwiki/new_user_info.table: datasets/ptwiki/new_user_info.no_header.tsv \
datasets/staging/new_user_info.table
mysql $(staging) -e "DELETE FROM new_user_info WHERE wiki_db = 'ptwiki';" && \
ln -s -f new_user_info.no_header.tsv datasets/ptwiki/new_user_info && \
mysqlimport $(staging) --local datasets/ptwiki/new_user_info && \
rm -f datasets/ptwiki/new_user_info && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_info WHERE wiki_db = 'ptwiki';" > \
datasets/ptwiki/new_user_info.table
datasets/ptwiki/new_user_info.no_header.tsv: sql/new_user_info.sql \
datasets/ptwiki/user_registration_type.table \
datasets/ptwiki/user_registration_approx.table
echo "SET @wiki_db = 'ptwiki';" | \
cat - sql/new_user_info.sql | \
mysql $(staging) -N > \
datasets/ptwiki/new_user_info.no_header.tsv
####### user_registration_type
datasets/ptwiki/user_registration_type.table: datasets/ptwiki/user_registration_type.no_header.tsv \
datasets/staging/user_registration_type.table
mysql $(staging) -e "DELETE FROM user_registration_type WHERE wiki_db = 'ptwiki';" && \
ln -s -f user_registration_type.no_header.tsv datasets/ptwiki/user_registration_type && \
mysqlimport $(staging) --local datasets/ptwiki/user_registration_type && \
rm -f datasets/ptwiki/user_registration_type && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_registration_type WHERE wiki_db = 'ptwiki';" > \
datasets/ptwiki/user_registration_type.table
datasets/ptwiki/user_registration_type.no_header.tsv: sql/user_registration_type.sql
cat sql/user_registration_type.sql | \
mysql $(ptwiki) -N > \
datasets/ptwiki/user_registration_type.no_header.tsv
####### user_first_edit
datasets/ptwiki/user_first_edit.table: datasets/ptwiki/user_first_edit.no_header.tsv \
datasets/staging/user_first_edit.table
mysql $(staging) -e "DELETE FROM user_first_edit WHERE wiki_db = 'ptwiki';" && \
ln -s -f user_first_edit.no_header.tsv datasets/ptwiki/user_first_edit && \
mysqlimport $(staging) --local datasets/ptwiki/user_first_edit && \
rm -f datasets/ptwiki/user_first_edit && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_first_edit WHERE wiki_db = 'ptwiki';" > \
datasets/ptwiki/user_first_edit.table
datasets/ptwiki/user_first_edit.no_header.tsv: sql/user_first_edit.sql
cat sql/user_first_edit.sql | \
mysql $(ptwiki) -N > \
datasets/ptwiki/user_first_edit.no_header.tsv
####### user_registration_approx
datasets/ptwiki/user_registration_approx.table: datasets/ptwiki/user_registration_approx.no_header.tsv \
datasets/ptwiki/user_registration_type.table
mysql $(staging) -e "DELETE FROM user_registration_approx WHERE wiki_db = 'ptwiki';" && \
ln -s -f user_registration_approx.no_header.tsv datasets/ptwiki/user_registration_approx && \
mysqlimport $(staging) --local datasets/ptwiki/user_registration_approx && \
rm -f datasets/ptwiki/user_registration_approx && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_registration_approx WHERE wiki_db = 'ptwiki';" > \
datasets/ptwiki/user_registration_approx.table
datasets/ptwiki/user_registration_approx.no_header.tsv: sql/old_user_registration_guess.sql \
datasets/ptwiki/user_first_edit.table
echo "SET @wiki_db = 'ptwiki';" | \
cat - sql/old_user_registration_guess.sql | \
mysql $(staging) | \
./user_registration_approx --no-header > \
datasets/ptwiki/user_registration_approx.no_header.tsv
####### sampled_newly_registered_users
datasets/ptwiki/sampled_newly_registered_users.no_header.tsv: sql/sampled_newly_registered_users.sql \
datasets/ptwiki/new_user_info.table
echo "SET @wiki_db = 'ptwiki';" | \
cat - sql/sampled_newly_registered_users.sql | \
mysql $(staging) > \
datasets/ptwiki/sampled_newly_registered_users.no_header.tsv
datasets/ptwiki/sampled_newly_registered_users.table: datasets/ptwiki/sampled_newly_registered_users.no_header.tsv \
datasets/staging/sampled_newly_registered_users.table
mysql $(staging) -e "DELETE FROM sampled_newly_registered_users WHERE wiki_db = 'ptwiki';" && \
ln -s -f sampled_newly_registered_users.no_header.tsv datasets/ptwiki/sampled_newly_registered_users && \
mysqlimport $(staging) --local datasets/ptwiki/sampled_newly_registered_users && \
rm -f datasets/ptwiki/sampled_newly_registered_users && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM sampled_newly_registered_users WHERE wiki_db = 'ptwiki';" > \
datasets/ptwiki/sampled_newly_registered_users.table
####### sampled_new_user_stats
datasets/ptwiki/sampled_new_user_stats.no_header.tsv: datasets/ptwiki/sampled_newly_registered_users.table \
metrics/new_user_stats.py
mysql $(staging) -e "SELECT * FROM sampled_newly_registered_users WHERE wiki_db = 'ptwiki';" | \
./new_user_stats --no-headers --defaults-file=~/.my.research.cnf -u research -h s2-analytics-slave.eqiad.wmnet -d ptwiki > \
datasets/ptwiki/sampled_new_user_stats.no_header.tsv
datasets/ptwiki/sampled_new_user_stats.table: datasets/ptwiki/sampled_new_user_stats.no_header.tsv \
datasets/staging/sampled_new_user_stats.table
mysql $(staging) -e "DELETE FROM sampled_new_user_stats WHERE wiki_db = 'ptwiki';" && \
ln -s -f sampled_new_user_stats.no_header.tsv datasets/ptwiki/sampled_new_user_stats && \
mysqlimport $(staging) --local datasets/ptwiki/sampled_new_user_stats && \
rm -f datasets/ptwiki/sampled_new_user_stats && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM sampled_new_user_stats WHERE wiki_db = 'ptwiki';" > \
datasets/ptwiki/sampled_new_user_stats.table
###########
## Spanish ##
################################################################################
####### user_activity_months
datasets/eswiki/user_activity_months.table: datasets/eswiki/user_activity_months.no_header.tsv \
datasets/staging/user_activity_months.table
mysql $(staging) -e "DELETE FROM user_activity_months WHERE wiki_db = 'eswiki';" && \
ln -s -f user_activity_months.no_header.tsv datasets/eswiki/user_activity_months && \
mysqlimport $(staging) --local datasets/eswiki/user_activity_months && \
rm -f datasets/eswiki/user_activity_months && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_activity_months WHERE wiki_db = 'eswiki';" > \
datasets/eswiki/user_activity_months.table
datasets/eswiki/user_activity_months.no_header.tsv: sql/user_activity_months.sql
cat sql/user_activity_months.sql | \
mysql $(eswiki) -N > \
datasets/eswiki/user_activity_months.no_header.tsv
####### new_user_survival
datasets/eswiki/new_user_survival.table: datasets/eswiki/new_user_survival.no_header.tsv \
datasets/staging/new_user_survival.table
mysql $(staging) -e "DELETE FROM new_user_survival WHERE wiki_db = 'eswiki';" && \
ln -s -f new_user_survival.no_header.tsv datasets/eswiki/new_user_survival && \
mysqlimport $(staging) --local datasets/eswiki/new_user_survival && \
rm -f datasets/eswiki/new_user_survival && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_survival WHERE wiki_db = 'eswiki';" > \
datasets/eswiki/new_user_survival.table
datasets/eswiki/new_user_survival.no_header.tsv: sql/new_user_survival.sql
cat sql/new_user_survival.sql | \
mysql $(eswiki) -N > \
datasets/eswiki/new_user_survival.no_header.tsv
####### new_user_revisions
datasets/eswiki/new_user_revisions.table: datasets/eswiki/new_user_revisions.no_header.tsv \
datasets/staging/new_user_revisions.table
mysql $(staging) -e "DELETE FROM new_user_revisions WHERE wiki_db = 'eswiki';" && \
ln -s -f new_user_revisions.no_header.tsv datasets/eswiki/new_user_revisions && \
mysqlimport $(staging) --local datasets/eswiki/new_user_revisions && \
rm -f datasets/eswiki/new_user_revisions && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_revisions WHERE wiki_db = 'eswiki';" > \
datasets/eswiki/new_user_revisions.table
datasets/eswiki/new_user_revisions.no_header.tsv: sql/new_user_revisions.sql
cat sql/new_user_revisions.sql | \
mysql $(eswiki) -N > \
datasets/eswiki/new_user_revisions.no_header.tsv
####### new_user_info
datasets/eswiki/new_user_info.table: datasets/eswiki/new_user_info.no_header.tsv \
datasets/staging/new_user_info.table
mysql $(staging) -e "DELETE FROM new_user_info WHERE wiki_db = 'eswiki';" && \
ln -s -f new_user_info.no_header.tsv datasets/eswiki/new_user_info && \
mysqlimport $(staging) --local datasets/eswiki/new_user_info && \
rm -f datasets/eswiki/new_user_info && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_info WHERE wiki_db = 'eswiki';" > \
datasets/eswiki/new_user_info.table
datasets/eswiki/new_user_info.no_header.tsv: sql/new_user_info.sql \
datasets/eswiki/user_registration_type.table \
datasets/eswiki/user_registration_approx.table
echo "SET @wiki_db = 'eswiki';" | \
cat - sql/new_user_info.sql | \
mysql $(staging) -N > \
datasets/eswiki/new_user_info.no_header.tsv
####### user_registration_type
datasets/eswiki/user_registration_type.table: datasets/eswiki/user_registration_type.no_header.tsv \
datasets/staging/user_registration_type.table
mysql $(staging) -e "DELETE FROM user_registration_type WHERE wiki_db = 'eswiki';" && \
ln -s -f user_registration_type.no_header.tsv datasets/eswiki/user_registration_type && \
mysqlimport $(staging) --local datasets/eswiki/user_registration_type && \
rm -f datasets/eswiki/user_registration_type && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_registration_type WHERE wiki_db = 'eswiki';" > \
datasets/eswiki/user_registration_type.table
datasets/eswiki/user_registration_type.no_header.tsv: sql/user_registration_type.sql
cat sql/user_registration_type.sql | \
mysql $(eswiki) -N > \
datasets/eswiki/user_registration_type.no_header.tsv
####### user_first_edit
datasets/eswiki/user_first_edit.table: datasets/eswiki/user_first_edit.no_header.tsv \
datasets/staging/user_first_edit.table
mysql $(staging) -e "DELETE FROM user_first_edit WHERE wiki_db = 'eswiki';" && \
ln -s -f user_first_edit.no_header.tsv datasets/eswiki/user_first_edit && \
mysqlimport $(staging) --local datasets/eswiki/user_first_edit && \
rm -f datasets/eswiki/user_first_edit && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_first_edit WHERE wiki_db = 'eswiki';" > \
datasets/eswiki/user_first_edit.table
datasets/eswiki/user_first_edit.no_header.tsv: sql/user_first_edit.sql
cat sql/user_first_edit.sql | \
mysql $(eswiki) -N > \
datasets/eswiki/user_first_edit.no_header.tsv
####### user_registration_approx
datasets/eswiki/user_registration_approx.table: datasets/eswiki/user_registration_approx.no_header.tsv \
datasets/eswiki/user_registration_type.table
mysql $(staging) -e "DELETE FROM user_registration_approx WHERE wiki_db = 'eswiki';" && \
ln -s -f user_registration_approx.no_header.tsv datasets/eswiki/user_registration_approx && \
mysqlimport $(staging) --local datasets/eswiki/user_registration_approx && \
rm -f datasets/eswiki/user_registration_approx && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_registration_approx WHERE wiki_db = 'eswiki';" > \
datasets/eswiki/user_registration_approx.table
datasets/eswiki/user_registration_approx.no_header.tsv: sql/old_user_registration_guess.sql \
datasets/eswiki/user_first_edit.table
echo "SET @wiki_db = 'eswiki';" | \
cat - sql/old_user_registration_guess.sql | \
mysql $(staging) | \
./user_registration_approx --no-header > \
datasets/eswiki/user_registration_approx.no_header.tsv
####### sampled_newly_registered_users
datasets/eswiki/sampled_newly_registered_users.no_header.tsv: sql/sampled_newly_registered_users.sql \
datasets/eswiki/new_user_info.table
echo "SET @wiki_db = 'eswiki';" | \
cat - sql/sampled_newly_registered_users.sql | \
mysql $(staging) > \
datasets/eswiki/sampled_newly_registered_users.no_header.tsv
datasets/eswiki/sampled_newly_registered_users.table: datasets/eswiki/sampled_newly_registered_users.no_header.tsv \
datasets/staging/sampled_newly_registered_users.table
mysql $(staging) -e "DELETE FROM sampled_newly_registered_users WHERE wiki_db = 'eswiki';" && \
ln -s -f sampled_newly_registered_users.no_header.tsv datasets/eswiki/sampled_newly_registered_users && \
mysqlimport $(staging) --local datasets/eswiki/sampled_newly_registered_users && \
rm -f datasets/eswiki/sampled_newly_registered_users && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM sampled_newly_registered_users WHERE wiki_db = 'eswiki';" > \
datasets/eswiki/sampled_newly_registered_users.table
####### sampled_new_user_stats
datasets/eswiki/sampled_new_user_stats.no_header.tsv: datasets/eswiki/sampled_newly_registered_users.table \
metrics/new_user_stats.py
mysql $(staging) -e "SELECT * FROM sampled_newly_registered_users WHERE wiki_db = 'eswiki';" | \
./new_user_stats --no-headers --defaults-file=~/.my.research.cnf -u research -h s7-analytics-slave.eqiad.wmnet -d eswiki > \
datasets/eswiki/sampled_new_user_stats.no_header.tsv
datasets/eswiki/sampled_new_user_stats.table: datasets/eswiki/sampled_new_user_stats.no_header.tsv \
datasets/staging/sampled_new_user_stats.table
mysql $(staging) -e "DELETE FROM sampled_new_user_stats WHERE wiki_db = 'eswiki';" && \
ln -s -f sampled_new_user_stats.no_header.tsv datasets/eswiki/sampled_new_user_stats && \
mysqlimport $(staging) --local datasets/eswiki/sampled_new_user_stats && \
rm -f datasets/eswiki/sampled_new_user_stats && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM sampled_new_user_stats WHERE wiki_db = 'eswiki';" > \
datasets/eswiki/sampled_new_user_stats.table
##########
## Polish ##
################################################################################
####### user_activity_months
datasets/plwiki/user_activity_months.table: datasets/plwiki/user_activity_months.no_header.tsv \
datasets/staging/user_activity_months.table
mysql $(staging) -e "DELETE FROM user_activity_months WHERE wiki_db = 'plwiki';" && \
ln -s -f user_activity_months.no_header.tsv datasets/plwiki/user_activity_months && \
mysqlimport $(staging) --local datasets/plwiki/user_activity_months && \
rm -f datasets/plwiki/user_activity_months && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_activity_months WHERE wiki_db = 'plwiki';" > \
datasets/plwiki/user_activity_months.table
datasets/plwiki/user_activity_months.no_header.tsv: sql/user_activity_months.sql
cat sql/user_activity_months.sql | \
mysql $(plwiki) -N > \
datasets/plwiki/user_activity_months.no_header.tsv
####### new_user_survival
datasets/plwiki/new_user_survival.table: datasets/plwiki/new_user_survival.no_header.tsv \
datasets/staging/new_user_survival.table
mysql $(staging) -e "DELETE FROM new_user_survival WHERE wiki_db = 'plwiki';" && \
ln -s -f new_user_survival.no_header.tsv datasets/plwiki/new_user_survival && \
mysqlimport $(staging) --local datasets/plwiki/new_user_survival && \
rm -f datasets/plwiki/new_user_survival && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_survival WHERE wiki_db = 'plwiki';" > \
datasets/plwiki/new_user_survival.table
datasets/plwiki/new_user_survival.no_header.tsv: sql/new_user_survival.sql
cat sql/new_user_survival.sql | \
mysql $(plwiki) -N > \
datasets/plwiki/new_user_survival.no_header.tsv
####### new_user_revisions
datasets/plwiki/new_user_revisions.table: datasets/plwiki/new_user_revisions.no_header.tsv \
datasets/staging/new_user_revisions.table
mysql $(staging) -e "DELETE FROM new_user_revisions WHERE wiki_db = 'plwiki';" && \
ln -s -f new_user_revisions.no_header.tsv datasets/plwiki/new_user_revisions && \
mysqlimport $(staging) --local datasets/plwiki/new_user_revisions && \
rm -f datasets/plwiki/new_user_revisions && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_revisions WHERE wiki_db = 'plwiki';" > \
datasets/plwiki/new_user_revisions.table
datasets/plwiki/new_user_revisions.no_header.tsv: sql/new_user_revisions.sql
cat sql/new_user_revisions.sql | \
mysql $(plwiki) -N > \
datasets/plwiki/new_user_revisions.no_header.tsv
####### new_user_info
datasets/plwiki/new_user_info.table: datasets/plwiki/new_user_info.no_header.tsv \
datasets/staging/new_user_info.table
mysql $(staging) -e "DELETE FROM new_user_info WHERE wiki_db = 'plwiki';" && \
ln -s -f new_user_info.no_header.tsv datasets/plwiki/new_user_info && \
mysqlimport $(staging) --local datasets/plwiki/new_user_info && \
rm -f datasets/plwiki/new_user_info && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_info WHERE wiki_db = 'plwiki';" > \
datasets/plwiki/new_user_info.table
datasets/plwiki/new_user_info.no_header.tsv: sql/new_user_info.sql \
datasets/plwiki/user_registration_type.table \
datasets/plwiki/user_registration_approx.table
echo "SET @wiki_db = 'plwiki';" | \
cat - sql/new_user_info.sql | \
mysql $(staging) -N > \
datasets/plwiki/new_user_info.no_header.tsv
####### user_registration_type
datasets/plwiki/user_registration_type.table: datasets/plwiki/user_registration_type.no_header.tsv \
datasets/staging/user_registration_type.table
mysql $(staging) -e "DELETE FROM user_registration_type WHERE wiki_db = 'plwiki';" && \
ln -s -f user_registration_type.no_header.tsv datasets/plwiki/user_registration_type && \
mysqlimport $(staging) --local datasets/plwiki/user_registration_type && \
rm -f datasets/plwiki/user_registration_type && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_registration_type WHERE wiki_db = 'plwiki';" > \
datasets/plwiki/user_registration_type.table
datasets/plwiki/user_registration_type.no_header.tsv: sql/user_registration_type.sql
cat sql/user_registration_type.sql | \
mysql $(plwiki) -N > \
datasets/plwiki/user_registration_type.no_header.tsv
####### user_first_edit
datasets/plwiki/user_first_edit.table: datasets/plwiki/user_first_edit.no_header.tsv \
datasets/staging/user_first_edit.table
mysql $(staging) -e "DELETE FROM user_first_edit WHERE wiki_db = 'plwiki';" && \
ln -s -f user_first_edit.no_header.tsv datasets/plwiki/user_first_edit && \
mysqlimport $(staging) --local datasets/plwiki/user_first_edit && \
rm -f datasets/plwiki/user_first_edit && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_first_edit WHERE wiki_db = 'plwiki';" > \
datasets/plwiki/user_first_edit.table
datasets/plwiki/user_first_edit.no_header.tsv: sql/user_first_edit.sql
cat sql/user_first_edit.sql | \
mysql $(plwiki) -N > \
datasets/plwiki/user_first_edit.no_header.tsv
####### user_registration_approx
datasets/plwiki/user_registration_approx.table: datasets/plwiki/user_registration_approx.no_header.tsv \
datasets/plwiki/user_registration_type.table
mysql $(staging) -e "DELETE FROM user_registration_approx WHERE wiki_db = 'plwiki';" && \
ln -s -f user_registration_approx.no_header.tsv datasets/plwiki/user_registration_approx && \
mysqlimport $(staging) --local datasets/plwiki/user_registration_approx && \
rm -f datasets/plwiki/user_registration_approx && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_registration_approx WHERE wiki_db = 'plwiki';" > \
datasets/plwiki/user_registration_approx.table
datasets/plwiki/user_registration_approx.no_header.tsv: sql/old_user_registration_guess.sql \
datasets/plwiki/user_first_edit.table
echo "SET @wiki_db = 'plwiki';" | \
cat - sql/old_user_registration_guess.sql | \
mysql $(staging) | \
./user_registration_approx --no-header > \
datasets/plwiki/user_registration_approx.no_header.tsv
####### sampled_newly_registered_users
datasets/plwiki/sampled_newly_registered_users.no_header.tsv: sql/sampled_newly_registered_users.sql \
datasets/plwiki/new_user_info.table
echo "SET @wiki_db = 'plwiki';" | \
cat - sql/sampled_newly_registered_users.sql | \
mysql $(staging) > \
datasets/plwiki/sampled_newly_registered_users.no_header.tsv
datasets/plwiki/sampled_newly_registered_users.table: datasets/plwiki/sampled_newly_registered_users.no_header.tsv \
datasets/staging/sampled_newly_registered_users.table
mysql $(staging) -e "DELETE FROM sampled_newly_registered_users WHERE wiki_db = 'plwiki';" && \
ln -s -f sampled_newly_registered_users.no_header.tsv datasets/plwiki/sampled_newly_registered_users && \
mysqlimport $(staging) --local datasets/plwiki/sampled_newly_registered_users && \
rm -f datasets/plwiki/sampled_newly_registered_users && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM sampled_newly_registered_users WHERE wiki_db = 'plwiki';" > \
datasets/plwiki/sampled_newly_registered_users.table
####### sampled_new_user_stats
datasets/plwiki/sampled_new_user_stats.no_header.tsv: datasets/plwiki/sampled_newly_registered_users.table \
metrics/new_user_stats.py
mysql $(staging) -e "SELECT * FROM sampled_newly_registered_users WHERE wiki_db = 'plwiki';" | \
./new_user_stats --no-headers --defaults-file=~/.my.research.cnf -u research -h s2-analytics-slave.eqiad.wmnet -d plwiki > \
datasets/plwiki/sampled_new_user_stats.no_header.tsv
datasets/plwiki/sampled_new_user_stats.table: datasets/plwiki/sampled_new_user_stats.no_header.tsv \
datasets/staging/sampled_new_user_stats.table
mysql $(staging) -e "DELETE FROM sampled_new_user_stats WHERE wiki_db = 'plwiki';" && \
ln -s -f sampled_new_user_stats.no_header.tsv datasets/plwiki/sampled_new_user_stats && \
mysqlimport $(staging) --local datasets/plwiki/sampled_new_user_stats && \
rm -f datasets/plwiki/sampled_new_user_stats && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM sampled_new_user_stats WHERE wiki_db = 'plwiki';" > \
datasets/plwiki/sampled_new_user_stats.table
##########
## French ##
################################################################################
####### user_activity_months
datasets/frwiki/user_activity_months.table: datasets/frwiki/user_activity_months.no_header.tsv \
datasets/staging/user_activity_months.table
mysql $(staging) -e "DELETE FROM user_activity_months WHERE wiki_db = 'frwiki';" && \
ln -s -f user_activity_months.no_header.tsv datasets/frwiki/user_activity_months && \
mysqlimport $(staging) --local datasets/frwiki/user_activity_months && \
rm -f datasets/frwiki/user_activity_months && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_activity_months WHERE wiki_db = 'frwiki';" > \
datasets/frwiki/user_activity_months.table
datasets/frwiki/user_activity_months.no_header.tsv: sql/user_activity_months.sql
cat sql/user_activity_months.sql | \
mysql $(frwiki) -N > \
datasets/frwiki/user_activity_months.no_header.tsv
####### new_user_survival
datasets/frwiki/new_user_survival.table: datasets/frwiki/new_user_survival.no_header.tsv \
datasets/staging/new_user_survival.table
mysql $(staging) -e "DELETE FROM new_user_survival WHERE wiki_db = 'frwiki';" && \
ln -s -f new_user_survival.no_header.tsv datasets/frwiki/new_user_survival && \
mysqlimport $(staging) --local datasets/frwiki/new_user_survival && \
rm -f datasets/frwiki/new_user_survival && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_survival WHERE wiki_db = 'frwiki';" > \
datasets/frwiki/new_user_survival.table
datasets/frwiki/new_user_survival.no_header.tsv: sql/new_user_survival.sql
cat sql/new_user_survival.sql | \
mysql $(frwiki) -N > \
datasets/frwiki/new_user_survival.no_header.tsv
####### new_user_revisions
datasets/frwiki/new_user_revisions.table: datasets/frwiki/new_user_revisions.no_header.tsv \
datasets/staging/new_user_revisions.table
mysql $(staging) -e "DELETE FROM new_user_revisions WHERE wiki_db = 'frwiki';" && \
ln -s -f new_user_revisions.no_header.tsv datasets/frwiki/new_user_revisions && \
mysqlimport $(staging) --local datasets/frwiki/new_user_revisions && \
rm -f datasets/frwiki/new_user_revisions && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_revisions WHERE wiki_db = 'frwiki';" > \
datasets/frwiki/new_user_revisions.table
datasets/frwiki/new_user_revisions.no_header.tsv: sql/new_user_revisions.sql
cat sql/new_user_revisions.sql | \
mysql $(frwiki) -N > \
datasets/frwiki/new_user_revisions.no_header.tsv
####### new_user_info
datasets/frwiki/new_user_info.table: datasets/frwiki/new_user_info.no_header.tsv \
datasets/staging/new_user_info.table
mysql $(staging) -e "DELETE FROM new_user_info WHERE wiki_db = 'frwiki';" && \
ln -s -f new_user_info.no_header.tsv datasets/frwiki/new_user_info && \
mysqlimport $(staging) --local datasets/frwiki/new_user_info && \
rm -f datasets/frwiki/new_user_info && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_info WHERE wiki_db = 'frwiki';" > \
datasets/frwiki/new_user_info.table
datasets/frwiki/new_user_info.no_header.tsv: sql/new_user_info.sql \
datasets/frwiki/user_registration_type.table \
datasets/frwiki/user_registration_approx.table
echo "SET @wiki_db = 'frwiki';" | \
cat - sql/new_user_info.sql | \
mysql $(staging) -N > \
datasets/frwiki/new_user_info.no_header.tsv
####### user_registration_type
datasets/frwiki/user_registration_type.table: datasets/frwiki/user_registration_type.no_header.tsv \
datasets/staging/user_registration_type.table
mysql $(staging) -e "DELETE FROM user_registration_type WHERE wiki_db = 'frwiki';" && \
ln -s -f user_registration_type.no_header.tsv datasets/frwiki/user_registration_type && \
mysqlimport $(staging) --local datasets/frwiki/user_registration_type && \
rm -f datasets/frwiki/user_registration_type && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_registration_type WHERE wiki_db = 'frwiki';" > \
datasets/frwiki/user_registration_type.table
datasets/frwiki/user_registration_type.no_header.tsv: sql/user_registration_type.sql
cat sql/user_registration_type.sql | \
mysql $(frwiki) -N > \
datasets/frwiki/user_registration_type.no_header.tsv
####### user_first_edit
datasets/frwiki/user_first_edit.table: datasets/frwiki/user_first_edit.no_header.tsv \
datasets/staging/user_first_edit.table
mysql $(staging) -e "DELETE FROM user_first_edit WHERE wiki_db = 'frwiki';" && \
ln -s -f user_first_edit.no_header.tsv datasets/frwiki/user_first_edit && \
mysqlimport $(staging) --local datasets/frwiki/user_first_edit && \
rm -f datasets/frwiki/user_first_edit && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_first_edit WHERE wiki_db = 'frwiki';" > \
datasets/frwiki/user_first_edit.table
datasets/frwiki/user_first_edit.no_header.tsv: sql/user_first_edit.sql
cat sql/user_first_edit.sql | \
mysql $(frwiki) -N > \
datasets/frwiki/user_first_edit.no_header.tsv
####### user_registration_approx
datasets/frwiki/user_registration_approx.table: datasets/frwiki/user_registration_approx.no_header.tsv \
datasets/frwiki/user_registration_type.table
mysql $(staging) -e "DELETE FROM user_registration_approx WHERE wiki_db = 'frwiki';" && \
ln -s -f user_registration_approx.no_header.tsv datasets/frwiki/user_registration_approx && \
mysqlimport $(staging) --local datasets/frwiki/user_registration_approx && \
rm -f datasets/frwiki/user_registration_approx && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_registration_approx WHERE wiki_db = 'frwiki';" > \
datasets/frwiki/user_registration_approx.table
datasets/frwiki/user_registration_approx.no_header.tsv: sql/old_user_registration_guess.sql \
datasets/frwiki/user_first_edit.table
echo "SET @wiki_db = 'frwiki';" | \
cat - sql/old_user_registration_guess.sql | \
mysql $(staging) | \
./user_registration_approx --no-header > \
datasets/frwiki/user_registration_approx.no_header.tsv
####### sampled_newly_registered_users
datasets/frwiki/sampled_newly_registered_users.no_header.tsv: sql/sampled_newly_registered_users.sql \
datasets/frwiki/new_user_info.table
echo "SET @wiki_db = 'frwiki';" | \
cat - sql/sampled_newly_registered_users.sql | \
mysql $(staging) > \
datasets/frwiki/sampled_newly_registered_users.no_header.tsv
datasets/frwiki/sampled_newly_registered_users.table: datasets/frwiki/sampled_newly_registered_users.no_header.tsv \
datasets/staging/sampled_newly_registered_users.table
mysql $(staging) -e "DELETE FROM sampled_newly_registered_users WHERE wiki_db = 'frwiki';" && \
ln -s -f sampled_newly_registered_users.no_header.tsv datasets/frwiki/sampled_newly_registered_users && \
mysqlimport $(staging) --local datasets/frwiki/sampled_newly_registered_users && \
rm -f datasets/frwiki/sampled_newly_registered_users && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM sampled_newly_registered_users WHERE wiki_db = 'frwiki';" > \
datasets/frwiki/sampled_newly_registered_users.table
####### sampled_new_user_stats
datasets/frwiki/sampled_new_user_stats.no_header.tsv: datasets/frwiki/sampled_newly_registered_users.table \
metrics/new_user_stats.py
mysql $(staging) -e "SELECT * FROM sampled_newly_registered_users WHERE wiki_db = 'frwiki';" | \
./new_user_stats --no-headers --defaults-file=~/.my.research.cnf -u research -h s6-analytics-slave.eqiad.wmnet -d frwiki > \
datasets/frwiki/sampled_new_user_stats.no_header.tsv
datasets/frwiki/sampled_new_user_stats.table: datasets/frwiki/sampled_new_user_stats.no_header.tsv \
datasets/staging/sampled_new_user_stats.table
mysql $(staging) -e "DELETE FROM sampled_new_user_stats WHERE wiki_db = 'frwiki';" && \
ln -s -f sampled_new_user_stats.no_header.tsv datasets/frwiki/sampled_new_user_stats && \
mysqlimport $(staging) --local datasets/frwiki/sampled_new_user_stats && \
rm -f datasets/frwiki/sampled_new_user_stats && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM sampled_new_user_stats WHERE wiki_db = 'frwiki';" > \
datasets/frwiki/sampled_new_user_stats.table
###########
## Russian ##
################################################################################
####### user_activity_months
datasets/ruwiki/user_activity_months.table: datasets/ruwiki/user_activity_months.no_header.tsv \
datasets/staging/user_activity_months.table
mysql $(staging) -e "DELETE FROM user_activity_months WHERE wiki_db = 'ruwiki';" && \
ln -s -f user_activity_months.no_header.tsv datasets/ruwiki/user_activity_months && \
mysqlimport $(staging) --local datasets/ruwiki/user_activity_months && \
rm -f datasets/ruwiki/user_activity_months && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_activity_months WHERE wiki_db = 'ruwiki';" > \
datasets/ruwiki/user_activity_months.table
datasets/ruwiki/user_activity_months.no_header.tsv: sql/user_activity_months.sql
cat sql/user_activity_months.sql | \
mysql $(ruwiki) -N > \
datasets/ruwiki/user_activity_months.no_header.tsv
####### new_user_survival
datasets/ruwiki/new_user_survival.table: datasets/ruwiki/new_user_survival.no_header.tsv \
datasets/staging/new_user_survival.table
mysql $(staging) -e "DELETE FROM new_user_survival WHERE wiki_db = 'ruwiki';" && \
ln -s -f new_user_survival.no_header.tsv datasets/ruwiki/new_user_survival && \
mysqlimport $(staging) --local datasets/ruwiki/new_user_survival && \
rm -f datasets/ruwiki/new_user_survival && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_survival WHERE wiki_db = 'ruwiki';" > \
datasets/ruwiki/new_user_survival.table
datasets/ruwiki/new_user_survival.no_header.tsv: sql/new_user_survival.sql
cat sql/new_user_survival.sql | \
mysql $(ruwiki) -N > \
datasets/ruwiki/new_user_survival.no_header.tsv
####### new_user_revisions
datasets/ruwiki/new_user_revisions.table: datasets/ruwiki/new_user_revisions.no_header.tsv \
datasets/staging/new_user_revisions.table
mysql $(staging) -e "DELETE FROM new_user_revisions WHERE wiki_db = 'ruwiki';" && \
ln -s -f new_user_revisions.no_header.tsv datasets/ruwiki/new_user_revisions && \
mysqlimport $(staging) --local datasets/ruwiki/new_user_revisions && \
rm -f datasets/ruwiki/new_user_revisions && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_revisions WHERE wiki_db = 'ruwiki';" > \
datasets/ruwiki/new_user_revisions.table
datasets/ruwiki/new_user_revisions.no_header.tsv: sql/new_user_revisions.sql
cat sql/new_user_revisions.sql | \
mysql $(ruwiki) -N > \
datasets/ruwiki/new_user_revisions.no_header.tsv
####### new_user_info
datasets/ruwiki/new_user_info.table: datasets/ruwiki/new_user_info.no_header.tsv \
datasets/staging/new_user_info.table
mysql $(staging) -e "DELETE FROM new_user_info WHERE wiki_db = 'ruwiki';" && \
ln -s -f new_user_info.no_header.tsv datasets/ruwiki/new_user_info && \
mysqlimport $(staging) --local datasets/ruwiki/new_user_info && \
rm -f datasets/ruwiki/new_user_info && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM new_user_info WHERE wiki_db = 'ruwiki';" > \
datasets/ruwiki/new_user_info.table
datasets/ruwiki/new_user_info.no_header.tsv: sql/new_user_info.sql \
datasets/ruwiki/user_registration_type.table \
datasets/ruwiki/user_registration_approx.table
echo "SET @wiki_db = 'ruwiki';" | \
cat - sql/new_user_info.sql | \
mysql $(staging) -N > \
datasets/ruwiki/new_user_info.no_header.tsv
####### user_registration_type
datasets/ruwiki/user_registration_type.table: datasets/ruwiki/user_registration_type.no_header.tsv \
datasets/staging/user_registration_type.table
mysql $(staging) -e "DELETE FROM user_registration_type WHERE wiki_db = 'ruwiki';" && \
ln -s -f user_registration_type.no_header.tsv datasets/ruwiki/user_registration_type && \
mysqlimport $(staging) --local datasets/ruwiki/user_registration_type && \
rm -f datasets/ruwiki/user_registration_type && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_registration_type WHERE wiki_db = 'ruwiki';" > \
datasets/ruwiki/user_registration_type.table
datasets/ruwiki/user_registration_type.no_header.tsv: sql/user_registration_type.sql
cat sql/user_registration_type.sql | \
mysql $(ruwiki) -N > \
datasets/ruwiki/user_registration_type.no_header.tsv
####### user_first_edit
datasets/ruwiki/user_first_edit.table: datasets/ruwiki/user_first_edit.no_header.tsv \
datasets/staging/user_first_edit.table
mysql $(staging) -e "DELETE FROM user_first_edit WHERE wiki_db = 'ruwiki';" && \
ln -s -f user_first_edit.no_header.tsv datasets/ruwiki/user_first_edit && \
mysqlimport $(staging) --local datasets/ruwiki/user_first_edit && \
rm -f datasets/ruwiki/user_first_edit && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_first_edit WHERE wiki_db = 'ruwiki';" > \
datasets/ruwiki/user_first_edit.table
datasets/ruwiki/user_first_edit.no_header.tsv: sql/user_first_edit.sql
cat sql/user_first_edit.sql | \
mysql $(ruwiki) -N > \
datasets/ruwiki/user_first_edit.no_header.tsv
####### user_registration_approx
datasets/ruwiki/user_registration_approx.table: datasets/ruwiki/user_registration_approx.no_header.tsv \
datasets/ruwiki/user_registration_type.table
mysql $(staging) -e "DELETE FROM user_registration_approx WHERE wiki_db = 'ruwiki';" && \
ln -s -f user_registration_approx.no_header.tsv datasets/ruwiki/user_registration_approx && \
mysqlimport $(staging) --local datasets/ruwiki/user_registration_approx && \
rm -f datasets/ruwiki/user_registration_approx && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM user_registration_approx WHERE wiki_db = 'ruwiki';" > \
datasets/ruwiki/user_registration_approx.table
datasets/ruwiki/user_registration_approx.no_header.tsv: sql/old_user_registration_guess.sql \
datasets/ruwiki/user_first_edit.table
echo "SET @wiki_db = 'ruwiki';" | \
cat - sql/old_user_registration_guess.sql | \
mysql $(staging) | \
./user_registration_approx --no-header > \
datasets/ruwiki/user_registration_approx.no_header.tsv
####### sampled_newly_registered_users
datasets/ruwiki/sampled_newly_registered_users.no_header.tsv: sql/sampled_newly_registered_users.sql \
datasets/ruwiki/new_user_info.table
echo "SET @wiki_db = 'ruwiki';" | \
cat - sql/sampled_newly_registered_users.sql | \
mysql $(staging) > \
datasets/ruwiki/sampled_newly_registered_users.no_header.tsv
datasets/ruwiki/sampled_newly_registered_users.table: datasets/ruwiki/sampled_newly_registered_users.no_header.tsv \
datasets/staging/sampled_newly_registered_users.table
mysql $(staging) -e "DELETE FROM sampled_newly_registered_users WHERE wiki_db = 'ruwiki';" && \
ln -s -f sampled_newly_registered_users.no_header.tsv datasets/ruwiki/sampled_newly_registered_users && \
mysqlimport $(staging) --local datasets/ruwiki/sampled_newly_registered_users && \
rm -f datasets/ruwiki/sampled_newly_registered_users && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM sampled_newly_registered_users WHERE wiki_db = 'ruwiki';" > \
datasets/ruwiki/sampled_newly_registered_users.table
####### sampled_new_user_stats
datasets/ruwiki/sampled_new_user_stats.no_header.tsv: datasets/ruwiki/sampled_newly_registered_users.table \
metrics/new_user_stats.py
mysql $(staging) -e "SELECT * FROM sampled_newly_registered_users WHERE wiki_db = 'ruwiki';" | \
./new_user_stats --no-headers --defaults-file=~/.my.research.cnf -u research -h s6-analytics-slave.eqiad.wmnet -d ruwiki > \
datasets/ruwiki/sampled_new_user_stats.no_header.tsv
datasets/ruwiki/sampled_new_user_stats.table: datasets/ruwiki/sampled_new_user_stats.no_header.tsv \
datasets/staging/sampled_new_user_stats.table
mysql $(staging) -e "DELETE FROM sampled_new_user_stats WHERE wiki_db = 'ruwiki';" && \
ln -s -f sampled_new_user_stats.no_header.tsv datasets/ruwiki/sampled_new_user_stats && \
mysqlimport $(staging) --local datasets/ruwiki/sampled_new_user_stats && \
rm -f datasets/ruwiki/sampled_new_user_stats && \
mysql $(staging) -e "SELECT COUNT(*), NOW() FROM sampled_new_user_stats WHERE wiki_db = 'ruwiki';" > \
datasets/ruwiki/sampled_new_user_stats.table
|
halfak/mwmetrics
|
Makefile
|
Makefile
|
mit
| 65,884 |
<?php
/**
* @package hubzero-cms
* @copyright Copyright 2005-2019 HUBzero Foundation, LLC.
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Components\Wishlist\Models;
use Hubzero\Database\Relational;
use Request;
use User;
use Lang;
use Date;
/**
* Wishlist model class for a vote
*/
class Vote extends Relational
{
/**
* The table namespace
*
* @var string
*/
protected $namespace = 'vote';
/**
* The table to which the class pertains
*
* This will default to #__{namespace}_{modelName} unless otherwise
* overwritten by a given subclass. Definition of this property likely
* indicates some derivation from standard naming conventions.
*
* @var string
**/
protected $table = '#__vote_log';
/**
* Default order by for model
*
* @var string
*/
public $orderBy = 'id';
/**
* Default order direction for select queries
*
* @var string
*/
public $orderDir = 'asc';
/**
* Fields and their validation criteria
*
* @var array
*/
protected $rules = array(
'referenceid' => 'positive|nonzero',
'category' => 'notempty'
);
/**
* Automatic fields to populate every time a row is created
*
* @var array
*/
public $initiate = array(
'voted',
'voter',
'ip'
);
/**
* Generates automatic voted field value
*
* @param array $data The data being saved
* @return string
**/
public function automaticVoted($data)
{
return (isset($data['voted']) && $data['voted'] ? $data['voted'] : Date::toSql());
}
/**
* Generates automatic userid field value
*
* @param array $data The data being saved
* @return int
**/
public function automaticVoter($data)
{
return (isset($data['voter']) && $data['voter'] ? (int)$data['voter'] : (int)User::get('id'));
}
/**
* Generates automatic userid field value
*
* @param array $data The data being saved
* @return int
**/
public function automaticIp($data)
{
return (isset($data['ip']) && $data['ip'] ? $data['ip'] : Request::ip());
}
/**
* Get the creator of this entry
*
* @return object
*/
public function voter()
{
return $this->belongsToOne('Hubzero\User\User', 'voter');
}
/**
* Return a formatted timestamp
*
* @param string $rtrn What data to return
* @return string
*/
public function voted($rtrn='')
{
$rtrn = strtolower($rtrn);
if ($rtrn == 'date')
{
return Date::of($this->get('voted'))->toLocal(Lang::txt('DATE_FORMAT_HZ1'));
}
if ($rtrn == 'time')
{
return Date::of($this->get('voted'))->toLocal(Lang::txt('TIME_FORMAT_HZ1'));
}
return $this->get('voted');
}
/**
* Load a record by user and wish
*
* @param integer $voter
* @param integer $referenceid
* @return object
*/
public static function oneByUserAndWish($voter, $referenceid)
{
return self::all()
->whereEquals('voter', $voter)
->whereEquals('referenceid', $referenceid)
->whereEquals('category', 'wish')
->row();
}
}
|
zweidner/hubzero-cms
|
core/components/com_wishlist/models/vote.php
|
PHP
|
mit
| 2,988 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>asio_handler_invoke</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../reference.html" title="Reference">
<link rel="prev" href="asio_handler_deallocate.html" title="asio_handler_deallocate">
<link rel="next" href="asio_handler_invoke/overload1.html" title="asio_handler_invoke (1 of 2 overloads)">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="asio_handler_deallocate.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../reference.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../boost_asio.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="asio_handler_invoke/overload1.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h3 class="title">
<a name="boost_asio.reference.asio_handler_invoke"></a><a class="link" href="asio_handler_invoke.html" title="asio_handler_invoke">asio_handler_invoke</a>
</h3></div></div></div>
<p>
<a class="indexterm" name="idp20161632"></a>
Default invoke function for handlers.
</p>
<pre class="programlisting"><span class="keyword">template</span><span class="special"><</span>
<span class="keyword">typename</span> <span class="identifier">Function</span><span class="special">></span>
<span class="keyword">void</span> <a class="link" href="asio_handler_invoke/overload1.html" title="asio_handler_invoke (1 of 2 overloads)">asio_handler_invoke</a><span class="special">(</span>
<span class="identifier">Function</span> <span class="special">&</span> <span class="identifier">function</span><span class="special">,</span>
<span class="special">...</span> <span class="special">);</span>
<span class="emphasis"><em>» <a class="link" href="asio_handler_invoke/overload1.html" title="asio_handler_invoke (1 of 2 overloads)">more...</a></em></span>
<span class="keyword">template</span><span class="special"><</span>
<span class="keyword">typename</span> <span class="identifier">Function</span><span class="special">></span>
<span class="keyword">void</span> <a class="link" href="asio_handler_invoke/overload2.html" title="asio_handler_invoke (2 of 2 overloads)">asio_handler_invoke</a><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">Function</span> <span class="special">&</span> <span class="identifier">function</span><span class="special">,</span>
<span class="special">...</span> <span class="special">);</span>
<span class="emphasis"><em>» <a class="link" href="asio_handler_invoke/overload2.html" title="asio_handler_invoke (2 of 2 overloads)">more...</a></em></span>
</pre>
<p>
Completion handlers for asynchronous operations are invoked by the <a class="link" href="io_service.html" title="io_service"><code class="computeroutput"><span class="identifier">io_service</span></code></a>
associated with the corresponding object (e.g. a socket or deadline_timer).
Certain guarantees are made on when the handler may be invoked, in particular
that a handler can only be invoked from a thread that is currently calling
<code class="computeroutput"><span class="identifier">run</span><span class="special">()</span></code>
on the corresponding <a class="link" href="io_service.html" title="io_service"><code class="computeroutput"><span class="identifier">io_service</span></code></a> object. Handlers may
subsequently be invoked through other objects (such as <a class="link" href="io_service__strand.html" title="io_service::strand"><code class="computeroutput"><span class="identifier">io_service</span><span class="special">::</span><span class="identifier">strand</span></code></a> objects) that provide additional
guarantees.
</p>
<p>
When asynchronous operations are composed from other asynchronous operations,
all intermediate handlers should be invoked using the same method as the
final handler. This is required to ensure that user-defined objects are not
accessed in a way that may violate the guarantees. This hooking function
ensures that the invoked method used for the final handler is accessible
at each intermediate step.
</p>
<p>
Implement asio_handler_invoke for your own handlers to specify a custom invocation
strategy.
</p>
<p>
This default implementation invokes the function object like so:
</p>
<pre class="programlisting"><span class="identifier">function</span><span class="special">();</span>
</pre>
<p>
If necessary, the default implementation makes a copy of the function object
so that the non-const operator() can be used.
</p>
<h5>
<a name="boost_asio.reference.asio_handler_invoke.h0"></a>
<span><a name="boost_asio.reference.asio_handler_invoke.example"></a></span><a class="link" href="asio_handler_invoke.html#boost_asio.reference.asio_handler_invoke.example">Example</a>
</h5>
<pre class="programlisting"><span class="keyword">class</span> <span class="identifier">my_handler</span><span class="special">;</span>
<span class="keyword">template</span> <span class="special"><</span><span class="keyword">typename</span> <span class="identifier">Function</span><span class="special">></span>
<span class="keyword">void</span> <span class="identifier">asio_handler_invoke</span><span class="special">(</span><span class="identifier">Function</span> <span class="identifier">function</span><span class="special">,</span> <span class="identifier">my_handler</span><span class="special">*</span> <span class="identifier">context</span><span class="special">)</span>
<span class="special">{</span>
<span class="identifier">context</span><span class="special">-></span><span class="identifier">strand_</span><span class="special">.</span><span class="identifier">dispatch</span><span class="special">(</span><span class="identifier">function</span><span class="special">);</span>
<span class="special">}</span>
</pre>
<h5>
<a name="boost_asio.reference.asio_handler_invoke.h1"></a>
<span><a name="boost_asio.reference.asio_handler_invoke.requirements"></a></span><a class="link" href="asio_handler_invoke.html#boost_asio.reference.asio_handler_invoke.requirements">Requirements</a>
</h5>
<p>
<span class="emphasis"><em>Header: </em></span><code class="literal">boost/asio/handler_invoke_hook.hpp</code>
</p>
<p>
<span class="emphasis"><em>Convenience header: </em></span><code class="literal">boost/asio.hpp</code>
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2015 Christopher M.
Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="asio_handler_deallocate.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../reference.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../boost_asio.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="asio_handler_invoke/overload1.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
yinchunlong/abelkhan-1
|
ext/c++/thirdpart/c++/boost/libs/asio/doc/html/boost_asio/reference/asio_handler_invoke.html
|
HTML
|
mit
| 8,573 |
import { Calendar } from '@fullcalendar/core'
import '@fullcalendar/interaction' // what!?
export function waitEventDrag(calendar: Calendar, dragging: Promise<any>) {
return new Promise<any>((resolve) => {
let modifiedEvent: any = false
calendar.on('eventDrop', (arg) => {
modifiedEvent = arg.event
})
calendar.on('_noEventDrop', () => {
resolve(false)
})
dragging.then(() => {
setTimeout(() => { // wait for eventDrop to fire
resolve(modifiedEvent)
})
})
})
}
export function waitEventDrag2(calendar: Calendar, dragging: Promise<any>) {
return new Promise<any>((resolve) => {
let theArg: any = false
calendar.on('eventDrop', (arg) => {
theArg = arg
})
calendar.on('_noEventDrop', () => {
resolve(false)
})
dragging.then(() => {
setTimeout(() => { // wait for eventDrop to fire
resolve(theArg)
})
})
})
}
export function waitEventResize(calendar: Calendar, dragging: Promise<any>) {
return new Promise<any>((resolve) => {
let modifiedEvent: any = false
calendar.on('eventResize', (arg) => {
modifiedEvent = arg.event
})
dragging.then(() => {
setTimeout(() => { // wait for eventResize to fire
resolve(modifiedEvent)
})
})
})
}
export function waitEventResize2(calendar: Calendar, dragging: Promise<any>) {
return new Promise<any>((resolve) => {
let theArg: any = false
calendar.on('eventResize', (arg) => {
theArg = arg
})
dragging.then(() => {
setTimeout(() => { // wait for eventResize to fire
resolve(theArg)
})
})
})
}
export function waitDateSelect(calendar: Calendar, dragging: Promise<any>) {
return new Promise<any>((resolve) => {
let selectInfo = null
calendar.on('select', (arg) => {
selectInfo = arg
})
dragging.then(() => {
setTimeout(() => { // wait for select to fire
resolve(selectInfo)
})
})
})
}
export function waitDateClick(calendar: Calendar, dragging: Promise<any>) {
return new Promise<any>((resolve) => {
let dateClickArg = null
calendar.on('dateClick', (arg) => {
dateClickArg = arg
})
dragging.then(() => {
setTimeout(() => { // wait for dateClick to fire
resolve(dateClickArg)
})
})
})
}
|
oleg-babintsev/fullcalendar
|
packages/__tests__/src/lib/wrappers/interaction-util.ts
|
TypeScript
|
mit
| 2,362 |
module.exports = {
"@id": "/analysis-steps/1b7bec83-dd21-4086-8673-2e08cf8f1c0f/",
"@type": ["AnalysisStep", "Item"],
"name": "encode-2-step",
"title": "ENCODE 2 step",
"analysis_step_types": [
"filtering",
"file format conversion",
"QA calculation",
"signal generation",
"peak calling"
],
"input_file_types": ["bam", "fasta", "bed"],
"output_file_types": ["bigWig", "narrowPeak"],
"qa_stats_generated": ["NSC", "RSC", "SPOT"],
"status": "released",
"uuid": "1b7bec83-dd21-4086-8673-2e08cf8f1c0f"
};
|
4dn-dcic/fourfront
|
src/encoded/static/components/testdata/analysis_step/encode-2-step.js
|
JavaScript
|
mit
| 585 |
/*
* Copyright (c) 2012 David Green
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package castledesigner;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
/**
*
* @author David Green
*/
public class TipsPanel extends JPanel
{
public TipsPanel()
{
setLayout(new GridLayout(2, 1));
setBorder(new TitledBorder("Tips!"));
add(new JLabel("<html>• Drag the mouse for faster placement of buildings</html>"));
add(new JLabel("<html>• Use the right mouse button to delete</html>"));
setMaximumSize(new Dimension(getMaximumSize().width, getMinimumSize().height));
}
}
|
DavidATGreen/stronghold-kingdoms-castle-designer
|
src/main/java/castledesigner/TipsPanel.java
|
Java
|
mit
| 1,717 |
# ITemplateFormatter.Initialize Method
Method to initialize the formatter with the proper TemplateProvider instance
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers](OfficeDevPnP.Core.Framework.Provisioning.Providers.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public abstract void Initialize(TemplateProviderBase provider)
```
### Parameters
#### provider
  Type: [OfficeDevPnP.Core.Framework.Provisioning.Providers.TemplateProviderBase](OfficeDevPnP.Core.Framework.Provisioning.Providers.TemplateProviderBase.md)
  The provider that is calling the current template formatter
### Return Value
Type: void
## See also
- [ITemplateFormatter](OfficeDevPnP.Core.Framework.Provisioning.Providers.ITemplateFormatter.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Providers](OfficeDevPnP.Core.Framework.Provisioning.Providers.md)
|
PaoloPia/PnP-Guidance
|
sitescore/OfficeDevPnP.Core.Framework.Provisioning.Providers.ITemplateFormatter.d92f5067.md
|
Markdown
|
mit
| 901 |
nanoGALLERY - jQuery plugin
===========
ChangeLog
------
v5.1.0
------
##### New features
- possibility to define the image swipe animation. Default (`swipe`) is optimized for modern browser but is supported by older ones also.
- image toolbar now in 2 sizes: minimized and standard. Minimized is used on small screens.
- define different thumbnail size dependant on the screen resolution (note: the syntax has evolved since beta).
##### New options
- **imageTransition**: image swipe animation. Possible values: `slideAppear`, `swipe`. Swipe is optimized for modern browser but is supported by older ones also.
*string; Default: `swipe`*
- **viewerToolbar**: new option `autoMinimize` (*integer; Default: `800`*) to define a breakpoint for switching between minimized and standard toolbar. If the width is lower than this value, the toolbar is switched to minimized.
- **thumbnailHeight** / **thumbnailWidth**: additional syntax to define sizes dependant of the screen resolution.
Syntax: `'defaultValue XSn1 SMn2 MEn3 LAn4 XLn5'` where `n1` to `n5` are the values for resolutions `XS` to `XL`. Syntax is case sensitive.
Examples: `'200 XS80 SM150 LA250 XL400'` / `'200 XSauto SMauto LA250 XL400'`.
Picasa/Google+: thumbnails can be cropped (square) or not. To get the cropped thumbnail, add `C` after the size.
Example: `'200C XS80C SM150C LA250 XL400'`.
- **thumbnailL1Height** / **thumbnailL1Width**: define the thumbnail size for the first navigation level. Same syntax as for **thumbnailHeight** / **thumbnailWidth**.
- **thumbnailSizeSM**: screen width breakpoint for thumbnail size SM.
*integer; Default: `480`*
- **thumbnailSizeME**: screen width breakpoint for thumbnail size ME.
*integer; Default: `992`*
- **thumbnailSizeLA**: screen width breakpoint for thumbnail size LA.
*integer; Default: `1200`*
- **thumbnailSizeXL**: screen width breakpoint for thumbnail size XL.
*integer; Default: `1800`*
##### Misc
- cleanup of the delivery package. Only jQuery still integrated.
- removed thumbnails loading gif.
- bugfix parameter `breadcrumbAutoHideTopLevel` not showing breadcrumb at all in some cases.
- bugfix issue #40 - Script errors in requirejs app (thanks to @jefftmills).
- bugfix PR #44 - pagination container not hidden if not used (thanks to @grief-of-these-days).
- bugfix `thumbnailWidth='auto'` image does not fill 100% of the thumbnail area.
##### Deprecated options:
- **SmugMug support removed**.
v5.0.3
------
##### Google+ and Picasa galleries not loading since 08-25-2014
Google has changed the MIME TYPE for JSONP preventing nanoGALLERY from executing.
Issue fixed by switching the Google+/Picasa requests to HTTPS.
##### Deprecated options:
- WARNING: v5.0.x is the last version supporting SmugMug storage. This support will be removed by lack of users and because the SmugMug API is not very smart.
v5.0.2
------
##### New feature
- BETA **imageTransition**: image swipe animation. Possible values: `slideAppear`, `swipe`. Swipe is optimized for modern browser but is supported by older ones also.
*string; Default: `slideAppear`*
##### Misc
- fixed issue with `colorScheme` and thumbnail hover effects `labelAppear` and `labelAppear75`
- added `none` to the supported values of `thumbnailHoverEffect`
- parameter `albumList` now supports album IDs as well as album names
##### Deprecated options:
- WARNING: v5.0.x is the last version supporting SmugMug storage. This support will be removed by lack of users and because the SmugMug API is not very smart.
v5.0.1
------
##### New feature
- BETA : thumbnail sizes can be configured according to different screen resolutions (Flickr/Picasa/Google+)
##### Misc
- fixed thumbnail hover animation issue on grid layout
- fixed issue on 'randomN' (parameters: albumSorting and photoSorting)
- fixed incompatibility issue on Safari Mobile before v6.0
- fixed touch twice issue on thumbnail (touchAutoOpenDelay=-1)
- fixed swip up/down on image display
- fixed incompatibility issue between transit.js plugin detection and Bootstrap
- pagination: scroll to gallery top if top is out of the viewport
- breadcrumb label 'List of Albums' renamed 'Galleries'
##### Deprecated options:
- WARNING: v5.0.x is the last version supporting SmugMug storage. This support will be removed by lack of users and because the SmugMug API is not very smart.
v5.0.0
------
##### New features:
- new gallery layout engine
- gallery alignment (left, right, center, justified)
- gutter space between thumbnails
- highly improved thumbnail hover effects (better combinations and now layout style regardless)
- removed the dependency to transit.js (no more required)
- removed support of hammer.js
- display full flickr photostream (set photoset='none', limited to 500 photos)
- new option to automatically start the slideshow
- new gallery fullpage mode
- new thumbnail hover effects
- sort content on title (Flickr, Picasa, Google+, SmugMug)
- thumbnail hover effects:
- new option to delay the effect
- changed default duration from 200ms to 400ms
- new loading animation (now even if breadcrumb is not visible)
- on touch-devices:
- delay to open automatically the touched thumbnail
- improved usability (gallery and image display)
- new embedded font version with additional icons (nano_icon_font3)
- imagesloaded is now embedded to avoid conflict with other version
- new javascript helpers (fnViewerInfo, fnProcessData, fnThumbnailHoverResize)
- possibility to define thumbnail images real size (inline and API methods)
- better IE9 support
##### New options:
- **thumbnailAlignment**: set the thumbnail alignment. Possible values: `left`, `right`, `justified`, `center`
*string; Default: `center`*
- **thumbnailGutterWidth**: set the horizontal gutter space between thumbnails
*integer; Default: `2`*
- **thumbnailGutterHeight**: set the vertical gutter space between thumbnails
*integer; Default: `2`*
- **touchAutoOpenDelay**: delay in ms before opening the touched thumbnail. Particular values: `-1`=disabled, `0`=automatic.
*integer; Default:`0`*
- **slideshowAutoStart**: start automatically the slideshow when an image is displayed
*boolean; default:`false`*
- **thumbnailHoverEffect**: new hover effects `descriptionAppear`, `imageScaleIn80`
- **thumbnailHoverEffect**: new parameters `delay`, `delayBack`
- **photoSorting** / **albumSorting** : new possible values `titleAsc`, `titleDesc`, `randomN` (N=integer representing the maximum number of items to display)
- **dataSorting**: Items sort order (only markup and API method). Possible values: `standard`, `reversed`, `random`
*string; default:`'standard'`*
- **galleryFullpageButton**: button to display the gallery in fullpage
*boolean; Default:`false`*
- **galleryFullpageBgColor**: background color when the gallery is displayed in fullpage
*string; Default:`'#111'`*
- **imgtHeigt** and **imgtWidth**: set the real size of thumbnail images (API method)
- **data-ngthumbImgHeight** and **data-ngthumbImgWidth**: set the real size of thumbnail images (inline method)
- **thumbnailAdjustLastRowHeight**: Automatically lower the last row height to avoid layout breaks (only for justified layout - thumbailWidth='auto')
*boolean; default:`true`*
- **fnProcessData**: javascript helper to extend data associated to thumbnails/images (Flickr, Picasa, Google+, SmugMug)
Parameters: item (thumbnail object), kind (api, markup, flickr, picasa, smugmug), sourceData (original data retrieved from the online photo sharing site)
- **fnThumbnailHoverResize**: javascript helper fired on gallery resize
Parameters: $elt (thumbail element), item (thumbnail object), data (public data)
- **fnViewerInfo**: javascript helper for info button on viewer toolbar
Parameters: item (thumbnail object), data (public data)
##### Deprecated options:
- removed support of hammer.js
- `paginationMaxItemsPerPage`
- `thumbnailWidth`=`autoUpScale`
- `viewerScrollBarHidden`
- effect `labelSlideUp2`
##### Misc
- fixed broken image icon on some browser
- fixed some bugs in themes clean and light
- added management of browser prefix for a better browser support even with odler jQuery versions
- some css optimization
- many code refactoring
- minor bugfixes
v4.4.2
------
##### New features:
- added native swipe support (hammer.js no more needed but still used if present)
##### New options:
- **viewerScrollBarHidden**: hide the viewer scrollbars
*boolean; Default: `true`*
##### Deprecated options:
- none
##### Misc
- enhanced Picasa / Google+ filename decode
- minor bugfixes
v4.4.1
------
##### New features:
- Flickr images now only over HTTPS (Flickr is going SSL-Only on June 27th, 2014)
- lazy gallery building
- use image filename as image title
- Flickr: new algorithm to retrieve the best image size depending on the screen resolution
- Flickr: do not display the original uploaded image (e.g. to avoid rotation issue)
##### New options:
- **lazyBuild**: display the gallery only when visible (possible values: 'loadData', 'display', 'none')
*string; Default: `display`*
- **lazyBuildTreshold**: Shorten the viewport area height (in pixel) for lazyBuild
*integer; Default: `150`*
- **thumbnailLabel.title**: variable to set the image title (undescores are replaced by spaces). Possible values: '%filename', '%filemaneNoExt'
*string; default:''*
- **thumbnailLabel.itemsCount: add the number of items in one per photo album (possible values: 'none', 'title', 'description')
*string; Default: `none`*
- **flickrSkipOriginal**: do not display the original uploaded image (e.g. to avoid rotation issue)
*boolean; default:true*
**Visit nanoGALLERY homepage for usage details: [http://nanogallery.brisbois.fr](http://www.nanogallery.brisbois.fr/)**
##### Deprecated options:
- **flickrSizeB**: no longer needed / new algorithm implemented
##### Misc
- improved Firefox for Android support
- removed demo panel from main plugin file (now available in jquery.nanogallerydemo.js)
- fixed on location hash not refreshed by breadcrumb
- fixed bug on Flickr album sorting (thanks to Mark Koh)
- fixed bug in fnThumbnailInit() call (thanks to Houlala - https://github.com/Houlala)
- minor bugfixes
v4.4.0
------
##### New features:
- SmugMug storage support
- new thumbnail display mode justified
- helpers to extend the capabilities of nanoGALLERY
- added image microdata
- refinement of demonstration panel
- removed support of browser-back to close the photo viewer
- added HTTPS support
- error messages displayed beneath the gallery (alert() was used up to now)
- restored icons in the light theme (hidding icons is now configurable)
##### New options:
- **thumbnailWidth**: new possible values 'auto' and 'autoUpScale'
- **fnThumbnailInit**, **fnThumbnailHoverInit**, **fnThumbnailHover**, **fnThumbnailHoverOut**, **fnThumbnailDisplayEffect**: javascript helpers
- **breadcrumbAutoHideTopLevel**: hide the breadcrumb if user on first level
*boolean; Default: `false`*
- **flickrSizeB**: include the large size (B-size / 1024) when needed
*boolean; Default: `false`*
- **imageTransition**: transition animation when moving from image to image (`default`, `fade')
*string; Default: `default`*
**Visit nanoGALLERY homepage for usage details: [http://nanogallery.brisbois.fr](http://www.nanogallery.brisbois.fr/)**
##### Deprecated options:
- none
##### Misc
- change default colorSchemeViewer default from 'none' to 'default'
- fixed compatibility issue with niceScroll plugin (http://areaaperta.com/nicescroll)
- minor bugfixes
v4.3.0
------
##### New features:
- new image display possibilities giving a larger area to the images (customizable position of navigation buttons and labels)
- set the maximum length of title and description to avoid too long content
- display or hide the icons of the thumbnails label and/or navigation breadcrumb
- thumbnail text alignment
- breadcrumb: new icon for home folder
- sorting of photos and of albums
- preload also previous image
- added Text-Shadow attribute to color schemes
- refinement of the 'light' theme
- new thumbnail hover effects
- added support of Picasa/Google+ albums that are limited to people who have a link with an authkey
##### New options:
- **viewerToolbar**: Display options for toolbar of the viewer (navigation buttons and captions)
*object; Default: `{position:'bottom', style:'innerImage'}`*
**position** : Position of the viewer toolbar (possible values: `top`, `bottom`)
*string; Default: `bottom`*
**style** : style of the toolbar (possible values: `innerImage`, `stuckImage`, `fullWidth`)
*string; Default: `innerImage`*
- **thumbnailLabel**: new parameters `titleMaxLength`, `descriptionMaxLength`, `hideIcons` and 'align'
- **galleryToolbarHideIcons**: display or not the icons in the navigation breadcrumb
- **photoSorting**: sort photo albums (possible values: `standard`, `reversed`, `random`) (Flickr/Picasa/Google+)
*string; Default: `standard`*
- **albumSorting**: sort photos in albums (possible values: `standard`, `reversed`, `random`) (Flickr/Picasa/Google+)
*string; Default: `standard`*
- **thumbnailHoverEffect**: new possible values: `labelSplitVert`, `labelSplit4`, `labelAppearSplitVert`, `labelAppearSplit4`, `imageSplitVert`, `imageSplit4`
**Visit nanoGALLERY homepage for usage details: [http://nanogallery.brisbois.fr](http://www.nanogallery.brisbois.fr/)**
##### Deprecated options:
- none
##### Misc
- CSS: renamed 'container' to 'nanoGalleryContainerParent'
- remove support of jQuery-JSONP
- bufix incorrect label display under the thumbnail
- minor bugfixes
**Contributors: Giovanni Chiodi and AlexRed --> many thanks!**
v4.2.1
------
##### New features:
- global photo/album title and description
- new label position `overImageOnMiddle`
- new theme `light` (optimized for light backgrounds)
##### New options:
- **i18n**: new elements `thumbnailImageTitle` `thumbnailAlbumTitle` `thumbnailImageDescription` `thumbnailAlbumDescription`.
- **thumbnailLabel**: new possible value `{position:'overImageOnMiddle'}
##### Deprecated options:
- none
##### Misc
- bug **mouse click outside gallery not working** - fixed
v4.2.0
------
##### New features:
- display current image number and total count of images
- close button in upper right corner
- use responsive image resolution with Flickr/Picasa/Google+ (small images on lowres display)
- back/forward navigation
- deep linking of images and albums
- thumbnail height auto: fill the thumbnail with the entire image (no black space)
##### New options:
**Name** | **Description**
------- | -------
**locationHash** | Enable or disable back/forward navigation and deep linking of images and photo albums.
| *boolean; Default: `false`*
| Note: only one gallery per page should use this feature.
**viewerDisplayLogo** | Enable or disable logo display on top of images (defined in CSS file)
| *boolean; Default: `false`*
**thumbnailHeight** | Height in pixels of the thumbnails
| *integer|auto*
##### Deprecated options:
- none
##### misc
- UI is no more freezed during thumbnails rendering
- removed hover delay on thumbnail (animation starts immediately on mouse hiver now)
- removed tags parameter in Flickr API requests
- changed default color scheme from 'default' to 'none'
- optimized image display
- fixed fancybox-related code (thanks to grief-of-these-days - https://github.com/grief-of-these-days)
- minor bugfixes
v4.1.0
------
##### New features:
- gesture support
- pagination
- optimized support of large galleries (thumbnails image lazy loading or pagination)
- support browser back-button to close the lightbox
- albums content are now cached to avoid reloads
- slideshow mode
- keyboard shortcuts
- i18n support in gallery content (titles and descriptions) and in UI elements
- fullscreen mode
- multi-level navigation support to API and HREF-methods
- dependency to jQuery-JSONP plugin is now optional (affects only Flickr/Picasa/Google+ storage)
##### New options:
* `paginationMaxItemsPerPage`: maximum number of thumbnails per page (pagination)
* `paginationMaxLinesPerPage`: maximum number of thumbnails lines per page (pagination)
* `galleryToolbarWidthAligned`: toolbar is automatically resized to the width of the thumbnails area
* `slideshowDelay`: delay in ms before displaying next image (slideshow)
* `thumbnailDisplayInterval`: interval in ms between the display of 2 thumbnails
* `thumbnailDisplayTransition`: enable transition animation before displaying one thumbnail
* `thumbnailLazyLoad`: enable lazy load of thumbnails image (image is loaded when displayed in the viewport)
* `thumbnailLazyLoadTreshold`: extend the viewport area for thumbnails image lazy load
* `i18n`: UI string translations
##### Outdated options:
* `topLabel`: replaced by i18n
##### Minor bugfixes
v4.0.3
------
* new: animation on touch event
* bugfix Flickr - no image displayed when original size is disabled
* bugfix on slow speed connection
v4.0.2
------
* Improved compatibility to Bootstrap Framework.
* Minor bug fixes.
v4.0.1
------
Typo in nanogallery.jquery.json
v4.0.0
------
Version 4 has been optimized and layout customization is now much easyer.
Main new features:
- parameter to set the thumbnails animated hover effects (combinations possible)
- color schemes to avoid having to edit any CSS file
- display images faster (thanks to pre-loading)
##### New general options:
* `thumbnailLabel`: Display options for the image label (title and description)
* `thumbnailHoverEffect`: Set the thumbnail mouse hover effect
* `colorScheme`: Set the color scheme for the gallery (breadcrumb and thumbnails)
* `colorSchemeViewer`: Set the color scheme for the image viewer
**See readme.md for details**
##### Note about CSS files / themes:
CSS files have been complety rewritten and files from previous version are not compatible with v4. Thumbnails hover effects are no more managed with CSS files/themes. The new `thumbnailHoverEffect` option should be used instead.
v3.3.0
------
Now even easier to implement thanks to the new internal viewer for displaying the images (less external files to include). Fancybox is still available but optional.
PNG-icons have been replaced by the icon font "Font Awesome" allowing an optimized display.
##### New general option:
* ```viewer``` : ```internal``` / ```fancybox``` - display images with the default viewer or with FancyBox. Internal viewer will be used if not defined.
##### New options specific to Picasa/Google+/Flickr storage:
* ```whiteList``` : list of keywords to authorize - albums must contain one of the keywords to be displayed. Keyword separator is '|'.
* ```albumList``` : list of albums to display. Separator is '|'.
|
mayursn/lms_classes
|
assets/gal2/changelog.md
|
Markdown
|
mit
| 18,836 |
/*
* This source file is part of libRocket, the HTML/CSS Interface Middleware
*
* For the latest information, see http://www.librocket.com
*
* Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
*
* 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.
*
*/
#include "WidgetSlider.h"
#include "../../Include/Rocket/Core.h"
#include "../../Include/Rocket/Controls/ElementFormControl.h"
namespace Rocket {
namespace Controls {
const float DEFAULT_REPEAT_DELAY = 0.5f;
const float DEFAULT_REPEAT_PERIOD = 0.1f;
WidgetSlider::WidgetSlider(ElementFormControl* _parent)
{
parent = _parent;
orientation = HORIZONTAL;
track = NULL;
bar = NULL;
arrows[0] = NULL;
arrows[1] = NULL;
bar_position = 0;
bar_drag_anchor = 0;
arrow_timers[0] = -1;
arrow_timers[1] = -1;
last_update_time = 0;
}
WidgetSlider::~WidgetSlider()
{
if (bar != NULL)
{
bar->RemoveEventListener("drag", this);
bar->RemoveEventListener("dragstart", this);
parent->RemoveChild(bar);
}
parent->RemoveEventListener("blur", this);
parent->RemoveEventListener("focus", this);
parent->RemoveEventListener("keydown", this, true);
if (track != NULL)
{
track->RemoveEventListener("click", this);
parent->RemoveChild(track);
}
for (int i = 0; i < 2; i++)
{
if (arrows[i] != NULL)
{
arrows[i]->RemoveEventListener("mousedown", this);
arrows[i]->RemoveEventListener("mouseup", this);
arrows[i]->RemoveEventListener("mouseout", this);
parent->RemoveChild(arrows[i]);
}
}
}
// Initialises the slider to a given orientation.
bool WidgetSlider::Initialise()
{
// Create all of our child elements as standard elements, and abort if we can't create them.
track = Core::Factory::InstanceElement(parent, "*", "slidertrack", Rocket::Core::XMLAttributes());
bar = Core::Factory::InstanceElement(parent, "*", "sliderbar", Rocket::Core::XMLAttributes());
bar->SetProperty("drag", "drag");
arrows[0] = Core::Factory::InstanceElement(parent, "*", "sliderarrowdec", Rocket::Core::XMLAttributes());
arrows[1] = Core::Factory::InstanceElement(parent, "*", "sliderarrowinc", Rocket::Core::XMLAttributes());
if (track == NULL ||
bar == NULL ||
arrows[0] == NULL ||
arrows[1] == NULL)
{
if (track != NULL)
track->RemoveReference();
if (bar != NULL)
bar->RemoveReference();
if (arrows[0] != NULL)
arrows[0]->RemoveReference();
if (arrows[1] != NULL)
arrows[1]->RemoveReference();
return false;
}
// Add them as non-DOM elements.
parent->AppendChild(track, false);
parent->AppendChild(bar, false);
parent->AppendChild(arrows[0], false);
parent->AppendChild(arrows[1], false);
// Remove the initial references on the elements.
track->RemoveReference();
bar->RemoveReference();
arrows[0]->RemoveReference();
arrows[1]->RemoveReference();
// Attach the listeners as appropriate.
bar->AddEventListener("drag", this);
bar->AddEventListener("dragstart", this);
parent->AddEventListener("blur", this);
parent->AddEventListener("focus", this);
parent->AddEventListener("keydown", this, true);
track->AddEventListener("click", this);
for (int i = 0; i < 2; i++)
{
arrows[i]->AddEventListener("mousedown", this);
arrows[i]->AddEventListener("mouseup", this);
arrows[i]->AddEventListener("mouseout", this);
}
return true;
}
// Updates the key repeats for the increment / decrement arrows.
void WidgetSlider::Update()
{
for (int i = 0; i < 2; i++)
{
bool updated_time = false;
float delta_time = 0;
if (arrow_timers[i] > 0)
{
if (!updated_time)
{
float current_time = Core::GetSystemInterface()->GetElapsedTime();
delta_time = current_time - last_update_time;
last_update_time = current_time;
}
arrow_timers[i] -= delta_time;
while (arrow_timers[i] <= 0)
{
arrow_timers[i] += DEFAULT_REPEAT_PERIOD;
SetBarPosition(i == 0 ? OnLineDecrement() : OnLineIncrement());
}
}
}
}
// Sets the position of the bar.
void WidgetSlider::SetBarPosition(float _bar_position)
{
bar_position = Rocket::Core::Math::Clamp(_bar_position, 0.0f, 1.0f);
PositionBar();
Rocket::Core::Dictionary parameters;
parameters.Set("value", bar_position);
parent->DispatchEvent("change", parameters);
}
// Returns the current position of the bar.
float WidgetSlider::GetBarPosition()
{
return bar_position;
}
// Sets the orientation of the slider.
void WidgetSlider::SetOrientation(Orientation _orientation)
{
orientation = _orientation;
}
// Returns the slider's orientation.
WidgetSlider::Orientation WidgetSlider::GetOrientation() const
{
return orientation;
}
// Sets the dimensions to the size of the slider.
void WidgetSlider::GetDimensions(Rocket::Core::Vector2f& dimensions) const
{
switch (orientation)
{
case VERTICAL: dimensions.x = 16; dimensions.y = 256; break;
case HORIZONTAL: dimensions.x = 256; dimensions.y = 16; break;
}
}
// Lays out and resizes the internal elements.
void WidgetSlider::FormatElements(const Rocket::Core::Vector2f& containing_block, float slider_length, float bar_length)
{
int length_axis = orientation == VERTICAL ? 1 : 0;
// Build the box for the containing slider element. As the containing block is not guaranteed to have a defined
// height, we must use the width for both axes.
Core::Box parent_box;
Core::ElementUtilities::BuildBox(parent_box, Rocket::Core::Vector2f(containing_block.x, containing_block.x), parent);
// Set the length of the slider.
Rocket::Core::Vector2f content = parent_box.GetSize();
content[length_axis] = slider_length;
parent_box.SetContent(content);
// Generate the initial dimensions for the track. It'll need to be cut down to fit the arrows.
Core::Box track_box;
Core::ElementUtilities::BuildBox(track_box, parent_box.GetSize(), track);
content = track_box.GetSize();
content[length_axis] = slider_length -= orientation == VERTICAL ? (track_box.GetCumulativeEdge(Core::Box::CONTENT, Core::Box::TOP) + track_box.GetCumulativeEdge(Core::Box::CONTENT, Core::Box::BOTTOM)) :
(track_box.GetCumulativeEdge(Core::Box::CONTENT, Core::Box::LEFT) + track_box.GetCumulativeEdge(Core::Box::CONTENT, Core::Box::RIGHT));
// If no height has been explicitly specified for the track, it'll be initialised to -1 as per normal block
// elements. We'll fix that up here.
if (orientation == HORIZONTAL &&
content.y < 0)
content.y = parent_box.GetSize().y;
// Now we size the arrows.
for (int i = 0; i < 2; i++)
{
Core::Box arrow_box;
Core::ElementUtilities::BuildBox(arrow_box, parent_box.GetSize(), arrows[i]);
// Clamp the size to (0, 0).
Rocket::Core::Vector2f arrow_size = arrow_box.GetSize();
if (arrow_size.x < 0 ||
arrow_size.y < 0)
arrow_box.SetContent(Rocket::Core::Vector2f(0, 0));
arrows[i]->SetBox(arrow_box);
// Shrink the track length by the arrow size.
content[length_axis] -= arrow_box.GetSize(Core::Box::MARGIN)[length_axis];
}
// Now the track has been sized, we can fix everything into position.
track_box.SetContent(content);
track->SetBox(track_box);
if (orientation == VERTICAL)
{
Rocket::Core::Vector2f offset(arrows[0]->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::LEFT), arrows[0]->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::TOP));
arrows[0]->SetOffset(offset, parent);
offset.x = track->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::LEFT);
offset.y += arrows[0]->GetBox().GetSize(Core::Box::BORDER).y + arrows[0]->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::BOTTOM) + track->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::TOP);
track->SetOffset(offset, parent);
offset.x = arrows[1]->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::LEFT);
offset.y += track->GetBox().GetSize(Core::Box::BORDER).y + track->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::BOTTOM) + arrows[1]->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::TOP);
arrows[1]->SetOffset(offset, parent);
}
else
{
Rocket::Core::Vector2f offset(arrows[0]->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::LEFT), arrows[0]->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::TOP));
arrows[0]->SetOffset(offset, parent);
offset.x += arrows[0]->GetBox().GetSize(Core::Box::BORDER).x + arrows[0]->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::RIGHT) + track->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::LEFT);
offset.y = track->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::TOP);
track->SetOffset(offset, parent);
offset.x += track->GetBox().GetSize(Core::Box::BORDER).x + track->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::RIGHT) + arrows[1]->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::LEFT);
offset.y = arrows[1]->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::TOP);
arrows[1]->SetOffset(offset, parent);
}
FormatBar(bar_length);
if (parent->IsDisabled())
{
// Propagate disabled state to child elements
bar->SetPseudoClass("disabled", true);
track->SetPseudoClass("disabled", true);
arrows[0]->SetPseudoClass("disabled", true);
arrows[1]->SetPseudoClass("disabled", true);
}
}
// Lays out and positions the bar element.
void WidgetSlider::FormatBar(float bar_length)
{
Core::Box bar_box;
Core::ElementUtilities::BuildBox(bar_box, parent->GetBox().GetSize(), bar);
Rocket::Core::Vector2f bar_box_content = bar_box.GetSize();
if (orientation == HORIZONTAL)
{
if (bar->GetLocalProperty("height") == NULL)
bar_box_content.y = parent->GetBox().GetSize().y;
}
if (bar_length >= 0)
{
Rocket::Core::Vector2f track_size = track->GetBox().GetSize();
if (orientation == VERTICAL)
{
float track_length = track_size.y - (bar_box.GetCumulativeEdge(Core::Box::CONTENT, Core::Box::TOP) + bar_box.GetCumulativeEdge(Core::Box::CONTENT, Core::Box::BOTTOM));
if (bar->GetLocalProperty("height") == NULL)
{
bar_box_content.y = track_length * bar_length;
// Check for 'min-height' restrictions.
float min_track_length = bar->ResolveProperty("min-height", track_length);
bar_box_content.y = Rocket::Core::Math::Max(min_track_length, bar_box_content.y);
// Check for 'max-height' restrictions.
float max_track_length = bar->ResolveProperty("max-height", track_length);
if (max_track_length > 0)
bar_box_content.y = Rocket::Core::Math::Min(max_track_length, bar_box_content.y);
}
// Make sure we haven't gone further than we're allowed to (min-height may have made us too big).
bar_box_content.y = Rocket::Core::Math::Min(bar_box_content.y, track_length);
}
else
{
float track_length = track_size.x - (bar_box.GetCumulativeEdge(Core::Box::CONTENT, Core::Box::LEFT) + bar_box.GetCumulativeEdge(Core::Box::CONTENT, Core::Box::RIGHT));
if (bar->GetLocalProperty("width") == NULL)
{
bar_box_content.x = track_length * bar_length;
// Check for 'min-width' restrictions.
float min_track_length = bar->ResolveProperty("min-width", track_length);
bar_box_content.x = Rocket::Core::Math::Max(min_track_length, bar_box_content.x);
// Check for 'max-width' restrictions.
float max_track_length = bar->ResolveProperty("max-width", track_length);
if (max_track_length > 0)
bar_box_content.x = Rocket::Core::Math::Min(max_track_length, bar_box_content.x);
}
// Make sure we haven't gone further than we're allowed to (min-width may have made us too big).
bar_box_content.x = Rocket::Core::Math::Min(bar_box_content.x, track_length);
}
}
// Set the new dimensions on the bar to re-decorate it.
bar_box.SetContent(bar_box_content);
bar->SetBox(bar_box);
// Now that it's been resized, re-position it.
PositionBar();
}
// Returns the widget's parent element.
Core::Element* WidgetSlider::GetParent() const
{
return parent;
}
// Handles events coming through from the slider's components.
void WidgetSlider::ProcessEvent(Core::Event& event)
{
if (parent->IsDisabled())
return;
if (event.GetTargetElement() == bar)
{
if (event == "drag")
{
if (orientation == HORIZONTAL)
{
float traversable_track_length = track->GetBox().GetSize(Core::Box::CONTENT).x - bar->GetBox().GetSize(Core::Box::CONTENT).x;
if (traversable_track_length > 0)
{
float traversable_track_origin = track->GetAbsoluteOffset().x + bar_drag_anchor;
float new_bar_position = (event.GetParameter< float >("mouse_x", 0) - traversable_track_origin) / traversable_track_length;
new_bar_position = Rocket::Core::Math::Clamp(new_bar_position, 0.0f, 1.0f);
SetBarPosition(OnBarChange(new_bar_position));
}
}
else
{
float traversable_track_length = track->GetBox().GetSize(Core::Box::CONTENT).y - bar->GetBox().GetSize(Core::Box::CONTENT).y;
if (traversable_track_length > 0)
{
float traversable_track_origin = track->GetAbsoluteOffset().y + bar_drag_anchor;
float new_bar_position = (event.GetParameter< float >("mouse_y", 0) - traversable_track_origin) / traversable_track_length;
new_bar_position = Rocket::Core::Math::Clamp(new_bar_position, 0.0f, 1.0f);
SetBarPosition(OnBarChange(new_bar_position));
}
}
}
else if (event == "dragstart")
{
if (orientation == HORIZONTAL)
bar_drag_anchor = event.GetParameter< int >("mouse_x", 0) - Rocket::Core::Math::RealToInteger(bar->GetAbsoluteOffset().x);
else
bar_drag_anchor = event.GetParameter< int >("mouse_y", 0) - Rocket::Core::Math::RealToInteger(bar->GetAbsoluteOffset().y);
}
}
else if (event.GetTargetElement() == track)
{
if (event == "click")
{
if (orientation == HORIZONTAL)
{
float mouse_position = event.GetParameter< float >("mouse_x", 0);
float click_position = (mouse_position - track->GetAbsoluteOffset().x) / track->GetBox().GetSize().x;
SetBarPosition(click_position <= bar_position ? OnPageDecrement(click_position) : OnPageIncrement(click_position));
}
else
{
float mouse_position = event.GetParameter< float >("mouse_y", 0);
float click_position = (mouse_position - track->GetAbsoluteOffset().y) / track->GetBox().GetSize().y;
SetBarPosition(click_position <= bar_position ? OnPageDecrement(click_position) : OnPageIncrement(click_position));
}
}
}
if (event == "mousedown")
{
if (event.GetTargetElement() == arrows[0])
{
arrow_timers[0] = DEFAULT_REPEAT_DELAY;
last_update_time = Core::GetSystemInterface()->GetElapsedTime();
SetBarPosition(OnLineDecrement());
}
else if (event.GetTargetElement() == arrows[1])
{
arrow_timers[1] = DEFAULT_REPEAT_DELAY;
last_update_time = Core::GetSystemInterface()->GetElapsedTime();
SetBarPosition(OnLineIncrement());
}
}
else if (event == "mouseup" ||
event == "mouseout")
{
if (event.GetTargetElement() == arrows[0])
arrow_timers[0] = -1;
else if (event.GetTargetElement() == arrows[1])
arrow_timers[1] = -1;
}
else if (event == "keydown")
{
Core::Input::KeyIdentifier key_identifier = (Core::Input::KeyIdentifier) event.GetParameter< int >("key_identifier", 0);
switch (key_identifier)
{
case Core::Input::KI_LEFT:
if (orientation == HORIZONTAL) SetBarPosition(OnLineDecrement());
break;
case Core::Input::KI_UP:
if (orientation == VERTICAL) SetBarPosition(OnLineDecrement());
break;
case Core::Input::KI_RIGHT:
if (orientation == HORIZONTAL) SetBarPosition(OnLineIncrement());
break;
case Core::Input::KI_DOWN:
if (orientation == VERTICAL) SetBarPosition(OnLineIncrement());
break;
default:
break;
}
}
if (event.GetTargetElement() == parent)
{
if (event == "focus")
{
bar->SetPseudoClass("focus", true);
}
else if (event == "blur")
{
bar->SetPseudoClass("focus", false);
}
}
}
void WidgetSlider::PositionBar()
{
const Rocket::Core::Vector2f& track_dimensions = track->GetBox().GetSize();
const Rocket::Core::Vector2f& bar_dimensions = bar->GetBox().GetSize(Core::Box::BORDER);
if (orientation == VERTICAL)
{
float traversable_track_length = track_dimensions.y - bar_dimensions.y;
bar->SetOffset(Rocket::Core::Vector2f(bar->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::LEFT), track->GetRelativeOffset().y + traversable_track_length * bar_position), parent);
}
else
{
float traversable_track_length = track_dimensions.x - bar_dimensions.x;
bar->SetOffset(Rocket::Core::Vector2f(track->GetRelativeOffset().x + traversable_track_length * bar_position, bar->GetBox().GetEdge(Core::Box::MARGIN, Core::Box::TOP)), parent);
}
}
}
}
|
gentlemans/gentlemanly_engine
|
deps/libRocket/Source/Controls/WidgetSlider.cpp
|
C++
|
mit
| 17,371 |
Copyright 2009 Tucker Beck
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.
|
ActiveState/code
|
recipes/Python/576703_xzip__Iterative_zip_functivery_large/LICENSE.md
|
Markdown
|
mit
| 1,050 |
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
////@file BuildFEVolRHS.h
///@brief This module computes a volumetric right-hand-side. This module is needed for TMS simulations in the BrainStimulator package.
///
///@author
/// ported by Moritz Dannhauer (09/24/2014) from SCIRun4
///
///@details
/// Calculates the divergence of a vector field over the volume. It is designed to calculate the volume integral of the vector field
/// (gradient of the potential in electrical simulations). Builds the volume portion of the RHS of FE calculations where the RHS of
/// the function is GRAD dot F.
/// Input: A FE mesh with field vectors distributed on the elements (constant basis). Output: The Grad dot F
#ifndef MODULES_LEGACY_FINITEELEMENTS_BuildFEVOLRHS_H__
#define MODULES_LEGACY_FINITEELEMENTS_BuildFEVOLRHS_H__
#include <Dataflow/Network/Module.h>
#include <Modules/Legacy/FiniteElements/share.h>
namespace SCIRun {
namespace Modules {
namespace FiniteElements {
class SCISHARE BuildFEVolRHS : public Dataflow::Networks::Module,
public Has1InputPort<FieldPortTag>,
public Has1OutputPort<MatrixPortTag>
{
public:
BuildFEVolRHS();
void setStateDefaults() override;
void execute() override;
INPUT_PORT(0, Mesh, Field);
OUTPUT_PORT(0, RHS, Matrix);
MODULE_TRAITS_AND_INFO(ModuleHasAlgorithm)
};
}
}
}
#endif
|
jcollfont/SCIRun
|
src/Modules/Legacy/FiniteElements/BuildFEVolRHS.h
|
C
|
mit
| 2,621 |
apt-get update && apt-get install -y wget unzip
wget https://services.gradle.org/distributions/gradle-5.6-bin.zip -O gradle.zip
mkdir /opt/gradle && unzip -d /opt/gradle gradle.zip
mv /opt/gradle/gradle-5.6 /opt/gradle/gradle
|
Lekanich/lombok
|
docker/provision/gradle/gradle-5.6.sh
|
Shell
|
mit
| 226 |
/* eslint-disable */
// This is extracted from the Babel runtime (original source: https://github.com/babel/babel/blob/9e0f5235b1ca5167c368a576ad7c5af62d20b0e3/packages/babel-helpers/src/helpers.js#L240).
// As part of the Rollup bundling process, it's injected once into workbox-core
// and reused throughout all of the other modules, avoiding code duplication.
// See https://github.com/GoogleChrome/workbox/pull/1048#issuecomment-344698046
// for further background.
self.babelHelpers = {
asyncToGenerator: function(fn) {
return function() {
var gen = fn.apply(this, arguments);
return new Promise(function(resolve, reject) {
function step(key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function(value) {
step('next', value);
}, function(err) {
step('throw', err);
});
}
}
return step('next');
});
};
},
};
this.workbox = this.workbox || {};
this.workbox.core = (function () {
'use strict';
try {
self.workbox.v['workbox:core:3.6.1'] = 1;
} catch (e) {} // eslint-disable-line
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* The available log levels in Workbox: debug, log, warn, error and silent.
*
* @property {int} debug Prints all logs from Workbox. Useful for debugging.
* @property {int} log Prints console log, warn, error and groups. Default for
* debug builds.
* @property {int} warn Prints console warn, error and groups. Default for
* non-debug builds.
* @property {int} error Print console error and groups.
* @property {int} silent Force no logging from Workbox.
*
* @alias workbox.core.LOG_LEVELS
*/
var LOG_LEVELS = {
debug: 0,
log: 1,
warn: 2,
error: 3,
silent: 4
};
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Safari doesn't print all console.groupCollapsed() arguments.
// Related bug: https://bugs.webkit.org/show_bug.cgi?id=182754
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
const GREY = `#7f8c8d`;
const GREEN = `#2ecc71`;
const YELLOW = `#f39c12`;
const RED = `#c0392b`;
const BLUE = `#3498db`;
const getDefaultLogLevel = () => LOG_LEVELS.log;
let logLevel = getDefaultLogLevel();
const shouldPrint = minLevel => logLevel <= minLevel;
const setLoggerLevel = newLogLevel => logLevel = newLogLevel;
const getLoggerLevel = () => logLevel;
// We always want groups to be logged unless logLevel is silent.
const groupLevel = LOG_LEVELS.error;
const _print = function (keyName, logArgs, levelColor) {
const logLevel = keyName.indexOf('group') === 0 ? groupLevel : LOG_LEVELS[keyName];
if (!shouldPrint(logLevel)) {
return;
}
if (!levelColor || keyName === 'groupCollapsed' && isSafari) {
console[keyName](...logArgs);
return;
}
const logPrefix = ['%cworkbox', `background: ${levelColor}; color: white; padding: 2px 0.5em; ` + `border-radius: 0.5em;`];
console[keyName](...logPrefix, ...logArgs);
};
const groupEnd = () => {
if (shouldPrint(groupLevel)) {
console.groupEnd();
}
};
const defaultExport = {
groupEnd,
unprefixed: {
groupEnd
}
};
const setupLogs = (keyName, color) => {
defaultExport[keyName] = (...args) => _print(keyName, args, color);
defaultExport.unprefixed[keyName] = (...args) => _print(keyName, args);
};
const levelToColor = {
debug: GREY,
log: GREEN,
warn: YELLOW,
error: RED,
groupCollapsed: BLUE
};
Object.keys(levelToColor).forEach(keyName => setupLogs(keyName, levelToColor[keyName]));
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var messages = {
'invalid-value': ({ paramName, validValueDescription, value }) => {
if (!paramName || !validValueDescription) {
throw new Error(`Unexpected input to 'invalid-value' error.`);
}
return `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + `${JSON.stringify(value)}.`;
},
'not-in-sw': ({ moduleName }) => {
if (!moduleName) {
throw new Error(`Unexpected input to 'not-in-sw' error.`);
}
return `The '${moduleName}' must be used in a service worker.`;
},
'not-an-array': ({ moduleName, className, funcName, paramName }) => {
if (!moduleName || !className || !funcName || !paramName) {
throw new Error(`Unexpected input to 'not-an-array' error.`);
}
return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.`;
},
'incorrect-type': ({ expectedType, paramName, moduleName, className,
funcName }) => {
if (!expectedType || !paramName || !moduleName || !funcName) {
throw new Error(`Unexpected input to 'incorrect-type' error.`);
}
return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className ? className + '.' : ''}` + `${funcName}()' must be of type ${expectedType}.`;
},
'incorrect-class': ({ expectedClass, paramName, moduleName, className,
funcName, isReturnValueProblem }) => {
if (!expectedClass || !moduleName || !funcName) {
throw new Error(`Unexpected input to 'incorrect-class' error.`);
}
if (isReturnValueProblem) {
return `The return value from ` + `'${moduleName}.${className ? className + '.' : ''}${funcName}()' ` + `must be an instance of class ${expectedClass.name}.`;
}
return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className ? className + '.' : ''}${funcName}()' ` + `must be an instance of class ${expectedClass.name}.`;
},
'missing-a-method': ({ expectedMethod, paramName, moduleName, className,
funcName }) => {
if (!expectedMethod || !paramName || !moduleName || !className || !funcName) {
throw new Error(`Unexpected input to 'missing-a-method' error.`);
}
return `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.`;
},
'add-to-cache-list-unexpected-type': ({ entry }) => {
return `An unexpected entry was passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' The entry ` + `'${JSON.stringify(entry)}' isn't supported. You must supply an array of ` + `strings with one or more characters, objects with a url property or ` + `Request objects.`;
},
'add-to-cache-list-conflicting-entries': ({ firstEntry, secondEntry }) => {
if (!firstEntry || !secondEntry) {
throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`);
}
return `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had matching ` + `URLs but different revision details. This means workbox-precaching ` + `is unable to determine cache the asset correctly. Please remove one ` + `of the entries.`;
},
'plugin-error-request-will-fetch': ({ thrownError }) => {
if (!thrownError) {
throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`);
}
return `An error was thrown by a plugins 'requestWillFetch()' method. ` + `The thrown error message was: '${thrownError.message}'.`;
},
'invalid-cache-name': ({ cacheNameId, value }) => {
if (!cacheNameId) {
throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`);
}
return `You must provide a name containing at least one character for ` + `setCacheDeatils({${cacheNameId}: '...'}). Received a value of ` + `'${JSON.stringify(value)}'`;
},
'unregister-route-but-not-found-with-method': ({ method }) => {
if (!method) {
throw new Error(`Unexpected input to ` + `'unregister-route-but-not-found-with-method' error.`);
}
return `The route you're trying to unregister was not previously ` + `registered for the method type '${method}'.`;
},
'unregister-route-route-not-registered': () => {
return `The route you're trying to unregister was not previously ` + `registered.`;
},
'queue-replay-failed': ({ name, count }) => {
return `${count} requests failed, while trying to replay Queue: ${name}.`;
},
'duplicate-queue-name': ({ name }) => {
return `The Queue name '${name}' is already being used. ` + `All instances of backgroundSync.Queue must be given unique names.`;
},
'expired-test-without-max-age': ({ methodName, paramName }) => {
return `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.`;
},
'unsupported-route-type': ({ moduleName, className, funcName, paramName }) => {
return `The supplied '${paramName}' parameter was an unsupported type. ` + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + `valid input types.`;
},
'not-array-of-class': ({ value, expectedClass,
moduleName, className, funcName, paramName }) => {
return `The supplied '${paramName}' parameter must be an array of ` + `'${expectedClass}' objects. Received '${JSON.stringify(value)},'. ` + `Please check the call to ${moduleName}.${className}.${funcName}() ` + `to fix the issue.`;
},
'max-entries-or-age-required': ({ moduleName, className, funcName }) => {
return `You must define either config.maxEntries or config.maxAgeSeconds` + `in ${moduleName}.${className}.${funcName}`;
},
'statuses-or-headers-required': ({ moduleName, className, funcName }) => {
return `You must define either config.statuses or config.headers` + `in ${moduleName}.${className}.${funcName}`;
},
'invalid-string': ({ moduleName, className, funcName, paramName }) => {
if (!paramName || !moduleName || !className || !funcName) {
throw new Error(`Unexpected input to 'invalid-string' error.`);
}
return `When using strings, the '${paramName}' parameter must start with ` + `'http' (for cross-origin matches) or '/' (for same-origin matches). ` + `Please see the docs for ${moduleName}.${className}.${funcName}() for ` + `more info.`;
},
'channel-name-required': () => {
return `You must provide a channelName to construct a ` + `BroadcastCacheUpdate instance.`;
},
'invalid-responses-are-same-args': () => {
return `The arguments passed into responsesAreSame() appear to be ` + `invalid. Please ensure valid Responses are used.`;
},
'expire-custom-caches-only': () => {
return `You must provide a 'cacheName' property when using the ` + `expiration plugin with a runtime caching strategy.`;
},
'unit-must-be-bytes': ({ normalizedRangeHeader }) => {
if (!normalizedRangeHeader) {
throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);
}
return `The 'unit' portion of the Range header must be set to 'bytes'. ` + `The Range header provided was "${normalizedRangeHeader}"`;
},
'single-range-only': ({ normalizedRangeHeader }) => {
if (!normalizedRangeHeader) {
throw new Error(`Unexpected input to 'single-range-only' error.`);
}
return `Multiple ranges are not supported. Please use a single start ` + `value, and optional end value. The Range header provided was ` + `"${normalizedRangeHeader}"`;
},
'invalid-range-values': ({ normalizedRangeHeader }) => {
if (!normalizedRangeHeader) {
throw new Error(`Unexpected input to 'invalid-range-values' error.`);
}
return `The Range header is missing both start and end values. At least ` + `one of those values is needed. The Range header provided was ` + `"${normalizedRangeHeader}"`;
},
'no-range-header': () => {
return `No Range header was found in the Request provided.`;
},
'range-not-satisfiable': ({ size, start, end }) => {
return `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.`;
},
'attempt-to-cache-non-get-request': ({ url, method }) => {
return `Unable to cache '${url}' because it is a '${method}' request and ` + `only 'GET' requests can be cached.`;
},
'cache-put-with-no-response': ({ url }) => {
return `There was an attempt to cache '${url}' but the response was not ` + `defined.`;
}
};
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const generatorFunction = (code, ...args) => {
const message = messages[code];
if (!message) {
throw new Error(`Unable to find message for code '${code}'.`);
}
return message(...args);
};
const exportedValue = generatorFunction;
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* Workbox errors should be thrown with this class.
* This allows use to ensure the type easily in tests,
* helps developers identify errors from workbox
* easily and allows use to optimise error
* messages correctly.
*
* @private
*/
class WorkboxError extends Error {
/**
*
* @param {string} errorCode The error code that
* identifies this particular error.
* @param {Object=} details Any relevant arguments
* that will help developers identify issues should
* be added as a key on the context object.
*/
constructor(errorCode, details) {
let message = exportedValue(errorCode, details);
super(message);
this.name = errorCode;
this.details = details;
}
}
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* This method returns true if the current context is a service worker.
*/
const isSwEnv = moduleName => {
if (!('ServiceWorkerGlobalScope' in self)) {
throw new WorkboxError('not-in-sw', { moduleName });
}
};
/*
* This method throws if the supplied value is not an array.
* The destructed values are required to produce a meaningful error for users.
* The destructed and restructured object is so it's clear what is
* needed.
*/
const isArray = (value, { moduleName, className, funcName, paramName }) => {
if (!Array.isArray(value)) {
throw new WorkboxError('not-an-array', {
moduleName,
className,
funcName,
paramName
});
}
};
const hasMethod = (object, expectedMethod, { moduleName, className, funcName, paramName }) => {
const type = typeof object[expectedMethod];
if (type !== 'function') {
throw new WorkboxError('missing-a-method', { paramName, expectedMethod,
moduleName, className, funcName });
}
};
const isType = (object, expectedType, { moduleName, className, funcName, paramName }) => {
if (typeof object !== expectedType) {
throw new WorkboxError('incorrect-type', { paramName, expectedType,
moduleName, className, funcName });
}
};
const isInstance = (object, expectedClass, { moduleName, className, funcName,
paramName, isReturnValueProblem }) => {
if (!(object instanceof expectedClass)) {
throw new WorkboxError('incorrect-class', { paramName, expectedClass,
moduleName, className, funcName, isReturnValueProblem });
}
};
const isOneOf = (value, validValues, { paramName }) => {
if (!validValues.includes(value)) {
throw new WorkboxError('invalid-value', {
paramName,
value,
validValueDescription: `Valid values are ${JSON.stringify(validValues)}.`
});
}
};
const isArrayOfClass = (value, expectedClass, { moduleName, className, funcName, paramName }) => {
const error = new WorkboxError('not-array-of-class', {
value, expectedClass,
moduleName, className, funcName, paramName
});
if (!Array.isArray(value)) {
throw error;
}
for (let item of value) {
if (!(item instanceof expectedClass)) {
throw error;
}
}
};
const finalAssertExports = {
hasMethod,
isArray,
isInstance,
isOneOf,
isSwEnv,
isType,
isArrayOfClass
};
/**
* Runs all of the callback functions, one at a time sequentially, in the order
* in which they were registered.
*
* @memberof workbox.core
* @private
*/
let executeQuotaErrorCallbacks = (() => {
var _ref = babelHelpers.asyncToGenerator(function* () {
{
defaultExport.log(`About to run ${callbacks.size} callbacks to clean up caches.`);
}
for (const callback of callbacks) {
yield callback();
{
defaultExport.log(callback, 'is complete.');
}
}
{
defaultExport.log('Finished running callbacks.');
}
});
return function executeQuotaErrorCallbacks() {
return _ref.apply(this, arguments);
};
})();
const callbacks = new Set();
/**
* Adds a function to the set of callbacks that will be executed when there's
* a quota error.
*
* @param {Function} callback
* @memberof workbox.core
*/
function registerQuotaErrorCallback(callback) {
{
finalAssertExports.isType(callback, 'function', {
moduleName: 'workbox-core',
funcName: 'register',
paramName: 'callback'
});
}
callbacks.add(callback);
{
defaultExport.log('Registered a callback to respond to quota errors.', callback);
}
}
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* A class that wraps common IndexedDB functionality in a promise-based API.
* It exposes all the underlying power and functionality of IndexedDB, but
* wraps the most commonly used features in a way that's much simpler to use.
*
* @private
*/
class DBWrapper {
/**
* @param {string} name
* @param {number} version
* @param {Object=} [callback]
* @param {function(this:DBWrapper, Event)} [callbacks.onupgradeneeded]
* @param {function(this:DBWrapper, Event)} [callbacks.onversionchange]
* Defaults to DBWrapper.prototype._onversionchange when not specified.
*/
constructor(name, version, {
onupgradeneeded,
onversionchange = this._onversionchange
} = {}) {
this._name = name;
this._version = version;
this._onupgradeneeded = onupgradeneeded;
this._onversionchange = onversionchange;
// If this is null, it means the database isn't open.
this._db = null;
}
/**
* Opens a connected to an IDBDatabase, invokes any onupgradedneeded
* callback, and added an onversionchange callback to the database.
*
* @return {IDBDatabase}
*
* @private
*/
open() {
var _this = this;
return babelHelpers.asyncToGenerator(function* () {
if (_this._db) return;
_this._db = yield new Promise(function (resolve, reject) {
// This flag is flipped to true if the timeout callback runs prior
// to the request failing or succeeding. Note: we use a timeout instead
// of an onblocked handler since there are cases where onblocked will
// never never run. A timeout better handles all possible scenarios:
// https://github.com/w3c/IndexedDB/issues/223
let openRequestTimedOut = false;
setTimeout(function () {
openRequestTimedOut = true;
reject(new Error('The open request was blocked and timed out'));
}, _this.OPEN_TIMEOUT);
const openRequest = indexedDB.open(_this._name, _this._version);
openRequest.onerror = function (evt) {
return reject(openRequest.error);
};
openRequest.onupgradeneeded = function (evt) {
if (openRequestTimedOut) {
openRequest.transaction.abort();
evt.target.result.close();
} else if (_this._onupgradeneeded) {
_this._onupgradeneeded(evt);
}
};
openRequest.onsuccess = function (evt) {
const db = evt.target.result;
if (openRequestTimedOut) {
db.close();
} else {
db.onversionchange = _this._onversionchange;
resolve(db);
}
};
});
return _this;
})();
}
/**
* Delegates to the native `get()` method for the object store.
*
* @param {string} storeName The name of the object store to put the value.
* @param {...*} args The values passed to the delegated method.
* @return {*} The key of the entry.
*
* @private
*/
get(storeName, ...args) {
var _this2 = this;
return babelHelpers.asyncToGenerator(function* () {
return yield _this2._call('get', storeName, 'readonly', ...args);
})();
}
/**
* Delegates to the native `add()` method for the object store.
*
* @param {string} storeName The name of the object store to put the value.
* @param {...*} args The values passed to the delegated method.
* @return {*} The key of the entry.
*
* @private
*/
add(storeName, ...args) {
var _this3 = this;
return babelHelpers.asyncToGenerator(function* () {
return yield _this3._call('add', storeName, 'readwrite', ...args);
})();
}
/**
* Delegates to the native `put()` method for the object store.
*
* @param {string} storeName The name of the object store to put the value.
* @param {...*} args The values passed to the delegated method.
* @return {*} The key of the entry.
*
* @private
*/
put(storeName, ...args) {
var _this4 = this;
return babelHelpers.asyncToGenerator(function* () {
return yield _this4._call('put', storeName, 'readwrite', ...args);
})();
}
/**
* Delegates to the native `delete()` method for the object store.
*
* @param {string} storeName
* @param {...*} args The values passed to the delegated method.
*
* @private
*/
delete(storeName, ...args) {
var _this5 = this;
return babelHelpers.asyncToGenerator(function* () {
yield _this5._call('delete', storeName, 'readwrite', ...args);
})();
}
/**
* Deletes the underlying database, ensuring that any open connections are
* closed first.
*
* @private
*/
deleteDatabase() {
var _this6 = this;
return babelHelpers.asyncToGenerator(function* () {
_this6.close();
_this6._db = null;
yield new Promise(function (resolve, reject) {
const request = indexedDB.deleteDatabase(_this6._name);
request.onerror = function (evt) {
return reject(evt.target.error);
};
request.onblocked = function () {
return reject(new Error('Deletion was blocked.'));
};
request.onsuccess = function () {
return resolve();
};
});
})();
}
/**
* Delegates to the native `getAll()` or polyfills it via the `find()`
* method in older browsers.
*
* @param {string} storeName
* @param {*} query
* @param {number} count
* @return {Array}
*
* @private
*/
getAll(storeName, query, count) {
var _this7 = this;
return babelHelpers.asyncToGenerator(function* () {
if ('getAll' in IDBObjectStore.prototype) {
return yield _this7._call('getAll', storeName, 'readonly', query, count);
} else {
return yield _this7.getAllMatching(storeName, { query, count });
}
})();
}
/**
* Supports flexible lookup in an object store by specifying an index,
* query, direction, and count. This method returns an array of objects
* with the signature .
*
* @param {string} storeName
* @param {Object} [opts]
* @param {IDBCursorDirection} [opts.direction]
* @param {*} [opts.query]
* @param {string} [opts.index] The index to use (if specified).
* @param {number} [opts.count] The max number of results to return.
* @param {boolean} [opts.includeKeys] When true, the structure of the
* returned objects is changed from an array of values to an array of
* objects in the form {key, primaryKey, value}.
* @return {Array}
*
* @private
*/
getAllMatching(storeName, opts = {}) {
var _this8 = this;
return babelHelpers.asyncToGenerator(function* () {
return yield _this8.transaction([storeName], 'readonly', function (stores, done) {
const store = stores[storeName];
const target = opts.index ? store.index(opts.index) : store;
const results = [];
// Passing `undefined` arguments to Edge's `openCursor(...)` causes
// 'DOMException: DataError'
// Details in issue: https://github.com/GoogleChrome/workbox/issues/1509
const query = opts.query || null;
const direction = opts.direction || 'next';
target.openCursor(query, direction).onsuccess = function (evt) {
const cursor = evt.target.result;
if (cursor) {
const { primaryKey, key, value } = cursor;
results.push(opts.includeKeys ? { primaryKey, key, value } : value);
if (opts.count && results.length >= opts.count) {
done(results);
} else {
cursor.continue();
}
} else {
done(results);
}
};
});
})();
}
/**
* Accepts a list of stores, a transaction type, and a callback and
* performs a transaction. A promise is returned that resolves to whatever
* value the callback chooses. The callback holds all the transaction logic
* and is invoked with three arguments:
* 1. An object mapping object store names to IDBObjectStore values.
* 2. A `done` function, that's used to resolve the promise when
* when the transaction is done.
* 3. An `abort` function that can be called to abort the transaction
* at any time.
*
* @param {Array<string>} storeNames An array of object store names
* involved in the transaction.
* @param {string} type Can be `readonly` or `readwrite`.
* @param {function(Object, function(), function(*)):?IDBRequest} callback
* @return {*} The result of the transaction ran by the callback.
*
* @private
*/
transaction(storeNames, type, callback) {
var _this9 = this;
return babelHelpers.asyncToGenerator(function* () {
yield _this9.open();
const result = yield new Promise(function (resolve, reject) {
const txn = _this9._db.transaction(storeNames, type);
const done = function (value) {
return resolve(value);
};
const abort = function () {
reject(new Error('The transaction was manually aborted'));
txn.abort();
};
txn.onerror = function (evt) {
return reject(evt.target.error);
};
txn.onabort = function (evt) {
return reject(evt.target.error);
};
txn.oncomplete = function () {
return resolve();
};
const stores = {};
for (const storeName of storeNames) {
stores[storeName] = txn.objectStore(storeName);
}
callback(stores, done, abort);
});
return result;
})();
}
/**
* Delegates async to a native IDBObjectStore method.
*
* @param {string} method The method name.
* @param {string} storeName The object store name.
* @param {string} type Can be `readonly` or `readwrite`.
* @param {...*} args The list of args to pass to the native method.
* @return {*} The result of the transaction.
*
* @private
*/
_call(method, storeName, type, ...args) {
var _this10 = this;
return babelHelpers.asyncToGenerator(function* () {
yield _this10.open();
const callback = function (stores, done) {
stores[storeName][method](...args).onsuccess = function (evt) {
done(evt.target.result);
};
};
return yield _this10.transaction([storeName], type, callback);
})();
}
/**
* The default onversionchange handler, which closes the database so other
* connections can open without being blocked.
*
* @param {Event} evt
*
* @private
*/
_onversionchange(evt) {
this.close();
}
/**
* Closes the connection opened by `DBWrapper.open()`. Generally this method
* doesn't need to be called since:
* 1. It's usually better to keep a connection open since opening
* a new connection is somewhat slow.
* 2. Connections are automatically closed when the reference is
* garbage collected.
* The primary use case for needing to close a connection is when another
* reference (typically in another tab) needs to upgrade it and would be
* blocked by the current, open connection.
*
* @private
*/
close() {
if (this._db) this._db.close();
}
}
// Exposed to let users modify the default timeout on a per-instance
// or global basis.
DBWrapper.prototype.OPEN_TIMEOUT = 2000;
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const _cacheNameDetails = {
prefix: 'workbox',
suffix: self.registration.scope,
googleAnalytics: 'googleAnalytics',
precache: 'precache',
runtime: 'runtime'
};
const _createCacheName = cacheName => {
return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix].filter(value => value.length > 0).join('-');
};
const cacheNames = {
updateDetails: details => {
Object.keys(_cacheNameDetails).forEach(key => {
if (typeof details[key] !== 'undefined') {
_cacheNameDetails[key] = details[key];
}
});
},
getGoogleAnalyticsName: userCacheName => {
return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics);
},
getPrecacheName: userCacheName => {
return userCacheName || _createCacheName(_cacheNameDetails.precache);
},
getRuntimeName: userCacheName => {
return userCacheName || _createCacheName(_cacheNameDetails.runtime);
}
};
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var pluginEvents = {
CACHE_DID_UPDATE: 'cacheDidUpdate',
CACHE_WILL_UPDATE: 'cacheWillUpdate',
CACHED_RESPONSE_WILL_BE_USED: 'cachedResponseWillBeUsed',
FETCH_DID_FAIL: 'fetchDidFail',
REQUEST_WILL_FETCH: 'requestWillFetch'
};
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var pluginUtils = {
filter: (plugins, callbackname) => {
return plugins.filter(plugin => callbackname in plugin);
}
};
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const getFriendlyURL = url => {
const urlObj = new URL(url, location);
if (urlObj.origin === location.origin) {
return urlObj.pathname;
}
return urlObj.href;
};
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* Wrapper around cache.put().
*
* Will call `cacheDidUpdate` on plugins if the cache was updated.
*
* @param {Object} options
* @param {string} options.cacheName
* @param {Request} options.request
* @param {Response} options.response
* @param {Event} [options.event]
* @param {Array<Object>} [options.plugins=[]]
*
* @private
* @memberof module:workbox-core
*/
const putWrapper = (() => {
var _ref = babelHelpers.asyncToGenerator(function* ({
cacheName,
request,
response,
event,
plugins = []
} = {}) {
if (!response) {
{
defaultExport.error(`Cannot cache non-existent response for ` + `'${getFriendlyURL(request.url)}'.`);
}
throw new WorkboxError('cache-put-with-no-response', {
url: getFriendlyURL(request.url)
});
}
let responseToCache = yield _isResponseSafeToCache({ request, response, event, plugins });
if (!responseToCache) {
{
defaultExport.debug(`Response '${getFriendlyURL(request.url)}' will not be ` + `cached.`, responseToCache);
}
return;
}
{
if (responseToCache.method && responseToCache.method !== 'GET') {
throw new WorkboxError('attempt-to-cache-non-get-request', {
url: getFriendlyURL(request.url),
method: responseToCache.method
});
}
}
const cache = yield caches.open(cacheName);
const updatePlugins = pluginUtils.filter(plugins, pluginEvents.CACHE_DID_UPDATE);
let oldResponse = updatePlugins.length > 0 ? yield matchWrapper({ cacheName, request }) : null;
{
defaultExport.debug(`Updating the '${cacheName}' cache with a new Response for ` + `${getFriendlyURL(request.url)}.`);
}
try {
yield cache.put(request, responseToCache);
} catch (error) {
// See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError
if (error.name === 'QuotaExceededError') {
yield executeQuotaErrorCallbacks();
}
throw error;
}
for (let plugin of updatePlugins) {
yield plugin[pluginEvents.CACHE_DID_UPDATE].call(plugin, {
cacheName,
request,
event,
oldResponse,
newResponse: responseToCache
});
}
});
return function putWrapper() {
return _ref.apply(this, arguments);
};
})();
/**
* This is a wrapper around cache.match().
*
* @param {Object} options
* @param {string} options.cacheName Name of the cache to match against.
* @param {Request} options.request The Request that will be used to look up
*. cache entries.
* @param {Event} [options.event] The event that propted the action.
* @param {Object} [options.matchOptions] Options passed to cache.match().
* @param {Array<Object>} [options.plugins=[]] Array of plugins.
* @return {Response} A cached response if available.
*
* @private
* @memberof module:workbox-core
*/
const matchWrapper = (() => {
var _ref2 = babelHelpers.asyncToGenerator(function* ({
cacheName,
request,
event,
matchOptions,
plugins = [] }) {
const cache = yield caches.open(cacheName);
let cachedResponse = yield cache.match(request, matchOptions);
{
if (cachedResponse) {
defaultExport.debug(`Found a cached response in '${cacheName}'.`);
} else {
defaultExport.debug(`No cached response found in '${cacheName}'.`);
}
}
for (let plugin of plugins) {
if (pluginEvents.CACHED_RESPONSE_WILL_BE_USED in plugin) {
cachedResponse = yield plugin[pluginEvents.CACHED_RESPONSE_WILL_BE_USED].call(plugin, {
cacheName,
request,
event,
matchOptions,
cachedResponse
});
{
if (cachedResponse) {
finalAssertExports.isInstance(cachedResponse, Response, {
moduleName: 'Plugin',
funcName: pluginEvents.CACHED_RESPONSE_WILL_BE_USED,
isReturnValueProblem: true
});
}
}
}
}
return cachedResponse;
});
return function matchWrapper(_x) {
return _ref2.apply(this, arguments);
};
})();
/**
* This method will call cacheWillUpdate on the available plugins (or use
* response.ok) to determine if the Response is safe and valid to cache.
*
* @param {Object} options
* @param {Request} options.request
* @param {Response} options.response
* @param {Event} [options.event]
* @param {Array<Object>} [options.plugins=[]]
* @return {Promise<Response>}
*
* @private
* @memberof module:workbox-core
*/
const _isResponseSafeToCache = (() => {
var _ref3 = babelHelpers.asyncToGenerator(function* ({ request, response, event, plugins }) {
let responseToCache = response;
let pluginsUsed = false;
for (let plugin of plugins) {
if (pluginEvents.CACHE_WILL_UPDATE in plugin) {
pluginsUsed = true;
responseToCache = yield plugin[pluginEvents.CACHE_WILL_UPDATE].call(plugin, {
request,
response: responseToCache,
event
});
{
if (responseToCache) {
finalAssertExports.isInstance(responseToCache, Response, {
moduleName: 'Plugin',
funcName: pluginEvents.CACHE_WILL_UPDATE,
isReturnValueProblem: true
});
}
}
if (!responseToCache) {
break;
}
}
}
if (!pluginsUsed) {
{
if (!responseToCache.ok) {
if (responseToCache.status === 0) {
defaultExport.warn(`The response for '${request.url}' is an opaque ` + `response. The caching strategy that you're using will not ` + `cache opaque responses by default.`);
} else {
defaultExport.debug(`The response for '${request.url}' returned ` + `a status code of '${response.status}' and won't be cached as a ` + `result.`);
}
}
}
responseToCache = responseToCache.ok ? responseToCache : null;
}
return responseToCache ? responseToCache : null;
});
return function _isResponseSafeToCache(_x2) {
return _ref3.apply(this, arguments);
};
})();
const cacheWrapper = {
put: putWrapper,
match: matchWrapper
};
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* Wrapper around the fetch API.
*
* Will call requestWillFetch on available plugins.
*
* @param {Object} options
* @param {Request|string} options.request
* @param {Object} [options.fetchOptions]
* @param {Event} [options.event]
* @param {Array<Object>} [options.plugins=[]]
* @return {Promise<Response>}
*
* @private
* @memberof module:workbox-core
*/
const wrappedFetch = (() => {
var _ref = babelHelpers.asyncToGenerator(function* ({
request,
fetchOptions,
event,
plugins = [] }) {
// We *should* be able to call `await event.preloadResponse` even if it's
// undefined, but for some reason, doing so leads to errors in our Node unit
// tests. To work around that, explicitly check preloadResponse's value first.
if (event && event.preloadResponse) {
const possiblePreloadResponse = yield event.preloadResponse;
if (possiblePreloadResponse) {
{
defaultExport.log(`Using a preloaded navigation response for ` + `'${getFriendlyURL(request.url)}'`);
}
return possiblePreloadResponse;
}
}
if (typeof request === 'string') {
request = new Request(request);
}
{
finalAssertExports.isInstance(request, Request, {
paramName: request,
expectedClass: 'Request',
moduleName: 'workbox-core',
className: 'fetchWrapper',
funcName: 'wrappedFetch'
});
}
const failedFetchPlugins = pluginUtils.filter(plugins, pluginEvents.FETCH_DID_FAIL);
// If there is a fetchDidFail plugin, we need to save a clone of the
// original request before it's either modified by a requestWillFetch
// plugin or before the original request's body is consumed via fetch().
const originalRequest = failedFetchPlugins.length > 0 ? request.clone() : null;
try {
for (let plugin of plugins) {
if (pluginEvents.REQUEST_WILL_FETCH in plugin) {
request = yield plugin[pluginEvents.REQUEST_WILL_FETCH].call(plugin, {
request: request.clone(),
event
});
{
if (request) {
finalAssertExports.isInstance(request, Request, {
moduleName: 'Plugin',
funcName: pluginEvents.CACHED_RESPONSE_WILL_BE_USED,
isReturnValueProblem: true
});
}
}
}
}
} catch (err) {
throw new WorkboxError('plugin-error-request-will-fetch', {
thrownError: err
});
}
// The request can be altered by plugins with `requestWillFetch` making
// the original request (Most likely from a `fetch` event) to be different
// to the Request we make. Pass both to `fetchDidFail` to aid debugging.
const pluginFilteredRequest = request.clone();
try {
const fetchResponse = yield fetch(request, fetchOptions);
{
defaultExport.debug(`Network request for ` + `'${getFriendlyURL(request.url)}' returned a response with ` + `status '${fetchResponse.status}'.`);
}
return fetchResponse;
} catch (error) {
{
defaultExport.error(`Network request for ` + `'${getFriendlyURL(request.url)}' threw an error.`, error);
}
for (let plugin of failedFetchPlugins) {
yield plugin[pluginEvents.FETCH_DID_FAIL].call(plugin, {
error,
event,
originalRequest: originalRequest.clone(),
request: pluginFilteredRequest.clone()
});
}
throw error;
}
});
return function wrappedFetch(_x) {
return _ref.apply(this, arguments);
};
})();
const fetchWrapper = {
fetch: wrappedFetch
};
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var _private = /*#__PURE__*/Object.freeze({
DBWrapper: DBWrapper,
WorkboxError: WorkboxError,
assert: finalAssertExports,
cacheNames: cacheNames,
cacheWrapper: cacheWrapper,
fetchWrapper: fetchWrapper,
getFriendlyURL: getFriendlyURL,
logger: defaultExport
});
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* Logs a warning to the user recommending changing
* to max-age=0 or no-cache.
*
* @param {string} cacheControlHeader
*
* @private
*/
function showWarning(cacheControlHeader) {
const docsUrl = 'https://developers.google.com/web/tools/workbox/guides/service-worker-checklist#cache-control_of_your_service_worker_file';
defaultExport.warn(`You are setting a 'cache-control' header of ` + `'${cacheControlHeader}' on your service worker file. This should be ` + `set to 'max-age=0' or 'no-cache' to ensure the latest service worker ` + `is served to your users. Learn more here: ${docsUrl}`);
}
/**
* Checks for cache-control header on SW file and
* warns the developer if it exists with a value
* other than max-age=0 or no-cache.
*
* @return {Promise}
* @private
*/
function checkSWFileCacheHeaders() {
// This is wrapped as an iife to allow async/await while making
// rollup exclude it in builds.
return babelHelpers.asyncToGenerator(function* () {
try {
const swFile = self.location.href;
const response = yield fetch(swFile);
if (!response.ok) {
// Response failed so nothing we can check;
return;
}
if (!response.headers.has('cache-control')) {
// No cache control header.
return;
}
const cacheControlHeader = response.headers.get('cache-control');
const maxAgeResult = /max-age\s*=\s*(\d*)/g.exec(cacheControlHeader);
if (maxAgeResult) {
if (parseInt(maxAgeResult[1], 10) === 0) {
return;
}
}
if (cacheControlHeader.indexOf('no-cache') !== -1) {
return;
}
if (cacheControlHeader.indexOf('no-store') !== -1) {
return;
}
showWarning(cacheControlHeader);
} catch (err) {
// NOOP
}
})();
}
const finalCheckSWFileCacheHeaders = checkSWFileCacheHeaders;
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* This class is never exposed publicly. Inidividual methods are exposed
* using jsdoc alias commands.
*
* @memberof workbox.core
* @private
*/
class WorkboxCore {
/**
* You should not instantiate this object directly.
*
* @private
*/
constructor() {
// Give our version strings something to hang off of.
try {
self.workbox.v = self.workbox.v || {};
} catch (err) {}
// NOOP
// A WorkboxCore instance must be exported before we can use the logger.
// This is so it can get the current log level.
{
const padding = ' ';
defaultExport.groupCollapsed('Welcome to Workbox!');
defaultExport.unprefixed.log(`You are currently using a development build. ` + `By default this will switch to prod builds when not on localhost. ` + `You can force this with workbox.setConfig({debug: true|false}).`);
defaultExport.unprefixed.log(`📖 Read the guides and documentation\n` + `${padding}https://developers.google.com/web/tools/workbox/`);
defaultExport.unprefixed.log(`❓ Use the [workbox] tag on Stack Overflow to ask questions\n` + `${padding}https://stackoverflow.com/questions/ask?tags=workbox`);
defaultExport.unprefixed.log(`🐛 Found a bug? Report it on GitHub\n` + `${padding}https://github.com/GoogleChrome/workbox/issues/new`);
defaultExport.groupEnd();
if (typeof finalCheckSWFileCacheHeaders === 'function') {
finalCheckSWFileCacheHeaders();
}
}
}
/**
* Get the current cache names used by Workbox.
*
* `cacheNames.precache` is used for precached assets,
* `cacheNames.googleAnalytics` is used by `workbox-google-analytics` to
* store `analytics.js`,
* and `cacheNames.runtime` is used for everything else.
*
* @return {Object} An object with `precache` and `runtime` cache names.
*
* @alias workbox.core.cacheNames
*/
get cacheNames() {
return {
googleAnalytics: cacheNames.getGoogleAnalyticsName(),
precache: cacheNames.getPrecacheName(),
runtime: cacheNames.getRuntimeName()
};
}
/**
* You can alter the default cache names used by the Workbox modules by
* changing the cache name details.
*
* Cache names are generated as `<prefix>-<Cache Name>-<suffix>`.
*
* @param {Object} details
* @param {Object} details.prefix The string to add to the beginning of
* the precache and runtime cache names.
* @param {Object} details.suffix The string to add to the end of
* the precache and runtime cache names.
* @param {Object} details.precache The cache name to use for precache
* caching.
* @param {Object} details.runtime The cache name to use for runtime caching.
* @param {Object} details.googleAnalytics The cache name to use for
* `workbox-google-analytics` caching.
*
* @alias workbox.core.setCacheNameDetails
*/
setCacheNameDetails(details) {
{
Object.keys(details).forEach(key => {
finalAssertExports.isType(details[key], 'string', {
moduleName: 'workbox-core',
className: 'WorkboxCore',
funcName: 'setCacheNameDetails',
paramName: `details.${key}`
});
});
if ('precache' in details && details.precache.length === 0) {
throw new WorkboxError('invalid-cache-name', {
cacheNameId: 'precache',
value: details.precache
});
}
if ('runtime' in details && details.runtime.length === 0) {
throw new WorkboxError('invalid-cache-name', {
cacheNameId: 'runtime',
value: details.runtime
});
}
if ('googleAnalytics' in details && details.googleAnalytics.length === 0) {
throw new WorkboxError('invalid-cache-name', {
cacheNameId: 'googleAnalytics',
value: details.googleAnalytics
});
}
}
cacheNames.updateDetails(details);
}
/**
* Get the current log level.
*
* @return {number}.
*
* @alias workbox.core.logLevel
*/
get logLevel() {
return getLoggerLevel();
}
/**
* Set the current log level passing in one of the values from
* [LOG_LEVELS]{@link module:workbox-core.LOG_LEVELS}.
*
* @param {number} newLevel The new log level to use.
*
* @alias workbox.core.setLogLevel
*/
setLogLevel(newLevel) {
{
finalAssertExports.isType(newLevel, 'number', {
moduleName: 'workbox-core',
className: 'WorkboxCore',
funcName: 'logLevel [setter]',
paramName: `logLevel`
});
}
if (newLevel > LOG_LEVELS.silent || newLevel < LOG_LEVELS.debug) {
throw new WorkboxError('invalid-value', {
paramName: 'logLevel',
validValueDescription: `Please use a value from LOG_LEVELS, i.e ` + `'logLevel = workbox.core.LOG_LEVELS.debug'.`,
value: newLevel
});
}
setLoggerLevel(newLevel);
}
}
var defaultExport$1 = new WorkboxCore();
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const finalExports = Object.assign(defaultExport$1, {
_private,
LOG_LEVELS,
registerQuotaErrorCallback
});
return finalExports;
}());
//# sourceMappingURL=workbox-core.dev.js.map
|
nasvillanueva/nasvillanueva.github.io
|
workbox-v3.6.1/workbox-core.dev.js
|
JavaScript
|
mit
| 59,451 |
"use strict";
module.exports = {
lazy: require("./lazy")
};
|
millerman86/CouponProject
|
node_modules/es5-ext/promise/index.js
|
JavaScript
|
mit
| 62 |
// Type definitions for @rdfjs/express-handler 1.1
// Project: https://github.com/rdfjs-base/express-handler
// Definitions by: tpluscode <https://github.com/tpluscode>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import { Stream, DatasetCore, DatasetCoreFactory } from 'rdf-js';
import { Request, Response, RequestHandler } from 'express';
import formats = require('@rdfjs/formats-common');
declare module 'express' {
interface Request {
dataset(parserOptions?: any): Promise<DatasetCore>;
quadStream(parserOptions?: any): Stream;
}
interface Response {
dataset(dataset: DatasetCore): Promise<void>;
quadStream(stream: Stream): Promise<void>;
}
}
interface BaseIriFromRequest {
(req: Request): Promise<string> | string;
}
interface RdfHandlerOptions {
factory?: DatasetCoreFactory;
formats?: typeof formats;
defaultMediaType?: string;
baseIriFromRequest?: boolean | BaseIriFromRequest;
}
interface RdfHandler {
(options?: RdfHandlerOptions): RequestHandler;
attach(req: Request, res: Response): Promise<void>;
}
declare const middleware: RdfHandler;
export = middleware;
|
dsebastien/DefinitelyTyped
|
types/rdfjs__express-handler/index.d.ts
|
TypeScript
|
mit
| 1,178 |
using System;
using System.Collections.Generic;
using System.Linq;
namespace DevExpress.Mvvm {
public interface ISupportParameter {
object Parameter { get; set; }
}
}
|
1gurucoder/DevExpress.Mvvm.Free
|
DevExpress.Mvvm/Services/ISupportParameter.cs
|
C#
|
mit
| 183 |
describe('tr.models.Radar', function () {
it('has no quadrants by default', function () {
radar = new tr.models.Radar();
expect(radar.quadrants().I).toBe(null);
expect(radar.quadrants().II).toBe(null);
expect(radar.quadrants().III).toBe(null);
expect(radar.quadrants().IV).toBe(null);
});
it('sets the first quadrant', function () {
var quadrant, radar, blip;
blip = new tr.models.Blip('A', new tr.models.Cycle('First'));
quadrant = new tr.models.Quadrant('First');
quadrant.add([blip]);
radar = new tr.models.Radar();
radar.setFirstQuadrant(quadrant);
expect(radar.quadrants().I).toEqual(quadrant);
expect(radar.quadrants().I.blips()[0].number()).toEqual(1);
});
it('sets the second quadrant', function () {
var quadrant, radar, blip;
blip = new tr.models.Blip('A', new tr.models.Cycle('First'));
quadrant = new tr.models.Quadrant('Second');
quadrant.add([blip]);
radar = new tr.models.Radar();
radar.setSecondQuadrant(quadrant);
expect(radar.quadrants().II).toEqual(quadrant);
expect(radar.quadrants().II.blips()[0].number()).toEqual(1);
});
it('sets the third quadrant', function () {
var quadrant, radar, blip;
blip = new tr.models.Blip('A', new tr.models.Cycle('First'));
quadrant = new tr.models.Quadrant('Third');
quadrant.add([blip]);
radar = new tr.models.Radar();
radar.setThirdQuadrant(quadrant);
expect(radar.quadrants().III).toEqual(quadrant);
expect(radar.quadrants().III.blips()[0].number()).toEqual(1);
});
it('sets the fourth quadrant', function () {
var quadrant, radar, blip;
blip = new tr.models.Blip('A', new tr.models.Cycle('First'));
quadrant = new tr.models.Quadrant('Fourth');
quadrant.add([blip]);
radar = new tr.models.Radar();
radar.setFourthQuadrant(quadrant);
expect(radar.quadrants().IV).toEqual(quadrant);
expect(radar.quadrants().IV.blips()[0].number()).toEqual(1);
});
describe('blip numbers', function () {
var firstQuadrant, secondQuadrant, radar, firstCycle;
beforeEach(function () {
firstCycle = new tr.models.Cycle('Adopt', 0);
firstQuadrant = new tr.models.Quadrant('First');
secondQuadrant = new tr.models.Quadrant('Second');
firstQuadrant.add([
new tr.models.Blip('A', firstCycle),
new tr.models.Blip('B', firstCycle)
]);
secondQuadrant.add([
new tr.models.Blip('C', firstCycle),
new tr.models.Blip('D', firstCycle)
]);
radar = new tr.models.Radar();
});
it('sets blip numbers starting on the first quadrant', function () {
radar.setFirstQuadrant(firstQuadrant);
expect(radar.quadrants().I.blips()[0].number()).toEqual(1);
expect(radar.quadrants().I.blips()[1].number()).toEqual(2);
});
it('continues the number from the previous quadrant set', function () {
radar.setFirstQuadrant(firstQuadrant);
radar.setSecondQuadrant(secondQuadrant);
expect(radar.quadrants().II.blips()[0].number()).toEqual(3);
expect(radar.quadrants().II.blips()[1].number()).toEqual(4);
});
});
describe('cycles', function () {
var quadrant, radar, firstCycle, secondCycle;
beforeEach(function () {
firstCycle = new tr.models.Cycle('Adopt', 0);
secondCycle = new tr.models.Cycle('Hold', 1);
quadrant = new tr.models.Quadrant('Fourth');
radar = new tr.models.Radar();
});
it('returns an array for a given set of blips', function () {
quadrant.add([
new tr.models.Blip('A', firstCycle),
new tr.models.Blip('B', secondCycle)
]);
radar.setFirstQuadrant(quadrant);
expect(radar.cycles()).toEqual([firstCycle, secondCycle]);
});
it('has unique cycles', function () {
quadrant.add([
new tr.models.Blip('A', firstCycle),
new tr.models.Blip('B', firstCycle),
new tr.models.Blip('C', secondCycle)
]);
radar.setFirstQuadrant(quadrant);
expect(radar.cycles()).toEqual([firstCycle, secondCycle]);
});
it('has sorts by the cycle order', function () {
quadrant.add([
new tr.models.Blip('C', secondCycle),
new tr.models.Blip('A', firstCycle),
new tr.models.Blip('B', firstCycle)
]);
radar.setFirstQuadrant(quadrant);
expect(radar.cycles()).toEqual([firstCycle, secondCycle]);
});
});
});
|
outware-mobile/tech-radar
|
test/models/radar-spec.js
|
JavaScript
|
mit
| 4,445 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.automation.v2015_10_31;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Definition of runas credential to use for hybrid worker.
*/
public class RunAsCredentialAssociationProperty {
/**
* Gets or sets the name of the credential.
*/
@JsonProperty(value = "name")
private String name;
/**
* Get gets or sets the name of the credential.
*
* @return the name value
*/
public String name() {
return this.name;
}
/**
* Set gets or sets the name of the credential.
*
* @param name the name value to set
* @return the RunAsCredentialAssociationProperty object itself.
*/
public RunAsCredentialAssociationProperty withName(String name) {
this.name = name;
return this;
}
}
|
navalev/azure-sdk-for-java
|
sdk/automation/mgmt-v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/RunAsCredentialAssociationProperty.java
|
Java
|
mit
| 1,069 |
/**
* 模板
* 1.安装ejs npm install ejs
* 2.
**/
var fs = require('fs');
var express = require('express');
var app = express();
app.set('view engine','xml');//设置模板引擎
app.set('views',__dirname);//设置模板的存放路径
//app.engine('.xml',require('ejs').__express);
app.engine('.xml',myrender);
app.get('/',function(req,res){
res.setHeader('Content-Type','text/html');
res.render('index',{username:'zfpx'});
});
app.listen(8080);
function myrender(path,data,cb){
var content = fs.readFileSync(path,{encoding:'utf8'});
content = content.replace('<%=username%>',data.username);
console.log(content);
cb(content);
}
|
plxiayutian/201505
|
19.express/4.template.js
|
JavaScript
|
mit
| 664 |
import * as OS from 'os'
import { compare } from 'compare-versions'
import memoizeOne from 'memoize-one'
function getSystemVersionSafe() {
if (__DARWIN__) {
// getSystemVersion only exists when running under Electron, and not when
// running unit tests which frequently end up calling this. There are no
// other known reasons why getSystemVersion() would return anything other
// than a string
return 'getSystemVersion' in process
? process.getSystemVersion()
: undefined
} else {
return OS.release()
}
}
function systemVersionGreaterThanOrEqualTo(version: string) {
const sysver = getSystemVersionSafe()
return sysver === undefined ? false : compare(sysver, version, '>=')
}
/** Get the OS we're currently running on. */
export function getOS() {
const version = getSystemVersionSafe()
if (__DARWIN__) {
return `Mac OS ${version}`
} else if (__WIN32__) {
return `Windows ${version}`
} else {
return `${OS.type()} ${version}`
}
}
/** We're currently running macOS and it is at least Mojave. */
export const isMacOSMojaveOrLater = memoizeOne(
() => __DARWIN__ && systemVersionGreaterThanOrEqualTo('10.13.0')
)
/** We're currently running macOS and it is at least Big Sur. */
export const isMacOSBigSurOrLater = memoizeOne(
// We're using 10.16 rather than 11.0 here due to
// https://github.com/electron/electron/issues/26419
() => __DARWIN__ && systemVersionGreaterThanOrEqualTo('10.16')
)
/** We're currently running Windows 10 and it is at least 1809 Preview Build 17666. */
export const isWindows10And1809Preview17666OrLater = memoizeOne(
() => __WIN32__ && systemVersionGreaterThanOrEqualTo('10.0.17666')
)
|
artivilla/desktop
|
app/src/lib/get-os.ts
|
TypeScript
|
mit
| 1,696 |
#include "hsHistogram.h"
HsHistogram::HsHistogram()
{
numBins = NUM_BINS_PER_CHANNEL_DEFAULT;
}
HsHistogram::~HsHistogram()
{
}
void HsHistogram::extract(cv::Mat & img, const cv::Rect_<int> & detBox)
{
int ii,jj;
float mValue, maskTotal;
float hValue, sValue;
int hBin, sBin;
//cv::Scalar_<uchar> hsvValue;
cv::Vec3b hsvValue;
//create a weighting mask given the box size
maskTotal = 0;
wMask = cv::Mat::zeros(detBox.height,detBox.width, CV_32FC1);
for (ii=0; ii<detBox.width; ii++)
{
//sinus pulse
mValue = sin(M_PI*(float)(ii)/(float)(detBox.width));
//trianglular pulse
//if (ii<detBox.width/2) mValue = (float)ii/(detBox.width/2.0);
//else mValue = 1-(float)(ii-detBox.width/2.0)/(detBox.width/2.0);
//quadratic pulse
//if (ii<detBox.width/2) mValue = pow((float)ii/(detBox.width/2.0),2);
//else mValue = pow(1-(float)(ii-detBox.width/2.0)/(detBox.width/2.0),2);
for (jj=0; jj<detBox.height; jj++)
{
wMask.at<float>(jj,ii) = mValue;
maskTotal += mValue;
}
}
//convert current frame to hsv
cvtColor(img, imgHsv, CV_BGR2HSV);
//split channels
cv::split(imgHsv,imgHsvSplit); //split RGB channels, just for GUI purposes
//clears HS histogram
hsHist = cv::Mat::zeros(numBins,numBins,CV_32FC1);
//fills histogram taking into account mask. Horizontal axis (width, cols) holds Hue. Vertical axis (height, rows) holds saturation
for (ii=detBox.x; ii<(detBox.x+detBox.width); ii++)
{
for (jj=detBox.y; jj<(detBox.y+detBox.height); jj++)
{
//hsvValue = imgHsv.at< cv::Scalar_<uchar> >(jj,ii);
hsvValue = imgHsv.at<cv::Vec3b>(jj,ii);
hValue = (float)hsvValue[0];
sValue = (float)hsvValue[1];
hBin = (int)(hValue*numBins/256.0);
sBin = (int)(sValue*numBins/256.0);
hsHist.at<float>(sBin,hBin) = hsHist.at<float>(sBin,hBin) + wMask.at<float>(jj-detBox.y,ii-detBox.x);
//std::cout << "hBin: " << hBin << "; sBin: " << sBin << std::endl;
}
}
//normalize histogram with the total "energy" of the box
//double maxVal=0; minMaxLoc(hsHist, 0, &maxVal, 0, 0); std::cout << "maxVal: " << maxVal << std::endl;
for (ii=0; ii<(int)numBins; ii++)
{
for (jj=0; jj<(int)numBins; jj++)
{
hsHist.at<float>(ii,jj) = 255*hsHist.at<float>(ii,jj)/maskTotal;
}
}
}
void HsHistogram::update()
{
//questions:
// * how much sense does it make to aggregate histograms in a reinforced learning fashion?
// * is it better to use a queue with fixed length storing the last N histograms
// and matching can be done by matching on each and evaluating results
// using a fixed discount coefficient
}
double HsHistogram::match(const AbstractAppearanceModel* app) const
{
//to do
return 0;
}
void HsHistogram::print() const
{
//to do, debugging purposes
}
cv::Mat & HsHistogram::getwMask()
{
return wMask;
}
cv::Mat & HsHistogram::getImgHsv()
{
return imgHsv;
}
cv::Mat & HsHistogram::getImgHsv(int chId)
{
return imgHsvSplit[chId];
}
cv::Mat & HsHistogram::getHsHist()
{
return hsHist;
}
|
v-lopez/pipol_tracker
|
src/pipol_tracker_lib/appearance_deprecated/hsHistogram.cpp
|
C++
|
mit
| 3,082 |
Bootstrap Skeleton for WordPress ChangeLog
==========================================
|
tepdara/Skeleton-WordPress-master
|
CHANGELOG.md
|
Markdown
|
mit
| 87 |
//
// immer: immutable data structures for C++
// Copyright (C) 2016, 2017, 2018 Juan Pedro Bolivar Puente
//
// This software is distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt
//
#pragma once
#include <immer/detail/util.hpp>
#include <immer/memory_policy.hpp>
namespace immer {
/*!
* Immutable box for a single value of type `T`.
*
* The box is always copiable and movable. The `T` copy or move
* operations are never called. Since a box is immutable, copying or
* moving just copy the underlying pointers.
*/
template <typename T,
typename MemoryPolicy = default_memory_policy>
class box
{
struct holder : MemoryPolicy::refcount
{
T value;
template <typename... Args>
holder(Args&&... args) : value{std::forward<Args>(args)...} {}
};
using heap = typename MemoryPolicy::heap::type;
holder* impl_ = nullptr;
box(holder* impl) : impl_{impl} {}
public:
using value_type = T;
using memory_policy = MemoryPolicy;
/*!
* Constructs a box holding `T{}`.
*/
box() : impl_{detail::make<heap, holder>()} {}
/*!
* Constructs a box holding `T{arg}`
*/
template <typename Arg,
typename Enable=std::enable_if_t<
!std::is_same<box, std::decay_t<Arg>>::value &&
std::is_constructible<T, Arg>::value>>
box(Arg&& arg)
: impl_{detail::make<heap, holder>(std::forward<Arg>(arg))} {}
/*!
* Constructs a box holding `T{arg1, arg2, args...}`
*/
template <typename Arg1, typename Arg2, typename... Args>
box(Arg1&& arg1, Arg2&& arg2, Args&& ...args)
: impl_{detail::make<heap, holder>(
std::forward<Arg1>(arg1),
std::forward<Arg2>(arg2),
std::forward<Args>(args)...)}
{}
friend void swap(box& a, box& b)
{ using std::swap; swap(a.impl_, b.impl_); }
box(box&& other) { swap(*this, other); }
box(const box& other) : impl_(other.impl_) { impl_->inc(); }
box& operator=(box&& other) { swap(*this, other); return *this; }
box& operator=(const box& other)
{
auto aux = other;
swap(*this, aux);
return *this;
}
~box()
{
if (impl_ && impl_->dec()) {
impl_->~holder();
heap::deallocate(sizeof(holder), impl_);
}
}
/*! Query the current value. */
const T& get() const { return impl_->value; }
/*! Conversion to the boxed type. */
operator const T&() const { return get(); }
/*! Access via dereference */
const T& operator* () const { return get(); }
/*! Access via pointer member access */
const T* operator-> () const { return &get(); }
/*! Comparison. */
bool operator==(detail::exact_t<const box&> other) const
{ return impl_ == other.value.impl_ || get() == other.value.get(); }
// Note that the `exact_t` disambiguates comparisons against `T{}`
// directly. In that case we want to use `operator T&` and
// compare directly. We definitely never want to convert a value
// to a box (which causes an allocation) just to compare it.
bool operator!=(detail::exact_t<const box&> other) const
{ return !(*this == other.value); }
bool operator<(detail::exact_t<const box&> other) const
{ return get() < other.value.get(); }
/*!
* Returns a new box built by applying the `fn` to the underlying
* value.
*
* @rst
*
* **Example**
* .. literalinclude:: ../example/box/box.cpp
* :language: c++
* :dedent: 8
* :start-after: update/start
* :end-before: update/end
*
* @endrst
*/
template <typename Fn>
box update(Fn&& fn) const&
{
return std::forward<Fn>(fn)(get());
}
template <typename Fn>
box&& update(Fn&& fn) &&
{
if (impl_->unique())
impl_->value = std::forward<Fn>(fn)(std::move(impl_->value));
else
*this = std::forward<Fn>(fn)(impl_->value);
return std::move(*this);
}
};
} // namespace immer
namespace std {
template <typename T, typename MP>
struct hash<immer::box<T, MP>>
{
std::size_t operator() (const immer::box<T, MP>& x) const
{
return std::hash<T>{}(*x);
}
};
} // namespace std
|
ivansib/sibcoin
|
src/immer/box.hpp
|
C++
|
mit
| 4,405 |
var app = require('app/app');
var channels = require('channels');
var Marionette = require('backbone.marionette');
module.exports = app.Behaviors.Navigator = Marionette.Behavior.extend({
ui: {
links: '[data-navigate], a[href^="/"]'
},
events: {
'click @ui.links': 'onClickNavigate'
},
onClickNavigate: function (e) {
e.preventDefault();
var url = $(e.currentTarget).data('navigate') || $(e.currentTarget).attr('href');
this.onNavigate(url);
},
onNavigate: function (url) {
channels.globalChannel.trigger('navigate', {
url: url,
trigger: true
});
}
});
|
gregcarrart/booket
|
src/javascript/app/behaviors/Navigator.js
|
JavaScript
|
mit
| 670 |
/**
* --- (C) Original BEM Tools
*
* Инструментарий для преобразования bemjson в bemdecl.
* Заимствованный.
*/
/**
* Добавляет второй депс в первый и возвращает результат.
* @param {Array} d1
* @param {Array} d2
* @returns {Array}
*/
function mergeDecls(d1, d2) {
var keys = {};
d1 ?
d1.forEach(function (o) { keys[o.name || o] = o; }) :
d1 = [];
d2.forEach(function (o2) {
var name = o2.name || o2;
if (keys.hasOwnProperty(name)) {
var o1 = keys[name];
o2.elems && (o1.elems = mergeDecls(o1.elems, o2.elems));
o2.mods && (o1.mods = mergeDecls(o1.mods, o2.mods));
o2.vals && (o1.vals = mergeDecls(o1.vals, o2.vals));
o2.techs && (o1.techs = mergeDecls(o1.techs, o2.techs));
} else {
d1.push(o2);
keys[name] = o2;
}
});
return d1;
}
/**
* Возвращает true, если переданное значение имеет примитивный тип.
* @param {*} obj
* @returns {Boolean}
*/
function isSimple(obj) {
var t = typeof obj;
return t === 'string' || t === 'number' || t === 'boolean';
}
/**
* Основная функция для преобразования в bemjson.
* @param {Object} obj
* @param {Function} fn
* @returns {Object}
*/
function iterateJson(obj, fn) {
if (obj && !isSimple(obj)) {
if (Array.isArray(obj)) {
var i = 0;
var l = obj.length;
while (i < l) {
iterateJson(obj[i++], fn);
}
} else {
fn(obj);
}
}
return obj;
}
function getBuilder(decl, block) {
return function (obj) {
var oldBlock = block;
block = obj.block || block;
obj.block && decl.push({ name: block });
obj.elem && decl.push({ name: block, elems: [{ name: obj.elem }] });
var mods;
var n;
var props;
if (mods = obj.mods) {
for (n in mods) {
if (mods.hasOwnProperty(n)) {
decl.push({
name: block,
mods: [{ name: n, vals: [ { name: mods[n] } ] }]
});
}
}
}
if (obj.elem && (mods = obj.elemMods)) {
for (n in mods) {
if (mods.hasOwnProperty(n)) {
decl.push({
name: block,
elems: [{
name: obj.elem,
mods: [{ name: n, vals: [ { name: mods[n] } ] }]
}]
});
}
}
}
props = Object.keys(obj).filter(function (k) {
return !({ block: 1, elem: 1, mods: 1, elemMods: 1 }).hasOwnProperty(k);
}).map(function (k) {
return obj[k];
});
iterateJson(props, getBuilder(decl, block));
block = oldBlock;
}
}
module.exports.iterateJson = iterateJson;
module.exports.getBuilder = getBuilder;
module.exports.mergeDecls = mergeDecls;
|
markelog/enb
|
exlib/bemjson2bemdecl.js
|
JavaScript
|
mit
| 3,243 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vi:ts=4:et
import pycurl
c = pycurl.Curl()
c.setopt(c.URL, 'http://pycurl.sourceforge.net/tests/testfileupload.php')
c.setopt(c.HTTPPOST, [
('fileupload', (
# upload the contents of this file
c.FORM_FILE, __file__,
# specify a different file name for the upload
c.FORM_FILENAME, 'helloworld.py',
# specify a different content type
c.FORM_CONTENTTYPE, 'application/x-python',
)),
])
c.perform()
c.close()
|
GarySparrow/mFlaskWeb
|
venv/doc/pycurl/examples/quickstart/file_upload_real_fancy.py
|
Python
|
mit
| 513 |
/* ====================================================================
* Copyright (c) 2004-2010 Open Source Applications Foundation.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
* ====================================================================
*/
#ifndef _dateformat_h
#define _dateformat_h
PyObject *wrap_SimpleDateFormat(SimpleDateFormat *, int);
void _init_dateformat(PyObject *m);
#endif /* _dateformat_h */
|
fish2000/pyicu-praxa
|
includes/dateformat.h
|
C
|
mit
| 1,458 |
---
title: Бог этого мира
date: 31/12/2017
---
Деньги стали богом этого мира, а материализм — его религией. Материализм — это сложная и коварная система, которая предлагает временную защищенность, но не гарантирует абсолютной безопасности.
Материализм — это жизненная позиция, при которой желание богатства и обладания становится более важным и ценным, чем духовная жизнь. Имущество имеет определенную ценность, но мы не должны от него зависеть: «Умножается имущество, умножаются и потребляющие его; и какое благо для владеющего им: разве только смотреть своими глазами?» (Еккл. 5:10). Желая обладать мирскими благами, мы сталкиваемся с одной проблемой: сколько бы мы ни получили, этого никогда не будет достаточно. Мы стремимся получить все больше и больше, но полученное не способно удовлетворить нас надолго. Вот такая ловушка!
`Прочитайте 1 Ин. 2:16, 17. Что этот текст говорит нам о том, что действительно имеет значение?`
`Прочитайте Лк. 14:26–33. Что, согласно словам Иисуса, имеет наибольшее значение для христианина?`
Те, для кого деньги или стремление к деньгам становятся в жизни всем, должны учесть неминуемые последствия. «Ибо какая польза человеку, если он приобретет весь мир, а душе своей повредит?» (Мк. 8:36).
«Когда Христос пришел на землю, человечество, казалось, стремительно катилось к самому низкому уровню. Устои общества были подорваны. Жизнь стала лживой и обычаи искусственными… Во всем мире различные религии утрачивали свое влияние на умы и души. Испытывая отвращение к небылицам и лжи и гоня прочь мысли о духовном, люди поворачивались к неверию и материализму. Оставив мысли о вечности, люди стали жить преходящим» (Эллен Уайт. Воспитание, с. 74, 75).
Люди обращаются к неверию и материализму и живут преходящим. Звучит знакомо, не правда ли?
`Нам всем нравится обладать имуществом. Вопрос заключается в следующем: как мы можем понять, что не мы владеем вещами, а они — нами? Кто один должен владеть нашими умами и как мы можем быть уверены в том, что Он действительно владеет нами?`
|
PrJared/sabbath-school-lessons
|
src/ru/2018-01/01/02.md
|
Markdown
|
mit
| 3,616 |
---
title: Разширено изучаване
date: 10/11/2017
---
**Прочетете още**:
Елън Уайт: По стъпките на великия Лекар – статията „Помощ във всекидневния живот”; Избрани вести, кн. 1 – статията „Христос – центърът на вестта”; Патриарси и пророци – статията „Изкушението и падението“ и Адвентна енциклопедия – статията „Оправдание”.
„Мнозина са измамени относно състоянието на сърцата си. Те не осъзнават, че естественото сърце е измамливо повече от всичко и е отчайващо зло. Обличат се със собствената си правда и са доволни да постигнат личните си човешки стандарти за характер“ (Уайт, Е. Избрани вести. Кн. 1. Гл. 48: „Божественият стандарт“, изд. „Ел Уай“, София, 2013, с. 321).
„Огромна е нуждата Христос да бъде проповядван като единствена надежда и спасение. Когато е представена доктрината за оправданието (...) тя достига до мнозина така, както водата до жадния пътешественик. Мисълта, че праведността на Христос ни е вменена не поради някакви наши заслуги, а като безплатен дар от Бога, изглежда скъпоценна” (Пак там. Гл. 56: „Истината, носеща Божествени пълномощия“, с. 360).
„Който е образ на Бъдещия (Римляни 5:14). Как Адам е образ на Христос? Както Адам става причина за смъртта на своите потомци, въпреки че те не са яли от забраненото дърво, така и Христос раздава праведност на тези, които са от Него, въпреки че не са заслужили никаква праведност; защото чрез Кръста Той осигурява (праведност) на всички хора. Образът на Адамовия грях е в нас, защото ние умираме точно така, сякаш сме съгрешили като него. Образът на Христос е в нас, защото ние живеем така, сякаш сме изпълнили всяка правда като Него” (Лутер, М. Коментар върху „Посланието към римляните“. С. 96, 97 – англ. изд.).
**За разискване**:
`1. Как разбираме следния цитат от Елън Уайт? „Нуждаем се от по-подробно изучаване на Божието Слово. Особено внимание да се обърне на „Даниил” и „Откровение”, както никога по-рано не се е правило в историята на нашето дело. Може би ще тряб¬ва да казваме по-малко неща, коато говорим по някои въпроси относно римската власт и папството, а да обръщаме внимание на това, което пророците и апостолите са писали под вдъхновението на Божия Дух“ (Уайт, Е. Евангелизъм. Кн. 3. Част XV: „Работа със специални групи хора“ – Достигане на католиците, изд. „Нов живот“, София, 2001, с. 129).`
`2. Помислете върху реалността на смъртта – какво причинява не само на живота, но и на смисъла на живота. Множество писатели и философи негодуват поради пълното безсмислие на живота, защото той приключва с вечна смърт. Как да им отговорим ние като християни? Защо надеждата, която имаме в Исус, е единственият отговор на това безсмислие?`
`3. Така както грехопадението на Адам налага върху всички нас греховното естество, победата на Исус предлага обещание за вечен живот на всички, които го приемат с вяра, без изключения. След като ни е осигурено нещо толкова прекрасно, какво пречи на хората да протегнат ръка и нетърпеливо да го изискат за себе си? Как всеки от нас може да помогне на търсещите да разберат по-добре това, което Христос предлага и е сторил за тях?`
|
imasaru/sabbath-school-lessons
|
src/bg/2017-04/06/07.md
|
Markdown
|
mit
| 5,479 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.Management.Compute.Models
{
public partial class DiffDiskSettings : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (Option != null)
{
writer.WritePropertyName("option");
writer.WriteStringValue(Option);
}
if (Placement != null)
{
writer.WritePropertyName("placement");
writer.WriteStringValue(Placement.Value.ToString());
}
writer.WriteEndObject();
}
internal static DiffDiskSettings DeserializeDiffDiskSettings(JsonElement element)
{
string option = default;
DiffDiskPlacement? placement = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("option"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
option = property.Value.GetString();
continue;
}
if (property.NameEquals("placement"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
placement = new DiffDiskPlacement(property.Value.GetString());
continue;
}
}
return new DiffDiskSettings(option, placement);
}
}
}
|
hyonholee/azure-sdk-for-net
|
sdk/testcommon/Azure.Management.Compute.2019_12/src/Generated/Models/DiffDiskSettings.Serialization.cs
|
C#
|
mit
| 1,842 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Component\Debug\Debug;
use Symfony\Component\HttpFoundation\Request;
/*
* Sylius front controller.
* Testing dev-like environment.
*/
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !(in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', 'fe80::1', '::1', '113.0.0.1', '10.0.0.1'], true) || php_sapi_name() === 'cli-server')
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
Debug::enable();
$kernel = new AppKernel('test', true);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
patrick-mcdougle/Sylius
|
web/app_test.php
|
PHP
|
mit
| 1,050 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.CosmosDB.Models;
namespace Azure.ResourceManager.CosmosDB
{
/// <summary> The CollectionPartition service client. </summary>
public partial class CollectionPartitionOperations
{
private readonly ClientDiagnostics _clientDiagnostics;
private readonly HttpPipeline _pipeline;
internal CollectionPartitionRestOperations RestClient { get; }
/// <summary> Initializes a new instance of CollectionPartitionOperations for mocking. </summary>
protected CollectionPartitionOperations()
{
}
/// <summary> Initializes a new instance of CollectionPartitionOperations. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="subscriptionId"> The ID of the target subscription. </param>
/// <param name="endpoint"> server parameter. </param>
internal CollectionPartitionOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null)
{
RestClient = new CollectionPartitionRestOperations(clientDiagnostics, pipeline, subscriptionId, endpoint);
_clientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
}
/// <summary> Retrieves the metrics determined by the given filter for the given collection, split by partition. </summary>
/// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
/// <param name="accountName"> Cosmos DB database account name. </param>
/// <param name="databaseRid"> Cosmos DB database rid. </param>
/// <param name="collectionRid"> Cosmos DB collection rid. </param>
/// <param name="filter"> An OData filter expression that describes a subset of metrics to return. The parameters that can be filtered are name.value (name of the metric, can have an or of multiple names), startTime, endTime, and timeGrain. The supported operator is eq. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="accountName"/>, <paramref name="databaseRid"/>, <paramref name="collectionRid"/>, or <paramref name="filter"/> is null. </exception>
public virtual AsyncPageable<PartitionMetric> ListMetricsAsync(string resourceGroupName, string accountName, string databaseRid, string collectionRid, string filter, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (accountName == null)
{
throw new ArgumentNullException(nameof(accountName));
}
if (databaseRid == null)
{
throw new ArgumentNullException(nameof(databaseRid));
}
if (collectionRid == null)
{
throw new ArgumentNullException(nameof(collectionRid));
}
if (filter == null)
{
throw new ArgumentNullException(nameof(filter));
}
async Task<Page<PartitionMetric>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("CollectionPartitionOperations.ListMetrics");
scope.Start();
try
{
var response = await RestClient.ListMetricsAsync(resourceGroupName, accountName, databaseRid, collectionRid, filter, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, null);
}
/// <summary> Retrieves the metrics determined by the given filter for the given collection, split by partition. </summary>
/// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
/// <param name="accountName"> Cosmos DB database account name. </param>
/// <param name="databaseRid"> Cosmos DB database rid. </param>
/// <param name="collectionRid"> Cosmos DB collection rid. </param>
/// <param name="filter"> An OData filter expression that describes a subset of metrics to return. The parameters that can be filtered are name.value (name of the metric, can have an or of multiple names), startTime, endTime, and timeGrain. The supported operator is eq. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="accountName"/>, <paramref name="databaseRid"/>, <paramref name="collectionRid"/>, or <paramref name="filter"/> is null. </exception>
public virtual Pageable<PartitionMetric> ListMetrics(string resourceGroupName, string accountName, string databaseRid, string collectionRid, string filter, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (accountName == null)
{
throw new ArgumentNullException(nameof(accountName));
}
if (databaseRid == null)
{
throw new ArgumentNullException(nameof(databaseRid));
}
if (collectionRid == null)
{
throw new ArgumentNullException(nameof(collectionRid));
}
if (filter == null)
{
throw new ArgumentNullException(nameof(filter));
}
Page<PartitionMetric> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("CollectionPartitionOperations.ListMetrics");
scope.Start();
try
{
var response = RestClient.ListMetrics(resourceGroupName, accountName, databaseRid, collectionRid, filter, cancellationToken);
return Page.FromValues(response.Value.Value, null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, null);
}
/// <summary> Retrieves the usages (most recent storage data) for the given collection, split by partition. </summary>
/// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
/// <param name="accountName"> Cosmos DB database account name. </param>
/// <param name="databaseRid"> Cosmos DB database rid. </param>
/// <param name="collectionRid"> Cosmos DB collection rid. </param>
/// <param name="filter"> An OData filter expression that describes a subset of usages to return. The supported parameter is name.value (name of the metric, can have an or of multiple names). </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="accountName"/>, <paramref name="databaseRid"/>, or <paramref name="collectionRid"/> is null. </exception>
public virtual AsyncPageable<PartitionUsage> ListUsagesAsync(string resourceGroupName, string accountName, string databaseRid, string collectionRid, string filter = null, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (accountName == null)
{
throw new ArgumentNullException(nameof(accountName));
}
if (databaseRid == null)
{
throw new ArgumentNullException(nameof(databaseRid));
}
if (collectionRid == null)
{
throw new ArgumentNullException(nameof(collectionRid));
}
async Task<Page<PartitionUsage>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("CollectionPartitionOperations.ListUsages");
scope.Start();
try
{
var response = await RestClient.ListUsagesAsync(resourceGroupName, accountName, databaseRid, collectionRid, filter, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, null);
}
/// <summary> Retrieves the usages (most recent storage data) for the given collection, split by partition. </summary>
/// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param>
/// <param name="accountName"> Cosmos DB database account name. </param>
/// <param name="databaseRid"> Cosmos DB database rid. </param>
/// <param name="collectionRid"> Cosmos DB collection rid. </param>
/// <param name="filter"> An OData filter expression that describes a subset of usages to return. The supported parameter is name.value (name of the metric, can have an or of multiple names). </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="accountName"/>, <paramref name="databaseRid"/>, or <paramref name="collectionRid"/> is null. </exception>
public virtual Pageable<PartitionUsage> ListUsages(string resourceGroupName, string accountName, string databaseRid, string collectionRid, string filter = null, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (accountName == null)
{
throw new ArgumentNullException(nameof(accountName));
}
if (databaseRid == null)
{
throw new ArgumentNullException(nameof(databaseRid));
}
if (collectionRid == null)
{
throw new ArgumentNullException(nameof(collectionRid));
}
Page<PartitionUsage> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("CollectionPartitionOperations.ListUsages");
scope.Start();
try
{
var response = RestClient.ListUsages(resourceGroupName, accountName, databaseRid, collectionRid, filter, cancellationToken);
return Page.FromValues(response.Value.Value, null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, null);
}
}
}
|
ayeletshpigelman/azure-sdk-for-net
|
sdk/cosmosdb/Azure.ResourceManager.CosmosDB/src/Generated/CollectionPartitionOperations.cs
|
C#
|
mit
| 12,355 |
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# Require this file using `require "spec_helper"` to ensure that it is only
# loaded once.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
require 'vcr'
require 'webmock/rspec'
require 'simplecov'
SimpleCov.start
VCR.configure do |config|
config.cassette_library_dir = File.expand_path('../cassettes', __FILE__)
config.hook_into :webmock
config.configure_rspec_metadata!
end
RSpec.configure do |config|
config.run_all_when_everything_filtered = true
config.filter_run :focus
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = 'random'
end
|
circle-cli/circle-cli
|
spec/spec_helper.rb
|
Ruby
|
mit
| 915 |
using System.Linq.Tests.Helpers;
using Xunit;
namespace System.Linq.Tests
{
public class SingleTests
{
[Fact]
public void FailOnEmpty()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().Single());
}
[Fact]
public void DefaultOnEmpty()
{
Assert.Equal(0, Enumerable.Empty<int>().SingleOrDefault());
}
[Fact]
public void FindSingle()
{
Assert.Equal(42, Enumerable.Repeat(42, 1).Single());
}
[Theory]
[InlineData(1, 100)]
[InlineData(42, 100)]
public void FindSingleMatch(int target, int range)
{
Assert.Equal(target, Enumerable.Range(0, range).Single(i => i == target));
}
}
}
|
misterzik/corefx
|
src/System.Linq/tests/SingleTests.cs
|
C#
|
mit
| 807 |
using Microsoft.Bot.Builder.Calling.ObjectModel.Misc;
using Newtonsoft.Json;
namespace Microsoft.Bot.Builder.Calling.ObjectModel.Contracts
{
/// <summary>
/// Once we have peformed the "actions" requested by the customer, we POST back to customer callback Url with this "result" object.
/// </summary>
[JsonObject(MemberSerialization.OptOut)]
public class ConversationResult : ConversationBase
{
/// <summary>
/// a. We would always return the outcome :
/// i. of the last operation if all operations were performed successfully OR
/// ii. outcome of first failed operation
/// b. If any operation fails, then we immediately callback the customer webservice with the outcome,
/// and skip processing other operations defined in the "actions" list.
/// c. If no callback link is provided, then we keep performing all specified operations, until
/// i. we hit the end - then we hangup (if call connected to server call agent)
/// ii. We hit a failure - then we hangup (if call connected to server call agent)
/// iii. We hit a max call duration timeout - then we hangup (if call connected to server call agent)
/// d. Any validation failure of this response object would result in us returning
/// the WorkflowValidationOutcome object to the customer's callback url and not proceed with any defined actions.
/// </summary>
[JsonProperty(Required = Required.Always)]
public OperationOutcomeBase OperationOutcome { get; set; }
/// <summary>
/// Current state of the Call
/// </summary>
[JsonProperty(Required = Required.Always)]
public CallState CallState { get; set; }
public override void Validate()
{
base.Validate();
ValidOutcomes.Validate(this.OperationOutcome);
}
}
}
|
dr-em/BotBuilder
|
CSharp/Library/Microsoft.Bot.Builder.Calling/Models/Contracts/ConversationResult.cs
|
C#
|
mit
| 1,943 |
(function() {
'use strict';
angular.module('foundation.notification', ['foundation.core'])
.controller('ZfNotificationController', ZfNotificationController)
.directive('zfNotificationSet', zfNotificationSet)
.directive('zfNotification', zfNotification)
.directive('zfNotificationStatic', zfNotificationStatic)
.directive('zfNotify', zfNotify)
;
ZfNotificationController.$inject = ['$scope', 'FoundationApi'];
function ZfNotificationController($scope, foundationApi) {
var controller = this;
controller.notifications = $scope.notifications = [];
controller.addNotification = function(info) {
var id = foundationApi.generateUuid();
info.id = id;
$scope.notifications.push(info);
};
controller.removeNotification = function(id) {
$scope.notifications.forEach(function(notification) {
if(notification.id === id) {
var ind = $scope.notifications.indexOf(notification);
$scope.notifications.splice(ind, 1);
}
});
};
controller.clearAll = function() {
while($scope.notifications.length > 0) {
$scope.notifications.pop();
}
};
}
zfNotificationSet.$inject = ['FoundationApi'];
function zfNotificationSet(foundationApi) {
var directive = {
restrict: 'EA',
templateUrl: 'components/notification/notification-set.html',
controller: 'ZfNotificationController',
scope: true,
link: link
};
return directive;
function link(scope, element, attrs, controller) {
foundationApi.subscribe(attrs.id, function(msg) {
if(msg === 'clearall') {
controller.clearAll();
} else {
controller.addNotification(msg);
scope.$apply();
}
});
}
}
zfNotification.$inject = ['FoundationApi'];
function zfNotification(foundationApi) {
var directive = {
restrict: 'EA',
templateUrl: 'components/notification/notification.html',
replace: true,
transclude: true,
require: '^zfNotificationSet',
controller: function() { },
scope: {
title: '=?',
content: '=?',
image: '=?',
notifId: '=',
position: '=?',
color: '=?'
},
compile: compile
};
return directive;
function compile() {
return {
pre: preLink,
post: postLink
};
function preLink(scope, iElement, iAttrs) {
iAttrs.$set('zf-closable', 'notification');
}
function postLink(scope, element, attrs, controller) {
scope.active = false;
scope.position = scope.position ? scope.position.split(' ').join('-') : 'top-right';
var animationIn = attrs.animationIn || 'fadeIn';
var animationOut = attrs.animationOut || 'fadeOut';
//due to dynamic insertion of DOM, we need to wait for it to show up and get working!
setTimeout(function() {
scope.active = true;
foundationApi.animate(element, scope.active, animationIn, animationOut);
}, 50);
scope.remove = function() {
scope.active = false;
foundationApi.animate(element, scope.active, animationIn, animationOut);
setTimeout(function() {
controller.removeNotification(scope.notifId);
}, 50);
};
}
}
}
zfNotificationStatic.$inject = ['FoundationApi'];
function zfNotificationStatic(foundationApi) {
var directive = {
restrict: 'EA',
templateUrl: 'components/notification/notification.html',
replace: true,
transclude: true,
scope: {
title: '@?',
content: '@?',
image: '@?',
position: '@?',
color: '@?'
},
compile: compile
};
return directive;
function compile() {
var type = 'notification';
return {
pre: preLink,
post: postLink
};
function preLink(scope, iElement, iAttrs, controller) {
iAttrs.$set('zf-closable', type);
}
function postLink(scope, element, attrs, controller) {
scope.position = scope.position ? scope.position.split(' ').join('-') : 'top-right';
var animationIn = attrs.animationIn || 'fadeIn';
var animationOut = attrs.animationOut || 'fadeOut';
foundationApi.subscribe(attrs.id, function(msg) {
if(msg === 'show' || msg === 'open') {
scope.show();
} else if (msg === 'close' || msg === 'hide') {
scope.hide();
} else if (msg === 'toggle') {
scope.toggle();
}
scope.$apply();
return;
});
scope.hide = function() {
scope.active = false;
foundationApi.animate(element, scope.active, animationIn, animationOut);
return;
};
scope.remove = function() {
scope.hide();
foundationApi.animate(element, scope.active, animationIn, animationOut);
};
scope.show = function() {
scope.active = true;
foundationApi.animate(element, scope.active, animationIn, animationOut);
return;
};
scope.toggle = function() {
scope.active = !scope.active;
foundationApi.animate(element, scope.active, animationIn, animationOut);
return;
};
}
}
}
zfNotify.$inject = ['FoundationApi'];
function zfNotify(foundationApi) {
var directive = {
restrict: 'A',
scope: {
title: '@?',
content: '@?',
position: '@?',
color: '@?',
image: '@?'
},
link: link
};
return directive;
function link(scope, element, attrs, controller) {
element.on('click', function(e) {
foundationApi.publish(attrs.zfNotify, {
title: scope.title,
content: scope.content,
position: scope.position,
color: scope.color,
image: scope.image
});
e.preventDefault();
});
}
}
})();
|
svil4ok/hranitelni-dobavki
|
public/assets/libs/foundation-apps/js/angular/components/notification/notification.js
|
JavaScript
|
mit
| 6,080 |
/*
* Responsee JS - v3 - 2015-08-22
* http://www.myresponsee.com
* Copyright 2015, Vision Design - graphic zoo
* Free to use under the MIT license.
*/
jQuery(document).ready(function($) {
//Responsee tabs
$('.tabs').each(function(intex, element) {
current_tabs = $(this);
$(this).prepend('<div class="tab-nav line"></div>');
var tab_buttons = $(element).find('.tab-label');
$(this).children('.tab-nav').prepend(tab_buttons);
$(this).children('.tab-item').each(function(i) {
$(this).attr("id", "tab-" + (i + 1));
});
$(".tab-nav").each(function() {
$(this).children().each(function(i) {
$(this).attr("href", "#tab-" + (i + 1));
});
});
$(this).find(".tab-nav a").click(function(event) {
$(this).parent().children().removeClass("active-btn");
$(this).addClass("active-btn");
var tab = $(this).attr("href");
$(this).parent().parent().find(".tab-item").not(tab).css("display", "none");
$(this).parent().parent().find(tab).fadeIn();
return false;
});
});
//Responsee eside nav
$('.aside-nav > ul > li ul').each(function(index, element) {
var count = $(element).find('li').length;
var content = '<span class="count-number"> ' + count + '</span>';
$(element).closest('li').children('a').append(content);
});
$('.aside-nav > ul > li:has(ul)').addClass('aside-submenu');
$('.aside-nav > ul ul > li:has(ul)').addClass('aside-sub-submenu');
$('.aside-nav > ul > li.aside-submenu > a').attr('aria-haspopup', 'true').click(function() {
//Close other open sub menus
$('.aside-nav ul li.aside-submenu > ul').removeClass('show-aside-ul', 'slow');
$('.aside-nav ul li.aside-submenu:hover > ul').toggleClass('show-aside-ul', 'slow');
});
$('.aside-nav > ul ul > li.aside-sub-submenu > a').attr('aria-haspopup', 'true').click(function() {
//Close other open sub menus
$('.aside-nav ul ul li > ul').removeClass('show-aside-ul', 'slow');
$('.aside-nav ul ul li:hover > ul').toggleClass('show-aside-ul', 'slow');
});
//Responsee nav
$('.top-nav > ul > li ul').each(function(index, element) {
var count = $(element).find('li').length;
var content = '<span class="count-number"> ' + count + '</span>';
$(element).closest('li').children('a').append(content);
});
$('.top-nav > ul li:has(ul)').addClass('submenu');
$('.top-nav > ul ul li:has(ul)').addClass('sub-submenu').removeClass('submenu');
$('.top-nav > ul li.submenu > a').attr('aria-haspopup', 'true').click(function() {
//Close other open sub menus
$('.top-nav > ul li.submenu > ul').removeClass('show-ul', 'slow');
$('.top-nav > ul li.submenu:hover > ul').toggleClass('show-ul', 'slow');
});
$('.top-nav > ul ul > li.sub-submenu > a').attr('aria-haspopup', 'true').click(function() {
//Close other open sub menus
$('.top-nav ul ul li > ul').removeClass('show-ul', 'slow');
$('.top-nav ul ul li:hover > ul').toggleClass('show-ul', 'slow');
});
$('.nav-text').click(function() {
$('.top-nav > ul').toggleClass('show-menu', 'slow');
});
//Custom forms
$(function() {
var input = document.createElement("input");
if (('placeholder' in input) == false) {
$('[placeholder]').focus(function() {
var i = $(this);
if (i.val() == i.attr('placeholder')) {
i.val('').removeClass('placeholder');
if (i.hasClass('password')) {
i.removeClass('password');
this.type = 'password';
}
}
}).blur(function() {
var i = $(this);
if (i.val() == '' || i.val() == i.attr('placeholder')) {
if (this.type == 'password') {
i.addClass('password');
this.type = 'text';
}
i.addClass('placeholder').val(i.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var i = $(this);
if (i.val() == i.attr('placeholder')) i.val('');
})
});
}
});
//Active item
var url = window.location.href;
$('a').filter(function() {
return this.href == url;
}).parent('li').addClass('active-item');
var url = window.location.href;
$('.aside-nav a').filter(function() {
return this.href == url;
}).parent('li').parent('ul').addClass('active-aside-item');
var url = window.location.href;
$('.aside-nav a').filter(function() {
return this.href == url;
}).parent('li').parent('ul').parent('li').parent('ul').addClass('active-aside-item');
var url = window.location.href;
$('.aside-nav a').filter(function() {
return this.href == url;
}).parent('li').parent('ul').parent('li').parent('ul').parent('li').parent('ul').addClass('active-aside-item');
});
|
rbuda/mgsi
|
mgsi/js/responsee.js
|
JavaScript
|
mit
| 4,875 |
-- *** STRUCTURE: `tbl_authors` ***
DROP TABLE IF EXISTS `tbl_authors`;
CREATE TABLE `tbl_authors` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(20) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`password` varchar(150) COLLATE utf8_unicode_ci NOT NULL,
`first_name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`last_name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`last_seen` datetime DEFAULT '1000-01-01 00:00:00',
`user_type` enum('author','manager','developer') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'author',
`primary` enum('yes','no') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'no',
`default_area` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`auth_token_active` enum('yes','no') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'no',
`language` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`),
UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_cache` ***
DROP TABLE IF EXISTS `tbl_cache`;
CREATE TABLE `tbl_cache` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`hash` varchar(32) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`namespace` VARCHAR(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`creation` int(14) NOT NULL DEFAULT '0',
`expiry` int(14) unsigned DEFAULT NULL,
`data` longtext COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `hash` (`hash`),
KEY `expiry` (`expiry`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_entries` ***
DROP TABLE IF EXISTS `tbl_entries`;
CREATE TABLE `tbl_entries` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`section_id` int(11) unsigned NOT NULL,
`author_id` int(11) unsigned NOT NULL,
`modification_author_id` int(11) unsigned NOT NULL DEFAULT 1,
`creation_date` datetime NOT NULL DEFAULT '1000-01-01 00:00:00',
`creation_date_gmt` datetime NOT NULL DEFAULT '1000-01-01 00:00:00',
`modification_date` datetime NOT NULL DEFAULT '1000-01-01 00:00:00',
`modification_date_gmt` datetime NOT NULL DEFAULT '1000-01-01 00:00:00',
PRIMARY KEY (`id`),
KEY `section_id` (`section_id`),
KEY `author_id` (`author_id`),
KEY `creation_date` (`creation_date`),
KEY `creation_date_gmt` (`creation_date_gmt`),
KEY `modification_date` (`modification_date`),
KEY `modification_date_gmt` (`modification_date_gmt`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_extensions` ***
DROP TABLE IF EXISTS `tbl_extensions`;
CREATE TABLE `tbl_extensions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`status` enum('enabled','disabled') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'enabled',
`version` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_extensions_delegates` ***
DROP TABLE IF EXISTS `tbl_extensions_delegates`;
CREATE TABLE `tbl_extensions_delegates` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`extension_id` int(11) NOT NULL,
`page` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`delegate` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`callback` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `extension_id` (`extension_id`),
KEY `page` (`page`),
KEY `delegate` (`delegate`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_fields` ***
DROP TABLE IF EXISTS `tbl_fields`;
CREATE TABLE `tbl_fields` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`label` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`element_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`type` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`parent_section` int(11) NOT NULL DEFAULT '0',
`required` enum('yes','no') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'yes',
`sortorder` int(11) NOT NULL DEFAULT '1',
`location` enum('main','sidebar') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'main',
`show_column` enum('yes','no') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'no',
PRIMARY KEY (`id`),
KEY `index` (`element_name`,`type`,`parent_section`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_fields_author` ***
DROP TABLE IF EXISTS `tbl_fields_author`;
CREATE TABLE `tbl_fields_author` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`field_id` int(11) unsigned NOT NULL,
`allow_multiple_selection` enum('yes','no') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'no',
`default_to_current_user` enum('yes','no') COLLATE utf8_unicode_ci NOT NULL,
`author_types` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `field_id` (`field_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_fields_checkbox` ***
DROP TABLE IF EXISTS `tbl_fields_checkbox`;
CREATE TABLE `tbl_fields_checkbox` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`field_id` int(11) unsigned NOT NULL,
`default_state` enum('on','off') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'on',
`description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `field_id` (`field_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_fields_date` ***
DROP TABLE IF EXISTS `tbl_fields_date`;
CREATE TABLE `tbl_fields_date` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`field_id` int(11) unsigned NOT NULL,
`pre_populate` varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL,
`calendar` enum('yes','no') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'no',
`time` enum('yes','no') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'yes',
PRIMARY KEY (`id`),
KEY `field_id` (`field_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_fields_input` ***
DROP TABLE IF EXISTS `tbl_fields_input`;
CREATE TABLE `tbl_fields_input` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`field_id` int(11) unsigned NOT NULL,
`validator` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `field_id` (`field_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_fields_select` ***
DROP TABLE IF EXISTS `tbl_fields_select`;
CREATE TABLE `tbl_fields_select` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`field_id` int(11) unsigned NOT NULL,
`allow_multiple_selection` enum('yes','no') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'no',
`sort_options` enum('yes','no') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'no',
`static_options` text COLLATE utf8_unicode_ci,
`dynamic_options` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `field_id` (`field_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_fields_taglist` ***
DROP TABLE IF EXISTS `tbl_fields_taglist`;
CREATE TABLE `tbl_fields_taglist` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`field_id` int(11) unsigned NOT NULL,
`validator` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`pre_populate_source` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `field_id` (`field_id`),
KEY `pre_populate_source` (`pre_populate_source`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_fields_textarea` ***
DROP TABLE IF EXISTS `tbl_fields_textarea`;
CREATE TABLE `tbl_fields_textarea` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`field_id` int(11) unsigned NOT NULL,
`formatter` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`size` int(3) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `field_id` (`field_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_fields_upload` ***
DROP TABLE IF EXISTS `tbl_fields_upload`;
CREATE TABLE `tbl_fields_upload` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`field_id` int(11) unsigned NOT NULL,
`destination` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`validator` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `field_id` (`field_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_forgotpass` ***
DROP TABLE IF EXISTS `tbl_forgotpass`;
CREATE TABLE `tbl_forgotpass` (
`author_id` int(11) NOT NULL DEFAULT '0',
`token` varchar(16) COLLATE utf8_unicode_ci NOT NULL,
`expiry` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`author_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_pages` ***
DROP TABLE IF EXISTS `tbl_pages`;
CREATE TABLE `tbl_pages` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`parent` int(11) DEFAULT NULL,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`handle` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`path` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`params` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`data_sources` text COLLATE utf8_unicode_ci,
`events` text COLLATE utf8_unicode_ci,
`sortorder` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `parent` (`parent`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_pages_types` ***
DROP TABLE IF EXISTS `tbl_pages_types`;
CREATE TABLE `tbl_pages_types` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`page_id` int(11) unsigned NOT NULL,
`type` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `page_id` (`page_id`,`type`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_sections` ***
DROP TABLE IF EXISTS `tbl_sections`;
CREATE TABLE `tbl_sections` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`handle` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`sortorder` int(11) NOT NULL DEFAULT '0',
`hidden` enum('yes','no') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'no',
`filter` enum('yes','no') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'yes',
`navigation_group` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Content',
`author_id` int(11) unsigned NOT NULL DEFAULT 1,
`modification_author_id` int(11) unsigned NOT NULL DEFAULT 1,
`creation_date` datetime NOT NULL DEFAULT '1000-01-01 00:00:00',
`creation_date_gmt` datetime NOT NULL DEFAULT '1000-01-01 00:00:00',
`modification_date` datetime NOT NULL DEFAULT '1000-01-01 00:00:00',
`modification_date_gmt` datetime NOT NULL DEFAULT '1000-01-01 00:00:00',
PRIMARY KEY (`id`),
UNIQUE KEY `handle` (`handle`),
KEY `creation_date` (`creation_date`),
KEY `creation_date_gmt` (`creation_date_gmt`),
KEY `modification_date` (`modification_date`),
KEY `modification_date_gmt` (`modification_date_gmt`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_sections_association` ***
DROP TABLE IF EXISTS `tbl_sections_association`;
CREATE TABLE `tbl_sections_association` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`parent_section_id` int(11) unsigned NOT NULL,
`parent_section_field_id` int(11) unsigned DEFAULT NULL,
`child_section_id` int(11) unsigned NOT NULL,
`child_section_field_id` int(11) unsigned NOT NULL,
`hide_association` enum('yes','no') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'no',
`interface` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`editor` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `parent_section_id` (`parent_section_id`,`child_section_id`,`child_section_field_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- *** STRUCTURE: `tbl_sessions` ***
DROP TABLE IF EXISTS `tbl_sessions`;
CREATE TABLE `tbl_sessions` (
`session` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`session_expires` int(10) unsigned NOT NULL DEFAULT '0',
`session_data` text COLLATE utf8_unicode_ci,
PRIMARY KEY (`session`),
KEY `session_expires` (`session_expires`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
|
jensscherbl/symphony
|
install/includes/install.sql
|
SQL
|
mit
| 12,249 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.