repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
drb/random-world | lib/methods/data/extensions.js | 329 | var extensions = [
'doc', 'dot', 'docx', 'docm', 'dotx', 'dotm', 'docb', 'csv', 'xls', 'xlt',
'xlm', 'xlsx', 'xlsm', 'xltx', 'xltm', 'xlsb', 'xla', 'xlam', 'xll', 'xlw',
'zip', 'a', 'ar', 'cpio', 'shar', 'lbr', 'iso', 'mar', 'tar', 'bz2', 'gz',
'xz', 'z', 'pdf', 'png', 'jpg', 'jpeg', 'gif'];
module.exports = extensions; | mit |
jinky32/story-project | config/deploy.rb | 1996 | # config valid only for current version of Capistrano
lock '3.4.0'
#set :tmp_dir, "#{fetch(:home)}/tmp"
set :tmp_dir, "/home/stuartbrown/pickingorganic.org/tmp"
set :application, 'storyproject'
set :repo_url, '[email protected]:jinky32/story-project.git'
# Default branch is :master
# ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp
# Default deploy_to directory is /var/www/my_app_name
set :deploy_to, '/home/stuartbrown/pickingorganic.org'
# Default value for :scm is :git
set :scm, :git
# Default value for :format is :pretty
# set :format, :pretty
# Default value for :log_level is :debug
set :log_level, :debug
# Default value for :pty is false
# set :pty, true
# Default value for :linked_files is []
set :linked_files, fetch(:linked_files, []).push('app/config/parameters.yml')
# Default value for linked_dirs is []
set :linked_dirs, fetch(:linked_dirs, []).push('vendor/bundle')
# Default value for default_env is {}
# set :default_env, { path: "/opt/ruby/bin:$PATH" }
# Default value for keep_releases is 5
# set :keep_releases, 5
#namespace :deploy do
# after :restart, :clear_cache do
# on roles(:web), in: :groups, limit: 3, wait: 10 do
# Here we can do anything such as:
# within release_path do
# execute :rake, 'cache:clear'
# end
# end
#end
#end
namespace :deploy do
desc 'composer install'
task :composer_install do
on roles(:web) do
within release_path do
execute 'composer', 'install', '--optimize-autoloader'
end
end
end
after :updated, 'deploy:composer_install'
desc 'Restart application - does nothing, see comments below'
task :restart do
on roles(:app), in: :sequence, wait: 5 do
# This is present b/c 'cap production deploy' is blowing up w/o it.
# Not sure what's up with that, the Google hasn't helped, and I'm tired
# of screwing with it. It stays in for now.
end
end
end
| mit |
soanni/onclinic | application/controllers/Operator.php | 3736 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
//implements User_interface
class Operator extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model('operator_model');
$this->load->helper('form');
$this->load->helper('url_helper');
$this->load->library('form_validation');
$this->load->library('session');
}
public function login(){
$data = new stdClass();
$data->title = 'OnClinic Employee Login';
$rules = array(
array(
'field'=>'username',
'label'=>'Username',
'rules'=>array('trim','required','alpha_numeric','min_length[4]')
),
array(
'field'=>'pass',
'label'=>'Password',
'rules'=>array('trim','required','min_length[6]')
)
);
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() === FALSE) {
$this->load->view('templates/lab_header',$data);
$this->load->view('operator/login', $data);
$this->load->view('templates/lab_footer');
}else{
$username = $this->input->post('username');
$password = $this->input->post('pass');
$userrow = $this->operator_model->getUserRow($username);
if(!empty($userrow)){
// if user is locked then login is impossible
if($userrow['locked']){
$data->error = "User {$username} is locked. You cannot proceed further.";
}else{
// user is unlocked so we need to check the password correctness
$salt = $userrow['salt'];
$encrypted_pass = $userrow['pwd'];
if($this->operator_model->isValidPassword($password,$salt,$encrypted_pass)){
// set session variables
$_SESSION['user_id'] = (int)$userrow['user_id'];
$_SESSION['username'] = (string)$username;
$_SESSION['logged_in'] = (bool)true;
$_SESSION['is_operator'] = (bool)true;
$_SESSION['is_patient'] = (bool)false;
$redirect = site_url('operator/profile/' . $userrow['user_id']);
//remove after completing profile
//$data->error = 'You are logged in';
redirect($redirect);
exit;
}else{
$data->error = "Incorrect password provided. Please, try again";
}
}
}else{
$data->error = "There is no such username {$username} in the system.";
}
$this->load->view('templates/lab_header',$data);
$this->load->view('operator/login', $data);
$this->load->view('templates/lab_footer');
}
}
public function logout(){
$data = new stdClass();
$data->title = 'Log out';
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in']) {
// remove session data
foreach ($_SESSION as $key => $value) {
unset($_SESSION[$key]);
}
session_destroy();
// user logout ok
redirect('/');
} else {
// there user was not logged in, we cannot logged him out,
// redirect him to site root
redirect('/');
}
}
public function profile($userid = null){
$this->load->view('operator/profile');
}
} | mit |
time-machine/boom | lib/boom/command.rb | 13022 | # coding: utf-8
# Command is the main point of entry for boom commands; shell arguments are
# passed through to Command, which then filters and parses through individual
# commands and reroutes them to constituent object classes.
#
# Command also keeps track of one connection to Storage, which is how new data
# changes are persisted to disk. It takes care of any data changes by calling
# Boom::Command#save.
module Boom
class Command
class << self
include Boom::Color
# Public: Accesses the in-memory JSON representation.
#
# Returns a Storage instance.
def storage
Boom.storage
end
# Public: Executes a command.
#
# args - The actuall commands to operate on. Can be as few as zero
# arguments or as many as three.
def execute(*args)
command = args.shift
major = args.shift
minor = args.empty? ? nil : args.join(' ')
return overview unless command
delegate(command, major, minor)
end
# Public: Prints any given String.
#
# s - The String to output
#
# Prints to STDOUT and returns. This method exists to standardize output
# and for easy mocking and overriding.
def output(s)
puts(s)
end
# Public: gets $stdin.
#
# Returns the $stdin object. This method exists to help with easy mocking
# or overriding.
def stdin
$stdin
end
# Public: Prints a tidy overview of your Lists in descending order of
# number of Items.
#
# Returns nothing.
def overview
storage.lists.each do |list|
output " #{list.name} (#{list.items.size})"
end
s = "You don't have anything yet! To start out, create a new list:"
s << "\n $ boom <list-name>"
s << "\nAnd then add something to your list!"
s << "\n $ boom <list-name> <item-name> <item-value>"
s << "\nYou can then grab your new item:"
s << "\n $ boom <item-name>"
output s if storage.lists.size == 0
end
# Public: Prints the detailed view of all your Lists and all their
# Items.
#
# Returns nothing.
def all
storage.lists.each do |list|
output " #{list.name}"
list.items.each do |item|
output " #{item.short_name}:#{item.spacer} #{item.value}"
end
end
end
# Public: Allows main access to most commands.
#
# Returns output based on method calls.
def delegate(command, major, minor)
return all if command == 'all'
return edit if command == 'edit'
return switch(major) if command == 'switch'
return show_storage if command == 'storage'
return version if command == '-v'
return version if command == '--version'
return help if command == 'help'
return help if command[0] == 45 || command[0] == '-' # any - dash options are please for help
return echo(major, minor) if command == 'echo' || command == 'e'
return open(major, minor) if command == 'open' || command == 'o'
return random(major) if command == 'random' || command == 'rand' || command == 'r'
# if we're operating on a List
if storage.list_exists?(command)
return delete_list(command) if major == 'delete'
return detail_list(command) unless major
unless minor == 'delete'
return add_item(command, major, minor) if minor
return add_item(command, major, stdin.read) if stdin.stat.size > 0
return search_list_for_item(command, major)
end
end
if minor == 'delete' and storage.item_exists?(major)
return delete_item(command, major)
end
return search_items(command) if storage.item_exists?(command)
return create_list(command, major, stdin.read) if !minor && stdin.stat.size > 0
return create_list(command, major, minor)
end
# Public: Shows the current user's storage.
#
# Returns nothing.
def show_storage
output "You're currently using #{Boom.config.attributes['backend']}."
end
# Public: Switch to a new backend.
#
# backend - The String of the backend desired.
#
# Returns nothing.
def switch(backend)
Storage.backend = backend
output "We've switched you over to #{backend}."
rescue NameError
output "We couldn't find that storage engine. Check the name and try again."
end
# Public: Prints all Items over a List.
#
# name - The List object to iterate over.
#
# Returns nothing.
def detail_list(name)
list = List.find(name)
list.items.sort {|x,y| x.name <=> y.name }.each do |item|
output " #{item.short_name}:#{item.spacer} #{item.value}"
end
end
# Public: Opens the Item.
#
# Returns nothing.
def open(major, minor)
if storage.list_exists?(major)
list = List.find(major)
if minor
item = storage.items.detect { |item| item.name == minor }
output "#{cyan("Boom!")} We just opened #{yellow(Platform.open(item))} for you."
else
list.items.each { |item| Platform.open(item) }
output "#{cyan("Boom!")} We just opened all of #{yellow(major)} for you."
end
else
item = storage.items.detect { |item| item.name == major }
output "#{cyan("Boom!")} We just opened #{yellow(Platform.open(item))} for you."
end
end
# Public : Opens a random item.
#
# Returns nothing.
def random(major)
if major.nil?
index = rand(storage.items.size)
item = storage.items[index]
elsif storage.list_exists?(major)
list = List.find(major)
index = rand(list.items.size)
item = list.items[index]
else
output "We couldn't find that list."
end
open(item.name, nil) unless item.nil?
end
# Public: Echoes only the Item's value without copying.
#
# item_name - The String term to search for in all Item names.
#
# Returns nothing.
def echo(major, minor)
unless minor
item = storage.items.detect do |item|
item.name == major
end
return output "#{yellow(major)} #{red("not found")}" unless item
else
list = List.find(major)
item = list.find_item(minor)
return output "#{yellow(minor)} #{red("not found in")} #{yellow(major)}" unless item
end
output item.value
end
# Public: Add a new List.
#
# name - The String name of the List.
# item - The String name of the Item.
# value - The String value of Item.
#
# Example
#
# Commands.create_list("snippets")
# Commands.create_list("hotness", "item", "value")
#
# Returns the newly created List and creates an item when asked.
def create_list(name, item=nil, value=nil)
lists = (storage.lists << List.new(name))
storage.lists = lists
output "#{cyan("Boom!")} Created a new list called #{yellow(name)}."
save
add_item(name, item, value) unless value.nil?
end
# Public: Remove a named List.
#
# name - The String name of the List.
#
# Example
#
# Commands.delete_list("snippets")
#
# Returns nothing.
def delete_list(name)
output "You sure you want to delete everything in #{yellow(name)}? (y/n):"
if $stdin.gets.chomp == 'y'
List.delete(name)
output "#{cyan("Boom!")} Deleted all your #{yellow(name)}."
save
else
output "Just kidding then."
end
end
# Public: Add a new Item to a list.
#
# list - The String name of the List to associate with this Item.
# name - The String name of the Item.
# value - The String value of the Item.
#
# Example
#
# Commands.add_item("snippets", "sig", "- @holman")
#
# Returns the newly created Item.
def add_item(list, name, value)
list = List.find(list)
list.add_item(Item.new(name, value))
output "#{cyan("Boom!")} #{yellow(name)} in #{yellow(list.name)} is #{yellow(value)}. Got it."
save
end
# Public: Remove a named Item.
#
# list_name - The String name of the List.
# name - The String name of the Item.
#
# Example
#
# Commands.delete_item("a-list-name", "an-item-name")
#
# Returns nothing.
def delete_item(list_name, name)
if storage.list_exists?(list_name)
list = List.find(list_name)
if list.delete_item(name)
output "#{cyan("Boom!")} #{yellow(name)} is gone forever."
save
else
output "#{yellow(name)} #{red("not found in")} #{yellow(list_name)}"
end
else
output "We couldn't find that list."
end
end
# Public: Search for an Item in all lists by name. Drops the
# corresponding entry into your clipboard.
#
# name - The String term to search for in all Item names.
#
# Returns the matching Item.
def search_items(name)
item = storage.items.detect do |item|
item.name == name
end
output "#{cyan("Boom!")} We just copied #{yellow(Platform.copy(item))} to your clipboard."
end
# Public: Search for an Item in a particular list by name. Drops the
# corresponding entry into your clipboard if found.
#
# list_name - The String name of the List in which to scope the search.
# item_name - The String term to search for in all Item names.
#
# Returns the matching Item if found.
def search_list_for_item(list_name, item_name)
list = List.find(list_name)
item = list.find_item(item_name)
if item
output "#{cyan("Boom!")} We just copied #{yellow(Platform.copy(item))} to your clipboard."
else
output "#{yellow(item_name)} #{red("not found in")} #{yellow(list_name)}"
end
end
# Public: Save in-memory data to disk
#
# Returns whether or not data was saved.
def save
storage.save
end
# Public: The version fo boom that you're currently running.
#
# Returns a String identifying the version number.
def version
output "You're running boom #{Boom::VERSION}. Congratulations!"
end
# Public: Launches JSON file in an editor for you to edit manually.
#
# Returns nothing.
def edit
if storage.respond_to?('json_file')
output "#{cyan("Boom!")} #{Platform.edit(storage.json_file)}"
else
output "This storage backend does not store #{cyan("Boom!")} data on your computer"
end
end
# Public: Prints all the commands of boom.
#
# Returns nothing.
def help
text = %{
- boom: help ---------------------------------------------------
boom display high-level overview
boom all show all items in all lists
boom edit edit the boom JSON file in $EDITOR
boom help this help text
boom storage shows which storage backend you're using
boom switch <storage> switches to a different storage backend
boom <list> create a new list
boom <list> show items for a list
boom <list> delete deletes a list
boom <list> <name> <value> create a new list item
boom <name> copy item's value to clipboard
boom <list> <name> copy item's value to clipboard
boom open <name> open item's url in browser
boom open <list> <name> open item's url in browser
boom random open a random item's url in browser
boom random <list> open a random item's url for a list in browser
boom echo <name> echo the item's value without copying
boom echo <list> <name> echo the item's value without copying
boom <list> <name> delete deletes an item
all other documentation is located at:
https://github.com/holman/boom
}.gsub(/^ {8}/, '') # strip the first eight spaces of every line
output text
end
end
end
end
| mit |
genusP/linq2db | Tests/Linq/Linq/AnalyticTests.cs | 56238 | namespace Tests.Linq
{
using System.Linq;
using LinqToDB;
using NUnit.Framework;
[TestFixture]
public class AnalyticTests : TestBase
{
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative,
ProviderName.SqlServer2012, ProviderName.SqlServer2014, ProviderName.PostgreSQL)]
public void Test(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Rank1 = Sql.Ext.Rank().Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ThenBy(c.ChildID).ThenBy(c.ParentID).ToValue(),
RowNumber = Sql.Ext.RowNumber().Over().PartitionBy(p.Value1, c.ChildID).OrderByDesc(p.Value1).ThenBy(c.ChildID).ThenByDesc(c.ParentID).ToValue(),
DenseRank = Sql.Ext.DenseRank().Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
Sum = Sql.Ext.Sum(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
Avg = Sql.Ext.Average<double>(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
Count1 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
Count2 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).ThenBy(c.ChildID).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
Count4 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).ThenByDesc(c.ChildID).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
Count6 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).Rows.Between.UnboundedPreceding.And.ValuePreceding(3).ToValue(),
Count7 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).Range.Between.CurrentRow.And.UnboundedFollowing.ToValue(),
Count8 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1, Sql.NullsPosition.None).Rows.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
Count9 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).Range.UnboundedPreceding.ToValue(),
Count10 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).Range.CurrentRow.ToValue(),
Count11 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).Rows.ValuePreceding(1).ToValue(),
Count12 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderByDesc(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
Count14 = Sql.Ext.Count().Over().ToValue(),
Combination = Sql.Ext.Rank().Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ThenBy(c.ChildID).ToValue() +
Sql.Sqrt(Sql.Ext.DenseRank().Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue()) +
Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue() +
Sql.Ext.Count().Over().ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative,
ProviderName.SqlServer2012, ProviderName.SqlServer2014, ProviderName.PostgreSQL)]
public void TestSubqueryOptimization(string context)
{
using (var db = GetDataContext(context))
{
var subq =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Rank = Sql.Ext.Rank().Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ThenBy(c.ChildID).ThenBy(c.ParentID).ToValue(),
RowNumber = Sql.Ext.RowNumber().Over().PartitionBy(p.Value1, c.ChildID).OrderByDesc(p.Value1).ThenBy(c.ChildID).ThenByDesc(c.ParentID).ToValue(),
DenseRank = Sql.Ext.DenseRank().Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
};
var q = from sq in subq
where sq.Rank > 0
select sq;
var res = q.ToList();
Assert.IsNotEmpty(res);
}
}
[Test, IncludeDataContextSource(ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestExtensionsOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Rank1 = Sql.Ext.Rank().Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ThenBy(c.ChildID).ThenBy(c.ParentID, Sql.NullsPosition.First).ToValue(),
Rank2 = Sql.Ext.Rank().Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1, Sql.NullsPosition.Last).ThenBy(c.ChildID).ThenBy(c.ParentID, Sql.NullsPosition.First).ToValue(),
RowNumber = Sql.Ext.RowNumber().Over().PartitionBy(p.Value1, c.ChildID).OrderByDesc(p.Value1, Sql.NullsPosition.First).ThenBy(c.ChildID).ThenByDesc(c.ParentID, Sql.NullsPosition.First).ToValue(),
DenseRank = Sql.Ext.DenseRank().Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
Count1 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
Count2 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).ThenBy(c.ChildID).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
Count3 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).ThenBy(c.ChildID, Sql.NullsPosition.First).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
Count4 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).ThenByDesc(c.ChildID).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
Count5 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).ThenByDesc(c.ChildID, Sql.NullsPosition.Last).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
Count6 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.ValuePreceding(3).ToValue(),
Count7 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).Range.Between.CurrentRow.And.UnboundedFollowing.ToValue(),
Count8 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1, Sql.NullsPosition.None).Rows.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
Count9 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1, Sql.NullsPosition.First).Range.UnboundedPreceding.ToValue(),
Count10 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1, Sql.NullsPosition.First).Range.CurrentRow.ToValue(),
Count11 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1, Sql.NullsPosition.First).Range.ValuePreceding(1).ToValue(),
Count12 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderByDesc(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
Count13 = Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderByDesc(p.Value1, Sql.NullsPosition.First).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
Count14 = Sql.Ext.Count().Over().ToValue(),
Combination = Sql.Ext.Rank().Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ThenBy(c.ChildID).ToValue() +
Sql.Sqrt(Sql.Ext.DenseRank().Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue()) +
Sql.Ext.Count(p.ParentID, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue() +
Sql.Ext.Count().Over().ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
}
}
[Test, IncludeDataContextSource(ProviderName.SqlServer2000, ProviderName.SqlServer2005, ProviderName.SqlServer2008, ProviderName.SqlServer2012, ProviderName.Oracle, ProviderName.OracleNative)]
public void TestAvg(string context)
{
using (var db = GetDataContext(context))
{
var qg =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
group c by p.ParentID
into g
select new
{
Average = g.Average(a => a.ChildID),
AverageNone = g.Average(a => a.ChildID, Sql.AggregateModifier.None),
AverageAll = g.Average(a => a.ChildID, Sql.AggregateModifier.All),
AverageDistinct = g.Average(a => a.ChildID, Sql.AggregateModifier.Distinct)
};
var res = qg.ToArray();
Assert.IsNotEmpty(res);
db.Child.Average(c => c.ParentID);
db.Child.Average(c => c.ParentID, Sql.AggregateModifier.All);
db.Child.Average(c => c.ParentID, Sql.AggregateModifier.Distinct);
}
}
[Test, IncludeDataContextSource(ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestAvgOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
AvgNoOrder = Sql.Ext.Average<double>(p.Value1, Sql.AggregateModifier.None).Over().ToValue(),
AvgRange = Sql.Ext.Average<double>(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).Range.Between.ValuePreceding(0).And.ValueFollowing(1).ToValue(),
AvgRangeNoModifier = Sql.Ext.Average<double>(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).Range.Between.ValuePreceding(0).And.ValueFollowing(1).ToValue(),
// Testing conversion. Average may fail with Overflow error
AvgD1 = Sql.Ext.Average<decimal>(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgD2 = Sql.Ext.Average<decimal>(p.Value1, Sql.AggregateModifier.Distinct).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgD3 = Sql.Ext.Average<decimal>(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgD4 = Sql.Ext.Average<decimal>(p.Value1, Sql.AggregateModifier.All).Over().ToValue(),
AvgDN1 = Sql.Ext.Average<decimal?>(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgDN2 = Sql.Ext.Average<decimal?>(p.Value1, Sql.AggregateModifier.Distinct).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgDN3 = Sql.Ext.Average<decimal?>(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgDN4 = Sql.Ext.Average<decimal?>(p.Value1, Sql.AggregateModifier.None).Over().ToValue(),
AvgIN1 = Sql.Ext.Average<int?>(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgIN2 = Sql.Ext.Average<int?>(p.Value1, Sql.AggregateModifier.Distinct).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgIN3 = Sql.Ext.Average<int?>(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgIN4 = Sql.Ext.Average<int?>(p.Value1, Sql.AggregateModifier.None).Over().ToValue(),
AvgI1 = Sql.Ext.Average<int>(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgI2 = Sql.Ext.Average<int>(p.Value1, Sql.AggregateModifier.Distinct).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgI3 = Sql.Ext.Average<int>(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgI4 = Sql.Ext.Average<int>(p.Value1, Sql.AggregateModifier.None).Over().ToValue(),
AvgL1 = Sql.Ext.Average<long>(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgL2 = Sql.Ext.Average<long>(p.Value1, Sql.AggregateModifier.Distinct).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgL3 = Sql.Ext.Average<long>(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgL4 = Sql.Ext.Average<long>(p.Value1, Sql.AggregateModifier.None).Over().ToValue(),
AvgLN1 = Sql.Ext.Average<long?>(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgLN2 = Sql.Ext.Average<long?>(p.Value1, Sql.AggregateModifier.Distinct).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgLN3 = Sql.Ext.Average<long?>(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgLN4 = Sql.Ext.Average<long?>(p.Value1, Sql.AggregateModifier.None).Over().ToValue(),
AvgF1 = Sql.Ext.Average<float>(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgF2 = Sql.Ext.Average<float>(p.Value1, Sql.AggregateModifier.Distinct).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgF3 = Sql.Ext.Average<float>(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgF4 = Sql.Ext.Average<float>(p.Value1, Sql.AggregateModifier.None).Over().ToValue(),
AvgFN1 = Sql.Ext.Average<float?>(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgFN2 = Sql.Ext.Average<float?>(p.Value1, Sql.AggregateModifier.Distinct).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgFN3 = Sql.Ext.Average<float?>(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgFN4 = Sql.Ext.Average<float?>(p.Value1, Sql.AggregateModifier.None).Over().ToValue(),
AvgDO1 = Sql.Ext.Average<double>(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgDO2 = Sql.Ext.Average<double>(p.Value1, Sql.AggregateModifier.Distinct).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgDO3 = Sql.Ext.Average<double>(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgDO4 = Sql.Ext.Average<double>(p.Value1, Sql.AggregateModifier.None).Over().ToValue(),
AvgDON1 = Sql.Ext.Average<double?>(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgDON2 = Sql.Ext.Average<double?>(p.Value1, Sql.AggregateModifier.Distinct).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgDON3 = Sql.Ext.Average<double?>(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgDON4 = Sql.Ext.Average<double?>(p.Value1, Sql.AggregateModifier.None).Over().ToValue(),
// modifications
AvgAll = Sql.Ext.Average<long?>(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
AvgNone = Sql.Ext.Average<long?>(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.ValueFollowing(1).ToValue(),
AvgDistinct1 = Sql.Ext.Average<long?>(p.Value1, Sql.AggregateModifier.Distinct).Over().ToValue(),
AvgDistinct2 = Sql.Ext.Average<long?>(p.Value1, Sql.AggregateModifier.Distinct).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
}
}
[Test, IncludeDataContextSource(ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestCorrOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
// type conversion tests
Corr1 = Sql.Ext.Corr<decimal>(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Corr2 = Sql.Ext.Corr<decimal?>(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Corr3 = Sql.Ext.Corr<float>(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Corr4 = Sql.Ext.Corr<int>(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
// variations
CorrSimple = Sql.Ext.Corr<decimal>(p.Value1, c.ChildID).Over().ToValue(),
CorrWithOrder = Sql.Ext.Corr<decimal>(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
CorrPartitionNoOrder = Sql.Ext.Corr<decimal>(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
CorrWithoutPartition = Sql.Ext.Corr<decimal>(p.Value1, c.ChildID).Over().OrderBy(p.Value1).ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
var qg =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
group c by p.ParentID
into g
select new
{
Corr = g.Corr(c => c.ParentID, c => c.ChildID),
};
var resg = qg.ToArray();
Assert.IsNotEmpty(resg);
db.Child.Corr(c => c.ParentID, c => c.ChildID);
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestCountOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Count1 = Sql.Ext.Count().Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Count2 = Sql.Ext.Count(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Count3 = Sql.Ext.Count(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Count4 = Sql.Ext.Count(p.Value1, Sql.AggregateModifier.Distinct).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Count5 = Sql.Ext.Count(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Count11 = Sql.Ext.Count().Over().ToValue(),
Count12 = Sql.Ext.Count(p.Value1).Over().ToValue(),
Count13 = Sql.Ext.Count(p.Value1, Sql.AggregateModifier.All).Over().ToValue(),
Count14 = Sql.Ext.Count(p.Value1, Sql.AggregateModifier.Distinct).Over().ToValue(),
Count15 = Sql.Ext.Count(p.Value1, Sql.AggregateModifier.None).Over().ToValue(),
Count21 = Sql.Ext.Count(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(c.ChildID).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
}
}
[Test, IncludeDataContextSource(ProviderName.SqlServer2000, ProviderName.SqlServer2005, ProviderName.SqlServer2008, ProviderName.SqlServer2012, ProviderName.Oracle, ProviderName.OracleManaged)]
public void TestCount(string context)
{
using (var db = GetDataContext(context))
{
var qg =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
group c by p.ParentID
into g
select new
{
Count = g.Count(),
CountMember = g.CountExt(a => a.ChildID),
CountNone = g.CountExt(a => a.ChildID, Sql.AggregateModifier.None),
CountAll = g.CountExt(a => a.ChildID, Sql.AggregateModifier.All),
CountDistinct = g.CountExt(a => a.ChildID, Sql.AggregateModifier.Distinct)
};
var res = qg.ToArray();
Assert.IsNotEmpty(res);
db.Child.Count();
db.Child.CountExt(c => c.ParentID);
db.Child.CountExt(c => c.ParentID, Sql.AggregateModifier.All);
db.Child.CountExt(c => c.ParentID, Sql.AggregateModifier.Distinct);
}
}
[Test, IncludeDataContextSource(ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestCovarPopOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
CovarPop1 = Sql.Ext.CovarPop(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
CovarPop2 = Sql.Ext.CovarPop(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
CovarPop3 = Sql.Ext.CovarPop(p.Value1, c.ChildID).Over().ToValue(),
CovarPop4 = Sql.Ext.CovarPop(p.Value1, c.ChildID).Over().PartitionBy(c.ChildID).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
var qg =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
group c by p.ParentID
into g
select new
{
CovarPop = g.CovarPop(c => c.ParentID, c => c.ChildID),
};
var resg = qg.ToArray();
Assert.IsNotEmpty(resg);
db.Child.CovarPop(c => c.ParentID, c => c.ChildID);
}
}
[Test, IncludeDataContextSource(ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestCovarSampOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
CovarSamp1 = Sql.Ext.CovarSamp(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
CovarSamp2 = Sql.Ext.CovarSamp(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
CovarSamp3 = Sql.Ext.CovarSamp(p.Value1, c.ChildID).Over().ToValue(),
CovarSamp4 = Sql.Ext.CovarSamp(p.Value1, c.ChildID).Over().PartitionBy(c.ChildID).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
var qg =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
group c by p.ParentID
into g
select new
{
CovarSamp = g.CovarSamp(c => c.ParentID, c => c.ChildID),
};
var resg = qg.ToArray();
Assert.IsNotEmpty(resg);
db.Child.CovarSamp(c => c.ParentID, c => c.ChildID);
}
}
[Test, IncludeDataContextSource(ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestCumeDistOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
CumeDist1 = Sql.Ext.CumeDist<decimal>().Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
CumeDist2 = Sql.Ext.CumeDist<decimal>().Over().OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
};
Assert.IsNotEmpty(q.ToArray());
var q2 =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
CumeDist1 = Sql.Ext.CumeDist<decimal>(1, 2).WithinGroup.OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
CumeDist2 = Sql.Ext.CumeDist<decimal>(2, 3).WithinGroup.OrderByDesc(p.Value1).ThenBy(c.ChildID).ToValue(),
};
Assert.IsNotEmpty(q2.ToArray());
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestDenseRankOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
DenseRank1 = Sql.Ext.DenseRank().Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
DenseRank2 = Sql.Ext.DenseRank().Over().OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
};
Assert.IsNotEmpty(q.ToArray());
var q2 =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
DenseRank1 = Sql.Ext.DenseRank(1, 2).WithinGroup.OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
};
Assert.IsNotEmpty(q2.ToArray());
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestFirstValueOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
FirstValue1 = Sql.Ext.FirstValue(p.Value1, Sql.Nulls.Ignore).Over().ToValue(),
FirstValue2 = Sql.Ext.FirstValue(p.Value1, Sql.Nulls.None).Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
FirstValue3 = Sql.Ext.FirstValue(p.Value1, Sql.Nulls.Respect).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
FirstValue4 = Sql.Ext.FirstValue(p.Value1, Sql.Nulls.Respect).Over().OrderBy(p.Value1).ToValue(),
FirstValue5 = Sql.Ext.FirstValue(p.Value1, Sql.Nulls.Respect).Over().OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
};
Assert.IsNotEmpty(q.ToArray());
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestLastValueOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
LastValue1 = Sql.Ext.LastValue(p.Value1, Sql.Nulls.Ignore).Over().ToValue(),
LastValue2 = Sql.Ext.LastValue(p.Value1, Sql.Nulls.None).Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
LastValue3 = Sql.Ext.LastValue(p.Value1, Sql.Nulls.Respect).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
LastValue4 = Sql.Ext.LastValue(p.Value1, Sql.Nulls.Respect).Over().OrderBy(p.Value1).ToValue(),
LastValue5 = Sql.Ext.LastValue(p.Value1, Sql.Nulls.Respect).Over().OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
};
Assert.IsNotEmpty(q.ToArray());
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestLagOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Lag1 = Sql.Ext.Lag(p.Value1, Sql.Nulls.Respect, 1, 0).Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
Lag2 = Sql.Ext.Lag(p.Value1, Sql.Nulls.Ignore, 1, 0).Over().OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
Lag3 = Sql.Ext.Lag(p.Value1, Sql.Nulls.None, 1, 0).Over().OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
Lag4 = Sql.Ext.Lag(p.Value1, Sql.Nulls.Ignore).Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
};
Assert.IsNotEmpty(q.ToArray());
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestLeadOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Lead1 = Sql.Ext.Lead(p.Value1, Sql.Nulls.Ignore).Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
Lead2 = Sql.Ext.Lead(p.Value1, Sql.Nulls.Respect).Over().OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
Lead3 = Sql.Ext.Lead(p.Value1, Sql.Nulls.None).Over().OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
Lead4 = Sql.Ext.Lead(p.Value1, Sql.Nulls.Respect, 1, null).Over().OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
Lead5 = Sql.Ext.Lead(p.Value1, Sql.Nulls.Respect, 1, c.ChildID).Over().OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
};
Assert.IsNotEmpty(q.ToArray());
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestListAggOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
ListAgg1 = Sql.Ext.ListAgg(c.ChildID).WithinGroup.OrderBy(p.Value1).ThenBy(p.ParentTest.Value1).ThenByDesc(c.ParentID).ToValue(),
ListAgg2 = Sql.Ext.ListAgg(c.ChildID).WithinGroup.OrderBy(p.Value1, Sql.NullsPosition.Last).ThenByDesc(c.ParentID, Sql.NullsPosition.First).ToValue(),
ListAgg3 = Sql.Ext.ListAgg(c.ChildID).WithinGroup.OrderBy(p.Value1, Sql.NullsPosition.First).ThenBy(c.ParentID).ThenBy(c.ParentID, Sql.NullsPosition.First).ToValue(),
ListAgg4 = Sql.Ext.ListAgg(c.ChildID).WithinGroup.OrderByDesc(p.Value1).ThenBy(p.ParentTest.Value1).ThenByDesc(c.ParentID).ToValue(),
ListAgg5 = Sql.Ext.ListAgg(c.ChildID).WithinGroup.OrderByDesc(p.Value1, Sql.NullsPosition.None).ThenBy(p.ParentTest.Value1).ThenByDesc(c.ParentID).ToValue(),
ListAgg6 = Sql.Ext.ListAgg(c.ChildID, "..").WithinGroup.OrderByDesc(p.Value1, Sql.NullsPosition.None).ThenBy(p.ParentTest.Value1).ThenByDesc(c.ParentID).ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestMaxOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Max1 = Sql.Ext.Max(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Max2 = Sql.Ext.Max(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Max3 = Sql.Ext.Max(p.Value1, Sql.AggregateModifier.Distinct).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Max4 = Sql.Ext.Max(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Max5 = Sql.Ext.Max(p.Value1).Over().ToValue(),
Max6 = Sql.Ext.Max(p.Value1, Sql.AggregateModifier.All).Over().ToValue(),
Max7 = Sql.Ext.Max(p.Value1, Sql.AggregateModifier.Distinct).Over().ToValue(),
Max8 = Sql.Ext.Max(p.Value1, Sql.AggregateModifier.None).Over().ToValue(),
Max9 = Sql.Ext.Max(p.Value1, Sql.AggregateModifier.None).Over().OrderBy(p.Value1).ToValue(),
Max10 = Sql.Ext.Max(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(c.ChildID).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
var q2 =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Max11 = Sql.Ext.Max(p.Value1, Sql.AggregateModifier.All).ToValue(),
};
var res2 = q2.ToArray();
Assert.IsNotEmpty(res2);
}
}
[Test, IncludeDataContextSource(ProviderName.SqlServer2000, ProviderName.SqlServer2005, ProviderName.SqlServer2008, ProviderName.SqlServer2012, ProviderName.Oracle)]
public void TestMax(string context)
{
using (var db = GetDataContext(context))
{
var qg =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
group c by p.ParentID
into g
select new
{
Max = g.Max(a => a.ChildID),
MaxNone = g.Max(a => a.ChildID, Sql.AggregateModifier.None),
MaxAll = g.Max(a => a.ChildID, Sql.AggregateModifier.All),
MaxDistinct = g.Max(a => a.ChildID, Sql.AggregateModifier.Distinct)
};
var res = qg.ToArray();
Assert.IsNotEmpty(res);
db.Child.Max(c => c.ParentID);
db.Child.Max(c => c.ParentID, Sql.AggregateModifier.All);
db.Child.Max(c => c.ParentID, Sql.AggregateModifier.Distinct);
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestMedianOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Median1 = Sql.Ext.Median(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Median2 = Sql.Ext.Median(p.Value1).Over().ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
var qg =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
group c by p.ParentID
into g
select new
{
Median = g.Median(c => c.ParentID),
};
var resg = qg.ToArray();
Assert.IsNotEmpty(resg);
db.Child.Median(c => c.ParentID);
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestMinOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Min1 = Sql.Ext.Min(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Min2 = Sql.Ext.Min(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Min3 = Sql.Ext.Min(p.Value1, Sql.AggregateModifier.Distinct).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Min4 = Sql.Ext.Min(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Min5 = Sql.Ext.Min(p.Value1).Over().ToValue(),
Min6 = Sql.Ext.Min(p.Value1, Sql.AggregateModifier.All).Over().ToValue(),
Min7 = Sql.Ext.Min(p.Value1, Sql.AggregateModifier.Distinct).Over().ToValue(),
Min8 = Sql.Ext.Min(p.Value1, Sql.AggregateModifier.None).Over().ToValue(),
Min9 = Sql.Ext.Min(p.Value1, Sql.AggregateModifier.None).Over().OrderBy(p.Value1).ToValue(),
Min10 = Sql.Ext.Min(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(c.ChildID).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
}
}
[Test, IncludeDataContextSource(ProviderName.SqlServer2000, ProviderName.SqlServer2005, ProviderName.SqlServer2008, ProviderName.SqlServer2012, ProviderName.Oracle, ProviderName.OracleManaged)]
public void TestMin(string context)
{
using (var db = GetDataContext(context))
{
var qg =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
group c by p.ParentID
into g
select new
{
Min = g.Min(a => a.ChildID),
MinNone = g.Min(a => a.ChildID, Sql.AggregateModifier.None),
MinAll = g.Min(a => a.ChildID, Sql.AggregateModifier.All),
MinDistinct = g.Min(a => a.ChildID, Sql.AggregateModifier.Distinct)
};
var res = qg.ToArray();
Assert.IsNotEmpty(res);
db.Child.Min(c => c.ParentID);
db.Child.Min(c => c.ParentID, Sql.AggregateModifier.All);
db.Child.Min(c => c.ParentID, Sql.AggregateModifier.Distinct);
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestNthValueOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
NthValue1 = Sql.Ext.NthValue(c.ChildID, 1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
NthValue2 = Sql.Ext.NthValue(c.ChildID, p.ParentID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
NthValue21 = Sql.Ext.NthValue(c.ChildID, 1, Sql.From.First, Sql.Nulls.Respect).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
NthValue22 = Sql.Ext.NthValue(c.ChildID, p.ParentID, Sql.From.Last, Sql.Nulls.Ignore).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
NthValue23 = Sql.Ext.NthValue(c.ChildID, p.ParentID, Sql.From.None, Sql.Nulls.None).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
NthValue5 = Sql.Ext.NthValue(c.ChildID, 1).Over().ToValue(),
NthValue9 = Sql.Ext.NthValue(c.ChildID, 1).Over().OrderBy(p.Value1).ToValue(),
NthValue10 = Sql.Ext.NthValue(c.ChildID, 1).Over().PartitionBy(c.ChildID).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestNTileOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
NTile1 = Sql.Ext.NTile(p.Value1.Value).Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
NTile2 = Sql.Ext.NTile(1).Over().OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
};
Assert.IsNotEmpty(q.ToArray());
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestPercentileContOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
PercentileCont1 = Sql.Ext.PercentileCont<double>(0.5).WithinGroup.OrderBy(p.Value1).Over().PartitionBy(p.Value1, p.ParentID).ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
var q2 =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
PercentileCont1 = Sql.Ext.PercentileCont<double>(0.5).WithinGroup.OrderByDesc(p.Value1).ToValue(),
PercentileCont2 = Sql.Ext.PercentileCont<double>(1).WithinGroup.OrderByDesc(p.Value1).ToValue(),
};
var res2 = q2.ToArray();
Assert.IsNotEmpty(res2);
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestPercentileDiscOracle(string Discext)
{
using (var db = GetDataContext(Discext))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
PercentileDisc1 = Sql.Ext.PercentileDisc<double>(0.5).WithinGroup.OrderBy(p.Value1).Over().PartitionBy(p.Value1, p.ParentID).ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
var q2 =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
PercentileDisc1 = Sql.Ext.PercentileDisc<double>(0.5).WithinGroup.OrderByDesc(p.Value1).ToValue(),
PercentileDisc2 = Sql.Ext.PercentileDisc<double>(1).WithinGroup.OrderByDesc(p.Value1).ToValue(),
};
var res2 = q2.ToArray();
Assert.IsNotEmpty(res2);
}
}
[Test, IncludeDataContextSource(false, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestPercentRankOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
PercentRank1 = Sql.Ext.PercentRank<double>().Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
PercentRank2 = Sql.Ext.PercentRank<double>().Over().OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
};
Assert.IsNotEmpty(q.ToArray());
var q2 =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
PercentRank3 = Sql.Ext.PercentRank<double>(2, 3).WithinGroup.OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
};
Assert.IsNotEmpty(q2.ToArray());
}
}
[Test, IncludeDataContextSource(ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestPercentRatioToReportOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
RatioToReport1 = Sql.Ext.RatioToReport<double>(1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
RatioToReport2 = Sql.Ext.RatioToReport<double>(c.ChildID).Over().ToValue(),
};
Assert.IsNotEmpty(q.ToArray());
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestRowNumberOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
RowNumber1 = Sql.Ext.RowNumber().Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
RowNumber2 = Sql.Ext.RowNumber().Over().OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
};
Assert.IsNotEmpty(q.ToArray());
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestRankOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Rank1 = Sql.Ext.Rank().Over().PartitionBy(p.Value1, c.ChildID).OrderBy(p.Value1).ToValue(),
Rank2 = Sql.Ext.Rank().Over().OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
};
Assert.IsNotEmpty(q.ToArray());
var q2 =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Rank1 = Sql.Ext.Rank(1000).WithinGroup.OrderBy(p.Value1).ToValue(),
Rank2 = Sql.Ext.Rank(0, 0.1).WithinGroup.OrderBy(p.Value1).ThenByDesc(c.ChildID).ToValue(),
};
Assert.IsNotEmpty(q2.ToArray());
}
}
[Test, IncludeDataContextSource(ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestRegrOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
// type conversion tests
AvgX = Sql.Ext.RegrAvgX<decimal>(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
AvgY = Sql.Ext.RegrAvgY<decimal>(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Count = Sql.Ext.RegrCount(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Intercept = Sql.Ext.RegrIntercept<decimal>(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
R2 = Sql.Ext.RegrR2<decimal>(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
SXX = Sql.Ext.RegrSXX<decimal>(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
SXY = Sql.Ext.RegrSXY<decimal>(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
XYY = Sql.Ext.RegrSYY<decimal>(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Slope = Sql.Ext.RegrSlope<decimal>(p.Value1, c.ChildID).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
}
}
[Test, IncludeDataContextSource(ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestStdDevOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
StdDev1 = Sql.Ext.StdDev<double>(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
StdDev2 = Sql.Ext.StdDev<double>(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
StdDev3 = Sql.Ext.StdDev<double>(p.Value1, Sql.AggregateModifier.Distinct).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
StdDev4 = Sql.Ext.StdDev<double>(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
StdDev11 = Sql.Ext.StdDev<double>(p.Value1).Over().ToValue(),
StdDev12 = Sql.Ext.StdDev<double>(p.Value1, Sql.AggregateModifier.All).Over().ToValue(),
StdDev13 = Sql.Ext.StdDev<double>(p.Value1, Sql.AggregateModifier.Distinct).Over().ToValue(),
StdDev14 = Sql.Ext.StdDev<double>(p.Value1, Sql.AggregateModifier.None).Over().ToValue(),
StdDev21 = Sql.Ext.StdDev<double>(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(c.ChildID).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
}
}
[Test, IncludeDataContextSource(ProviderName.SqlServer2000, ProviderName.SqlServer2005, ProviderName.SqlServer2008, ProviderName.SqlServer2012, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestStdDev(string context)
{
using (var db = GetDataContext(context))
{
var qg =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
group c by p.ParentID
into g
select new
{
StdDev = g.StdDev(a => a.ChildID),
StdDevNone = g.StdDev(a => a.ChildID, Sql.AggregateModifier.None),
StdDevAll = g.StdDev(a => a.ChildID, Sql.AggregateModifier.All),
StdDevDistinct = g.StdDev(a => a.ChildID, Sql.AggregateModifier.Distinct)
};
var res = qg.ToArray();
Assert.IsNotEmpty(res);
db.Child.StdDev(c => c.ParentID);
db.Child.StdDev(c => c.ParentID, Sql.AggregateModifier.All);
db.Child.StdDev(c => c.ParentID, Sql.AggregateModifier.Distinct);
}
}
[Test, IncludeDataContextSource(ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestStdDevPopOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
StdDevPop1 = Sql.Ext.StdDevPop<double>(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
StdDevPop2 = Sql.Ext.StdDevPop<double>(p.Value1).Over().OrderBy(p.Value1).ToValue(),
StdDevPop3 = Sql.Ext.StdDevPop<double>(p.Value1).Over().ToValue(),
StdDevPop4 = Sql.Ext.StdDevPop<double>(p.Value1).Over().PartitionBy(c.ChildID).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
var qg =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
group c by p.ParentID
into g
select new
{
StdDevPop = g.StdDevPop(c => c.ParentID),
};
var resg = qg.ToArray();
Assert.IsNotEmpty(resg);
db.Child.StdDevPop(c => c.ParentID);
}
}
[Test, IncludeDataContextSource(ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestStdDevSampOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
StdDevSamp1 = Sql.Ext.StdDevSamp<double>(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
StdDevSamp2 = Sql.Ext.StdDevSamp<double>(p.Value1).Over().OrderBy(p.Value1).ToValue(),
StdDevSamp3 = Sql.Ext.StdDevSamp<double>(p.Value1).Over().ToValue(),
StdDevSamp4 = Sql.Ext.StdDevSamp<double>(p.Value1).Over().PartitionBy(c.ChildID).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
var qg =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
group c by p.ParentID
into g
select new
{
StdDevSamp = g.StdDevSamp(c => c.ParentID),
};
var resg = qg.ToArray();
Assert.IsNotEmpty(resg);
db.Child.StdDevSamp(c => c.ParentID);
}
}
[Test, IncludeDataContextSource(true, ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestSumOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Sum1 = Sql.Ext.Sum(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Sum2 = Sql.Ext.Sum(p.Value1, Sql.AggregateModifier.All).Over().OrderBy(p.Value1).ToValue(),
Sum3 = Sql.Ext.Sum(p.Value1, Sql.AggregateModifier.Distinct).Over().ToValue(),
Sum4 = Sql.Ext.Sum(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(c.ChildID).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
var q2 =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Sum1 = Sql.Ext.Sum(p.Value1).ToValue(),
};
var res2 = q2.ToArray();
Assert.IsNotEmpty(res2);
}
}
[Test, IncludeDataContextSource(ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestVarPopOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
VarPop1 = Sql.Ext.VarPop<double>(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
VarPop2 = Sql.Ext.VarPop<double>(p.Value1).Over().OrderBy(p.Value1).ToValue(),
VarPop3 = Sql.Ext.VarPop<double>(p.Value1).Over().ToValue(),
VarPop4 = Sql.Ext.VarPop<double>(p.Value1).Over().PartitionBy(c.ChildID).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
var qg =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
group c by p.ParentID
into g
select new
{
VarPop = g.VarPop(c => c.ParentID),
};
var resg = qg.ToArray();
Assert.IsNotEmpty(resg);
db.Child.VarPop(c => c.ParentID);
}
}
[Test, IncludeDataContextSource(ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestVarSampOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
VarSamp1 = Sql.Ext.VarSamp<double>(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
VarSamp2 = Sql.Ext.VarSamp<double>(p.Value1).Over().OrderBy(p.Value1).ToValue(),
VarSamp3 = Sql.Ext.VarSamp<double>(p.Value1).Over().ToValue(),
VarSamp4 = Sql.Ext.VarSamp<double>(p.Value1).Over().PartitionBy(c.ChildID).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
var qg =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
group c by p.ParentID
into g
select new
{
VarSamp = g.VarSamp(c => c.ParentID),
};
var resg = qg.ToArray();
Assert.IsNotEmpty(resg);
db.Child.VarSamp(c => c.ParentID);
}
}
[Test, IncludeDataContextSource(ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestVarianceOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Variance1 = Sql.Ext.Variance<double>(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Variance2 = Sql.Ext.Variance<double>(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Variance3 = Sql.Ext.Variance<double>(p.Value1, Sql.AggregateModifier.Distinct).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Variance4 = Sql.Ext.Variance<double>(p.Value1, Sql.AggregateModifier.None).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Variance11 = Sql.Ext.Variance<double>(p.Value1).Over().ToValue(),
Variance12 = Sql.Ext.Variance<double>(p.Value1, Sql.AggregateModifier.All).Over().ToValue(),
Variance13 = Sql.Ext.Variance<double>(p.Value1, Sql.AggregateModifier.Distinct).Over().ToValue(),
Variance14 = Sql.Ext.Variance<double>(p.Value1, Sql.AggregateModifier.None).Over().ToValue(),
Variance21 = Sql.Ext.Variance<double>(p.Value1, Sql.AggregateModifier.All).Over().PartitionBy(c.ChildID).OrderBy(p.Value1).Range.Between.UnboundedPreceding.And.CurrentRow.ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
var qg =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
group c by p.ParentID
into g
select new
{
Variance = g.Variance(a => a.ChildID),
VarianceNone = g.Variance(a => a.ChildID, Sql.AggregateModifier.None),
VarianceAll = g.Variance(a => a.ChildID, Sql.AggregateModifier.All),
VarianceDistinct = g.Variance(a => a.ChildID, Sql.AggregateModifier.Distinct)
};
var resg = qg.ToArray();
Assert.IsNotEmpty(resg);
db.Child.Variance(c => c.ParentID);
db.Child.Variance(c => c.ParentID, Sql.AggregateModifier.All);
db.Child.Variance(c => c.ParentID, Sql.AggregateModifier.Distinct);
}
}
[Test, IncludeDataContextSource(ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestKeepFirstOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Min = Sql.Ext.Min(p.Value1).KeepFirst().OrderBy(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Max = Sql.Ext.Max(p.Value1).KeepFirst().OrderBy(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Sum = Sql.Ext.Sum(p.Value1).KeepFirst().OrderBy(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Variance = Sql.Ext.Variance<double>(p.Value1).KeepFirst().OrderBy(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
}
}
[Test, IncludeDataContextSource(ProviderName.Oracle, ProviderName.OracleManaged, ProviderName.OracleNative)]
public void TestKeepLastOracle(string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID
select new
{
Min = Sql.Ext.Min(p.Value1).KeepLast().OrderBy(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Max = Sql.Ext.Max(p.Value1).KeepLast().OrderBy(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Sum = Sql.Ext.Sum(p.Value1).KeepLast().OrderBy(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
Variance = Sql.Ext.Variance<double>(p.Value1).KeepLast().OrderBy(p.Value1).Over().PartitionBy(p.Value1, c.ChildID).ToValue(),
};
var res = q.ToArray();
Assert.IsNotEmpty(res);
}
}
}
} | mit |
marom17/Teaching-HEIGVD-RES-2015-Labo-05 | frontend/mysite/index.php | 314 | <!DOCTYPE html>
<html>
<head>
<script src="./bouton.js"></script>
</head>
<body>
<h2>Quelle heure est-il?</h2>
<div id="div1"></div>
<p>
<button onclick="onClick();" id="bt1">Avoir l'heure</button>
</p>
<br/>
<p>Ce service vous est fourni par <b>
<?php
echo $_SERVER['SERVER_ADDR'];
?>
</b></p>
</body>
</html>
| mit |
peter17/Propel2 | tests/Propel/Tests/Runtime/ActiveQuery/ModelCriteriaTest.php | 146560 | <?php
/**
* MIT License. This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Propel\Tests\Runtime\ActiveQuery;
use PDO;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\Exception\UnknownColumnException;
use Propel\Runtime\ActiveQuery\Exception\UnknownRelationException;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Propel\Runtime\Collection\Collection;
use Propel\Runtime\Exception\ClassNotFoundException;
use Propel\Runtime\Exception\EntityNotFoundException;
use Propel\Runtime\Exception\InvalidArgumentException;
use Propel\Runtime\Exception\PropelException;
use Propel\Runtime\Exception\UnexpectedValueException;
use Propel\Runtime\Formatter\AbstractFormatter;
use Propel\Runtime\Formatter\ArrayFormatter;
use Propel\Runtime\Formatter\StatementFormatter;
use Propel\Runtime\Propel;
use Propel\Runtime\Util\PropelModelPager;
use Propel\Tests\Bookstore\AuthorQuery;
use Propel\Tests\Bookstore\Book;
use Propel\Tests\Bookstore\Book2;
use Propel\Tests\Bookstore\Book2Query;
use Propel\Tests\Bookstore\BookQuery;
use Propel\Tests\Bookstore\BookstoreEmployeeQuery;
use Propel\Tests\Bookstore\Map\AuthorTableMap;
use Propel\Tests\Bookstore\Map\BookTableMap;
use Propel\Tests\Bookstore\Map\PublisherTableMap;
use Propel\Tests\Bookstore\Map\ReviewTableMap;
use Propel\Tests\Helpers\Bookstore\BookstoreDataPopulator;
use Propel\Tests\Helpers\Bookstore\BookstoreTestBase;
/**
* Test class for ModelCriteria.
*
* @author Francois Zaninotto
*
* @group database
*/
class ModelCriteriaTest extends BookstoreTestBase
{
/**
* @return void
*/
protected function assertCriteriaTranslation($criteria, $expectedSql, $expectedParams, $message = '')
{
$params = [];
$result = $criteria->createSelectSql($params);
$this->assertEquals($expectedSql, $result, $message);
$this->assertEquals($expectedParams, $params, $message);
}
/**
* @return void
*/
public function testGetModelName()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$this->assertEquals('Propel\Tests\Bookstore\Book', $c->getModelName(), 'getModelName() returns the name of the class associated to the model class');
$c = new ModelCriteria('bookstore', '\Propel\Tests\Bookstore\Book');
$this->assertEquals('Propel\Tests\Bookstore\Book', $c->getModelName(), 'getModelName() returns the name of the class associated to the model class');
}
/**
* @return void
*/
public function testGetFullyQualifiedModelName()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$this->assertEquals('\Propel\Tests\Bookstore\Book', $c->getFullyQualifiedModelName(), 'getFullyQualifiedModelName() returns the name of the class associated to the model class');
$c = new ModelCriteria('bookstore', '\Propel\Tests\Bookstore\Book');
$this->assertEquals('\Propel\Tests\Bookstore\Book', $c->getFullyQualifiedModelName(), 'getFullyQualifiedModelName() returns the name of the class associated to the model class');
}
/**
* @return void
*/
public function testFormatter()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$this->assertTrue($c->getFormatter() instanceof AbstractFormatter, 'getFormatter() returns a PropelFormatter instance');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setFormatter(ModelCriteria::FORMAT_STATEMENT);
$this->assertTrue($c->getFormatter() instanceof StatementFormatter, 'setFormatter() accepts the name of a AbstractFormatter class');
try {
$c->setFormatter('Propel\Tests\Bookstore\Book');
$this->fail('setFormatter() throws an exception when passed the name of a class not extending AbstractFormatter');
} catch (InvalidArgumentException $e) {
$this->assertTrue(true, 'setFormatter() throws an exception when passed the name of a class not extending AbstractFormatter');
}
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$formatter = new StatementFormatter();
$c->setFormatter($formatter);
$this->assertTrue($c->getFormatter() instanceof StatementFormatter, 'setFormatter() accepts a AbstractFormatter instance');
try {
$formatter = new Book();
$c->setFormatter($formatter);
$this->fail('setFormatter() throws an exception when passed an object not extending AbstractFormatter');
} catch (InvalidArgumentException $e) {
$this->assertTrue(true, 'setFormatter() throws an exception when passed an object not extending AbstractFormatter');
}
}
public static function conditionsForTestReplaceNames()
{
return [
['Propel\Tests\Bookstore\Book.Title = ?', 'Title', 'book.title = ?'], // basic case
['Propel\Tests\Bookstore\Book.Title=?', 'Title', 'book.title=?'], // without spaces
['Propel\Tests\Bookstore\Book.Id<= ?', 'Id', 'book.id<= ?'], // with non-equal comparator
['Propel\Tests\Bookstore\Book.AuthorId LIKE ?', 'AuthorId', 'book.author_id LIKE ?'], // with SQL keyword separator
['(Propel\Tests\Bookstore\Book.AuthorId) LIKE ?', 'AuthorId', '(book.author_id) LIKE ?'], // with parenthesis
['(Propel\Tests\Bookstore\Book.Id*1.5)=1', 'Id', '(book.id*1.5)=1'], // ignore numbers
// dealing with quotes
["Propel\Tests\Bookstore\Book.Id + ' ' + Propel\Tests\Bookstore\Book.AuthorId", null, "book.id + ' ' + book.author_id"],
["'Propel\Tests\Bookstore\Book.Id' + Propel\Tests\Bookstore\Book.AuthorId", null, "'Propel\Tests\Bookstore\Book.Id' + book.author_id"],
["Propel\Tests\Bookstore\Book.Id + 'Propel\Tests\Bookstore\Book.AuthorId'", null, "book.id + 'Propel\Tests\Bookstore\Book.AuthorId'"],
['1=1', null, '1=1'], // with no name
['', null, ''], // with empty string
//without NS
['Book.Title = ?', 'Title', 'book.title = ?'], // basic case
['Book.Title=?', 'Title', 'book.title=?'], // without spaces
['Book.Id<= ?', 'Id', 'book.id<= ?'], // with non-equal comparator
['Book.AuthorId LIKE ?', 'AuthorId', 'book.author_id LIKE ?'], // with SQL keyword separator
['(Book.AuthorId) LIKE ?', 'AuthorId', '(book.author_id) LIKE ?'], // with parenthesis
['(Book.Id*1.5)=1', 'Id', '(book.id*1.5)=1'], // ignore numbers
// dealing with quotes
["Book.Id + ' ' + Book.AuthorId", null, "book.id + ' ' + book.author_id"],
["'Book.Id' + Book.AuthorId", null, "'Book.Id' + book.author_id"],
["Book.Id + 'Book.AuthorId'", null, "book.id + 'Book.AuthorId'"],
];
}
/**
* @dataProvider conditionsForTestReplaceNames
*
* @return void
*/
public function testReplaceNames($origClause, $columnPhpName, $modifiedClause)
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$this->doTestReplaceNames($c, BookTableMap::getTableMap(), $origClause, $columnPhpName, $modifiedClause);
}
/**
* @return void
*/
public function doTestReplaceNames(Criteria $c, $tableMap, $origClause, $columnPhpName, $modifiedClause)
{
$c->replaceNames($origClause);
$columns = $c->replacedColumns;
if ($columnPhpName) {
$this->assertEquals([$tableMap->getColumnByPhpName($columnPhpName)], $columns);
}
$this->assertEquals($modifiedClause, $origClause);
}
public static function conditionsForTestReplaceMultipleNames()
{
return [
['(Propel\Tests\Bookstore\Book.Id+Book.Id)=1', ['Id', 'Id'], '(book.id+book.id)=1'], // match multiple names
['CONCAT(Propel\Tests\Bookstore\Book.Title,"Book.Id")= ?', ['Title', 'Id'], 'CONCAT(book.title,"Book.Id")= ?'], // ignore names in strings
['CONCAT(Propel\Tests\Bookstore\Book.Title," Book.Id ")= ?', ['Title', 'Id'], 'CONCAT(book.title," Book.Id ")= ?'], // ignore names in strings
['MATCH (Propel\Tests\Bookstore\Book.Title,Book.isbn) AGAINST (?)', ['Title', 'ISBN'], 'MATCH (book.title,book.isbn) AGAINST (?)'],
];
}
/**
* @dataProvider conditionsForTestReplaceMultipleNames
*
* @return void
*/
public function testReplaceMultipleNames($origClause, $expectedColumns, $modifiedClause)
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->replaceNames($origClause);
$foundColumns = $c->replacedColumns;
foreach ($foundColumns as $column) {
$expectedColumn = BookTableMap::getTableMap()->getColumnByPhpName(array_shift($expectedColumns));
$this->assertEquals($expectedColumn, $column);
}
$this->assertEquals($modifiedClause, $origClause);
}
/**
* @return void
*/
public function testTableAlias()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setModelAlias('b');
$c->where('b.Title = ?', 'foo');
$sql = $this->getSql('SELECT FROM book WHERE book.title = :p1');
$params = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'setModelAlias() allows the definition of the alias after construction');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('b.Title = ?', 'foo');
$sql = $this->getSql('SELECT FROM book WHERE book.title = :p1');
$params = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'A ModelCriteria accepts a model name with an alias');
}
/**
* @return void
*/
public function testTrueTableAlias()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setModelAlias('b', true);
$c->where('b.Title = ?', 'foo');
$c->join('b.Author a');
$c->where('a.FirstName = ?', 'john');
$sql = $this->getSql('SELECT FROM book b INNER JOIN author a ON (b.author_id=a.id) WHERE b.title = :p1 AND a.first_name = :p2');
$params = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
['table' => 'author', 'column' => 'first_name', 'value' => 'john'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'setModelAlias() allows the definition of a true SQL alias after construction');
}
/**
* @return void
*/
public function testCondition()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->condition('cond1', 'Propel\Tests\Bookstore\Book.Title <> ?', 'foo');
$c->condition('cond2', 'Propel\Tests\Bookstore\Book.Title like ?', '%bar%');
$c->combine(['cond1', 'cond2'], 'or');
$sql = $this->getSql('SELECT FROM book WHERE (book.title <> :p1 OR book.title like :p2)');
$params = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
['table' => 'book', 'column' => 'title', 'value' => '%bar%'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'condition() can store condition for later combination');
}
/**
* @return void
*/
public function testConditionCustomOperator()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->withColumn('SUBSTRING(Book.Title, 1, 4)', 'title_start');
$c->condition('cond1', 'Book.Title <> ?', 'foo');
$c->condition('cond2', 'title_start like ?', '%bar%', PDO::PARAM_STR);
$c->combine(['cond1', 'cond2'], 'or');
$sql = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id, SUBSTRING(book.title, 1, 4) AS title_start FROM book WHERE (book.title <> :p1 OR title_start like :p2)');
$params = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
['table' => null, 'type' => PDO::PARAM_STR, 'value' => '%bar%'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'condition() accepts RAW sql parameters');
}
public static function conditionsForTestWhere()
{
return [
['Propel\Tests\Bookstore\Book.Title = ?', 'foo', 'book.title = :p1', [['table' => 'book', 'column' => 'title', 'value' => 'foo']]],
['Propel\Tests\Bookstore\Book.AuthorId = ?', 12, 'book.author_id = :p1', [['table' => 'book', 'column' => 'author_id', 'value' => 12]]],
['Propel\Tests\Bookstore\Book.AuthorId IS NULL', null, 'book.author_id IS NULL', []],
['Propel\Tests\Bookstore\Book.Id BETWEEN ? AND ?', [3, 4], 'book.id BETWEEN :p1 AND :p2', [['table' => 'book', 'column' => 'id', 'value' => 3], ['table' => 'book', 'column' => 'id', 'value' => 4]]],
['Propel\Tests\Bookstore\Book.Id betWEen ? and ?', [3, 4], 'book.id betWEen :p1 and :p2', [['table' => 'book', 'column' => 'id', 'value' => 3], ['table' => 'book', 'column' => 'id', 'value' => 4]]],
['Propel\Tests\Bookstore\Book.Id IN ?', [1, 2, 3], 'book.id IN (:p1,:p2,:p3)', [['table' => 'book', 'column' => 'id', 'value' => 1], ['table' => 'book', 'column' => 'id', 'value' => 2], ['table' => 'book', 'column' => 'id', 'value' => 3]]],
['Propel\Tests\Bookstore\Book.Id in ?', [1, 2, 3], 'book.id in (:p1,:p2,:p3)', [['table' => 'book', 'column' => 'id', 'value' => 1], ['table' => 'book', 'column' => 'id', 'value' => 2], ['table' => 'book', 'column' => 'id', 'value' => 3]]],
['Propel\Tests\Bookstore\Book.Id IN ?', [], '1<>1', []],
['Propel\Tests\Bookstore\Book.Id not in ?', [], '1=1', []],
['UPPER(Propel\Tests\Bookstore\Book.Title) = ?', 'foo', 'UPPER(book.title) = :p1', [['table' => 'book', 'column' => 'title', 'value' => 'foo']]],
['MATCH (Propel\Tests\Bookstore\Book.Title,Propel\Tests\Bookstore\Book.isbn) AGAINST (?)', 'foo', 'MATCH (book.title,book.isbn) AGAINST (:p1)', [['table' => 'book', 'column' => 'title', 'value' => 'foo']]],
];
}
/**
* @dataProvider conditionsForTestWhere
*
* @return void
*/
public function testWhere($clause, $value, $sql, $params)
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->where($clause, $value);
$sql = $this->getSql('SELECT FROM book WHERE ' . $sql);
$this->assertCriteriaTranslation($c, $sql, $params, 'where() accepts a string clause');
}
/**
* @return void
*/
public function testWhereUsesDefaultOperator()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->where('Propel\Tests\Bookstore\Book.Id = ?', 12);
$c->_or();
$c->where('Propel\Tests\Bookstore\Book.Title = ?', 'foo');
$sql = $this->getSql('SELECT FROM book WHERE (book.id = :p1 OR book.title = :p2)');
$params = [
['table' => 'book', 'column' => 'id', 'value' => '12'],
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'where() uses the default operator');
}
/**
* @return void
*/
public function testWhereTwiceSameColumn()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->where('Propel\Tests\Bookstore\Book.Id IN ?', [1, 2, 3]);
$c->where('Propel\Tests\Bookstore\Book.Id <> ?', 5);
$params = [
['table' => 'book', 'column' => 'id', 'value' => '1'],
['table' => 'book', 'column' => 'id', 'value' => '2'],
['table' => 'book', 'column' => 'id', 'value' => '3'],
['table' => 'book', 'column' => 'id', 'value' => '5'],
];
$sql = $this->getSql('SELECT FROM book WHERE (book.id IN (:p1,:p2,:p3) AND book.id <> :p4)');
$this->assertCriteriaTranslation($c, $sql, $params, 'where() adds clauses on the same column correctly');
}
/**
* @return void
*/
public function testWhereConditions()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->condition('cond1', 'Propel\Tests\Bookstore\Book.Title <> ?', 'foo');
$c->condition('cond2', 'Propel\Tests\Bookstore\Book.Title like ?', '%bar%');
$c->where(['cond1', 'cond2']);
$sql = $this->getSql('SELECT FROM book WHERE (book.title <> :p1 AND book.title like :p2)');
$params = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
['table' => 'book', 'column' => 'title', 'value' => '%bar%'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'where() accepts an array of named conditions');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->condition('cond1', 'Propel\Tests\Bookstore\Book.Title <> ?', 'foo');
$c->condition('cond2', 'Propel\Tests\Bookstore\Book.Title like ?', '%bar%');
$c->where(['cond1', 'cond2'], Criteria::LOGICAL_OR);
$sql = $this->getSql('SELECT FROM book WHERE (book.title <> :p1 OR book.title like :p2)');
$this->assertCriteriaTranslation($c, $sql, $params, 'where() accepts an array of named conditions with operator');
}
/**
* @return void
*/
public function testWhereNoReplacement()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('b.Title = ?', 'foo');
$c->where('1=1');
$sql = $this->getSql('SELECT FROM book WHERE book.title = :p1 AND 1=1');
$params = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'where() results in a Criteria::CUSTOM if no column name is matched');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
try {
$c->where('b.Title = ?', 'foo');
$this->fail('where() throws an exception when it finds a ? but cannot determine a column');
} catch (PropelException $e) {
$this->assertTrue(true, 'where() throws an exception when it finds a ? but cannot determine a column');
}
}
/**
* @return void
*/
public function testWhereFunction()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('UPPER(b.Title) = ?', 'foo');
$sql = $this->getSql('SELECT FROM book WHERE UPPER(book.title) = :p1');
$params = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'where() accepts a complex calculation');
}
/**
* @group mysql
*
* @return void
*/
public function testWhereTypeValue()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('LOCATE(\'foo\', b.Title) = ?', true, PDO::PARAM_BOOL);
$sql = $this->getSql("SELECT FROM book WHERE LOCATE('foo', book.title) = :p1");
$params = [
['table' => null, 'type' => PDO::PARAM_BOOL, 'value' => true],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'where() accepts a complex calculation');
$c->find($this->con);
$expected = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE LOCATE('foo', book.title) = true");
$this->assertEquals($expected, $this->con->getLastExecutedQuery());
}
/**
* @return void
*/
public function testOrWhere()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->where('Propel\Tests\Bookstore\Book.Title <> ?', 'foo');
$c->_or()->where('Propel\Tests\Bookstore\Book.Title like ?', '%bar%');
$sql = $this->getSql('SELECT FROM book WHERE (book.title <> :p1 OR book.title like :p2)');
$params = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
['table' => 'book', 'column' => 'title', 'value' => '%bar%'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'orWhere() combines the clause with the previous one using OR');
}
/**
* @return void
*/
public function testOrWhereConditions()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->where('Propel\Tests\Bookstore\Book.Id = ?', 12);
$c->condition('cond1', 'Propel\Tests\Bookstore\Book.Title <> ?', 'foo');
$c->condition('cond2', 'Propel\Tests\Bookstore\Book.Title like ?', '%bar%');
$c->_or()->where(['cond1', 'cond2']);
$sql = $this->getSql('SELECT FROM book WHERE (book.id = :p1 OR (book.title <> :p2 AND book.title like :p3))');
$params = [
['table' => 'book', 'column' => 'id', 'value' => 12],
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
['table' => 'book', 'column' => 'title', 'value' => '%bar%'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'orWhere() accepts an array of named conditions');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->where('Propel\Tests\Bookstore\Book.Id = ?', 12);
$c->condition('cond1', 'Propel\Tests\Bookstore\Book.Title <> ?', 'foo');
$c->condition('cond2', 'Propel\Tests\Bookstore\Book.Title like ?', '%bar%');
$c->_or()->where(['cond1', 'cond2'], Criteria::LOGICAL_OR);
$sql = $this->getSql('SELECT FROM book WHERE (book.id = :p1 OR (book.title <> :p2 OR book.title like :p3))');
$this->assertCriteriaTranslation($c, $sql, $params, 'orWhere() accepts an array of named conditions with operator');
}
/**
* @return void
*/
public function testMixedCriteria()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->where('Propel\Tests\Bookstore\Book.Title = ?', 'foo');
$c->add(BookTableMap::COL_ID, [1, 2], Criteria::IN);
$sql = $this->getSql('SELECT FROM book WHERE book.title = :p1 AND book.id IN (:p2,:p3)');
$params = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
['table' => 'book', 'column' => 'id', 'value' => 1],
['table' => 'book', 'column' => 'id', 'value' => 2],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'ModelCriteria accepts Criteria operators');
}
/**
* @return void
*/
public function testFilterBy()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->filterBy('Title', 'foo');
$sql = $this->getSql('SELECT FROM book WHERE book.title=:p1');
$params = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'filterBy() accepts a simple column name');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->filterBy('Title', 'foo', Criteria::NOT_EQUAL);
$sql = $this->getSql('SELECT FROM book WHERE book.title<>:p1');
$params = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'filterBy() accepts a sicustom comparator');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->filterBy('Title', 'foo');
$sql = $this->getSql('SELECT FROM book WHERE book.title=:p1');
$params = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
];
$this->assertCriteriaTranslation(
$c,
$sql,
$params,
'filterBy() accepts a simple column name, even if initialized with an alias'
);
}
/**
* @return void
*/
public function testGetParams()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->filterBy('Title', 'foo');
$expectedParams = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
];
$params = $c->getParams();
$this->assertEquals($expectedParams, $params, 'test getting parameters with a simple criterion');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->filterBy('Title', 'foo', Criteria::LIKE);
$expectedParams = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
];
$this->assertEquals($expectedParams, $params, 'test getting parameters with Specialized Criterion used for LIKE expressions');
}
/**
* @return void
*/
public function testHaving()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->having('Propel\Tests\Bookstore\Book.Title <> ?', 'foo');
$sql = 'SELECT FROM HAVING book.title <> :p1';
$params = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'having() accepts a string clause');
}
/**
* @return void
*/
public function testHavingConditions()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->condition('cond1', 'Propel\Tests\Bookstore\Book.Title <> ?', 'foo');
$c->condition('cond2', 'Propel\Tests\Bookstore\Book.Title like ?', '%bar%');
$c->having(['cond1', 'cond2']);
$sql = 'SELECT FROM HAVING (book.title <> :p1 AND book.title like :p2)';
$params = [
['table' => 'book', 'column' => 'title', 'value' => 'foo'],
['table' => 'book', 'column' => 'title', 'value' => '%bar%'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'having() accepts an array of named conditions');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->condition('cond1', 'Propel\Tests\Bookstore\Book.Title <> ?', 'foo');
$c->condition('cond2', 'Propel\Tests\Bookstore\Book.Title like ?', '%bar%');
$c->having(['cond1', 'cond2'], Criteria::LOGICAL_OR);
$sql = 'SELECT FROM HAVING (book.title <> :p1 OR book.title like :p2)';
$this->assertCriteriaTranslation($c, $sql, $params, 'having() accepts an array of named conditions with an operator');
}
/**
* @group mysql
*
* @return void
*/
public function testHavingWithColumn()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->withColumn('SUBSTRING(Book.Title, 1, 4)', 'title_start');
$c->having('title_start = ?', 'foo', PDO::PARAM_STR);
$sql = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id, SUBSTRING(book.title, 1, 4) AS title_start FROM book HAVING title_start = :p1');
$params = [
['table' => null, 'type' => 2, 'value' => 'foo'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'having() accepts a string clause');
$c->find($this->con);
$expected = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id, SUBSTRING(book.title, 1, 4) AS title_start FROM book HAVING title_start = \'foo\'');
$this->assertEquals($expected, $this->con->getLastExecutedQuery());
}
/**
* @return void
*/
public function testOrderBy()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->orderBy('Propel\Tests\Bookstore\Book.Title');
$sql = 'SELECT FROM ORDER BY book.title ASC';
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'orderBy() accepts a column name and adds an ORDER BY clause');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->orderBy('Propel\Tests\Bookstore\Book.Title', 'desc');
$sql = 'SELECT FROM ORDER BY book.title DESC';
$this->assertCriteriaTranslation($c, $sql, $params, 'orderBy() accepts an order parameter');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
try {
$c->orderBy('Propel\Tests\Bookstore\Book.Foo');
$this->fail('orderBy() throws an exception when called with an unknown column name');
} catch (UnknownColumnException $e) {
$this->assertTrue(true, 'orderBy() throws an exception when called with an unknown column name');
}
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
try {
$c->orderBy('Propel\Tests\Bookstore\Book.Title', 'foo');
$this->fail('orderBy() throws an exception when called with an unknown order');
} catch (UnexpectedValueException $e) {
$this->assertTrue(true, 'orderBy() throws an exception when called with an unknown order');
}
}
/**
* @return void
*/
public function testOrderBySimpleColumn()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->orderBy('Title');
$sql = 'SELECT FROM ORDER BY book.title ASC';
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'orderBy() accepts a simple column name and adds an ORDER BY clause');
}
/**
* @return void
*/
public function testOrderByAlias()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->addAsColumn('t', BookTableMap::COL_TITLE);
$c->orderBy('t');
$sql = 'SELECT book.title AS t FROM ORDER BY t ASC';
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'orderBy() accepts a column alias and adds an ORDER BY clause');
}
/**
* @return void
*/
public function testGroupBy()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->groupBy('Propel\Tests\Bookstore\Book.AuthorId');
$sql = 'SELECT FROM GROUP BY book.author_id';
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'groupBy() accepts a column name and adds a GROUP BY clause');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
try {
$c->groupBy('Book.Foo');
$this->fail('groupBy() throws an exception when called with an unknown column name');
} catch (UnknownColumnException $e) {
$this->assertTrue(true, 'groupBy() throws an exception when called with an unknown column name');
}
}
/**
* @return void
*/
public function testGroupBySimpleColumn()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->groupBy('AuthorId');
$sql = 'SELECT FROM GROUP BY book.author_id';
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'groupBy() accepts a simple column name and adds a GROUP BY clause');
}
/**
* @return void
*/
public function testGroupByAlias()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->addAsColumn('t', BookTableMap::COL_TITLE);
$c->groupBy('t');
$sql = 'SELECT book.title AS t FROM GROUP BY t';
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'groupBy() accepts a column alias and adds a GROUP BY clause');
}
/**
* @return void
*/
public function testGroupByClassThrowsExceptionOnUnknownClass()
{
$this->expectException(ClassNotFoundException::class);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->groupByClass('Author');
}
/**
* @return void
*/
public function testGroupByClass()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->groupByClass('Propel\Tests\Bookstore\Book');
$sql = 'SELECT FROM GROUP BY book.id,book.title,book.isbn,book.price,book.publisher_id,book.author_id';
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'groupByClass() accepts a class name and adds a GROUP BY clause for all columns of the class');
}
/**
* @return void
*/
public function testGroupByClassAlias()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->groupByClass('b');
$sql = 'SELECT FROM GROUP BY book.id,book.title,book.isbn,book.price,book.publisher_id,book.author_id';
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'groupByClass() accepts a class alias and adds a GROUP BY clause for all columns of the class');
}
/**
* @return void
*/
public function testGroupByClassTrueAlias()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setModelAlias('b', true);
$c->groupByClass('b');
$sql = 'SELECT FROM GROUP BY b.id,b.title,b.isbn,b.price,b.publisher_id,b.author_id';
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'groupByClass() accepts a true class alias and adds a GROUP BY clause for all columns of the class');
}
/**
* @return void
*/
public function testGroupByClassJoinedModel()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Author');
$c->join('Propel\Tests\Bookstore\Author.Book');
$c->groupByClass('Book');
$sql = $this->getSql('SELECT FROM author INNER JOIN book ON (author.id=book.author_id) GROUP BY book.id,book.title,book.isbn,book.price,book.publisher_id,book.author_id');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'groupByClass() accepts the class name of a joined model');
}
/**
* @return void
*/
public function testGroupByClassJoinedModelWithAlias()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Author');
$c->join('Propel\Tests\Bookstore\Author.Book b');
$c->groupByClass('b');
$sql = $this->getSql('SELECT FROM author INNER JOIN book b ON (author.id=b.author_id) GROUP BY b.id,b.title,b.isbn,b.price,b.publisher_id,b.author_id');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'groupByClass() accepts the alias of a joined model');
}
/**
* @return void
*/
public function testDistinct()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->distinct();
$sql = 'SELECT DISTINCT FROM ';
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'distinct() adds a DISTINCT clause');
}
/**
* @return void
*/
public function testLimit()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->limit(10);
$sql = 'SELECT FROM LIMIT 10';
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'limit() adds a LIMIT clause');
//test that limit 0 also works
$c->limit(0);
$sql = 'SELECT FROM LIMIT 0';
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'limit() adds a LIMIT clause');
}
/**
* @return void
*/
public function testOffset()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->limit(50);
$c->offset(10);
if ($this->isDb('mysql')) {
$sql = 'SELECT FROM LIMIT 10, 50';
} else {
$sql = 'SELECT FROM LIMIT 50 OFFSET 10';
}
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'offset() adds an OFFSET clause');
}
/**
* @return void
*/
public function testAddJoin()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->addJoin(BookTableMap::COL_AUTHOR_ID, AuthorTableMap::COL_ID);
$c->addJoin(BookTableMap::COL_PUBLISHER_ID, PublisherTableMap::COL_ID);
$sql = $this->getSql('SELECT FROM book INNER JOIN author ON (book.author_id=author.id) INNER JOIN publisher ON (book.publisher_id=publisher.id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'addJoin() works the same as in Criteria');
}
/**
* @return void
*/
public function testJoin()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author');
$sql = $this->getSql('SELECT FROM book INNER JOIN author ON (book.author_id=author.id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() uses a relation to guess the columns');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
try {
$c->join('Propel\Tests\Bookstore\Book.Foo');
$this->fail('join() throws an exception when called with a non-existing relation');
} catch (UnknownRelationException $e) {
$this->assertTrue(true, 'join() throws an exception when called with a non-existing relation');
}
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author');
$c->where('Author.FirstName = ?', 'Leo');
$sql = $this->getSql('SELECT FROM book INNER JOIN author ON (book.author_id=author.id) WHERE author.first_name = :p1');
$params = [
['table' => 'author', 'column' => 'first_name', 'value' => 'Leo'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() uses a relation to guess the columns');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Author');
$c->where('Author.FirstName = ?', 'Leo');
$sql = $this->getSql('SELECT FROM book INNER JOIN author ON (book.author_id=author.id) WHERE author.first_name = :p1');
$params = [
['table' => 'author', 'column' => 'first_name', 'value' => 'Leo'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() uses the current model name when given a simple relation name');
}
/**
* @return void
*/
public function testJoinQuery()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
BookstoreDataPopulator::depopulate($con);
BookstoreDataPopulator::populate($con);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author');
$c->where('Author.FirstName = ?', 'Neal');
$books = BookQuery::create(null, $c)->find();
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book INNER JOIN author ON (book.author_id=author.id) WHERE author.first_name = 'Neal'");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'join() issues a real JOIN query');
$this->assertEquals(1, count($books), 'join() issues a real JOIN query');
}
/**
* @return void
*/
public function testJoinRelationName()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\BookstoreEmployee');
$c->join('Propel\Tests\Bookstore\BookstoreEmployee.Supervisor');
$sql = $this->getSql('SELECT FROM INNER JOIN bookstore_employee ON (bookstore_employee.supervisor_id=bookstore_employee.id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() uses relation names as defined in schema.xml');
}
/**
* @return void
*/
public function testJoinComposite()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\ReaderFavorite');
$c->join('Propel\Tests\Bookstore\ReaderFavorite.BookOpinion');
$sql = $this->getSql('SELECT FROM reader_favorite INNER JOIN book_opinion ON (reader_favorite.book_id=book_opinion.book_id AND reader_favorite.reader_id=book_opinion.reader_id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() knows how to create a JOIN clause for relationships with composite fkeys');
}
/**
* @return void
*/
public function testJoinType()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author');
$sql = $this->getSql('SELECT FROM book INNER JOIN author ON (book.author_id=author.id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() adds an INNER JOIN by default');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author', Criteria::INNER_JOIN);
$sql = $this->getSql('SELECT FROM book INNER JOIN author ON (book.author_id=author.id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() adds an INNER JOIN by default');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author', Criteria::LEFT_JOIN);
$sql = $this->getSql('SELECT FROM book LEFT JOIN author ON (book.author_id=author.id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() can add a LEFT JOIN');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author', Criteria::RIGHT_JOIN);
$sql = $this->getSql('SELECT FROM book RIGHT JOIN author ON (book.author_id=author.id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() can add a RIGHT JOIN');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author', 'incorrect join');
$sql = $this->getSql('SELECT FROM book incorrect join author ON (book.author_id=author.id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() accepts any join string');
}
/**
* @return void
*/
public function testJoinDirection()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author');
$sql = $this->getSql('SELECT FROM book INNER JOIN author ON (book.author_id=author.id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() adds a JOIN clause correctly for many to one relationship');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Author');
$c->join('Propel\Tests\Bookstore\Author.Book');
$sql = $this->getSql('SELECT FROM author INNER JOIN book ON (author.id=book.author_id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() adds a JOIN clause correctly for one to many relationship');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\BookstoreEmployee');
$c->join('Propel\Tests\Bookstore\BookstoreEmployee.BookstoreEmployeeAccount');
$sql = $this->getSql('SELECT FROM bookstore_employee INNER JOIN bookstore_employee_account ON (bookstore_employee.id=bookstore_employee_account.employee_id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() adds a JOIN clause correctly for one to one relationship');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\BookstoreEmployeeAccount');
$c->join('Propel\Tests\Bookstore\BookstoreEmployeeAccount.BookstoreEmployee');
$sql = $this->getSql('SELECT FROM bookstore_employee_account INNER JOIN bookstore_employee ON (bookstore_employee_account.employee_id=bookstore_employee.id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() adds a JOIN clause correctly for one to one relationship');
}
/**
* @return void
*/
public function testJoinSeveral()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Author');
$c->join('Propel\Tests\Bookstore\Author.Book');
$c->join('Book.Publisher');
$c->where('Publisher.Name = ?', 'foo');
$sql = $this->getSql('SELECT FROM author INNER JOIN book ON (author.id=book.author_id) INNER JOIN publisher ON (book.publisher_id=publisher.id) WHERE publisher.name = :p1');
$params = [
['table' => 'publisher', 'column' => 'name', 'value' => 'foo'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() can guess relationships from related tables');
}
/**
* @return void
*/
public function testJoinAlias()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->join('b.Author');
$sql = $this->getSql('SELECT FROM book INNER JOIN author ON (book.author_id=author.id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() supports relation on main alias');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->join('Author');
$sql = $this->getSql('SELECT FROM book INNER JOIN author ON (book.author_id=author.id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() can use a simple relation name when the model has an alias');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author a');
$sql = $this->getSql('SELECT FROM book INNER JOIN author a ON (book.author_id=a.id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() supports relation alias');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->join('b.Author a');
$sql = $this->getSql('SELECT FROM book INNER JOIN author a ON (book.author_id=a.id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() supports relation alias on main alias');
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->join('b.Author a');
$c->where('a.FirstName = ?', 'Leo');
$sql = $this->getSql('SELECT FROM book INNER JOIN author a ON (book.author_id=a.id) WHERE a.first_name = :p1');
$params = [
['table' => 'author', 'column' => 'first_name', 'value' => 'Leo'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() allows the use of relation alias in where()');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Author', 'a');
$c->join('a.Book b');
$c->join('b.Publisher p');
$c->where('p.Name = ?', 'foo');
$sql = $this->getSql('SELECT FROM author INNER JOIN book b ON (author.id=b.author_id) INNER JOIN publisher p ON (b.publisher_id=p.id) WHERE p.name = :p1');
$params = [
['table' => 'publisher', 'column' => 'name', 'value' => 'foo'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() allows the use of relation alias in further join()');
}
/**
* @return void
*/
public function testJoinTrueTableAlias()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setModelAlias('b', true);
$c->join('b.Author');
$sql = $this->getSql('SELECT FROM book b INNER JOIN author ON (b.author_id=author.id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() supports relation on true table alias');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setModelAlias('b', true);
$c->join('Author');
$sql = $this->getSql('SELECT FROM book b INNER JOIN author ON (b.author_id=author.id)');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() supports relation without alias name on true table alias');
}
/**
* @return void
*/
public function testJoinOnSameTable()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\BookstoreEmployee', 'be');
$c->join('be.Supervisor sup');
$c->join('sup.Subordinate sub');
$c->where('sub.Name = ?', 'Foo');
$sql = $this->getSql('SELECT FROM bookstore_employee INNER JOIN bookstore_employee sup ON (bookstore_employee.supervisor_id=sup.id) INNER JOIN bookstore_employee sub ON (sup.id=sub.supervisor_id) WHERE sub.name = :p1');
$params = [
['table' => 'bookstore_employee', 'column' => 'name', 'value' => 'Foo'],
];
$this->assertCriteriaTranslation($c, $sql, $params, 'join() allows two joins on the same table thanks to aliases');
}
/**
* @return void
*/
public function testJoinAliasQuery()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->join('b.Author a');
$c->where('a.FirstName = ?', 'Leo');
$books = BookQuery::create(null, $c)->find($con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book INNER JOIN author a ON (book.author_id=a.id) WHERE a.first_name = 'Leo'");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'join() allows the use of relation alias in where()');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\BookstoreEmployee', 'be');
$c->join('be.Supervisor sup');
$c->join('sup.Subordinate sub');
$c->where('sub.Name = ?', 'Foo');
$employees = BookstoreEmployeeQuery::create(null, $c)->find($con);
$expectedSQL = $this->getSql("SELECT bookstore_employee.id, bookstore_employee.class_key, bookstore_employee.name, bookstore_employee.job_title, bookstore_employee.supervisor_id FROM bookstore_employee INNER JOIN bookstore_employee sup ON (bookstore_employee.supervisor_id=sup.id) INNER JOIN bookstore_employee sub ON (sup.id=sub.supervisor_id) WHERE sub.name = 'Foo'");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'join() allows the use of relation alias in further joins()');
}
/**
* @return void
*/
public function testAddJoinConditionSimple()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author', Criteria::INNER_JOIN);
$c->addJoinCondition('Author', 'Propel\Tests\Bookstore\Book.Title IS NOT NULL');
$books = BookQuery::create(null, $c)->find($con);
$expectedSQL = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book INNER JOIN author ON (book.author_id=author.id AND book.title IS NOT NULL)');
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'addJoinCondition() allows the use of custom conditions');
}
/**
* @return void
*/
public function testAddJoinConditionBinding()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author', Criteria::INNER_JOIN);
$c->addJoinCondition('Author', 'Propel\Tests\Bookstore\Book.Title = ?', 'foo');
$books = BookQuery::create(null, $c)->find($con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book INNER JOIN author ON (book.author_id=author.id AND book.title = 'foo')");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'addJoinCondition() allows the use of custom conditions with values to bind');
}
/**
* @return void
*/
public function testAddJoinConditionSeveral()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author', Criteria::INNER_JOIN);
$c->addJoinCondition('Author', 'Propel\Tests\Bookstore\Book.Title = ?', 'foo');
$c->addJoinCondition('Author', 'Propel\Tests\Bookstore\Book.isbn IS NOT NULL');
$books = BookQuery::create(null, $c)->find($con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book INNER JOIN author ON ((book.author_id=author.id AND book.title = 'foo') AND book.isbn IS NOT NULL)");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'addJoinCondition() allows the use of several custom conditions');
}
/**
* @return void
*/
public function testAddJoinConditionBindingAndWhere()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->where('Propel\Tests\Bookstore\Book.Title LIKE ?', 'foo%');
$c->join('Propel\Tests\Bookstore\Book.Author', Criteria::INNER_JOIN);
$c->addJoinCondition('Author', 'Propel\Tests\Bookstore\Book.Title = ?', 'foo');
$books = BookQuery::create(null, $c)->find($con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book INNER JOIN author ON (book.author_id=author.id AND book.title = 'foo') WHERE book.title LIKE 'foo%'");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'addJoinCondition() allows the use of custom conditions with values and lives well with WHERE conditions');
}
/**
* @return void
*/
public function testAddJoinConditionAlias()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author a', Criteria::INNER_JOIN);
$c->addJoinCondition('a', 'Book.Title IS NOT NULL');
$books = BookQuery::create(null, $c)->find($con);
$expectedSQL = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book INNER JOIN author a ON (book.author_id=a.id AND book.title IS NOT NULL)');
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'addJoinCondition() allows the use of custom conditions even on aliased relations');
}
/**
* @return void
*/
public function testAddJoinConditionOperator()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author', Criteria::INNER_JOIN);
$c->addJoinCondition('Author', 'Propel\Tests\Bookstore\Book.Title IS NOT NULL', null, Criteria::LOGICAL_OR);
$books = BookQuery::create(null, $c)->find($con);
$expectedSQL = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book INNER JOIN author ON (book.author_id=author.id OR book.title IS NOT NULL)');
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'addJoinCondition() allows the use of custom conditions with a custom operator');
}
/**
* @return void
*/
public function testSetJoinConditionCriterion()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author', Criteria::INNER_JOIN);
$criterion = $c->getNewCriterion(BookTableMap::COL_TITLE, BookTableMap::COL_TITLE . ' = ' . AuthorTableMap::COL_FIRST_NAME, Criteria::CUSTOM);
$c->setJoinCondition('Author', $criterion);
$books = BookQuery::create(null, $c)->find($con);
$expectedSQL = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book INNER JOIN author ON book.title = author.first_name');
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'setJoinCondition() can override a previous join condition with a Criterion');
}
/**
* @return void
*/
public function testSetJoinConditionNamedCondition()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author', Criteria::INNER_JOIN);
$c->condition('cond1', 'Propel\Tests\Bookstore\Book.Title = Author.FirstName');
$c->setJoinCondition('Author', 'cond1');
$books = BookQuery::create(null, $c)->find($con);
$expectedSQL = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book INNER JOIN author ON book.title = author.first_name');
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'setJoinCondition() can override a previous join condition with a named condition');
}
/**
* @return void
*/
public function testGetJoin()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author');
$joins = $c->getJoins();
$this->assertEquals($joins['Author'], $c->getJoin('Author'), 'getJoin() returns a specific Join from the ModelCriteria');
}
/**
* @return void
*/
public function testWith()
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author');
$c->with('Author');
$withs = $c->getWith();
$this->assertTrue(array_key_exists('Author', $withs), 'with() adds an entry to the internal list of Withs');
$this->assertInstanceOf('Propel\Runtime\ActiveQuery\ModelWith', $withs['Author'], 'with() references the ModelWith object');
}
/**
* @return void
*/
public function testWithThrowsExceptionWhenJoinLacks()
{
$this->expectException(UnknownRelationException::class);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->with('Propel\Tests\Bookstore\Author');
}
/**
* @return void
*/
public function testWithAlias()
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author a');
$c->with('a');
$withs = $c->getWith();
$this->assertTrue(array_key_exists('a', $withs), 'with() uses the alias for the index of the internal list of Withs');
}
/**
* @return void
*/
public function testWithThrowsExceptionWhenNotUsingAlias()
{
$this->expectException(UnknownRelationException::class);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author a');
$c->with('Propel\Tests\Bookstore\Author');
}
/**
* @return void
*/
public function testWithAddsSelectColumns()
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
BookTableMap::addSelectColumns($c);
$c->join('Propel\Tests\Bookstore\Book.Author');
$c->with('Author');
$expectedColumns = [
BookTableMap::COL_ID,
BookTableMap::COL_TITLE,
BookTableMap::COL_ISBN,
BookTableMap::COL_PRICE,
BookTableMap::COL_PUBLISHER_ID,
BookTableMap::COL_AUTHOR_ID,
AuthorTableMap::COL_ID,
AuthorTableMap::COL_FIRST_NAME,
AuthorTableMap::COL_LAST_NAME,
AuthorTableMap::COL_EMAIL,
AuthorTableMap::COL_AGE,
];
$this->assertEquals($expectedColumns, $c->getSelectColumns(), 'with() adds the columns of the related table');
}
/**
* @return void
*/
public function testWithAliasAddsSelectColumns()
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
BookTableMap::addSelectColumns($c);
$c->join('Propel\Tests\Bookstore\Book.Author a');
$c->with('a');
$expectedColumns = [
BookTableMap::COL_ID,
BookTableMap::COL_TITLE,
BookTableMap::COL_ISBN,
BookTableMap::COL_PRICE,
BookTableMap::COL_PUBLISHER_ID,
BookTableMap::COL_AUTHOR_ID,
'a.id',
'a.first_name',
'a.last_name',
'a.email',
'a.age',
];
$this->assertEquals($expectedColumns, $c->getSelectColumns(), 'with() adds the columns of the related table');
}
/**
* @return void
*/
public function testWithAddsSelectColumnsOfMainTable()
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Author');
$c->with('Author');
$expectedColumns = [
BookTableMap::COL_ID,
BookTableMap::COL_TITLE,
BookTableMap::COL_ISBN,
BookTableMap::COL_PRICE,
BookTableMap::COL_PUBLISHER_ID,
BookTableMap::COL_AUTHOR_ID,
AuthorTableMap::COL_ID,
AuthorTableMap::COL_FIRST_NAME,
AuthorTableMap::COL_LAST_NAME,
AuthorTableMap::COL_EMAIL,
AuthorTableMap::COL_AGE,
];
$this->assertEquals($expectedColumns, $c->getSelectColumns(), 'with() adds the columns of the main table if required');
}
/**
* @return void
*/
public function testWithAliasAddsSelectColumnsOfMainTable()
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setModelAlias('b', true);
$c->join('b.Author a');
$c->with('a');
$expectedColumns = [
'b.id',
'b.title',
'b.isbn',
'b.price',
'b.publisher_id',
'b.author_id',
'a.id',
'a.first_name',
'a.last_name',
'a.email',
'a.age',
];
$this->assertEquals($expectedColumns, $c->getSelectColumns(), 'with() adds the columns of the main table with an alias if required');
}
/**
* @return void
*/
public function testWithOneToManyAddsSelectColumns()
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Author');
AuthorTableMap::addSelectColumns($c);
$c->leftJoin('Propel\Tests\Bookstore\Author.Book');
$c->with('Book');
$expectedColumns = [
AuthorTableMap::COL_ID,
AuthorTableMap::COL_FIRST_NAME,
AuthorTableMap::COL_LAST_NAME,
AuthorTableMap::COL_EMAIL,
AuthorTableMap::COL_AGE,
BookTableMap::COL_ID,
BookTableMap::COL_TITLE,
BookTableMap::COL_ISBN,
BookTableMap::COL_PRICE,
BookTableMap::COL_PUBLISHER_ID,
BookTableMap::COL_AUTHOR_ID,
];
$this->assertEquals($expectedColumns, $c->getSelectColumns(), 'with() adds the columns of the related table even in a one-to-many relationship');
}
/**
* @return void
*/
public function testJoinWith()
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->joinWith('Propel\Tests\Bookstore\Book.Author');
$expectedColumns = [
BookTableMap::COL_ID,
BookTableMap::COL_TITLE,
BookTableMap::COL_ISBN,
BookTableMap::COL_PRICE,
BookTableMap::COL_PUBLISHER_ID,
BookTableMap::COL_AUTHOR_ID,
AuthorTableMap::COL_ID,
AuthorTableMap::COL_FIRST_NAME,
AuthorTableMap::COL_LAST_NAME,
AuthorTableMap::COL_EMAIL,
AuthorTableMap::COL_AGE,
];
$this->assertEquals($expectedColumns, $c->getSelectColumns(), 'joinWith() adds the join');
$joins = $c->getJoins();
$join = $joins['Author'];
$this->assertEquals(Criteria::INNER_JOIN, $join->getJoinType(), 'joinWith() adds an INNER JOIN by default');
}
/**
* @return void
*/
public function testJoinWithType()
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->joinWith('Propel\Tests\Bookstore\Book.Author', Criteria::LEFT_JOIN);
$joins = $c->getJoins();
$join = $joins['Author'];
$this->assertEquals(Criteria::LEFT_JOIN, $join->getJoinType(), 'joinWith() accepts a join type as second parameter');
}
/**
* @return void
*/
public function testJoinWithAlias()
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->joinWith('Propel\Tests\Bookstore\Book.Author a');
$expectedColumns = [
BookTableMap::COL_ID,
BookTableMap::COL_TITLE,
BookTableMap::COL_ISBN,
BookTableMap::COL_PRICE,
BookTableMap::COL_PUBLISHER_ID,
BookTableMap::COL_AUTHOR_ID,
'a.id',
'a.first_name',
'a.last_name',
'a.email',
'a.age',
];
$this->assertEquals($expectedColumns, $c->getSelectColumns(), 'joinWith() adds the join with the alias');
}
/**
* @return void
*/
public function testJoinWithSeveral()
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Review');
$c->joinWith('Review.Book');
$c->joinWith('Propel\Tests\Bookstore\Book.Author');
$c->joinWith('Book.Publisher');
$expectedColumns = [
ReviewTableMap::COL_ID,
ReviewTableMap::COL_REVIEWED_BY,
ReviewTableMap::COL_REVIEW_DATE,
ReviewTableMap::COL_RECOMMENDED,
ReviewTableMap::COL_STATUS,
ReviewTableMap::COL_BOOK_ID,
BookTableMap::COL_ID,
BookTableMap::COL_TITLE,
BookTableMap::COL_ISBN,
BookTableMap::COL_PRICE,
BookTableMap::COL_PUBLISHER_ID,
BookTableMap::COL_AUTHOR_ID,
AuthorTableMap::COL_ID,
AuthorTableMap::COL_FIRST_NAME,
AuthorTableMap::COL_LAST_NAME,
AuthorTableMap::COL_EMAIL,
AuthorTableMap::COL_AGE,
PublisherTableMap::COL_ID,
PublisherTableMap::COL_NAME,
];
$this->assertEquals($expectedColumns, $c->getSelectColumns(), 'joinWith() adds the with');
$joins = $c->getJoins();
$expectedJoinKeys = ['Book', 'Author', 'Publisher'];
$this->assertEquals($expectedJoinKeys, array_keys($joins), 'joinWith() adds the join');
}
/**
* @return void
*/
public function testJoinWithTwice()
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->join('Propel\Tests\Bookstore\Book.Review');
$c->joinWith('Propel\Tests\Bookstore\Book.Author');
$c->joinWith('Propel\Tests\Bookstore\Book.Review');
$expectedColumns = [
BookTableMap::COL_ID,
BookTableMap::COL_TITLE,
BookTableMap::COL_ISBN,
BookTableMap::COL_PRICE,
BookTableMap::COL_PUBLISHER_ID,
BookTableMap::COL_AUTHOR_ID,
AuthorTableMap::COL_ID,
AuthorTableMap::COL_FIRST_NAME,
AuthorTableMap::COL_LAST_NAME,
AuthorTableMap::COL_EMAIL,
AuthorTableMap::COL_AGE,
ReviewTableMap::COL_ID,
ReviewTableMap::COL_REVIEWED_BY,
ReviewTableMap::COL_REVIEW_DATE,
ReviewTableMap::COL_RECOMMENDED,
ReviewTableMap::COL_STATUS,
ReviewTableMap::COL_BOOK_ID,
];
$this->assertEquals($expectedColumns, $c->getSelectColumns(), 'joinWith() adds the with');
$joins = $c->getJoins();
$expectedJoinKeys = ['Review', 'Author'];
$this->assertEquals($expectedJoinKeys, array_keys($joins), 'joinWith() adds the join');
}
public static function conditionsForTestWithColumn()
{
return [
['Propel\Tests\Bookstore\Book.Title', 'BookTitle', 'book.title AS BookTitle'],
['Book.Title', null, 'book.title AS BookTitle'],
['UPPER(Book.Title)', null, 'UPPER(book.title) AS UPPERBookTitle'],
['CONCAT(Propel\Tests\Bookstore\Book.Title, Propel\Tests\Bookstore\Book.isbn)', 'foo', 'CONCAT(book.title, book.isbn) AS foo'],
];
}
/**
* @dataProvider conditionsForTestWithColumn
*
* @return void
*/
public function testWithColumn($clause, $alias, $selectTranslation)
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->withColumn($clause, $alias);
$sql = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id, ' . $selectTranslation . ' FROM book');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'withColumn() adds a calculated column to the select clause');
}
public static function conditionsForTestWithColumnAndQuotes()
{
return [
// Examples for simple string concatenation needed for MSSQL.
// MSSQL has no CONCAT() function so uses + to join strings.
["CONVERT(varchar, Propel\Tests\Bookstore\Author.Age, 120) + \' GMT\'", 'GMTCreatedAt', "CONVERT(varchar, author.age, 120) + \' GMT\' AS GMTCreatedAt"],
["(Propel\Tests\Bookstore\Author.FirstName + ' ' + Propel\Tests\Bookstore\Author.LastName)", 'AuthorFullname', "(author.first_name + ' ' + author.last_name) AS AuthorFullname"],
["('\"' + Propel\Tests\Bookstore\Author.FirstName + ' ' + Propel\Tests\Bookstore\Author.LastName + '\"')", 'QuotedAuthorFullname', "('\"' + author.first_name + ' ' + author.last_name + '\"') AS QuotedAuthorFullname"],
// Examples for simple string concatenation needed for Sqlite
// Sqlite has no CONCAT() function so uses || to join strings. || can also be used to join strings in PQSql and Oracle
["(Propel\Tests\Bookstore\Author.FirstName || ' ' || Propel\Tests\Bookstore\Author.LastName)", 'AuthorFullname', "(author.first_name || ' ' || author.last_name) AS AuthorFullname"],
["('\"' || Propel\Tests\Bookstore\Author.FirstName || ' ' || Propel\Tests\Bookstore\Author.LastName || '\"')", 'QuotedAuthorFullname', "('\"' || author.first_name || ' ' || author.last_name || '\"') AS QuotedAuthorFullname"],
];
}
/**
* @dataProvider conditionsForTestWithColumnAndQuotes
*
* @return void
*/
public function testWithColumnAndQuotes($clause, $alias, $selectTranslation)
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Author');
$c->withColumn($clause, $alias);
$sql = $this->getSql('SELECT author.id, author.first_name, author.last_name, author.email, author.age, ' . $selectTranslation . ' FROM author');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'withColumn() adds a calculated column using quotes to the select clause');
}
/**
* @return void
*/
public function testWithColumnAndSelectColumns()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->withColumn('UPPER(Propel\Tests\Bookstore\Book.Title)', 'foo');
$sql = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id, UPPER(book.title) AS foo FROM book');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'withColumn() adds the object columns if the criteria has no select columns');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->addSelectColumn('book.id');
$c->withColumn('UPPER(Propel\Tests\Bookstore\Book.Title)', 'foo');
$sql = $this->getSql('SELECT book.id, UPPER(book.title) AS foo FROM book');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'withColumn() does not add the object columns if the criteria already has select columns');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->addSelectColumn('book.id');
$c->withColumn('UPPER(Propel\Tests\Bookstore\Book.Title)', 'foo');
$c->addSelectColumn('book.title');
$sql = $this->getSql('SELECT book.id, book.title, UPPER(book.title) AS foo FROM book');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'withColumn() does adds as column after the select columns even though the withColumn() method was called first');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->addSelectColumn('book.id');
$c->withColumn('UPPER(Propel\Tests\Bookstore\Book.Title)', 'foo');
$c->withColumn('UPPER(Propel\Tests\Bookstore\Book.isbn)', 'isbn');
$sql = $this->getSql('SELECT book.id, UPPER(book.title) AS foo, UPPER(book.isbn) AS isbn FROM book');
$params = [];
$this->assertCriteriaTranslation($c, $sql, $params, 'withColumn() called repeatedly adds several as columns');
}
/**
* @return void
*/
public function testKeepQuery()
{
$c = BookQuery::create();
$this->assertTrue($c->isKeepQuery(), 'keepQuery is enabled by default');
$c->keepQuery(false);
$this->assertFalse($c->isKeepQuery(), 'keepQuery(false) disables the keepQuery property');
$c->keepQuery();
$this->assertTrue($c->isKeepQuery(), 'keepQuery() enables the keepQuery property');
}
/**
* @return void
*/
public function testKeepQueryFind()
{
$c = BookQuery::create();
$c->filterByTitle('foo');
$c->find();
$this->assertEquals([], $c->getSelectColumns(), 'find() clones the query by default');
$c = BookQuery::create();
$c->filterByTitle('foo');
$c->keepQuery(false);
$c->find();
$expected = ['book.id', 'book.title', 'book.isbn', 'book.price', 'book.publisher_id', 'book.author_id'];
$this->assertEquals($expected, $c->getSelectColumns(), 'keepQuery(false) forces find() to use the original query');
}
/**
* @return void
*/
public function testKeepQueryFindOne()
{
$c = BookQuery::create();
$c->filterByTitle('foo');
$c->findOne();
$this->assertEquals(-1, $c->getLimit(), 'findOne() clones the query by default');
$c = BookQuery::create();
$c->filterByTitle('foo');
$c->keepQuery(false);
$c->findOne();
$this->assertEquals(1, $c->getLimit(), 'keepQuery(false) forces findOne() to use the original query');
}
/**
* @return void
*/
public function testKeepQueryFindPk()
{
$c = BookQuery::create();
$c->findPk(1);
$this->assertEquals([], $c->getSelectColumns(), 'findPk() clones the query by default');
$c = BookQuery::create('b');
$c->keepQuery(false);
$c->findPk(1);
$expected = ['book.id', 'book.title', 'book.isbn', 'book.price', 'book.publisher_id', 'book.author_id'];
$this->assertEquals($expected, $c->getSelectColumns(), 'keepQuery(false) forces findPk() to use the original query');
}
/**
* @return void
*/
public function testKeepQueryCount()
{
$c = BookQuery::create();
$c->orderByTitle();
$c->count();
$this->assertEquals(['book.title ASC'], $c->getOrderByColumns(), 'count() clones the query by default');
$c = BookQuery::create();
$c->orderByTitle();
$c->keepQuery(false);
$c->count();
$this->assertEquals([], $c->getOrderByColumns(), 'keepQuery() forces count() to use the original query');
}
/**
* @return void
*/
public function testFind()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('b.Title = ?', 'foo');
$books = $c->find();
$this->assertTrue($books instanceof Collection, 'find() returns a collection by default');
$this->assertEquals(0, count($books), 'find() returns an empty array when the query returns no result');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->join('b.Author a');
$c->where('a.FirstName = ?', 'Neal');
$books = $c->find();
$this->assertTrue($books instanceof Collection, 'find() returns a collection by default');
$this->assertEquals(1, count($books), 'find() returns as many rows as the results in the query');
$book = $books->shift();
$this->assertTrue($book instanceof Book, 'find() returns an array of Model objects by default');
$this->assertEquals('Quicksilver', $book->getTitle(), 'find() returns the model objects matching the query');
}
/**
* @return void
*/
public function testFindAddsSelectColumns()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$books = $c->find($con);
$sql = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book');
$this->assertEquals($sql, $con->getLastExecutedQuery(), 'find() adds the select columns of the current model');
}
/**
* @return void
*/
public function testFindTrueAliasAddsSelectColumns()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setModelAlias('b', true);
$books = $c->find($con);
$sql = $this->getSql('SELECT b.id, b.title, b.isbn, b.price, b.publisher_id, b.author_id FROM book b');
$this->assertEquals($sql, $con->getLastExecutedQuery(), 'find() uses the true model alias if available');
}
/**
* @return void
*/
public function testFindOne()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('b.Title = ?', 'foo');
$book = $c->findOne();
$this->assertNull($book, 'findOne() returns null when the query returns no result');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->orderBy('b.Title');
$book = $c->findOne();
$this->assertTrue($book instanceof Book, 'findOne() returns a Model object by default');
$this->assertEquals('Don Juan', $book->getTitle(), 'find() returns the model objects matching the query');
}
/**
* @return void
*/
public function testFindOneOrCreateNotExists()
{
BookQuery::create()->deleteAll();
$book = BookQuery::create('b')
->where('b.Title = ?', 'foo')
->filterByPrice(125)
->findOneOrCreate();
$this->assertTrue($book instanceof Book, 'findOneOrCreate() returns an instance of the model when the request has no result');
$this->assertTrue($book->isNew(), 'findOneOrCreate() returns a new instance of the model when the request has no result');
$this->assertEquals('foo', $book->getTitle(), 'findOneOrCreate() returns a populated objects based on the conditions');
$this->assertEquals(125, $book->getPrice(), 'findOneOrCreate() returns a populated objects based on the conditions');
}
/**
* @return void
*/
public function testFindOneOrCreateNotExistsFormatter()
{
BookQuery::create()->deleteAll();
$book = BookQuery::create('b')
->where('b.Title = ?', 'foo')
->filterByPrice(125)
->setFormatter(ModelCriteria::FORMAT_ARRAY)
->findOneOrCreate();
$this->assertTrue(is_array($book), 'findOneOrCreate() uses the query formatter even when the request has no result');
$this->assertEquals('foo', $book['Title'], 'findOneOrCreate() returns a populated array based on the conditions');
$this->assertEquals(125, $book['Price'], 'findOneOrCreate() returns a populated array based on the conditions');
}
/**
* @return void
*/
public function testFindOneOrCreateExists()
{
BookQuery::create()->deleteAll();
$book = new Book();
$book->setTitle('foo');
$book->setISBN('FA404');
$book->setPrice(125);
$book->save();
$book = BookQuery::create('b')
->where('b.Title = ?', 'foo')
->filterByPrice(125)
->findOneOrCreate();
$this->assertTrue($book instanceof Book, 'findOneOrCreate() returns an instance of the model when the request has one result');
$this->assertFalse($book->isNew(), 'findOneOrCreate() returns an existing instance of the model when the request has one result');
$this->assertEquals('foo', $book->getTitle(), 'findOneOrCreate() returns a populated objects based on the conditions');
$this->assertEquals(125, $book->getPrice(), 'findOneOrCreate() returns a populated objects based on the conditions');
}
/**
* @return void
*/
public function testFindOneOrCreateThrowsExceptionWhenQueryContainsJoin()
{
$this->expectException(PropelException::class);
$book = BookQuery::create('b')
->filterByPrice(125)
->useAuthorQuery()
->filterByFirstName('Leo')
->endUse()
->findOneOrCreate();
}
/**
* @return void
*/
public function testFindOneOrCreateMakesOneQueryWhenRecordNotExists()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
BookQuery::create()->deleteAll($con);
$count = $con->getQueryCount();
$book = BookQuery::create('b')
->filterByPrice(125)
->findOneOrCreate($con);
$this->assertEquals($count + 1, $con->getQueryCount(), 'findOneOrCreate() makes only a single query when the record doesn\'t exist');
}
/**
* @return void
*/
public function testFindOneOrCreateMakesOneQueryWhenRecordExists()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
BookQuery::create()->deleteAll($con);
$book = new Book();
$book->setTitle('Title');
$book->setISBN('FA404');
$book->setPrice(125);
$book->save($con);
$count = $con->getQueryCount();
$book = BookQuery::create('b')
->filterByPrice(125)
->findOneOrCreate($con);
$this->assertEquals($count + 1, $con->getQueryCount(), 'findOneOrCreate() makes only a single query when the record exists');
}
/**
* @return void
*/
public function testFindOneOrCreateWithEnums()
{
Book2Query::create()->deleteAll();
$book = Book2Query::create('b')
->where('b.Title = ?', 'bar')
->filterByStyle('poetry')
->findOneOrCreate();
$this->assertTrue($book instanceof Book2, 'findOneOrCreate() returns an instance of the model when the request has no result');
$this->assertTrue($book->isNew(), 'findOneOrCreate() returns a new instance of the model when the request has no result');
$this->assertEquals('bar', $book->getTitle(), 'findOneOrCreate() returns a populated objects based on the conditions');
$this->assertEquals('poetry', $book->getStyle(), 'findOneOrCreate() returns a populated objects based on the conditions');
$book = Book2Query::create('b')
->where('b.Title = ?', 'foobar')
->filterByStyle('essay')
->findOneOrCreate();
$this->assertTrue($book instanceof Book2, 'findOneOrCreate() returns an instance of the model when the request has no result');
$this->assertTrue($book->isNew(), 'findOneOrCreate() returns a new instance of the model when the request has no result');
$this->assertEquals('foobar', $book->getTitle(), 'findOneOrCreate() returns a populated objects based on the conditions');
$this->assertEquals('essay', $book->getStyle(), 'findOneOrCreate() returns a populated objects based on the conditions');
$book = Book2Query::create('b')
->where('b.Style = ?', 'novel')
->findOneOrCreate();
$this->assertTrue($book instanceof Book2, 'findOneOrCreate() returns an instance of the model when the request has no result');
$this->assertTrue($book->isNew(), 'findOneOrCreate() returns a new instance of the model when the request has no result');
$this->assertEquals('novel', $book->getStyle(), 'findOneOrCreate() returns a populated objects based on the conditions');
}
/**
* @return void
*/
public function testFindOneOrCreateWithSets()
{
Book2Query::create()->deleteAll();
$book = Book2Query::create('b')
->where('b.Title = ?', 'bar')
->filterByStyle2('poetry')
->findOneOrCreate();
$this->assertTrue($book instanceof Book2, 'findOneOrCreate() returns an instance of the model when the request has no result');
$this->assertTrue($book->isNew(), 'findOneOrCreate() returns a new instance of the model when the request has no result');
$this->assertEquals('bar', $book->getTitle(), 'findOneOrCreate() returns a populated objects based on the conditions');
$this->assertEquals(['poetry'], $book->getStyle2(), 'findOneOrCreate() returns a populated objects based on the conditions');
$book = Book2Query::create('b')
->where('b.Title = ?', 'foobar')
->filterByStyle2('essay')
->findOneOrCreate();
$this->assertTrue($book instanceof Book2, 'findOneOrCreate() returns an instance of the model when the request has no result');
$this->assertTrue($book->isNew(), 'findOneOrCreate() returns a new instance of the model when the request has no result');
$this->assertEquals('foobar', $book->getTitle(), 'findOneOrCreate() returns a populated objects based on the conditions');
$this->assertEquals(['essay'], $book->getStyle2(), 'findOneOrCreate() returns a populated objects based on the conditions');
$book = Book2Query::create('b')
->where('b.Style2 = ?', ['novel', 'essay'])
->findOneOrCreate();
$this->assertTrue($book instanceof Book2, 'findOneOrCreate() returns an instance of the model when the request has no result');
$this->assertTrue($book->isNew(), 'findOneOrCreate() returns a new instance of the model when the request has no result');
$this->assertEquals(['novel', 'essay'], $book->getStyle2(), 'findOneOrCreate() returns a populated objects based on the conditions');
}
/**
* @return void
*/
public function testFindOneOrCreateWithArrays()
{
Book2Query::create()->deleteAll();
$book = Book2Query::create('b')
->filterByTag('russian')
->findOneOrCreate();
$this->assertTrue($book instanceof Book2, 'findOneOrCreate() returns an instance of the model when the request has no result');
$this->assertTrue($book->isNew(), 'findOneOrCreate() returns a new instance of the model when the request has no result');
$this->assertTrue(is_array($book->getTags()), 'findOneOrCreate() returns a populated objects based on the conditions');
$this->assertSame(['russian'], $book->getTags(), 'findOneOrCreate() returns a populated objects based on the conditions');
$book = Book2Query::create('b')
->filterByTags(['poetry'])
->findOneOrCreate();
$this->assertTrue($book instanceof Book2, 'findOneOrCreate() returns an instance of the model when the request has no result');
$this->assertTrue($book->isNew(), 'findOneOrCreate() returns a new instance of the model when the request has no result');
$this->assertTrue(is_array($book->getTags()), 'findOneOrCreate() returns a populated objects based on the conditions');
$this->assertSame(['poetry'], $book->getTags(), 'findOneOrCreate() returns a populated objects based on the conditions');
}
/**
* @return void
*/
public function testFindPkSimpleKey()
{
BookstoreDataPopulator::depopulate();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$book = $c->findPk(765432);
$this->assertNull($book, 'findPk() returns null when the primary key is not found');
BookstoreDataPopulator::populate();
// retrieve the test data
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$testBook = $c->findOne();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$book = $c->findPk($testBook->getId());
$this->assertEquals($testBook, $book, 'findPk() returns a model object corresponding to the pk');
}
/**
* @return void
*/
public function testFindPksSimpleKey()
{
BookstoreDataPopulator::depopulate();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$books = $c->findPks([765432, 434535]);
$this->assertTrue($books instanceof Collection, 'findPks() returns a Collection');
$this->assertEquals(0, count($books), 'findPks() returns an empty collection when the primary keys are not found');
BookstoreDataPopulator::populate();
// retrieve the test data
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$testBooks = $c->find();
$testBook1 = $testBooks->pop();
$testBook2 = $testBooks->pop();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$books = $c->findPks([$testBook1->getId(), $testBook2->getId()]);
$this->assertEquals([$testBook2, $testBook1], $books->getData(), 'findPks() returns an array of model objects corresponding to the pks');
}
/**
* @return void
*/
public function testFindPkCompositeKey()
{
BookstoreDataPopulator::depopulate();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\BookListRel');
$bookListRel = $c->findPk([1, 2]);
$this->assertNull($bookListRel, 'findPk() returns null when the composite primary key is not found');
Propel::enableInstancePooling();
BookstoreDataPopulator::populate();
// save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$books = $c->find();
foreach ($books as $book) {
$book->save();
}
// retrieve the test data
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\BookListRel');
$bookListRelTest = $c->findOne();
$pk = $bookListRelTest->getPrimaryKey();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\BookListRel');
$bookListRel = $c->findPk($pk);
$this->assertEquals($bookListRelTest, $bookListRel, 'findPk() can find objects with composite primary keys');
}
/**
* @return void
*/
public function testFindPksCompositeKey()
{
$this->expectException(PropelException::class);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\BookListRel');
$bookListRel = $c->findPks([[1, 2]]);
}
/**
* @return void
*/
public function testFindBy()
{
try {
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$books = $c->findBy('Foo', 'Bar');
$this->fail('findBy() throws an exception when called on an unknown column name');
} catch (UnknownColumnException $e) {
$this->assertTrue(true, 'findBy() throws an exception when called on an unknown column name');
}
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$books = $c->findBy('Title', 'Don Juan', $con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE book.title='Don Juan'");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findBy() adds simple column conditions');
$this->assertTrue($books instanceof Collection, 'findBy() issues a find()');
$this->assertEquals(1, count($books), 'findBy() adds simple column conditions');
$book = $books->shift();
$this->assertTrue($book instanceof Book, 'findBy() returns an array of Model objects by default');
$this->assertEquals('Don Juan', $book->getTitle(), 'findBy() returns the model objects matching the query');
}
/**
* @return void
*/
public function testFindByArray()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$books = $c->findByArray(['Title' => 'Don Juan', 'ISBN' => 12345], $con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE book.title='Don Juan' AND book.isbn=12345");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findByArray() adds multiple column conditions');
}
/**
* @return void
*/
public function testFindOneBy()
{
try {
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$book = $c->findOneBy('Foo', 'Bar');
$this->fail('findOneBy() throws an exception when called on an unknown column name');
} catch (UnknownColumnException $e) {
$this->assertTrue(true, 'findOneBy() throws an exception when called on an unknown column name');
}
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$book = $c->findOneBy('Title', 'Don Juan', $con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE book.title='Don Juan' LIMIT 1");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findOneBy() adds simple column conditions');
$this->assertTrue($book instanceof Book, 'findOneBy() returns a Model object by default');
$this->assertEquals('Don Juan', $book->getTitle(), 'findOneBy() returns the model object matching the query');
}
/**
* @return void
*/
public function testFindOneByArray()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$book = $c->findOneByArray(['Title' => 'Don Juan', 'ISBN' => 12345], $con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE book.title='Don Juan' AND book.isbn=12345 LIMIT 1");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findOneBy() adds multiple column conditions');
}
/**
* @return void
*/
public function testGetIteratorReturnsATraversable()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$this->assertInstanceOf('Traversable', $c->getIterator());
}
/**
* @return void
*/
public function testGetIteratorAllowsTraversingQueryObjects()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$nbResults = 0;
foreach ($c as $book) {
$nbResults++;
}
$this->assertEquals(4, $nbResults);
}
/**
* @return void
*/
public function testGetIteratorReturnsATraversableWithArrayFormatter()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$this->assertInstanceOf('Traversable', $c->getIterator());
}
/**
* @return void
*/
public function testGetIteratorAllowsTraversingQueryObjectsWithArrayFormatter()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setFormatter(ModelCriteria::FORMAT_ARRAY);
$nbResults = 0;
foreach ($c as $book) {
$nbResults++;
}
$this->assertEquals(4, $nbResults);
}
/**
* @return void
*/
public function testGetIteratorReturnsATraversableWithOnDemandFormatter()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND);
$it = $c->getIterator();
$this->assertInstanceOf('Traversable', $it);
$it->closeCursor();
}
/**
* @return void
*/
public function testGetIteratorAllowsTraversingQueryObjectsWithOnDemandFormatter()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND);
$nbResults = 0;
foreach ($c as $book) {
$nbResults++;
}
$this->assertEquals(4, $nbResults);
}
/**
* @return void
*/
public function testGetIteratorReturnsATraversableWithStatementFormatter()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setFormatter(ModelCriteria::FORMAT_STATEMENT);
$this->assertInstanceOf('Traversable', $c->getIterator());
}
/**
* @return void
*/
public function testGetIteratorAllowsTraversingQueryObjectsWithStatementFormatter()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setFormatter(ModelCriteria::FORMAT_STATEMENT);
$nbResults = 0;
foreach ($c as $book) {
$nbResults++;
}
$this->assertEquals(4, $nbResults);
}
/**
* @return void
*/
public function testGetIteratorReturnsATraversableWithSimpleArrayFormatter()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->select('Id');
$this->assertInstanceOf('Traversable', $c->getIterator());
}
/**
* @return void
*/
public function testGetIteratorAllowsTraversingQueryObjectsWithSimpleArrayFormatter()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->select('Id');
$nbResults = 0;
foreach ($c as $book) {
$nbResults++;
}
$this->assertEquals(4, $nbResults);
}
/**
* @return void
*/
public function testCount()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('b.Title = ?', 'foo');
$nbBooks = $c->count();
$this->assertTrue(is_int($nbBooks), 'count() returns an integer');
$this->assertEquals(0, $nbBooks, 'count() returns 0 when the query returns no result');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->join('b.Author a');
$c->where('a.FirstName = ?', 'Neal');
$nbBooks = $c->count();
$this->assertTrue(is_int($nbBooks), 'count() returns an integer');
$this->assertEquals(1, $nbBooks, 'count() returns the number of results in the query');
}
/**
* @return void
*/
public function testExists()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('b.Title = ?', 'foo');
$booksExists = $c->exists();
$this->assertFalse($booksExists, 'exists() returns false when there are are matching results');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->join('b.Author a');
$c->where('a.FirstName = ?', 'Neal');
$booksExists = $c->exists();
$this->assertTrue($booksExists, 'exists() returns true when there are matching results');
}
/**
* @return void
*/
public function testPaginate()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->join('b.Author a');
$c->where('a.FirstName = ?', 'Neal');
$books = $c->paginate(1, 5);
$this->assertTrue($books instanceof PropelModelPager, 'paginate() returns a PropelModelPager');
$this->assertEquals(1, count($books), 'paginate() returns a countable pager with the correct count');
foreach ($books as $book) {
$this->assertEquals('Neal', $book->getAuthor()->getFirstName(), 'paginate() returns an iterable pager');
}
}
/**
* @return void
*/
public function testDelete()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
try {
$nbBooks = $c->delete();
$this->fail('delete() throws an exception when called on an empty Criteria');
} catch (PropelException $e) {
$this->assertTrue(true, 'delete() throws an exception when called on an empty Criteria');
}
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('b.Title = ?', 'foo');
$nbBooks = $c->delete();
$this->assertTrue(is_int($nbBooks), 'delete() returns an integer');
$this->assertEquals(0, $nbBooks, 'delete() returns 0 when the query deleted no rows');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('b.Title = ?', 'Don Juan');
$nbBooks = $c->delete();
$this->assertTrue(is_int($nbBooks), 'delete() returns an integer');
$this->assertEquals(1, $nbBooks, 'delete() returns the number of the deleted rows');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$nbBooks = $c->count();
$this->assertEquals(3, $nbBooks, 'delete() deletes rows in the database');
}
/**
* @return void
*/
public function testDeleteUsingTableAlias()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setModelAlias('b', false);
$c->where('b.Title = ?', 'foo');
$c->delete();
$expectedSQL = $this->getSql("DELETE FROM book WHERE book.title = 'foo'");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'delete() also works on tables with table alias');
if ($this->runningOnMySQL() || $this->runningOnPostgreSQL()) {
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setModelAlias('b', true);
$c->where('b.Title = ?', 'foo');
$c->delete();
if (!$this->runningOnMySQL()) {
$expectedSQL = $this->getSql("DELETE FROM book AS b WHERE b.title = 'foo'");
} else {
$expectedSQL = $this->getSql("DELETE b FROM book AS b WHERE b.title = 'foo'");
}
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'delete() also works on tables with true table alias');
}
}
/**
* @return void
*/
public function testDeleteAll()
{
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$nbBooks = $c->deleteAll();
$this->assertTrue(is_int($nbBooks), 'deleteAll() returns an integer');
$this->assertEquals(4, $nbBooks, 'deleteAll() returns the number of deleted rows');
BookstoreDataPopulator::depopulate();
BookstoreDataPopulator::populate();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('b.Title = ?', 'Don Juan');
$nbBooks = $c->deleteAll();
$this->assertEquals(4, $nbBooks, 'deleteAll() ignores conditions on the criteria');
}
/**
* @return void
*/
public function testUpdate()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
BookstoreDataPopulator::depopulate($con);
BookstoreDataPopulator::populate($con);
$count = $con->getQueryCount();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$nbBooks = $c->update(['Title' => 'foo'], $con);
$this->assertEquals(4, $nbBooks, 'update() returns the number of updated rows');
$this->assertEquals($count + 1, $con->getQueryCount(), 'update() updates all the objects in one query by default');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('b.Title = ?', 'foo');
$nbBooks = $c->count();
$this->assertEquals(4, $nbBooks, 'update() updates all records by default');
BookstoreDataPopulator::depopulate($con);
BookstoreDataPopulator::populate($con);
$count = $con->getQueryCount();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('b.Title = ?', 'Don Juan');
$nbBooks = $c->update(['ISBN' => '3456'], $con);
$this->assertEquals(1, $nbBooks, 'update() updates only the records matching the criteria');
$this->assertEquals($count + 1, $con->getQueryCount(), 'update() updates all the objects in one query by default');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('b.Title = ?', 'Don Juan');
$book = $c->findOne();
$this->assertEquals('3456', $book->getISBN(), 'update() updates only the records matching the criteria');
}
/**
* @return void
*/
public function testUpdateUsingTableAlias()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setModelAlias('b', false);
$c->where('b.Title = ?', 'foo');
$c->update(['Title' => 'foo2'], $con);
$expectedSQL = $this->getSql("UPDATE book SET title='foo2' WHERE book.title = 'foo'");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'update() also works on tables with table alias');
if ($this->runningOnMySQL() || $this->runningOnPostgreSQL()) {
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setModelAlias('b', true);
$c->where('b.Title = ?', 'foo');
$c->update(['Title' => 'foo2'], $con);
$expectedSQL = $this->getSql("UPDATE book b SET title='foo2' WHERE b.title = 'foo'");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'update() also works on tables with true table alias');
}
}
/**
* @return void
*/
public function testUpdateOneByOne()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
BookstoreDataPopulator::depopulate($con);
BookstoreDataPopulator::populate($con);
// save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$books = $c->find();
foreach ($books as $book) {
$book->save();
}
$count = $con->getQueryCount();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$nbBooks = $c->update(['Title' => 'foo'], $con, true);
$this->assertEquals(4, $nbBooks, 'update() returns the number of updated rows');
$this->assertEquals($count + 1 + 4, $con->getQueryCount(), 'update() updates the objects one by one when called with true as last parameter');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('b.Title = ?', 'foo');
$nbBooks = $c->count();
$this->assertEquals(4, $nbBooks, 'update() updates all records by default');
BookstoreDataPopulator::depopulate($con);
BookstoreDataPopulator::populate($con);
// save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$books = $c->find();
foreach ($books as $book) {
$book->save();
}
$count = $con->getQueryCount();
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('b.Title = ?', 'Don Juan');
$nbBooks = $c->update(['ISBN' => '3456'], $con, true);
$this->assertEquals(1, $nbBooks, 'update() updates only the records matching the criteria');
$this->assertEquals($count + 1 + 1, $con->getQueryCount(), 'update() updates the objects one by one when called with true as last parameter');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->where('b.Title = ?', 'Don Juan');
$book = $c->findOne();
$this->assertEquals('3456', $book->getISBN(), 'update() updates only the records matching the criteria');
}
public static function conditionsForTestGetRelationName()
{
return [
['Author', 'Author'],
['Book.Author', 'Author'],
['Author.Book', 'Book'],
['Book.Author a', 'a'],
];
}
/**
* @dataProvider conditionsForTestGetRelationName
*
* @return void
*/
public function testGetRelationName($relation, $relationName)
{
$this->assertEquals($relationName, ModelCriteria::getrelationName($relation));
}
/**
* @return void
*/
public function testMagicJoin()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->leftJoin('b.Author a');
$c->where('a.FirstName = ?', 'Leo');
$books = $c->findOne($con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book LEFT JOIN author a ON (book.author_id=a.id) WHERE a.first_name = 'Leo' LIMIT 1");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'leftJoin($x) is turned into join($x, Criteria::LEFT_JOIN)');
$books = BookQuery::create()
->leftJoinAuthor('a')
->where('a.FirstName = ?', 'Leo')
->findOne($con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book LEFT JOIN author a ON (book.author_id=a.id) WHERE a.first_name = 'Leo' LIMIT 1");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'leftJoinX() is turned into join($x, Criteria::LEFT_JOIN)');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->innerJoin('b.Author a');
$c->where('a.FirstName = ?', 'Leo');
$books = $c->findOne($con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book INNER JOIN author a ON (book.author_id=a.id) WHERE a.first_name = 'Leo' LIMIT 1");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'innerJoin($x) is turned into join($x, Criteria::INNER_JOIN)');
$books = BookQuery::create()
->innerJoinAuthor('a')
->where('a.FirstName = ?', 'Leo')
->findOne($con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book INNER JOIN author a ON (book.author_id=a.id) WHERE a.first_name = 'Leo' LIMIT 1");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'innerJoinX() is turned into join($x, Criteria::INNER_JOIN)');
if (!$this->runningOnSQLite()) {
//SQLITE: SQLSTATE[HY000]: General error: 1 RIGHT and FULL OUTER JOINs are not currently supported
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->rightJoin('b.Author a');
$c->where('a.FirstName = ?', 'Leo');
$books = $c->findOne($con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book RIGHT JOIN author a ON (book.author_id=a.id) WHERE a.first_name = 'Leo' LIMIT 1");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'rightJoin($x) is turned into join($x, Criteria::RIGHT_JOIN)');
$books = BookQuery::create()
->rightJoinAuthor('a')
->where('a.FirstName = ?', 'Leo')
->findOne($con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book RIGHT JOIN author a ON (book.author_id=a.id) WHERE a.first_name = 'Leo' LIMIT 1");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'rightJoinX() is turned into join($x, Criteria::RIGHT_JOIN)');
$books = BookQuery::create()
->leftJoinAuthor()
->where('Author.FirstName = ?', 'Leo')
->findOne($con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book LEFT JOIN author ON (book.author_id=author.id) WHERE author.first_name = 'Leo' LIMIT 1");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'leftJoinX() is turned into join($x, Criteria::LEFT_JOIN)');
}
}
/**
* @return void
*/
public function testMagicJoinWith()
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->leftJoinWith('Propel\Tests\Bookstore\Book.Author a');
$expectedColumns = [
BookTableMap::COL_ID,
BookTableMap::COL_TITLE,
BookTableMap::COL_ISBN,
BookTableMap::COL_PRICE,
BookTableMap::COL_PUBLISHER_ID,
BookTableMap::COL_AUTHOR_ID,
'a.id',
'a.first_name',
'a.last_name',
'a.email',
'a.age',
];
$this->assertEquals($expectedColumns, $c->getSelectColumns(), 'leftJoinWith() adds the join with the alias');
$joins = $c->getJoins();
$join = $joins['a'];
$this->assertEquals(Criteria::LEFT_JOIN, $join->getJoinType(), 'leftJoinWith() adds a LEFT JOIN');
}
/**
* @return void
*/
public function testMagicJoinWithRelation()
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->joinWithAuthor();
$expectedColumns = [
BookTableMap::COL_ID,
BookTableMap::COL_TITLE,
BookTableMap::COL_ISBN,
BookTableMap::COL_PRICE,
BookTableMap::COL_PUBLISHER_ID,
BookTableMap::COL_AUTHOR_ID,
AuthorTableMap::COL_ID,
AuthorTableMap::COL_FIRST_NAME,
AuthorTableMap::COL_LAST_NAME,
AuthorTableMap::COL_EMAIL,
AuthorTableMap::COL_AGE,
];
$this->assertEquals($expectedColumns, $c->getSelectColumns(), 'joinWithXXX() adds the join with the XXX relation');
$joins = $c->getJoins();
$join = $joins['Author'];
$this->assertEquals(Criteria::INNER_JOIN, $join->getJoinType(), 'joinWithXXX() adds an INNER JOIN');
}
/**
* @return void
*/
public function testMagicJoinWithTypeAndRelation()
{
$c = new TestableModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->leftJoinWithAuthor();
$expectedColumns = [
BookTableMap::COL_ID,
BookTableMap::COL_TITLE,
BookTableMap::COL_ISBN,
BookTableMap::COL_PRICE,
BookTableMap::COL_PUBLISHER_ID,
BookTableMap::COL_AUTHOR_ID,
AuthorTableMap::COL_ID,
AuthorTableMap::COL_FIRST_NAME,
AuthorTableMap::COL_LAST_NAME,
AuthorTableMap::COL_EMAIL,
AuthorTableMap::COL_AGE,
];
$this->assertEquals($expectedColumns, $c->getSelectColumns(), 'leftJoinWithXXX() adds the join with the XXX relation');
$joins = $c->getJoins();
$join = $joins['Author'];
$this->assertEquals(Criteria::LEFT_JOIN, $join->getJoinType(), 'leftJoinWithXXX() adds an INNER JOIN');
}
/**
* @return void
*/
public function testMagicFind()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$books = $c->findByTitle('Don Juan');
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE book.title='Don Juan'");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findByXXX($value) is turned into findBy(XXX, $value)');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$books = $c->findByTitleAndISBN('Don Juan', 1234);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE book.title='Don Juan' AND book.isbn=1234");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findByXXXAndYYY($value) is turned into findBy(array(XXX,YYY), $value)');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$book = $c->findOneByTitle('Don Juan');
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE book.title='Don Juan' LIMIT 1");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findOneByXXX($value) is turned into findOneBy(XXX, $value)');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$book = $c->findOneByTitleAndISBN('Don Juan', 1234);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE book.title='Don Juan' AND book.isbn=1234 LIMIT 1");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findOneByXXX($value) is turned into findOneBy(XXX, $value)');
}
/**
* @return void
*/
public function testMagicFilterBy()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$books = $c->filterByTitle('Don Juan')->find($con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE book.title='Don Juan'");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'filterByXXX($value) is turned into filterBy(XXX, $value)');
}
/**
* @return void
*/
public function testMagicOrderBy()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$books = $c->orderByTitle()->find($con);
$expectedSQL = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book ORDER BY book.title ASC');
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'orderByXXX() is turned into orderBy(XXX)');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$books = $c->orderByTitle(Criteria::DESC)->find($con);
$expectedSQL = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book ORDER BY book.title DESC');
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'orderByXXX($direction) is turned into orderBy(XXX, $direction)');
}
/**
* @return void
*/
public function testMagicGroupBy()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$books = $c->groupByTitle()->find($con);
if ($this->isDb('pgsql')) {
$expectedSQL = 'SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book GROUP BY book.title,book.id,book.isbn,book.price,book.publisher_id,book.author_id';
} else {
$expectedSQL = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book GROUP BY book.title');
}
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'groupByXXX() is turned into groupBy(XXX)');
}
/**
* @return void
*/
public function testUseQuery()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->thisIsMe = true;
$c->where('b.Title = ?', 'foo');
$c->setOffset(10);
$c->leftJoin('b.Author');
$c2 = $c->useQuery('Author');
$this->assertTrue($c2 instanceof AuthorQuery, 'useQuery() returns a secondary Criteria');
$this->assertEquals($c, $c2->getPrimaryCriteria(), 'useQuery() sets the primary Criteria os the secondary Criteria');
$c2->where('Author.FirstName = ?', 'john');
$c2->limit(5);
$c = $c2->endUse();
$this->assertTrue($c->thisIsMe, 'endUse() returns the Primary Criteria');
$this->assertEquals('Propel\Tests\Bookstore\Book', $c->getModelName(), 'endUse() returns the Primary Criteria');
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c->find($con);
if (!$this->runningOnMySQL()) {
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book LEFT JOIN author ON (book.author_id=author.id) WHERE book.title = 'foo' AND author.first_name = 'john' LIMIT 5 OFFSET 10");
} else {
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book LEFT JOIN author ON (book.author_id=author.id) WHERE book.title = 'foo' AND author.first_name = 'john' LIMIT 10, 5");
}
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'useQuery() and endUse() allow to merge a secondary criteria');
}
/**
* @return void
*/
public function testUseQueryAlias()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->thisIsMe = true;
$c->where('b.Title = ?', 'foo');
$c->setOffset(10);
$c->leftJoin('b.Author a');
$c2 = $c->useQuery('a');
$this->assertTrue($c2 instanceof AuthorQuery, 'useQuery() returns a secondary Criteria');
$this->assertEquals($c, $c2->getPrimaryCriteria(), 'useQuery() sets the primary Criteria os the secondary Criteria');
$this->assertEquals(['a' => 'author'], $c2->getAliases(), 'useQuery() sets the secondary Criteria alias correctly');
$c2->where('a.FirstName = ?', 'john');
$c2->limit(5);
$c = $c2->endUse();
$this->assertTrue($c->thisIsMe, 'endUse() returns the Primary Criteria');
$this->assertEquals('Propel\Tests\Bookstore\Book', $c->getModelName(), 'endUse() returns the Primary Criteria');
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c->find($con);
if (!$this->runningOnMySQL()) {
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book LEFT JOIN author a ON (book.author_id=a.id) WHERE book.title = 'foo' AND a.first_name = 'john' LIMIT 5 OFFSET 10");
} else {
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book LEFT JOIN author a ON (book.author_id=a.id) WHERE book.title = 'foo' AND a.first_name = 'john' LIMIT 10, 5");
}
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'useQuery() and endUse() allow to merge a secondary criteria');
}
/**
* @return void
*/
public function testUseQueryCustomClass()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c->thisIsMe = true;
$c->where('b.Title = ?', 'foo');
$c->setLimit(10);
$c->leftJoin('b.Author a');
$c2 = $c->useQuery('a', 'Propel\Tests\Runtime\ActiveQuery\ModelCriteriaForUseQuery');
$this->assertTrue($c2 instanceof ModelCriteriaForUseQuery, 'useQuery() returns a secondary Criteria with the custom class');
$c2->withNoName();
$c = $c2->endUse();
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c->find($con);
$expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book LEFT JOIN author a ON (book.author_id=a.id) WHERE book.title = 'foo' AND a.first_name IS NOT NULL AND a.last_name IS NOT NULL LIMIT 10");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'useQuery() and endUse() allow to merge a custom secondary criteria');
}
/**
* @return void
*/
public function testUseQueryJoinWithFind()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Review');
$c->joinWith('Book');
$c2 = $c->useQuery('Book');
$joins = $c->getJoins();
$this->assertEquals($c->getPreviousJoin(), null, 'The default value for previousJoin remains null');
$this->assertEquals($c2->getPreviousJoin(), $joins['Book'], 'useQuery() sets the previousJoin');
// join Book with Author, which is possible since previousJoin is set, which makes resolving of relations possible during hydration
$c2->joinWith('Author');
$c = $c2->endUse();
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c->find($con);
$expectedSQL = $this->getSql('SELECT review.id, review.reviewed_by, review.review_date, review.recommended, review.status, review.book_id, book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id, author.id, author.first_name, author.last_name, author.email, author.age FROM review INNER JOIN book ON (review.book_id=book.id) INNER JOIN author ON (book.author_id=author.id)');
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'useQuery() and joinWith() can be used together and form a correct query');
}
/**
* @return void
*/
public function testUseQueryCustomRelationPhpName()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\BookstoreContest');
$c->leftJoin('Propel\Tests\Bookstore\BookstoreContest.Work');
$c2 = $c->useQuery('Work');
$this->assertTrue($c2 instanceof BookQuery, 'useQuery() returns a secondary Criteria');
$this->assertEquals($c, $c2->getPrimaryCriteria(), 'useQuery() sets the primary Criteria os the secondary Criteria');
//$this->assertEquals(array('a' => 'author'), $c2->getAliases(), 'useQuery() sets the secondary Criteria alias correctly');
$c2->where('Work.Title = ?', 'War And Peace');
$c = $c2->endUse();
$this->assertEquals('Propel\Tests\Bookstore\BookstoreContest', $c->getModelName(), 'endUse() returns the Primary Criteria');
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c->find($con);
$expectedSQL = $this->getSql("SELECT bookstore_contest.bookstore_id, bookstore_contest.contest_id, bookstore_contest.prize_book_id FROM bookstore_contest LEFT JOIN book ON (bookstore_contest.prize_book_id=book.id) WHERE book.title = 'War And Peace'");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'useQuery() and endUse() allow to merge a secondary criteria');
}
/**
* @return void
*/
public function testUseQueryCustomRelationPhpNameAndAlias()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\BookstoreContest');
$c->leftJoin('Propel\Tests\Bookstore\BookstoreContest.Work w');
$c2 = $c->useQuery('w');
$this->assertTrue($c2 instanceof BookQuery, 'useQuery() returns a secondary Criteria');
$this->assertEquals($c, $c2->getPrimaryCriteria(), 'useQuery() sets the primary Criteria os the secondary Criteria');
$this->assertEquals(['w' => 'book'], $c2->getAliases(), 'useQuery() sets the secondary Criteria alias correctly');
$c2->where('w.Title = ?', 'War And Peace');
$c = $c2->endUse();
$this->assertEquals('Propel\Tests\Bookstore\BookstoreContest', $c->getModelName(), 'endUse() returns the Primary Criteria');
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c->find($con);
$expectedSQL = $this->getSql("SELECT bookstore_contest.bookstore_id, bookstore_contest.contest_id, bookstore_contest.prize_book_id FROM bookstore_contest LEFT JOIN book w ON (bookstore_contest.prize_book_id=w.id) WHERE w.title = 'War And Peace'");
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'useQuery() and endUse() allow to merge a secondary criteria');
}
/**
* @return void
*/
public function testMergeWithJoins()
{
$c1 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c1->leftJoin('b.Author a');
$c2 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Author');
$c1->mergeWith($c2);
$joins = $c1->getJoins();
$this->assertEquals(1, count($joins), 'mergeWith() does not remove an existing join');
$this->assertEquals('LEFT JOIN author a ON (book.author_id=a.id)', $joins['a']->toString(), 'mergeWith() does not remove an existing join');
$c1 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c2 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c2->leftJoin('b.Author a');
$c1->mergeWith($c2);
$joins = $c1->getJoins();
$this->assertEquals(1, count($joins), 'mergeWith() merge joins to an empty join');
$this->assertEquals('LEFT JOIN author a ON (book.author_id=a.id)', $joins['a']->toString(), 'mergeWith() merge joins to an empty join');
$c1 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c1->leftJoin('b.Author a');
$c2 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c2->innerJoin('b.Publisher p');
$c1->mergeWith($c2);
$joins = $c1->getJoins();
$this->assertEquals(2, count($joins), 'mergeWith() merge joins to an existing join');
$this->assertEquals('LEFT JOIN author a ON (book.author_id=a.id)', $joins['a']->toString(), 'mergeWith() merge joins to an empty join');
$this->assertEquals('INNER JOIN publisher p ON (book.publisher_id=p.id)', $joins['p']->toString(), 'mergeWith() merge joins to an empty join');
}
/**
* @return void
*/
public function testMergeWithWiths()
{
$c1 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c1->leftJoinWith('b.Author a');
$c2 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Author');
$c1->mergeWith($c2);
$this->assertCount(1, array_filter($c1->getSelectColumns(), function($v) { return BookTableMap::COL_ID == $v; }), '$c1 criteria has selected Book columns twice');
$with = $c1->getWith();
$this->assertEquals(1, count($with), 'mergeWith() does not remove an existing join');
$this->assertEquals('modelName: Propel\Tests\Bookstore\Author, relationName: Author, relationMethod: setAuthor, leftPhpName: , rightPhpName: a', $with['a']->__toString(), 'mergeWith() does not remove an existing join');
$c1 = new ModelCriteria('bookstore', '\Propel\Tests\Bookstore\Book', 'b');
$c1->leftJoinWith('b.Author a');
$c2 = new ModelCriteria('bookstore', '\Propel\Tests\Bookstore\Author');
$c1->mergeWith($c2);
$this->assertCount(1, array_filter($c1->getSelectColumns(), function($v) { return BookTableMap::COL_ID == $v; }), '$c1 criteria has selected Book columns twice');
$with = $c1->getWith();
$this->assertEquals(1, count($with), 'mergeWith() does not remove an existing join');
$this->assertEquals('modelName: Propel\Tests\Bookstore\Author, relationName: Author, relationMethod: setAuthor, leftPhpName: , rightPhpName: a', $with['a']->__toString(), 'mergeWith() does not remove an existing join');
$c1 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c2 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c2->leftJoinWith('b.Author a');
$c1->mergeWith($c2);
$this->assertCount(1, array_filter($c1->getSelectColumns(), function($v) { return BookTableMap::COL_ID == $v; }), '$c1 criteria has selected Book columns twice');
$with = $c1->getWith();
$this->assertEquals(1, count($with), 'mergeWith() merge joins to an empty join');
$this->assertEquals('modelName: Propel\Tests\Bookstore\Author, relationName: Author, relationMethod: setAuthor, leftPhpName: , rightPhpName: a', $with['a']->__toString(), 'mergeWith() merge joins to an empty join');
$c1 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c1->leftJoinWith('b.Author a');
$c2 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c2->innerJoinWith('b.Publisher p');
$c1->mergeWith($c2);
$this->assertCount(1, array_filter($c1->getSelectColumns(), function($v) { return BookTableMap::COL_ID == $v; }), '$c1 criteria has selected Book columns twice');
$with = $c1->getWith();
$this->assertEquals(2, count($with), 'mergeWith() merge joins to an existing join');
$this->assertEquals('modelName: Propel\Tests\Bookstore\Author, relationName: Author, relationMethod: setAuthor, leftPhpName: , rightPhpName: a', $with['a']->__toString(), 'mergeWith() merge joins to an empty join');
$this->assertEquals('modelName: Propel\Tests\Bookstore\Publisher, relationName: Publisher, relationMethod: setPublisher, leftPhpName: , rightPhpName: p', $with['p']->__toString(), 'mergeWith() merge joins to an empty join');
}
/**
* @return void
*/
public function testGetAliasedColName()
{
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$this->assertEquals(BookTableMap::COL_TITLE, $c->getAliasedColName(BookTableMap::COL_TITLE), 'getAliasedColName() returns the input when the table has no alias');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setModelAlias('foo');
$this->assertEquals(BookTableMap::COL_TITLE, $c->getAliasedColName(BookTableMap::COL_TITLE), 'getAliasedColName() returns the input when the table has a query alias');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c->setModelAlias('foo', true);
$this->assertEquals('foo.title', $c->getAliasedColName(BookTableMap::COL_TITLE), 'getAliasedColName() returns the column name with table alias when the table has a true alias');
}
/**
* @return void
*/
public function testAddUsingAliasNoAlias()
{
$c1 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c1->addUsingAlias(BookTableMap::COL_TITLE, 'foo');
$c2 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c2->add(BookTableMap::COL_TITLE, 'foo');
$this->assertEquals($c2, $c1, 'addUsingalias() translates to add() when the table has no alias');
}
/**
* @return void
*/
public function testAddUsingAliasQueryAlias()
{
$c1 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c1->addUsingAlias(BookTableMap::COL_TITLE, 'foo');
$c2 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book', 'b');
$c2->add(BookTableMap::COL_TITLE, 'foo');
$this->assertEquals($c2, $c1, 'addUsingalias() translates the colname using the table alias before calling add() when the table has a true alias');
}
/**
* @return void
*/
public function testAddUsingAliasTrueAlias()
{
$c1 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c1->setModelAlias('b', true);
$c1->addUsingAlias(BookTableMap::COL_TITLE, 'foo');
$c2 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c2->setModelAlias('b', true);
$c2->add('b.title', 'foo');
$this->assertEquals($c2, $c1, 'addUsingalias() translates to add() when the table has a true alias');
}
/**
* @return void
*/
public function testAddUsingAliasTwice()
{
$c1 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c1->addUsingAlias(BookTableMap::COL_TITLE, 'foo');
$c1->addUsingAlias(BookTableMap::COL_TITLE, 'bar');
$c2 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c2->add(BookTableMap::COL_TITLE, 'foo');
$c2->addAnd(BookTableMap::COL_TITLE, 'bar');
$this->assertEquals($c2, $c1, 'addUsingalias() translates to addAnd() when the table already has a condition on the column');
}
/**
* @return void
*/
public function testAddUsingAliasTrueAliasTwice()
{
$c1 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c1->setModelAlias('b', true);
$c1->addUsingAlias(BookTableMap::COL_TITLE, 'foo');
$c1->addUsingAlias(BookTableMap::COL_TITLE, 'bar');
$c2 = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$c2->setModelAlias('b', true);
$c2->add('b.title', 'foo');
$c2->addAnd('b.title', 'bar');
$this->assertEquals($c2, $c1, 'addUsingalias() translates to addAnd() when the table already has a condition on the column');
}
/**
* @return void
*/
public function testCloneCopiesConditions()
{
$bookQuery1 = BookQuery::create()
->filterByPrice(1);
$bookQuery2 = clone $bookQuery1;
$bookQuery2
->filterByPrice(2);
$params = [];
$sql = $bookQuery1->createSelectSql($params);
$expected = $this->getSql('SELECT FROM book WHERE book.price=:p1');
$this->assertEquals($expected, $sql, 'conditions applied on a cloned query don\'t get applied on the original query');
}
/**
* @return void
*/
public function testCloneCopiesFormatter()
{
$formatter1 = new ArrayFormatter();
$formatter1->test = false;
$bookQuery1 = BookQuery::create();
$bookQuery1->setFormatter($formatter1);
$bookQuery2 = clone $bookQuery1;
$formatter2 = $bookQuery2->getFormatter();
$this->assertFalse($formatter2->test);
$formatter2->test = true;
$this->assertFalse($formatter1->test);
}
/**
* @return void
*/
public function testCloneCopiesSelect()
{
$bookQuery1 = BookQuery::create();
$bookQuery1->select(['Id', 'Title']);
$bookQuery2 = clone $bookQuery1;
$bookQuery2->select(['ISBN', 'Price']);
$this->assertEquals(['Id', 'Title'], $bookQuery1->getSelect());
}
/**
* @return void
*/
public function testMagicFindByObject()
{
$con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Author');
$testAuthor = $c->findOne();
$q = BookQuery::create()
->findByAuthor($testAuthor);
$expectedSQL = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE book.author_id=' . $testAuthor->getId());
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findByXXX($value) is turned into findBy(XXX, $value)');
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Author');
$testAuthor = $c->findOne();
$q = BookQuery::create()
->findByAuthorAndISBN($testAuthor, 1234);
$expectedSQL = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE book.author_id=' . $testAuthor->getId() . ' AND book.isbn=1234');
$this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findByXXXAndYYY($value) is turned into findBy(array(XXX, YYY), $value)');
}
/**
* @return void
*/
public function testRequirePkReturnsModel()
{
// retrieve the test data
$c = new ModelCriteria('bookstore', 'Propel\Tests\Bookstore\Book');
$testBook = $c->findOne();
$book = BookQuery::create()->requirePk($testBook->getId());
$this->assertInstanceOf(BookTableMap::OM_CLASS, $book);
}
/**
* @return void
*/
public function testRequirePkThrowsException()
{
$this->expectException(EntityNotFoundException::class);
BookQuery::create()->requirePk(-1337);
}
/**
* @return void
*/
public function testRequireOneReturnsModel()
{
$book = BookQuery::create()->orderByTitle()->requireOne();
$this->assertInstanceOf(BookTableMap::OM_CLASS, $book);
}
/**
* @return void
*/
public function testRequireOneThrowsException()
{
$this->expectException(EntityNotFoundException::class);
BookQuery::create()->filterByTitle('Not existing title')->requireOne();
}
/**
* @return void
*/
public function testMagicRequireOneReturnsModel()
{
$book = BookQuery::create()->requireOneByTitle('Harry Potter and the Order of the Phoenix');
$this->assertInstanceOf(BookTableMap::OM_CLASS, $book);
}
/**
* @return void
*/
public function testMagicRequireOneThrowsException()
{
$this->expectException(EntityNotFoundException::class);
BookQuery::create()->requireOneById(-1337);
}
/**
* @return void
*/
public function testMagicRequireOneWithAndReturnsModel()
{
$book = BookQuery::create()->requireOneByIsbnAndTitle('043935806X', 'Harry Potter and the Order of the Phoenix');
$this->assertInstanceOf(BookTableMap::OM_CLASS, $book);
}
/**
* @return void
*/
public function testMagicRequireOneWithAndThrowsException()
{
$this->expectException(EntityNotFoundException::class);
BookQuery::create()->requireOneByTitleAndId('Not Existing Book', -1337);
}
/**
* @return void
*/
public function testJoinSelectColumn()
{
BookQuery::create()
->innerJoinAuthor()
->select(AuthorTableMap::COL_LAST_NAME)
->find();
}
}
| mit |
facelessuser/ColorHelper | lib/coloraide/spaces/hwb/css.py | 3881 | """HWB class."""
import re
from .. import hwb as base
from ... import parse
from ... import util
from ...util import MutableVector
from typing import Union, Optional, Tuple, Any, TYPE_CHECKING
if TYPE_CHECKING: # pragma: no cover
from ...color import Color
class HWB(base.HWB):
"""HWB class."""
DEF_VALUE = "hwb(0 0% 0% / 1)"
MATCH = re.compile(
r"""(?xi)
\bhwb\(\s*
(?:
# Space separated format
{angle}{space}{percent}{space}{percent}(?:{slash}(?:{percent}|{float}))? |
# comma separated format
{angle}{comma}{percent}{comma}{percent}(?:{comma}(?:{percent}|{float}))?
)
\s*\)
""".format(**parse.COLOR_PARTS)
)
def to_string(
self,
parent: 'Color',
*,
alpha: Optional[bool] = None,
precision: Optional[int] = None,
fit: Union[str, bool] = True,
none: bool = False,
**kwargs: Any
) -> str:
"""Convert to CSS."""
if precision is None:
precision = parent.PRECISION
options = kwargs
if options.get("color"):
return super().to_string(parent, alpha=alpha, precision=precision, fit=fit, none=none, **kwargs)
a = util.no_nan(self.alpha) if not none else self.alpha
alpha = alpha is not False and (alpha is True or a < 1.0 or util.is_nan(a))
method = None if not isinstance(fit, str) else fit
coords = parent.fit(method=method).coords() if fit else self.coords()
if not none:
coords = util.no_nans(coords)
if alpha:
template = "hwb({}, {}, {}, {})" if options.get("comma") else "hwb({} {} {} / {})"
return template.format(
util.fmt_float(coords[0], precision),
util.fmt_percent(coords[1] * 100, precision),
util.fmt_percent(coords[2] * 100, precision),
util.fmt_float(self.alpha, max(util.DEF_PREC, precision))
)
else:
template = "hwb({}, {}, {})" if options.get("comma") else "hwb({} {} {})"
return template.format(
util.fmt_float(coords[0], precision),
util.fmt_percent(coords[1] * 100, precision),
util.fmt_percent(coords[2] * 100, precision)
)
@classmethod
def translate_channel(cls, channel: int, value: str) -> float:
"""Translate channel string."""
if channel == 0:
return parse.norm_angle_channel(value)
elif channel in (1, 2):
return parse.norm_percent_channel(value, True)
elif channel == -1:
return parse.norm_alpha_channel(value)
else: # pragma: no cover
raise ValueError('{} is not a valid channel index'.format(channel))
@classmethod
def split_channels(cls, color: str) -> Tuple[MutableVector, float]:
"""Split channels."""
start = 4
channels = []
alpha = 1.0
for i, c in enumerate(parse.RE_CHAN_SPLIT.split(color[start:-1].strip()), 0):
c = c.lower()
if i <= 2:
channels.append(cls.translate_channel(i, c))
elif i == 3:
alpha = cls.translate_channel(-1, c)
return cls.null_adjust(channels, alpha)
@classmethod
def match(
cls,
string: str,
start: int = 0,
fullmatch: bool = True
) -> Optional[Tuple[Tuple[MutableVector, float], int]]:
"""Match a CSS color string."""
match = super().match(string, start, fullmatch)
if match is not None:
return match
m = cls.MATCH.match(string, start)
if m is not None and (not fullmatch or m.end(0) == len(string)):
return cls.split_channels(string[m.start(0):m.end(0)]), m.end(0)
return None
| mit |
Borodutch/hello-bot-telekit | helpers/bot.js | 808 | const config = require('../config');
class Bot {
checkDate(date, diff = 10800000) {
const now = new Date().valueOf();
const dateOf = new Date(date).valueOf();
return now - dateOf < diff;
}
isAdmin(id) {
return id === config.adminId;
}
async sendMessageWithDelay(api, message, chat_id) {
const action = !chat_id ? {
action: 'typing'
} : {
action: 'typing',
chat_id
};
let delay = 0;
if (message.text) {
const typeSpeed = 60/800;
if (message.text.length > 45) {
delay = 25*typeSpeed;
} else {
delay = message.text.length * typeSpeed;
}
}
await api.sendChatAction(action);
setTimeout(async () => {
await api.sendMessage(message);
}, delay * 1000)
}
}
module.exports = Bot;
| mit |
enkessler/cuke_cataloger | testing/rspec/spec/unique_test_case_tagger_unit_spec.rb | 2301 | require_relative '../../../environments/rspec_env'
RSpec.describe 'UniqueTestCaseTagger, Unit' do
clazz = CukeCataloger::UniqueTestCaseTagger
before(:each) do
@tagger = clazz.new
end
describe 'test tagging' do
it "can tag a suite's tests" do
expect(@tagger).to respond_to(:tag_tests)
end
it 'takes a directory, optional tag prefix, and an optional start index' do
expect(@tagger.method(:tag_tests).arity).to eq(-2)
end
end
describe 'data validation' do
it "can check the validity of a suite's test ids" do
expect(@tagger).to respond_to(:validate_test_ids)
end
it 'validates based on a directory, optional tag prefix, and optional row tagging flag' do
expect(@tagger.method(:validate_test_ids).arity).to eq(-2)
end
it 'returns validation results' do
path = CukeCataloger::FileHelper.create_directory
results = @tagger.validate_test_ids(path, '')
expect(results).to be_a_kind_of(Array)
end
end
describe 'test scanning' do
it 'can scan for tagged tests' do
expect(@tagger).to respond_to(:scan_for_tagged_tests)
end
it 'validates based on a directory, optional tag prefix, and optional column name' do
expect(@tagger.method(:scan_for_tagged_tests).arity).to eq(-2)
end
it 'returns scanning results' do
path = CukeCataloger::FileHelper.create_directory
results = @tagger.scan_for_tagged_tests(path, '')
expect(results).to be_a_kind_of(Array)
end
end
describe 'tag indexing' do
it 'can determine used test case indexes' do
expect(@tagger).to respond_to(:determine_known_ids)
end
it 'determines used indexes based on a directory, optional tag prefix, and optional column name' do
expect(@tagger.method(:determine_known_ids).arity).to eq(-2)
end
end
describe 'formatting' do
it 'has a tag location' do
expect(@tagger).to respond_to(:tag_location)
end
it 'can change its tag location' do
expect(@tagger).to respond_to(:tag_location=)
@tagger.tag_location = :some_flag_value
expect(@tagger.tag_location).to eq(:some_flag_value)
@tagger.tag_location = :some_other_flag_value
expect(@tagger.tag_location).to eq(:some_other_flag_value)
end
end
end
| mit |
RichardTMiles/CarbonPHP | tests/feature/UserTest.php | 4557 | <?php
/**
* Created by IntelliJ IDEA.
* User: rmiles
* Date: 6/26/2018
* Time: 3:21 PM
*/
declare(strict_types=1);
namespace Tests\Feature;
use CarbonPHP\Error\PublicAlert;
use CarbonPHP\Rest;
use CarbonPHP\Tables\Users;
final class UserTest extends Config
{
public array $user = [];
/**
* Ideally this is run with a fresh build. If not, the relation between create new users
* must depend on can be deleted. This is cyclic and can not be annotated.
* @throws PublicAlert
*/
public function setUp(): void /* The :void return type declaration that should be here would cause a BC issue */
{
parent::setUp();
$_SERVER['REQUEST_TIME'] = time();
$this->user = [];
Users::Get($this->user, null, [
Rest::WHERE => [
Users::USER_USERNAME => Config::ADMIN_USERNAME
]
]);
}
/**
* @return string
* @throws PublicAlert
*/
public function testUserCanBeCreated(): string
{
if (!empty($this->user)) {
$this->testUserCanBeDeleted();
}
$post = [
Users::USER_TYPE => 'Athlete',
Users::USER_IP => '127.0.0.1',
Users::USER_SPORT => 'GOLF',
Users::USER_EMAIL_CONFIRMED => 1,
Users::USER_USERNAME => Config::ADMIN_USERNAME,
Users::USER_PASSWORD => Config::ADMIN_PASSWORD,
Users::USER_EMAIL => '[email protected]',
Users::USER_FIRST_NAME => 'Richard',
Users::USER_LAST_NAME => 'Miles',
Users::USER_GENDER => 'Male'
];
self::assertIsString($id = Users::Post($post), 'No string ID was returned');
return $id;
}
/**
* @depends testUserCanBeCreated
*/
public function testUserCanBeRetrieved(): void
{
$this->user = [];
self::assertTrue(
Users::Get($this->user, null, [
Rest::WHERE => [
Users::USER_USERNAME => Config::ADMIN_USERNAME
],
Rest::PAGINATION => [
Rest::LIMIT => 1
]
]
));
self::assertIsArray($this->user);
self::assertArrayHasKey(
Users::COLUMNS[Users::USER_EMAIL],
$this->user);
}
/**
* @depends testUserCanBeRetrieved
*/
public function testUserCanBeUpdated(): void
{
self::assertTrue(
Users::Get($this->user, null, [
Rest::WHERE => [
Users::USER_USERNAME => Config::ADMIN_USERNAME
]
]
));
$this->user = $this->user[0];
self::assertTrue(
Users::Put($this->user,
$this->user[Users::COLUMNS[Users::USER_ID]],
[
Users::USER_FIRST_NAME => 'lil\'Rich'
]));
$this->user = [];
self::assertTrue(
Users::Get($this->user, null, [
Rest::WHERE => [
Users::USER_USERNAME => Config::ADMIN_USERNAME
],
Rest::PAGINATION => [
Rest::LIMIT => 1
]
]
));
self::assertEquals('lil\'Rich',
$this->user[Users::COLUMNS[Users::USER_FIRST_NAME]]);
}
/**
* @depends testUserCanBeRetrieved
*/
public function testUserCanBeDeleted(): void
{
global $json;
$this->user = [];
Users::Get($this->user, null, [
Rest::WHERE => [
Users::USER_USERNAME => Config::ADMIN_USERNAME
],
Rest::PAGINATION => [
Rest::LIMIT => 1
]
]);
self::assertNotEmpty($this->user,
'User (' . Config::ADMIN_USERNAME . ') does not appear to exist.');
self::assertTrue(
Users::Delete($this->user,
$this->user[Users::COLUMNS[Users::USER_ID]], [])
);
self::assertEmpty($this->user);
$this->user = [];
Users::Get($this->user, null, [
Rest::WHERE => [
Users::USER_USERNAME => Config::ADMIN_USERNAME
],
Rest::PAGINATION => [
Rest::LIMIT => 1
]
]);
self::assertEmpty($this->user, 'Failed asserting delete removed the user :: ' . json_encode($json));
}
} | mit |
lookout/oraculum-fastTable | docs/doc-filelist.js | 154 | var tree={"files":["LICENSE.md","README.md"],"dirs":{"src":{"files":["main.coffee"],"dirs":{"views":{"dirs":{"mixins":{"files":["fast-row.coffee"]}}}}}}}; | mit |
TrackerNetwork/DestinyStatus | destiny/DestinyPlatform.php | 5603 | <?php
namespace Destiny;
use App\Account;
use App\Enums\ActivityModeType;
use App\Enums\StatGroupType;
use Destiny\Definitions\Components\Character;
/**
* Class DestinyPlatform.
*/
class DestinyPlatform
{
/**
* @param $uri
* @param array $params
* @param null $cacheMinutes
* @param bool $salvageable
*
* @return DestinyRequest
*/
protected function destinyRequest($uri, $params = [], $cacheMinutes = null, $salvageable = true): DestinyRequest
{
return new DestinyRequest($uri, $params, $cacheMinutes, $salvageable);
}
/**
* @return DestinyRequest
*/
public function manifest(): DestinyRequest
{
return $this->destinyRequest('destiny2/manifest/', false);
}
/**
* @param $gamertag
*
* @return DestinyRequest
*/
public function searchDestinyPlayer(string $gamertag): DestinyRequest
{
$gamertag = rawurlencode(trim($gamertag));
return $this->destinyRequest("Destiny2/SearchDestinyPlayer/all/$gamertag/", CACHE_PLAYER, false);
}
/**
* @param string $activityId
*
* @return DestinyRequest
*/
public function getPostGameCarnageReport(string $activityId)
{
return $this->destinyRequest("Destiny2/Stats/PostGameCarnageReport/$activityId/");
}
/**
* @param Account $account
*
* @return DestinyRequest
*/
public function getDestinyProfile(Account $account): DestinyRequest
{
$profileBuilder = (new DestinyComponentUrlBuilder("Destiny2/$account->membership_type/Profile/$account->membership_id/"))
->addProfiles()
->addProfileCurrencies()
->addCharacters()
->addCharacterProgressions()
->addCharacterEquipment()
->addItemInstances();
return $this->destinyRequest($profileBuilder->buildUrl(), $profileBuilder->getComponentArray(), CACHE_DEFAULT, false);
}
/**
* @param Account $account
* @param array $modes
*
* @return DestinyRequest
*/
public function getDestinyStats(Account $account, $modes = [StatGroupType::GENERAL, StatGroupType::ACTIVITY, StatGroupType::WEAPONS]): DestinyRequest
{
return $this->destinyRequest("Destiny2/$account->membership_type/Account/$account->membership_id/Stats/", ['groups' => implode(',', $modes)], CACHE_DEFAULT, true);
}
/**
* @param Player $player
*
* @return DestinyRequest
*/
public function getGroups(Player $player): DestinyRequest
{
// 0/1 = no filters & groupType = clan. Thanks vpzed
return $this->destinyRequest('GroupV2/User/'.$player->membershipType.'/'.$player->membershipId.'/0/1/', null, CACHE_DEFAULT, false);
}
/**
* @param Group $group
*
* @return DestinyRequest
*/
public function getClan(Group $group): DestinyRequest
{
return $this->destinyRequest("GroupV2/$group->groupId/", null, CACHE_DEFAULT, true);
}
/**
* @param Group $group
*
* @return DestinyRequest
*/
public function getClanMembers(Group $group): DestinyRequest
{
return $this->destinyRequest('GroupV2/'.$group->groupId.'/Members/', ['currentPage' => 1], CACHE_DEFAULT, false);
}
/**
* @param Group $group
* @param array $modes
*
* @return DestinyRequest
*/
public function getClanStats(Group $group, array $modes = [ActivityModeType::ALL_PVE, ActivityModeType::ALL_PVP, ActivityModeType::NIGHTFALL]): DestinyRequest
{
return $this->destinyRequest('Destiny2/Stats/AggregateClanStats/'.$group->groupId.'/', ['modes' => $modes], CACHE_DEFAULT, false);
}
/**
* @param Group $group
* @param array $modes
* @param string $statId
*
* @return DestinyRequest
*/
public function getClanLeaderboard(Group $group, array $modes = [ActivityModeType::ALL_PVP, ActivityModeType::ALL_PVE], string $statId = ''): DestinyRequest
{
$params = ['modes' => implode(',', $modes), 'maxtop' => 10];
if (!empty($statId)) {
$params = array_add($params, 'statId', $statId);
}
return $this->destinyRequest("Destiny2/Stats/Leaderboards/Clans/$group->groupId/", $params, 60 * 24, true);
}
/**
* @param Group $group
*
* @return DestinyRequest
*/
public function getClanWeeklyRewards(Group $group)
{
return $this->destinyRequest("Destiny2/Clan/$group->groupId/WeeklyRewardState/", null, 60, true);
}
/**
* @return DestinyRequest
*/
public function getMilestones(): DestinyRequest
{
return $this->destinyRequest('Destiny2/Milestones/', null, CACHE_INDEX, false);
}
/**
* @param string $milestoneHash
*
* @return DestinyRequest
*/
public function getMilestoneContent(string $milestoneHash): DestinyRequest
{
return $this->destinyRequest("Destiny2/Milestones/$milestoneHash/Content/", null, CACHE_INDEX, false);
}
/**
* @param Profile $profile
* @param Character $character
*
* @return DestinyRequest
*/
public function getCharacterStats(Profile $profile, Character $character): DestinyRequest
{
$membershipType = $profile->account->membership_type;
$membershipId = $profile->account->membership_id;
return $this->destinyRequest("Destiny2/$membershipType/Account/$membershipId/Character/$character->characterId/Stats/AggregateActivityStats/", null, CACHE_DEFAULT, true);
}
}
| mit |
LambdaInnovation/LambdaLib | src/main/java/cn/lambdalib/cgui/gui/event/LeftClickEvent.java | 511 | /**
* Copyright (c) Lambda Innovation, 2013-2016
* This file is part of LambdaLib modding library.
* https://github.com/LambdaInnovation/LambdaLib
* Licensed under MIT, see project root for more information.
*/
package cn.lambdalib.cgui.gui.event;
/**
* Fired on CGui and current focus when user presses left mouse button.
*/
public class LeftClickEvent implements GuiEvent {
public final double x, y;
public LeftClickEvent(double _x, double _y) {
x = _x;
y = _y;
}
}
| mit |
wiseallie/rails_admin_has_many_nested | lib/rails_admin_has_many_nested.rb | 574 | require "rails_admin"
require 'rails_admin/nested_abstract_model'
require 'rails_admin/extensions/pundit_nested'
require 'rails_admin/extensions/cancan_nested'
require 'rails_admin/extensions/cancancan_nested'
require 'rails_admin/config/fields/types/has_many_nested_association_extension'
require 'rails_admin/config/actions_extension'
require 'rails_admin/config/model_extension'
require 'rails_admin/controllers/concerns/application_concern'
require "rails_admin_has_many_nested/engine"
require "rails_admin_has_many_nested/version"
module RailsAdminHasManyNested
end
| mit |
freyr69/mh | app/Http/Controllers/Dom/AssignedPunishmentController.php | 3242 | <?php
namespace Mistress\Http\Controllers\Dom;
use Auth;
use Carbon\Carbon;
use Flash;
use Input;
use Mistress\AssignedPunishment;
use Mistress\Http\Controllers\Controller;
use Redirect;
use Response;
class AssignedPunishmentController extends Controller
{
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$punishments = Auth::user()->sub->punishments;
return view('dom.assigned_punishment.index', compact('punishments'));
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
$punishments = Auth::user()->punishmentList->lists('name', 'id');
return view('dom.assigned_punishment.create', ['punishments' => $punishments]);
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
$user = Auth::user();
$data = Input::all();
$punishment = $user->punishmentList->find($data['punishment']);
$data['name'] = $punishment->name;
$data['description'] = $punishment->description;
$data['assigned_on'] = Carbon::now();
unset($data['punishment']);
$user->sub->punishments()->create($data);
$name = $user->sub->name;
Flash::success('A punishment was assigned to ' . $name);
return redirect('/dom');
}
/**
* Display the specified resource.
*
* @param AssignedPunishment $punishment
* @return Response
*/
public function show(AssignedPunishment $punishment)
{
return view('dom.assigned_punishment.show', compact('punishment'));
}
/**
* Show the form for editing the specified resource.
*
* @param AssignedPunishment $punishment
* @return Response
*/
public function edit(AssignedPunishment $punishment)
{
return view('dom.assigned_punishment.edit', compact('punishment'));
}
/**
* Update the specified resource in storage.
*
* @param AssignedPunishment $punishment
* @return Response
*/
public function update(AssignedPunishment $punishment)
{
$input = array_except(Input::all(), ['_method', '_token']);
$punishment->update($input);
Flash::success('Punishment Updated.');
return Redirect::route('dom.assigned_punishment.index');
}
/**
*
* @param AssignedPunishment $punishment
* @return Response
*/
public function complete(AssignedPunishment $punishment)
{
$punishment->complete = true;
$punishment->completed_on = Carbon::now();
$punishment->save();
Flash::success('Punishment Completed.');
return Redirect::route('dom.assigned_punishment.index');
}
/**
* Remove the specified resource from storage.
*
* @param AssignedPunishment $punishment
* @return Response
*/
public function destroy(AssignedPunishment $punishment)
{
$punishment->delete();
Flash::success('Punishment Deleted.');
return Redirect::route('dom.assigned_punishment.index');
}
}
| mit |
selviamago/PWEB161_51014023 | application/config/routes.php | 304 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route['biodata'] = 'biodata';
$route['ukmku'] = 'ukm';
$route['ceritaku'] = 'ceritasaya';
$route['plus'] = 'plus';
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
| mit |
myayo/EADJAVA | src/main/java/com/inf380/ead/service/LdapService.java | 357 | package com.inf380.ead.service;
public class LdapService {
private final String LDAP_CONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
private final String LDAP_AUTHENTICATION_MODE = "simple";
private final String LDAP_REFERRAL_MODE = "follow";
public boolean authenticate(String username, String password){
return false;
}
}
| mit |
iluminar/goodwork | tests/Feature/CycleTest.php | 4751 | <?php
namespace Tests\Feature;
use Tests\TestCase;
class CycleTest extends TestCase
{
/** @test */
public function admin_can_create_new_cycle()
{
$project = factory(\App\Project\Models\Project::class)->create(['owner_id' => $this->user->id]);
$this->actingAs($this->user);
resolve('Authorization')->setupDefaultPermissions($project);
$project->members()->save($this->user);
$this->post('/cycles', [
'name' => 'V.1',
'start_date' => '2019-06-13',
'end_date' => '2019-06-21',
'group_type' => 'project',
'group_id' => $project->id,
])
->assertJsonFragment([
'status' => 'success',
'name' => 'V.1',
'start_date' => 'Jun 13, 2019',
'end_date' => 'Jun 21, 2019',
]);
$this->assertDatabaseHas('cycles', [
'name' => 'V.1',
'start_date' => '2019-06-13',
'end_date' => '2019-06-21',
'cyclable_type' => 'project',
'cyclable_id' => $project->id,
]);
}
/** @test */
public function cycle_in_same_group_cant_overlap_another_cycle()
{
$project = factory(\App\Project\Models\Project::class)->create(['owner_id' => $this->user->id]);
$this->actingAs($this->user);
resolve('Authorization')->setupDefaultPermissions($project);
$project->members()->save($this->user);
factory(\App\Base\Models\Cycle::class)->create([
'cyclable_type' => 'project',
'cyclable_id' => $project->id,
'start_date' => '2019-06-10',
'end_date' => '2019-06-25',
]);
$this->post('/cycles', [
'name' => 'V.1',
'start_date' => '2019-06-13',
'end_date' => '2019-06-21',
'group_type' => 'project',
'group_id' => $project->id,
])
->assertJsonFragment([
'status' => 'error',
'message' => 'This cycle overlap another cycle, try again',
]);
$this->post('/cycles', [
'name' => 'V.2',
'start_date' => '2019-06-01',
'end_date' => '2019-06-21',
'group_type' => 'project',
'group_id' => $project->id,
])
->assertJsonFragment([
'status' => 'error',
'message' => 'This cycle overlap another cycle, try again',
]);
$this->post('/cycles', [
'name' => 'V.3',
'start_date' => '2019-06-21',
'end_date' => '2019-06-29',
'group_type' => 'project',
'group_id' => $project->id,
])
->assertJsonFragment([
'status' => 'error',
'message' => 'This cycle overlap another cycle, try again',
]);
$this->post('/cycles', [
'name' => 'V.4',
'start_date' => '2019-06-01',
'end_date' => '2019-06-29',
'group_type' => 'project',
'group_id' => $project->id,
])
->assertJsonFragment([
'status' => 'error',
'message' => 'This cycle overlap another cycle, try again',
]);
}
/** @test */
public function user_can_get_all_cycles()
{
$project = factory(\App\Project\Models\Project::class)->create(['owner_id' => $this->user->id]);
factory(\App\Base\Models\Cycle::class)->create([
'name' => 'June Release Cycle',
'start_date' => '2019-06-01',
'end_date' => '2019-06-28',
'cyclable_type' => 'project',
'cyclable_id' => $project->id,
]);
factory(\App\Base\Models\Cycle::class)->create([
'name' => 'July Release Cycle',
'start_date' => '2019-07-01',
'end_date' => '2019-07-28',
'cyclable_type' => 'project',
'cyclable_id' => $project->id,
]);
$this->actingAs($this->user)
->call('GET', '/cycles', [
'group_type' => 'project',
'group_id' => $project->id,
])
->assertJsonFragment([
'status' => 'success',
'name' => 'June Release Cycle',
'start_date' => 'Jun 1, 2019',
'end_date' => 'Jun 28, 2019',
])
->assertJsonFragment([
'name' => 'July Release Cycle',
'start_date' => 'Jul 1, 2019',
'end_date' => 'Jul 28, 2019',
]);
}
}
| mit |
dwivivagoal/KuizMilioner | application/libraries/php-google-sdk/google/apiclient-services/src/Google/Service/Compute/MachineTypesScopedList.php | 1331 | <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_Compute_MachineTypesScopedList extends Google_Collection
{
protected $collection_key = 'machineTypes';
protected $machineTypesType = 'Google_Service_Compute_MachineType';
protected $machineTypesDataType = 'array';
protected $warningType = 'Google_Service_Compute_MachineTypesScopedListWarning';
protected $warningDataType = '';
public function setMachineTypes($machineTypes)
{
$this->machineTypes = $machineTypes;
}
public function getMachineTypes()
{
return $this->machineTypes;
}
public function setWarning(Google_Service_Compute_MachineTypesScopedListWarning $warning)
{
$this->warning = $warning;
}
public function getWarning()
{
return $this->warning;
}
}
| mit |
stivalet/PHP-Vulnerability-test-suite | Injection/CWE_89/safe/CWE_89__GET__CAST-cast_int__multiple_select-concatenation.php | 1559 | <?php
/*
Safe sample
input : reads the field UserData from the variable $_GET
sanitize : cast into int
construction : concatenation
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$tainted = $_GET['UserData'];
$tainted = (int) $tainted ;
$query = "SELECT * FROM COURSE c WHERE c.id IN (SELECT idcourse FROM REGISTRATION WHERE idstudent=". $tainted . ")";
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password)
mysql_select_db('dbname') ;
echo "query : ". $query ."<br /><br />" ;
$res = mysql_query($query); //execution
while($data =mysql_fetch_array($res)){
print_r($data) ;
echo "<br />" ;
}
mysql_close($conn);
?> | mit |
trampoline/hash_graph | spec/hash_graph_spec.rb | 3400 | require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
require 'set'
describe HashGraph do
module HashGraph
describe DirectedGraph do
it "should not create a top-level key on top-level access" do
h = DirectedGraph.new
h[:foo]
h.should == {}
end
it "should not create a top-level key on second-level access" do
h = DirectedGraph.new
h[:foo][:bar]
h.should == {}
end
it "should create a top-level key for new target nodes" do
h = DirectedGraph.new
h[:foo][:bar] = 1
h.should == {:foo=>{:bar=>1}, :bar=>{}}
end
it "should create new edges on existing top-level keys" do
h = DirectedGraph.new
h[:foo][:bar] = 1
h[:bar][:baz] = 5
h.should == {:foo=>{:bar=>1}, :bar=>{:baz=>5}, :baz=>{}}
end
describe "to_undirected_graph" do
it "should convert a directed graph with bi-directional edges to an undirected graph" do
h = DirectedGraph.new
h[:foo][:bar] = 1
h[:bar][:foo] = 3
h.to_undirected_graph do |a,b,wab,wba|
[a,b].to_set.should == [:foo,:bar].to_set
[wab,wba].to_set.should == [1,3].to_set
wab+wba
end.should=={:foo=>{:bar=>4}, :bar=>{:foo=>4}}
end
it "should convert a directed graph with asymmetric edges to an undirected graph" do
h = DirectedGraph.new
h[:foo][:bar] = 1
h.to_undirected_graph do |a,b,wab,wba|
[a,b].should == [:foo,:bar]
[wab,wba].should == [1,nil]
wab
end.should=={:foo=>{:bar=>1}, :bar=>{:foo=>1}}
end
it "should not create undirected edges if the proc returns nil" do
h = DirectedGraph.new
h[:foo][:bar] = 1
h.to_undirected_graph do |a,b,wab,wba|
[a,b].should == [:foo,:bar]
[wab,wba].should == [1,nil]
nil
end.should=={}
end
end
end
describe UndirectedGraph do
it "should not create a top-level key on top-level access" do
h = UndirectedGraph.new
h[:foo]
h.should == {}
end
it "should not create a top-leve key on second level acces" do
h = UndirectedGraph.new
h[:foo][:bar]
h.should == {}
end
it "should create the reverse edge on edge creation" do
h = UndirectedGraph.new
h[:foo][:bar]=1
h.should == {:foo=>{:bar=>1}, :bar=>{:foo=>1}}
end
it "should extract components from an UndirectedGraph" do
h=UndirectedGraph.new
h[:foo][:bar]=1
h[:foo][:baz]=1
h[:boo][:woo]=1
h.components.map(&:to_set).to_set.should == [[:foo, :bar, :baz].to_set,
[:boo, :woo].to_set].to_set
end
it "should permit nodes to be filtered out when extracting components" do
h=UndirectedGraph.new
h[:foo][:bar]=1
h[:foo][:baz]=1
h[:boo][:woo]=1
h[:foo][:foofoo]=1
h[:foofoo][:boo]=1
h.components.size.should ==(1)
h.components{|v| v!=:foofoo}.map(&:to_set).to_set.should == [[:foo, :bar, :baz].to_set,
[:boo, :woo].to_set].to_set
end
end
end
end
| mit |
zce/electron-boilerplate | src/main/preload.ts | 275 | /**
* Helpful links
* - https://github.com/electron/electron-quick-start/blob/master/preload.js
* - http://electronjs.org/docs/api/process#event-loaded
*/
// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
| mit |
uzura8/tasks | fuel/app/bootstrap.php | 1626 | <?php
// Load original setting file.
require APPPATH.'config.inc.php';
// Load in the Autoloader
require COREPATH.'classes'.DIRECTORY_SEPARATOR.'autoloader.php';
class_alias('Fuel\\Core\\Autoloader', 'Autoloader');
// Bootstrap the framework DO NOT edit this
require COREPATH.'bootstrap.php';
Autoloader::add_classes(array(
// Add classes you want to override here
// Example: 'View' => APPPATH.'classes/view.php',
'Controller' => APPPATH.'classes/controller.php',
//'DB' => APPPATH.'classes/db.php',
'Database_Query_Builder_Update' => APPPATH.'classes/database/query/builder/update.php',
'Validation' => APPPATH.'classes/validation.php',
'Input' => APPPATH.'classes/input.php',
'Agent' => APPPATH.'classes/agent.php',
'Fieldset_Field' => APPPATH.'classes/fieldset/field.php',
));
// Register the autoloader
Autoloader::register();
/**
* Your environment. Can be set to any of the following:
*
* Fuel::DEVELOPMENT
* Fuel::TEST
* Fuel::STAGING
* Fuel::PRODUCTION
*/
Fuel::$env = (isset($_SERVER['FUEL_ENV']) ? $_SERVER['FUEL_ENV'] : constant('Fuel::'.PRJ_ENVIRONMENT));
// Initialize the framework with the config file.
Fuel::init('config.php');
// include helpers.
Util_toolkit::include_php_files(APPPATH.'helpers');
// Config load.
Config::load('site', 'site');
Config::load('term', 'term');
// Config of each module load.
$modules = Module::loaded();
foreach ($modules as $module => $path)
{
if (file_exists(sprintf('%sconfig/%s.php', $path, $module)))
{
Config::load(sprintf('%s::%s', $module, $module), $module);
}
}
// Config of navigation load.
Config::load('navigation', 'navigation');
| mit |
miguelgazela/sinf | webapp/templates_c/f28f4b8764ef2860f1784330f77851a0a4e12b17.file.login.tpl.php | 2858 | <?php /* Smarty version Smarty-3.1.13, created on 2013-12-14 14:42:39
compiled from "C:\xampp\htdocs\webapp\templates\auth\login.tpl" */ ?>
<?php /*%%SmartyHeaderCode:7635529b73c44957d8-50822242%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'f28f4b8764ef2860f1784330f77851a0a4e12b17' =>
array (
0 => 'C:\\xampp\\htdocs\\webapp\\templates\\auth\\login.tpl',
1 => 1386624454,
2 => 'file',
),
),
'nocache_hash' => '7635529b73c44957d8-50822242',
'function' =>
array (
),
'version' => 'Smarty-3.1.13',
'unifunc' => 'content_529b73c48df358_19387682',
'has_nocache_code' => false,
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_529b73c48df358_19387682')) {function content_529b73c48df358_19387682($_smarty_tpl) {?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../docs-assets/ico/favicon.png">
<style type="text/css">
body {
background: url(http://localhost/webapp/img/login.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#loginBox {
background-color: white;
opacity: 0.8;
padding-bottom: 10px;
max-width: 300px;
padding-top: 10px;
border-radius: 15px;
}
#blackdude{
color: black;
}
.form-group.last { margin-bottom:0px; }
</style>
<?php echo $_smarty_tpl->getSubTemplate ("common/css.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, null, null, array(), 0);?>
</head>
<body class="login">
<div id="imagetd">
<img width="600" src="../../img/BelaFlor.png">
</div>
<div class="container" id="loginBox">
<form role="form" id="login">
<div id="blackdude">
<span class="glyphicon glyphicon-lock" ></span> Login </div>
<br/>
<div class="form-group">
<label for="inputUsernameEmail" id="blackdude">NIF</label>
<input type="text" class="form-control" id="inputNif">
</div>
<div class="form-group">
<label for="inputPassword" id="blackdude">Password</label>
<input type="password" class="form-control" id="inputPassword">
</div>
<button id="loginButton" type="submit" class="btn btn btn-default pull-right">LOGIN</button>
</form>
</div>
<footer id="footer">
<img width="500" src="../../img/primavera_logo.png">
</footer>
<?php echo $_smarty_tpl->getSubTemplate ("common/js.tpl", $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, null, null, array(), 0);?>
</body>
</html>
<?php }} ?> | mit |
vissense/angular-vissense | src/angular-vissense/directives/vissense-monitor.js | 2710 | (function (angular) {
angular.module('angular-vissense.directives')
.directive('vissenseMonitor', ['VisSense', 'VisUtils',
function (VisSense, VisUtils) {
var d = {
scope: {
monitor: '=?ngModel',
config: '@',
onStart: '&',
onStop: '&',
onUpdate: '&',
onHidden: '&',
onVisible: '&',
onFullyvisible: '&',
onPercentagechange: '&',
onVisibilitychange: '&'
},
link: function ($scope, $element) {
var digest = VisUtils.throttle(function () {
$scope.$digest();
$scope.$parent.$digest();
}, 1000);
$element.addClass('vissense-monitor');
$scope.monitor = new VisSense($element[0], $scope.config).monitor({
start: function (monitor) {
$scope.onStart({monitor: monitor});
},
stop: function (monitor) {
$scope.onStop({monitor: monitor});
},
update: function (monitor) {
$scope.onUpdate({monitor: monitor});
digest();
},
hidden: function (monitor) {
$scope.onHidden({monitor: monitor});
},
visible: function (monitor) {
$scope.onVisible({monitor: monitor});
},
fullyvisible: function (monitor) {
$scope.onFullyvisible({monitor: monitor});
},
percentagechange: function (monitor, newValue, oldValue) {
$scope.onPercentagechange({
monitor: monitor,
newValue: newValue,
oldValue: oldValue
});
},
visibilitychange: function (monitor) {
$scope.onVisibilitychange({monitor: monitor});
$element.removeClass('vissense-monitor-hidden');
$element.removeClass('vissense-monitor-fullyvisible');
$element.removeClass('vissense-monitor-visible');
if (monitor.state().fullyvisible) {
$element.addClass('vissense-monitor-fullyvisible');
} else if (monitor.state().hidden) {
$element.addClass('vissense-monitor-hidden');
} else {
$element.addClass('vissense-monitor-visible');
}
}
}).startAsync();
$scope.$on('$destroy', function () {
$scope.monitor.stop();
});
}
};
return d;
}])
;
})(angular);
| mit |
djgalaxy/AndroidSpinnerExample | app/src/androidTest/java/djgalaxy/github/spinnerdemo/ApplicationTest.java | 358 | package djgalaxy.github.spinnerdemo;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | mit |
talentnest/amcharts.rb | app/helpers/amcharts/amcharts_helper.rb | 1895 | module AmCharts
module AmChartsHelper
def amchart(chart, container)
# Load necessary JS and CSS files, without loading one more than once
@loaded_amchart_files ||= { js: [], css: []}
js_files = ['amcharts', "amcharts/#{chart.type}"]
js_files << "amcharts/lang/#{chart.language}" if chart.language? && chart.language != 'en' # English is default already
css_files = ['amcharts']
if chart.export?
chart.export.settings.libs = { autoLoad: false } # Turn off automatic loading of libraries
export_dir = 'amcharts/plugins/export'
# For any export
js_files << "#{export_dir}/export.min"
js_files << "#{export_dir}/libs/fabric.js/fabric.min"
# Used to offer download files
js_files << "#{export_dir}/libs/FileSaver.js/FileSaver.min"
# For PDF format
js_files << "#{export_dir}/libs/pdfmake/pdfmake"
js_files << "#{export_dir}/libs/pdfmake/vfs_fonts"
# For XLSX format
js_files << "#{export_dir}/libs/jszip/jszip.min"
js_files << "#{export_dir}/libs/xlsx/xlsx"
# Language support
js_files << "#{export_dir}/lang/#{chart.language}" if chart.language?
# CSS
css_files << "#{export_dir}/export"
end
js_files -= @loaded_amchart_files[:js]
css_files -= @loaded_amchart_files[:css]
@loaded_amchart_files[:js] += js_files
@loaded_amchart_files[:css] += css_files
content_for(:javascript) { javascript_include_tag(*js_files) }
content_for(:stylesheets) { stylesheet_link_tag(*css_files) }
# Render the chart builder
builder = AmCharts::ChartBuilder.new(chart, self)
chart.container = container
javascript_tag do
builder.render_js('chart_builder', template_type: :file, locals: { chart: chart, container: container })
end
end
end
end
| mit |
andrehjr/rd_highrise_api | spec/rd_highrise_api/api_spec.rb | 378 | require 'spec_helper'
class Test; include RdHighriseApi::Api; end
describe RdHighriseApi::Api do
let(:xml) { "<errors><error>First name can't be blank</error><error>Last name can't be blank</error></errors>"}
it "should parse error messages correctly" do
expect(Test.new.error_messages_from(xml)).to eql(["First name can't be blank", "Last name can't be blank"])
end
end | mit |
redding/scmd | test/unit/stored_commands_tests.rb | 3884 | # frozen_string_literal: true
require "assert"
require "scmd/stored_commands"
require "scmd/command_spy"
class Scmd::StoredCommands
class UnitTests < Assert::Context
desc "Scmd::StoredCommands"
setup do
@cmd_str = Factory.string
@opts = { Factory.string => Factory.string }
@output = Factory.text
@commands = Scmd::StoredCommands.new
end
subject{ @commands }
should have_imeths :add, :get, :remove, :remove_all, :empty?
should "allow adding and getting commands when yielded a command" do
yielded = nil
subject.add(@cmd_str) do |cmd|
yielded = cmd
cmd.stdout = @output
end
cmd_spy = subject.get(@cmd_str, {})
assert_instance_of Scmd::CommandSpy, yielded
assert_equal yielded, cmd_spy
assert_equal @output, cmd_spy.stdout
end
should "return a stub when adding a command" do
stub = subject.add(@cmd_str)
assert_instance_of Scmd::StoredCommands::Stub, stub
stub.with(@opts){ |cmd| cmd.stdout = @output }
cmd = subject.get(@cmd_str, @opts)
assert_equal @output, cmd.stdout
cmd = subject.get(@cmd_str, {})
assert_not_equal @output, cmd.stdout
end
should "return a unaltered cmd spy for a cmd str that isn't configured" do
cmd_spy = Scmd::CommandSpy.new(@cmd_str)
cmd = subject.get(@cmd_str)
assert_equal cmd_spy, cmd
end
should "not call a cmd block until it is retrieved" do
called = false
subject.add(@cmd_str){ called = true }
assert_false called
subject.get(@cmd_str)
assert_true called
end
should "allow removing a stub" do
subject.add(@cmd_str){ |cmd| cmd.stdout = @output }
cmd = subject.get(@cmd_str)
assert_equal @output, cmd.stdout
subject.remove(@cmd_str)
cmd = subject.get(@cmd_str)
assert_not_equal @output, cmd.stdout
end
should "allow removing all commands" do
subject.add(@cmd_str){ |cmd| cmd.stdout = @output }
other_cmd_str = Factory.string
subject.add(other_cmd_str){ |cmd| cmd.stdout = @output }
subject.remove_all
cmd = subject.get(@cmd_str)
assert_not_equal @output, cmd.stdout
cmd = subject.get(other_cmd_str)
assert_not_equal @output, cmd.stdout
end
should "know if it is empty or not" do
assert_empty subject
subject.add(@cmd_str)
assert_not_empty subject
subject.remove_all
assert_empty subject
end
should "know if it is equal to another stored commands or not" do
cmds1 = Scmd::StoredCommands.new
cmds2 = Scmd::StoredCommands.new
assert_equal cmds1, cmds2
cmds1.add(@cmd_str)
assert_not_equal cmds1, cmds2
end
end
class StubTests < UnitTests
desc "Stub"
setup do
@stub = Stub.new(@cmd_str)
end
subject{ @stub }
should have_readers :cmd_str, :hash
should have_imeths :set_default_proc, :with, :call
should "default its default command proc" do
cmd_spy = Scmd::CommandSpy.new(@cmd_str, @opts)
cmd = subject.call(@opts)
assert_equal cmd_spy, cmd
end
should "allow setting its default proc" do
subject.set_default_proc{ |cmd| cmd.stdout = @output }
cmd = subject.call(@opts)
assert_equal @output, cmd.stdout
end
should "allow setting commands for specific opts" do
cmd = subject.call(@opts)
assert_equal "", cmd.stdout
subject.with({}){ |cmd| cmd.stdout = @output }
cmd = subject.call({})
assert_equal @output, cmd.stdout
end
should "know if it is equal to another stub or not" do
stub1 = Stub.new(@cmd_str)
stub2 = Stub.new(@cmd_str)
assert_equal stub1, stub2
Assert.stub(stub1, [:cmd_str, :hash].sample){ Factory.string }
assert_not_equal stub1, stub2
end
end
end
| mit |
ndvalkov/TelerikAcademy2016 | Homework/CSharp-Part-2/04. Numeral-Systems/BinToDec.cs | 413 | using System;
class BinaryToDecimalConversion
{
static void Main()
{
string binary = Console.ReadLine();
Console.WriteLine(BinaryToDecimal(binary));
}
static ulong BinaryToDecimal(string binary)
{
ulong result = 0;
foreach (var c in binary)
{
result *= 2;
result += (ulong)(c - '0');
}
return result;
}
}
| mit |
tholum/crm42 | pages/welcome.main.php | 857 | <?php
require_once('app_code/config.inc.php');
require_once 'class/class.tasks.php';
require_once('class/class.message.php');
require_once('class/class.news.php');
require_once 'class/class.contacts.php';
require_once 'class/class.bugs.php';
require_once 'Zend/Loader.php';
require_once('class/class.CapacityReport.php');
require_once('class/class.WorkOrder.php');
require_once('class/class.welcome.php');
$welcome = new welcome();
$welcome_message = $welcome->get_news();
?>
<div style="position: relative;left: 35px; display: inline-block" >
<?php echo base64_decode( $welcome_message['news'] ); ?>
</div>
<div style="padding: 10px;padding-right: 35px;position: absolute;right: 0px;top: 2px;display:inline-block;width: 250px;min-width: 250px;background: #A7CDF0" >
Quick Search: <input class="welcome_quicksearch" onfocus="$(this).select()" />
</div> | mit |
jimmydorry/d2moddin-invite-access | auth/index.php | 1925 | <?php
require_once("../functions.php");
require_once("../connections/parameters.php");
try {
if (!isset($_SESSION)) {
session_start();
}
$user = new user;
$user->apikey = $steam_api_key; // put your API key here
$user->domain = $steam_api_domain; // put your domain
//echo $steam_api_key . '<br />' . $steam_api_domain . '<br />';
if (isset($_GET['login'])) {
$user->signIn('../');
}
if (isset($_GET['logout'])) {
$user->signOut('../');
}
/*if(empty($_SESSION['user_id']))
{
print ('<form action="?login" method="post">
<input type="image" src="http://cdn.steamcommunity.com/public/images/signinthroughsteam/sits_large_border.png"/>
</form>');
}
else
{
echo '<pre>';
echo $_SESSION['user_name'].'<br />';
print('<form method="post"><button title="Logout" name="logout">Logout</button></form>');
print_r( $user->GetPlayerSummaries($_SESSION['user_id']) );
echo '</pre>';
}
*/
/*
stdClass Object
(
[steamid] => 76561198111755442
[communityvisibilitystate] => 3
[profilestate] => 1
[personaname] => getdotabet
[profileurl] => http://steamcommunity.com/id/getdotabet/
[avatar] => http://media.steampowered.com/steamcommunity/public/images/avatars/63/6334ac1c60cbd025d4cc87071414e6569d2b64e8.jpg
[avatarmedium] => http://media.steampowered.com/steamcommunity/public/images/avatars/63/6334ac1c60cbd025d4cc87071414e6569d2b64e8_medium.jpg
[avatarfull] => http://media.steampowered.com/steamcommunity/public/images/avatars/63/6334ac1c60cbd025d4cc87071414e6569d2b64e8_full.jpg
[personastate] => 0
[primaryclanid] => 103582791429521408
[timecreated] => 1382411448
[loccountrycode] => RU
)
*/
} catch (Exception $e) {
echo $e->getMessage();
}
?>
| mit |
jezhiggins/content-api-ng | test/integration/hello_world.js | 593 | const app = require('../../app');
const request = require('supertest')(app);
describe('Smoke', () => {
basic('/', 'text/html', 'Hello World');
basic('/hello.json', 'application/json', { greeting: 'Hello World'});
it('notfound', done => {
request.
get('/no-way-dude').
expect(404).
end(done);
}); // not_found
});
/////////////////////////
function basic(url, content_type, content) {
it(url, done => {
request.
get(url).
expect('Content-Type', `${content_type}; charset=utf-8`).
expect(200, content).
end(done);
});
} // basic
| mit |
Supamiu/ffxiv-teamcraft | apps/client/src/app/pages/about/about.module.ts | 705 | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AboutComponent } from './about/about.component';
import { RouterModule, Routes } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
import { MaintenanceGuard } from '../maintenance/maintenance.guard';
import { VersionLockGuard } from '../version-lock/version-lock.guard';
const routes: Routes = [
{
path: '',
component: AboutComponent,
canActivate: [MaintenanceGuard, VersionLockGuard]
}
];
@NgModule({
imports: [
CommonModule,
TranslateModule,
RouterModule.forChild(routes)
],
declarations: [AboutComponent]
})
export class AboutModule {
}
| mit |
JohnGrekso/GeckoUBL | src/GeckoUBL/Ubl21/Cac/MeterType.cs | 1879 | using GeckoUBL.Ubl21.Udt;
namespace GeckoUBL.Ubl21.Cac
{
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
[System.Xml.Serialization.XmlRootAttribute("Meter", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", IsNullable=false)]
public class MeterType {
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType MeterNumber { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType MeterName { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType MeterConstant { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public CodeType MeterConstantCode { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public QuantityType TotalDeliveredQuantity { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("MeterReading")]
public MeterReadingType[] MeterReading { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("MeterProperty")]
public MeterPropertyType[] MeterProperty { get; set; }
}
} | mit |
CeciliaHinga/HebaShop | resources/views/layouts/owner.blade.php | 3735 | <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Heba : @yield('title')</title>
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
<link rel="stylesheet" href="{!! elixir('css/final.css') !!}">
<!-- Bootstrap 3.3.2
<link href="{{ asset("/bower_components/admin-lte/bootstrap/css/bootstrap.min.css") }}" rel="stylesheet" type="text/css" />
Font Awesome Icons
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
Ionicons
<link href="http://code.ionicframework.com/ionicons/2.0.0/css/ionicons.min.css" rel="stylesheet" type="text/css" />
Theme style
<link href="{{ asset("/bower_components/admin-lte/dist/css/AdminLTE.min.css")}}" rel="stylesheet" type="text/css" />
AdminLTE Skins. We have chosen the skin-blue for this starter
page. However, you can choose any other skin. Make sure you
apply the skin class to the body tag so the changes take effect.
<link href="{{ asset("/bower_components/admin-lte/dist/css/skins/skin-blue.min.css")}}" rel="stylesheet" type="text/css" />-->
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body class="hold-transition skin-yellow sidebar-mini">
<div class="wrapper">
<!-- Header -->
@include('header')
<!-- Sidebar -->
@include('sidebar')
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>@yield('title')
<small>{{ $page_description or null }}</small>
</h1>
<!-- You can dynamically generate breadcrumbs here -->
<ol class="breadcrumb">
<li><a href="/owners"><i class="fa fa-dashboard"></i> Level</a></li>
<li class="active">Here</li>
</ol>
</section>
<div class="notice">
@if (isset($errors) && $errors -> any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><b>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul></b>
</div>
@endif
</div>
<!-- Main content -->
<section class="content">
<!-- Your Page Content Here -->
@yield('content')
</section><!-- /.content -->
</div><!-- /.content-wrapper -->
<!-- Footer -->
@include('footer')
</div><!-- ./wrapper -->
<!-- REQUIRED JS SCRIPTS -->
<!-- jQuery 2.1.3
<script src="{{ asset ("/bower_components/admin-lte/plugins/jQuery/jQuery-2.1.3.min.js") }}"></script>
Bootstrap 3.3.2 JS
<script src="{{ asset ("/bower_components/admin-lte/bootstrap/js/bootstrap.min.js") }}" type="text/javascript"></script>
AdminLTE App
<script src="{{ asset ("/bower_components/admin-lte/dist/js/app.min.js") }}" type="text/javascript"></script>-->
<script src="/js/jquery.js" type="text/javascript"></script>
<script src="{!! elixir('js/final.js') !!}" async defer></script>
@yield('scripts')
<!-- Optionally, you can add Slimscroll and FastClick plugins.
Both of these plugins are recommended to enhance the
user experience -->
</body>
</html> | mit |
Kris-LIBIS/LIBIS_Format | lib/libis/format/converter/pdf_converter.rb | 6170 | # encoding: utf-8
require_relative 'base'
require 'libis/tools/extend/hash'
require 'libis/format/tool/pdf_copy'
require 'libis/format/tool/pdf_to_pdfa'
require 'libis/format/tool/pdf_optimizer'
module Libis
module Format
module Converter
class PdfConverter < Libis::Format::Converter::Base
def self.input_types
[:PDF]
end
def self.output_types(format = nil)
return [] unless input_types.include?(format)
[:PDF, :PDFA]
end
def pdf_convert(_)
#force usage of this converter
end
# Set metadata for Pdf file
#
# valid metadata keys are):
# - title
# - author
# - creator
# - keywords
# - subject
#
# @param [Hash] values list of metadata values to set
def metadata(values = {})
values.key_strings_to_symbols!
values.each do |k, v|
next unless [:title, :author, :creator, :keywords, :subject].include?(k)
@options["md_#{k}"] = v
end
end
# Select a partial list of pages
# @param [String] selection as described in com.itextpdf.text.pdf.SequenceList: [!][o][odd][e][even]start-end
def range(selection)
@options[:ranges] = selection
end
# Create or use a watermark image.
#
# The watermark options are (use symbols):
# - text: text to create a watermark from
# - file: watermark image to use
# - rotation: rotation of the watermark text (in degrees; integer number)
# - size: font size of the watermark text
# - opacity: opacity of the watermark (fraction 0.0 - 1.0)
# - gap: size of the gap between watermark instances. Integer value is absolute size in points (1/72 inch). Fractions are percentage of widht/height.
# If both options are given, the file will be used as-is if it exists and is a valid image file. Otherwise the
# file will be created or overwritten with a newly created watermark image.
#
# The created watermark file will be a PNG image with transparent background containing the supplied text
# slanted by 30 degrees counter-clockwise.
#
# @param [Hash] options Hash of options for watermark creation.
def watermark(options = {})
options.key_strings_to_symbols!
if options[:file] && File.exist?(options[:file])
@options['wm_image'] = options[:file]
else
@options['wm_text'] = (options[:text] || '© LIBIS').split('\n')
@options['wm_text_rotation'] = options[:rotation] if options[:rotation]
@options['wm_font_size'] = options[:size] if options[:size]
end
@options['wm_opacity'] = options[:opacity] || '0.3'
@options['wm_gap_ratio'] = options[:gap] if options[:gap].to_s =~ /^\s*(0+\.\d+|1\.0+)\s*$/
@options['wm_gap_size'] = options[:gap] if options[:gap].to_s =~ /^\s*\d+\s*$/
end
# Optimize the PDF
#
# This reduces the graphics quality to a level in order to limit file size. This option relies on the
# presence of ghostscript and takes one argument: the quality level. It should be one of:
#
# - 0 : lowest quality (Acrobat Distiller 'Screen Optimized' equivalent)
# - 1 : medium quality (Acrobat Distiller 'eBook' equivalent)
# - 2 : good quality
# - 3 : high quality (Acrobat Distiller 'Print Optimized' equivalent)
# - 4 : highest quality (Acrobat Distiller 'Prepress Optimized' equivalent)
#
# Note that the optimization is intended to be used with PDF's containing high-resolution images.
#
# @param [Integer] setting quality setting. [0-4]
def optimize(setting = 1)
@options['optimize'] = %w(screen ebook default printer prepress)[setting] if (0..4) === setting
end
def convert(source, target, format, opts = {})
super
result = nil
if (quality = @options.delete('optimize'))
result = optimize_pdf(source, target, quality)
return nil unless result
source = result
end
unless @options.empty?
result = convert_pdf(source, target)
return nil unless result
source = result
end
if format == :PDFA and source
result = pdf_to_pdfa(source, target)
end
result
end
def optimize_pdf(source, target, quality)
using_temp(target) do |tmpname|
result = Libis::Format::Tool::PdfOptimizer.run(source, tmpname, quality)
unless result[:status] == 0
error("Pdf optimization encountered errors:\n%s", (result[:err] + result[:out]).join("\n"))
next nil
end
tmpname
end
end
def convert_pdf(source, target)
using_temp(target) do |tmpname|
result = Libis::Format::Tool::PdfCopy.run(
source, tmpname,
@options.map {|k, v|
if v.nil?
nil
else
["--#{k}", (v.is_a?(Array) ? v : v.to_s)]
end}.flatten
)
unless result[:err].empty?
error("Pdf conversion encountered errors:\n%s", result[:err].join(join("\n")))
next nil
end
tmpname
end
end
def pdf_to_pdfa(source, target)
using_temp(target) do |tmpname|
result = Libis::Format::Tool::PdfToPdfa.run source, tmpname
if result[:status] != 0
error("Pdf/A conversion encountered errors:\n%s", result[:err].join("\n"))
next nil
else
warn("Pdf/A conversion warnings:\n%s", result[:err].join("\n")) unless result[:err].empty?
end
tmpname
end
end
end
end
end
end
| mit |
Matuteale/trekApp | src/graphic/EmailValidator.java | 656 | package Graphic;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidator {
private static Pattern pattern;
private static Matcher matcher;
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
/**
* Validate hex with regular expression
*
* @param hex
* hex for validation
* @return true valid hex, false invalid hex
*/
public static boolean validate(final String hex) {
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(hex);
return matcher.matches();
}
} | mit |
stiftungswo/Dime | src/Dime/InvoiceBundle/DimeInvoiceBundle.php | 276 | <?php
namespace Dime\InvoiceBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class DimeInvoiceBundle extends Bundle
{
//public function build(ContainerBuilder $container)
//{
// $container->addCompilerPass(new RegisterJsonSchemasPass($this));
//}
}
| mit |
fnando/upstarter | lib/upstarter/templates/instance.rb | 891 | module Upstarter
module Templates
class Instance < Base
attr_reader :options
def initialize(options)
@options = options
end
def export_to(dir)
create_file file_name, render(:instance), dir
end
def file_name
"#{options.name}-#{options.process_name}.conf"
end
def additional_options
{
logfile: logfile,
pidfile: pidfile
}
end
def logfile
"/var/log/#{base_name}.log"
end
def pidfile
"/var/run/#{base_name}.pid"
end
def log_dir
"/var/log/#{options.parent_name}-#{options.process_name}"
end
def run_dir
"/var/run/#{options.parent_name}-#{options.process_name}"
end
def base_name
"#{options.name}-#{options.process_name}/#{options.process_name}"
end
end
end
end
| mit |
garganti/info2_oop_unibg | cap06/20/cap06/DomandaDati.java | 1117 | package cap06;
import prog.io.ConsoleInputManager;
import prog.utili.Cerchio;
import prog.utili.Quadrato;
import prog.utili.Rettangolo;
// domanda all'utene i due lati di un rettangolo o quadrato
// se sono uguali isntazia un quadrato
// altrimenti costruisc eun rettangolo
// stampa area e perimetro
public class DomandaDati {
public static void main(String[] args) {
ConsoleInputManager in = new ConsoleInputManager();
int a = in.readInt("primo lato");
int b = in.readInt("secondo lato");
Rettangolo r;
if (a==b) {
r = new Quadrato(a);
} else {
r = new Rettangolo(a,b);
}
// NON POSSO r = new Cerchio(5)
// posso saper qui se e è un rettangolo o un quadrato????
//instanceof
if (r instanceof Quadrato) {
System.out.println("questo è un quadrato");
System.out.println(" con lato " + ((Quadrato)r).getLato());
}
if (r instanceof Rettangolo)
System.out.println("questo è un rettangolo");
// non c'è nel libro
System.out.println(r.getClass());
System.out.println(r.toString());
System.out.println(r.getArea());
System.out.println(r.getPerimetro());
}
}
| mit |
facile-it/moka | src/Plugin/PluginInterface.php | 351 | <?php
declare(strict_types=1);
namespace Moka\Plugin;
use Moka\Exception\MissingDependencyException;
use Moka\Strategy\MockingStrategyInterface;
interface PluginInterface
{
/**
* @return MockingStrategyInterface
*
* @throws MissingDependencyException
*/
public static function getStrategy(): MockingStrategyInterface;
}
| mit |
jinutm/silvfinal | vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.6.9.171/lib/new_relic/agent/instrumentation/merb/controller.rb | 1250 | # encoding: utf-8
# This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
require 'set'
DependencyDetection.defer do
@name = :merb_controller
depends_on do
defined?(Merb) && defined?(Merb::Controller)
end
executes do
::NewRelic::Agent.logger.info 'Installing Merb Controller instrumentation'
end
executes do
require 'merb-core/controller/merb_controller'
Merb::Controller.class_eval do
include NewRelic::Agent::Instrumentation::ControllerInstrumentation
class_inheritable_accessor :do_not_trace
class_inheritable_accessor :ignore_apdex
def self.newrelic_write_attr(attr_name, value) # :nodoc:
self.send "#{attr_name}=", attr_name, value
end
def self.newrelic_read_attr(attr_name) # :nodoc:
self.send attr_name
end
protected
# determine the path that is used in the metric name for
# the called controller action
def newrelic_metric_path
"#{controller_name}/#{action_name}"
end
alias_method :perform_action_without_newrelic_trace, :_dispatch
alias_method :_dispatch, :perform_action_with_newrelic_trace
end
end
end
| mit |
enmasseio/timesync | examples/basic/http/node_client.js | 555 | // node.js client
if (typeof global.Promise === 'undefined') {
global.Promise = require('promise');
}
var timesync = require('../../../dist/timesync');
// create a timesync client
var ts = timesync.create({
peers: 'http://localhost:8081/timesync',
interval: 10000
});
// get notified on changes in the offset
ts.on('change', function (offset) {
console.log('changed offset: ' + offset + ' ms');
});
// get synchronized time
setInterval(function () {
var now = new Date(ts.now());
console.log('now: ' + now.toISOString() + ' ms');
}, 1000); | mit |
yWorks/jsPDF | src/modules/png_support.js | 14760 | /* global jsPDF, Deflater, PNG */
/**
* @license
*
* Copyright (c) 2014 James Robb, https://github.com/jamesbrobb
*
* 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.
* ====================================================================
*/
/**
* jsPDF PNG PlugIn
* @name png_support
* @module
*/
(function(jsPDFAPI, global) {
"use strict";
/*
* @see http://www.w3.org/TR/PNG-Chunks.html
*
Color Allowed Interpretation
Type Bit Depths
0 1,2,4,8,16 Each pixel is a grayscale sample.
2 8,16 Each pixel is an R,G,B triple.
3 1,2,4,8 Each pixel is a palette index;
a PLTE chunk must appear.
4 8,16 Each pixel is a grayscale sample,
followed by an alpha sample.
6 8,16 Each pixel is an R,G,B triple,
followed by an alpha sample.
*/
/*
* PNG filter method types
*
* @see http://www.w3.org/TR/PNG-Filters.html
* @see http://www.libpng.org/pub/png/book/chapter09.html
*
* This is what the value 'Predictor' in decode params relates to
*
* 15 is "optimal prediction", which means the prediction algorithm can change from line to line.
* In that case, you actually have to read the first byte off each line for the prediction algorthim (which should be 0-4, corresponding to PDF 10-14) and select the appropriate unprediction algorithm based on that byte.
*
0 None
1 Sub
2 Up
3 Average
4 Paeth
*/
var doesNotHavePngJS = function() {
return (
typeof global.PNG !== "function" ||
typeof global.FlateStream !== "function"
);
};
var canCompress = function(value) {
return value !== jsPDFAPI.image_compression.NONE && hasCompressionJS();
};
var hasCompressionJS = function() {
return typeof Deflater === "function";
};
var compressBytes = function(bytes, lineLength, colorsPerPixel, compression) {
var level = 5;
var filter_method = filterUp;
switch (compression) {
case jsPDFAPI.image_compression.FAST:
level = 3;
filter_method = filterSub;
break;
case jsPDFAPI.image_compression.MEDIUM:
level = 6;
filter_method = filterAverage;
break;
case jsPDFAPI.image_compression.SLOW:
level = 9;
filter_method = filterPaeth;
break;
}
bytes = applyPngFilterMethod(
bytes,
lineLength,
colorsPerPixel,
filter_method
);
var header = new Uint8Array(createZlibHeader(level));
var checksum = jsPDF.API.adler32cs.fromBuffer(bytes.buffer);
var deflate = new Deflater(level);
var a = deflate.append(bytes);
var cBytes = deflate.flush();
var len = header.length + a.length + cBytes.length;
var cmpd = new Uint8Array(len + 4);
cmpd.set(header);
cmpd.set(a, header.length);
cmpd.set(cBytes, header.length + a.length);
cmpd[len++] = (checksum >>> 24) & 0xff;
cmpd[len++] = (checksum >>> 16) & 0xff;
cmpd[len++] = (checksum >>> 8) & 0xff;
cmpd[len++] = checksum & 0xff;
return jsPDFAPI.__addimage__.arrayBufferToBinaryString(cmpd);
};
var createZlibHeader = function(level) {
/*
* @see http://www.ietf.org/rfc/rfc1950.txt for zlib header
*/
var hdr = 30720;
var flevel = Math.min(3, ((level - 1) & 0xff) >> 1);
hdr |= flevel << 6;
hdr |= 0; //FDICT
hdr += 31 - (hdr % 31);
return [120, hdr & 0xff & 0xff];
};
var applyPngFilterMethod = function(
bytes,
lineLength,
colorsPerPixel,
filter_method
) {
var lines = bytes.length / lineLength,
result = new Uint8Array(bytes.length + lines),
filter_methods = getFilterMethods(),
line,
prevLine,
offset;
for (var i = 0; i < lines; i += 1) {
offset = i * lineLength;
line = bytes.subarray(offset, offset + lineLength);
if (filter_method) {
result.set(filter_method(line, colorsPerPixel, prevLine), offset + i);
} else {
var len = filter_methods.length,
results = [];
for (var j; j < len; j += 1) {
results[j] = filter_methods[j](line, colorsPerPixel, prevLine);
}
var ind = getIndexOfSmallestSum(results.concat());
result.set(results[ind], offset + i);
}
prevLine = line;
}
return result;
};
var filterNone = function(line) {
/*var result = new Uint8Array(line.length + 1);
result[0] = 0;
result.set(line, 1);*/
var result = Array.apply([], line);
result.unshift(0);
return result;
};
var filterSub = function(line, colorsPerPixel) {
var result = [],
len = line.length,
left;
result[0] = 1;
for (var i = 0; i < len; i += 1) {
left = line[i - colorsPerPixel] || 0;
result[i + 1] = (line[i] - left + 0x0100) & 0xff;
}
return result;
};
var filterUp = function(line, colorsPerPixel, prevLine) {
var result = [],
len = line.length,
up;
result[0] = 2;
for (var i = 0; i < len; i += 1) {
up = (prevLine && prevLine[i]) || 0;
result[i + 1] = (line[i] - up + 0x0100) & 0xff;
}
return result;
};
var filterAverage = function(line, colorsPerPixel, prevLine) {
var result = [],
len = line.length,
left,
up;
result[0] = 3;
for (var i = 0; i < len; i += 1) {
left = line[i - colorsPerPixel] || 0;
up = (prevLine && prevLine[i]) || 0;
result[i + 1] = (line[i] + 0x0100 - ((left + up) >>> 1)) & 0xff;
}
return result;
};
var filterPaeth = function(line, colorsPerPixel, prevLine) {
var result = [],
len = line.length,
left,
up,
upLeft,
paeth;
result[0] = 4;
for (var i = 0; i < len; i += 1) {
left = line[i - colorsPerPixel] || 0;
up = (prevLine && prevLine[i]) || 0;
upLeft = (prevLine && prevLine[i - colorsPerPixel]) || 0;
paeth = paethPredictor(left, up, upLeft);
result[i + 1] = (line[i] - paeth + 0x0100) & 0xff;
}
return result;
};
var paethPredictor = function(left, up, upLeft) {
if (left === up && up === upLeft) {
return left;
}
var pLeft = Math.abs(up - upLeft),
pUp = Math.abs(left - upLeft),
pUpLeft = Math.abs(left + up - upLeft - upLeft);
return pLeft <= pUp && pLeft <= pUpLeft
? left
: pUp <= pUpLeft
? up
: upLeft;
};
var getFilterMethods = function() {
return [filterNone, filterSub, filterUp, filterAverage, filterPaeth];
};
var getIndexOfSmallestSum = function(arrays) {
var sum = arrays.map(function(value) {
return value.reduce(function(pv, cv) {
return pv + Math.abs(cv);
}, 0);
});
return sum.indexOf(Math.min.apply(null, sum));
};
var getPredictorFromCompression = function(compression) {
var predictor;
switch (compression) {
case jsPDFAPI.image_compression.FAST:
predictor = 11;
break;
case jsPDFAPI.image_compression.MEDIUM:
predictor = 13;
break;
case jsPDFAPI.image_compression.SLOW:
predictor = 14;
break;
default:
predictor = 12;
break;
}
return predictor;
};
/**
* @name processPNG
* @function
* @ignore
*/
jsPDFAPI.processPNG = function(imageData, index, alias, compression) {
"use strict";
var colorSpace,
filter = this.decode.FLATE_DECODE,
bitsPerComponent,
image,
decodeParameters = "",
trns,
colors,
pal,
smask,
pixels,
len,
alphaData,
imgData,
hasColors,
pixel,
i,
n;
if (this.__addimage__.isArrayBuffer(imageData))
imageData = new Uint8Array(imageData);
if (this.__addimage__.isArrayBufferView(imageData)) {
if (doesNotHavePngJS()) {
throw new Error("PNG support requires png.js and zlib.js");
}
image = new PNG(imageData);
imageData = image.imgData;
bitsPerComponent = image.bits;
colorSpace = image.colorSpace;
colors = image.colors;
/*
* colorType 6 - Each pixel is an R,G,B triple, followed by an alpha sample.
*
* colorType 4 - Each pixel is a grayscale sample, followed by an alpha sample.
*
* Extract alpha to create two separate images, using the alpha as a sMask
*/
if ([4, 6].indexOf(image.colorType) !== -1) {
/*
* processes 8 bit RGBA and grayscale + alpha images
*/
if (image.bits === 8) {
pixels =
image.pixelBitlength == 32
? new Uint32Array(image.decodePixels().buffer)
: image.pixelBitlength == 16
? new Uint16Array(image.decodePixels().buffer)
: new Uint8Array(image.decodePixels().buffer);
len = pixels.length;
imgData = new Uint8Array(len * image.colors);
alphaData = new Uint8Array(len);
var pDiff = image.pixelBitlength - image.bits;
i = 0;
n = 0;
var pbl;
for (; i < len; i++) {
pixel = pixels[i];
pbl = 0;
while (pbl < pDiff) {
imgData[n++] = (pixel >>> pbl) & 0xff;
pbl = pbl + image.bits;
}
alphaData[i] = (pixel >>> pbl) & 0xff;
}
}
/*
* processes 16 bit RGBA and grayscale + alpha images
*/
if (image.bits === 16) {
pixels = new Uint32Array(image.decodePixels().buffer);
len = pixels.length;
imgData = new Uint8Array(
len * (32 / image.pixelBitlength) * image.colors
);
alphaData = new Uint8Array(len * (32 / image.pixelBitlength));
hasColors = image.colors > 1;
i = 0;
n = 0;
var a = 0;
while (i < len) {
pixel = pixels[i++];
imgData[n++] = (pixel >>> 0) & 0xff;
if (hasColors) {
imgData[n++] = (pixel >>> 16) & 0xff;
pixel = pixels[i++];
imgData[n++] = (pixel >>> 0) & 0xff;
}
alphaData[a++] = (pixel >>> 16) & 0xff;
}
bitsPerComponent = 8;
}
if (canCompress(compression)) {
imageData = compressBytes(
imgData,
image.width * image.colors,
image.colors,
compression
);
smask = compressBytes(alphaData, image.width, 1, compression);
} else {
imageData = imgData;
smask = alphaData;
filter = undefined;
}
}
/*
* Indexed png. Each pixel is a palette index.
*/
if (image.colorType === 3) {
colorSpace = this.color_spaces.INDEXED;
pal = image.palette;
if (image.transparency.indexed) {
var trans = image.transparency.indexed;
var total = 0;
i = 0;
len = trans.length;
for (; i < len; ++i) {
total += trans[i];
}
total = total / 255;
/*
* a single color is specified as 100% transparent (0),
* so we set trns to use a /Mask with that index
*/
if (total === len - 1 && trans.indexOf(0) !== -1) {
trns = [trans.indexOf(0)];
/*
* there's more than one colour within the palette that specifies
* a transparency value less than 255, so we unroll the pixels to create an image sMask
*/
} else if (total !== len) {
pixels = image.decodePixels();
alphaData = new Uint8Array(pixels.length);
i = 0;
len = pixels.length;
for (; i < len; i++) {
alphaData[i] = trans[pixels[i]];
}
smask = compressBytes(alphaData, image.width, 1);
}
}
}
var predictor = getPredictorFromCompression(compression);
if (filter === this.decode.FLATE_DECODE) {
decodeParameters = "/Predictor " + predictor + " ";
}
decodeParameters +=
"/Colors " +
colors +
" /BitsPerComponent " +
bitsPerComponent +
" /Columns " +
image.width;
if (
this.__addimage__.isArrayBuffer(imageData) ||
this.__addimage__.isArrayBufferView(imageData)
) {
imageData = this.__addimage__.arrayBufferToBinaryString(imageData);
}
if (
(smask && this.__addimage__.isArrayBuffer(smask)) ||
this.__addimage__.isArrayBufferView(smask)
) {
smask = this.__addimage__.arrayBufferToBinaryString(smask);
}
return {
alias: alias,
data: imageData,
index: index,
filter: filter,
decodeParameters: decodeParameters,
transparency: trns,
palette: pal,
sMask: smask,
predictor: predictor,
width: image.width,
height: image.height,
bitsPerComponent: bitsPerComponent,
colorSpace: colorSpace
};
}
};
})(
jsPDF.API,
(typeof self !== "undefined" && self) ||
(typeof window !== "undefined" && window) ||
(typeof global !== "undefined" && global) ||
Function('return typeof this === "object" && this.content')() ||
Function("return this")()
);
// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window
| mit |
Princess310/onehower-frontend | app/components/Icon/tests/index.test.js | 225 | // import React from 'react';
// import { shallow } from 'enzyme';
// import Icon from '../index';
describe('<Icon />', () => {
it('Expect to have unit tests specified', () => {
expect(true).toEqual(false);
});
});
| mit |
tuyto/715_ps_temp | modules/blocksupplier/blocksupplier.php | 7745 | <?php
/*
* 2007-2014 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <[email protected]>
* @copyright 2007-2014 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
if (!defined('_PS_VERSION_'))
exit;
class BlockSupplier extends Module
{
function __construct()
{
$this->name = 'blocksupplier';
$this->tab = 'front_office_features';
$this->version = 1.1;
$this->author = 'PrestaShop';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Suppliers block');
$this->description = $this->l('Adds a block displaying your product suppliers.');
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
}
function install()
{
if (!parent::install())
return false;
if (!$this->registerHook('displayHeader') ||
!$this->registerHook('actionObjectSupplierDeleteAfter') ||
!$this->registerHook('actionObjectSupplierAddAfter') ||
!$this->registerHook('actionObjectSupplierUpdateAfter')
)
return false;
$theme = new Theme(Context::getContext()->shop->id_theme);
if ((!$theme->default_right_column || !$this->registerHook('rightColumn'))
&& (!$theme->default_left_column || !$this->registerHook('leftColumn'))
)
{
parent::uninstall();
return false;
}
Configuration::updateValue('SUPPLIER_DISPLAY_TEXT', true);
Configuration::updateValue('SUPPLIER_DISPLAY_TEXT_NB', 5);
Configuration::updateValue('SUPPLIER_DISPLAY_FORM', false);
return true;
}
public function uninstall()
{
if (!parent::uninstall())
return false;
/* remove the configuration variable */
$result = Configuration::deleteByName('SUPPLIER_DISPLAY_TEXT');
$result &= Configuration::deleteByName('SUPPLIER_DISPLAY_TEXT_NB');
$result &= Configuration::deleteByName('SUPPLIER_DISPLAY_FORM');
return $result;
}
function hookDisplayLeftColumn($params)
{
$id_lang = (int)Context::getContext()->language->id;
if (!$this->isCached('blocksupplier.tpl', $this->getCacheId()))
$this->smarty->assign(array(
'suppliers' => Supplier::getSuppliers(false, $id_lang),
'link' => $this->context->link,
'text_list' => Configuration::get('SUPPLIER_DISPLAY_TEXT'),
'text_list_nb' => Configuration::get('SUPPLIER_DISPLAY_TEXT_NB'),
'form_list' => Configuration::get('SUPPLIER_DISPLAY_FORM'),
'display_link_supplier' => Configuration::get('PS_DISPLAY_SUPPLIERS')
));
return $this->display(__FILE__, 'blocksupplier.tpl', $this->getCacheId());
}
function getContent()
{
$output = '';
if (Tools::isSubmit('submitBlockSuppliers'))
{
$text_list = (int)(Tools::getValue('SUPPLIER_DISPLAY_TEXT'));
$text_nb = (int)(Tools::getValue('SUPPLIER_DISPLAY_TEXT_NB'));
$form_list = (int)(Tools::getValue('SUPPLIER_DISPLAY_FORM'));
if ($text_list AND !Validate::isUnsignedInt($text_nb))
$errors[] = $this->l('Invalid number of elements.');
elseif (!$text_list AND !$form_list)
$errors[] = $this->l('Please activate at least one type of list.');
else
{
Configuration::updateValue('SUPPLIER_DISPLAY_TEXT', $text_list);
Configuration::updateValue('SUPPLIER_DISPLAY_TEXT_NB', $text_nb);
Configuration::updateValue('SUPPLIER_DISPLAY_FORM', $form_list);
$this->_clearCache('blocksupplier.tpl');
}
if (isset($errors) AND sizeof($errors))
$output .= $this->displayError(implode('<br />', $errors));
else
$output .= $this->displayConfirmation($this->l('Settings updated.'));
}
return $output.$this->renderForm();
}
public function hookDisplayRightColumn($params)
{
return $this->hookDisplayLeftColumn($params);
}
public function hookDisplayHeader($params)
{
$this->context->controller->addCSS(($this->_path).'blocksupplier.css', 'all');
}
public function hookActionObjectSupplierUpdateAfter($params)
{
$this->_clearCache('blocksupplier.tpl');
}
public function hookActionObjectSupplierAddAfter($params)
{
$this->_clearCache('blocksupplier.tpl');
}
public function hookActionObjectSupplierDeleteAfter($params)
{
$this->_clearCache('blocksupplier.tpl');
}
public function renderForm()
{
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'switch',
'label' => $this->l('Use a plain-text list'),
'name' => 'SUPPLIER_DISPLAY_TEXT',
'desc' => $this->l('Display suppliers in a plain-text list.'),
'values' => array(
array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Enabled')
),
array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('Disabled')
)
),
),
array(
'type' => 'text',
'label' => $this->l('Number of elements to display'),
'name' => 'SUPPLIER_DISPLAY_TEXT_NB',
'class' => 'fixed-width-xs'
),
array(
'type' => 'switch',
'label' => $this->l('Use a drop-down list'),
'name' => 'SUPPLIER_DISPLAY_FORM',
'desc' => $this->l('Display suppliers in a drop-down list.'),
'values' => array(
array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Enabled')
),
array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('Disabled')
)
),
)
),
'submit' => array(
'title' => $this->l('Save'),
)
),
);
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitBlockSuppliers';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFieldsValues(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id
);
return $helper->generateForm(array($fields_form));
}
public function getConfigFieldsValues()
{
return array(
'SUPPLIER_DISPLAY_TEXT' => Tools::getValue('SUPPLIER_DISPLAY_TEXT', Configuration::get('SUPPLIER_DISPLAY_TEXT')),
'SUPPLIER_DISPLAY_TEXT_NB' => Tools::getValue('SUPPLIER_DISPLAY_TEXT_NB', Configuration::get('SUPPLIER_DISPLAY_TEXT_NB')),
'SUPPLIER_DISPLAY_FORM' => Tools::getValue('SUPPLIER_DISPLAY_FORM', Configuration::get('SUPPLIER_DISPLAY_FORM')),
);
}
}
| mit |
candice2cc/nox-react-components | src/Layout/components/Layout.js | 506 | /**
* Created by candice on 17/3/29.
*/
import React, {Component, PropTypes} from 'react'
import classNames from 'classnames'
import styles from '../sass/Layout.scss'
class Layout extends Component {
render() {
const {className, hasSider, children, ...others} = this.props;
const cls = classNames(className, styles.layout, {[styles.layoutHasSider]: hasSider});
return (
<div className={cls} {...others}>{children}</div>
)
}
}
export default Layout | mit |
emilio-martinez/is-datatype | src/spec/test-cases/index.ts | 2383 | import { DataType } from '@lib';
import {
invalidNumberUseCases,
validArrayUseCases,
validBooleanUseCases,
validFunctionUseCases,
validNullUseCases,
validNumberNegativeUseCases,
validNumberUseCases,
validObjectUseCases,
validStringUseCases,
validSymbolPolyfilledUseCases,
validSymbolUseCases,
validUndefinedUseCases,
} from './non-schema';
const dataTypeTestCaseMap = {
[DataType.number]: [
...validNumberUseCases,
...validNumberNegativeUseCases,
...invalidNumberUseCases,
],
[DataType.string]: [...validStringUseCases],
[DataType.boolean]: [...validBooleanUseCases],
[DataType.function]: [...validFunctionUseCases],
[DataType.array]: validArrayUseCases.slice().map((n) => n.test),
[DataType.object]: [...validObjectUseCases],
[DataType.undefined]: [...validUndefinedUseCases],
[DataType.null]: [...validNullUseCases],
[DataType.symbol]: [...validSymbolUseCases, ...validSymbolPolyfilledUseCases],
};
export function getDataTypeUseCases(
exclusions: DataType | DataType[] = [],
testCaseMap: { [k: number]: unknown[] } = dataTypeTestCaseMap
): unknown[] {
/**
* Ensure array of strings.
* Strings are preferred because Object key iteration will convert keys to strings anyway.
* DataType numeric keys will be converted to strings once validated.
*/
const exclude: string[] = (<DataType[]>[])
.concat(exclusions)
.reduce<string[]>(
(acc, k) => (typeof k === 'number' && k in DataType ? acc.concat(k.toString()) : acc),
[]
);
/**
* Create array from sample data types.
* Filters out exclusions and remaps into an array of arrays of sample data
*/
return Object.keys(testCaseMap).reduce<unknown[]>(
(acc, k) =>
Object.prototype.hasOwnProperty.call(testCaseMap, k) &&
k in DataType &&
exclude.indexOf(k) === -1
? acc.concat(testCaseMap[+k])
: acc,
[]
);
}
/**
* An array with all the non-named DataType keys.
*/
export const dataTypeKeys: number[] = Object.keys(DataType)
.map((k) => parseInt(k, 10))
.filter((k) => typeof k === 'number' && !isNaN(k));
/**
* Guards against Symbol into string conversion errors
*/
export function safeString<T extends unknown>(value: T): T | string {
return value ? (value as { toString: () => string }).toString() : value;
}
export * from './non-schema';
export * from './schema';
| mit |
ShaneCourtrille/ang2-learning | api/app/on-change.component.ts | 792 | import {Component} from 'angular2/core';
import {OnChangeChildComponent} from './on-change-child.component';
import {Entity} from './entity';
@Component({
selector: 'on-change',
directives: [OnChangeChildComponent],
template: `<h3>OnChanges</h3>
<on-change-child [textValue]="textValue" [entityValue]="entityValue" [numericValue]="numericValue"></on-change-child>
<button (click)="changeValues()">Change Values</button>
`
})
export class OnChangeComponent {
textValue: string = 'Text Value';
entityValue: Entity = new Entity(1, 'Entity');
numericValue: number = 1;
changeValues() {
this.textValue = this.textValue + '1';
this.numericValue = this.numericValue + 1;
this.entityValue.name = this.entityValue.name + '1';
}
} | mit |
Hexeption/Youtube-Hacked-Client-1.8 | minecraft/net/minecraft/network/play/server/S28PacketEffect.java | 2250 | package net.minecraft.network.play.server;
import java.io.IOException;
import net.minecraft.network.INetHandler;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.INetHandlerPlayClient;
import net.minecraft.util.BlockPos;
public class S28PacketEffect implements Packet
{
private int soundType;
private BlockPos field_179747_b;
/** can be a block/item id or other depending on the soundtype */
private int soundData;
/** If true the sound is played across the server */
private boolean serverWide;
private static final String __OBFID = "CL_00001307";
public S28PacketEffect() {}
public S28PacketEffect(int p_i45978_1_, BlockPos p_i45978_2_, int p_i45978_3_, boolean p_i45978_4_)
{
this.soundType = p_i45978_1_;
this.field_179747_b = p_i45978_2_;
this.soundData = p_i45978_3_;
this.serverWide = p_i45978_4_;
}
/**
* Reads the raw packet data from the data stream.
*/
public void readPacketData(PacketBuffer data) throws IOException
{
this.soundType = data.readInt();
this.field_179747_b = data.readBlockPos();
this.soundData = data.readInt();
this.serverWide = data.readBoolean();
}
/**
* Writes the raw packet data to the data stream.
*/
public void writePacketData(PacketBuffer data) throws IOException
{
data.writeInt(this.soundType);
data.writeBlockPos(this.field_179747_b);
data.writeInt(this.soundData);
data.writeBoolean(this.serverWide);
}
public void func_180739_a(INetHandlerPlayClient p_180739_1_)
{
p_180739_1_.handleEffect(this);
}
public boolean isSoundServerwide()
{
return this.serverWide;
}
public int getSoundType()
{
return this.soundType;
}
public int getSoundData()
{
return this.soundData;
}
public BlockPos func_179746_d()
{
return this.field_179747_b;
}
/**
* Passes this Packet on to the NetHandler for processing.
*/
public void processPacket(INetHandler handler)
{
this.func_180739_a((INetHandlerPlayClient)handler);
}
}
| mit |
Xon/XenForo2-RedisCache | upload/src/addons/SV/RedisCache/_no_upload/config.redis-example-single-slave.php | 978 | <?php
// setup redis caching
$config['cache']['enabled'] = true;
$config['cache']['provider'] = 'SV\RedisCache\Redis';
// all keys and their defaults
$config['cache']['config'] = array(
'server' => '127.0.0.1',
'port' => 6379,
'timeout' => 2.5,
'persistent' => null,
'force_standalone' => false,
'connect_retries' => 1,
'read_timeout' => null,
'password' => null,
'database' => 0,
'compress_data' => 1,
'lifetimelimit' => 2592000,
'compress_threshold' => 20480,
'compression_lib' => null, // dynamically select first of; snappy,lzf,l4z,gzip IF EMPTY/null
'use_lua' => true,
'serializer' => 'igbinary', // to disable set ot 'php'
'retry_reads_on_master' => false,
);
// single slave (has most of the details of config):
$config['cache']['config']['load_from_slave'] = array(
'server' => '127.0.0.1',
'port' => 6378,
);
| mit |
andy-goryachev/PasswordSafeFX | src/goryachev/common/util/platform/SysInfo.java | 5002 | // Copyright © 2009-2017 Andy Goryachev <[email protected]>
package goryachev.common.util.platform;
import goryachev.common.util.CKit;
import goryachev.common.util.CList;
import goryachev.common.util.CSorter;
import goryachev.common.util.Hex;
import goryachev.common.util.SB;
import java.security.Security;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.Properties;
public class SysInfo
{
protected DecimalFormat numberFormat = new DecimalFormat("#,##0.##");
protected final Out out;
public SysInfo(Out out)
{
this.out = out;
}
/** generates system information report as text string */
public static String getSystemInfo()
{
StringOut out = new StringOut();
SysInfo s = new SysInfo(out);
s.extractApp();
s.extractEnvironment();
s.extractSystemProperties();
return out.getReport();
}
protected void header(String title)
{
out.header(title);
}
protected void nl()
{
out.nl();
}
protected void print(String x)
{
print(1, x);
}
protected void print(int indents, String x)
{
out.print(indents, x);
}
protected String number(Object x)
{
return numberFormat.format(x);
}
protected String safe(String s)
{
if(s != null)
{
boolean notSafe = false;
int sz = s.length();
for(int i=0; i<sz; i++)
{
char c = s.charAt(i);
if(c < 0x20)
{
notSafe = true;
break;
}
}
if(notSafe)
{
SB sb = new SB(sz);
for(int i=0; i<sz; i++)
{
char c = s.charAt(i);
if(c < 0x20)
{
sb.a(unicode(c));
}
else
{
sb.a(c);
}
}
s = sb.toString();
}
}
return s;
}
protected static String unicode(char c)
{
return "\\u" + Hex.toHexString(c, 4);
}
public void extractApp()
{
print("Time: " + new SimpleDateFormat("yyyy-MMdd HH:mm:ss").format(System.currentTimeMillis()));
long max = Runtime.getRuntime().maxMemory();
long free = max - Runtime.getRuntime().totalMemory() + Runtime.getRuntime().freeMemory();
print("Available Memory: " + number(max));
print("Free Memory:" + number(free));
nl();
}
public void extractEnvironment()
{
header("Environment");
Map<String,String> env = System.getenv();
CList<String> keys = new CList<>(env.keySet());
CSorter.sort(keys);
for(String key: keys)
{
print(key + " = " + safe(env.get(key)));
}
nl();
}
public void extractSystemProperties()
{
header("System Properties");
Properties p = System.getProperties();
CList<String> keys = new CList<>(p.stringPropertyNames());
CSorter.sort(keys);
for(String key: keys)
{
print(key + " = " + safe(p.getProperty(key)));
}
nl();
}
public void extractSecurity()
{
header("Security");
listSecurityAlgorithms("Cipher");
listSecurityAlgorithms("KeyStore");
listSecurityAlgorithms("Mac");
listSecurityAlgorithms("MessageDigest");
listSecurityAlgorithms("Signature");
nl();
}
protected void listSecurityAlgorithms(String name)
{
print(name);
try
{
CList<String> names = new CList<>(Security.getAlgorithms(name));
CSorter.sort(names);
for(String s: names)
{
print(2, s);
}
}
catch(Exception e)
{
print(CKit.stackTrace(e));
}
}
//
public abstract static class Out
{
public abstract void header(String title);
public abstract void nl();
public abstract void print(int count, String x);
public abstract void describe(Object key, Object v);
public abstract Out a(Object x);
//
protected void describe(Object x)
{
if(x == null)
{
}
else if(x instanceof String)
{
a('"');
a(x);
a('"');
}
else if(x instanceof Object[])
{
Object[] a = (Object[])x;
a("Object[");
a(a.length);
a("]");
}
else if(x instanceof int[])
{
int[] a = (int[])x;
a("int[");
a(a.length);
a("]");
}
else
{
a(x);
}
}
}
//
public static class StringOut
extends Out
{
private final SB sb;
private String indent = "\t";
public StringOut()
{
sb = new SB();
}
public Out a(Object x)
{
sb.a(x);
return this;
}
public void header(String title)
{
sb.a(title).nl();
}
public void nl()
{
sb.nl();
}
public void print(int count, String x)
{
for(int i=0; i<count; i++)
{
sb.a(indent);
}
sb.append(x);
sb.nl();
}
public void describe(Object key, Object v)
{
sb.a(indent);
sb.a(key);
sb.a(" = ");
describe(sb, v);
sb.nl();
}
public String getReport()
{
return sb.getAndClear();
}
}
}
| mit |
codetitlan/codetitlan-org | .storybook/i18next.js | 586 | import { initReactI18next } from 'react-i18next';
import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
const ns = ['translation'];
const supportedLngs = ['en'];
i18n
.use(initReactI18next)
.use(LanguageDetector)
.init({
debug:
process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test',
fallbackLng: 'en',
interpolation: { escapeValue: false },
});
supportedLngs.forEach(lang => {
ns.forEach(n =>
i18n.addResources(lang, n, require(`../src/locales/${lang}/${n}.json`)),
);
});
export { i18n };
| mit |
mpapis/gh_contributors | lib/plugins/gh_contributors/reader/repo.rb | 165 | class GhContributors::Reader::Repo
def self.load(name)
data = load_json("repos/#{name}/contributors")
yield(data, name) if block_given?
data
end
end
| mit |
pinax/django-user-accounts | account/tests/settings.py | 1517 | DEBUG = True
USE_TZ = True
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.messages",
"account",
"account.tests",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
SITE_ID = 1
ROOT_URLCONF = "account.tests.urls"
SECRET_KEY = "notasecret"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [
# insert your TEMPLATE_DIRS here
],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
# Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
# list if you haven"t customized them:
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.debug",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
],
},
},
]
MIDDLEWARE = [
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware"
]
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
| mit |
gurkenlabs/litiengine | core/src/main/java/de/gurkenlabs/litiengine/graphics/emitters/particles/PolygonParticle.java | 1232 | package de.gurkenlabs.litiengine.graphics.emitters.particles;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
public class PolygonParticle extends ShapeParticle {
private int sides;
public PolygonParticle(float width, float height, int sides) {
super(width, height);
this.sides = sides;
}
@Override
protected Shape getShape(Point2D emitterOrigin) {
Path2D path = new Path2D.Double();
double x = this.getAbsoluteX(emitterOrigin) + this.getWidth() / 2;
double y = this.getAbsoluteY(emitterOrigin) + this.getHeight() / 2;
double theta = 2 * Math.PI / this.sides;
path.moveTo(x + this.getWidth(), y + 0);
for (int i = 0; i < this.sides; i++) {
path.lineTo(
x + this.getWidth() * Math.cos(theta * i),
y + this.getHeight() * Math.sin(theta * i));
}
path.closePath();
final AffineTransform rotate =
AffineTransform.getRotateInstance(
Math.toRadians(this.getAngle()),
this.getAbsoluteX(emitterOrigin) + this.getWidth() * 0.5,
this.getAbsoluteY(emitterOrigin) + this.getHeight() * 0.5);
return rotate.createTransformedShape(path);
}
}
| mit |
lordmos/blink | LayoutTests/svg/dynamic-updates/script-tests/SVGForeignObjectElement-svgdom-requiredFeatures.js | 1836 | // [Name] SVGForeignObjectElement-svgdom-requiredFeatures.js
// [Expected rendering result] a series of PASS messages
createSVGTestCase();
var foreignObjectElement = createSVGElement("foreignObject");
foreignObjectElement.setAttribute("width", "200");
foreignObjectElement.setAttribute("height", "200");
var htmlDivElement = document.createElementNS(xhtmlNS, "xhtml:div");
htmlDivElement.setAttribute("style", "background-color: green; color: white; text-align: center");
htmlDivElement.textContent = "Test passed";
foreignObjectElement.appendChild(htmlDivElement);
rootSVGElement.appendChild(foreignObjectElement);
function repaintTest() {
debug("Check that SVGForeignObjectElement is initially displayed");
shouldHaveBBox("foreignObjectElement", "200", "200");
debug("Check that setting requiredFeatures to something invalid makes it not render");
foreignObjectElement.requiredFeatures.appendItem("http://www.w3.org/TR/SVG11/feature#BogusFeature");
shouldHaveBBox("foreignObjectElement", "0", "0");
debug("Check that setting requiredFeatures to something valid makes it render again");
foreignObjectElement.requiredFeatures.replaceItem("http://www.w3.org/TR/SVG11/feature#Shape", 0);
shouldHaveBBox("foreignObjectElement", "200", "200");
debug("Check that adding something valid to requiredFeatures keeps rendering the element");
foreignObjectElement.requiredFeatures.appendItem("http://www.w3.org/TR/SVG11/feature#Gradient");
shouldHaveBBox("foreignObjectElement", "200", "200");
debug("Check that adding something invalid to requiredFeatures makes it not render");
foreignObjectElement.requiredFeatures.appendItem("http://www.w3.org/TR/SVG11/feature#BogusFeature");
shouldHaveBBox("foreignObjectElement", "0", "0");
completeTest();
}
var successfullyParsed = true;
| mit |
IGZjonasdacruz/igz-enterprise-geoshare | src/server/test/user-test.js | 5199 | var should = require('should'),
sanitize = require('validator').sanitize;
var VALID_USER = {
_id: '09477529074259',
email: '[email protected]',
domain: 'test.com'
};
var lat = sanitize("40.421431").toFloat();
var lng = sanitize("-3.705434").toFloat();
var userManager = require('../lib/manager/user');
var userDao = require('../lib/dao/user');
describe('manager/user.js', function() {
beforeEach(function(done){
userDao.reset(function () {
userDao.get(VALID_USER._id, function(err, userDB) {
should.not.exist(err);
should.not.exist(userDB);
done();
});
});
});
describe('saveLocation', function() {
it('There is no error', function(done) {
userManager.saveLocation(undefined, undefined, undefined, function(err, userDB) {
should.exist(err);
should.not.exist(userDB);
done();
});
});
it('Invalid position param', function(done) {
userManager.saveLocation(VALID_USER, 1, 'string', function(err, userDB) {
should.exist(err);
should.not.exist(userDB);
done();
});
});
it('Valid position', function(done) {
userManager.saveLocation(VALID_USER, lat, lng, function(err, userDB) {
should.not.exist(err);
should.exist(userDB);
userDB._id.should.equal(VALID_USER._id);
userDB.domain.should.equal(VALID_USER.domain);
userDB.email.should.equal(VALID_USER.email);
userDB.location.coordinates[0].should.equal(lng);
userDB.location.coordinates[1].should.equal(lat);
done();
});
});
});
describe('myNearestContacts', function() {
describe('Invalid parameters', function() {
it('Invalid user', function(done) {
userManager.myNearestContacts(undefined, function(err, result) {
should.exist(err);
should.not.exist(result);
done();
});
});
it('Invalid user id', function(done) {
userManager.myNearestContacts({}, function(err, result) {
should.exist(err);
should.not.exist(result);
done();
});
});
it('Invalid user domain', function(done) {
userManager.myNearestContacts({_id: VALID_USER._id}, function(err, result) {
should.exist(err);
should.not.exist(result);
done();
});
});
});
describe('Valid parameters', function() {
beforeEach(function (done) {
// Create user
userManager.saveLocation(VALID_USER, lat, lng, function(err, userDB) {
should.not.exist(err);
should.exist(userDB);
userDB._id.should.equal(VALID_USER._id);
userDB.domain.should.equal(VALID_USER.domain);
userDB.email.should.equal(VALID_USER.email);
userDB.location.coordinates[0].should.equal(lng);
userDB.location.coordinates[1].should.equal(lat);
done();
});
});
it('valid user, no contacts', function(done) {
userManager.myNearestContacts(VALID_USER, function(err, result) {
should.not.exist(err);
result.should.be.an.instanceOf(Array).and.be.empty;
done();
});
describe('valid user with contacts', function() {
it('Add a near user of the same domain', function(done) {
userManager.saveLocation({
_id: '09477529074260',
email: '[email protected]',
domain: 'test.com'
}, lat + 0.00001, lng, done);
});
it('Add a near user of the other domain', function(done) {
userManager.saveLocation({
_id: '09477529074261',
email: '[email protected]',
domain: 'test2.com'
}, lat + 0.00001, lng, done);
});
it('Add a remote user of the same domain', function(done) {
userManager.saveLocation({
_id: '09477529074262',
email: '[email protected]',
domain: 'test.com'
}, lat + 10, lng, done);
});
it('Retrieve the nearest contacts', function(done) {
userManager.myNearestContacts(VALID_USER, function(err, result) {
should.not.exist(err);
result.should.be.an.instanceOf(Array).with.a.lengthOf(1);
result[0].email.should.equal('[email protected]');
done();
});
});
});
});
});
});
describe('ChangeGcmId', function() {
beforeEach(function (done) {
// Create user
userManager.saveLocation(VALID_USER, lat, lng, function(err, userDB) {
should.not.exist(err);
should.exist(userDB);
userDB._id.should.equal(VALID_USER._id);
userDB.domain.should.equal(VALID_USER.domain);
userDB.email.should.equal(VALID_USER.email);
userDB.location.coordinates[0].should.equal(lng);
userDB.location.coordinates[1].should.equal(lat);
done();
});
});
it('Invalid gcm id', function (done) {
userManager.changeGcmId(VALID_USER, null, function (err, result) {
should.exist(err);
should.not.exist(result);
done();
})
});
it('Valid gcm id', function (done) {
const VALID_GCM_ID = '123456789012345678901234567890';
userManager.changeGcmId(VALID_USER, VALID_GCM_ID, function (err, result) {
should.not.exist(err);
should.exist(result);
result.should.equal(1);
userDao.get(VALID_USER._id, function (err, userDB) {
should.not.exist(err);
should.exist(userDB);
should.exist(userDB.gcmId);
userDB.gcmId.should.equal(VALID_GCM_ID);
done();
});
});
});
});
}); | mit |
yyx990803/buble | src/utils/destructure.js | 8001 | import CompileError from '../utils/CompileError.js';
import { findIndex } from './array.js';
const handlers = {
Identifier: destructureIdentifier,
AssignmentPattern: destructureAssignmentPattern,
ArrayPattern: destructureArrayPattern,
ObjectPattern: destructureObjectPattern
};
export default function destructure(
code,
createIdentifier,
resolveName,
node,
ref,
inline,
statementGenerators
) {
handlers[node.type](code, createIdentifier, resolveName, node, ref, inline, statementGenerators);
}
function destructureIdentifier(
code,
createIdentifier,
resolveName,
node,
ref,
inline,
statementGenerators
) {
statementGenerators.push((start, prefix, suffix) => {
code.overwrite(node.start, node.end, (inline ? prefix : `${prefix}var `) + resolveName(node) + ` = ${ref}${suffix}`);
code.move(node.start, node.end, start);
});
}
function destructureMemberExpression(
code,
createIdentifier,
resolveName,
node,
ref,
inline,
statementGenerators
) {
statementGenerators.push((start, prefix, suffix) => {
code.prependRight(node.start, inline ? prefix : `${prefix}var `);
code.appendLeft(node.end, ` = ${ref}${suffix}`);
code.move(node.start, node.end, start);
});
}
function destructureAssignmentPattern(
code,
createIdentifier,
resolveName,
node,
ref,
inline,
statementGenerators
) {
const isIdentifier = node.left.type === 'Identifier';
const name = isIdentifier ? node.left.name : ref;
if (!inline) {
statementGenerators.push((start, prefix, suffix) => {
code.prependRight(
node.left.end,
`${prefix}if ( ${name} === void 0 ) ${name}`
);
code.move(node.left.end, node.right.end, start);
code.appendLeft(node.right.end, suffix);
});
}
if (!isIdentifier) {
destructure(code, createIdentifier, resolveName, node.left, ref, inline, statementGenerators);
}
}
function destructureArrayPattern(
code,
createIdentifier,
resolveName,
node,
ref,
inline,
statementGenerators
) {
let c = node.start;
node.elements.forEach((element, i) => {
if (!element) return;
if (element.type === 'RestElement') {
handleProperty(
code,
createIdentifier,
resolveName,
c,
element.argument,
`${ref}.slice(${i})`,
inline,
statementGenerators
);
} else {
handleProperty(
code,
createIdentifier,
resolveName,
c,
element,
`${ref}[${i}]`,
inline,
statementGenerators
);
}
c = element.end;
});
code.remove(c, node.end);
}
function destructureObjectPattern(
code,
createIdentifier,
resolveName,
node,
ref,
inline,
statementGenerators
) {
let c = node.start;
const nonRestKeys = [];
node.properties.forEach(prop => {
let value;
let content;
if (prop.type === 'Property') {
const isComputedKey = prop.computed || prop.key.type !== 'Identifier';
const key = isComputedKey
? code.slice(prop.key.start, prop.key.end)
: prop.key.name;
value = isComputedKey ? `${ref}[${key}]` : `${ref}.${key}`;
content = prop.value;
nonRestKeys.push(isComputedKey ? key : '"' + key + '"');
} else if (prop.type === 'RestElement') {
content = prop.argument;
value = createIdentifier('rest');
statementGenerators.push((start, prefix, suffix) => {
const helper = prop.program.getObjectWithoutPropertiesHelper(code);
code.overwrite(
prop.start,
(c = prop.argument.start),
(inline ? prefix : `${prefix}var `) + `${value} = ${helper}( ${ref}, [${nonRestKeys.join(', ')}] )${suffix}`
);
code.move(prop.start, c, start);
});
} else {
throw new CompileError(
this,
`Unexpected node of type ${prop.type} in object pattern`
);
}
handleProperty(code, createIdentifier, resolveName, c, content, value, inline, statementGenerators);
c = prop.end;
});
code.remove(c, node.end);
}
function handleProperty(
code,
createIdentifier,
resolveName,
c,
node,
value,
inline,
statementGenerators
) {
switch (node.type) {
case 'Identifier': {
code.remove(c, node.start);
destructureIdentifier(
code,
createIdentifier,
resolveName,
node,
value,
inline,
statementGenerators
);
break;
}
case 'MemberExpression':
code.remove(c, node.start);
destructureMemberExpression(
code,
createIdentifier,
resolveName,
node,
value,
true,
statementGenerators
);
break;
case 'AssignmentPattern': {
let name;
const isIdentifier = node.left.type === 'Identifier';
if (isIdentifier) {
name = resolveName(node.left);
} else {
name = createIdentifier(value);
}
statementGenerators.push((start, prefix, suffix) => {
if (inline) {
code.prependRight(
node.right.start,
`${name} = ${value}, ${name} = ${name} === void 0 ? `
);
code.appendLeft(node.right.end, ` : ${name}${suffix}`);
} else {
code.prependRight(
node.right.start,
`${prefix}var ${name} = ${value}; if ( ${name} === void 0 ) ${name} = `
);
code.appendLeft(node.right.end, suffix);
}
code.move(node.right.start, node.right.end, start);
});
if (isIdentifier) {
code.remove(c, node.right.start);
} else {
code.remove(c, node.left.start);
code.remove(node.left.end, node.right.start);
handleProperty(
code,
createIdentifier,
resolveName,
c,
node.left,
name,
inline,
statementGenerators
);
}
break;
}
case 'ObjectPattern': {
code.remove(c, (c = node.start));
let ref = value;
if (node.properties.length > 1) {
ref = createIdentifier(value);
statementGenerators.push((start, prefix, suffix) => {
// this feels a tiny bit hacky, but we can't do a
// straightforward appendLeft and keep correct order...
code.prependRight(node.start, (inline ? '' : `${prefix}var `) + `${ref} = `);
code.overwrite(node.start, (c = node.start + 1), value);
code.appendLeft(c, suffix);
code.overwrite(
node.start,
(c = node.start + 1),
(inline ? '' : `${prefix}var `) + `${ref} = ${value}${suffix}`
);
code.move(node.start, c, start);
});
}
destructureObjectPattern(
code,
createIdentifier,
resolveName,
node,
ref,
inline,
statementGenerators
);
break;
}
case 'ArrayPattern': {
code.remove(c, (c = node.start));
if (node.elements.filter(Boolean).length > 1) {
const ref = createIdentifier(value);
statementGenerators.push((start, prefix, suffix) => {
code.prependRight(node.start, (inline ? '' : `${prefix}var `) + `${ref} = `);
code.overwrite(node.start, (c = node.start + 1), value, {
contentOnly: true
});
code.appendLeft(c, suffix);
code.move(node.start, c, start);
});
node.elements.forEach((element, i) => {
if (!element) return;
if (element.type === 'RestElement') {
handleProperty(
code,
createIdentifier,
resolveName,
c,
element.argument,
`${ref}.slice(${i})`,
inline,
statementGenerators
);
} else {
handleProperty(
code,
createIdentifier,
resolveName,
c,
element,
`${ref}[${i}]`,
inline,
statementGenerators
);
}
c = element.end;
});
} else {
const index = findIndex(node.elements, Boolean);
const element = node.elements[index];
if (element.type === 'RestElement') {
handleProperty(
code,
createIdentifier,
resolveName,
c,
element.argument,
`${value}.slice(${index})`,
inline,
statementGenerators
);
} else {
handleProperty(
code,
createIdentifier,
resolveName,
c,
element,
`${value}[${index}]`,
inline,
statementGenerators
);
}
c = element.end;
}
code.remove(c, node.end);
break;
}
default: {
throw new Error(`Unexpected node type in destructuring (${node.type})`);
}
}
}
| mit |
usartkom/materials | extract_features.lua | 2175 | local csv = require 'csvigo'
local path = require 'paths'
require 'nn'
require 'torch'
require 'image'
tempfilename = "ae_features.csv"
-- saving model
modelName = '/AE_model.net'
filename = path.cwd() .. modelName
if path.filep(filename) then
print("Model exists!")
model = torch.load(filename)
autoencoder = model:get(1)
print(autoencoder)
end
function rgb2gray(im)
-- Image.rgb2y uses a different weight mixture
local dim, w, h = im:size()[1], im:size()[2], im:size()[3]
if dim ~= 3 then
print('<error> expected 3 channels')
return im
end
-- a cool application of tensor:select
local r = im:select(1, 1):csub(124)
local g = im:select(1, 2):csub(117)
local b = im:select(1, 3):csub(104)
local z = torch.Tensor(w, h):zero()
-- z = z + 0.21r
z = z:add(0.21, r)
z = z:add(0.72, g)
z = z:add(0.07, b)
return z
end
local img
local temp
local output
-- local loader = require "loader"
-- local XTrain = loader:load_fmd('/Users/art/datasets/materials_textures/materials_textures/fmd/images_cropped_256/'):float():div(255)
-- autoencoder:forward(XTrain)
csvf = csv.File(tempfilename, "w")
local file = io.open("/opt/home/datasets/materials_textures/fmd/FMD_paths.txt")
if file then
for line in file:lines() do
--line = '/Users/art/datasets/materials_textures/materials_textures/fmd/images_cropped_256/fabric/fabric_moderate_001_new.jpg'
--print(line)
temp = torch.Tensor(1,256,256)
img = image.load(line)
temp[1] = rgb2gray(img)
temp = temp:float():div(255)
--print(#temp)
output = autoencoder:forward(temp)
--print(output:size())
output = output:view(-1)
--print(output:size())
list = output:totable()
--print(#list)
table.insert(list, 1, line)
csvf:write(list)
end
else
end
csvf:close()
-- local combine = function(list, features)
-- for i,val in ipairs(features) do
--
-- end
--
-- return list
-- end
-- -- test writing file
-- function writeRecs(csvf)
-- csvf:write({"a","b","c"})
-- csvf:write({01, 02, 03})
-- csvf:write({11, 12, 13})
-- end
--
--
-- csvf = csv.File(tempfilename, "w")
-- writeRecs(csvf)
-- csvf:close()
| mit |
zhangbobell/mallshop | plugins/onekey/taobao/top/request/FenxiaoProductAddRequest.php | 13688 | <?php
/**
* TOP API: taobao.fenxiao.product.add request
*
* @author auto create
* @since 1.0, 2014-09-13 16:51:04
*/
class FenxiaoProductAddRequest
{
/**
* 警戒库存必须是0到29999。
**/
private $alarmNumber;
/**
* 所属类目id,参考Taobao.itemcats.get,不支持成人等类目,输入成人类目id保存提示类目属性错误。
**/
private $categoryId;
/**
* 所在地:市,例:“杭州”
**/
private $city;
/**
* 代销采购价格,单位:元。例:“10.56”。必须在0.01元到10000000元之间。
**/
private $costPrice;
/**
* 经销采购价,单位:元。例:“10.56”。必须在0.01元到10000000元之间。
**/
private $dealerCostPrice;
/**
* 产品描述,长度为5到25000字符。
**/
private $desc;
/**
* 折扣ID
**/
private $discountId;
/**
* 是否有保修,可选值:false(否)、true(是),默认false。
**/
private $haveGuarantee;
/**
* 是否有发票,可选值:false(否)、true(是),默认false。
**/
private $haveInvoice;
/**
* 产品主图,大小不超过500k,格式为gif,jpg,jpeg,png,bmp等图片
**/
private $image;
/**
* 自定义属性。格式为pid:value;pid:value
**/
private $inputProperties;
/**
* 添加产品时,添加入参isAuthz:yes|no
yes:需要授权
no:不需要授权
默认是需要授权
**/
private $isAuthz;
/**
* 导入的商品ID
**/
private $itemId;
/**
* 产品名称,长度不超过60个字节。
**/
private $name;
/**
* 商家编码,长度不能超过60个字节。
**/
private $outerId;
/**
* 产品主图图片空间相对路径或绝对路径
**/
private $picPath;
/**
* ems费用,单位:元。例:“10.56”。 大小为0.00元到999999元之间。
**/
private $postageEms;
/**
* 快递费用,单位:元。例:“10.56”。 大小为0.01元到999999元之间。
**/
private $postageFast;
/**
* 运费模板ID,参考taobao.postages.get。
**/
private $postageId;
/**
* 平邮费用,单位:元。例:“10.56”。 大小为0.01元到999999元之间。
**/
private $postageOrdinary;
/**
* 运费类型,可选值:seller(供应商承担运费)、buyer(分销商承担运费),默认seller。
**/
private $postageType;
/**
* 产品线ID
**/
private $productcatId;
/**
* 产品属性,格式为pid:vid;pid:vid
**/
private $properties;
/**
* 属性别名,格式为:pid:vid:alias;pid:vid:alias(alias为别名)
**/
private $propertyAlias;
/**
* 所在地:省,例:“浙江”
**/
private $prov;
/**
* 产品库存必须是1到999999。
**/
private $quantity;
/**
* 最高零售价,单位:元。例:“10.56”。必须在0.01元到10000000元之间,最高零售价必须大于最低零售价。
**/
private $retailPriceHigh;
/**
* 最低零售价,单位:元。例:“10.56”。必须在0.01元到10000000元之间。
**/
private $retailPriceLow;
/**
* sku的采购价。如果多个,用逗号分隔,并与其他sku信息保持相同顺序
**/
private $skuCostPrices;
/**
* sku的经销采购价。如果多个,用逗号分隔,并与其他sku信息保持相同顺序。其中每个值的单位:元。例:“10.56,12.3”。必须在0.01元到10000000元之间。
**/
private $skuDealerCostPrices;
/**
* sku的商家编码。如果多个,用逗号分隔,并与其他sku信息保持相同顺序
**/
private $skuOuterIds;
/**
* sku的属性。如果多个,用逗号分隔,并与其他sku信息保持相同顺序
**/
private $skuProperties;
/**
* sku的库存。如果多个,用逗号分隔,并与其他sku信息保持相同顺序
**/
private $skuQuantitys;
/**
* sku的采购基准价。如果多个,用逗号分隔,并与其他sku信息保持相同顺序
**/
private $skuStandardPrices;
/**
* 产品spuID,达尔文产品必须要传spuID,否则不能发布。其他非达尔文产品,看情况传
**/
private $spuId;
/**
* 采购基准价格,单位:元。例:“10.56”。必须在0.01元到10000000元之间。
**/
private $standardPrice;
/**
* 零售基准价,单位:元。例:“10.56”。必须在0.01元到10000000元之间。
**/
private $standardRetailPrice;
/**
* 分销方式:AGENT(只做代销,默认值)、DEALER(只做经销)、ALL(代销和经销都做)
**/
private $tradeType;
private $apiParas = array();
public function setAlarmNumber($alarmNumber)
{
$this->alarmNumber = $alarmNumber;
$this->apiParas["alarm_number"] = $alarmNumber;
}
public function getAlarmNumber()
{
return $this->alarmNumber;
}
public function setCategoryId($categoryId)
{
$this->categoryId = $categoryId;
$this->apiParas["category_id"] = $categoryId;
}
public function getCategoryId()
{
return $this->categoryId;
}
public function setCity($city)
{
$this->city = $city;
$this->apiParas["city"] = $city;
}
public function getCity()
{
return $this->city;
}
public function setCostPrice($costPrice)
{
$this->costPrice = $costPrice;
$this->apiParas["cost_price"] = $costPrice;
}
public function getCostPrice()
{
return $this->costPrice;
}
public function setDealerCostPrice($dealerCostPrice)
{
$this->dealerCostPrice = $dealerCostPrice;
$this->apiParas["dealer_cost_price"] = $dealerCostPrice;
}
public function getDealerCostPrice()
{
return $this->dealerCostPrice;
}
public function setDesc($desc)
{
$this->desc = $desc;
$this->apiParas["desc"] = $desc;
}
public function getDesc()
{
return $this->desc;
}
public function setDiscountId($discountId)
{
$this->discountId = $discountId;
$this->apiParas["discount_id"] = $discountId;
}
public function getDiscountId()
{
return $this->discountId;
}
public function setHaveGuarantee($haveGuarantee)
{
$this->haveGuarantee = $haveGuarantee;
$this->apiParas["have_guarantee"] = $haveGuarantee;
}
public function getHaveGuarantee()
{
return $this->haveGuarantee;
}
public function setHaveInvoice($haveInvoice)
{
$this->haveInvoice = $haveInvoice;
$this->apiParas["have_invoice"] = $haveInvoice;
}
public function getHaveInvoice()
{
return $this->haveInvoice;
}
public function setImage($image)
{
$this->image = $image;
$this->apiParas["image"] = $image;
}
public function getImage()
{
return $this->image;
}
public function setInputProperties($inputProperties)
{
$this->inputProperties = $inputProperties;
$this->apiParas["input_properties"] = $inputProperties;
}
public function getInputProperties()
{
return $this->inputProperties;
}
public function setIsAuthz($isAuthz)
{
$this->isAuthz = $isAuthz;
$this->apiParas["is_authz"] = $isAuthz;
}
public function getIsAuthz()
{
return $this->isAuthz;
}
public function setItemId($itemId)
{
$this->itemId = $itemId;
$this->apiParas["item_id"] = $itemId;
}
public function getItemId()
{
return $this->itemId;
}
public function setName($name)
{
$this->name = $name;
$this->apiParas["name"] = $name;
}
public function getName()
{
return $this->name;
}
public function setOuterId($outerId)
{
$this->outerId = $outerId;
$this->apiParas["outer_id"] = $outerId;
}
public function getOuterId()
{
return $this->outerId;
}
public function setPicPath($picPath)
{
$this->picPath = $picPath;
$this->apiParas["pic_path"] = $picPath;
}
public function getPicPath()
{
return $this->picPath;
}
public function setPostageEms($postageEms)
{
$this->postageEms = $postageEms;
$this->apiParas["postage_ems"] = $postageEms;
}
public function getPostageEms()
{
return $this->postageEms;
}
public function setPostageFast($postageFast)
{
$this->postageFast = $postageFast;
$this->apiParas["postage_fast"] = $postageFast;
}
public function getPostageFast()
{
return $this->postageFast;
}
public function setPostageId($postageId)
{
$this->postageId = $postageId;
$this->apiParas["postage_id"] = $postageId;
}
public function getPostageId()
{
return $this->postageId;
}
public function setPostageOrdinary($postageOrdinary)
{
$this->postageOrdinary = $postageOrdinary;
$this->apiParas["postage_ordinary"] = $postageOrdinary;
}
public function getPostageOrdinary()
{
return $this->postageOrdinary;
}
public function setPostageType($postageType)
{
$this->postageType = $postageType;
$this->apiParas["postage_type"] = $postageType;
}
public function getPostageType()
{
return $this->postageType;
}
public function setProductcatId($productcatId)
{
$this->productcatId = $productcatId;
$this->apiParas["productcat_id"] = $productcatId;
}
public function getProductcatId()
{
return $this->productcatId;
}
public function setProperties($properties)
{
$this->properties = $properties;
$this->apiParas["properties"] = $properties;
}
public function getProperties()
{
return $this->properties;
}
public function setPropertyAlias($propertyAlias)
{
$this->propertyAlias = $propertyAlias;
$this->apiParas["property_alias"] = $propertyAlias;
}
public function getPropertyAlias()
{
return $this->propertyAlias;
}
public function setProv($prov)
{
$this->prov = $prov;
$this->apiParas["prov"] = $prov;
}
public function getProv()
{
return $this->prov;
}
public function setQuantity($quantity)
{
$this->quantity = $quantity;
$this->apiParas["quantity"] = $quantity;
}
public function getQuantity()
{
return $this->quantity;
}
public function setRetailPriceHigh($retailPriceHigh)
{
$this->retailPriceHigh = $retailPriceHigh;
$this->apiParas["retail_price_high"] = $retailPriceHigh;
}
public function getRetailPriceHigh()
{
return $this->retailPriceHigh;
}
public function setRetailPriceLow($retailPriceLow)
{
$this->retailPriceLow = $retailPriceLow;
$this->apiParas["retail_price_low"] = $retailPriceLow;
}
public function getRetailPriceLow()
{
return $this->retailPriceLow;
}
public function setSkuCostPrices($skuCostPrices)
{
$this->skuCostPrices = $skuCostPrices;
$this->apiParas["sku_cost_prices"] = $skuCostPrices;
}
public function getSkuCostPrices()
{
return $this->skuCostPrices;
}
public function setSkuDealerCostPrices($skuDealerCostPrices)
{
$this->skuDealerCostPrices = $skuDealerCostPrices;
$this->apiParas["sku_dealer_cost_prices"] = $skuDealerCostPrices;
}
public function getSkuDealerCostPrices()
{
return $this->skuDealerCostPrices;
}
public function setSkuOuterIds($skuOuterIds)
{
$this->skuOuterIds = $skuOuterIds;
$this->apiParas["sku_outer_ids"] = $skuOuterIds;
}
public function getSkuOuterIds()
{
return $this->skuOuterIds;
}
public function setSkuProperties($skuProperties)
{
$this->skuProperties = $skuProperties;
$this->apiParas["sku_properties"] = $skuProperties;
}
public function getSkuProperties()
{
return $this->skuProperties;
}
public function setSkuQuantitys($skuQuantitys)
{
$this->skuQuantitys = $skuQuantitys;
$this->apiParas["sku_quantitys"] = $skuQuantitys;
}
public function getSkuQuantitys()
{
return $this->skuQuantitys;
}
public function setSkuStandardPrices($skuStandardPrices)
{
$this->skuStandardPrices = $skuStandardPrices;
$this->apiParas["sku_standard_prices"] = $skuStandardPrices;
}
public function getSkuStandardPrices()
{
return $this->skuStandardPrices;
}
public function setSpuId($spuId)
{
$this->spuId = $spuId;
$this->apiParas["spu_id"] = $spuId;
}
public function getSpuId()
{
return $this->spuId;
}
public function setStandardPrice($standardPrice)
{
$this->standardPrice = $standardPrice;
$this->apiParas["standard_price"] = $standardPrice;
}
public function getStandardPrice()
{
return $this->standardPrice;
}
public function setStandardRetailPrice($standardRetailPrice)
{
$this->standardRetailPrice = $standardRetailPrice;
$this->apiParas["standard_retail_price"] = $standardRetailPrice;
}
public function getStandardRetailPrice()
{
return $this->standardRetailPrice;
}
public function setTradeType($tradeType)
{
$this->tradeType = $tradeType;
$this->apiParas["trade_type"] = $tradeType;
}
public function getTradeType()
{
return $this->tradeType;
}
public function getApiMethodName()
{
return "taobao.fenxiao.product.add";
}
public function getApiParas()
{
return $this->apiParas;
}
public function check()
{
RequestCheckUtil::checkNotNull($this->alarmNumber,"alarmNumber");
RequestCheckUtil::checkNotNull($this->categoryId,"categoryId");
RequestCheckUtil::checkNotNull($this->city,"city");
RequestCheckUtil::checkNotNull($this->desc,"desc");
RequestCheckUtil::checkNotNull($this->haveGuarantee,"haveGuarantee");
RequestCheckUtil::checkNotNull($this->haveInvoice,"haveInvoice");
RequestCheckUtil::checkNotNull($this->name,"name");
RequestCheckUtil::checkNotNull($this->postageType,"postageType");
RequestCheckUtil::checkNotNull($this->productcatId,"productcatId");
RequestCheckUtil::checkNotNull($this->prov,"prov");
RequestCheckUtil::checkNotNull($this->quantity,"quantity");
RequestCheckUtil::checkNotNull($this->retailPriceHigh,"retailPriceHigh");
RequestCheckUtil::checkNotNull($this->retailPriceLow,"retailPriceLow");
RequestCheckUtil::checkNotNull($this->standardPrice,"standardPrice");
}
public function putOtherTextParam($key, $value) {
$this->apiParas[$key] = $value;
$this->$key = $value;
}
}
| mit |
djmcguigan/a3pluscg | A3PLUSCG.Web/Controllers/ManageController.cs | 14118 | using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using A3PLUSCG.Models;
namespace A3PLUSCG.Controllers
{
[Authorize]
public class ManageController : Controller
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
public ManageController()
{
}
public ManageController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
{
UserManager = userManager;
SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
//
// GET: /Manage/Index
public async Task<ActionResult> Index(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var userId = User.Identity.GetUserId();
var model = new IndexViewModel
{
HasPassword = HasPassword(),
PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
Logins = await UserManager.GetLoginsAsync(userId),
BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> RemoveLogin(string loginProvider, string providerKey)
{
ManageMessageId? message;
var result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
message = ManageMessageId.RemoveLoginSuccess;
}
else
{
message = ManageMessageId.Error;
}
return RedirectToAction("ManageLogins", new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public ActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number);
if (UserManager.SmsService != null)
{
var message = new IdentityMessage
{
Destination = model.Number,
Body = "Your security code is: " + code
};
await UserManager.SmsService.SendAsync(message);
}
return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EnableTwoFactorAuthentication()
{
await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true);
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DisableTwoFactorAuthentication()
{
await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), false);
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
public async Task<ActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), phoneNumber);
// Send an SMS through the SMS provider to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await UserManager.ChangePhoneNumberAsync(User.Identity.GetUserId(), model.PhoneNumber, model.Code);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess });
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "Failed to verify phone");
return View(model);
}
//
// POST: /Manage/RemovePhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> RemovePhoneNumber()
{
var result = await UserManager.SetPhoneNumberAsync(User.Identity.GetUserId(), null);
if (!result.Succeeded)
{
return RedirectToAction("Index", new { Message = ManageMessageId.Error });
}
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess });
}
//
// GET: /Manage/ChangePassword
public ActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
//
// GET: /Manage/SetPassword
public ActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SetPassword(SetPasswordViewModel model)
{
if (ModelState.IsValid)
{
var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Manage/ManageLogins
public async Task<ActionResult> ManageLogins(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user == null)
{
return View("Error");
}
var userLogins = await UserManager.GetLoginsAsync(User.Identity.GetUserId());
var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList();
ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
return new AccountController.ChallengeResult(provider, Url.Action("LinkLoginCallback", "Manage"), User.Identity.GetUserId());
}
//
// GET: /Manage/LinkLoginCallback
public async Task<ActionResult> LinkLoginCallback()
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
if (loginInfo == null)
{
return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
protected override void Dispose(bool disposing)
{
if (disposing && _userManager != null)
{
_userManager.Dispose();
_userManager = null;
}
base.Dispose(disposing);
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private bool HasPassword()
{
var user = UserManager.FindById(User.Identity.GetUserId());
if (user != null)
{
return user.PasswordHash != null;
}
return false;
}
private bool HasPhoneNumber()
{
var user = UserManager.FindById(User.Identity.GetUserId());
if (user != null)
{
return user.PhoneNumber != null;
}
return false;
}
public enum ManageMessageId
{
AddPhoneSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
#endregion
}
} | mit |
Digibos/videojs-inread | lib/vast/request/bucket.js | 418 | videojs.Bucket = videojs.VastCoreObject.extend({
init: function (player, options, ready) {
videojs.VastCoreObject.call(this, player, options, ready);
}
});
videojs.Bucket.isBucketEvent = function (uri) {
videojs.log('isBucketEvent,', uri);
return false;
};
videojs.Bucket.prototype.add = function () {
return false;
};
videojs.Bucket.prototype.empty = function () {
return false;
};
| mit |
xiewulong/express-auto-server | sample/common/db/user.js | 352 | /*!
* user
* xiewulong <[email protected]>
* create: 2017/04/13
* since: 0.0.1
*/
'use strict';
const faker = require('faker/locale/zh_CN');
let rows = [];
for(let i = 0, len = 10; i < len; i++) {
rows.push({
id: i + 1,
name: faker.internet.userName(),
email: faker.internet.email(),
});
}
module.exports = rows;
| mit |
wilfriedE/FIRSTMastery | db/migrate/20160605030135_add_column_to_course_lessons.rb | 186 | class AddColumnToCourseLessons < ActiveRecord::Migration
def change
add_column :course_lessons, :course_id, :integer
add_column :course_lessons, :lesson_id, :integer
end
end
| mit |
Branlute/epsAndroid | app/src/main/java/com/efreipicturestudio/ui/activity/MainActivity.java | 8770 | package com.efreipicturestudio.ui.activity;
import android.animation.ValueAnimator;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.animation.DecelerateInterpolator;
import com.efreipicturestudio.R;
import com.efreipicturestudio.ui.fragment.common.EPSFragment;
import com.efreipicturestudio.ui.fragment.common.photo.ListAlbumsFragment;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
//region Attributes
//region Stack
private EPSFragment rootFragment;
//endregion Stack
//region DrawLayer
private ActionBarDrawerToggle toggle;
private boolean backButtonVisible = false;
@Bind(R.id.toolbar)
protected Toolbar toolbar;
@Bind(R.id.drawer_layout)
protected DrawerLayout drawer;
//endregion DrawLayer
//endregion Attributes
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
//drawer.setDrawerListener(toggle);
toggle.syncState();
toolbar.setNavigationOnClickListener(this);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
//region DrawLayer
/**
* Fonction appelé au clic sur le bouton du menu ou du back
* @param view La vue qui déclenche l'action
*/
@Override
public void onClick(View view) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else {
if (backButtonVisible) {//Si on a la bouton back d'afficher, on pop un fragment de la stack
popFragment(true);
}
else {
drawer.openDrawer(GravityCompat.START);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
EPSFragment fragment = null;
if (id == R.id.nav_camera) {
fragment = ListAlbumsFragment.newInstance();
// Handle the camera action
} else if (id == R.id.nav_gallery) {
fragment = new EPSFragment();
} else if (id == R.id.nav_slideshow) {
fragment = new EPSFragment();
} else if (id == R.id.nav_manage) {
fragment = new EPSFragment();
} else if (id == R.id.nav_share) {
fragment = new EPSFragment();
} else if (id == R.id.nav_send) {
fragment = new EPSFragment();
}
if (fragment != null) {
pushFragment(fragment);
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void showBackButton(boolean value) {
if (backButtonVisible == value) {//Si l'état est déjà bon
return;
}
ValueAnimator anim = ValueAnimator.ofFloat(value ? 0 : 1, value ? 1 : 0);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float slideOffset = (Float) valueAnimator.getAnimatedValue();
toggle.onDrawerSlide(null, slideOffset);
}
});
anim.setInterpolator(new DecelerateInterpolator());
anim.setDuration(500);
anim.start();
backButtonVisible = value;
}
//endregion DrawLayer
//region Navigation
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
//Si on peut faire un back sur la satck des fragments
if (getCountOfFragmentInStack() > 1) {
popFragment(true);
}
else {// Sinon on fait le back par défault
super.onBackPressed();
}
}
}
public void pushFragment(EPSFragment newFragment, boolean shouldSave) {
if (getFragmentManager().getBackStackEntryCount() >= 1) {
showBackButton(true);
}
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, newFragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if (shouldSave) {
transaction.addToBackStack(newFragment.getUniqueId());
}
transaction.commit();
}
public void pushFragment(EPSFragment newFragment) {
pushFragment(newFragment, true);
}
public void pushFragmentWithNoSave(EPSFragment newFragment) {
pushFragment(newFragment, false);
}
public boolean popFragment(boolean immediately) {
if (getFragmentManager().getBackStackEntryCount() > 1) {
if (getFragmentManager().getBackStackEntryCount() == 2) {
showBackButton(false);
}
if (immediately) {
return getFragmentManager().popBackStackImmediate();
} else {
getFragmentManager().popBackStack();
return true;
}
}
return false;
}
public boolean popToFragment(EPSFragment fragment, boolean immediately) {
if (getFragmentManager().getBackStackEntryCount() > 1) {
if (immediately) {
return getFragmentManager().popBackStackImmediate(fragment.getUniqueId(), 0);
} else {
getFragmentManager().popBackStack(fragment.getUniqueId(), 0);
return true;
}
}
return false;
}
public boolean popToRootFragment(boolean immediately) {
return popToFragment(rootFragment, immediately);
}
public Fragment popToClassOfFragment(Class classFragment) {
for (int i = getFragmentManager().getBackStackEntryCount() - 1; i > 0; i--) {
String nameTransaction = getFragmentManager().getBackStackEntryAt(i).getName();
if (nameTransaction.contains(classFragment.getName())) {
getFragmentManager().popBackStackImmediate(nameTransaction, 0);
return getCurrentFragment();
}
}
return null;
}
public Fragment getCurrentFragment() {
return getFragmentManager().findFragmentById(R.id.content_frame);
}
public int getCountOfFragmentInStack() {
return getFragmentManager().getBackStackEntryCount();
}
//endregion Navigation
}
| mit |
rjocoleman/middleman-google-tag-manager | lib/middleman_extension.rb | 39 | require 'middleman-google-tag-manager'
| mit |
fajar125/mpd_ci | application/libraries/transaksi/T_vat_setlement_manual_controller.php | 1721 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Json library
* @class vats_controller
* @version 07/05/2015 12:18:00
*/
class T_vat_setlement_manual_controller {
function insertUpdate(){
$page = getVarClean('page','int',1);
$limit = getVarClean('rows','int',5);
$t_cust_account_id = getVarClean('t_cust_account_id','int',0);
$p_finance_period_id = getVarClean('p_finance_period_id','int',0);
$npwd = getVarClean('npwd','str','');
$start_date = getVarClean('start_date','str','');
$end_date = getVarClean('end_date','str','');
$qty_room_sold = getVarClean('qty_room_sold','int',0);
$trans_amount = getVarClean('trans_amount','int',0);
$p_vat_type_dtl_id = getVarClean('p_vat_type_dtl_id','int',0);
$p_vat_type_dtl_cls_id = getVarClean('p_vat_type_dtl_cls_id','int',0);
$data = array('rows' => array(), 'page' => 1, 'records' => 0, 'total' => 1, 'success' => false, 'message' => '');
try {
$ci = & get_instance();
$ci->load->model('transaksi/t_vat_setlement_manual');
$table = $ci->t_vat_setlement_manual;
$result = $table->insertUpdate($t_cust_account_id,$p_finance_period_id,$npwd,$start_date,$end_date,$qty_room_sold,$trans_amount,$p_vat_type_dtl_id,$p_vat_type_dtl_cls_id ) ;
$count = count($result);
$data['rows'] = $result;
$data['success'] = true;
}catch (Exception $e) {
$data['message'] = $e->getMessage();
}
return $data;
}
}
/* End of file vats_controller.php */ | mit |
GhoulMilk/grouprad.io | server.js | 3030 |
/**
* Module dependencies.
*/
var express = require('express');
var http = require('http');
var path = require('path');
var app = express();
var rooms = [];
// all environments
app.set('port', process.env.PORT || 80);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
var indexCon = function (req, res) {
res.render('index', {}, function (err, html) {
res.render('layout', {
body: html, title: 'Home',
style: '/css/index.css',
script: '/js/index.js'
});
});
};
var roomCon = function (req, res) {
var room = req.params.name
if (roomExists(room)) {
res.render('room', {}, function (err, html) {
res.render('layout', {
body: html, title: 'Room',
style: '/css/room.css',
script: '/js/room.js'
});
});
} else {
console.log('tried to access room: ', room);
res.redirect('/');
}
}
app.get('/', indexCon);
app.get('/room/:name', roomCon);
var serv = http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
function roomExists(name){
for (var i = 0; i < rooms.length; i++) if (rooms[i].name == name) return true;
return false;
}
function createRoom(name, cb){
if (roomExists(name)) {
// room already exists
} else {
rooms.push({ name: name, users:[] });
}
cb(name);
}
function addUser(room, user, id, cb) {
for (var i = 0; i < rooms.length; i++) {
if (rooms[i].name == room) {
rooms[i].users[id] = user;
cb();
break;
}
}
}
var io = require('socket.io').listen(serv);
io.on('connection', function (socket) {
socket.on('create', function (create) {
console.log('Create:', create);
createRoom(create.name, function (name) {
io.to(socket.id).emit('created', name);
});
});
socket.on('join', function (user) {
console.log('Join:', user);
addUser(user.room, user.name, socket.id, function () {
io.to(socket.id).emit('joined');
});
});
socket.on('chat message', function (msg) {
console.log('Chat Message:', msg);
for (var i = 0; i < rooms.length; i++) {
if (msg.room == rooms[i].name) {
for (id in rooms[i].users) {
io.to(id).emit('chat message', msg);
}
}
}
});
}); | mit |
mathiasbynens/unicode-data | 6.1.0/scripts/Coptic-code-points.js | 1287 | // All code points in the `Coptic` script as per Unicode v6.1.0:
[
0x3E2,
0x3E3,
0x3E4,
0x3E5,
0x3E6,
0x3E7,
0x3E8,
0x3E9,
0x3EA,
0x3EB,
0x3EC,
0x3ED,
0x3EE,
0x3EF,
0x2C80,
0x2C81,
0x2C82,
0x2C83,
0x2C84,
0x2C85,
0x2C86,
0x2C87,
0x2C88,
0x2C89,
0x2C8A,
0x2C8B,
0x2C8C,
0x2C8D,
0x2C8E,
0x2C8F,
0x2C90,
0x2C91,
0x2C92,
0x2C93,
0x2C94,
0x2C95,
0x2C96,
0x2C97,
0x2C98,
0x2C99,
0x2C9A,
0x2C9B,
0x2C9C,
0x2C9D,
0x2C9E,
0x2C9F,
0x2CA0,
0x2CA1,
0x2CA2,
0x2CA3,
0x2CA4,
0x2CA5,
0x2CA6,
0x2CA7,
0x2CA8,
0x2CA9,
0x2CAA,
0x2CAB,
0x2CAC,
0x2CAD,
0x2CAE,
0x2CAF,
0x2CB0,
0x2CB1,
0x2CB2,
0x2CB3,
0x2CB4,
0x2CB5,
0x2CB6,
0x2CB7,
0x2CB8,
0x2CB9,
0x2CBA,
0x2CBB,
0x2CBC,
0x2CBD,
0x2CBE,
0x2CBF,
0x2CC0,
0x2CC1,
0x2CC2,
0x2CC3,
0x2CC4,
0x2CC5,
0x2CC6,
0x2CC7,
0x2CC8,
0x2CC9,
0x2CCA,
0x2CCB,
0x2CCC,
0x2CCD,
0x2CCE,
0x2CCF,
0x2CD0,
0x2CD1,
0x2CD2,
0x2CD3,
0x2CD4,
0x2CD5,
0x2CD6,
0x2CD7,
0x2CD8,
0x2CD9,
0x2CDA,
0x2CDB,
0x2CDC,
0x2CDD,
0x2CDE,
0x2CDF,
0x2CE0,
0x2CE1,
0x2CE2,
0x2CE3,
0x2CE4,
0x2CE5,
0x2CE6,
0x2CE7,
0x2CE8,
0x2CE9,
0x2CEA,
0x2CEB,
0x2CEC,
0x2CED,
0x2CEE,
0x2CEF,
0x2CF0,
0x2CF1,
0x2CF2,
0x2CF3,
0x2CF9,
0x2CFA,
0x2CFB,
0x2CFC,
0x2CFD,
0x2CFE,
0x2CFF
]; | mit |
BBC-News/alephant-broker | lib/alephant/broker/request/asset.rb | 827 | require "alephant/logger"
require "alephant/broker/errors/invalid_asset_id"
module Alephant
module Broker
module Request
class Asset
include Logger
attr_accessor :component
def initialize(component_factory, env = nil)
return if env.nil?
@component = component_factory.create(
component_id(env.path),
nil,
env.options
)
rescue InvalidAssetId
logger.metric "InvalidAssetId"
logger.error(
method: 'Broker.Request.Asset.initialize',
message: 'Exception raised (InvalidAssetId)'
)
end
private
def component_id(path)
path.split("/")[2] || (raise InvalidAssetId.new "No Asset ID specified")
end
end
end
end
end
| mit |
amoinier/ft_retro | srcs/D7.cpp | 974 | #include "D7.hpp"
/******************************************************************************
** CONSTRUCTOR
******************************************************************************/
D7::D7( Weapon *Weapon, unsigned int color) : Enemy(*new AEntity(2, 2, 2, 7), Weapon, 25, color, 10)
{
this->getShape().setDefinition(0, 0, 0);
this->getShape().setDefinition(1, 1, 0);
return ;
}
D7::D7( D7 const & src ) : Enemy(src)
{
*this = src;
return ;
}
/******************************************************************************
** DESTRUCTOR
******************************************************************************/
D7::~D7( void )
{
delete &_shape;
delete _weapon;
return ;
}
/******************************************************************************
** OPERATOR OVERLOAD
******************************************************************************/
D7 & D7::operator=( D7 const & rhs )
{
(void)rhs;
return *this;
}
| mit |
mmbros/mananno | templates/templates.go | 3504 | // Generated by gentmpl; *** DO NOT EDIT ***
// Created: 2018-01-07 10:08:57
// Params: no_cache=false, no_go_format=false, asset_manager="go-bindata", func_map="funcMap"
package templates
import (
"html/template"
"io"
"path/filepath"
)
// type definitions
type (
// templateEnum is the type of the Templates
templateEnum uint8
// PageEnum is the type of the Pages
PageEnum uint8
)
// number of templates
const templatesLen = 6
// PageEnum constants
const (
PageAcestreamidChannel PageEnum = iota
PageAcestreamidChannels
PageArenavisionChannel
PageArenavisionSchedule
PageCorsaroIndex
PageHomepage
PageTestTransmission
PageTntVillageIndex
)
// module variables
var mTemplates [templatesLen]*template.Template
func file2path(file string) string {
const templatesFolder = "tmpl"
var path string
switch {
case len(file) == 0, file[0] == '.', file[0] == filepath.Separator:
path = file
default:
path = filepath.Join(templatesFolder, file)
}
return path
}
// Files returns the files used by the `t` template
func (t templateEnum) Files() []string {
var (
// files paths
files = [...]string{"partials/_header.tmpl", "partials/_footer.tmpl", "acestreamid/main.tmpl", "arenavision/schedule.tmpl", "ilcorsaronero/_base.tmpl", "ilcorsaronero/index.tmpl", "index.html", "test/transmission.tmpl", "tntvillage/_base.tmpl", "tntvillage/index.tmpl"}
// template-index to array of file-index
ti2afi = [...][]uint8{
{0, 1, 2}, // acestreamid
{0, 1, 3}, // av_schedule
{4, 5}, // corsaro
{6}, // homepage
{0, 1, 7}, // test_transmission
{8, 9}, // tntvillage
}
)
// get the template files indexes
idxs := ti2afi[t]
// build the array of files
astr := make([]string, len(idxs))
for j, idx := range idxs {
astr[j] = files[idx]
}
return astr
}
// Files returns the files used by the template of the page
func (page PageEnum) Files() []string {
// from page to template indexes
var p2t = [...]templateEnum{0, 0, 1, 1, 2, 3, 4, 5}
// get the template of the page
t := p2t[page]
return t.Files()
}
func init() {
// init base templates
for t := templateEnum(0); t < templatesLen; t++ {
files := t.Files()
// use go-bindata MustAsset func to load templates
tmpl := template.New(filepath.Base(files[0])).Funcs(funcMap)
for _, file := range files {
tmpl.Parse(string(MustAsset(file2path(file))))
}
mTemplates[t] = tmpl
}
}
// Template returns the template.Template of the page
func (page PageEnum) Template() *template.Template {
var idx = [...]templateEnum{0, 0, 1, 1, 2, 3, 4, 5}
return mTemplates[idx[page]]
}
// Base returns the template name of the page
func (page PageEnum) Base() string {
var bases = [...]string{"channel", "channels", "schedule", "", "main"}
var pi2bi = [...]PageEnum{0, 1, 0, 2, 3, 3, 4, 3}
return bases[pi2bi[page]]
}
// Execute applies a parsed page template to the specified data object,
// writing the output to wr.
// If an error occurs executing the template or writing its output, execution
// stops, but partial results may already have been written to the output writer.
// A template may be executed safely in parallel.
func (page PageEnum) Execute(wr io.Writer, data interface{}) error {
tmpl := page.Template()
name := page.Base()
if name != "" {
return tmpl.ExecuteTemplate(wr, name, data)
}
return tmpl.Execute(wr, data)
}
/*
func main(){
var page = PageAcestreamidChannel
wr := os.Stdout
if err := page.Execute(wr, nil); err != nil {
fmt.Print(err)
}
}
*/
| mit |
nrooney/greatLaura | js/main.js | 400 | jQuery(document).ready(function(){
jQuery('button.play').live('click', function(){
jQuery('section').hide();
jQuery('section#question').show();
});
jQuery('button#yes').live('click', function(){
jQuery('section').hide();
jQuery('section#answeryes').show();
});
jQuery('button#no').live('click', function(){
jQuery('section').hide();
jQuery('section#answerno').show();
});
});
| mit |
bmottag/vci_app | application/modules/jobs/views/form_erp_map.php | 4548 | <div id="page-wrapper">
<br>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-success">
<div class="panel-heading">
<a class="btn btn-success btn-xs" href=" <?php echo base_url().'jobs'; ?> "><span class="glyphicon glyphicon glyphicon-chevron-left" aria-hidden="true"></span> Go back </a>
<i class="fa fa-fire-extinguisher "></i> <strong>ERP - EMERGENCY RESPONSE PLAN</strong>
</div>
<div class="panel-body">
<ul class="nav nav-pills">
<li ><a href="<?php echo base_url("jobs/erp/" . $jobInfo[0]["id_job"]); ?>">ERP - INFO</a>
</li>
<li ><a href="<?php echo base_url("jobs/erp_personnel/" . $jobInfo[0]["id_job"]); ?>">ERP - EVACUATION PERSONNEL </a>
</li>
<li class='active'><a href="<?php echo base_url("jobs/erp_map/" . $jobInfo[0]["id_job"]); ?>">ERP - EVACUATION MAP</a>
</li>
</ul>
<div class="alert alert-success">
<strong>Job Code/Name: </strong><?php echo $jobInfo[0]['job_description']; ?>
<br><strong>Date: </strong>
<?php
if($information){
echo $information[0]["date_erp"];
echo "<br><strong>Dowloand ERP: </strong>";
?>
<a href='<?php echo base_url('jobs/generaERPPDF/' . $information[0]["id_erp"] ); ?>' target="_blank">PDF <img src='<?php echo base_url_images('pdf.png'); ?>' ></a>
<?php
}else{
echo date("Y-m-d");
}
?>
</div>
<?php
$retornoExito = $this->session->flashdata('retornoExito');
if ($retornoExito) {
?>
<div class="col-lg-12">
<div class="alert alert-success">
<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
<?php echo $retornoExito ?>
</div>
</div>
<?php
}
$retornoError = $this->session->flashdata('retornoError');
if ($retornoError) {
?>
<div class="col-lg-12">
<div class="alert alert-danger ">
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<?php echo $retornoError ?>
</div>
</div>
<?php
}
?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-success">
<div class="panel-heading">
<strong>EVACUATION MAP</strong>
</div>
<div class="panel-body">
<?php
if($information[0]["evacuation_map"]){ ?>
<div class="col-lg-3">
<div class="form-group">
<div class="row" align="center">
<div style="width:70%;" align="center">
<h3><a href="<?php echo base_url($information[0]["evacuation_map"]); ?>" target="_blank" /> - View map -</a></h3>
</div>
</div>
</div>
</div>
<?php } ?>
<form name="form_map" id="form_map" class="form-horizontal" method="post" enctype="multipart/form-data" action="<?php echo base_url("jobs/do_upload"); ?>">
<input type="hidden" id="hddIdJobMap" name="hddIdJobMap" value="<?php echo $jobInfo[0]["id_job"]; ?>"/>
<div class="col-lg-6">
<div class="form-group">
<label class="col-sm-5 control-label" for="hddTask">Attach evacuation map</label>
<div class="col-sm-5">
<input type="file" name="userfile" />
</div>
</div>
</div>
<div class="col-lg-3">
<div class="form-group">
<div class="row" align="center">
<div style="width:50%;" align="center">
<button type="submit" id="btnSubmitMap" name="btnSubmitMap" class='btn btn-primary'>
Upload map <span class="glyphicon glyphicon-floppy-disk" aria-hidden="true">
</button>
</div>
</div>
</div>
</div>
</form>
<?php if($error){ ?>
<div class="col-lg-12">
<div class="alert alert-danger">
<?php
echo "<strong>Error :</strong>";
pr($error);
?><!--$ERROR MUESTRA LOS ERRORES QUE PUEDAN HABER AL SUBIR LA IMAGEN-->
</div>
</div>
<?php } ?>
<div class="col-lg-12">
<div class="alert alert-danger">
<strong>Note :</strong><br>
Allowed format: gif - jpg - png - pdf<br>
Maximum size: 3000 KB<br>
Maximum width: 3200 pixels<br>
Maximum height: 2400 pixels<br>
<strong>Don´t forget the following items :</strong><br>
1.Emergency exits<br>
2.Primary and secondary evacuation routes<br>
3.Locations of fire extinguishers<br>
4.Fire alarm pull stations’ location<br>
5.Assembly points<br>
6.Medical center<br>
7.First Aid locations
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /#page-wrapper --> | mit |
eric-chahin/query_parser | test/test_parsing.rb | 3208 | require 'test/unit'
require 'query_parser'
class ParsingTest < Test::Unit::TestCase
def test_parsing_normal_queries
parser = QueryParser::ParamParser.new
assert_equal parser.parse_query("foo"), "foo" => nil
assert_equal parser.parse_query("foo="), "foo" => ""
assert_equal parser.parse_query("foo=bar"), "foo" => "bar"
assert_equal parser.parse_query("foo=\"bar\""), "foo" => "\"bar\""
assert_equal parser.parse_query("foo=bar&foo=quux"), "foo" => "quux"
assert_equal parser.parse_query("foo&foo="), "foo" => ""
assert_equal parser.parse_query("foo=1&bar=2"), "foo" => "1", "bar" => "2"
assert_equal parser.parse_query("&foo=1&&bar=2"), "foo" => "1", "bar" => "2"
assert_equal parser.parse_query("foo&bar="), "foo" => nil, "bar" => ""
assert_equal parser.parse_query("foo=bar&baz="), "foo" => "bar", "baz" => ""
assert_equal parser.parse_query("my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F"),
"my weird field" => "q1!2\"'w$5&7/z8)?"
assert_equal parser.parse_query("a=b&pid%3D1234=1023"), "pid=1234" => "1023", "a" => "b"
end
def test_parsing_arrays
parser = QueryParser::ParamParser.new
assert_equal parser.parse_query("foo[]"), "foo" => [nil]
assert_equal parser.parse_query("foo[]="), "foo" => [""]
assert_equal parser.parse_query("foo[]=bar"), "foo" => ["bar"]
assert_equal parser.parse_query("foo[]=1&foo[]=2"), "foo" => ["1","2"]
assert_equal parser.parse_query("foo=bar&baz[]=1&baz[]=2&baz[]=3"), "foo" => "bar", "baz" => ["1", "2", "3"]
assert_equal parser.parse_query("foo[]=bar&baz[]=1&baz[]=2&baz[]=3"), "foo" => ["bar"], "baz" => ["1", "2", "3"]
end
def test_parsing_multidimensional_hashes
parser = QueryParser::ParamParser.new
assert_equal parser.parse_query("x[y][z]=1"), "x" => {"y" => {"z" => "1"}}
assert_equal parser.parse_query("x[y][z][]=1"), "x" => {"y" => {"z" => ["1"]}}
assert_equal parser.parse_query("x[y][z]=1&x[y][z]=2"), "x" => {"y" => {"z" => "2"}}
assert_equal parser.parse_query("x[y][z][]=1&x[y][z][]=2"), "x" => {"y" => {"z" => ["1", "2"]}}
assert_equal parser.parse_query("x[y][][z]=1"), "x" => {"y" => [{"z" => "1"}]}
assert_equal parser.parse_query("x[y][][z][]=1"), "x" => {"y" => [{"z" => ["1"]}]}
assert_equal parser.parse_query("x[y][][z]=1&x[y][][w]=2"), "x" => {"y" => [{"z" => "1", "w" => "2"}]}
assert_equal parser.parse_query("x[y][][v][w]=1"), "x" => {"y" => [{"v" => {"w" => "1"}}]}
assert_equal parser.parse_query("x[y][][z]=1&x[y][][v][w]=2"), "x" => {"y" => [{"z" => "1", "v" => {"w" => "2"}}]}
assert_equal parser.parse_query("x[y][][z]=1&x[y][][z]=2"),"x" => {"y" => [{"z" => "1"}, {"z" => "2"}]}
assert_equal parser.parse_query("x[y][][z]=1&x[y][][w]=a&x[y][][z]=2&x[y][][w]=3"),
"x" => {"y" => [{"z" => "1", "w" => "a"}, {"z" => "2", "w" => "3"}]}
end
def test_raising_TypeError
parser = QueryParser::ParamParser.new
assert_raise TypeError do
parser.parse_query("x[y]=1&x[y]z=2")
end
assert_raise TypeError do
parser.parse_query("x[y]=1&x[]=1")
end
assert_raise TypeError do
parser.parse_query("x[y]=1&x[y][][w]=2")
end
end
end
| mit |
albertlouisong/albertlouisong.github.io | seasons_of_change_code/EnemyCount.cs | 245 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyCount : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| mit |
AstaraelWeeper/Portfolio | Portfolio/Portfolio/Account/VerifyPhoneNumber.aspx.designer.cs | 1419 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Portfolio.Account {
public partial class VerifyPhoneNumber {
/// <summary>
/// ErrorMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ErrorMessage;
/// <summary>
/// PhoneNumber control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField PhoneNumber;
/// <summary>
/// Code control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Code;
}
}
| mit |
gnerkus/chiffre | src/app/profile/profile.service.js | 523 | define([
'angular'
], function (angular) {
/* Profile Service */
// This defines a solution for problem spec 2
'use strict';
return function () {
// Set default username
// Localstorate is used for persistence
localStorage.setItem('username', 'Ifeanyi');
function setName(username) {
localStorage.setItem('username', username);
}
function getName() {
return localStorage.getItem('username');
}
return {
setName: setName,
getName: getName
}
};
});
| mit |
psyipm/postman_mta | app/models/postman_mta/tag.rb | 375 | module PostmanMta
class Tag < ApplicationModel
attr_reader :conversation_id
def initialize(conversation_id)
@conversation_id = conversation_id
end
def create(params)
post("/conversations/#{conversation_id}/tags", body: params)
end
def destroy(tag_id)
delete("/conversations/#{conversation_id}/tags/#{tag_id}")
end
end
end
| mit |
cherniavskii/material-ui | packages/material-ui-icons/src/Stars.js | 325 | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zm4.24 16L12 15.45 7.77 18l1.12-4.81-3.73-3.23 4.92-.42L12 5l1.92 4.53 4.92.42-3.73 3.23L16.23 18z" /></g>
, 'Stars');
| mit |
alchemy-fr/resource-component | src/ResourceReaderResolver.php | 499 | <?php
/*
* This file is part of alchemy/resource-component.
*
* (c) Alchemy <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Resource;
interface ResourceReaderResolver
{
/**
* Resolves a reader for the given resource URI.
*
* @param ResourceUri $resource
* @return ResourceReader
*/
public function resolveReader(ResourceUri $resource);
}
| mit |
etiam/ov | src/core/directionalLightNode.cpp | 2402 | /*
* directionallight.cpp
*
* Created on: Aug 19, 2016
* Author: jasonr
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <memory>
#include <sg/global.h>
#include <sg/nodeFactory.h>
#include <sg/boolAttribute.h>
#include <sg/floatAttribute.h>
#include <ut/utils.h>
#include <ut/box.h>
#include "meshData.h"
#include "shaderObject.h"
#include "directionalLightNodeMeshData.h"
#include "directionalLightNode.h"
namespace
{
class DirectionalLightMeshData : public Core::MeshData
{
public:
DirectionalLightMeshData();
virtual ~DirectionalLightMeshData() = default;
};
DirectionalLightMeshData::DirectionalLightMeshData()
{
using namespace directionallightnodemeshdata;
using namespace glm;
request_vertex_normals();
std::map<unsigned int, Core::MeshData::VertexHandle> meshindextovhandle;
// add vertices
for (auto i=0; i < (sizeof(pos)/sizeof(pos[0]))/3; ++i)
{
auto handle = add_vertex(Core::MeshData::Point(pos[(i*3)+0], pos[(i*3)+1], pos[(i*3)+2]));
set_normal(handle, Core::MeshData::Normal(norm[(i*3)+0], norm[(i*3)+1], norm[(i*3)+2]));
meshindextovhandle[i] = handle;
}
// add faces
std::vector<Core::MeshData::VertexHandle> facehandles;
for (auto i=0, n=0; i < sizeof(sizes)/sizeof(sizes[0]); ++i)
{
facehandles.clear();
for (auto j=0; j < sizes[i]; ++j, ++n)
facehandles.push_back(meshindextovhandle.at(n));
add_face(facehandles);
}
}
}
namespace Core
{
std::string DirectionalLightNode::nodetype = "dirlight";
DirectionalLightNode::DirectionalLightNode()
{
m_type = UNMANGLE(*this);
}
std::string
DirectionalLightNode::nodeType() const
{
return DirectionalLightNode::nodetype;
}
void
DirectionalLightNode::initializeNode()
{
// call parent initializer
Super::initializeNode();
// don't allow shader override
auto override = Sg::asBoolAttribute(Sg::createAttribute("bool"));
addAttribute(".noshaderoverride", std::move(override));
// set shader
auto shader = Core::asShaderObject(Sg::findNode("/lib/.smoothshader"));
assert(shader != nullptr);
Sg::makeTrue(shader, "shades", this);
setLocalBoundingBox(directionallightnodemeshdata::boundingbox);
}
std::unique_ptr<Core::MeshData>
DirectionalLightNode::createGlMeshData()
{
return std::make_unique<DirectionalLightMeshData>();
}
}
| mit |
clbr/SGDK | tools/resourcemanager/src/main/java/org/sgdk/resourcemanager/ui/panels/projectexplorer/modals/CreateSpriteDialog.java | 4832 | package org.sgdk.resourcemanager.ui.panels.projectexplorer.modals;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;
import org.apache.commons.lang3.StringUtils;
import org.sgdk.resourcemanager.entities.SGDKElement;
import org.sgdk.resourcemanager.entities.SGDKFolder;
import org.sgdk.resourcemanager.entities.SGDKSprite;
import org.sgdk.resourcemanager.entities.factory.SGDKEntityFactory;
import org.sgdk.resourcemanager.ui.ResourceManagerFrame;
public class CreateSpriteDialog extends JDialog{
/**
*
*/
private static final int minimizeWidth = 340;
private static final int minimizeHeight = 220;
private JTextField spritePathText = new JTextField();
private JFileChooser spritePath = new JFileChooser(System.getProperty("user.home"));
private File[] selectedFiles = null;
private JButton acceptButon = new JButton("Ok");
private static final long serialVersionUID = 1L;
public CreateSpriteDialog(ResourceManagerFrame parent, SGDKElement parentNode) {
super(parent, "New Sprite");
parent.setEnabled(false);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = new Long(Math.round(screenSize.getWidth())).intValue();
int screenHeight = new Long(Math.round(screenSize.getHeight())).intValue();
setBounds(new Rectangle(screenWidth/2 - minimizeWidth/2, screenHeight/2 - minimizeHeight/2, minimizeWidth, minimizeHeight));
setResizable(false);
// setAlwaysOnTop(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
clean();
parent.setEnabled(true);
}
});
spritePath.addChoosableFileFilter(new FileFilter() {
@Override
public String getDescription() {
return StringUtils.join(SGDKSprite.ValidFormat.values(), ", ");
}
@Override
public boolean accept(File f) {
return SGDKSprite.isValidFormat(f.getAbsolutePath()) || f.isDirectory();
}
});
spritePath.setAcceptAllFileFilterUsed(false);
spritePath.setMultiSelectionEnabled(true);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.CENTER;
c.weightx = 1d/6d;
c.weighty = 1d/2d;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
add(new JLabel("Sprite Path: "), c);
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.LINE_START;
c.weightx = 5d/6d;
c.weighty = 1d/2d;
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 5;
c.gridheight = 1;
add(spritePathText, c);
spritePathText.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e){
int returnVal = spritePath.showDialog(parent, "New Sprite");
if (returnVal == JFileChooser.APPROVE_OPTION) {
selectedFiles = spritePath.getSelectedFiles();
String[] values = new String[selectedFiles.length];
int i = 0;
for(File f : selectedFiles) {
values[i] = f.getAbsolutePath();
i++;
}
spritePathText.setText(StringUtils.join(values, ","));
}
}
});
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_END;
c.weightx = 1d/6d;
c.weighty = 1d/2d;
c.gridx = 5;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
add(acceptButon, c);
acceptButon.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean validForm = true;
if(validForm && (spritePathText.getText() == null || spritePathText.getText().isEmpty())) {
validForm = false;
JPanel panel = new JPanel();
JOptionPane.showMessageDialog(panel,
"Invalid Sprite File",
"Error",
JOptionPane.ERROR_MESSAGE);
}
if (validForm) {
for(File f : selectedFiles) {
SGDKSprite sprite = SGDKEntityFactory.createSGDKSprite(f.getAbsolutePath(), (SGDKFolder)parentNode);
if(sprite != null) {
parent.getProjectExplorer().getProjectExplorerTree().addElement(sprite, parentNode);
}
}
clean();
parent.setEnabled(true);
setVisible(false);
}
}
});
setVisible(true);
}
protected void clean() {
spritePathText.setText("");
}
}
| mit |
moto2002/tianzi-work | NgEnum.cs | 397 | using System;
public class NgEnum
{
public enum AXIS
{
X,
Y,
Z
}
public enum TRANSFORM
{
POSITION,
ROTATION,
SCALE
}
public static string[] m_TextureSizeStrings = new string[]
{
"32",
"64",
"128",
"256",
"512",
"1024",
"2048",
"4096"
};
public static int[] m_TextureSizeIntters = new int[]
{
32,
64,
128,
256,
512,
1024,
2048,
4096
};
}
| mit |
sasagichuki/nkemi_new_site | cache/compiled/files/2471d9bcd9da0ee42c88eef82eede279.yaml.php | 2789 | <?php
return [
'@class' => 'Grav\\Common\\File\\CompiledYamlFile',
'filename' => '/Users/chaos/projects/nkemi_new_site/system/languages/ru.yaml',
'modified' => 1461737248,
'data' => [
'INFLECTOR_IRREGULAR' => [
'person' => 'люди',
'man' => 'человек',
'child' => 'ребенок',
'sex' => 'пол',
'move' => 'движется'
],
'NICETIME' => [
'NO_DATE_PROVIDED' => 'Дата не указана',
'BAD_DATE' => 'Неверная дата',
'AGO' => 'назад',
'FROM_NOW' => 'теперь',
'SECOND' => 'секунда',
'MINUTE' => 'минута',
'HOUR' => 'час',
'DAY' => 'д',
'WEEK' => 'неделя',
'MONTH' => 'месяц',
'YEAR' => 'год',
'DECADE' => 'десятилетие',
'SEC' => 'с',
'MIN' => 'мин',
'HR' => 'ч',
'WK' => 'нед',
'MO' => 'мес',
'YR' => 'г.',
'DEC' => 'гг.',
'SECOND_PLURAL' => 'секунды',
'MINUTE_PLURAL' => 'минуты',
'HOUR_PLURAL' => 'часы',
'DAY_PLURAL' => 'д',
'WEEK_PLURAL' => 'недели',
'MONTH_PLURAL' => 'месяцы',
'YEAR_PLURAL' => 'годы',
'DECADE_PLURAL' => 'десятилетия',
'SEC_PLURAL' => 'с',
'MIN_PLURAL' => 'мин',
'HR_PLURAL' => 'ч',
'WK_PLURAL' => 'нед',
'MO_PLURAL' => 'мес',
'YR_PLURAL' => 'г.',
'DEC_PLURAL' => 'гг.'
],
'FORM' => [
'VALIDATION_FAIL' => '<b>Проверка не удалась:</b>',
'INVALID_INPUT' => 'Неверный ввод в',
'MISSING_REQUIRED_FIELD' => 'Отсутствует необходимое поле:'
],
'MONTHS_OF_THE_YEAR' => [
0 => 'Январь',
1 => 'Февраль',
2 => 'Март',
3 => 'Апрель',
4 => 'Май',
5 => 'Июнь',
6 => 'Июль',
7 => 'Август',
8 => 'Сентябрь',
9 => 'Октябрь',
10 => 'Ноябрь',
11 => 'Декабрь'
],
'DAYS_OF_THE_WEEK' => [
0 => 'Понедельник',
1 => 'Вторник',
2 => 'Среда',
3 => 'Четверг',
4 => 'Пятница',
5 => 'Суббота',
6 => 'Воскресенье'
]
]
];
| mit |
bartsch-dev/jabref | src/main/java/org/jabref/gui/preftabs/AdvancedTab.java | 6980 | package org.jabref.gui.preftabs;
import java.awt.BorderLayout;
import java.util.Optional;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.jabref.Globals;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.remote.JabRefMessageHandler;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.remote.RemotePreferences;
import org.jabref.logic.remote.RemoteUtil;
import org.jabref.preferences.JabRefPreferences;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
class AdvancedTab extends JPanel implements PrefsTab {
private final JabRefPreferences preferences;
private final JCheckBox useRemoteServer;
private final JCheckBox useIEEEAbrv;
private final JTextField remoteServerPort;
private final JCheckBox useCaseKeeperOnSearch;
private final JCheckBox useUnitFormatterOnSearch;
private final RemotePreferences remotePreferences;
public AdvancedTab(JabRefPreferences prefs) {
preferences = prefs;
remotePreferences = prefs.getRemotePreferences();
useRemoteServer = new JCheckBox(Localization.lang("Listen for remote operation on port") + ':');
useIEEEAbrv = new JCheckBox(Localization.lang("Use IEEE LaTeX abbreviations"));
remoteServerPort = new JTextField();
useCaseKeeperOnSearch = new JCheckBox(Localization.lang("Add {} to specified title words on search to keep the correct case"));
useUnitFormatterOnSearch = new JCheckBox(Localization.lang("Format units by adding non-breaking separators and keeping the correct case on search"));
FormLayout layout = new FormLayout
("1dlu, 8dlu, left:pref, 4dlu, fill:3dlu",//, 4dlu, fill:pref",// 4dlu, left:pref, 4dlu",
"");
DefaultFormBuilder builder = new DefaultFormBuilder(layout);
JPanel pan = new JPanel();
builder.appendSeparator(Localization.lang("Remote operation"));
builder.nextLine();
builder.append(new JPanel());
builder.append(new JLabel("<html>"
+ Localization.lang("This feature lets new files be opened or imported into an "
+ "already running instance of JabRef<BR>instead of opening a new instance. For instance, this "
+ "is useful when you open a file in JabRef<br>from your web browser."
+ "<BR>Note that this will prevent you from running more than one instance of JabRef at a time.")
+ "</html>"));
builder.nextLine();
builder.append(new JPanel());
JPanel p = new JPanel();
p.add(useRemoteServer);
p.add(remoteServerPort);
p.add(new HelpAction(HelpFile.REMOTE).getHelpButton());
builder.append(p);
// IEEE
builder.nextLine();
builder.appendSeparator(Localization.lang("Search %0", "IEEEXplore"));
builder.nextLine();
builder.append(new JPanel());
builder.append(useIEEEAbrv);
builder.nextLine();
builder.appendSeparator(Localization.lang("Import conversions"));
builder.nextLine();
builder.append(pan);
builder.append(useCaseKeeperOnSearch);
builder.nextLine();
builder.append(pan);
builder.append(useUnitFormatterOnSearch);
pan = builder.getPanel();
pan.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout());
add(pan, BorderLayout.CENTER);
}
@Override
public void setValues() {
useRemoteServer.setSelected(remotePreferences.useRemoteServer());
remoteServerPort.setText(String.valueOf(remotePreferences.getPort()));
useIEEEAbrv.setSelected(Globals.prefs.getBoolean(JabRefPreferences.USE_IEEE_ABRV));
useCaseKeeperOnSearch.setSelected(Globals.prefs.getBoolean(JabRefPreferences.USE_CASE_KEEPER_ON_SEARCH));
useUnitFormatterOnSearch.setSelected(Globals.prefs.getBoolean(JabRefPreferences.USE_UNIT_FORMATTER_ON_SEARCH));
}
@Override
public void storeSettings() {
if (preferences.getBoolean(JabRefPreferences.USE_IEEE_ABRV) != useIEEEAbrv.isSelected()) {
preferences.putBoolean(JabRefPreferences.USE_IEEE_ABRV, useIEEEAbrv.isSelected());
Globals.journalAbbreviationLoader.update(Globals.prefs.getJournalAbbreviationPreferences());
}
storeRemoteSettings();
preferences.putBoolean(JabRefPreferences.USE_CASE_KEEPER_ON_SEARCH, useCaseKeeperOnSearch.isSelected());
preferences.putBoolean(JabRefPreferences.USE_UNIT_FORMATTER_ON_SEARCH, useUnitFormatterOnSearch.isSelected());
}
private void storeRemoteSettings() {
getPortAsInt().ifPresent(newPort -> {
if (remotePreferences.isDifferentPort(newPort)) {
remotePreferences.setPort(newPort);
if (remotePreferences.useRemoteServer()) {
JOptionPane.showMessageDialog(null,
Localization.lang("Remote server port").concat(" ")
.concat(Localization.lang("You must restart JabRef for this to come into effect.")),
Localization.lang("Remote server port"), JOptionPane.WARNING_MESSAGE);
}
}
});
remotePreferences.setUseRemoteServer(useRemoteServer.isSelected());
if (remotePreferences.useRemoteServer()) {
Globals.REMOTE_LISTENER.openAndStart(new JabRefMessageHandler(), remotePreferences.getPort());
} else {
Globals.REMOTE_LISTENER.stop();
}
preferences.setRemotePreferences(remotePreferences);
}
private Optional<Integer> getPortAsInt() {
try {
return Optional.of(Integer.parseInt(remoteServerPort.getText()));
} catch (NumberFormatException ex) {
return Optional.empty();
}
}
@Override
public boolean validateSettings() {
try {
int portNumber = Integer.parseInt(remoteServerPort.getText());
if (RemoteUtil.isUserPort(portNumber)) {
return true;
} else {
throw new NumberFormatException();
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null,
Localization.lang("You must enter an integer value in the interval 1025-65535 in the text field for")
+ " '" + Localization.lang("Remote server port") + '\'',
Localization.lang("Remote server port"), JOptionPane.ERROR_MESSAGE);
return false;
}
}
@Override
public String getTabName() {
return Localization.lang("Advanced");
}
}
| mit |
zertico/softlayer | lib/softlayer/network/application/delivery/controller/load_balancer/virtual_server.rb | 2765 | module Softlayer
class Network
module Application
module Delivery
class Controller
module LoadBalancer
class VirtualServer < Softlayer::Entity
SERVICE = 'SoftLayer_Network_Application_Delivery_Controller_LoadBalancer_VirtualServer'
attr_accessor :allocation
attr_accessor :id
attr_accessor :name
attr_accessor :notes
attr_accessor :port
attr_accessor :routing_method_id
attr_accessor :virtual_ip_address_id
attr_accessor :scale_load_balancer_count
attr_accessor :service_group_count
attr_accessor :routing_method
attr_accessor :scale_load_balancers
attr_accessor :service_groups
attr_accessor :virtual_ip_address
def delete_object
request(:delete_object, Boolean)
end
def get_object
request(:get_object, Softlayer::Network::Application::Delivery::Controller::LoadBalancer::VirtualServer)
end
def get_routing_method
request(:get_routing_method, Softlayer::Network::Application::Delivery::Controller::LoadBalancer::Routing::Method)
end
def get_scale_load_balancers
request(:get_scale_load_balancers, Array[Softlayer::Scale::LoadBalancer])
end
def get_service_groups
request(:get_service_groups, Array[Softlayer::Network::Application::Delivery::Controller::LoadBalancer::Service::Group])
end
def get_virtual_ip_address
request(:get_virtual_ip_address, Softlayer::Network::Application::Delivery::Controller::LoadBalancer::VirtualIpAddress)
end
def start_ssl
request(:start_ssl, Boolean)
end
def stop_ssl
request(:stop_ssl, Boolean)
end
class Representer < Softlayer::Entity::Representer
include Representable::Hash
include Representable::Coercion
property :allocation, type: Integer
property :id, type: Integer
property :name, type: String
property :notes, type: String
property :port, type: Integer
property :routing_method_id, type: Integer
property :virtual_ip_address_id, type: Integer
property :scale_load_balancer_count, type: BigDecimal
property :service_group_count, type: BigDecimal
end
end
end
end
end
end
end
end
| mit |
grmlin/watched | src/__tests__/ModuleFactory-test.js | 38 | /**
* Created by aw on 07.03.15.
*/
| mit |
TeamLabyrinth4/Labyrinth-4 | Labyrinth-Game.Tests/MementoTests.cs | 493 | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Labyrinth.Users;
namespace Labyrinth_Game.Tests
{
[TestClass]
public class MementoTests
{
[TestMethod]
public void TestMementoScore()
{
var testedMemento = new Memento(10, 5, 5);
Assert.AreEqual(testedMemento.Score, 10);
Assert.AreEqual(testedMemento.PositionCol, 5);
Assert.AreEqual(testedMemento.PositionRow, 5);
}
}
}
| mit |
TheoGauchoux/LudoTech | LudoTech/src/frontend/members/view/MemberSearchView.java | 2501 | package frontend.members.view;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import frontend.LudoTechApplication;
import frontend.utils.gui.SpringUtilities;
import frontend.utils.gui.TextView;
@SuppressWarnings("serial")
public class MemberSearchView extends JPanel {
private JTextField firstName;
private JTextField lastName;
private JTextField pseudo;
private JButton searchButton;
public MemberSearchView() {
this.setLayout(new BorderLayout());
this.makeGUI();
}
private void makeGUI() {
JLabel title = new JLabel(TextView.get("membersSearchTitle"));
Font police = new Font("Arial", Font.BOLD, 16);
title.setFont(police);
title.setHorizontalAlignment(JLabel.CENTER);
this.add(title, BorderLayout.NORTH);
JPanel searchPropertiesPanel = new JPanel(new SpringLayout());
// prénom
JLabel firstNameLabel = new JLabel(TextView.get("firstName"));
searchPropertiesPanel.add(firstNameLabel);
this.firstName = new JTextField();
this.firstName.setMaximumSize(new Dimension(LudoTechApplication.WINDOW_WIDTH, 20));
firstNameLabel.setLabelFor(this.firstName);
searchPropertiesPanel.add(this.firstName);
// nom
JLabel lastNameLabel = new JLabel(TextView.get("lastName"));
searchPropertiesPanel.add(lastNameLabel);
this.lastName = new JTextField();
this.lastName.setMaximumSize(new Dimension(LudoTechApplication.WINDOW_WIDTH, 20));
lastNameLabel.setLabelFor(this.lastName);
searchPropertiesPanel.add(this.lastName);
// pseudo
JLabel pseudoLabel = new JLabel(TextView.get("pseudo"));
searchPropertiesPanel.add(pseudoLabel);
this.pseudo = new JTextField();
this.pseudo.setMaximumSize(new Dimension(LudoTechApplication.WINDOW_WIDTH, 20));
pseudoLabel.setLabelFor(this.pseudo);
searchPropertiesPanel.add(this.pseudo);
SpringUtilities.makeCompactGrid(searchPropertiesPanel, 3, 2, 6, 6, 6, 6);
this.add(searchPropertiesPanel, BorderLayout.CENTER);
this.searchButton = new JButton(TextView.get("validate"));
this.add(this.searchButton, BorderLayout.SOUTH);
}
public JButton getSearchButton() {
return this.searchButton;
}
public String getFirstNameValue() {
return this.firstName.getText();
}
public String getLastNameValue() {
return this.lastName.getText();
}
public String getPseudoValue() {
return this.pseudo.getText();
}
}
| mit |
bati11/study-algorithm | aizu/Introduction-to-Algorithms-and-Data-Structures/ALDS1_4_C_Dictionary/ALDS1_4_C.rb | 956 | def to_key(s)
s.gsub!('A', '1')
s.gsub!('C', '2')
s.gsub!('G', '3')
s.gsub!('T', '4')
s.to_i
end
def hash(key, i)
(h1(key) + i * h2(key)) % 1046527
end
def h1(key)
key % 1046527
end
def h2(key)
1 + (key % (1046527 - 1))
end
class Dict
def initialize
@arr = []
end
def insert(s)
key = to_key(s)
i = 0
loop do
h = hash(key, i)
if @arr[h] == s
return
elsif @arr[h].nil?
@arr[h] = s
return
end
i = i + 1
end
end
def find(s)
key = to_key(s)
i = 0
loop do
h = hash(key, i)
if @arr[h] == s
return true
elsif @arr[h].nil?
return false
end
i = i + 1
end
false
end
end
n = STDIN.gets.to_i
dict = Dict.new
n.times.each {
ss = STDIN.gets.split(' ')
if ss[0] == 'insert' then
dict.insert(ss[1])
else
if dict.find(ss[1]) then
puts 'yes'
else
puts 'no'
end
end
}
| mit |
billwen/netopt | harpy3/test/models/cm_netopt_user_test.rb | 126 | require 'test_helper'
class CmNetoptUserTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| mit |
timj/scons | test/Climb/filename--D.py | 2292 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# 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.
#
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify the ability to use the -D option with the -f option to
specify a different top-level file name.
"""
import TestSCons
test = TestSCons.TestSCons()
test.subdir('subdir', 'other')
test.write('main.scons', """\
print("main.scons")
SConscript('subdir/sub.scons')
""")
test.write(['subdir', 'sub.scons'], """\
print("subdir/sub.scons")
""")
read_str = """\
main.scons
subdir/sub.scons
"""
expect = "scons: Entering directory `%s'\n" % test.workpath() \
+ test.wrap_stdout(read_str = read_str,
build_str = "scons: `subdir' is up to date.\n")
test.run(chdir='subdir', arguments='-D -f main.scons .', stdout=expect)
expect = test.wrap_stdout(read_str = "subdir/sub.scons\n",
build_str = "scons: `.' is up to date.\n")
test.run(chdir='other', arguments='-D -f ../subdir/sub.scons .', stdout=expect)
test.run(chdir='other',
arguments='-D -f %s .' % test.workpath('subdir', 'sub.scons'),
stdout=expect)
test.pass_test()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| mit |
jaredbeck/hivegame | spec/board_spec.rb | 2699 | require "spec_helper"
describe Hivegame::Board do
let(:origin) { [0,0,0] }
context "when initialized" do
it("is empty") { should be_empty }
it("has a count of zero") { subject.count.should == 0 }
end
describe "#add" do
let(:bug) { double("Bug") }
it "adds a piece to the given position" do
subject.add(origin, bug).should be_true
end
it 'raises error if point is invalid' do
expect { subject.add([0,0,0.1], bug) }.to raise_error ArgumentError
end
it 'can only add bugs connected to the hive' do
subject.add(origin, double("Bug One")).should be_true
subject.add([2,0,0], double("Bug Two")).should be_false
subject.should have(1).bug
subject.add([1,0,0], double("Bug Three")).should be_true
subject.should have(2).bugs
end
it "fails if the position is occupied" do
subject.add(origin, bug).should be_true
subject.add(origin, bug).should be_false
end
it "fails to add to a z-level with no bug underneath" do
subject.add([0, 0, 1], bug).should be_false
end
it "increases the count" do
expect { subject.add(origin, bug) }.to change { subject.count }.by(+1)
end
context 'on top of another bug' do
before do
subject.add([0,0,0], bug)
end
it "adds a climber" do
bug.stub(:climber?) { true }
subject.add([0,0,1], bug).should be_true
end
it "fails to add a non-climber" do
bug.stub(:climber?) { false }
subject.add([0,0,1], bug).should be_false
end
end
end
describe "#to_ascii" do
it "shows the correct board after a few moves" do
subject.add [0,0,0], 'B'
subject.add [0,1,0], 'b'
subject.add [0,-1,0], 'A'
subject.add [1,2,0], 'a'
expected = <<-eod
-01: . . . . . .
000: . A B b . .
001: . . . . a .
002: . . . . . .
eod
subject.to_ascii.should == expected.strip
end
context "empty board" do
it "shows the origin and neighbors" do
expected = <<-eod
-01: . . .
000: . . .
001: . . .
eod
subject.to_ascii.should == expected.strip
end
end
it "shows bugs instead of a dot" do
subject.add([42,42,0], 'X')
board = remove_line_nums(subject.to_ascii)
distincts = Set.new(board.split('')).to_a
distincts.should =~ "X .\n".split('')
end
def remove_line_nums ascii_board
ascii_board.split("\n").map{|n| n.sub(/^\d{3}\:/, '')}.join("\n")
end
end
describe "#neighbor_points" do
it "returns eight for any point" do
r = rand(10000)
subject.neighbor_points([r,r,r]).should have(8).neighbors
end
end
end
| mit |
olympum/caffeine | examples/jms-client/JMSSender.cs | 1250 | using System;
using javax.jms;
using javax.naming;
public class JMSSender {
public static void Main(string[] args) {
Console.WriteLine("Looking up context factory");
Context context = NamingContextHelper.getContext();
Console.WriteLine("Looking up connection factory");
QueueConnectionFactory queueConnectionFactory =
new QueueConnectionFactoryJNIImpl(context.lookup(new java.lang.String("ConnectionFactory")));
Console.WriteLine("Looking up queue");
Queue queue = new QueueJNIImpl(context.lookup(new java.lang.String("queue/A")));
Console.WriteLine("Creating queue connection");
QueueConnection queueConnection =
queueConnectionFactory.createQueueConnection();
Console.WriteLine("Creating queue session");
QueueSession queueSession =
queueConnection.createQueueSession(false,
SessionJNIImpl.AUTO_ACKNOWLEDGE);
Console.WriteLine("Creating sender");
QueueSender queueSender = queueSession.createSender(queue);
TextMessage message = queueSession.createTextMessage();
for (int i = 0; i < 5; i++) {
message.setText(new java.lang.String("This is message " + (i + 1)));
Console.WriteLine("Sending message: " + message.getText());
queueSender.send(message);
}
queueConnection.close();
}
}
| mit |
nicholaskim94/iotpaas | app/controllers/projects_api_controller.rb | 383 | class ProjectsApiController < BaseApiController
before_filter :find_project, only: [:show]
def index
render json: Project.where('owner_id = ?', @user.id)
end
def show
@project
end
private
def find_project
@project = Project.find_by_name(params[:projectName])
render nothing: true, status: :user_not_found unless @project.present? && @project.user == @user
end
end
| mit |
pacmacro/pm-server | src/main/java/com/pm/server/manager/TagManagerImpl.java | 4512 | package com.pm.server.manager;
import com.pm.server.PmServerException;
import com.pm.server.datatype.GameState;
import com.pm.server.datatype.Player;
import com.pm.server.registry.GameStateRegistry;
import com.pm.server.registry.PlayerRegistry;
import com.pm.server.registry.TagRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import static com.pm.server.datatype.Player.Name.Pacman;
@Service
public class TagManagerImpl implements TagManager {
private GameStateRegistry gameStateRegistry;
private PlayerRegistry playerRegistry;
private TagRegistry tagRegistry;
@Autowired
public TagManagerImpl(
GameStateRegistry gameStateRegistry,
PlayerRegistry playerRegistry,
TagRegistry tagRegistry) {
this.gameStateRegistry = gameStateRegistry;
this.playerRegistry = playerRegistry;
this.tagRegistry = tagRegistry;
}
public void registerTag(
Player.Name reporter,
Player.Name source,
Player.Name destination
) throws PmServerException {
Boolean reporterIsTagger;
Player.Name otherPlayer;
if(source == null) {
if(destination == null) {
throw new PmServerException(
HttpStatus.BAD_REQUEST,
"Either source or destination must be sent."
);
}
else {
reporterIsTagger = true;
otherPlayer = destination;
}
}
else if(destination != null) {
throw new PmServerException(
HttpStatus.BAD_REQUEST,
"Only one of source or destination can be sent."
);
}
else {
reporterIsTagger = false;
otherPlayer = source;
}
if(!gameStateRegistry.getCurrentState().equals(GameState.IN_PROGRESS)) {
throw new PmServerException(
HttpStatus.CONFLICT,
"The game is not currently in progress."
);
}
if(reporter == otherPlayer) {
throw new PmServerException(
HttpStatus.CONFLICT, "The players are the same."
);
}
if(reporter != Pacman &&
otherPlayer != Pacman) {
throw new PmServerException(
HttpStatus.CONFLICT, "A ghost cannot tag a ghost."
);
}
Player.State reporterState = playerRegistry.getPlayerState(reporter);
if(!reporterState.equals(Player.State.ACTIVE) &&
!reporterState.equals(Player.State.POWERUP)) {
throw new PmServerException(
HttpStatus.CONFLICT,
"The player reporting the tag is not currently active " +
"in the game."
);
}
Player.State otherPlayerState =
playerRegistry.getPlayerState(otherPlayer);
if(!otherPlayerState.equals(Player.State.ACTIVE) &&
!otherPlayerState.equals(Player.State.POWERUP)) {
if(reporterIsTagger) {
throw new PmServerException(
HttpStatus.CONFLICT,
"The tagged player is not currently active " +
"in the game."
);
}
else {
throw new PmServerException(
HttpStatus.CONFLICT,
"That tagger is not currently active " +
"in the game."
);
}
}
Boolean success;
if(reporterIsTagger) {
success = tagRegistry.tagPlayer(reporter, otherPlayer);
if(success) {
completeTag(otherPlayer);
}
}
else {
success = tagRegistry.receiveTagFromPlayer(reporter, otherPlayer);
if(success) {
completeTag(reporter);
}
}
}
private void completeTag(Player.Name taggee) {
playerRegistry.setPlayerStateByName(taggee, Player.State.CAPTURED);
if(taggee.equals(Pacman)) {
gameStateRegistry.setWinnerGhosts();
}
else if(playerRegistry.allGhostsCaptured()) {
gameStateRegistry.setWinnerPacman();
}
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.