code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
/**
* The result of the parser is an array of statements are extensions of the
* class defined here.
*
* A statement represents the result of parsing the lexemes.
*
* @package SqlParser
*/
namespace SqlParser;
use SqlParser\Components\OptionsArray;
/**
* Abstract statement definition.
*
* @category Statements
* @package SqlParser
* @license https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
*/
abstract class Statement
{
/**
* Options for this statement.
*
* The option would be the key and the value can be an integer or an array.
*
* The integer represents only the index used.
*
* The array may have two keys: `0` is used to represent the index used and
* `1` is the type of the option (which may be 'var' or 'var='). Both
* options mean they expect a value after the option (e.g. `A = B` or `A B`,
* in which case `A` is the key and `B` is the value). The only difference
* is in the building process. `var` options are built as `A B` and `var=`
* options are built as `A = B`
*
* Two options that can be used together must have different values for
* indexes, else, when they will be used together, an error will occur.
*
* @var array
*/
public static $OPTIONS = array();
/**
* The clauses of this statement, in order.
*
* The value attributed to each clause is used by the builder and it may
* have one of the following values:
*
* - 1 = 01 - add the clause only
* - 2 = 10 - add the keyword
* - 3 = 11 - add both the keyword and the clause
*
* @var array
*/
public static $CLAUSES = array();
/**
* The options of this query.
*
* @var OptionsArray
*
* @see static::$OPTIONS
*/
public $options;
/**
* The index of the first token used in this statement.
*
* @var int
*/
public $first;
/**
* The index of the last token used in this statement.
*
* @var int
*/
public $last;
/**
* Constructor.
*
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*/
public function __construct(Parser $parser = null, TokensList $list = null)
{
if (($parser !== null) && ($list !== null)) {
$this->parse($parser, $list);
}
}
/**
* Builds the string representation of this statement.
*
* @return string
*/
public function build()
{
/**
* Query to be returned.
*
* @var string $query
*/
$query = '';
/**
* Clauses which were built already.
*
* It is required to keep track of built clauses because some fields,
* for example `join` is used by multiple clauses (`JOIN`, `LEFT JOIN`,
* `LEFT OUTER JOIN`, etc.). The same happens for `VALUE` and `VALUES`.
*
* A clause is considered built just after fields' value
* (`$this->field`) was used in building.
*
* @var array
*/
$built = array();
/**
* Statement's clauses.
*
* @var array
*/
$clauses = $this->getClauses();
foreach ($clauses as $clause) {
/**
* The name of the clause.
*
* @var string $name
*/
$name = $clause[0];
/**
* The type of the clause.
*
* @see self::$CLAUSES
* @var int $type
*/
$type = $clause[1];
/**
* The builder (parser) of this clause.
*
* @var Component $class
*/
$class = Parser::$KEYWORD_PARSERS[$name]['class'];
/**
* The name of the field that is used as source for the builder.
* Same field is used to store the result of parsing.
*
* @var string $field
*/
$field = Parser::$KEYWORD_PARSERS[$name]['field'];
// The field is empty, there is nothing to be built.
if (empty($this->$field)) {
continue;
}
// Checking if this field was already built.
if ($type & 1) {
if (!empty($built[$field])) {
continue;
}
$built[$field] = true;
}
// Checking if the name of the clause should be added.
if ($type & 2) {
$query .= $name . ' ';
}
// Checking if the result of the builder should be added.
if ($type & 1) {
$query .= $class::build($this->$field) . ' ';
}
}
return $query;
}
/**
* Parses the statements defined by the tokens list.
*
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*
* @return void
*/
public function parse(Parser $parser, TokensList $list)
{
/**
* Array containing all list of clauses parsed.
* This is used to check for duplicates.
*
* @var array $parsedClauses
*/
$parsedClauses = array();
// This may be corrected by the parser.
$this->first = $list->idx;
/**
* Whether options were parsed or not.
* For statements that do not have any options this is set to `true` by
* default.
*
* @var bool $parsedOptions
*/
$parsedOptions = empty(static::$OPTIONS);
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Checking if this closing bracket is the pair for a bracket
// outside the statement.
if (($token->value === ')') && ($parser->brackets > 0)) {
--$parser->brackets;
continue;
}
// Only keywords are relevant here. Other parts of the query are
// processed in the functions below.
if ($token->type !== Token::TYPE_KEYWORD) {
if (($token->type !== TOKEN::TYPE_COMMENT)
&& ($token->type !== Token::TYPE_WHITESPACE)
) {
$parser->error(__('Unexpected token.'), $token);
}
continue;
}
// Unions are parsed by the parser because they represent more than
// one statement.
if (($token->value === 'UNION') || ($token->value === 'UNION ALL') || ($token->value === 'UNION DISTINCT')) {
break;
}
$lastIdx = $list->idx;
// ON DUPLICATE KEY UPDATE ...
// has to be parsed in parent statement (INSERT or REPLACE)
// so look for it and break
if (get_class($this) === 'SqlParser\Statements\SelectStatement'
&& $token->value === 'ON'
) {
++$list->idx; // Skip ON
// look for ON DUPLICATE KEY UPDATE
$first = $list->getNextOfType(Token::TYPE_KEYWORD);
$second = $list->getNextOfType(Token::TYPE_KEYWORD);
$third = $list->getNextOfType(Token::TYPE_KEYWORD);
if ($first && $second && $third
&& $first->value === 'DUPLICATE'
&& $second->value === 'KEY'
&& $third->value === 'UPDATE'
) {
$list->idx = $lastIdx;
break;
}
}
$list->idx = $lastIdx;
/**
* The name of the class that is used for parsing.
*
* @var Component $class
*/
$class = null;
/**
* The name of the field where the result of the parsing is stored.
*
* @var string $field
*/
$field = null;
/**
* Parser's options.
*
* @var array $options
*/
$options = array();
// Looking for duplicated clauses.
if ((!empty(Parser::$KEYWORD_PARSERS[$token->value]))
|| (!empty(Parser::$STATEMENT_PARSERS[$token->value]))
) {
if (!empty($parsedClauses[$token->value])) {
$parser->error(
__('This type of clause was previously parsed.'),
$token
);
break;
}
$parsedClauses[$token->value] = true;
}
// Checking if this is the beginning of a clause.
if (!empty(Parser::$KEYWORD_PARSERS[$token->value])) {
$class = Parser::$KEYWORD_PARSERS[$token->value]['class'];
$field = Parser::$KEYWORD_PARSERS[$token->value]['field'];
if (!empty(Parser::$KEYWORD_PARSERS[$token->value]['options'])) {
$options = Parser::$KEYWORD_PARSERS[$token->value]['options'];
}
}
// Checking if this is the beginning of the statement.
if (!empty(Parser::$STATEMENT_PARSERS[$token->value])) {
if ((!empty(static::$CLAUSES)) // Undefined for some statements.
&& (empty(static::$CLAUSES[$token->value]))
) {
// Some keywords (e.g. `SET`) may be the beginning of a
// statement and a clause.
// If such keyword was found and it cannot be a clause of
// this statement it means it is a new statement, but no
// delimiter was found between them.
$parser->error(
__('A new statement was found, but no delimiter between it and the previous one.'),
$token
);
break;
}
if (!$parsedOptions) {
if (empty(static::$OPTIONS[$token->value])) {
// Skipping keyword because if it is not a option.
++$list->idx;
}
$this->options = OptionsArray::parse(
$parser,
$list,
static::$OPTIONS
);
$parsedOptions = true;
}
} elseif ($class === null) {
// There is no parser for this keyword and isn't the beginning
// of a statement (so no options) either.
$parser->error(__('Unrecognized keyword.'), $token);
continue;
}
$this->before($parser, $list, $token);
// Parsing this keyword.
if ($class !== null) {
++$list->idx; // Skipping keyword or last option.
$this->$field = $class::parse($parser, $list, $options);
}
$this->after($parser, $list, $token);
}
// This may be corrected by the parser.
$this->last = --$list->idx; // Go back to last used token.
}
/**
* Function called before the token is processed.
*
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
* @param Token $token The token that is being parsed.
*
* @return void
*/
public function before(Parser $parser, TokensList $list, Token $token)
{
}
/**
* Function called after the token was processed.
*
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
* @param Token $token The token that is being parsed.
*
* @return void
*/
public function after(Parser $parser, TokensList $list, Token $token)
{
}
/**
* Gets the clauses of this statement.
*
* @return array
*/
public function getClauses()
{
return static::$CLAUSES;
}
/**
* Builds the string representation of this statement.
*
* @see static::build
*
* @return string
*/
public function __toString()
{
return $this->build();
}
}
| TheCaveman93/TheCaveman93.github.io | wp-content/plugins/versionpress/vendor/phpmyadmin/sql-parser/src/Statement.php | PHP | mit | 12,965 |
var React = require('react');
var Router = require('react-router');
var whenKeys = require('when/keys');
var EventEmitter = require('events').EventEmitter;
var { Route, DefaultRoute, RouteHandler, Link } = Router;
var API = 'http://addressbook-api.herokuapp.com';
var loadingEvents = new EventEmitter();
function getJSON(url) {
if (getJSON._cache[url])
return Promise.resolve(getJSON._cache[url]);
return new Promise((resolve, reject) => {
var req = new XMLHttpRequest();
req.onload = function () {
if (req.status === 404) {
reject(new Error('not found'));
} else {
// fake a slow response every now and then
setTimeout(function () {
var data = JSON.parse(req.response);
resolve(data);
getJSON._cache[url] = data;
}, Math.random() > 0.5 ? 0 : 1000);
}
};
req.open('GET', url);
req.send();
});
}
getJSON._cache = {};
var App = React.createClass({
statics: {
fetchData (params) {
return getJSON(`${API}/contacts`).then((res) => res.contacts);
}
},
getInitialState () {
return { loading: false };
},
componentDidMount () {
var timer;
loadingEvents.on('loadStart', () => {
clearTimeout(timer);
// for slow responses, indicate the app is thinking
// otherwise its fast enough to just wait for the
// data to load
timer = setTimeout(() => {
this.setState({ loading: true });
}, 300);
});
loadingEvents.on('loadEnd', () => {
clearTimeout(timer);
this.setState({ loading: false });
});
},
renderContacts () {
return this.props.data.contacts.map((contact) => {
return (
<li>
<Link to="contact" params={contact}>{contact.first} {contact.last}</Link>
</li>
);
});
},
render () {
return (
<div className={this.state.loading ? 'loading' : ''}>
<ul>
{this.renderContacts()}
</ul>
<RouteHandler {...this.props}/>
</div>
);
}
});
var Contact = React.createClass({
statics: {
fetchData (params) {
return getJSON(`${API}/contacts/${params.id}`).then((res) => res.contact);
}
},
render () {
var { contact } = this.props.data;
return (
<div>
<p><Link to="contacts">Back</Link></p>
<h1>{contact.first} {contact.last}</h1>
<img key={contact.avatar} src={contact.avatar}/>
</div>
);
}
});
var Index = React.createClass({
render () {
return (
<div>
<h1>Welcome!</h1>
</div>
);
}
});
var routes = (
<Route name="contacts" path="/" handler={App}>
<DefaultRoute name="index" handler={Index}/>
<Route name="contact" path="contact/:id" handler={Contact}/>
</Route>
);
function fetchData(routes, params) {
return whenKeys.all(routes.filter((route) => {
return route.handler.fetchData;
}).reduce((data, route) => {
data[route.name] = route.handler.fetchData(params);
return data;
}, {}));
}
Router.run(routes, function (Handler, state) {
loadingEvents.emit('loadStart');
fetchData(state.routes, state.params).then((data) => {
loadingEvents.emit('loadEnd');
React.render(<Handler data={data}/>, document.getElementById('example'));
});
});
| winkler1/react-router | examples/async-data/app.js | JavaScript | mit | 3,295 |
#!/usr/bin/env python
#
# Copyright 2007 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
#
# 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.
#
"""Simple, schema-based database abstraction layer for the datastore.
Modeled after Django's abstraction layer on top of SQL databases,
http://www.djangoproject.com/documentation/mode_api/. Ours is a little simpler
and a lot less code because the datastore is so much simpler than SQL
databases.
The programming model is to declare Python subclasses of the Model class,
declaring datastore properties as class members of that class. So if you want to
publish a story with title, body, and created date, you would do it like this:
class Story(db.Model):
title = db.StringProperty()
body = db.TextProperty()
created = db.DateTimeProperty(auto_now_add=True)
You can create a new Story in the datastore with this usage pattern:
story = Story(title='My title')
story.body = 'My body'
story.put()
You query for Story entities using built in query interfaces that map directly
to the syntax and semantics of the datastore:
stories = Story.all().filter('date >=', yesterday).order('-date')
for story in stories:
print story.title
The Property declarations enforce types by performing validation on assignment.
For example, the DateTimeProperty enforces that you assign valid datetime
objects, and if you supply the "required" option for a property, you will not
be able to assign None to that property.
We also support references between models, so if a story has comments, you
would represent it like this:
class Comment(db.Model):
story = db.ReferenceProperty(Story)
body = db.TextProperty()
When you get a story out of the datastore, the story reference is resolved
automatically the first time it is referenced, which makes it easy to use
model instances without performing additional queries by hand:
comment = Comment.get(key)
print comment.story.title
Likewise, you can access the set of comments that refer to each story through
this property through a reverse reference called comment_set, which is a Query
preconfigured to return all matching comments:
story = Story.get(key)
for comment in story.comment_set:
print comment.body
"""
import base64
import copy
import datetime
import logging
import re
import time
import urlparse
import warnings
from google.appengine.api import datastore
from google.appengine.api import datastore_errors
from google.appengine.api import datastore_types
from google.appengine.api import users
from google.appengine.datastore import datastore_pb
Error = datastore_errors.Error
BadValueError = datastore_errors.BadValueError
BadPropertyError = datastore_errors.BadPropertyError
BadRequestError = datastore_errors.BadRequestError
EntityNotFoundError = datastore_errors.EntityNotFoundError
BadArgumentError = datastore_errors.BadArgumentError
QueryNotFoundError = datastore_errors.QueryNotFoundError
TransactionNotFoundError = datastore_errors.TransactionNotFoundError
Rollback = datastore_errors.Rollback
TransactionFailedError = datastore_errors.TransactionFailedError
BadFilterError = datastore_errors.BadFilterError
BadQueryError = datastore_errors.BadQueryError
BadKeyError = datastore_errors.BadKeyError
InternalError = datastore_errors.InternalError
NeedIndexError = datastore_errors.NeedIndexError
Timeout = datastore_errors.Timeout
CommittedButStillApplying = datastore_errors.CommittedButStillApplying
ValidationError = BadValueError
Key = datastore_types.Key
Category = datastore_types.Category
Link = datastore_types.Link
Email = datastore_types.Email
GeoPt = datastore_types.GeoPt
IM = datastore_types.IM
PhoneNumber = datastore_types.PhoneNumber
PostalAddress = datastore_types.PostalAddress
Rating = datastore_types.Rating
Text = datastore_types.Text
Blob = datastore_types.Blob
ByteString = datastore_types.ByteString
BlobKey = datastore_types.BlobKey
READ_CAPABILITY = datastore.READ_CAPABILITY
WRITE_CAPABILITY = datastore.WRITE_CAPABILITY
STRONG_CONSISTENCY = datastore.STRONG_CONSISTENCY
EVENTUAL_CONSISTENCY = datastore.EVENTUAL_CONSISTENCY
_kind_map = {}
_SELF_REFERENCE = object()
_RESERVED_WORDS = set(['key_name'])
class NotSavedError(Error):
"""Raised when a saved-object action is performed on a non-saved object."""
class KindError(BadValueError):
"""Raised when an entity is used with incorrect Model."""
class PropertyError(Error):
"""Raised when non-existent property is referenced."""
class DuplicatePropertyError(Error):
"""Raised when a property is duplicated in a model definition."""
class ConfigurationError(Error):
"""Raised when a property or model is improperly configured."""
class ReservedWordError(Error):
"""Raised when a property is defined for a reserved word."""
class DerivedPropertyError(Error):
"""Raised when attempting to assign a value to a derived property."""
_ALLOWED_PROPERTY_TYPES = set([
basestring,
str,
unicode,
bool,
int,
long,
float,
Key,
datetime.datetime,
datetime.date,
datetime.time,
Blob,
ByteString,
Text,
users.User,
Category,
Link,
Email,
GeoPt,
IM,
PhoneNumber,
PostalAddress,
Rating,
BlobKey,
])
_ALLOWED_EXPANDO_PROPERTY_TYPES = set(_ALLOWED_PROPERTY_TYPES)
_ALLOWED_EXPANDO_PROPERTY_TYPES.update((list, tuple, type(None)))
_OPERATORS = ['<', '<=', '>', '>=', '=', '==', '!=', 'in']
_FILTER_REGEX = re.compile(
'^\s*([^\s]+)(\s+(%s)\s*)?$' % '|'.join(_OPERATORS),
re.IGNORECASE | re.UNICODE)
def class_for_kind(kind):
"""Return base-class responsible for implementing kind.
Necessary to recover the class responsible for implementing provided
kind.
Args:
kind: Entity kind string.
Returns:
Class implementation for kind.
Raises:
KindError when there is no implementation for kind.
"""
try:
return _kind_map[kind]
except KeyError:
raise KindError('No implementation for kind \'%s\'' % kind)
def check_reserved_word(attr_name):
"""Raise an exception if attribute name is a reserved word.
Args:
attr_name: Name to check to see if it is a reserved word.
Raises:
ReservedWordError when attr_name is determined to be a reserved word.
"""
if datastore_types.RESERVED_PROPERTY_NAME.match(attr_name):
raise ReservedWordError(
"Cannot define property. All names both beginning and "
"ending with '__' are reserved.")
if attr_name in _RESERVED_WORDS or attr_name in dir(Model):
raise ReservedWordError(
"Cannot define property using reserved word '%(attr_name)s'. "
"If you would like to use this name in the datastore consider "
"using a different name like %(attr_name)s_ and adding "
"name='%(attr_name)s' to the parameter list of the property "
"definition." % locals())
def query_descendants(model_instance):
"""Returns a query for all the descendants of a model instance.
Args:
model_instance: Model instance to find the descendants of.
Returns:
Query that will retrieve all entities that have the given model instance
as an ancestor. Unlike normal ancestor queries, this does not include the
ancestor itself.
"""
result = Query().ancestor(model_instance);
result.filter(datastore_types._KEY_SPECIAL_PROPERTY + ' >',
model_instance.key());
return result;
def model_to_protobuf(model_instance, _entity_class=datastore.Entity):
"""Encodes a model instance as a protocol buffer.
Args:
model_instance: Model instance to encode.
Returns:
entity_pb.EntityProto representation of the model instance
"""
return model_instance._populate_entity(_entity_class).ToPb()
def model_from_protobuf(pb, _entity_class=datastore.Entity):
"""Decodes a model instance from a protocol buffer.
Args:
pb: The protocol buffer representation of the model instance. Can be an
entity_pb.EntityProto or str encoding of an entity_bp.EntityProto
Returns:
Model instance resulting from decoding the protocol buffer
"""
entity = _entity_class.FromPb(pb)
return class_for_kind(entity.kind()).from_entity(entity)
def _initialize_properties(model_class, name, bases, dct):
"""Initialize Property attributes for Model-class.
Args:
model_class: Model class to initialize properties for.
"""
model_class._properties = {}
property_source = {}
def get_attr_source(name, cls):
for src_cls in cls.mro():
if name in src_cls.__dict__:
return src_cls
defined = set()
for base in bases:
if hasattr(base, '_properties'):
property_keys = set(base._properties.keys())
duplicate_property_keys = defined & property_keys
for dupe_prop_name in duplicate_property_keys:
old_source = property_source[dupe_prop_name] = get_attr_source(
dupe_prop_name, property_source[dupe_prop_name])
new_source = get_attr_source(dupe_prop_name, base)
if old_source != new_source:
raise DuplicatePropertyError(
'Duplicate property, %s, is inherited from both %s and %s.' %
(dupe_prop_name, old_source.__name__, new_source.__name__))
property_keys -= duplicate_property_keys
if property_keys:
defined |= property_keys
property_source.update(dict.fromkeys(property_keys, base))
model_class._properties.update(base._properties)
for attr_name in dct.keys():
attr = dct[attr_name]
if isinstance(attr, Property):
check_reserved_word(attr_name)
if attr_name in defined:
raise DuplicatePropertyError('Duplicate property: %s' % attr_name)
defined.add(attr_name)
model_class._properties[attr_name] = attr
attr.__property_config__(model_class, attr_name)
model_class._unindexed_properties = frozenset(
name for name, prop in model_class._properties.items() if not prop.indexed)
def _coerce_to_key(value):
"""Returns the value's key.
Args:
value: a Model or Key instance or string encoded key or None
Returns:
The corresponding key, or None if value is None.
"""
if value is None:
return None
value, multiple = datastore.NormalizeAndTypeCheck(
value, (Model, Key, basestring))
if len(value) > 1:
raise datastore_errors.BadArgumentError('Expected only one model or key')
value = value[0]
if isinstance(value, Model):
return value.key()
elif isinstance(value, basestring):
return Key(value)
else:
return value
class PropertiedClass(type):
"""Meta-class for initializing Model classes properties.
Used for initializing Properties defined in the context of a model.
By using a meta-class much of the configuration of a Property
descriptor becomes implicit. By using this meta-class, descriptors
that are of class Model are notified about which class they
belong to and what attribute they are associated with and can
do appropriate initialization via __property_config__.
Duplicate properties are not permitted.
"""
def __init__(cls, name, bases, dct, map_kind=True):
"""Initializes a class that might have property definitions.
This method is called when a class is created with the PropertiedClass
meta-class.
Loads all properties for this model and its base classes in to a dictionary
for easy reflection via the 'properties' method.
Configures each property defined in the new class.
Duplicate properties, either defined in the new class or defined separately
in two base classes are not permitted.
Properties may not assigned to names which are in the list of
_RESERVED_WORDS. It is still possible to store a property using a reserved
word in the datastore by using the 'name' keyword argument to the Property
constructor.
Args:
cls: Class being initialized.
name: Name of new class.
bases: Base classes of new class.
dct: Dictionary of new definitions for class.
Raises:
DuplicatePropertyError when a property is duplicated either in the new
class or separately in two base classes.
ReservedWordError when a property is given a name that is in the list of
reserved words, attributes of Model and names of the form '__.*__'.
"""
super(PropertiedClass, cls).__init__(name, bases, dct)
_initialize_properties(cls, name, bases, dct)
if map_kind:
_kind_map[cls.kind()] = cls
class Property(object):
"""A Property is an attribute of a Model.
It defines the type of the attribute, which determines how it is stored
in the datastore and how the property values are validated. Different property
types support different options, which change validation rules, default
values, etc. The simplest example of a property is a StringProperty:
class Story(db.Model):
title = db.StringProperty()
"""
creation_counter = 0
def __init__(self,
verbose_name=None,
name=None,
default=None,
required=False,
validator=None,
choices=None,
indexed=True):
"""Initializes this Property with the given options.
Args:
verbose_name: User friendly name of property.
name: Storage name for property. By default, uses attribute name
as it is assigned in the Model sub-class.
default: Default value for property if none is assigned.
required: Whether property is required.
validator: User provided method used for validation.
choices: User provided set of valid property values.
indexed: Whether property is indexed.
"""
self.verbose_name = verbose_name
self.name = name
self.default = default
self.required = required
self.validator = validator
self.choices = choices
self.indexed = indexed
self.creation_counter = Property.creation_counter
Property.creation_counter += 1
def __property_config__(self, model_class, property_name):
"""Configure property, connecting it to its model.
Configure the property so that it knows its property name and what class
it belongs to.
Args:
model_class: Model class which Property will belong to.
property_name: Name of property within Model instance to store property
values in. By default this will be the property name preceded by
an underscore, but may change for different subclasses.
"""
self.model_class = model_class
if self.name is None:
self.name = property_name
def __get__(self, model_instance, model_class):
"""Returns the value for this property on the given model instance.
See http://docs.python.org/ref/descriptors.html for a description of
the arguments to this class and what they mean."""
if model_instance is None:
return self
try:
return getattr(model_instance, self._attr_name())
except AttributeError:
return None
def __set__(self, model_instance, value):
"""Sets the value for this property on the given model instance.
See http://docs.python.org/ref/descriptors.html for a description of
the arguments to this class and what they mean.
"""
value = self.validate(value)
setattr(model_instance, self._attr_name(), value)
def default_value(self):
"""Default value for unassigned values.
Returns:
Default value as provided by __init__(default).
"""
return self.default
def validate(self, value):
"""Assert that provided value is compatible with this property.
Args:
value: Value to validate against this Property.
Returns:
A valid value, either the input unchanged or adapted to the
required type.
Raises:
BadValueError if the value is not appropriate for this
property in any way.
"""
if self.empty(value):
if self.required:
raise BadValueError('Property %s is required' % self.name)
else:
if self.choices:
match = False
for choice in self.choices:
if choice == value:
match = True
if not match:
raise BadValueError('Property %s is %r; must be one of %r' %
(self.name, value, self.choices))
if self.validator is not None:
self.validator(value)
return value
def empty(self, value):
"""Determine if value is empty in the context of this property.
For most kinds, this is equivalent to "not value", but for kinds like
bool, the test is more subtle, so subclasses can override this method
if necessary.
Args:
value: Value to validate against this Property.
Returns:
True if this value is considered empty in the context of this Property
type, otherwise False.
"""
return not value
def get_value_for_datastore(self, model_instance):
"""Datastore representation of this property.
Looks for this property in the given model instance, and returns the proper
datastore representation of the value that can be stored in a datastore
entity. Most critically, it will fetch the datastore key value for
reference properties.
Args:
model_instance: Instance to fetch datastore value from.
Returns:
Datastore representation of the model value in a form that is
appropriate for storing in the datastore.
"""
return self.__get__(model_instance, model_instance.__class__)
def make_value_from_datastore(self, value):
"""Native representation of this property.
Given a value retrieved from a datastore entity, return a value,
possibly converted, to be stored on the model instance. Usually
this returns the value unchanged, but a property class may
override this when it uses a different datatype on the model
instance than on the entity.
This API is not quite symmetric with get_value_for_datastore(),
because the model instance on which to store the converted value
may not exist yet -- we may be collecting values to be passed to a
model constructor.
Args:
value: value retrieved from the datastore entity.
Returns:
The value converted for use as a model instance attribute.
"""
return value
def _require_parameter(self, kwds, parameter, value):
"""Sets kwds[parameter] to value.
If kwds[parameter] exists and is not value, raises ConfigurationError.
Args:
kwds: The parameter dict, which maps parameter names (strings) to values.
parameter: The name of the parameter to set.
value: The value to set it to.
"""
if parameter in kwds and kwds[parameter] != value:
raise ConfigurationError('%s must be %s.' % (parameter, value))
kwds[parameter] = value
def _attr_name(self):
"""Attribute name we use for this property in model instances.
DO NOT USE THIS METHOD.
"""
return '_' + self.name
data_type = str
def datastore_type(self):
"""Deprecated backwards-compatible accessor method for self.data_type."""
return self.data_type
class Model(object):
"""Model is the superclass of all object entities in the datastore.
The programming model is to declare Python subclasses of the Model class,
declaring datastore properties as class members of that class. So if you want
to publish a story with title, body, and created date, you would do it like
this:
class Story(db.Model):
title = db.StringProperty()
body = db.TextProperty()
created = db.DateTimeProperty(auto_now_add=True)
A model instance can have a single parent. Model instances without any
parent are root entities. It is possible to efficiently query for
instances by their shared parent. All descendents of a single root
instance also behave as a transaction group. This means that when you
work one member of the group within a transaction all descendents of that
root join the transaction. All operations within a transaction on this
group are ACID.
"""
__metaclass__ = PropertiedClass
def __init__(self,
parent=None,
key_name=None,
_app=None,
_from_entity=False,
**kwds):
"""Creates a new instance of this model.
To create a new entity, you instantiate a model and then call put(),
which saves the entity to the datastore:
person = Person()
person.name = 'Bret'
person.put()
You can initialize properties in the model in the constructor with keyword
arguments:
person = Person(name='Bret')
We initialize all other properties to the default value (as defined by the
properties in the model definition) if they are not provided in the
constructor.
Args:
parent: Parent instance for this instance or None, indicating a top-
level instance.
key_name: Name for new model instance.
_from_entity: Intentionally undocumented.
kwds: Keyword arguments mapping to properties of model. Also:
key: Key instance for this instance, if provided makes parent and
key_name redundant (they do not need to be set but if they are
they must match the key).
"""
key = kwds.get('key', None)
if key is not None:
if isinstance(key, (tuple, list)):
key = Key.from_path(*key)
if isinstance(key, basestring):
key = Key(encoded=key)
if not isinstance(key, Key):
raise TypeError('Expected Key type; received %s (is %s)' %
(key, key.__class__.__name__))
if not key.has_id_or_name():
raise BadKeyError('Key must have an id or name')
if key.kind() != self.kind():
raise BadKeyError('Expected Key kind to be %s; received %s' %
(self.kind(), key.kind()))
if _app is not None and key.app() != _app:
raise BadKeyError('Expected Key app to be %s; received %s' %
(_app, key.app()))
if key_name and key_name != key.name():
raise BadArgumentError('Cannot use key and key_name at the same time'
' with different values')
if parent and parent != key.parent():
raise BadArgumentError('Cannot use key and parent at the same time'
' with different values')
self._key = key
self._key_name = None
self._parent = None
self._parent_key = None
else:
if key_name == '':
raise BadKeyError('Name cannot be empty.')
elif key_name is not None and not isinstance(key_name, basestring):
raise BadKeyError('Name must be string type, not %s' %
key_name.__class__.__name__)
if parent is not None:
if not isinstance(parent, (Model, Key)):
raise TypeError('Expected Model type; received %s (is %s)' %
(parent, parent.__class__.__name__))
if isinstance(parent, Model) and not parent.has_key():
raise BadValueError(
"%s instance must have a complete key before it can be used as a "
"parent." % parent.kind())
if isinstance(parent, Key):
self._parent_key = parent
self._parent = None
else:
self._parent_key = parent.key()
self._parent = parent
else:
self._parent_key = None
self._parent = None
self._key_name = key_name
self._key = None
self._entity = None
if _app is not None and isinstance(_app, Key):
raise BadArgumentError('_app should be a string; received Key(\'%s\'):\n'
' This may be the result of passing \'key\' as '
'a positional parameter in SDK 1.2.6. Please '
'only pass \'key\' as a keyword parameter.' % _app)
self._app = _app
for prop in self.properties().values():
if prop.name in kwds:
value = kwds[prop.name]
else:
value = prop.default_value()
try:
prop.__set__(self, value)
except DerivedPropertyError, e:
if prop.name in kwds and not _from_entity:
raise
def key(self):
"""Unique key for this entity.
This property is only available if this entity is already stored in the
datastore or if it has a full key, so it is available if this entity was
fetched returned from a query, or after put() is called the first time
for new entities, or if a complete key was given when constructed.
Returns:
Datastore key of persisted entity.
Raises:
NotSavedError when entity is not persistent.
"""
if self.is_saved():
return self._entity.key()
elif self._key:
return self._key
elif self._key_name:
parent = self._parent_key or (self._parent and self._parent.key())
self._key = Key.from_path(self.kind(), self._key_name, parent=parent)
return self._key
else:
raise NotSavedError()
def _to_entity(self, entity):
"""Copies information from this model to provided entity.
Args:
entity: Entity to save information on.
"""
for prop in self.properties().values():
datastore_value = prop.get_value_for_datastore(self)
if datastore_value == []:
try:
del entity[prop.name]
except KeyError:
pass
else:
entity[prop.name] = datastore_value
entity.set_unindexed_properties(self._unindexed_properties)
def _populate_internal_entity(self, _entity_class=datastore.Entity):
"""Populates self._entity, saving its state to the datastore.
After this method is called, calling is_saved() will return True.
Returns:
Populated self._entity
"""
self._entity = self._populate_entity(_entity_class=_entity_class)
for attr in ('_key_name', '_key'):
try:
delattr(self, attr)
except AttributeError:
pass
return self._entity
def put(self, **kwargs):
"""Writes this model instance to the datastore.
If this instance is new, we add an entity to the datastore.
Otherwise, we update this instance, and the key will remain the
same.
Returns:
The key of the instance (either the existing key or a new key).
Raises:
TransactionFailedError if the data could not be committed.
"""
rpc = datastore.GetRpcFromKwargs(kwargs)
self._populate_internal_entity()
return datastore.Put(self._entity, rpc=rpc)
save = put
def _populate_entity(self, _entity_class=datastore.Entity):
"""Internal helper -- Populate self._entity or create a new one
if that one does not exist. Does not change any state of the instance
other than the internal state of the entity.
This method is separate from _populate_internal_entity so that it is
possible to call to_xml without changing the state of an unsaved entity
to saved.
Returns:
self._entity or a new Entity which is not stored on the instance.
"""
if self.is_saved():
entity = self._entity
else:
kwds = {'_app': self._app,
'unindexed_properties': self._unindexed_properties}
if self._key is not None:
if self._key.id():
kwds['id'] = self._key.id()
else:
kwds['name'] = self._key.name()
if self._key.parent():
kwds['parent'] = self._key.parent()
else:
if self._key_name is not None:
kwds['name'] = self._key_name
if self._parent_key is not None:
kwds['parent'] = self._parent_key
elif self._parent is not None:
kwds['parent'] = self._parent._entity
entity = _entity_class(self.kind(), **kwds)
self._to_entity(entity)
return entity
def delete(self, **kwargs):
"""Deletes this entity from the datastore.
Raises:
TransactionFailedError if the data could not be committed.
"""
rpc = datastore.GetRpcFromKwargs(kwargs)
datastore.Delete(self.key(), rpc=rpc)
self._key = self.key()
self._key_name = None
self._parent_key = None
self._entity = None
def is_saved(self):
"""Determine if entity is persisted in the datastore.
New instances of Model do not start out saved in the data. Objects which
are saved to or loaded from the Datastore will have a True saved state.
Returns:
True if object has been persisted to the datastore, otherwise False.
"""
return self._entity is not None
def has_key(self):
"""Determine if this model instance has a complete key.
When not using a fully self-assigned Key, ids are not assigned until the
data is saved to the Datastore, but instances with a key name always have
a full key.
Returns:
True if the object has been persisted to the datastore or has a key
or has a key_name, otherwise False.
"""
return self.is_saved() or self._key or self._key_name
def dynamic_properties(self):
"""Returns a list of all dynamic properties defined for instance."""
return []
def instance_properties(self):
"""Alias for dyanmic_properties."""
return self.dynamic_properties()
def parent(self):
"""Get the parent of the model instance.
Returns:
Parent of contained entity or parent provided in constructor, None if
instance has no parent.
"""
if self._parent is None:
parent_key = self.parent_key()
if parent_key is not None:
self._parent = get(parent_key)
return self._parent
def parent_key(self):
"""Get the parent's key.
This method is useful for avoiding a potential fetch from the datastore
but still get information about the instances parent.
Returns:
Parent key of entity, None if there is no parent.
"""
if self._parent_key is not None:
return self._parent_key
elif self._parent is not None:
return self._parent.key()
elif self._entity is not None:
return self._entity.parent()
elif self._key is not None:
return self._key.parent()
else:
return None
def to_xml(self, _entity_class=datastore.Entity):
"""Generate an XML representation of this model instance.
atom and gd:namespace properties are converted to XML according to their
respective schemas. For more information, see:
http://www.atomenabled.org/developers/syndication/
http://code.google.com/apis/gdata/common-elements.html
"""
entity = self._populate_entity(_entity_class)
return entity.ToXml()
@classmethod
def get(cls, keys, **kwargs):
"""Fetch instance from the datastore of a specific Model type using key.
We support Key objects and string keys (we convert them to Key objects
automatically).
Useful for ensuring that specific instance types are retrieved from the
datastore. It also helps that the source code clearly indicates what
kind of object is being retreived. Example:
story = Story.get(story_key)
Args:
keys: Key within datastore entity collection to find; or string key;
or list of Keys or string keys.
Returns:
If a single key was given: a Model instance associated with key
for provided class if it exists in the datastore, otherwise
None; if a list of keys was given: a list whose items are either
a Model instance or None.
Raises:
KindError if any of the retreived objects are not instances of the
type associated with call to 'get'.
"""
rpc = datastore.GetRpcFromKwargs(kwargs)
results = get(keys, rpc=rpc)
if results is None:
return None
if isinstance(results, Model):
instances = [results]
else:
instances = results
for instance in instances:
if not(instance is None or isinstance(instance, cls)):
raise KindError('Kind %r is not a subclass of kind %r' %
(instance.kind(), cls.kind()))
return results
@classmethod
def get_by_key_name(cls, key_names, parent=None, **kwargs):
"""Get instance of Model class by its key's name.
Args:
key_names: A single key-name or a list of key-names.
parent: Parent of instances to get. Can be a model or key.
"""
try:
parent = _coerce_to_key(parent)
except BadKeyError, e:
raise BadArgumentError(str(e))
rpc = datastore.GetRpcFromKwargs(kwargs)
key_names, multiple = datastore.NormalizeAndTypeCheck(key_names, basestring)
keys = [datastore.Key.from_path(cls.kind(), name, parent=parent)
for name in key_names]
if multiple:
return get(keys, rpc=rpc)
else:
return get(keys[0], rpc=rpc)
@classmethod
def get_by_id(cls, ids, parent=None, **kwargs):
"""Get instance of Model class by id.
Args:
key_names: A single id or a list of ids.
parent: Parent of instances to get. Can be a model or key.
"""
rpc = datastore.GetRpcFromKwargs(kwargs)
if isinstance(parent, Model):
parent = parent.key()
ids, multiple = datastore.NormalizeAndTypeCheck(ids, (int, long))
keys = [datastore.Key.from_path(cls.kind(), id, parent=parent)
for id in ids]
if multiple:
return get(keys, rpc=rpc)
else:
return get(keys[0], rpc=rpc)
@classmethod
def get_or_insert(cls, key_name, **kwds):
"""Transactionally retrieve or create an instance of Model class.
This acts much like the Python dictionary setdefault() method, where we
first try to retrieve a Model instance with the given key name and parent.
If it's not present, then we create a new instance (using the *kwds
supplied) and insert that with the supplied key name.
Subsequent calls to this method with the same key_name and parent will
always yield the same entity (though not the same actual object instance),
regardless of the *kwds supplied. If the specified entity has somehow
been deleted separately, then the next call will create a new entity and
return it.
If the 'parent' keyword argument is supplied, it must be a Model instance.
It will be used as the parent of the new instance of this Model class if
one is created.
This method is especially useful for having just one unique entity for
a specific identifier. Insertion/retrieval is done transactionally, which
guarantees uniqueness.
Example usage:
class WikiTopic(db.Model):
creation_date = db.DatetimeProperty(auto_now_add=True)
body = db.TextProperty(required=True)
# The first time through we'll create the new topic.
wiki_word = 'CommonIdioms'
topic = WikiTopic.get_or_insert(wiki_word,
body='This topic is totally new!')
assert topic.key().name() == 'CommonIdioms'
assert topic.body == 'This topic is totally new!'
# The second time through will just retrieve the entity.
overwrite_topic = WikiTopic.get_or_insert(wiki_word,
body='A totally different message!')
assert topic.key().name() == 'CommonIdioms'
assert topic.body == 'This topic is totally new!'
Args:
key_name: Key name to retrieve or create.
**kwds: Keyword arguments to pass to the constructor of the model class
if an instance for the specified key name does not already exist. If
an instance with the supplied key_name and parent already exists, the
rest of these arguments will be discarded.
Returns:
Existing instance of Model class with the specified key_name and parent
or a new one that has just been created.
Raises:
TransactionFailedError if the specified Model instance could not be
retrieved or created transactionally (due to high contention, etc).
"""
def txn():
entity = cls.get_by_key_name(key_name, parent=kwds.get('parent'))
if entity is None:
entity = cls(key_name=key_name, **kwds)
entity.put()
return entity
return run_in_transaction(txn)
@classmethod
def all(cls, **kwds):
"""Returns a query over all instances of this model from the datastore.
Returns:
Query that will retrieve all instances from entity collection.
"""
return Query(cls, **kwds)
@classmethod
def gql(cls, query_string, *args, **kwds):
"""Returns a query using GQL query string.
See appengine/ext/gql for more information about GQL.
Args:
query_string: properly formatted GQL query string with the
'SELECT * FROM <entity>' part omitted
*args: rest of the positional arguments used to bind numeric references
in the query.
**kwds: dictionary-based arguments (for named parameters).
"""
return GqlQuery('SELECT * FROM %s %s' % (cls.kind(), query_string),
*args, **kwds)
@classmethod
def _load_entity_values(cls, entity):
"""Load dynamic properties from entity.
Loads attributes which are not defined as part of the entity in
to the model instance.
Args:
entity: Entity which contain values to search dyanmic properties for.
"""
entity_values = {}
for prop in cls.properties().values():
if prop.name in entity:
try:
value = prop.make_value_from_datastore(entity[prop.name])
entity_values[prop.name] = value
except KeyError:
entity_values[prop.name] = []
return entity_values
@classmethod
def from_entity(cls, entity):
"""Converts the entity representation of this model to an instance.
Converts datastore.Entity instance to an instance of cls.
Args:
entity: Entity loaded directly from datastore.
Raises:
KindError when cls is incorrect model for entity.
"""
if cls.kind() != entity.kind():
raise KindError('Class %s cannot handle kind \'%s\'' %
(repr(cls), entity.kind()))
entity_values = cls._load_entity_values(entity)
if entity.key().has_id_or_name():
entity_values['key'] = entity.key()
instance = cls(None, _from_entity=True, **entity_values)
if entity.is_saved():
instance._entity = entity
del instance._key_name
del instance._key
return instance
@classmethod
def kind(cls):
"""Returns the datastore kind we use for this model.
We just use the name of the model for now, ignoring potential collisions.
"""
return cls.__name__
@classmethod
def entity_type(cls):
"""Soon to be removed alias for kind."""
return cls.kind()
@classmethod
def properties(cls):
"""Returns a dictionary of all the properties defined for this model."""
return dict(cls._properties)
@classmethod
def fields(cls):
"""Soon to be removed alias for properties."""
return cls.properties()
def create_rpc(deadline=None, callback=None, read_policy=STRONG_CONSISTENCY):
"""Create an rpc for use in configuring datastore calls.
Args:
deadline: float, deadline for calls in seconds.
callback: callable, a callback triggered when this rpc completes,
accepts one argument: the returned rpc.
read_policy: flag, set to EVENTUAL_CONSISTENCY to enable eventually
consistent reads
Returns:
A datastore.DatastoreRPC instance.
"""
return datastore.CreateRPC(
deadline=deadline, callback=callback, read_policy=read_policy)
def get(keys, **kwargs):
"""Fetch the specific Model instance with the given key from the datastore.
We support Key objects and string keys (we convert them to Key objects
automatically).
Args:
keys: Key within datastore entity collection to find; or string key;
or list of Keys or string keys.
Returns:
If a single key was given: a Model instance associated with key
for if it exists in the datastore, otherwise None; if a list of
keys was given: a list whose items are either a Model instance or
None.
"""
rpc = datastore.GetRpcFromKwargs(kwargs)
keys, multiple = datastore.NormalizeAndTypeCheckKeys(keys)
try:
entities = datastore.Get(keys, rpc=rpc)
except datastore_errors.EntityNotFoundError:
assert not multiple
return None
models = []
for entity in entities:
if entity is None:
model = None
else:
cls1 = class_for_kind(entity.kind())
model = cls1.from_entity(entity)
models.append(model)
if multiple:
return models
assert len(models) == 1
return models[0]
def put(models, **kwargs):
"""Store one or more Model instances.
Args:
models: Model instance or list of Model instances.
Returns:
A Key or a list of Keys (corresponding to the argument's plurality).
Raises:
TransactionFailedError if the data could not be committed.
"""
rpc = datastore.GetRpcFromKwargs(kwargs)
models, multiple = datastore.NormalizeAndTypeCheck(models, Model)
entities = [model._populate_internal_entity() for model in models]
keys = datastore.Put(entities, rpc=rpc)
if multiple:
return keys
assert len(keys) == 1
return keys[0]
save = put
def delete(models, **kwargs):
"""Delete one or more Model instances.
Args:
models_or_keys: Model instance or list of Model instances.
Raises:
TransactionFailedError if the data could not be committed.
"""
rpc = datastore.GetRpcFromKwargs(kwargs)
if not isinstance(models, (list, tuple)):
models = [models]
keys = [_coerce_to_key(v) for v in models]
datastore.Delete(keys, rpc=rpc)
def allocate_ids(model, size, **kwargs):
"""Allocates a range of IDs of size for the model_key defined by model.
Allocates a range of IDs in the datastore such that those IDs will not
be automatically assigned to new entities. You can only allocate IDs
for model keys from your app. If there is an error, raises a subclass of
datastore_errors.Error.
Args:
model: Model instance, Key or string to serve as a template specifying the
ID sequence in which to allocate IDs. Returned ids should only be used
in entities with the same parent (if any) and kind as this key.
Returns:
(start, end) of the allocated range, inclusive.
"""
return datastore.AllocateIds(_coerce_to_key(model), size, **kwargs)
class Expando(Model):
"""Dynamically expandable model.
An Expando does not require (but can still benefit from) the definition
of any properties before it can be used to store information in the
datastore. Properties can be added to an expando object by simply
performing an assignment. The assignment of properties is done on
an instance by instance basis, so it is possible for one object of an
expando type to have different properties from another or even the same
properties with different types. It is still possible to define
properties on an expando, allowing those properties to behave the same
as on any other model.
Example:
import datetime
class Song(db.Expando):
title = db.StringProperty()
crazy = Song(title='Crazy like a diamond',
author='Lucy Sky',
publish_date='yesterday',
rating=5.0)
hoboken = Song(title='The man from Hoboken',
author=['Anthony', 'Lou'],
publish_date=datetime.datetime(1977, 5, 3))
crazy.last_minute_note=db.Text('Get a train to the station.')
Possible Uses:
One use of an expando is to create an object without any specific
structure and later, when your application mature and it in the right
state, change it to a normal model object and define explicit properties.
Additional exceptions for expando:
Protected attributes (ones whose names begin with '_') cannot be used
as dynamic properties. These are names that are reserved for protected
transient (non-persisted) attributes.
Order of lookup:
When trying to set or access an attribute value, any other defined
properties, such as methods and other values in __dict__ take precedence
over values in the datastore.
1 - Because it is not possible for the datastore to know what kind of
property to store on an undefined expando value, setting a property to
None is the same as deleting it from the expando.
2 - Persistent variables on Expando must not begin with '_'. These
variables considered to be 'protected' in Python, and are used
internally.
3 - Expando's dynamic properties are not able to store empty lists.
Attempting to assign an empty list to a dynamic property will raise
ValueError. Static properties on Expando can still support empty
lists but like normal Model properties is restricted from using
None.
"""
_dynamic_properties = None
def __init__(self, parent=None, key_name=None, _app=None, **kwds):
"""Creates a new instance of this expando model.
Args:
parent: Parent instance for this instance or None, indicating a top-
level instance.
key_name: Name for new model instance.
_app: Intentionally undocumented.
args: Keyword arguments mapping to properties of model.
"""
super(Expando, self).__init__(parent, key_name, _app, **kwds)
self._dynamic_properties = {}
for prop, value in kwds.iteritems():
if prop not in self.properties() and prop != 'key':
setattr(self, prop, value)
def __setattr__(self, key, value):
"""Dynamically set field values that are not defined.
Tries to set the value on the object normally, but failing that
sets the value on the contained entity.
Args:
key: Name of attribute.
value: Value to set for attribute. Must be compatible with
datastore.
Raises:
ValueError on attempt to assign empty list.
"""
check_reserved_word(key)
if (key[:1] != '_' and
not hasattr(getattr(type(self), key, None), '__set__')):
if value == []:
raise ValueError('Cannot store empty list to dynamic property %s' %
key)
if type(value) not in _ALLOWED_EXPANDO_PROPERTY_TYPES:
raise TypeError("Expando cannot accept values of type '%s'." %
type(value).__name__)
if self._dynamic_properties is None:
self._dynamic_properties = {}
self._dynamic_properties[key] = value
else:
super(Expando, self).__setattr__(key, value)
def __getattribute__(self, key):
"""Get attribute from expando.
Must be overridden to allow dynamic properties to obscure class attributes.
Since all attributes are stored in self._dynamic_properties, the normal
__getattribute__ does not attempt to access it until __setattr__ is called.
By then, the static attribute being overwritten has already been located
and returned from the call.
This method short circuits the usual __getattribute__ call when finding a
dynamic property and returns it to the user via __getattr__. __getattr__
is called to preserve backward compatibility with older Expando models
that may have overridden the original __getattr__.
NOTE: Access to properties defined by Python descriptors are not obscured
because setting those attributes are done through the descriptor and does
not place those attributes in self._dynamic_properties.
"""
if not key.startswith('_'):
dynamic_properties = self._dynamic_properties
if dynamic_properties is not None and key in dynamic_properties:
return self.__getattr__(key)
return super(Expando, self).__getattribute__(key)
def __getattr__(self, key):
"""If no explicit attribute defined, retrieve value from entity.
Tries to get the value on the object normally, but failing that
retrieves value from contained entity.
Args:
key: Name of attribute.
Raises:
AttributeError when there is no attribute for key on object or
contained entity.
"""
_dynamic_properties = self._dynamic_properties
if _dynamic_properties is not None and key in _dynamic_properties:
return _dynamic_properties[key]
else:
return getattr(super(Expando, self), key)
def __delattr__(self, key):
"""Remove attribute from expando.
Expando is not like normal entities in that undefined fields
can be removed.
Args:
key: Dynamic property to be deleted.
"""
if self._dynamic_properties and key in self._dynamic_properties:
del self._dynamic_properties[key]
else:
object.__delattr__(self, key)
def dynamic_properties(self):
"""Determine which properties are particular to instance of entity.
Returns:
Set of names which correspond only to the dynamic properties.
"""
if self._dynamic_properties is None:
return []
return self._dynamic_properties.keys()
def _to_entity(self, entity):
"""Store to entity, deleting dynamic properties that no longer exist.
When the expando is saved, it is possible that a given property no longer
exists. In this case, the property will be removed from the saved instance.
Args:
entity: Entity which will receive dynamic properties.
"""
super(Expando, self)._to_entity(entity)
if self._dynamic_properties is None:
self._dynamic_properties = {}
for key, value in self._dynamic_properties.iteritems():
entity[key] = value
all_properties = set(self._dynamic_properties.iterkeys())
all_properties.update(self.properties().iterkeys())
for key in entity.keys():
if key not in all_properties:
del entity[key]
@classmethod
def _load_entity_values(cls, entity):
"""Load dynamic properties from entity.
Expando needs to do a second pass to add the entity values which were
ignored by Model because they didn't have an corresponding predefined
property on the model.
Args:
entity: Entity which contain values to search dyanmic properties for.
"""
entity_values = super(Expando, cls)._load_entity_values(entity)
for key, value in entity.iteritems():
if key not in entity_values:
entity_values[str(key)] = value
return entity_values
class _BaseQuery(object):
"""Base class for both Query and GqlQuery."""
_compile = False
def __init__(self, model_class=None, keys_only=False, compile=True,
cursor=None):
"""Constructor.
Args:
model_class: Model class from which entities are constructed.
keys_only: Whether the query should return full entities or only keys.
compile: Whether the query should also return a compiled query.
cursor: A compiled query from which to resume.
"""
self._model_class = model_class
self._keys_only = keys_only
self._compile = compile
self.with_cursor(cursor)
def is_keys_only(self):
"""Returns whether this query is keys only.
Returns:
True if this query returns keys, False if it returns entities.
"""
return self._keys_only
def _get_query(self):
"""Subclass must override (and not call their super method).
Returns:
A datastore.Query instance representing the query.
"""
raise NotImplementedError
def run(self, **kwargs):
"""Iterator for this query.
If you know the number of results you need, consider fetch() instead,
or use a GQL query with a LIMIT clause. It's more efficient.
Args:
rpc: datastore.DatastoreRPC to use for this request.
Returns:
Iterator for this query.
"""
rpc = datastore.GetRpcFromKwargs(kwargs)
raw_query = self._get_query()
iterator = raw_query.Run(rpc=rpc)
if self._compile:
self._last_raw_query = raw_query
if self._keys_only:
return iterator
else:
return _QueryIterator(self._model_class, iter(iterator))
def __iter__(self):
"""Iterator for this query.
If you know the number of results you need, consider fetch() instead,
or use a GQL query with a LIMIT clause. It's more efficient.
"""
return self.run()
def get(self, **kwargs):
"""Get first result from this.
Beware: get() ignores the LIMIT clause on GQL queries.
Returns:
First result from running the query if there are any, else None.
"""
rpc = datastore.GetRpcFromKwargs(kwargs)
results = self.fetch(1, rpc=rpc)
try:
return results[0]
except IndexError:
return None
def count(self, limit=None, **kwargs):
"""Number of entities this query fetches.
Beware: count() ignores the LIMIT clause on GQL queries.
Args:
limit, a number. If there are more results than this, stop short and
just return this number. Providing this argument makes the count
operation more efficient.
Returns:
Number of entities this query fetches.
"""
rpc = datastore.GetRpcFromKwargs(kwargs)
raw_query = self._get_query()
result = raw_query.Count(limit=limit, rpc=rpc)
self._last_raw_query = None
return result
def fetch(self, limit, offset=0, **kwargs):
"""Return a list of items selected using SQL-like limit and offset.
Whenever possible, use fetch() instead of iterating over the query
results with run() or __iter__() . fetch() is more efficient.
Beware: fetch() ignores the LIMIT clause on GQL queries.
Args:
limit: Maximum number of results to return.
offset: Optional number of results to skip first; default zero.
rpc: datastore.DatastoreRPC to use for this request.
Returns:
A list of db.Model instances. There may be fewer than 'limit'
results if there aren't enough results to satisfy the request.
"""
rpc = datastore.GetRpcFromKwargs(kwargs)
accepted = (int, long)
if not (isinstance(limit, accepted) and isinstance(offset, accepted)):
raise TypeError('Arguments to fetch() must be integers')
if limit < 0 or offset < 0:
raise ValueError('Arguments to fetch() must be >= 0')
if limit == 0:
return []
raw_query = self._get_query()
raw = raw_query.Get(limit, offset, rpc=rpc)
if self._compile:
self._last_raw_query = raw_query
if self._keys_only:
return raw
else:
if self._model_class is not None:
return [self._model_class.from_entity(e) for e in raw]
else:
return [class_for_kind(e.kind()).from_entity(e) for e in raw]
def cursor(self):
"""Get a serialized cursor for an already executed query.
The returned cursor effectively lets a future invocation of a similar
query to begin fetching results immediately after the last returned
result from this query invocation.
Returns:
A base64-encoded serialized cursor.
"""
if not self._compile:
raise AssertionError(
'Query must be created with compile=True to produce cursors')
try:
return base64.urlsafe_b64encode(
self._last_raw_query.GetCompiledCursor().Encode())
except AttributeError:
raise AssertionError('No cursor available.')
def with_cursor(self, cursor):
"""Set the start of this query to the given serialized cursor.
When executed, this query will start from the next result for a previous
invocation of a similar query.
Returns:
This Query instance, for chaining.
"""
if not cursor:
cursor = None
elif not isinstance(cursor, basestring):
raise BadValueError(
'Cursor must be a str or unicode instance, not a %s'
% type(cursor).__name__)
else:
cursor = str(cursor)
try:
decoded = base64.urlsafe_b64decode(cursor)
cursor = datastore_pb.CompiledCursor(decoded)
except (ValueError, TypeError), e:
raise datastore_errors.BadValueError(
'Invalid cursor %s. Details: %s' % (cursor, e))
except Exception, e:
if e.__class__.__name__ == 'ProtocolBufferDecodeError':
raise datastore_errors.BadValueError('Invalid cursor %s. '
'Details: %s' % (cursor, e))
else:
raise
self._cursor = cursor
return self
def __getitem__(self, arg):
"""Support for query[index] and query[start:stop].
Beware: this ignores the LIMIT clause on GQL queries.
Args:
arg: Either a single integer, corresponding to the query[index]
syntax, or a Python slice object, corresponding to the
query[start:stop] or query[start:stop:step] syntax.
Returns:
A single Model instance when the argument is a single integer.
A list of Model instances when the argument is a slice.
"""
if isinstance(arg, slice):
start, stop, step = arg.start, arg.stop, arg.step
if start is None:
start = 0
if stop is None:
raise ValueError('Open-ended slices are not supported')
if step is None:
step = 1
if start < 0 or stop < 0 or step != 1:
raise ValueError(
'Only slices with start>=0, stop>=0, step==1 are supported')
limit = stop - start
if limit < 0:
return []
return self.fetch(limit, start)
elif isinstance(arg, (int, long)):
if arg < 0:
raise ValueError('Only indices >= 0 are supported')
results = self.fetch(1, arg)
if results:
return results[0]
else:
raise IndexError('The query returned fewer than %d results' % (arg+1))
else:
raise TypeError('Only integer indices and slices are supported')
class _QueryIterator(object):
"""Wraps the datastore iterator to return Model instances.
The datastore returns entities. We wrap the datastore iterator to
return Model instances instead.
"""
def __init__(self, model_class, datastore_iterator):
"""Iterator constructor
Args:
model_class: Model class from which entities are constructed.
datastore_iterator: Underlying datastore iterator.
"""
self.__model_class = model_class
self.__iterator = datastore_iterator
def __iter__(self):
"""Iterator on self.
Returns:
Self.
"""
return self
def next(self):
"""Get next Model instance in query results.
Returns:
Next model instance.
Raises:
StopIteration when there are no more results in query.
"""
if self.__model_class is not None:
return self.__model_class.from_entity(self.__iterator.next())
else:
entity = self.__iterator.next()
return class_for_kind(entity.kind()).from_entity(entity)
def _normalize_query_parameter(value):
"""Make any necessary type conversions to a query parameter.
The following conversions are made:
- Model instances are converted to Key instances. This is necessary so
that querying reference properties will work.
- datetime.date objects are converted to datetime.datetime objects (see
_date_to_datetime for details on this conversion). This is necessary so
that querying date properties with date objects will work.
- datetime.time objects are converted to datetime.datetime objects (see
_time_to_datetime for details on this conversion). This is necessary so
that querying time properties with time objects will work.
Args:
value: The query parameter value.
Returns:
The input value, or a converted value if value matches one of the
conversions specified above.
"""
if isinstance(value, Model):
value = value.key()
if (isinstance(value, datetime.date) and
not isinstance(value, datetime.datetime)):
value = _date_to_datetime(value)
elif isinstance(value, datetime.time):
value = _time_to_datetime(value)
return value
class Query(_BaseQuery):
"""A Query instance queries over instances of Models.
You construct a query with a model class, like this:
class Story(db.Model):
title = db.StringProperty()
date = db.DateTimeProperty()
query = Query(Story)
You modify a query with filters and orders like this:
query.filter('title =', 'Foo')
query.order('-date')
query.ancestor(key_or_model_instance)
Every query can return an iterator, so you access the results of a query
by iterating over it:
for story in query:
print story.title
For convenience, all of the filtering and ordering methods return "self",
so the easiest way to use the query interface is to cascade all filters and
orders in the iterator line like this:
for story in Query(story).filter('title =', 'Foo').order('-date'):
print story.title
"""
def __init__(self, model_class=None, keys_only=False, cursor=None):
"""Constructs a query over instances of the given Model.
Args:
model_class: Model class to build query for.
keys_only: Whether the query should return full entities or only keys.
cursor: A compiled query from which to resume.
"""
super(Query, self).__init__(model_class, keys_only, cursor=cursor)
self.__query_sets = [{}]
self.__orderings = []
self.__ancestor = None
def _get_query(self,
_query_class=datastore.Query,
_multi_query_class=datastore.MultiQuery):
queries = []
for query_set in self.__query_sets:
if self._model_class is not None:
kind = self._model_class.kind()
else:
kind = None
query = _query_class(kind,
query_set,
keys_only=self._keys_only,
compile=self._compile,
cursor=self._cursor)
query.Order(*self.__orderings)
if self.__ancestor is not None:
query.Ancestor(self.__ancestor)
queries.append(query)
if (_query_class != datastore.Query and
_multi_query_class == datastore.MultiQuery):
warnings.warn(
'Custom _query_class specified without corresponding custom'
' _query_multi_class. Things will break if you use queries with'
' the "IN" or "!=" operators.', RuntimeWarning)
if len(queries) > 1:
raise datastore_errors.BadArgumentError(
'Query requires multiple subqueries to satisfy. If _query_class'
' is overridden, _multi_query_class must also be overridden.')
elif (_query_class == datastore.Query and
_multi_query_class != datastore.MultiQuery):
raise BadArgumentError('_query_class must also be overridden if'
' _multi_query_class is overridden.')
if len(queries) == 1:
return queries[0]
else:
return _multi_query_class(queries, self.__orderings)
def __filter_disjunction(self, operations, values):
"""Add a disjunction of several filters and several values to the query.
This is implemented by duplicating queries and combining the
results later.
Args:
operations: a string or list of strings. Each string contains a
property name and an operator to filter by. The operators
themselves must not require multiple queries to evaluate
(currently, this means that 'in' and '!=' are invalid).
values: a value or list of filter values, normalized by
_normalize_query_parameter.
"""
if not isinstance(operations, (list, tuple)):
operations = [operations]
if not isinstance(values, (list, tuple)):
values = [values]
new_query_sets = []
for operation in operations:
if operation.lower().endswith('in') or operation.endswith('!='):
raise BadQueryError('Cannot use "in" or "!=" in a disjunction.')
for query_set in self.__query_sets:
for value in values:
new_query_set = copy.deepcopy(query_set)
datastore._AddOrAppend(new_query_set, operation, value)
new_query_sets.append(new_query_set)
self.__query_sets = new_query_sets
def filter(self, property_operator, value):
"""Add filter to query.
Args:
property_operator: string with the property and operator to filter by.
value: the filter value.
Returns:
Self to support method chaining.
Raises:
PropertyError if invalid property is provided.
"""
match = _FILTER_REGEX.match(property_operator)
prop = match.group(1)
if match.group(3) is not None:
operator = match.group(3)
else:
operator = '=='
if self._model_class is None:
if prop != datastore_types._KEY_SPECIAL_PROPERTY:
raise BadQueryError(
'Only %s filters are allowed on kindless queries.' %
datastore_types._KEY_SPECIAL_PROPERTY)
elif prop in self._model_class._unindexed_properties:
raise PropertyError('Property \'%s\' is not indexed' % prop)
if operator.lower() == 'in':
if self._keys_only:
raise BadQueryError('Keys only queries do not support IN filters.')
elif not isinstance(value, (list, tuple)):
raise BadValueError('Argument to the "in" operator must be a list')
values = [_normalize_query_parameter(v) for v in value]
self.__filter_disjunction(prop + ' =', values)
else:
if isinstance(value, (list, tuple)):
raise BadValueError('Filtering on lists is not supported')
if operator == '!=':
if self._keys_only:
raise BadQueryError('Keys only queries do not support != filters.')
self.__filter_disjunction([prop + ' <', prop + ' >'],
_normalize_query_parameter(value))
else:
value = _normalize_query_parameter(value)
for query_set in self.__query_sets:
datastore._AddOrAppend(query_set, property_operator, value)
return self
def order(self, property):
"""Set order of query result.
To use descending order, prepend '-' (minus) to the property
name, e.g., '-date' rather than 'date'.
Args:
property: Property to sort on.
Returns:
Self to support method chaining.
Raises:
PropertyError if invalid property is provided.
"""
if property.startswith('-'):
property = property[1:]
order = datastore.Query.DESCENDING
else:
order = datastore.Query.ASCENDING
if self._model_class is None:
if (property != datastore_types._KEY_SPECIAL_PROPERTY or
order != datastore.Query.ASCENDING):
raise BadQueryError(
'Only %s ascending orders are supported on kindless queries' %
datastore_types._KEY_SPECIAL_PROPERTY)
else:
if not issubclass(self._model_class, Expando):
if (property not in self._model_class.properties() and
property not in datastore_types._SPECIAL_PROPERTIES):
raise PropertyError('Invalid property name \'%s\'' % property)
if property in self._model_class._unindexed_properties:
raise PropertyError('Property \'%s\' is not indexed' % property)
self.__orderings.append((property, order))
return self
def ancestor(self, ancestor):
"""Sets an ancestor for this query.
This restricts the query to only return results that descend from
a given model instance. In other words, all of the results will
have the ancestor as their parent, or parent's parent, etc. The
ancestor itself is also a possible result!
Args:
ancestor: Model or Key (that has already been saved)
Returns:
Self to support method chaining.
Raises:
TypeError if the argument isn't a Key or Model; NotSavedError
if it is, but isn't saved yet.
"""
if isinstance(ancestor, datastore.Key):
if ancestor.has_id_or_name():
self.__ancestor = ancestor
else:
raise NotSavedError()
elif isinstance(ancestor, Model):
if ancestor.has_key():
self.__ancestor = ancestor.key()
else:
raise NotSavedError()
else:
raise TypeError('ancestor should be Key or Model')
return self
class GqlQuery(_BaseQuery):
"""A Query class that uses GQL query syntax instead of .filter() etc."""
def __init__(self, query_string, *args, **kwds):
"""Constructor.
Args:
query_string: Properly formatted GQL query string.
*args: Positional arguments used to bind numeric references in the query.
**kwds: Dictionary-based arguments for named references.
Raises:
PropertyError if the query filters or sorts on a property that's not
indexed.
"""
from google.appengine.ext import gql
app = kwds.pop('_app', None)
self._proto_query = gql.GQL(query_string, _app=app)
if self._proto_query._entity is not None:
model_class = class_for_kind(self._proto_query._entity)
else:
model_class = None
super(GqlQuery, self).__init__(model_class,
keys_only=self._proto_query._keys_only)
if model_class is not None:
for property, unused in (self._proto_query.filters().keys() +
self._proto_query.orderings()):
if property in model_class._unindexed_properties:
raise PropertyError('Property \'%s\' is not indexed' % property)
self.bind(*args, **kwds)
def bind(self, *args, **kwds):
"""Bind arguments (positional or keyword) to the query.
Note that you can also pass arguments directly to the query
constructor. Each time you call bind() the previous set of
arguments is replaced with the new set. This is useful because
the hard work in in parsing the query; so if you expect to be
using the same query with different sets of arguments, you should
hold on to the GqlQuery() object and call bind() on it each time.
Args:
*args: Positional arguments used to bind numeric references in the query.
**kwds: Dictionary-based arguments for named references.
"""
self._args = []
for arg in args:
self._args.append(_normalize_query_parameter(arg))
self._kwds = {}
for name, arg in kwds.iteritems():
self._kwds[name] = _normalize_query_parameter(arg)
def run(self, **kwargs):
"""Iterator for this query that handles the LIMIT clause property.
If the GQL query string contains a LIMIT clause, this function fetches
all results before returning an iterator. Otherwise results are retrieved
in batches by the iterator.
Args:
rpc: datastore.DatastoreRPC to use for this request.
Returns:
Iterator for this query.
"""
if self._proto_query.limit() >= 0:
return iter(self.fetch(limit=self._proto_query.limit(),
offset=self._proto_query.offset(),
**kwargs))
else:
results = _BaseQuery.run(self, **kwargs)
try:
for _ in xrange(self._proto_query.offset()):
results.next()
except StopIteration:
pass
return results
def _get_query(self):
return self._proto_query.Bind(self._args, self._kwds, self._cursor)
class UnindexedProperty(Property):
"""A property that isn't indexed by either built-in or composite indices.
TextProperty and BlobProperty derive from this class.
"""
def __init__(self, *args, **kwds):
"""Construct property. See the Property class for details.
Raises:
ConfigurationError if indexed=True.
"""
self._require_parameter(kwds, 'indexed', False)
kwds['indexed'] = True
super(UnindexedProperty, self).__init__(*args, **kwds)
def validate(self, value):
"""Validate property.
Returns:
A valid value.
Raises:
BadValueError if property is not an instance of data_type.
"""
if value is not None and not isinstance(value, self.data_type):
try:
value = self.data_type(value)
except TypeError, err:
raise BadValueError('Property %s must be convertible '
'to a %s instance (%s)' %
(self.name, self.data_type.__name__, err))
value = super(UnindexedProperty, self).validate(value)
if value is not None and not isinstance(value, self.data_type):
raise BadValueError('Property %s must be a %s instance' %
(self.name, self.data_type.__name__))
return value
class TextProperty(UnindexedProperty):
"""A string that can be longer than 500 bytes."""
data_type = Text
class StringProperty(Property):
"""A textual property, which can be multi- or single-line."""
def __init__(self, verbose_name=None, multiline=False, **kwds):
"""Construct string property.
Args:
verbose_name: Verbose name is always first parameter.
multi-line: Carriage returns permitted in property.
"""
super(StringProperty, self).__init__(verbose_name, **kwds)
self.multiline = multiline
def validate(self, value):
"""Validate string property.
Returns:
A valid value.
Raises:
BadValueError if property is not multi-line but value is.
"""
value = super(StringProperty, self).validate(value)
if value is not None and not isinstance(value, basestring):
raise BadValueError(
'Property %s must be a str or unicode instance, not a %s'
% (self.name, type(value).__name__))
if not self.multiline and value and value.find('\n') != -1:
raise BadValueError('Property %s is not multi-line' % self.name)
return value
data_type = basestring
class _CoercingProperty(Property):
"""A Property subclass that extends validate() to coerce to self.data_type."""
def validate(self, value):
"""Coerce values (except None) to self.data_type.
Args:
value: The value to be validated and coerced.
Returns:
The coerced and validated value. It is guaranteed that this is
either None or an instance of self.data_type; otherwise an exception
is raised.
Raises:
BadValueError if the value could not be validated or coerced.
"""
value = super(_CoercingProperty, self).validate(value)
if value is not None and not isinstance(value, self.data_type):
value = self.data_type(value)
return value
class CategoryProperty(_CoercingProperty):
"""A property whose values are Category instances."""
data_type = Category
class LinkProperty(_CoercingProperty):
"""A property whose values are Link instances."""
def validate(self, value):
value = super(LinkProperty, self).validate(value)
if value is not None:
scheme, netloc, path, query, fragment = urlparse.urlsplit(value)
if not scheme or not netloc:
raise BadValueError('Property %s must be a full URL (\'%s\')' %
(self.name, value))
return value
data_type = Link
URLProperty = LinkProperty
class EmailProperty(_CoercingProperty):
"""A property whose values are Email instances."""
data_type = Email
class GeoPtProperty(_CoercingProperty):
"""A property whose values are GeoPt instances."""
data_type = GeoPt
class IMProperty(_CoercingProperty):
"""A property whose values are IM instances."""
data_type = IM
class PhoneNumberProperty(_CoercingProperty):
"""A property whose values are PhoneNumber instances."""
data_type = PhoneNumber
class PostalAddressProperty(_CoercingProperty):
"""A property whose values are PostalAddress instances."""
data_type = PostalAddress
class BlobProperty(UnindexedProperty):
"""A byte string that can be longer than 500 bytes."""
data_type = Blob
class ByteStringProperty(Property):
"""A short (<=500 bytes) byte string.
This type should be used for short binary values that need to be indexed. If
you do not require indexing (regardless of length), use BlobProperty instead.
"""
def validate(self, value):
"""Validate ByteString property.
Returns:
A valid value.
Raises:
BadValueError if property is not instance of 'ByteString'.
"""
if value is not None and not isinstance(value, ByteString):
try:
value = ByteString(value)
except TypeError, err:
raise BadValueError('Property %s must be convertible '
'to a ByteString instance (%s)' % (self.name, err))
value = super(ByteStringProperty, self).validate(value)
if value is not None and not isinstance(value, ByteString):
raise BadValueError('Property %s must be a ByteString instance'
% self.name)
return value
data_type = ByteString
class DateTimeProperty(Property):
"""The base class of all of our date/time properties.
We handle common operations, like converting between time tuples and
datetime instances.
"""
def __init__(self, verbose_name=None, auto_now=False, auto_now_add=False,
**kwds):
"""Construct a DateTimeProperty
Args:
verbose_name: Verbose name is always first parameter.
auto_now: Date/time property is updated with the current time every time
it is saved to the datastore. Useful for properties that want to track
the modification time of an instance.
auto_now_add: Date/time is set to the when its instance is created.
Useful for properties that record the creation time of an entity.
"""
super(DateTimeProperty, self).__init__(verbose_name, **kwds)
self.auto_now = auto_now
self.auto_now_add = auto_now_add
def validate(self, value):
"""Validate datetime.
Returns:
A valid value.
Raises:
BadValueError if property is not instance of 'datetime'.
"""
value = super(DateTimeProperty, self).validate(value)
if value and not isinstance(value, self.data_type):
raise BadValueError('Property %s must be a %s' %
(self.name, self.data_type.__name__))
return value
def default_value(self):
"""Default value for datetime.
Returns:
value of now() as appropriate to the date-time instance if auto_now
or auto_now_add is set, else user configured default value implementation.
"""
if self.auto_now or self.auto_now_add:
return self.now()
return Property.default_value(self)
def get_value_for_datastore(self, model_instance):
"""Get value from property to send to datastore.
Returns:
now() as appropriate to the date-time instance in the odd case where
auto_now is set to True, else the default implementation.
"""
if self.auto_now:
return self.now()
else:
return super(DateTimeProperty,
self).get_value_for_datastore(model_instance)
data_type = datetime.datetime
@staticmethod
def now():
"""Get now as a full datetime value.
Returns:
'now' as a whole timestamp, including both time and date.
"""
return datetime.datetime.now()
def _date_to_datetime(value):
"""Convert a date to a datetime for datastore storage.
Args:
value: A datetime.date object.
Returns:
A datetime object with time set to 0:00.
"""
assert isinstance(value, datetime.date)
return datetime.datetime(value.year, value.month, value.day)
def _time_to_datetime(value):
"""Convert a time to a datetime for datastore storage.
Args:
value: A datetime.time object.
Returns:
A datetime object with date set to 1970-01-01.
"""
assert isinstance(value, datetime.time)
return datetime.datetime(1970, 1, 1,
value.hour, value.minute, value.second,
value.microsecond)
class DateProperty(DateTimeProperty):
"""A date property, which stores a date without a time."""
@staticmethod
def now():
"""Get now as a date datetime value.
Returns:
'date' part of 'now' only.
"""
return datetime.datetime.now().date()
def validate(self, value):
"""Validate date.
Returns:
A valid value.
Raises:
BadValueError if property is not instance of 'date',
or if it is an instance of 'datetime' (which is a subclass
of 'date', but for all practical purposes a different type).
"""
value = super(DateProperty, self).validate(value)
if isinstance(value, datetime.datetime):
raise BadValueError('Property %s must be a %s, not a datetime' %
(self.name, self.data_type.__name__))
return value
def get_value_for_datastore(self, model_instance):
"""Get value from property to send to datastore.
We retrieve a datetime.date from the model instance and return a
datetime.datetime instance with the time set to zero.
See base class method documentation for details.
"""
value = super(DateProperty, self).get_value_for_datastore(model_instance)
if value is not None:
assert isinstance(value, datetime.date)
value = _date_to_datetime(value)
return value
def make_value_from_datastore(self, value):
"""Native representation of this property.
We receive a datetime.datetime retrieved from the entity and return
a datetime.date instance representing its date portion.
See base class method documentation for details.
"""
if value is not None:
assert isinstance(value, datetime.datetime)
value = value.date()
return value
data_type = datetime.date
class TimeProperty(DateTimeProperty):
"""A time property, which stores a time without a date."""
@staticmethod
def now():
"""Get now as a time datetime value.
Returns:
'time' part of 'now' only.
"""
return datetime.datetime.now().time()
def empty(self, value):
"""Is time property empty.
"0:0" (midnight) is not an empty value.
Returns:
True if value is None, else False.
"""
return value is None
def get_value_for_datastore(self, model_instance):
"""Get value from property to send to datastore.
We retrieve a datetime.time from the model instance and return a
datetime.datetime instance with the date set to 1/1/1970.
See base class method documentation for details.
"""
value = super(TimeProperty, self).get_value_for_datastore(model_instance)
if value is not None:
assert isinstance(value, datetime.time), repr(value)
value = _time_to_datetime(value)
return value
def make_value_from_datastore(self, value):
"""Native representation of this property.
We receive a datetime.datetime retrieved from the entity and return
a datetime.date instance representing its time portion.
See base class method documentation for details.
"""
if value is not None:
assert isinstance(value, datetime.datetime)
value = value.time()
return value
data_type = datetime.time
class IntegerProperty(Property):
"""An integer property."""
def validate(self, value):
"""Validate integer property.
Returns:
A valid value.
Raises:
BadValueError if value is not an integer or long instance.
"""
value = super(IntegerProperty, self).validate(value)
if value is None:
return value
if not isinstance(value, (int, long)) or isinstance(value, bool):
raise BadValueError('Property %s must be an int or long, not a %s'
% (self.name, type(value).__name__))
if value < -0x8000000000000000 or value > 0x7fffffffffffffff:
raise BadValueError('Property %s must fit in 64 bits' % self.name)
return value
data_type = int
def empty(self, value):
"""Is integer property empty.
0 is not an empty value.
Returns:
True if value is None, else False.
"""
return value is None
class RatingProperty(_CoercingProperty, IntegerProperty):
"""A property whose values are Rating instances."""
data_type = Rating
class FloatProperty(Property):
"""A float property."""
def validate(self, value):
"""Validate float.
Returns:
A valid value.
Raises:
BadValueError if property is not instance of 'float'.
"""
value = super(FloatProperty, self).validate(value)
if value is not None and not isinstance(value, float):
raise BadValueError('Property %s must be a float' % self.name)
return value
data_type = float
def empty(self, value):
"""Is float property empty.
0.0 is not an empty value.
Returns:
True if value is None, else False.
"""
return value is None
class BooleanProperty(Property):
"""A boolean property."""
def validate(self, value):
"""Validate boolean.
Returns:
A valid value.
Raises:
BadValueError if property is not instance of 'bool'.
"""
value = super(BooleanProperty, self).validate(value)
if value is not None and not isinstance(value, bool):
raise BadValueError('Property %s must be a bool' % self.name)
return value
data_type = bool
def empty(self, value):
"""Is boolean property empty.
False is not an empty value.
Returns:
True if value is None, else False.
"""
return value is None
class UserProperty(Property):
"""A user property."""
def __init__(self,
verbose_name=None,
name=None,
required=False,
validator=None,
choices=None,
auto_current_user=False,
auto_current_user_add=False,
indexed=True):
"""Initializes this Property with the given options.
Note: this does *not* support the 'default' keyword argument.
Use auto_current_user_add=True instead.
Args:
verbose_name: User friendly name of property.
name: Storage name for property. By default, uses attribute name
as it is assigned in the Model sub-class.
required: Whether property is required.
validator: User provided method used for validation.
choices: User provided set of valid property values.
auto_current_user: If true, the value is set to the current user
each time the entity is written to the datastore.
auto_current_user_add: If true, the value is set to the current user
the first time the entity is written to the datastore.
indexed: Whether property is indexed.
"""
super(UserProperty, self).__init__(verbose_name, name,
required=required,
validator=validator,
choices=choices,
indexed=indexed)
self.auto_current_user = auto_current_user
self.auto_current_user_add = auto_current_user_add
def validate(self, value):
"""Validate user.
Returns:
A valid value.
Raises:
BadValueError if property is not instance of 'User'.
"""
value = super(UserProperty, self).validate(value)
if value is not None and not isinstance(value, users.User):
raise BadValueError('Property %s must be a User' % self.name)
return value
def default_value(self):
"""Default value for user.
Returns:
Value of users.get_current_user() if auto_current_user or
auto_current_user_add is set; else None. (But *not* the default
implementation, since we don't support the 'default' keyword
argument.)
"""
if self.auto_current_user or self.auto_current_user_add:
return users.get_current_user()
return None
def get_value_for_datastore(self, model_instance):
"""Get value from property to send to datastore.
Returns:
Value of users.get_current_user() if auto_current_user is set;
else the default implementation.
"""
if self.auto_current_user:
return users.get_current_user()
return super(UserProperty, self).get_value_for_datastore(model_instance)
data_type = users.User
class ListProperty(Property):
"""A property that stores a list of things.
This is a parameterized property; the parameter must be a valid
non-list data type, and all items must conform to this type.
"""
def __init__(self, item_type, verbose_name=None, default=None, **kwds):
"""Construct ListProperty.
Args:
item_type: Type for the list items; must be one of the allowed property
types.
verbose_name: Optional verbose name.
default: Optional default value; if omitted, an empty list is used.
**kwds: Optional additional keyword arguments, passed to base class.
Note that the only permissible value for 'required' is True.
"""
if item_type is str:
item_type = basestring
if not isinstance(item_type, type):
raise TypeError('Item type should be a type object')
if item_type not in _ALLOWED_PROPERTY_TYPES:
raise ValueError('Item type %s is not acceptable' % item_type.__name__)
if issubclass(item_type, (Blob, Text)):
self._require_parameter(kwds, 'indexed', False)
kwds['indexed'] = True
self._require_parameter(kwds, 'required', True)
if default is None:
default = []
self.item_type = item_type
super(ListProperty, self).__init__(verbose_name,
default=default,
**kwds)
def validate(self, value):
"""Validate list.
Returns:
A valid value.
Raises:
BadValueError if property is not a list whose items are instances of
the item_type given to the constructor.
"""
value = super(ListProperty, self).validate(value)
if value is not None:
if not isinstance(value, list):
raise BadValueError('Property %s must be a list' % self.name)
value = self.validate_list_contents(value)
return value
def validate_list_contents(self, value):
"""Validates that all items in the list are of the correct type.
Returns:
The validated list.
Raises:
BadValueError if the list has items are not instances of the
item_type given to the constructor.
"""
if self.item_type in (int, long):
item_type = (int, long)
else:
item_type = self.item_type
for item in value:
if not isinstance(item, item_type):
if item_type == (int, long):
raise BadValueError('Items in the %s list must all be integers.' %
self.name)
else:
raise BadValueError(
'Items in the %s list must all be %s instances' %
(self.name, self.item_type.__name__))
return value
def empty(self, value):
"""Is list property empty.
[] is not an empty value.
Returns:
True if value is None, else false.
"""
return value is None
data_type = list
def default_value(self):
"""Default value for list.
Because the property supplied to 'default' is a static value,
that value must be shallow copied to prevent all fields with
default values from sharing the same instance.
Returns:
Copy of the default value.
"""
return list(super(ListProperty, self).default_value())
def get_value_for_datastore(self, model_instance):
"""Get value from property to send to datastore.
Returns:
validated list appropriate to save in the datastore.
"""
value = self.validate_list_contents(
super(ListProperty, self).get_value_for_datastore(model_instance))
if self.validator:
self.validator(value)
return value
class StringListProperty(ListProperty):
"""A property that stores a list of strings.
A shorthand for the most common type of ListProperty.
"""
def __init__(self, verbose_name=None, default=None, **kwds):
"""Construct StringListProperty.
Args:
verbose_name: Optional verbose name.
default: Optional default value; if omitted, an empty list is used.
**kwds: Optional additional keyword arguments, passed to ListProperty().
"""
super(StringListProperty, self).__init__(basestring,
verbose_name=verbose_name,
default=default,
**kwds)
class ReferenceProperty(Property):
"""A property that represents a many-to-one reference to another model.
For example, a reference property in model A that refers to model B forms
a many-to-one relationship from A to B: every instance of A refers to a
single B instance, and every B instance can have many A instances refer
to it.
"""
def __init__(self,
reference_class=None,
verbose_name=None,
collection_name=None,
**attrs):
"""Construct ReferenceProperty.
Args:
reference_class: Which model class this property references.
verbose_name: User friendly name of property.
collection_name: If provided, alternate name of collection on
reference_class to store back references. Use this to allow
a Model to have multiple fields which refer to the same class.
"""
super(ReferenceProperty, self).__init__(verbose_name, **attrs)
self.collection_name = collection_name
if reference_class is None:
reference_class = Model
if not ((isinstance(reference_class, type) and
issubclass(reference_class, Model)) or
reference_class is _SELF_REFERENCE):
raise KindError('reference_class must be Model or _SELF_REFERENCE')
self.reference_class = self.data_type = reference_class
def __property_config__(self, model_class, property_name):
"""Loads all of the references that point to this model.
We need to do this to create the ReverseReferenceProperty properties for
this model and create the <reference>_set attributes on the referenced
model, e.g.:
class Story(db.Model):
title = db.StringProperty()
class Comment(db.Model):
story = db.ReferenceProperty(Story)
story = Story.get(id)
print [c for c in story.comment_set]
In this example, the comment_set property was created based on the reference
from Comment to Story (which is inherently one to many).
Args:
model_class: Model class which will have its reference properties
initialized.
property_name: Name of property being configured.
Raises:
DuplicatePropertyError if referenced class already has the provided
collection name as a property.
"""
super(ReferenceProperty, self).__property_config__(model_class,
property_name)
if self.reference_class is _SELF_REFERENCE:
self.reference_class = self.data_type = model_class
if self.collection_name is None:
self.collection_name = '%s_set' % (model_class.__name__.lower())
existing_prop = getattr(self.reference_class, self.collection_name, None)
if existing_prop is not None:
if not (isinstance(existing_prop, _ReverseReferenceProperty) and
existing_prop._prop_name == property_name and
existing_prop._model.__name__ == model_class.__name__ and
existing_prop._model.__module__ == model_class.__module__):
raise DuplicatePropertyError('Class %s already has property %s '
% (self.reference_class.__name__,
self.collection_name))
setattr(self.reference_class,
self.collection_name,
_ReverseReferenceProperty(model_class, property_name))
def __get__(self, model_instance, model_class):
"""Get reference object.
This method will fetch unresolved entities from the datastore if
they are not already loaded.
Returns:
ReferenceProperty to Model object if property is set, else None.
"""
if model_instance is None:
return self
if hasattr(model_instance, self.__id_attr_name()):
reference_id = getattr(model_instance, self.__id_attr_name())
else:
reference_id = None
if reference_id is not None:
resolved = getattr(model_instance, self.__resolved_attr_name())
if resolved is not None:
return resolved
else:
instance = get(reference_id)
if instance is None:
raise Error('ReferenceProperty failed to be resolved')
setattr(model_instance, self.__resolved_attr_name(), instance)
return instance
else:
return None
def __set__(self, model_instance, value):
"""Set reference."""
value = self.validate(value)
if value is not None:
if isinstance(value, datastore.Key):
setattr(model_instance, self.__id_attr_name(), value)
setattr(model_instance, self.__resolved_attr_name(), None)
else:
setattr(model_instance, self.__id_attr_name(), value.key())
setattr(model_instance, self.__resolved_attr_name(), value)
else:
setattr(model_instance, self.__id_attr_name(), None)
setattr(model_instance, self.__resolved_attr_name(), None)
def get_value_for_datastore(self, model_instance):
"""Get key of reference rather than reference itself."""
return getattr(model_instance, self.__id_attr_name())
def validate(self, value):
"""Validate reference.
Returns:
A valid value.
Raises:
BadValueError for the following reasons:
- Value is not saved.
- Object not of correct model type for reference.
"""
if isinstance(value, datastore.Key):
return value
if value is not None and not value.has_key():
raise BadValueError(
'%s instance must have a complete key before it can be stored as a '
'reference' % self.reference_class.kind())
value = super(ReferenceProperty, self).validate(value)
if value is not None and not isinstance(value, self.reference_class):
raise KindError('Property %s must be an instance of %s' %
(self.name, self.reference_class.kind()))
return value
def __id_attr_name(self):
"""Get attribute of referenced id.
Returns:
Attribute where to store id of referenced entity.
"""
return self._attr_name()
def __resolved_attr_name(self):
"""Get attribute of resolved attribute.
The resolved attribute is where the actual loaded reference instance is
stored on the referring model instance.
Returns:
Attribute name of where to store resolved reference model instance.
"""
return '_RESOLVED' + self._attr_name()
Reference = ReferenceProperty
def SelfReferenceProperty(verbose_name=None, collection_name=None, **attrs):
"""Create a self reference.
Function for declaring a self referencing property on a model.
Example:
class HtmlNode(db.Model):
parent = db.SelfReferenceProperty('Parent', 'children')
Args:
verbose_name: User friendly name of property.
collection_name: Name of collection on model.
Raises:
ConfigurationError if reference_class provided as parameter.
"""
if 'reference_class' in attrs:
raise ConfigurationError(
'Do not provide reference_class to self-reference.')
return ReferenceProperty(_SELF_REFERENCE,
verbose_name,
collection_name,
**attrs)
SelfReference = SelfReferenceProperty
class _ReverseReferenceProperty(Property):
"""The inverse of the Reference property above.
We construct reverse references automatically for the model to which
the Reference property is pointing to create the one-to-many property for
that model. For example, if you put a Reference property in model A that
refers to model B, we automatically create a _ReverseReference property in
B called a_set that can fetch all of the model A instances that refer to
that instance of model B.
"""
def __init__(self, model, prop):
"""Constructor for reverse reference.
Constructor does not take standard values of other property types.
Args:
model: Model class that this property is a collection of.
property: Name of foreign property on referred model that points back
to this properties entity.
"""
self.__model = model
self.__property = prop
@property
def _model(self):
"""Internal helper to access the model class, read-only."""
return self.__model
@property
def _prop_name(self):
"""Internal helper to access the property name, read-only."""
return self.__property
def __get__(self, model_instance, model_class):
"""Fetches collection of model instances of this collection property."""
if model_instance is not None:
query = Query(self.__model)
return query.filter(self.__property + ' =', model_instance.key())
else:
return self
def __set__(self, model_instance, value):
"""Not possible to set a new collection."""
raise BadValueError('Virtual property is read-only')
run_in_transaction = datastore.RunInTransaction
run_in_transaction_custom_retries = datastore.RunInTransactionCustomRetries
RunInTransaction = run_in_transaction
RunInTransactionCustomRetries = run_in_transaction_custom_retries
| rev2004/android2cloud.app-engine | google_appengine/google/appengine/ext/db/__init__.py | Python | mit | 101,475 |
//= require ./core/monocle
//= require ./compat/env
//= require ./compat/css
//= require ./compat/stubs
//= require ./compat/browser
//= require ./compat/gala
//= require ./core/bookdata
//= require ./core/factory
//= require ./core/events
//= require ./core/styles
//= require ./core/formatting
//= require ./core/reader
//= require ./core/book
//= require ./core/place
//= require ./core/component
//= require ./core/selection
//= require ./core/billboard
//= require ./controls/panel
//= require ./panels/twopane
//= require ./panels/imode
//= require ./panels/eink
//= require ./panels/marginal
//= require ./panels/magic
//= require ./dimensions/columns
//= require ./flippers/slider
//= require ./flippers/scroller
//= require ./flippers/instant
| joseph/Monocle | src/monocore.js | JavaScript | mit | 752 |
<?php
/**
* This file is part of the Bruery Platform.
*
* (c) Viktore Zara <viktore.zara@gmail.com>
* (c) Mell Zamora <mellzamora@outlook.com>
*
* Copyright (c) 2017. For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
*/
namespace Bruery\EntityAuditBundle\EventListener;
use Bruery\EntityAuditBundle\Model\AuditManager;
use Doctrine\Common\EventSubscriber;
use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;
use Doctrine\ORM\Mapping\ClassMetadata;
class LogRevisionsListener implements EventSubscriber
{
/**
* @var \SimpleThings\EntityAudit\AuditConfiguration
*/
protected $config;
/**
* @var \SimpleThings\EntityAudit\Metadata\MetadataFactory
*/
protected $metadataFactory;
/**
* @var \Doctrine\DBAL\Connection
*/
protected $conn;
/**
* @var \Doctrine\DBAL\Platforms\AbstractPlatform
*/
protected $platform;
/**
* @var \Doctrine\ORM\EntityManager
*/
protected $sourceEm;
/**
* @var array
*/
protected $insertRevisionSQL = array();
/**
* @var \Doctrine\ORM\UnitOfWork
*/
protected $uow;
/**
* @var int
*/
protected $revisionId;
protected $auditEm;
public function __construct(AuditManager $auditManager)
{
$this->config = $auditManager->getConfiguration();
$this->metadataFactory = $auditManager->getMetadataFactory();
}
public function getSubscribedEvents()
{
return array(Events::onFlush, Events::postPersist, Events::postUpdate);
}
public function postPersist(LifecycleEventArgs $eventArgs)
{
// onFlush was executed before, everything already initialized
$entity = $eventArgs->getEntity();
$class = $this->sourceEm->getClassMetadata(get_class($entity));
if (!$this->metadataFactory->isAudited($class->name)) {
return;
}
$this->saveRevisionEntityData($class, $this->getOriginalEntityData($entity), 'INS');
}
public function postUpdate(LifecycleEventArgs $eventArgs)
{
// onFlush was executed before, everything already initialized
$entity = $eventArgs->getEntity();
$class = $this->sourceEm->getClassMetadata(get_class($entity));
if (!$this->metadataFactory->isAudited($class->name)) {
return;
}
// get changes => should be already computed here (is a listener)
$changeset = $this->uow->getEntityChangeSet($entity);
foreach ($this->config->getGlobalIgnoreColumns() as $column) {
if (isset($changeset[$column])) {
unset($changeset[$column]);
}
}
// if we have no changes left => don't create revision log
if (count($changeset) == 0) {
return;
}
$entityData = array_merge($this->getOriginalEntityData($entity), $this->uow->getEntityIdentifier($entity));
$this->saveRevisionEntityData($class, $entityData, 'UPD');
}
public function onFlush(OnFlushEventArgs $eventArgs)
{
$this->sourceEm = $eventArgs->getEntityManager();
$this->conn = $this->sourceEm->getConnection();
$this->uow = $this->sourceEm->getUnitOfWork();
$this->platform = $this->conn->getDatabasePlatform();
$this->revisionId = null; // reset revision
foreach ($this->uow->getScheduledEntityDeletions() as $entity) {
$class = $this->sourceEm->getClassMetadata(get_class($entity));
if (!$this->metadataFactory->isAudited($class->name)) {
continue;
}
$entityData = array_merge($this->getOriginalEntityData($entity), $this->uow->getEntityIdentifier($entity));
$this->saveRevisionEntityData($class, $entityData, 'DEL');
}
}
/**
* get original entity data, including versioned field, if "version" constraint is used
*
* @param mixed $entity
* @return array
*/
protected function getOriginalEntityData($entity)
{
$class = $this->sourceEm->getClassMetadata(get_class($entity));
$data = $this->uow->getOriginalEntityData($entity);
if ($class->isVersioned) {
$versionField = $class->versionField;
$data[$versionField] = $class->reflFields[$versionField]->getValue($entity);
}
return $data;
}
protected function getRevisionId()
{
if ($this->revisionId === null) {
$this->auditEm->getConnection()->insert($this->config->getRevisionTableName(), array(
'timestamp' => date_create('now'),
'username' => $this->config->getCurrentUsername() ?: 'admin',
), array(
Type::DATETIME,
Type::STRING
));
$sequenceName = $this->platform->supportsSequences()
? 'REVISIONS_ID_SEQ'
: null;
$this->revisionId = $this->auditEm->getConnection()->lastInsertId($sequenceName);
}
return $this->revisionId;
}
protected function getInsertRevisionSQL($class)
{
if (!isset($this->insertRevisionSQL[$class->name])) {
$placeholders = array('?', '?');
$tableName = $this->config->getTablePrefix() . $class->table['name'] . $this->config->getTableSuffix();
$sql = "INSERT INTO " . $tableName . " (" .
$this->config->getRevisionFieldName() . ", " . $this->config->getRevisionTypeFieldName();
$fields = array();
foreach ($class->associationMappings as $assoc) {
if (($assoc['type'] & ClassMetadata::TO_ONE) > 0 && $assoc['isOwningSide']) {
foreach ($assoc['targetToSourceKeyColumns'] as $sourceCol) {
$fields[$sourceCol] = true;
$sql .= ', ' . $sourceCol;
$placeholders[] = '?';
}
}
}
foreach ($class->fieldNames as $field) {
if (array_key_exists($field, $fields)) {
continue;
}
$type = Type::getType($class->fieldMappings[$field]['type']);
$placeholders[] = (!empty($class->fieldMappings[$field]['requireSQLConversion']))
? $type->convertToDatabaseValueSQL('?', $this->platform)
: '?';
$sql .= ', ' . $class->getQuotedColumnName($field, $this->platform);
}
$sql .= ") VALUES (" . implode(", ", $placeholders) . ")";
$this->insertRevisionSQL[$class->name] = $sql;
}
return $this->insertRevisionSQL[$class->name];
}
/**
* @param ClassMetadata $class
* @param array $entityData
* @param string $revType
*/
protected function saveRevisionEntityData($class, $entityData, $revType)
{
$params = array($this->getRevisionId(), $revType);
$types = array(\PDO::PARAM_INT, \PDO::PARAM_STR);
$fields = array();
foreach ($class->associationMappings as $field => $assoc) {
if (($assoc['type'] & ClassMetadata::TO_ONE) > 0 && $assoc['isOwningSide']) {
$targetClass = $this->sourceEm->getClassMetadata($assoc['targetEntity']);
if ($entityData[$field] !== null) {
$relatedId = $this->uow->getEntityIdentifier($entityData[$field]);
}
$targetClass = $this->sourceEm->getClassMetadata($assoc['targetEntity']);
foreach ($assoc['sourceToTargetKeyColumns'] as $sourceColumn => $targetColumn) {
$fields[$sourceColumn] = true;
if ($entityData[$field] === null) {
$params[] = null;
$types[] = \PDO::PARAM_STR;
} else {
$params[] = $relatedId[$targetClass->fieldNames[$targetColumn]];
$types[] = $targetClass->getTypeOfColumn($targetColumn);
}
}
}
}
foreach ($class->fieldNames as $field) {
if (array_key_exists($field, $fields)) {
continue;
}
$params[] = $entityData[$field];
$types[] = $class->fieldMappings[$field]['type'];
}
$this->auditEm->getConnection()->executeUpdate($this->getInsertRevisionSQL($class), $params, $types);
}
/**
* @return mixed
*/
public function getAuditEm()
{
return $this->auditEm;
}
/**
* @param mixed $auditEm
*/
public function setAuditEm($auditEm)
{
$this->auditEm = $auditEm;
}
}
| bruery/platform | src/bundles/EntityAuditBundle/EventListener/LogRevisionsListener.php | PHP | mit | 8,931 |
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const fs = jest.genMockFromModule('fs');
const mockFiles = new Map();
function __setMockFiles(newMockFiles) {
mockFiles.clear();
Object.keys(newMockFiles).forEach(fileName => {
mockFiles.set(fileName, newMockFiles[fileName]);
});
}
fs.__setMockFiles = __setMockFiles;
fs.readFileSync = jest.fn(file => mockFiles.get(file));
module.exports = fs;
| bookman25/jest | packages/jest-config/src/__mocks__/fs.js | JavaScript | mit | 584 |
using System;
using System.Runtime.InteropServices;
using OpenTK.Graphics.OpenGL;
namespace Gwen.Renderer.OpenTK
{
public class OpenTKGL10 : OpenTKBase
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Vertex
{
public short x, y;
public float u, v;
public byte r, g, b, a;
}
private const int MaxVerts = 1024;
private int m_VertNum;
private readonly Vertex[] m_Vertices;
private readonly int m_VertexSize;
private bool m_WasBlendEnabled, m_WasTexture2DEnabled, m_WasDepthTestEnabled;
private int m_PrevBlendSrc, m_PrevBlendDst, m_PrevAlphaFunc;
private float m_PrevAlphaRef;
private bool m_RestoreRenderState;
public OpenTKGL10(bool restoreRenderState = true)
: base()
{
m_Vertices = new Vertex[MaxVerts];
m_VertexSize = Marshal.SizeOf(m_Vertices[0]);
m_RestoreRenderState = restoreRenderState;
}
public override void Begin()
{
if (m_RestoreRenderState)
{
// Get previous parameter values before changing them.
GL.GetInteger(GetPName.BlendSrc, out m_PrevBlendSrc);
GL.GetInteger(GetPName.BlendDst, out m_PrevBlendDst);
GL.GetInteger(GetPName.AlphaTestFunc, out m_PrevAlphaFunc);
GL.GetFloat(GetPName.AlphaTestRef, out m_PrevAlphaRef);
m_WasBlendEnabled = GL.IsEnabled(EnableCap.Blend);
m_WasTexture2DEnabled = GL.IsEnabled(EnableCap.Texture2D);
m_WasDepthTestEnabled = GL.IsEnabled(EnableCap.DepthTest);
}
// Set default values and enable/disable caps.
GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
GL.AlphaFunc(AlphaFunction.Greater, 1.0f);
GL.Enable(EnableCap.Blend);
GL.Disable(EnableCap.DepthTest);
GL.Disable(EnableCap.Texture2D);
m_VertNum = 0;
m_DrawCallCount = 0;
m_ClipEnabled = false;
m_TextureEnabled = false;
m_LastTextureID = -1;
GL.EnableClientState(ArrayCap.VertexArray);
GL.EnableClientState(ArrayCap.ColorArray);
GL.EnableClientState(ArrayCap.TextureCoordArray);
}
public override void End()
{
Flush();
if (m_RestoreRenderState)
{
GL.BindTexture(TextureTarget.Texture2D, 0);
m_LastTextureID = 0;
// Restore the previous parameter values.
GL.BlendFunc((BlendingFactorSrc)m_PrevBlendSrc, (BlendingFactorDest)m_PrevBlendDst);
GL.AlphaFunc((AlphaFunction)m_PrevAlphaFunc, m_PrevAlphaRef);
if (!m_WasBlendEnabled)
GL.Disable(EnableCap.Blend);
if (m_WasTexture2DEnabled && !m_TextureEnabled)
GL.Enable(EnableCap.Texture2D);
if (m_WasDepthTestEnabled)
GL.Enable(EnableCap.DepthTest);
}
GL.DisableClientState(ArrayCap.VertexArray);
GL.DisableClientState(ArrayCap.ColorArray);
GL.DisableClientState(ArrayCap.TextureCoordArray);
}
public override int VertexCount { get { return m_VertNum; } }
protected override unsafe void Flush()
{
if (m_VertNum == 0) return;
fixed (short* ptr1 = &m_Vertices[0].x)
fixed (byte* ptr2 = &m_Vertices[0].r)
fixed (float* ptr3 = &m_Vertices[0].u)
{
GL.VertexPointer(2, VertexPointerType.Short, m_VertexSize, (IntPtr)ptr1);
GL.ColorPointer(4, ColorPointerType.UnsignedByte, m_VertexSize, (IntPtr)ptr2);
GL.TexCoordPointer(2, TexCoordPointerType.Float, m_VertexSize, (IntPtr)ptr3);
GL.DrawArrays(PrimitiveType.Quads, 0, m_VertNum);
}
m_DrawCallCount++;
m_VertNum = 0;
}
protected override void DrawRect(Rectangle rect, float u1 = 0, float v1 = 0, float u2 = 1, float v2 = 1)
{
if (m_VertNum + 4 >= MaxVerts)
{
Flush();
}
if (m_ClipEnabled)
{
// cpu scissors test
if (rect.Y < ClipRegion.Y)
{
int oldHeight = rect.Height;
int delta = ClipRegion.Y - rect.Y;
rect.Y = ClipRegion.Y;
rect.Height -= delta;
if (rect.Height <= 0)
{
return;
}
float dv = (float)delta / (float)oldHeight;
v1 += dv * (v2 - v1);
}
if ((rect.Y + rect.Height) > (ClipRegion.Y + ClipRegion.Height))
{
int oldHeight = rect.Height;
int delta = (rect.Y + rect.Height) - (ClipRegion.Y + ClipRegion.Height);
rect.Height -= delta;
if (rect.Height <= 0)
{
return;
}
float dv = (float)delta / (float)oldHeight;
v2 -= dv * (v2 - v1);
}
if (rect.X < ClipRegion.X)
{
int oldWidth = rect.Width;
int delta = ClipRegion.X - rect.X;
rect.X = ClipRegion.X;
rect.Width -= delta;
if (rect.Width <= 0)
{
return;
}
float du = (float)delta / (float)oldWidth;
u1 += du * (u2 - u1);
}
if ((rect.X + rect.Width) > (ClipRegion.X + ClipRegion.Width))
{
int oldWidth = rect.Width;
int delta = (rect.X + rect.Width) - (ClipRegion.X + ClipRegion.Width);
rect.Width -= delta;
if (rect.Width <= 0)
{
return;
}
float du = (float)delta / (float)oldWidth;
u2 -= du * (u2 - u1);
}
}
int vertexIndex = m_VertNum;
m_Vertices[vertexIndex].x = (short)rect.X;
m_Vertices[vertexIndex].y = (short)rect.Y;
m_Vertices[vertexIndex].u = u1;
m_Vertices[vertexIndex].v = v1;
m_Vertices[vertexIndex].r = m_Color.R;
m_Vertices[vertexIndex].g = m_Color.G;
m_Vertices[vertexIndex].b = m_Color.B;
m_Vertices[vertexIndex].a = m_Color.A;
vertexIndex++;
m_Vertices[vertexIndex].x = (short)(rect.X + rect.Width);
m_Vertices[vertexIndex].y = (short)rect.Y;
m_Vertices[vertexIndex].u = u2;
m_Vertices[vertexIndex].v = v1;
m_Vertices[vertexIndex].r = m_Color.R;
m_Vertices[vertexIndex].g = m_Color.G;
m_Vertices[vertexIndex].b = m_Color.B;
m_Vertices[vertexIndex].a = m_Color.A;
vertexIndex++;
m_Vertices[vertexIndex].x = (short)(rect.X + rect.Width);
m_Vertices[vertexIndex].y = (short)(rect.Y + rect.Height);
m_Vertices[vertexIndex].u = u2;
m_Vertices[vertexIndex].v = v2;
m_Vertices[vertexIndex].r = m_Color.R;
m_Vertices[vertexIndex].g = m_Color.G;
m_Vertices[vertexIndex].b = m_Color.B;
m_Vertices[vertexIndex].a = m_Color.A;
vertexIndex++;
m_Vertices[vertexIndex].x = (short)rect.X;
m_Vertices[vertexIndex].y = (short)(rect.Y + rect.Height);
m_Vertices[vertexIndex].u = u1;
m_Vertices[vertexIndex].v = v2;
m_Vertices[vertexIndex].r = m_Color.R;
m_Vertices[vertexIndex].g = m_Color.G;
m_Vertices[vertexIndex].b = m_Color.B;
m_Vertices[vertexIndex].a = m_Color.A;
m_VertNum += 4;
}
public override void Resize(int width, int height)
{
GL.Viewport(0, 0, width, height);
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Ortho(0, width, height, 0, -1, 1);
}
}
}
| kpalosaa/gwen-net-ex | Gwen.Renderer.OpenTK/Renderer/OpenTKGL10.cs | C# | mit | 6,584 |
package com.rohos.logon1;
/*
* Copyright 2014 Tesline-Service SRL. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
/**
* Created by Alex on 03.01.14.
* Rohos Loogn Key How it works help
*
* @author AlexShilon
*/
public class HelpActivity extends Activity {
private final String TAG = "HelpActiviy";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
Button learnMore = findViewById(R.id.learn_more);
learnMore.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
openWebPage();
}
});
//setPageContentView(R.layout.activity_help);
//setTextViewHtmlFromResource(R.id.details, R.string.howitworks_page_enter_code_details);
}
private void openWebPage() {
try {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.rohos.com/2013/12/login-unlock-computer-by-using-smartphone/"));
startActivity(intent);
} catch (Exception e) {
// Log.e(TAG, e.toString());
}
}
/*@Override
protected void onRightButtonPressed() {
//startPageActivity(IntroVerifyDeviceActivity.class);
}*/
}
| AlexShilon/RohosLogonMobile | Android/RohosLogonKey/src/main/java/com/rohos/logon1/HelpActivity.java | Java | mit | 1,571 |
# Generated by Django 3.2 on 2021-05-11 13:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('stock', '0062_auto_20210511_2151'),
]
operations = [
migrations.RemoveField(
model_name='stockitemtracking',
name='link',
),
migrations.RemoveField(
model_name='stockitemtracking',
name='quantity',
),
migrations.RemoveField(
model_name='stockitemtracking',
name='system',
),
migrations.RemoveField(
model_name='stockitemtracking',
name='title',
),
]
| inventree/InvenTree | InvenTree/stock/migrations/0063_auto_20210511_2343.py | Python | mit | 676 |
'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Profiles', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
first_name: {
type: Sequelize.STRING
},
last_name: {
type: Sequelize.STRING
},
gender: {
type: Sequelize.STRING
},
age: {
type: Sequelize.INTEGER
},
country_origin: {
type: Sequelize.STRING
},
catch_phrase: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Profiles');
}
}; | bigkangtheory/wanderly | back/migrations/20170131224205-create-profile.js | JavaScript | mit | 897 |
// -*- Mode: C++; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
#define YBUTIL_SOURCE
#include "util/string_type.h"
#if defined(YB_USE_WX)
#include <wx/strconv.h>
#elif defined(YB_USE_QT)
#include <QTextCodec>
#endif
#include <cstring>
#include <locale>
#include <stdexcept>
namespace Yb {
static size_t do_fast_narrow(const std::wstring &wide, std::string &narrow)
{
const wchar_t *src = wide.c_str();
const wchar_t *src0 = src;
char *dst = &narrow[0];
do {
wchar_t c = *src;
if (!c || (c & ~(wchar_t)0x7f))
break;
*dst = (char)c;
++dst;
++src;
} while (1);
size_t processed = src - src0;
if (processed == wide.size())
narrow.resize(dst - &narrow[0]);
return processed;
}
static size_t do_fast_widen(const std::string &narrow, std::wstring &wide)
{
const char *src = narrow.c_str();
const char *src0 = src;
wchar_t *dst = &wide[0];
do {
char c = *src;
if (!c || (c & ~(char)0x7f))
break;
*dst = (wchar_t)c;
++dst;
++src;
} while (1);
size_t processed = src - src0;
if (processed == narrow.size())
wide.resize(dst - &wide[0]);
return processed;
}
YBUTIL_DECL const std::string fast_narrow(const std::wstring &wide)
{
if (wide.empty())
return std::string();
std::string narrow(4 * wide.size(), '\0'); // max character length in UTF-8
size_t processed = do_fast_narrow(wide, narrow);
if (processed == wide.size())
return narrow;
throw std::runtime_error("non ascii detected, fast_narrow failed");
}
YBUTIL_DECL const std::wstring fast_widen(const std::string &narrow)
{
if (narrow.empty())
return std::wstring();
std::wstring wide(narrow.size(), L'\0');
size_t processed = do_fast_widen(narrow, wide);
if (processed == narrow.size())
return wide;
throw std::runtime_error("non ascii detected, fast_widen failed");
}
static const std::string do_narrow(
const std::wstring &wide, const std::locale &loc)
{
if (wide.empty())
return std::string();
std::string narrow(4*wide.size(), '\0'); // max character length in UTF-8
size_t processed = do_fast_narrow(wide, narrow);
if (processed == wide.size())
return narrow;
typedef std::wstring::traits_type::state_type state_type;
typedef std::codecvt<wchar_t, char, state_type> CVT;
const CVT& cvt = std::use_facet<CVT>(loc);
//std::string narrow(cvt.max_length()*wide.size(), '\0');
state_type state = state_type();
const wchar_t* from_beg = &wide[0];
const wchar_t* from_end = from_beg + wide.size();
const wchar_t* from_nxt;
char* to_beg = &narrow[0];
char* to_end = to_beg + narrow.size();
char* to_nxt;
std::string::size_type sz = 0;
std::codecvt_base::result r;
do {
r = cvt.out(state, from_beg, from_end, from_nxt,
to_beg, to_end, to_nxt);
switch (r)
{
case std::codecvt_base::error:
throw std::runtime_error("error converting wstring to string");
case std::codecvt_base::partial:
sz += to_nxt - to_beg;
narrow.resize(2*narrow.size());
to_beg = &narrow[sz];
to_end = &narrow[0] + narrow.size();
break;
case std::codecvt_base::noconv:
narrow.resize(sz + (from_end-from_beg)*sizeof(wchar_t));
std::memcpy(&narrow[sz], from_beg,(from_end-from_beg)*sizeof(wchar_t));
r = std::codecvt_base::ok;
break;
case std::codecvt_base::ok:
sz += to_nxt - to_beg;
narrow.resize(sz);
break;
}
} while (r != std::codecvt_base::ok);
return narrow;
}
static const std::wstring do_widen(
const std::string &narrow, const std::locale &loc)
{
if (narrow.empty())
return std::wstring();
std::wstring wide(narrow.size(), L'\0');
size_t processed = do_fast_widen(narrow, wide);
if (processed == narrow.size())
return wide;
typedef std::string::traits_type::state_type state_type;
typedef std::codecvt<wchar_t, char, state_type> CVT;
const CVT& cvt = std::use_facet<CVT>(loc);
state_type state = state_type();
const char* from_beg = &narrow[0];
const char* from_end = from_beg + narrow.size();
const char* from_nxt;
wchar_t* to_beg = &wide[0];
wchar_t* to_end = to_beg + wide.size();
wchar_t* to_nxt;
std::wstring::size_type sz = 0;
std::codecvt_base::result r;
do {
r = cvt.in(state, from_beg, from_end, from_nxt,
to_beg, to_end, to_nxt);
switch (r)
{
case std::codecvt_base::error:
throw std::runtime_error("error converting string to wstring");
case std::codecvt_base::partial:
sz += to_nxt - to_beg;
wide.resize(2*wide.size());
to_beg = &wide[sz];
to_end = &wide[0] + wide.size();
break;
case std::codecvt_base::noconv:
wide.resize(sz + (from_end-from_beg));
std::memcpy(&wide[sz], from_beg, (std::size_t)(from_end-from_beg));
r = std::codecvt_base::ok;
break;
case std::codecvt_base::ok:
sz += to_nxt - to_beg;
wide.resize(sz);
break;
}
} while (r != std::codecvt_base::ok);
return wide;
}
YBUTIL_DECL const std::string get_locale(const std::string &enc_name = "")
{
if (enc_name.empty())
return
#ifdef YBUTIL_WINDOWS
"rus_rus.866"
#else
"ru_RU.UTF-8"
#endif
;
return enc_name;
}
YBUTIL_DECL const std::string str2std(const String &s, const std::string &enc_name)
{
#if defined(YB_USE_WX)
if (enc_name.empty())
return std::string(s.mb_str(wxConvUTF8));
wxCSConv conv(wxString(enc_name.c_str(), wxConvUTF8).GetData());
return std::string(s.mb_str(conv));
#elif defined(YB_USE_QT)
if (enc_name.empty())
return std::string(s.toLocal8Bit().constData());
QTextCodec *codec = QTextCodec::codecForName(enc_name.c_str());
return std::string(codec->fromUnicode(s).constData());
#elif defined(YB_USE_UNICODE)
std::locale loc(get_locale(enc_name).c_str());
return do_narrow(s, loc);
#else
return s;
#endif
}
YBUTIL_DECL const String std2str(const std::string &s, const std::string &enc_name)
{
#if defined(YB_USE_WX)
if (enc_name.empty())
return wxString(s.c_str(), wxConvUTF8);
wxCSConv conv(wxString(enc_name.c_str(), wxConvUTF8).GetData());
return wxString(s.c_str(), conv);
#elif defined(YB_USE_QT)
if (enc_name.empty())
return QString::fromLocal8Bit(s.c_str());
QTextCodec *codec = QTextCodec::codecForName(enc_name.c_str());
return codec->toUnicode(s.c_str());
#elif defined(YB_USE_UNICODE)
std::locale loc(get_locale(enc_name).c_str());
return do_widen(s, loc);
#else
return s;
#endif
}
YBUTIL_DECL const std::string str_narrow(
const std::wstring &wide, const std::string &enc_name)
{
std::locale loc(get_locale(enc_name).c_str());
return do_narrow(wide, loc);
}
YBUTIL_DECL const std::wstring str_widen(
const std::string &narrow, const std::string &enc_name)
{
std::locale loc(get_locale(enc_name).c_str());
return do_widen(narrow, loc);
}
YBUTIL_DECL const std::string get_locale_enc()
{
std::string loc_name = get_locale();
int pos = loc_name.find('.');
if (pos != std::string::npos)
return loc_name.substr(pos + 1);
return loc_name;
}
} // namespace Yb
// vim:ts=4:sts=4:sw=4:et:
| kamaroly/yb-orm | src/util/string_type.cpp | C++ | mit | 7,838 |
<?php
/**
* Russian language file
*
* @package MajorDoMo
* @author Serge Dzheigalo <jey@tut.by> http://smartliving.ru/
* @version 1.0
*/
$dictionary = array(
/* general */
'WIKI_URL' => 'http://smartliving.ru/',
'KB_URL'=>'https://kb.smartliving.ru/',
'DEFAULT_COMPUTER_NAME' => 'Αλίκη',
'WELCOME_GREETING' => 'Καλωσόρισμα!',
'WELCOME_TEXT' => 'Σας ευχαριστούμε που χρησιμοποιήσατε το MajorDoMo, μια ανοιχτή πλατφόρμα για οικιακό αυτοματισμό. <br/><br/>Μάθετε περισσότερα και συμμετέχετε στην κοινότητα:<a href="<#LANG_WIKI_URL#>" target=_blank>Ιστοσελίδα</a> | <a href="<#LANG_WIKI_URL#>forum/" target=_blank>Φόρουμ</a> | <a href="https://www.facebook.com/SmartLivingRu" target=_blank>Σελίδα Facebook</a> <br/> <br/> <br/><small>P.S. Μπορείτε να αλλάξετε ή να διαγράψετε αυτή τη σελίδα <a href="/admin.php?pd=&md=panel&inst=&action=layouts">Πίνακας ελέγχου</a></small>',
'CONTROL_PANEL' => 'Πίνακας ελέγχου',
'TERMINAL' => 'Τερματικό',
'USER' => 'Χρήστης',
'SELECT' => 'επιλέξτε',
'CONTROL_MENU' => 'Μενού',
'YOU_ARE_HERE' => 'Είστε εδώ',
'FRONTEND' => 'Ιστοσελίδα',
'MY_ACCOUNT' => 'Ο λογαριασμός μου',
'LOGOFF' => 'Αποσυνδεθείτε',
'CONSOLE' => 'Κονσόλα',
'CONSOLE_RETRY' => 'Αναπαραγωγή',
'MODULE_DESCRIPTION' => 'Περιγραφή ενότητας',
'STILL_WORKING' => 'Φόρτωση δεδομένων ... Κάντε κλικ',
'CLICK_HERE' => 'εδώ',
'TAKES_TOO_LONG' => 'αν η διαδικασία φόρτωσης διαρκεί πολύ.',
'SUBMIT_DIAGNOSTIC'=>'Αποστολή δεδομένων διάγνωσης',
'GENERAL_SENSORS' => 'Αισθητήρες',
'GENERAL_OPERATIONAL_MODES' => 'Τρόποι λειτουργίας',
'GENERAL_ENERGY_SAVING_MODE' => 'Εξοικονόμηση ενέργειας',
'GENERAL_SECURITY_MODE' => 'Ασφάλεια',
'GENERAL_NOBODYS_HOME_MODE' => 'Κανείς δεν είναι σπίτι',
'GENERAL_WE_HAVE_GUESTS_MODE' => 'Έχουμε επισκέπτες',
'GENERAL_NIGHT_MODE' => 'Νυχτερινή λειτουργία',
'GENERAL_DARKNESS_MODE' => 'Σκοτεινή ώρα της ημέρας',
'GENERAL_CLIMATE' => 'Κλίμα',
'GENERAL_WEATHER_FORECAST' => 'Πρόγνωση καιρού',
'GENERAL_TEMPERATURE_OUTSIDE' => 'Θερμοκρασία έξω από το παράθυρο',
'GENERAL_GRAPHICS' => 'Χάρτες',
'GENERAL_SECURITY_CAMERA' => 'Κάμερες παρακολούθησης',
'GENERAL_EVENTS_LOG' => 'Ιστορία των γεγονότων',
'GENERAL_SERVICE' => 'Υπηρεσία',
'GENERAL_GREEN' => 'Πράσινο',
'GENERAL_YELLOW' => 'Κίτρινο',
'GENERAL_RED' => 'Κόκκινο',
'GENERAL_CHANGED_TO' => 'άλλαξε σε',
'GENERAL_RESTORED_TO' => 'ανακτηθεί',
'GENERAL_SYSTEM_STATE' => 'Κατάσταση συστήματος',
'GENERAL_SECURITY_STATE' => 'Κατάσταση ασφαλείας',
'GENERAL_COMMUNICATION_STATE' => 'Κατάσταση επικοινωνίας',
'GENERAL_STOPPED' => 'σταμάτησε',
'GENERAL_CYCLE' => 'κύκλου',
'GENERAL_NO_INTERNET_ACCESS' => 'Δεν υπάρχει πρόσβαση στο διαδίκτυο',
'GENERAL_SETTING_UP_LIGHTS' => 'Ρυθμίζω τον φωτισμό',
'GENERAL_CONTROL' => 'Διαχείριση',
'GENERAL_INSIDE' => 'Σπίτια',
'GENERAL_OUTSIDE' => 'Στο δρόμο',
'GENERAL_LIGHT' => 'Φως',
'GENERAL_TURNOFF_EVERYTHING' => 'Απενεργοποιήστε τα πάντα',
'GENERAL_DAYTIME' =>'Φως',
'GENERAL_NIGHTTIME' =>'Σκούρο',
'GENERAL_MESSAGES' =>'Μηνύματα',
'GENERAL_TOMORROW' =>'Αύριο',
'GENERAL_MINMAX' => 'Min / Μέγ',
'GENERAL_METERS_PER_SECOND' => 'm / s',
'GENERAL_CHART' => 'Γράφημα',
'GENERAL_ROOM_BATHROOM' => 'Μπάνιο',
'GENERAL_ROOM_LIVINGROOM' => 'Σαλόνι',
'GENERAL_ROOM_HALL' => 'Ο διάδρομος',
'GENERAL_ROOM_KITCHEN' => 'Κουζίνα',
'GENERAL_ROOM_BEDROOM' => 'Υπνοδωμάτιο',
'GENERAL_ROOM_TOILET' => 'Τουαλέτα',
'GENERAL_SYSTEM_SHUTDOWN_REBOOT' => 'Επανεκκίνηση / τερματισμός λειτουργίας',
'GENERAL_SYSTEM_SHUTDOWN_WARNING' => 'Περιμένετε 30 δευτερόλεπτα μετά την εκκίνηση της εντολής πριν απενεργοποιήσετε την τροφοδοσία.',
'GENERAL_SYSTEM_SHUTDOWN' => 'Απενεργοποιήστε το σύστημα',
'GENERAL_SYSTEM_REBOOT' => 'Επανεκκίνηση του συστήματος',
'GENERAL_STARTING' => 'την αρχή',
'GENERAL_ENDING' => 'το τέλος',
'GENERAL_CLOCKCHIME' => 'Κούκος',
'GENERAL_LANGUAGE_TIMEZONE' => 'Γλώσσα / Ζώνη ώρας',
'GENERAL_ACTIVATED' => 'ενεργοποιημένη',
'GENERAL_DEACTIVATED' => 'απενεργοποιημένο',
'GENERAL_STARTING_REBOOT' => 'Επανεκκίνηση της διαδικασίας.',
'GENERAL_STARTING_SHUTDOWN' => 'Η διαδικασία τερματισμού λειτουργίας εκτελείται..',
'GENERAL_IP_ADDRESS' => 'Διεύθυνση IP',
'GENERAL_SECURITY' => 'Ασφάλεια',
'GENERAL_RUNNING_OUT_SPACE' => 'Δεν υπάρχει αρκετός χώρος στο δίσκο',
'SECTION_OBJECTS' => 'Αντικείμενα',
'SECTION_APPLICATIONS' => 'Εφαρμογές',
'SECTION_DEVICES' => 'Συσκευές',
'SECTION_SETTINGS' => 'Ρυθμίσεις',
'SECTION_SYSTEM' => 'Συστήματος',
'SECTION_PANEL'=>'Πίνακας',
/* end general */
/* module names */
'APP_GPSTRACK' => 'GPS tracker',
'APP_PLAYER' => 'Παίκτης',
'APP_MEDIA_BROWSER' => 'Μέσα ενημέρωσης',
'APP_PRODUCTS' => 'Προϊόντα',
'APP_TDWIKI' => 'Σημειωματάριο',
'APP_WEATHER' => 'Καιρός',
'APP_CALENDAR' => 'Ημερολόγιο',
'APP_READIT' => 'Συνημμένο συνδέσεις',
'APP_QUOTES' => 'Αποσπάσματα',
'APP_ALARMCLOCK' => 'Ξυπνητήρι',
'APP_OPENWEATHER' => 'OpenWeatherMap καιρός',
'SYS_DATEFORMAT' => 'Μορφή ημερομηνίας',
'APP_YATRAFFIC' => 'Yandex.Probki',
'APP_CHATBOX' => 'Μηνύματα',
'MODULE_OBJECTS_HISTORY' => 'Ιστορικό αντικειμένων',
'MODULE_BT_DEVICES' => 'Συσκευές Bluetooth',
'MODULE_CONTROL_MENU' => 'Μενού ελέγχου',
'MODULE_OBJECTS' => 'Αντικείμενα',
'MODULE_PINGHOSTS' => 'Διαδικτυακές συσκευές',
'MODULE_SCRIPTS' => 'Σενάρια',
'MODULE_USB_DEVICES' => 'Συσκευές USB',
'MODULE_WATCHFOLDERS' => 'Φάκελοι',
'MODULE_LAYOUTS' => 'Αρχική σελίδα',
'MODULE_LOCATIONS' => 'Τοποθεσία',
'MODULE_RSS_CHANNELS' => 'Τροφοδοσίες RSS',
'MODULE_SETTINGS' => 'Γενικές ρυθμίσεις',
'MODULE_TERMINALS' => 'Τερματικά',
'MODULE_USERS' => 'Χρήστες',
'MODULE_EVENTS' => 'Εκδηλώσεις',
'MODULE_JOBS' => 'Εργασίες',
'MODULE_MASTER_LOGIN' => 'Κωδικός πρόσβασης πρόσβασης',
'MODULE_SAVERESTORE' => 'Ελέγξτε για ενημερώσεις',
'MODULE_WEBVARS' => 'Μεταβλητές ιστού',
'MODULE_PATTERNS' => 'Μοτίβα συμπεριφοράς',
'MODULE_ONEWIRE' => '1-Wire',
'MODULE_SCENES' => 'Σκηνές',
'MODULE_SNMP' => 'SNMP',
'MODULE_ZWAVE' => 'Z-Wave',
'MODULE_SECURITY_RULES' => 'Κανόνες ασφαλείας',
'MODULE_MQTT' => 'MQTT',
'MODULE_MODBUS' => 'ModBus',
'MODULE_CONNECT' => 'CONNECT',
'MODULE_MARKET' => 'Αγορά πρόσθετων',
'MODULE_MYBLOCKS' => 'Τα μπλοκ μου',
'MODULE_TEXTFILES' => 'Αρχεία κειμένου',
'MODULE_SOUNDFILES' => 'Αρχεία ήχου',
'MODULE_SYSTEM_ERRORS' => 'Σφάλματα συστήματος',
'MODULE_MODULES' => 'Ενότητες',
'MODULE_USERLOG' => 'Εγγραφή δράσης',
'SCENE_HIDDEN' => 'Μην συμπεριλάβετε τη λίστα σκηνών εναλλαγής.',
'SCENE_AUTO_SCALE' => 'Αυτόματη αλλαγή μεγέθους σκηνής για να ταιριάζει στο πλάτος οθόνης',
'SETUP' => 'Προσαρμογή',
'DATA_SAVED' => 'Τα δεδομένα αποθηκεύτηκαν!',
'ALL' => 'Όλα τα',
'EXECUTE' => 'Εκτέλεση',
'SCRIPT' => 'Σενάριο',
'CODE' => 'Κωδικός',
'CALL_PARENT_METHOD' => 'Κλήση γονικής μεθόδου',
'BEFORE_CODE_EXECUTION' => 'πριν από την εκτέλεση κώδικα',
'AFTER_CODE_EXECUTION' => 'μετά την εκτέλεση κώδικα',
'NEVER' => 'ποτέ',
'UPDATE' => 'Ανανέωση',
'CANCEL' => 'Ακύρωση',
'MAKE_COPY' => 'Δημιουργήστε ένα αντίγραφο (κλώνος)',
'ARE_YOU_SURE' => 'Είστε βέβαιοι Επιβεβαιώστε τη λειτουργία.',
'DELETE' => 'Διαγραφή',
'DELETE_SELECTED' => 'Διαγραφή επιλεγμένων',
'EXPORT_SELECTED' => 'Εξαγωγή επιλεγμένων',
'CALL_METHOD' => 'Μελέτη μεθόδου',
'BY_URL' => 'Με παραπομπή',
'COMMAND_LINE' => 'Μέσω της γραμμής εντολών',
'FILLOUT_REQURED' => 'Συμπληρώστε τα απαραίτητα πεδία!',
'NEW_OBJECT' => 'Νέο αντικείμενο',
'TITLE' => 'Όνομα',
'ALT_TITLES'=>'Συνώνυμα (διαχωρισμένα με κόμμα)',
'CLASS' => 'Κατηγορίας',
'DESCRIPTION' => 'Περιγραφή',
'LOCATION' => 'Τοποθεσία',
'ADD' => 'Για να προσθέσετε',
'BACK' => 'Πίσω',
'OBJECT' => 'Το αντικείμενο',
'DETAILS' => 'Λεπτομέρειες',
'PROPERTIES' => 'Ιδιότητες',
'METHODS' => 'Μέθοδοι',
'HISTORY' => 'Ιστορία του',
'ADD_NEW_OBJECT' => 'Προσθέστε ένα νέο αντικείμενο',
'PAGES' => 'Σελίδες',
'EDIT' => 'Για να επεξεργαστείτε',
'NO_OBJECTS_DEFINED' => 'Δεν έχουν οριστεί αντικείμενα',
'ADD_NEW_PROPERTY' => 'Προσθήκη νέας ιδιότητας',
'NEW_RECORD' => 'Νέα εγγραφή',
'PATTERN' => 'Μοτίβο',
'TIME_LIMIT' => 'Χρονικό όριο',
'SECONDS' => 'δευτερολέπτων',
'EXECUTE_ON_MATCH' => 'Τρέξτε στο αγώνα',
'SUBMIT' => 'Αποθήκευση',
'ADD_NEW_RECORD' => 'Προσθήκη νέας καταχώρησης',
'EDIT_RECORD' => 'Επεξεργασία εγγραφής',
'NO_RECORDS_FOUND' => 'Δεν υπάρχουν δεδομένα',
'COMMAND' => 'Ομάδα',
'RUN_IN' => 'Περάστε κατευθείαν',
'MINUTES' => 'λεπτά',
'HOURS' => 'το ρολόι',
'PROCESSED' => 'επεξεργασία',
'IN_QUEUE' => 'στη γραμμή',
'NEW_SCRIPT' => 'Νέο σενάριο',
'EXECUTE_SCRIPT_AFTER_UPDATE' => 'εκτέλεση μετά την αποθήκευση',
'RUN_BY_URL' => 'Εκτελέστε με παραπομπή',
'ADD_NEW_SCRIPT' => 'Προσθήκη νέας δέσμης ενεργειών',
'GENERAL_SETTINGS' => 'Γενικές ρυθμίσεις',
'SETTINGS_UPDATED' => 'Οι ρυθμίσεις αποθηκεύτηκαν!',
'DEFAULT_VALUE' => 'Προεπιλεγμένη τιμή',
'RESET_TO_DEFAULT' => 'Επαναφορά',
'SEARCH' => 'Αναζήτηση',
'USERNAME' => 'Όνομα χρήστη',
'NAME' => 'Όνομα',
'EMAIL' => 'Ηλεκτρονικό ταχυδρομείο',
'SKYPE' => 'Skype',
'MOBILE_PHONE' => 'Κινητό τηλέφωνο',
'ADD_METHOD' => 'Προσθήκη νέας μεθόδου',
'PARENT_METHODS' => 'Γονικές μέθοδοι:',
'OVERWRITE' => 'Ξαναγράψτε',
'ONLY_CLASSES' => 'Μην εισάγετε αντικείμενα',
'NEW_METHOD' => 'Νέα μέθοδος',
'HOME' => 'Ξεκινήστε',
'OFF' => 'Off',
'ON' => 'On',
'ADD_NEW_SECTION' => 'Προσθήκη νέας ενότητας',
'EXPAND' => 'Για επέκταση',
'PARENT_MENU_ITEM' => 'Στοιχείο γονικού μενού',
'PRIORITY' => 'Προτεραιότητα',
'TYPE' => 'Πληκτρολογήστε',
'LABEL' => 'Υπογραφή',
'NEW_WINDOW' => 'Νέο παράθυρο',
'URL' => 'Αναφορά',
'JS_COMMAND' => 'Javascript ομάδα',
'BUTTON' => 'Κουμπί',
'ON_OFF_SWITCH' => 'Διακόπτης',
'SELECT_BOX' => 'Πεδίο επιλογής',
'PLUS_MINUS_BOX' => 'Πλέον ή μείον',
'TIME_PICKER' => 'Χρονισμός',
'TEXT_BOX' => 'Πεδίο κειμένου',
'DATE_BOX' => 'Ημερομηνία',
'COLOR_PICKER' => 'Επιλογή χρώματος',
'CUSTOM_HTML_BOX' => 'μπλοκ HTML',
'ICON' => 'Εικονίδιο',
'MIN_VALUE' => 'Ελάχ. αξία',
'MAX_VALUE' => 'Μέγ. αξία ',
'STEP_VALUE' => 'Βήμα αλλαγής',
'DATA' => 'Δεδομένα',
'INTERFACE' => 'Διεπαφή',
'AUTO_UPDATE_PERIOD' => 'Περίοδος αυτόματης ενημέρωσης',
'POLLING_PERIOD' => 'Περίοδος δημοσκόπησης',
'CURRENT_VALUE' => 'Τρέχουσα τιμή',
'ΑΚΙΝΗΤΟ' => 'Ακίνητα',
'ONCHANGE_OBJECT' => 'Εκκίνηση αντικειμένου',
'ONCHANGE_METHOD' => 'Εκτέλεση μεθόδου αλλαγής',
'METHOD' => 'Μέθοδος',
'ONCHANGE_SCRIPT' => 'Σενάριο',
'ONCHANGE_CODE' => 'Κωδικός',
'TARGET_WINDOW' => 'Παράθυρο',
'WIDTH' => 'Πλάτος',
'HEIGHT' => 'ύψος',
'ON_THE_SAME_LEVEL' => 'Σε αυτό το επίπεδο',
'CHILD_ITEMS' => 'Παιδικά αντικείμενα',
'ADDED' => 'Προστέθηκε',
'VALUE' => 'Τιμή',
'OLD_VALUE' => 'Παλαιά αξία',
'NEW_VALUE' => 'Νέα τιμή',
'UPDATES' => 'Ενημερώσεις',
'NO_UPDATES_AVAILABLE' => 'Δεν υπάρχουν διαθέσιμες ενημερώσεις',
'NEW_VERSION' => 'Νέα έκδοση',
'INSTALL_NEW_MODULES' => 'Εγκατάσταση νέων ενοτήτων',
'NO_MODULES_AVAILABLE' => 'Δεν υπάρχουν διαθέσιμες ενότητες',
'GET_LIST_OF_MODULES' => 'Αποκτήστε τη λίστα των ενοτήτων',
'SUBMIT_NEWER_FILES' => 'Αποστολή νέων αρχείων',
'NO_FILES_TO_SUBMIT' => 'Δεν υπάρχουν αρχεία για αποστολή',
'FOLDER' => 'Φάκελος',
'YOUR_NAME' => 'Το όνομά σας',
'YOUR_EMAIL' => 'Το ηλεκτρονικό ταχυδρομείο σας',
'NOTES' => 'Σημειώσεις',
'SUBMIT_SELECTED_FILES' => 'Αποστολή επιλεγμένων αρχείων',
'CHECK_FILES_FOR_SUBMIT' => 'Επιλογή αρχείων για αποστολή',
'DESIGN' => 'Σχεδιασμός',
'FILES_UPLOADED' => 'Ανέβασμα αρχείων',
'CLEAR_TEMPORARY_FOLDER' => 'Καθαρισμός προσωρινού φακέλου',
'ADD_NEW_CLASS' => 'Προσθήκη νέας κλάσης',
'OBJECTS' => 'Αντικείμενα',
'EXPORT' => 'Εξαγωγή',
'EXPORT_CLASS_FULL' => 'Εξαγωγή κατηγορίας και αντικειμένων',
'EXPORT_CLASS_NO_OBJECTS' => 'Κλάση εξαγωγής (χωρίς αντικείμενα)',
'IMPORT_CLASS_FROM_FILE' => 'Κλάση εισαγωγής από αρχείο',
'IMPORT' => 'Εισαγωγή',
'NEW_CLASS' => 'Νέα τάξη',
'PARENT_CLASS' => 'Η τάξη των γονέων',
'DO_NOT_SAVE_CLASS_ACTIVITY' => 'δεν αποθηκεύει τη δραστηριότητα των αντικειμένων κλάσης στο αρχείο καταγραφής',
'MAIN' => 'Κύρια',
'STRING_BACK' => 'Επιστροφή',
'STRING_SUCCESS' => 'Τα δεδομένα έχουν αποθηκευτεί!',
'STRING_ERROR' => 'Σφάλμα',
'STRING_NEW_RECORD' => 'Νέα δημοσίευση',
'SHOUTROOMS_TITLE' => 'Όνομα',
'SHOUTROOMS_PRIORITY' => 'Προτεραιότητα',
'FORM_SUBMIT' => 'Αποθήκευση',
'FORM_ADD' => 'Προσθήκη',
'FORM_CANCEL' => 'Ακύρωση',
'STRING_ADD_NEW' => 'Προσθήκη',
'SHOUTROOMS_STRING_PUBLIC' => 'Άνοιγμα',
'SHOUTROOMS_STRING_PRIVATE' => 'Ιδιωτικός',
'STRING_EDIT' => 'Επεξεργασία',
'STRING_DELETE' => 'Διαγραφή',
'STRING_NOT_FOUND' => 'Δεν βρέθηκε',
'SHOUTROOMS_STRING_SHOUTROOMS' => 'ShoutRooms',
'NEW_LOCATION' => 'Νέα τοποθεσία',
'ADD_NEW_LOCATION' => 'Προσθήκη νέας τοποθεσίας',
'LOADING' => 'Φόρτωση ...',
'PLEASE_LOGIN' => 'Παρακαλώ συνδεθείτε.',
'SEND' => 'Αποστολή',
'SHOUTBOX_STRING_DELETE_ALL' => 'Διαγραφή όλων',
'STRING_PAGES' => 'Σελίδες',
'MEMBERS_MEMBER' => 'Χρήστης',
'SHOUTBOX_MESSAGE' => 'Μήνυμα',
'SHOUTBOX_ADDED' => 'Προστέθηκε',
'STRING_DELETE_CONFIRM' => 'Είστε σίγουροι;',
'DELETE_UNKNOWN_DEVICES' => 'Διαγραφή άγνωστων συσκευών',
'SERIAL' => 'Αύξων αριθμός',
'FIRST_ATTACHED' => 'First Connected',
'LAST_ATTACHED' => 'Τελευταία σύνδεση',
'EXECUTE_ON_ATTACH' => 'Εκτέλεση στη σύνδεση',
'HOSTNAME' => 'Υποδοχή (διεύθυνση)',
'SEARCH_WORD' => 'Αναζήτηση για μια λέξη',
'ONLINE_ACTION' => 'Δράση στο online',
'OFFLINE_ACTION' => 'Δράση σε εξέλιξη εκτός σύνδεσης',
'ONLINE_CHECK_INTERVAL' => 'Έλεγχος διαστήματος (όταν είναι online)',
'OFFLINE_CHECK_INTERVAL' => 'Έλεγχος διαστήματος (όταν είναι εκτός σύνδεσης)',
'LOG' => 'Καταγραφή συμβάντων',
'ADD_NEW_HOST' => 'Προσθήκη νέου κεντρικού υπολογιστή',
'ONLINE' => 'Online',
'OFFLINE' => 'Εκτός σύνδεσης',
'UNKNOWN' => 'Άγνωστο',
'DELETE_ALL_UNKNOWN_DEVICES' => 'Διαγραφή όλων των άγνωστων συσκευών',
'DELETE_FOUND_ONCE' => 'Διαγραφή όλων των συσκευών που βρέθηκαν μόνο μία φορά',
'FOUND_FIRST' => 'Ανακαλύφθηκε για πρώτη φορά',
'FOUND_LAST' => 'Τέλος βρέθηκε',
'PAST_DUE' => 'Απούσα',
'TODAY' => 'Σήμερα',
'NOTHING_TO_DO' => 'Δεν υπάρχει τίποτα να κάνει ... Είναι τυχερός!',
'SOON' => 'Σύντομα',
'DONE_RECENTLY' => 'Πρόσφατα Έγινε',
'PREVIEW' => 'Προβολή',
'SYSTEM_NAME' => 'Όνομα συστήματος',
'EVENT' => 'Εκδήλωση',
'TASK' => 'Task',
'DONE' => 'Έγινε',
'DATE' => 'Ημερομηνία',
'DUE_DATE' => 'χωρίς συγκεκριμένη ημερομηνία',
'IS_REPEATING' => 'επαναλαμβανόμενο',
'ΕΤΗΣΙΑ' => 'Ετησίως',
'ΜΗΝΙΑΙΑ' => 'Μηνιαία',
'WEEKLY' => 'Εβδομαδιαία',
'OTHER' => 'Άλλο',
'RESTORE_IN' => 'Επαναφορά μέσω',
'IN_DAYS' => 'ημέρες',
'AFTER_COMPLETION' => 'μετά την εκτέλεση',
'MORE_DETAILS' => 'Λεπτομέρειες',
'ANY_USER' => 'Οποιοσδήποτε χρήστης',
'ANY_LOCATION' => 'Οποιαδήποτε τοποθεσία',
'RUN_SCRIPT' => 'Εκτέλεση σεναρίου',
'WHEN_TASK_WILL_BE_DONE' => 'όταν ολοκληρωθεί η εργασία',
'SIMILAR_ITEMS' => 'Σχετικές καταχωρήσεις',
'LOCATION_CODE' => 'Κωδικός της πόλης (αναγνωριστικό πόλης)',
'REFRESH' => 'Ανανέωση',
'ERROR_GETTING_WEATHER_DATA' => 'Σφάλμα κατά τη λήψη δεδομένων καιρού',
'CLEAR_ALL' => 'Διαγραφή όλων',
'ADD_NEW_CHANNEL' => 'Προσθήκη νέου καναλιού',
'LAST_CHECKED' => 'Τελευταίος έλεγχος',
'RSS_CHANNELS' => 'Τροφοδοσίες RSS',
'RSS_NEWS' => 'Τροφοδοσίες RSS',
'NEW_CHANNEL' => 'Νέο κανάλι',
'SOURCE_URL' => 'Πηγή URL',
'CHECK_EVERY' => 'Ελέγξτε κάθε',
'EXECUTE_FOR_NEW_RECORDS' => 'Εκτέλεση νέων καταχωρήσεων',
'TERMINAL_FROM' => 'Από το τερματικό',
'USER_FROM' => 'Από το χρήστη',
'USER_TO' => 'Για τον χρήστη',
'WINDOW' => 'Παράθυρο',
'EXPIRE' => 'Λήγει',
'TERMINAL_TO' => 'Στο τερματικό',
'NEW_PAGE' => 'Νέα σελίδα',
'APP' => 'Εφαρμογή',
'QUANTITY' => 'Ποσότητα',
'ACTION' => 'Δράση',
'ΚΑΤΗΓΟΡΙΑ' => 'Κατηγορία',
'ADD_NEW_CATEGORY' => 'Προσθήκη κατηγορίας',
'PRODUCT' => 'Προϊόν',
'DELETE_CATEGORY' => 'Διαγραφή κατηγορίας',
'MISSING' => 'Λείπει',
'IN_STORAGE' => 'Διαθέσιμο',
'BUY' => 'Αγορά',
'CODES' => 'Κωδικοί',
'PARENT' => 'γονέας',
'ROOT' => '(root)',
'CREATE_NOTE' => 'Δημιουργία σημείωσης',
'TOTAL' => 'Σύνολο',
'EXPIRE_IN' => 'Λήγει στο',
'DAYS' => 'ημέρες',
'CATEGORIES' => 'Κατηγορίες',
'ALL_PRODUCTS' => 'Όλα τα προϊόντα',
'EXPIRED' => 'Έληξε',
'SHOPPING_LIST' => 'Αγορές',
'PRODUCTS' => 'Προϊόντα',
'IMAGE' => 'Εικόνα',
'EXPIRATION_DATE' => 'Ημερομηνία λήξης',
'DEFAULT_EXPIRE_IN' => 'Από προεπιλογή λήγει μετά το ',
'UPDATED' => 'Ενημερώθηκε',
'RECOMENDED_QUANTITY' => 'Συνιστώμενη ποσότητα',
'DELETE_FROM_DATABASE' => 'Διαγραφή από βάση δεδομένων',
'RESCAN_DEVICES' => 'Συσκευές σάρωσης',
'NO_DEVICES_FOUND' => 'Δεν υπάρχουν συσκευές',
'Id' => 'id',
'CHECK_INTERVAL' => 'Έλεγχος διαστήματος',
'LINKED_OBJECT' => 'Σχετικό αντικείμενο',
'LINKED_PROPERTY' => 'Συνδεδεμένη ιδιότητα',
'SET' => 'set',
'ONCHANGE_ACTION' => 'Δράση για Αλλαγή',
'RESET' => 'Επαναφορά',
'MORE_INFO' => 'Λεπτομέρειες',
'PATH' => 'Διαδρομή',
'INCLUDE_SUBFOLDERS' => 'συμπεριλαμβανομένων των υποφακέλων',
'CHECK_MASK' => 'Μάσκα αρχείων',
'ΠΑΡΑΔΕΙΓΜΑ' => 'Παράδειγμα',
'AUTHORIZATION_REQUIRED' => 'απαιτείται άδεια',
'PASSWORD' => 'Κωδικός πρόσβασης',
'SOURCE_PAGE_ENCODING' => 'Κωδικοποίηση σελίδας',
'OPTIONAL' => 'προαιρετικό',
'BY_DEFAULT' => 'από προεπιλογή',
'SEARCH_PATTERN' => 'Πρότυπο αναζήτησης',
'LATEST_VALUE' => 'Τελευταία τιμή',
'ADD_NEW' => 'Προσθήκη',
'REFRESH_ALL' => 'Ανανέωση όλων',
'NEW_PROPERTY' => 'Νέα ιδιοκτησία',
'KEEP_HISTORY_DAYS' => 'Διατήρηση ιστορικού (ημέρες)',
'DO_NOT_KEEP' => 'Μην αποθηκεύετε ιστορικό',
'KEEP_HISTORY' => 'ιστορικό καταστήματος',
'PARENT_PROPERTIES' => 'Γονικές ιδιότητες',
'ADD_NEW_COLLECTION' => 'Προσθήκη νέας συλλογής',
'NEW_SKIN_INSTALLED' => 'Εγκατάσταση νέου δέρματος',
'INCORRECT_FILE_FORMAT' => 'Μη έγκυρη μορφή αρχείου',
'CANNOT_CREATE_FOLDER' => 'Δεν μπορώ να δημιουργήσω φάκελο',
'SKIN_ALREADY_EXISTS' => 'Το δέρμα υπάρχει ήδη',
'UPLOAD_NEW_SKIN' => 'Φόρτωση νέου δέρματος',
'INSTALL_SKIN' => 'Εγκατάσταση δέρματος',
'NO_ADDITIONAL_SKINS_INSTALLED' => 'Χωρίς πρόσθετο δέρμα',
'BACKGROUND' => 'Εικόνα φόντου',
'SCENE' => 'Σκηνή',
'ADD_NEW_SCENE' => 'Προσθήκη νέας σκηνής',
'USE_ELEMENT_TO_POSITION_RELATED' => 'Θέση σχετικά',
'NO_RELATED' => 'Αριστερά άνω γωνία',
'TOP' => 'Κορυφή Πίσω',
'LEFT' => 'Εσοχή αριστερά',
'ΚΡΑΤΗ' => 'κράτη',
'ADD_NEW_STATE' => 'Προσθήκη νέου κράτους',
'RUN_SCRIPT_ON_CLICK' => 'Εκτέλεση σεναρίου σε κλικ',
'SHOW_MENU_ON_CLICK' => 'Εμφάνιση μενού όταν κάνετε κλικ',
'SHOW_HOMEPAGE_ON_CLICK' => 'Εμφάνιση αρχικής σελίδας με κλικ',
'SHOW_URL_ON_CLICK' => 'Άνοιγμα συνδέσμου όταν πατήσετε',
'SHOW_SCENE_ON_CLICK' => 'Εμφάνιση άλλης σκηνής',
'DISPLAY_CONDITION' => 'Προϋπόθεση προβολής',
'ALWAYS_VISIBLE' => 'πάντα εμφάνιση',
'SIMPLE' => 'απλό',
'ADVANCED' => 'επέκταση',
'SWITCH_SCENE_WHEN_ACTIVATED' => 'μεταβείτε στο στάδιο όταν ενεργοποιηθεί',
'APPEAR_ANIMATION' => 'Φαντασία εμφάνισης',
'APPEAR_LEFTTORIGHT' => 'Από αριστερά προς δεξιά',
'APPEAR_RIGHTTOLEFT' => 'Από δεξιά προς τα αριστερά',
'APPEAR_TOPTOBOTTOM' => 'Top-Down',
'APPEAR_BOTTOMTOTOP' => 'Από κάτω προς τα πάνω',
'APPEAR_BLINK' => 'Αναβοσβήνει',
'APPEAR_SCALE' => 'Κλίμακα',
'ADD_NEW_ELEMENT' => 'Προσθήκη νέου στοιχείου',
'ELEMENTS' => 'Στοιχεία',
'CAN_PLAY_MEDIA' => 'μπορεί να αναπαράγει περιεχόμενο πολυμέσων',
'PLAYER_TYPE' => 'Τύπος παίκτη',
'DEFAULT' => 'Προεπιλογή',
'MAKE_SURE_YOU_HAVE_CONTROL_OVER_HTTP_ENABLED' => 'Ελέγξτε ότι ο έλεγχος του πρωτοκόλλου HTTP είναι ενεργοποιημένος',
'PLAYER_PORT' => 'Θύρα Πρόσβασης Παίκτη',
'PLAYER_USERNAME' => 'Όνομα χρήστη για πρόσβαση στη συσκευή αναπαραγωγής',
'PLAYER_PASSWORD' => 'Κωδικός πρόσβασης για πρόσβαση στη συσκευή αναπαραγωγής',
'DEVICE' => 'Συσκευή',
'CLEAR_LOG' => 'Διαγραφή αρχείου καταγραφής',
'OPTIMIZE_LOG' => 'Βελτιστοποίηση αρχείου καταγραφής',
'LATITUDE' => 'Γεωγραφικό πλάτος',
'LONGITUDE' => 'Γεωγραφικό μήκος',
'SPEED' => 'Ταχύτητα',
'ΑΚΡΙΒΕΙΑ' => 'Ακρίβεια',
'BATTERY_LEVEL' => 'Επίπεδο χρέωσης',
'CHARGING' => 'On Charging',
'MAP' => 'Χάρτης',
'RANGE' => 'Εύρος',
'ALTITUDE' => 'ύψος',
'PROVIDER' => 'Παροχέας',
'LOCATIONS' => 'Χώροι',
'DEVICES' => 'Συσκευές',
'ΔΡΑΣΕΙΣ' => 'Ενέργειες',
'HOME_LOCATION' => 'Σπίτι (τόπος)',
'ACTION_TYPE' => 'Τύπος ενέργειας',
'EXECUTED' => 'Έγινε',
'VIRTUAL_USER' => 'Εικονικός χρήστης',
'WIND' => 'Αέρας',
'PRESSURE' => 'Πίεση',
'HUMIDITY' => 'Υγρασία',
'GET_AT' => 'Ενημερώθηκε',
'MMHG' => 'mmHg',
'HPA' => 'hPa',
'M_S' => 'm / s',
'Ν' => 'c',
'NNE' => 'CER',
'NE' => 'SV',
'ENE' => 'ENE',
'Ε' => 'Β',
'ESE' => 'WYV',
'SE' => 'SE',
'SSE' => 'SEW',
'S' => 'u',
'SSW' => 'UYUZ',
'SW' => 'SW',
'WSW' => 'ZYUZ',
'W' => 'W',
'WNW' => 'CSV',
'NW' => 'CZ',
'NNW' => 'CCZ',
'LONG_OPERATION_WARNING' => 'Προειδοποίηση: Η λειτουργία αυτή μπορεί να διαρκέσει πολύ (μερικά λεπτά). Περιμένετε μέχρι να ολοκληρωθεί μετά την εκκίνηση. ',
'STARRED' => 'Αγαπημένα',
'USE_BACKGROUND' => 'Χρήση φόντου',
'ΝΑΙ' => 'Ναι',
'ΟΧΙ' => 'Κανένα',
'USE_JAVASCRIPT' => 'Πρόσθετος κώδικας JavaScript',
'USE_CSS' => 'Πρόσθετος κωδικός CSS',
'PERIOD' => 'Περίοδος',
'PERIOD_TODAY' => 'Σήμερα',
'PERIOD_DAY' => 'Ημέρα (24 ώρες)',
'PERIOD_WEEK' => 'Εβδομάδα',
'PERIOD_MONTH' => 'Μήνας',
'PERIOD_CUSTOM' => 'Επιλογή',
'ΑΝΑΖΗΤΗΣΗ' => 'Αναζήτηση',
'SHOWHIDE' => 'Εμφάνιση / Απόκρυψη',
'AUTO_UPDATE' => 'Αυτόματη ενημέρωση',
'CHANNEL' => 'Κανάλι',
'ADD_URL' => 'Προσθήκη URL',
'OPEN' => 'Άνοιγμα',
'SEND_TO_HOME' => 'Απεσταλμένα σπίτι ',
'EXT_ID' => 'Χρήση στοιχείου',
'VISIBLE_DELAY' => 'Καθυστέρηση κατά την περιστροφή',
'TREE_VIEW' => 'Ως δέντρο',
'LIST_VIEW' => 'Σε προβολή λίστας',
'FILTER_BY_CLASS' => 'Φίλτρο ανά τάξη',
'FILTER_BY_LOCATION' => 'Φίλτρο τοποθεσίας',
'PHOTO' => 'Φωτογραφία',
'DEFAULT_USER' => 'προεπιλεγμένος χρήστης για το σύστημα',
'IS_ADMIN' => 'διαχειριστής συστήματος',
'COUNTER_REQUIRED' => 'Αριθμός επαναλήψεων',
'COUNTER_REQUIRED_COMMENT' => '(0 για την αλλαγή της πρώτης ώρας)',
'ACCESS_CONTROL' => 'Έλεγχος πρόσβασης',
'SECURITY_OBJECT_ID' => 'Αντικείμενο Προστασίας',
'SECURITY_TERMINALS' => 'Πρόσβαση από τερματικούς σταθμούς',
'SECURITY_USERS' => 'Διαθέσιμο στους χρήστες',
'SECURITY_TIMES' => 'Διαθέσιμο σε ώρες',
'ALLOW_EXCEPT_ABOVE' => 'είναι πάντα διαθέσιμη εκτός από την επιλεγμένη',
'INLINE_POSITION' => 'Θέση στο επίπεδο του προηγούμενου στοιχείου',
'SUB_PRELOAD' => 'Φόρτωση στοιχείων παιδιού στην αναπτυσσόμενη περιοχή',
'RUN_PERIODICALLY' => 'Εκτέλεση περιοδικά',
'RUN_TIME' => 'Χρόνος έναρξης',
'RUN_WEEKDAYS' => 'Ημέρες της εβδομάδας',
'WEEK_SUN' => 'Κυριακή',
'WEEK_MON' => 'Δευτέρα',
'WEEK_TUE' => 'Τρίτη',
'WEEK_WED' => 'Περιβάλλον',
'WEEK_THU' => 'Πέμπτη',
'WEEK_FRI' => 'Παρασκευή',
'WEEK_SAT' => 'Σάββατο',
'PARENT_CONTEXT' => 'Διαθέσιμο στο πλαίσιο',
'IS_CONTEXT' => 'χρήση ως πλαίσιο',
'TIMEOUT' => 'Χρόνος ομάδας',
'SET_CONTEXT_TIMEOUT' => 'Μετά το πέρας του χρόνου, μεταβείτε στο',
'TIMEOUT_CODE' => 'Μετά την εκτέλεση του χρόνου',
'GLOBAL_CONTEXT' => 'παγκόσμιο πλαίσιο',
'LAST_RULE' => 'Μην ελέγχετε άλλα μοτίβα με έναν αγώνα',
'SETTINGS_SECTION_' => 'Γενικά',
'SETTINGS_SECTION_HOOK' => 'Χειριστές',
'DEVICE_ID' => 'Αναγνωριστικό συσκευής',
'REQUEST_TYPE' => 'Τύπος αιτήματος',
'REQUEST_START' => 'Διεύθυνση εκκίνησης',
'REQUEST_TOTAL' => 'Αριθμός στοιχείων',
'RESPONSE_CONVERT' => 'Μετασχηματισμός δεδομένων',
'CHECK_NEXT' => 'Επόμενος έλεγχος',
'CODE_TYPE' => 'Χρήση για προγραμματισμό',
'GENERAL' => 'Γενικά',
'TIME' => 'Χρόνος',
'LOGIC' => 'Λογική',
'LOOPS' => 'Loops',
'MATH' => 'Μαθηματικά',
'TEXT' => 'Κείμενο',
'LISTS' => 'Λίστες',
'ΜΕΤΑΒΛΗΤΕΣ' => 'Μεταβλητές',
'FUNCTIONS' => 'Λειτουργίες',
'DO_NOTHING' => 'Μην κάνετε τίποτα',
'DO_ONCLICK' => 'Εκτέλεση με κλικ',
'STYLE' => 'Στυλ',
'PLACE_IN_CONTAINER' => 'Τακτοποιήστε σε ένα κοντέινερ',
'POSITION_TYPE' => 'Τοποθέτηση',
'POSITION_TYPE_ABSOLUTE' => 'Απόλυτο',
'POSITION_TYPE_SIDE' => 'Ένα μετά το άλλο',
'CONTAINER' => 'Δοχείο',
'INFORMER' => 'Πληροφόρηση',
'NAV_LINK' => 'Nav. σύνδεσμος (νέο παράθυρο) ',
'WARNING' => 'Ανακοίνωση',
'NAV_LINK_GO' => 'Nav. σύνδεσμος (μετάβαση) ',
'TOOLS' => 'Εργαλεία',
'COLOR' => 'Χρώμα',
'WALLPAPER' => 'Ταπετσαρίες',
'ADDITIONAL_STATES' => 'Πρόσθετες καταστάσεις',
'MODE_SWITCH' => 'Ένδειξη λειτουργίας',
'HIGH_ABOVE' => 'Η τιμή είναι υψηλότερη',
'LOW_BELOW' => 'Η τιμή είναι χαμηλότερη',
'ADDITIONAL_STATES_NOTE' => '(μπορείτε να χρησιμοποιήσετε το% object.property% construct ως οριακές τιμές)',
'UNIT' => 'Μονάδα μέτρησης',
'COUNTER' => 'Μετρητής',
'USE_CLASS_SETTINGS' => 'Χρήση ρυθμίσεων ιδιότητας κλάσης',
'USING_LATEST_VERSION' => 'Χρησιμοποιείτε την τελευταία έκδοση!',
'LATEST_UPDATES' => 'Τελευταίες ενημερώσεις',
'UPDATE_TO_THE_LATEST' => 'Αναβάθμιση του συστήματος',
'SAVE_BACKUP' => 'Δημιουργία αντιγράφων ασφαλείας',
'CREATE_BACKUP' => 'Δημιουργία αντιγράφων ασφαλείας',
'UPLOAD_BACKUP' => 'Επαναφορά αντιγράφων ασφαλείας',
'CONTINUE' => 'Συνέχεια',
'RESTORE' => 'Επαναφορά',
'SHOW' => 'Εμφάνιση',
'HIDE' => 'Απόκρυψη',
'UPDATING' => 'Ενεργοποίηση στην ενημέρωση ',
'NOT_UPDATING' => 'Δεν ενημερώθηκε',
'SCRIPTS' => 'Σενάρια',
'CLASSES' => 'Μαθήματα / Αντικείμενα',
'CLASS_PROPERTIES' => 'Ιδιότητες κλάσης',
'CLASS_METHODS' => 'Μέθοδοι κλάσης',
'CLASS_OBJECTS' => 'Αντικείμενα κλάσης',
'OBJECT_PROPERTIES' => 'Ιδιότητες αντικειμένου',
'OBJECT_METHODS' => 'Μέθοδοι αντικειμένου',
'PORT' => 'Λιμάνι',
'USE_DEFAULT' => 'Χρήση προεπιλογής',
'FAVORITES' => 'Αγαπημένα',
'RECENTLY_PLAYED' => 'Πρόσφατα αναπαραχθεί',
'CLEAR_FAVORITES' => 'Εκκαθάριση Αγαπημένων',
'CLEAR_HISTORY' => 'Διαγραφή πρόσφατα χαμένος',
'SKIP_SYSTEM' => 'Μην απαντάτε στα μηνύματα συστήματος',
'ONETIME_PATTERN' => 'Μία φορά (να διαγραφεί)',
'PATTERN_ENTER' => 'είσοδος',
'PATTERN_EXIT' => 'έξοδος',
'PATTERN_TYPE' => 'Τύπος προτύπου',
'PATTERN_MESSAGE' => 'Με βάση τα μηνύματα',
'PATTERN_CONDITIONAL' => 'Με βάση τις τιμές ιδιοκτησίας',
'CONDITION' => 'Condition',
'ADD_EXIT_CODE' => 'Προσθήκη κωδικού εξόδου',
'SMART_REPEAT' => 'Αυτόματη επανάληψη',
'READ_ONLY' => 'Μόνο για ανάγνωση',
'ADVANCED_CONFIG' => 'Σύνθετη ρύθμιση',
'UPDATE_ALL_EXTENSIONS' => 'Ενημέρωση όλων των εγκατεστημένων πρόσθετων',
'SAVE_CHANGES' => 'Αποθήκευση αλλαγών',
'ADD_PANE' => 'Προσθήκη πλαισίου',
'DATA_KEY' => 'Βασικά δεδομένα',
'DATA_TYPE' => 'Τύπος δεδομένων',
'DATA_TYPE_GENERAL' => 'Κοινή μορφή',
'DATA_TYPE_IMAGE' => 'Εικόνα',
'CLASS_TEMPLATE' => 'Πρότυπο εμφάνισης',
'TEST' => 'δοκιμή',
'MODULES_UPDATES_AVAILABLE' => 'Οι ενημερώσεις ενότητας είναι διαθέσιμες',
'SYSTEM_UPDATES_AVAILABLE' => 'Οι ενημερώσεις συστήματος είναι διαθέσιμες',
'ERRORS_SAVED' => 'Αποθηκευμένα σφάλματα',
// DEVICES
'DEVICES_MODULE_TITLE' => 'Απλές συσκευές',
'DEVICES_LINKED_WARNING' => 'Προειδοποίηση: η επιλογή ενός υπάρχοντος αντικειμένου θα οδηγήσει στη σύνδεση του σε μια νέα κλάση.',
'DEVICES_RELAY' => 'Ελεγχόμενη ρελέ / διακόπτης',
'DEVICES_DIMMER' => 'Έλεγχος φωτισμού',
'DEVICES_RGB' => 'Ελεγκτής RGB',
'DEVICES_MOTION' => 'Αισθητήρας κίνησης',
'DEVICES_BUTTON' => 'Κουμπί',
'DEVICES_SWITCH' => 'Διακόπτης',
'DEVICES_OPENCLOSE' => 'Άνοιγμα / κλείσιμο αισθητήρα',
'DEVICES_GENERAL_SENSOR' => 'Κοινός αισθητήρας',
'DEVICES_TEMP_SENSOR' => 'Αισθητήρας θερμοκρασίας',
'DEVICES_HUM_SENSOR' => 'Αισθητήρας υγρασίας',
'DEVICES_STATE_SENSOR' => 'Αισθητήρας κατάστασης',
'DEVICES_PERCENTAGE_SENSOR' => 'Ποσοστό αισθητήρων',
'DEVICES_PRESSURE_SENSOR' => 'αισθητήρας ατμοσφαιρικής πίεσης',
'DEVICES_POWER_SENSOR' => 'Αισθητήρας ισχύος',
'DEVICES_VOLTAGE_SENSOR' => 'Αισθητήρας τάσης',
'DEVICES_CURRENT_SENSOR' => 'Αισθητήρας ρεύματος',
'DEVICES_LIGHT_SENSOR' => 'Αισθητήρας φωτός',
'DEVICES_LEAK_SENSOR' => 'αισθητήρας διαρροής',
'DEVICES_SMOKE_SENSOR' => 'Ανιχνευτής καπνού',
'DEVICES_COUNTER' => 'Μετρητής',
'DEVICES_UNIT' => 'Μονάδα μέτρησης',
'DEVICES_BATTERY_LOW' =>'Χαμηλή μπαταρία',
'M_VOLTAGE'=>'Β',
'M_CURRENT' => 'Α',
'M_PRESSURE' => 'Torr',
'M_WATT' => 'W',
// ----
'DEVICES_LINKS' => 'Συνδεδεμένες συσκευές',
'DEVICES_STATUS' => 'Κατάσταση',
'DEVICES_LOGIC_ACTION' => 'Ενέργειες',
'DEVICES_CURRENT_VALUE' => 'Τρέχουσα τιμή',
'DEVICES_CURRENT_HUMIDITY' => 'Υγρασία',
'DEVICES_CURRENT_TEMPERATURE' => 'Θερμοκρασία',
'DEVICES_MIN_VALUE' => 'Κάτω όριο',
'DEVICES_MAX_VALUE' => 'Υψηλό όριο',
'DEVICES_NOTIFY' => 'Ειδοποιήστε όταν υπερβαίνετε το όριο',
'DEVICES_NORMAL_VALUE' => 'Η τιμή είναι εντός των κανονικών ορίων',
'DEVICES_DIRECTION_TIMEOUT' => 'Χρονικό διάστημα για τον υπολογισμό της κατεύθυνσης αλλαγών (sec)',
'DEVICES_NOTIFY_STATUS' => 'Ειδοποίηση κατά την αλλαγή της κατάστασης',
'DEVICES_NOTIFY_OUTOFRANGE' => 'Τιμή αισθητήρα εκτός ορίου',
'DEVICES_NOTIFY_BACKTONORMAL' => 'Η τιμή του αισθητήρα επέστρεψε στο κανονικό',
'DEVICES_NOTIFY_NOT_CLOSED' => 'Υπενθύμιση για την ανοιχτή κατάσταση',
'DEVICES_MOTION_IGNORE' => 'Παράβλεψη συμβάντων από τη συσκευή όταν κανείς δεν είναι στο σπίτι',
'DEVICES_MOTION_TIMEOUT' => 'Χρόνος δραστηριότητας (δευτερόλεπτα)',
'DEVICES_ALIVE_TIMEOUT' => 'Επιτρεπτός χρόνος για δεδομένα που λείπουν (ώρες)',
'DEVICES_MAIN_SENSOR' => 'Κύριος αισθητήρας δωματίου',
'DEVICES_NOT_UPDATING' => 'δεν ενημερώθηκε',
'DEVICES_IS_ON' => 'Ενεργοποιημένο',
'DEVICES_IS_CLOSED' => 'Κλειστό',
'DEVICES_MOTION_DETECTED' => 'Εντοπίστηκε',
'DEVICES_PRESS' => 'Κάντε κλικ',
'DEVICES_TURN_ON' => 'Ενεργοποίηση',
'DEVICES_TURN_OFF' => 'Απενεργοποίηση',
'DEVICES_SET_COLOR' => 'Ορισμός χρώματος',
'DEVICES_GROUP_ECO' => 'Απενεργοποίηση σε λειτουργία οικονομίας',
'DEVICES_GROUP_ECO_ON' => 'Ενεργοποίηση κατά την έξοδο από τη λειτουργία οικονομίας',
'DEVICES_GROUP_SUNRISE' => 'Απενεργοποίηση την αυγή',
'DEVICES_IS_ACTIVITY' => 'Αλλαγή σημαίνει εσωτερική δραστηριότητα',
'DEVICES_NCNO' => 'Τύπος συσκευής / αισθητήρα',
'DEVICES_LOADTYPE' => 'Τύπος συσκευής',
'DEVICES_LOADTYPE_VENT' => 'Εξαερισμός',
'DEVICES_LOADTYPE_HEATING' => 'Θέρμανση',
'DEVICES_LOADTYPE_CURTAINS' => 'Κουρτίνες',
'DEVICES_LOADTYPE_GATES' => 'Πύλη',
'DEVICES_LOADTYPE_LIGHT' => 'Φωτισμός',
'DEVICES_LOADTYPE_LIGHT_ALT' => 'Φως',
'DEVICES_LOADTYPE_POWER' => 'Διάφορα',
'DEVICES_ADD_MENU' => 'Προσθήκη συσκευής στο μενού',
'DEVICES_ADD_SCENE' => 'Προσθήκη συσκευής στο στάδιο',
'DEVICES_LINKS_NOT_ADDED' => 'Δεν υπάρχουν συνδεδεμένες συσκευές',
'DEVICES_LINKS_AVAILABLE' => 'Διαθέσιμοι τύποι σύνδεσης',
'DEVICES_LINKS_COMMENT' => 'Σχόλιο (προαιρετικό)',
'DEVICES_LINKS_LINKED_DEVICE' => 'Συνδεδεμένη συσκευή',
'DEVICES_LINKS_ADDED' => 'Συνδεδεμένες συσκευές',
'DEVICES_LINK_ACTION_TYPE' => 'Δράση',
'DEVICES_LINK_TYPE_TURN_ON' => 'Ενεργοποίηση',
'DEVICES_LINK_TYPE_TURN_OFF' => 'Απενεργοποίηση',
'DEVICES_LINK_TYPE_SWITCH' => 'Εναλλαγή',
'DEVICES_LINK_SWITCH_IT' => 'Ενεργοποίηση / Απενεργοποίηση',
'DEVICES_LINK_SWITCH_IT_DESCRIPTION' => 'Διαχείριση άλλης συσκευής σε ένα συμβάν',
'DEVICES_LINK_SWITCH_IT_PARAM_ACTION_DELAY' => 'Διάρκεια εκτέλεσης (δευτερόλεπτα)',
'DEVICES_LINK_SET_COLOR' => 'Ορισμός χρώματος',
'DEVICES_LINK_SET_COLOR_DESCRIPTION' => 'Ορισμός χρώματος ανά συμβάν',
'DEVICES_LINK_SET_COLOR_PARAM_ACTION_COLOR' => 'Χρώμα',
'DEVICES_LINK_SENSOR_SWITCH' => 'Υπό όρους έλεγχος',
'DEVICES_LINK_SENSOR_SWITCH_DESCRIPTION' => 'Έλεγχος άλλης συσκευής με ανάγνωση αισθητήρα',
'DEVICES_LINK_SENSOR_SWITCH_PARAM_CONDITION' => 'Τύπος κατάστασης',
'DEVICES_LINK_SENSOR_SWITCH_PARAM_CONDITION_ABOVE' => 'Πάνω Σετ',
'DEVICES_LINK_SENSOR_SWITCH_PARAM_CONDITION_BELOW' => 'Κάτω από αυτό',
'DEVICES_LINK_SENSOR_SWITCH_PARAM_VALUE' => 'Τιμή κατωφλίου',
'DEVICES_LINK_SENSOR_PASS' => 'Μεταφορά δεδομένων',
'DEVICES_LINK_SENSOR_PASS_DESCRIPTION' => 'Μεταφορά δεδομένων από τον αισθητήρα σε άλλη συσκευή',
'DEVICES_LINK_THERMOSTAT_SWITCH' => 'Διαχείριση Συσκευών',
'DEVICES_LINK_THERMOSTAT_SWITCH_DESCRIPTION' => 'Έλεγχος άλλων συσκευών ανάλογα με την κατάσταση του θερμοστάτη',
'DEVICES_LINK_THERMOSTAT_INVERT' => 'Αντιστροφή ρύθμισης κατάστασης',
'DEVICES_UPDATE_CLASSSES' => 'Ενημέρωση κλάσεων',
'DEVICES_ADD_OBJECT_AUTOMATICALLY' => 'Δημιουργία αυτόματης',
'DEVICES_PATTERN_TURNON' => 'Ανάψτε το φως',
'DEVICES_PATTERN_TURNOFF' => 'απενεργοποίηση | σβήνει | απενεργοποίηση',
'DEVICES_DEGREES' => 'βαθμοί',
'DEVICES_STATUS_OPEN' => 'ανοιχτό',
'DEVICES_STATUS_CLOSED' => 'κλειστό',
'DEVICES_STATUS_ALARM' => 'κατάσταση συναγερμού',
'DEVICES_COMMAND_CONFIRMATION' => 'Έγινε Done όπως σας αρέσει',
'DEVICES_ROOMS_NOBODYHOME' => 'Κανένας.',
'DEVICES_ROOMS_SOMEBODYHOME' => 'Κάποιος είναι.',
'DEVICES_ROOMS_ACTIVITY' => 'Ενεργός:',
'DEVICES_PASSED_NOW' => 'ακριβώς',
'DEVICES_PASSED_SECONDS_AGO' => 'sec. πίσω ',
'DEVICES_PASSED_MINUTES_AGO' => 'min. πίσω ',
'DEVICES_PASSED_HOURS_AGO' => 'h. πίσω ',
'DEVICES_CHOOSE_EXISTING' => '... ή επιλέξτε μια ήδη προστιθέμενη συσκευή',
'DEVICES_CAMERA' => 'Κάμερα IP',
'DEVICES_CAMERA_STREAM_URL' => 'URL ροής βίντεο',
'DEVICES_CAMERA_USERNAME' => 'Όνομα χρήστη',
'DEVICES_CAMERA_PASSWORD' => 'Κωδικός πρόσβασης',
'DEVICES_CAMERA_SNAPSHOT_URL' => 'Στατική URL στιγμιότυπου',
'DEVICES_CAMERA_SNAPSHOT' => 'Στιγμιότυπο',
'DEVICES_CAMERA_TAKE_SNAPSHOT' => 'Αποθήκευση στιγμιότυπου',
'DEVICES_CAMERA_SNAPSHOT_HISTORY' => 'Ιστορικό',
'DEVICES_CAMERA_STREAM_TRANSPORT' => 'Μεταφορά ρεύματος',
'DEVICES_CAMERA_PREVIEW_TYPE' => 'Προεπισκόπηση',
'DEVICES_CAMERA_PREVIEW_TYPE_STATIC' => 'Στατικό στιγμιότυπο',
'DEVICES_CAMERA_PREVIEW_TYPE_SLIDESHOW' => 'Slideshow',
'DEVICES_CAMERA_PREVIEW_ONCLICK' => 'Ενέργεια κάνοντας κλικ στην εικόνα',
'DEVICES_CAMERA_PREVIEW_ONCLICK_ENLARGE' => 'Μεγέθυνση εικόνας',
'DEVICES_CAMERA_PREVIEW_ONCLICK_ORIGINAL' => 'Γρήγορα στο ροή',
'DEVICES_THERMOSTAT' => 'Θερμοστάτης',
'DEVICES_THERMOSTAT_MODE' => 'Λειτουργία',
'DEVICES_THERMOSTAT_MODE_NORMAL' => 'Συνήθης',
'DEVICES_THERMOSTAT_MODE_ECO' => 'Eco',
'DEVICES_THERMOSTAT_MODE_OFF' => 'Off',
'DEVICES_THERMOSTAT_ECO_MODE' => 'λειτουργία ECO',
'DEVICES_THERMOSTAT_NORMAL_TEMP' => 'Κανονική θερμοκρασία στόχος',
'DEVICES_THERMOSTAT_ECO_TEMP' => 'Θερμοκρασία στόχου ECO',
'DEVICES_THERMOSTAT_CURRENT_TEMP' => 'Τρέχουσα θερμοκρασία',
'DEVICES_THERMOSTAT_CURRENT_TARGET_TEMP' => 'Στόχευση της θερμοκρασίας',
'DEVICES_THERMOSTAT_THRESHOLD' => 'ιριο θερμοστάτης (0,25 από προεπιλογή)',
'DEVICES_THERMOSTAT_RELAY_STATUS' => 'Κατάσταση αναμετάδοσης',
'DEVICES_ALL_BY_TYPE' => 'Όλα από τον τύπο',
'DEVICES_ALL_BY_ROOM' => 'Όλα τα δωμάτια',
'DEVICES_LOAD_TIMEOUT'=>'Χρονοδιακόπτης κατάστασης φόρτωσης',
'GROUPS' => 'Ομάδες',
'APPLIES_TO' => 'Εφαρμογή σε',
'AUTO_LINK' => 'Αυτόματη εκτέλεση δέσμης ενεργειών',
'FAVORITE_DEVICE' => 'В списке быстрого доступа',
'ROOMS' => 'Δωμάτια',
'APPEARANCE' => 'Εμφάνιση',
'MAINTENANCE' => 'Υπηρεσία',
'LIST' => 'Λίστα',
'DATA_OPTIMIZING' => 'Βελτιστοποίηση δεδομένων',
'DID_YOU_KNOW' => 'Ξέρεις τι ...',
'NEWS' => 'Ειδήσεις του MajorDoMo',
'KNOWLEDGE_BASE' => 'Βάση γνώσεων',
'ACTIVITIES' => 'Συμπεριφορά',
'COMMANDS' => 'Ομάδες',
'ADDON_FILE' => 'Πρόσθετο αρχείο',
'UPLOAD_AND_INSTALL' => 'Λήψη και εγκατάσταση',
'ADD_UPDATE_MANUALLY' =>'Προσθήκη / ενημέρωση με μη αυτόματο τρόπο',
'TURNING_ON' =>'Ενεργοποιήστε',
'TURNING_OFF' =>'Απενεργοποιήστε',
'PATTERN_TIMER' => 'χρονοδιακόπτη',
'PATTERN_DO_AFTER' => 'μέσω',
'PATTERN_DO_FOR' => 'on',
'PATTERN_SECOND' => 'δευτερολέπτων',
'PATTERN_MINUTE' => 'λεπτά',
'PATTERN_HOUR' => 'μια ώρα',
'THEME' => 'Θέμα',
'THEME_DARK' => 'Σκούρο',
'THEME_LIGHT' => 'Φως',
'DATA_SOURCE' => 'Πηγή δεδομένων',
'WIDGET' => 'Widget',
'PANE' => 'Πίνακας',
'COLUMNS' => 'Στήλες',
'SIZE' => 'Μέγεθος',
'CLOCK' => 'Ρολόγια',
'UPDATES_SOURCE' => 'Πηγή ενημέρωσης πυρήνα',
'UPDATES_SOURCE_MASTER' => 'Οδηγός (σταθερή έκδοση)',
'UPDATES_SOURCE_ALPHA' => 'Alpha (έγκαιρη πρόσβαση σε ενημερώσεις)',
'MAINCYCLEDOWN' => 'Ανάπτυξη βρόχου κύριου συστήματος',
'MAINCYCLEDOWN_DETAILS' => '<b> Μην πανικοβάστε! :) </ B> <br/> Διακόπηκε κύρια διαδικασία συστήματος Majordomo <br/> Ίσως αρκεί να περιμένετε μερικά δευτερόλεπτα και η εργασία θα αποκατασταθεί, αλλά εάν το σφάλμα επιμένει, χρησιμοποιήστε μία από τις παρακάτω επιλογές.',
/* end module names */
);
foreach ($dictionary as $k => $v) {
if (!defined('LANG_' . $k)) {
define('LANG_' . $k, $v);
}
}
| sergejey/majordomo | languages/el.php | PHP | mit | 49,076 |
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactMixin = require('react-mixin');
var _reactMixin2 = _interopRequireDefault(_reactMixin);
var _mixins = require('./mixins');
var _utilsHexToRgb = require('../../utils/hexToRgb');
var _utilsHexToRgb2 = _interopRequireDefault(_utilsHexToRgb);
var styles = {
base: {
paddingTop: 3,
paddingBottom: 3,
paddingRight: 0,
marginLeft: 14
},
label: {
display: 'inline-block',
marginRight: 5
}
};
var JSONStringNode = (function (_React$Component) {
_inherits(JSONStringNode, _React$Component);
function JSONStringNode() {
_classCallCheck(this, _JSONStringNode);
_React$Component.apply(this, arguments);
}
JSONStringNode.prototype.render = function render() {
var backgroundColor = 'transparent';
if (this.props.previousValue !== this.props.value) {
var bgColor = _utilsHexToRgb2['default'](this.props.theme.base06);
backgroundColor = 'rgba(' + bgColor.r + ', ' + bgColor.g + ', ' + bgColor.b + ', 0.1)';
}
return _react2['default'].createElement(
'li',
{ style: _extends({}, styles.base, { backgroundColor: backgroundColor }), onClick: this.handleClick.bind(this) },
_react2['default'].createElement(
'label',
{ style: _extends({}, styles.label, {
color: this.props.theme.base0D
}) },
this.props.keyName,
':'
),
_react2['default'].createElement(
'span',
{ style: { color: this.props.theme.base0B } },
'"',
this.props.value,
'"'
)
);
};
var _JSONStringNode = JSONStringNode;
JSONStringNode = _reactMixin2['default'].decorate(_mixins.SquashClickEventMixin)(JSONStringNode) || JSONStringNode;
return JSONStringNode;
})(_react2['default'].Component);
exports['default'] = JSONStringNode;
module.exports = exports['default']; | toke182/react-redux-experiment | node_modules/redux-devtools/lib/react/JSONTree/JSONStringNode.js | JavaScript | mit | 2,907 |
# -- coding: utf-8
=begin
$ cat foo.rb
require "rubygems"
require "kyototycoon"
KyotoTycoon::Stream.run($stdin) do |line|
... do some stuff ..
end
$ ktremotemgr slave -uw | ruby foo.rb
=end
class KyotoTycoon
module Stream
def self.run(io=$stdin, &block)
io.each_line{|line|
line = Line.new(*line.strip.split("\t", 5))
block.call(line)
}
end
class Line < Struct.new(:ts, :sid, :db, :cmd, :raw_args)
def args
@args ||= begin
return [] if raw_args.nil?
k,v = *raw_args.split("\t").map{|v| v.unpack('m').first}
return [k] unless v
xt = 0
v.unpack('C5').each{|num|
xt = (xt << 8) + num
}
v = v[5, v.length]
[k, v, xt]
end
end
def key
@key ||= begin
args.first || nil
end
end
def value
@value ||= begin
args[1] || nil
end
end
def xt
@xt ||= begin
args[2] || nil
end
end
def xt_time
@xt_time ||= begin
if args[2]
# if not set xt:
# Time.at(1099511627775) # => 36812-02-20 09:36:15 +0900
Time.at(args[2].to_i)
else
Time.at(0)
end
end
end
def time
@time ||= Time.at(*[ts[0,10], ts[10, ts.length]].map(&:to_i))
end
end
end
end
| genki/kyototycoon-ruby | lib/kyototycoon/stream.rb | Ruby | mit | 1,445 |
<?php
/*
* This file is part of the Scribe Cache Bundle.
*
* (c) Scribe Inc. <source@scribe.software>
*
* For the full copyright and license information, please view the LICENSE.md
* file that was distributed with this source code.
*/
namespace Scribe\SwimBundle\Rendering\Manager\Factory;
use Scribe\Component\DependencyInjection\Container\ServiceFinder;
use Scribe\SwimBundle\Rendering\Manager\SwimRenderingManagerInterface;
/**
* Class SwimRendererFactory.
*/
class SwimRendererFactory
{
/**
* Service name of Swim renderer without caching.
*
* @var string
*/
const SWIM_RENDERER_CACHING_DISABLED = 's.swim.renderer_caching_disabled';
/**
* Service name of Swim renderer with caching.
*
* @var string
*/
const SWIM_RENDERER_CACHING_ENABLED = 's.swim.renderer_caching_enabled';
/**
* @param ServiceFinder $serviceFinder
* @param bool $cachingEnabled
*
* @return SwimRenderingManagerInterface
*/
public static function getRenderer(ServiceFinder $serviceFinder, $cachingEnabled = true)
{
if (true === $cachingEnabled) {
return $serviceFinder(self::SWIM_RENDERER_CACHING_ENABLED);
}
return $serviceFinder(self::SWIM_RENDERER_CACHING_DISABLED);
}
}
/* EOF */
| scribenet/symfony-swim-bundle | src/Rendering/Manager/Factory/SwimRendererFactory.php | PHP | mit | 1,316 |
import falcor from 'falcor';
import _ from 'lodash';
import * as db from 'lib/db';
import { has } from 'lib/utilities';
const $ref = falcor.Model.ref;
export default [
{
// get featured article
route: "issues['byNumber'][{integers:issueNumbers}]['featured']",
get: pathSet =>
new Promise(resolve => {
db.featuredArticleQuery(pathSet.issueNumbers).then(data => {
const results = [];
data.forEach(row => {
results.push({
path: ['issues', 'byNumber', row.issue_number, 'featured'],
value: $ref(['articles', 'bySlug', row.slug]),
});
});
resolve(results);
});
}),
},
{
// get editor's picks
route:
"issues['byNumber'][{integers:issueNumbers}]['picks'][{integers:indices}]",
get: pathSet =>
new Promise(resolve => {
db.editorPickQuery(pathSet.issueNumbers).then(data => {
const results = [];
_.forEach(data, (postSlugArray, issueNumber) => {
pathSet.indices.forEach(index => {
if (index < postSlugArray.length) {
results.push({
path: ['issues', 'byNumber', issueNumber, 'picks', index],
value: $ref(['articles', 'bySlug', postSlugArray[index]]),
});
}
});
});
resolve(results);
});
}),
},
{
// Get articles category information from articles.
/* This is a special case as it actually makes us store a bit of information twice
But we can't just give a ref here since because the articles of a category is different
depending on whether it is fetched directly from categories which is ordered chronologically
and all articles from that category are fetched or from an issue where it is ordered by
editor tools */
route:
"issues['byNumber'][{integers:issueNumbers}]['categories'][{integers:indices}]['id', 'name', 'slug']", // eslint-disable-line max-len
get: pathSet =>
new Promise(resolve => {
const requestedFields = pathSet[5];
db.issueCategoryQuery(pathSet.issueNumbers, requestedFields).then(
data => {
// data is an object with keys of issue numbers and values
// arrays of category objects in correct order as given in editor tools
const results = [];
_.forEach(data, (categorySlugArray, issueNumber) => {
pathSet.indices.forEach(index => {
if (index < categorySlugArray.length) {
requestedFields.forEach(field => {
results.push({
path: [
'issues',
'byNumber',
issueNumber,
'categories',
index,
field,
],
value: categorySlugArray[index][field],
});
});
}
});
});
resolve(results);
},
);
}),
},
{
// Get articles within issue categories
route:
"issues['byNumber'][{integers:issueNumbers}]['categories'][{integers:categoryIndices}]['articles'][{integers:articleIndices}]", // eslint-disable-line max-len
get: pathSet =>
// This will currently fetch every single article from the issue
// every time, and then just only return the ones asked for
// which shouldn't at all be a problem at current capacity of
// 10-20 articles an issue.
new Promise(resolve => {
db.issueCategoryArticleQuery(pathSet.issueNumbers).then(data => {
// data is an object with keys equal to issueNumbers and values
// being an array of arrays, the upper array being the categories
// in their given order, and the lower level array within each category
// is article slugs also in their given order.
const results = [];
_.forEach(data, (categoryArray, issueNumber) => {
pathSet.categoryIndices.forEach(categoryIndex => {
if (categoryIndex < categoryArray.length) {
pathSet.articleIndices.forEach(articleIndex => {
if (articleIndex < categoryArray[categoryIndex].length) {
results.push({
path: [
'issues',
'byNumber',
issueNumber,
'categories',
categoryIndex,
'articles',
articleIndex,
],
value: $ref([
'articles',
'bySlug',
categoryArray[categoryIndex][articleIndex],
]),
});
}
});
}
});
});
resolve(results);
});
}),
},
{
// Get issue data
// eslint-disable-next-line max-len
route:
"issues['byNumber'][{integers:issueNumbers}]['id', 'published_at', 'name', 'issueNumber']",
get: pathSet => {
const mapFields = field => {
switch (field) {
case 'issueNumber':
return 'issue_number';
default:
return field;
}
};
return new Promise(resolve => {
const requestedFields = pathSet[3];
const dbColumns = requestedFields.map(mapFields);
db.issueQuery(pathSet.issueNumbers, dbColumns).then(data => {
const results = [];
data.forEach(issue => {
// Convert Date object to time integer
const processedIssue = { ...issue };
if (
has.call(processedIssue, 'published_at') &&
processedIssue.published_at instanceof Date
) {
processedIssue.published_at = processedIssue.published_at.getTime();
}
requestedFields.forEach(field => {
results.push({
path: [
'issues',
'byNumber',
processedIssue.issue_number,
field,
],
value: processedIssue[mapFields(field)],
});
});
});
resolve(results);
});
});
},
set: jsonGraphArg =>
new Promise(resolve => {
const issueNumber = Object.keys(jsonGraphArg.issues.byNumber)[0];
const issueObject = jsonGraphArg.issues.byNumber[issueNumber];
const results = [];
db.updateIssueData(jsonGraphArg).then(flag => {
if (flag !== true) {
throw new Error('Error while updating issue data');
}
_.forEach(issueObject, (value, field) => {
results.push({
path: ['issues', 'byNumber', parseInt(issueNumber, 10), field],
value,
});
});
results.push({
path: ['issues', 'latest'],
invalidated: true,
});
resolve(results);
});
}),
},
{
route: "issues['byNumber']['updateIssueArticles']",
call: (callPath, args) =>
new Promise(resolve => {
const issueNumber = args[0];
const featuredArticles = args[1];
const picks = args[2];
const mainArticles = args[3];
db.updateIssueArticles(
issueNumber,
featuredArticles,
picks,
mainArticles,
).then(data => {
let results = [];
const toAdd = data.data;
const toInvalidate = data.invalidated;
// Build the return array from the structure we know it returns
// from db.js
if (toInvalidate) {
results = results.concat(toInvalidate);
}
if (has.call(toAdd, 'featured')) {
results.push(toAdd.featured);
}
if (has.call(toAdd, 'picks')) {
results = results.concat(toAdd.picks);
}
if (has.call(toAdd, 'categories')) {
_.forEach(toAdd.categories, (category, key) => {
results.push({
path: [
'issues',
'byNumber',
issueNumber,
'categories',
key,
'name',
],
value: category.name,
});
results.push({
path: [
'issues',
'byNumber',
issueNumber,
'categories',
key,
'slug',
],
value: category.slug,
});
results = results.concat(category.articles);
});
}
if (has.call(toAdd, 'published')) {
results = results.concat(toAdd.published);
}
resolve(results);
});
}),
},
{
route:
"issues['byNumber'][{integers:issueNumbers}]['updateIssueCategories']",
call: (callPath, args) =>
new Promise(resolve => {
const issueNumber = callPath.issueNumbers[0];
const idArray = args[0];
db.updateIssueCategories(issueNumber, idArray).then(flag => {
if (flag !== true) {
throw new Error('updateIssueCategories returned non-true flag');
}
const results = [
{
path: ['placeholder'],
value: 'placeholder',
},
{
path: ['issues', 'byNumber', issueNumber, 'categories'],
invalidated: true,
},
];
resolve(results);
});
}),
},
{
route: "issues['byNumber'][{integers:issueNumbers}]['publishIssue']",
call: (callPath, args) =>
new Promise(resolve => {
const issueId = args[0];
const issueNumber = callPath.issueNumbers[0];
db.publishIssue(issueId).then(data => {
const results = [];
const publishTime = data.date.getTime();
results.push({
path: ['issues', 'byNumber', issueNumber, 'published_at'],
value: publishTime,
});
data.publishedArticles.forEach(slug => {
results.push({
path: ['articles', 'bySlug', slug, 'published_at'],
value: publishTime,
});
});
resolve(results);
});
}),
},
{
route: "issues['byNumber']['addIssue']",
call: (callPath, args) =>
new Promise((resolve, reject) => {
const issue = args[0];
verifyIssue(issue);
const fields = Object.keys(issue);
db.addIssue(issue)
.then(flag => {
if (flag !== true) {
throw new Error(
'For some reason addIssue db function returned a non-true flag',
);
}
const results = [];
fields.forEach(field => {
results.push({
path: ['issues', 'byNumber', issue.issue_number, field],
value: issue[field],
});
});
results.push({
path: ['issues', 'latest'],
invalidated: true,
});
resolve(results);
})
.catch(reject);
}),
},
];
function verifyIssue(issue) {
const requiredFields = ['name', 'issue_number'];
const optionalFields = ['published_at'];
requiredFields.every(field => {
if (!has.call(issue, field)) {
throw new Error(`Required field ${field} was not present`);
}
return true;
});
const allFields = requiredFields.concat(optionalFields);
Object.keys(issue).every(issueField => {
if (!allFields.includes(issueField)) {
throw new Error(`Unknown field ${issueField} was found on issue`);
}
return true;
});
}
| thegazelle-ad/gazelle-server | src/lib/falcor/routes/issues/by-number.js | JavaScript | mit | 12,136 |
<?php
namespace Kemer\UPnP\Server\MediaServer;
use SoapVar;
use SoapParam;
use SimpleXmlElement;
use Kemer\MediaLibrary\LibraryInterface;
class ContentDirectory
{
/**
* Media library
*
* @var LibraryInterface
*/
protected $library;
/**
* ContentDirectory server constructor
*
* @param LibraryInterface $library
*/
public function __construct(LibraryInterface $library)
{
$this->library = $library;
}
/**
* {@inheritDoc}
*/
public function GetSearchCapabilities()
{
}
/**
* {@inheritDoc}
*/
public function GetSortCapabilities()
{
return '';
}
/**
* {@inheritDoc}
*/
public function GetSystemUpdateID()
{
}
/**
* {@inheritDoc}
*/
public function Browse($ObjectID, $BrowseFlag, $Filter, $StartingIndex, $RequestedCount, $SortCriteria)
{
$result = $this->library->get("$ObjectID")->asXML();
$xml = new \DOMDocument( "1.0");
$xml->loadXML($result->asXML());
$result = $xml->saveHTML();
$xml = new \DOMDocument( "1.0");
$xml->appendChild($xml->createElement("Result", $result));
$xml->appendChild($xml->createElement("NumberReturned", count($result)));
$xml->appendChild($xml->createElement("TotalMatches", count($result)));
$xml->appendChild($xml->createElement("UpdateID", 1));
return new \SoapVar($xml->saveHTML(), XSD_ANYXML);
}
public function Search()
{
}
public function CreateObject()
{
}
public function DestroyObject()
{
}
public function UpdateObject()
{
}
public function ImportResource()
{
}
public function ExportResource()
{
}
public function StopTransferResource()
{
}
public function GetTransferProgress()
{
}
public function DeleteResource()
{
}
public function CreateReference()
{
}
}
| gallna/UPnPServer | src/Kemer/UPnP/Server/MediaServer/ContentDirectory.php | PHP | mit | 2,014 |
import React, {PropTypes} from 'react'
import styles from './Form.css'
export default React.createClass({
propTypes: {
username: PropTypes.string.isRequired,
onLogout: PropTypes.func
},
render() {
return (
<div className={styles.forms}>
<section>
<label>当前用户:</label>
<input type="text" value={this.props.username} readOnly />
</section>
<section>
<button
onClick={this.props.onLogout}
className={`${styles.btn} ${styles.btnBorderOpen} ${styles.btnPurple}`}
>
注销
</button>
</section>
</div>
)
}
})
| simongfxu/sync-editor | app/components/LoginStatus.js | JavaScript | mit | 667 |
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
/**
* @codeCoverageIgnore
*/
class InstallSchema implements InstallSchemaInterface
{
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$installer = $setup;
$installer->startSetup();
/**
* Create table 'sales_order'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_order')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'state',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'State'
)->addColumn(
'status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Status'
)->addColumn(
'coupon_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Coupon Code'
)->addColumn(
'protect_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Protect Code'
)->addColumn(
'shipping_description',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Shipping Description'
)->addColumn(
'is_virtual',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Is Virtual'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'customer_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true],
'Customer Id'
)->addColumn(
'base_discount_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Amount'
)->addColumn(
'base_discount_canceled',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Canceled'
)->addColumn(
'base_discount_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Invoiced'
)->addColumn(
'base_discount_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Refunded'
)->addColumn(
'base_grand_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Grand Total'
)->addColumn(
'base_shipping_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Amount'
)->addColumn(
'base_shipping_canceled',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Canceled'
)->addColumn(
'base_shipping_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Invoiced'
)->addColumn(
'base_shipping_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Refunded'
)->addColumn(
'base_shipping_tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Tax Amount'
)->addColumn(
'base_shipping_tax_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Tax Refunded'
)->addColumn(
'base_subtotal',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Subtotal'
)->addColumn(
'base_subtotal_canceled',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Subtotal Canceled'
)->addColumn(
'base_subtotal_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Subtotal Invoiced'
)->addColumn(
'base_subtotal_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Subtotal Refunded'
)->addColumn(
'base_tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Tax Amount'
)->addColumn(
'base_tax_canceled',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Tax Canceled'
)->addColumn(
'base_tax_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Tax Invoiced'
)->addColumn(
'base_tax_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Tax Refunded'
)->addColumn(
'base_to_global_rate',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base To Global Rate'
)->addColumn(
'base_to_order_rate',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base To Order Rate'
)->addColumn(
'base_total_canceled',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Total Canceled'
)->addColumn(
'base_total_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Total Invoiced'
)->addColumn(
'base_total_invoiced_cost',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Total Invoiced Cost'
)->addColumn(
'base_total_offline_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Total Offline Refunded'
)->addColumn(
'base_total_online_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Total Online Refunded'
)->addColumn(
'base_total_paid',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Total Paid'
)->addColumn(
'base_total_qty_ordered',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Total Qty Ordered'
)->addColumn(
'base_total_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Total Refunded'
)->addColumn(
'discount_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Amount'
)->addColumn(
'discount_canceled',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Canceled'
)->addColumn(
'discount_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Invoiced'
)->addColumn(
'discount_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Refunded'
)->addColumn(
'grand_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Grand Total'
)->addColumn(
'shipping_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Amount'
)->addColumn(
'shipping_canceled',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Canceled'
)->addColumn(
'shipping_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Invoiced'
)->addColumn(
'shipping_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Refunded'
)->addColumn(
'shipping_tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Tax Amount'
)->addColumn(
'shipping_tax_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Tax Refunded'
)->addColumn(
'store_to_base_rate',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Store To Base Rate'
)->addColumn(
'store_to_order_rate',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Store To Order Rate'
)->addColumn(
'subtotal',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Subtotal'
)->addColumn(
'subtotal_canceled',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Subtotal Canceled'
)->addColumn(
'subtotal_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Subtotal Invoiced'
)->addColumn(
'subtotal_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Subtotal Refunded'
)->addColumn(
'tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Tax Amount'
)->addColumn(
'tax_canceled',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Tax Canceled'
)->addColumn(
'tax_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Tax Invoiced'
)->addColumn(
'tax_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Tax Refunded'
)->addColumn(
'total_canceled',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Canceled'
)->addColumn(
'total_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Invoiced'
)->addColumn(
'total_offline_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Offline Refunded'
)->addColumn(
'total_online_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Online Refunded'
)->addColumn(
'total_paid',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Paid'
)->addColumn(
'total_qty_ordered',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Qty Ordered'
)->addColumn(
'total_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Refunded'
)->addColumn(
'can_ship_partially',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Can Ship Partially'
)->addColumn(
'can_ship_partially_item',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Can Ship Partially Item'
)->addColumn(
'customer_is_guest',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Customer Is Guest'
)->addColumn(
'customer_note_notify',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Customer Note Notify'
)->addColumn(
'billing_address_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Billing Address Id'
)->addColumn(
'customer_group_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
[],
'Customer Group Id'
)->addColumn(
'edit_increment',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Edit Increment'
)->addColumn(
'email_sent',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Email Sent'
)->addColumn(
'send_email',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Send Email'
)->addColumn(
'forced_shipment_with_invoice',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Forced Do Shipment With Invoice'
)->addColumn(
'payment_auth_expiration',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Payment Authorization Expiration'
)->addColumn(
'quote_address_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Quote Address Id'
)->addColumn(
'quote_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Quote Id'
)->addColumn(
'shipping_address_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Shipping Address Id'
)->addColumn(
'adjustment_negative',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Adjustment Negative'
)->addColumn(
'adjustment_positive',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Adjustment Positive'
)->addColumn(
'base_adjustment_negative',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Adjustment Negative'
)->addColumn(
'base_adjustment_positive',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Adjustment Positive'
)->addColumn(
'base_shipping_discount_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Discount Amount'
)->addColumn(
'base_subtotal_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Subtotal Incl Tax'
)->addColumn(
'base_total_due',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Total Due'
)->addColumn(
'payment_authorization_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Payment Authorization Amount'
)->addColumn(
'shipping_discount_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Discount Amount'
)->addColumn(
'subtotal_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Subtotal Incl Tax'
)->addColumn(
'total_due',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Due'
)->addColumn(
'weight',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Weight'
)->addColumn(
'customer_dob',
\Magento\Framework\DB\Ddl\Table::TYPE_DATETIME,
null,
[],
'Customer Dob'
)->addColumn(
'increment_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Increment Id'
)->addColumn(
'applied_rule_ids',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
[],
'Applied Rule Ids'
)->addColumn(
'base_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Base Currency Code'
)->addColumn(
'customer_email',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
[],
'Customer Email'
)->addColumn(
'customer_firstname',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
[],
'Customer Firstname'
)->addColumn(
'customer_lastname',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
[],
'Customer Lastname'
)->addColumn(
'customer_middlename',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
[],
'Customer Middlename'
)->addColumn(
'customer_prefix',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Customer Prefix'
)->addColumn(
'customer_suffix',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Customer Suffix'
)->addColumn(
'customer_taxvat',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Customer Taxvat'
)->addColumn(
'discount_description',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Discount Description'
)->addColumn(
'ext_customer_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Ext Customer Id'
)->addColumn(
'ext_order_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Ext Order Id'
)->addColumn(
'global_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Global Currency Code'
)->addColumn(
'hold_before_state',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Hold Before State'
)->addColumn(
'hold_before_status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Hold Before Status'
)->addColumn(
'order_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Order Currency Code'
)->addColumn(
'original_increment_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Original Increment Id'
)->addColumn(
'relation_child_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Relation Child Id'
)->addColumn(
'relation_child_real_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Relation Child Real Id'
)->addColumn(
'relation_parent_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Relation Parent Id'
)->addColumn(
'relation_parent_real_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Relation Parent Real Id'
)->addColumn(
'remote_ip',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Remote Ip'
)->addColumn(
'shipping_method',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Shipping Method'
)->addColumn(
'store_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Store Currency Code'
)->addColumn(
'store_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Store Name'
)->addColumn(
'x_forwarded_for',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'X Forwarded For'
)->addColumn(
'customer_note',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Customer Note'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
'Created At'
)->addColumn(
'updated_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE],
'Updated At'
)->addColumn(
'total_item_count',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Total Item Count'
)->addColumn(
'customer_gender',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Customer Gender'
)->addColumn(
'discount_tax_compensation_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Tax Compensation Amount'
)->addColumn(
'base_discount_tax_compensation_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Tax Compensation Amount'
)->addColumn(
'shipping_discount_tax_compensation_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Discount Tax Compensation Amount'
)->addColumn(
'base_shipping_discount_tax_compensation_amnt',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Discount Tax Compensation Amount'
)->addColumn(
'discount_tax_compensation_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Tax Compensation Invoiced'
)->addColumn(
'base_discount_tax_compensation_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Tax Compensation Invoiced'
)->addColumn(
'discount_tax_compensation_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Tax Compensation Refunded'
)->addColumn(
'base_discount_tax_compensation_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Tax Compensation Refunded'
)->addColumn(
'shipping_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Incl Tax'
)->addColumn(
'base_shipping_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Incl Tax'
)->addColumn(
'coupon_rule_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
['nullable' => true],
'Coupon Sales Rule Name'
)->addIndex(
$installer->getIdxName('sales_order', ['status']),
['status']
)->addIndex(
$installer->getIdxName('sales_order', ['state']),
['state']
)->addIndex(
$installer->getIdxName('sales_order', ['store_id']),
['store_id']
)->addIndex(
$installer->getIdxName(
'sales_order',
['increment_id', 'store_id'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['increment_id', 'store_id'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_order', ['created_at']),
['created_at']
)->addIndex(
$installer->getIdxName('sales_order', ['customer_id']),
['customer_id']
)->addIndex(
$installer->getIdxName('sales_order', ['ext_order_id']),
['ext_order_id']
)->addIndex(
$installer->getIdxName('sales_order', ['quote_id']),
['quote_id']
)->addIndex(
$installer->getIdxName('sales_order', ['updated_at']),
['updated_at']
)->addIndex(
$installer->getIdxName('sales_order', ['send_email']),
['send_email']
)->addIndex(
$installer->getIdxName('sales_order', ['email_sent']),
['email_sent']
)->addForeignKey(
$installer->getFkName('sales_order', 'customer_id', 'customer_entity', 'entity_id'),
'customer_id',
$installer->getTable('customer_entity'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_SET_NULL
)->addForeignKey(
$installer->getFkName('sales_order', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_SET_NULL
)->setComment(
'Sales Flat Order'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_order_grid'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_order_grid')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Status'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'store_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Store Name'
)->addColumn(
'customer_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true],
'Customer Id'
)->addColumn(
'base_grand_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Grand Total'
)->addColumn(
'base_total_paid',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Total Paid'
)->addColumn(
'grand_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Grand Total'
)->addColumn(
'total_paid',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Paid'
)->addColumn(
'increment_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
[],
'Increment Id'
)->addColumn(
'base_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Base Currency Code'
)->addColumn(
'order_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Order Currency Code'
)->addColumn(
'shipping_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Shipping Name'
)->addColumn(
'billing_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Billing Name'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
[],
'Created At'
)->addColumn(
'updated_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
[],
'Updated At'
)->addColumn(
'billing_address',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Billing Address'
)->addColumn(
'shipping_address',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Shipping Address'
)->addColumn(
'shipping_information',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Shipping Method Name'
)->addColumn(
'customer_email',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Customer Email'
)->addColumn(
'customer_group',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Customer Group'
)->addColumn(
'subtotal',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Subtotal'
)->addColumn(
'shipping_and_handling',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping and handling amount'
)->addColumn(
'customer_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Customer Name'
)->addColumn(
'payment_method',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Payment Method'
)->addColumn(
'total_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Refunded'
)->addIndex(
$installer->getIdxName('sales_order_grid', ['status']),
['status']
)->addIndex(
$installer->getIdxName('sales_order_grid', ['store_id']),
['store_id']
)->addIndex(
$installer->getIdxName('sales_order_grid', ['base_grand_total']),
['base_grand_total']
)->addIndex(
$installer->getIdxName('sales_order_grid', ['base_total_paid']),
['base_total_paid']
)->addIndex(
$installer->getIdxName('sales_order_grid', ['grand_total']),
['grand_total']
)->addIndex(
$installer->getIdxName('sales_order_grid', ['total_paid']),
['total_paid']
)->addIndex(
$installer->getIdxName(
'sales_order_grid',
['increment_id', 'store_id'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['increment_id', 'store_id'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_order_grid', ['shipping_name']),
['shipping_name']
)->addIndex(
$installer->getIdxName('sales_order_grid', ['billing_name']),
['billing_name']
)->addIndex(
$installer->getIdxName('sales_order_grid', ['created_at']),
['created_at']
)->addIndex(
$installer->getIdxName('sales_order_grid', ['customer_id']),
['customer_id']
)->addIndex(
$installer->getIdxName('sales_order_grid', ['updated_at']),
['updated_at']
)->addIndex(
$installer->getIdxName(
'sales_order_grid',
[
'increment_id',
'billing_name',
'shipping_name',
'shipping_address',
'billing_address',
'customer_name',
'customer_email'
],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
),
[
'increment_id',
'billing_name',
'shipping_name',
'shipping_address',
'billing_address',
'customer_name',
'customer_email'
],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT]
)->setComment(
'Sales Flat Order Grid'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_order_address'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_order_address')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'parent_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true],
'Parent Id'
)->addColumn(
'customer_address_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Customer Address Id'
)->addColumn(
'quote_address_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Quote Address Id'
)->addColumn(
'region_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Region Id'
)->addColumn(
'customer_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Customer Id'
)->addColumn(
'fax',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Fax'
)->addColumn(
'region',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Region'
)->addColumn(
'postcode',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Postcode'
)->addColumn(
'lastname',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Lastname'
)->addColumn(
'street',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Street'
)->addColumn(
'city',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'City'
)->addColumn(
'email',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Email'
)->addColumn(
'telephone',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Phone Number'
)->addColumn(
'country_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
2,
[],
'Country Id'
)->addColumn(
'firstname',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Firstname'
)->addColumn(
'address_type',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Address Type'
)->addColumn(
'prefix',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Prefix'
)->addColumn(
'middlename',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Middlename'
)->addColumn(
'suffix',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Suffix'
)->addColumn(
'company',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Company'
)->addIndex(
$installer->getIdxName('sales_order_address', ['parent_id']),
['parent_id']
)->addForeignKey(
$installer->getFkName('sales_order_address', 'parent_id', 'sales_order', 'entity_id'),
'parent_id',
$installer->getTable('sales_order'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Flat Order Address'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_order_status_history'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_order_status_history')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'parent_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Parent Id'
)->addColumn(
'is_customer_notified',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Is Customer Notified'
)->addColumn(
'is_visible_on_front',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Is Visible On Front'
)->addColumn(
'comment',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Comment'
)->addColumn(
'status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Status'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
'Created At'
)->addColumn(
'entity_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
['nullable' => true],
'Shows what entity history is bind to.'
)->addIndex(
$installer->getIdxName('sales_order_status_history', ['parent_id']),
['parent_id']
)->addIndex(
$installer->getIdxName('sales_order_status_history', ['created_at']),
['created_at']
)->addForeignKey(
$installer->getFkName('sales_order_status_history', 'parent_id', 'sales_order', 'entity_id'),
'parent_id',
$installer->getTable('sales_order'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE,
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Flat Order Status History'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_order_item'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_order_item')
)->addColumn(
'item_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Item Id'
)->addColumn(
'order_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Order Id'
)->addColumn(
'parent_item_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true],
'Parent Item Id'
)->addColumn(
'quote_item_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true],
'Quote Item Id'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
'Created At'
)->addColumn(
'updated_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE],
'Updated At'
)->addColumn(
'product_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true],
'Product Id'
)->addColumn(
'product_type',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Product Type'
)->addColumn(
'product_options',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Product Options'
)->addColumn(
'weight',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Weight'
)->addColumn(
'is_virtual',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Is Virtual'
)->addColumn(
'sku',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Sku'
)->addColumn(
'name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Name'
)->addColumn(
'description',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Description'
)->addColumn(
'applied_rule_ids',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Applied Rule Ids'
)->addColumn(
'additional_data',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Additional Data'
)->addColumn(
'is_qty_decimal',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Is Qty Decimal'
)->addColumn(
'no_discount',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'No Discount'
)->addColumn(
'qty_backordered',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Qty Backordered'
)->addColumn(
'qty_canceled',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Qty Canceled'
)->addColumn(
'qty_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Qty Invoiced'
)->addColumn(
'qty_ordered',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Qty Ordered'
)->addColumn(
'qty_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Qty Refunded'
)->addColumn(
'qty_shipped',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Qty Shipped'
)->addColumn(
'base_cost',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Base Cost'
)->addColumn(
'price',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Price'
)->addColumn(
'base_price',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Base Price'
)->addColumn(
'original_price',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Original Price'
)->addColumn(
'base_original_price',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Original Price'
)->addColumn(
'tax_percent',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Tax Percent'
)->addColumn(
'tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Tax Amount'
)->addColumn(
'base_tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Base Tax Amount'
)->addColumn(
'tax_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Tax Invoiced'
)->addColumn(
'base_tax_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Base Tax Invoiced'
)->addColumn(
'discount_percent',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Discount Percent'
)->addColumn(
'discount_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Discount Amount'
)->addColumn(
'base_discount_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Base Discount Amount'
)->addColumn(
'discount_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Discount Invoiced'
)->addColumn(
'base_discount_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Base Discount Invoiced'
)->addColumn(
'amount_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Amount Refunded'
)->addColumn(
'base_amount_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Base Amount Refunded'
)->addColumn(
'row_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Row Total'
)->addColumn(
'base_row_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Base Row Total'
)->addColumn(
'row_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Row Invoiced'
)->addColumn(
'base_row_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Base Row Invoiced'
)->addColumn(
'row_weight',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['default' => '0.0000'],
'Row Weight'
)->addColumn(
'base_tax_before_discount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Tax Before Discount'
)->addColumn(
'tax_before_discount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Tax Before Discount'
)->addColumn(
'ext_order_item_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Ext Order Item Id'
)->addColumn(
'locked_do_invoice',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Locked Do Invoice'
)->addColumn(
'locked_do_ship',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Locked Do Ship'
)->addColumn(
'price_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Price Incl Tax'
)->addColumn(
'base_price_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Price Incl Tax'
)->addColumn(
'row_total_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Row Total Incl Tax'
)->addColumn(
'base_row_total_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Row Total Incl Tax'
)->addColumn(
'discount_tax_compensation_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Tax Compensation Amount'
)->addColumn(
'base_discount_tax_compensation_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Tax Compensation Amount'
)->addColumn(
'discount_tax_compensation_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Tax Compensation Invoiced'
)->addColumn(
'base_discount_tax_compensation_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Tax Compensation Invoiced'
)->addColumn(
'discount_tax_compensation_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Tax Compensation Refunded'
)->addColumn(
'base_discount_tax_compensation_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Tax Compensation Refunded'
)->addColumn(
'tax_canceled',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Tax Canceled'
)->addColumn(
'discount_tax_compensation_canceled',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Tax Compensation Canceled'
)->addColumn(
'tax_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Tax Refunded'
)->addColumn(
'base_tax_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Tax Refunded'
)->addColumn(
'discount_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Refunded'
)->addColumn(
'base_discount_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Refunded'
)->addIndex(
$installer->getIdxName('sales_order_item', ['order_id']),
['order_id']
)->addIndex(
$installer->getIdxName('sales_order_item', ['store_id']),
['store_id']
)->addForeignKey(
$installer->getFkName('sales_order_item', 'order_id', 'sales_order', 'entity_id'),
'order_id',
$installer->getTable('sales_order'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->addForeignKey(
$installer->getFkName('sales_order_item', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_SET_NULL
)->setComment(
'Sales Flat Order Item'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_order_payment'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_order_payment')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'parent_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Parent Id'
)->addColumn(
'base_shipping_captured',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Captured'
)->addColumn(
'shipping_captured',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Captured'
)->addColumn(
'amount_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Amount Refunded'
)->addColumn(
'base_amount_paid',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Amount Paid'
)->addColumn(
'amount_canceled',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Amount Canceled'
)->addColumn(
'base_amount_authorized',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Amount Authorized'
)->addColumn(
'base_amount_paid_online',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Amount Paid Online'
)->addColumn(
'base_amount_refunded_online',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Amount Refunded Online'
)->addColumn(
'base_shipping_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Amount'
)->addColumn(
'shipping_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Amount'
)->addColumn(
'amount_paid',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Amount Paid'
)->addColumn(
'amount_authorized',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Amount Authorized'
)->addColumn(
'base_amount_ordered',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Amount Ordered'
)->addColumn(
'base_shipping_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Refunded'
)->addColumn(
'shipping_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Refunded'
)->addColumn(
'base_amount_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Amount Refunded'
)->addColumn(
'amount_ordered',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Amount Ordered'
)->addColumn(
'base_amount_canceled',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Amount Canceled'
)->addColumn(
'quote_payment_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Quote Payment Id'
)->addColumn(
'additional_data',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Additional Data'
)->addColumn(
'cc_exp_month',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
12,
[],
'Cc Exp Month'
)->addColumn(
'cc_ss_start_year',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
12,
[],
'Cc Ss Start Year'
)->addColumn(
'echeck_bank_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
[],
'Echeck Bank Name'
)->addColumn(
'method',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
[],
'Method'
)->addColumn(
'cc_debug_request_body',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Cc Debug Request Body'
)->addColumn(
'cc_secure_verify',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Cc Secure Verify'
)->addColumn(
'protection_eligibility',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Protection Eligibility'
)->addColumn(
'cc_approval',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Cc Approval'
)->addColumn(
'cc_last_4',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
100,
[],
'Cc Last 4'
)->addColumn(
'cc_status_description',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Cc Status Description'
)->addColumn(
'echeck_type',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Echeck Type'
)->addColumn(
'cc_debug_response_serialized',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Cc Debug Response Serialized'
)->addColumn(
'cc_ss_start_month',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
[],
'Cc Ss Start Month'
)->addColumn(
'echeck_account_type',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Echeck Account Type'
)->addColumn(
'last_trans_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Last Trans Id'
)->addColumn(
'cc_cid_status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Cc Cid Status'
)->addColumn(
'cc_owner',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
[],
'Cc Owner'
)->addColumn(
'cc_type',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Cc Type'
)->addColumn(
'po_number',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Po Number'
)->addColumn(
'cc_exp_year',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
4,
['nullable' => true, 'default' => null],
'Cc Exp Year'
)->addColumn(
'cc_status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
4,
[],
'Cc Status'
)->addColumn(
'echeck_routing_number',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Echeck Routing Number'
)->addColumn(
'account_status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Account Status'
)->addColumn(
'anet_trans_method',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Anet Trans Method'
)->addColumn(
'cc_debug_response_body',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Cc Debug Response Body'
)->addColumn(
'cc_ss_issue',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Cc Ss Issue'
)->addColumn(
'echeck_account_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Echeck Account Name'
)->addColumn(
'cc_avs_status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Cc Avs Status'
)->addColumn(
'cc_number_enc',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Cc Number Enc'
)->addColumn(
'cc_trans_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Cc Trans Id'
)->addColumn(
'address_status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Address Status'
)->addColumn(
'additional_information',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Additional Information'
)->addIndex(
$installer->getIdxName('sales_order_payment', ['parent_id']),
['parent_id']
)->addForeignKey(
$installer->getFkName('sales_order_payment', 'parent_id', 'sales_order', 'entity_id'),
'parent_id',
$installer->getTable('sales_order'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Flat Order Payment'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_shipment'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_shipment')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'total_weight',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Weight'
)->addColumn(
'total_qty',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Qty'
)->addColumn(
'email_sent',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Email Sent'
)->addColumn(
'send_email',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Send Email'
)->addColumn(
'order_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Order Id'
)->addColumn(
'customer_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Customer Id'
)->addColumn(
'shipping_address_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Shipping Address Id'
)->addColumn(
'billing_address_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Billing Address Id'
)->addColumn(
'shipment_status',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Shipment Status'
)->addColumn(
'increment_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
[],
'Increment Id'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
'Created At'
)->addColumn(
'updated_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE],
'Updated At'
)->addColumn(
'packages',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'20000',
[],
'Packed Products in Packages'
)->addColumn(
'shipping_label',
\Magento\Framework\DB\Ddl\Table::TYPE_VARBINARY,
'2m',
[],
'Shipping Label Content'
)->addColumn(
'customer_note',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
null,
[],
'Customer Note'
)->addColumn(
'customer_note_notify',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Customer Note Notify'
)->addIndex(
$installer->getIdxName('sales_shipment', ['store_id']),
['store_id']
)->addIndex(
$installer->getIdxName('sales_shipment', ['total_qty']),
['total_qty']
)->addIndex(
$installer->getIdxName(
'sales_shipment',
['increment_id', 'store_id'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['increment_id', 'store_id'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_shipment', ['order_id']),
['order_id']
)->addIndex(
$installer->getIdxName('sales_shipment', ['created_at']),
['created_at']
)->addIndex(
$installer->getIdxName('sales_shipment', ['updated_at']),
['updated_at']
)->addIndex(
$installer->getIdxName('sales_shipment', ['send_email']),
['send_email']
)->addIndex(
$installer->getIdxName('sales_shipment', ['email_sent']),
['email_sent']
)->addForeignKey(
$installer->getFkName('sales_shipment', 'order_id', 'sales_order', 'entity_id'),
'order_id',
$installer->getTable('sales_order'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->addForeignKey(
$installer->getFkName('sales_shipment', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_SET_NULL
)->setComment(
'Sales Flat Shipment'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_shipment_grid'
*
* @add order_id, shipping_description
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_shipment_grid')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'increment_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
[],
'Increment Id'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'order_increment_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
['nullable' => false],
'Order Increment Id'
)->addColumn(
'order_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Order Id'
)->addColumn(
'order_created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false],
'Order Increment Id'
)->addColumn(
'customer_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
['nullable' => false],
'Customer Name'
)->addColumn(
'total_qty',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Qty'
)->addColumn(
'shipment_status',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Shipment Status'
)->addColumn(
'order_status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Order'
)->addColumn(
'billing_address',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Billing Address'
)->addColumn(
'shipping_address',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Shipping Address'
)->addColumn(
'billing_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
[],
'Billing Name'
)->addColumn(
'shipping_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
[],
'Shipping Name'
)->addColumn(
'customer_email',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
[],
'Customer Email'
)->addColumn(
'customer_group_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
[],
'Customer Group Id'
)->addColumn(
'payment_method',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Payment Method'
)->addColumn(
'shipping_information',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Shipping Method Name'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
[],
'Created At'
)->addColumn(
'updated_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
[],
'Updated At'
)->addIndex(
$installer->getIdxName(
'sales_shipment_grid',
[
'increment_id',
'store_id'
],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['increment_id', 'store_id'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName(
'sales_shipment_grid',
['store_id']
),
['store_id']
)->addIndex(
$installer->getIdxName(
'sales_shipment_grid',
['total_qty']
),
['total_qty']
)->addIndex(
$installer->getIdxName(
'sales_shipment_grid',
['order_increment_id']
),
['order_increment_id']
)->addIndex(
$installer->getIdxName(
'sales_shipment_grid',
['shipment_status']
),
['shipment_status']
)->addIndex(
$installer->getIdxName(
'sales_shipment_grid',
['order_status']
),
['order_status']
)->addIndex(
$installer->getIdxName('sales_shipment_grid', ['created_at']),
['created_at']
)->addIndex(
$installer->getIdxName('sales_shipment_grid', ['updated_at']),
['updated_at']
)->addIndex(
$installer->getIdxName('sales_shipment_grid', ['order_created_at']),
['order_created_at']
)->addIndex(
$installer->getIdxName('sales_shipment_grid', ['shipping_name']),
['shipping_name']
)->addIndex(
$installer->getIdxName('sales_shipment_grid', ['billing_name']),
['billing_name']
)->addIndex(
$installer->getIdxName(
'sales_shipment_grid',
[
'increment_id',
'order_increment_id',
'shipping_name',
'customer_name',
'customer_email',
'billing_address',
'shipping_address'
],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
),
[
'increment_id',
'order_increment_id',
'shipping_name',
'customer_name',
'customer_email',
'billing_address',
'shipping_address'
],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT]
)->setComment(
'Sales Flat Shipment Grid'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_shipment_item'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_shipment_item')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'parent_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Parent Id'
)->addColumn(
'row_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Row Total'
)->addColumn(
'price',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Price'
)->addColumn(
'weight',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Weight'
)->addColumn(
'qty',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Qty'
)->addColumn(
'product_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Product Id'
)->addColumn(
'order_item_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Order Item Id'
)->addColumn(
'additional_data',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Additional Data'
)->addColumn(
'description',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Description'
)->addColumn(
'name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Name'
)->addColumn(
'sku',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Sku'
)->addIndex(
$installer->getIdxName('sales_shipment_item', ['parent_id']),
['parent_id']
)->addForeignKey(
$installer->getFkName('sales_shipment_item', 'parent_id', 'sales_shipment', 'entity_id'),
'parent_id',
$installer->getTable('sales_shipment'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Flat Shipment Item'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_shipment_track'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_shipment_track')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'parent_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Parent Id'
)->addColumn(
'weight',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Weight'
)->addColumn(
'qty',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Qty'
)->addColumn(
'order_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Order Id'
)->addColumn(
'track_number',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Number'
)->addColumn(
'description',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Description'
)->addColumn(
'title',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Title'
)->addColumn(
'carrier_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Carrier Code'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
'Created At'
)->addColumn(
'updated_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE],
'Updated At'
)->addIndex(
$installer->getIdxName('sales_shipment_track', ['parent_id']),
['parent_id']
)->addIndex(
$installer->getIdxName('sales_shipment_track', ['order_id']),
['order_id']
)->addIndex(
$installer->getIdxName('sales_shipment_track', ['created_at']),
['created_at']
)->addForeignKey(
$installer->getFkName('sales_shipment_track', 'parent_id', 'sales_shipment', 'entity_id'),
'parent_id',
$installer->getTable('sales_shipment'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Flat Shipment Track'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_shipment_comment'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_shipment_comment')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'parent_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Parent Id'
)->addColumn(
'is_customer_notified',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Is Customer Notified'
)->addColumn(
'is_visible_on_front',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Is Visible On Front'
)->addColumn(
'comment',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Comment'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
'Created At'
)->addIndex(
$installer->getIdxName('sales_shipment_comment', ['created_at']),
['created_at']
)->addIndex(
$installer->getIdxName('sales_shipment_comment', ['parent_id']),
['parent_id']
)->addForeignKey(
$installer->getFkName('sales_shipment_comment', 'parent_id', 'sales_shipment', 'entity_id'),
'parent_id',
$installer->getTable('sales_shipment'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Flat Shipment Comment'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_invoice'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_invoice')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false, 'primary' => true, 'identity' => true],
'Entity Id'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'base_grand_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Grand Total'
)->addColumn(
'shipping_tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Tax Amount'
)->addColumn(
'tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Tax Amount'
)->addColumn(
'base_tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Tax Amount'
)->addColumn(
'store_to_order_rate',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Store To Order Rate'
)->addColumn(
'base_shipping_tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Tax Amount'
)->addColumn(
'base_discount_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Amount'
)->addColumn(
'base_to_order_rate',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base To Order Rate'
)->addColumn(
'grand_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Grand Total'
)->addColumn(
'shipping_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Amount'
)->addColumn(
'subtotal_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Subtotal Incl Tax'
)->addColumn(
'base_subtotal_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Subtotal Incl Tax'
)->addColumn(
'store_to_base_rate',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Store To Base Rate'
)->addColumn(
'base_shipping_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Amount'
)->addColumn(
'total_qty',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Qty'
)->addColumn(
'base_to_global_rate',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base To Global Rate'
)->addColumn(
'subtotal',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Subtotal'
)->addColumn(
'base_subtotal',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Subtotal'
)->addColumn(
'discount_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Amount'
)->addColumn(
'billing_address_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Billing Address Id'
)->addColumn(
'is_used_for_refund',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Is Used For Refund'
)->addColumn(
'order_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Order Id'
)->addColumn(
'email_sent',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Email Sent'
)->addColumn(
'send_email',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Send Email'
)->addColumn(
'can_void_flag',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Can Void Flag'
)->addColumn(
'state',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'State'
)->addColumn(
'shipping_address_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Shipping Address Id'
)->addColumn(
'store_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Store Currency Code'
)->addColumn(
'transaction_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Transaction Id'
)->addColumn(
'order_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Order Currency Code'
)->addColumn(
'base_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Base Currency Code'
)->addColumn(
'global_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Global Currency Code'
)->addColumn(
'increment_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
[],
'Increment Id'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
'Created At'
)->addColumn(
'updated_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE],
'Updated At'
)->addColumn(
'discount_tax_compensation_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Tax Compensation Amount'
)->addColumn(
'base_discount_tax_compensation_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Tax Compensation Amount'
)->addColumn(
'shipping_discount_tax_compensation_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Discount Tax Compensation Amount'
)->addColumn(
'base_shipping_discount_tax_compensation_amnt',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Discount Tax Compensation Amount'
)->addColumn(
'shipping_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Incl Tax'
)->addColumn(
'base_shipping_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Incl Tax'
)->addColumn(
'base_total_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Total Refunded'
)->addColumn(
'discount_description',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Discount Description'
)->addColumn(
'customer_note',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
null,
[],
'Customer Note'
)->addColumn(
'customer_note_notify',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Customer Note Notify'
)->addIndex(
$installer->getIdxName('sales_invoice', ['store_id']),
['store_id']
)->addIndex(
$installer->getIdxName('sales_invoice', ['grand_total']),
['grand_total']
)->addIndex(
$installer->getIdxName('sales_invoice', ['order_id']),
['order_id']
)->addIndex(
$installer->getIdxName('sales_invoice', ['state']),
['state']
)->addIndex(
$installer->getIdxName(
'sales_invoice',
['increment_id', 'store_id'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['increment_id', 'store_id'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_invoice', ['created_at']),
['created_at']
)->addIndex(
$installer->getIdxName('sales_invoice', ['updated_at']),
['updated_at']
)->addIndex(
$installer->getIdxName('sales_invoice', ['send_email']),
['send_email']
)->addIndex(
$installer->getIdxName('sales_invoice', ['email_sent']),
['email_sent']
)->addForeignKey(
$installer->getFkName('sales_invoice', 'order_id', 'sales_order', 'entity_id'),
'order_id',
$installer->getTable('sales_order'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->addForeignKey(
$installer->getFkName('sales_invoice', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_SET_NULL
)->setComment(
'Sales Flat Invoice'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_invoice_grid'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_invoice_grid')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'increment_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
[],
'Increment Id'
)->addColumn(
'state',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'State'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'store_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Store Name'
)->addColumn(
'order_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Order Id'
)->addColumn(
'order_increment_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
[],
'Order Increment Id'
)->addColumn(
'order_created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
[],
'Order Created At'
)->addColumn(
'customer_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Customer Name'
)->addColumn(
'customer_email',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Customer Email'
)->addColumn(
'customer_group_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
[],
'Customer Group Id'
)->addColumn(
'payment_method',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
[],
'Payment Method'
)->addColumn(
'store_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Store Currency Code'
)->addColumn(
'order_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Order Currency Code'
)->addColumn(
'base_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Base Currency Code'
)->addColumn(
'global_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Global Currency Code'
)->addColumn(
'billing_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Billing Name'
)->addColumn(
'billing_address',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Billing Address'
)->addColumn(
'shipping_address',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Shipping Address'
)->addColumn(
'shipping_information',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Shipping Method Name'
)->addColumn(
'subtotal',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Subtotal'
)->addColumn(
'shipping_and_handling',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping and handling amount'
)->addColumn(
'grand_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Grand Total'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
[],
'Created At'
)->addColumn(
'updated_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
[],
'Updated At'
)->addIndex(
$installer->getIdxName('sales_invoice_grid', ['store_id']),
['store_id']
)->addIndex(
$installer->getIdxName('sales_invoice_grid', ['grand_total']),
['grand_total']
)->addIndex(
$installer->getIdxName('sales_invoice_grid', ['order_id']),
['order_id']
)->addIndex(
$installer->getIdxName('sales_invoice_grid', ['state']),
['state']
)->addIndex(
$installer->getIdxName(
'sales_invoice_grid',
['increment_id', 'store_id'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['increment_id', 'store_id'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_invoice_grid', ['order_increment_id']),
['order_increment_id']
)->addIndex(
$installer->getIdxName('sales_invoice_grid', ['created_at']),
['created_at']
)->addIndex(
$installer->getIdxName('sales_invoice_grid', ['updated_at']),
['updated_at']
)->addIndex(
$installer->getIdxName('sales_invoice_grid', ['order_created_at']),
['order_created_at']
)->addIndex(
$installer->getIdxName('sales_invoice_grid', ['billing_name']),
['billing_name']
)->addIndex(
$installer->getIdxName(
'sales_invoice_grid',
[
'increment_id',
'order_increment_id',
'billing_name',
'billing_address',
'shipping_address',
'customer_name',
'customer_email'
],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
),
[
'increment_id',
'order_increment_id',
'billing_name',
'billing_address',
'shipping_address',
'customer_name',
'customer_email'
],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT]
)->setComment(
'Sales Flat Invoice Grid'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_invoice_item'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_invoice_item')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'parent_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Parent Id'
)->addColumn(
'base_price',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Price'
)->addColumn(
'tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Tax Amount'
)->addColumn(
'base_row_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Row Total'
)->addColumn(
'discount_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Amount'
)->addColumn(
'row_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Row Total'
)->addColumn(
'base_discount_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Amount'
)->addColumn(
'price_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Price Incl Tax'
)->addColumn(
'base_tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Tax Amount'
)->addColumn(
'base_price_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Price Incl Tax'
)->addColumn(
'qty',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Qty'
)->addColumn(
'base_cost',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Cost'
)->addColumn(
'price',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Price'
)->addColumn(
'base_row_total_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Row Total Incl Tax'
)->addColumn(
'row_total_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Row Total Incl Tax'
)->addColumn(
'product_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Product Id'
)->addColumn(
'order_item_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Order Item Id'
)->addColumn(
'additional_data',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Additional Data'
)->addColumn(
'description',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Description'
)->addColumn(
'sku',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Sku'
)->addColumn(
'name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Name'
)->addColumn(
'discount_tax_compensation_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Tax Compensation Amount'
)->addColumn(
'base_discount_tax_compensation_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Tax Compensation Amount'
)->addColumn(
'tax_ratio',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
512,
[],
'Ratio of tax invoiced over tax of the order item'
)->addIndex(
$installer->getIdxName('sales_invoice_item', ['parent_id']),
['parent_id']
)->addForeignKey(
$installer->getFkName('sales_invoice_item', 'parent_id', 'sales_invoice', 'entity_id'),
'parent_id',
$installer->getTable('sales_invoice'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Flat Invoice Item'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_invoice_comment'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_invoice_comment')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'parent_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Parent Id'
)->addColumn(
'is_customer_notified',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Is Customer Notified'
)->addColumn(
'is_visible_on_front',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Is Visible On Front'
)->addColumn(
'comment',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Comment'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
'Created At'
)->addIndex(
$installer->getIdxName('sales_invoice_comment', ['created_at']),
['created_at']
)->addIndex(
$installer->getIdxName('sales_invoice_comment', ['parent_id']),
['parent_id']
)->addForeignKey(
$installer->getFkName('sales_invoice_comment', 'parent_id', 'sales_invoice', 'entity_id'),
'parent_id',
$installer->getTable('sales_invoice'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Flat Invoice Comment'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_creditmemo'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_creditmemo')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'adjustment_positive',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Adjustment Positive'
)->addColumn(
'base_shipping_tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Tax Amount'
)->addColumn(
'store_to_order_rate',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Store To Order Rate'
)->addColumn(
'base_discount_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Amount'
)->addColumn(
'base_to_order_rate',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base To Order Rate'
)->addColumn(
'grand_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Grand Total'
)->addColumn(
'base_adjustment_negative',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Adjustment Negative'
)->addColumn(
'base_subtotal_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Subtotal Incl Tax'
)->addColumn(
'shipping_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Amount'
)->addColumn(
'subtotal_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Subtotal Incl Tax'
)->addColumn(
'adjustment_negative',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Adjustment Negative'
)->addColumn(
'base_shipping_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Amount'
)->addColumn(
'store_to_base_rate',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Store To Base Rate'
)->addColumn(
'base_to_global_rate',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base To Global Rate'
)->addColumn(
'base_adjustment',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Adjustment'
)->addColumn(
'base_subtotal',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Subtotal'
)->addColumn(
'discount_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Amount'
)->addColumn(
'subtotal',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Subtotal'
)->addColumn(
'adjustment',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Adjustment'
)->addColumn(
'base_grand_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Grand Total'
)->addColumn(
'base_adjustment_positive',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Adjustment Positive'
)->addColumn(
'base_tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Tax Amount'
)->addColumn(
'shipping_tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Tax Amount'
)->addColumn(
'tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Tax Amount'
)->addColumn(
'order_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Order Id'
)->addColumn(
'email_sent',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Email Sent'
)->addColumn(
'send_email',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Send Email'
)->addColumn(
'creditmemo_status',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Creditmemo Status'
)->addColumn(
'state',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'State'
)->addColumn(
'shipping_address_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Shipping Address Id'
)->addColumn(
'billing_address_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Billing Address Id'
)->addColumn(
'invoice_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Invoice Id'
)->addColumn(
'store_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Store Currency Code'
)->addColumn(
'order_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Order Currency Code'
)->addColumn(
'base_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Base Currency Code'
)->addColumn(
'global_currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'Global Currency Code'
)->addColumn(
'transaction_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Transaction Id'
)->addColumn(
'increment_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
[],
'Increment Id'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
'Created At'
)->addColumn(
'updated_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE],
'Updated At'
)->addColumn(
'discount_tax_compensation_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Tax Compensation Amount'
)->addColumn(
'base_discount_tax_compensation_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Tax Compensation Amount'
)->addColumn(
'shipping_discount_tax_compensation_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Discount Tax Compensation Amount'
)->addColumn(
'base_shipping_discount_tax_compensation_amnt',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Discount Tax Compensation Amount'
)->addColumn(
'shipping_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping Incl Tax'
)->addColumn(
'base_shipping_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Shipping Incl Tax'
)->addColumn(
'discount_description',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Discount Description'
)->addColumn(
'customer_note',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
null,
[],
'Customer Note'
)->addColumn(
'customer_note_notify',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Customer Note Notify'
)->addIndex(
$installer->getIdxName('sales_creditmemo', ['store_id']),
['store_id']
)->addIndex(
$installer->getIdxName('sales_creditmemo', ['order_id']),
['order_id']
)->addIndex(
$installer->getIdxName('sales_creditmemo', ['creditmemo_status']),
['creditmemo_status']
)->addIndex(
$installer->getIdxName(
'sales_creditmemo',
['increment_id', 'store_id'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['increment_id', 'store_id'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_creditmemo', ['state']),
['state']
)->addIndex(
$installer->getIdxName('sales_creditmemo', ['created_at']),
['created_at']
)->addIndex(
$installer->getIdxName('sales_creditmemo', ['updated_at']),
['updated_at']
)->addIndex(
$installer->getIdxName('sales_creditmemo', ['send_email']),
['send_email']
)->addIndex(
$installer->getIdxName('sales_creditmemo', ['email_sent']),
['email_sent']
)->addForeignKey(
$installer->getFkName('sales_creditmemo', 'order_id', 'sales_order', 'entity_id'),
'order_id',
$installer->getTable('sales_order'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->addForeignKey(
$installer->getFkName('sales_creditmemo', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_SET_NULL
)->setComment(
'Sales Flat Creditmemo'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_creditmemo_grid'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_creditmemo_grid')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'increment_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
[],
'Increment Id'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
[],
'Created At'
)->addColumn(
'updated_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
[],
'Updated At'
)->addColumn(
'order_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Order Id'
)->addColumn(
'order_increment_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
[],
'Order Increment Id'
)->addColumn(
'order_created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
[],
'Order Created At'
)->addColumn(
'billing_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Billing Name'
)->addColumn(
'state',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Status'
)->addColumn(
'base_grand_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Grand Total'
)->addColumn(
'order_status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Order Status'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'billing_address',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Billing Address'
)->addColumn(
'shipping_address',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Shipping Address'
)->addColumn(
'customer_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
['nullable' => false],
'Customer Name'
)->addColumn(
'customer_email',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
[],
'Customer Email'
)->addColumn(
'customer_group_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
[],
'Customer Group Id'
)->addColumn(
'payment_method',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Payment Method'
)->addColumn(
'shipping_information',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Shipping Method Name'
)->addColumn(
'subtotal',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Subtotal'
)->addColumn(
'shipping_and_handling',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Shipping and handling amount'
)->addColumn(
'adjustment_positive',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Adjustment Positive'
)->addColumn(
'adjustment_negative',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Adjustment Negative'
)->addColumn(
'order_base_grand_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Order Grand Total'
)->addIndex(
$installer->getIdxName(
'sales_creditmemo_grid',
[
'increment_id',
'store_id'
],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['increment_id', 'store_id'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_creditmemo_grid', ['order_increment_id']),
['order_increment_id']
)->addIndex(
$installer->getIdxName('sales_creditmemo_grid', ['created_at']),
['created_at']
)->addIndex(
$installer->getIdxName('sales_creditmemo_grid', ['updated_at']),
['updated_at']
)->addIndex(
$installer->getIdxName('sales_creditmemo_grid', ['order_created_at']),
['order_created_at']
)->addIndex(
$installer->getIdxName('sales_creditmemo_grid', ['state']),
['state']
)->addIndex(
$installer->getIdxName('sales_creditmemo_grid', ['billing_name']),
['billing_name']
)->addIndex(
$installer->getIdxName('sales_creditmemo_grid', ['order_status']),
['order_status']
)->addIndex(
$installer->getIdxName('sales_creditmemo_grid', ['base_grand_total']),
['base_grand_total']
)->addIndex(
$installer->getIdxName('sales_creditmemo_grid', ['store_id']),
['store_id']
)->addIndex(
$installer->getIdxName('sales_creditmemo_grid', ['order_base_grand_total']),
['order_base_grand_total']
)->addIndex(
$installer->getIdxName('sales_creditmemo_grid', ['order_id']),
['order_id']
)->addIndex(
$installer->getIdxName(
'sales_creditmemo_grid',
[
'increment_id',
'order_increment_id',
'billing_name',
'billing_address',
'shipping_address',
'customer_name',
'customer_email'
],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
),
[
'increment_id',
'order_increment_id',
'billing_name',
'billing_address',
'shipping_address',
'customer_name',
'customer_email'
],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT]
)->setComment(
'Sales Flat Creditmemo Grid'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_creditmemo_item'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_creditmemo_item')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'parent_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Parent Id'
)->addColumn(
'base_price',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Price'
)->addColumn(
'tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Tax Amount'
)->addColumn(
'base_row_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Row Total'
)->addColumn(
'discount_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Amount'
)->addColumn(
'row_total',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Row Total'
)->addColumn(
'base_discount_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Amount'
)->addColumn(
'price_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Price Incl Tax'
)->addColumn(
'base_tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Tax Amount'
)->addColumn(
'base_price_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Price Incl Tax'
)->addColumn(
'qty',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Qty'
)->addColumn(
'base_cost',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Cost'
)->addColumn(
'price',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Price'
)->addColumn(
'base_row_total_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Row Total Incl Tax'
)->addColumn(
'row_total_incl_tax',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Row Total Incl Tax'
)->addColumn(
'product_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Product Id'
)->addColumn(
'order_item_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Order Item Id'
)->addColumn(
'additional_data',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Additional Data'
)->addColumn(
'description',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Description'
)->addColumn(
'sku',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Sku'
)->addColumn(
'name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Name'
)->addColumn(
'discount_tax_compensation_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Discount Tax Compensation Amount'
)->addColumn(
'base_discount_tax_compensation_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Discount Tax Compensation Amount'
)->addColumn(
'tax_ratio',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
512,
[],
'Ratio of tax in the creditmemo item over tax of the order item'
)->addIndex(
$installer->getIdxName('sales_creditmemo_item', ['parent_id']),
['parent_id']
)->addForeignKey(
$installer->getFkName('sales_creditmemo_item', 'parent_id', 'sales_creditmemo', 'entity_id'),
'parent_id',
$installer->getTable('sales_creditmemo'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Flat Creditmemo Item'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_creditmemo_comment'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_creditmemo_comment')
)->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Entity Id'
)->addColumn(
'parent_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Parent Id'
)->addColumn(
'is_customer_notified',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Is Customer Notified'
)->addColumn(
'is_visible_on_front',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Is Visible On Front'
)->addColumn(
'comment',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
[],
'Comment'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
'Created At'
)->addIndex(
$installer->getIdxName('sales_creditmemo_comment', ['created_at']),
['created_at']
)->addIndex(
$installer->getIdxName('sales_creditmemo_comment', ['parent_id']),
['parent_id']
)->addForeignKey(
$installer->getFkName('sales_creditmemo_comment', 'parent_id', 'sales_creditmemo', 'entity_id'),
'parent_id',
$installer->getTable('sales_creditmemo'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Flat Creditmemo Comment'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_invoiced_aggregated'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_invoiced_aggregated')
)->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)->addColumn(
'period',
\Magento\Framework\DB\Ddl\Table::TYPE_DATE,
null,
[],
'Period'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'order_status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
[],
'Order Status'
)->addColumn(
'orders_count',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['nullable' => false, 'default' => '0'],
'Orders Count'
)->addColumn(
'orders_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Orders Invoiced'
)->addColumn(
'invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Invoiced'
)->addColumn(
'invoiced_captured',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Invoiced Captured'
)->addColumn(
'invoiced_not_captured',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Invoiced Not Captured'
)->addIndex(
$installer->getIdxName(
'sales_invoiced_aggregated',
['period', 'store_id', 'order_status'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['period', 'store_id', 'order_status'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_invoiced_aggregated', ['store_id']),
['store_id']
)->addForeignKey(
$installer->getFkName('sales_invoiced_aggregated', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_SET_NULL
)->setComment(
'Sales Invoiced Aggregated'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_invoiced_aggregated_order'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_invoiced_aggregated_order')
)->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)->addColumn(
'period',
\Magento\Framework\DB\Ddl\Table::TYPE_DATE,
null,
[],
'Period'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'order_status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['nullable' => false, 'default' => false],
'Order Status'
)->addColumn(
'orders_count',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['nullable' => false, 'default' => '0'],
'Orders Count'
)->addColumn(
'orders_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Orders Invoiced'
)->addColumn(
'invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Invoiced'
)->addColumn(
'invoiced_captured',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Invoiced Captured'
)->addColumn(
'invoiced_not_captured',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Invoiced Not Captured'
)->addIndex(
$installer->getIdxName(
'sales_invoiced_aggregated_order',
['period', 'store_id', 'order_status'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['period', 'store_id', 'order_status'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_invoiced_aggregated_order', ['store_id']),
['store_id']
)->addForeignKey(
$installer->getFkName('sales_invoiced_aggregated_order', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_SET_NULL
)->setComment(
'Sales Invoiced Aggregated Order'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_order_aggregated_created'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_order_aggregated_created')
)->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)->addColumn(
'period',
\Magento\Framework\DB\Ddl\Table::TYPE_DATE,
null,
[],
'Period'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'order_status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['nullable' => false, 'default' => false],
'Order Status'
)->addColumn(
'orders_count',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['nullable' => false, 'default' => '0'],
'Orders Count'
)->addColumn(
'total_qty_ordered',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Total Qty Ordered'
)->addColumn(
'total_qty_invoiced',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Total Qty Invoiced'
)->addColumn(
'total_income_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Total Income Amount'
)->addColumn(
'total_revenue_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Total Revenue Amount'
)->addColumn(
'total_profit_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Total Profit Amount'
)->addColumn(
'total_invoiced_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Total Invoiced Amount'
)->addColumn(
'total_canceled_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Total Canceled Amount'
)->addColumn(
'total_paid_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Total Paid Amount'
)->addColumn(
'total_refunded_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Total Refunded Amount'
)->addColumn(
'total_tax_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Total Tax Amount'
)->addColumn(
'total_tax_amount_actual',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Total Tax Amount Actual'
)->addColumn(
'total_shipping_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Total Shipping Amount'
)->addColumn(
'total_shipping_amount_actual',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Total Shipping Amount Actual'
)->addColumn(
'total_discount_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Total Discount Amount'
)->addColumn(
'total_discount_amount_actual',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Total Discount Amount Actual'
)->addIndex(
$installer->getIdxName(
'sales_order_aggregated_created',
['period', 'store_id', 'order_status'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['period', 'store_id', 'order_status'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_order_aggregated_created', ['store_id']),
['store_id']
)->addForeignKey(
$installer->getFkName('sales_order_aggregated_created', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_SET_NULL
)->setComment(
'Sales Order Aggregated Created'
);
$installer->getConnection()->createTable($table);
$installer->getConnection()->createTable(
$installer->getConnection()->createTableByDdl(
$installer->getTable('sales_order_aggregated_created'),
$installer->getTable('sales_order_aggregated_updated')
)
);
/**
* Create table 'sales_payment_transaction'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_payment_transaction')
)->addColumn(
'transaction_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Transaction Id'
)->addColumn(
'parent_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true],
'Parent Id'
)->addColumn(
'order_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Order Id'
)->addColumn(
'payment_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Payment Id'
)->addColumn(
'txn_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
100,
[],
'Txn Id'
)->addColumn(
'parent_txn_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
100,
[],
'Parent Txn Id'
)->addColumn(
'txn_type',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
15,
[],
'Txn Type'
)->addColumn(
'is_closed',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '1'],
'Is Closed'
)->addColumn(
'additional_information',
\Magento\Framework\DB\Ddl\Table::TYPE_BLOB,
'64K',
[],
'Additional Information'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
'Created At'
)->addIndex(
$installer->getIdxName(
'sales_payment_transaction',
['order_id', 'payment_id', 'txn_id'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['order_id', 'payment_id', 'txn_id'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_payment_transaction', ['parent_id']),
['parent_id']
)->addIndex(
$installer->getIdxName('sales_payment_transaction', ['payment_id']),
['payment_id']
)->addForeignKey(
$installer->getFkName('sales_payment_transaction', 'order_id', 'sales_order', 'entity_id'),
'order_id',
$installer->getTable('sales_order'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->addForeignKey(
$installer->getFkName(
'sales_payment_transaction',
'parent_id',
'sales_payment_transaction',
'transaction_id'
),
'parent_id',
$installer->getTable('sales_payment_transaction'),
'transaction_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->addForeignKey(
$installer->getFkName('sales_payment_transaction', 'payment_id', 'sales_order_payment', 'entity_id'),
'payment_id',
$installer->getTable('sales_order_payment'),
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Payment Transaction'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_refunded_aggregated'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_refunded_aggregated')
)->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)->addColumn(
'period',
\Magento\Framework\DB\Ddl\Table::TYPE_DATE,
null,
[],
'Period'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'order_status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['nullable' => false, 'default' => false],
'Order Status'
)->addColumn(
'orders_count',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['nullable' => false, 'default' => '0'],
'Orders Count'
)->addColumn(
'refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Refunded'
)->addColumn(
'online_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Online Refunded'
)->addColumn(
'offline_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Offline Refunded'
)->addIndex(
$installer->getIdxName(
'sales_refunded_aggregated',
['period', 'store_id', 'order_status'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['period', 'store_id', 'order_status'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_refunded_aggregated', ['store_id']),
['store_id']
)->addForeignKey(
$installer->getFkName('sales_refunded_aggregated', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_SET_NULL
)->setComment(
'Sales Refunded Aggregated'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_refunded_aggregated_order'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_refunded_aggregated_order')
)->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)->addColumn(
'period',
\Magento\Framework\DB\Ddl\Table::TYPE_DATE,
null,
[],
'Period'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'order_status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
[],
'Order Status'
)->addColumn(
'orders_count',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['nullable' => false, 'default' => '0'],
'Orders Count'
)->addColumn(
'refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Refunded'
)->addColumn(
'online_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Online Refunded'
)->addColumn(
'offline_refunded',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Offline Refunded'
)->addIndex(
$installer->getIdxName(
'sales_refunded_aggregated_order',
['period', 'store_id', 'order_status'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['period', 'store_id', 'order_status'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_refunded_aggregated_order', ['store_id']),
['store_id']
)->addForeignKey(
$installer->getFkName('sales_refunded_aggregated_order', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_SET_NULL
)->setComment(
'Sales Refunded Aggregated Order'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_shipping_aggregated'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_shipping_aggregated')
)->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)->addColumn(
'period',
\Magento\Framework\DB\Ddl\Table::TYPE_DATE,
null,
[],
'Period'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'order_status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
[],
'Order Status'
)->addColumn(
'shipping_description',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Shipping Description'
)->addColumn(
'orders_count',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['nullable' => false, 'default' => '0'],
'Orders Count'
)->addColumn(
'total_shipping',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Shipping'
)->addColumn(
'total_shipping_actual',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Shipping Actual'
)->addIndex(
$installer->getIdxName(
'sales_shipping_aggregated',
['period', 'store_id', 'order_status', 'shipping_description'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['period', 'store_id', 'order_status', 'shipping_description'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_shipping_aggregated', ['store_id']),
['store_id']
)->addForeignKey(
$installer->getFkName('sales_shipping_aggregated', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_SET_NULL
)->setComment(
'Sales Shipping Aggregated'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_shipping_aggregated_order'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_shipping_aggregated_order')
)->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)->addColumn(
'period',
\Magento\Framework\DB\Ddl\Table::TYPE_DATE,
null,
[],
'Period'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'order_status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
[],
'Order Status'
)->addColumn(
'shipping_description',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Shipping Description'
)->addColumn(
'orders_count',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['nullable' => false, 'default' => '0'],
'Orders Count'
)->addColumn(
'total_shipping',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Shipping'
)->addColumn(
'total_shipping_actual',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Total Shipping Actual'
)->addIndex(
$installer->getIdxName(
'sales_shipping_aggregated_order',
['period', 'store_id', 'order_status', 'shipping_description'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['period', 'store_id', 'order_status', 'shipping_description'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_shipping_aggregated_order', ['store_id']),
['store_id']
)->addForeignKey(
$installer->getFkName('sales_shipping_aggregated_order', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_SET_NULL
)->setComment(
'Sales Shipping Aggregated Order'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_bestsellers_aggregated_daily'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_bestsellers_aggregated_daily')
)->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)->addColumn(
'period',
\Magento\Framework\DB\Ddl\Table::TYPE_DATE,
null,
[],
'Period'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'product_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true],
'Product Id'
)->addColumn(
'product_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
['nullable' => true],
'Product Name'
)->addColumn(
'product_price',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Product Price'
)->addColumn(
'qty_ordered',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Qty Ordered'
)->addColumn(
'rating_pos',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Rating Pos'
)->addIndex(
$installer->getIdxName(
'sales_bestsellers_aggregated_daily',
['period', 'store_id', 'product_id'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['period', 'store_id', 'product_id'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_bestsellers_aggregated_daily', ['store_id']),
['store_id']
)->addIndex(
$installer->getIdxName('sales_bestsellers_aggregated_daily', ['product_id']),
['product_id']
)->addForeignKey(
$installer->getFkName('sales_bestsellers_aggregated_daily', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Bestsellers Aggregated Daily'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_bestsellers_aggregated_monthly'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_bestsellers_aggregated_monthly')
)->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)->addColumn(
'period',
\Magento\Framework\DB\Ddl\Table::TYPE_DATE,
null,
[],
'Period'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'product_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true],
'Product Id'
)->addColumn(
'product_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
['nullable' => true],
'Product Name'
)->addColumn(
'product_price',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Product Price'
)->addColumn(
'qty_ordered',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Qty Ordered'
)->addColumn(
'rating_pos',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Rating Pos'
)->addIndex(
$installer->getIdxName(
'sales_bestsellers_aggregated_monthly',
['period', 'store_id', 'product_id'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['period', 'store_id', 'product_id'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_bestsellers_aggregated_monthly', ['store_id']),
['store_id']
)->addIndex(
$installer->getIdxName('sales_bestsellers_aggregated_monthly', ['product_id']),
['product_id']
)->addForeignKey(
$installer->getFkName('sales_bestsellers_aggregated_monthly', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Bestsellers Aggregated Monthly'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_bestsellers_aggregated_yearly'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_bestsellers_aggregated_yearly')
)->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)->addColumn(
'period',
\Magento\Framework\DB\Ddl\Table::TYPE_DATE,
null,
[],
'Period'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true],
'Store Id'
)->addColumn(
'product_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true],
'Product Id'
)->addColumn(
'product_name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
['nullable' => true],
'Product Name'
)->addColumn(
'product_price',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Product Price'
)->addColumn(
'qty_ordered',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false, 'default' => '0.0000'],
'Qty Ordered'
)->addColumn(
'rating_pos',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Rating Pos'
)->addIndex(
$installer->getIdxName(
'sales_bestsellers_aggregated_yearly',
['period', 'store_id', 'product_id'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['period', 'store_id', 'product_id'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addIndex(
$installer->getIdxName('sales_bestsellers_aggregated_yearly', ['store_id']),
['store_id']
)->addIndex(
$installer->getIdxName('sales_bestsellers_aggregated_yearly', ['product_id']),
['product_id']
)->addForeignKey(
$installer->getFkName('sales_bestsellers_aggregated_yearly', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Bestsellers Aggregated Yearly'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_order_tax'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_order_tax')
)->addColumn(
'tax_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Tax Id'
)->addColumn(
'order_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Order Id'
)->addColumn(
'code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Code'
)->addColumn(
'title',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[],
'Title'
)->addColumn(
'percent',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Percent'
)->addColumn(
'amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Amount'
)->addColumn(
'priority',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['nullable' => false],
'Priority'
)->addColumn(
'position',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['nullable' => false],
'Position'
)->addColumn(
'base_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Amount'
)->addColumn(
'process',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['nullable' => false],
'Process'
)->addColumn(
'base_real_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
[],
'Base Real Amount'
)->addIndex(
$installer->getIdxName('sales_order_tax', ['order_id', 'priority', 'position']),
['order_id', 'priority', 'position']
)->setComment(
'Sales Order Tax Table'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_order_tax_item'
*/
$table = $setup->getConnection()->newTable(
$setup->getTable('sales_order_tax_item')
)->addColumn(
'tax_item_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Tax Item Id'
)->addColumn(
'tax_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Tax Id'
)->addColumn(
'item_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => true],
'Item Id'
)->addColumn(
'tax_percent',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false],
'Real Tax Percent For Item'
)->addColumn(
'amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false],
'Tax amount for the item and tax rate'
)->addColumn(
'base_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false],
'Base tax amount for the item and tax rate'
)->addColumn(
'real_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false],
'Real tax amount for the item and tax rate'
)->addColumn(
'real_base_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'12,4',
['nullable' => false],
'Real base tax amount for the item and tax rate'
)->addColumn(
'associated_item_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['nullable' => true, 'unsigned' => true],
'Id of the associated item'
)->addColumn(
'taxable_item_type',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
['nullable' => false],
'Type of the taxable item'
)->addIndex(
$setup->getIdxName('sales_order_tax_item', ['item_id']),
['item_id']
)->addIndex(
$setup->getIdxName(
'sales_order_tax_item',
['tax_id', 'item_id'],
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
),
['tax_id', 'item_id'],
['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
)->addForeignKey(
$setup->getFkName('sales_order_tax_item', 'associated_item_id', 'sales_order_item', 'item_id'),
'associated_item_id',
$setup->getTable('sales_order_item'),
'item_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->addForeignKey(
$setup->getFkName('sales_order_tax_item', 'tax_id', 'sales_order_tax', 'tax_id'),
'tax_id',
$setup->getTable('sales_order_tax'),
'tax_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->addForeignKey(
$setup->getFkName('sales_order_tax_item', 'item_id', 'sales_order_item', 'item_id'),
'item_id',
$setup->getTable('sales_order_item'),
'item_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Order Tax Item'
);
$setup->getConnection()->createTable($table);
/**
* Create table 'sales_order_status'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_order_status')
)->addColumn(
'status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
['nullable' => false, 'primary' => true],
'Status'
)->addColumn(
'label',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
['nullable' => false],
'Label'
)->setComment(
'Sales Order Status Table'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_order_status_state'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_order_status_state')
)->addColumn(
'status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
['nullable' => false, 'primary' => true],
'Status'
)->addColumn(
'state',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
['nullable' => false, 'primary' => true],
'Label'
)->addColumn(
'is_default',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Is Default'
)->addColumn(
'visible_on_front',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
1,
['unsigned' => true, 'nullable' => false, 'default' => '0'],
'Visible on front'
)->addForeignKey(
$installer->getFkName('sales_order_status_state', 'status', 'sales_order_status', 'status'),
'status',
$installer->getTable('sales_order_status'),
'status',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Order Status Table'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'sales_order_status_label'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('sales_order_status_label')
)->addColumn(
'status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
['nullable' => false, 'primary' => true],
'Status'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'primary' => true],
'Store Id'
)->addColumn(
'label',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
['nullable' => false],
'Label'
)->addIndex(
$installer->getIdxName('sales_order_status_label', ['store_id']),
['store_id']
)->addForeignKey(
$installer->getFkName('sales_order_status_label', 'status', 'sales_order_status', 'status'),
'status',
$installer->getTable('sales_order_status'),
'status',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->addForeignKey(
$installer->getFkName('sales_order_status_label', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Sales Order Status Label Table'
);
$installer->getConnection()->createTable($table);
$installer->endSetup();
}
}
| j-froehlich/magento2_wk | vendor/magento/module-sales/Setup/InstallSchema.php | PHP | mit | 184,211 |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osuTK;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Input.Events;
using osu.Game.Rulesets;
using osu.Framework.Input.Bindings;
using osu.Game.Input.Bindings;
namespace osu.Game.Overlays.Toolbar
{
public class Toolbar : VisibilityContainer, IKeyBindingHandler<GlobalAction>
{
public const float HEIGHT = 40;
public const float TOOLTIP_HEIGHT = 30;
/// <summary>
/// Whether the user hid this <see cref="Toolbar"/> with <see cref="GlobalAction.ToggleToolbar"/>.
/// In this state, automatic toggles should not occur, respecting the user's preference to have no toolbar.
/// </summary>
private bool hiddenByUser;
public Action OnHome;
private ToolbarUserButton userButton;
private ToolbarRulesetSelector rulesetSelector;
private const double transition_time = 500;
protected readonly IBindable<OverlayActivation> OverlayActivationMode = new Bindable<OverlayActivation>(OverlayActivation.All);
// Toolbar and its components need keyboard input even when hidden.
public override bool PropagateNonPositionalInputSubTree => true;
public Toolbar()
{
RelativeSizeAxes = Axes.X;
Size = new Vector2(1, HEIGHT);
AlwaysPresent = true;
}
protected override void UpdateAfterChildren()
{
base.UpdateAfterChildren();
// this only needed to be set for the initial LoadComplete/Update, so layout completes and gets buttons in a state they can correctly handle keyboard input for hotkeys.
AlwaysPresent = false;
}
[BackgroundDependencyLoader(true)]
private void load(OsuGame osuGame, Bindable<RulesetInfo> parentRuleset)
{
Children = new Drawable[]
{
new ToolbarBackground(),
new FillFlowContainer
{
Direction = FillDirection.Horizontal,
RelativeSizeAxes = Axes.Y,
AutoSizeAxes = Axes.X,
Children = new Drawable[]
{
new ToolbarSettingsButton(),
new ToolbarHomeButton
{
Action = () => OnHome?.Invoke()
},
rulesetSelector = new ToolbarRulesetSelector()
}
},
new FillFlowContainer
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Direction = FillDirection.Horizontal,
RelativeSizeAxes = Axes.Y,
AutoSizeAxes = Axes.X,
Children = new Drawable[]
{
new ToolbarNewsButton(),
new ToolbarChangelogButton(),
new ToolbarRankingsButton(),
new ToolbarBeatmapListingButton(),
new ToolbarChatButton(),
new ToolbarSocialButton(),
new ToolbarWikiButton(),
new ToolbarMusicButton(),
//new ToolbarButton
//{
// Icon = FontAwesome.Solid.search
//},
userButton = new ToolbarUserButton(),
new ToolbarNotificationButton(),
}
}
};
// Bound after the selector is added to the hierarchy to give it a chance to load the available rulesets
rulesetSelector.Current.BindTo(parentRuleset);
if (osuGame != null)
OverlayActivationMode.BindTo(osuGame.OverlayActivationMode);
}
public class ToolbarBackground : Container
{
private readonly Box gradientBackground;
public ToolbarBackground()
{
RelativeSizeAxes = Axes.Both;
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.Gray(0.1f),
},
gradientBackground = new Box
{
RelativeSizeAxes = Axes.X,
Anchor = Anchor.BottomLeft,
Alpha = 0,
Height = 100,
Colour = ColourInfo.GradientVertical(
OsuColour.Gray(0).Opacity(0.9f), OsuColour.Gray(0).Opacity(0)),
},
};
}
protected override bool OnHover(HoverEvent e)
{
gradientBackground.FadeIn(transition_time, Easing.OutQuint);
return true;
}
protected override void OnHoverLost(HoverLostEvent e)
{
gradientBackground.FadeOut(transition_time, Easing.OutQuint);
}
}
protected override void UpdateState(ValueChangedEvent<Visibility> state)
{
bool blockShow = hiddenByUser || OverlayActivationMode.Value == OverlayActivation.Disabled;
if (state.NewValue == Visibility.Visible && blockShow)
{
State.Value = Visibility.Hidden;
return;
}
base.UpdateState(state);
}
protected override void PopIn()
{
this.MoveToY(0, transition_time, Easing.OutQuint);
this.FadeIn(transition_time / 4, Easing.OutQuint);
}
protected override void PopOut()
{
userButton.StateContainer?.Hide();
this.MoveToY(-DrawSize.Y, transition_time, Easing.OutQuint);
this.FadeOut(transition_time, Easing.InQuint);
}
public bool OnPressed(GlobalAction action)
{
if (OverlayActivationMode.Value == OverlayActivation.Disabled)
return false;
switch (action)
{
case GlobalAction.ToggleToolbar:
hiddenByUser = State.Value == Visibility.Visible; // set before toggling to allow the operation to always succeed.
ToggleVisibility();
return true;
}
return false;
}
public void OnReleased(GlobalAction action)
{
}
}
}
| UselessToucan/osu | osu.Game/Overlays/Toolbar/Toolbar.cs | C# | mit | 7,041 |
(function() {
'use strict';
angular
.module('echarliApp')
.factory('Activate', Activate);
Activate.$inject = ['$resource'];
function Activate ($resource) {
var service = $resource('api/activate', {}, {
'get': { method: 'GET', params: {}, isArray: false}
});
return service;
}
})();
| dilosung/ad-manage | ad_manage/static/js/app/services/auth/activate.service.js | JavaScript | mit | 358 |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M22 11h-5V6h-3v5h-4V3H7v8H1.84v2H7v8h3v-8h4v5h3v-5h5z"
}), 'AlignVerticalCenterOutlined');
exports.default = _default; | oliviertassinari/material-ui | packages/mui-icons-material/lib/AlignVerticalCenterOutlined.js | JavaScript | mit | 536 |
package org.spongycastle.openssl.jcajce;
import java.io.IOException;
import java.io.OutputStream;
import java.security.AlgorithmParameterGenerator;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.Provider;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import org.spongycastle.asn1.ASN1EncodableVector;
import org.spongycastle.asn1.ASN1Integer;
import org.spongycastle.asn1.ASN1ObjectIdentifier;
import org.spongycastle.asn1.ASN1Primitive;
import org.spongycastle.asn1.DEROctetString;
import org.spongycastle.asn1.DERSequence;
import org.spongycastle.asn1.nist.NISTObjectIdentifiers;
import org.spongycastle.asn1.pkcs.KeyDerivationFunc;
import org.spongycastle.asn1.pkcs.PBES2Parameters;
import org.spongycastle.asn1.pkcs.PBKDF2Params;
import org.spongycastle.asn1.pkcs.PKCS12PBEParams;
import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.spongycastle.asn1.x509.AlgorithmIdentifier;
import org.spongycastle.jcajce.PKCS12KeyWithParameters;
import org.spongycastle.jcajce.util.DefaultJcaJceHelper;
import org.spongycastle.jcajce.util.JcaJceHelper;
import org.spongycastle.jcajce.util.NamedJcaJceHelper;
import org.spongycastle.jcajce.util.ProviderJcaJceHelper;
import org.spongycastle.operator.GenericKey;
import org.spongycastle.operator.OperatorCreationException;
import org.spongycastle.operator.OutputEncryptor;
import org.spongycastle.operator.jcajce.JceGenericKey;
public class JceOpenSSLPKCS8EncryptorBuilder
{
public static final String AES_128_CBC = NISTObjectIdentifiers.id_aes128_CBC.getId();
public static final String AES_192_CBC = NISTObjectIdentifiers.id_aes192_CBC.getId();
public static final String AES_256_CBC = NISTObjectIdentifiers.id_aes256_CBC.getId();
public static final String DES3_CBC = PKCSObjectIdentifiers.des_EDE3_CBC.getId();
public static final String PBE_SHA1_RC4_128 = PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC4.getId();
public static final String PBE_SHA1_RC4_40 = PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC4.getId();
public static final String PBE_SHA1_3DES = PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC.getId();
public static final String PBE_SHA1_2DES = PKCSObjectIdentifiers.pbeWithSHAAnd2_KeyTripleDES_CBC.getId();
public static final String PBE_SHA1_RC2_128 = PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC.getId();
public static final String PBE_SHA1_RC2_40 = PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC.getId();
private JcaJceHelper helper = new DefaultJcaJceHelper();
private AlgorithmParameters params;
private ASN1ObjectIdentifier algOID;
byte[] salt;
int iterationCount;
private Cipher cipher;
private SecureRandom random;
private AlgorithmParameterGenerator paramGen;
private char[] password;
private SecretKey key;
public JceOpenSSLPKCS8EncryptorBuilder(ASN1ObjectIdentifier algorithm)
{
algOID = algorithm;
this.iterationCount = 2048;
}
public JceOpenSSLPKCS8EncryptorBuilder setRandom(SecureRandom random)
{
this.random = random;
return this;
}
public JceOpenSSLPKCS8EncryptorBuilder setPasssword(char[] password)
{
this.password = password;
return this;
}
public JceOpenSSLPKCS8EncryptorBuilder setIterationCount(int iterationCount)
{
this.iterationCount = iterationCount;
return this;
}
public JceOpenSSLPKCS8EncryptorBuilder setProvider(String providerName)
{
helper = new NamedJcaJceHelper(providerName);
return this;
}
public JceOpenSSLPKCS8EncryptorBuilder setProvider(Provider provider)
{
helper = new ProviderJcaJceHelper(provider);
return this;
}
public OutputEncryptor build()
throws OperatorCreationException
{
final AlgorithmIdentifier algID;
salt = new byte[20];
if (random == null)
{
random = new SecureRandom();
}
random.nextBytes(salt);
try
{
this.cipher = helper.createCipher(algOID.getId());
if (PEMUtilities.isPKCS5Scheme2(algOID))
{
this.paramGen = helper.createAlgorithmParameterGenerator(algOID.getId());
}
}
catch (GeneralSecurityException e)
{
throw new OperatorCreationException(algOID + " not available: " + e.getMessage(), e);
}
if (PEMUtilities.isPKCS5Scheme2(algOID))
{
params = paramGen.generateParameters();
try
{
KeyDerivationFunc scheme = new KeyDerivationFunc(algOID, ASN1Primitive.fromByteArray(params.getEncoded()));
KeyDerivationFunc func = new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(salt, iterationCount));
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(func);
v.add(scheme);
algID = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, PBES2Parameters.getInstance(new DERSequence(v)));
}
catch (IOException e)
{
throw new OperatorCreationException(e.getMessage(), e);
}
try
{
key = PEMUtilities.generateSecretKeyForPKCS5Scheme2(helper, algOID.getId(), password, salt, iterationCount);
cipher.init(Cipher.ENCRYPT_MODE, key, params);
}
catch (GeneralSecurityException e)
{
throw new OperatorCreationException(e.getMessage(), e);
}
}
else if (PEMUtilities.isPKCS12(algOID))
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DEROctetString(salt));
v.add(new ASN1Integer(iterationCount));
algID = new AlgorithmIdentifier(algOID, PKCS12PBEParams.getInstance(new DERSequence(v)));
try
{
cipher.init(Cipher.ENCRYPT_MODE, new PKCS12KeyWithParameters(password, salt, iterationCount));
}
catch (GeneralSecurityException e)
{
throw new OperatorCreationException(e.getMessage(), e);
}
}
else
{
throw new OperatorCreationException("unknown algorithm: " + algOID, null);
}
return new OutputEncryptor()
{
public AlgorithmIdentifier getAlgorithmIdentifier()
{
return algID;
}
public OutputStream getOutputStream(OutputStream encOut)
{
return new CipherOutputStream(encOut, cipher);
}
public GenericKey getKey()
{
return new JceGenericKey(algID, key);
}
};
}
}
| open-keychain/spongycastle | pkix/src/main/java/org/spongycastle/openssl/jcajce/JceOpenSSLPKCS8EncryptorBuilder.java | Java | mit | 6,994 |
// conf.js
exports.config = {
seleniumServerJar: "./node_modules/protractor/selenium/selenium-server-standalone-2.45.0.jar",
specs: ["test/e2e/*.scenarios.coffee"],
baseUrl: "http://localhost:3000",
capabilities: {
"browserName": "chrome"
},
framework: "mocha"
}
| doug-wade/generator-koa-angular | app/templates/protractor.conf.js | JavaScript | mit | 279 |
def linear_search(lst,size,value):
i = 0
while i < size:
if lst[i] == value:
return i
i = i + 1
return -1
def main():
lst = [-31, 0, 1, 2, 2, 4, 65, 83, 99, 782]
size = len(lst)
original_list = ""
value = int(input("\nInput a value to search for: "))
print("\nOriginal Array: ")
for i in lst:
original_list += str(i) + " "
print(original_list)
print("\nLinear Search Big O Notation:\n--> Best Case: O(1)\n--> Average Case: O(n)\n--> Worst Case: O(n)\n")
index = linear_search(lst,size,value)
if index == -1:
print(str(value) + " was not found in that array\n")
else:
print(str(value) + " was found at index " + str(index))
if __name__ == '__main__':
main()
| EverythingAbout/Python | Searches/linear_search.py | Python | mit | 775 |
// This file is part of the VroomJs library.
//
// Author:
// Federico Di Gregorio <fog@initd.org>
//
// Copyright (c) 2013
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using VroomJs;
namespace Sandbox
{
class Sandbox
{
public static void Main (string[] args)
{
using (JsEngine js = new JsEngine()) {
for (int i=0 ; i < 10 ; i++) {
js.SetVariable("a", new Simple { N = i, S = (i*10).ToString() });
Console.WriteLine(js.Execute("a.N+' '+a.S"));
}
Console.WriteLine(js.Execute("a.N+' '+a.X"));
}
}
}
class Simple
{
public int N { get; set; }
public string S { get; set; }
public string X {
get { throw new InvalidOperationException("ahr ahr"); }
}
}
}
| fogzot/vroomjs | Sandbox/Sandbox.cs | C# | mit | 1,907 |
# Analyze Color of Object
import os
import cv2
import numpy as np
from . import print_image
from . import plot_image
from . import fatal_error
from . import plot_colorbar
def _pseudocolored_image(device, histogram, bins, img, mask, background, channel, filename, resolution,
analysis_images, debug):
"""Pseudocolor image.
Inputs:
histogram = a normalized histogram of color values from one color channel
bins = number of color bins the channel is divided into
img = input image
mask = binary mask image
background = what background image?: channel image (img) or white
channel = color channel name
filename = input image filename
resolution = output image resolution
analysis_images = list of analysis image filenames
debug = print or plot. Print = save to file, Plot = print to screen.
Returns:
analysis_images = list of analysis image filenames
:param histogram: list
:param bins: int
:param img: numpy array
:param mask: numpy array
:param background: str
:param channel: str
:param filename: str
:param resolution: int
:param analysis_images: list
:return analysis_images: list
"""
mask_inv = cv2.bitwise_not(mask)
cplant = cv2.applyColorMap(histogram, colormap=2)
cplant1 = cv2.bitwise_and(cplant, cplant, mask=mask)
output_imgs = {"pseudo_on_img": {"background": "img", "img": None},
"pseudo_on_white": {"background": "white", "img": None}}
if background == 'img' or background == 'both':
# mask the background and color the plant with color scheme 'jet'
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_back = cv2.bitwise_and(img_gray, img_gray, mask=mask_inv)
img_back3 = np.dstack((img_back, img_back, img_back))
output_imgs["pseudo_on_img"]["img"] = cv2.add(cplant1, img_back3)
if background == 'white' or background == 'both':
# Get the image size
if np.shape(img)[2] == 3:
ix, iy, iz = np.shape(img)
else:
ix, iy = np.shape(img)
size = ix, iy
back = np.zeros(size, dtype=np.uint8)
w_back = back + 255
w_back3 = np.dstack((w_back, w_back, w_back))
img_back3 = cv2.bitwise_and(w_back3, w_back3, mask=mask_inv)
output_imgs["pseudo_on_white"]["img"] = cv2.add(cplant1, img_back3)
if filename:
for key in output_imgs:
if output_imgs[key]["img"] is not None:
fig_name_pseudo = str(filename[0:-4]) + '_' + str(channel) + '_pseudo_on_' + \
output_imgs[key]["background"] + '.jpg'
path = os.path.dirname(filename)
print_image(output_imgs[key]["img"], fig_name_pseudo)
analysis_images.append(['IMAGE', 'pseudo', fig_name_pseudo])
else:
path = "."
if debug is not None:
if debug == 'print':
for key in output_imgs:
if output_imgs[key]["img"] is not None:
print_image(output_imgs[key]["img"], (str(device) + "_" + output_imgs[key]["background"] +
'_pseudocolor.jpg'))
fig_name = 'VIS_pseudocolor_colorbar_' + str(channel) + '_channel.svg'
if not os.path.isfile(os.path.join(path, fig_name)):
plot_colorbar(path, fig_name, bins)
elif debug == 'plot':
for key in output_imgs:
if output_imgs[key]["img"] is not None:
plot_image(output_imgs[key]["img"])
return analysis_images
def analyze_color(img, imgname, mask, bins, device, debug=None, hist_plot_type=None, pseudo_channel='v',
pseudo_bkg='img', resolution=300, filename=False):
"""Analyze the color properties of an image object
Inputs:
img = image
imgname = name of input image
mask = mask made from selected contours
device = device number. Used to count steps in the pipeline
debug = None, print, or plot. Print = save to file, Plot = print to screen.
hist_plot_type = 'None', 'all', 'rgb','lab' or 'hsv'
color_slice_type = 'None', 'rgb', 'hsv' or 'lab'
pseudo_channel = 'None', 'l', 'm' (green-magenta), 'y' (blue-yellow), h','s', or 'v', creates pseduocolored image
based on the specified channel
pseudo_bkg = 'img' => channel image, 'white' => white background image, 'both' => both img and white options
filename = False or image name. If defined print image
Returns:
device = device number
hist_header = color histogram data table headers
hist_data = color histogram data table values
analysis_images = list of output images
:param img: numpy array
:param imgname: str
:param mask: numpy array
:param bins: int
:param device: int
:param debug: str
:param hist_plot_type: str
:param pseudo_channel: str
:param pseudo_bkg: str
:param resolution: int
:param filename: str
:return device: int
:return hist_header: list
:return hist_data: list
:return analysis_images: list
"""
device += 1
masked = cv2.bitwise_and(img, img, mask=mask)
b, g, r = cv2.split(masked)
lab = cv2.cvtColor(masked, cv2.COLOR_BGR2LAB)
l, m, y = cv2.split(lab)
hsv = cv2.cvtColor(masked, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
# Color channel dictionary
norm_channels = {"b": b / (256 / bins),
"g": g / (256 / bins),
"r": r / (256 / bins),
"l": l / (256 / bins),
"m": m / (256 / bins),
"y": y / (256 / bins),
"h": h / (256 / bins),
"s": s / (256 / bins),
"v": v / (256 / bins)
}
# Histogram plot types
hist_types = {"all": ("b", "g", "r", "l", "m", "y", "h", "s", "v"),
"rgb": ("b", "g", "r"),
"lab": ("l", "m", "y"),
"hsv": ("h", "s", "v")}
# If the user-input pseudo_channel is not None and is not found in the list of accepted channels, exit
if pseudo_channel is not None and pseudo_channel not in norm_channels:
fatal_error("Pseudocolor channel was " + str(pseudo_channel) +
', but can only be one of the following: None, "l", "m", "y", "h", "s" or "v"!')
# If the user-input pseudocolored image background is not in the accepted input list, exit
if pseudo_bkg not in ["white", "img", "both"]:
fatal_error("The pseudocolored image background was " + str(pseudo_bkg) +
', but can only be one of the following: "white", "img", or "both"!')
# If the user-input histogram color-channel plot type is not in the list of accepted channels, exit
if hist_plot_type is not None and hist_plot_type not in hist_types:
fatal_error("The histogram plot type was " + str(hist_plot_type) +
', but can only be one of the following: None, "all", "rgb", "lab", or "hsv"!')
histograms = {
"b": {"label": "blue", "graph_color": "blue",
"hist": cv2.calcHist([norm_channels["b"]], [0], mask, [bins], [0, (bins - 1)])},
"g": {"label": "green", "graph_color": "forestgreen",
"hist": cv2.calcHist([norm_channels["g"]], [0], mask, [bins], [0, (bins - 1)])},
"r": {"label": "red", "graph_color": "red",
"hist": cv2.calcHist([norm_channels["r"]], [0], mask, [bins], [0, (bins - 1)])},
"l": {"label": "lightness", "graph_color": "dimgray",
"hist": cv2.calcHist([norm_channels["l"]], [0], mask, [bins], [0, (bins - 1)])},
"m": {"label": "green-magenta", "graph_color": "magenta",
"hist": cv2.calcHist([norm_channels["m"]], [0], mask, [bins], [0, (bins - 1)])},
"y": {"label": "blue-yellow", "graph_color": "yellow",
"hist": cv2.calcHist([norm_channels["y"]], [0], mask, [bins], [0, (bins - 1)])},
"h": {"label": "hue", "graph_color": "blueviolet",
"hist": cv2.calcHist([norm_channels["h"]], [0], mask, [bins], [0, (bins - 1)])},
"s": {"label": "saturation", "graph_color": "cyan",
"hist": cv2.calcHist([norm_channels["s"]], [0], mask, [bins], [0, (bins - 1)])},
"v": {"label": "value", "graph_color": "orange",
"hist": cv2.calcHist([norm_channels["v"]], [0], mask, [bins], [0, (bins - 1)])}
}
hist_data_b = [l[0] for l in histograms["b"]["hist"]]
hist_data_g = [l[0] for l in histograms["g"]["hist"]]
hist_data_r = [l[0] for l in histograms["r"]["hist"]]
hist_data_l = [l[0] for l in histograms["l"]["hist"]]
hist_data_m = [l[0] for l in histograms["m"]["hist"]]
hist_data_y = [l[0] for l in histograms["y"]["hist"]]
hist_data_h = [l[0] for l in histograms["h"]["hist"]]
hist_data_s = [l[0] for l in histograms["s"]["hist"]]
hist_data_v = [l[0] for l in histograms["v"]["hist"]]
binval = np.arange(0, bins)
bin_values = [l for l in binval]
# Store Color Histogram Data
hist_header = [
'HEADER_HISTOGRAM',
'bin-number',
'bin-values',
'blue',
'green',
'red',
'lightness',
'green-magenta',
'blue-yellow',
'hue',
'saturation',
'value'
]
hist_data = [
'HISTOGRAM_DATA',
bins,
bin_values,
hist_data_b,
hist_data_g,
hist_data_r,
hist_data_l,
hist_data_m,
hist_data_y,
hist_data_h,
hist_data_s,
hist_data_v
]
analysis_images = []
if pseudo_channel is not None:
analysis_images = _pseudocolored_image(device, norm_channels[pseudo_channel], bins, img, mask, pseudo_bkg,
pseudo_channel, filename, resolution, analysis_images, debug)
if hist_plot_type is not None and filename:
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
# Create Histogram Plot
for channel in hist_types[hist_plot_type]:
plt.plot(histograms[channel]["hist"], color=histograms[channel]["graph_color"],
label=histograms[channel]["label"])
plt.xlim([0, bins - 1])
plt.legend()
# Print plot
fig_name = (str(filename[0:-4]) + '_' + str(hist_plot_type) + '_hist.svg')
plt.savefig(fig_name)
analysis_images.append(['IMAGE', 'hist', fig_name])
if debug == 'print':
fig_name = (str(device) + '_' + str(hist_plot_type) + '_hist.svg')
plt.savefig(fig_name)
plt.clf()
return device, hist_header, hist_data, analysis_images
| AntonSax/plantcv | plantcv/analyze_color.py | Python | mit | 11,048 |
<?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.
*/
declare(strict_types=1);
namespace Sylius\Behat\Context\Ui\Admin;
use Behat\Behat\Context\Context;
use Sylius\Behat\NotificationType;
use Sylius\Behat\Page\Admin\Crud\IndexPageInterface;
use Sylius\Behat\Page\Admin\PromotionCoupon\CreatePageInterface;
use Sylius\Behat\Page\Admin\PromotionCoupon\GeneratePageInterface;
use Sylius\Behat\Page\Admin\PromotionCoupon\UpdatePageInterface;
use Sylius\Behat\Service\NotificationCheckerInterface;
use Sylius\Behat\Service\Resolver\CurrentPageResolverInterface;
use Sylius\Component\Core\Model\PromotionCouponInterface;
use Sylius\Component\Promotion\Model\PromotionInterface;
use Webmozart\Assert\Assert;
final class ManagingPromotionCouponsContext implements Context
{
/** @var CreatePageInterface */
private $createPage;
/** @var GeneratePageInterface */
private $generatePage;
/** @var IndexPageInterface */
private $indexPage;
/** @var UpdatePageInterface */
private $updatePage;
/** @var CurrentPageResolverInterface */
private $currentPageResolver;
/** @var NotificationCheckerInterface */
private $notificationChecker;
public function __construct(
CreatePageInterface $createPage,
GeneratePageInterface $generatePage,
IndexPageInterface $indexPage,
UpdatePageInterface $updatePage,
CurrentPageResolverInterface $currentPageResolver,
NotificationCheckerInterface $notificationChecker
) {
$this->createPage = $createPage;
$this->generatePage = $generatePage;
$this->indexPage = $indexPage;
$this->updatePage = $updatePage;
$this->currentPageResolver = $currentPageResolver;
$this->notificationChecker = $notificationChecker;
}
/**
* @Given /^I browse coupons of (this promotion)$/
* @Given /^I want to view all coupons of (this promotion)$/
* @When /^I browse all coupons of ("[^"]+" promotion)$/
*/
public function iWantToViewAllCouponsOfThisPromotion(PromotionInterface $promotion)
{
$this->indexPage->open(['promotionId' => $promotion->getId()]);
}
/**
* @Given /^I want to create a new coupon for (this promotion)$/
*/
public function iWantToCreateANewCouponForThisPromotion(PromotionInterface $promotion)
{
$this->createPage->open(['promotionId' => $promotion->getId()]);
}
/**
* @Given /^I want to modify the ("[^"]+" coupon) for (this promotion)$/
*/
public function iWantToModifyTheCoupon(PromotionCouponInterface $coupon, PromotionInterface $promotion)
{
$this->updatePage->open(['id' => $coupon->getId(), 'promotionId' => $promotion->getId()]);
}
/**
* @Given /^I want to generate a new coupons for (this promotion)$/
*/
public function iWantToGenerateANewCouponsForThisPromotion(PromotionInterface $promotion)
{
$this->generatePage->open(['promotionId' => $promotion->getId()]);
}
/**
* @When /^I specify its code length as (\d+)$/
* @When I do not specify its code length
*/
public function iSpecifyItsCodeLengthAs($codeLength = null)
{
$this->generatePage->specifyCodeLength($codeLength);
}
/**
* @When /^I limit generated coupons usage to (\d+) times$/
*/
public function iSetGeneratedCouponsUsageLimitTo($limit)
{
$this->generatePage->setUsageLimit($limit);
}
/**
* @When I make generated coupons valid until :date
*/
public function iMakeGeneratedCouponsValidUntil(\DateTimeInterface $date)
{
$this->generatePage->setExpiresAt($date);
}
/**
* @When I specify its code as :code
* @When I do not specify its code
*/
public function iSpecifyItsCodeAs($code = null)
{
$this->createPage->specifyCode($code);
}
/**
* @When I limit its usage to :limit times
*/
public function iLimitItsUsageLimitTo($limit)
{
$this->createPage->setUsageLimit($limit);
}
/**
* @When I change its usage limit to :limit
*/
public function iChangeItsUsageLimitTo($limit)
{
$this->updatePage->setUsageLimit($limit);
}
/**
* @When I specify its amount as :amount
* @When I do not specify its amount
*/
public function iSpecifyItsAmountAs($amount = null)
{
$this->generatePage->specifyAmount($amount);
}
/**
* @When I limit its per customer usage to :limit times
*/
public function iLimitItsPerCustomerUsageLimitTo($limit)
{
$this->createPage->setCustomerUsageLimit($limit);
}
/**
* @When I change its per customer usage limit to :limit
*/
public function iChangeItsPerCustomerUsageLimitTo($limit)
{
$this->updatePage->setCustomerUsageLimit($limit);
}
/**
* @When I make it valid until :date
*/
public function iMakeItValidUntil(\DateTimeInterface $date)
{
$this->createPage->setExpiresAt($date);
}
/**
* @When I change expires date to :date
*/
public function iChangeExpiresDateTo(\DateTimeInterface $date)
{
$this->updatePage->setExpiresAt($date);
}
/**
* @When I add it
* @When I try to add it
*/
public function iAddIt()
{
$this->createPage->create();
}
/**
* @When I save my changes
*/
public function iSaveMyChanges()
{
$this->updatePage->saveChanges();
}
/**
* @When I generate it
* @When I try to generate it
*/
public function iGenerateIt()
{
$this->generatePage->generate();
}
/**
* @When /^I delete ("[^"]+" coupon) related to (this promotion)$/
* @When /^I try to delete ("[^"]+" coupon) related to (this promotion)$/
*/
public function iDeleteCouponRelatedToThisPromotion(PromotionCouponInterface $coupon, PromotionInterface $promotion)
{
$this->indexPage->open(['promotionId' => $promotion->getId()]);
$this->indexPage->deleteResourceOnPage(['code' => $coupon->getCode()]);
}
/**
* @When I check (also) the :couponCode coupon
*/
public function iCheckTheCoupon(string $couponCode): void
{
$this->indexPage->checkResourceOnPage(['code' => $couponCode]);
}
/**
* @When I delete them
*/
public function iDeleteThem(): void
{
$this->indexPage->bulkDelete();
}
/**
* @Then /^there should be (\d+) coupon related to (this promotion)$/
*/
public function thereShouldBeCouponRelatedTo($number, PromotionInterface $promotion)
{
$this->indexPage->open(['promotionId' => $promotion->getId()]);
Assert::same($this->indexPage->countItems(), (int) $number);
}
/**
* @Then I should see a single coupon in the list
*/
public function iShouldSeeASingleCouponInTheList(): void
{
Assert::same($this->indexPage->countItems(), 1);
}
/**
* @Then /^there should be coupon with code "([^"]+)"$/
*/
public function thereShouldBeCouponWithCode($code)
{
Assert::true($this->indexPage->isSingleResourceOnPage(['code' => $code]));
}
/**
* @Then this coupon should be valid until :date
*/
public function thisCouponShouldBeValidUntil(\DateTimeInterface $date)
{
Assert::true($this->indexPage->isSingleResourceOnPage(['expiresAt' => date('d-m-Y', $date->getTimestamp())]));
}
/**
* @Then /^this coupon should have (\d+) usage limit$/
*/
public function thisCouponShouldHaveUsageLimit($limit)
{
Assert::true($this->indexPage->isSingleResourceOnPage(['usageLimit' => $limit]));
}
/**
* @Then /^("[^"]+" coupon) should be used (\d+) time(?:|s)$/
*/
public function couponShouldHaveUsageLimit(PromotionCouponInterface $promotionCoupon, $used)
{
Assert::true($this->indexPage->isSingleResourceOnPage(['code' => $promotionCoupon->getCode(), 'used' => $used]));
}
/**
* @Then /^this coupon should have (\d+) per customer usage limit$/
*/
public function thisCouponShouldHavePerCustomerUsageLimit($limit)
{
Assert::true($this->indexPage->isSingleResourceOnPage(['perCustomerUsageLimit' => $limit]));
}
/**
* @Then the code field should be disabled
*/
public function theCodeFieldShouldBeDisabled()
{
Assert::true($this->updatePage->isCodeDisabled());
}
/**
* @Then /^I should be notified that coupon with this code already exists$/
*/
public function iShouldBeNotifiedThatCouponWithThisCodeAlreadyExists()
{
/** @var CreatePageInterface|UpdatePageInterface $currentPage */
$currentPage = $this->currentPageResolver->getCurrentPageWithForm([$this->createPage, $this->updatePage]);
Assert::same($currentPage->getValidationMessage('code'), 'This coupon already exists.');
}
/**
* @Then I should be notified that :element is required
*/
public function iShouldBeNotifiedThatIsRequired($element)
{
/** @var CreatePageInterface|UpdatePageInterface $currentPage */
$currentPage = $this->currentPageResolver->getCurrentPageWithForm([$this->createPage, $this->updatePage]);
Assert::same($currentPage->getValidationMessage($element), sprintf('Please enter coupon %s.', $element));
}
/**
* @Then I should be notified that generate amount is required
*/
public function iShouldBeNotifiedThatGenerateAmountIsRequired()
{
Assert::true($this->generatePage->checkAmountValidation('Please enter amount of coupons to generate.'));
}
/**
* @Then I should be notified that generate code length is required
*/
public function iShouldBeNotifiedThatCodeLengthIsRequired()
{
Assert::true($this->generatePage->checkCodeLengthValidation('Please enter coupon code length.'));
}
/**
* @Then /^there should still be only one coupon with code "([^"]+)" related to (this promotion)$/
*/
public function thereShouldStillBeOnlyOneCouponWithCodeRelatedTo($code, PromotionInterface $promotion)
{
$this->indexPage->open(['promotionId' => $promotion->getId()]);
Assert::true($this->indexPage->isSingleResourceOnPage(['code' => $code]));
}
/**
* @Then I should be notified that coupon usage limit must be at least one
*/
public function iShouldBeNotifiedThatCouponUsageLimitMustBeAtLeast()
{
/** @var CreatePageInterface|UpdatePageInterface $currentPage */
$currentPage = $this->currentPageResolver->getCurrentPageWithForm([$this->createPage, $this->updatePage]);
Assert::same($currentPage->getValidationMessage('usage_limit'), 'Coupon usage limit must be at least 1.');
}
/**
* @Then /^(this coupon) should no longer exist in the coupon registry$/
*/
public function couponShouldNotExistInTheRegistry(PromotionCouponInterface $coupon)
{
Assert::false($this->indexPage->isSingleResourceOnPage(['code' => $coupon->getCode()]));
}
/**
* @Then I should be notified that it has been successfully generated
*/
public function iShouldBeNotifiedThatItHasBeenSuccessfullyGenerated()
{
$this->notificationChecker->checkNotification('Success Promotion coupons have been successfully generated.', NotificationType::success());
}
/**
* @Then I should be notified that it is in use and cannot be deleted
*/
public function iShouldBeNotifiedOfFailure()
{
$this->notificationChecker->checkNotification(
'Error Cannot delete, the promotion coupon is in use.',
NotificationType::failure()
);
}
/**
* @Then /^(this coupon) should still exist in the registry$/
*/
public function couponShouldStillExistInTheRegistry(PromotionCouponInterface $coupon)
{
Assert::true($this->indexPage->isSingleResourceOnPage(['code' => $coupon->getCode()]));
}
/**
* @Then /^I should be notified that generating (\d+) coupons with code length equal to (\d+) is not possible$/
*/
public function iShouldBeNotifiedThatGeneratingCouponsWithCodeLengthIsNotPossible($amount, $codeLength)
{
$message = sprintf('Invalid coupons code length or coupons amount. It is not possible to generate %d unique coupons with code length equals %d. Possible generate amount is 8.', $amount, $codeLength);
Assert::true($this->generatePage->checkGenerationValidation($message));
}
/**
* @Then I should see the coupon :couponCode in the list
*/
public function iShouldSeeTheCouponInTheList(string $couponCode): void
{
Assert::true($this->indexPage->isSingleResourceOnPage(['code' => $couponCode]));
}
}
| torinaki/Sylius | src/Sylius/Behat/Context/Ui/Admin/ManagingPromotionCouponsContext.php | PHP | mit | 13,089 |
import { CustomLocale } from "../types/locale";
export declare const Khmer: CustomLocale;
declare const _default: {
default?: CustomLocale | undefined;
hr?: CustomLocale | undefined;
th?: CustomLocale | undefined;
tr?: CustomLocale | undefined;
ar?: CustomLocale | undefined;
at?: CustomLocale | undefined;
az?: CustomLocale | undefined;
be?: CustomLocale | undefined;
bg?: CustomLocale | undefined;
bn?: CustomLocale | undefined;
bs?: CustomLocale | undefined;
cat?: CustomLocale | undefined;
cs?: CustomLocale | undefined;
cy?: CustomLocale | undefined;
da?: CustomLocale | undefined;
de?: CustomLocale | undefined;
en?: CustomLocale | undefined;
eo?: CustomLocale | undefined;
es?: CustomLocale | undefined;
et?: CustomLocale | undefined;
fa?: CustomLocale | undefined;
fi?: CustomLocale | undefined;
fo?: CustomLocale | undefined;
fr?: CustomLocale | undefined;
gr?: CustomLocale | undefined;
he?: CustomLocale | undefined;
hi?: CustomLocale | undefined;
hu?: CustomLocale | undefined;
id?: CustomLocale | undefined;
is?: CustomLocale | undefined;
it?: CustomLocale | undefined;
ja?: CustomLocale | undefined;
ka?: CustomLocale | undefined;
ko?: CustomLocale | undefined;
km?: CustomLocale | undefined;
kz?: CustomLocale | undefined;
lt?: CustomLocale | undefined;
lv?: CustomLocale | undefined;
mk?: CustomLocale | undefined;
mn?: CustomLocale | undefined;
ms?: CustomLocale | undefined;
my?: CustomLocale | undefined;
nl?: CustomLocale | undefined;
no?: CustomLocale | undefined;
pa?: CustomLocale | undefined;
pl?: CustomLocale | undefined;
pt?: CustomLocale | undefined;
ro?: CustomLocale | undefined;
ru?: CustomLocale | undefined;
si?: CustomLocale | undefined;
sk?: CustomLocale | undefined;
sl?: CustomLocale | undefined;
sq?: CustomLocale | undefined;
sr?: CustomLocale | undefined;
sv?: CustomLocale | undefined;
uk?: CustomLocale | undefined;
vn?: CustomLocale | undefined;
zh?: CustomLocale | undefined;
zh_tw?: CustomLocale | undefined;
} & {
default: import("../types/locale").Locale;
};
export default _default;
| anomalylabs/datetime-field_type | resources/js/l10n/km.d.ts | TypeScript | mit | 2,271 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WPFSerialAssistant
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
InitCore();
}
}
}
| ChrisLeeGit/SerialAssistant | WPFSerialAssistant/MainWindow.xaml.cs | C# | mit | 662 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace StopGuessing.Interfaces
{
public interface IBinomialLadderFilter
{
Task<int> StepAsync(string key, int? heightOfLadderInRungs = null, TimeSpan? timeout = null,
CancellationToken cancellationToken = new CancellationToken());
Task<int> GetHeightAsync(string element, int? heightOfLadderInRungs = null, TimeSpan? timeout = null,
CancellationToken cancellationToken = new CancellationToken());
}
}
| Microsoft/StopGuessing | StopGuessingOld/Interfaces/IBinomialLadderFilter.cs | C# | mit | 583 |
<?php
if(empty($_POST))
{
//F5 Refresh Check
$redirect = admin_url('admin.php?page=duplicator&tab=new1');
echo "<script>window.location.href = '{$redirect}'</script>";
exit;
}
global $wp_version;
$Package = new DUP_Package();
if(isset($_POST['package-hash']))
{
// If someone is trying to pass the hasn into us that is illegal so stop it immediately.
die('Unauthorized');
}
$Package->saveActive($_POST);
$Package = DUP_Package::getActive();
$mysqldump_on = DUP_Settings::Get('package_mysqldump') && DUP_DB::getMySqlDumpPath();
$mysqlcompat_on = isset($Package->Database->Compatible) && strlen($Package->Database->Compatible);
$mysqlcompat_on = ($mysqldump_on && $mysqlcompat_on) ? true : false;
$dbbuild_mode = ($mysqldump_on) ? 'mysqldump (fast)' : 'PHP (slow)';
$zip_check = DUP_Util::getZipPath();
?>
<style>
/* ============----------
PROGRESS ARES-CHECKS */
div#dup-progress-area {text-align:center; max-width:650px; min-height:200px; margin:0px auto 0px auto; padding:0px;}
div.dup-progress-title {font-size:22px; padding:5px 0 20px 0; font-weight: bold}
div#dup-msg-success {padding:5px; text-align: left}
div#dup-msg-success-subtitle {font-style: italic; margin:7px 0px}
div#dup-msg-error {color:#A62426; padding:5px; max-width: 790px;}
div#dup-msg-error-response-text { max-height:500px; overflow-y:scroll; border:1px solid silver; border-radius:3px; padding:10px;background:#fff}
div.dup-hdr-error-details {text-align: left; margin:20px 0}
div.dup-panel {margin-bottom: 25px}
div.dup-scan-filter-status {display:inline; float: right; font-size:11px; margin-right:10px; color:#AF0000; font-style: italic}
/* SERVER-CHECKS */
div.dup-scan-title {display:inline-block; padding:1px; font-weight: bold;}
div.dup-scan-title a {display:inline-block; min-width:200px; padding:3px; }
div.dup-scan-title a:focus {outline: 1px solid #fff; box-shadow: none}
div.dup-scan-title div {display:inline-block; }
div.dup-scan-info {display:none; padding:5px 20px 10px 10px}
div.dup-scan-good {display:inline-block; color:green;font-weight: bold;}
div.dup-scan-warn {display:inline-block; color:#AF0000;font-weight: bold;}
span.dup-toggle {float:left; margin:0 2px 2px 0; }
/*DATABASE*/
table#dup-scan-db-details {line-height: 14px; margin:15px 0px 0px 5px; width:98%}
table#dup-scan-db-details td {padding:0px;}
table#dup-scan-db-details td:first-child {font-weight: bold; white-space: nowrap; width:90px}
div#dup-scan-db-info {margin:0px 0px 0px 10px}
div#data-db-tablelist {max-height: 300px; overflow-y: scroll; border: 1px dashed silver; padding: 5px; margin-top:5px}
div#data-db-tablelist div{padding:0px 0px 0px 15px;}
div#data-db-tablelist span{display:inline-block; min-width: 75px}
div#data-db-size1 {display: inline-block; float:right; font-size:11px; margin-right:5px; font-style: italic}
/*FILES */
div#data-arc-size1 {display: inline-block; float:right; font-size:11px; margin-right:5px; font-style: italic}
i.data-size-help { float:right; margin-right:5px; display: block; font-size: 11px}
div#data-arc-names-data, div#data-arc-big-data {word-wrap: break-word;font-size:10px; border:1px dashed silver; padding:5px; display: none}
div#dup-scan-warning-continue {display:none; text-align: center; padding: 0 0 15px 0}
div#dup-scan-warning-continue div.msg1 label{font-size:16px; color:maroon}
div#dup-scan-warning-continue div.msg2 {padding:2px; line-height: 13px}
div#dup-scan-warning-continue div.msg2 label {font-size:11px !important}
/*Footer*/
div.dup-button-footer {text-align:center; margin:0}
button.button {font-size:15px !important; height:30px !important; font-weight:bold; padding:3px 5px 5px 5px !important;}
</style>
<!-- =========================================
TOOL BAR: STEPS -->
<table id="dup-toolbar">
<tr valign="top">
<td style="white-space: nowrap">
<div id="dup-wiz">
<div id="dup-wiz-steps">
<div class="completed-step"><a>1-<?php _e('Setup', 'duplicator'); ?></a></div>
<div class="active-step"><a>2-<?php _e('Scan', 'duplicator'); ?> </a></div>
<div><a>3-<?php _e('Build', 'duplicator'); ?> </a></div>
</div>
<div id="dup-wiz-title">
<?php _e('Step 2: System Scan', 'duplicator'); ?>
</div>
</div>
</td>
<td>
<a id="dup-pro-create-new" href="?page=duplicator" class="add-new-h2"><i class="fa fa-archive"></i> <?php _e('All Packages', 'duplicator'); ?></a>
<span> <?php _e('Create New', 'duplicator'); ?></span>
</td>
</tr>
</table>
<hr class="dup-toolbar-line">
<form id="form-duplicator" method="post" action="?page=duplicator&tab=new3">
<div id="dup-progress-area">
<!-- PROGRESS BAR -->
<div id="dup-progress-bar-area">
<div class="dup-progress-title"><i class="fa fa-circle-o-notch fa-spin"></i> <?php _e('Scanning Site', 'duplicator'); ?></div>
<div id="dup-progress-bar"></div>
<b><?php _e('Please Wait...', 'duplicator'); ?></b><br/><br/>
<i><?php _e('Keep this window open during the scan process.', 'duplicator'); ?></i><br/>
<i><?php _e('This can take several minutes.', 'duplicator'); ?></i><br/>
</div>
<!-- SUCCESS MESSAGE -->
<div id="dup-msg-success" style="display:none">
<div style="text-align:center">
<div class="dup-hdr-success"><i class="fa fa-check-square-o fa-lg"></i> <?php _e('Scan Complete', 'duplicator'); ?></div>
<div id="dup-msg-success-subtitle">
<?php _e('Process Time:', 'duplicator'); ?> <span id="data-rpt-scantime"></span>
</div>
</div><br/>
<!-- ================================================================
META-BOX: SERVER
================================================================ -->
<div class="dup-panel">
<div class="dup-panel-title">
<i class="fa fa-hdd-o"></i> <?php _e("Server", 'duplicator'); ?>
<div style="float:right; margin:-1px 10px 0px 0px">
<small><a href="?page=duplicator-tools&tab=diagnostics" target="_blank"><?php _e('Diagnostics', 'duplicator');?></a></small>
</div>
</div>
<div class="dup-panel-panel">
<!-- ============
WEB SERVER -->
<div>
<div class='dup-scan-title'>
<a><?php _e('Web Server', 'duplicator');?></a> <div id="data-srv-web-all"></div>
</div>
<div class='dup-scan-info dup-info-box'>
<?php
$web_servers = implode(', ', $GLOBALS['DUPLICATOR_SERVER_LIST']);
echo '<span id="data-srv-web-model"></span> <b>' . __('Web Server', 'duplicator') . ":</b> '{$_SERVER['SERVER_SOFTWARE']}'";
echo '<small>';
_e("Supported web servers:", 'duplicator');
echo "{$web_servers}";
echo '</small>';
?>
</div>
</div>
<!-- ============
PHP SETTINGS -->
<div>
<div class='dup-scan-title'>
<a><?php _e('PHP Setup', 'duplicator');?></a> <div id="data-srv-php-all"></div>
</div>
<div class='dup-scan-info dup-info-box'>
<?php
//PHP VERSION
echo '<span id="data-srv-php-version"></span> <b>' . __('PHP Version', 'duplicator') . "</b> <br/>";
echo '<small>';
_e('The minium PHP version supported by Duplicator is 5.2.9, however it is highly recommended to use PHP 5.3 or higher for improved stability.', 'duplicator');
echo " <i><a href='http://php.net/ChangeLog-5.php' target='_blank'>[" . __('details', 'duplicator') . "]</a></i>";
echo '</small>';
//OPEN_BASEDIR
$test = ini_get("open_basedir");
echo '<hr size="1" /><span id="data-srv-php-openbase"></span> <b>' . __('Open Base Dir', 'duplicator') . ":</b> '{$test}' <br/>";
echo '<small>';
_e('Issues might occur when [open_basedir] is enabled. Work with your server admin to disable this value in the php.ini file if you’re having issues building a package.', 'duplicator');
echo " <i><a href='http://www.php.net/manual/en/ini.core.php#ini.open-basedir' target='_blank'>[" . __('details', 'duplicator') . "]</a></i><br/>";
echo '</small>';
//MYSQLI
echo '<hr size="1" /><span id="data-srv-php-mysqli"></span> <b>' . __('MySQLi', 'duplicator') . "</b> <br/>";
echo '<small>';
_e('Creating the package does not require the mysqli module. However the installer.php file requires that the PHP module mysqli be installed on the server it is deployed on.', 'duplicator');
echo " <i><a href='http://php.net/manual/en/mysqli.installation.php' target='_blank'>[" . __('details', 'duplicator') . "]</a></i>";
echo '</small>';
//MAX_EXECUTION_TIME
$test = (@set_time_limit(0)) ? 0 : ini_get("max_execution_time");
echo '<hr size="1" /><span id="data-srv-php-maxtime"></span> <b>' . __('Max Execution Time', 'duplicator') . ":</b> '{$test}' <br/>";
echo '<small>';
printf(__('Issues might occur for larger packages when the [max_execution_time] value in the php.ini is too low. The minimum recommended timeout is "%1$s" seconds or higher. An attempt is made to override this value if the server allows it. A value of 0 (recommended) indicates that PHP has no time limits.', 'duplicator'), DUPLICATOR_SCAN_TIMEOUT);
echo '<br/><br/>';
_e('Note: Timeouts can also be set at the web server layer, so if the PHP max timeout passes and you still see a build interrupt messages, then your web server could be killing the process. If you are limited on processing time, consider using the database or file filters to shrink the size of your overall package. However use caution as excluding the wrong resources can cause your install to not work properly.', 'duplicator');
echo " <i><a href='http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time' target='_blank'>[" . __('details', 'duplicator') . "]</a></i>";
if ($zip_check != null) {
echo '<br/><br/>';
echo '<span style="font-weight:bold">';
_e('Get faster builds with Duplicator Pro with access to shell_exec zip.', 'duplicator');
echo '</span>';
echo " <i><a href='https://snapcreek.com/duplicator/?utm_source=duplicator_free&utm_medium=wordpress_plugin&utm_content=free_max_execution_time_warn&utm_campaign=duplicator_pro' target='_blank'>[" . __('details', 'duplicator') . "]</a></i>";
}
echo '</small>';
?>
</div>
</div>
<!-- ============
WORDPRESS SETTINGS -->
<div>
<div class='dup-scan-title'>
<a><?php _e('WordPress', 'duplicator');?></a> <div id="data-srv-wp-all"></div>
</div>
<div class='dup-scan-info dup-info-box'>
<?php
//VERSION CHECK
echo '<span id="data-srv-wp-version"></span> <b>' . __('WordPress Version', 'duplicator') . ":</b> '{$wp_version}' <br/>";
echo '<small>';
printf(__('It is recommended to have a version of WordPress that is greater than %1$s', 'duplicator'), DUPLICATOR_SCAN_MIN_WP);
echo '</small>';
//CORE FILES
echo '<hr size="1" /><span id="data-srv-wp-core"></span> <b>' . __('Core Files', 'duplicator') . "</b> <br/>";
echo '<small>';
_e("If the scanner is unable to locate the wp-config.php file in the root directory, then you will need to manually copy it to its new location.", 'duplicator');
echo '</small>';
//CACHE DIR
$cache_path = $cache_path = DUP_Util::safePath(WP_CONTENT_DIR) . '/cache';
$cache_size = DUP_Util::byteSize(DUP_Util::getDirectorySize($cache_path));
echo '<hr size="1" /><span id="data-srv-wp-cache"></span> <b>' . __('Cache Path', 'duplicator') . ":</b> '{$cache_path}' ({$cache_size}) <br/>";
echo '<small>';
_e("Cached data will lead to issues at install time and increases your archive size. It is recommended to empty your cache directory at build time. Use caution when removing data from the cache directory. If you have a cache plugin review the documentation for how to empty it; simply removing files might cause errors on your site. The cache size minimum threshold is currently set at ", 'duplicator');
echo DUP_Util::byteSize(DUPLICATOR_SCAN_CACHESIZE) . '.';
echo '</small>';
//MU SITE
if (is_multisite())
{
echo '<hr size="1" /><span><div class="dup-scan-warn"><i class="fa fa-exclamation-triangle"></i></div></span> <b>' . __('Multisite: Unsupported', 'duplicator') . "</b> <br/>";
echo '<small>';
_e('Duplicator does not officially support Multisite. However, Duplicator Pro supports duplication of a full Multisite network and also has the ability to install a Multisite subsite as a standalone site.', 'duplicator');
echo " <i><a href='https://snapcreek.com/duplicator/?utm_source=duplicator_free&utm_medium=wordpress_plugin&utm_content=free_is_mu_warn&utm_campaign=duplicator_pro' target='_blank'>[" . __('details', 'duplicator') . "]</a></i>";
echo '</small>';
}
else
{
echo '<hr size="1" /><span><div class="dup-scan-good"><i class="fa fa-check"></i></div></span> <b>' . __('Multisite: N/A', 'duplicator') . "</b> <br/>";
echo '<small>';
_e('This is not a Multisite install so duplication will proceed without issue. Duplicator does not officially support Multisite. However, Duplicator Pro supports duplication of a full Multisite network and also has the ability to install a Multisite subsite as a standalone site.', 'duplicator');
echo " <i><a href='https://snapcreek.com/duplicator/?utm_source=duplicator_free&utm_medium=wordpress_plugin&utm_content=free_is_mu_warn&utm_campaign=duplicator_pro' target='_blank'>[" . __('details', 'duplicator') . "]</a></i>";
echo '</small>';
}
?>
</div>
</div>
</div><!-- end .dup-panel -->
</div><!-- end .dup-panel-panel -->
<h2 style="font-size:18px; font-weight:bold; margin:-10px 0 5px 10px"><i class="fa fa-file-archive-o"></i> <?php _e('Archive', 'duplicator');?> </h2>
<!-- ================================================================
FILES
================================================================ -->
<div class="dup-panel">
<div class="dup-panel-title">
<i class="fa fa-files-o"></i>
<?php _e("Files", 'duplicator'); ?>
<i class="fa fa-question-circle data-size-help"
data-tooltip-title="<?php _e("File Size:", 'duplicator'); ?>"
data-tooltip="<?php _e('The files size represents only the included files before compression is applied. It does not include the size of the database script and in most cases the package size once completed will be smaller than this number.', 'duplicator'); ?>"></i>
<div id="data-arc-size1"></div>
<div class="dup-scan-filter-status">
<?php
if ($Package->Archive->ExportOnlyDB) {
echo '<i class="fa fa-filter"></i> '; _e('Database Only', 'duplicator');
}elseif ($Package->Archive->FilterOn) {
echo '<i class="fa fa-filter"></i> '; _e('Enabled', 'duplicator');
}
?>
</div>
</div>
<div class="dup-panel-panel">
<!-- ============
TOTAL SIZE -->
<div>
<div class='dup-scan-title'>
<a><?php _e('Total Size', 'duplicator');?></a> <div id="data-arc-status-size"></div>
</div>
<div class='dup-scan-info dup-info-box'>
<b><?php _e('Size', 'duplicator');?>:</b> <span id="data-arc-size2"></span> |
<b><?php _e('File Count', 'duplicator');?>:</b> <span id="data-arc-files"></span> |
<b><?php _e('Directory Count', 'duplicator');?>:</b> <span id="data-arc-dirs"></span>
<small>
<?php
printf(__('Total size represents all files minus any filters that have been setup. The current thresholds that triggers a warning is %1$s for the total size. Some budget hosts limit the amount of time a PHP/Web request process can run. When working with larger sites this can cause timeout issues. Consider using a file filter in step 1 to shrink and filter the overall size of your package.', 'duplicator'),
DUP_Util::byteSize(DUPLICATOR_SCAN_SITE),
DUP_Util::byteSize(DUPLICATOR_SCAN_WARNFILESIZE));
if ($zip_check != null) {
echo '<br/><br/>';
echo '<span style="font-weight:bold">';
_e('Package support up to 2GB available in Duplicator Pro.', 'duplicator');
echo '</span>';
echo " <i><a href='https://snapcreek.com/duplicator/?utm_source=duplicator_free&utm_medium=wordpress_plugin&utm_content=free_size_warn&utm_campaign=duplicator_pro' target='_blank'>[" . __('details', 'duplicator') . "]</a></i>";
}
?>
</small>
</div>
</div>
<!-- ============
FILE NAME LENGTHS -->
<div>
<div class='dup-scan-title'>
<a><?php _e('Name Checks', 'duplicator');?></a> <div id="data-arc-status-names"></div>
</div>
<div class='dup-scan-info dup-info-box'>
<small>
<?php
_e('File or directory names may cause issues when working across different environments and servers. Names that are over 250 characters, contain special characters (such as * ? > < : / \ |) or are unicode might cause issues in a remote enviroment. It is recommended to remove or filter these files before building the archive if you have issues at install time.', 'duplicator');
?>
</small><br/>
<a href="javascript:void(0)" onclick="jQuery('#data-arc-names-data').toggle()">[<?php _e('Show Paths', 'duplicator');?>]</a>
<div id="data-arc-names-data"></div>
</div>
</div>
<!-- ============
LARGE FILES -->
<div>
<div class='dup-scan-title'>
<a><?php _e('Large Files', 'duplicator');?></a> <div id="data-arc-status-big"></div>
</div>
<div class='dup-scan-info dup-info-box'>
<small>
<?php
printf(__('Large files such as movies or other backuped data can cause issues with timeouts. The current check for large files is %1$s per file. If your having issues creating a package consider excluding these files with the files filter and manually moving them to your new location.', 'duplicator'),
DUP_Util::byteSize(DUPLICATOR_SCAN_WARNFILESIZE));
?>
</small><br/>
<a href="javascript:void(0)" onclick="jQuery('#data-arc-big-data').toggle()">[<?php _e('Show Paths', 'duplicator');?>]</a>
<div id="data-arc-big-data"></div>
</div>
</div>
<!-- ============
VIEW FILTERS -->
<?php if ($Package->Archive->FilterOn) : ?>
<div>
<div class='dup-scan-title'>
<a style='font-weight: normal'><?php _e('Archive Details', 'duplicator');?></a>
</div>
<div class='dup-scan-info dup-info-box'>
<b>[<?php _e('Root Directory', 'duplicator');?>]</b><br/>
<?php echo DUPLICATOR_WPROOTPATH;?>
<br/><br/>
<b>[<?php _e('Excluded Directories', 'duplicator');?>]</b><br/>
<?php
if (strlen( $Package->Archive->FilterDirs)) {
echo str_replace(";", "<br/>", $Package->Archive->FilterDirs);
} else {
_e('No directory filters have been set.', 'duplicator');
}
?>
<br/>
<b>[<?php _e('Excluded File Extensions', 'duplicator');?>]</b><br/>
<?php
if (strlen( $Package->Archive->FilterExts)) {
echo $Package->Archive->FilterExts;
} else {
_e('No file extension filters have been set.', 'duplicator');
}
?>
<small>
<?php
_e('The root directory is where Duplicator starts archiving files. The excluded sections will be skipped during the archive process. ', 'duplicator');
_e('All results are stored in a json file. ', 'duplicator');
?>
<a href="<?php echo DUPLICATOR_SITE_URL ?>/wp-admin/admin-ajax.php?action=duplicator_package_scan" target="dup_report"><?php _e('[view json report]', 'duplicator');?></a>
</small><br/>
</div>
</div>
<?php endif; ?>
</div><!-- end .dup-panel -->
<!-- ================================================================
DATABASE
================================================================ -->
<div class="dup-panel-title">
<i class="fa fa-table"></i>
<?php _e("Database", 'duplicator'); ?>
<i class="fa fa-question-circle data-size-help"
data-tooltip-title="<?php _e("Database Size:", 'duplicator'); ?>"
data-tooltip="<?php _e('The database size represents only the included tables. The process for gathering the size uses the query SHOW TABLE STATUS. The overall size of the database file can impact the final size of the package.', 'duplicator'); ?>"></i>
<div id="data-db-size1"></div>
<div class="dup-scan-filter-status">
<?php
if ($Package->Database->FilterOn) {
echo '<i class="fa fa-filter"></i> '; _e('Enabled', 'duplicator');
}
?>
</div>
</div>
<div class="dup-panel-panel" id="dup-scan-db">
<!-- ============
TOTAL SIZE -->
<div>
<div class='dup-scan-title'>
<a><?php _e('Total Size', 'duplicator');?></a>
<div id="data-db-status-size"></div>
</div>
<div class='dup-scan-info dup-info-box'>
<b><?php _e('Size', 'duplicator');?>:</b> <span id="data-db-size2"></span> |
<b><?php _e('Tables', 'duplicator');?>:</b> <span id="data-db-tablecount"></span> |
<b><?php _e('Records', 'duplicator');?>:</b> <span id="data-db-rows"></span>
<br/><br/>
<?php
//OVERVIEW
echo '<b>' . __('Overview:', 'duplicator') . '</b><br/>';
printf(__('Total size and row count for all database tables are approximate values. The thresholds that trigger warnings are %1$s OR %2$s records total for the entire database. The larger the databases the more time it takes to process and execute. This can cause issues with budget hosts that have cpu/memory limits, and timeout constraints.', 'duplicator'),
DUP_Util::byteSize(DUPLICATOR_SCAN_DB_ALL_SIZE),
number_format(DUPLICATOR_SCAN_DB_ALL_ROWS));
//OPTIONS
echo '<br/><br/>';
echo '<b>' . __('Options:', 'duplicator') . '</b><br/>';
$lnk = '<a href="maint/repair.php" target="_blank">' . __('Repair and Optimization', 'duplicator') . '</a>';
printf(__('1. Running a %1$s on your database will help to improve the overall size, performance and efficiency of the database.', 'duplicator'), $lnk);
echo '<br/><br/>';
$lnk = '<a href="?page=duplicator-settings" target="_blank">' . __('Duplicator Settings', 'duplicator') . '</a>';
printf(__('2. If your server supports shell_exec and mysqldump it is recommended to enable this option from the %1$s menu.', 'duplicator'), $lnk);
echo '<br/><br/>';
_e('3. Consider removing data from tables that store logging, statistical or other non-critical information about your site.', 'duplicator');
?>
</div>
</div>
<!-- ============
TABLE DETAILS -->
<div>
<div class='dup-scan-title'>
<a><?php _e('Table Details', 'duplicator');?></a>
<div id="data-db-status-details"></div>
</div>
<div class='dup-scan-info dup-info-box'>
<?php
//OVERVIEW
echo '<b>' . __('Overview:', 'duplicator') . '</b><br/>';
printf(__('The thresholds that trigger warnings for individual tables are %1$s OR %2$s records OR tables names with upper-case characters. The larger the table the more time it takes to process and execute. This can cause issues with budget hosts that have cpu/memory limits, and timeout constraints.', 'duplicator'),
DUP_Util::byteSize(DUPLICATOR_SCAN_DB_TBL_SIZE),
number_format(DUPLICATOR_SCAN_DB_TBL_ROWS));
//OPTIONS
echo '<br/><br/>';
echo '<b>' . __('Options:', 'duplicator') . '</b><br/>';
$lnk = '<a href="maint/repair.php" target="_blank">' . __('Repair and Optimization', 'duplicator') . '</a>';
printf(__('1. Run a %1$s on the table to improve the overall size and performance.', 'duplicator'), $lnk);
echo '<br/><br/>';
_e('2. Remove stale date from tables such as logging, statistical or other non-critical data.', 'duplicator');
echo '<br/><br/>';
$lnk = '<a href="http://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_lower_case_table_names" target="_blank">' . __('lower_case_table_names', 'duplicator') . '</a>';
printf(__('3. For table name case sensitivity issues either rename the table with lower case characters or be prepared to work with the %1$s system variable setting.', 'duplicator'), $lnk);
echo '<br/><br/>';
echo '<b>' . __('Tables:', 'duplicator') . '</b><br/>';
?>
<div id="dup-scan-db-info">
<div id="data-db-tablelist"></div>
</div>
</div>
</div>
<table id="dup-scan-db-details">
<tr><td><b><?php _e('Name:', 'duplicator');?></b></td><td><?php echo DB_NAME ;?> </td></tr>
<tr><td><b><?php _e('Host:', 'duplicator');?></b></td><td><?php echo DB_HOST ;?> </td></tr>
<tr>
<td style="vertical-align: top"><b><?php _e('Build Mode:', 'duplicator');?></b></td>
<td style="line-height:18px">
<a href="?page=duplicator-settings" target="_blank"><?php echo $dbbuild_mode ;?></a>
<?php if ($mysqlcompat_on) :?>
<br/>
<small style="font-style:italic; color:maroon">
<i class="fa fa-exclamation-circle"></i> <?php _e('MySQL Compatibility Mode Enabled', 'duplicator'); ?>
<a href="https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_compatible" target="_blank">[<?php _e('details', 'duplicator'); ?>]</a>
</small>
<?php endif;?>
</td>
</tr>
</table>
</div><!-- end .dup-panel -->
</div><!-- end .dup-panel-panel -->
<!-- WARNING CONTINUE -->
<div id="dup-scan-warning-continue">
<div class="msg1">
<label for="dup-scan-warning-continue-checkbox">
<?php _e('A warning status was detected, are you sure you want to continue?', 'duplicator');?>
</label>
<div style="padding:8px 0">
<input type="checkbox" id="dup-scan-warning-continue-checkbox" onclick="Duplicator.Pack.WarningContinue(this)"/>
<label for="dup-scan-warning-continue-checkbox"><?php _e('Yes. Continue with the build process!', 'duplicator');?></label>
</div>
</div>
<div class="msg2">
<label for="dup-scan-warning-continue-checkbox">
<?php
_e("Scan checks are not required to pass, however they could cause issues on some systems.", 'duplicator');
echo '<br/>';
_e("Please review the details for each warning by clicking on the detail link.", 'duplicator');
?>
</label>
</div>
</div>
</div>
<!-- ERROR MESSAGE -->
<div id="dup-msg-error" style="display:none">
<div class="dup-hdr-error"><i class="fa fa-exclamation-circle"></i> <?php _e('Scan Error', 'duplicator'); ?></div>
<i><?php _e('Please try again!', 'duplicator'); ?></i><br/>
<div class="dup-hdr-error-details">
<b><?php _e("Server Status:", 'duplicator'); ?></b>
<div id="dup-msg-error-response-status" style="display:inline-block"></div><br/>
<b><?php _e("Error Message:", 'duplicator'); ?></b>
<div id="dup-msg-error-response-text"></div>
</div>
</div>
</div> <!-- end #dup-progress-area -->
<div class="dup-button-footer" style="display:none">
<input type="button" value="◀ <?php _e("Back", 'duplicator') ?>" onclick="window.location.assign('?page=duplicator&tab=new1')" class="button button-large" />
<input type="button" value="<?php _e("Rescan", 'duplicator') ?>" onclick="Duplicator.Pack.Rescan()" class="button button-large" />
<input type="submit" value="<?php _e("Build", 'duplicator') ?> ▶" class="button button-primary button-large" id="dup-build-button" />
</div>
</form>
<script>
jQuery(document).ready(function($) {
/* Performs Ajax post to create check system */
Duplicator.Pack.Scan = function()
{
var data = {action : 'duplicator_package_scan'}
$.ajax({
type: "POST",
url: ajaxurl,
dataType: "json",
timeout: 10000000,
data: data,
complete: function() {$('.dup-button-footer').show()},
success: function(data) {
Duplicator.Pack.LoadScanData(data)
//Imacros testing required
$('#dup-automation-imacros').html('<input type="hidden" id="dup-finished" value="done" />');
},
error: function(data) {
$('#dup-progress-bar-area').hide();
var status = data.status + ' -' + data.statusText;
$('#dup-msg-error-response-status').html(status)
$('#dup-msg-error-response-text').html(data.responseText);
$('#dup-msg-error').show(200);
console.log(data);
}
});
}
Duplicator.Pack.Rescan = function()
{
$('#dup-msg-success,#dup-msg-error,.dup-button-footer').hide();
$('#dup-progress-bar-area').show();
Duplicator.Pack.Scan();
}
Duplicator.Pack.WarningContinue = function(checkbox)
{
($(checkbox).is(':checked'))
? $('#dup-build-button').prop('disabled',false).addClass('button-primary')
: $('#dup-build-button').prop('disabled',true).removeClass('button-primary');
}
Duplicator.Pack.LoadScanStatus = function(status)
{
var result;
switch (status) {
case false : result = '<div class="dup-scan-warn"><i class="fa fa-exclamation-triangle"></i></div>'; break;
case 'Warn' : result = '<div class="dup-scan-warn"><i class="fa fa-exclamation-triangle"></i> Warn</div>'; break;
case true : result = '<div class="dup-scan-good"><i class="fa fa-check"></i></div>'; break;
case 'Good' : result = '<div class="dup-scan-good"><i class="fa fa-check"></i> Good</div>'; break;
default :
result = 'unable to read';
}
return result;
}
/* Load Scan Data */
Duplicator.Pack.LoadScanData = function(data)
{
var errMsg = "unable to read";
$('#dup-progress-bar-area').hide();
//****************
//ERROR: Data object is corrupt or empty return error
if (data == undefined || data.RPT == undefined)
{
var html_msg;
html_msg = '<?php _e("Unable to perform a full scan, please try the following actions:", 'duplicator') ?><br/><br/>';
html_msg += '<?php _e("1. Go back and create a root path directory filter to validate the site is scan-able.", 'duplicator') ?><br/>';
html_msg += '<?php _e("2. Continue to add/remove filters to isolate which path is causing issues.", 'duplicator') ?><br/>';
html_msg += '<?php _e("3. This message will go away once the correct filters are applied.", 'duplicator') ?><br/><br/>';
html_msg += '<?php _e("Common Issues:", 'duplicator') ?><ul>';
html_msg += '<li><?php _e("- On some budget hosts scanning over 30k files can lead to timeout/gateway issues. Consider scanning only your main WordPress site and avoid trying to backup other external directories.", 'duplicator') ?></li>';
html_msg += '<li><?php _e("- Symbolic link recursion can cause timeouts. Ask your server admin if any are present in the scan path. If they are add the full path as a filter and try running the scan again.", 'duplicator') ?></li>';
html_msg += '</ul>';
$('#dup-msg-error-response-status').html('Scan Path Error [<?php echo rtrim(DUPLICATOR_WPROOTPATH, '/'); ?>]');
$('#dup-msg-error-response-text').html(html_msg);
$('#dup-msg-error').show(200);
console.log('JSON Report Data:');
console.log(data);
return;
}
//****************
//REPORT
var base = $('#data-rpt-scanfile').attr('href');
$('#data-rpt-scanfile').attr('href', base + '&scanfile=' + data.RPT.ScanFile);
$('#data-rpt-scantime').text(data.RPT.ScanTime || 0);
//****************
//SERVER
$('#data-srv-web-model').html(Duplicator.Pack.LoadScanStatus(data.SRV.WEB.model));
$('#data-srv-web-all').html(Duplicator.Pack.LoadScanStatus(data.SRV.WEB.ALL));
$('#data-srv-php-openbase').html(Duplicator.Pack.LoadScanStatus(data.SRV.PHP.openbase));
$('#data-srv-php-maxtime').html(Duplicator.Pack.LoadScanStatus(data.SRV.PHP.maxtime));
$('#data-srv-php-mysqli').html(Duplicator.Pack.LoadScanStatus(data.SRV.PHP.mysqli));
$('#data-srv-php-version').html(Duplicator.Pack.LoadScanStatus(data.SRV.PHP.version));
$('#data-srv-php-openssl').html(Duplicator.Pack.LoadScanStatus(data.SRV.PHP.openssl));
$('#data-srv-php-all').html(Duplicator.Pack.LoadScanStatus(data.SRV.PHP.ALL));
$('#data-srv-wp-version').html(Duplicator.Pack.LoadScanStatus(data.SRV.WP.version));
$('#data-srv-wp-core').html(Duplicator.Pack.LoadScanStatus(data.SRV.WP.core));
$('#data-srv-wp-cache').html(Duplicator.Pack.LoadScanStatus(data.SRV.WP.cache));
$('#data-srv-wp-all').html(Duplicator.Pack.LoadScanStatus(data.SRV.WP.ALL));
//****************
//DATABASE
var html = "";
var DB_TotalSize = 'Good';
var DB_TableDetails = 'Good';
var DB_TableRowMax = <?php echo DUPLICATOR_SCAN_DB_TBL_ROWS; ?>;
var DB_TableSizeMax = <?php echo DUPLICATOR_SCAN_DB_TBL_SIZE; ?>;
if (data.DB.Status.Success)
{
DB_TotalSize = data.DB.Status.DB_Rows == 'Warn' || data.DB.Status.DB_Size == 'Warn' ? 'Warn' : 'Good';
DB_TableDetails = data.DB.Status.TBL_Rows == 'Warn' || data.DB.Status.TBL_Size == 'Warn' || data.DB.Status.TBL_Case == 'Warn' ? 'Warn' : 'Good';
$('#data-db-status-size').html(Duplicator.Pack.LoadScanStatus(DB_TotalSize));
$('#data-db-status-details').html(Duplicator.Pack.LoadScanStatus(DB_TableDetails));
$('#data-db-size1').text(data.DB.Size || errMsg);
$('#data-db-size2').text(data.DB.Size || errMsg);
$('#data-db-rows').text(data.DB.Rows || errMsg);
$('#data-db-tablecount').text(data.DB.TableCount || errMsg);
//Table Details
if (data.DB.TableList == undefined || data.DB.TableList.length == 0) {
html = '<?php _e("Unable to report on any tables", 'duplicator') ?>';
} else {
$.each(data.DB.TableList, function(i) {
html += '<b>' + i + '</b><br/>';
$.each(data.DB.TableList[i], function(key,val) {
html += (key == 'Case' && val == 1) || (key == 'Rows' && val > DB_TableRowMax) || (key == 'Size' && parseInt(val) > DB_TableSizeMax)
? '<div style="color:red"><span>' + key + ':</span>' + val + '</div>'
: '<div><span>' + key + ':</span>' + val + '</div>';
});
});
}
$('#data-db-tablelist').append(html);
} else {
html = '<?php _e("Unable to report on database stats", 'duplicator') ?>';
$('#dup-scan-db').html(html);
}
//****************
//ARCHIVE
$('#data-arc-status-size').html(Duplicator.Pack.LoadScanStatus(data.ARC.Status.Size));
$('#data-arc-status-names').html(Duplicator.Pack.LoadScanStatus(data.ARC.Status.Names));
$('#data-arc-status-big').html(Duplicator.Pack.LoadScanStatus(data.ARC.Status.Big));
$('#data-arc-size1').text(data.ARC.Size || errMsg);
$('#data-arc-size2').text(data.ARC.Size || errMsg);
$('#data-arc-files').text(data.ARC.FileCount || errMsg);
$('#data-arc-dirs').text(data.ARC.DirCount || errMsg);
//Name Checks
html = '';
//Dirs
if (data.ARC.FilterInfo.Dirs.Warning !== undefined && data.ARC.FilterInfo.Dirs.Warning.length > 0) {
$.each(data.ARC.FilterInfo.Dirs.Warning, function (key, val) {
html += '<?php _e("DIR", 'duplicator') ?> ' + key + ':<br/>[' + val + ']<br/>';
});
}
//Files
if (data.ARC.FilterInfo.Files.Warning !== undefined && data.ARC.FilterInfo.Files.Warning.length > 0) {
$.each(data.ARC.FilterInfo.Files.Warning, function (key, val) {
html += '<?php _e("FILE", 'duplicator') ?> ' + key + ':<br/>[' + val + ']<br/>';
});
}
html = (html.length == 0) ? '<?php _e("No name warning issues found.", 'duplicator') ?>' : html;
$('#data-arc-names-data').html(html);
//Large Files
html = '<?php _e("No large files found.", 'duplicator') ?>';
if (data.ARC.FilterInfo.Files.Size !== undefined && data.ARC.FilterInfo.Files.Size.length > 0) {
html = '';
$.each(data.ARC.FilterInfo.Files.Size, function (key, val) {
html += '<?php _e("FILE", 'duplicator') ?> ' + key + ':<br/>' + val + '<br/>';
});
}
$('#data-arc-big-data').html(html);
$('#dup-msg-success').show();
//Waring Check
var warnCount = data.RPT.Warnings || 0;
if (warnCount > 0) {
$('#dup-scan-warning-continue').show();
$('#dup-build-button').prop("disabled",true).removeClass('button-primary');
} else {
$('#dup-scan-warning-continue').hide();
$('#dup-build-button').prop("disabled",false).addClass('button-primary');
}
}
//Page Init:
Duplicator.UI.AnimateProgressBar('dup-progress-bar');
Duplicator.Pack.Scan();
//Init: Toogle for system requirment detial links
$('.dup-scan-title a').each(function()
{
$(this).attr('href', 'javascript:void(0)');
$(this).click({selector : '.dup-scan-info'}, Duplicator.Pack.ToggleSystemDetails);
$(this).prepend("<span class='ui-icon ui-icon-triangle-1-e dup-toggle' />");
});
});
</script> | PatrickJamesHoban/patrickjameshoban | wp-content/plugins/duplicator/views/packages/main/new2.scan.php | PHP | mit | 37,114 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Csla.ApplicationContext.User = new Csla.Security.UnauthenticatedPrincipal();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
//var obj = BusinessLibrary.Order.NewOrder();
var obj = BusinessLibrary.Order.GetOrder(441);
this.cslaActionExtender1.ResetActionBehaviors(obj);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
| BrettJaner/csla | Samples/NET/cs/SimpleNTier/WindowsUI/Form1.cs | C# | mit | 747 |
/// \file
// Range v3 library
//
// Copyright Eric Niebler 2014-present
// Copyright Rostislav Khlebnikov 2017
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/ericniebler/range-v3
//
#ifndef RANGES_V3_ALGORITHM_FOR_EACH_N_HPP
#define RANGES_V3_ALGORITHM_FOR_EACH_N_HPP
#include <functional>
#include "../range_fwd.hpp"
#include "../range_traits.hpp"
#include "../range_concepts.hpp"
#include "../algorithm/tagspec.hpp"
#include "../utility/functional.hpp"
#include "../utility/iterator_traits.hpp"
#include "../utility/static_const.hpp"
#include "../utility/tagged_pair.hpp"
namespace ranges
{
inline namespace v3
{
/// \addtogroup group-algorithms
/// @{
struct for_each_n_fn
{
template<typename I, typename F, typename P = ident,
CONCEPT_REQUIRES_(InputIterator<I>() &&
MoveIndirectInvocable<F, projected<I, P>>())>
I operator()(I begin, difference_type_t<I> n, F fun, P proj = P{}) const
{
RANGES_EXPECT(0 <= n);
auto norig = n;
auto b = uncounted(begin);
for(; 0 < n; ++b, --n)
invoke(fun, invoke(proj, *b));
return recounted(begin, b, norig);
}
template<typename Rng, typename F, typename P = ident,
CONCEPT_REQUIRES_(InputRange<Rng>() &&
MoveIndirectInvocable<F, projected<iterator_t<Rng>, P>>())>
safe_iterator_t<Rng>
operator()(Rng &&rng, range_difference_type_t<Rng> n, F fun, P proj = P{}) const
{
if (SizedRange<Rng>())
RANGES_EXPECT(n <= distance(rng));
return (*this)(begin(rng), n, detail::move(fun), detail::move(proj));
}
};
/// \sa `for_each_n_fn`
/// \ingroup group-algorithms
RANGES_INLINE_VARIABLE(with_braced_init_args<for_each_n_fn>, for_each_n)
/// @}
} // namespace v3
} // namespace ranges
#endif // include guard
| thewizardplusplus/wizard-parser | source/thewizardplusplus/wizard_parser/vendor/range/v3/algorithm/for_each_n.hpp | C++ | mit | 2,247 |
class Solution:
# @param {integer[]} height
# @return {integer}
def largestRectangleArea(self, height):
n = len(height)
ma = 0
stack = [-1]
for i in xrange(n):
while(stack[-1] > -1):
if height[i]<height[stack[-1]]:
top = stack.pop()
ma = max(ma, height[top]*(i-1-stack[-1]))
else:
break
stack.append(i)
while(stack[-1] != -1):
top = stack.pop()
ma = max(ma, height[top]*(n-1-stack[-1]))
return ma | saai/codingbitch | DP/largestRectangleArea.py | Python | mit | 597 |
/* Magic Mirror
* Log
*
* This logger is very simple, but needs to be extended.
* This system can eventually be used to push the log messages to an external target.
*
* By Michael Teeuw https://michaelteeuw.nl
* MIT Licensed.
*/
(function (root, factory) {
if (typeof exports === "object") {
if (process.env.JEST_WORKER_ID === undefined) {
// add timestamps in front of log messages
require("console-stamp")(console, {
pattern: "yyyy-mm-dd HH:MM:ss.l",
include: ["debug", "log", "info", "warn", "error"]
});
}
// Node, CommonJS-like
module.exports = factory(root.config);
} else {
// Browser globals (root is window)
root.Log = factory(root.config);
}
})(this, function (config) {
let logLevel;
let enableLog;
if (typeof exports === "object") {
// in nodejs and not running with jest
enableLog = process.env.JEST_WORKER_ID === undefined;
} else {
// in browser and not running with jsdom
enableLog = typeof window === "object" && window.name !== "jsdom";
}
if (enableLog) {
logLevel = {
debug: Function.prototype.bind.call(console.debug, console),
log: Function.prototype.bind.call(console.log, console),
info: Function.prototype.bind.call(console.info, console),
warn: Function.prototype.bind.call(console.warn, console),
error: Function.prototype.bind.call(console.error, console),
group: Function.prototype.bind.call(console.group, console),
groupCollapsed: Function.prototype.bind.call(console.groupCollapsed, console),
groupEnd: Function.prototype.bind.call(console.groupEnd, console),
time: Function.prototype.bind.call(console.time, console),
timeEnd: Function.prototype.bind.call(console.timeEnd, console),
timeStamp: Function.prototype.bind.call(console.timeStamp, console)
};
logLevel.setLogLevel = function (newLevel) {
if (newLevel) {
Object.keys(logLevel).forEach(function (key, index) {
if (!newLevel.includes(key.toLocaleUpperCase())) {
logLevel[key] = function () {};
}
});
}
};
} else {
logLevel = {
debug: function () {},
log: function () {},
info: function () {},
warn: function () {},
error: function () {},
group: function () {},
groupCollapsed: function () {},
groupEnd: function () {},
time: function () {},
timeEnd: function () {},
timeStamp: function () {}
};
logLevel.setLogLevel = function () {};
}
return logLevel;
});
| Tyvonne/MagicMirror | js/logger.js | JavaScript | mit | 2,418 |
/**
* Dummy file for grunt-nodemon to run node-inspector task
*/
| rorymadden/angular-neo4j | node-inspector.js | JavaScript | mit | 67 |
'use strict';
var a = 0;
var b = 1;
var x = a;
var y = b;
console.log( x + y ); | Victorystick/rollup | test/form/skips-dead-branches-g/_expected/cjs.js | JavaScript | mit | 81 |
using System;
using System.Diagnostics;
namespace Palaso.Reporting
{
public class ConsoleErrorReporter:IErrorReporter
{
private enum Severity
{
Fatal,
NonFatal
}
public void ReportFatalException(Exception error)
{
WriteExceptionToConsole(error, null, Severity.Fatal);
}
public ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy, string alternateButton1Label, ErrorResult resultIfAlternateButtonPressed, string message)
{
if (!policy.ShouldShowMessage(message))
{
return ErrorResult.OK;
}
if (ErrorReport.IsOkToInteractWithUser)
{
if (ErrorReport.IsOkToInteractWithUser)
{
Console.WriteLine(message);
Console.WriteLine(policy.ReoccurenceMessage);
}
return ErrorResult.OK;
}
else
{
throw new ErrorReport.ProblemNotificationSentToUserException(message);
}
}
public void ReportNonFatalException(Exception exception, IRepeatNoticePolicy policy)
{
if (policy.ShouldShowErrorReportDialog(exception))
{
WriteExceptionToConsole(exception, null, Severity.NonFatal);
}
}
public void ReportNonFatalExceptionWithMessage(Exception error, string message, params object[] args)
{
var s = string.Format(message, args);
WriteExceptionToConsole(error, s, Severity.NonFatal);
}
public void ReportNonFatalMessageWithStackTrace(string message, params object[] args)
{
var s = string.Format(message, args);
var stack = new StackTrace(true);
WriteStackToConsole(s, stack, Severity.NonFatal);
}
public void ReportFatalMessageWithStackTrace(string message, object[] args)
{
var s = string.Format(message, args);
var stack = new StackTrace(true);
WriteStackToConsole(s, stack, Severity.Fatal);
}
//This implementation is a stripped down version of what is found in
//ExceptionReportingDialog.Report(string message, string messageBeforeStack, Exception error, Form owningForm)
private void WriteExceptionToConsole(Exception error, string message, Severity severity)
{
var textToReport = GetErrorStamp(severity);
Exception innerMostException = null;
textToReport += ErrorReport.GetHiearchicalExceptionInfo(error, ref innerMostException);
//if the exception had inner exceptions, show the inner-most exception first, since that is usually the one
//we want the developer to read.
if (innerMostException != null)
{
textToReport += "Inner-most exception:\r\n" + ErrorReport.GetExceptionText(innerMostException) +
"\r\n\r\nFull, hierarchical exception contents:\r\n" + textToReport;
}
textToReport += ErrorReportingProperties;
if (!string.IsNullOrEmpty(message))
{
textToReport += "Message (not an exception): " + message + Environment.NewLine;
textToReport += Environment.NewLine;
}
if (innerMostException != null)
{
error = innerMostException;
}
try
{
Logger.WriteEvent("Got exception " + error.GetType().Name);
}
catch (Exception err)
{
//We have more than one report of dieing while logging an exception.
textToReport += "****Could not write to log (" + err.Message + ")" + Environment.NewLine;
textToReport += "Was trying to log the exception: " + error.Message + Environment.NewLine;
textToReport += "Recent events:" + Environment.NewLine;
textToReport += Logger.MinorEventsLog;
}
Console.WriteLine(textToReport);
}
private static string GetErrorStamp(Severity severity)
{
var textToReport = String.Format("{0}:", DateTime.UtcNow.ToString("r")) + Environment.NewLine;
textToReport += "Severity: ";
switch (severity)
{
case Severity.Fatal:
textToReport = textToReport + "Fatal";
break;
case Severity.NonFatal:
textToReport = textToReport + "Warning";
break;
default:
throw new ArgumentOutOfRangeException("severity");
}
textToReport += Environment.NewLine;
return textToReport;
}
private string ErrorReportingProperties
{
get
{
var properties = "";
properties += Environment.NewLine + "--Error Reporting Properties--" + Environment.NewLine;
foreach (string label in ErrorReport.Properties.Keys)
{
properties += label + ": " + ErrorReport.Properties[label] + Environment.NewLine;
}
return properties;
}
}
//This implementation is a stripped down version of what is found in
//ExceptionReportingDialog.Report(string message, string messageBeforeStack, StackTrace stackTrace, Form owningForm)
private void WriteStackToConsole(string message, StackTrace stack, Severity severity)
{
var textToReport = GetErrorStamp(severity);
textToReport += "Message (not an exception): " + message + Environment.NewLine;
textToReport += Environment.NewLine;
textToReport += "--Stack--" + Environment.NewLine; ;
textToReport += stack.ToString() + Environment.NewLine; ;
textToReport += ErrorReportingProperties;
try
{
Logger.WriteEvent("Got error message " + message);
}
catch (Exception err)
{
//We have more than one report of dieing while logging an exception.
textToReport += "****Could not write to log (" + err.Message + ")" + Environment.NewLine;
}
Console.WriteLine(textToReport);
}
}
}
| phillip-hopper/libpalaso | Palaso/Reporting/ConsoleErrorReporter.cs | C# | mit | 5,229 |
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {MatButtonModule} from '@angular/material/button';
import {MatCardModule} from '@angular/material/card';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatIconModule} from '@angular/material/icon';
import {MatInputModule} from '@angular/material/input';
import {MatSelectModule} from '@angular/material/select';
import {MatToolbarModule} from '@angular/material/toolbar';
import {RouterModule} from '@angular/router';
import {SelectDemo} from './select-demo';
@NgModule({
imports: [
CommonModule,
FormsModule,
MatButtonModule,
MatCardModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatSelectModule,
MatToolbarModule,
ReactiveFormsModule,
RouterModule.forChild([{path: '', component: SelectDemo}]),
],
declarations: [SelectDemo],
})
export class SelectDemoModule {
}
| jelbourn/material2 | src/dev-app/select/select-demo-module.ts | TypeScript | mit | 1,215 |
'''
Created on Jan 18, 2010
@author: Paul
'''
from SQLEng import SQLEng
class PduSender(object):
'''
classdocs
This class is designed for Gammu-smsd
Inserting a record into MySQL
Gammu-smsd will send the record
Using command line will cause smsd stop for a while
'''
def get_mesg(self,byte_array):
mesg = ""
for byte in byte_array:
if byte < 16 :
val = hex(byte)
if val == "0x0" :
val = "00"
else :
val = val.lstrip("0x")
val = "{0}{1}".format('0', val)
else :
val = hex(byte)
val = val.lstrip("0x")
mesg += val
return mesg
def send(self,to,byte_array):
sEng = SQLEng()
sEng.exeSQL(sEng.getInsetSentBox(to, self.get_mesg(byte_array)))
def __init__(self):
'''
Constructor
'''
pass
| lubao/UjU_Windows | src/GammuSender.py | Python | mit | 1,013 |
from __future__ import absolute_import
# Copyright (c) 2010-2017 openpyxl
from .cell import Cell, WriteOnlyCell
from .read_only import ReadOnlyCell
| 171121130/SWI | venv/Lib/site-packages/openpyxl/cell/__init__.py | Python | mit | 149 |
from Robinhood import Robinhood
#Setup
my_trader = Robinhood(username="YOUR_USERNAME", password="YOUR_PASSWORD");
#Get stock information
#Note: Sometimes more than one instrument may be returned for a given stock symbol
stock_instrument = my_trader.instruments("GEVO")[0]
#Get a stock's quote
my_trader.print_quote("AAPL")
#Prompt for a symbol
my_trader.print_quote();
#Print multiple symbols
my_trader.print_quotes(stocks=["BBRY", "FB", "MSFT"])
#View all data for a given stock ie. Ask price and size, bid price and size, previous close, adjusted previous close, etc.
quote_info = my_trader.quote_data("GEVO")
print(quote_info);
#Place a buy order (uses market bid price)
buy_order = my_trader.place_buy_order(stock_instrument, 1)
#Place a sell order
sell_order = my_trader.place_sell_order(stock_instrument, 1)
| itsff/Robinhood | example.py | Python | mit | 826 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S12.10_A1.4_T4;
* @section: 12.10;
* @assertion: The with statement adds a computed object to the front of the
* scope chain of the current execution context;
* @description: Using "with" statement within iteration statement, leading to completion by break;
* @strict_mode_negative
*/
this.p1 = 1;
this.p2 = 2;
this.p3 = 3;
var result = "result";
var myObj = {p1: 'a',
p2: 'b',
p3: 'c',
value: 'myObj_value',
valueOf : function(){return 'obj_valueOf';},
parseInt : function(){return 'obj_parseInt';},
NaN : 'obj_NaN',
Infinity : 'obj_Infinity',
eval : function(){return 'obj_eval';},
parseFloat : function(){return 'obj_parseFloat';},
isNaN : function(){return 'obj_isNaN';},
isFinite : function(){return 'obj_isFinite';}
}
var del;
var st_p1 = "p1";
var st_p2 = "p2";
var st_p3 = "p3";
var st_parseInt = "parseInt";
var st_NaN = "NaN";
var st_Infinity = "Infinity";
var st_eval = "eval";
var st_parseFloat = "parseFloat";
var st_isNaN = "isNaN";
var st_isFinite = "isFinite";
do{
with(myObj){
st_p1 = p1;
st_p2 = p2;
st_p3 = p3;
st_parseInt = parseInt;
st_NaN = NaN;
st_Infinity = Infinity;
st_eval = eval;
st_parseFloat = parseFloat;
st_isNaN = isNaN;
st_isFinite = isFinite;
p1 = 'x1';
this.p2 = 'x2';
del = delete p3;
var p4 = 'x4';
p5 = 'x5';
var value = 'value';
break;
}
}
while(false);
if(!(p1 === 1)){
$ERROR('#1: p1 === 1. Actual: p1 ==='+ p1 );
}
if(!(p2 === "x2")){
$ERROR('#2: p2 === "x2". Actual: p2 ==='+ p2 );
}
if(!(p3 === 3)){
$ERROR('#3: p3 === 3. Actual: p3 ==='+ p3 );
}
if(!(p4 === "x4")){
$ERROR('#4: p4 === "x4". Actual: p4 ==='+ p4 );
}
if(!(p5 === "x5")){
$ERROR('#5: p5 === "x5". Actual: p5 ==='+ p5 );
}
if(!(myObj.p1 === "x1")){
$ERROR('#6: myObj.p1 === "x1". Actual: myObj.p1 ==='+ myObj.p1 );
}
if(!(myObj.p2 === "b")){
$ERROR('#7: myObj.p2 === "b". Actual: myObj.p2 ==='+ myObj.p2 );
}
if(!(myObj.p3 === undefined)){
$ERROR('#8: myObj.p3 === undefined. Actual: myObj.p3 ==='+ myObj.p3 );
}
if(!(myObj.p4 === undefined)){
$ERROR('#9: myObj.p4 === undefined. Actual: myObj.p4 ==='+ myObj.p4 );
}
if(!(myObj.p5 === undefined)){
$ERROR('#10: myObj.p5 === undefined. Actual: myObj.p5 ==='+ myObj.p5 );
}
if(!(st_parseInt !== parseInt)){
$ERROR('#11: myObj.parseInt !== parseInt');
}
if(!(st_NaN === "obj_NaN")){
$ERROR('#12: myObj.NaN !== NaN');
}
if(!(st_Infinity !== Infinity)){
$ERROR('#13: myObj.Infinity !== Infinity');
}
if(!(st_eval !== eval)){
$ERROR('#14: myObj.eval !== eval');
}
if(!(st_parseFloat !== parseFloat)){
$ERROR('#15: myObj.parseFloat !== parseFloat');
}
if(!(st_isNaN !== isNaN)){
$ERROR('#16: myObj.isNaN !== isNaN');
}
if(!(st_isFinite !== isFinite)){
$ERROR('#17: myObj.isFinite !== isFinite');
}
if(!(value === undefined)){
$ERROR('#18: value === undefined. Actual: value ==='+ value );
}
if(!(myObj.value === "value")){
$ERROR('#19: myObj.value === "value". Actual: myObj.value ==='+ myObj.value );
}
| rustoscript/js.rs | sputnik/12_Statement/12.10_The_with_Statement/S12.10_A1.4_T4.js | JavaScript | mit | 3,319 |
package domain;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* 全体系统消息
* Created by sibyl.sun on 16/2/22.
*/
public class Msg implements Serializable {
private static final long serialVersionUID = 1L;
private long msgId;//消息id
private String msgTitle; //消息标题
private String msgContent;//消息内容
private String msgImg; //消息商品图片
private String msgUrl; //消息跳转的URL
private String msgType; //消息类型
private Timestamp createAt; //创建时间
private Timestamp endAt;//失效时间
private String targetType; //T:主题,D:详细页面,P:拼购商品页,A:拼购活动页面,U:一个促销活动的链接
public long getMsgId() {
return msgId;
}
public void setMsgId(long msgId) {
this.msgId = msgId;
}
public String getMsgTitle() {
return msgTitle;
}
public void setMsgTitle(String msgTitle) {
this.msgTitle = msgTitle;
}
public String getMsgContent() {
return msgContent;
}
public void setMsgContent(String msgContent) {
this.msgContent = msgContent;
}
public String getMsgImg() {
return msgImg;
}
public void setMsgImg(String msgImg) {
this.msgImg = msgImg;
}
public String getMsgUrl() {
return msgUrl;
}
public void setMsgUrl(String msgUrl) {
this.msgUrl = msgUrl;
}
public Timestamp getCreateAt() {
return createAt;
}
public void setCreateAt(Timestamp createAt) {
this.createAt = createAt;
}
public Timestamp getEndAt() {
return endAt;
}
public void setEndAt(Timestamp endAt) {
this.endAt = endAt;
}
public String getTargetType() {
return targetType;
}
public void setTargetType(String targetType) {
this.targetType = targetType;
}
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
@Override
public String toString(){
return "Msg [msgTitle="+msgTitle+
",msgContent="+msgContent+
",msgImg="+msgImg+
",msgUrl="+msgUrl+
",msgType="+msgType+
",createAt="+createAt+
",endAt="+endAt+
",targetType="+targetType;
}
}
| howenkakao/style-web | app/domain/Msg.java | Java | mit | 2,436 |
///////////////////////////////////////////////////////////////////////////////
//
// File : $Id: _rb.cpp 27 2006-05-20 19:31:15Z mbabuskov $
// Subject : IBPP, internal RB class implementation
//
///////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright 2000-2006 T.I.P. Group S.A. and the IBPP Team (www.ibpp.org)
//
// The contents of this file are subject to the IBPP License (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.ibpp.org or in the 'license.txt'
// file which must have been distributed along with this file.
//
// This software, distributed under the License, is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
// License for the specific language governing rights and limitations
// under the License.
//
///////////////////////////////////////////////////////////////////////////////
//
// COMMENTS
// * RB == Result Block/Buffer, see Interbase 6.0 C-API
// * Tabulations should be set every four characters when editing this file.
//
///////////////////////////////////////////////////////////////////////////////
#ifdef _MSC_VER
#pragma warning(disable: 4786 4996)
#ifndef _DEBUG
#pragma warning(disable: 4702)
#endif
#endif
#include "_ibpp.h"
#ifdef HAS_HDRSTOP
#pragma hdrstop
#endif
using namespace ibpp_internals;
char* RB::FindToken(char token)
{
char* p = mBuffer;
while (*p != isc_info_end)
{
int len;
if (*p == token) return p;
len = (*gds.Call()->m_vax_integer)(p+1, 2);
p += (len + 3);
}
return 0;
}
char* RB::FindToken(char token, char subtoken)
{
char* p = mBuffer;
while (*p != isc_info_end)
{
int len;
if (*p == token)
{
// Found token, now find subtoken
int inlen = (*gds.Call()->m_vax_integer)(p+1, 2);
p += 3;
while (inlen > 0)
{
if (*p == subtoken) return p;
len = (*gds.Call()->m_vax_integer)(p+1, 2);
p += (len + 3);
inlen -= (len + 3);
}
return 0;
}
len = (*gds.Call()->m_vax_integer)(p+1, 2);
p += (len + 3);
}
return 0;
}
int RB::GetValue(char token)
{
int value;
int len;
char* p = FindToken(token);
if (p == 0)
throw LogicExceptionImpl("RB::GetValue", _("Token not found."));
len = (*gds.Call()->m_vax_integer)(p+1, 2);
if (len == 0) value = 0;
else value = (*gds.Call()->m_vax_integer)(p+3, (short)len);
return value;
}
int RB::GetCountValue(char token)
{
// Specifically used on tokens like isc_info_insert_count and the like
// which return detailed counts per relation. We sum up the values.
int value;
int len;
char* p = FindToken(token);
if (p == 0)
throw LogicExceptionImpl("RB::GetCountValue", _("Token not found."));
// len is the number of bytes in the following array
len = (*gds.Call()->m_vax_integer)(p+1, 2);
p += 3;
value = 0;
while (len > 0)
{
// Each array item is 6 bytes : 2 bytes for the relation_id which
// we skip, and 4 bytes for the count value which we sum up accross
// all tables.
value += (*gds.Call()->m_vax_integer)(p+2, 4);
p += 6;
len -= 6;
}
return value;
}
int RB::GetValue(char token, char subtoken)
{
int value;
int len;
char* p = FindToken(token, subtoken);
if (p == 0)
throw LogicExceptionImpl("RB::GetValue", _("Token/Subtoken not found."));
len = (*gds.Call()->m_vax_integer)(p+1, 2);
if (len == 0) value = 0;
else value = (*gds.Call()->m_vax_integer)(p+3, (short)len);
return value;
}
bool RB::GetBool(char token)
{
int value;
char* p = FindToken(token);
if (p == 0)
throw LogicExceptionImpl("RB::GetBool", _("Token not found."));
value = (*gds.Call()->m_vax_integer)(p+1, 4);
return value == 0 ? false : true;
}
int RB::GetString(char token, std::string& data)
{
int len;
char* p = FindToken(token);
if (p == 0)
throw LogicExceptionImpl("RB::GetString", _("Token not found."));
len = (*gds.Call()->m_vax_integer)(p+1, 2);
data = std::string(p+3, len);
return len;
}
void RB::Reset()
{
delete [] mBuffer;
mBuffer = new char [mSize];
memset(mBuffer, 255, mSize);
}
RB::RB()
{
mSize = 1024;
mBuffer = new char [1024];
memset(mBuffer, 255, mSize);
}
RB::RB(int Size)
{
mSize = Size;
mBuffer = new char [Size];
memset(mBuffer, 255, mSize);
}
RB::~RB()
{
try { delete [] mBuffer; }
catch (...) { }
}
//
// EOF
//
| cyborgve/FBExport | ibpp/_rb.cpp | C++ | mit | 4,364 |
package main
import (
"compress/gzip"
"fmt"
"io/ioutil"
"os"
)
func main() {
fpath := "test.tar.gz"
if err := toGzip("Hello World!", fpath); err != nil {
panic(err)
}
if tb, err := toBytes(fpath); err != nil {
panic(err)
} else {
fmt.Println(fpath, ":", string(tb))
// test.tar.gz : Hello World!
}
os.Remove(fpath)
}
// exec.Command("gzip", "-f", fpath).Run()
func toGzip(txt, fpath string) error {
f, err := os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0777)
if err != nil {
f, err = os.Create(fpath)
if err != nil {
return err
}
}
defer f.Close()
gw := gzip.NewWriter(f)
if _, err := gw.Write([]byte(txt)); err != nil {
return err
}
gw.Close()
gw.Flush()
return nil
}
func toBytes(fpath string) ([]byte, error) {
f, err := os.OpenFile(fpath, os.O_RDONLY, 0444)
if err != nil {
return nil, err
}
defer f.Close()
fz, err := gzip.NewReader(f)
if err != nil {
return nil, err
}
defer fz.Close()
// or JSON
// http://jmoiron.net/blog/crossing-streams-a-love-letter-to-ioreader/
s, err := ioutil.ReadAll(fz)
if err != nil {
return nil, err
}
return s, nil
}
| mmoya/learn | doc/go_os_io/code/16_gzip.go | GO | mit | 1,116 |
require 'spec_helper'
describe PagesController, type: :controller do
render_views
it "#index" do
get :index
expect(response).to render_template(:index)
expect(response).to have_http_status(:success)
end
end
| sethetter/startupwichita.com | spec/controllers/pages_controller_spec.rb | Ruby | mit | 228 |
<?php require("includes/helpers.php"); ?>
<?php render("header", ["title" => "Week 0"]); ?>
<ul>
<li><a href="http://cdn.cs50.net/2013/fall/lectures/0/w/week0w.pdf">Wednesday</a></li>
<li><a href="http://cdn.cs50.net/2013/fall/lectures/0/f/week0f.pdf">Friday</a></li>
</ul>
<?php render("footer"); ?>
| karanaditya993/karans-code-samples | code/php/mvc/mvc2/public/week0.php | PHP | mit | 308 |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// A constant buffer exposed by an effect.
/// </summary>
/// <remarks>
/// Constant buffers are created and shared inside a same <see cref="EffectPool"/>. The creation of the underlying GPU buffer
/// can be overridden using <see cref="EffectPool.ConstantBufferAllocator"/>.
/// </remarks>
public sealed class EffectConstantBuffer : DataBuffer, IEquatable<EffectConstantBuffer>
{
private GraphicsDevice device;
private readonly Buffer nativeBuffer;
internal EffectData.ConstantBuffer Description;
private readonly int hashCode;
internal EffectConstantBuffer(GraphicsDevice device, EffectData.ConstantBuffer description) : base(description.Size)
{
this.device = device;
Description = description;
Name = description.Name;
Parameters = new EffectParameterCollection(description.Parameters.Count);
hashCode = description.GetHashCode();
// Add all parameters to this constant buffer.
for (int i = 0; i < description.Parameters.Count; i++)
{
var parameterRaw = description.Parameters[i];
var parameter = new EffectParameter(parameterRaw, this) {Index = i};
Parameters.Add(parameter);
}
// By default, all constant buffers are cleared with 0
Clear();
nativeBuffer = ToDispose(Buffer.Constant.New(device, Size));
// The buffer is considered dirty for the first usage.
IsDirty = true;
}
/// <summary>
/// Set this flag to true to notify that the buffer was changed
/// </summary>
/// <remarks>
/// When using Set(value) methods on this buffer, this property must be set to true to ensure that the buffer will
/// be uploaded.
/// </remarks>
public bool IsDirty;
/// <summary>
/// Gets the parameters registered for this constant buffer.
/// </summary>
public readonly EffectParameterCollection Parameters;
/// <summary>
/// Updates the specified constant buffer from all parameters value.
/// </summary>
public void Update()
{
Update(device);
}
/// <summary>
/// Copies the CPU content of this buffer to another constant buffer.
/// Destination buffer will be flagged as dirty.
/// </summary>
/// <param name="toBuffer">To buffer to receive the content.</param>
public void CopyTo(EffectConstantBuffer toBuffer)
{
if (toBuffer == null)
throw new ArgumentNullException("toBuffer");
if (Size != toBuffer.Size)
{
throw new ArgumentOutOfRangeException("toBuffer",
"Size of the source and destination buffer are not the same");
}
Utilities.CopyMemory(toBuffer.DataPointer, DataPointer, Size);
toBuffer.IsDirty = true;
}
/// <summary>
/// Updates the specified constant buffer from all parameters value.
/// </summary>
/// <param name="device">The device.</param>
public void Update(GraphicsDevice device)
{
if (IsDirty)
{
nativeBuffer.SetData(device, new DataPointer(DataPointer, Size));
IsDirty = false;
}
}
public bool Equals(EffectConstantBuffer other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
// Fast comparison using hashCode.
return hashCode == other.hashCode && Description.Equals(other.Description);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((EffectConstantBuffer) obj);
}
public override int GetHashCode()
{
// Return precalculated hashcode
return hashCode;
}
public static bool operator ==(EffectConstantBuffer left, EffectConstantBuffer right)
{
return Equals(left, right);
}
public static bool operator !=(EffectConstantBuffer left, EffectConstantBuffer right)
{
return !Equals(left, right);
}
public static implicit operator SharpDX.Direct3D11.Buffer(EffectConstantBuffer from)
{
return from.nativeBuffer;
}
public static implicit operator Buffer(EffectConstantBuffer from)
{
return from.nativeBuffer;
}
}
} | VirusFree/SharpDX | Source/Toolkit/SharpDX.Toolkit.Graphics/EffectConstantBuffer.cs | C# | mit | 6,095 |
frappe.ui.form.ControlCurrency = frappe.ui.form.ControlFloat.extend({
format_for_input: function(value) {
var formatted_value = format_number(value, this.get_number_format(), this.get_precision());
return isNaN(parseFloat(value)) ? "" : formatted_value;
},
get_precision: function() {
// always round based on field precision or currency's precision
// this method is also called in this.parse()
if (!this.df.precision) {
if(frappe.boot.sysdefaults.currency_precision) {
this.df.precision = frappe.boot.sysdefaults.currency_precision;
} else {
this.df.precision = get_number_format_info(this.get_number_format()).precision;
}
}
return this.df.precision;
}
});
| vjFaLk/frappe | frappe/public/js/frappe/form/controls/currency.js | JavaScript | mit | 697 |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M19 5c0-1.1-.9-2-2-2h-6.17c-.53 0-1.04.21-1.42.59L7.95 5.06 19 16.11V5zM3.09 4.44c-.39.39-.39 1.02 0 1.41L5 7.78V19c0 1.11.9 2 2 2h11.23l.91.91c.39.39 1.02.39 1.41 0 .39-.39.39-1.02 0-1.41L4.5 4.44a.9959.9959 0 0 0-1.41 0z"
}), 'SignalCellularNoSimRounded');
exports.default = _default; | oliviertassinari/material-ui | packages/mui-icons-material/lib/SignalCellularNoSimRounded.js | JavaScript | mit | 704 |
describe('ngThrottleSpec', function() {
var $animate, body, $rootElement, $throttle, $timeout;
beforeEach(module('material.services.throttle', 'material.animations'));
beforeEach(inject(function(_$throttle_, _$timeout_, _$animate_, _$rootElement_, $document ){
$throttle = _$throttle_;
$timeout = _$timeout_;
$animate = _$animate_;
$rootElement = _$rootElement_;
body = angular.element($document[0].body);
body.append($rootElement);
}));
describe('use $throttle with no configurations', function() {
var finished, started, ended;
var done = function() { finished = true; };
beforeEach( function() { finished = started = ended = false; });
it("should start and end without configuration",function() {
var process = $throttle()( done );
$timeout.flush();
expect(finished).toBe(true);
});
it("should run process function without throttle configuration",function() {
var process = $throttle()( done );
process("a");
$timeout.flush();
expect(finished).toBe(true);
});
it("should start and end with `done` callbacks",function() {
var startFn = function(done){ started = true; done(); };
var process = $throttle({start:startFn})( done );
expect(process).toBeDefined();
expect(started).toBe(false);
$timeout.flush(); // flush start()
expect(started).toBe(true);
expect(finished).toBe(true);
});
it("should start and end withOUT `done` callbacks",function() {
var startFn = function(){ started = true; };
var endFn = function(){ ended = true; };
var process = $throttle({start:startFn, end:endFn})( done );
$timeout.flush(); // throttle()
expect(started).toBe(true);
expect(ended).toBe(true);
expect(finished).toBe(true);
});
it("should start without throttle or end calls specified",function() {
var startFn = function(){ started = true; };
var throttledFn = $throttle({start:startFn})();
$timeout.flush();
expect(started).toBe(true);
});
it("should start but NOT end if throttle does not complete",function() {
var startFn = function(){ started = true;},
endFn = function(){ ended = true;};
lockFn = function(done){ ; }, // do not callback for completion
$throttle({start:startFn, throttle:lockFn, end:endFn})();
$timeout.flush();
expect(started).toBe(true);
expect(ended).toBe(false);
});
});
describe('use $throttle with synchronous processing', function() {
it("should process n-times correctly",function() {
var wanted="The Hulk";
var sCount=0, title="",
startFn = function(){
sCount++;
},
processFn = function(text, done){
title += text;
if ( title == wanted ) {
// Conditional termination of throttle phase
done();
}
};
concat = $throttle({start:startFn, throttle:processFn})( );
concat("The ");
concat("Hulk");
$timeout.flush();
expect(title).toBe(wanted);
});
it("should properly process with report callbacks",function() {
var pCount= 10, total, callCount= 0,
processFn = function(count, done){
pCount -= count;
if ( pCount == 5 ) {
// Conditional termination of throttle phase
// report total value in callback
done(pCount);
}
},
/**
* only called when ALL processing is done
*/
reportFn = function(count){ total = count; callCount +=1;},
subtract = $throttle({throttle:processFn})( );
subtract(2, reportFn );
subtract(3, reportFn );
$timeout.flush();
expect(total).toBe(5);
expect(callCount).toBe(1);
});
it("should restart if already finished",function() {
var total= 0, started = 0,
startFn = function(){
started += 1;
},
processFn = function(count, done){
total += count;
done(); // !!finish throttling
},
add = $throttle({start:startFn, throttle:processFn})();
add(1); $timeout.flush(); // proceed to end()
add(1); $timeout.flush(); // proceed to end()
add(1); $timeout.flush(); // proceed to end()
expect(total).toBe(3);
expect(started).toBe(3); // restarted 1x
});
});
describe('use $throttle with exceptions', function() {
it("should report error within start()", function() {
var started = false;
var error = "";
var fn = $throttle({start:function(done){
started = true;
throw new Error("fault_with_start");
}})(null, function(fault){
error = fault;
});
$timeout.flush();
expect(started).toBe(true);
expect(error).toNotBe("");
});
it("should report error within end()", function() {
var ended = false, error = "";
var config = { end : function(done){
ended = true;
throw new Error("fault_with_end");
}};
var captureError = function(fault) { error = fault; };
$throttle(config)(null, captureError );
$timeout.flush();
expect(ended).toBe(true);
expect(error).toNotBe("");
});
it("should report error within throttle()", function() {
var count = 0, error = "";
var config = { throttle : function(done){
count += 1;
switch(count)
{
case 1 : break;
case 2 : throw new Error("fault_with_throttle"); break;
case 3 : done(); break;
}
}};
var captureError = function(fault) { error = fault; };
var fn = $throttle(config)(null, captureError );
$timeout.flush();
fn( 1 );
fn( 2 );
fn( 3 );
expect(count).toBe(2);
expect(error).toNotBe("");
});
});
describe('use $throttle with async processing', function() {
var finished = false;
var done = function() { finished = true; };
beforeEach( function() { finished = false; });
it("should pass with async start()",function() {
var sCount=0,
startFn = function(){
return $timeout(function(){
sCount++;
},100)
},
concat = $throttle({start:startFn})( done );
concat("The ");
concat("Hulk");
$timeout.flush();
expect(sCount).toBe(1);
});
it("should pass with async start(done)",function() {
var sCount=0,
startFn = function(done){
return $timeout(function(){
sCount++;
done();
},100)
},
concat = $throttle({start:startFn})( done );
concat("The ");
concat("Hulk");
$timeout.flush(); // flush to begin 1st deferred start()
expect(sCount).toBe(1);
});
it("should pass with async start(done) and end(done)",function() {
var sCount=3, eCount= 0,
startFn = function(done){
return $timeout(function(){
sCount--;
done();
},100)
},
endFn = function(done){
return $timeout(function(){
eCount++;
done();
},100)
};
$throttle({start:startFn, end:endFn})( done );
$timeout.flush(); // flush to begin 1st deferred start()
$timeout.flush(); // start()
$timeout.flush(); // end()
expect(sCount).toBe(2);
expect(eCount).toBe(1);
expect(finished).toBe(true);
});
it("should pass with async start(done) and process(done)",function() {
var title="",
startFn = function(){
return $timeout(function(){
done();
},200);
},
processFn = function(data, done){
$timeout(function(){
title += data;
},400);
},
concat = $throttle({start:startFn, throttle:processFn})( done );
$timeout.flush(); // start()
concat("The "); $timeout.flush(); // throttle(1)
concat("Hulk"); $timeout.flush(); // throttle(2)
expect(title).toBe("The Hulk");
});
it("should pass with async process(done) and restart with cancellable end",function() {
var content="", numStarts= 0, numEnds = 0,
startFn = function(done){
numStarts++;
done("start-done");
},
throttleFn = function(data, done){
$timeout(function(){
content += data;
if ( data == "e" ) {
done("throttle-done");
}
},400);
},
endFn = function(done){
numEnds++;
var procID = $timeout(function(){
done("end-done");
},500,false);
return function() {
$timeout.cancel( procID );
};
},
concat = $throttle({ start:startFn, throttle:throttleFn, end:endFn })( done );
$timeout.flush(); // flush to begin 1st start()
concat("a"); // Build string...
concat("b");
concat("c");
concat("d");
concat("e"); // forces end()
$timeout.flush(); // flush to throttle( 5x )
$timeout(function(){
concat("a"); // forces restart()
concat("e"); // forces end()
},400,false);
$timeout.flush(); // flush() 278
$timeout.flush(); // flush to throttle( 2x )
expect(content).toBe("abcdeae");
expect(numStarts).toBe(2);
expect(numEnds).toBe(2);
});
});
describe('use $throttle with inkRipple', function(){
var finished, started, ended;
var done = function() { finished = true; };
beforeEach( function() { finished = started = ended = false; });
function setup() {
var el;
var tmpl = '' +
'<div style="width:50px; height:50px;">'+
'<canvas class="material-ink-ripple" ></canvas>' +
'</div>';
inject(function($compile, $rootScope) {
el = $compile(tmpl)($rootScope);
$rootElement.append( el );
$rootScope.$apply();
});
return el;
}
it('should start, animate, and end.', inject(function($compile, $rootScope, $materialEffects) {
var cntr = setup(),
canvas = cntr.find('canvas'),
rippler, makeRipple, throttled = 0,
config = {
start : function() {
rippler = rippler || $materialEffects.inkRipple( canvas[0] );
cntr.on('mousedown', makeRipple);
started = true;
},
throttle : function(e, done) {
throttled += 1;
switch(e.type)
{
case 'mousedown' :
rippler.createAt( {x:25,y:25} );
rippler.draw( done );
break;
default:
break;
}
}
}
// prepare rippler wave function...
makeRipple = $throttle(config)(done);
$timeout.flush();
expect(started).toBe(true);
// trigger wave animation...
cntr.triggerHandler("mousedown");
// Allow animation to finish...
$timeout(function(){
expect(throttled).toBe(1);
expect(ended).toBe(true);
expect(finished).toBe(true);
},10);
// Remove from $rootElement
cntr.remove();
}));
});
});
| Hotell/ng-material-demo | src/services/throttle/throttle.spec.js | JavaScript | mit | 11,313 |
<?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\AdminBundle\Util;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Exception\AclAlreadyExistsException;
use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Security\Handler\AclSecurityHandlerInterface;
abstract class ObjectAclManipulator implements ObjectAclManipulatorInterface
{
/**
* Configure the object ACL for the passed object identities
*
* @param OutputInterface $output
* @param AdminInterface $admin
* @param array $oids an array of ObjectIdentityInterface implementations
* @param UserSecurityIdentity $securityIdentity
* @throws \Exception
* @return array [countAdded, countUpdated]
*/
public function configureAcls(OutputInterface $output, AdminInterface $admin, array $oids, UserSecurityIdentity $securityIdentity = null)
{
$countAdded = 0;
$countUpdated = 0;
$securityHandler = $admin->getSecurityHandler();
if (!$securityHandler instanceof AclSecurityHandlerInterface) {
$output->writeln(sprintf('Admin `%s` is not configured to use ACL : <info>ignoring</info>', $admin->getCode()));
return;
}
$acls = $securityHandler->findObjectAcls($oids);
foreach ($oids as $oid) {
if ($acls->contains($oid)) {
$acl = $acls->offsetGet($oid);
$countUpdated++;
} else {
$acl = $securityHandler->createAcl($oid);
$countAdded++;
}
if (!is_null($securityIdentity)) {
// add object owner
$securityHandler->addObjectOwner($acl, $securityIdentity);
}
$securityHandler->addObjectClassAces($acl, $securityHandler->buildSecurityInformation($admin));
try {
$securityHandler->updateAcl($acl);
} catch(\Exception $e) {
$output->writeln(sprintf('Error saving ObjectIdentity (%s, %s) ACL : %s <info>ignoring</info>', $oid->getIdentifier(), $oid->getType(), $e->getMessage()));
}
}
return array($countAdded, $countUpdated);
}
} | carechimba/symfony | vendor/bundles/Sonata/AdminBundle/Util/ObjectAclManipulator.php | PHP | mit | 2,500 |
//Libraries
const React = require("react");
const _ = require("lodash");
const DataActions = require("../actions/data_actions");
const DataStore = require("../stores/data_store");
const FilterStore = require("../stores/filter_store");
const ColumnsStore = require("../stores/columns_store");
//Mixins
const cssMixins = require("morse-react-mixins").css_mixins;
const textMixins = require("morse-react-mixins").text_mixins;
class SearchFilters extends React.Component{
constructor(props) {
super(props);
this.dropdown = ["input-group-btn", {"open":false}];
this.state = {
dropdown:this.getClasses(this.dropdown),
expanded:"false",
selectedkey:"all",
searchVal:""
};
}
componentDidMount() {
this.quickSearch = (_.isBoolean(this.props.quickSearch)) ? this.props.quickSearch : true;
if(FilterStore.isSelectedKey(this.props.item)){
this.active = [{active:true}];
this.setState({active:this.getClasses(this.active)});
}
this.setState({searchVal:DataStore.getSearchVal()});
// FilterStore.addChangeListener("change_key", this._openDropdown.bind(this));
ColumnsStore.addChangeListener("adding", this._onAdd.bind(this));
}
componentWillUnmount() {
// FilterStore.removeChangeListener("change_key", this._openDropdown);
ColumnsStore.removeChangeListener("adding", this._onAdd);
}
_onAdd(){
this.setState({
keys:ColumnsStore.getSearchable()
});
}
_onChange(e){
if(this.quickSearch){
if(this.loop){
window.clearTimeout(this.loop);
}
this.loop = window.setTimeout((val)=>{
if(val.length > 2 || val === ""){
DataActions.searching(val);
}
}, 200, e.target.value);
this.setState({searchVal:e.target.value});
}
// _.defer((val)=>{
// DataActions.searching(val);
// }, e.target.value);
}
// _openDropdown(){
// this.dropdown = this.toggleCss(this.dropdown);
// let expanded = (this.state.expended === "true") ? "false" : "true";
// this.setState({
// dropdown:this.getClasses(this.dropdown),
// expanded:expanded,
// selectedkey:FilterStore.getSelectedKey()
// });
// }
_preventSubmit(e){
// console.log("submiting", e);
e.preventDefault();
}
// renderKeys(){
// if(this.state.keys){
// let items = this.state.keys.map(function(k){
// return (<Keys item={k} key={_.uniqueId("key")} />);
// });
// return items;
// }
// }
render() {
return (
<form onSubmit={this._preventSubmit.bind(this)} className="search-filter">
<input alt="Search" type="image" src={this.props.icon} />
<div className="fields-container">
<input type="text" name="querystr" id="querystr" placeholder="Search" value={this.state.searchVal} onChange={this._onChange.bind(this)} />
</div>
</form>
);
}
}
Object.assign(SearchFilters.prototype, cssMixins);
Object.assign(SearchFilters.prototype, textMixins);
module.exports = SearchFilters;
| djforth/walkabout-jobs-search | src/vanilla_components/searchfilter.js | JavaScript | mit | 3,083 |
#
# The MIT License
#
# Copyright (c) 2010 Samuel R. Baskinger
#
# 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.
#
module SClust
module Util
class Word
attr_reader :word, :weight, :data
attr_writer :word, :weight, :data
def initialize(word="", weight=0.0, other_data={})
@word = word
@weight = weight
@data = other_data
end
# Return @word.
def to_s
@word
end
def hash
@word.hash
end
def eql?(w)
@word.eql?(w)
end
end
end
end
| basking2/sclust | lib/sclust/util/word.rb | Ruby | mit | 1,753 |
class Api::V1::ProblemsController < ApplicationController
skip_before_action :verify_authenticity_token
respond_to :json, :xml
rescue_from ActiveRecord::RecordNotFound do
head :not_found
end
expose(:err) { Err.find(params[:id]) }
expose(:problem) { err.problem }
expose(:selected_problems) { Problem.where(id: params[:problems]) }
def index
problems = Problem.all
if params.key?(:start_date) && params.key?(:end_date)
start_date = Time.parse(params[:start_date]).utc
end_date = Time.parse(params[:end_date]).utc
problems = problems.in_date_range(start_date..end_date)
end
if params.key?(:since)
since = Time.parse(params[:since]).utc
problems = problems.occurred_since(since)
end
if params.key?(:app_id)
problems = problems.where(app_id: params[:app_id])
end
if params[:open].to_s.downcase == "true"
problems = problems.unresolved
end
presenter = ProblemPresenter
if params[:comments].to_s.downcase == "true"
problems = problems.includes(comments: :user)
presenter = ProblemWithCommentsPresenter
end
respond_to do |format|
format.html { render json: presenter.new(self, problems) } # render JSON if no extension specified on path
format.json { render json: presenter.new(self, problems) }
format.xml { render xml: presenter.new(self, problems).as_json }
end
end
def changed
begin
since = Time.parse(params.fetch(:since)).utc
rescue KeyError
render json: { ok: false, message: "'since' is a required parameter" }, status: 400
return
rescue ArgumentError
render json: { ok: false, message: "'since' must be an ISO8601 formatted timestamp" }, status: 400
return
end
problems = Problem.with_deleted.changed_since(since)
problems = problems.where(app_id: params[:app_id]) if params.key?(:app_id)
presenter = ProblemWithDeletedPresenter
respond_to do |format|
format.html { render json: presenter.new(self, problems) } # render JSON if no extension specified on path
format.json { render json: presenter.new(self, problems) }
format.xml { render xml: presenter.new(self, problems).as_json }
end
end
def resolve
unless problem.resolved?
err.comments.create!(body: params[:message]) if params[:message]
problem.resolve!
end
head :ok
end
def unresolve
problem.unresolve!
head :ok
end
def merge_several
if selected_problems.length < 2
render json: I18n.t('controllers.problems.flash.need_two_errors_merge'), status: 422
else
count = selected_problems.count
ProblemMerge.new(selected_problems).merge
render json: I18n.t('controllers.problems.flash.merge_several.success', nb: count), status: 200
end
end
def unmerge_several
if selected_problems.length < 1
render json: I18n.t('controllers.problems.flash.no_select_problem'), status: 422
else
all = selected_problems.map(&:unmerge!).flatten
render json: "#{I18n.t(:n_errs_have, count: all.length)} been unmerged.", status: 200
end
end
def destroy_several
if selected_problems.length < 1
render json: I18n.t('controllers.problems.flash.no_select_problem'), status: 422
else
nb_problem_destroy = ProblemDestroy.execute(selected_problems)
render json: "#{I18n.t(:n_errs_have, count: nb_problem_destroy)} been deleted.", status: 200
end
end
end
| cph/errbit | app/controllers/api/v1/problems_controller.rb | Ruby | mit | 3,489 |
/* State
* @class
* @classdesc This class reprensent an automata state, a sub-type of a generic Node */
k.data.State = (function(_super)
{
'use strict';
/* jshint latedef:false */
k.utils.obj.inherit(state, _super);
/*
* Constructor Automata State
*
* @constructor
* @param {[ItemRule]} options.items Array of item rules that initialy compone this state
* @param {[Object]} options.transitions Array of object that initialy compone this node
* @param {[Node]} options.nodes Array of State instances that are children of this State
*/
function state (options) {
_super.apply(this, arguments);
k.utils.obj.defineProperty(this, 'isAcceptanceState'); // This is set by the automata generator
k.utils.obj.defineProperty(this, '_items');
k.utils.obj.defineProperty(this, '_registerItems');
k.utils.obj.defineProperty(this, '_condencedView');
k.utils.obj.defineProperty(this, '_unprocessedItems');
this.isAcceptanceState = false;
this._items = options.items || [];
this._unprocessedItems = this._items.length ? k.utils.obj.shallowClone(this._items) : [];
options.items = null;
this._registerItems = {};
this._registerItemRules();
}
/* @method REgister the list of item rules of the current stateso they are assesible by its id
* @returns {Void} */
state.prototype._registerItemRules = function ()
{
k.utils.obj.each(this._items, function (itemRule)
{
this._registerItems[itemRule.getIdentity()] = itemRule;
}, this);
};
state.constants = {
AcceptanceStateName: 'AcceptanceState'
};
/* @method Get the next unprocessed item rule
* @returns {ItemRule} Next Item Rule */
state.prototype.getNextItem = function() {
return this._unprocessedItems.splice(0,1)[0];
};
/* @method Adds an array of item rule into the state. Only the rules that are not already present in the state will be added
* @param {[ItemRule]} itemRules Array of item rules to add into the state
* @param {Boolean} options.notMergeLookAhead If specified as true does not marge the lookAhead of the already existing items. Default: falsy
* @returns {void} Nothing */
state.prototype.addItems = function(itemRules, options) {
this._id = null;
k.utils.obj.each(itemRules, function (itemRule)
{
// The same item rule can be added more than once if the grammar has loops.
// For sample: (1)S -> A *EXPS B (2)EXPS -> *EXPS
if (!this._registerItems[itemRule.getIdentity()])
{
this._registerItems[itemRule.getIdentity()] = itemRule;
this._items.push(itemRule);
this._unprocessedItems.push(itemRule);
}
else if (!options || !options.notMergeLookAhead)
{
//As a way of generating a LALR(1) automata adds a item rule for each lookAhead we simply merge its lookAheads
var original_itemRule = this._registerItems[itemRule.getIdentity()];
if (itemRule.lookAhead && itemRule.lookAhead.length)
{
original_itemRule.lookAhead = original_itemRule.lookAhead || [];
itemRule.lookAhead = itemRule.lookAhead || [];
var mergedLookAheads = original_itemRule.lookAhead.concat(itemRule.lookAhead),
original_itemRule_lookAhead_length = this._registerItems[itemRule.getIdentity()].lookAhead.length;
this._registerItems[itemRule.getIdentity()].lookAhead = k.utils.obj.uniq(mergedLookAheads, function (item) { return item.name;});
var is_item_already_queued = k.utils.obj.filter(this._unprocessedItems, function (unprocessed_item)
{
return unprocessed_item.getIdentity() === itemRule.getIdentity();
}).length > 0;
//If there were changes in the lookAhead and the rule is not already queued.
if (original_itemRule_lookAhead_length !== this._registerItems[itemRule.getIdentity()].lookAhead.length && !is_item_already_queued)
{
this._unprocessedItems.push(itemRule);
}
}
}
}, this);
};
/* @method Convert the current state to its string representation
* @returns {String} formatted string */
state.prototype.toString = function() {
var strResult = 'ID: ' + this.getIdentity() + '\n' +
this._items.join('\n') +
'\nTRANSITIONS:\n';
k.utils.obj.each(this.transitions, function (transition)
{
strResult += '*--' + transition.symbol + '-->' + transition.state.getIdentity() + '\n';
});
return strResult;
};
/* @method Returns the condenced (one line) string that reprenset the current 'state' of the current state
* @returns {String} State Representation in one line */
state.prototype.getCondencedString = function() {
if(!this._condencedView)
{
this._condencedView = this._generateCondencedString();
}
return this._condencedView;
};
/* @method Internal method to generate a condenced (one line) string that reprenset the current 'state' of the current state
* @returns {String} State Representation in one line */
state.prototype._generateCondencedString = function() {
return k.utils.obj.map(
k.utils.obj.sortBy(this._items, function(item)
{
return item.rule.index;
}),
function (item) {
return item.rule.index;
}).join('-');
};
/* @method Generates an ID that identify this state from any other state
* @returns {String} Generated ID */
state.prototype._generateIdentity = function() {
if (this.isAcceptanceState)
{
return state.constants.AcceptanceStateName;
}
else if (!this._items.length)
{
return _super.prototype._generateIdentity.apply(this, arguments);
}
return k.utils.obj.reduce(
k.utils.obj.sortBy(this._items, function(item)
{
return item.rule.index;
}),
function (acc, item) {
return acc + item.getIdentity(); //.rule.index + '(' + item.dotLocation + ')';
}, '');
};
/* @method Returns a copy the items contained in the current state
* @returns {[ItemRule]} Array of cloned item rules */
state.prototype.getItems = function() {
return k.utils.obj.map(this._items, function(item) {
return item.clone();
});
};
/* @method Returns an orignal item rule based on its id.
This method is intended to be use as READ-ONLY, editing the returned items will affect the state and the rest of the automata at with this state belongs to.
* @returns {[ItemRule]} Array of current item rules */
state.prototype.getOriginalItems = function() {
return this._items;
};
/* @method Returns an orignal item rule based on its id.
This method is intended to be use as READ-ONLY, editing the returned items will affect the state and the rest of the automata at with this state belongs to.
* @returns {ItemRule} Item rule corresponding to the id passed in if present or null otherwise */
state.prototype.getOriginalItemById = function(id) {
return this._registerItems[id];
};
/** @method Get the list of all supported symbol which are valid to generata transition from the current state.
* @returns {[Object]} Array of object of the form: {symbol, items} where items have an array of item rules */
state.prototype.getSupportedTransitionSymbols = function() {
var itemsAux = {},
result = [],
symbol;
k.utils.obj.each(this._items, function (item)
{
symbol = item.getCurrentSymbol();
if (symbol)
{
if (itemsAux[symbol.name]) {
itemsAux[symbol.name].push(item);
}
else
{
itemsAux[symbol.name] = [item];
result.push({
symbol: symbol,
items: itemsAux[symbol.name]
});
}
}
});
return result;
};
/* @method Responsible of new transitions. We override this method to use the correct variable names and be more meanful
* @param {Symbol} symbol Symbol use to make the transition, like the name of the transition
* @param {State} state Destination state arrived when moving with the specified tranisiotn
* @returns {Object} Transition object */
state.prototype._generateNewTransition = function (symbol, state) {
return {
symbol: symbol,
state: state
};
};
/* @method Returns the list of item rules contained in the current state that are reduce item rules.
* @returns {[ItemRule]} Recude Item Rules */
state.prototype.getRecudeItems = function () {
return k.utils.obj.filter(this._items, function (item) {
return item.isReduce();
});
};
return state;
})(k.data.Node); | Mictian/kappa | src/data/state.js | JavaScript | mit | 8,200 |
#include "pch.h"
#include "CertCommands.h"
#include "Console.h"
#include "ProcessHost.h"
#include<vector>
#include "TerminalHelper.h"
using namespace std;
void CertsCommand::ProcessCommand(IConsole *pConsole, ParsedCommandLine *pCmdLine) {
if (pCmdLine->GetArgs().size()<2)
pConsole->WriteLine("SYNTAX: certs storename");
else {
// Convert char* string to a wchar_t* string.
std:string str = pCmdLine->GetArgs().at(1);
std::wstring wsTmp(str.begin(), str.end());
HANDLE hStoreHandle = NULL;
PCCERT_CONTEXT pCertContext = NULL;
char * pszStoreName = "CA";
pConsole->WriteLine("Listing certs");
//--------------------------------------------------------------------
// Open a system certificate store.
if (hStoreHandle = (*CertOpenStore)(CERT_STORE_PROV_SYSTEM_W, // The store provider type
0, // The encoding type is
// not needed
NULL, // Use the default HCRYPTPROV
CERT_SYSTEM_STORE_CURRENT_USER, // Set the store location in a
// registry location
wsTmp.c_str() // The store name as a Unicode
// string
))
{
pConsole->WriteLine("Opened certificate store");
}
else
{
pConsole->WriteLine(GetLastErrorAsString());
return;
}
while (pCertContext = CertEnumCertificatesInStore(
hStoreHandle,
pCertContext))
{
char buf[1000];
(*CertNameToStrA)(1, &pCertContext->pCertInfo->Subject, 2, (char *)buf, sizeof(buf));
pConsole->WriteLine("Found %s", buf);
}
//--------------------------------------------------------------------
// Clean up.
if (!(*CertCloseStore)(
hStoreHandle,
0))
{
pConsole->WriteLine("Failed CertCloseStore");
}
}
}
CommandInfo CertsCommand::GetInfo() {
return CommandInfo("certs", "", "Certificate Manager");
}
| FurballTheGreat/WPTelnetD | WPTelnetDLib/CertCommands.cpp | C++ | mit | 1,852 |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Eurofurence.App.Domain.Model.Fragments;
namespace Eurofurence.App.Domain.Model.Knowledge
{
[DataContract]
public class KnowledgeEntryRecord : EntityBase
{
[Required]
[DataMember]
public Guid KnowledgeGroupId { get; set; }
[Required]
[DataMember]
public string Title { get; set; }
[Required]
[DataMember]
public string Text { get; set; }
[Required]
[DataMember]
public int Order { get; set; }
[DataMember]
public LinkFragment[] Links { get; set; }
[DataMember]
public Guid[] ImageIds { get; set; }
}
} | Pinselohrkater/ef_app-backend-dotnet_core | src/Eurofurence.App.Domain.Model/Knowledge/KnowledgeEntryRecord.cs | C# | mit | 788 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function (mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function (CodeMirror) {
"use strict";
CodeMirror.defineMode("dylan", function (_config) {
// Words
var words = {
// Words that introduce unnamed definitions like "define interface"
unnamedDefinition: ["interface"],
// Words that introduce simple named definitions like "define library"
namedDefinition: ["module", "library", "macro",
"C-struct", "C-union",
"C-function", "C-callable-wrapper"
],
// Words that introduce type definitions like "define class".
// These are also parameterized like "define method" and are
// appended to otherParameterizedDefinitionWords
typeParameterizedDefinition: ["class", "C-subtype", "C-mapped-subtype"],
// Words that introduce trickier definitions like "define method".
// These require special definitions to be added to startExpressions
otherParameterizedDefinition: ["method", "function",
"C-variable", "C-address"
],
// Words that introduce module constant definitions.
// These must also be simple definitions and are
// appended to otherSimpleDefinitionWords
constantSimpleDefinition: ["constant"],
// Words that introduce module variable definitions.
// These must also be simple definitions and are
// appended to otherSimpleDefinitionWords
variableSimpleDefinition: ["variable"],
// Other words that introduce simple definitions
// (without implicit bodies).
otherSimpleDefinition: ["generic", "domain",
"C-pointer-type",
"table"
],
// Words that begin statements with implicit bodies.
statement: ["if", "block", "begin", "method", "case",
"for", "select", "when", "unless", "until",
"while", "iterate", "profiling", "dynamic-bind"
],
// Patterns that act as separators in compound statements.
// This may include any general pattern that must be indented
// specially.
separator: ["finally", "exception", "cleanup", "else",
"elseif", "afterwards"
],
// Keywords that do not require special indentation handling,
// but which should be highlighted
other: ["above", "below", "by", "from", "handler", "in",
"instance", "let", "local", "otherwise", "slot",
"subclass", "then", "to", "keyed-by", "virtual"
],
// Condition signaling function calls
signalingCalls: ["signal", "error", "cerror",
"break", "check-type", "abort"
]
};
words["otherDefinition"] =
words["unnamedDefinition"]
.concat(words["namedDefinition"])
.concat(words["otherParameterizedDefinition"]);
words["definition"] =
words["typeParameterizedDefinition"]
.concat(words["otherDefinition"]);
words["parameterizedDefinition"] =
words["typeParameterizedDefinition"]
.concat(words["otherParameterizedDefinition"]);
words["simpleDefinition"] =
words["constantSimpleDefinition"]
.concat(words["variableSimpleDefinition"])
.concat(words["otherSimpleDefinition"]);
words["keyword"] =
words["statement"]
.concat(words["separator"])
.concat(words["other"]);
// Patterns
var symbolPattern = "[-_a-zA-Z?!*@<>$%]+";
var symbol = new RegExp("^" + symbolPattern);
var patterns = {
// Symbols with special syntax
symbolKeyword: symbolPattern + ":",
symbolClass: "<" + symbolPattern + ">",
symbolGlobal: "\\*" + symbolPattern + "\\*",
symbolConstant: "\\$" + symbolPattern
};
var patternStyles = {
symbolKeyword: "atom",
symbolClass: "tag",
symbolGlobal: "variable-2",
symbolConstant: "variable-3"
};
// Compile all patterns to regular expressions
for (var patternName in patterns)
if (patterns.hasOwnProperty(patternName))
patterns[patternName] = new RegExp("^" + patterns[patternName]);
// Names beginning "with-" and "without-" are commonly
// used as statement macro
patterns["keyword"] = [/^with(?:out)?-[-_a-zA-Z?!*@<>$%]+/];
var styles = {};
styles["keyword"] = "keyword";
styles["definition"] = "def";
styles["simpleDefinition"] = "def";
styles["signalingCalls"] = "builtin";
// protected words lookup table
var wordLookup = {};
var styleLookup = {};
[
"keyword",
"definition",
"simpleDefinition",
"signalingCalls"
].forEach(function (type) {
words[type].forEach(function (word) {
wordLookup[word] = type;
styleLookup[word] = styles[type];
});
});
function chain(stream, state, f) {
state.tokenize = f;
return f(stream, state);
}
function tokenBase(stream, state) {
// String
var ch = stream.peek();
if (ch == "'" || ch == '"') {
stream.next();
return chain(stream, state, tokenString(ch, "string"));
}
// Comment
else if (ch == "/") {
stream.next();
if (stream.eat("*")) {
return chain(stream, state, tokenComment);
} else if (stream.eat("/")) {
stream.skipToEnd();
return "comment";
}
stream.backUp(1);
}
// Decimal
else if (/[+\-\d\.]/.test(ch)) {
if (stream.match(/^[+-]?[0-9]*\.[0-9]*([esdx][+-]?[0-9]+)?/i) ||
stream.match(/^[+-]?[0-9]+([esdx][+-]?[0-9]+)/i) ||
stream.match(/^[+-]?\d+/)) {
return "number";
}
}
// Hash
else if (ch == "#") {
stream.next();
// Symbol with string syntax
ch = stream.peek();
if (ch == '"') {
stream.next();
return chain(stream, state, tokenString('"', "string"));
}
// Binary number
else if (ch == "b") {
stream.next();
stream.eatWhile(/[01]/);
return "number";
}
// Hex number
else if (ch == "x") {
stream.next();
stream.eatWhile(/[\da-f]/i);
return "number";
}
// Octal number
else if (ch == "o") {
stream.next();
stream.eatWhile(/[0-7]/);
return "number";
}
// Token concatenation in macros
else if (ch == '#') {
stream.next();
return "punctuation";
}
// Sequence literals
else if ((ch == '[') || (ch == '(')) {
stream.next();
return "bracket";
// Hash symbol
} else if (stream.match(/f|t|all-keys|include|key|next|rest/i)) {
return "atom";
} else {
stream.eatWhile(/[-a-zA-Z]/);
return "error";
}
} else if (ch == "~") {
stream.next();
ch = stream.peek();
if (ch == "=") {
stream.next();
ch = stream.peek();
if (ch == "=") {
stream.next();
return "operator";
}
return "operator";
}
return "operator";
} else if (ch == ":") {
stream.next();
ch = stream.peek();
if (ch == "=") {
stream.next();
return "operator";
} else if (ch == ":") {
stream.next();
return "punctuation";
}
} else if ("[](){}".indexOf(ch) != -1) {
stream.next();
return "bracket";
} else if (".,".indexOf(ch) != -1) {
stream.next();
return "punctuation";
} else if (stream.match("end")) {
return "keyword";
}
for (var name in patterns) {
if (patterns.hasOwnProperty(name)) {
var pattern = patterns[name];
if ((pattern instanceof Array && pattern.some(function (p) {
return stream.match(p);
})) || stream.match(pattern))
return patternStyles[name];
}
}
if (/[+\-*\/^=<>&|]/.test(ch)) {
stream.next();
return "operator";
}
if (stream.match("define")) {
return "def";
} else {
stream.eatWhile(/[\w\-]/);
// Keyword
if (wordLookup[stream.current()]) {
return styleLookup[stream.current()];
} else if (stream.current().match(symbol)) {
return "variable";
} else {
stream.next();
return "variable-2";
}
}
}
function tokenComment(stream, state) {
var maybeEnd = false, maybeNested = false, nestedCount = 0, ch;
while ((ch = stream.next())) {
if (ch == "/" && maybeEnd) {
if (nestedCount > 0) {
nestedCount--;
} else {
state.tokenize = tokenBase;
break;
}
} else if (ch == "*" && maybeNested) {
nestedCount++;
}
maybeEnd = (ch == "*");
maybeNested = (ch == "/");
}
return "comment";
}
function tokenString(quote, style) {
return function (stream, state) {
var escaped = false, next, end = false;
while ((next = stream.next()) != null) {
if (next == quote && !escaped) {
end = true;
break;
}
escaped = !escaped && next == "\\";
}
if (end || !escaped) {
state.tokenize = tokenBase;
}
return style;
};
}
// Interface
return {
startState: function () {
return {
tokenize: tokenBase,
currentIndent: 0
};
},
token: function (stream, state) {
if (stream.eatSpace())
return null;
var style = state.tokenize(stream, state);
return style;
},
blockCommentStart: "/*",
blockCommentEnd: "*/"
};
});
CodeMirror.defineMIME("text/x-dylan", "dylan");
});
| Kipsora/KitJudge | utility/js/mode/dylan/dylan.js | JavaScript | mit | 12,442 |
$(document).ready(function() {
$("#frmChangePass").submit(function() {
//get the url for the form
AJAX.post(
$("#frmChangePass").attr("action"),
{
_password_current : $("#currentPass").val(),
_password : $("#newPass").val(),
_password_confirm : $("#newPass2").val()
},
$("#msgbox_changepass"),
$("#btnChangepass"));
//we dont what the browser to submit the form
return false;
});
});
| c4d3r/mcsuite-application-eyeofender | src/Maxim/Theme/EOEBundle/Resources/public/theme/js/changepassword.js | JavaScript | mit | 425 |
require 'spec_helper'
describe API::Templates do
context 'the Template Entity' do
before { get api('/templates/gitignores/Ruby') }
it { expect(json_response['name']).to eq('Ruby') }
it { expect(json_response['content']).to include('*.gem') }
end
context 'the TemplateList Entity' do
before { get api('/templates/gitignores') }
it { expect(json_response.first['name']).not_to be_nil }
it { expect(json_response.first['content']).to be_nil }
end
context 'requesting gitignores' do
it 'returns a list of available gitignore templates' do
get api('/templates/gitignores')
expect(response).to have_http_status(200)
expect(response).to include_pagination_headers
expect(json_response).to be_an Array
expect(json_response.size).to be > 15
end
end
context 'requesting gitlab-ci-ymls' do
it 'returns a list of available gitlab_ci_ymls' do
get api('/templates/gitlab_ci_ymls')
expect(response).to have_http_status(200)
expect(response).to include_pagination_headers
expect(json_response).to be_an Array
expect(json_response.first['name']).not_to be_nil
end
end
context 'requesting gitlab-ci-yml for Ruby' do
it 'adds a disclaimer on the top' do
get api('/templates/gitlab_ci_ymls/Ruby')
expect(response).to have_http_status(200)
expect(json_response['content']).to start_with("# This file is a template,")
end
end
context 'the License Template Entity' do
before { get api('/templates/licenses/mit') }
it 'returns a license template' do
expect(json_response['key']).to eq('mit')
expect(json_response['name']).to eq('MIT License')
expect(json_response['nickname']).to be_nil
expect(json_response['popular']).to be true
expect(json_response['html_url']).to eq('http://choosealicense.com/licenses/mit/')
expect(json_response['source_url']).to eq('https://opensource.org/licenses/MIT')
expect(json_response['description']).to include('A short and simple permissive license with conditions')
expect(json_response['conditions']).to eq(%w[include-copyright])
expect(json_response['permissions']).to eq(%w[commercial-use modifications distribution private-use])
expect(json_response['limitations']).to eq(%w[no-liability])
expect(json_response['content']).to include('MIT License')
end
end
context 'GET templates/licenses' do
it 'returns a list of available license templates' do
get api('/templates/licenses')
expect(response).to have_http_status(200)
expect(response).to include_pagination_headers
expect(json_response).to be_an Array
expect(json_response.size).to eq(12)
expect(json_response.map { |l| l['key'] }).to include('agpl-3.0')
end
describe 'the popular parameter' do
context 'with popular=1' do
it 'returns a list of available popular license templates' do
get api('/templates/licenses?popular=1')
expect(response).to have_http_status(200)
expect(response).to include_pagination_headers
expect(json_response).to be_an Array
expect(json_response.size).to eq(3)
expect(json_response.map { |l| l['key'] }).to include('apache-2.0')
end
end
end
end
context 'GET templates/licenses/:name' do
context 'with :project and :fullname given' do
before do
get api("/templates/licenses/#{license_type}?project=My+Awesome+Project&fullname=Anton+#{license_type.upcase}")
end
context 'for the mit license' do
let(:license_type) { 'mit' }
it 'returns the license text' do
expect(json_response['content']).to include('MIT License')
end
it 'replaces placeholder values' do
expect(json_response['content']).to include("Copyright (c) #{Time.now.year} Anton")
end
end
context 'for the agpl-3.0 license' do
let(:license_type) { 'agpl-3.0' }
it 'returns the license text' do
expect(json_response['content']).to include('GNU AFFERO GENERAL PUBLIC LICENSE')
end
it 'replaces placeholder values' do
expect(json_response['content']).to include('My Awesome Project')
expect(json_response['content']).to include("Copyright (C) #{Time.now.year} Anton")
end
end
context 'for the gpl-3.0 license' do
let(:license_type) { 'gpl-3.0' }
it 'returns the license text' do
expect(json_response['content']).to include('GNU GENERAL PUBLIC LICENSE')
end
it 'replaces placeholder values' do
expect(json_response['content']).to include('My Awesome Project')
expect(json_response['content']).to include("Copyright (C) #{Time.now.year} Anton")
end
end
context 'for the gpl-2.0 license' do
let(:license_type) { 'gpl-2.0' }
it 'returns the license text' do
expect(json_response['content']).to include('GNU GENERAL PUBLIC LICENSE')
end
it 'replaces placeholder values' do
expect(json_response['content']).to include('My Awesome Project')
expect(json_response['content']).to include("Copyright (C) #{Time.now.year} Anton")
end
end
context 'for the apache-2.0 license' do
let(:license_type) { 'apache-2.0' }
it 'returns the license text' do
expect(json_response['content']).to include('Apache License')
end
it 'replaces placeholder values' do
expect(json_response['content']).to include("Copyright #{Time.now.year} Anton")
end
end
context 'for an uknown license' do
let(:license_type) { 'muth-over9000' }
it 'returns a 404' do
expect(response).to have_http_status(404)
end
end
end
context 'with no :fullname given' do
context 'with an authenticated user' do
let(:user) { create(:user) }
it 'replaces the copyright owner placeholder with the name of the current user' do
get api('/templates/licenses/mit', user)
expect(json_response['content']).to include("Copyright (c) #{Time.now.year} #{user.name}")
end
end
end
end
end
| htve/GitlabForChinese | spec/requests/api/templates_spec.rb | Ruby | mit | 6,307 |
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2018, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@author: Richard Steffen, 2015
----------------------------------------------------------------------
*/
#ifndef ASSIMP_BUILD_NO_EXPORT
#ifndef ASSIMP_BUILD_NO_STEP_EXPORTER
#include "StepExporter.h"
#include "ConvertToLHProcess.h"
#include <assimp/Bitmap.h>
#include <assimp/BaseImporter.h>
#include <assimp/fast_atof.h>
#include <assimp/SceneCombiner.h>
#include <iostream>
#include <ctime>
#include <set>
#include <map>
#include <list>
#include <memory>
#include <assimp/Exceptional.h>
#include <assimp/DefaultIOSystem.h>
#include <assimp/IOSystem.hpp>
#include <assimp/scene.h>
#include <assimp/light.h>
//
#if _MSC_VER > 1500 || (defined __GNUC___)
# define ASSIMP_STEP_USE_UNORDERED_MULTIMAP
# else
# define step_unordered_map map
# define step_unordered_multimap multimap
#endif
#ifdef ASSIMP_STEP_USE_UNORDERED_MULTIMAP
# include <unordered_map>
# if _MSC_VER > 1600
# define step_unordered_map unordered_map
# define step_unordered_multimap unordered_multimap
# else
# define step_unordered_map tr1::unordered_map
# define step_unordered_multimap tr1::unordered_multimap
# endif
#endif
typedef std::step_unordered_map<aiVector3D*, int> VectorIndexUMap;
/* Tested with Step viewer v4 from www.ida-step.net */
using namespace Assimp;
namespace Assimp
{
// ------------------------------------------------------------------------------------------------
// Worker function for exporting a scene to Collada. Prototyped and registered in Exporter.cpp
void ExportSceneStep(const char* pFile,IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
{
std::string path = DefaultIOSystem::absolutePath(std::string(pFile));
std::string file = DefaultIOSystem::completeBaseName(std::string(pFile));
// create/copy Properties
ExportProperties props(*pProperties);
// invoke the exporter
StepExporter iDoTheExportThing( pScene, pIOSystem, path, file, &props);
// we're still here - export successfully completed. Write result to the given IOSYstem
std::unique_ptr<IOStream> outfile (pIOSystem->Open(pFile,"wt"));
if(outfile == NULL) {
throw DeadlyExportError("could not open output .stp file: " + std::string(pFile));
}
// XXX maybe use a small wrapper around IOStream that behaves like std::stringstream in order to avoid the extra copy.
outfile->Write( iDoTheExportThing.mOutput.str().c_str(), static_cast<size_t>(iDoTheExportThing.mOutput.tellp()),1);
}
} // end of namespace Assimp
namespace {
// Collect world transformations for each node
void CollectTrafos(const aiNode* node, std::map<const aiNode*, aiMatrix4x4>& trafos) {
const aiMatrix4x4& parent = node->mParent ? trafos[node->mParent] : aiMatrix4x4();
trafos[node] = parent * node->mTransformation;
for (unsigned int i = 0; i < node->mNumChildren; ++i) {
CollectTrafos(node->mChildren[i], trafos);
}
}
// Generate a flat list of the meshes (by index) assigned to each node
void CollectMeshes(const aiNode* node, std::multimap<const aiNode*, unsigned int>& meshes) {
for (unsigned int i = 0; i < node->mNumMeshes; ++i) {
meshes.insert(std::make_pair(node, node->mMeshes[i]));
}
for (unsigned int i = 0; i < node->mNumChildren; ++i) {
CollectMeshes(node->mChildren[i], meshes);
}
}
}
// ------------------------------------------------------------------------------------------------
// Constructor for a specific scene to export
StepExporter::StepExporter(const aiScene* pScene, IOSystem* pIOSystem, const std::string& path,
const std::string& file, const ExportProperties* pProperties):
mProperties(pProperties),mIOSystem(pIOSystem),mFile(file), mPath(path),
mScene(pScene), endstr(";\n") {
CollectTrafos(pScene->mRootNode, trafos);
CollectMeshes(pScene->mRootNode, meshes);
// make sure that all formatting happens using the standard, C locale and not the user's current locale
mOutput.imbue( std::locale("C") );
mOutput.precision(16);
// start writing
WriteFile();
}
// ------------------------------------------------------------------------------------------------
// Starts writing the contents
void StepExporter::WriteFile()
{
// see http://shodhganga.inflibnet.ac.in:8080/jspui/bitstream/10603/14116/11/11_chapter%203.pdf
// note, that all realnumber values must be comma separated in x files
mOutput.setf(std::ios::fixed);
// precision for double
// see http://stackoverflow.com/questions/554063/how-do-i-print-a-double-value-with-full-precision-using-cout
mOutput.precision(16);
// standard color
aiColor4D fColor;
fColor.r = 0.8f;
fColor.g = 0.8f;
fColor.b = 0.8f;
int ind = 100; // the start index to be used
int faceEntryLen = 30; // number of entries for a triangle/face
// prepare unique (count triangles and vertices)
VectorIndexUMap uniqueVerts; // use a map to reduce find complexity to log(n)
VectorIndexUMap::iterator it;
int countFace = 0;
for (unsigned int i=0; i<mScene->mNumMeshes; ++i)
{
aiMesh* mesh = mScene->mMeshes[i];
for (unsigned int j=0; j<mesh->mNumFaces; ++j)
{
aiFace* face = &(mesh->mFaces[j]);
if (face->mNumIndices == 3) countFace++;
}
for (unsigned int j=0; j<mesh->mNumVertices; ++j)
{
aiVector3D* v = &(mesh->mVertices[j]);
it =uniqueVerts.find(v);
if (it == uniqueVerts.end())
{
uniqueVerts[v] = -1; // first mark the vector as not transformed
}
}
}
static const unsigned int date_nb_chars = 20;
char date_str[date_nb_chars];
std::time_t date = std::time(NULL);
std::strftime(date_str, date_nb_chars, "%Y-%m-%dT%H:%M:%S", std::localtime(&date));
// write the header
mOutput << "ISO-10303-21" << endstr;
mOutput << "HEADER" << endstr;
mOutput << "FILE_DESCRIPTION(('STEP AP214'),'1')" << endstr;
mOutput << "FILE_NAME('" << mFile << ".stp','" << date_str << "',(' '),(' '),'Spatial InterOp 3D',' ',' ')" << endstr;
mOutput << "FILE_SCHEMA(('automotive_design'))" << endstr;
mOutput << "ENDSEC" << endstr;
// write the top of data
mOutput << "DATA" << endstr;
mOutput << "#1=MECHANICAL_DESIGN_GEOMETRIC_PRESENTATION_REPRESENTATION(' ',(";
for (int i=0; i<countFace; ++i)
{
mOutput << "#" << i*faceEntryLen + ind + 2*uniqueVerts.size();
if (i!=countFace-1) mOutput << ",";
}
mOutput << "),#6)" << endstr;
mOutput << "#2=PRODUCT_DEFINITION_CONTEXT('',#7,'design')" << endstr;
mOutput << "#3=APPLICATION_PROTOCOL_DEFINITION('INTERNATIONAL STANDARD','automotive_design',1994,#7)" << endstr;
mOutput << "#4=PRODUCT_CATEGORY_RELATIONSHIP('NONE','NONE',#8,#9)" << endstr;
mOutput << "#5=SHAPE_DEFINITION_REPRESENTATION(#10,#11)" << endstr;
mOutput << "#6= (GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#12))GLOBAL_UNIT_ASSIGNED_CONTEXT((#13,#14,#15))REPRESENTATION_CONTEXT('NONE','WORKSPACE'))" << endstr;
mOutput << "#7=APPLICATION_CONTEXT(' ')" << endstr;
mOutput << "#8=PRODUCT_CATEGORY('part','NONE')" << endstr;
mOutput << "#9=PRODUCT_RELATED_PRODUCT_CATEGORY('detail',' ',(#17))" << endstr;
mOutput << "#10=PRODUCT_DEFINITION_SHAPE('NONE','NONE',#18)" << endstr;
mOutput << "#11=MANIFOLD_SURFACE_SHAPE_REPRESENTATION('Root',(#16,#19),#6)" << endstr;
mOutput << "#12=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.0E-006),#13,'','')" << endstr;
mOutput << "#13=(CONVERSION_BASED_UNIT('METRE',#20)LENGTH_UNIT()NAMED_UNIT(#21))" << endstr;
mOutput << "#14=(NAMED_UNIT(#22)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))" << endstr;
mOutput << "#15=(NAMED_UNIT(#22)SOLID_ANGLE_UNIT()SI_UNIT($,.STERADIAN.))" << endstr;
mOutput << "#16=SHELL_BASED_SURFACE_MODEL('Root',(#29))" << endstr;
mOutput << "#17=PRODUCT('Root','Root','Root',(#23))" << endstr;
mOutput << "#18=PRODUCT_DEFINITION('NONE','NONE',#24,#2)" << endstr;
mOutput << "#19=AXIS2_PLACEMENT_3D('',#25,#26,#27)" << endstr;
mOutput << "#20=LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.0),#28)" << endstr;
mOutput << "#21=DIMENSIONAL_EXPONENTS(1.0,0.0,0.0,0.0,0.0,0.0,0.0)" << endstr;
mOutput << "#22=DIMENSIONAL_EXPONENTS(0.0,0.0,0.0,0.0,0.0,0.0,0.0)" << endstr;
mOutput << "#23=PRODUCT_CONTEXT('',#7,'mechanical')" << endstr;
mOutput << "#24=PRODUCT_DEFINITION_FORMATION_WITH_SPECIFIED_SOURCE(' ','NONE',#17,.NOT_KNOWN.)" << endstr;
mOutput << "#25=CARTESIAN_POINT('',(0.0,0.0,0.0))" << endstr;
mOutput << "#26=DIRECTION('',(0.0,0.0,1.0))" << endstr;
mOutput << "#27=DIRECTION('',(1.0,0.0,0.0))" << endstr;
mOutput << "#28= (NAMED_UNIT(#21)LENGTH_UNIT()SI_UNIT(.MILLI.,.METRE.))" << endstr;
mOutput << "#29=CLOSED_SHELL('',(";
for (int i=0; i<countFace; ++i)
{
mOutput << "#" << i*faceEntryLen + ind + 2*uniqueVerts.size() + 8;
if (i!=countFace-1) mOutput << ",";
}
mOutput << "))" << endstr;
// write all the unique transformed CARTESIAN and VERTEX
for (MeshesByNodeMap::const_iterator it2 = meshes.begin(); it2 != meshes.end(); ++it2)
{
const aiNode& node = *(*it2).first;
unsigned int mesh_idx = (*it2).second;
const aiMesh* mesh = mScene->mMeshes[mesh_idx];
aiMatrix4x4& trafo = trafos[&node];
for (unsigned int i = 0; i < mesh->mNumVertices; ++i)
{
aiVector3D* v = &(mesh->mVertices[i]);
it = uniqueVerts.find(v);
if (it->second >=0 ) continue;
it->second = ind; // this one is new, so set the index (ind)
aiVector3D vt = trafo * (*v); // transform the coordinate
mOutput << "#" << it->second << "=CARTESIAN_POINT('',(" << vt.x << "," << vt.y << "," << vt.z << "))" << endstr;
mOutput << "#" << it->second+1 << "=VERTEX_POINT('',#" << it->second << ")" << endstr;
ind += 2;
}
}
// write the triangles
for (unsigned int i=0; i<mScene->mNumMeshes; ++i)
{
aiMesh* mesh = mScene->mMeshes[i];
for (unsigned int j=0; j<mesh->mNumFaces; ++j)
{
aiFace* face = &(mesh->mFaces[j]);
if (face->mNumIndices != 3) continue;
aiVector3D* v1 = &(mesh->mVertices[face->mIndices[0]]);
aiVector3D* v2 = &(mesh->mVertices[face->mIndices[1]]);
aiVector3D* v3 = &(mesh->mVertices[face->mIndices[2]]);
aiVector3D dv12 = *v2 - *v1;
aiVector3D dv23 = *v3 - *v2;
aiVector3D dv31 = *v1 - *v3;
aiVector3D dv13 = *v3 - *v1;
dv12.Normalize();
dv23.Normalize();
dv31.Normalize();
dv13.Normalize();
int pid1 = uniqueVerts.find(v1)->second;
int pid2 = uniqueVerts.find(v2)->second;
int pid3 = uniqueVerts.find(v3)->second;
// mean vertex color for the face if available
if (mesh->HasVertexColors(0))
{
fColor.r = 0.0;
fColor.g = 0.0;
fColor.b = 0.0;
fColor += mesh->mColors[0][face->mIndices[0]];
fColor += mesh->mColors[0][face->mIndices[1]];
fColor += mesh->mColors[0][face->mIndices[2]];
fColor /= 3.0f;
}
int sid = ind; // the sub index
mOutput << "#" << sid << "=STYLED_ITEM('',(#" << sid+1 << "),#" << sid+8 << ")" << endstr; /* the item that must be referenced in #1 */
/* This is the color information of the Triangle */
mOutput << "#" << sid+1 << "=PRESENTATION_STYLE_ASSIGNMENT((#" << sid+2 << "))" << endstr;
mOutput << "#" << sid+2 << "=SURFACE_STYLE_USAGE(.BOTH.,#" << sid+3 << ")" << endstr;
mOutput << "#" << sid+3 << "=SURFACE_SIDE_STYLE('',(#" << sid+4 << "))" << endstr;
mOutput << "#" << sid+4 << "=SURFACE_STYLE_FILL_AREA(#" << sid+5 << ")" << endstr;
mOutput << "#" << sid+5 << "=FILL_AREA_STYLE('',(#" << sid+6 << "))" << endstr;
mOutput << "#" << sid+6 << "=FILL_AREA_STYLE_COLOUR('',#" << sid+7 << ")" << endstr;
mOutput << "#" << sid+7 << "=COLOUR_RGB(''," << fColor.r << "," << fColor.g << "," << fColor.b << ")" << endstr;
/* this is the geometry */
mOutput << "#" << sid+8 << "=FACE_SURFACE('',(#" << sid+13 << "),#" << sid+9<< ",.T.)" << endstr; /* the face that must be referenced in 29 */
/* 2 directions of the plane */
mOutput << "#" << sid+9 << "=PLANE('',#" << sid+10 << ")" << endstr;
mOutput << "#" << sid+10 << "=AXIS2_PLACEMENT_3D('',#" << pid1 << ", #" << sid+11 << ",#" << sid+12 << ")" << endstr;
mOutput << "#" << sid+11 << "=DIRECTION('',(" << dv12.x << "," << dv12.y << "," << dv12.z << "))" << endstr;
mOutput << "#" << sid+12 << "=DIRECTION('',(" << dv13.x << "," << dv13.y << "," << dv13.z << "))" << endstr;
mOutput << "#" << sid+13 << "=FACE_BOUND('',#" << sid+14 << ",.T.)" << endstr;
mOutput << "#" << sid+14 << "=EDGE_LOOP('',(#" << sid+15 << ",#" << sid+16 << ",#" << sid+17 << "))" << endstr;
/* edge loop */
mOutput << "#" << sid+15 << "=ORIENTED_EDGE('',*,*,#" << sid+18 << ",.T.)" << endstr;
mOutput << "#" << sid+16 << "=ORIENTED_EDGE('',*,*,#" << sid+19 << ",.T.)" << endstr;
mOutput << "#" << sid+17 << "=ORIENTED_EDGE('',*,*,#" << sid+20 << ",.T.)" << endstr;
/* oriented edges */
mOutput << "#" << sid+18 << "=EDGE_CURVE('',#" << pid1+1 << ",#" << pid2+1 << ",#" << sid+21 << ",.F.)" << endstr;
mOutput << "#" << sid+19 << "=EDGE_CURVE('',#" << pid2+1 << ",#" << pid3+1 << ",#" << sid+22 << ",.T.)" << endstr;
mOutput << "#" << sid+20 << "=EDGE_CURVE('',#" << pid3+1 << ",#" << pid1+1 << ",#" << sid+23 << ",.T.)" << endstr;
/* 3 lines and 3 vectors for the lines for the 3 edge curves */
mOutput << "#" << sid+21 << "=LINE('',#" << pid1 << ",#" << sid+24 << ")" << endstr;
mOutput << "#" << sid+22 << "=LINE('',#" << pid2 << ",#" << sid+25 << ")" << endstr;
mOutput << "#" << sid+23 << "=LINE('',#" << pid3 << ",#" << sid+26 << ")" << endstr;
mOutput << "#" << sid+24 << "=VECTOR('',#" << sid+27 << ",1.0)" << endstr;
mOutput << "#" << sid+25 << "=VECTOR('',#" << sid+28 << ",1.0)" << endstr;
mOutput << "#" << sid+26 << "=VECTOR('',#" << sid+29 << ",1.0)" << endstr;
mOutput << "#" << sid+27 << "=DIRECTION('',(" << dv12.x << "," << dv12.y << "," << dv12.z << "))" << endstr;
mOutput << "#" << sid+28 << "=DIRECTION('',(" << dv23.x << "," << dv23.y << "," << dv23.z << "))" << endstr;
mOutput << "#" << sid+29 << "=DIRECTION('',(" << dv31.x << "," << dv31.y << "," << dv31.z << "))" << endstr;
ind += faceEntryLen; // increase counter
}
}
mOutput << "ENDSEC" << endstr; // end of data section
mOutput << "END-ISO-10303-21" << endstr; // end of file
}
#endif
#endif
| MadManRises/Madgine | shared/assimp/code/StepExporter.cpp | C++ | mit | 16,941 |
/**
* Created by joonkukang on 2014. 1. 16..
*/
var math = require('./utils').math;
let optimize = module.exports;
optimize.hillclimb = function(options){
var domain = options['domain'];
var costf = options['costf'];
var i;
var vec = [];
for(i=0 ; i<domain.length ; i++)
vec.push(math.randInt(domain[i][0],domain[i][1]));
var current, best;
while(true) {
var neighbors = [];
var i,j;
for(i=0 ; i<domain.length ; i++) {
if(vec[i] > domain[i][0]) {
var newVec = [];
for(j=0 ; j<domain.length ; j++)
newVec.push(vec[j]);
newVec[i]-=1;
neighbors.push(newVec);
} else if (vec[i] < domain[i][1]) {
var newVec = [];
for(j=0 ; j<domain.length ; j++)
newVec.push(vec[j]);
newVec[i]+=1;
neighbors.push(newVec);
}
}
current = costf(vec);
best = current;
for(i=0 ; i<neighbors.length ; i++) {
var cost = costf(neighbors[i]);
if(cost < best) {
best = cost;
vec = neighbors[i];
}
}
if(best === current)
break;
}
return vec;
}
optimize.anneal = function(options){
var domain = options['domain'];
var costf = options['costf'];
var temperature = options['temperature'];
var cool = options['cool'];
var step = options['step'];
var callback
var i;
var vec = [];
for(i=0 ; i<domain.length ; i++)
vec.push(math.randInt(domain[i][0],domain[i][1]));
while(temperature > 0.1) {
var idx = math.randInt(0,domain.length - 1);
var dir = math.randInt(-step,step);
var newVec = [];
for(i=0; i<vec.length ; i++)
newVec.push(vec[i]);
newVec[idx]+=dir;
if(newVec[idx] < domain[idx][0]) newVec[idx] = domain[idx][0];
if(newVec[idx] > domain[idx][1]) newVec[idx] = domain[idx][1];
var ea = costf(vec);
var eb = costf(newVec);
var p = Math.exp(-1.*(eb-ea)/temperature);
if(eb < ea || Math.random() < p)
vec = newVec;
temperature *= cool;
}
return vec;
}
optimize.genetic = function(options){
var domain = options['domain'];
var costf = options['costf'];
var population = options['population'];
var q = options['q'] || 0.3;
var elite = options['elite'] || population * 0.04;
var epochs = options['epochs'] || 100;
var i,j;
// Initialize population array
var pop =[];
for(i=0; i<population; i++) {
var vec = [];
for(j=0; j<domain.length; j++)
vec.push(math.randInt(domain[j][0],domain[j][1]));
pop.push(vec);
}
pop.sort(function(a,b){return costf(a) - costf(b);});
for(i=0 ; i<epochs ; i++) {
// elitism
var newPop = [];
for(j=0;j<elite;j++)
newPop.push(pop[j]);
// compute fitnesses
var fitnesses = [];
for(j=0; j<pop.length; j++)
fitnesses[j] = q * Math.pow(1-q,j);
fitnesses = math.normalizeVec(fitnesses);
// crossover, mutate
for(j=0; j<pop.length - elite;j++) {
var idx1 = rouletteWheel(fitnesses);
var idx2 = rouletteWheel(fitnesses);
var crossovered = crossover(pop[idx1],pop[idx2]);
var mutated = mutate(crossovered);
newPop.push(mutated);
}
// replacement
pop = newPop;
pop.sort(function(a,b){return costf(a) - costf(b);});
//console.log("Current Cost : ",costf(pop[0]));
}
return pop[0];
function mutate(vec) {
var idx = math.randInt(0,domain.length - 1);
var newVec = [];
var i;
for(i=0; i<domain.length ; i++)
newVec.push(vec[i]);
newVec[idx] += (Math.random() < 0.5) ? 1 : -1;
if(newVec[idx] < domain[idx][0]) newVec[idx] = domain[idx][0];
if(newVec[idx] > domain[idx][1]) newVec[idx] = domain[idx][1];
return newVec;
}
function crossover(vec1,vec2) {
var idx = math.randInt(0,domain.length - 2);
var newVec = [];
var i;
for(i=0; i<idx ; i++)
newVec.push(vec1[i]);
for(i=idx; i<domain.length; i++)
newVec.push(vec2[i]);
return newVec;
}
function rouletteWheel(vec) {
var a = [0.0];
var i;
for(i=0;i<vec.length;i++) {
a.push(a[i] + vec[i]);
}
var rand = Math.random();
for(i=0;i< a.length;i++) {
if(rand > a[i] && rand <= a[i+1])
return i;
}
return -1;
}
};
| pulipulichen/blog-pulipuli-info-data-2017 | 06/generative_path/machine_learning-master/machine_learning-master/lib/optimize.js | JavaScript | mit | 4,797 |
#!/usr/bin/env python3
from multiprocessing import Process, Pool
import os, time
def proc(name):
print(time.asctime(), 'child process(name: %s) id %s. ppid %s' % (name, os.getpid(), os.getppid()))
time.sleep(3)
print(time.asctime(), 'child process end')
if __name__ == '__main__':
p = Process(target = proc, args = ('child',))
print(time.asctime(), 'child process will start')
p.start()
p.join()
print('first child process end')
pl = Pool(4)
for index in range(4):
pl.apply_async(proc, args = (index,))
pl.close()
pl.join()
print(time.asctime(), 'parent process end')
| JShadowMan/package | python/multi-process-thread/multiprocess.py | Python | mit | 660 |
package rres.knetminer.datasource.server;
import static uk.ac.ebi.utils.exceptions.ExceptionUtils.getSignificantMessage;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ObjectMessage;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import com.brsanthu.googleanalytics.GoogleAnalytics;
import com.brsanthu.googleanalytics.GoogleAnalyticsBuilder;
import rres.knetminer.datasource.api.KnetminerDataSource;
import rres.knetminer.datasource.api.KnetminerRequest;
import rres.knetminer.datasource.api.KnetminerResponse;
import uk.ac.ebi.utils.exceptions.ExceptionUtils;
import uk.ac.ebi.utils.opt.springweb.exceptions.ResponseStatusException2;
/**
* KnetminerServer is a fully working server, except that it lacks any data
* sources. To make a server with data sources, just add one or more JARs to the
* classpath which include classes that implement KnetminerDataSourceProvider
* (and are in package rres.knetminer.datasource). They are detected and loaded
* via autowiring. See the sister server-example project for how this is done.
*
* @author holland
* @author Marco Brandizi (2021, removed custom exception management and linked it to {@link KnetminerExceptionHandler})
*/
@Controller
@RequestMapping("/")
public class KnetminerServer {
protected final Logger log = LogManager.getLogger(getClass());
@Autowired
private List<KnetminerDataSource> dataSources;
private Map<String, KnetminerDataSource> dataSourceCache;
private String gaTrackingId;
// Special logging to achieve web analytics info.
private static final Logger logAnalytics = LogManager.getLogger("analytics-log");
/**
* Autowiring will populate the basic dataSources list with all instances of
* KnetminerDataSourceProvider. This method is used, upon first access, to take
* that list and turn it into a map of URL paths to data sources, using the
* getName() function of each data source to build an equivalent URL. For
* instance a data source with getName()='hello' will receive all requests
* matching '/hello/**'.
*/
@PostConstruct
public void _buildDataSourceCache() {
this.dataSourceCache = new HashMap<String, KnetminerDataSource>();
for (KnetminerDataSource dataSource : this.dataSources) {
for (String ds : dataSource.getDataSourceNames()) {
this.dataSourceCache.put(ds, dataSource);
log.info("Mapped /" + ds + " to " + dataSource.getClass().getName());
}
}
}
/**
* Loads Google Analytics properties from src/main/resources/ga.properties . It expects
* to find GOOGLE_ANALYTICS_ENABLED = True or False. If True, it also expects to find
* GOOGLE_ANALYTICS_TRACKING_ID with a valid Google Analytics tracking ID.
*/
@PostConstruct
public void _loadGATrackingId() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("ga.properties");
Properties props = new Properties();
try {
props.load(input);
log.info("GA enabled= "+ props.getProperty("GOOGLE_ANALYTICS_ENABLED")); // test passing val
log.info("ga_id to use= "+ props.getProperty("GOOGLE_ANALYTICS_TRACKING_ID")); // test passed val
} catch (IOException ex) {
log.warn("Failed to load Google Analytics properties file", ex);
return;
}
if (Boolean.parseBoolean(props.getProperty("GOOGLE_ANALYTICS_ENABLED", "false"))) {
this.gaTrackingId = props.getProperty("GOOGLE_ANALYTICS_TRACKING_ID", null);
if (this.gaTrackingId == null)
log.warn("Google Analytics properties file enabled analytics but did not provide tracking ID");
else
log.info("Google Analytics enabled");
} else
log.info("Google Analytics disabled");
}
private void _googlePageView(String ds, String mode, HttpServletRequest rawRequest)
{
String ipAddress = rawRequest.getHeader("X-FORWARDED-FOR");
log.debug("IP TRACING 1, IP for X-FORWARDED-FOR: {}", ipAddress);
if (ipAddress == null) {
ipAddress = rawRequest.getRemoteAddr();
log.debug("IP TRACING 2, getRemoteAddr(): {}", ipAddress);
}else{
log.debug("IP TRACING 3, IP to be split: {}", ipAddress);
if(ipAddress.indexOf(',')!= -1){
ipAddress = ipAddress.split(",")[0];
}
log.debug("IP TRACING 4, splitted IP: {}", ipAddress);
}
log.debug("IP TRACING 5 post-processed IP: {}", ipAddress);
String[] IP_HEADER_CANDIDATES = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR" };
for (String header : IP_HEADER_CANDIDATES) {
String ip = rawRequest.getHeader(header);
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
log.debug("IP TRACING, req headers, {}:{}", header, ip);
}
}
if (this.gaTrackingId!=null) {
String pageName = ds+"/"+mode;
GoogleAnalytics ga = new GoogleAnalyticsBuilder().withTrackingId(this.gaTrackingId).build();
ga.pageView().documentTitle(pageName).documentPath("/" + pageName)
.userIp(ipAddress).send();
}
}
/**
* A /genepage shortcut which generates a redirect to a prepopulated KnetMaps
* template with the /network query built for the user already. See WEB-INF/views
* to find the HTML template that this query will return.
* @param ds
* @param keyword
* @param list
* @param rawRequest
* @param model
* @return
*/
@CrossOrigin
@GetMapping("/{ds}/genepage")
public String genepage(@PathVariable String ds, @RequestParam(required = false) String keyword,
@RequestParam(required = true) List<String> list, HttpServletRequest rawRequest, Model model) {
KnetminerDataSource dataSource = this.getConfiguredDatasource(ds, rawRequest);
if (dataSource == null) {
throw new HttpClientErrorException ( HttpStatus.BAD_REQUEST, "Data source '" + ds + "' doesn't exist" );
}
this._googlePageView(ds, "genepage", rawRequest);
model.addAttribute("list", new JSONArray(list).toString());
if (keyword != null && !"".equals(keyword)) {
model.addAttribute("keyword", keyword);
}
return "genepage";
}
/**
* A /evidencepage shortcut which generates a redirect to a prepopulated KnetMaps
* template with the /evidencePath query built for the user already. See WEB-INF/views
* to find the HTML template that this query will return.
* @param ds
* @param keyword
* @param list
* @param rawRequest
* @param model
* @return
*/
@CrossOrigin
@GetMapping("/{ds}/evidencepage")
public String evidencepage(@PathVariable String ds, @RequestParam(required = true) String keyword,
@RequestParam(required = false) List<String> list, HttpServletRequest rawRequest, Model model) {
KnetminerDataSource dataSource = this.getConfiguredDatasource(ds, rawRequest);
if (dataSource == null) {
throw new HttpClientErrorException ( HttpStatus.BAD_REQUEST, "Data source '" + ds + "' doesn't exist" );
}
this._googlePageView(ds, "evidencepage", rawRequest);
if (!list.isEmpty()) {
model.addAttribute("list", new JSONArray(list).toString());
}
model.addAttribute("keyword", keyword);
return "evidencepage";
}
/**
* Pick up all GET requests sent to any URL matching /X/Y. X is taken to be the
* name of the data source to look up by its getName() function (see above for
* the mapping function buildDataSourceCache(). Y is the 'mode' of the request.
* Spring magic automatically converts the response into JSON. We convert the
* GET parameters into a KnetminerRequest object for handling by the _handle()
* method.
*
* @param ds
* @param mode
* @param qtl
* @param keyword
* @param list TODO: what is this?!
* @param listMode
* @param rawRequest
* @return
*/
@CrossOrigin
@GetMapping("/{ds}/{mode}")
public @ResponseBody ResponseEntity<KnetminerResponse> handle(@PathVariable String ds, @PathVariable String mode,
@RequestParam(required = false) List<String> qtl,
@RequestParam(required = false, defaultValue = "") String keyword,
@RequestParam(required = false) List<String> list,
@RequestParam(required = false, defaultValue = "") String listMode, HttpServletRequest rawRequest) {
if (qtl == null) {
qtl = Collections.emptyList();
}
if (list == null) {
list = Collections.emptyList();
}
// TODO: We need VERY MUCH to stop polluting code this way!
// This MUST go to some utilty and there there MUST BE only some invocation that clearly recalls the semantics
// of these operations, eg, KnetminerServerUtils.logAnalytics ( logger, rawRequest, mode, list )
// This is filed under #462
//
Map<String, String> map = new TreeMap<>();
map.put("host",rawRequest.getServerName());
map.put("port",Integer.toString(rawRequest.getServerPort()));
map.put("mode", mode);
if(keyword != null) {
map.put("keywords", keyword);
}
if(!list.isEmpty()) {
map.put("list", new JSONArray(list).toString());
}
map.put("qtl", new JSONArray(qtl).toString());
map.put("datasource", ds);
if (mode.equals("genome") || mode.equals("genepage") || mode.equals("network")) {
ObjectMessage msg = new ObjectMessage(map);
logAnalytics.log(Level.getLevel("ANALYTICS"),msg);
}
KnetminerRequest request = new KnetminerRequest();
request.setKeyword(keyword);
request.setListMode(listMode);
request.setList(list);
request.setQtl(qtl);
return this._handle(ds, mode, request, rawRequest);
}
/**
* Pick up all POST requests sent to any URL matching /X/Y. X is taken to be the
* name of the data source to look up by its getName() function (see above for
* the mapping function buildDataSourceCache(). Y is the 'mode' of the request.
* Spring magic automatically converts the response into JSON. Spring magic also
* automatically converts the inbound POST JSON body into a KnetminerRequest
* object for handling by the _handle() method.
*
* @param ds
* @param mode
* @param request
* @param rawRequest
* @return
*/
@CrossOrigin
@PostMapping("/{ds}/{mode}")
public @ResponseBody ResponseEntity<KnetminerResponse> handle(@PathVariable String ds, @PathVariable String mode,
@RequestBody KnetminerRequest request, HttpServletRequest rawRequest) {
// TODO WRONG! Duplicating code like this is way too poor and
// it needs to be factorised in a separated utility anyway!
//
Map<String, String> map = new TreeMap<>();
map.put("host",rawRequest.getServerName());
map.put("port",Integer.toString(rawRequest.getServerPort()));
map.put("mode", mode);
String keyword = request.getKeyword();
List<String> list = request.getList();
List<String> qtl = request.getQtl();
if(keyword != null) {
map.put("keywords", keyword);
}
if(!list.isEmpty()) {
map.put("list", new JSONArray(list).toString());
}
map.put("qtl", new JSONArray(qtl).toString());
map.put("datasource", ds);
if (mode.equals("genome") || mode.equals("genepage") || mode.equals("network")) {
ObjectMessage msg = new ObjectMessage(map);
logAnalytics.log(Level.getLevel("ANALYTICS"),msg);
}
return this._handle(ds, mode, request, rawRequest);
}
private KnetminerDataSource getConfiguredDatasource(String ds, HttpServletRequest rawRequest) {
KnetminerDataSource dataSource = this.dataSourceCache.get(ds);
if (dataSource == null) {
log.info("Invalid data source requested: /" + ds);
return null;
}
String incomingUrlPath = rawRequest.getRequestURL().toString().split("\\?")[0];
dataSource.setApiUrl(incomingUrlPath.substring(0, incomingUrlPath.lastIndexOf('/')));
return dataSource;
}
/**
* We use reflection to take the 'mode' (the Y part of the /X/Y request path)
* and look up an equivalent method on the requested data source, then we call
* it with the request parameters passed in.
*
* @param ds
* @param mode
* @param request
* @param rawRequest
* @return
*/
private ResponseEntity<KnetminerResponse> _handle(
String ds, String mode, KnetminerRequest request, HttpServletRequest rawRequest)
{
if ( mode == null || mode.isEmpty () || mode.isBlank () )
throw new IllegalArgumentException ( "Knetminer API invoked with null/empty method name" );
KnetminerDataSource dataSource = this.getConfiguredDatasource(ds, rawRequest);
if (dataSource == null) {
throw new HttpServerErrorException (
HttpStatus.BAD_REQUEST,
"data source name isn't set, probably a Knetminer configuration error"
);
}
if (log.isDebugEnabled()) {
String paramsStr = "Keyword:" + request.getKeyword() + " , List:"
+ Arrays.toString ( request.getList().toArray() ) + " , ListMode:" + request.getListMode()
+ " , QTL:" + Arrays.toString(request.getQtl().toArray());
log.debug ( "Calling " + mode + " with " + paramsStr );
}
this._googlePageView(ds, mode, rawRequest);
try
{
Method method = dataSource.getClass().getMethod(mode, String.class, KnetminerRequest.class);
try {
KnetminerResponse response = (KnetminerResponse) method.invoke(dataSource, ds, request);
return new ResponseEntity<>(response, HttpStatus.OK);
}
catch ( InvocationTargetException ex ) {
// This was caused by a underlying more significant exception, best is to try to catch and re-throw it.
throw ( (Exception) ExceptionUtils.getSignificantException ( ex ) );
}
}
catch (NoSuchMethodException|IllegalAccessException|SecurityException ex) {
throw new ResponseStatusException2 (
HttpStatus.BAD_REQUEST, "Bad API call '" + mode + "': " + getSignificantMessage ( ex ), ex
);
}
catch (IllegalArgumentException ex) {
throw new ResponseStatusException2 (
HttpStatus.BAD_REQUEST,
"Bad parameters passed to the API call '" + mode + "': " + getSignificantMessage ( ex ),
ex
);
}
catch ( RuntimeException ex )
{
// Let's re-throw the same exception, with a wrapping message
throw ExceptionUtils.buildEx (
ex.getClass(), ex, "Application error while running the API call '%s': %s", mode, getSignificantMessage ( ex )
);
}
catch (Exception ex) {
throw new RuntimeException (
"Application error while running the API call '" + mode + "': " + getSignificantMessage ( ex ),
ex
);
}
catch (Error ex) {
// TODO: should we really catch this?!
throw new Error (
"System error while running the API call '" + mode + "': " + getSignificantMessage ( ex ),
ex
);
}
}
}
| AjitPS/KnetMiner | server-base/src/main/java/rres/knetminer/datasource/server/KnetminerServer.java | Java | mit | 15,807 |
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">SLAG</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="nav-make"><a href="/make/index.php">MAKE</a></li>
<li class="nav-move"><a href="/move/index.php">MOVE</a></li>
<li class="nav-sabio"><a href="/sabio/index.php">SABIO</a></li>
</ul>
</div>
</div>
</nav>
<script>highlightActiveTab();</script> | sphynxypoo/slag-of-the-internet | src/inc/header.php | PHP | mit | 970 |
<?php
const COST = 100;
const COST = 50;
echo COST;
| evmorov/lang-compare | code/php/OtherStructureConstant.php | PHP | mit | 53 |
/*
AdMobAdsListener.java
Copyright 2015 AppFeel. All rights reserved.
http://www.appfeel.com
AdMobAds Cordova Plugin (com.admob.google)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.appfeel.cordova.admob;
import android.annotation.SuppressLint;
import android.util.Log;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
@SuppressLint("DefaultLocale")
public class AdMobAdsAdListener extends AdListener {
private String adType = "";
private AdMobAds admobAds;
private boolean isBackFill = false;
public AdMobAdsAdListener(String adType, AdMobAds admobAds, boolean isBackFill) {
this.adType = adType;
this.admobAds = admobAds;
this.isBackFill = isBackFill;
}
@Override
public void onAdLoaded() {
admobAds.onAdLoaded(adType);
admobAds.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(AdMobAds.ADMOBADS_LOGTAG, adType + ": ad loaded");
String event = String.format("javascript:cordova.fireDocumentEvent(admob.events.onAdLoaded, { 'adType': '%s' });", adType);
admobAds.webView.loadUrl(event);
}
});
}
@Override
public void onAdFailedToLoad(int errorCode) {
if (this.isBackFill) {
final int code = errorCode;
admobAds.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
String reason = getErrorReason(code);
Log.d(AdMobAds.ADMOBADS_LOGTAG, adType + ": fail to load ad (" + reason + ")");
String event = String.format("javascript:cordova.fireDocumentEvent(admob.events.onAdFailedToLoad, { 'adType': '%s', 'error': %d, 'reason': '%s' });", adType, code, reason);
admobAds.webView.loadUrl(event);
}
});
} else {
admobAds.tryBackfill(adType);
}
}
/** Gets a string error reason from an error code. */
public String getErrorReason(int errorCode) {
String errorReason = "Unknown";
switch (errorCode) {
case AdRequest.ERROR_CODE_INTERNAL_ERROR:
errorReason = "Internal error";
break;
case AdRequest.ERROR_CODE_INVALID_REQUEST:
errorReason = "Invalid request";
break;
case AdRequest.ERROR_CODE_NETWORK_ERROR:
errorReason = "Network Error";
break;
case AdRequest.ERROR_CODE_NO_FILL:
errorReason = "No fill";
break;
}
return errorReason;
}
@Override
public void onAdOpened() {
admobAds.onAdOpened(adType);
admobAds.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(AdMobAds.ADMOBADS_LOGTAG, adType + ": ad opened");
String event = String.format("javascript:cordova.fireDocumentEvent(admob.events.onAdOpened, { 'adType': '%s' });", adType);
admobAds.webView.loadUrl(event);
}
});
}
@Override
public void onAdLeftApplication() {
admobAds.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(AdMobAds.ADMOBADS_LOGTAG, adType + ": left application");
String event = String.format("javascript:cordova.fireDocumentEvent(admob.events.onAdLeftApplication, { 'adType': '%s' });", adType);
admobAds.webView.loadUrl(event);
}
});
}
@Override
public void onAdClosed() {
admobAds.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(AdMobAds.ADMOBADS_LOGTAG, adType + ": ad closed after clicking on it");
String event = String.format("javascript:cordova.fireDocumentEvent(admob.events.onAdClosed, { 'adType': '%s' });", adType);
admobAds.webView.loadUrl(event);
}
});
}
}
| QuantumRand/admob-google-cordova | src/android/AdMobAdsAdListener.java | Java | mit | 4,742 |
/*****************************************************************************
* This file is part of the Prolog Development Tool (PDT)
*
* Author: Andreas Becker, Ilshat Aliev
* WWW: http://sewiki.iai.uni-bonn.de/research/pdt/start
* Mail: pdt@lists.iai.uni-bonn.de
* Copyright (C): 2013, CS Dept. III, University of Bonn
*
* All rights reserved. This program is made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
****************************************************************************/
package org.cs3.pdt.graphicalviews.internal.ui;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
public class PredicatesListDialog extends Dialog {
String predicates;
private org.eclipse.swt.widgets.List list;
public PredicatesListDialog(Shell parentShell, String predicates) {
super(parentShell);
setShellStyle(getShellStyle() | SWT.RESIZE);
this.predicates = predicates;
}
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
String[] predicateList = predicates.split("[\\[,\\]]");
list = new org.eclipse.swt.widgets.List(composite, SWT.V_SCROLL | SWT.BORDER);
for (String p : predicateList) {
if (p.length() > 0)
list.add(p);
}
list.setSelection(0);
GridData gridData = new GridData();
gridData.grabExcessHorizontalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
gridData.grabExcessVerticalSpace = true;
gridData.verticalAlignment = GridData.FILL;
list.setLayoutData(gridData);
return composite;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText("Predicates");
}
@Override
protected Point getInitialSize() {
return new Point(400, 300);
}
}
| TeamSPoon/logicmoo_base | prolog/logicmoo/pdt_server/pdt.graphicalviews/src/org/cs3/pdt/graphicalviews/internal/ui/PredicatesListDialog.java | Java | mit | 2,350 |
<?php
/*
* @version 0.1 (auto-set)
*/
global $filter_name;
global $clear_codeeditor;
if ($this->filter_name) {
$out['FILTER_SET'] = $this->filter_name;
}
if ($filter_name) {
$this->filter_name = $filter_name;
}
if ($clear_codeeditor) {
$this->clear_codeeditor = $clear_codeeditor;
}
$sections = array();
$filters = array('', 'system', 'behavior', 'hook', 'backup', 'scenes', 'calendar', 'codeeditor');
$total = count($filters);
for ($i = 0; $i < $total; $i++) {
$rec = array();
$rec['FILTER'] = $filters[$i];
if ($rec['FILTER'] == $this->filter_name) {
$rec['SELECTED'] = 1;
}
if (defined('LANG_SETTINGS_SECTION_' . strtoupper($rec['FILTER']))) {
$rec['TITLE'] = constant('LANG_SETTINGS_SECTION_' . strtoupper($rec['FILTER']));
} elseif ($rec['FILTER']=='system') {
$rec['TITLE'] = LANG_SECTION_SYSTEM;
} else {
$rec['TITLE'] = ucfirst($rec['FILTER']);
}
$sections[] = $rec;
if ($filters[$i]) {
$words[] = $filters[$i];
}
}
$out['SECTIONS'] = $sections;
if ($this->filter_name == '' && !defined('SETTINGS_GENERAL_ALICE_NAME')) {
$options = array(
'GENERAL_ALICE_NAME' => 'Computer\'s name'
);
foreach ($options as $k => $v) {
$tmp = SQLSelectOne("SELECT ID FROM settings WHERE NAME LIKE '" . $k . "'");
if (!$tmp['ID']) {
$tmp = array();
$tmp['NAME'] = $k;
$tmp['TITLE'] = $v;
$tmp['TYPE'] = 'text';
$tmp['DEFAULTVALUE'] = '';
$tmp['NOTES'] = '';
$tmp['DATA'] = '';
SQLInsert('settings', $tmp);
}
}
}
if ($this->filter_name == '' && !defined('SETTINGS_GENERAL_START_LAYOUT')) {
$options = array(
'GENERAL_START_LAYOUT' => 'Homepage Layout'
);
foreach ($options as $k => $v) {
$tmp = SQLSelectOne("SELECT ID FROM settings WHERE NAME LIKE '" . $k . "'");
if (!$tmp['ID']) {
$tmp = array();
$tmp['NAME'] = $k;
$tmp['TITLE'] = $v;
$tmp['TYPE'] = 'select';
$tmp['DEFAULTVALUE'] = '';
$tmp['NOTES'] = '';
$tmp['DATA'] = '=Default|homepages=Home Pages|menu=Menu|apps=Applications|cp=Control Panel';
SQLInsert('settings', $tmp);
}
}
}
if ($this->filter_name == 'system' && !defined('SETTINGS_SYSTEM_DISABLE_DEBMES')) {
$options = array(
'SYSTEM_DISABLE_DEBMES' => 'Disable logging (DebMes)'
);
foreach ($options as $k => $v) {
$tmp = SQLSelectOne("SELECT ID FROM settings WHERE NAME LIKE '" . $k . "'");
if (!$tmp['ID']) {
$tmp = array();
$tmp['NAME'] = $k;
$tmp['TITLE'] = $v;
$tmp['TYPE'] = 'onoff';
$tmp['DEFAULTVALUE'] = '0';
$tmp['NOTES'] = '';
$tmp['DATA'] = '';
SQLInsert('settings', $tmp);
}
}
}
if ($this->filter_name == 'system' && !defined('SETTINGS_SYSTEM_DEBMES_PATH')) {
$options = array(
'SYSTEM_DEBMES_PATH' => 'Path to DebMes logs'
);
foreach ($options as $k => $v) {
$tmp = SQLSelectOne("SELECT ID FROM settings WHERE NAME LIKE '" . $k . "'");
if (!$tmp['ID']) {
$tmp = array();
$tmp['NAME'] = $k;
$tmp['TITLE'] = $v;
$tmp['TYPE'] = 'text';
$tmp['DEFAULTVALUE'] = '';
$tmp['NOTES'] = '';
$tmp['DATA'] = '';
SQLInsert('settings', $tmp);
}
}
}
if ($this->filter_name == 'system' && !defined('SETTINGS_SYSTEM_DB_MAIN_SAVE_PERIOD')) {
$options = array(
'SYSTEM_DB_MAIN_SAVE_PERIOD' => array(
'TITLE' => 'Database save period (main data), minutes',
'DEFAULTVALUE' => 15,
'NOTES' => ''
),
'SYSTEM_DB_HISTORY_SAVE_PERIOD' => array(
'TITLE' => 'Database save period (history data), minutes',
'DEFAULTVALUE' => 60,
'NOTES' => ''
)
);
foreach ($options as $k => $v) {
$tmp = SQLSelectOne("SELECT ID FROM settings WHERE NAME LIKE '" . $k . "'");
if (!$tmp['ID']) {
$tmp = array();
$tmp['NAME'] = $k;
$tmp['TITLE'] = $v['TITLE'];
$tmp['TYPE'] = 'text';
$tmp['DEFAULTVALUE'] = $v['DEFAULTVALUE'];
$tmp['NOTES'] = '';
$tmp['DATA'] = '';
SQLInsert('settings', $tmp);
}
}
}
if ($this->filter_name == 'behavior' && !defined('SETTINGS_BEHAVIOR_NOBODYHOME_TIMEOUT')) {
$options = array(
'BEHAVIOR_NOBODYHOME_TIMEOUT' => array(
'TITLE' => 'NobodyHome mode activation timeout (minutes)',
'DEFAULTVALUE' => 60,
'NOTES' => 'Set 0 to disable'
)
);
foreach ($options as $k => $v) {
$tmp = SQLSelectOne("SELECT ID FROM settings WHERE NAME LIKE '" . $k . "'");
if (!$tmp['ID']) {
$tmp = array();
$tmp['NAME'] = $k;
$tmp['TITLE'] = $v['TITLE'];
$tmp['TYPE'] = 'text';
$tmp['DEFAULTVALUE'] = $v['DEFAULTVALUE'];
$tmp['NOTES'] = $v['NOTES'];
$tmp['DATA'] = '';
SQLInsert('settings', $tmp);
}
}
}
if ($this->filter_name == 'hook' && !defined('SETTINGS_HOOK_BARCODE')) {
//SETTINGS_HOOK_BEFORE_PLAYSOUND
//SETTINGS_HOOK_AFTER_PLAYSOUND
$options = array(
'HOOK_BARCODE' => 'Bar-code reading (code)',
'HOOK_PLAYMEDIA' => 'Playmedia (code)',
'HOOK_BEFORE_PLAYSOUND' => 'Before PlaySound (code)',
'HOOK_AFTER_PLAYSOUND' => 'After PlaySound (code)'
);
foreach ($options as $k => $v) {
$tmp = SQLSelectOne("SELECT ID FROM settings WHERE NAME LIKE '" . $k . "'");
if (!$tmp['ID']) {
$tmp = array();
$tmp['NAME'] = $k;
$tmp['TITLE'] = $v;
$tmp['TYPE'] = 'text';
$tmp['DEFAULTVALUE'] = '';
$tmp['NOTES'] = '';
$tmp['DATA'] = '';
SQLInsert('settings', $tmp);
}
}
}
if ($this->filter_name == 'codeeditor') {
if(!defined('SETTINGS_CODEEDITOR_TURNONSETTINGS') || !defined('SETTINGS_CODEEDITOR_SHOWLINE') ||
!defined('SETTINGS_CODEEDITOR_MIXLINE') || !defined('SETTINGS_CODEEDITOR_UPTOLINE') ||
!defined('SETTINGS_CODEEDITOR_SHOWERROR') || !defined('SETTINGS_CODEEDITOR_AUTOCLOSEQUOTES') ||
!defined('SETTINGS_CODEEDITOR_WRAPLINES') || !defined('SETTINGS_CODEEDITOR_AUTOCOMPLETE') ||
!defined('SETTINGS_CODEEDITOR_AUTOCOMPLETE_TYPE') || !defined('SETTINGS_CODEEDITOR_THEME') || !defined('SETTINGS_CODEEDITOR_AUTOSAVE')) {
$cmd = "DELETE FROM `settings` WHERE `NAME` LIKE '%CODEEDITOR_%'";
SQLExec($cmd);
}
$options = array(
'CODEEDITOR_TURNONSETTINGS' => LANG_CODEEDITOR_TURNONSETTINGS,
'CODEEDITOR_SHOWLINE' => LANG_CODEEDITOR_SHOWLINE,
'CODEEDITOR_MIXLINE' => LANG_CODEEDITOR_MIXLINE,
'CODEEDITOR_UPTOLINE' => LANG_CODEEDITOR_UPTOLINE,
'CODEEDITOR_SHOWERROR' => LANG_CODEEDITOR_SHOWERROR,
'CODEEDITOR_AUTOCLOSEQUOTES' => LANG_CODEEDITOR_AUTOCLOSEQUOTES,
'CODEEDITOR_WRAPLINES' => LANG_CODEEDITOR_WRAPLINES,
'CODEEDITOR_AUTOCOMPLETE' => LANG_CODEEDITOR_AUTOCOMPLETE,
'CODEEDITOR_AUTOCOMPLETE_TYPE' => LANG_CODEEDITOR_AUTOCOMPLETE_TYPE,
'CODEEDITOR_THEME' => LANG_CODEEDITOR_THEME,
'CODEEDITOR_AUTOSAVE' => LANG_CODEEDITOR_AUTOSAVE,
);
foreach ($options as $k => $v) {
$tmp = SQLSelectOne("SELECT ID FROM settings WHERE NAME LIKE '" . $k . "'");
if (!$tmp['ID']) {
$tmp = array();
$tmp['NAME'] = $k;
$tmp['TITLE'] = $v;
$tmp['DATA'] = '';
$tmp['DEFAULTVALUE'] = '';
if ($k == 'CODEEDITOR_SHOWLINE') {
$tmp['TYPE'] = 'select';
$tmp['DATA'] = '10=10|35=35|45=45|100=100|500=500|1000=1000|99999='.LANG_CODEEDITOR_BYCODEHEIGHT;
} elseif ($k == 'CODEEDITOR_MIXLINE') {
$tmp['TYPE'] = 'select';
$tmp['DATA'] = '5=5|10=10|25=25|40=40|1='.LANG_CODEEDITOR_BYCODEHEIGHT;
} elseif ($k == 'CODEEDITOR_AUTOSAVE') {
$tmp['TYPE'] = 'select';
$tmp['DATA'] = '0='.LANG_CODEEDITOR_AUTOSAVE_PARAMS_ONLY_HANDS.'|5='.LANG_CODEEDITOR_AUTOSAVE_PARAMS_EVERY_5.'|10='.LANG_CODEEDITOR_AUTOSAVE_PARAMS_EVERY_10.'|15='.LANG_CODEEDITOR_AUTOSAVE_PARAMS_EVERY_15.'|30='.LANG_CODEEDITOR_AUTOSAVE_PARAMS_EVERY_30.'|60='.LANG_CODEEDITOR_AUTOSAVE_PARAMS_EVERY_60;
} elseif ($k == 'CODEEDITOR_THEME') {
$tmp['TYPE'] = 'select';
$tmp['DATA'] = 'codemirror='.LANG_DEFAULT.'|smoke_theme=SmoKE xD Theme|ambiance=Ambiance|base16-light=base16-light|dracula=Dracula|icecoder=Icecoder|material=Material|moxer=Moxer|neat=Neat';
$tmp['DEFAULTVALUE'] = 'codemirror';
} elseif ($k == 'CODEEDITOR_AUTOCOMPLETE_TYPE') {
$tmp['TYPE'] = 'select';
$tmp['DATA'] = 'none='.LANG_DEFAULT.'|php='.LANG_CODEEDITOR_AUTOCOMPLETE_TYPE_ONLYPHP.'|phpmjdm='.LANG_CODEEDITOR_AUTOCOMPLETE_TYPE_PHPMJDM.'|mjdmuser='.LANG_CODEEDITOR_AUTOCOMPLETE_TYPE_MJDMUSER.'|user='.LANG_CODEEDITOR_AUTOCOMPLETE_TYPE_USER.'|all='.LANG_CODEEDITOR_AUTOCOMPLETE_TYPE_PHPMJDMUSER.'';
$tmp['DEFAULTVALUE'] = 'codemirror';
} else {
$tmp['TYPE'] = 'onoff';
}
$tmp['NOTES'] = '';
SQLInsert('settings', $tmp);
}
}
}
if ($this->filter_name == 'scenes' && !defined('SETTINGS_SCENES_VERTICAL_NAV')) {
$options = array(
'SCENES_VERTICAL_NAV' => 'Vertical navigation'
);
foreach ($options as $k => $v) {
$tmp = SQLSelectOne("SELECT ID FROM settings WHERE NAME LIKE '" . $k . "'");
if (!$tmp['ID']) {
$tmp = array();
$tmp['NAME'] = $k;
$tmp['TITLE'] = $v;
$tmp['TYPE'] = 'onoff';
$tmp['DEFAULTVALUE'] = '0';
$tmp['NOTES'] = '';
$tmp['DATA'] = '';
SQLInsert('settings', $tmp);
}
}
}
if ($this->filter_name == 'scenes' && !defined('SETTINGS_SCENES_BACKGROUND_VIDEO')) {
$options = array(
'SCENES_BACKGROUND' => 'Path to background',
'SCENES_BACKGROUND_VIDEO' => 'Path to video background',
'SCENES_CLICKSOUND' => 'Path to click-sound file'
);
foreach ($options as $k => $v) {
$tmp = SQLSelectOne("SELECT ID FROM settings WHERE NAME LIKE '" . $k . "'");
if (!$tmp['ID']) {
$tmp = array();
$tmp['NAME'] = $k;
$tmp['TITLE'] = $v;
$tmp['TYPE'] = 'path';
$tmp['NOTES'] = '';
$tmp['DATA'] = '';
SQLInsert('settings', $tmp);
}
}
$options = array(
'SCENES_BACKGROUND_FIXED' => 'Backround Fixed',
'SCENES_BACKGROUND_NOREPEAT' => 'Background No repeat'
);
foreach ($options as $k => $v) {
$tmp = SQLSelectOne("SELECT ID FROM settings WHERE NAME LIKE '" . $k . "'");
if (!$tmp['ID']) {
$tmp = array();
$tmp['NAME'] = $k;
$tmp['TITLE'] = $v;
$tmp['TYPE'] = 'onoff';
$tmp['DEFAULTVALUE'] = '0';
$tmp['NOTES'] = '';
$tmp['DATA'] = '';
SQLInsert('settings', $tmp);
}
}
}
if ($this->filter_name == 'backup' && !defined('SETTINGS_BACKUP_PATH')) {
$options = array(
'BACKUP_PATH' => 'Path to store backup'
);
foreach ($options as $k => $v) {
$tmp = SQLSelectOne("SELECT ID FROM settings WHERE NAME LIKE '" . $k . "'");
if (!$tmp['ID']) {
$tmp = array();
$tmp['NAME'] = $k;
$tmp['TITLE'] = $v;
$tmp['TYPE'] = 'text';
$tmp['NOTES'] = '';
$tmp['DATA'] = '';
SQLInsert('settings', $tmp);
}
}
}
// if (!empty($options)) {
// }
global $session;
if ($this->owner->name == 'panel') {
$out['CONTROLPANEL'] = 1;
}
$qry = "1";
// search filters
// search filters
if ($this->filter_name != '') {
$qry .= " AND NAME LIKE '%" . DBSafe($this->filter_name) . "%'";
$out['FILTER_NAME'] = $this->filter_name;
}
if ($this->filter_exname != '') {
$qry .= " AND NAME NOT LIKE '%" . DBSafe($this->filter_exname) . "%'";
$out['FILTER_EXNAME'] = $this->filter_exname;
}
if (!$this->filter_name) {
//$words=array('HP', 'PROFILE');
foreach ($words as $wrd) {
$qry .= " AND NAME NOT LIKE '%" . DBSafe($wrd) . "%'";
}
}
if ($this->section_title != '') {
$out['SECTION_TITLE'] = $this->section_title;
}
if (($this->filter_name == '') and ($this->name == 'settings')) {
$qry .= " and NAME IN('GENERAL_START_LAYOUT','SCENES_WIDTH','SCENES_HEIGHT','VOICE_LANGUAGE','THEME','SPEAK_SIGNAL','HOOK_BEFORE_SAY',
'HOOK_AFTER_SAY','BACKUP_PATH', 'GENERAL_ALICE_NAME','SITE_TIMEZONE','TTS_GOOGLE','SITE_LANGUAGE','HOOK_EVENT_SAY','HOOK_EVENT_HOURLY',
'HOOK_BARCODE', 'HOOK_PLAYMEDIA','HOOK_BEFORE_PLAYSOUND','HOOK_AFTER_PLAYSOUND','HOOK_EVENT_COMMAND','HOOK_EVENT_SAYREPLY','HOOK_EVENT_SAYTO','HOOK_EVENT_ASK')";
}
// QUERY READY
// QUERY READY
global $save_qry;
if ($save_qry) {
$qry = $session->data['settings_qry'];
} else {
$session->data['settings_qry'] = $qry;
}
if (!$qry) $qry = "1";
// FIELDS ORDER
// FIELDS ORDER
global $sortby;
if (!$sortby) {
$sortby = $session->data['settings_sort'];
} else {
if ($session->data['settings_sort'] == $sortby) {
if (Is_Integer(strpos($sortby, ' DESC'))) {
$sortby = str_replace(' DESC', '', $sortby);
} else {
$sortby = $sortby . " DESC";
}
}
$session->data['settings_sort'] = $sortby;
}
$sortby = "PRIORITY DESC, NAME";
$out['SORTBY'] = $sortby;
// SEARCH RESULTS
// SEARCH RESULTS
$sql = "SELECT * FROM settings WHERE $qry ORDER BY $sortby";
$res = SQLSelect($sql);
debmes($sql, 'settings');
if ($res[0]['ID']) {
$total = count($res);
for ($i = 0; $i < $total; $i++) {
// some action for every record if required
// some action for every record if required
if ($this->mode == 'update') {
global ${'value_' . $res[$i]['ID']};
global ${'notes_' . $res[$i]['ID']};
if ($res[$i]['TYPE'] == 'json' && preg_match('/^hook/is', $res[$i]['NAME'])) {
$data = json_decode($res[$i]['VALUE'], true);
foreach ($data as $k => $v) {
$data[$k]['filter'] = gr($k . '_' . $res[$i]['ID'] . '_filter');
if ($data[$k]['filter'] == '') {
unset($data[$k]['filter']);
}
$data[$k]['priority'] = gr($k . '_' . $res[$i]['ID'] . '_priority', 'int');
}
${'value_' . $res[$i]['ID']} = json_encode($data);
}
if (!isset(${'value_' . $res[$i]['ID']})) continue;
$all_settings[$res[$i]['NAME']] = ${'value_' . $res[$i]['ID']};
$res[$i]['VALUE'] = ${'value_' . $res[$i]['ID']};
$res[$i]['NOTES'] = htmlspecialchars(${'notes_' . $res[$i]['ID']});
SQLUpdate('settings', $res[$i]);
}
if ($this->mode == 'reset') {
$res[$i]['VALUE'] = $res[$i]['DEFAULTVALUE'];
SQLUpdate('settings', $res[$i]);
}
if ($res[$i]['TYPE'] == 'select') {
$data = explode('|', $res[$i]['DATA']);
foreach ($data as $v) {
list($ov, $ot) = explode('=', $v);
$res[$i]['OPTIONS'][] = array('OPTION_TITLE' => $ot, 'OPTION_VALUE' => $ov);
}
} elseif ($res[$i]['TYPE'] == 'json' && preg_match('/^hook/is', $res[$i]['NAME'])) {
$data = json_decode($res[$i]['VALUE'], true);
if (is_array($data)) {
foreach ($data as $k => $v) {
$row = array('OPTION_TITLE' => $k, 'FILTER' => $v['filter'], 'PRIORITY' => (int)$v['priority']);
$res[$i]['OPTIONS'][] = $row;
}
}
if (is_array($res[$i]['OPTIONS'])) {
usort($res[$i]['OPTIONS'], function ($a, $b) {
if ($a['PRIORITY'] == $b['PRIORITY']) {
return 0;
}
return ($a['PRIORITY'] > $b['PRIORITY']) ? -1 : 1;
});
}
}
if ($res[$i]['VALUE'] == $res[$i]['DEFAULTVALUE']) {
$res[$i]['ISDEFAULT'] = '1';
}
$res[$i]['VALUE'] = htmlspecialchars($res[$i]['VALUE']);
$res[$i]['HINT_NAME'] = 'settings' . str_replace('_', '', $res[$i]['NAME']);
}
$out['RESULT'] = $res;
}
// some action for every record if required
if ($this->mode == 'update') {
if ($this->filter_name == 'system' && file_exists(ROOT.'scripts/cycle_db_save.php')) {
$service = 'cycle_db_save';
sg($service . 'Run', '');
sg($service . 'Control', 'restart');
}
$this->redirect("?updated=1&filter_name=" . $this->filter_name);
}
| sergejey/majordomo | modules/settings/settings_search.inc.php | PHP | mit | 17,008 |
dimensions(8,8)
wall((2,0),(2,4))
wall((2,4),(4,4))
wall((2,6),(6,6))
wall((6,6),(6,0))
wall((6,2),(4,2))
initialRobotLoc(1.0, 1.0)
| Cynary/distro6.01 | arch/6.01Soft/lib601-F13-4/soar/worlds/bigFrustrationWorld.py | Python | mit | 133 |
System.register(['@angular/core', '@angular/router', '../user/user.service', './login.service', '../shared/alert/dtalert.component', '../shared/spinner/dtspinner.component'], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1, router_1, user_service_1, login_service_1, dtalert_component_1, dtspinner_component_1;
var LoginComponent;
return {
setters:[
function (core_1_1) {
core_1 = core_1_1;
},
function (router_1_1) {
router_1 = router_1_1;
},
function (user_service_1_1) {
user_service_1 = user_service_1_1;
},
function (login_service_1_1) {
login_service_1 = login_service_1_1;
},
function (dtalert_component_1_1) {
dtalert_component_1 = dtalert_component_1_1;
},
function (dtspinner_component_1_1) {
dtspinner_component_1 = dtspinner_component_1_1;
}],
execute: function() {
LoginComponent = (function () {
function LoginComponent(_loginService, _router, _userService) {
this._loginService = _loginService;
this._router = _router;
this._userService = _userService;
this.pageTitle = "Login";
this.EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
this.dtAlert = new dtalert_component_1.DtAlertComponent();
}
LoginComponent.prototype.submit = function () {
var _this = this;
var isValid = this.validateEmailAndPassword();
if (!isValid) {
return;
}
var payload = { "email": this.email, "password": this.password };
this._loginService
.login(payload)
.subscribe(function (result) {
if (!result.success) {
_this.dtAlert.failure(result.message);
return;
}
_this._userService.add(result);
_this._router.navigate(['dashboard']);
}, function (error) { return _this.dtAlert.failure(error); });
};
LoginComponent.prototype.validateEmailAndPassword = function () {
if (this.email == null || this.email == "" || !this.EMAIL_REGEXP.test(this.email)) {
this.dtAlert.failure("Please enter a valid email");
return false;
}
if (this.password == null || this.password == "") {
this.dtAlert.failure("Please enter a password");
return false;
}
return true;
};
__decorate([
core_1.Input(),
__metadata('design:type', String)
], LoginComponent.prototype, "email", void 0);
__decorate([
core_1.Input(),
__metadata('design:type', String)
], LoginComponent.prototype, "password", void 0);
LoginComponent = __decorate([
core_1.Component({
templateUrl: 'app/login/login.component.html',
directives: [dtalert_component_1.DtAlertComponent, dtspinner_component_1.DtSpinButtonComponent]
}),
__metadata('design:paramtypes', [login_service_1.LoginService, router_1.Router, user_service_1.UserService])
], LoginComponent);
return LoginComponent;
}());
exports_1("LoginComponent", LoginComponent);
}
}
});
//# sourceMappingURL=login.component.js.map | alphaCoder/DollarTracker.Web | app/login/login.component.js | JavaScript | mit | 4,925 |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestBlogSettings(unittest.TestCase):
pass
| adityahase/frappe | frappe/website/doctype/blog_settings/test_blog_settings.py | Python | mit | 224 |
<?php
namespace Mopa\BootstrapBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class BarcodeController extends WebTestCase
{
public function testTest()
{
$this->assertTrue(True, 'Wow');
}
} | phiamo/MopaBarcodeBundle | Tests/Controller/BarcodeControllerTest.php | PHP | mit | 240 |
package com.ocdsoft.bacta.swg.shared.collision;
/**
* Created by crush on 8/13/2014.
*/
public class DoorInfo {
public String frameAppearance;
public String doorAppearance;
public String doorAppearance2;
public boolean doorFlip2;
//public Vector delta;
public float openTime;
public float closeTime;
public float sprint;
public float smoothness;
public float triggerRadius;
public boolean forceField;
public String openBeginEffect;
public String openEndEffect;
public String closeBeginEffect;
public String closeEndEffect;
//public IndexedTriangleList portalGeometry;
public boolean alwaysOpen;
}
| bacta/pre-cu | src/main/java/com/ocdsoft/bacta/swg/shared/collision/DoorInfo.java | Java | mit | 672 |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm2 16H5V5h11.17L19 7.83V19zm-7-7c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3zM6 6h9v4H6z"
}), 'SaveOutlined');
exports.default = _default; | oliviertassinari/material-ui | packages/mui-icons-material/lib/SaveOutlined.js | JavaScript | mit | 632 |
class AddDeviseToUsers < ActiveRecord::Migration
def self.up
change_table(:users) do |t|
## Database authenticatable
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
t.string :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
t.string :unlock_token # Only if unlock strategy is :email or :both
t.datetime :locked_at
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
add_index :users, :confirmation_token, unique: true
add_index :users, :unlock_token, unique: true
end
def self.down
# By default, we don't want to make any assumption about how to roll back a migration when your
# model already existed. Please edit below which fields you would like to remove in this migration.
raise ActiveRecord::IrreversibleMigration
end
end
| marceloboeira/spread_blood | db/migrate/20150411175700_add_devise_to_users.rb | Ruby | mit | 1,517 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeCleanup;
using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics.CSharp;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting
{
[UseExportProvider]
public class CodeCleanupTests
{
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task RemoveUsings()
{
var code = @"using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}
";
var expected = @"using System;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine();
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task SortUsings()
{
var code = @"using System.Collections.Generic;
using System;
class Program
{
static void Main(string[] args)
{
var list = new List<int>();
Console.WriteLine(list.Count);
}
}
";
var expected = @"using System;
using System.Collections.Generic;
internal class Program
{
private static void Main(string[] args)
{
List<int> list = new List<int>();
Console.WriteLine(list.Count);
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact, WorkItem(36984, "https://github.com/dotnet/roslyn/issues/36984")]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task GroupUsings()
{
var code = @"using M;
using System;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(""Hello World!"");
new Goo();
}
}
namespace M
{
public class Goo { }
}
";
var expected = @"using M;
using System;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(""Hello World!"");
new Goo();
}
}
namespace M
{
public class Goo { }
}
";
return AssertCodeCleanupResult(expected, code, systemUsingsFirst: false, separateUsingGroups: true);
}
[Fact, WorkItem(36984, "https://github.com/dotnet/roslyn/issues/36984")]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task SortAndGroupUsings()
{
var code = @"using M;
using System;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(""Hello World!"");
new Goo();
}
}
namespace M
{
public class Goo { }
}
";
var expected = @"using System;
using M;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(""Hello World!"");
new Goo();
}
}
namespace M
{
public class Goo { }
}
";
return AssertCodeCleanupResult(expected, code, systemUsingsFirst: true, separateUsingGroups: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixAddRemoveBraces()
{
var code = @"class Program
{
void Method()
{
int a = 0;
if (a > 0)
a ++;
}
}
";
var expected = @"internal class Program
{
private void Method()
{
int a = 0;
if (a > 0)
{
a++;
}
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task RemoveUnusedVariable()
{
var code = @"class Program
{
void Method()
{
int a;
}
}
";
var expected = @"internal class Program
{
private void Method()
{
}
}
";
return AssertCodeCleanupResult(expected, code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeCleanup)]
public Task FixAccessibilityModifiers()
{
var code = @"class Program
{
void Method()
{
int a;
}
}
";
var expected = @"internal class Program
{
private void Method()
{
}
}
";
return AssertCodeCleanupResult(expected, code);
}
protected static async Task AssertCodeCleanupResult(string expected, string code, bool systemUsingsFirst = true, bool separateUsingGroups = false)
{
var exportProvider = ExportProviderCache
.GetOrCreateExportProviderFactory(
TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(typeof(CodeCleanupAnalyzerProviderService)))
.CreateExportProvider();
using var workspace = TestWorkspace.CreateCSharp(code, exportProvider: exportProvider);
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp, systemUsingsFirst)
.WithChangedOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp, separateUsingGroups)));
// register this workspace to solution crawler so that analyzer service associate itself with given workspace
var incrementalAnalyzerProvider = workspace.ExportProvider.GetExportedValue<IDiagnosticAnalyzerService>() as IIncrementalAnalyzerProvider;
incrementalAnalyzerProvider.CreateIncrementalAnalyzer(workspace);
var hostdoc = workspace.Documents.Single();
var document = workspace.CurrentSolution.GetDocument(hostdoc.Id);
var codeCleanupService = document.GetLanguageService<ICodeCleanupService>();
var enabledDiagnostics = codeCleanupService.GetAllDiagnostics();
var newDoc = await codeCleanupService.CleanupAsync(
document, enabledDiagnostics, new ProgressTracker(), CancellationToken.None);
var actual = await newDoc.GetTextAsync();
Assert.Equal(expected, actual.ToString());
}
[Export(typeof(IHostDiagnosticAnalyzerPackageProvider))]
private class CodeCleanupAnalyzerProviderService : IHostDiagnosticAnalyzerPackageProvider
{
private readonly HostDiagnosticAnalyzerPackage _info;
[ImportingConstructor]
public CodeCleanupAnalyzerProviderService()
{
_info = new HostDiagnosticAnalyzerPackage("CodeCleanup", GetCompilerAnalyzerAssemblies().Distinct().ToImmutableArray());
}
private static IEnumerable<string> GetCompilerAnalyzerAssemblies()
{
yield return typeof(CSharpCompilerDiagnosticAnalyzer).Assembly.Location;
yield return typeof(UseExpressionBodyDiagnosticAnalyzer).Assembly.Location;
}
public IAnalyzerAssemblyLoader GetAnalyzerAssemblyLoader()
{
return FromFileLoader.Instance;
}
public ImmutableArray<HostDiagnosticAnalyzerPackage> GetHostDiagnosticAnalyzerPackages()
{
return ImmutableArray.Create(_info);
}
public class FromFileLoader : IAnalyzerAssemblyLoader
{
public static FromFileLoader Instance = new FromFileLoader();
public void AddDependencyLocation(string fullPath)
{
}
public Assembly LoadFromPath(string fullPath)
{
return Assembly.LoadFrom(fullPath);
}
}
}
}
}
| abock/roslyn | src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.cs | C# | mit | 8,573 |
package rule
import (
"encoding/json"
"fmt"
"github.com/influxdata/flux/ast"
"github.com/influxdata/influxdb/v2"
"github.com/influxdata/influxdb/v2/notification/endpoint"
"github.com/influxdata/influxdb/v2/notification/flux"
)
// PagerDuty is the rule config of pagerduty notification.
type PagerDuty struct {
Base
MessageTemplate string `json:"messageTemplate"`
}
type pagerDutyAlias PagerDuty
// MarshalJSON implement json.Marshaler interface.
func (s PagerDuty) MarshalJSON() ([]byte, error) {
return json.Marshal(
struct {
pagerDutyAlias
Type string `json:"type"`
}{
pagerDutyAlias: pagerDutyAlias(s),
Type: s.Type(),
})
}
// Valid returns where the config is valid.
func (s PagerDuty) Valid() error {
if err := s.Base.valid(); err != nil {
return err
}
if s.MessageTemplate == "" {
return &influxdb.Error{
Code: influxdb.EInvalid,
Msg: "pagerduty invalid message template",
}
}
return nil
}
// Type returns the type of the rule config.
func (s PagerDuty) Type() string {
return "pagerduty"
}
// GenerateFlux generates a flux script for the pagerduty notification rule.
func (s *PagerDuty) GenerateFlux(e influxdb.NotificationEndpoint) (string, error) {
pagerdutyEndpoint, ok := e.(*endpoint.PagerDuty)
if !ok {
return "", fmt.Errorf("endpoint provided is a %s, not an PagerDuty endpoint", e.Type())
}
p, err := s.GenerateFluxAST(pagerdutyEndpoint)
if err != nil {
return "", err
}
return ast.Format(p), nil
}
// GenerateFluxAST generates a flux AST for the pagerduty notification rule.
func (s *PagerDuty) GenerateFluxAST(e *endpoint.PagerDuty) (*ast.Package, error) {
f := flux.File(
s.Name,
flux.Imports("influxdata/influxdb/monitor", "pagerduty", "influxdata/influxdb/secrets", "experimental"),
s.generateFluxASTBody(e),
)
return &ast.Package{Package: "main", Files: []*ast.File{f}}, nil
}
func (s *PagerDuty) generateFluxASTBody(e *endpoint.PagerDuty) []ast.Statement {
var statements []ast.Statement
statements = append(statements, s.generateTaskOption())
statements = append(statements, s.generateFluxASTSecrets(e))
statements = append(statements, s.generateFluxASTEndpoint(e))
statements = append(statements, s.generateFluxASTNotificationDefinition(e))
statements = append(statements, s.generateFluxASTStatuses())
statements = append(statements, s.generateLevelChecks()...)
statements = append(statements, s.generateFluxASTNotifyPipe(e.ClientURL))
return statements
}
func (s *PagerDuty) generateFluxASTSecrets(e *endpoint.PagerDuty) ast.Statement {
call := flux.Call(flux.Member("secrets", "get"), flux.Object(flux.Property("key", flux.String(e.RoutingKey.Key))))
return flux.DefineVariable("pagerduty_secret", call)
}
func (s *PagerDuty) generateFluxASTEndpoint(e *endpoint.PagerDuty) ast.Statement {
call := flux.Call(flux.Member("pagerduty", "endpoint"),
flux.Object(),
)
return flux.DefineVariable("pagerduty_endpoint", call)
}
func (s *PagerDuty) generateFluxASTNotifyPipe(url string) ast.Statement {
endpointProps := []*ast.Property{}
// routing_key:
// required
// string
// A version 4 UUID expressed as a 32-digit hexadecimal number. This is the Integration Key for an integration on any given service.
endpointProps = append(endpointProps, flux.Property("routingKey", flux.Identifier("pagerduty_secret")))
// client:
// optional
// string
// name of the client sending the alert.
endpointProps = append(endpointProps, flux.Property("client", flux.String("influxdata")))
// clientURL
// optional
// string
// url of the client sending the alert.
endpointProps = append(endpointProps, flux.Property("clientURL", flux.String(url)))
// class:
// optional
// string
// The class/type of the event, for example ping failure or cpu load
endpointProps = append(endpointProps, flux.Property("class", flux.Identifier("r._check_name")))
// group:
// optional
// string
// Logical grouping of components of a service, for example app-stack
endpointProps = append(endpointProps, flux.Property("group", flux.Member("r", "_source_measurement")))
// severity:
// required
// string
// The perceived severity of the status the event is describing with respect to the affected system. This can be critical, error, warning or info.
endpointProps = append(endpointProps, flux.Property("severity", severityFromLevel()))
// event_action:
// required
// string trigger
// The type of event. Can be trigger, acknowledge or resolve. See Event Action.
endpointProps = append(endpointProps, flux.Property("eventAction", actionFromLevel()))
// source:
// required
// string
// The unique location of the affected system, preferably a hostname or FQDN
endpointProps = append(endpointProps, flux.Property("source", flux.Member("notification", "_notification_rule_name")))
// summary:
// required
// string
// A brief text summary of the event, used to generate the summaries/titles of any associated alerts. The maximum permitted length of this property is 1024 characters.
endpointProps = append(endpointProps, flux.Property("summary", flux.Member("r", "_message")))
// timestamp:
// optional
// timestamp (rfc3339 milliseconds)
// The time at which the emitting tool detected or generated the event.
endpointProps = append(endpointProps, flux.Property("timestamp", generateTime()))
endpointFn := flux.Function(flux.FunctionParams("r"), flux.Object(endpointProps...))
props := []*ast.Property{}
props = append(props, flux.Property("data", flux.Identifier("notification")))
props = append(props, flux.Property("endpoint",
flux.Call(flux.Identifier("pagerduty_endpoint"), flux.Object(flux.Property("mapFn", endpointFn)))))
call := flux.Call(flux.Member("monitor", "notify"), flux.Object(props...))
return flux.ExpressionStatement(flux.Pipe(flux.Identifier("all_statuses"), call))
}
func severityFromLevel() *ast.CallExpression {
return flux.Call(
flux.Member("pagerduty", "severityFromLevel"),
flux.Object(
flux.Property("level", flux.Member("r", "_level")),
),
)
}
func actionFromLevel() *ast.CallExpression {
return flux.Call(
flux.Member("pagerduty", "actionFromLevel"),
flux.Object(
flux.Property("level", flux.Member("r", "_level")),
),
)
}
func generateTime() *ast.CallExpression {
props := []*ast.Property{
flux.Property("v", flux.Member("r", "_source_timestamp")),
}
return flux.Call(flux.Identifier("time"), flux.Object(props...))
}
| nooproblem/influxdb | notification/rule/pagerduty.go | GO | mit | 6,445 |
package net.bitm.items;
import net.bitm.creativeTab;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.ItemHoe;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class nythoe extends ItemHoe{
public nythoe(ToolMaterial par2ToolMaterial) {
super(par2ToolMaterial);
this.maxStackSize = 1;
this.setCreativeTab(creativeTab.bonetabTools);
this.setUnlocalizedName("nythoe");
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister register){
itemIcon = register.registerIcon("bitm" + ":" + "nythoe");
}
}
| xbony2/Bitm | src/main/java/net/bitm/items/nythoe.java | Java | mit | 613 |
using System;
using LibGit2Sharp;
namespace GitTools.Testing
{
/// <summary>
/// Static helper class for generating data git needs, like signatures
/// </summary>
public static class Generate
{
/// <summary>
/// Create a libgit2sharp signature at VirtualTime.Now
/// </summary>
public static Signature SignatureNow()
{
var dateTimeOffset = VirtualTime.Now;
return Signature(dateTimeOffset);
}
/// <summary>
/// Creates a libgit2sharp signature at the specified time
/// </summary>
public static Signature Signature(DateTimeOffset dateTimeOffset)
{
return new Signature("A. U. Thor", "thor@valhalla.asgard.com", dateTimeOffset);
}
}
} | JakeGinnivan/GitTools.Testing | src/GitTools.Testing/Generate.cs | C# | mit | 794 |
package wordsegm;
import java.util.ArrayList;
public class Preprocess {
public ArrayList<String> pretreat(String str, int maxSize) {
ArrayList<String> prepare = new ArrayList<String>();
str = str.replaceAll("[\\pP¡®¡¯¡°¡±]", "");
char[] strChars = str.toCharArray();
for(int index = 0; index < strChars.length; index++) {
String temp = "" + strChars[index];
prepare.add(temp);
for(int count = 1; count < maxSize; count++) {
if(index + count < strChars.length) {
temp = temp + strChars[index + count];
prepare.add(temp);
}
}
}
return prepare;
}
}
| lkmcl37/Simple-WordSeg-Greedy-Algorithm | Preprocess.java | Java | mit | 595 |
/*
* Date: September 1st 2014
* Author: Adil Imroz
* Twitter handle: @adilimroz
* Organization: Moolya Software Testing Pvt Ltd
* License Type: MIT
*/
package utils;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.testng.annotations.Test;
import com.google.gdata.client.spreadsheet.CellQuery;
import com.google.gdata.client.spreadsheet.FeedURLFactory;
import com.google.gdata.client.spreadsheet.SpreadsheetQuery;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.CellEntry;
import com.google.gdata.data.spreadsheet.CellFeed;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.data.spreadsheet.WorksheetEntry;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
public class ReportParseGoogleUpdate {
private static SpreadsheetService service;
private static FeedURLFactory factory;
private static URL url;
public static ReportParseGoogleUpdate spreadSheetDemo;
public static SpreadsheetEntry spreadsheet;
public static WorksheetEntry worksheetEntry;
public static SpreadsheetQuery query;
static int rowFromSearch;
static int colFromSearch;
static List<String> searchArr=new ArrayList<String>();
static List<Object> objects = new ArrayList<Object>();
@Test
public static void ReportParsingGoogleDocUpdate() throws IOException, ServiceException {
System.out.println("Script to parse test report and update google doc with results");
FileReader reader = new FileReader("../orangeHRM/config.properties"); //Reading configuration file
Properties prop = new Properties();
prop.load(reader);
String googleReportParserExecutionFlag = prop.getProperty("googleReportParserExecutionFlag");
String parserGoogleEmail = prop.getProperty("parserGoogleEmail");
String parserGooglePassword = prop.getProperty("parserGooglePassword");
int parserIndexSpreadsheet = Integer.parseInt(prop.getProperty("parserIndexSpreadsheet"));
int parserIndexWorksheet = Integer.parseInt(prop.getProperty("parserIndexWorksheet"));
String parserInputFilePath = prop.getProperty("parserInputFilePath");
if(googleReportParserExecutionFlag.contentEquals("true"))
{
//Auth to access google doc
spreadSheetDemo = new ReportParseGoogleUpdate(parserGoogleEmail, parserGooglePassword); //gmail account via which doc will be accessed for updating test results
spreadsheet = spreadSheetDemo.getSpreadSheet(parserIndexSpreadsheet);//give index to select the spreadsheet from the folder
worksheetEntry = spreadsheet.getWorksheets().get(parserIndexWorksheet); //providing index to access the desired worksheet
url = worksheetEntry.getCellFeedUrl();
query = new SpreadsheetQuery(url);
System.out.println("Title of spreadsheet being updated :: "+spreadsheet.getTitle().getPlainText());
System.out.println("Title of worksheet being updated :: "+worksheetEntry.getTitle().getPlainText());
//
CellFeed feed = service.query(query, CellFeed.class);
//Parsing the Test report from desired folder
File input = new File(parserInputFilePath);
System.out.println("Starting ....");
Document doc = Jsoup.parse(input,null);
System.out.println("midway ....");
Elements testNames = doc.select("html>body>table>tbody>tr>td>a[href~=#t]");//gets the name of the test names from the report
Elements testNameSiblings = doc.select("html>body>table>tbody>tr>td[class~=num]");//gets the siblings of all the test names...they are the test results numbers
System.out.println("testNames size ::"+testNames.size());
System.out.println("testNameSiblings size :: "+testNameSiblings.size());
/////
for (CellEntry entry : feed.getEntries()) {
searchArr.add(entry.getCell().getInputValue());
objects.add(entry.getCell());
}
System.out.println(searchArr);
System.out.println(objects);
int j =0;
for (int i = 0; i < testNames.size(); i++) {
System.out.println("test>"+testNames.get(i).text());
int passed = Integer.parseInt(testNameSiblings.get(j).text());
j=j+1;
int skipped = Integer.parseInt(testNameSiblings.get(j).text());
j=j+1;
int failed = Integer.parseInt(testNameSiblings.get(j).text());
j=j+1;
String testTime = testNameSiblings.get(j).text();
j=j+1;
System.out.println("******************************");
if (passed!=0) {
search(testNames.get(i).text());
CellContentUpdate(worksheetEntry, rowFromSearch, colFromSearch+2, "PASSED");
}
else if (skipped!=0) {
search(testNames.get(i).text());
CellContentUpdate(worksheetEntry, rowFromSearch, colFromSearch+2, "SKIPPED");
}
else if (failed!=0) {
search(testNames.get(i).text());
CellContentUpdate(worksheetEntry, rowFromSearch, colFromSearch+2, "FAILED");
}
}
}
else
{
System.out.println();
System.out.println("googleReportParserExecution feature is turned off via googleReportParserExecutionFlag in config.properties file...");
}
}
/*
* Method Definitions
*/
//Method for authentication to access google doc
public ReportParseGoogleUpdate(String username, String password) throws AuthenticationException {
service = new SpreadsheetService("SpreadSheet-Demo");
factory = FeedURLFactory.getDefault();
System.out.println("Authenticating...");
service.setUserCredentials(username, password);
System.out.println("Successfully authenticated");
}
//Method to get all the spreadsheets associated to the given account
public void GetAllSpreadsheets() throws IOException, ServiceException{
SpreadsheetFeed feed = service.getFeed(factory.getSpreadsheetsFeedUrl(), SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
System.out.println("Total number of SpreadSheets found : " + spreadsheets.size());
for (int i = 0; i < spreadsheets.size(); ++i) {
System.out.println("("+i+") : "+spreadsheets.get(i).getTitle().getPlainText());
}
}
// Returns spreadsheet
public SpreadsheetEntry getSpreadSheet(int spreadsheetIndex) throws IOException, ServiceException {
SpreadsheetFeed feed = service.getFeed(factory.getSpreadsheetsFeedUrl(), SpreadsheetFeed.class);
SpreadsheetEntry spreadsheet = feed.getEntries().get(spreadsheetIndex);
return spreadsheet;
}
//Method to get Spread sheet details
public void GetSpreadsheetDetails(SpreadsheetEntry spreadsheet) throws IOException, ServiceException{
System.out.println("SpreadSheet Title : "+spreadsheet.getTitle().getPlainText());
List<WorksheetEntry> worksheets = spreadsheet.getWorksheets();
for (int i = 0; i < worksheets.size(); ++i) {
WorksheetEntry worksheetEntry = worksheets.get(i);
System.out.println("("+i+") Worksheet Title : "+worksheetEntry.getTitle().getPlainText()+", num of Rows : "+worksheetEntry.getRowCount()+", num of Columns : "+worksheetEntry.getColCount());
}
}
public static void CellContentUpdate(WorksheetEntry worksheetEntry,int row, int col, String formulaOrValue) throws IOException, ServiceException{
URL cellFeedUrl = worksheetEntry.getCellFeedUrl();
CellEntry newEntry = new CellEntry(row, col, formulaOrValue);
service.insert(cellFeedUrl, newEntry);
System.out.println("Cell Updated!");
}
// public static void searchTestNameGDoc(String testNameToSearch) throws IOException, ServiceException{
//
// CellFeed feed = service.query(query, CellFeed.class);
//
// for (CellEntry entry : feed.getEntries()) {
// searchArr.add(entry.getCell().getInputValue());
// objects.add(entry.getCell());
// }
//
// for (int i = 0; i < objects.size(); i++) {
// if (searchArr.get(i)=="BalanaceEnquiry_MandatoryField" ){
// rowFromSearch = feed.getEntries().get(i).getCell().getRow();
// colFromSearch = feed.getEntries().get(i).getCell().getCol();
// break;
// }
//
// }
//
// }
// public static void printCell(CellEntry cell) {
// System.out.println(cell.getCell().getValue());
// }
public static void printCell(CellEntry cell) {
String shortId = cell.getId().substring(cell.getId().lastIndexOf('/') + 1);
System.out.println(" -- Cell(" + shortId + "/" + cell.getTitle().getPlainText()+ ") formula(" + cell.getCell().getInputValue() + ") numeric("+ cell.getCell().getNumericValue() + ") value("+ cell.getCell().getValue() + ")");
rowFromSearch = cell.getCell().getRow();
colFromSearch = cell.getCell().getCol();
System.out.println("row :: "+rowFromSearch);
System.out.println("col :: "+colFromSearch);
}
public static void search(String fullTextSearchString) throws IOException,ServiceException {
CellQuery query = new CellQuery(url);
query.setFullTextQuery(fullTextSearchString);
CellFeed feed = service.query(query, CellFeed.class);
System.out.println("Results for [" + fullTextSearchString + "]");
for (CellEntry entry : feed.getEntries()) {
printCell(entry);
}
}
}
| YagneshShah/SeleniumLearnExploreContribute | orangeHRM/src/utils/ReportParseGoogleUpdate.java | Java | mit | 9,210 |
<?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Rest\Pricing\V1;
use Twilio\Page;
class MessagingPage extends Page {
public function __construct($version, $response, $solution) {
parent::__construct($version, $response);
// Path Solution
$this->solution = $solution;
}
public function buildInstance(array $payload) {
return new MessagingInstance($this->version, $payload);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString() {
return '[Twilio.Pricing.V1.MessagingPage]';
}
} | unaio/una | upgrade/files/12.1.0-13.0.0.A1/files/plugins/twilio/sdk/src/Twilio/Rest/Pricing/V1/MessagingPage.php | PHP | mit | 726 |
//
// This is example code from Chapter 25.7 "Drill" of
// "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup
//
#include <iostream>
using namespace std;
//------------------------------------------------------------------------------
int main()
{
// for int
{
int v = 1;
for (int i = 0; i<sizeof(v)*8; ++i)
{
cout << v << ' '; v <<=1;
}
}
// for unsigned int
{
unsigned int v = 1;
for (int i = 0; i<sizeof(v)*8; ++i)
{
cout << v << ' '; v <<=1;
}
}
}
//------------------------------------------------------------------------------
| bewuethr/stroustrup_ppp | code_snippets/Chapter25/chapter.25.7.cpp | C++ | mit | 681 |
define(['../lib/circle', '../lib/aura', './collision', '../lib/vector', '../lib/dictionary'],function(Circle, Aura, collision, Vector, Dictionary){
var Particle = function(world, options) {
var options = options || {}
Circle.call(this, options);
//TODO: implement singleton for the world
this.world = world;
this.mass = this.radius;
// this.energy = 100;
this.speed = options.speed || 3;
// todo: move this somewhere else
this.directions = new Dictionary({
n: new Vector(0, 1),
s: new Vector(0, -1),
e: new Vector(1, 0),
w: new Vector(-1, 0),
ne: new Vector(1, 1),
se: new Vector(1, -1),
nw: new Vector(-1, 1),
sw: new Vector(-1, -1)
});
this.setDirection(options.direction || this.directions.random());
this.aura = new Aura(this);
};
// inheritance
Particle.prototype = Object.create(Circle.prototype);
Particle.prototype.act = function() {
this.move();
};
/**
* Change position of object based on direction
* and speed
*/
Particle.prototype.move = function() {
var pos = this.position.add(new Vector(this.direction.normalize().x * this.speed, this.direction.normalize().y * this.speed));
this.setPosition(pos);
};
/**
* React to collision depending on the type of object
*/
Particle.prototype.reactToCollision = function(other) {
//TODO: fix this
//http://en.wikipedia.org/wiki/Elastic_collision
//http://www.gamasutra.com/view/feature/131424/pool_hall_lessons_fast_accurate_.php?page=3
var n = this.position.sub(other.prevPosition).normalize();
var a1 = this.direction.dot(n);
var a2 = other.prevDirection.dot(n);
var optimizedP = (2 * (a1 - a2)) / (this.mass + other.mass);
var newDir = this.direction.sub(n.mult(optimizedP * other.mass));
// this.setPosition(this.prevPosition);
this.setDirection(newDir);
// this.move();
};
/**
* Needed to keep track of the previous direction
*/
Particle.prototype.setDirection = function(vector){
this.prevDirection = this.direction || vector;
this.direction = vector;
};
/**
* Render
*/
Particle.prototype.render = function(){
this.aura.render();
this.constructor.prototype.render.call(this);
};
Particle.prototype.setPosition = function(pos){
this.prevPosition = this.position || pos;
this.constructor.prototype.setPosition.call(this, pos);
};
return Particle;
}); | dayllanmaza/particles | game/particle.js | JavaScript | mit | 2,363 |
/*
Copyright 2013-2015 ASIAL CORPORATION
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.
*/
import animit from '../../ons/animit';
import SplitterAnimator from './animator.js';
export default class PushSplitterAnimator extends SplitterAnimator {
_getSlidingElements() {
const slidingElements = [this._side, this._content];
if (this._oppositeSide && this._oppositeSide.mode === 'split') {
slidingElements.push(this._oppositeSide);
}
return slidingElements;
}
translate(distance) {
if (!this._slidingElements) {
this._slidingElements = this._getSlidingElements();
}
animit(this._slidingElements)
.queue({
transform: `translate3d(${this.minus + distance}px, 0px, 0px)`
})
.play();
}
/**
* @param {Function} done
*/
open(done) {console.log('opening');
const max = this._side.offsetWidth;
this._slidingElements = this._getSlidingElements();
animit.runAll(
animit(this._slidingElements)
.wait(this.delay)
.queue({
transform: `translate3d(${this.minus + max}px, 0px, 0px)`
}, {
duration: this.duration,
timing: this.timing
})
.queue(callback => {
this._slidingElements = null;
callback();
done && done();
}),
animit(this._mask)
.wait(this.delay)
.queue({
display: 'block'
})
);
}
/**
* @param {Function} done
*/
close(done) {
this._slidingElements = this._getSlidingElements();
animit.runAll(
animit(this._slidingElements)
.wait(this.delay)
.queue({
transform: 'translate3d(0px, 0px, 0px)'
}, {
duration: this.duration,
timing: this.timing
})
.queue(callback => {
this._slidingElements = null;
super.clearTransition();
done && done();
callback();
}),
animit(this._mask)
.wait(this.delay)
.queue({
display: 'none'
})
);
}
}
| nocommon/ecbook_app | www/lib/onsenui/core-src/elements/ons-splitter/push-animator.js | JavaScript | mit | 2,549 |
;modjewel.define("weinre/target/SqlStepper", function(require, exports, module) { // Generated by CoffeeScript 1.3.3
var Binding, SqlStepper, executeSql, ourErrorCallback, runStep;
Binding = require('../common/Binding');
module.exports = SqlStepper = (function() {
function SqlStepper(steps) {
var context;
if (!(this instanceof SqlStepper)) {
return new SqlStepper(steps);
}
this.__context = {};
context = this.__context;
context.steps = steps;
}
SqlStepper.prototype.run = function(db, errorCallback) {
var context;
context = this.__context;
if (context.hasBeenRun) {
throw new Ex(arguments, "stepper has already been run");
}
context.hasBeenRun = true;
context.db = db;
context.errorCallback = errorCallback;
context.nextStep = 0;
context.ourErrorCallback = new Binding(this, ourErrorCallback);
context.runStep = new Binding(this, runStep);
this.executeSql = new Binding(this, executeSql);
return db.transaction(context.runStep);
};
SqlStepper.example = function(db, id) {
var errorCb, step1, step2, stepper;
step1 = function() {
return this.executeSql("SELECT name FROM sqlite_master WHERE type='table'");
};
step2 = function(resultSet) {
var i, name, result, rows;
rows = resultSet.rows;
result = [];
i = 0;
while (i < rows.length) {
name = rows.item(i).name;
if (name === "__WebKitDatabaseInfoTable__") {
i++;
continue;
}
result.push(name);
i++;
}
return console.log(("[" + this.id + "] table names: ") + result.join(", "));
};
errorCb = function(sqlError) {
return console.log(("[" + this.id + "] sql error:" + sqlError.code + ": ") + sqlError.message);
};
stepper = new SqlStepper([step1, step2]);
stepper.id = id;
return stepper.run(db, errorCb);
};
return SqlStepper;
})();
executeSql = function(statement, data) {
var context;
context = this.__context;
return context.tx.executeSql(statement, data, context.runStep, context.ourErrorCallback);
};
ourErrorCallback = function(tx, sqlError) {
var context;
context = this.__context;
return context.errorCallback.call(this, sqlError);
};
runStep = function(tx, resultSet) {
var context, step;
context = this.__context;
if (context.nextStep >= context.steps.length) {
return;
}
context.tx = tx;
context.currentStep = context.nextStep;
context.nextStep++;
step = context.steps[context.currentStep];
return step.call(this, resultSet);
};
require("../common/MethodNamer").setNamesForClass(module.exports);
});
| junlonghuo/ak47 | weinre/web/weinre/target/SqlStepper.amd.js | JavaScript | mit | 2,660 |
Given /^There are many snippets$/ do
100.times do |i|
Snippet.create(:name => "snippet_#{i}", :content => "This is snippet #{i}")
end
end
Given /^There are few snippets$/ do
#
end
Then /^I should not see pagination controls$/ do
response.body.should_not have_tag('div.pagination')
end
Then /^I should not see a depagination link$/ do
response.body.should_not have_tag('div.depaginate')
end
Then /^I should see pagination controls$/ do
response.body.should have_tag('div.pagination')
end
Then /^I should see page (\d+) of the results$/ do |p|
response.body.should have_tag('div.pagination') do
with_tag("span.current", :text => p)
end
end
Then /^I should see a depagination link$/ do
response.body.should have_tag('div.depaginate') do
with_tag("a", :text => "show all")
end
end
Then /^I should mention the request parameters$/ do
puts "!! params: #{request.params.inspect}"
true
end
Then /^I should see all the snippets$/ do
Snippet.all.each do |snippet|
response.body.should have_tag('tr.node') do
with_tag("a", :text => snippet.name)
end
end
end
| davidsevcik/propeople-cms | vendor/radiant/features/step_definitions/admin/pagination_steps.rb | Ruby | mit | 1,110 |
#!/usr/bin/env python
import sys,os
import textwrap
def print_header():
print textwrap.dedent("""\
##fileformat=VCFv4.1
##phasing=none
##INDIVIDUAL=TRUTH
##SAMPLE=<ID=TRUTH,Individual="TRUTH",Description="bamsurgeon spike-in">
##INFO=<ID=CIPOS,Number=2,Type=Integer,Description="Confidence interval around POS for imprecise variants">
##INFO=<ID=IMPRECISE,Number=0,Type=Flag,Description="Imprecise structural variation">
##INFO=<ID=SVTYPE,Number=1,Type=String,Description="Type of structural variant">
##INFO=<ID=SVLEN,Number=.,Type=Integer,Description="Difference in length between REF and ALT alleles">
##INFO=<ID=SOMATIC,Number=0,Type=Flag,Description="Somatic mutation in primary">
##INFO=<ID=VAF,Number=1,Type=Float,Description="Variant Allele Frequency">
##INFO=<ID=DPR,Number=1,Type=Float,Description="Avg Depth in Region (+/- 1bp)">
##INFO=<ID=MATEID,Number=1,Type=String,Description="Breakend mate">
##ALT=<ID=INV,Description="Inversion">
##ALT=<ID=DUP,Description="Duplication">
##ALT=<ID=DEL,Description="Deletion">
##ALT=<ID=INS,Description="Insertion">
##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype">
#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tSPIKEIN""")
if len(sys.argv) == 2:
print_header()
logdir_files = os.listdir(sys.argv[1])
for filename in logdir_files:
if filename.endswith('.log'):
with open(sys.argv[1] + '/' + filename, 'r') as infile:
for line in infile:
if line.startswith('snv'):
#chrom, pos, mut = line.strip().split()
c = line.strip().split()
chrom = c[1].split(':')[0]
pos = c[3]
mut = c[4]
dpr = c[6]
vaf = c[7]
ref,alt = mut.split('-->')
print "\t".join((chrom,pos,'.',ref,alt,'100','PASS','SOMATIC;VAF=' + vaf + ';DPR=' + dpr,'GT','0/1'))
else:
print "usage:", sys.argv[0], "<log directory>"
| MischaLundberg/bamsurgeon | scripts/makevcf.py | Python | mit | 2,120 |
package lfs
import (
"bufio"
"fmt"
"strconv"
"strings"
"github.com/git-lfs/git-lfs/errors"
"github.com/git-lfs/git-lfs/git"
)
// Status represents the status of a file that appears in the output of `git
// diff-index`.
//
// More information about each of its valid instances can be found:
// https://git-scm.com/docs/git-diff-index
type DiffIndexStatus rune
const (
StatusAddition DiffIndexStatus = 'A'
StatusCopy DiffIndexStatus = 'C'
StatusDeletion DiffIndexStatus = 'D'
StatusModification DiffIndexStatus = 'M'
StatusRename DiffIndexStatus = 'R'
StatusTypeChange DiffIndexStatus = 'T'
StatusUnmerged DiffIndexStatus = 'U'
StatusUnknown DiffIndexStatus = 'X'
)
// String implements fmt.Stringer by returning a human-readable name for each
// status.
func (s DiffIndexStatus) String() string {
switch s {
case StatusAddition:
return "addition"
case StatusCopy:
return "copy"
case StatusDeletion:
return "deletion"
case StatusModification:
return "modification"
case StatusRename:
return "rename"
case StatusTypeChange:
return "change"
case StatusUnmerged:
return "unmerged"
case StatusUnknown:
return "unknown"
}
return "<unknown>"
}
// Format implements fmt.Formatter. If printed as "%+d", "%+s", or "%+v", the
// status will be written out as an English word: i.e., "addition", "copy",
// "deletion", etc.
//
// If the '+' flag is not given, the shorthand will be used instead: 'A', 'C',
// and 'D', respectively.
//
// If any other format verb is given, this function will panic().
func (s DiffIndexStatus) Format(state fmt.State, c rune) {
switch c {
case 'd', 's', 'v':
if state.Flag('+') {
state.Write([]byte(s.String()))
} else {
state.Write([]byte{byte(rune(s))})
}
default:
panic(fmt.Sprintf("cannot format %v for DiffIndexStatus", c))
}
}
// DiffIndexEntry holds information about a single item in the results of a `git
// diff-index` command.
type DiffIndexEntry struct {
// SrcMode is the file mode of the "src" file, stored as a string-based
// octal.
SrcMode string
// DstMode is the file mode of the "dst" file, stored as a string-based
// octal.
DstMode string
// SrcSha is the Git blob ID of the "src" file.
SrcSha string
// DstSha is the Git blob ID of the "dst" file.
DstSha string
// Status is the status of the file in the index.
Status DiffIndexStatus
// StatusScore is the optional "score" associated with a particular
// status.
StatusScore int
// SrcName is the name of the file in its "src" state as it appears in
// the index.
SrcName string
// DstName is the name of the file in its "dst" state as it appears in
// the index.
DstName string
}
// DiffIndexScanner scans the output of the `git diff-index` command.
type DiffIndexScanner struct {
// next is the next entry scanned by the Scanner.
next *DiffIndexEntry
// err is any error that the Scanner encountered while scanning.
err error
// from is the underlying scanner, scanning the `git diff-index`
// command's stdout.
from *bufio.Scanner
}
// NewDiffIndexScanner initializes a new `DiffIndexScanner` scanning at the
// given ref, "ref".
//
// If "cache" is given, the DiffIndexScanner will scan for differences between
// the given ref and the index. If "cache" is _not_ given, DiffIndexScanner will
// scan for differences between the given ref and the currently checked out
// tree.
//
// If "refresh" is given, the DiffIndexScanner will refresh the index. This is
// probably what you want in all cases except fsck, where invoking a filtering
// operation would be undesirable due to the possibility of corruption. It can
// also be disabled where another operation will have refreshed the index.
//
// If any error was encountered in starting the command or closing its `stdin`,
// that error will be returned immediately. Otherwise, a `*DiffIndexScanner`
// will be returned with a `nil` error.
func NewDiffIndexScanner(ref string, cached bool, refresh bool) (*DiffIndexScanner, error) {
scanner, err := git.DiffIndex(ref, cached, refresh)
if err != nil {
return nil, err
}
return &DiffIndexScanner{
from: scanner,
}, nil
}
// Scan advances the scan line and yields either a new value for Entry(), or an
// Err(). It returns true or false, whether or not it can continue scanning for
// more entries.
func (s *DiffIndexScanner) Scan() bool {
if !s.prepareScan() {
return false
}
s.next, s.err = s.scan(s.from.Text())
if s.err != nil {
s.err = errors.Wrap(s.err, "scan")
}
return s.err == nil
}
// Entry returns the last entry that was Scan()'d by the DiffIndexScanner.
func (s *DiffIndexScanner) Entry() *DiffIndexEntry { return s.next }
// Entry returns the last error that was encountered by the DiffIndexScanner.
func (s *DiffIndexScanner) Err() error { return s.err }
// prepareScan clears out the results from the last Scan() loop, and advances
// the internal scanner to fetch a new line of Text().
func (s *DiffIndexScanner) prepareScan() bool {
s.next, s.err = nil, nil
if !s.from.Scan() {
s.err = s.from.Err()
return false
}
return true
}
// scan parses the given line and returns a `*DiffIndexEntry` or an error,
// depending on whether or not the parse was successful.
func (s *DiffIndexScanner) scan(line string) (*DiffIndexEntry, error) {
// Format is:
// :100644 100644 c5b3d83a7542255ec7856487baa5e83d65b1624c 9e82ac1b514be060945392291b5b3108c22f6fe3 M foo.gif
// :<old mode> <new mode> <old sha1> <new sha1> <status>\t<file name>[\t<file name>]
parts := strings.Split(line, "\t")
if len(parts) < 2 {
return nil, errors.Errorf("invalid line: %s", line)
}
desc := strings.Fields(parts[0])
if len(desc) < 5 {
return nil, errors.Errorf("invalid description: %s", parts[0])
}
entry := &DiffIndexEntry{
SrcMode: strings.TrimPrefix(desc[0], ":"),
DstMode: desc[1],
SrcSha: desc[2],
DstSha: desc[3],
Status: DiffIndexStatus(rune(desc[4][0])),
SrcName: parts[1],
}
if score, err := strconv.Atoi(desc[4][1:]); err != nil {
entry.StatusScore = score
}
if len(parts) > 2 {
entry.DstName = parts[2]
}
return entry, nil
}
| github/git-lfs | lfs/diff_index_scanner.go | GO | mit | 6,132 |
<?php
declare(strict_types=1);
namespace Phan\Tests\Language\Type;
use Phan\Language\Type\ArrayShapeType;
use Phan\Tests\BaseTest;
/**
* Unit tests of ArrayShapeType
*/
final class ArrayShapeTypeTest extends BaseTest
{
private function assertUnescapedKeyEquals(string $expected, string $unescaped): void
{
$this->assertSame($expected, ArrayShapeType::unescapeKey($unescaped), "unexpected value for $unescaped");
}
public function testUnescapedKey(): void
{
$this->assertUnescapedKeyEquals("", "");
$this->assertUnescapedKeyEquals("\\", "\\\\");
$this->assertUnescapedKeyEquals("\n", "\\n");
$this->assertUnescapedKeyEquals("\n\\", "\\x0a\\\\");
$this->assertUnescapedKeyEquals("", "");
$this->assertUnescapedKeyEquals("~", "\\x7e");
$this->assertUnescapedKeyEquals("\x1c", "\\x1c");
$this->assertUnescapedKeyEquals("\n\t\r\\<", "\\n\\t\\r\\\\\x3c");
$this->assertUnescapedKeyEquals("hello world", "hello\x20world");
}
private function assertEscapedKeyEquals(string $expected, string $unescaped): void
{
$this->assertSame($expected, ArrayShapeType::escapeKey($unescaped), "unexpected escaped key");
}
public function testEscapedKey(): void
{
$this->assertEscapedKeyEquals("", "");
$this->assertEscapedKeyEquals("\\\\", "\\");
$this->assertEscapedKeyEquals("\\n\\\\", "\x0a\\");
$this->assertEscapedKeyEquals("\\x7e", "~");
$this->assertEscapedKeyEquals("\\x1c", "\x1c");
$this->assertEscapedKeyEquals("\\n\\t\\r\\\\\\x3a", "\n\t\r\\:");
}
}
| etsy/phan | tests/Phan/Language/Type/ArrayShapeTypeTest.php | PHP | mit | 1,633 |
import 'moment';
export class MomentValueConverter {
toView(date: Date, format: string) {
if (!format) format = 'LLL';
if (!date) return undefined;
return moment(date).format(format);
}
}
| Thanood/monterey | app/src/shared/converters/moment.ts | TypeScript | mit | 206 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.containerservice.models;
import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;
/** Defines values for Code. */
public final class Code extends ExpandableStringEnum<Code> {
/** Static value Running for Code. */
public static final Code RUNNING = fromString("Running");
/** Static value Stopped for Code. */
public static final Code STOPPED = fromString("Stopped");
/**
* Creates or finds a Code from its string representation.
*
* @param name a name to look for.
* @return the corresponding Code.
*/
@JsonCreator
public static Code fromString(String name) {
return fromString(name, Code.class);
}
/** @return known Code values. */
public static Collection<Code> values() {
return values(Code.class);
}
}
| Azure/azure-sdk-for-java | sdk/resourcemanagerhybrid/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/Code.java | Java | mit | 1,061 |
const dec = () => {};
class Foo {
@dec #x() {}
bar() {
([...this.#x] = this.baz);
}
}
| babel/babel | packages/babel-plugin-proposal-decorators/test/fixtures/2021-12-misc/setting-private-method-via-rest/input.js | JavaScript | mit | 98 |
#!/usr/bin/python
# -- Content-Encoding: UTF-8 --
"""
Utility methods, for compatibility between Python version
:author: Thomas Calmant
:copyright: Copyright 2017, Thomas Calmant
:license: Apache License 2.0
:version: 0.3.1
..
Copyright 2017 Thomas Calmant
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.
"""
import sys
# ------------------------------------------------------------------------------
# Module version
__version_info__ = (0, 3, 1)
__version__ = ".".join(str(x) for x in __version_info__)
# Documentation strings format
__docformat__ = "restructuredtext en"
# ------------------------------------------------------------------------------
if sys.version_info[0] < 3:
# Python 2
# pylint: disable=E1101
import types
try:
STRING_TYPES = (
types.StringType,
types.UnicodeType
)
except NameError:
# Python built without unicode support
STRING_TYPES = (types.StringType,)
NUMERIC_TYPES = (
types.IntType,
types.LongType,
types.FloatType
)
def to_bytes(string):
"""
Converts the given string into bytes
"""
# pylint: disable=E0602
if type(string) is unicode:
return str(string)
return string
def from_bytes(data):
"""
Converts the given bytes into a string
"""
if type(data) is str:
return data
return str(data)
else:
# Python 3
# pylint: disable=E1101
STRING_TYPES = (
bytes,
str
)
NUMERIC_TYPES = (
int,
float
)
def to_bytes(string):
"""
Converts the given string into bytes
"""
if type(string) is bytes:
return string
return bytes(string, "UTF-8")
def from_bytes(data):
"""
Converts the given bytes into a string
"""
if type(data) is str:
return data
return str(data, "UTF-8")
# ------------------------------------------------------------------------------
# Enumerations
try:
import enum
def is_enum(obj):
"""
Checks if an object is from an enumeration class
:param obj: Object to test
:return: True if the object is an enumeration item
"""
return isinstance(obj, enum.Enum)
except ImportError:
# Pre-Python 3.4
def is_enum(_):
"""
Before Python 3.4, enumerations didn't exist.
:param _: Object to test
:return: Always False
"""
return False
# ------------------------------------------------------------------------------
# Common
DictType = dict
ListType = list
TupleType = tuple
ITERABLE_TYPES = (
list,
set, frozenset,
tuple
)
VALUE_TYPES = (
bool,
type(None)
)
PRIMITIVE_TYPES = STRING_TYPES + NUMERIC_TYPES + VALUE_TYPES
| CloudI/CloudI | src/service_api/python/jsonrpclib/jsonrpclib/utils.py | Python | mit | 3,412 |
import * as React from "react";
import { CarbonIconProps } from "../../";
declare const FlowData20: React.ForwardRefExoticComponent<
CarbonIconProps & React.RefAttributes<SVGSVGElement>
>;
export default FlowData20;
| mcliment/DefinitelyTyped | types/carbon__icons-react/lib/flow--data/20.d.ts | TypeScript | mit | 218 |
require 'chefspec'
describe 'apt_repository::add' do
let(:chef_run) do
ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04')
.converge(described_recipe)
end
it 'adds a apt_repository with default action' do
expect(chef_run).to add_apt_repository('default_action')
expect(chef_run).to_not add_apt_repository('not_default_action')
end
it 'installs a apt_repository with an explicit action' do
expect(chef_run).to add_apt_repository('explicit_action')
end
end
| mcoolive/chefspec | examples/apt_repository/spec/add_spec.rb | Ruby | mit | 525 |