repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
mgitgrullon/Eurodental | app/models/gcolor.rb | 113 | class Gcolor < ActiveRecord::Base
# belongs_to :store
has_many :stores
validates :name, presence: true
end
| mit |
kbolduc/cloud_tempfile | lib/cloud_tempfile/railtie.rb | 194 | # cloud_tempfile/railtie.rb
#
# Author:: Kevin Bolduc
# Date:: 14-02-24
# Time:: 3:23 PM
class Rails::Railtie::Configuration
def cloud_tempfile
CloudTempfile.config
end
end | mit |
Chunxiaojiu/-unity- | wuziqi/Assets/Script/Cross.cs | 330 | using UnityEngine;
using UnityEngine.UI;
// 每个交叉点逻辑
public class Cross : MonoBehaviour {
// 位置
public int GridX;
public int GridY;
public MainLoop mainLoop;
void Start () {
GetComponent<Button>().onClick.AddListener( ( )=>{
mainLoop.OnClick(this);
});
}
}
| mit |
lengrensheng/gallery-react | src/main/TimePickerLoading.js | 2675 | /**
* Created by on 2016/5/23.
*/
import React,{Component} from 'react';
import {
TimePickerAndroid,
StyleSheet,
Text,
View,
TouchableOpacity
}from 'react-native';
function _formatTime(hour, minute){
return hour + ":" + (minute < 10 ? '0' + minute : minute);
};
var TimePickerAndroidExample = React.createClass({
getInitialState(){
return {
isoFormatText: 'pick a time (24-hour format)',
presetHour: 4,
presetMinute: 4,
presetText: 'pick a time, default:4:04AM',
simpleText: 'pick a time',
}
},
async showPicker(stateKey, option){
try {
const {action,minute,hour} = await TimePickerAndroid.open(option);
var newState = {};
if (action === TimePickerAndroid.timeSetAction) {
newState[stateKey + 'Text'] = _formatTime(hour, minute);
newState[stateKey + 'Hour'] = hour;
newState[stateKey + 'Minute'] = minute;
} else if (action === TimePickerAndroid.dismissedAction) {
newState[stateKey + 'Text'] = 'dismissed';
}
this.setState(newState);
} catch ({code, message}){
console.warn(`Error in example '${stateKey}':`, message);
}
},
render(){
return (
<View>
<TouchableOpacity
onPress={this.showPicker.bind(this,'simple')}>
<Text style={styles.text}>{this.state.simpleText}</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={this.showPicker.bind(this,'preset',{
hour:this.state.presetHour,
minute:this.state.presetMinute
})}>
<Text style={styles.text}>{this.state.presetText}</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={this.showPicker.bind(this,'isoFormat',{
hour:this.state.isoFormatHour,
minute:this.state.isoFormatMinute,
is24Hour:false,
})}>
<Text style={styles.text}>{this.state.isoFormatText}</Text>
</TouchableOpacity>
</View>
);
}
});
export default class TimePickerLoading extends Component {
render() {
return (
<TimePickerAndroidExample/>
);
}
};
var styles = StyleSheet.create({
text: {
color: 'black',
margin: 20
},
});
| mit |
jiiis/ptn | plugins/indikator/backend/lang/es/lang.php | 7419 | <?php
return [
'plugin' => [
'name' => 'Backend Plus',
'description' => 'Nuevas características y widgets para el Backend.',
'author' => 'Gergő Szabó'
],
'settings' => [
'tab_display' => 'Monitor',
'avatar_label' => 'Imagen de perfil redondeado en lugar de un solo cubo',
'avatar_comment' => 'La avataro modifas nur en supera menuo.',
'topmenu_label' => 'Ocultar la etiqueta en el menú superior',
'topmenu_comment' => 'Funciona con todo el estilo de menú.',
'sidebar_desc_label' => 'Ocultar la descripción del menú en la barra lateral',
'sidebar_desc_comment' => 'Ocultar la descripción de los menús en la barra lateral.',
'sidebar_search_label' => 'Ocultar el campo de búsqueda en la barra lateral',
'sidebar_search_comment' => 'Ocultar la descripción de los menús en la barra lateral.',
'themes_label' => 'Esconder el "Buscar nuevos temas" enlace',
'themes_comment' => 'Está en la página del tema Front-end.',
'tab_behavior' => 'Comportamiento',
'search_label' => 'Hacer "focus" en el campo de búsqueda automáticamente',
'search_comment' => 'En primer lugar en las listas, en segundo lugar, en la barra lateral.',
'context_menu_label' => 'Habilitar el menú contextual',
'context_menu_comment' => 'Haga clic con el botón derecho del ratón para mostrar el menú.',
'clearbutton_label' => 'Agregar el botón de limpieza de campos de entrada (beta)',
'clearbutton_comment' => 'Funciona únicamente por los campos de texto simples.',
'keyboard_label' => 'Mostrar el teclado virtual para introducir datos (beta)',
'keyboard_comment' => 'Sólo funciona con campos de texto simples.',
'enabled_gzip_label' => 'Habilitar la compresión gzip',
'enabled_gzip_comment' => 'Funciona en la herramienta de frontend y backend.'
],
'trash' => [
'title' => 'Trash items',
'description' => 'Delete the unused files and folders.',
'permission' => 'Manage the trash items',
'type' => 'Type',
'path' => 'Path',
'size' => 'Size',
'file' => 'File',
'folder' => 'Folder',
'database' => 'Database',
'items' => 'Item|Items',
'hint' => 'After that you updated the OctoberCMS core, you click on the Search button again. If you want to delete the cache of your webpage, you need to add the "Backend - Cache" widget to the Dashboard. Please <b>rate this plugin</b> if it helped your work:',
'search' => 'Search',
'success' => 'The scan was successfully completed.',
'no_items' => 'Congratulations, no unused files on the website!',
'remove_all' => 'Delete all',
'delete' => 'Do you want to delete this items?',
'remove' => 'Successfully removed those items.'
],
'widgets' => [
'system' => [
'title' => 'Backend - Estado del Sistema Plus',
'label' => 'Estado del Sistema Plus',
'webpage' => 'Página Web',
'updates' => 'Actualizaciones',
'plugins' => 'Plugins',
'themes' => 'Temas'
],
'version' => [
'title' => 'Backend - Versiones',
'label' => 'Versiones',
'cms' => 'CMS',
'php' => 'PHP',
'gd' => 'GD'
],
'logs' => [
'title' => 'Backend - Logs',
'label' => 'Logs',
'access' => 'Accesos',
'event' => 'Evento',
'request' => 'Petición (Request)',
'total' => 'Total'
],
'admins' => [
'title' => 'Backend - Administradores',
'label' => 'Administradores',
'users' => 'Usuarios',
'groups' => 'Grupos',
'login' => 'Último acceso'
],
'logins' => [
'title' => 'Backend - Últimos accesos',
'label' => 'Últimos accesos'
],
'server' => [
'title' => 'Backend - Información del Servidor',
'label' => 'Información del Servidor',
'host' => 'Host',
'ip' => 'Dirección IP',
'os' => 'Sistema Operativo'
],
'php' => [
'title' => 'Backend - Configuración PHP',
'label' => 'Configuración PHP',
'upload_limit' => 'Upload límite',
'memory_limit' => 'Memoria límite',
'timezone' => 'Zona Horaria'
],
'rss' => [
'title' => 'Backend - Visor RSS',
'label' => 'Visor RSS',
'error' => 'La dirección URL es incorrecta o',
'refresh' => 'Actualizar página'
],
'images' => [
'title' => 'Backend - Imágenes aleatorias',
'label' => 'Imágenes aleatorias',
'error' => 'El campo solo puede contener números.',
'simple' => 'Simple',
'slideshow' => 'Slideshow'
],
'cache' => [
'title' => 'Backend - Cache',
'label' => 'Cache',
'clear' => 'Limpiar cache'
]
],
'properties' => [
'webpage' => 'Mostrar página web',
'updates' => 'Mostrar actualizaciones',
'plugins' => 'Mostrar plugins',
'themes' => 'Mostrar temas',
'cms' => 'Mostrar versión CMS',
'php' => 'Mostrar versión PHP',
'gd' => 'Mostrar versión GD',
'access' => 'Mostrar accesos',
'event' => 'Mostrar evento',
'request' => 'Mostrar petición (request)',
'total' => 'Mostrar total',
'users' => 'Mostrar usuarios',
'groups' => 'Mostrar grupos',
'login' => 'Mostrar últimos acceso',
'logins' => 'Mostrar el número de accesos',
'url' => 'Mostrar dirección URL',
'ip' => 'Mostrar dirección IP',
'os' => 'Mostrar Sistema Operativo',
'upload_limit' => 'Mostrar upload límite',
'memory_limit' => 'Mostrar memoria límite',
'timezone' => 'Mostrar zona horaria',
'rss_title' => 'RSS url',
'rss_url' => 'http://feeds.bbci.co.uk/news/rss.xml',
'news' => 'Número de noticias',
'date' => 'Mostrar fecha',
'description' => 'Mostrar descripción',
'category' => 'Categoría',
'type' => 'Tipo',
'number' => 'Imágenes en slideshow',
'width' => 'Ancho (en pixel)',
'height' => 'Altura (en pixel)',
'text' => 'Texto'
],
'category' => [
'all' => 'Todo',
'abstract' => 'Abstracto',
'animals' => 'Animales',
'business' => 'Negocios',
'cats' => 'Gatos',
'city' => 'Ciudad',
'food' => 'Comida',
'nightlife' => 'Vida nocturna',
'fashion' => 'Moda',
'people' => 'Gente',
'nature' => 'Naturaleza',
'sports' => 'Deportes',
'technics' => 'Técnicos',
'transport' => 'Transporte'
],
'component' => [
'image' => [
'name' => 'Lorem ipsum image',
'description' => ''
],
'text' => [
'name' => 'Lorem ipsum text',
'description' => '',
'length' => 'Longitud',
'bit' => 'un poco',
'some' => 'algo',
'lots' => 'mucho'
]
]
];
| mit |
hyperandroid/Automata | lib/Transition.js | 692 | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A Transition is a link between two states.
* It fires whenever an state has an exit transition identified by `event`.
*/
class Transition {
constructor(from, to, event) {
this.event_ = event;
this.from_ = from;
this.to_ = to;
}
setup() {
this.from_.addExitTransition(this);
this.to_.addEnterTransition(this);
return this;
}
get from() {
return this.from_;
}
get to() {
return this.to_;
}
get event() {
return this.event_;
}
}
exports.default = Transition;
//# sourceMappingURL=Transition.js.map | mit |
pienkowskip/cryptobroker | lib/cryptobroker/indicator/histogram_based_filtered.rb | 1254 | require_relative 'histogram_based'
module Cryptobroker::Indicator
module HistogramBasedFiltered
include HistogramBased
DEFAULT_FILTER_LENGTH = 1
def initialize(conf = {filter_length: DEFAULT_FILTER_LENGTH})
super conf
@filter_len = conf.fetch :filter_length, DEFAULT_FILTER_LENGTH
end
def name
"filtered(#{@filter_len}) " + super
end
def reset
super
@awaiting_signal = nil
end
protected
def update_startup(startup)
super startup.nil? ? nil : startup + @filter_len
end
def signal_with_filter(type, _, i)
if @awaiting_signal.nil?
@awaiting_signal = [type, i]
else
@awaiting_signal = nil if @awaiting_signal[0] != type
end
end
alias_method :signal_without_filter, :signal
alias_method :signal, :signal_with_filter
def finish(&block)
unless @awaiting_signal.nil?
type, i = @awaiting_signal
if i + @filter_len <= @finished
@awaiting_signal = nil
i = @finished - @buffer_at
raise IndexError, 'buffer is out of operation range' if i < 0
signal_without_filter type, @bars_buffer[i], @finished, &block
end
end
super()
end
end
end | mit |
conwqi1/more-rubyExcersise | 11_dictionary/dictionary.rb | 679 | class Dictionary
def entries
#@entries=Hash.new(" ")
@entries ||= {}
end
def keywords
@entries.keys.sort
end
def include? (word)
entries.keys.include? word
end
def add (keywords, value=nil)
entries[keywords]=value
end
def find (input)
arr={}
entries.each do |key,value|
arr[key]=value if key.include?input
end
arr
end
def printable
entries.map do |key|
%Q{[#{key.first}] "#{key.last}"}
end.sort.join("\n")
end
end
@dictionary=Dictionary.new
@dictionary.add("jack","rich")
puts @dictionary.entries
puts @dictionary.keywords
puts @dictionary.include?("jack")
puts @dictionary.include?("pack")
puts @dictionary.printable
| mit |
131/yks | 3rd/shop/subs/Admin/Meta/list.php | 397 | <?php
if($action == "meta_product_trash") try {
$meta_product_id = $_POST['meta_product_id'];
$meta_product = $meta_products_list[$meta_product_id];
if(!$meta_product)
throw rbx::error("Vous n'avez pas le droit de détruire ce meta produit");
$res = $meta_product->sql_delete();
if(!$res)
throw rbx::error("Impossible de détruire ce meta produit");
}catch(rbx $e) {} | mit |
TedPowers/happy | application/config/routes.php | 2059 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| http://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There are three reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router which controller/method to use if those
| provided in the URL cannot be matched to a valid route.
|
| $route['translate_uri_dashes'] = FALSE;
|
| This is not exactly a route, but allows you to automatically route
| controller and method names that contain dashes. '-' isn't a valid
| class or method name character, so it requires translation.
| When you set this option to TRUE, it will replace ALL dashes in the
| controller and method URI segments.
|
| Examples: my-controller/index -> my_controller/index
| my-controller/my-method -> my_controller/my_method
*/
$route['contact'] = 'venues/contact';
$route['nearby/(:any)'] = 'venues/nearby/$1';
$route['(:any)/(:any)'] = 'venues/view/$1/$2';
$route['venues'] = 'venues';
$route['default_controller'] = 'venues';
| mit |
jtstriker3/Joe.Business | Report/IChartPoint.cs | 226 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Joe.Business.Report
{
public interface IChartPoint : IPoint
{
Object Series { get; set; }
}
}
| mit |
d3QUone/build_django_templates | config.py | 1462 | #
# Vladimir Kasatkin. April, 2015
#
# --- EXAMPLE ---
#
# Run the 'build.py' script after doing "python manage.py collectstatic"
#
# all folders must bu pointed form this config-file, e.g:
#
# - base_folder/
# |---config.py
# |---dev_templates/
# |---templates/
# Django's standart folder-style
SOURCE_DIRS = [
"example/core/templates/core/",
"example/user_profile/templates/user_profile/"
]
# results will be saved here
# !!! this folder must exist !!!
TARGET_DIR = "example/templates/"
# all files that have [[[ "file_name.html" ]]] - include tag OR must be in target dir
TARGET_FILES = [
"base.html",
"core__index.html",
"core__question_page.html",
"user_profile__base.html"
]
"""
Output in this example:
$ python build.py
Found "navbar.html"
Found "navbar.html"
File "example/templates/base.html" complete with 2 insertions
--------------------------------------------------------------------------------
File "example/templates/core__index.html" complete with 0 insertions
--------------------------------------------------------------------------------
File "example/templates/core__question_page.html" complete with 0 insertions
--------------------------------------------------------------------------------
Found "user_profile login.html"
Found "login form validation.js"
File "example/templates/user_profile__base.html" complete with 2 insertions
--------------------------------------------------------------------------------
"""
| mit |
j4y/landslider | lib/landslider/entities/ws_address.rb | 267 |
class Landslider
class WsAddress < WsEntity
# @return [Integer]
attr_reader :address_id
# @return [String]
attr_reader :address1, :address2, :address3, :address_node, :city
# @return [String]
attr_reader :country, :state, :zip_postal
end
end | mit |
scottmcnab/cordova-cookie-master | www/cookieMaster.js | 1095 | var cookieMaster = {
getCookieValue: function(url, cookieName, successCallback, errorCallback) {
cordova.exec(successCallback,
errorCallback,
'CookieMaster', 'getCookieValue',
[url, cookieName]
);
},
setCookieValue: function (url, cookieName, cookieValue, successCallback, errorCallback) {
cordova.exec(successCallback,
errorCallback,
'CookieMaster', 'setCookieValue',
[url, cookieName, cookieValue]
);
},
setCookieOption: function(option, successCallback, errorCallback) {
//ios
cordova.exec(successCallback,
errorCallback,
'CookieMaster', 'setCookieOption',
[option]
);
},
clear: function(successCallback, errorCallback) {
cordova.exec(successCallback,
errorCallback,
'CookieMaster', 'clearCookies',
[]
);
}
};
module.exports = cookieMaster;
| mit |
Mange/roadie | lib/roadie/provider_list.rb | 2760 | # frozen_string_literal: true
require "forwardable"
module Roadie
# An asset provider that just composes a list of other asset providers.
#
# Give it a list of providers and they will all be tried in order.
#
# {ProviderList} behaves like an Array, *and* an asset provider, and can be coerced into an array.
class ProviderList
extend Forwardable
include Enumerable
# Wrap a single provider, or a list of providers into a {ProviderList}.
#
# @overload wrap(provider_list)
# @param [ProviderList] provider_list An actual instance of {ProviderList}.
# @return The passed in provider_list
#
# @overload wrap(provider)
# @param [asset provider] provider
# @return a new {ProviderList} with just the passed provider in it
#
# @overload wrap(provider1, provider2, ...)
# @return a new {ProviderList} with all the passed providers in it.
def self.wrap(*providers)
if providers.size == 1 && providers.first.instance_of?(self)
providers.first
else
new(providers.flatten)
end
end
# Returns a new empty list.
def self.empty
new([])
end
def initialize(providers)
@providers = providers
end
# @return [Stylesheet, nil]
def find_stylesheet(name)
@providers.each do |provider|
css = provider.find_stylesheet(name)
return css if css
end
nil
end
# Tries to find the given stylesheet and raises an {ProvidersFailed} error
# if no provider could find the asset.
#
# @return [Stylesheet]
def find_stylesheet!(name)
errors = []
@providers.each do |provider|
return provider.find_stylesheet!(name)
rescue CssNotFound => error
errors << error
end
raise ProvidersFailed.new(
css_name: name, providers: self, errors: errors
)
end
def to_s
list = @providers.map { |provider|
# Indent every line one level
provider.to_s.split("\n").join("\n\t")
}
"ProviderList: [\n\t#{list.join(",\n\t")}\n]\n"
end
# ProviderList can be coerced to an array. This makes Array#flatten work
# with it, among other things.
def to_ary
to_a
end
# @!method each
# @see Array#each
# @!method size
# @see Array#size
# @!method empty?
# @see Array#empty?
# @!method push
# @see Array#push
# @!method <<
# @see Array#<<
# @!method pop
# @see Array#pop
# @!method unshift
# @see Array#unshift
# @!method shift
# @see Array#shift
# @!method last
# @see Array#last
def_delegators :@providers, :each, :size, :empty?, :push, :<<, :pop, :unshift, :shift, :last
end
end
| mit |
rao1219/Vedio | node_modules/sequelize-fixtures/tests/models/Foo.js | 223 | module.exports = function (sequelize, DataTypes) {
return sequelize.define("foo", {
propA: {type: DataTypes.STRING},
propB: {type: DataTypes.INTEGER},
status: {type: DataTypes.BOOLEAN}
});
}; | mit |
shivan1b/codes | karum/stackLL.cpp | 1490 | #include<iostream>
#include<cstdlib>
using namespace std;
class Node{
public:
int data;
Node *next;
Node(){}
Node(int d){
data=d;
next=NULL;
}
Node *push(Node *head, int data){
Node *np=new Node(data);
Node *t=head;
cout<<"Pushing "<<np->data<<"...\n";
if(head==NULL)
return np;
while(t->next!=NULL)
t=t->next;
t->next=np;
return head;
}
Node *pop(Node *head){
Node *t=head;
Node *p;
if(head==NULL){
cout<<"Nothing to pop. Stack empty.\n";
return NULL;
}
if(head->next==NULL){
cout<<"Popping "<<head->data<<"...\n";
free(head);
return NULL;
}
while(t->next!=NULL){
p=t;
t=t->next;
}
p->next=NULL;
cout<<"Popping "<<t->data<<"...\n";
free(t);
return head;
}
void displayStack(Node *head){
if(head==NULL)
cout<<"Nothing to display. Stack empty.\n";
else{
cout<<"\nThe list is as follows:\n";
while(head!=NULL){
cout<<head->data<<"\n";
head=head->next;
}
}
}
};
int main()
{
int d,e;
Node *head=NULL;
Node np;
while(1){
cout<<"Press 1/2/3 to push pop or display the elements of stack. Press anything else to exit.\n";
cin>>e;
switch(e){
case 1:
cout<<"Enter the data you want to push: ";
cin>>d;
head=np.push(head,d);
break;
case 2:
head=np.pop(head);
break;
case 3:
np.displayStack(head);
break;
default:
goto stack;
}
}
stack:
return 0;
}
| mit |
danigb/sample-player | test/support/audio.js | 724 | /* globals AudioContext */
require('web-audio-test-api')
module.exports = function Audio (keys) {
var ac = new AudioContext()
var names = !keys ? [] : keys.split ? keys.split(' ') : keys || []
var buffers = {}
names.forEach(function (key, i) {
buffers[key] = ac.createBuffer(2, i, 44100)
})
function output () {
return ac.toJSON().inputs[0]
}
function played (i) {
if (arguments.length > 0) return played()[i]
return output().inputs.map(function (input) {
var amp = input
var source = amp.inputs[0]
var buffer = source.buffer
var bufferName = names[buffer.length]
return { amp, source, buffer, bufferName }
})
}
return { ac, buffers, output, played }
}
| mit |
adzhazhev/Airline-System | Airline-System/AirlineSystem.Web.Tests/Controllers/HomeControllerTest.cs | 1401 | namespace AirlineSystem.Web.Tests.Controllers
{
using System.Web.Mvc;
using AirlineSystem.Data;
using AirlineSystem.Web.Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class HomeControllerTest
{
public HomeControllerTest(IAirlineSystemData data)
{
}
private IAirlineSystemData Data { get; set; }
[TestMethod]
public void Index()
{
// Arrange
HomeController controller = new HomeController(this.Data);
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
[TestMethod]
public void About()
{
// Arrange
HomeController controller = new HomeController(this.Data);
// Act
ViewResult result = controller.OurMission() as ViewResult;
// Assert
Assert.AreEqual("Your application description page.", result.ViewBag.Message);
}
[TestMethod]
public void Contact()
{
// Arrange
HomeController controller = new HomeController(this.Data);
// Act
ViewResult result = controller.Contact() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
}
} | mit |
MiteshSharma/ContentApi | app/webhook/WebhookEventHandler.java | 2336 | package webhook;
import akka.actor.ActorRef;
import akka.pattern.Patterns;
import com.google.inject.Inject;
import dispatcher.IEventDispatcher;
import dispatcher.IEventHandler;
import event_handler.EventName;
import play.Play;
import play.libs.ws.WSResponse;
import pojo.WebhookObject;
import scala.compat.java8.FutureConverters;
import services.IWebhookService;
import javax.inject.Named;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
/**
* Created by mitesh on 22/01/17.
*/
public class WebhookEventHandler implements IEventHandler {
@Inject
@Named("webhook-handler-actor")
ActorRef webhookEventHandlerActor;
@Inject
IWebhookService webhookService;
private static final long TIMEOUT_IN_MILLIS = 120;
public WebhookEventHandler() {
this.webhookService = Play.application().injector().instanceOf(IWebhookService.class);
}
@Override
public void handle(EventName eventName, Map<String, String> params) {
String projectId = params.get("projectId");
if (projectId != null) {
List<WebhookObject> webhookObjects = this.webhookService.getAll(projectId);
for (WebhookObject webhookObject : webhookObjects) {
if (webhookObject.getEventName() == eventName) {
// Fire event and wait for response in sync
if (webhookObject.getIsSync()) {
CompletableFuture<WSResponse> futureResponse = FutureConverters.toJava(Patterns.ask(webhookEventHandlerActor, webhookObject, TIMEOUT_IN_MILLIS))
.toCompletableFuture()
.thenApply(wsResponse -> (WSResponse) wsResponse);
try {
futureResponse.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
webhookEventHandlerActor.tell(webhookObject, ActorRef.noSender());
}
}
}
}
}
}
| mit |
vaj25/SICBAF | application/controllers/Bodega/Solicitud_control.php | 28545 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Solicitud_control extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'paginacion'));
$this->load->library(array('table', 'notificacion'));
$this->load->model(array('Bodega/Solicitud_Model','Bodega/Detalle_solicitud_producto_model', 'Bodega/Fuentefondos_model'));
}
public function index(){
if($this->session->userdata('logged_in')){
$data['title'] = "Control Solicitudes";
$data['js'] = "assets/js/validate/solc.js";
$pri=$this->Solicitud_Model->obtenerId();
$USER = $this->session->userdata('logged_in');
$id_seccion=$USER['id_seccion'];
$sec=$this->Solicitud_Model->obtenerSeccion($id_seccion);
//$data['js'] = "assets/js/validate/factura.js";
date_default_timezone_set('America/El_Salvador');
$anyo=20;
$fecha_actual=date($anyo."y-m-d");
$msg = array('alert' => $this->uri->segment(4),'fecha'=>$fecha_actual,'id'=>$pri,'controller'=>'solicitud',
'seccion'=>$sec);
$data['body'] = $this->load->view('mensajes', $msg, TRUE) . $this->load->view('Bodega/solicitud_control_view',$msg,TRUE) .
"<br><div class='content_table '>" .
"<div class='limit-content-title'><span class='icono icon-table icon-title'> Control de Solicitudes</span></div>".
"<div class='limit-content'>" . $this->mostrarTabla() . "</div></div>";
$data['menu'] = $this->menu_dinamico->menus($this->session->userdata('logged_in'),$this->uri->segment(1));
$this->load->view('base', $data);
} else {
redirect('login/index/error_no_autenticado?md='.$this->User_model->obtenerModulo('Bodega/Solicitud_control'));
}
}
public function mostrarTabla() {
$USER = $this->session->userdata('logged_in');
if($USER){
/*
* Configuracion de la tabla
*/
$seccion;
$template = array(
'table_open' => '<table class="table table-striped table-bordered">'
);
$this->table->set_template($template);
$this->table->set_heading('Id', 'Número', 'Sección', 'Fuente Fondo', 'Fecha', 'Comentario','Estado','Acciones');
$nivel = array();
if ($USER['rol'] == 'DIRECTOR ADMINISTRATIVO') {
$nivel[] = 2;
$nivel[] = 3;
$nivel[] = 4;
$nivel[] = 9;
$seccion = 0;
} elseif ($USER['rol'] == 'JEFE UNIDAD' || $USER['rol'] == 'JEFE BODEGA' || $USER['rol'] == 'COLABORADOR BODEGA' || $USER['rol'] == 'JEFE COMPRAS' || $USER['rol'] == 'COLABORADOR COMPRAS'
|| $USER['rol'] == 'JEFE AF' || $USER['rol'] == 'COLABORADOR AF' || $USER['rol'] == 'JEFE UACI' || $USER['rol'] == 'COLABORADOR UACI' || $USER['rol'] == 'REPORTES SICBAF') {
$nivel[] = 1;
$nivel[] = 2;
$nivel[] = 3;
$nivel[] = 4;
$nivel[] = 9;
$seccion = $USER['id_seccion'];
} elseif ($USER['rol'] == 'ADMINISTRADOR SICBAF') {
$nivel[] = 0;
$nivel[] = 1;
$nivel[] = 2;
$nivel[] = 3;
$nivel[] = 4;
$nivel[] = 9;
$seccion = 108;
$this->table->set_heading('Id', 'Número', 'Sección', 'Fuente Fondo', 'Fecha', 'Comentario', 'Estado', 'Nivel','Acciones');
}
$num = '10';
$pagination = '';
$registros;
if ($this->input->is_ajax_request()) {
if (!($this->input->post('busca') == "")) {
$registros = $this->Solicitud_Model->buscarSolicitudes($this->input->post('busca'));
} else {
$registros = $this->Solicitud_Model->obtenerSolicitudesEstadoLimit($nivel, $seccion, $num, $this->uri->segment(4));
$pagination = paginacion('index.php/Bodega/Solicitud_control/index/', $this->Solicitud_Model->totalSolicitudes($USER['id_seccion'])->total,
$num, '4');
}
} else {
$registros = $this->Solicitud_Model->obtenerSolicitudesEstadoLimit($nivel, $seccion, $num, $this->uri->segment(4));
$pagination = paginacion('index.php/Bodega/Solicitud_control/index/', $this->Solicitud_Model->totalSolicitudes($USER['id_seccion'])->total,
$num, '4');
}
/*
* llena la tabla con los datos consultados
*/
if (!($registros == FALSE)) {
foreach($registros as $sol) {
$id_rol = $USER['rol'];
$comentario='';
if ($USER['rol'] == 'JEFE UNIDAD' || $USER['rol'] == 'JEFE BODEGA' || $USER['rol'] == 'COLABORADOR BODEGA' || $USER['rol'] == 'JEFE COMPRAS' || $USER['rol'] == 'COLABORADOR COMPRAS' ||
$USER['rol'] == 'JEFE AF'|| $USER['rol'] == 'COLABORADOR AF' || $USER['rol'] == 'JEFE UACI' || $USER['rol'] == 'COLABORADOR UACI' || $USER['rol'] == 'REPORTES SICBAF') {
$comentario=$sol->comentario_jefe;
}elseif ($USER['rol'] == 'DIRECTOR ADMINISTRATIVO') {
$comentario=$sol->comentario_admin;
}
$seccion = $this->Solicitud_Model->obtenerSeccion($sol->id_seccion);
$fuente = $this->Fuentefondos_model->obtenerFuente($sol->id_fuentes);
if ($USER['rol'] == 'ADMINISTRADOR SICBAF') {
if ($sol->nivel_solicitud == 0 || $sol->nivel_solicitud == 3 || $sol->nivel_solicitud == 4 || $sol->nivel_solicitud == 9){
$onClick = "llenarFormulario('solicitud', ['id', 'fecha_solicitud', 'id_seccion', 'numero_solicitud', 'nivel'],
[$sol->id_solicitud, '$sol->fecha_solicitud', '$seccion', '$sol->numero_solicitud',
'$sol->nivel_solicitud'],false,false,false,'comentario_solicitud','$sol->comentario_jefe')";
$botones='<a class="action icono icon-detalle" href="'.base_url('index.php/Bodega/Detalle_Solicitud_Control/index/'.$sol->id_solicitud.'/').'" data-toggle="tooltip" title="Detalle"></a>';
//$eliminar='<a class="icono icon-denegar"></a>';
$actualizar = '';
$aprobar = '';
$denegar = '';
$estado = $sol->estado_solicitud;
$this->table->add_row($sol->id_solicitud, $sol->numero_solicitud, $seccion, $fuente, $sol->fecha_solicitud, $comentario,
$estado,$sol->nivel_solicitud, $botones.$aprobar.$denegar.$actualizar);
} else {
$onClick = "llenarFormulario('solicitud', ['id', 'fecha_solicitud', 'id_seccion', 'numero_solicitud', 'nivel'],
[$sol->id_solicitud, '$sol->fecha_solicitud', '$seccion', '$sol->numero_solicitud',
'$sol->nivel_solicitud'],false,false,false,'comentario_solicitud','$sol->comentario_jefe')";
$botones='<a class="action icono icon-detalle" href="'.base_url('index.php/Bodega/Detalle_Solicitud_Control/index/'.$sol->id_solicitud.'/').'" data-toggle="tooltip" title="Detalle"></a>';
//$eliminar='<a class="icono icon-eliminar" uri='.base_url('index.php/Bodega/solicitud/EliminarDato/'.$sol->id_solicitud).'></a>';
$actualizar = '<a class="action icono icon-actualizar" data-toggle="tooltip" title="Editar" onClick="'.$onClick.'"></a>';
$aprobar = '<a class="action icono icon-liquidar" data-toggle="tooltip" title="Aprobar" href="'.base_url('index.php/Bodega/Solicitud_control/Aprobar/'.$sol->id_solicitud.'/').'"></a>';
$denegar = '<a class="action icono icon-cross" data-toggle="tooltip" title="Denegar" href="'.base_url('index.php/Bodega/Solicitud_control/Denegar/'.$sol->id_solicitud.'/').'"></a>';
$estado = $sol->estado_solicitud;
$this->table->add_row($sol->id_solicitud, $sol->numero_solicitud, $seccion, $fuente, $sol->fecha_solicitud, $comentario
,$estado,$sol->nivel_solicitud, $botones.$aprobar.$denegar.$actualizar);
}
}
if ($USER['rol'] == 'JEFE UNIDAD' || $USER['rol'] == 'JEFE BODEGA' || $USER['rol'] == 'JEFE COMPRAS' || $USER['rol'] == 'JEFE AF' || $USER['rol'] == 'JEFE UACI' || $USER['rol'] == 'REPORTES SICBAF'){
if ($sol->nivel_solicitud == 1){
$onClick = "llenarFormulario('solicitud', ['id', 'fecha_solicitud', 'id_seccion', 'numero_solicitud', 'nivel'],
[$sol->id_solicitud, '$sol->fecha_solicitud', '$seccion', '$sol->numero_solicitud',
'$sol->nivel_solicitud'],false,false,false,'comentario_solicitud','$sol->comentario_jefe')";
$botones='<a class="action icono icon-detalle" href="'.base_url('index.php/Bodega/Detalle_Solicitud_Control/index/'.$sol->id_solicitud.'/'.$id_rol.'/').'" data-toggle="tooltip" title="Detalle"></a>';
//$eliminar='<a class="icono icon-eliminar" uri='.base_url('index.php/Bodega/solicitud/EliminarDato/'.$sol->id_solicitud).'></a>';
$actualizar = '<a class="action icono icon-actualizar" data-toggle="tooltip" title="Editar" onClick="'.$onClick.'"></a>';
$aprobar = '<a class="action icono icon-liquidar" data-toggle="tooltip" title="Aprobar" href="'.base_url('index.php/Bodega/Solicitud_control/Aprobar/'.$sol->id_solicitud.'/').'"></a>';
$denegar = '<a class="action icono icon-cross" data-toggle="tooltip" title="Denegar" href="'.base_url('index.php/Bodega/Solicitud_control/Denegar/'.$sol->id_solicitud.'/').'"></a>';
$estado = 'POR APROBAR';
$this->table->add_row($sol->id_solicitud, $sol->numero_solicitud, $seccion, $fuente, $sol->fecha_solicitud, $comentario,
$estado,$botones.$aprobar.$denegar.$actualizar);
} elseif ($sol->nivel_solicitud == 2){
$onClick = "llenarFormulario('solicitud', ['id', 'fecha_solicitud', 'id_seccion', 'numero_solicitud', 'nivel'],
[$sol->id_solicitud, '$sol->fecha_solicitud', '$seccion', '$sol->numero_solicitud', '$sol->nivel_solicitud'],false,false,false,'comentario_solicitud','$sol->comentario_jefe')";
$botones='<a class="action icono icon-detalle" href="'.base_url('index.php/Bodega/Detalle_Solicitud_Control/index/'.$sol->id_solicitud.'/'.$id_rol.'/').'" data-toggle="tooltip" title="Detalle"></a>';
//$eliminar='<a class="icono icon-denegar"></a>';
$actualizar = '<a class="action icono icon-actualizar" data-toggle="tooltip" title="Editar" onClick="'.$onClick.'"></a>';
$aprobar = '';
$denegar = '<a class="action icono icon-cross" data-toggle="tooltip" title="Denegar" href="'.base_url('index.php/Bodega/Solicitud_control/Denegar/'.$sol->id_solicitud.'/').'"></a>';
$estado = 'APROBADA';
$this->table->add_row($sol->id_solicitud, $sol->numero_solicitud, $seccion, $fuente, $sol->fecha_solicitud, $comentario,
$estado,$botones.$aprobar.$denegar.$actualizar);
} elseif ($sol->nivel_solicitud == 3 || $sol->nivel_solicitud == 4){
$onClick = "llenarFormulario('solicitud', ['id', 'fecha_solicitud', 'id_seccion', 'numero_solicitud', 'comentario_solicitud', 'nivel'],
[$sol->id_solicitud, '$sol->fecha_solicitud', '$seccion', '$sol->numero_solicitud', '$comentario', '$sol->nivel_solicitud'])";
$botones='<a class="action icono icon-detalle" href="'.base_url('index.php/Bodega/Detalle_Solicitud_Control/index/'.$sol->id_solicitud.'/'.$id_rol.'/').'" data-toggle="tooltip" title="Detalle"></a>';
//$eliminar='<a class="icono icon-denegar"></a>';
$actualizar = '';
$aprobar = '';
$denegar = '';
$estado = 'APROBADA';
$this->table->add_row($sol->id_solicitud, $sol->numero_solicitud, $seccion, $fuente, $sol->fecha_solicitud, $comentario,
$estado,$botones.$aprobar.$denegar.$actualizar);
} elseif ($sol->nivel_solicitud == 9) {
if ($sol->nivel_anterior == 1){
$estado = $sol->estado_solicitud;
}
if ($sol->nivel_anterior == 2){
$estado = 'APROBADA';
}
$onClick = "llenarFormulario('solicitud', ['id', 'fecha_solicitud', 'id_seccion', 'numero_solicitud', 'comentario_solicitud', 'nivel'],
[$sol->id_solicitud, '$sol->fecha_solicitud', '$seccion', '$sol->numero_solicitud', '$sol->comentario', '$sol->nivel_solicitud'])";
$botones='<a class="action icono icon-detalle" href="'.base_url('index.php/Bodega/Detalle_Solicitud_Control/index/'.$sol->id_solicitud.'/'.$id_rol.'/').'" data-toggle="tooltip" title="Detalle"></a>';
//$eliminar='<a class="icono icon-denegar"></a>';
$actualizar = '';
$aprobar = '';
$denegar = '';
$this->table->add_row($sol->id_solicitud, $sol->numero_solicitud, $seccion, $fuente, $sol->fecha_solicitud, $comentario,
$estado,$botones.$aprobar.$denegar.$actualizar);
}
}
//control de permisos de colaboradores
if ($USER['rol'] == 'COLABORADOR BODEGA' || $USER['rol'] == 'COLABORADOR COMPRAS' || $USER['rol'] == 'COLABORADOR AF' || $USER['rol'] == 'COLABORADOR UACI'){
if ($sol->nivel_solicitud == 1){
$onClick = "llenarFormulario('solicitud', ['id', 'fecha_solicitud', 'id_seccion', 'numero_solicitud', 'nivel'],
[$sol->id_solicitud, '$sol->fecha_solicitud', '$seccion', '$sol->numero_solicitud',
'$sol->nivel_solicitud'],false,false,false,'comentario_solicitud','$sol->comentario_jefe')";
$botones='<a class="action icono icon-detalle" href="'.base_url('index.php/Bodega/Detalle_Solicitud_Control/index/'.$sol->id_solicitud.'/'.$id_rol.'/').'" data-toggle="tooltip" title="Detalle"></a>';
//$eliminar='<a class="icono icon-eliminar" uri='.base_url('index.php/Bodega/solicitud/EliminarDato/'.$sol->id_solicitud).'></a>';
$actualizar = '<a class="action icono icon-actualizar" data-toggle="tooltip" title="Editar" onClick="'.$onClick.'"></a>';
$aprobar = '';
$denegar = '';
$estado = 'POR APROBAR';
$this->table->add_row($sol->id_solicitud, $sol->numero_solicitud, $seccion, $fuente, $sol->fecha_solicitud, $comentario,
$estado,$botones.$aprobar.$denegar.$actualizar);
} elseif ($sol->nivel_solicitud == 2){
$onClick = "llenarFormulario('solicitud', ['id', 'fecha_solicitud', 'id_seccion', 'numero_solicitud', 'nivel'],
[$sol->id_solicitud, '$sol->fecha_solicitud', '$seccion', '$sol->numero_solicitud', '$sol->nivel_solicitud'],false,false,false,'comentario_solicitud','$sol->comentario_jefe')";
$botones='<a class="action icono icon-detalle" href="'.base_url('index.php/Bodega/Detalle_Solicitud_Control/index/'.$sol->id_solicitud.'/'.$id_rol.'/').'" data-toggle="tooltip" title="Detalle"></a>';
//$eliminar='<a class="icono icon-denegar"></a>';
$actualizar = '<a class="action icono icon-actualizar" data-toggle="tooltip" title="Editar" onClick="'.$onClick.'"></a>';
$aprobar = '';
$denegar = '';
$estado = 'APROBADA';
$this->table->add_row($sol->id_solicitud, $sol->numero_solicitud, $seccion, $fuente, $sol->fecha_solicitud, $comentario,
$estado,$botones.$aprobar.$denegar.$actualizar);
} elseif ($sol->nivel_solicitud == 3 || $sol->nivel_solicitud == 4){
$onClick = "llenarFormulario('solicitud', ['id', 'fecha_solicitud', 'id_seccion', 'numero_solicitud', 'comentario_solicitud', 'nivel'],
[$sol->id_solicitud, '$sol->fecha_solicitud', '$seccion', '$sol->numero_solicitud', '$comentario', '$sol->nivel_solicitud'])";
$botones='<a class="action icono icon-detalle" href="'.base_url('index.php/Bodega/Detalle_Solicitud_Control/index/'.$sol->id_solicitud.'/'.$id_rol.'/').'" data-toggle="tooltip" title="Detalle"></a>';
//$eliminar='<a class="icono icon-denegar"></a>';
$actualizar = '';
$aprobar = '';
$denegar = '';
$estado = 'APROBADA';
$this->table->add_row($sol->id_solicitud, $sol->numero_solicitud, $seccion, $fuente, $sol->fecha_solicitud, $comentario,
$estado,$botones.$aprobar.$denegar.$actualizar);
} elseif ($sol->nivel_solicitud == 9) {
if ($sol->nivel_anterior == 1){
$estado = $sol->estado_solicitud;
}
if ($sol->nivel_anterior == 2){
$estado = 'APROBADA';
}
$onClick = "llenarFormulario('solicitud', ['id', 'fecha_solicitud', 'id_seccion', 'numero_solicitud', 'comentario_solicitud', 'nivel'],
[$sol->id_solicitud, '$sol->fecha_solicitud', '$seccion', '$sol->numero_solicitud', '$sol->comentario', '$sol->nivel_solicitud'])";
$botones='<a class="action icono icon-detalle" href="'.base_url('index.php/Bodega/Detalle_Solicitud_Control/index/'.$sol->id_solicitud.'/'.$id_rol.'/').'" data-toggle="tooltip" title="Detalle"></a>';
//$eliminar='<a class="icono icon-denegar"></a>';
$actualizar = '';
$aprobar = '';
$denegar = '';
$this->table->add_row($sol->id_solicitud, $sol->numero_solicitud, $seccion, $fuente, $sol->fecha_solicitud, $comentario,
$estado,$botones.$aprobar.$denegar.$actualizar);
}
}
if ($USER['rol'] == 'DIRECTOR ADMINISTRATIVO'){
if ($sol->nivel_solicitud == 2){
$onClick = "llenarFormulario('solicitud', ['id', 'fecha_solicitud', 'id_seccion', 'numero_solicitud', 'nivel'],
[$sol->id_solicitud, '$sol->fecha_solicitud', '$seccion', '$sol->numero_solicitud', '$sol->nivel_solicitud'],
false,false,false,'comentario_solicitud','$sol->comentario_admin')";
$botones='<a class="action icono icon-detalle" href="'.base_url('index.php/Bodega/Detalle_Solicitud_Control/index/'.$sol->id_solicitud.'/'.$id_rol.'/').'" data-toggle="tooltip" title="Detalle"></a>';
//$eliminar='<a class="icono icon-eliminar" uri='.base_url('index.php/Bodega/solicitud/EliminarDato/'.$sol->id_solicitud).'></a>';
$actualizar = '<a class="action icono icon-actualizar" data-toggle="tooltip" title="Editar" onClick="'.$onClick.'"></a>';
$aprobar = '<a class="action icono icon-liquidar" data-toggle="tooltip" title="Aprobar" href="'.base_url('index.php/Bodega/Solicitud_control/Aprobar/'.$sol->id_solicitud.'/').'"></a>';
$denegar = '<a class="action icono icon-cross" data-toggle="tooltip" title="Denegar" href="'.base_url('index.php/Bodega/Solicitud_control/Denegar/'.$sol->id_solicitud.'/').'"></a>';
$estado = 'POR APROBAR';
$this->table->add_row($sol->id_solicitud, $sol->numero_solicitud, $seccion, $fuente, $sol->fecha_solicitud, $comentario,
$estado,$botones.$aprobar.$denegar.$actualizar);
}
if ($sol->nivel_solicitud == 3){
$onClick = "llenarFormulario('solicitud', ['id', 'fecha_solicitud', 'id_seccion', 'numero_solicitud', 'nivel'],
[$sol->id_solicitud, '$sol->fecha_solicitud', '$seccion', '$sol->numero_solicitud', '$sol->nivel_solicitud'],
false,false,false,'comentario_solicitud','$sol->comentario_admin')";
$botones='<a class="action icono icon-detalle" href="'.base_url('index.php/Bodega/Detalle_Solicitud_Control/index/'.$sol->id_solicitud.'/'.$id_rol.'/').'" data-toggle="tooltip" title="Detalle"></a>';
//$eliminar='<a class="icono icon-denegar"></a>';
$actualizar = '<a class="action icono icon-actualizar" data-toggle="tooltip" title="Editar" onClick="'.$onClick.'"></a>';
$aprobar = '';
$denegar = '<a class="action icono icon-cross" data-toggle="tooltip" title="Denegar" href="'.base_url('index.php/Bodega/Solicitud_control/Denegar/'.$sol->id_solicitud.'/').'"></a>';
$estado = 'APROBADA';
$this->table->add_row($sol->id_solicitud, $sol->numero_solicitud, $seccion, $fuente, $sol->fecha_solicitud, $comentario,
$estado,$botones.$aprobar.$denegar.$actualizar);
}if ($sol->nivel_solicitud == 4){
$onClick = "llenarFormulario('solicitud', ['id', 'fecha_solicitud', 'id_seccion', 'numero_solicitud', 'comentario_solicitud', 'nivel'],
[$sol->id_solicitud, '$sol->fecha_solicitud', '$seccion', '$sol->numero_solicitud', '$comentario', '$sol->nivel_solicitud'])";
$botones='<a class="action icono icon-detalle" href="'.base_url('index.php/Bodega/Detalle_Solicitud_Control/index/'.$sol->id_solicitud.'/'.$id_rol.'/').'" data-toggle="tooltip" title="Detalle"></a>';
//$eliminar='<a class="icono icon-denegar"></a>';
$actualizar = '';
$aprobar = '';
$denegar = '';
$estado = 'APROBADA';
$this->table->add_row($sol->id_solicitud, $sol->numero_solicitud, $seccion, $fuente, $sol->fecha_solicitud, $comentario,
$estado,$botones.$aprobar.$denegar.$actualizar);
}
if ($sol->nivel_solicitud == 9 && $sol->nivel_anterior == 2) {
$onClick = "llenarFormulario('solicitud', ['id', 'fecha_solicitud', 'id_seccion', 'numero_solicitud', 'comentario_solicitud', 'nivel'],
[$sol->id_solicitud, '$sol->fecha_solicitud', '$seccion', '$sol->numero_solicitud', '$sol->comentario', '$sol->nivel_solicitud'])";
$botones='<a class="action icono icon-detalle" href="'.base_url('index.php/Bodega/Detalle_Solicitud_Control/index/'.$sol->id_solicitud.'/').'" data-toggle="tooltip" title="Detalle"></a>';
//$eliminar='<a class="icono icon-denegar"></a>';
$actualizar = '';
$aprobar = '';
$denegar = '';
$estado = $sol->estado_solicitud;
$this->table->add_row($sol->id_solicitud, $sol->numero_solicitud, $seccion, $fuente, $sol->fecha_solicitud, $comentario,
$estado,$botones.$aprobar.$denegar.$actualizar);
}
}
}
} else {
$msg = array('data' => "Texto no encontrado", 'colspan' => "9");
$this->table->add_row($msg);
}
/*
* vuelve a verificar para mostrar los datos
*/
if ($this->input->is_ajax_request()) {
echo "<div class='table-responsive'>" . $this->table->generate() . "</div>" . $pagination;
} else {
return "<div class='table-responsive'>" . $this->table->generate() . "</div>" . $pagination;
}
} else {
redirect('login/index/error_no_autenticado');
}
}
public function Aprobar() {
$USER = $this->session->userdata('logged_in');
if($USER){
$id = $this->uri->segment(4);
$estado = $this->Solicitud_Model->retornarEstado($id);
$nivel = $this->Solicitud_Model->retornarNivel($id);
if ($estado == 'ENVIADA' || $estado == 'APROBADA'){
$data = array(
'estado_solicitud' => 'APROBADA',
'nivel_solicitud' => $nivel + 1
);
}
$this->Solicitud_Model->actualizarSolicitud($id,$data);
$this->notificacion->NotificacionSolicitudBodega($id, $USER, $nivel + 1);
redirect('/Bodega/Solicitud_control/index/aprobada');
} else {
redirect('login/index/error_no_autenticado');
}
}
public function Denegar() {
$USER = $this->session->userdata('logged_in');
if($USER){
$id = $this->uri->segment(4);
$nivel = $this->Solicitud_Model->retornarNivel($id);
$data = array(
'estado_solicitud' => 'DENEGADA',
'nivel_anterior' => $nivel,
'nivel_solicitud' => 9
);
$this->Solicitud_Model->actualizarSolicitud($id,$data);
$this->notificacion->NotificacionSolicitudBodega($id, $USER, 9);
redirect('/Bodega/Solicitud_control/index/denegada');
} else {
redirect('login/index/error_no_autenticado');
}
}
public function ActualizarDatos() {
$modulo=$this->User_model->obtenerModulo('Bodega/Solicitud_control');
$USER = $this->session->userdata('logged_in');
date_default_timezone_set('America/El_Salvador');
$anyo=20;
$fecha_actual=date($anyo."y-m-d");
$hora=date("H:i:s");
$rastrea = array(
'id_usuario' =>$USER['id'],
'id_modulo' =>$modulo,
'fecha' =>$fecha_actual,
'hora' =>$hora,
);
$id_seccion=$USER['id_seccion'];
$botones;
$nivel_solicitud = $this->Solicitud_Model->retornarNivel($this->input->post('id'));
$comentario='';
if ($USER['rol'] == 'JEFE UNIDAD' || $USER['rol'] == 'JEFE BODEGA' || $USER['rol'] == 'JEFE COMPRAS' || $USER['rol'] == 'JEFE UACI' || $USER['rol'] == 'JEFE AF'
|| $USER['rol'] == 'COLABORADOR BODEGA' || $USER['rol'] == 'COLABORADOR COMPRAS' || $USER['rol'] == 'COLABORADOR UACI' || $USER['rol'] == 'COLABORADOR AF') { //verificar act para colaboradores
$comentario='comentario_jefe';
}elseif ($USER['rol'] == 'DIRECTOR ADMINISTRATIVO') {
$comentario='comentario_admin';
}
if($USER){
$data = array(
$comentario => $this->input->post('comentario_solicitud'),
);
if (!($this->input->post('id') == '')){
if ($this->User_model->validarAccesoCrud($modulo, $USER['id'], 'update')) {
$rastrea['operacion']='ACTUALIZA';
$rastrea['id_registro']=$this->input->post('id');
$this->User_model->insertarRastreabilidad($rastrea);
$this->Solicitud_Model->actualizarSolicitud($this->input->post('id'),$data);
redirect('/Bodega/Solicitud_control/index/update');
} else {
redirect('/Bodega/Solicitud_control/index/forbidden');
}
}
} else {
redirect('login/index/error_no_autenticado');
}
}
}
?>
| mit |
AlenQi/toolscript | src/detectIE.js | 868 | /**
* Judge the IE browser version.
*
* @param {Int} Internet explorer version.
* @returns {Boolean} Returns is it the current version.
*/
const detectIE = function(version) {
const ua = window.navigator.userAgent
if (version < 10) {
const b = document.createElement('b')
b.innerHTML = '<!--[if IE ' + version + ']><i></i><![endif]-->'
return b.getElementsByTagName('i').length === 1
}
switch (version) {
case 10:
const msie = ua.indexOf('MSIE ')
if (msie > 0) {
return true
}
break
case 11:
const trident = ua.indexOf('Trident/')
if (trident > 0) {
return true
}
break
case 12:
const edge = ua.indexOf('Edge/')
if (edge > 0) {
return true
}
break
default:
}
// other browser
return false
}
export default detectIE
| mit |
taufandardiry/frk-shop | application/views/user/index.php | 20716 | <html>
<head>
<meta charset="utf-8">
<meta name="robots" content="all,follow">
<meta name="googlebot" content="index,follow,snippet,archive">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="FRK Olshop e-commerce">
<meta name="author" content="Taufan Dardiry">
<meta name="keywords" content="">
<title> FRK Olshop : e-commerce </title>
<meta name="keywords" content="">
<link href="http://fonts.googleapis.com/css?family=Roboto:400,500,700,300,100" rel="stylesheet" type="text/css">
<!-- styles -->
<link href="<?php echo base_url() ?>assets/front-end/css/font-awesome.css" rel="stylesheet">
<link href="<?php echo base_url() ?>assets/front-end/css/bootstrap.min.css" rel="stylesheet">
<link href="<?php echo base_url() ?>assets/front-end/css/animate.min.css" rel="stylesheet">
<link href="<?php echo base_url() ?>assets/front-end/css/owl.carousel.css" rel="stylesheet">
<link href="<?php echo base_url() ?>assets/front-end/css/owl.theme.css" rel="stylesheet">
<!-- theme stylesheet -->
<link href="<?php echo base_url() ?>assets/front-end/css/style.default.css" rel="stylesheet" id="theme-stylesheet">
<!-- your stylesheet with modifications -->
<link href="<?php echo base_url() ?>assets/front-end/css/custom.css" rel="stylesheet">
<script src="<?php echo base_url() ?>assets/front-end/js/respond.min.js"></script>
<link rel="shortcut icon" href="<?php echo base_url() ?>assets/front-end/favicon.png"> </head>
<body>
<!-- *** TOPBAR ***
_________________________________________________________ -->
<div id="top">
<div class="container">
<div class="col-md-12" data-animate="fadeInDown">
<ul class="menu">
<li>
<a href="#" data-toggle="modal" data-target="#login-modal">Hai, <?php echo $this->session->userdata('nama_depan') ?></a>
</li>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/logout" ?>">Logout</a>
</li>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/contactpage" ?>">Contact</a>
</li>
</ul>
</div>
</div>
</div>
<!-- *** TOP BAR END *** -->
<!-- *** NAVBAR ***
_________________________________________________________ -->
<div class="navbar navbar-default yamm" role="navigation" id="navbar">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand home" href="<?php echo base_url()."index.php/MyControllerUser/index" ?>" data-animate-hover="bounce">
<img src="<?php echo base_url() ?>assets/front-end/img/logo1.png" alt="Obaju logo" class="hidden-xs">
<img src="<?php echo base_url() ?>assets/front-end/img/logo-small1.png" alt="Obaju logo" class="visible-xs"><span class="sr-only">FRK Olshop - go to homepage</span> </a>
<div class="navbar-buttons">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navigation"> <span class="sr-only">Toggle navigation</span> <i class="fa fa-align-justify"></i> </button>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#search"> <span class="sr-only">Toggle search</span> <i class="fa fa-search"></i> </button>
<a class="btn btn-default navbar-toggle" href="<?php echo base_url()."index.php/MyController/basketpage" ?>"> <i class="fa fa-shopping-cart"></i> <span class="hidden-xs">View items in cart</span> </a>
</div>
</div>
<!--/.navbar-header -->
<div class="navbar-collapse collapse" id="navigation">
<ul class="nav navbar-nav navbar-left">
<li class="active">
<a href="<?php echo base_url()."index.php/MyControllerUser/index" ?>">Home</a>
</li>
<li class="dropdown yamm-fw">
<a href="<?php echo base_url()."index.php/MyControllerUser/categorypage" ?>" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="200">Product <b class="caret"></b></a>
<ul class="dropdown-menu">
<li>
<div class="yamm-content">
<div class="row">
<div class="col-sm-6">
<h5>Ladies</h5>
<ul>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/categorypage" ?>">Jilbab</a>
</li>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/categorypage" ?>">Ciput</a>
</li>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/categorypage" ?>">Kaos Kaki</a>
</li>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/categorypage" ?>">Accessories</a>
</li>
</ul>
</div>
<div class="col-sm-6">
<h5>Accessories</h5>
<ul>
<li>
<a href="#">Coming Soon :)</a>
</li>
</ul>
</div>
</div>
</div>
<!-- /.yamm-content -->
</li>
</ul>
</li>
<li class="dropdown yamm-fw">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="200">INFO<b class="caret"></b></a>
<ul class="dropdown-menu">
<li>
<div class="yamm-content">
<div class="row">
<div class="col-sm-3">
<h5>User</h5>
<ul>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/customeraccountpage" ?>">Customer account / change password</a>
</li>
</ul>
</div>
<div class="col-sm-3">
<h5>Order process</h5>
<ul>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/basketpage" ?>">Shopping cart</a>
</li>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/checkout1page" ?>">Checkout</a>
</li>
</ul>
</div>
<div class="col-sm-3">
<h5>Pages</h5>
<ul>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/textpage" ?>">About Us</a>
</li>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/faqpage" ?>">FAQ</a>
</li>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/contactpage" ?>">Contact</a>
</li>
</ul>
</div>
<div class="col-sm-3">
<h5>Blog</h5>
<ul>
<li>
<a href="#" >Coming Soon :)</a>
</li>
</ul>
</div>
</div>
</div>
<!-- /.yamm-content -->
</li>
</ul>
</li>
</ul>
</div>
<!--/.nav-collapse -->
<div class="navbar-buttons">
<div class="navbar-collapse collapse right" id="basket-overview">
<a href="<?php echo base_url()."index.php/MyControllerUser/basketpage" ?>" class="btn btn-primary navbar-btn"><i class="fa fa-shopping-cart"></i><span class="hidden-sm">View items in cart</span></a>
</div>
<!--/.nav-collapse -->
<div class="navbar-collapse collapse right" id="search-not-mobile">
<button type="button" class="btn navbar-btn btn-primary" data-toggle="collapse" data-target="#search"> <span class="sr-only">Toggle search</span> <i class="fa fa-search"></i> </button>
</div>
</div>
<div class="collapse clearfix" id="search">
<form class="navbar-form" role="search">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search"> <span class="input-group-btn">
<button type="submit" class="btn btn-primary"><i class="fa fa-search"></i></button>
</span> </div>
</form>
</div>
<!--/.nav-collapse -->
</div>
<!-- /.container -->
</div>
<!-- /#navbar -->
<!-- *** NAVBAR END *** -->
<div id="all">
<div id="content">
<div class="container">
<div class="col-md-12">
<div id="main-slider">
<div class="item">
<img src="<?php echo base_url() ?>assets/front-end/img/main1.jpg" alt="" class="img-responsive"> </div>
<div class="item">
<img class="img-responsive" src="<?php echo base_url() ?>assets/front-end/img/main2.jpg" alt=""> </div>
<div class="item">
<img class="img-responsive" src="<?php echo base_url() ?>assets/front-end/img/main3.jpg" alt=""> </div>
<div class="item">
<img class="img-responsive" src="<?php echo base_url() ?>assets/front-end/img/main4.jpg" alt=""> </div>
</div>
<!-- /#main-slider -->
</div>
</div>
<!-- *** ADVANTAGES HOMEPAGE ***
_________________________________________________________ -->
<div id="advantages">
<div class="container">
<div class="same-height-row">
<div class="col-sm-4">
<div class="box same-height clickable">
<div class="icon"><i class="fa fa-heart"></i> </div>
<h3>
<a href="#">We love our customers</a>
</h3>
<p>We are known to provide best possible service ever</p>
</div>
</div>
<div class="col-sm-4">
<div class="box same-height clickable">
<div class="icon"><i class="fa fa-tags"></i> </div>
<h3>
<a href="#">Best prices</a>
</h3>
<p>You can check that the height of the boxes adjust when longer text like this one is used in one of them.</p>
</div>
</div>
<div class="col-sm-4">
<div class="box same-height clickable">
<div class="icon"><i class="fa fa-thumbs-up"></i> </div>
<h3>
<a href="#">100% satisfaction guaranteed</a>
</h3>
<p>Free returns on everything for 2 weeks.</p>
</div>
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
<!-- /#advantages -->
<!-- *** ADVANTAGES END *** -->
<!-- *** HOT PRODUCT SLIDESHOW ***
_________________________________________________________ -->
<div id="hot">
<div class="box">
<div class="container">
<div class="col-md-12">
<h2>NEW RELEASE</h2>
</div>
</div>
</div>
<div class="container">
<div class="product-slider">
<?php foreach ($data as $x ) { ?>
<div class="item">
<div class="product">
<div class="flip-container">
<div class="flipper">
<div class="front">
<a href="<?php echo base_url()."index.php/MyControllerUser/detailpage" ?>">
<img src="<?php echo base_url().'/upload/'.$x['image']; ?>" alt="" class="img-responsive"> </a>
</div>
<div class="back">
<a href="<?php echo base_url()."index.php/MyControllerUser/detailpage" ?>">
<img src="<?php echo base_url().'/upload/'.$x['image']; ?>" alt="" class="img-responsive"> </a>
</div>
</div>
</div>
<a href="<?php echo base_url()."index.php/MyControllerUser/detailpage" ?>" class="invisible">
<img src="<?php echo base_url().'/upload/'.$x['image']; ?>" alt="" class="img-responsive"> </a>
<div class="text">
<h3>
<a href="<?php echo base_url()."index.php/MyControllerUser/detailpage" ?>"><?= $x['nama_barang'] ?></a>
</h3>
<p class="price">RP <?= $x['harga'] ?></p>
</div>
<!-- /.text -->
<div class="ribbon sale">
<div class="theribbon">NEW</div>
<div class="ribbon-background"></div>
</div>
</div>
<!-- /.product -->
</div>
<?php } ?>
</div>
<!-- /.product-slider -->
</div>
<!-- /.container -->
</div>
<!-- /#hot -->
<!-- *** HOT END *** -->
<!-- *** GET INSPIRED ***
_________________________________________________________ -->
<div class="container" data-animate="fadeInUpBig">
<div class="col-md-12">
<div class="box slideshow">
<h3>Get Inspired</h3>
<p class="lead">Inspirasi mengenai fashion hijab kekinian.</p>
<div id="get-inspired" class="owl-carousel owl-theme">
<div class="item">
<a href="#">
<img src="<?php echo base_url() ?>assets/front-end/img/inspired1.jpg" alt="Get inspired" class="img-responsive"> </a>
</div>
<div class="item">
<a href="#">
<img src="<?php echo base_url() ?>assets/front-end/img/inspired2.jpg" alt="Get inspired" class="img-responsive"> </a>
</div>
<div class="item">
<a href="#">
<img src="<?php echo base_url() ?>assets/front-end/img/inspired3.jpg" alt="Get inspired" class="img-responsive"> </a>
</div>
</div>
</div>
</div>
</div>
<!-- *** GET INSPIRED END *** -->
<!-- *** BLOG HOMEPAGE ***
_________________________________________________________ -->
<div class="box text-center" data-animate="fadeInUp">
<div class="container">
<div class="col-md-12">
<h3 class="text-uppercase">F.R.K OLSHOP</h3>
<p class="lead">Bagaimana perkembangan fashion masa kini?
<a href="<?php echo base_url()."index.php/MyControllerUser/textpage" ?>">Ini tentang frk oshop!</a>
</p>
</div>
</div>
</div>
<!-- /.container -->
<!-- *** BLOG HOMEPAGE END *** -->
</div>
<!-- /#content -->
<!-- *** FOOTER ***
_________________________________________________________ -->
<div id="footer" data-animate="fadeInUp">
<div class="container">
<div class="row">
<div class="col-md-3 col-sm-6">
<h4>Pages</h4>
<ul>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/textpage" ?>">About us</a>
</li>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/textpage" ?>">Terms and conditions</a>
</li>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/faqpage" ?>">FAQ</a>
</li>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/contactpage" ?>">Contact us</a>
</li>
</ul>
<hr>
<h4>User section</h4>
<ul>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/logout" ?>">Logout</a>
</li>
</ul>
<hr class="hidden-md hidden-lg hidden-sm"> </div>
<!-- /.col-md-3 -->
<div class="col-md-3 col-sm-6">
<h4>Top categories</h4>
<h5>Ladies</h5>
<ul>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/categorypage" ?>">Jilbab</a>
</li>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/categorypage" ?>">Ciput</a>
</li>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/categorypage" ?>">Kaos Kaki</a>
</li>
<li>
<a href="<?php echo base_url()."index.php/MyControllerUser/categorypage" ?>">Accessories</a>
</li>
</ul>
<hr class="hidden-md hidden-lg"> </div>
<!-- /.col-md-3 -->
<div class="col-md-3 col-sm-6">
<h4>Where to find us</h4>
<p>F.R.K Olshop.
<br>Perumahan Nyalabu Permai IV Pamekasan, Madura
<br>69317
<br>Indonesia</p>
<a href="<?php echo base_url()."index.php/MyControllerUser/contactpage" ?>">Go to contact page</a>
<hr class="hidden-md hidden-lg"> </div>
<!-- /.col-md-3 -->
<div class="col-md-3 col-sm-6">
<h4>Get the news</h4>
<p class="text-muted">Jangan lewati promo-promo terbaik dari FRK Shop. Jadilah yang pertama untuk mengetahui info promo-promo dari kami!</p>
<form>
<div class="input-group">
<!-- <input type="text" class="form-control"> <span class="input-group-btn">
<button class="btn btn-default" type="button">Subscribe!</button>
-->
</span> </div>
<!-- /input-group -->
</form>
<hr>
<h4>Stay in touch</h4>
<p class="social">
<a href="https://www.facebook.com/profile.php?id=100004634076601&fref=ts" class="facebook external" data-animate-hover="shake"><i class="fa fa-facebook"></i></a>
<a href="https://www.instagram.com/frk_olshop/" class="instagram external" data-animate-hover="shake"><i class="fa fa-instagram"></i></a>
<a href="https://mail.google.com/mail/?view=cm&fs=1&tf=1&to=olshopfrk@gmail.com&su=Hello&shva=1" class="email external" data-animate-hover="shake"><i class="fa fa-envelope"></i></a>
</p>
</div>
<!-- /.col-md-3 -->
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
<!-- /#footer -->
<!-- *** FOOTER END *** -->
<!-- *** COPYRIGHT ***
_________________________________________________________ -->
<div id="copyright">
<div class="container">
<div class="col-md-6">
<p class="pull-left">© 2017 FRK Olshop.</p>
</div>
<div class="col-md-6">
<p class="pull-right">Template by
<a href="https://bootstrapious.com/e-commerce-templates">Bootstrapious.com</a>
<!-- Not removing these links is part of the license conditions of the template. Thanks for understanding :) If you want to use the template without the attribution links, you can do so after supporting further themes development at https://bootstrapious.com/donate -->
</p>
</div>
</div>
</div>
<!-- *** COPYRIGHT END *** -->
</div>
<!-- /#all -->
<!-- *** SCRIPTS TO INCLUDE ***
_________________________________________________________ -->
<script src="<?php echo base_url() ?>assets/front-end/js/jquery-1.11.0.min.js"></script>
<script src="<?php echo base_url() ?>assets/front-end/js/bootstrap.min.js"></script>
<script src="<?php echo base_url() ?>assets/front-end/js/jquery.cookie.js"></script>
<script src="<?php echo base_url() ?>assets/front-end/js/waypoints.min.js"></script>
<script src="<?php echo base_url() ?>assets/front-end/js/modernizr.js"></script>
<script src="<?php echo base_url() ?>assets/front-end/js/bootstrap-hover-dropdown.js"></script>
<script src="<?php echo base_url() ?>assets/front-end/js/owl.carousel.min.js"></script>
<script src="<?php echo base_url() ?>assets/front-end/js/front.js"></script>
</body>
</html> | mit |
tartavull/tigertrace | tigertrace/util/rehuman_semantics.py | 1483 | from tqdm import tqdm
from collections import defaultdict
import h5py
import networkx as nx
import struct
import numpy as np
# hl = None
# ml = None
# with h5py.File('/usr/people/it2/seungmount/research/datasets/blended_piriform_157x2128x2128/all/human_semantic_labels.h5','r') as f:
# hl = f['main'][:]
# with h5py.File('/usr/people/it2/seungmount/research/datasets/blended_piriform_157x2128x2128/all/sparse_human_labels.h5','r') as f:
# ml = f['main'][:]
# soft_labels = defaultdict(lambda: defaultdict(int))
# def max_key_from_dict( d ):
# max_key = d.keys()[0]
# max_val = d[max_key]
# for k,v in d.iteritems():
# if v > max_val:
# max_val = v
# max_key = k
# return max_key
# for z in tqdm(xrange(hl.shape[0])):
# for y in xrange(hl.shape[1]):
# for x in xrange(hl.shape[2]):
# soft_labels[ml[z,y,x]][hl[z,y,x]] += 1
# mapping = dict()
# for ml_label, soft_label in soft_labels.iteritems():
# best_hl = max_key_from_dict(soft_label)
# mapping[ml_label] = best_hl
# final = np.zeros(shape=ml.shape)
# for z in tqdm(xrange(hl.shape[0])):
# for y in xrange(hl.shape[1]):
# for x in xrange(hl.shape[2]):
# final[z,y,x] = mapping[ml[z,y,x]]
with h5py.File('/usr/people/it2/seungmount/research/datasets/blended_piriform_157x2128x2128/all/sparse_semantic_labels.h5') as f:
exp = np.zeros(shape=(4,157,2128,2128))
for i in range(5):
exp[i,:,:,:] = f['main'][:,:,:] == i
f.create_dataset('expanded',data=exp) | mit |
dlennox24/ricro-app-template | scripts/scripts.js | 3749 | #! /usr/bin/env node
const sh = require('shelljs');
const pk = require('../package.json');
const utils = require('./_utils.js');
let args = process.argv.splice(2);
// For debugging/testing script. This way all scripts don't execute each run.
const debug = args.includes('debug');
/*
* valid arg prefixes:
* no-: doesn't do the task of the suffix
*
* valid arg suffixes:
* clean: removes node_modules folders
* install-lib: installs node_modules in library
* install-ex: installs node_modules in example
* link-lib: links library
* link-ex: links example
* peers: installs peers via npm-install-peers
*
* other args:
* debug: doesn't execute shell commands
*
* e.g.:
* no-clean
* only-peers
*/
const script = new utils.Script({ name: 'scripts' });
sh.exec('clear');
// eslint-disable-next-line no-console
console.log(utils.headerColor(`\n${pk.name}@${pk.version} - ${script.name}`));
script.log(utils.bodyColor('Running scripts...'));
script.log(utils.bodyColor(`args passed:\t[${args.sort().toString()}]`));
// aliases for install and link
if (args.includes('install')) {
args.push('install-lib', 'install-ex');
}
if (args.includes('link')) {
args.push('link-lib', 'link-ex');
}
// clean args is present then ignore all other args as this purges all node_modules
// and will cause this script to crash
if (args.includes('clean') || !args.includes('no-clean')) {
args = ['clean'];
script.log(utils.warnColor('Warning: clean detected. Running only clean option.'));
}
if (args.length === 0) {
args = ['no-clean'];
}
/*
* Creates an array of negative args to run. prepends 'no-' to all other args
* in `validArgs` array. Mutiple values from `validArgs` can be chained together.
*
* Ignores all args not in `validArgs` array even if prefixed with 'no-'.
*
* e.g. if args is
* ['link-ex', clean']
* then it converts it to
* [no-install', 'no-link']
*/
let validArgs = ['clean', 'install-lib', 'install-ex', 'link-lib', 'link-ex'];
const argsToRun = args.filter(arg => validArgs.indexOf(arg) !== -1);
if (argsToRun.length > 0) {
validArgs = validArgs.filter(arg => argsToRun.indexOf(arg) === -1);
args = validArgs.map(arg => `no-${arg}`);
}
if (debug && !args.includes('debug')) {
args.push('debug');
}
script.log(`args ran:\t[${args.sort().toString()}]\n`);
if (!args.includes('no-clean')) {
new utils.Script({
name: 'clean',
description: 'Cleaning node_modules',
// order matters for shellScripts here
// delete example/node_modules then node_modules as this script depends on the latter
shellScripts: ['rm -rf example/node_modules', 'rm -rf node_modules'],
debug,
}).exec();
}
if (!args.includes('no-install')) {
if (!args.includes('no-install-lib')) {
new utils.Script({
name: 'install-lib',
description: 'Installing library dependencies',
shellScripts: 'yarn install',
debug,
}).exec();
}
if (!args.includes('no-install-ex')) {
new utils.Script({
name: 'install-ex',
description: 'Installing example dependencies',
shellScripts: [{ func: 'cd', args: 'example' }, 'yarn install', { func: 'cd', args: '..' }],
debug,
}).exec();
}
}
if (!args.includes('no-link')) {
if (!args.includes('no-link-lib')) {
new utils.Script({
name: 'link-lib',
description: 'Linking library',
shellScripts: 'yarn link',
debug,
}).exec();
}
if (!args.includes('no-link-ex')) {
new utils.Script({
name: 'link-ex',
description: 'Linking example',
shellScripts: [
{ func: 'cd', args: 'example' },
'yarn link colostate-ricro-ui',
{ func: 'cd', args: '..' },
],
debug,
}).exec();
}
}
| mit |
rafaelmariotti/oradock | preconfig/amazon_linux/chef_config/attributes/oradock.rb | 840 | #backup and data settings - configure your backup and data directories and their respective devices
default['backup']['directory'] = '/backup'
default['backup']['device'] = '/dev/sdb'
default['data']['directory'] = '/data'
default['data']['device'] = '/dev/sdc'
#python settings - DO NOT CHANGE THIS
default['pyenv']['version'] = '3.5.1'
default['pyenv']['root_path'] = '/root/.pyenv'
default['pyenv']['default_modules'] = 'boto docopt'
default['pyenv']['docker_module'] = 'docker-py'
default['pyenv']['docker_module_version'] = '1.9.0'
#yum settings - DO NOT CHANGE THIS
default['yum']['install'] = 'wget.x86_64','git.x86_64','patch.x86_64','gcc44.x86_64','zlib.x86_64','zlib-devel.x86_64','bzip2.x86_64','bzip2-devel.x86_64','sqlite.x86_64','sqlite-devel.x86_64','openssl.x86_64','openssl-devel.x86_64', 'docker.x86_64'
| mit |
kalinalazarova1/TelerikAcademy | Programming/2. CSharpPartTwo/CS2_03.Methods/12. MultiplyPolynomials/Properties/AssemblyInfo.cs | 1422 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("12. MultiplyPolynomials")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("12. MultiplyPolynomials")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("78cd441c-55c0-41a0-bd84-7739086e2821")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
gatero/nightwatch | lib/api/expect/value.js | 1645 | /**
* Property that retrieves the value (i.e. the value attributed) of an element. Can be chained to check if contains/equals/matches the specified text or regex.
*
* ```
* this.demoTest = function (browser) {
* browser.expect.element('#q').to.have.value.that.equals('search');
* browser.expect.element('#q').to.have.value.not.equals('search');
* browser.expect.element('#q').to.have.value.which.contains('search');
* browser.expect.element('#q').to.have.value.which.matches(/search/);
* };
* ```
*
* @display .value
* @method value
* @api expect
*/
var util = require('util');
var events = require('events');
var BaseAssertion = require('./_baseAssertion.js');
function ValueAssertion() {
this.flag('valueFlag', true);
BaseAssertion.call(this);
this.message = 'Expected element <%s> to have value' + (this.negate ? ' not' : '');
this.start();
}
util.inherits(ValueAssertion, BaseAssertion);
ValueAssertion.prototype.executeCommand = function(callback) {
this.protocol.elementIdValue(this.elementResult.ELEMENT, callback);
};
ValueAssertion.prototype.elementFound = function() {
if (this.retries > 0 && this.negate) {
return;
}
if (this.passed && this.waitForMs) {
var message = '';
if (this.hasCondition()) {
message = 'condition was met';
}
this.elapsedTime = this.getElapsedTime();
this.messageParts.push(' - ' + message + ' in ' + this.elapsedTime + 'ms');
}
};
ValueAssertion.prototype.elementNotFound = function() {
this.passed = false;
};
ValueAssertion.prototype.retryCommand = function() {
this.onPromiseResolved();
};
module.exports = ValueAssertion; | mit |
Nillerr/Amplified.CSharp | Amplified.CSharp.Tests/Units/StaticConstructors.cs | 1820 | using System;
using System.Threading.Tasks;
using Xunit;
namespace Amplified.CSharp
{
// ReSharper disable once InconsistentNaming
public class Units__StaticConstructors
{
[Fact]
public void UnitConstructors()
{
var staticValue = Units.Unit();
var defaultValue = default(Unit);
var constructedValue = new Unit();
var staticPropertyValue = Unit.Instance;
Assert.Equal(staticValue, defaultValue);
Assert.Equal(staticValue, constructedValue);
Assert.Equal(staticValue, staticPropertyValue);
}
[Fact]
public void WithLambdaAsAction_ReturnsFunc_Unit()
{
var result = Units.Unit(() => { });
Assert.Equal(result, default(Unit));
}
[Fact]
public void WithMethodReferenceAsAction_ReturnsFunc_Unit()
{
void Foo() => Console.WriteLine("bar");
var result = Units.Unit(Foo);
Assert.Equal(result, default(Unit));
}
[Fact]
public async Task WithLambdaAsFunc_Task_ReturnsFunc_Task_Unit()
{
var result = await Units.UnitAsync(() => Task.CompletedTask);
Assert.Equal(result, default(Unit));
}
[Fact]
public async Task WithAsyncLambdaAsFunc_Task_ReturnsFunc_Task_Unit()
{
var result = await Units.UnitAsync(async () => await Task.CompletedTask);
Assert.Equal(result, default(Unit));
}
[Fact]
public async Task WithMethodReferenceAsFunc_Task_ReturnsFunc_Task_Unit()
{
Task Foo() => Task.CompletedTask;
var result = await Units.UnitAsync(Foo);
Assert.Equal(result, default(Unit));
}
}
} | mit |
DineroRegnskab/dinero-csharp-sdk | DineroClientSDK/DineroPortableClientSDK/Dashboard/DineroDashboard.cs | 2922 | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace DineroPortableClientSDK.Dashboard
{
public sealed class DineroDashboard : DineroLibaryBase
{
internal DineroDashboard(Dinero dinero) : base(dinero) { }
/// <summary>
/// Get the dashboard data with income and expenses for the organization, for a given time periode
/// </summary>
/// <param name="startDate">Start date. If you define a start date, you also need to define and end date.
/// You can only get dashboard for the last 12 months. If start and end date are both empty, the last 6 months are returned.
/// </param>
/// <param name="endDate">End date. If you define a end date, you also need to define and start date.
/// You can only get dashboard for the last 12 months. If start and end date are both empty, the last 6 months are returned.
/// </param>
/// <returns>Dashboard data</returns>
public Task<Dashboard> GetDashboardAsync(DateTime? startDate = null, DateTime? endDate = null)
{
var parameters = new Dictionary<string, string>
{
{DineroApiParameterName.Endpoint, "dashboard"},
};
if (startDate.HasValue)
{
parameters.Add(DineroApiParameterName.StartDate, startDate.Value.ToString("yyyy-MM-dd"));
}
if (endDate.HasValue)
{
parameters.Add(DineroApiParameterName.EndDate, endDate.Value.ToString("yyyy-MM-dd"));
}
return Dinero.GetAsync<Dashboard>(parameters);
}
/// <summary>
/// Get the dashboard data with income and expenses for the organization, for a given time periode
/// </summary>
/// <param name="startDate">Start date. If you define a start date, you also need to define and end date.
/// You can only get dashboard for the last 12 months. If start and end date are both empty, the last 6 months are returned.
/// </param>
/// <param name="endDate">End date. If you define a end date, you also need to define and start date.
/// You can only get dashboard for the last 12 months. If start and end date are both empty, the last 6 months are returned.
/// </param>
/// <returns>Dashboard data</returns>
public Dashboard GetDashboard(DateTime? startDate = null, DateTime? endDate = null)
{
return TaskHelper.ExecuteSync(() => GetDashboardAsync(startDate, endDate));
}
public Task<YearlyResultModel> GetYearlyResultAsync()
{
var parameters = new Dictionary<string, string>
{
{DineroApiParameterName.Endpoint, "dashboard/yearlyresult"},
};
return Dinero.GetAsync<YearlyResultModel>(parameters);
}
}
} | mit |
yonggu/taobao | lib/taobao.rb | 691 | module Taobao
class << self
attr_accessor :app_key, :app_secret, :endpoint
def configure
yield self
true
end
end
autoload :Client, "taobao/client"
autoload :Model, "taobao/model"
autoload :TaobaokeItem, "models/taobaoke_item"
autoload :TaobaokeShop, "models/taobaoke_shop"
autoload :TaobaokeReport, "models/taobaoke_report"
autoload :TaobaokeReportMember, "models/taobaoke_report_member"
autoload :Trade, "models/trade"
autoload :Order, "models/order"
autoload :PromotionDetail, "models/promotion_detail"
autoload :Item, "models/item"
autoload :Task, "models/task"
autoload :Subtask, "models/subtask"
autoload :Shop, "models/shop"
end
| mit |
mlalic/lepp2 | src/lepp2/BaseVideoSource.hpp | 3455 | #ifndef BASE_VIDEO_SOURCE_H_
#define BASE_VIDEO_SOURCE_H_
#include <vector>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include "VideoObserver.hpp"
namespace lepp {
typedef pcl::PointXYZ SimplePoint;
typedef pcl::PointCloud<SimplePoint> SimplePointCloud;
typedef pcl::PointXYZRGBA ColoredPoint;
typedef pcl::PointCloud<ColoredPoint> ColoredPointCloud;
/**
* The abstract base class for all classes that wish to be sources of point
* cloud video information.
*
* The VideoSource is an "Observable" object to which interested observers
* (implementing the VideoObserver interface) can attach.
*
* This class provides the common functionality for all VideoSource
* implementations. Most importantly, it implements all logic regarding tracking
* and notifying observers of the source when a new point cloud is received by
* the source.
*/
template<class PointT>
class VideoSource {
public:
/**
* Convenience type for defining observers for a particular VideoSource.
*/
typedef VideoObserver<PointT> ObserverType;
/**
* Convenience type for referring to the type of the pcl::PointCloud that is
* handled by a particular VideoSource.
*/
typedef pcl::PointCloud<PointT> PointCloudType;
VideoSource() : frame_counter_(0) {}
virtual ~VideoSource();
/**
* Starts the video source.
*/
virtual void open() = 0;
/**
* Attaches a new VideoObserver to the VideoSource instance.
* Each observer will get notified once the VideoSource has received a new
* frame and converted it into a point cloud.
*/
virtual void attachObserver(boost::shared_ptr<ObserverType> observer);
protected:
/**
* Convenience method for subclasses to indicate that a new cloud has been
* received. It is enough to invoke this method in order to register a new
* point cloud as the most recent one, as well as to notify all source
* observers.
*/
virtual void setNextFrame(const typename PointCloudType::ConstPtr& cloud);
private:
/**
* Private helper method. Notifies all known observers that a new point cloud
* has been received.
*/
void notifyObservers(
int idx,
const typename PointCloudType::ConstPtr& cloud) const;
/**
* Keeps track of all observers that are attached to the source.
*/
std::vector<boost::shared_ptr<ObserverType> > observers_;
/**
* Counts how many frames have been seen by the video source.
*/
int frame_counter_;
};
template<class PointT>
VideoSource<PointT>::~VideoSource() {
// Empty!
}
template<class PointT>
void VideoSource<PointT>::notifyObservers(
int idx,
const typename pcl::PointCloud<PointT>::ConstPtr& cloud) const {
size_t const sz = observers_.size();
for (size_t i = 0; i < sz; ++i) {
observers_[i]->notifyNewFrame(idx, cloud);
}
}
template<class PointT>
void VideoSource<PointT>::setNextFrame(
const typename PointCloudType::ConstPtr& cloud) {
++frame_counter_;
notifyObservers(frame_counter_, cloud);
}
template<class PointT>
void VideoSource<PointT>::attachObserver(
boost::shared_ptr<ObserverType> observer) {
observers_.push_back(observer);
}
/**
* Convenience typedefs referring to VideoSource classes based on the template
* parameter.
*/
typedef VideoSource<ColoredPoint> ColoredVideoSource;
typedef VideoSource<SimplePoint> SimpleVideoSource;
} // namespace lepp
#endif
| mit |
pyos/libcno | setup.py | 2102 | #!/usr/bin/env python3
import os
import sys
import cffi
import subprocess
from distutils.core import setup
from distutils.command.build_ext import build_ext as BuildExtCommand
def make_ffi(root):
ffi = cffi.FFI()
ffi.set_source('cno.ffi', '#include <cno/core.h>', libraries=['cno'],
include_dirs=[root],
library_dirs=[root + '/obj']
)
ffi.cdef(
subprocess.check_output(['gcc', '-I' + root, '-std=c11', '-E', '-'], input=b'''
#define CFFI_CDEF_MODE 1
#define __attribute__(...)
#include <cno/core.h>
extern "Python" {
int on_writev (void *, const struct cno_buffer_t *, size_t);
int on_close (void *);
int on_stream_start (void *, uint32_t);
int on_stream_end (void *, uint32_t, uint32_t, enum CNO_PEER_KIND);
int on_flow_increase (void *, uint32_t);
int on_message_head (void *, uint32_t, const struct cno_message_t *);
int on_message_tail (void *, uint32_t, const struct cno_tail_t *);
int on_message_push (void *, uint32_t, const struct cno_message_t *, uint32_t);
int on_message_data (void *, uint32_t, const char *, size_t);
int on_frame (void *, const struct cno_frame_t *);
int on_frame_send (void *, const struct cno_frame_t *);
int on_pong (void *, const char[8]);
int on_settings (void *);
int on_upgrade (void *, uint32_t);
}
''').decode('utf-8')
)
return ffi
class MakeBuildExtCommand (BuildExtCommand):
def run(self):
subprocess.check_call(['make'])
super().run()
setup(
name='cno',
version='0.1.1',
author='pyos',
author_email='pyos100500@gmail.com',
packages=['cno'],
package_dir={'cno': 'python/cno'},
ext_modules=[make_ffi('.').distutils_extension()],
requires=['cffi (>=1.0.1)'],
cmdclass={'build_ext': MakeBuildExtCommand},
)
| mit |
marbros/Computer-Graphics | Challenge_7/Math/Matrix3x3.java | 3469 | package Math;
/**
* This class handles a 3x3 matrix
* The matrix is used to store the coefficients of a 3x3 linear system of
* 3 equations with 3 unknowns
* @author htrefftz
*/
public class Matrix3x3 {
/** 3 x 3 matrix */
protected double [][] matrix;
private final boolean DEBUG = false;
/**
* Constructs a 3x3 matrix
*/
public Matrix3x3() {
matrix = new double[3][3];
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
matrix[i][j] = 0;
}
}
}
/**
* Constructs a 3x3 matrix
* @param matrix2 matrix2 contains the values to be copied into the new
* Matrix3x3
*/
public Matrix3x3(Matrix3x3 matrix2) {
matrix = new double[3][3];
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
matrix[i][j] = matrix2.matrix[i][j];
}
}
}
/**
* Constructs a 3x3 matrix
* @param m00 element to be stored at position 00
* @param m01 element to be stored at position 01
* @param m02 element to be stored at position 02
* @param m10 element to be stored at position 10
* @param m11 element to be stored at position 11
* @param m12 element to be stored at position 12
* @param m20 element to be stored at position 20
* @param m21 element to be stored at position 21
* @param m22 element to be stored at position 22
*/
public Matrix3x3(double m00, double m01, double m02,
double m10, double m11, double m12,
double m20, double m21, double m22) {
matrix = new double[3][3];
matrix[0][0] = m00; matrix[0][1] = m01; matrix[0][2] = m02;
matrix[1][0] = m10; matrix[1][1] = m11; matrix[1][2] = m12;
matrix[2][0] = m20; matrix[2][1] = m21; matrix[2][2] = m22;
}
/**
* Changes the column vecctor in position "column" for the contents
* of "vector" in the 3x3 "matrix"
* @param matrix original matrix (remains unchanged)
* @param vector vector to insert into the matrix
* @param column position to insert the vector into
* @return
*/
public static Matrix3x3 injectVector(Matrix3x3 matrix, Vector3 vector, int column) {
Matrix3x3 mNew = new Matrix3x3(matrix);
for(int row = 0; row < 3; row++) {
mNew.matrix[row][column] = vector.vector[row];
}
return mNew;
}
/**
* Computes the determinant of a given matrix.
* @param matrix matrix to compute the determinant of.
* @return determinant of the matrix.
*/
public static double determinant(Matrix3x3 matrix) {
double acum = 0d;
acum += matrix.matrix[0][0] * (matrix.matrix[1][1] * matrix.matrix[2][2] - matrix.matrix[1][2] * matrix.matrix[2][1]);
acum -= matrix.matrix[0][1] * (matrix.matrix[1][0] * matrix.matrix[2][2] - matrix.matrix[1][2] * matrix.matrix[2][0]);
acum += matrix.matrix[0][2] * (matrix.matrix[1][0] * matrix.matrix[2][1] - matrix.matrix[1][1] * matrix.matrix[2][0]);
return acum;
}
@Override
public String toString() {
String s = new String();
for(int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
s += this.matrix[row][col] + " ";
}
s += "\n";
}
return s;
}
}
| mit |
PRX/Infrastructure | etc/serverless-s3-upload/lambdas/StaticWebsiteAuthorizerFunction/lambda_function.py | 1077 | # This function is triggered by API Gateway as an authorizer. It uses the HTTP
# basic auth Authorization header to permit access to API Gateway methods by
# returning a policy document when the credentials match those defined as stack
# parameters.
import os
import base64
def lambda_handler(event, context):
headers = event["headers"]
if headers["Authorization"] is None:
return
base_64_credentials = headers["Authorization"].split(" ")[1]
credentials = base64.b64decode(base_64_credentials).decode("utf-8")
username = credentials.split(":")[0]
password = credentials.split(":")[1]
if username != os.environ["BASIC_AUTH_USERNAME"]:
return
if password != os.environ["BASIC_AUTH_PASSWORD"]:
return
return {
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Allow",
"Resource": event["methodArn"],
}
],
}
}
| mit |
atanas-georgiev/TelerikAcademy | 16.ASP.NET-Web-Forms/Homeworks/TestExam/TestExam.Data/Repositories/IRepository.cs | 499 | namespace TestExam.Data.Repositories
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public interface IRepository<T> : IDisposable where T : class
{
IQueryable<T> All();
T GetById(int id);
void Add(T entity);
void Update(T entity);
void Delete(T entity);
void Delete(int id);
void Detach(T entity);
int SaveChanges();
}
}
| mit |
terminalvelocity/soil-cli-example | lib/cli.js | 171 | "use strict"
var Cli = require('soil-cli');
class ExampleCli extends Cli {
constructor(args, options) {
super(args, options);
}
}
module.exports = ExampleCli;
| mit |
plotly/plotly.py | packages/python/plotly/plotly/validators/scattergl/marker/colorbar/_orientation.py | 521 | import _plotly_utils.basevalidators
class OrientationValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self,
plotly_name="orientation",
parent_name="scattergl.marker.colorbar",
**kwargs
):
super(OrientationValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
values=kwargs.pop("values", ["h", "v"]),
**kwargs
)
| mit |
somebee/imba | polyfills/crypto/esm/lib/hash/hash/sha/512.js | 8715 | import * as utils from "../utils";
import * as common from "../common";
import assert from "assert";
'use strict';
var rotr64_hi = utils.rotr64_hi;
var rotr64_lo = utils.rotr64_lo;
var shr64_hi = utils.shr64_hi;
var shr64_lo = utils.shr64_lo;
var sum64 = utils.sum64;
var sum64_hi = utils.sum64_hi;
var sum64_lo = utils.sum64_lo;
var sum64_4_hi = utils.sum64_4_hi;
var sum64_4_lo = utils.sum64_4_lo;
var sum64_5_hi = utils.sum64_5_hi;
var sum64_5_lo = utils.sum64_5_lo;
var BlockHash = common.BlockHash;
var sha512_K = [
0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
];
function SHA512() {
if (!(this instanceof SHA512))
return new SHA512();
BlockHash.call(this);
this.h = [
0x6a09e667, 0xf3bcc908,
0xbb67ae85, 0x84caa73b,
0x3c6ef372, 0xfe94f82b,
0xa54ff53a, 0x5f1d36f1,
0x510e527f, 0xade682d1,
0x9b05688c, 0x2b3e6c1f,
0x1f83d9ab, 0xfb41bd6b,
0x5be0cd19, 0x137e2179
];
this.k = sha512_K;
this.W = new Array(160);
}
utils.inherits(SHA512, BlockHash);
SHA512.blockSize = 1024;
SHA512.outSize = 512;
SHA512.hmacStrength = 192;
SHA512.padLength = 128;
SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
var W = this.W;
// 32 x 32bit words
for (var i = 0; i < 32; i++)
W[i] = msg[start + i];
for (; i < W.length; i += 2) {
var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
var c1_hi = W[i - 14]; // i - 7
var c1_lo = W[i - 13];
var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
var c3_hi = W[i - 32]; // i - 16
var c3_lo = W[i - 31];
W[i] = sum64_4_hi(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo);
W[i + 1] = sum64_4_lo(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo);
}
};
SHA512.prototype._update = function _update(msg, start) {
this._prepareBlock(msg, start);
var W = this.W;
var ah = this.h[0];
var al = this.h[1];
var bh = this.h[2];
var bl = this.h[3];
var ch = this.h[4];
var cl = this.h[5];
var dh = this.h[6];
var dl = this.h[7];
var eh = this.h[8];
var el = this.h[9];
var fh = this.h[10];
var fl = this.h[11];
var gh = this.h[12];
var gl = this.h[13];
var hh = this.h[14];
var hl = this.h[15];
assert(this.k.length === W.length);
for (var i = 0; i < W.length; i += 2) {
var c0_hi = hh;
var c0_lo = hl;
var c1_hi = s1_512_hi(eh, el);
var c1_lo = s1_512_lo(eh, el);
var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
var c3_hi = this.k[i];
var c3_lo = this.k[i + 1];
var c4_hi = W[i];
var c4_lo = W[i + 1];
var T1_hi = sum64_5_hi(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo);
var T1_lo = sum64_5_lo(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo);
c0_hi = s0_512_hi(ah, al);
c0_lo = s0_512_lo(ah, al);
c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
eh = sum64_hi(dh, dl, T1_hi, T1_lo);
el = sum64_lo(dl, dl, T1_hi, T1_lo);
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
}
sum64(this.h, 0, ah, al);
sum64(this.h, 2, bh, bl);
sum64(this.h, 4, ch, cl);
sum64(this.h, 6, dh, dl);
sum64(this.h, 8, eh, el);
sum64(this.h, 10, fh, fl);
sum64(this.h, 12, gh, gl);
sum64(this.h, 14, hh, hl);
};
SHA512.prototype._digest = function digest(enc) {
if (enc === 'hex')
return utils.toHex32(this.h, 'big');
else
return utils.split32(this.h, 'big');
};
function ch64_hi(xh, xl, yh, yl, zh) {
var r = (xh & yh) ^ ((~xh) & zh);
if (r < 0)
r += 0x100000000;
return r;
}
function ch64_lo(xh, xl, yh, yl, zh, zl) {
var r = (xl & yl) ^ ((~xl) & zl);
if (r < 0)
r += 0x100000000;
return r;
}
function maj64_hi(xh, xl, yh, yl, zh) {
var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
if (r < 0)
r += 0x100000000;
return r;
}
function maj64_lo(xh, xl, yh, yl, zh, zl) {
var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
if (r < 0)
r += 0x100000000;
return r;
}
function s0_512_hi(xh, xl) {
var c0_hi = rotr64_hi(xh, xl, 28);
var c1_hi = rotr64_hi(xl, xh, 2); // 34
var c2_hi = rotr64_hi(xl, xh, 7); // 39
var r = c0_hi ^ c1_hi ^ c2_hi;
if (r < 0)
r += 0x100000000;
return r;
}
function s0_512_lo(xh, xl) {
var c0_lo = rotr64_lo(xh, xl, 28);
var c1_lo = rotr64_lo(xl, xh, 2); // 34
var c2_lo = rotr64_lo(xl, xh, 7); // 39
var r = c0_lo ^ c1_lo ^ c2_lo;
if (r < 0)
r += 0x100000000;
return r;
}
function s1_512_hi(xh, xl) {
var c0_hi = rotr64_hi(xh, xl, 14);
var c1_hi = rotr64_hi(xh, xl, 18);
var c2_hi = rotr64_hi(xl, xh, 9); // 41
var r = c0_hi ^ c1_hi ^ c2_hi;
if (r < 0)
r += 0x100000000;
return r;
}
function s1_512_lo(xh, xl) {
var c0_lo = rotr64_lo(xh, xl, 14);
var c1_lo = rotr64_lo(xh, xl, 18);
var c2_lo = rotr64_lo(xl, xh, 9); // 41
var r = c0_lo ^ c1_lo ^ c2_lo;
if (r < 0)
r += 0x100000000;
return r;
}
function g0_512_hi(xh, xl) {
var c0_hi = rotr64_hi(xh, xl, 1);
var c1_hi = rotr64_hi(xh, xl, 8);
var c2_hi = shr64_hi(xh, xl, 7);
var r = c0_hi ^ c1_hi ^ c2_hi;
if (r < 0)
r += 0x100000000;
return r;
}
function g0_512_lo(xh, xl) {
var c0_lo = rotr64_lo(xh, xl, 1);
var c1_lo = rotr64_lo(xh, xl, 8);
var c2_lo = shr64_lo(xh, xl, 7);
var r = c0_lo ^ c1_lo ^ c2_lo;
if (r < 0)
r += 0x100000000;
return r;
}
function g1_512_hi(xh, xl) {
var c0_hi = rotr64_hi(xh, xl, 19);
var c1_hi = rotr64_hi(xl, xh, 29); // 61
var c2_hi = shr64_hi(xh, xl, 6);
var r = c0_hi ^ c1_hi ^ c2_hi;
if (r < 0)
r += 0x100000000;
return r;
}
function g1_512_lo(xh, xl) {
var c0_lo = rotr64_lo(xh, xl, 19);
var c1_lo = rotr64_lo(xl, xh, 29); // 61
var c2_lo = shr64_lo(xh, xl, 6);
var r = c0_lo ^ c1_lo ^ c2_lo;
if (r < 0)
r += 0x100000000;
return r;
}
export default SHA512;
| mit |
bsnape/eir | lib/eir/version.rb | 35 | module Eir
VERSION = '0.2.0'
end
| mit |
gogo-wwc/gogo-wwc | store/modules/products.js | 809 | import shop from '../../api/shop'
import * as types from '../mutation-types'
// initial state
const state = {
all: []
}
// getters
const getters = {
allProducts: state => state.all
}
// actions
const actions = {
getAllProducts ({ commit }) {
shop.fetchProducts().then((products) => {
commit(types.RECEIVE_PRODUCTS, { products })
})
}
}
// mutations
const mutations = {
[types.RECEIVE_PRODUCTS] (state, { products }) {
// state.all is a property of state, see line 6
state.all = products
},
[types.ADD_TO_CART] (state, { id }) {
state.all.find(p => p.id === id).inventory--
},
// Remove from cart
[types.REMOVE_FROM_CART] (state, { id }) {
state.all.find(p => p.id === id).inventory++
}
}
export default {
state,
getters,
actions,
mutations
}
| mit |
j2jensen/CallMeMaybe | CallMeMaybe.UnitTests/MaybeLinqTests.cs | 2131 | using System;
using System.Linq;
using Xunit;
namespace CallMeMaybe.UnitTests
{
public class MaybeLinqTests
{
[Fact]
public void TestNotStringJoin()
{
var q = Maybe.Not;
Assert.Equal("", string.Join(",", q));
}
[Fact]
public void TestSingleLinq()
{
Assert.Equal(1, Maybe.From(1).Single());
Assert.Equal("hi", Maybe.From("hi").Single());
}
[Fact]
public void TestSelectManyLinq()
{
var q =
(from number in Maybe.From(1)
from name in Maybe.From("hi")
select new {number, name})
.Single();
Assert.Equal(1, q.number);
Assert.Equal("hi", q.name);
}
[Fact]
public void TestSelectManyLambda()
{
Assert.Equal("hi", Maybe.From(1).SelectMany(i => Maybe.From("hi")).Single());
Assert.Equal("hi", Maybe.From(Maybe.From("hi")).SelectMany(i => i).Single());
Assert.False(Maybe.From(1).SelectMany(i => Maybe.From((string)null)).HasValue);
Assert.False(Maybe.From((string)null).SelectMany(s => Maybe.From(1)).HasValue);
Assert.False(Maybe.From(Maybe.From((string)null)).SelectMany(s => s).HasValue);
// Make sure selector is not called
Assert.False(Maybe.From((string)null).SelectMany(new Func<string, Maybe<int>>(s => throw new Exception())).HasValue);
}
[Fact]
public void TestWhereLinq()
{
var q =
(from number in Maybe.From(1)
from name in Maybe.From("hi")
select new { number, name })
.Single();
Assert.Equal(1, q.number);
Assert.Equal("hi", q.name);
}
[Fact]
public void TestValuesLinq()
{
var q = new[] {Maybe.From("hi"), Maybe.From((string) null), Maybe.From("world")}
.Values();
Assert.True(q.SequenceEqual(new[]{"hi", "world"}));
}
}
} | mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_import_export/lib/version.rb | 234 | # encoding: utf-8
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
module Azure::ImportExport::Mgmt
VERSION = '0.17.1'
end
| mit |
Mervodactyl/thermostat_front_and_back | src/thermostat.js | 1880 | var Thermostat = function() {
this.DEFAULT_TEMP = 20;
this.currentTemperature = this.DEFAULT_TEMP;
this.MINIMUM_TEMP = 10;
this.isPowerSavingOn = true;
this.LOW_USAGE_LIMIT = 18;
this.MAXIMUM_TEMP = 25;
this.POWER_SAVING_ON_MAXIMUM_TEMP = 25;
this.POWER_SAVING_OFF_MAXIMUM_TEMP = 32;
};
Thermostat.prototype.increaseTemperature = function(degreesToChangeBy) {
if (this.currentTemperature + degreesToChangeBy > this.MAXIMUM_TEMP) {
this.currentTemperature = this.MAXIMUM_TEMP;
} else {
this.currentTemperature += degreesToChangeBy;
}
};
Thermostat.prototype.decreaseTemperature = function(degreesToChangeBy) {
if (this.currentTemperature - degreesToChangeBy < this.MINIMUM_TEMP) {
this.currentTemperature = this.MINIMUM_TEMP;
} else {
this.currentTemperature -= degreesToChangeBy;
}
};
Thermostat.prototype.togglePowerSavingMode = function() {
if (this.isPowerSavingOn === true) {
this.isPowerSavingOn = false;
this.MAXIMUM_TEMP = this.POWER_SAVING_OFF_MAXIMUM_TEMP;
} else {
this.isPowerSavingOn = true;
this.MAXIMUM_TEMP = this.POWER_SAVING_ON_MAXIMUM_TEMP;
this.temperatureLimitSafeguard();
}
};
Thermostat.prototype.temperatureLimitSafeguard = function() {
if (this.currentTemperature > this.MAXIMUM_TEMP) {
this.currentTemperature = this.MAXIMUM_TEMP;
}
};
Thermostat.prototype.energyUsageIndicator = function() {
if (this.currentTemperature < this.LOW_USAGE_LIMIT) {
// this.energyUsageIndicator = 'low-usage';
return "low-usage";
} else if (this.currentTemperature < this.POWER_SAVING_ON_MAXIMUM_TEMP) {
// this.energyUsageIndicator = 'medium-usage';
return "medium-usage";
} else {
// this.energyUsageIndicator = 'high-usage';
return "high-usage";
}
};
Thermostat.prototype.resetTemperature = function() {
this.currentTemperature = this.DEFAULT_TEMP;
};
| mit |
ard71/VotingSoftware | src/main/java/TallyTable.java | 26 | public class TallyTable{
} | mit |
AlephTav/presenters | src/UniversalPresenter.php | 2198 | <?php
/**
* Copyright (c) 2017 Aleph Tav
*
* 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.
*
* @author Aleph Tav <4lephtav@gmail.com>
* @copyright Copyright © 2017 Aleph Tav
* @license http://www.opensource.org/licenses/MIT
*/
namespace AlephTools\Data\Presenters;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
/**
* Used to present data of any (arrayable) type.
*
* @author Aleph Tav <4lephtav@gmail.com>
* @version 1.0.0
* @package alephtools.data.presenters
*/
class UniversalPresenter extends ArrayPresenter
{
/**
* Constructor.
*
* @param mixed $data Data to present.
* @access public
* @throws \InvalidArgumentException
*/
public function __construct($data)
{
if (is_object($data)) {
if (method_exists($data, 'toArray')) {
$data = $data->toArray();
} else {
$data = (array)$data;
}
} else if (!is_array($data)) {
throw new \InvalidArgumentException('Data must only be an object or array. ' . gettype($data) . ' was given.');
}
parent::__construct($data);
}
} | mit |
preslavc/SoftUni | Programming Fundamentals/Objects and Classes/Lab/Randomize Words/Program.cs | 735 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Randomize_Words
{
class Program
{
static void Main(string[] args)
{
string[] words = Console.ReadLine().Split(' ');
Random rnd = new Random();
for (int i = 0; i < words.Length; i++)
{
int position = rnd.Next(words.Length);
if (position != i)
{
var temp = words[i];
words[i] = words[position];
words[position] = temp;
}
}
Console.WriteLine(string.Join("\n", words));
}
}
}
| mit |
Prezent/prezent-dompdf-bundle | Creator/Creator.php | 4374 | <?php
namespace Prezent\DompdfBundle\Creator;
use Dompdf\Dompdf;
use Dompdf\Options;
/**
* Abstract creator class. Initializes the Dompdf instance
*
* @author Robert-Jan Bijl<robert-jan@prezent.nl>
*/
abstract class Creator implements CreatorInterface
{
/**
* @var Dompdf
*/
protected $pdf;
/**
* @var Options
*/
protected $options;
/**
* @var string
*/
protected $configFile;
/**
* @var string
*/
protected $orientation = 'portrait';
/**
* @var string
*/
protected $paperSize = 'a4';
/**
* Whether or not the pdf is rendered
*
* @var bool
*/
protected $rendered = false;
/**
* Constructor
* @param $configFile
*/
public function __construct($configFile = null)
{
$this->configFile = $configFile;
}
/**
* Initialize the configuration
*
* @return true
*/
public function initialize()
{
if (file_exists($this->configFile)) {
require_once $this->configFile;
}
$this->options = new Options();
// legacy 0.6.2 support, WARNING: not all old properties are supported
if (defined('DOMPDF_CHROOT')) {
$this->options->setChroot(DOMPDF_CHROOT);
}
if (defined('DOMPDF_DIR')) {
$this->options->setRootDir(DOMPDF_DIR);
}
if (defined('DOMPDF_TEMP_DIR')) {
$this->options->setTempDir(DOMPDF_TEMP_DIR);
}
if (defined('DOMPDF_FONT_DIR')) {
$this->options->setFontDir(DOMPDF_FONT_DIR);
}
if (defined('DOMPDF_FONT_CACHE')) {
$this->options->setFontCache(DOMPDF_FONT_CACHE);
}
if (defined('DOMPDF_LOG_OUTPUT_FILE')) {
$this->options->setLogOutputFile(DOMPDF_LOG_OUTPUT_FILE);
}
if (defined('DOMPDF_DPI')) {
$this->options->setDpi(DOMPDF_DPI);
}
if (defined('DOMPDF_DEFAULT_PAPER_SIZE')) {
$this->options->setDefaultPaperSize(DOMPDF_DEFAULT_PAPER_SIZE);
}
if (defined('DOMPDF_DEFAULT_PAPER_SIZE')) {
$this->options->setDefaultPaperOrientation(DOMPDF_DEFAULT_PAPER_SIZE);
}
if (defined('DOMPDF_ENABLE_REMOTE')) {
$this->options->setIsRemoteEnabled(DOMPDF_ENABLE_REMOTE);
}
if (defined('DOMPDF_ENABLE_PHP')) {
$this->options->setIsPhpEnabled(DOMPDF_ENABLE_PHP);
}
if (defined('DOMPDF_DEFAULT_FONT')) {
$this->options->setDefaultFont(DOMPDF_DEFAULT_FONT);
}
if (defined('DOMPDF_FONT_HEIGHT_RATIO')) {
$this->options->setFontHeightRatio(DOMPDF_FONT_HEIGHT_RATIO);
}
return true;
}
/**
* {@inheritDoc}
*/
abstract public function render();
/**
* @return Options
*/
public function getOptions()
{
return $this->options;
}
/**
* Stream the pdf document
*
* @param string $fileName The name of the document
* @return bool
*/
public function stream($fileName)
{
if (!$this->rendered) {
$this->render();
}
$this->pdf->stream($fileName);
return true;
}
/**
* Get the raw pdf output
*
* @return string
*/
public function output()
{
if (!$this->rendered) {
$this->render();
}
return $this->pdf->output();
}
/**
* Getter for orientation
*
* @return string
*/
public function getOrientation()
{
return $this->options->getDefaultPaperOrientation();
}
/**
* Setter for orientation
*
* @param string $orientation
* @return self
*/
public function setOrientation($orientation)
{
$this->options->setDefaultPaperOrientation($orientation);
return $this;
}
/**
* Getter for paperSize
*
* @return string
*/
public function getPaperSize()
{
return $this->options->getDefaultPaperSize();
}
/**
* Setter for paperSize
*
* @param string $paperSize
* @return self
*/
public function setPaperSize($paperSize)
{
$this->options->setDefaultPaperSize($paperSize);
return $this;
}
}
| mit |
andyroberts007/3Slice | node_modules/save/node_modules/mingo/mingo.js | 59800 | // Mingo.js 0.6.2
// Copyright (c) 2015 Francis Asante <kofrasa@gmail.com>
// MIT
;
(function (root, undefined) {
"use strict";
// global on the server, window in the browser
var Mingo = {}, previousMingo;
var _;
Mingo.VERSION = '0.6.2';
// backup previous Mingo
if (root != null) {
previousMingo = root.Mingo;
}
Mingo.noConflict = function () {
root.Mingo = previousMingo;
return Mingo;
};
var nodeEnabled = ('undefined' !== typeof module && 'undefined' !== typeof require);
// Export the Mingo object for Node.js
if (nodeEnabled) {
if (typeof module !== 'undefined') {
module.exports = Mingo;
}
_ = require("underscore"); // get a reference to underscore
} else {
root.Mingo = Mingo;
_ = root._; // get a reference to underscore
}
// quick reference for
var primitives = [
_.isString, _.isBoolean, _.isNumber, _.isDate, _.isNull, _.isRegExp
];
function isPrimitive(value) {
for (var i = 0; i < primitives.length; i++) {
if (primitives[i](value)) {
return true;
}
}
return false;
}
/**
* Simplify expression for easy evaluation with query operators map
* @param expr
* @returns {*}
*/
function normalize(expr) {
// normalized primitives
if (isPrimitive(expr)) {
return _.isRegExp(expr) ? {"$regex": expr} : {"$eq": expr};
}
// normalize object expression
if (_.isObject(expr)) {
var keys = _.keys(expr);
var notQuery = _.intersection(ops(OP_QUERY), keys).length === 0;
// no valid query operator found, so we do simple comparison
if (notQuery) {
return {"$eq": expr};
}
// ensure valid regex
if (_.contains(keys, "$regex")) {
var regex = expr['$regex'];
var options = expr['$options'] || "";
var modifiers = "";
if (_.isString(regex)) {
modifiers += (regex.ignoreCase || options.indexOf("i") >= 0) ? "i" : "";
modifiers += (regex.multiline || options.indexOf("m") >= 0) ? "m" : "";
modifiers += (regex.global || options.indexOf("g") >= 0) ? "g" : "";
regex = new RegExp(regex, modifiers);
}
expr['$regex'] = regex;
delete expr['$options'];
}
}
return expr;
}
// Settings used by Mingo internally
var settings = {
key: "_id"
};
/**
* Setup default settings for Mingo
* @param options
*/
Mingo.setup = function (options) {
_.extend(settings, options || {});
};
/**
* Query object to test collection elements with
* @param criteria the pass criteria for the query
* @param projection optional projection specifiers
* @constructor
*/
Mingo.Query = function (criteria, projection) {
if (!(this instanceof Mingo.Query))
return new Mingo.Query(criteria, projection);
this._criteria = criteria;
this._projection = projection;
this._compiled = [];
this._compile();
};
Mingo.Query.prototype = {
_compile: function () {
if (_.isEmpty(this._criteria)) return;
if (_.isArray(this._criteria) || _.isFunction(this._criteria) || !_.isObject(this._criteria)) {
throw new Error("Invalid type for criteria");
}
for (var field in this._criteria) {
if (this._criteria.hasOwnProperty(field)) {
var expr = this._criteria[field];
if (_.contains(['$and', '$or', '$nor', '$where'], field)) {
this._processOperator(field, field, expr);
} else {
// normalize expression
expr = normalize(expr);
for (var op in expr) {
if (expr.hasOwnProperty(op)) {
this._processOperator(field, op, expr[op]);
}
}
}
}
}
},
_processOperator: function (field, operator, value) {
if (_.contains(ops(OP_QUERY), operator)) {
this._compiled.push(queryOperators[operator](field, value));
} else {
throw new Error("Invalid query operator '" + operator + "' detected");
}
},
/**
* Checks if the object passes the query criteria. Returns true if so, false otherwise.
* @param obj
* @returns {boolean}
*/
test: function (obj) {
for (var i = 0; i < this._compiled.length; i++) {
if (!this._compiled[i].test(obj)) {
return false;
}
}
return true;
},
/**
* Performs a query on a collection and returns a cursor object.
* @param collection
* @param projection
* @returns {Mingo.Cursor}
*/
find: function (collection, projection) {
return new Mingo.Cursor(collection, this, projection);
},
/**
* Remove matched documents from the collection returning the remainder
* @param collection
* @returns {Array}
*/
remove: function (collection) {
var arr = [];
for (var i = 0; i < collection.length; i++) {
if (!this.test(collection[i])) {
arr.push(collection[i]);
}
}
return arr;
}
};
if (nodeEnabled) {
var Transform = require('stream').Transform;
var util = require('util');
Mingo.Query.prototype.stream = function (options) {
return new Mingo.Stream(this, options);
};
/**
* Create a Transform class
* @param query
* @param options
* @returns {Mingo.Stream}
* @constructor
*/
Mingo.Stream = function (query, options) {
if (!(this instanceof Mingo.Stream))
return new Mingo.Stream(query, options);
options = options || {};
_.extend(options, {objectMode: true});
Transform.call(this, options);
// query for this stream
this._query = query;
};
// extend Transform
util.inherits(Mingo.Stream, Transform);
Mingo.Stream.prototype._transform = function (chunk, encoding, done) {
if (_.isObject(chunk) && this._query.test(chunk)) {
if (_.isEmpty(this._query._projection)) {
this.push(chunk);
} else {
var cursor = new Mingo.Cursor([chunk], this._query);
if (cursor.hasNext()) {
this.push(cursor.next());
}
}
}
done();
};
}
/**
* Cursor to iterate and perform filtering on matched objects
* @param collection
* @param query
* @param projection
* @constructor
*/
Mingo.Cursor = function (collection, query, projection) {
if (!(this instanceof Mingo.Cursor))
return new Mingo.Cursor(collection, query, projection);
this._query = query;
this._collection = collection;
this._projection = projection || query._projection;
this._operators = {};
this._result = false;
this._position = 0;
};
Mingo.Cursor.prototype = {
_fetch: function () {
var self = this;
if (this._result !== false) {
return this._result;
}
// inject projection operator
if (_.isObject(this._projection)) {
_.extend(this._operators, {"$project": this._projection});
}
if (!_.isArray(this._collection)) {
throw new Error("Input collection is not of valid type. Must be an Array.");
}
// filter collection
this._result = _.filter(this._collection, this._query.test, this._query);
var pipeline = [];
_.each(['$sort', '$skip', '$limit', '$project'], function (op) {
if (_.has(self._operators, op)) {
pipeline.push(_.pick(self._operators, op));
}
});
if (pipeline.length > 0) {
var aggregator = new Mingo.Aggregator(pipeline);
this._result = aggregator.run(this._result, this._query);
}
return this._result;
},
/**
* Fetch and return all matched results
* @returns {Array}
*/
all: function () {
return this._fetch();
},
/**
* Fetch and return the first matching result
* @returns {Object}
*/
first: function () {
return this.count() > 0 ? this._fetch()[0] : null;
},
/**
* Fetch and return the last matching object from the result
* @returns {Object}
*/
last: function () {
return this.count() > 0 ? this._fetch()[this.count() - 1] : null;
},
/**
* Counts the number of matched objects found
* @returns {Number}
*/
count: function () {
return this._fetch().length;
},
/**
* Returns a cursor that begins returning results only after passing or skipping a number of documents.
* @param {Number} n the number of results to skip.
* @return {Mingo.Cursor} Returns the cursor, so you can chain this call.
*/
skip: function (n) {
_.extend(this._operators, {"$skip": n});
return this;
},
/**
* Constrains the size of a cursor's result set.
* @param {Number} n the number of results to limit to.
* @return {Mingo.Cursor} Returns the cursor, so you can chain this call.
*/
limit: function (n) {
_.extend(this._operators, {"$limit": n});
return this;
},
/**
* Returns results ordered according to a sort specification.
* @param {Object} modifier an object of key and values specifying the sort order. 1 for ascending and -1 for descending
* @return {Mingo.Cursor} Returns the cursor, so you can chain this call.
*/
sort: function (modifier) {
_.extend(this._operators, {"$sort": modifier});
return this;
},
/**
* Returns the next document in a cursor.
* @returns {Object | Boolean}
*/
next: function () {
if (this.hasNext()) {
return this._fetch()[this._position++];
}
return null;
},
/**
* Returns true if the cursor has documents and can be iterated.
* @returns {boolean}
*/
hasNext: function () {
return this.count() > this._position;
},
/**
* Specifies the exclusive upper bound for a specific field
* @param expr
* @returns {Number}
*/
max: function (expr) {
return groupOperators.$max(this._fetch(), expr);
},
/**
* Specifies the inclusive lower bound for a specific field
* @param expr
* @returns {Number}
*/
min: function (expr) {
return groupOperators.$min(this._fetch(), expr);
},
/**
* Applies a function to each document in a cursor and collects the return values in an array.
* @param callback
* @returns {Array}
*/
map: function (callback) {
return _.map(this._fetch(), callback);
},
/**
* Applies a JavaScript function for every document in a cursor.
* @param callback
*/
forEach: function (callback) {
_.each(this._fetch(), callback);
}
};
/**
* Aggregator for defining filter using mongoDB aggregation pipeline syntax
* @param operators an Array of pipeline operators
* @constructor
*/
Mingo.Aggregator = function (operators) {
if (!(this instanceof Mingo.Aggregator))
return new Mingo.Aggregator(operators);
this._operators = operators;
};
Mingo.Aggregator.prototype = {
/**
* Apply the pipeline operations over the collection by order of the sequence added
* @param collection an array of objects to process
* @param query the `Mingo.Query` object to use as context
* @returns {Array}
*/
run: function (collection, query) {
if (!_.isEmpty(this._operators)) {
// run aggregation pipeline
for (var i = 0; i < this._operators.length; i++) {
var operator = this._operators[i];
var key = _.keys(operator);
if (key.length == 1 && _.contains(ops(OP_PIPELINE), key[0])) {
key = key[0];
if (query instanceof Mingo.Query) {
collection = pipelineOperators[key].call(query, collection, operator[key]);
} else {
collection = pipelineOperators[key](collection, operator[key]);
}
} else {
throw new Error("Invalid aggregation operator '" + key + "'");
}
}
}
return collection;
}
};
/**
* Retrieve the value of a given key on an object
* @param obj
* @param field
* @returns {*}
* @private
*/
function getValue(obj, field) {
return _.result(obj, field);
}
/**
* Resolve the value of the field (dot separated) on the given object
* @param obj
* @param field
* @returns {*}
*/
function resolve(obj, field) {
if (!field) {
return undefined;
}
var names = field.split(".");
var value = obj;
var isText;
for (var i = 0; i < names.length; i++) {
isText = names[i].match(/^\d+$/) === null;
if (isText && _.isArray(value)) {
var res = [];
_.each(value, function (item) {
res.push(resolve(item, names[i]));
});
value = res;
} else {
value = getValue(value, names[i]);
}
if (value === undefined) {
break;
}
}
return value;
}
/**
* Performs a query on a collection and returns a cursor object.
* @param collection
* @param criteria
* @param projection
* @returns {Mingo.Cursor}
*/
Mingo.find = function (collection, criteria, projection) {
return (new Mingo.Query(criteria)).find(collection, projection);
};
/**
* Returns a new array without objects which match the criteria
* @param collection
* @param criteria
* @returns {Array}
*/
Mingo.remove = function (collection, criteria) {
return (new Mingo.Query(criteria)).remove(collection);
};
/**
* Return the result collection after running the aggregation pipeline for the given collection
* @param collection
* @param pipeline
* @returns {Array}
*/
Mingo.aggregate = function (collection, pipeline) {
if (!_.isArray(pipeline)) {
throw new Error("Aggregation pipeline must be an array");
}
return (new Mingo.Aggregator(pipeline)).run(collection);
};
/**
* Add new operators
* @param type the operator type to extend
* @param f a function returning an object of new operators
*/
Mingo.addOperators = function (type, f) {
var newOperators = f({
resolve: resolve,
computeValue: computeValue,
ops: ops,
key: function () {
return settings.key;
}
});
// ensure correct type specified
if (!_.contains([OP_AGGREGATE, OP_GROUP, OP_PIPELINE, OP_PROJECTION, OP_QUERY], type)) {
throw new Error("Could not identify type '" + type + "'");
}
var operators = ops(type);
// check for existing operators
_.each(_.keys(newOperators), function (op) {
if (!/^\$\w+$/.test(op)) {
throw new Error("Invalid operator name '" + op + "'");
}
if (_.contains(operators, op)) {
throw new Error("Operator " + op + " is already defined for " + type + " operators");
}
});
var wrapped = {};
switch (type) {
case OP_QUERY:
_.each(_.keys(newOperators), function (op) {
wrapped[op] = (function (f, ctx) {
return function (selector, value) {
return {
test: function (obj) {
// value of field must be fully resolved.
var lhs = resolve(obj, selector);
var result = f.call(ctx, selector, lhs, value);
if (_.isBoolean(result)) {
return result;
} else if (result instanceof Mingo.Query) {
return result.test(obj);
} else {
throw new Error("Invalid return type for '" + op + "'. Must return a Boolean or Mingo.Query");
}
}
};
}
}(newOperators[op], newOperators));
});
break;
case OP_PROJECTION:
_.each(_.keys(newOperators), function (op) {
wrapped[op] = (function (f, ctx) {
return function (obj, expr, selector) {
var lhs = resolve(obj, selector);
return f.call(ctx, selector, lhs, expr);
}
}(newOperators[op], newOperators));
});
break;
default:
_.each(_.keys(newOperators), function (op) {
wrapped[op] = (function (f, ctx) {
return function () {
var args = Array.prototype.slice.call(arguments);
return f.apply(ctx, args);
}
}(newOperators[op], newOperators));
});
}
// toss the operator salad :)
_.extend(OPERATORS[type], wrapped);
};
/**
* Mixin for Backbone.Collection objects
*/
Mingo.CollectionMixin = {
/**
* Runs a query and returns a cursor to the result
* @param criteria
* @param projection
* @returns {Mingo.Cursor}
*/
query: function (criteria, projection) {
return Mingo.find(this.toJSON(), criteria, projection);
},
/**
* Runs the given aggregation operators on this collection
* @params pipeline
* @returns {Array}
*/
aggregate: function (pipeline) {
var args = [this.toJSON(), pipeline];
return Mingo.aggregate.apply(null, args);
}
};
var pipelineOperators = {
/**
* Groups documents together for the purpose of calculating aggregate values based on a collection of documents.
*
* @param collection
* @param expr
* @returns {Array}
*/
$group: function (collection, expr) {
// lookup key for grouping
var idKey = expr[settings.key];
var partitions = groupBy(collection, function (obj) {
return computeValue(obj, idKey, idKey);
});
var result = [];
// remove the group key
expr = _.omit(expr, settings.key);
_.each(partitions.keys, function (value, i) {
var obj = {};
// exclude undefined key value
if (!_.isUndefined(value)) {
obj[settings.key] = value;
}
// compute remaining keys in expression
for (var key in expr) {
if (expr.hasOwnProperty(key)) {
obj[key] = accumulate(partitions.groups[i], key, expr[key]);
}
}
result.push(obj);
});
return result;
},
/**
* Filters the document stream, and only allows matching documents to pass into the next pipeline stage.
* $match uses standard MongoDB queries.
*
* @param collection
* @param expr
* @returns {Array|*}
*/
$match: function (collection, expr) {
return (new Mingo.Query(expr)).find(collection).all();
},
/**
* Reshapes a document stream.
* $project can rename, add, or remove fields as well as create computed values and sub-documents.
*
* @param collection
* @param expr
* @returns {Array}
*/
$project: function (collection, expr) {
if (_.isEmpty(expr)) {
return collection;
}
// result collection
var projected = [];
var objKeys = _.keys(expr);
var idOnlyExcludedExpression = false;
if (_.contains(objKeys, settings.key)) {
var id = expr[settings.key];
if (id === 0 || id === false) {
objKeys = _.without(objKeys, settings.key);
if (_.isEmpty(objKeys)) {
idOnlyExcludedExpression = true;
}
}
} else {
// if not specified the add the ID field
objKeys.push(settings.key);
}
for (var i = 0; i < collection.length; i++) {
var obj = collection[i];
var cloneObj = {};
var foundSlice = false;
var foundExclusion = false;
var dropKeys = [];
if (idOnlyExcludedExpression) {
dropKeys.push(settings.key);
}
_.each(objKeys, function (key) {
var subExpr = expr[key];
var newValue;
if (key !== settings.key && subExpr === 0) {
foundExclusion = true;
}
// tiny optimization here to skip over id
if (key === settings.key && _.isEmpty(subExpr)) {
newValue = obj[key];
} else if (_.isString(subExpr)) {
newValue = computeValue(obj, subExpr, key);
} else if (subExpr === 1 || subExpr === true) {
newValue = _.result(obj, key);
} else if (_.isObject(subExpr)) {
var operator = _.keys(subExpr);
operator = operator.length > 1 ? false : operator[0];
if (operator !== false && _.contains(ops(OP_PROJECTION), operator)) {
// apply the projection operator on the operator expression for the key
var temp = projectionOperators[operator](obj, subExpr[operator], key);
if (!_.isUndefined(temp)) {
newValue = temp;
}
if (operator == '$slice') {
foundSlice = true;
}
} else {
// compute the value for the sub expression for the key
newValue = computeValue(obj, subExpr, key);
}
} else {
dropKeys.push(key);
}
if (!_.isUndefined(newValue)) {
cloneObj[key] = newValue;
}
});
// if projection included $slice operator
// Also if exclusion fields are found or we want to exclude only the id field
// include keys that were not explicitly excluded
if (foundSlice || foundExclusion || idOnlyExcludedExpression) {
cloneObj = _.defaults(cloneObj, _.omit(obj, dropKeys));
}
projected.push(cloneObj);
}
return projected;
},
/**
* Restricts the number of documents in an aggregation pipeline.
*
* @param collection
* @param value
* @returns {Object|*}
*/
$limit: function (collection, value) {
return _.first(collection, value);
},
/**
* Skips over a specified number of documents from the pipeline and returns the rest.
*
* @param collection
* @param value
* @returns {*}
*/
$skip: function (collection, value) {
return _.rest(collection, value);
},
/**
* Takes an array of documents and returns them as a stream of documents.
*
* @param collection
* @param expr
* @returns {Array}
*/
$unwind: function (collection, expr) {
var result = [];
var field = expr.substr(1);
for (var i = 0; i < collection.length; i++) {
var obj = collection[i];
// must throw an error if value is not an array
var value = getValue(obj, field);
if (_.isArray(value)) {
_.each(value, function (item) {
var tmp = _.clone(obj);
tmp[field] = item;
result.push(tmp);
});
} else {
throw new Error("Target field '" + field + "' is not of type Array.");
}
}
return result;
},
/**
* Takes all input documents and returns them in a stream of sorted documents.
*
* @param collection
* @param sortKeys
* @returns {*}
*/
$sort: function (collection, sortKeys) {
if (!_.isEmpty(sortKeys) && _.isObject(sortKeys)) {
var modifiers = _.keys(sortKeys);
modifiers.reverse().forEach(function (key) {
var indexes = [];
var grouped = _.groupBy(collection, function (obj) {
var value = resolve(obj, key);
indexes.push(value);
return value;
});
indexes = _.sortBy(_.uniq(indexes), function (item) {
return item;
});
if (sortKeys[key] === -1) {
indexes.reverse();
}
collection = [];
_.each(indexes, function (item) {
Array.prototype.push.apply(collection, grouped[item]);
});
});
}
return collection;
}
};
////////// QUERY OPERATORS //////////
var queryOperators = {};
var compoundOperators = {
/**
* Joins query clauses with a logical AND returns all documents that match the conditions of both clauses.
*
* @param selector
* @param value
* @returns {{test: Function}}
*/
$and: function (selector, value) {
if (!_.isArray(value)) {
throw new Error("Invalid expression for $and criteria");
}
var queries = [];
_.each(value, function (expr) {
queries.push(new Mingo.Query(expr));
});
return {
test: function (obj) {
for (var i = 0; i < queries.length; i++) {
if (!queries[i].test(obj)) {
return false;
}
}
return true;
}
};
},
/**
* Joins query clauses with a logical OR returns all documents that match the conditions of either clause.
*
* @param selector
* @param value
* @returns {{test: Function}}
*/
$or: function (selector, value) {
if (!_.isArray(value)) {
throw new Error("Invalid expression for $or criteria");
}
var queries = [];
_.each(value, function (expr) {
queries.push(new Mingo.Query(expr));
});
return {
test: function (obj) {
for (var i = 0; i < queries.length; i++) {
if (queries[i].test(obj)) {
return true;
}
}
return false;
}
};
},
/**
* Joins query clauses with a logical NOR returns all documents that fail to match both clauses.
*
* @param selector
* @param value
* @returns {{test: Function}}
*/
$nor: function (selector, value) {
if (!_.isArray(value)) {
throw new Error("Invalid expression for $nor criteria");
}
var query = this.$or("$or", value);
return {
test: function (obj) {
return !query.test(obj);
}
};
},
/**
* Inverts the effect of a query expression and returns documents that do not match the query expression.
*
* @param selector
* @param value
* @returns {{test: Function}}
*/
$not: function (selector, value) {
var criteria = {};
criteria[selector] = normalize(value);
var query = new Mingo.Query(criteria);
return {
test: function (obj) {
return !query.test(obj);
}
};
},
/**
* Matches documents that satisfy a JavaScript expression.
*
* @param selector
* @param value
* @returns {{test: test}}
*/
$where: function (selector, value) {
if (!_.isFunction(value)) {
value = new Function("return " + value + ";");
}
return {
test: function (obj) {
return value.call(obj) === true;
}
};
}
};
// add compound query operators
_.extend(queryOperators, compoundOperators);
var simpleOperators = {
/**
* Checks that two values are equal. Pseudo operator introduced for convenience and consistency
*
* @param a
* @param b
* @returns {*}
*/
$eq: function (a, b) {
// flatten to reach nested values. fix for https://github.com/kofrasa/mingo/issues/19
a = _.flatten(_.isArray(a) ? a : [a]);
a = _.find(a, function (val) {
return _.isEqual(val, b);
});
return a !== undefined;
},
/**
* Matches all values that are not equal to the value specified in the query.
*
* @param a
* @param b
* @returns {boolean}
*/
$ne: function (a, b) {
return !this.$eq(a, b);
},
/**
* Matches any of the values that exist in an array specified in the query.
*
* @param a
* @param b
* @returns {*}
*/
$in: function (a, b) {
a = _.isArray(a) ? a : [a];
return _.intersection(a, b).length > 0;
},
/**
* Matches values that do not exist in an array specified to the query.
*
* @param a
* @param b
* @returns {*|boolean}
*/
$nin: function (a, b) {
return _.isUndefined(a) || !this.$in(a, b);
},
/**
* Matches values that are less than the value specified in the query.
*
* @param a
* @param b
* @returns {boolean}
*/
$lt: function (a, b) {
a = _.isArray(a) ? a : [a];
a = _.find(a, function (val) {
return val < b
});
return a !== undefined;
},
/**
* Matches values that are less than or equal to the value specified in the query.
*
* @param a
* @param b
* @returns {boolean}
*/
$lte: function (a, b) {
a = _.isArray(a) ? a : [a];
a = _.find(a, function (val) {
return val <= b
});
return a !== undefined;
},
/**
* Matches values that are greater than the value specified in the query.
*
* @param a
* @param b
* @returns {boolean}
*/
$gt: function (a, b) {
a = _.isArray(a) ? a : [a];
a = _.find(a, function (val) {
return val > b
});
return a !== undefined;
},
/**
* Matches values that are greater than or equal to the value specified in the query.
*
* @param a
* @param b
* @returns {boolean}
*/
$gte: function (a, b) {
a = _.isArray(a) ? a : [a];
a = _.find(a, function (val) {
return val >= b
});
return a !== undefined;
},
/**
* Performs a modulo operation on the value of a field and selects documents with a specified result.
*
* @param a
* @param b
* @returns {*|boolean|boolean}
*/
$mod: function (a, b) {
a = _.isArray(a) ? a : [a];
a = _.find(a, function (val) {
return _.isNumber(val) && _.isArray(b) && b.length === 2 && (val % b[0]) === b[1];
});
return a !== undefined;
},
/**
* Selects documents where values match a specified regular expression.
*
* @param a
* @param b
* @returns {*|boolean}
*/
$regex: function (a, b) {
a = _.isArray(a) ? a : [a];
a = _.find(a, function (val) {
return _.isString(val) && _.isRegExp(b) && (!!val.match(b));
});
return a !== undefined;
},
/**
* Matches documents that have the specified field.
*
* @param a
* @param b
* @returns {boolean|*|boolean}
*/
$exists: function (a, b) {
return (b === false && _.isUndefined(a)) || (b === true && !_.isUndefined(a));
},
/**
* Matches arrays that contain all elements specified in the query.
*
* @param a
* @param b
* @returns boolean
*/
$all: function (a, b) {
var self = this;
var matched = false;
if (_.isArray(a) && _.isArray(b)) {
for (var i = 0; i < b.length; i++) {
if (_.isObject(b[i]) && _.contains(_.keys(b[i]), "$elemMatch")) {
matched = matched || self.$elemMatch(a, b[i].$elemMatch);
} else {
// order of arguments matter. underscore maintains order after intersection
return _.intersection(b, a).length === b.length;
}
}
}
return matched;
},
/**
* Selects documents if the array field is a specified size.
*
* @param a
* @param b
* @returns {*|boolean}
*/
$size: function (a, b) {
return _.isArray(a) && _.isNumber(b) && (a.length === b);
},
/**
* Selects documents if element in the array field matches all the specified $elemMatch condition.
*
* @param a
* @param b
*/
$elemMatch: function (a, b) {
if (_.isArray(a) && !_.isEmpty(a)) {
var query = new Mingo.Query(b);
for (var i = 0; i < a.length; i++) {
if (query.test(a[i])) {
return true;
}
}
}
return false;
},
/**
* Selects documents if a field is of the specified type.
*
* @param a
* @param b
* @returns {boolean}
*/
$type: function (a, b) {
switch (b) {
case 1:
return _.isNumeric(a) && (a + "").indexOf(".") !== -1;
case 2:
case 5:
return _.isString(a);
case 3:
return _.isObject(a);
case 4:
return _.isArray(a);
case 8:
return _.isBoolean(a);
case 9:
return _.isDate(a);
case 10:
return _.isNull(a);
case 11:
return _.isRegExp(a);
case 16:
return _.isNumeric(a) && a <= 2147483647 && (a + "").indexOf(".") === -1;
case 18:
return _.isNumeric(a) && a > 2147483647 && a <= 9223372036854775807 && (a + "").indexOf(".") === -1;
default:
return false;
}
}
};
// add simple query operators
_.each(_.keys(simpleOperators), function (op) {
queryOperators[op] = (function (f, ctx) {
return function (selector, value) {
return {
test: function (obj) {
// value of field must be fully resolved.
var lhs = resolve(obj, selector);
return f.call(ctx, lhs, value);
}
};
}
}(simpleOperators[op], simpleOperators));
});
var projectionOperators = {
/**
* Projects the first element in an array that matches the query condition.
*
* @param obj
* @param field
* @param expr
*/
$: function (obj, expr, field) {
throw new Error("$ not implemented");
},
/**
* Projects only the first element from an array that matches the specified $elemMatch condition.
*
* @param obj
* @param field
* @param expr
* @returns {*}
*/
$elemMatch: function (obj, expr, field) {
var array = resolve(obj, field);
var query = new Mingo.Query(expr);
if (_.isUndefined(array) || !_.isArray(array)) {
return undefined;
}
for (var i = 0; i < array.length; i++) {
if (query.test(array[i])) {
return [array[i]];
}
}
return undefined;
},
/**
* Limits the number of elements projected from an array. Supports skip and limit slices.
*
* @param obj
* @param field
* @param expr
*/
$slice: function (obj, expr, field) {
var array = resolve(obj, field);
if (!_.isArray(array)) {
return array;
}
if (!_.isArray(expr)) {
if (!_.isNumber(expr)) {
throw new Error("Invalid type for $slice operator");
}
expr = expr < 0 ? [expr] : [0, expr];
} else {
// MongoDB $slice works a bit differently from Array.slice
// Uses single argument for 'limit' and array argument [skip, limit]
var skip = (expr[0] < 0) ? array.length + expr[0] : expr;
var limit = skip + expr[1];
expr = [skip, limit];
}
return Array.prototype.slice.apply(array, expr);
}
};
var groupOperators = {
/**
* Returns an array of all the unique values for the selected field among for each document in that group.
*
* @param collection
* @param expr
* @returns {*}
*/
$addToSet: function (collection, expr) {
var result = _.map(collection, function (obj) {
return computeValue(obj, expr, null);
});
return _.uniq(result);
},
/**
* Returns the sum of all the values in a group.
*
* @param collection
* @param expr
* @returns {*}
*/
$sum: function (collection, expr) {
if (!_.isArray(collection)) {
return 0;
}
if (_.isNumber(expr)) {
// take a short cut if expr is number literal
return collection.length * expr;
}
return _.reduce(collection, function (acc, obj) {
// pass empty field to avoid naming conflicts with fields on documents
return acc + computeValue(obj, expr, null);
}, 0);
},
/**
* Returns the highest value in a group.
*
* @param collection
* @param expr
* @returns {*}
*/
$max: function (collection, expr) {
var obj = _.max(collection, function (obj) {
return computeValue(obj, expr, null);
});
return computeValue(obj, expr, null);
},
/**
* Returns the lowest value in a group.
*
* @param collection
* @param expr
* @returns {*}
*/
$min: function (collection, expr) {
var obj = _.min(collection, function (obj) {
return computeValue(obj, expr, null);
});
return computeValue(obj, expr, null);
},
/**
* Returns an average of all the values in a group.
*
* @param collection
* @param expr
* @returns {number}
*/
$avg: function (collection, expr) {
return this.$sum(collection, expr) / (collection.length || 1);
},
/**
* Returns an array of all values for the selected field among for each document in that group.
*
* @param collection
* @param expr
* @returns {Array|*}
*/
$push: function (collection, expr) {
return _.map(collection, function (obj) {
return computeValue(obj, expr, null);
});
},
/**
* Returns the first value in a group.
*
* @param collection
* @param expr
* @returns {*}
*/
$first: function (collection, expr) {
return (collection.length > 0) ? computeValue(collection[0], expr) : undefined;
},
/**
* Returns the last value in a group.
*
* @param collection
* @param expr
* @returns {*}
*/
$last: function (collection, expr) {
return (collection.length > 0) ? computeValue(collection[collection.length - 1], expr) : undefined;
}
};
/////////// Aggregation Operators ///////////
var arithmeticOperators = {
/**
* Computes the sum of an array of numbers.
*
* @param obj
* @param expr
* @returns {Object}
*/
$add: function (obj, expr) {
var args = computeValue(obj, expr, null);
return _.reduce(args, function (memo, num) {
return memo + num;
}, 0);
},
/**
* Takes an array that contains two numbers or two dates and subtracts the second value from the first.
*
* @param obj
* @param expr
* @returns {number}
*/
$subtract: function (obj, expr) {
var args = computeValue(obj, expr, null);
return args[0] - args[1];
},
/**
* Takes two numbers and divides the first number by the second.
*
* @param obj
* @param expr
* @returns {number}
*/
$divide: function (obj, expr) {
var args = computeValue(obj, expr, null);
return args[0] / args[1];
},
/**
* Computes the product of an array of numbers.
*
* @param obj
* @param expr
* @returns {Object}
*/
$multiply: function (obj, expr) {
var args = computeValue(obj, expr, null);
return _.reduce(args, function (memo, num) {
return memo * num;
}, 1);
},
/**
* Takes two numbers and calculates the modulo of the first number divided by the second.
*
* @param obj
* @param expr
* @returns {number}
*/
$mod: function (obj, expr) {
var args = computeValue(obj, expr, null);
return args[0] % args[1];
}
};
var stringOperators = {
/**
* Concatenates two strings.
*
* @param obj
* @param expr
* @returns {string|*}
*/
$concat: function (obj, expr) {
var args = computeValue(obj, expr, null);
// does not allow concatenation with nulls
if (_.contains(args, null) || _.contains(args, undefined)) {
return null;
}
return args.join("");
},
/**
* Compares two strings and returns an integer that reflects the comparison.
*
* @param obj
* @param expr
* @returns {number}
*/
$strcasecmp: function (obj, expr) {
var args = computeValue(obj, expr, null);
args[0] = _.isEmpty(args[0]) ? "" : args[0].toUpperCase();
args[1] = _.isEmpty(args[1]) ? "" : args[1].toUpperCase();
if (args[0] > args[1]) {
return 1;
}
return (args[0] < args[1]) ? -1 : 0;
},
/**
* Returns a substring of a string, starting at a specified index position and including the specified number of characters.
* The index is zero-based.
*
* @param obj
* @param expr
* @returns {string}
*/
$substr: function (obj, expr) {
var args = computeValue(obj, expr, null);
if (_.isString(args[0])) {
if (args[1] < 0) {
return "";
} else if (args[2] < 0) {
return args[0].substr(args[1]);
} else {
return args[0].substr(args[1], args[2]);
}
}
return "";
},
/**
* Converts a string to lowercase.
*
* @param obj
* @param expr
* @returns {string}
*/
$toLower: function (obj, expr) {
var value = computeValue(obj, expr, null);
return _.isEmpty(value) ? "" : value.toLowerCase();
},
/**
* Converts a string to uppercase.
*
* @param obj
* @param expr
* @returns {string}
*/
$toUpper: function (obj, expr) {
var value = computeValue(obj, expr, null);
return _.isEmpty(value) ? "" : value.toUpperCase();
}
};
var dateOperators = {
/**
* Returns the day of the year for a date as a number between 1 and 366 (leap year).
* @param obj
* @param expr
*/
$dayOfYear: function (obj, expr) {
var d = computeValue(obj, expr, null);
if (_.isDate(d)) {
var start = new Date(d.getFullYear(), 0, 0);
var diff = d - start;
var oneDay = 1000 * 60 * 60 * 24;
return Math.round(diff / oneDay);
}
return undefined;
},
/**
* Returns the day of the month for a date as a number between 1 and 31.
* @param obj
* @param expr
*/
$dayOfMonth: function (obj, expr) {
var d = computeValue(obj, expr, null);
return _.isDate(d) ? d.getDate() : undefined;
},
/**
* Returns the day of the week for a date as a number between 1 (Sunday) and 7 (Saturday).
* @param obj
* @param expr
*/
$dayOfWeek: function (obj, expr) {
var d = computeValue(obj, expr, null);
return _.isDate(d) ? d.getDay() + 1 : undefined;
},
/**
* Returns the year for a date as a number (e.g. 2014).
* @param obj
* @param expr
*/
$year: function (obj, expr) {
var d = computeValue(obj, expr, null);
return _.isDate(d) ? d.getFullYear() : undefined;
},
/**
* Returns the month for a date as a number between 1 (January) and 12 (December).
* @param obj
* @param expr
*/
$month: function (obj, expr) {
var d = computeValue(obj, expr, null);
return _.isDate(d) ? d.getMonth() + 1 : undefined;
},
/**
* Returns the week number for a date as a number between 0
* (the partial week that precedes the first Sunday of the year) and 53 (leap year).
* @param obj
* @param expr
*/
$week: function (obj, expr) {
// source: http://stackoverflow.com/a/6117889/1370481
var d = computeValue(obj, expr, null);
// Copy date so don't modify original
d = new Date(+d);
d.setHours(0, 0, 0);
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
d.setDate(d.getDate() + 4 - (d.getDay() || 7));
// Get first day of year
var yearStart = new Date(d.getFullYear(), 0, 1);
// Calculate full weeks to nearest Thursday
return Math.floor(( ( (d - yearStart) / 8.64e7) + 1) / 7);
},
/**
* Returns the hour for a date as a number between 0 and 23.
* @param obj
* @param expr
*/
$hour: function (obj, expr) {
var d = computeValue(obj, expr, null);
return _.isDate(d) ? d.getHours() : undefined;
},
/**
* Returns the minute for a date as a number between 0 and 59.
* @param obj
* @param expr
*/
$minute: function (obj, expr) {
var d = computeValue(obj, expr, null);
return _.isDate(d) ? d.getMinutes() : undefined;
},
/**
* Returns the seconds for a date as a number between 0 and 60 (leap seconds).
* @param obj
* @param expr
*/
$second: function (obj, expr) {
var d = computeValue(obj, expr, null);
return _.isDate(d) ? d.getSeconds() : undefined;
},
/**
* Returns the milliseconds of a date as a number between 0 and 999.
* @param obj
* @param expr
*/
$millisecond: function (obj, expr) {
var d = computeValue(obj, expr, null);
return _.isDate(d) ? d.getMilliseconds() : undefined;
},
/**
* Returns the date as a formatted string.
*
* %Y Year (4 digits, zero padded) 0000-9999
* %m Month (2 digits, zero padded) 01-12
* %d Day of Month (2 digits, zero padded) 01-31
* %H Hour (2 digits, zero padded, 24-hour clock) 00-23
* %M Minute (2 digits, zero padded) 00-59
* %S Second (2 digits, zero padded) 00-60
* %L Millisecond (3 digits, zero padded) 000-999
* %j Day of year (3 digits, zero padded) 001-366
* %w Day of week (1-Sunday, 7-Saturday) 1-7
* %U Week of year (2 digits, zero padded) 00-53
* %% Percent Character as a Literal %
*
* @param obj current object
* @param expr operator expression
*/
$dateToString: function (obj, expr) {
var fmt = expr['format'];
var date = computeValue(obj, expr['date'], null);
var matches = fmt.match(/(%%|%Y|%m|%d|%H|%M|%S|%L|%j|%w|%U)/g);
for (var i = 0, len = matches.length; i < len; i++) {
var hdlr = DATE_SYM_TABLE[matches[i]];
var value = hdlr;
if (_.isArray(hdlr)) {
// reuse date operators
var fn = this[hdlr[0]];
var pad = hdlr[1];
value = padDigits(fn.call(this, obj, date), pad);
}
// replace the match with resolved value
fmt = fmt.replace(matches[i], value);
}
return fmt;
}
};
var setOperators = {
/**
* Returns true if two sets have the same elements.
* @param obj
* @param expr
*/
$setEquals: function (obj, expr) {
var args = computeValue(obj, expr, null);
var first = _.uniq(args[0]);
var second = _.uniq(args[1]);
if (first.length !== second.length) {
return false;
}
return _.difference(first, second).length == 0;
},
/**
* Returns the common elements of the input sets.
* @param obj
* @param expr
*/
$setIntersection: function (obj, expr) {
var args = computeValue(obj, expr, null);
return _.intersection(args[0], args[1]);
},
/**
* Returns elements of a set that do not appear in a second set.
* @param obj
* @param expr
*/
$setDifference: function (obj, expr) {
var args = computeValue(obj, expr, null);
return _.difference(args[0], args[1]);
},
/**
* Returns a set that holds all elements of the input sets.
* @param obj
* @param expr
*/
$setUnion: function (obj, expr) {
var args = computeValue(obj, expr, null);
return _.union(args[0], args[1]);
},
/**
* Returns true if all elements of a set appear in a second set.
* @param obj
* @param expr
*/
$setIsSubset: function (obj, expr) {
var args = computeValue(obj, expr, null);
return _.intersection(args[0], args[1]).length === args[0].length;
},
/**
* Returns true if any elements of a set evaluate to true, and false otherwise.
* @param obj
* @param expr
*/
$anyElementTrue: function (obj, expr) {
// mongodb nests the array expression in another
var args = computeValue(obj, expr, null)[0];
for (var i = 0; i < args.length; i++) {
if (!!args[i])
return true;
}
return false;
},
/**
* Returns true if all elements of a set evaluate to true, and false otherwise.
* @param obj
* @param expr
*/
$allElementsTrue: function (obj, expr) {
// mongodb nests the array expression in another
var args = computeValue(obj, expr, null)[0];
for (var i = 0; i < args.length; i++) {
if (!args[i])
return false;
}
return true;
}
};
var conditionalOperators = {
/**
* A ternary operator that evaluates one expression,
* and depending on the result returns the value of one following expressions.
*
* @param obj
* @param expr
*/
$cond: function (obj, expr) {
var ifExpr, thenExpr, elseExpr;
if (_.isArray(expr)) {
if (expr.length != 3) {
throw new Error("Invalid arguments for $cond operator");
}
ifExpr = expr[0];
thenExpr = expr[1];
elseExpr = expr[2];
} else if (_.isObject(expr)) {
ifExpr = expr['if'];
thenExpr = expr['then'];
elseExpr = expr['else'];
}
var condition = computeValue(obj, ifExpr, null);
return condition ? computeValue(obj, thenExpr, null) : computeValue(obj, elseExpr, null);
},
/**
* Evaluates an expression and returns the first expression if it evaluates to a non-null value.
* Otherwise, $ifNull returns the second expression's value.
*
* @param obj
* @param expr
* @returns {*}
*/
$ifNull: function (obj, expr) {
if (!_.isArray(expr) || expr.length != 2) {
throw new Error("Invalid arguments for $ifNull operator");
}
var args = computeValue(obj, expr, null);
return (args[0] === null || args[0] === undefined) ? args[1] : args[0];
}
};
var comparisonOperators = {
/**
* Compares two values and returns the result of the comparison as an integer.
*
* @param obj
* @param expr
* @returns {number}
*/
$cmp: function (obj, expr) {
var args = computeValue(obj, expr, null);
if (args[0] > args[1]) {
return 1;
}
return (args[0] < args[1]) ? -1 : 0;
}
};
// mixin comparison operators
_.each(["$eq", "$ne", "$gt", "$gte", "$lt", "$lte"], function (op) {
comparisonOperators[op] = function (obj, expr) {
var args = computeValue(obj, expr, null);
return simpleOperators[op](args[0], args[1]);
};
});
var arrayOperators = {
/**
* Counts and returns the total the number of items in an array.
* @param obj
* @param expr
*/
$size: function (obj, expr) {
var value = computeValue(obj, expr, null);
return _.isArray(value) ? value.length : undefined;
}
};
var literalOperators = {
/**
* Return a value without parsing.
* @param obj
* @param expr
*/
$literal: function (obj, expr) {
return expr;
}
};
var variableOperators = {
/**
* Applies a subexpression to each element of an array and returns the array of resulting values in order.
* @param obj
* @param expr
* @returns {Array|*}
*/
$map: function (obj, expr) {
var inputExpr = computeValue(obj, expr["input"], null);
if (!_.isArray(inputExpr)) {
throw new Error("Input expression for $map must resolve to an array");
}
var asExpr = expr["as"];
var inExpr = expr["in"];
// HACK: add the "as" expression as a value on the object to take advantage of "resolve()"
// which will reduce to that value when invoked. The reference to the as expression will be prefixed with "$$".
// But since a "$" is stripped of before passing the name to "resolve()" we just need to prepend "$" to the key.
var tempKey = "$" + asExpr;
// let's save any value that existed, kinda useless but YOU CAN NEVER BE TOO SURE, CAN YOU :)
var original = obj[tempKey];
return _.map(inputExpr, function (item) {
obj[tempKey] = item;
var value = computeValue(obj, inExpr, null);
// cleanup and restore
if (_.isUndefined(original)) {
delete obj[tempKey];
} else {
obj[tempKey] = original;
}
return value;
});
},
/**
* Defines variables for use within the scope of a subexpression and returns the result of the subexpression.
* @param obj
* @param expr
* @returns {*}
*/
$let: function (obj, expr) {
var varsExpr = expr["vars"];
var inExpr = expr["in"];
// resolve vars
var originals = {};
var varsKeys = _.keys(varsExpr);
_.each(varsKeys, function (key) {
var val = computeValue(obj, varsExpr[key], null);
var tempKey = "$" + key;
// set value on object using same technique as in "$map"
originals[tempKey] = obj[tempKey];
obj[tempKey] = val;
});
var value = computeValue(obj, inExpr, null);
// cleanup and restore
_.each(varsKeys, function (key) {
var tempKey = "$" + key;
if (_.isUndefined(originals[tempKey])) {
delete obj[tempKey];
} else {
obj[tempKey] = originals[tempKey];
}
});
return value;
}
};
var booleanOperators = {
/**
* Returns true only when all its expressions evaluate to true. Accepts any number of argument expressions.
* @param obj
* @param expr
* @returns {boolean}
*/
$and: function (obj, expr) {
var value = computeValue(obj, expr, null);
return _.every(value);
},
/**
* Returns true when any of its expressions evaluates to true. Accepts any number of argument expressions.
* @param obj
* @param expr
* @returns {boolean}
*/
$or: function (obj, expr) {
var value = computeValue(obj, expr, null);
return _.some(value);
},
/**
* Returns the boolean value that is the opposite of its argument expression. Accepts a single argument expression.
* @param obj
* @param expr
* @returns {boolean}
*/
$not: function (obj, expr) {
return !computeValue(obj, expr[0], null);
}
};
// combine aggregate operators
var aggregateOperators = _.extend(
{},
arrayOperators,
arithmeticOperators,
booleanOperators,
comparisonOperators,
conditionalOperators,
dateOperators,
literalOperators,
setOperators,
stringOperators,
variableOperators
);
var OP_QUERY = Mingo.OP_QUERY = 'query',
OP_GROUP = Mingo.OP_GROUP = 'group',
OP_AGGREGATE = Mingo.OP_AGGREGATE = 'aggregate',
OP_PIPELINE = Mingo.OP_PIPELINE = 'pipeline',
OP_PROJECTION = Mingo.OP_PROJECTION = 'projection';
// operator definitions
var OPERATORS = {
'aggregate': aggregateOperators,
'group': groupOperators,
'pipeline': pipelineOperators,
'projection': projectionOperators,
'query': queryOperators
};
// used for formatting dates in $dateToString operator
var DATE_SYM_TABLE = {
'%Y': ['$year', 4],
'%m': ['$month', 2],
'%d': ['$dayOfMonth', 2],
'%H': ['$hour', 2],
'%M': ['$minute', 2],
'%S': ['$second', 2],
'%L': ['$millisecond', 3],
'%j': ['$dayOfYear', 3],
'%w': ['$dayOfWeek', 1],
'%U': ['$week', 2],
'%%': '%'
};
function padDigits(number, digits) {
return new Array(Math.max(digits - String(number).length + 1, 0)).join('0') + number;
}
/**
* Return the registered operators on the given operator category
* @param type catgory of operators
* @returns {*}
*/
function ops(type) {
return _.keys(OPERATORS[type]);
}
/**
* Groups the collection into sets by the returned key
*
* @param collection
* @param fn
*/
function groupBy(collection, fn) {
var result = {
'keys': [],
'groups': []
};
_.each(collection, function (obj) {
var key = fn(obj);
var index = -1;
if (_.isObject(key)) {
for (var i = 0; i < result.keys.length; i++) {
if (_.isEqual(key, result.keys[i])) {
index = i;
break;
}
}
} else {
index = _.indexOf(result.keys, key);
}
if (index > -1) {
result.groups[index].push(obj);
} else {
result.keys.push(key);
result.groups.push([obj]);
}
});
// assert this
if (result.keys.length !== result.groups.length) {
throw new Error("assert groupBy(): keys.length !== groups.length");
}
return result;
}
/**
* Returns the result of evaluating a $group operation over a collection
*
* @param collection
* @param field the name of the aggregate operator or field
* @param expr the expression of the aggregate operator for the field
* @returns {*}
*/
function accumulate(collection, field, expr) {
if (_.contains(ops(OP_GROUP), field)) {
return groupOperators[field](collection, expr);
}
if (_.isObject(expr)) {
var result = {};
for (var key in expr) {
if (expr.hasOwnProperty(key)) {
result[key] = accumulate(collection, key, expr[key]);
// must run ONLY one group operator per expression
// if so, return result of the computed value
if (_.contains(ops(OP_GROUP), key)) {
result = result[key];
// if there are more keys in expression this is bad
if (_.keys(expr).length > 1) {
throw new Error("Invalid $group expression '" + JSON.stringify(expr) + "'");
}
break;
}
}
}
return result;
}
return undefined;
}
/**
* Computes the actual value of the expression using the given object as context
*
* @param obj the current object from the collection
* @param expr the expression for the given field
* @param field the field name (may also be an aggregate operator)
* @returns {*}
*/
function computeValue(obj, expr, field) {
// if the field of the object is a valid operator
if (_.contains(ops(OP_AGGREGATE), field)) {
return aggregateOperators[field](obj, expr);
}
// if expr is a variable for an object field
// field not used in this case
if (_.isString(expr) && expr.length > 0 && expr[0] === "$") {
return resolve(obj, expr.slice(1));
}
var result;
// check and return value if already in a resolved state
if (isPrimitive(expr)) {
return expr;
} else if (_.isArray(expr)) {
result = _.map(expr, function (item) {
return computeValue(obj, item, null);
});
} else if (_.isObject(expr)) {
result = {};
for (var key in expr) {
if (expr.hasOwnProperty(key)) {
result[key] = computeValue(obj, expr[key], key);
// must run ONLY one aggregate operator per expression
// if so, return result of the computed value
if (_.contains(ops(OP_AGGREGATE), key)) {
result = result[key];
// if there are more keys in expression this is bad
if (_.keys(expr).length > 1) {
throw new Error("Invalid aggregation expression '" + JSON.stringify(expr) + "'");
}
break;
}
}
}
}
return result;
}
}(this));
| mit |
gogilo2003/admin | src/Models/BlogCategory.php | 485 | <?php
namespace Ogilo\Admin\Models;
use Illuminate\Database\Eloquent\Model;
/**
* Hit model
*/
class BlogCategory extends Model
{
public function blogs()
{
return $this->hasMany('Ogilo\Admin\Models\Blog');
}
public function pages()
{
return $this->belongsToMany('Ogilo\Admin\Models\Page');
}
public function pageIds()
{
$ids = array();
foreach ($this->pages as $key => $value) {
$ids[] = $value->id;
}
return $ids;
}
} | mit |
Tape-Worm/Gorgon | PlugIns/Gorgon.Editor.FontEditor/_Internal/Controls/WeightHandleComparer.cs | 2529 | #region MIT
//
// Gorgon.
// Copyright (C) 2021 Michael Winsor
//
// 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
// 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.
//
// Created: September 7, 2021 11:04:32 PM
//
#endregion
using System.Collections.Generic;
using Gorgon.Math;
namespace Gorgon.Editor.FontEditor
{
/// <summary>
/// Comparer class for sorting the weight nodes.
/// </summary>
internal class WeightHandleComparer
: IComparer<WeightHandle>
{
#region IComparer<WeightHandle> Members
/// <summary>
/// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
/// </summary>
/// <param name="x">The first object to compare.</param>
/// <param name="y">The second object to compare.</param>
/// <returns>
/// A signed integer that indicates the relative values of <paramref name="x" /> and <paramref name="y" />, as shown in the following table.Value Meaning Less than zero<paramref name="x" /> is less than <paramref name="y" />.Zero<paramref name="x" /> equals <paramref name="y" />.Greater than zero<paramref name="x" /> is greater than <paramref name="y" />.
/// </returns>
public int Compare(WeightHandle x, WeightHandle y)
{
if ((x is null)
|| (y is null))
{
return 0;
}
if (x.Weight.EqualsEpsilon(y.Weight))
{
return 0;
}
return x.Weight < y.Weight ? -1 : 1;
}
#endregion
}
}
| mit |
leandrochomp/prj_GAF | sources/controller/desativa.aluno.repositorio.php | 747 | <?php
require_once '../model/aluno.class.php';
$hoje = date("Y/m/d");
$codigo = $_GET['cod'];
$testando = new pessoa(array(
'idPerfil' => '4',
'idPessoa' => $codigo,
'nome' => $_POST['txtNome'],
'CPF' => $_POST['txtCPF'],
'email' => $_POST['txtEmail'],
'telefone' => $_POST['txtFone'],
'celular' => $_POST['txtCel'],
'sexo' => $_POST['sltSexo'],
'dtNascimento' => $_POST['dtNasc'],
'login' => $_POST['txtLogin'],
'dtCadastro' => $hoje
));
$testando->Desativar = $codigo;
var_dump($codigo);
// var_dump($testando);
if ($testando->Desativar($testando))
echo "Desativou";
else
var_dump($testando);
echo"<pre>";
echo "Não desativou";
?> | mit |
springer-math/Mathematics-of-Epidemics-on-Networks | setup.py | 1049 | #!/usr/bin/env python
r'''
Setup script for EoN (Epidemics on Networks)
to install from this script, run
python setup.py install
Alternately, you can install with pip.
pip install EoN
If this is a "release candidate" (has an "rc" in the version name below), then
pip will download the previous version - see the download_url below.
'''
from setuptools import setup
setup(name='EoN',
packages = ['EoN'],
version='1.2rc1', #http://semver.org/
description = 'Epidemics on Networks',
author = 'Joel C. Miller, Istvan Z. Kiss, and Peter Simon',
author_email = 'joel.c.miller.research@gmail.com',
url = 'https://springer-math.github.io/Mathematics-of-Epidemics-on-Networks/',
#download_url = 'https://github.com/springer-math/Mathematics-of-Epidemics-on-Networks/archive/1.1.tar.gz',
keywords = ['Epidemics on Networks', 'Epidemic Sonnet Works'],
install_requires = [
'networkx>=2',
'numpy',
'scipy',
'matplotlib'
],
)
| mit |
NicolaasWeideman/DirectoryListingRESTfulService | src/main/java/spring/directorylisting/DirectoryListingResultCache.java | 3333 | package spring.directorylisting;
import java.util.concurrent.ConcurrentHashMap;
import java.io.IOException;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.FileSystems;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.nio.file.WatchService;
import java.nio.file.WatchKey;
import java.nio.file.WatchEvent;
import java.nio.file.StandardWatchEventKinds;
import debugging.Debug;
/**
* A class for caching Directory Listing Results.
* @author N. H. Weideman
*/
public class DirectoryListingResultCache {
private final ConcurrentHashMap<String, DirectoryListingResult> cacheMap;
private final FileSystem fileSystem;
private final WatchService watchService;
/**
* Creates a new cache.
* @throws IOException If an I/O error occurs
*/
public DirectoryListingResultCache() throws IOException {
this.cacheMap = new ConcurrentHashMap<String, DirectoryListingResult>();
this.fileSystem = FileSystems.getDefault();
this.watchService = fileSystem.newWatchService();
/* Start a new thread to handle events from the watch service. */
DirectoryListingResultValidityThread dlrvt = new DirectoryListingResultValidityThread();
dlrvt.start();
}
/**
* Obtains the directory listing result for the cached path.
* @param path The path of the directory listing result
* @return The directory listing result if the path has been cached, NULL otherwise
*/
public DirectoryListingResult get(String fileStr) {
return cacheMap.get(fileStr);
}
/**
* Adds a new entry to the cache.
* @param path The path of the directory listing result
* @param directoryListingResult The directory listing result to cache
* @throws IOException If an I/O error occurs
*/
public void put(String fileStr, DirectoryListingResult directoryListingResult) throws IOException {
Path path = fileSystem.getPath(fileStr);
/* Obtaining the canonical path */
path = new File(path.toFile().getCanonicalPath()).toPath();
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
Debug.debugln("Adding " + fileStr + " to cache.");
cacheMap.put(fileStr, directoryListingResult);
}
/**
* Checks if a path has a cached entry
* @return True if the path has a cached entry, false otherwise
*/
public boolean contains(String fileStr) {
return cacheMap.containsKey(fileStr);
}
/**
* A thread to handle events of the watch service.
*/
private class DirectoryListingResultValidityThread extends Thread {
@Override
public void run() {
try {
boolean watchDirectory = true;
/* If an event occurs in a watched directory, remove it from the cache, as the cached entry has become invalid. */
while (watchDirectory) {
WatchKey watchKey = watchService.take();
for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
Path directory = (Path) watchKey.watchable();
String directoryStr = directory.toString();
if (cacheMap.containsKey(directoryStr)) {
Debug.debugln("Removing " + directoryStr + " from cache.");
cacheMap.remove(directoryStr);
Debug.debugln("Canceling " + directory + " from watch service.");
watchKey.cancel();
}
}
}
} catch (InterruptedException ie) {
}
}
}
}
| mit |
yvanwangl/Blog | client/store/configureStore.js | 208 | if (process.env.NODE_ENV === 'production') {
//console.log(process.env.NODE_ENV+'store');
module.exports = require('./configureStore.prod');
} else {
module.exports = require('./configureStore.dev');
}
| mit |
vchrisb/emc_phoenix2 | content/views.py | 4275 | # load settings file
from django.conf import settings
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
#cache
from django.views.decorators.cache import cache_page
from django.views.decorators.cache import cache_control
import os
from django.core.mail import send_mail
from phoenix.decorators import specific_verified_email_required, cache_on_auth
from .forms import ContactForm, ContactFormSignedIn
from .models import Featurette, FAQ
import json
# Create your views here.
@cache_on_auth(60 * 15)
@cache_control(no_cache=True, must_revalidate=True, no_store=True)
def home(request):
featurette_list = Featurette.objects.filter(publish=True).order_by('position')
context = {
"featurettes": featurette_list,
}
return render(request, "home.html", context)
@cache_on_auth(60 * 15)
@cache_control(no_cache=True, must_revalidate=True, no_store=True)
def faq(request):
faq_list = FAQ.objects.filter(publish=True).order_by('position')
context = {
"faqs": faq_list,
}
return render(request, "faq.html", context)
@cache_page(60 * 15)
@specific_verified_email_required(domains=settings.ALLOWED_DOMAINS)
def accommodation(request):
context = {
}
return render(request, "accommodation.html", context)
@cache_page(60 * 15)
@specific_verified_email_required(domains=settings.ALLOWED_DOMAINS)
def shuttle(request):
context = {
}
return render(request, "shuttle.html", context)
@cache_page(60 * 5)
@specific_verified_email_required(domains=settings.ALLOWED_DOMAINS)
def gallery(request):
context = {
}
return render(request, "gallery.html", context)
@cache_on_auth(60 * 15)
def contact(request):
title = "Contact:"
if request.user.is_authenticated():
form = ContactFormSignedIn(request.POST or None)
else:
form = ContactForm(request.POST or None)
context = {
"contact": 'active',
"title": title,
"form": form,
}
if form.is_valid():
form_email = form.cleaned_data.get("email")
form_message = form.cleaned_data.get("message")
form_full_name = form.cleaned_data.get("full_name")
subject = 'Site contact form'
from_email = settings.DEFAULT_FROM_EMAIL
to_email = [settings.DEFAULT_TO_EMAIL]
contact_message = "%s: %s via %s" %(form_full_name, form_message, form_email)
some_html_message = """
<h1>This message was send to you from %s via %s:</h1>
%s
""" %(form_full_name, form_email, form_message)
# send asynchronous
send_mail(subject,
contact_message,
from_email,
to_email,
html_message = some_html_message,
fail_silently = False)
context = {
"contact": 'active',
"title": "Thank You!",
}
return render(request, "contact.html", context)
from .tasks import prime_number
from django.contrib.admin.views.decorators import staff_member_required
@staff_member_required
def primes(request):
if request.method == 'GET':
searchrange = 3
tasks = 1
if 'range' in request.GET:
try:
searchrange = int(request.GET.get('range'))
except ValueError:
searchrange = 3
if 'tasks' in request.GET:
try:
tasks = int(request.GET.get('tasks'))
except ValueError:
tasks = 1
if tasks < 1:
tasks = 1
if searchrange < 3:
searchrange = 3
if searchrange > 500000:
searchrange = 500000
if (searchrange/tasks) > 100000:
searchrange = 100000
tasks = 5
window = int(searchrange / tasks)
low = 0
high = window
for n in range(0, tasks):
if high > searchrange:
high = searchrange
prime_number.delay(low,high)
low += window
high += window
context = {
"title": "Primes:",
"range": searchrange,
"tasks": tasks,
}
return render(request, "primes.html", context)
| mit |
nailsapp/module-sitemap | services/services.php | 589 | <?php
return [
'services' => [
'SiteMap' => function () {
if (class_exists('\App\SiteMap\Service\SiteMap')) {
return new \App\SiteMap\Service\SiteMap();
} else {
return new \Nails\SiteMap\Service\SiteMap();
}
},
],
'factories' => [
'Url' => function () {
if (class_exists('\App\SiteMap\Factory\Url')) {
return new \App\SiteMap\Factory\Url();
} else {
return new \Nails\SiteMap\Factory\Url();
}
},
],
];
| mit |
xyz252631m/web | libs/acorn-8.0.5/src/expression.js | 39975 | // A recursive descent parser operates by defining functions for all
// syntactic elements, and recursively calling those, each function
// advancing the input stream and returning an AST node. Precedence
// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
// instead of `(!x)[1]` is handled by the fact that the parser
// function that parses unary prefix operators is called first, and
// in turn calls the function that parses `[]` subscripts — that
// way, it'll receive the node for `x[1]` already parsed, and wraps
// *that* in the unary operator node.
//
// Acorn uses an [operator precedence parser][opp] to handle binary
// operator precedence, because it is much more compact than using
// the technique outlined above, which uses different, nesting
// functions to specify precedence, for all of the ten binary
// precedence levels that JavaScript defines.
//
// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
import {types as tt} from "./tokentype.js"
import {Parser} from "./state.js"
import {DestructuringErrors} from "./parseutil.js"
import {lineBreak} from "./whitespace.js"
import {functionFlags, SCOPE_ARROW, SCOPE_SUPER, SCOPE_DIRECT_SUPER, BIND_OUTSIDE, BIND_VAR} from "./scopeflags.js"
const pp = Parser.prototype
// Check if property name clashes with already added.
// Object/class getters and setters are not allowed to clash —
// either with each other or with an init property — and in
// strict mode, init properties are also not allowed to be repeated.
pp.checkPropClash = function(prop, propHash, refDestructuringErrors) {
if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
return
if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
return
let {key} = prop, name
switch (key.type) {
case "Identifier": name = key.name; break
case "Literal": name = String(key.value); break
default: return
}
let {kind} = prop
if (this.options.ecmaVersion >= 6) {
if (name === "__proto__" && kind === "init") {
if (propHash.proto) {
if (refDestructuringErrors) {
if (refDestructuringErrors.doubleProto < 0)
refDestructuringErrors.doubleProto = key.start
// Backwards-compat kludge. Can be removed in version 6.0
} else this.raiseRecoverable(key.start, "Redefinition of __proto__ property")
}
propHash.proto = true
}
return
}
name = "$" + name
let other = propHash[name]
if (other) {
let redefinition
if (kind === "init") {
redefinition = this.strict && other.init || other.get || other.set
} else {
redefinition = other.init || other[kind]
}
if (redefinition)
this.raiseRecoverable(key.start, "Redefinition of property")
} else {
other = propHash[name] = {
init: false,
get: false,
set: false
}
}
other[kind] = true
}
// ### Expression parsing
// These nest, from the most general expression type at the top to
// 'atomic', nondivisible expression types at the bottom. Most of
// the functions will simply let the function(s) below them parse,
// and, *if* the syntactic construct they handle is present, wrap
// the AST node that the inner parser gave them in another node.
// Parse a full expression. The optional arguments are used to
// forbid the `in` operator (in for loops initalization expressions)
// and provide reference for storing '=' operator inside shorthand
// property assignment in contexts where both object expression
// and object pattern might appear (so it's possible to raise
// delayed syntax error at correct position).
pp.parseExpression = function(noIn, refDestructuringErrors) {
let startPos = this.start, startLoc = this.startLoc
let expr = this.parseMaybeAssign(noIn, refDestructuringErrors)
if (this.type === tt.comma) {
let node = this.startNodeAt(startPos, startLoc)
node.expressions = [expr]
while (this.eat(tt.comma)) node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors))
return this.finishNode(node, "SequenceExpression")
}
return expr
}
// Parse an assignment expression. This includes applications of
// operators like `+=`.
pp.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
if (this.isContextual("yield")) {
if (this.inGenerator) return this.parseYield(noIn)
// The tokenizer will assume an expression is allowed after
// `yield`, but this isn't that kind of yield
else this.exprAllowed = false
}
let ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1
if (refDestructuringErrors) {
oldParenAssign = refDestructuringErrors.parenthesizedAssign
oldTrailingComma = refDestructuringErrors.trailingComma
refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1
} else {
refDestructuringErrors = new DestructuringErrors
ownDestructuringErrors = true
}
let startPos = this.start, startLoc = this.startLoc
if (this.type === tt.parenL || this.type === tt.name)
this.potentialArrowAt = this.start
let left = this.parseMaybeConditional(noIn, refDestructuringErrors)
if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc)
if (this.type.isAssign) {
let node = this.startNodeAt(startPos, startLoc)
node.operator = this.value
if (this.type === tt.eq)
left = this.toAssignable(left, false, refDestructuringErrors)
if (!ownDestructuringErrors) {
refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1
}
if (refDestructuringErrors.shorthandAssign >= left.start)
refDestructuringErrors.shorthandAssign = -1 // reset because shorthand default was used correctly
if (this.type === tt.eq)
this.checkLValPattern(left)
else
this.checkLValSimple(left)
node.left = left
this.next()
node.right = this.parseMaybeAssign(noIn)
return this.finishNode(node, "AssignmentExpression")
} else {
if (ownDestructuringErrors) this.checkExpressionErrors(refDestructuringErrors, true)
}
if (oldParenAssign > -1) refDestructuringErrors.parenthesizedAssign = oldParenAssign
if (oldTrailingComma > -1) refDestructuringErrors.trailingComma = oldTrailingComma
return left
}
// Parse a ternary conditional (`?:`) operator.
pp.parseMaybeConditional = function(noIn, refDestructuringErrors) {
let startPos = this.start, startLoc = this.startLoc
let expr = this.parseExprOps(noIn, refDestructuringErrors)
if (this.checkExpressionErrors(refDestructuringErrors)) return expr
if (this.eat(tt.question)) {
let node = this.startNodeAt(startPos, startLoc)
node.test = expr
node.consequent = this.parseMaybeAssign()
this.expect(tt.colon)
node.alternate = this.parseMaybeAssign(noIn)
return this.finishNode(node, "ConditionalExpression")
}
return expr
}
// Start the precedence parser.
pp.parseExprOps = function(noIn, refDestructuringErrors) {
let startPos = this.start, startLoc = this.startLoc
let expr = this.parseMaybeUnary(refDestructuringErrors, false)
if (this.checkExpressionErrors(refDestructuringErrors)) return expr
return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
}
// Parse binary operators with the operator precedence parsing
// algorithm. `left` is the left-hand side of the operator.
// `minPrec` provides context that allows the function to stop and
// defer further parser to one of its callers when it encounters an
// operator that has a lower precedence than the set it is parsing.
pp.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
let prec = this.type.binop
if (prec != null && (!noIn || this.type !== tt._in)) {
if (prec > minPrec) {
let logical = this.type === tt.logicalOR || this.type === tt.logicalAND
let coalesce = this.type === tt.coalesce
if (coalesce) {
// Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
// In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
prec = tt.logicalAND.binop
}
let op = this.value
this.next()
let startPos = this.start, startLoc = this.startLoc
let right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn)
let node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce)
if ((logical && this.type === tt.coalesce) || (coalesce && (this.type === tt.logicalOR || this.type === tt.logicalAND))) {
this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses")
}
return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
}
}
return left
}
pp.buildBinary = function(startPos, startLoc, left, right, op, logical) {
let node = this.startNodeAt(startPos, startLoc)
node.left = left
node.operator = op
node.right = right
return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
}
// Parse unary operators, both prefix and postfix.
pp.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
let startPos = this.start, startLoc = this.startLoc, expr
if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) {
expr = this.parseAwait()
sawUnary = true
} else if (this.type.prefix) {
let node = this.startNode(), update = this.type === tt.incDec
node.operator = this.value
node.prefix = true
this.next()
node.argument = this.parseMaybeUnary(null, true)
this.checkExpressionErrors(refDestructuringErrors, true)
if (update) this.checkLValSimple(node.argument)
else if (this.strict && node.operator === "delete" &&
node.argument.type === "Identifier")
this.raiseRecoverable(node.start, "Deleting local variable in strict mode")
else sawUnary = true
expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression")
} else {
expr = this.parseExprSubscripts(refDestructuringErrors)
if (this.checkExpressionErrors(refDestructuringErrors)) return expr
while (this.type.postfix && !this.canInsertSemicolon()) {
let node = this.startNodeAt(startPos, startLoc)
node.operator = this.value
node.prefix = false
node.argument = expr
this.checkLValSimple(expr)
this.next()
expr = this.finishNode(node, "UpdateExpression")
}
}
if (!sawUnary && this.eat(tt.starstar))
return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false)
else
return expr
}
// Parse call, dot, and `[]`-subscript expressions.
pp.parseExprSubscripts = function(refDestructuringErrors) {
let startPos = this.start, startLoc = this.startLoc
let expr = this.parseExprAtom(refDestructuringErrors)
if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
return expr
let result = this.parseSubscripts(expr, startPos, startLoc)
if (refDestructuringErrors && result.type === "MemberExpression") {
if (refDestructuringErrors.parenthesizedAssign >= result.start) refDestructuringErrors.parenthesizedAssign = -1
if (refDestructuringErrors.parenthesizedBind >= result.start) refDestructuringErrors.parenthesizedBind = -1
}
return result
}
pp.parseSubscripts = function(base, startPos, startLoc, noCalls) {
let maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
this.potentialArrowAt === base.start
let optionalChained = false
while (true) {
let element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained)
if (element.optional) optionalChained = true
if (element === base || element.type === "ArrowFunctionExpression") {
if (optionalChained) {
const chainNode = this.startNodeAt(startPos, startLoc)
chainNode.expression = element
element = this.finishNode(chainNode, "ChainExpression")
}
return element
}
base = element
}
}
pp.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
let optionalSupported = this.options.ecmaVersion >= 11
let optional = optionalSupported && this.eat(tt.questionDot)
if (noCalls && optional) this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions")
let computed = this.eat(tt.bracketL)
if (computed || (optional && this.type !== tt.parenL && this.type !== tt.backQuote) || this.eat(tt.dot)) {
let node = this.startNodeAt(startPos, startLoc)
node.object = base
node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never")
node.computed = !!computed
if (computed) this.expect(tt.bracketR)
if (optionalSupported) {
node.optional = optional
}
base = this.finishNode(node, "MemberExpression")
} else if (!noCalls && this.eat(tt.parenL)) {
let refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos
this.yieldPos = 0
this.awaitPos = 0
this.awaitIdentPos = 0
let exprList = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors)
if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
this.checkPatternErrors(refDestructuringErrors, false)
this.checkYieldAwaitInDefaultParams()
if (this.awaitIdentPos > 0)
this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function")
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
this.awaitIdentPos = oldAwaitIdentPos
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
}
this.checkExpressionErrors(refDestructuringErrors, true)
this.yieldPos = oldYieldPos || this.yieldPos
this.awaitPos = oldAwaitPos || this.awaitPos
this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos
let node = this.startNodeAt(startPos, startLoc)
node.callee = base
node.arguments = exprList
if (optionalSupported) {
node.optional = optional
}
base = this.finishNode(node, "CallExpression")
} else if (this.type === tt.backQuote) {
if (optional || optionalChained) {
this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions")
}
let node = this.startNodeAt(startPos, startLoc)
node.tag = base
node.quasi = this.parseTemplate({isTagged: true})
base = this.finishNode(node, "TaggedTemplateExpression")
}
return base
}
// Parse an atomic expression — either a single token that is an
// expression, an expression started by a keyword like `function` or
// `new`, or an expression wrapped in punctuation like `()`, `[]`,
// or `{}`.
pp.parseExprAtom = function(refDestructuringErrors) {
// If a division operator appears in an expression position, the
// tokenizer got confused, and we force it to read a regexp instead.
if (this.type === tt.slash) this.readRegexp()
let node, canBeArrow = this.potentialArrowAt === this.start
switch (this.type) {
case tt._super:
if (!this.allowSuper)
this.raise(this.start, "'super' keyword outside a method")
node = this.startNode()
this.next()
if (this.type === tt.parenL && !this.allowDirectSuper)
this.raise(node.start, "super() call outside constructor of a subclass")
// The `super` keyword can appear at below:
// SuperProperty:
// super [ Expression ]
// super . IdentifierName
// SuperCall:
// super ( Arguments )
if (this.type !== tt.dot && this.type !== tt.bracketL && this.type !== tt.parenL)
this.unexpected()
return this.finishNode(node, "Super")
case tt._this:
node = this.startNode()
this.next()
return this.finishNode(node, "ThisExpression")
case tt.name:
let startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc
let id = this.parseIdent(false)
if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(tt._function))
return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true)
if (canBeArrow && !this.canInsertSemicolon()) {
if (this.eat(tt.arrow))
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false)
if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === tt.name && !containsEsc) {
id = this.parseIdent(false)
if (this.canInsertSemicolon() || !this.eat(tt.arrow))
this.unexpected()
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
}
}
return id
case tt.regexp:
let value = this.value
node = this.parseLiteral(value.value)
node.regex = {pattern: value.pattern, flags: value.flags}
return node
case tt.num: case tt.string:
return this.parseLiteral(this.value)
case tt._null: case tt._true: case tt._false:
node = this.startNode()
node.value = this.type === tt._null ? null : this.type === tt._true
node.raw = this.type.keyword
this.next()
return this.finishNode(node, "Literal")
case tt.parenL:
let start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow)
if (refDestructuringErrors) {
if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
refDestructuringErrors.parenthesizedAssign = start
if (refDestructuringErrors.parenthesizedBind < 0)
refDestructuringErrors.parenthesizedBind = start
}
return expr
case tt.bracketL:
node = this.startNode()
this.next()
node.elements = this.parseExprList(tt.bracketR, true, true, refDestructuringErrors)
return this.finishNode(node, "ArrayExpression")
case tt.braceL:
return this.parseObj(false, refDestructuringErrors)
case tt._function:
node = this.startNode()
this.next()
return this.parseFunction(node, 0)
case tt._class:
return this.parseClass(this.startNode(), false)
case tt._new:
return this.parseNew()
case tt.backQuote:
return this.parseTemplate()
case tt._import:
if (this.options.ecmaVersion >= 11) {
return this.parseExprImport()
} else {
return this.unexpected()
}
default:
this.unexpected()
}
}
pp.parseExprImport = function() {
const node = this.startNode()
// Consume `import` as an identifier for `import.meta`.
// Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
if (this.containsEsc) this.raiseRecoverable(this.start, "Escape sequence in keyword import")
const meta = this.parseIdent(true)
switch (this.type) {
case tt.parenL:
return this.parseDynamicImport(node)
case tt.dot:
node.meta = meta
return this.parseImportMeta(node)
default:
this.unexpected()
}
}
pp.parseDynamicImport = function(node) {
this.next() // skip `(`
// Parse node.source.
node.source = this.parseMaybeAssign()
// Verify ending.
if (!this.eat(tt.parenR)) {
const errorPos = this.start
if (this.eat(tt.comma) && this.eat(tt.parenR)) {
this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()")
} else {
this.unexpected(errorPos)
}
}
return this.finishNode(node, "ImportExpression")
}
pp.parseImportMeta = function(node) {
this.next() // skip `.`
const containsEsc = this.containsEsc
node.property = this.parseIdent(true)
if (node.property.name !== "meta")
this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'")
if (containsEsc)
this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters")
if (this.options.sourceType !== "module")
this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module")
return this.finishNode(node, "MetaProperty")
}
pp.parseLiteral = function(value) {
let node = this.startNode()
node.value = value
node.raw = this.input.slice(this.start, this.end)
if (node.raw.charCodeAt(node.raw.length - 1) === 110) node.bigint = node.raw.slice(0, -1).replace(/_/g, "")
this.next()
return this.finishNode(node, "Literal")
}
pp.parseParenExpression = function() {
this.expect(tt.parenL)
let val = this.parseExpression()
this.expect(tt.parenR)
return val
}
pp.parseParenAndDistinguishExpression = function(canBeArrow) {
let startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8
if (this.options.ecmaVersion >= 6) {
this.next()
let innerStartPos = this.start, innerStartLoc = this.startLoc
let exprList = [], first = true, lastIsComma = false
let refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart
this.yieldPos = 0
this.awaitPos = 0
// Do not save awaitIdentPos to allow checking awaits nested in parameters
while (this.type !== tt.parenR) {
first ? first = false : this.expect(tt.comma)
if (allowTrailingComma && this.afterTrailingComma(tt.parenR, true)) {
lastIsComma = true
break
} else if (this.type === tt.ellipsis) {
spreadStart = this.start
exprList.push(this.parseParenItem(this.parseRestBinding()))
if (this.type === tt.comma) this.raise(this.start, "Comma is not permitted after the rest element")
break
} else {
exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem))
}
}
let innerEndPos = this.start, innerEndLoc = this.startLoc
this.expect(tt.parenR)
if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
this.checkPatternErrors(refDestructuringErrors, false)
this.checkYieldAwaitInDefaultParams()
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
return this.parseParenArrowList(startPos, startLoc, exprList)
}
if (!exprList.length || lastIsComma) this.unexpected(this.lastTokStart)
if (spreadStart) this.unexpected(spreadStart)
this.checkExpressionErrors(refDestructuringErrors, true)
this.yieldPos = oldYieldPos || this.yieldPos
this.awaitPos = oldAwaitPos || this.awaitPos
if (exprList.length > 1) {
val = this.startNodeAt(innerStartPos, innerStartLoc)
val.expressions = exprList
this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc)
} else {
val = exprList[0]
}
} else {
val = this.parseParenExpression()
}
if (this.options.preserveParens) {
let par = this.startNodeAt(startPos, startLoc)
par.expression = val
return this.finishNode(par, "ParenthesizedExpression")
} else {
return val
}
}
pp.parseParenItem = function(item) {
return item
}
pp.parseParenArrowList = function(startPos, startLoc, exprList) {
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
}
// New's precedence is slightly tricky. It must allow its argument to
// be a `[]` or dot subscript expression, but not a call — at least,
// not without wrapping it in parentheses. Thus, it uses the noCalls
// argument to parseSubscripts to prevent it from consuming the
// argument list.
const empty = []
pp.parseNew = function() {
if (this.containsEsc) this.raiseRecoverable(this.start, "Escape sequence in keyword new")
let node = this.startNode()
let meta = this.parseIdent(true)
if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) {
node.meta = meta
let containsEsc = this.containsEsc
node.property = this.parseIdent(true)
if (node.property.name !== "target")
this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'")
if (containsEsc)
this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters")
if (!this.inNonArrowFunction)
this.raiseRecoverable(node.start, "'new.target' can only be used in functions")
return this.finishNode(node, "MetaProperty")
}
let startPos = this.start, startLoc = this.startLoc, isImport = this.type === tt._import
node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true)
if (isImport && node.callee.type === "ImportExpression") {
this.raise(startPos, "Cannot use new with import()")
}
if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8, false)
else node.arguments = empty
return this.finishNode(node, "NewExpression")
}
// Parse template expression.
pp.parseTemplateElement = function({isTagged}) {
let elem = this.startNode()
if (this.type === tt.invalidTemplate) {
if (!isTagged) {
this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal")
}
elem.value = {
raw: this.value,
cooked: null
}
} else {
elem.value = {
raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
cooked: this.value
}
}
this.next()
elem.tail = this.type === tt.backQuote
return this.finishNode(elem, "TemplateElement")
}
pp.parseTemplate = function({isTagged = false} = {}) {
let node = this.startNode()
this.next()
node.expressions = []
let curElt = this.parseTemplateElement({isTagged})
node.quasis = [curElt]
while (!curElt.tail) {
if (this.type === tt.eof) this.raise(this.pos, "Unterminated template literal")
this.expect(tt.dollarBraceL)
node.expressions.push(this.parseExpression())
this.expect(tt.braceR)
node.quasis.push(curElt = this.parseTemplateElement({isTagged}))
}
this.next()
return this.finishNode(node, "TemplateLiteral")
}
pp.isAsyncProp = function(prop) {
return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
(this.type === tt.name || this.type === tt.num || this.type === tt.string || this.type === tt.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === tt.star)) &&
!lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
}
// Parse an object literal or binding pattern.
pp.parseObj = function(isPattern, refDestructuringErrors) {
let node = this.startNode(), first = true, propHash = {}
node.properties = []
this.next()
while (!this.eat(tt.braceR)) {
if (!first) {
this.expect(tt.comma)
if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(tt.braceR)) break
} else first = false
const prop = this.parseProperty(isPattern, refDestructuringErrors)
if (!isPattern) this.checkPropClash(prop, propHash, refDestructuringErrors)
node.properties.push(prop)
}
return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
}
pp.parseProperty = function(isPattern, refDestructuringErrors) {
let prop = this.startNode(), isGenerator, isAsync, startPos, startLoc
if (this.options.ecmaVersion >= 9 && this.eat(tt.ellipsis)) {
if (isPattern) {
prop.argument = this.parseIdent(false)
if (this.type === tt.comma) {
this.raise(this.start, "Comma is not permitted after the rest element")
}
return this.finishNode(prop, "RestElement")
}
// To disallow parenthesized identifier via `this.toAssignable()`.
if (this.type === tt.parenL && refDestructuringErrors) {
if (refDestructuringErrors.parenthesizedAssign < 0) {
refDestructuringErrors.parenthesizedAssign = this.start
}
if (refDestructuringErrors.parenthesizedBind < 0) {
refDestructuringErrors.parenthesizedBind = this.start
}
}
// Parse argument.
prop.argument = this.parseMaybeAssign(false, refDestructuringErrors)
// To disallow trailing comma via `this.toAssignable()`.
if (this.type === tt.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
refDestructuringErrors.trailingComma = this.start
}
// Finish
return this.finishNode(prop, "SpreadElement")
}
if (this.options.ecmaVersion >= 6) {
prop.method = false
prop.shorthand = false
if (isPattern || refDestructuringErrors) {
startPos = this.start
startLoc = this.startLoc
}
if (!isPattern)
isGenerator = this.eat(tt.star)
}
let containsEsc = this.containsEsc
this.parsePropertyName(prop)
if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
isAsync = true
isGenerator = this.options.ecmaVersion >= 9 && this.eat(tt.star)
this.parsePropertyName(prop, refDestructuringErrors)
} else {
isAsync = false
}
this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc)
return this.finishNode(prop, "Property")
}
pp.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
if ((isGenerator || isAsync) && this.type === tt.colon)
this.unexpected()
if (this.eat(tt.colon)) {
prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors)
prop.kind = "init"
} else if (this.options.ecmaVersion >= 6 && this.type === tt.parenL) {
if (isPattern) this.unexpected()
prop.kind = "init"
prop.method = true
prop.value = this.parseMethod(isGenerator, isAsync)
} else if (!isPattern && !containsEsc &&
this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
(prop.key.name === "get" || prop.key.name === "set") &&
(this.type !== tt.comma && this.type !== tt.braceR && this.type !== tt.eq)) {
if (isGenerator || isAsync) this.unexpected()
prop.kind = prop.key.name
this.parsePropertyName(prop)
prop.value = this.parseMethod(false)
let paramCount = prop.kind === "get" ? 0 : 1
if (prop.value.params.length !== paramCount) {
let start = prop.value.start
if (prop.kind === "get")
this.raiseRecoverable(start, "getter should have no params")
else
this.raiseRecoverable(start, "setter should have exactly one param")
} else {
if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params")
}
} else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
if (isGenerator || isAsync) this.unexpected()
this.checkUnreserved(prop.key)
if (prop.key.name === "await" && !this.awaitIdentPos)
this.awaitIdentPos = startPos
prop.kind = "init"
if (isPattern) {
prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key))
} else if (this.type === tt.eq && refDestructuringErrors) {
if (refDestructuringErrors.shorthandAssign < 0)
refDestructuringErrors.shorthandAssign = this.start
prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key))
} else {
prop.value = this.copyNode(prop.key)
}
prop.shorthand = true
} else this.unexpected()
}
pp.parsePropertyName = function(prop) {
if (this.options.ecmaVersion >= 6) {
if (this.eat(tt.bracketL)) {
prop.computed = true
prop.key = this.parseMaybeAssign()
this.expect(tt.bracketR)
return prop.key
} else {
prop.computed = false
}
}
return prop.key = this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
}
// Initialize empty function node.
pp.initFunction = function(node) {
node.id = null
if (this.options.ecmaVersion >= 6) node.generator = node.expression = false
if (this.options.ecmaVersion >= 8) node.async = false
}
// Parse object or class method.
pp.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
let node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos
this.initFunction(node)
if (this.options.ecmaVersion >= 6)
node.generator = isGenerator
if (this.options.ecmaVersion >= 8)
node.async = !!isAsync
this.yieldPos = 0
this.awaitPos = 0
this.awaitIdentPos = 0
this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0))
this.expect(tt.parenL)
node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8)
this.checkYieldAwaitInDefaultParams()
this.parseFunctionBody(node, false, true)
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
this.awaitIdentPos = oldAwaitIdentPos
return this.finishNode(node, "FunctionExpression")
}
// Parse arrow function expression with given parameters.
pp.parseArrowExpression = function(node, params, isAsync) {
let oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos
this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW)
this.initFunction(node)
if (this.options.ecmaVersion >= 8) node.async = !!isAsync
this.yieldPos = 0
this.awaitPos = 0
this.awaitIdentPos = 0
node.params = this.toAssignableList(params, true)
this.parseFunctionBody(node, true, false)
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
this.awaitIdentPos = oldAwaitIdentPos
return this.finishNode(node, "ArrowFunctionExpression")
}
// Parse function body and check parameters.
pp.parseFunctionBody = function(node, isArrowFunction, isMethod) {
let isExpression = isArrowFunction && this.type !== tt.braceL
let oldStrict = this.strict, useStrict = false
if (isExpression) {
node.body = this.parseMaybeAssign()
node.expression = true
this.checkParams(node, false)
} else {
let nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params)
if (!oldStrict || nonSimple) {
useStrict = this.strictDirective(this.end)
// If this is a strict mode function, verify that argument names
// are not repeated, and it does not try to bind the words `eval`
// or `arguments`.
if (useStrict && nonSimple)
this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list")
}
// Start a new scope with regard to labels and the `inFunction`
// flag (restore them to their old value afterwards).
let oldLabels = this.labels
this.labels = []
if (useStrict) this.strict = true
// Add the params to varDeclaredNames to ensure that an error is thrown
// if a let/const declaration in the function clashes with one of the params.
this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params))
// Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
if (this.strict && node.id) this.checkLValSimple(node.id, BIND_OUTSIDE)
node.body = this.parseBlock(false, undefined, useStrict && !oldStrict)
node.expression = false
this.adaptDirectivePrologue(node.body.body)
this.labels = oldLabels
}
this.exitScope()
}
pp.isSimpleParamList = function(params) {
for (let param of params)
if (param.type !== "Identifier") return false
return true
}
// Checks function params for various disallowed patterns such as using "eval"
// or "arguments" and duplicate parameters.
pp.checkParams = function(node, allowDuplicates) {
let nameHash = Object.create(null)
for (let param of node.params)
this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash)
}
// Parses a comma-separated list of expressions, and returns them as
// an array. `close` is the token type that ends the list, and
// `allowEmpty` can be turned on to allow subsequent commas with
// nothing in between them to be parsed as `null` (which is needed
// for array literals).
pp.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
let elts = [], first = true
while (!this.eat(close)) {
if (!first) {
this.expect(tt.comma)
if (allowTrailingComma && this.afterTrailingComma(close)) break
} else first = false
let elt
if (allowEmpty && this.type === tt.comma)
elt = null
else if (this.type === tt.ellipsis) {
elt = this.parseSpread(refDestructuringErrors)
if (refDestructuringErrors && this.type === tt.comma && refDestructuringErrors.trailingComma < 0)
refDestructuringErrors.trailingComma = this.start
} else {
elt = this.parseMaybeAssign(false, refDestructuringErrors)
}
elts.push(elt)
}
return elts
}
pp.checkUnreserved = function({start, end, name}) {
if (this.inGenerator && name === "yield")
this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator")
if (this.inAsync && name === "await")
this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function")
if (this.keywords.test(name))
this.raise(start, `Unexpected keyword '${name}'`)
if (this.options.ecmaVersion < 6 &&
this.input.slice(start, end).indexOf("\\") !== -1) return
const re = this.strict ? this.reservedWordsStrict : this.reservedWords
if (re.test(name)) {
if (!this.inAsync && name === "await")
this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function")
this.raiseRecoverable(start, `The keyword '${name}' is reserved`)
}
}
// Parse the next token as an identifier. If `liberal` is true (used
// when parsing properties), it will also convert keywords into
// identifiers.
pp.parseIdent = function(liberal, isBinding) {
let node = this.startNode()
if (this.type === tt.name) {
node.name = this.value
} else if (this.type.keyword) {
node.name = this.type.keyword
// To fix https://github.com/acornjs/acorn/issues/575
// `class` and `function` keywords push new context into this.context.
// But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
// If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
if ((node.name === "class" || node.name === "function") &&
(this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
this.context.pop()
}
} else {
this.unexpected()
}
this.next(!!liberal)
this.finishNode(node, "Identifier")
if (!liberal) {
this.checkUnreserved(node)
if (node.name === "await" && !this.awaitIdentPos)
this.awaitIdentPos = node.start
}
return node
}
// Parses yield expression inside generator.
pp.parseYield = function(noIn) {
if (!this.yieldPos) this.yieldPos = this.start
let node = this.startNode()
this.next()
if (this.type === tt.semi || this.canInsertSemicolon() || (this.type !== tt.star && !this.type.startsExpr)) {
node.delegate = false
node.argument = null
} else {
node.delegate = this.eat(tt.star)
node.argument = this.parseMaybeAssign(noIn)
}
return this.finishNode(node, "YieldExpression")
}
pp.parseAwait = function() {
if (!this.awaitPos) this.awaitPos = this.start
let node = this.startNode()
this.next()
node.argument = this.parseMaybeUnary(null, true)
return this.finishNode(node, "AwaitExpression")
}
| mit |
rickding/Hello | HelloHackerRank/src/main/java/com/hello/ReductionCost.java | 571 | package com.hello;
import java.util.Arrays;
public class ReductionCost {
public static int reductionCost(int[] numArr) {
if (numArr == null || numArr.length <= 0) {
return 0;
}
int cost = 0;
for (int i = 0; i < numArr.length - 1; i++) {
// Sort ascending
Arrays.sort(numArr);
// Pickup the smallest two ones
int sum = numArr[i] + numArr[i + 1];
numArr[i] = 0;
numArr[i + 1] = sum;
cost += sum;
}
return cost;
}
}
| mit |
DarkenNav/UnionFreeArts | DesktopApp/UI.Desktop.UFart/Mapping/MapperConfigurate.cs | 575 | using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UFart.Desktop.Domain.Entity;
using UFart.Desktop.UI.DTO;
namespace UFart.Desktop.UI.Mapping
{
public static class MapperConfigurate
{
internal static void Initialize(IMapperConfigurationExpression cfg)
{
cfg.CreateMap<Site, SiteDTO>();
cfg.CreateMap<SiteDTO, Site>();
cfg.CreateMap<Person, PersonDTO>();
cfg.CreateMap<PersonDTO, Person>();
}
}
}
| mit |
alphagov/publishing-api | spec/commands/v2/represent_downstream_spec.rb | 3911 | require "rails_helper"
RSpec.describe Commands::V2::RepresentDownstream do
before do
stub_request(:put, %r{.*content-store.*/content/.*})
end
describe "call" do
before do
2.times { create(:draft_edition) }
create(
:live_edition,
document: create(:document, locale: "en"),
document_type: "nonexistent-schema",
)
create(
:live_edition,
document: create(:document, locale: "fr"),
document_type: "nonexistent-schema",
)
create(:live_edition, document_type: "press_release")
end
context "downstream live" do
it "sends to downstream live worker" do
expect(DownstreamLiveWorker).to receive(:perform_async_in_queue)
.exactly(3).times
subject.call(Document.pluck(:content_id), with_drafts: false)
end
it "uses 'downstream_low' queue" do
expect(DownstreamLiveWorker).to receive(:perform_async_in_queue)
.with("downstream_low", anything)
.at_least(1).times
subject.call(Document.pluck(:content_id), with_drafts: false)
end
it "doesn't update dependencies" do
expect(DownstreamLiveWorker).to receive(:perform_async_in_queue)
.with(anything, a_hash_including(update_dependencies: false))
.at_least(1).times
subject.call(Document.pluck(:content_id), with_drafts: false)
end
it "has a message_queue_event_type of 'links'" do
expect(DownstreamLiveWorker).to receive(:perform_async_in_queue)
.with(anything, a_hash_including(message_queue_event_type: "links"))
.at_least(1).times
subject.call(Document.pluck(:content_id), with_drafts: false)
end
it "updates for each locale" do
expect(DownstreamLiveWorker).to receive(:perform_async_in_queue)
.with(anything, a_hash_including(locale: "en"))
.exactly(2).times
expect(DownstreamLiveWorker).to receive(:perform_async_in_queue)
.with(anything, a_hash_including(locale: "fr"))
.exactly(1).times
subject.call(Document.pluck(:content_id), with_drafts: false)
end
it "has a source_command of 'represent_downstream'" do
expect(DownstreamLiveWorker).to receive(:perform_async_in_queue)
.with(anything, a_hash_including(source_command: "represent_downstream"))
.at_least(1).times
subject.call(Document.pluck(:content_id), with_drafts: false)
end
end
context "scope" do
it "can specify a scope" do
expect(DownstreamLiveWorker).to receive(:perform_async_in_queue)
.with("downstream_low", a_hash_including(:content_id, :locale))
.exactly(2).times
subject.call(
Edition.with_document.where(document_type: "nonexistent-schema").pluck("documents.content_id"),
with_drafts: false,
)
end
end
context "drafts optional" do
it "can send to downstream draft worker" do
expect(DownstreamDraftWorker).to receive(:perform_async_in_queue)
.with(
"downstream_low",
a_hash_including(:content_id, :locale, update_dependencies: false),
)
.exactly(5).times
subject.call(Document.pluck(:content_id), with_drafts: true)
end
it "can not send to downstream draft worker" do
expect(DownstreamDraftWorker).to_not receive(:perform_async_in_queue)
subject.call(Document.pluck(:content_id), with_drafts: false)
end
end
context "queue optional" do
it "can be set to use the high priority queue" do
expect(DownstreamLiveWorker).to receive(:perform_async_in_queue)
.with("downstream_high", a_hash_including(:content_id))
.at_least(1).times
subject.call(Document.pluck(:content_id), queue: DownstreamQueue::HIGH_QUEUE)
end
end
end
end
| mit |
NewSpring/Apollos | src/@data/withUser/withAddressState.js | 1065 | import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
export const QUERY = gql`
query GetAddressState($state: Int!, $country: Int!) {
states: definedValues(id: $state, all: true) {
description
id
_id
value
}
countries: definedValues(id: $country, all: true) {
description
id
_id
value
}
person: currentPerson {
id
firstName
nickName
lastName
email
home {
id
street1
street2
city
state
zip
country
}
}
}
`;
export default graphql(QUERY, {
options: {
variables: {
state: 28,
country: 45,
},
},
props({ ownProps, data }) {
const {
countries, states, person, loading,
} = data;
return {
isLoading: ownProps.isLoading || loading,
countries: (countries || []).map(c => ({ label: c.description, id: c.value })),
states: (states || []).map(s => ({ label: s.description, id: s.value })),
person,
};
},
});
| mit |
r4ndr4s4/draw-sth | imports/views/view/view.events.js | 635 | 'use strict';
import { viewState } from './';
Template.view.events({
'keyup #tip' (event, templateInstance) {
const roomId = localStorage.getItem('roomId');
const userId = localStorage.getItem('userId');
const tip = $(event.currentTarget).val().trim().toLowerCase();
$(event.currentTarget).val(tip);
viewState.set('tipLength', tip.length);
if (tip.length >= viewState.get('wordLength')) {
Meteor.call('checkTip', roomId, userId, tip, function (error, result) {
if (error) return toastr.error('Sending the tip failed!');
$(event.currentTarget).val('');
viewState.set('tipLength', 0);
});
}
}
});
| mit |
begriffs/ramda | test/test.range.js | 871 | var assert = require("assert");
var Lib = require("./../ramda");
describe('range', function() {
var range = Lib.range;
it('should return list of numbers', function() {
assert.deepEqual(range(0, 5), [0, 1, 2, 3, 4]);
assert.deepEqual(range(4, 7), [4, 5, 6]);
});
it('should return the empty list if the first parameter is not larger than the second', function() {
assert.deepEqual(range(7, 3), []);
assert.deepEqual(range(5, 5), []);
});
it('should be automatically curried', function() {
var from10 = range(10);
assert.deepEqual(from10(15), [10, 11, 12, 13, 14]);
});
it('should return an empty array if from > to', function() {
var result = range(10, 5);
assert.deepEqual(result, []);
result.push(5);
assert.deepEqual(range(10, 5), []);
});
});
| mit |
joshfrench/radiant | lib/generators/instance/templates/instance_environment.rb | 3828 | # Be sure to restart your server when you modify this file
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
require File.join(File.dirname(__FILE__), 'boot')
require 'radius'
Radiant::Initializer.run do |config|
# Skip frameworks you're not going to use (only works if using vendor/rails).
# To use Rails without a database, you must remove the Active Record framework
config.frameworks -= [ :action_mailer ]
# Only load the extensions named here, in the order given. By default all
# extensions in vendor/extensions are loaded, in alphabetical order. :all
# can be used as a placeholder for all extensions not explicitly named.
# config.extensions = [ :all ]
# By default, only English translations are loaded. Remove any of these from
# the list below if you'd like to provide any of the supported languages
config.extensions -= [:dutch_language_pack, :french_language_pack, :german_language_pack,
:italian_language_pack, :japanese_language_pack, :russian_language_pack]
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
config.action_controller.session = {
:session_key => '_<%= app_name %>_session',
:secret => <% require 'digest/sha1' %>'<%= Digest::SHA1.hexdigest("--#{app_name}--#{Time.now.to_s}--#{rand(10000000)}--") %>'
}
# Comment out this line if you want to turn off all caching, or
# add options to modify the behavior. In the majority of deployment
# scenarios it is desirable to leave Radiant's cache enabled and in
# the default configuration.
#
# Additional options:
# :use_x_sendfile => true
# Turns on X-Sendfile support for Apache with mod_xsendfile or lighttpd.
# :use_x_accel_redirect => '/some/virtual/path'
# Turns on X-Accel-Redirect support for nginx. You have to provide
# a path that corresponds to a virtual location in your webserver
# configuration.
# :entitystore => "radiant:tmp/cache/entity"
# Sets the entity store type (preceding the colon) and storage
# location (following the colon, relative to Rails.root).
# We recommend you use radiant: since this will enable manual expiration.
# :metastore => "radiant:tmp/cache/meta"
# Sets the meta store type and storage location. We recommend you use
# radiant: since this will enable manual expiration and acceleration headers.
config.middleware.use ::Radiant::Cache
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with 'rake db:sessions:create')
config.action_controller.session_store = :cookie_store
# Activate observers that should always be running
config.active_record.observers = :user_action_observer
# Make Active Record use UTC-base instead of local time
config.time_zone = 'UTC'
# Set the default field error proc
config.action_view.field_error_proc = Proc.new do |html, instance|
if html !~ /label/
%{<span class="error-with-field">#{html} <span class="error">• #{[instance.error_message].flatten.first}</span></span>}
else
html
end
end
config.gem 'will_paginate', :version => '~> 2.3.11', :source => 'http://gemcutter.org'
config.after_initialize do
# Add new inflection rules using the following format:
ActiveSupport::Inflector.inflections do |inflect|
inflect.uncountable 'config'
end
end
end | mit |
huyson012/fuelphp | fuel/app/classes/model/PageInfo.php | 144 | <?php
//
namespace Model;
class PageInfo {
public function getPageInfo() {
return "training fueldPHP page title";
}
}
| mit |
marinovskiy/money_manager_server | src/AppBundle/Controller/Api/ApiReportsController.php | 8921 | <?php
namespace AppBundle\Controller\Api;
use AppBundle\Entity\Account;
use AppBundle\Entity\Category;
use AppBundle\Entity\Operation;
use AppBundle\Entity\Organization;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
/**
* @Route("/api/report")
*/
class ApiReportsController extends Controller
{
// /**
// * @Route("/test", name="api_report")
// * @Method("GET")
// */
// public function apiReportAction1(Request $request)
// {
// $em = $this->getDoctrine()->getManager();
//
// $searchType = $request->query->get('searchType');
// if ($searchType) {
//// if ($searchType != 'user' || $searchType != 'organization') {
//// return $this->json('Wrong search type', 400);
//// }
//
// $accountsIds = array();
//
// if ($searchType == 'user') {
// foreach ($this->getUser()->getAccounts() as $account) {
// array_push($accountsIds, $account->getId());
// }
// } else if ($searchType == 'organization') {
// $organizationId = $request->query->get('organizationId');
// if (!$organizationId) {
// return $this->json('No organizationId provided', 400);
// }
//
// $organization = $em->getRepository(Organization::class)->find($organizationId);
// if (!$organization) {
// return $this->json('Organization not found', 404);
// }
//
// $membersIds = array();
// foreach ($organization->getMembers() as $member) {
// array_push($membersIds, $member->getId());
// }
// if (!in_array($this->getUser()->getId(), $membersIds)) {
// return $this->json('Not a member', 403);
// }
//
// foreach ($organization->getAccounts() as $account) {
// array_push($accountsIds, $account->getId());
// }
// } else {
// return $this->json('Wrong search type', 400);
// }
// } else {
// $accountsIds = $request->query->get('accountId');
// }
//
//// $accounts = $this
//// ->getDoctrine()
//// ->getRepository(Account::class)
//// ->loadAccounts($accountsIds);
// $type = $request->query->get('operationType');
// $categoriesIds = $request->query->get('categoryId');
//
// $categories = array();
// if ($categoriesIds) {
// foreach ($categoriesIds as $categoryId) {
// $category = $em->getRepository(Category::class)->find($categoryId);
// if (!$category) {
// continue;
// }
// array_push($categories, $category);
// }
// }
//
// $operations = array();
//
// foreach ($accountsIds as $accountId) {
// $account = $em->getRepository(Account::class)->find($accountId);
// if (!$account) {
// continue;
// }
//
// if ($account->getUser()) {
// if ($account->getUser()->getId() != $this->getUser()->getId()) {
// continue;
// }
// } else if ($account->getOrganization()) {
// $organization = $em->getRepository(Organization::class)->find($account->getOrganization()->getId());
// if (!$organization) {
// continue;
// }
//
// $membersIds = array();
// foreach ($organization->getMembers() as $member) {
// array_push($membersIds, $member->getId());
// }
// if (!in_array($this->getUser()->getId(), $membersIds)) {
// continue;
// }
// }
//
// foreach ($account->getOperations() as $operation) {
// if ($type) {
// if ($operation->getType() == $type) {
// array_push($operations, $operation);
// }
// } else if ($categories) {
// if (in_array($operation->getCategory(), $categories)) {
// array_push($operations, $operation);
// }
// } else {
// array_push($operations, $operation);
// }
// }
// }
//
// return $this->json(['operations' => $operations], 200);
// }
/**
* @Route("/get", name="api_report")
* @Method("GET")
*/
public function apiReportAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$accounts = array();
if ($request->query->has('accountId')) {
$accountId = $request->query->get('accountId');
$account = $em->getRepository(Account::class)->find($accountId);
if (!$account) {
return $this->json(['msg' => 'not found'], 404);
}
if ($this->getUser()->getId() != $account->getUser()->getId()) {
return $this->json(['msg' => 'not owner'], 403);
}
array_push($accounts, $account);
} else if ($request->query->has('organizationId')) {
$organizationId = $request->query->get('organizationId');
$organization = $em->getRepository(Organization::class)->find($organizationId);
if (!$organization) {
return $this->json(['msg' => 'not found'], 404);
}
$membersIds = array();
foreach ($organization->getMembers() as $member) {
array_push($membersIds, $member->getId());
}
if (!in_array($this->getUser()->getId(), $membersIds)) {
return $this->json(['msg' => 'not a member'], 403);
}
foreach ($organization->getAccounts() as $acc) {
array_push($accounts, $acc);
}
} else {
if (!$this->getUser()) {
return $this->json(['msg' => 'bad request'], 400);
}
$accounts = $em->getRepository(Account::class)->findBy(['user' => $this->getUser()->getId()]);
}
$operationsAll = array();
$operations = array();
foreach ($accounts as $acc) {
foreach ($acc->getOperations() as $opr) {
array_push($operationsAll, $opr);
}
}
if ($request->query->has('type') || $request->query->has('categoryId') || $request->query->has('fromDate') || $request->query->has('toDate')) {
$type = $request->query->get('type');
$categories = $request->query->get('categoryId');
$fromDate = $request->query->get('fromDate');
$toDate = $request->query->get('toDate');
if ($request->query->has('type')) {
if ($type == 'all') {
foreach ($operationsAll as $opr) {
array_push($operations, $opr);
}
} else {
foreach ($operationsAll as $opr) {
if ($opr->getType() == $type) {
array_push($operations, $opr);
}
}
}
} else if ($request->query->has('categoryId')) {
foreach ($operationsAll as $opr) {
if (in_array($opr->getCategory()->getId(), $categories)) {
array_push($operations, $opr);
}
}
}
if ($request->query->has('fromDate') && $request->query->has('toDate')) {
foreach ($operationsAll as $opr) {
if ($opr->getCreatedAt()->getTimestamp() >= $fromDate && $opr->getCreatedAt()->getTimestamp() <= $toDate && !in_array($opr, $operations)) {
array_push($operations, $opr);
}
}
}
} else {
$operations = $operationsAll;
}
$operationsSumIncome = 0;
$operationsSumExpense = 0;
foreach ($operations as $opr) {
if ($opr->getType() == Operation::TYPE_INCOME) {
$operationsSumIncome = $operationsSumIncome + $opr->getSum();
} else {
$operationsSumExpense = $operationsSumExpense - $opr->getSum();
}
}
return $this->json(['operations' => $operations, 'operationSumIncome' => $operationsSumIncome, 'operationsSumExpense' => $operationsSumExpense], 200);
}
} | mit |
mojmir-svoboda/BlackBoxTT | plugins/bbInterface/src/AgentType_SystemInfo.cpp | 21532 | /*===================================================
AGENTTYPE_SYSTEMINFO CODE
===================================================*/
// Global Include
#include <blackbox/plugin/bb.h>
#include <string.h>
#include <windows.h>
#include <tchar.h>
//Parent Include
#include "AgentType_SystemInfo.h"
//Includes
#include "PluginMaster.h"
#include "AgentMaster.h"
#include "Definitions.h"
#include "ConfigMaster.h"
#include "MessageMaster.h"
#include "ListMaster.h"
#ifndef SM_TABLETPC
#define SM_TABLETPC 86
#endif
#ifndef SM_MEDIACENTER
#define SM_MEDIACENTER 87
#endif
#ifndef SM_STARTER
#define SM_STARTER 88
#endif
#ifndef SM_SERVERR2
#define SM_SERVERR2 89
#endif
#ifndef VER_SUITE_WH_SERVER
#define VER_SUITE_WH_SERVER 0x00008000
#endif
//Declare the function prototypes;
VOID CALLBACK agenttype_systeminfo_timercall(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime);
LRESULT CALLBACK agenttype_systeminfo_event(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
void agenttype_systeminfo_propogatenewvalues();
void agenttype_systeminfo_updatevalue(int monitor_type);
wchar_t * GetOSDetailInfo(wchar_t * os_string, size_t n, int type);
// Some windowing variables
HWND agenttype_systeminfo_window;
bool agenttype_systeminfo_windowclassregistered;
//Local primitives
unsigned long agenttype_systeminfo_counter;
const wchar_t agenttype_systeminfo_timerclass[] = L"BBInterfaceAgentSystemInfo";
//A list of this type of agent
list *agenttype_systeminfo_agents;
bool agenttype_systeminfo_hastimer = false;
//Declare the number of types
#define SYSTEMINFO_NUMTYPES 8
//Array of string types - must have SYSTEMINFO_NUMTYPES entries
enum SYSTEMINFO_TYPE
{
SYSTEMINFO_TYPE_NONE = 0,
SYSTEMINFO_TYPE_HOSTNAME,
SYSTEMINFO_TYPE_USERNAME,
SYSTEMINFO_TYPE_UPTIME,
SYSTEMINFO_TYPE_OSNAME,
SYSTEMINFO_TYPE_OSBUILDNUM,
SYSTEMINFO_TYPE_BBVER,
SYSTEMINFO_TYPE_STYLENAME
};
//Must match the enum ordering above! Must have SYSTEMINFO_NUMTYPES entries
const wchar_t *agenttype_systeminfo_types[] =
{
L"None", // Unused
L"HostName",
L"UserName",
L"Uptime",
L"OSName",
L"OSBuildNum",
L"BBVer",
L"StyleName"
};
//Must match the enum ordering above! Must have SYSTEMINFO_NUMTYPES entries
const wchar_t *agenttype_systeminfo_friendlytypes[] =
{
L"None", // Unused
L"Host Name",
L"User Name",
L"Uptime",
L"OS Name",
L"OS Build Number",
L"BB Version",
L"Style Name"
};
//Must be the same size as the above array and enum
wchar_t agenttype_systeminfo_values[SYSTEMINFO_NUMTYPES][256];
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//controltype_button_startup
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int agenttype_systeminfo_startup()
{
//Create the list
agenttype_systeminfo_agents = list_create();
//Register the window class
agenttype_systeminfo_windowclassregistered = false;
if (window_helper_register(agenttype_systeminfo_timerclass, &agenttype_systeminfo_event))
{
//Couldn't register the window
BBMessageBox(NULL, L"failed on register class", L"test", MB_OK);
return 1;
}
agenttype_systeminfo_windowclassregistered = true;
//Create the window
agenttype_systeminfo_window = window_helper_create(agenttype_systeminfo_timerclass);
if (!agenttype_systeminfo_window)
{
//Couldn't create the window
BBMessageBox(NULL, L"failed on window", "test", MB_OK);
return 1;
}
//initialize
for (int i = 1; i < SYSTEMINFO_NUMTYPES; i++){
agenttype_systeminfo_updatevalue(i);
}
//If we got this far, we can successfully use this function
//Register this type with the AgentMaster
agent_registertype(
L"System Information", //Friendly name of agent type
L"SystemInfo", //Name of agent type
CONTROL_FORMAT_TEXT, //Control type
false,
&agenttype_systeminfo_create,
&agenttype_systeminfo_destroy,
&agenttype_systeminfo_message,
&agenttype_systeminfo_notify,
&agenttype_systeminfo_getdata,
&agenttype_systeminfo_menu_set,
&agenttype_systeminfo_menu_context,
&agenttype_systeminfo_notifytype
);
//No errors
return 0;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//agenttype_systeminfo_shutdown
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int agenttype_systeminfo_shutdown()
{
if(agenttype_systeminfo_hastimer){
agenttype_systeminfo_hastimer = false;
KillTimer(agenttype_systeminfo_window, 0);
}
//Destroy the internal tracking list
if (agenttype_systeminfo_agents) list_destroy(agenttype_systeminfo_agents);
//Destroy the window
if (agenttype_systeminfo_window) window_helper_destroy(agenttype_systeminfo_window);
//Unregister the window class
if (agenttype_systeminfo_windowclassregistered) window_helper_unregister(agenttype_systeminfo_timerclass);
//No errors
return 0;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//agenttype_systeminfo_create
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int agenttype_systeminfo_create(agent *a, wchar_t *parameterstring)
{
if (0 == * parameterstring)
return 2; // no param, no agent
//Find the monitor type
int monitor_type = SYSTEMINFO_TYPE_NONE;
for (int i = 1; i < SYSTEMINFO_NUMTYPES; i++)
{
if (_wcsicmp(agenttype_systeminfo_types[i], parameterstring) == 0)
{
monitor_type = i;
break;
}
}
//If we didn't find a correct monitor type
if (monitor_type == SYSTEMINFO_TYPE_NONE)
{
//On an error
if (!plugin_suppresserrors)
{
wchar_t buffer[1000];
swprintf(buffer,1000, L"There was an error setting the System Information agent:\n\nType \"%s\" is not a valid type.", parameterstring);
BBMessageBox(NULL, buffer, szAppName, MB_OK|MB_SYSTEMMODAL);
}
return 1;
}
//Create the details
agenttype_systeminfo_details *details = new agenttype_systeminfo_details;
details->monitor_type = monitor_type;
//Create a unique string to assign to this (just a number from a counter)
wchar_t identifierstring[64];
swprintf(identifierstring, L"%ul", agenttype_systeminfo_counter);
details->internal_identifier = new_string(identifierstring);
//Set the details
a->agentdetails = (void *)details;
//Add this to our internal tracking list ( need update value only )
if(details->monitor_type == SYSTEMINFO_TYPE_UPTIME || details->monitor_type == SYSTEMINFO_TYPE_STYLENAME){
agent *oldagent;
list_add(agenttype_systeminfo_agents, details->internal_identifier, (void *) a, (void **) &oldagent);
agenttype_systeminfo_updatevalue(details->monitor_type);
//Start Timer
if (!agenttype_systeminfo_hastimer)
{
SetTimer(agenttype_systeminfo_window, 0, 1000, agenttype_systeminfo_timercall);
agenttype_systeminfo_hastimer = true;
}
}
//Increment the counter
agenttype_systeminfo_counter++;
//No errors
return 0;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//agenttype_systeminfo_destroy
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int agenttype_systeminfo_destroy(agent *a)
{
if (a->agentdetails)
{
agenttype_systeminfo_details *details = (agenttype_systeminfo_details *) a->agentdetails;
//Delete from the tracking list
if(details->monitor_type == SYSTEMINFO_TYPE_UPTIME || details->monitor_type == SYSTEMINFO_TYPE_STYLENAME){
list_remove(agenttype_systeminfo_agents, details->internal_identifier);
}
//Free the string
free_string(&details->internal_identifier);
delete details;
a->agentdetails = NULL;
}
//No errors
return 0;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//agenttype_systeminfo_message
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int agenttype_systeminfo_message(agent *a, int tokencount, wchar_t *tokens[])
{
//No errors
return 0;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//agenttype_systeminfo_notify
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void agenttype_systeminfo_notify(agent *a, int notifytype, void *messagedata)
{
//Get the agent details
agenttype_systeminfo_details *details = (agenttype_systeminfo_details *) a->agentdetails;
switch(notifytype)
{
case NOTIFY_CHANGE:
control_notify(a->controlptr, NOTIFY_NEEDUPDATE, NULL);
break;
case NOTIFY_SAVE_AGENT:
//Write existance
config_write(config_get_control_setagent_c(a->controlptr, a->agentaction, a->agenttypeptr->agenttypename, agenttype_systeminfo_types[details->monitor_type]));
break;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//agenttype_systeminfo_getdata
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void *agenttype_systeminfo_getdata(agent *a, int datatype)
{
//Get the agent details
agenttype_systeminfo_details *details = (agenttype_systeminfo_details *) a->agentdetails;
return &agenttype_systeminfo_values[details->monitor_type];
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//agenttype_systeminfo_menu_set
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void agenttype_systeminfo_menu_set(std::shared_ptr<bb::MenuConfig> m, control *c, agent *a, wchar_t *action, int controlformat)
{
//Add a menu item for every type
for (int i = 1; i < SYSTEMINFO_NUMTYPES; i++)
{
make_menuitem_cmd(m, agenttype_systeminfo_friendlytypes[i], config_getfull_control_setagent_c(c, action, L"SystemInfo", agenttype_systeminfo_types[i]));
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//agenttype_systeminfo_menu_context
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void agenttype_systeminfo_menu_context(std::shared_ptr<bb::MenuConfig> m, agent *a)
{
make_menuitem_nop(m, L"No options available.");
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//agenttype_systeminfo_notifytype
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void agenttype_systeminfo_notifytype(int notifytype, void *messagedata)
{
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//agenttype_systeminfo_timercall
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
VOID CALLBACK agenttype_systeminfo_timercall(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
//If there are agents left
if (agenttype_systeminfo_agents->first != NULL)
{
agenttype_systeminfo_propogatenewvalues();
}
else
{
agenttype_systeminfo_hastimer = false;
KillTimer(hwnd, 0);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//agenttype_systeminfo_event
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
LRESULT CALLBACK agenttype_systeminfo_event(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return DefWindowProc(hwnd, msg, wParam, lParam);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//agenttype_systeminfo_propogatenewvalues
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void agenttype_systeminfo_propogatenewvalues()
{
//Declare variables
agent *currentagent;
//Go through every agent
listnode *currentnode;
dolist(currentnode, agenttype_systeminfo_agents)
{
//Get the agent
currentagent = (agent *) currentnode->value;
//Get the monitor type
int monitor_type = ((agenttype_systeminfo_details *) (currentagent->agentdetails))->monitor_type;
//Calculate a new value for this type
agenttype_systeminfo_updatevalue(monitor_type);
control_notify(currentagent->controlptr, NOTIFY_NEEDUPDATE, NULL);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//agenttype_systeminfo_updatevalue
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void agenttype_systeminfo_updatevalue(int monitor_type)
{
wchar_t tmpstr[256];
DWORD len = 256;
DWORD time;
switch(monitor_type)
{
case SYSTEMINFO_TYPE_HOSTNAME:
if(GetComputerName(tmpstr,&len))
wcsncpy(agenttype_systeminfo_values[monitor_type],tmpstr,256);
break;
case SYSTEMINFO_TYPE_USERNAME:
if(GetUserName(tmpstr,&len))
wcsncpy(agenttype_systeminfo_values[monitor_type],tmpstr,256);
break;
case SYSTEMINFO_TYPE_UPTIME:
time = GetTickCount();
swprintf(agenttype_systeminfo_values[monitor_type],256, L"%dd %2dh %2dm %2ds",time/86400000,(time/3600000)%24,(time/60000)%60,(time/1000)%60);
break;
case SYSTEMINFO_TYPE_OSNAME:
case SYSTEMINFO_TYPE_OSBUILDNUM:
GetOSDetailInfo(agenttype_systeminfo_values[monitor_type], 256, monitor_type);
break;
case SYSTEMINFO_TYPE_BBVER:
wcsncpy(agenttype_systeminfo_values[monitor_type],GetBBVersion(),256);
break;
case SYSTEMINFO_TYPE_STYLENAME:
wcsncpy(agenttype_systeminfo_values[monitor_type], ReadString(stylePath(), L"style.name:", L"no name"), 256);
break;
}
return;
}
//-------------------------------------------------------------
//GetOSDetailInfo
//-------------------------------------------------------------
wchar_t * GetOSDetailInfo(wchar_t *os_string, size_t n, int type){
OSVERSIONINFOEX osver;
BOOL success_getver;
typedef BOOL (WINAPI *PFUNC_GetProductInfo)(DWORD, DWORD, DWORD, DWORD, PDWORD);
PFUNC_GetProductInfo pGetProductInfo = NULL;
DWORD dwReturnedProductType = 0;
ZeroMemory(&osver,sizeof(OSVERSIONINFOEX));
osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if(!(success_getver = GetVersionEx((OSVERSIONINFO *) &osver)))
{
//OSVERSIONINFOEX does not support
osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx((OSVERSIONINFO *) &osver);
}
if(type == SYSTEMINFO_TYPE_OSBUILDNUM){
if(osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS){
swprintf(os_string, n, L"%d",LOWORD(osver.dwBuildNumber));
}else{
swprintf(os_string, n, L"%d",osver.dwBuildNumber);
}
return os_string;
}
if(osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
{
switch(osver.dwMinorVersion){
case 0:
if( LOWORD(osver.dwBuildNumber) == 1111){
wcscpy(os_string,L"Windows 95 OSR2");
}else if( LOWORD(osver.dwBuildNumber) >= 1214){
wcscpy(os_string,L"Windows 95 OSR2.5");
}else if( LOWORD(osver.dwBuildNumber) >= 1212){
wcscpy(os_string,L"Windows 95 OSR2.1");
}else{
wcscpy(os_string,L"Windows 95");
}
break;
case 10:
if( LOWORD(osver.dwBuildNumber) >= 2222){
wcscpy(os_string,L"Windows 98 SE");
}else if( LOWORD(osver.dwBuildNumber) >= 2000){
wcscpy(os_string,L"Windows 98 SP1");
}else{
wcscpy(os_string,L"Windows 98");
}
break;
case 90:
wcscpy(os_string,L"Windows Me");
break;
default:
wcscpy(os_string,L"Windows 9x");
break;
}
}
else if(osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
{
if(osver.dwMajorVersion == 3){
swprintf(os_string, n, L"Windows NT3.%d",osver.dwMinorVersion);
}else if(osver.dwMajorVersion == 4){
if(success_getver){
if(osver.wProductType == VER_NT_WORKSTATION){
wcscpy(os_string, L"Windows NT Workstation 4.0");
}else if(osver.wProductType == VER_NT_SERVER){
wcscpy(os_string, L"Windows NT Server 4.0");
}else{
wcscpy(os_string, L"Windows NT 4.0");
}
if(osver.wSuiteMask & VER_SUITE_ENTERPRISE){
wcscat(os_string, L" Enterprise Edition");
}
}
else{
wcscpy(os_string,L"Windows NT 4.0");
}
}else if(osver.dwMajorVersion == 5){
if(osver.dwMinorVersion == 0){ // Win2k
if(success_getver){
if(osver.wProductType == VER_NT_WORKSTATION){
wcscpy(os_string, L"Windows 2000 Professional");
}else if(osver.wProductType == VER_NT_SERVER){
if(osver.wSuiteMask & VER_SUITE_ENTERPRISE){
wcscpy(os_string, L"Windows 2000 Advanced Server");
}else if(osver.wSuiteMask & VER_SUITE_DATACENTER){
wcscpy(os_string, L"Windows 2000 Datacenter Server");
}else{
wcscpy(os_string, L"Windows 2000 Server");
}
}else{
wcscpy(os_string,L"Windows 2000");
}
}else{
wcscpy(os_string,L"Windows 2000");
}
}else if(osver.dwMinorVersion == 1){ // WinXP
if(success_getver){
if(GetSystemMetrics(SM_MEDIACENTER)){
wcscpy(os_string,L"Windows XP Media Center Edition");
}else if(GetSystemMetrics(SM_TABLETPC)){
wcscpy(os_string,L"Windows XP Tablet PC Edition");
}else if(GetSystemMetrics(SM_STARTER)){
wcscpy(os_string,L"Windows XP Starter Edition");
}else if(osver.wSuiteMask & VER_SUITE_PERSONAL){
wcscpy(os_string,L"Windows XP Home Edition");
}else{
wcscpy(os_string,L"Windows XP Professional");
}
}else{
wcscpy(os_string,L"Windows XP");
}
}else if(osver.dwMinorVersion == 2){ //WinServer2003
if(success_getver){
wchar_t r2[4];
wcscpy(r2, GetSystemMetrics(SM_SERVERR2)? L" R2": L"");
if(osver.wProductType == VER_NT_WORKSTATION){
wcscpy(os_string,L"Windows XP Professional x64 Edition");
}else if(osver.wSuiteMask & VER_SUITE_ENTERPRISE){
swprintf(os_string,n,L"Windows Server 2003%s Enterprise Edition",r2);
}else if(osver.wSuiteMask & VER_SUITE_DATACENTER){
swprintf(os_string,n,L"Windows Server 2003%s Datacenter Edition",r2);
}else if(osver.wSuiteMask & VER_SUITE_BLADE){
swprintf(os_string,n,L"Windows Server 2003%s Web Edition",r2);
}else if(osver.wSuiteMask & VER_SUITE_COMPUTE_SERVER){
swprintf(os_string,n,L"Windows Server 2003%s Compute Cluster Edition",r2);
}else if(osver.wSuiteMask & VER_SUITE_STORAGE_SERVER){
swprintf(os_string,n,L"Windows Storage Server 2003%s",r2);
}else if(osver.wSuiteMask & VER_SUITE_SMALLBUSINESS_RESTRICTED){
swprintf(os_string,n,L"Microsoft Small Business Server 2003%s",r2);
}else if(osver.wSuiteMask & VER_SUITE_WH_SERVER){
wcscpy(os_string,L"Windows Home Server");
}else{
swprintf(os_string,n,L"Windows Server 2003%s Standard Edition",r2);
}
}else{
wcscpy(os_string,L"Windows Server 2003");
}
}
}else if(osver.dwMajorVersion == 6){
if(success_getver){
pGetProductInfo = (PFUNC_GetProductInfo)::GetProcAddress(GetModuleHandle(_T("kernel32.dll")), "GetProductInfo");
if(pGetProductInfo && pGetProductInfo(osver.dwMajorVersion,osver.dwMinorVersion,osver.wServicePackMajor,osver.wServicePackMinor,&dwReturnedProductType)){
switch(dwReturnedProductType){
case 0x00000006://PRODUCT_BUSINESS
case 0x00000010://PRODUCT_BUSINESS
wcscpy(os_string,L"Windows Vista Business");
break;
case 0x00000012://PRODUCT_CLUSTER_SERVER
wcscpy(os_string,L"Cluster Server Edition");
break;
case 0x00000008://PRODUCT_DATACENTER_SERVER
wcscpy(os_string,L"Datacenter Edition (full installation)");
break;
case 0x0000000C://PRODUCT_DATACENTER_SERVER_CORE
wcscpy(os_string,L"Datacenter Edition (core installation)");
break;
case 0x00000004://PRODUCT_ENTERPRISE
case 0x0000001B://PRODUCT_ENTERPRISE
wcscpy(os_string,L"Windows Vista Enterprise");
break;
case 0x0000000A://PRODUCT_ENTERPRISE_SERVER
wcscpy(os_string,L"Server Enterprise Edition (full installation)");
break;
case 0x0000000E://PRODUCT_ENTERPRISE_SERVER_CORE
wcscpy(os_string,L"Server Enterprise Edition (core installation)");
break;
case 0x0000000F://PRODUCT_ENTERPRISE_SERVER_IA64
wcscpy(os_string,L"Server Enterprise Edition for Itanium-based Systems");
break;
case 0x00000002://PRODUCT_HOME_BASIC
case 0x00000005://PRODUCT_HOME_BASIC_N
wcscpy(os_string,L"Windows Vista Home Basic");
break;
case 0x00000003://PRODUCT_HOME_PREMIUM
case 0x0000001A://PRODUCT_HOME_PREMIUM_N
wcscpy(os_string,L"Windows Vista Home Premium");
break;
case 0x00000013://PRODUCT_HOME_SERVER
wcscpy(os_string,L"Home Server");
break;
case 0x00000018://PRODUCT_SERVER_FOR_SMALLBUSINESS
wcscpy(os_string,L"Server for Small Business Edition");
break;
case 0x00000009://PRODUCT_SMALLBUSINESS_SERVER
wcscpy(os_string,L"Small Business Server");
break;
case 0x00000019://PRODUCT_SMALLBUSINESS_SERVER_PREMIUM
wcscpy(os_string,L"Small Business Server Premium Edition");
break;
case 0x00000007://PRODUCT_STANDARD_SERVER
wcscpy(os_string,L"Server Standard Edition (full installation)");
break;
case 0x0000000D://PRODUCT_STANDARD_SERVER_CORE
wcscpy(os_string,L"Server Standard Edition (core installation)");
break;
case 0x0000000B://PRODUCT_STARTER
wcscpy(os_string,L"Windows Vista Starter");
break;
case 0x00000017://PRODUCT_STORAGE_ENTERPRISE_SERVER
wcscpy(os_string,L"Storage Server Enterprise Edition");
break;
case 0x00000014://PRODUCT_STORAGE_EXPRESS_SERVER
wcscpy(os_string,L"Storage Server Express Edition");
break;
case 0x00000015://PRODUCT_STORAGE_STANDARD_SERVER
wcscpy(os_string,L"Storage Server Standard Edition");
break;
case 0x00000016://PRODUCT_STORAGE_WORKGROUP_SERVER
wcscpy(os_string,L"Storage Server Workgroup Edition");
break;
case 0x00000001://PRODUCT_ULTIMATE
case 0x0000001C://PRODUCT_ULTIMATE_N
wcscpy(os_string,L"Windows Vista Ultimate");
break;
case 0x00000011://PRODUCT_WEB_SERVER
wcscpy(os_string,L"Web Server Edition");
break;
default:
wcscpy(os_string,L"Windows Vista");
break;
}//end switch
}// end if(pGetProductInfo ... )
else
{
wcscpy(os_string,L"Windows Vista");
}
}// end if(success_getver)
else
{
wcscpy(os_string,L"Windows Vista");
}
}//end if vista
if(success_getver && osver.wServicePackMajor){
//Service Pack Check
if(osver.wServicePackMinor){
swprintf(os_string,n,L"%s SP%d.%d",os_string,osver.wServicePackMajor,osver.wServicePackMinor);
}else{
swprintf(os_string,n,L"%s SP%d",os_string,osver.wServicePackMajor);
}
}
}//end if(WinNT)
return os_string;
}
| mit |
Episerver-trainning/SiteAttention | rdContentArea/Business/Channels/DisplayResolutions.cs | 1151 | namespace rdContentArea.Business.Channels
{
/// <summary>
/// Defines resolution for desktop displays
/// </summary>
public class StandardResolution : DisplayResolutionBase
{
public StandardResolution() : base("/resolutions/standard", 1366, 768)
{
}
}
/// <summary>
/// Defines resolution for a horizontal iPad
/// </summary>
public class IpadHorizontalResolution : DisplayResolutionBase
{
public IpadHorizontalResolution() : base("/resolutions/ipadhorizontal", 1024, 768)
{
}
}
/// <summary>
/// Defines resolution for a vertical iPhone 5s
/// </summary>
public class IphoneVerticalResolution : DisplayResolutionBase
{
public IphoneVerticalResolution() : base("/resolutions/iphonevertical", 320, 568)
{
}
}
/// <summary>
/// Defines resolution for a vertical Android handheld device
/// </summary>
public class AndroidVerticalResolution : DisplayResolutionBase
{
public AndroidVerticalResolution() : base("/resolutions/androidvertical", 480, 800)
{
}
}
}
| mit |
cetusfinance/qwack | src/Qwack.Transport/BasicTypes/FixingDictionaryType.cs | 116 | namespace Qwack.Transport.BasicTypes
{
public enum FixingDictionaryType
{
Asset,
FX
}
}
| mit |
chrisJohn404/ljswitchboard-builder | build_scripts/build_project.js | 3544 |
console.log('Building Kipling');
var errorCatcher = require('./error_catcher');
var fs = require('fs');
var fse = require('fs-extra');
var path = require('path');
var cwd = process.cwd();
var async = require('async');
var child_process = require('child_process');
// Figure out what OS we are building for
var buildOS = {
'darwin': 'darwin',
'win32': 'win32'
}[process.platform];
if(typeof(buildOS) === 'undefined') {
buildOS = 'linux';
}
var mac_notarize = false;
if(process.argv.some((arg)=>{return process.argv.indexOf('mac_sign') > 0;})) {
mac_notarize = true;
console.log('**************************\n ****Signing ****\n**************************');
} else {
console.log('**************************\n**** Not Signing ****\n**************************');
}
var BUILD_SCRIPTS_DIR = 'build_scripts';
var commands = {};
var buildScripts = [
{'script': 'prepare_build', 'text': 'Preparing Build'},
{'script': 'gather_project_files', 'text': 'Gathering Project Files'},
{'script': 'edit_k3_startup_settings', 'text': 'Edit K3 Startup Settings'},
{'script': 'install_production_dependencies', 'text': 'Installing production dependencies'},
{'script': 'rebuild_native_modules', 'text': 'Rebuilding Native Modules (ffi & ref)'},
{'script': 'clean_project', 'text': 'Cleaning Project'},
]
var conditionalMacBuildSteps = [
{'script': 'sign_mac_build_before_compression', 'text': 'Signing Mac OS Build.'},
];
if((buildOS === 'darwin') && mac_notarize) {
buildScripts = buildScripts.concat(conditionalMacBuildSteps);
}
var buildScriptsSecondary = [
{'script': 'organize_project_files', 'text': 'Organizing Project Files & compress into packages.'},
{'script': 'brand_project', 'text': 'Branding Project Files'},
{'script': 'compress_output', 'text': 'Compressing Output and renaming'},
];
buildScripts = buildScripts.concat(buildScriptsSecondary);
var conditionalMacBuildStepsActerCompression = [
{'script': 'sign_mac_build_after_compression', 'text': 'Signing Mac OS Build.'},
];
if((buildOS === 'darwin') && mac_notarize) {
buildScripts = buildScripts.concat(conditionalMacBuildStepsActerCompression);
}
var finalBuildSteps = [
{'script': 'compress_output', 'text': 'Compressing Output and renaming'},
];
buildScripts = buildScripts.concat(finalBuildSteps);
buildScripts.forEach(function(buildScript) {
buildScript.scriptPath = path.normalize(path.join(
BUILD_SCRIPTS_DIR, buildScript.script + '.js'
));
buildScript.cmd = 'node ' + buildScript.scriptPath;
buildScript.isFinished = false;
buildScript.isSuccessful = false;
});
// Synchronous version of executing scripts
// buildScripts.forEach(function(buildScript) {
// try {
// console.log('Starting Step:', buildScript.text);
// var execOutput = child_process.execSync(buildScript.cmd);
// console.log('execOutput: ' , execOutput.toString());
// } catch(err) {
// console.log('Error Executing', buildScript.script, buildScript.text);
// process.exit(1);
// }
// });
// Asynchronous version of executing scripts
async.eachSeries(
buildScripts,
function(buildScript, cb) {
console.log('Starting Step:', buildScript.text);
child_process.exec(buildScript.cmd, function(error, stdout, stderr) {
if (error) {
console.error('Error Executing', error);
console.error(buildScript.script, buildScript.text);
cb(error);
}
console.log('stdout: ',stdout);
console.log('stderr: ',stderr);
cb();
})
},
function(err) {
if(err) {
console.log('Error Executing Build Scripts...', err);
process.exit(1);
}
});
| mit |
PUT-PTM/STMArkanoid | core/src/com/arkanoid/stm/ScreenProperties.java | 207 | package com.arkanoid.stm;
/**
* Created by Grzegorz on 2015-05-26.
*/
public class ScreenProperties
{
public static int widthFit; public static int heightFit;
public static int pipeVelocity=0;
}
| mit |
blesh/angular | packages/language-service/ivy/utils.ts | 12828 | /**
* @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 {AbsoluteSourceSpan, CssSelector, ParseSourceSpan, SelectorMatcher, TmplAstBoundEvent} from '@angular/compiler';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {isExternalResource} from '@angular/compiler-cli/src/ngtsc/metadata';
import {DeclarationNode} from '@angular/compiler-cli/src/ngtsc/reflection';
import {DirectiveSymbol} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import * as e from '@angular/compiler/src/expression_parser/ast'; // e for expression AST
import * as t from '@angular/compiler/src/render3/r3_ast'; // t for template AST
import * as ts from 'typescript';
import {ALIAS_NAME, SYMBOL_PUNC} from './display_parts';
import {findTightestNode, getParentClassDeclaration} from './ts_utils';
export function getTextSpanOfNode(node: t.Node|e.AST): ts.TextSpan {
if (isTemplateNodeWithKeyAndValue(node)) {
return toTextSpan(node.keySpan);
} else if (
node instanceof e.PropertyWrite || node instanceof e.MethodCall ||
node instanceof e.BindingPipe || node instanceof e.PropertyRead) {
// The `name` part of a `PropertyWrite`, `MethodCall`, and `BindingPipe` does not
// have its own AST so there is no way to retrieve a `Symbol` for just the `name` via a specific
// node.
return toTextSpan(node.nameSpan);
} else {
return toTextSpan(node.sourceSpan);
}
}
export function toTextSpan(span: AbsoluteSourceSpan|ParseSourceSpan|e.ParseSpan): ts.TextSpan {
let start: number, end: number;
if (span instanceof AbsoluteSourceSpan || span instanceof e.ParseSpan) {
start = span.start;
end = span.end;
} else {
start = span.start.offset;
end = span.end.offset;
}
return {start, length: end - start};
}
interface NodeWithKeyAndValue extends t.Node {
keySpan: ParseSourceSpan;
valueSpan?: ParseSourceSpan;
}
export function isTemplateNodeWithKeyAndValue(node: t.Node|e.AST): node is NodeWithKeyAndValue {
return isTemplateNode(node) && node.hasOwnProperty('keySpan');
}
export function isWithinKey(position: number, node: NodeWithKeyAndValue): boolean {
let {keySpan, valueSpan} = node;
if (valueSpan === undefined && node instanceof TmplAstBoundEvent) {
valueSpan = node.handlerSpan;
}
const isWithinKeyValue =
isWithin(position, keySpan) || !!(valueSpan && isWithin(position, valueSpan));
return isWithinKeyValue;
}
export function isWithinKeyValue(position: number, node: NodeWithKeyAndValue): boolean {
let {keySpan, valueSpan} = node;
if (valueSpan === undefined && node instanceof TmplAstBoundEvent) {
valueSpan = node.handlerSpan;
}
const isWithinKeyValue =
isWithin(position, keySpan) || !!(valueSpan && isWithin(position, valueSpan));
return isWithinKeyValue;
}
export function isTemplateNode(node: t.Node|e.AST): node is t.Node {
// Template node implements the Node interface so we cannot use instanceof.
return node.sourceSpan instanceof ParseSourceSpan;
}
export function isExpressionNode(node: t.Node|e.AST): node is e.AST {
return node instanceof e.AST;
}
export interface TemplateInfo {
template: t.Node[];
component: ts.ClassDeclaration;
}
function getInlineTemplateInfoAtPosition(
sf: ts.SourceFile, position: number, compiler: NgCompiler): TemplateInfo|undefined {
const expression = findTightestNode(sf, position);
if (expression === undefined) {
return undefined;
}
const classDecl = getParentClassDeclaration(expression);
if (classDecl === undefined) {
return undefined;
}
// Return `undefined` if the position is not on the template expression or the template resource
// is not inline.
const resources = compiler.getComponentResources(classDecl);
if (resources === null || isExternalResource(resources.template) ||
expression !== resources.template.expression) {
return undefined;
}
const template = compiler.getTemplateTypeChecker().getTemplate(classDecl);
if (template === null) {
return undefined;
}
return {template, component: classDecl};
}
/**
* Retrieves the `ts.ClassDeclaration` at a location along with its template nodes.
*/
export function getTemplateInfoAtPosition(
fileName: string, position: number, compiler: NgCompiler): TemplateInfo|undefined {
if (isTypeScriptFile(fileName)) {
const sf = compiler.getNextProgram().getSourceFile(fileName);
if (sf === undefined) {
return undefined;
}
return getInlineTemplateInfoAtPosition(sf, position, compiler);
} else {
return getFirstComponentForTemplateFile(fileName, compiler);
}
}
/**
* First, attempt to sort component declarations by file name.
* If the files are the same, sort by start location of the declaration.
*/
function tsDeclarationSortComparator(a: DeclarationNode, b: DeclarationNode): number {
const aFile = a.getSourceFile().fileName;
const bFile = b.getSourceFile().fileName;
if (aFile < bFile) {
return -1;
} else if (aFile > bFile) {
return 1;
} else {
return b.getFullStart() - a.getFullStart();
}
}
function getFirstComponentForTemplateFile(fileName: string, compiler: NgCompiler): TemplateInfo|
undefined {
const templateTypeChecker = compiler.getTemplateTypeChecker();
const components = compiler.getComponentsWithTemplateFile(fileName);
const sortedComponents = Array.from(components).sort(tsDeclarationSortComparator);
for (const component of sortedComponents) {
if (!ts.isClassDeclaration(component)) {
continue;
}
const template = templateTypeChecker.getTemplate(component);
if (template === null) {
continue;
}
return {template, component};
}
return undefined;
}
/**
* Given an attribute node, converts it to string form.
*/
function toAttributeString(attribute: t.TextAttribute|t.BoundAttribute|t.BoundEvent): string {
if (attribute instanceof t.BoundEvent) {
return `[${attribute.name}]`;
} else {
return `[${attribute.name}=${attribute.valueSpan?.toString() ?? ''}]`;
}
}
function getNodeName(node: t.Template|t.Element): string {
return node instanceof t.Template ? node.tagName : node.name;
}
/**
* Given a template or element node, returns all attributes on the node.
*/
function getAttributes(node: t.Template|
t.Element): Array<t.TextAttribute|t.BoundAttribute|t.BoundEvent> {
const attributes: Array<t.TextAttribute|t.BoundAttribute|t.BoundEvent> =
[...node.attributes, ...node.inputs, ...node.outputs];
if (node instanceof t.Template) {
attributes.push(...node.templateAttrs);
}
return attributes;
}
/**
* Given two `Set`s, returns all items in the `left` which do not appear in the `right`.
*/
function difference<T>(left: Set<T>, right: Set<T>): Set<T> {
const result = new Set<T>();
for (const dir of left) {
if (!right.has(dir)) {
result.add(dir);
}
}
return result;
}
/**
* Given an element or template, determines which directives match because the tag is present. For
* example, if a directive selector is `div[myAttr]`, this would match div elements but would not if
* the selector were just `[myAttr]`. We find which directives are applied because of this tag by
* elimination: compare the directive matches with the tag present against the directive matches
* without it. The difference would be the directives which match because the tag is present.
*
* @param element The element or template node that the attribute/tag is part of.
* @param directives The list of directives to match against.
* @returns The list of directives matching the tag name via the strategy described above.
*/
// TODO(atscott): Add unit tests for this and the one for attributes
export function getDirectiveMatchesForElementTag(
element: t.Template|t.Element, directives: DirectiveSymbol[]): Set<DirectiveSymbol> {
const attributes = getAttributes(element);
const allAttrs = attributes.map(toAttributeString);
const allDirectiveMatches =
getDirectiveMatchesForSelector(directives, getNodeName(element) + allAttrs.join(''));
const matchesWithoutElement = getDirectiveMatchesForSelector(directives, allAttrs.join(''));
return difference(allDirectiveMatches, matchesWithoutElement);
}
export function makeElementSelector(element: t.Element|t.Template): string {
const attributes = getAttributes(element);
const allAttrs = attributes.map(toAttributeString);
return getNodeName(element) + allAttrs.join('');
}
/**
* Given an attribute name, determines which directives match because the attribute is present. We
* find which directives are applied because of this attribute by elimination: compare the directive
* matches with the attribute present against the directive matches without it. The difference would
* be the directives which match because the attribute is present.
*
* @param name The name of the attribute
* @param hostNode The node which the attribute appears on
* @param directives The list of directives to match against.
* @returns The list of directives matching the tag name via the strategy described above.
*/
export function getDirectiveMatchesForAttribute(
name: string, hostNode: t.Template|t.Element,
directives: DirectiveSymbol[]): Set<DirectiveSymbol> {
const attributes = getAttributes(hostNode);
const allAttrs = attributes.map(toAttributeString);
const allDirectiveMatches =
getDirectiveMatchesForSelector(directives, getNodeName(hostNode) + allAttrs.join(''));
const attrsExcludingName = attributes.filter(a => a.name !== name).map(toAttributeString);
const matchesWithoutAttr = getDirectiveMatchesForSelector(
directives, getNodeName(hostNode) + attrsExcludingName.join(''));
return difference(allDirectiveMatches, matchesWithoutAttr);
}
/**
* Given a list of directives and a text to use as a selector, returns the directives which match
* for the selector.
*/
function getDirectiveMatchesForSelector(
directives: DirectiveSymbol[], selector: string): Set<DirectiveSymbol> {
const selectors = CssSelector.parse(selector);
if (selectors.length === 0) {
return new Set();
}
return new Set(directives.filter((dir: DirectiveSymbol) => {
if (dir.selector === null) {
return false;
}
const matcher = new SelectorMatcher();
matcher.addSelectables(CssSelector.parse(dir.selector));
return selectors.some(selector => matcher.match(selector, null));
}));
}
/**
* Returns a new `ts.SymbolDisplayPart` array which has the alias imports from the tcb filtered
* out, i.e. `i0.NgForOf`.
*/
export function filterAliasImports(displayParts: ts.SymbolDisplayPart[]): ts.SymbolDisplayPart[] {
const tcbAliasImportRegex = /i\d+/;
function isImportAlias(part: {kind: string, text: string}) {
return part.kind === ALIAS_NAME && tcbAliasImportRegex.test(part.text);
}
function isDotPunctuation(part: {kind: string, text: string}) {
return part.kind === SYMBOL_PUNC && part.text === '.';
}
return displayParts.filter((part, i) => {
const previousPart = displayParts[i - 1];
const nextPart = displayParts[i + 1];
const aliasNameFollowedByDot =
isImportAlias(part) && nextPart !== undefined && isDotPunctuation(nextPart);
const dotPrecededByAlias =
isDotPunctuation(part) && previousPart !== undefined && isImportAlias(previousPart);
return !aliasNameFollowedByDot && !dotPrecededByAlias;
});
}
export function isDollarEvent(n: t.Node|e.AST): n is e.PropertyRead {
return n instanceof e.PropertyRead && n.name === '$event' &&
n.receiver instanceof e.ImplicitReceiver && !(n.receiver instanceof e.ThisReceiver);
}
/**
* Returns a new array formed by applying a given callback function to each element of the array,
* and then flattening the result by one level.
*/
export function flatMap<T, R>(items: T[]|readonly T[], f: (item: T) => R[] | readonly R[]): R[] {
const results: R[] = [];
for (const x of items) {
results.push(...f(x));
}
return results;
}
export function isTypeScriptFile(fileName: string): boolean {
return fileName.endsWith('.ts');
}
export function isExternalTemplate(fileName: string): boolean {
return !isTypeScriptFile(fileName);
}
export function isWithin(position: number, span: AbsoluteSourceSpan|ParseSourceSpan): boolean {
let start: number, end: number;
if (span instanceof ParseSourceSpan) {
start = span.start.offset;
end = span.end.offset;
} else {
start = span.start;
end = span.end;
}
// Note both start and end are inclusive because we want to match conditions
// like ¦start and end¦ where ¦ is the cursor.
return start <= position && position <= end;
}
| mit |
Mangopay/mangopay2-nodejs-sdk | typings/models/client.d.ts | 4845 | import { ValueOf } from "../types";
import { enums } from "../enums";
import { address } from "./address";
import { entityBase } from "./entityBase";
export namespace client {
type BusinessType = "MARKETPLACE" | "CROWDFUNDING" | "FRANCHISE" | "OTHER";
type Sector =
| "RENTALS"
| "STORES_FASHION_ACCESSORIES_OBJECTS"
| "BEAUTY_COSMETICS_HEALTH"
| "FOOD_WINE_RESTAURANTS"
| "HOSPITALITY_TRAVEL_CORIDING"
| "ART_MUSIC_ENTERTAINMENT"
| "FURNITURE_GARDEN"
| "SERVICES_JOBBING_EDUCATION"
| "SPORT_RECREATION_ACTIVITIES"
| "TICKETING"
| "LOAN"
| "EQUITY"
| "PROPERTY_EQUITY"
| "REWARDS_CHARITY"
| "POOL_GROUP_PAYMENT"
| "FRANCHISE_"
| "OTHER_";
type PlatformType = ValueOf<enums.IPlatformType>;
interface PlatformCategorization {
Sector: Sector;
BusinessType: BusinessType;
}
interface ClientData extends entityBase.EntityBaseData {
/**
* The pretty name for the client
*/
Name: string;
/**
* The registered name of your company
*/
RegisteredName: string;
/**
* An ID for the client (i.e. url friendly, lowercase etc - sort of namespace identifier)
*/
ClientId: string;
/**
* The primary branding colour to use for your merchant
*/
PrimaryThemeColour: string;
/**
* The primary branding colour to use for buttons for your merchant
*/
PrimaryButtonColour: string;
/**
* The URL of the logo of your client
*/
Logo: string;
/**
* A list of email addresses to use when contacting you for technical issues/communications
*/
TechEmails: string[];
/**
* A list of email addresses to use when contacting you for admin/commercial issues/communications
*/
AdminEmails: string[];
/**
* A list of email addresses to use when contacting you for fraud/compliance issues/communications
*/
FraudEmails: string[];
/**
* A list of email addresses to use when contacting you for billing issues/communications
*/
BillingEmails: string[];
/**
* The Categorization of your platform, in terms of Business Type and Sector
*/
PlatformCategorization: PlatformCategorization;
/**
* A description of what your platform does
*/
PlatformDescription: string;
/**
* The URL for your website
*/
PlatformURL: string;
/**
* The address of the company’s headquarters
*/
HeadquartersAddress: address.AddressType;
/**
* The phone number of the company's headquarters
*/
HeadquartersPhoneNumber: string;
/**
* The tax (or VAT) number for your company
*/
TaxNumber: string;
/**
* Your unique MANGOPAY reference which you should use when contacting us
*/
CompanyReference: string;
}
interface UpdateClient {
/**
* The primary branding colour to use for buttons for your merchant
*/
PrimaryButtonColour?: string;
/**
* The primary branding colour to use for your merchant
*/
PrimaryThemeColour?: string;
/**
* A list of email addresses to use when contacting you for admin/commercial issues/communications
*/
AdminEmails?: string[];
/**
* A list of email addresses to use when contacting you for technical issues/communications
*/
TechEmails?: string[];
/**
* A list of email addresses to use when contacting you for billing issues/communications
*/
BillingEmails?: string[];
/**
* A list of email addresses to use when contacting you for fraud/compliance issues/communications
*/
FraudEmails?: string[];
/**
* The address of the company’s headquarters
*/
HeadquartersAddress?: address.AddressType;
/**
* The tax (or VAT) number for your company
*/
TaxNumber?: string;
/**
* The type of platform
*/
PlatformType?: PlatformType;
/**
* A description of what your platform does
*/
PlatformDescription?: string;
/**
* The URL for your website
*/
PlatformURL?: string;
}
interface UpdateClientLogo {
/**
* The base64 encoded file which needs to be uploaded
*/
File: string;
}
}
| mit |
OnePonyGames/frozen | src/main/java/com/oneponygames/frozen/base/eventsystem/events/sound/StopAllSoundsEvent.java | 358 | package com.oneponygames.frozen.base.eventsystem.events.sound;
import com.badlogic.ashley.core.Entity;
import com.oneponygames.frozen.base.eventsystem.events.entity.EntityEvent;
/**
* Created by Icewind on 13.03.2017.
*/
public class StopAllSoundsEvent extends EntityEvent {
public StopAllSoundsEvent(Entity entity) {
super(entity);
}
}
| mit |
jstedfast/MailKit | MailKit/Net/Proxy/ProxyClient.cs | 15207 | //
// ProxyClient.cs
//
// Author: Jeffrey Stedfast <jestedfa@microsoft.com>
//
// Copyright (c) 2013-2022 .NET Foundation and Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace MailKit.Net.Proxy
{
/// <summary>
/// An abstract proxy client base class.
/// </summary>
/// <remarks>
/// A proxy client can be used to connect to a service through a firewall that
/// would otherwise be blocked.
/// </remarks>
public abstract class ProxyClient : IProxyClient
{
/// <summary>
/// Initializes a new instance of the <see cref="T:MailKit.Net.Proxy.ProxyClient"/> class.
/// </summary>
/// <remarks>
/// Initializes a new instance of the <see cref="T:MailKit.Net.Proxy.ProxyClient"/> class.
/// </remarks>
/// <param name="host">The host name of the proxy server.</param>
/// <param name="port">The proxy server port.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="host"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="port"/> is not between <c>0</c> and <c>65535</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para>The <paramref name="host"/> is a zero-length string.</para>
/// <para>-or-</para>
/// <para>The length of <paramref name="host"/> is greater than 255 characters.</para>
/// </exception>
protected ProxyClient (string host, int port)
{
if (host == null)
throw new ArgumentNullException (nameof (host));
if (host.Length == 0 || host.Length > 255)
throw new ArgumentException ("The length of the host name must be between 0 and 256 characters.", nameof (host));
if (port < 0 || port > 65535)
throw new ArgumentOutOfRangeException (nameof (port));
ProxyHost = host;
ProxyPort = port == 0 ? 1080 : port;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:MailKit.Net.Proxy.ProxyClient"/> class.
/// </summary>
/// <remarks>
/// Initializes a new instance of the <see cref="T:MailKit.Net.Proxy.ProxyClient"/> class.
/// </remarks>
/// <param name="host">The host name of the proxy server.</param>
/// <param name="port">The proxy server port.</param>
/// <param name="credentials">The credentials to use to authenticate with the proxy server.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="host"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="credentials"/>is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="port"/> is not between <c>0</c> and <c>65535</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para>The <paramref name="host"/> is a zero-length string.</para>
/// <para>-or-</para>
/// <para>The length of <paramref name="host"/> is greater than 255 characters.</para>
/// </exception>
protected ProxyClient (string host, int port, NetworkCredential credentials) : this (host, port)
{
if (credentials == null)
throw new ArgumentNullException (nameof (credentials));
ProxyCredentials = credentials;
}
/// <summary>
/// Gets the proxy credentials.
/// </summary>
/// <remarks>
/// Gets the credentials to use when authenticating with the proxy server.
/// </remarks>
/// <value>The proxy credentials.</value>
public NetworkCredential ProxyCredentials {
get; private set;
}
/// <summary>
/// Get the proxy host.
/// </summary>
/// <remarks>
/// Gets the host name of the proxy server.
/// </remarks>
/// <value>The host name of the proxy server.</value>
public string ProxyHost {
get; private set;
}
/// <summary>
/// Get the proxy port.
/// </summary>
/// <remarks>
/// Gets the port to use when connecting to the proxy server.
/// </remarks>
/// <value>The proxy port.</value>
public int ProxyPort {
get; private set;
}
/// <summary>
/// Get or set the local IP end point to use when connecting to a remote host.
/// </summary>
/// <remarks>
/// Gets or sets the local IP end point to use when connecting to a remote host.
/// </remarks>
/// <value>The local IP end point or <c>null</c> to use the default end point.</value>
public IPEndPoint LocalEndPoint {
get; set;
}
internal static void ValidateArguments (string host, int port)
{
if (host == null)
throw new ArgumentNullException (nameof (host));
if (host.Length == 0 || host.Length > 255)
throw new ArgumentException ("The length of the host name must be between 0 and 256 characters.", nameof (host));
if (port <= 0 || port > 65535)
throw new ArgumentOutOfRangeException (nameof (port));
}
static void ValidateArguments (string host, int port, int timeout)
{
ValidateArguments (host, port);
if (timeout < -1)
throw new ArgumentOutOfRangeException (nameof (timeout));
}
static void AsyncOperationCompleted (object sender, SocketAsyncEventArgs args)
{
var tcs = (TaskCompletionSource<bool>) args.UserToken;
if (args.SocketError == SocketError.Success) {
tcs.TrySetResult (true);
return;
}
tcs.TrySetException (new SocketException ((int) args.SocketError));
}
internal static async Task SendAsync (Socket socket, byte[] buffer, int offset, int length, bool doAsync, CancellationToken cancellationToken)
{
if (doAsync || cancellationToken.CanBeCanceled) {
var tcs = new TaskCompletionSource<bool> ();
using (var registration = cancellationToken.Register (() => tcs.TrySetCanceled (), false)) {
using (var args = new SocketAsyncEventArgs ()) {
args.Completed += AsyncOperationCompleted;
args.SetBuffer (buffer, offset, length);
args.AcceptSocket = socket;
args.UserToken = tcs;
if (!socket.SendAsync (args))
AsyncOperationCompleted (null, args);
if (doAsync)
await tcs.Task.ConfigureAwait (false);
else
tcs.Task.GetAwaiter ().GetResult ();
return;
}
}
}
SocketUtils.Poll (socket, SelectMode.SelectWrite, cancellationToken);
socket.Send (buffer, offset, length, SocketFlags.None);
}
internal static async Task<int> ReceiveAsync (Socket socket, byte[] buffer, int offset, int length, bool doAsync, CancellationToken cancellationToken)
{
if (doAsync || cancellationToken.CanBeCanceled) {
var tcs = new TaskCompletionSource<bool> ();
using (var registration = cancellationToken.Register (() => tcs.TrySetCanceled (), false)) {
using (var args = new SocketAsyncEventArgs ()) {
args.Completed += AsyncOperationCompleted;
args.SetBuffer (buffer, offset, length);
args.AcceptSocket = socket;
args.UserToken = tcs;
if (!socket.ReceiveAsync (args))
AsyncOperationCompleted (null, args);
if (doAsync)
await tcs.Task.ConfigureAwait (false);
else
tcs.Task.GetAwaiter ().GetResult ();
return args.BytesTransferred;
}
}
}
SocketUtils.Poll (socket, SelectMode.SelectRead, cancellationToken);
return socket.Receive (buffer, offset, length, SocketFlags.None);
}
/// <summary>
/// Connect to the target host.
/// </summary>
/// <remarks>
/// Connects to the target host and port through the proxy server.
/// </remarks>
/// <returns>The connected network stream.</returns>
/// <param name="host">The host name of the proxy server.</param>
/// <param name="port">The proxy server port.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="host"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="port"/> is not between <c>1</c> and <c>65535</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="host"/> is a zero-length string.
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled via the cancellation token.
/// </exception>
/// <exception cref="System.Net.Sockets.SocketException">
/// A socket error occurred trying to connect to the remote host.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public abstract Stream Connect (string host, int port, CancellationToken cancellationToken = default (CancellationToken));
/// <summary>
/// Asynchronously connect to the target host.
/// </summary>
/// <remarks>
/// Asynchronously connects to the target host and port through the proxy server.
/// </remarks>
/// <returns>The connected network stream.</returns>
/// <param name="host">The host name of the proxy server.</param>
/// <param name="port">The proxy server port.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="host"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="port"/> is not between <c>1</c> and <c>65535</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="host"/> is a zero-length string.
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled via the cancellation token.
/// </exception>
/// <exception cref="System.Net.Sockets.SocketException">
/// A socket error occurred trying to connect to the remote host.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public abstract Task<Stream> ConnectAsync (string host, int port, CancellationToken cancellationToken = default (CancellationToken));
/// <summary>
/// Connect to the target host.
/// </summary>
/// <remarks>
/// Connects to the target host and port through the proxy server.
/// </remarks>
/// <returns>The connected network stream.</returns>
/// <param name="host">The host name of the proxy server.</param>
/// <param name="port">The proxy server port.</param>
/// <param name="timeout">The timeout, in milliseconds.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="host"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <para><paramref name="port"/> is not between <c>1</c> and <c>65535</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="timeout"/> is less than <c>-1</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="host"/> is a zero-length string.
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled via the cancellation token.
/// </exception>
/// <exception cref="System.TimeoutException">
/// The operation timed out.
/// </exception>
/// <exception cref="System.Net.Sockets.SocketException">
/// A socket error occurred trying to connect to the remote host.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public virtual Stream Connect (string host, int port, int timeout, CancellationToken cancellationToken = default (CancellationToken))
{
ValidateArguments (host, port, timeout);
using (var ts = new CancellationTokenSource (timeout)) {
using (var linked = CancellationTokenSource.CreateLinkedTokenSource (cancellationToken, ts.Token)) {
try {
return Connect (host, port, linked.Token);
} catch (OperationCanceledException) {
if (!cancellationToken.IsCancellationRequested)
throw new TimeoutException ();
throw;
}
}
}
}
/// <summary>
/// Asynchronously connect to the target host.
/// </summary>
/// <remarks>
/// Asynchronously connects to the target host and port through the proxy server.
/// </remarks>
/// <returns>The connected network stream.</returns>
/// <param name="host">The host name of the proxy server.</param>
/// <param name="port">The proxy server port.</param>
/// <param name="timeout">The timeout, in milliseconds.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="host"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <para><paramref name="port"/> is not between <c>1</c> and <c>65535</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="timeout"/> is less than <c>-1</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="host"/> is a zero-length string.
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled via the cancellation token.
/// </exception>
/// <exception cref="System.TimeoutException">
/// The operation timed out.
/// </exception>
/// <exception cref="System.Net.Sockets.SocketException">
/// A socket error occurred trying to connect to the remote host.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public async virtual Task<Stream> ConnectAsync (string host, int port, int timeout, CancellationToken cancellationToken = default (CancellationToken))
{
ValidateArguments (host, port, timeout);
using (var ts = new CancellationTokenSource (timeout)) {
using (var linked = CancellationTokenSource.CreateLinkedTokenSource (cancellationToken, ts.Token)) {
try {
return await ConnectAsync (host, port, linked.Token).ConfigureAwait (false);
} catch (OperationCanceledException) {
if (!cancellationToken.IsCancellationRequested)
throw new TimeoutException ();
throw;
}
}
}
}
}
}
| mit |
topsycreed/Selenium-Java | addressbook-selenium-test/src/com/example/tests/GroupCreationTests.java | 1203 | package com.example.tests;
import static com.example.tests.GroupDataGenerator.loadGroupsFromCsvFile;
import static com.example.tests.GroupDataGenerator.loadGroupsFromXmlFile;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.example.utils.SortedListOf;
public class GroupCreationTests extends TestBase {
@DataProvider
public Iterator<Object[]> groupsFromFile() throws IOException{
return wrapGroupsForDataProvider(loadGroupsFromXmlFile (new File("groups.xml"))).iterator();
}
@Test(dataProvider="groupsFromFile")
public void testGroupCreationWithValidData(GroupData group) throws Exception {
// save old
SortedListOf<GroupData> oldList=app.getGroupHelper().getGrous();
//action
app.getGroupHelper().createGroup(group);
// save new
SortedListOf<GroupData> newList=app.getGroupHelper().getGrous();
//compare
assertThat(newList,equalTo(oldList.withAdded(group)));
}
} | mit |
dopse/maildump | src/main/java/fr/dopse/maildump/model/AttachmentContentEntity.java | 571 | package fr.dopse.maildump.model;
import javax.persistence.*;
import java.io.Serializable;
/**
* Created by fr27a86n on 13/04/2017.
*/
@Entity
@Table(name = "ATTACHMENT_CONTENT")
public class AttachmentContentEntity implements Serializable {
@Id
@GeneratedValue
private Long id;
@Lob
private byte[] data;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
}
| mit |
QuinntyneBrown/wedding-bidders | src/app/components/wb-bids.js | 1096 | (function () {
"use strict";
function BidsComponent(bid, bidStore) {
var self = this;
self.bids = [];
for(var i = 0; i < bidStore.byProfile.length; i++) {
self.bids.push(bid.createInstance({ data: bidStore.byProfile[i]}));
}
return self;
}
BidsComponent.canActivate = function () {
return ["invokeAsync", "bidActions", function (invokeAsync, bidActions) {
return invokeAsync(bidActions.getAllByCurrentProfile);
}];
};
ngX.Component({
component: BidsComponent,
route: "/bids",
providers: ["bid", "bidStore"],
template: [
"<div class='bids viewComponent'>",
"<h1>Bids</h1>",
" <div data-ng-repeat='bid in vm.bids'> ",
" <h3>Wedding Id: {{ ::bid.weddingId }}</h3>",
" <h3>Price: {{ ::bid.price }}</h3>",
" <h3>Description: {{ ::bid.description }}</h3>",
" <br/><br/> ",
" </div> ",
"</div>"
]
});
})();
| mit |
dacodekid/gulp-factory-examples | test/jade.js | 605 | 'use strict';
const test = require('tape');
const jade = require('../plugins/jade');
const fixture = require('./fixtures/file-gen');
test('jade render should output', assert => {
const plugin = jade({
layout: process.cwd() + '/test/fixtures/layout.jade',
title: 'test title'
});
plugin.once('data', file => {
assert.equal(file.contents.toString(),
'<html>' +
'<head><title>test title</title>' +
'</head><body><h1>test title</h1>' +
'<div>awesome</div></body>' +
'</html>');
});
plugin.write(fixture('awesome', 'test.md'));
plugin.end();
assert.end();
});
| mit |
Kagamine/CodeComb.ChinaTelecom | CodeComb.ChinaTelecom.Website/Controllers/BaseController.cs | 328 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using CodeComb.ChinaTelecom.Website.Models;
namespace CodeComb.ChinaTelecom.Website.Controllers
{
public class BaseController : BaseController<User, CTContext, string>
{
}
}
| mit |
livioribeiro/neo4j-rust-driver | src/lib.rs | 1654 | extern crate byteorder;
extern crate rustc_serialize;
#[macro_use]
extern crate log;
pub mod v1;
use std::io::prelude::*;
use std::io::Cursor;
use std::net::{TcpStream, Shutdown};
use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
use v1::Connection;
const PREAMBLE: [u8; 4] = [0x60, 0x60, 0xB0, 0x17];
const SUPPORTED_VERSIONS: [u32; 4] = [1, 0, 0, 0];
/// Connect and perform a handshake in order to return a valid
/// Connection object if a protocol version can be agreed.
pub fn connect(host: &str, port: u16) -> Result<Connection, ()> {
info!("Creating connection to {} on port {}", host, port);
let mut stream = TcpStream::connect((host, port)).unwrap();
info!("Supported protocols are: {:?}", &SUPPORTED_VERSIONS);
let data = {
let mut data = Cursor::new(vec![0u8; (4 * 4)]);
for i in PREAMBLE.iter() {
data.write_u8(*i).unwrap();
}
for v in SUPPORTED_VERSIONS.iter() {
data.write_u32::<BigEndian>(*v).unwrap();
}
data.into_inner()
};
debug!("Sending handshake data: {:?}", &data);
stream.write(&data).unwrap();
let mut buf = [0u8; 4];
stream.read(&mut buf).unwrap();
debug!("Received handshake data: {:?}", &buf);
let agreed_version = {
let mut data = Cursor::new(&buf);
data.read_u32::<BigEndian>().unwrap()
};
if agreed_version == 0 {
warn!("Closing connection as no protocol version could be agreed");
stream.shutdown(Shutdown::Both).unwrap();
return Err(())
}
info!("Protocol version {} agreed", agreed_version);
Ok(Connection::new(stream))
}
| mit |
bobar/tdfb | app/models/wrong_frankiz_id.rb | 77 | class WrongFrankizId < ActiveRecord::Base
self.table_name = :wrong_ids
end
| mit |
boynoiz/liverpoolthailand | app/Http/Requests/Admin/FootballTeamsRequest.php | 999 | <?php
namespace LTF\Http\Requests\Admin;
use LTF\Http\Requests\Request;
class FootballTeamsRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'sometimes',
'shortname' => 'required|min:3|max:6',
'country' => 'sometimes',
'founded' => 'sometimes|date_format:Y',
'leagues' => 'sometimes',
'venue_name' => 'sometimes',
'venue_city' => 'sometimes',
'venue_capcity' => 'sometimes|integer',
'coach_name' => 'sometimes',
'image' => 'sometimes|max:2048|image',
'detail' => 'sometimes'
];
}
}
| mit |
digitalrizzle/recovery-journal-v3 | src/RecoveryJournal.Website/webpack.config.vendor.js | 3771 | const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');
const treeShakableModules = [
'@angular/animations',
'@angular/common',
'@angular/compiler',
'@angular/core',
'@angular/forms',
'@angular/http',
'@angular/platform-browser',
'@angular/platform-browser-dynamic',
'@angular/router',
'zone.js',
];
const nonTreeShakableModules = [
'angular2-toaster/toaster.css',
'bootstrap',
'bootstrap/dist/css/bootstrap.css',
'es6-promise',
'es6-shim',
'event-source-polyfill',
'jquery',
'ngx-bootstrap/datepicker/bs-datepicker.css',
'./ClientApp/styles/style.css'
];
const allModules = treeShakableModules.concat(nonTreeShakableModules);
module.exports = (env) => {
const extractCSS = new ExtractTextPlugin('vendor.css');
const isDevBuild = !(env && env.prod);
const sharedConfig = {
stats: { modules: false },
resolve: { extensions: [ '.js' ] },
module: {
rules: [
{ test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' }
]
},
output: {
publicPath: 'dist/',
filename: '[name].js',
library: '[name]_[hash]'
},
plugins: [
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
new webpack.ContextReplacementPlugin(/\@angular\b.*\b(bundles|linker)/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/11580
new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)@angular/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/14898
new webpack.IgnorePlugin(/^vertx$/) // Workaround for https://github.com/stefanpenner/es6-promise/issues/100
]
};
const clientBundleConfig = merge(sharedConfig, {
entry: {
// To keep development builds fast, include all vendor dependencies in the vendor bundle.
// But for production builds, leave the tree-shakable ones out so the AOT compiler can produce a smaller bundle.
vendor: isDevBuild ? allModules : nonTreeShakableModules
},
output: { path: path.join(__dirname, 'wwwroot', 'dist') },
module: {
rules: [
{ test: /\.css(\?|$)/, use: extractCSS.extract({ use: isDevBuild ? 'css-loader' : 'css-loader?minimize' }) }
]
},
plugins: [
extractCSS,
new webpack.DllPlugin({
path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
].concat(isDevBuild ? [] : [
new webpack.optimize.UglifyJsPlugin()
])
});
const serverBundleConfig = merge(sharedConfig, {
target: 'node',
resolve: { mainFields: ['main'] },
entry: { vendor: allModules.concat(['aspnet-prerendering']) },
output: {
path: path.join(__dirname, 'ClientApp', 'dist'),
libraryTarget: 'commonjs2',
},
module: {
rules: [ { test: /\.css(\?|$)/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] } ]
},
plugins: [
new webpack.DllPlugin({
path: path.join(__dirname, 'ClientApp', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
]
});
return [clientBundleConfig, serverBundleConfig];
}
| mit |
opsmatic/puppet-opsmatic | spec/classes/params_spec.rb | 472 | require 'spec_helper'
# Facts mocked up for unit testing
FACTS = {
:osfamily => 'Debian',
:operatingsystem => 'Ubuntu',
:operatingsystemrelease => '12',
:lsbdistid => 'Ubuntu',
:lsbdistcodename => 'precise',
:lsbdistrelease => '12.04',
:lsbmajdistrelease => '12',
:kernel => 'linux',
}
describe 'opsmatic::params', :type => 'class' do
context 'default params' do
let(:facts) { FACTS }
it do
should compile.with_all_deps
end
end
end
| mit |
nunit/nunit | src/NUnitFramework/nunitlite.tests/CreateTestFilterTests.cs | 6058 | // Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using NUnit.Common;
using NUnit.Framework;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Filters;
using NUnit.TestUtilities;
namespace NUnitLite.Tests
{
public class CreateTestFilterTests
{
[Test]
public void EmptyFilter()
{
var filter = GetFilter();
Assert.That(filter.IsEmpty);
}
[Test]
public void OneTestSelected()
{
var filter = GetFilter("--test:My.Test.Name");
Assert.That(filter, Is.TypeOf<FullNameFilter>());
Assert.That(((FullNameFilter)filter).ExpectedValue,
Is.EqualTo("My.Test.Name"));
}
[Test]
public void ThreeTestsSelected()
{
var filter = GetFilter("--test:My.First.Test", "--test:My.Second.Test", "--test:My.Third.Test");
Assert.That(filter, Is.TypeOf<OrFilter>());
var filters = ((OrFilter)filter).Filters;
Assert.That(filters.Count, Is.EqualTo(3));
Assert.That(filters[0], Is.TypeOf<FullNameFilter>());
Assert.That(((FullNameFilter)filters[0]).ExpectedValue, Is.EqualTo("My.First.Test"));
Assert.That(filters[1], Is.TypeOf<FullNameFilter>());
Assert.That(((FullNameFilter)filters[1]).ExpectedValue, Is.EqualTo("My.Second.Test"));
Assert.That(filters[2], Is.TypeOf<FullNameFilter>());
Assert.That(((FullNameFilter)filters[2]).ExpectedValue, Is.EqualTo("My.Third.Test"));
}
[Test]
public void ThreeTestsFromATestListFile()
{
using (var tf = new TestFile("TestListFile.txt"))
{
var filter = GetFilter("--testlist:" + tf.File.FullName);
Assert.That(filter, Is.TypeOf<OrFilter>());
var filters = ((OrFilter)filter).Filters;
Assert.That(filters.Count, Is.EqualTo(3));
Assert.That(filters[0], Is.TypeOf<FullNameFilter>());
Assert.That(((FullNameFilter)filters[0]).ExpectedValue, Is.EqualTo("My.First.Test"));
Assert.That(filters[1], Is.TypeOf<FullNameFilter>());
Assert.That(((FullNameFilter)filters[1]).ExpectedValue, Is.EqualTo("My.Second.Test"));
Assert.That(filters[2], Is.TypeOf<FullNameFilter>());
Assert.That(((FullNameFilter)filters[2]).ExpectedValue, Is.EqualTo("My.Third.Test"));
}
}
[Test]
public void SixTestsFromTwoTestListFiles()
{
using (var tf = new TestFile("TestListFile.txt"))
using (var tf2 = new TestFile("TestListFile2.txt"))
{
var filter = GetFilter("--testlist:" + tf.File.FullName, "--testlist:" + tf2.File.FullName );
Assert.That(filter, Is.TypeOf<OrFilter>());
var filters = ((OrFilter)filter).Filters;
Assert.That(filters.Count, Is.EqualTo(6));
Assert.That(filters[0], Is.TypeOf<FullNameFilter>());
Assert.That(((FullNameFilter)filters[0]).ExpectedValue, Is.EqualTo("My.First.Test"));
Assert.That(filters[1], Is.TypeOf<FullNameFilter>());
Assert.That(((FullNameFilter)filters[1]).ExpectedValue, Is.EqualTo("My.Second.Test"));
Assert.That(filters[2], Is.TypeOf<FullNameFilter>());
Assert.That(((FullNameFilter)filters[2]).ExpectedValue, Is.EqualTo("My.Third.Test"));
Assert.That(filters[3], Is.TypeOf<FullNameFilter>());
Assert.That(((FullNameFilter)filters[3]).ExpectedValue, Is.EqualTo("My.Fourth.Test"));
Assert.That(filters[4], Is.TypeOf<FullNameFilter>());
Assert.That(((FullNameFilter)filters[4]).ExpectedValue, Is.EqualTo("My.Fifth.Test"));
Assert.That(filters[5], Is.TypeOf<FullNameFilter>());
Assert.That(((FullNameFilter)filters[5]).ExpectedValue, Is.EqualTo("My.Sixth.Test"));
}
}
[Test]
public void TestListFileMissing()
{
var options = new NUnitLiteOptions("--testlist:\\badtestlistfile");
Assert.That(options.ErrorMessages.Count, Is.EqualTo(1));
Assert.That(options.ErrorMessages, Does.Contain("Unable to locate file: \\badtestlistfile"));
var filter = TextRunner.CreateTestFilter(options);
Assert.That(filter, Is.EqualTo(TestFilter.Empty));
}
[Test]
public void WhereClauseSpecified()
{
var filter = GetFilter("--where:cat==Urgent");
Assert.That(filter, Is.TypeOf<CategoryFilter>());
Assert.That(((CategoryFilter)filter).ExpectedValue, Is.EqualTo("Urgent"));
}
[Test]
public void TwoTestsAndWhereClauseSpecified()
{
var filter = GetFilter("--test:My.First.Test", "--test:My.Second.Test", "--where:cat==Urgent");
Assert.That(filter, Is.TypeOf<AndFilter>());
var filters = ((AndFilter)filter).Filters;
Assert.That(filters.Count, Is.EqualTo(2));
Assert.That(filters[1], Is.TypeOf<CategoryFilter>());
Assert.That(((CategoryFilter)filters[1]).ExpectedValue, Is.EqualTo("Urgent"));
Assert.That(filters[0], Is.TypeOf<OrFilter>());
filters = ((OrFilter)filters[0]).Filters;
Assert.That(filters.Count, Is.EqualTo(2));
Assert.That(filters[0], Is.TypeOf<FullNameFilter>());
Assert.That(((FullNameFilter)filters[0]).ExpectedValue, Is.EqualTo("My.First.Test"));
Assert.That(filters[1], Is.TypeOf<FullNameFilter>());
Assert.That(((FullNameFilter)filters[1]).ExpectedValue, Is.EqualTo("My.Second.Test"));
}
private TestFilter GetFilter(params string[] args)
{
return TextRunner.CreateTestFilter(new NUnitLiteOptions(args));
}
}
}
| mit |
sschultz/FHSU-GSCI-Weather | Weather/admin.py | 524 | from django.contrib import admin
from Weather.models import *
from Weather.util import updateForecast
def update_forecast(modeladmin, request, queryset):
for forecast in queryset:
updateForecast(forecast)
update_forecast.short_description = "Force forecast update from NWS"
class forecastAdmin(admin.ModelAdmin):
actions = [update_forecast]
class WMSRadarOverlayAdmin(admin.ModelAdmin):
pass
admin.site.register(Forecast, forecastAdmin)
admin.site.register(WMSRadarOverlay, WMSRadarOverlayAdmin) | mit |
cenkalti/rain | torrent/version.go | 118 | package torrent
// Version of client. Set during build.
// "0.0.0" is the development version.
var Version = "0.0.0"
| mit |
fjpavm/ChilliSource | Source/CSBackend/Platform/Windows/Main.cpp | 2273 | //
// Main.cpp
// Chilli Source
// Created by Ian Copland on 06/07/2011.
//
// The MIT License (MIT)
//
// Copyright (c) 2010 Tag Games Limited
//
// 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.
//
#ifdef CS_TARGETPLATFORM_WINDOWS
#include <CSBackend/Platform/Windows/SFML/Base/SFMLWindow.h>
#include <Windows.h>
//----------------------------------------------------------------------------------
/// Includes the "main" function as required by Windows and will create
/// the inherited CS application using the exposed CreateApplication method that
/// the application code base must implement.
///
/// @author S Downie
///
/// @param Handle to current application instance
/// @param Handle to previous application instance
/// @param Command line
/// @param Controls how the window is to be shown (i.e hide, maximize, etc)
///
/// @return Exit status
//----------------------------------------------------------------------------------
int CALLBACK WinMain(_In_ HINSTANCE in_instance, _In_ HINSTANCE in_prevInstance, _In_ LPSTR in_cmdLine, _In_ int in_cmdShow)
{
CSBackend::Windows::SFMLWindow::Create();
CSBackend::Windows::SFMLWindow::Get()->Run();
CSBackend::Windows::SFMLWindow::Destroy();
return 0;
}
#endif
| mit |
emclab/rfqx_emc | spec/dummy/app/models/authentify_user.rb | 159 | class AuthentifyUser < ActiveRecord::Base
#attr_accessible :customer_id, :email, :encrypted_password, :last_updated_by_id, :login, :name, :salt, :status
end
| mit |
mjzitek/goingtohell | config/logger.js | 2572 | /*
From: http://www.snyders.co.uk/2013/04/11/async-logging-in-node-js-just-chill-winston/
*/
var winston = require('winston');
require('winston-mongodb').MongoDB;
var customLevels = {
levels: {
debug: 0,
info: 1,
warn: 2,
error: 3
},
colors: {
debug: 'blue',
info: 'green',
warn: 'yellow',
error: 'red'
}
};
// winston.add(winston.transports.Console, {
// level: 'warn',
// prettyPrint: true,
// colorize: true,
// silent: false,
// timestamp: false
// });
// create the main logger
var debuglogger = new(winston.Logger)({
level: 'debug',
levels: customLevels.levels,
transports: [
// setup console logging
new(winston.transports.Console)({
level: 'info',
levels: customLevels.levels,
colorize: true
}),
// setup logging to file
new(winston.transports.File)({
filename: './logs/debug.log',
maxsize: 1024 * 1024 * 10, // 10MB
level: 'debug',
levels: customLevels.levels
})
]
});
// create the data logger - I only log specific app output data here
var datalogger = new (winston.Logger) ({
level: 'info',
transports: [
new (winston.transports.File) ({
filename: './logs/data.log',
maxsize: 1024 * 1024 * 10 // 10MB
}),
new (winston.transports.MongoDB) ({
db: 'villagelog2',
collection: 'logtest'
})
]
});
var dblogger = new (winston.Logger) ({
level: 'info',
transports: [
new (winston.transports.MongoDB) ({
db: 'villagelog',
collection: 'logtest'
})
]
});
// make winston aware of your awesome colour choices
winston.addColors(customLevels.colors);
var Logging = function() {
var loggers = {};
// always return the singleton instance, if it has been initialised once already.
if (Logging.prototype._singletonInstance) {
return Logging.prototype._singletonInstance;
}
this.getLogger = function(name) {
return loggers[name];
}
this.get = this.getLogger;
loggers['debug'] = debuglogger;
loggers['data'] = datalogger;
loggers['db'] = dblogger;
Logging.prototype._singletonInstance = this;
};
new Logging(); // I decided to force instantiation of the singleton logger here
debuglogger.debug('Debug Logging set up OK!');
datalogger.info('Data Logging set up OK!');
//dblogger.info('Database Logging set up OK!');
exports.Logging = Logging; | mit |
aszczesn/rma-iqutech | application/modules/diy_part_type/models/mdl_perfectcontroller.php | 2324 | <?php if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}
class Mdl_diy_part_type extends CI_Model {
function __construct() {
parent::__construct();
}
function get_table() {
$table = "tablename";
return $table;
}
function get($order_by) {
$table = $this->get_table();
$this->db->order_by($order_by);
$query=$this->db->get($table);
return $query;
}
function get_with_limit($limit, $offset, $order_by) {
$table = $this->get_table();
$this->db->limit($limit, $offset);
$this->db->order_by($order_by);
$query=$this->db->get($table);
return $query;
}
function get_where($id) {
$table = $this->get_table();
$this->db->where('id', $id);
$query=$this->db->get($table);
return $query;
}
function get_where_custom($col, $value) {
$table = $this->get_table();
$this->db->where($col, $value);
$query=$this->db->get($table);
return $query;
}
function _insert($data) {
$table = $this->get_table();
$this->db->insert($table, $data);
}
function _update($id, $data) {
$table = $this->get_table();
$this->db->where('id', $id);
$this->db->update($table, $data);
}
function _delete($id) {
$table = $this->get_table();
$this->db->where('id', $id);
$this->db->delete($table);
}
function count_where($column, $value) {
$table = $this->get_table();
$this->db->where($column, $value);
$query=$this->db->get($table);
$num_rows = $query->num_rows();
return $num_rows;
}
function count_all() {
$table = $this->get_table();
$query=$this->db->get($table);
$num_rows = $query->num_rows();
return $num_rows;
}
function get_max() {
$table = $this->get_table();
$this->db->select_max('id');
$query = $this->db->get($table);
$row=$query->row();
$id=$row->id;
return $id;
}
function _custom_query($mysql_query) {
$query = $this->db->query($mysql_query);
return $query;
}
}
| mit |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2015_06_15/models/bgp_settings_py3.py | 1414 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class BgpSettings(Model):
"""BgpSettings.
:param asn: Gets or sets this BGP speaker's ASN
:type asn: long
:param bgp_peering_address: Gets or sets the BGP peering address and BGP
identifier of this BGP speaker
:type bgp_peering_address: str
:param peer_weight: Gets or sets the weight added to routes learned from
this BGP speaker
:type peer_weight: int
"""
_attribute_map = {
'asn': {'key': 'asn', 'type': 'long'},
'bgp_peering_address': {'key': 'bgpPeeringAddress', 'type': 'str'},
'peer_weight': {'key': 'peerWeight', 'type': 'int'},
}
def __init__(self, *, asn: int=None, bgp_peering_address: str=None, peer_weight: int=None, **kwargs) -> None:
super(BgpSettings, self).__init__(**kwargs)
self.asn = asn
self.bgp_peering_address = bgp_peering_address
self.peer_weight = peer_weight
| mit |
jclo/picodb | test/int/private/query/query_1.js | 10616 | // ESLint declarations:
/* global describe, it */
/* eslint one-var: 0, semi-style: 0, no-underscore-dangle: 0 */
// -- Vendor Modules
const { expect } = require('chai')
;
// -- Local Modules
// -- Local Constants
// -- Local Variables
// -- Main
module.exports = function(PicoDB) {
describe('Test the Comparison Operators:', () => {
const db = PicoDB();
const doc = [
{ a: 1 },
{ a: 1, b: 'bbb', c: 5 },
/* eslint-disable-next-line object-curly-newline */
{ a: 2, b: 'bbb', c: ['a', 'b', 'c'], d: { e: { f: 'f' } } },
];
it('Expects db.insertMany([...]) to return an array with all the documents.', async () => {
const resp = await db.insertMany(doc);
expect(resp).to.be.an('array').that.has.lengthOf(doc.length);
});
describe('$eq:', () => {
it('Expects db.find({ a: { $eq: 1 } }).toArray() to return 2 documents.', async () => {
const resp = await db.find({ a: { $eq: 1 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(2);
});
it('Expects db.find({ b: { $eq: "bbb" } }).toArray() to return 2 documents.', async () => {
const resp = await db.find({ b: { $eq: 'bbb' } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(2);
});
it('Expects db.find({ a: 1, b: { $eq: "bbb" }}).toArray() to return 1 document.', async () => {
const resp = await db.find({ a: 1, b: { $eq: 'bbb' } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(1);
});
it('Expects db.find({ a: { $eq: 1 }, b: { $eq: "bbb" }}).toArray() to return 1 document.', async () => {
const resp = await db.find({ a: { $eq: 1 }, b: { $eq: 'bbb' } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(1);
});
it('Expects db.find({ d: { e: { f: { $eq: "f" }}}}).toArray() to return 1 document.', async () => {
const resp = await db.find({ d: { e: { f: { $eq: 'f' } } } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(1);
});
});
describe('$gt:', () => {
it('Expects db.find({ a: { $gt: 0 }}).toArray() to return 3 documents.', async () => {
const resp = await db.find({ a: { $gt: 0 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(3);
});
it('Expects db.find({ a: { $gt: 1 }}).toArray() to return 1 document.', async () => {
const resp = await db.find({ a: { $gt: 1 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(1);
});
it('Expects db.find({ a: { $gt: 1 }, c: { $gt: 4 }}).toArray() to return 1 document.', async () => {
const resp = await db.find({ a: { $gt: 0 }, c: { $gt: 4 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(1);
});
});
describe('$gte:', () => {
it('Expects db.find({ a: { $gte: 0 }}).toArray() to return 3 documents.', async () => {
const resp = await db.find({ a: { $gte: 0 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(3);
});
it('Expects db.find({ a: { $gte: 1 }}).toArray() to return 3 documents.', async () => {
const resp = await db.find({ a: { $gte: 1 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(3);
});
it('Expects db.find({ a: { $gte: 0 }, c: { $gte: 5 }}).toArray() to return 1 document.', async () => {
const resp = await db.find({ a: { $gte: 0 }, c: { $gte: 5 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(1);
});
});
describe('$lt:', () => {
it('Expects db.find({ a: { $lt: 3 }}).toArray() to return 3 documents.', async () => {
const resp = await db.find({ a: { $lt: 3 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(3);
});
it('Expects db.find({ a: { $lt: 2 }}).toArray() to return 2 documents.', async () => {
const resp = await db.find({ a: { $lt: 2 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(2);
});
it('Expects db.find({ a: { $lt: 3 }, c: { $lt: 6 }}).toArray() to return 1 document.', async () => {
const resp = await db.find({ a: { $lt: 3 }, c: { $lt: 6 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(1);
});
});
describe('$lte:', () => {
it('Expects db.find({ a: { $lte: 2 }}).toArray() to return 3 documents.', async () => {
const resp = await db.find({ a: { $lte: 2 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(3);
});
it('Expects db.find({ a: { $lte: 1 }}).toArray() to return 2 documents.', async () => {
const resp = await db.find({ a: { $lte: 1 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(2);
});
it('Expects db.find({ a: { $lte: 2 }, c: { $lte: 5 }}).toArray() to return 1 document.', async () => {
const resp = await db.find({ a: { $lte: 2 }, c: { $lte: 5 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(1);
});
});
describe('$ne:', () => {
it('Expects db.find({ a: { $ne: 1 }}).toArray() to return 1 document.', async () => {
const resp = await db.find({ a: { $ne: 1 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(1);
});
it('Expects db.find({ a: { $ne: 2 }}).toArray() to return 2 documents.', async () => {
const resp = await db.find({ a: { $ne: 2 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(2);
});
it('Expects db.find({ b: { $ne: "bbb" }}).toArray() to return 1 document.', async () => {
const resp = await db.find({ b: { $ne: 'bbb' } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(1);
});
it('Expects db.find({ bc: { $ne: "bbb" }}).toArray() to return 3 documents.', async () => {
const resp = await db.find({ bc: { $ne: 'bbb' } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(3);
});
it('Expects db.find({ d: { e: { f: { $ne: "f" }}}}).toArray() to return 2 documents.', async () => {
const resp = await db.find({ d: { e: { f: { $ne: 'f' } } } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(2);
});
it('Expects db.find({ c: { $ne: 5 }}).toArray() to return 2 documents.', async () => {
const resp = await db.find({ c: { $ne: 5 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(2);
});
it('Expects db.find({ a: { $eq: 2 }, d: { e: { f: { $ne: "f" }}}}).toArray() to return 0 document.', async () => {
const resp = await db.find({ a: { $eq: 2 }, d: { e: { f: { $ne: 'f' } } } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(0);
});
});
describe('$in:', () => {
it('Expects db.find({ b: { $in: ["aaa", "bbb"] }}).toArray() to return 2 documents.', async () => {
const resp = await db.find({ b: { $in: ['aaa', 'bbb'] } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(2);
});
it('Expects db.find({ a: { $in: [1, 2] }}).toArray() to return 3 documents.', async () => {
const resp = await db.find({ a: { $in: [1, 2] } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(3);
});
it('Expects db.find({ c: { $in: ["a", "b", "d"] }}).toArray() to return 1 document.', async () => {
const resp = await db.find({ c: { $in: ['a', 'b', 'd'] } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(1);
});
it('Expects db.find({ c: { $in: ["d", "e"] }}).toArray() to return 0 document.', async () => {
const resp = await db.find({ c: { $in: ['d', 'e'] } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(0);
});
});
describe('$nin:', () => {
it('Expects db.find({ b: { $nin: ["ccc", "ddd"] }}).toArray() to return 3 documents.', async () => {
const resp = await db.find({ b: { $nin: ['ccc', 'ddd'] } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(3);
});
it('Expects db.find({ b: { $nin: ["bbb", "ccc"] }}).toArray() to return 1 document.', async () => {
const resp = await db.find({ b: { $nin: ['bbb', 'ccc'] } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(1);
});
it('Expects db.find({ c: { $nin: [1, 5] }}).toArray() to return 2 documents.', async () => {
const resp = await db.find({ c: { $nin: [1, 5] } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(2);
});
it('Expects db.find({ c: { $nin: [1, "a"] }}).toArray() to return 1 document.', async () => {
const resp = await db.find({ c: { $nin: [5, 'a'] } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(1);
});
});
describe('gt & $lt:', () => {
it('Expects db.find({ a: { $gt: 1, $lt: 3 }}).toArray() to return 1 document.', async () => {
const resp = await db.find({ a: { $gt: 1, $lt: 3 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(1);
});
it('Expects db.find({ a: { $gte: 1, $lte: 2 }}).toArray() to return 3 documents.', async () => {
const resp = await db.find({ a: { $gte: 1, $lte: 2 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(3);
});
it('Expects db.find({ a: { $gt: 1, $lt: 2 }}).toArray() to return 0 document.', async () => {
const resp = await db.find({ a: { $gt: 1, $lt: 2 } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(0);
});
});
describe('$ne & $nin:', () => {
it('Expects db.find({ a: { $ne: 3 }, b: { $nin: ["bbb"] }}).toArray() to return 1 document.', async () => {
const resp = await db.find({ a: { $ne: 3 }, b: { $nin: ['bbb'] } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(1);
});
it('Expects db.find({ b: { $nin: ["b"] }, c: { $nin: ["a"] }}).toArray() to return 2 documents.', async () => {
const resp = await db.find({ b: { $nin: ['b'] }, c: { $nin: ['a'] } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(2);
});
it('Expects db.find({ b: { $nin: ["bbb"] }, c: { $nin: ["a"] }}).toArray() to return 1 document.', async () => {
const resp = await db.find({ b: { $nin: ['bbb'] }, c: { $nin: ['a'] } }).toArray();
expect(resp).to.be.an('array').that.has.lengthOf(1);
});
});
});
};
| mit |
minimus/final-task | client-src/redux/modules/search/search.js | 3572 | import { prepareFacets } from '../helpers'
const SEARCH_FETCH_STARTED = 'SEARCH_FETCH_STARTED'
const SEARCH_FETCH_COMPLETED = 'SEARCH_FETCH_COMPLETED'
const SEARCH_FETCH_UNCOMPLETED = 'SEARCH_FETCH_UNCOMPLETED'
const SEARCH_FACET_CHANGED = 'SEARCH_FACET_CHANGED'
const SEARCH_FACETS_CLEAR = 'SEARCH_FACETS_CLEAR'
const SEARCH_BAR_CHANGED = 'SEARCH_BAR_CHANGED'
export function fetchSearchData(phrase, page, filter = []) {
return function (dispatch) {
dispatch({ type: SEARCH_FETCH_STARTED, payload: { loading: true, notFound: false } })
const url = new URL(`/data/search/${encodeURIComponent(phrase)}/${page}/`, window.location.origin)
if (filter.length) url.searchParams.append('filter', JSON.stringify(filter))
fetch(url)
.then(data => data.json())
.then(data => dispatch({
type: SEARCH_FETCH_COMPLETED,
payload: {
data: data.data,
categories: data.cats,
facets: prepareFacets(data),
count: (!!data.count && data.count.length) ? data.count[0].count : 0,
page: data.page,
offersOnPage: data.offersOnPage,
phrase: data.phrase,
loading: false,
notFound: false,
},
}))
.catch(e => dispatch({
type: SEARCH_FETCH_UNCOMPLETED,
payload: {
data: null,
categories: null,
facets: null,
count: 0,
page: 1,
offersOnPage: 0,
phrase: '',
loading: false,
notFound: true,
error: e,
},
}))
}
}
export function facetChanged(event) {
return function (dispatch) {
const target = event.currentTarget
const filterValue = (value) => {
if (/^(-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/
.test(value)) { return Number(value) }
return value
}
dispatch({
type: SEARCH_FACET_CHANGED,
payload: {
field: target.dataset.field,
name: target.dataset.name,
value: filterValue(target.dataset.value),
},
})
}
}
export function facetsClearSelected() {
return function (dispatch) {
dispatch({ type: SEARCH_FACETS_CLEAR })
}
}
export function clearFacets() {
return function (dispatch) {
dispatch({ type: SEARCH_FACETS_CLEAR })
}
}
const initialState = {
data: null,
categories: null,
facets: null,
selectedFacets: [],
count: 0,
phrase: '',
page: 1,
pages: 0,
offersOnPage: 0,
loading: false,
notFound: false,
error: '',
}
export default function reducer(state = initialState, action) {
switch (action.type) {
case SEARCH_FETCH_STARTED:
return { ...state, ...action.payload }
case SEARCH_FETCH_COMPLETED:
return {
...state,
...action.payload,
pages: (!action.payload.notFound) ?
Math.ceil(action.payload.count / action.payload.offersOnPage) : 0,
}
case SEARCH_FETCH_UNCOMPLETED:
return { ...state, ...action.payload }
case SEARCH_FACET_CHANGED: {
const selFacets = [...state.selectedFacets]
const idx = selFacets.findIndex(e =>
(e.field === action.payload.field &&
e.name === action.payload.name &&
e.value === action.payload.value))
if (idx > -1) selFacets.splice(idx, 1)
else selFacets.push(action.payload)
return { ...state, selectedFacets: selFacets }
}
case SEARCH_FACETS_CLEAR:
return { ...state, selectedFacets: [] }
case SEARCH_BAR_CHANGED:
return { ...state, phrase: action.payload }
default:
return state
}
}
| mit |
samitheberber/pathfinder | src/test/java/fi/cs/helsinki/saada/pathfinder/pathfinding/PathTest.java | 1953 | package fi.cs.helsinki.saada.pathfinder.pathfinding;
import fi.cs.helsinki.saada.pathfinder.world.Coordinate;
import static org.easymock.EasyMock.createMock;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import static org.junit.matchers.JUnitMatchers.hasItem;
/**
*
* @author stb
*/
public class PathTest {
private Path path;
private Coordinate start, end;
@Before
public void setUp() throws Exception {
start = createMock(Coordinate.class);
end = createMock(Coordinate.class);
path = new Path(start, end);
}
@Test
public void roadless_path_should_be_empty() {
assertTrue(path.isEmpty());
assertEquals(0, path.size());
}
@Test
public void path_contains_start_point() {
assertEquals(start, path.getStart());
}
@Test
public void path_contains_end_point() {
assertEquals(end, path.getEnd());
}
@Test
public void path_contains_added_road() {
Coordinate road = createMock(Coordinate.class);
addRoad(road, 1);
}
@Test
public void path_contains_multiple_roads() {
Coordinate road1 = createMock(Coordinate.class);
addRoad(road1, 1);
Coordinate road2 = createMock(Coordinate.class);
addRoad(road2, 2);
Coordinate road3 = createMock(Coordinate.class);
addRoad(road3, 3);
Coordinate road4 = createMock(Coordinate.class);
addRoad(road4, 4);
}
@Test
public void path_contains_road_only_once() {
Coordinate road = createMock(Coordinate.class);
addRoad(road, 1);
assertFalse(path.add(road));
assertEquals(1, path.size());
}
private void addRoad(Coordinate road, int expectedSize) {
assertTrue(path.add(road));
assertEquals(expectedSize, path.size());
assertFalse(path.isEmpty());
assertThat(path, hasItem(road));
}
}
| mit |
guless/SWFAnimator | src/interface/IWritable.js | 2958 | /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// @Copyright ~2016 ☜Samlv9☞ and other contributors
/// @MIT-LICENSE | 1.0.0 | http://apidev.guless.com/
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// }|
/// }|
/// }| へ /|
/// _______ _______ ______ }| / │ / /
/// / ___ | |_ __ \ .' ____ '. }| │ Z _,< / /`ヽ
/// | (__ \_| | |__) | | (____) | }| │ ヽ / 〉
/// '.___`-. | __ / '_.____. | }| Y ` / /
/// |`\____) | _| | \ \_ | \____| | }| イ● 、 ● ⊂⊃〈 /
/// |_______.' |____| |___| \______,' }| () v | \〈
/// |=========================================\| >ー 、_ ィ │ //
/// |> LESS IS MORE || / へ / ノ<|\\
/// `=========================================/| ヽ_ノ (_/ │//
/// }| 7 |/
/// }| >―r ̄ ̄`ー―_`
/// }|
/// }|
/// 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.
/*< export default interface IWritable { >*/
/*< setBool( value ); >*/
/*< setUI8 ( value ); >*/
/*< setSI8 ( value ); >*/
/*< setUI16( value ); >*/
/*< setSI16( value ); >*/
/*< setUI32( value ); >*/
/*< setSI32( value ); >*/
/*< setFL32( value ); >*/
/*< setFL64( value ); >*/
/*< setBytes( bytes ); >*/
/*<}>*/ | mit |
signumsoftware/framework | Signum.Entities/DynamicQuery/Filter.cs | 8921 | using Signum.Utilities.Reflection;
using System.Collections;
using System.ComponentModel;
namespace Signum.Entities.DynamicQuery;
[InTypeScript(true), DescriptionOptions(DescriptionOptions.Members | DescriptionOptions.Description)]
public enum FilterGroupOperation
{
And,
Or,
}
public abstract class Filter
{
public abstract Expression GetExpression(BuildExpressionContext ctx);
public abstract IEnumerable<FilterCondition> GetFilterConditions();
public abstract bool IsAggregate();
}
public class FilterGroup : Filter
{
public FilterGroupOperation GroupOperation { get; }
public QueryToken? Token { get; }
public List<Filter> Filters { get; }
public FilterGroup(FilterGroupOperation groupOperation, QueryToken? token, List<Filter> filters)
{
this.GroupOperation = groupOperation;
this.Token = token;
this.Filters = filters;
}
public override IEnumerable<FilterCondition> GetFilterConditions()
{
return Filters.SelectMany(a => a.GetFilterConditions());
}
public override Expression GetExpression(BuildExpressionContext ctx)
{
if (Token is not CollectionAnyAllToken anyAll)
{
return this.GroupOperation == FilterGroupOperation.And ?
Filters.Select(f => f.GetExpression(ctx)).AggregateAnd() :
Filters.Select(f => f.GetExpression(ctx)).AggregateOr();
}
else
{
Expression collection = anyAll.Parent!.BuildExpression(ctx);
Type elementType = collection.Type.ElementType()!;
var p = Expression.Parameter(elementType, elementType.Name.Substring(0, 1).ToLower());
ctx.Replacemens.Add(anyAll, p.BuildLite().Nullify());
var body = this.GroupOperation == FilterGroupOperation.And ?
Filters.Select(f => f.GetExpression(ctx)).AggregateAnd() :
Filters.Select(f => f.GetExpression(ctx)).AggregateOr();
ctx.Replacemens.Remove(anyAll);
return anyAll.BuildAnyAll(collection, p, body);
}
}
public override string ToString()
{
return $@"{this.GroupOperation}{(this.Token != null ? $" ({this.Token})" : null)}
{Filters.ToString("\r\n").Indent(4)}";
}
public override bool IsAggregate()
{
return this.Filters.Any(f => f.IsAggregate());
}
}
public class FilterCondition : Filter
{
public QueryToken Token { get; }
public FilterOperation Operation { get; }
public object? Value { get; }
public FilterCondition(QueryToken token, FilterOperation operation, object? value)
{
this.Token = token;
this.Operation = operation;
this.Value = ReflectionTools.ChangeType(value, operation.IsList() ? typeof(IEnumerable<>).MakeGenericType(Token.Type.Nullify()) : Token.Type);
}
public override IEnumerable<FilterCondition> GetFilterConditions()
{
yield return this;
}
static MethodInfo miContainsEnumerable = ReflectionTools.GetMethodInfo((IEnumerable<int> s) => s.Contains(2)).GetGenericMethodDefinition();
public override Expression GetExpression(BuildExpressionContext ctx)
{
CollectionAnyAllToken? anyAll = Token.Follow(a => a.Parent)
.OfType<CollectionAnyAllToken>()
.TakeWhile(c => !ctx.Replacemens.ContainsKey(c))
.LastOrDefault();
if (anyAll == null)
return GetConditionExpressionBasic(ctx);
Expression collection = anyAll.Parent!.BuildExpression(ctx);
Type elementType = collection.Type.ElementType()!;
var p = Expression.Parameter(elementType, elementType.Name.Substring(0, 1).ToLower());
ctx.Replacemens.Add(anyAll, p.BuildLiteNullifyUnwrapPrimaryKey(new[] { anyAll.GetPropertyRoute()! }));
var body = GetExpression(ctx);
ctx.Replacemens.Remove(anyAll);
return anyAll.BuildAnyAll(collection, p, body);
}
public static Func<bool> ToLowerString = () => false;
private Expression GetConditionExpressionBasic(BuildExpressionContext context)
{
Expression left = Token.BuildExpression(context);
if (Operation.IsList())
{
if (Value == null)
return Expression.Constant(false);
IList clone = (IList)Activator.CreateInstance(Value.GetType(), Value)!;
bool hasNull = false;
while (clone.Contains(null))
{
clone.Remove(null);
hasNull = true;
}
if (Token.Type == typeof(string))
{
while (clone.Contains(""))
{
clone.Remove("");
hasNull = true;
}
if (ToLowerString())
{
clone = clone.Cast<string>().Select(a => a.ToLower()).ToList();
left = Expression.Call(left, miToLower);
}
if (hasNull)
{
clone.Add("");
left = Expression.Coalesce(left, Expression.Constant(""));
}
}
Expression right = Expression.Constant(clone, typeof(IEnumerable<>).MakeGenericType(Token.Type.Nullify()));
var contains = Expression.Call(miContainsEnumerable.MakeGenericMethod(Token.Type.Nullify()), right, left.Nullify());
var result = !hasNull || Token.Type == typeof(string) ? (Expression)contains :
Expression.Or(Expression.Equal(left, Expression.Constant(null, Token.Type.Nullify())), contains);
if (Operation == FilterOperation.IsIn)
return result;
if (Operation == FilterOperation.IsNotIn)
return Expression.Not(result);
throw new InvalidOperationException("Unexpected operation");
}
else
{
var val = Value;
if (Token.Type == typeof(string) && (val == null || val is string str && string.IsNullOrEmpty(str)))
{
val ??= "";
left = Expression.Coalesce(left, Expression.Constant(""));
}
if (Token.Type == typeof(string) && ToLowerString())
{
Expression right = Expression.Constant(((string)val!).ToLower(), Token.Type);
return QueryUtils.GetCompareExpression(Operation, Expression.Call(left, miToLower), right);
}
else if (Token.Type == typeof(bool) && val == null)
{
return QueryUtils.GetCompareExpression(Operation, left, Expression.Constant(false, typeof(bool)));
}
else
{
Expression right = Expression.Constant(val, Token.Type);
return QueryUtils.GetCompareExpression(Operation, left, right);
}
}
}
static MethodInfo miToLower = ReflectionTools.GetMethodInfo(() => "".ToLower());
public override bool IsAggregate()
{
return this.Token is AggregateToken;
}
public override string ToString()
{
return "{0} {1} {2}".FormatWith(Token.FullKey(), Operation, Value);
}
}
[InTypeScript(true), DescriptionOptions(DescriptionOptions.Members | DescriptionOptions.Description)]
public enum FilterOperation
{
EqualTo,
DistinctTo,
GreaterThan,
GreaterThanOrEqual,
LessThan,
LessThanOrEqual,
Contains,
StartsWith,
EndsWith,
Like,
NotContains,
NotStartsWith,
NotEndsWith,
NotLike,
IsIn,
IsNotIn,
}
[InTypeScript(true)]
public enum FilterType
{
Integer,
Decimal,
String,
DateTime,
Time,
Lite,
Embedded,
Boolean,
Enum,
Guid,
}
[InTypeScript(true)]
public enum UniqueType
{
First,
FirstOrDefault,
Single,
SingleOrDefault,
Only
}
[InTypeScript(true), DescriptionOptions(DescriptionOptions.Members | DescriptionOptions.Description)]
public enum PinnedFilterActive
{
Always,
WhenHasValue,
[Description("Checkbox (start checked)")]
Checkbox_StartChecked,
[Description("Checkbox (start unchecked)")]
Checkbox_StartUnchecked,
}
[InTypeScript(true), DescriptionOptions(DescriptionOptions.Members | DescriptionOptions.Description)]
public enum DashboardBehaviour
{
//ShowAsPartFilter = 0, //Pinned Filter shown in the Part Widget
PromoteToDasboardPinnedFilter = 1, //Pinned Filter promoted to dashboard
UseAsInitialSelection, //Filters other parts in the same interaction group as if the user initially selected
UseWhenNoFilters
}
| mit |
balvig/chili | spec/spec_helper.rb | 1045 | # This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../example_app/config/environment", __FILE__)
require 'rspec/rails'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
Dir[File.join(File.dirname(__FILE__),'support', '**', '*.rb')].each {|f| require f}
RSpec.configure do |config|
# == Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
end
| mit |