repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
Alwnikrotikz/marinemap | lingcod/google-analytics/admin.py | 517 | from django.conf import settings
from django.contrib import admin
from django.contrib.sites.models import Site
from models import Analytics
if getattr(settings, 'GOOGLE_ANALYTICS_MODEL', False):
class AnalyticsInline(admin.StackedInline):
model = Analytics
extra = 1
class SiteAdminGA(admin.ModelAdmin):
list_display = ('domain', 'name')
model = Site
inlines = [AnalyticsInline]
admin.site.unregister(Site)
admin.site.register(Site, SiteAdminGA)
| bsd-3-clause |
johnd0e/FarManager | plugins/newarc.ex/Framework/Src/UnicodeAnsi.cpp | 1378 | #include "UnicodeAnsi.hpp"
//как-то ANSI тут неумно звучит
wchar_t* AnsiToUnicode(const char* lpSrc, int CodePage)
{
if ( !lpSrc )
return NULL;
int nLength = MultiByteToWideChar(CodePage, 0, lpSrc, -1, NULL, 0);
wchar_t* lpResult = (wchar_t*)malloc((nLength+1)*sizeof(wchar_t));
MultiByteToWideChar(CodePage, 0, lpSrc, -1, lpResult, nLength);
return lpResult;
}
char* UnicodeToAnsi(const wchar_t* lpSrc, int CodePage)
{
if ( !lpSrc )
return NULL;
int nLength = WideCharToMultiByte(CodePage, 0, lpSrc, -1, NULL, 0, NULL, NULL);
char* lpResult = (char*)malloc(nLength+1);
WideCharToMultiByte(CodePage, 0, lpSrc, -1, lpResult, nLength, NULL, NULL);
return lpResult;
}
char* UnicodeToUTF8(const wchar_t* lpSrc)
{
return UnicodeToAnsi(lpSrc, CP_UTF8); //ааа!!!! ToAnsi!!!
}
char* AnsiToUTF8(const char* lpSrc, int CodePage)
{
if ( !lpSrc )
return nullptr;
wchar_t* lpUnicode = AnsiToUnicode(lpSrc, CodePage);
char* lpResult = UnicodeToUTF8(lpUnicode);
free(lpUnicode);
return lpResult;
}
wchar_t* UTF8ToUnicode(const char* lpSrc)
{
return AnsiToUnicode(lpSrc, CP_UTF8); //aaa!!!
}
char* UTF8ToAnsi(const char* lpSrc, int CodePage)
{
if ( !lpSrc )
return nullptr;
wchar_t* lpUnicode = AnsiToUnicode(lpSrc, CP_UTF8);
char* lpResult = UnicodeToAnsi(lpUnicode, CP_OEMCP);
free(lpUnicode);
return lpResult;
} | bsd-3-clause |
shawnl/go | src/cmd/7g/peep.go | 2791 | // Derived from Inferno utils/6c/peep.c
// http://code.google.com/p/inferno-os/source/browse/utils/6c/peep.c
//
// Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved.
// Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
// Portions Copyright © 1997-1999 Vita Nuova Limited
// Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
// Portions Copyright © 2004,2006 Bruce Ellis
// Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
// Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
// Portions Copyright © 2009 The Go Authors. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package main
import (
"cmd/internal/gc"
"cmd/internal/obj"
"cmd/internal/obj/arm64"
"fmt"
)
var gactive uint32
func peep(firstp *obj.Prog) {
// TODO(aram)
}
func excise(r *gc.Flow) {
p := (*obj.Prog)(r.Prog)
if gc.Debug['P'] != 0 && gc.Debug['v'] != 0 {
fmt.Printf("%v ===delete===\n", p)
}
obj.Nopout(p)
gc.Ostats.Ndelmov++
}
func regtyp(a *obj.Addr) bool {
// TODO(rsc): Floating point register exclusions?
return a.Type == obj.TYPE_REG && arm64.REG_R0 <= a.Reg && a.Reg <= arm64.REG_F31 && a.Reg != arm64.REGZERO
}
func sameaddr(a *obj.Addr, v *obj.Addr) bool {
if a.Type != v.Type {
return false
}
if regtyp(v) && a.Reg == v.Reg {
return true
}
if v.Type == obj.NAME_AUTO || v.Type == obj.NAME_PARAM {
if v.Offset == a.Offset {
return true
}
}
return false
}
func smallindir(a *obj.Addr, reg *obj.Addr) bool {
return reg.Type == obj.TYPE_REG && a.Type == obj.TYPE_MEM && a.Reg == reg.Reg && 0 <= a.Offset && a.Offset < 4096
}
func stackaddr(a *obj.Addr) bool {
return a.Type == obj.TYPE_REG && a.Reg == arm64.REGSP
}
| bsd-3-clause |
hsu/chrono | src/collision/edgetempest/ChCAABB.cpp | 6739 | //
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2010 Alessandro Tasora
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//
//////////////////////////////////////////////////
//
// ChCAABB.cpp
//
// ------------------------------------------------
// www.deltaknowledge.com
// ------------------------------------------------
///////////////////////////////////////////////////
#include <stdlib.h>
#include <math.h>
#include "ChCAABB.h"
#include "ChCMatVec.h"
#include "collision/ChCCollisionPair.h"
namespace chrono {
namespace collision {
CHAABB::CHAABB() {
first_child = 0;
To = VNULL;
d = VNULL;
}
CHAABB::~CHAABB() {
}
void CHAABB::FitToGeometries(std::vector<geometry::ChGeometry*> mgeos, int firstgeo, int ngeos, double envelope) {
double minx, maxx, miny, maxy, minz, maxz;
minx = miny = minz = +10e20;
maxx = maxy = maxz = -10e20;
geometry::ChGeometry* nit = mgeos[firstgeo];
for (int count = 0; count < ngeos; ++count) {
nit = mgeos[firstgeo + count];
if (nit) {
nit->InflateBoundingBox(minx, maxx, miny, maxy, minz, maxz, NULL);
}
}
To.x = 0.5 * (maxx + minx);
To.y = 0.5 * (maxy + miny);
To.z = 0.5 * (maxz + minz);
d.x = 0.5 * (maxx - minx) + envelope;
d.y = 0.5 * (maxy - miny) + envelope;
d.z = 0.5 * (maxz - minz) + envelope;
}
bool CHAABB::AABB_Overlap(ChMatrix33<>& B, Vector T, CHAABB* b1, CHAABB* b2) {
ChMatrix33<> Bf;
const double reps = (double)1e-6;
// Bf = fabs(B)
Bf(0, 0) = myfabs(B.Get33Element(0, 0));
Bf(0, 0) += reps;
Bf(0, 1) = myfabs(B.Get33Element(0, 1));
Bf(0, 1) += reps;
Bf(0, 2) = myfabs(B.Get33Element(0, 2));
Bf(0, 2) += reps;
Bf(1, 0) = myfabs(B.Get33Element(1, 0));
Bf(1, 0) += reps;
Bf(1, 1) = myfabs(B.Get33Element(1, 1));
Bf(1, 1) += reps;
Bf(1, 2) = myfabs(B.Get33Element(1, 2));
Bf(1, 2) += reps;
Bf(2, 0) = myfabs(B.Get33Element(2, 0));
Bf(2, 0) += reps;
Bf(2, 1) = myfabs(B.Get33Element(2, 1));
Bf(2, 1) += reps;
Bf(2, 2) = myfabs(B.Get33Element(2, 2));
Bf(2, 2) += reps;
return AABB_Overlap(B, Bf, T, b1, b2);
}
bool CHAABB::AABB_Overlap(ChMatrix33<>& B, ChMatrix33<>& Bf, Vector T, CHAABB* b1, CHAABB* b2) {
double t, s;
int r;
Vector& a = b1->d;
Vector& b = b2->d;
// if any of these tests are one-sided, then the polyhedra are disjoint
r = 1;
// A1 x A2 = A0
t = myfabs(T.x);
r &= (t <= (a.x + b.x * Bf.Get33Element(0, 0) + b.y * Bf.Get33Element(0, 1) + b.z * Bf.Get33Element(0, 2)));
if (!r)
return false;
// B1 x B2 = B0
s = T.x * B.Get33Element(0, 0) + T.y * B.Get33Element(1, 0) + T.z * B.Get33Element(2, 0);
t = myfabs(s);
r &= (t <= (b.x + a.x * Bf.Get33Element(0, 0) + a.y * Bf.Get33Element(1, 0) + a.z * Bf.Get33Element(2, 0)));
if (!r)
return false;
// A2 x A0 = A1
t = myfabs(T.y);
r &= (t <= (a.y + b.x * Bf.Get33Element(1, 0) + b.y * Bf.Get33Element(1, 1) + b.z * Bf.Get33Element(1, 2)));
if (!r)
return false;
// A0 x A1 = A2
t = myfabs(T.z);
r &= (t <= (a.z + b.x * Bf.Get33Element(2, 0) + b.y * Bf.Get33Element(2, 1) + b.z * Bf.Get33Element(2, 2)));
if (!r)
return false;
// B2 x B0 = B1
s = T.x * B.Get33Element(0, 1) + T.y * B.Get33Element(1, 1) + T.z * B.Get33Element(2, 1);
t = myfabs(s);
r &= (t <= (b.y + a.x * Bf.Get33Element(0, 1) + a.y * Bf.Get33Element(1, 1) + a.z * Bf.Get33Element(2, 1)));
if (!r)
return false;
// B0 x B1 = B2
s = T.x * B.Get33Element(0, 2) + T.y * B.Get33Element(1, 2) + T.z * B.Get33Element(2, 2);
t = myfabs(s);
r &= (t <= (b.z + a.x * Bf.Get33Element(0, 2) + a.y * Bf.Get33Element(1, 2) + a.z * Bf.Get33Element(2, 2)));
if (!r)
return false;
// A0 x B0
s = T.z * B.Get33Element(1, 0) - T.y * B.Get33Element(2, 0);
t = myfabs(s);
r &= (t <= (a.y * Bf.Get33Element(2, 0) + a.z * Bf.Get33Element(1, 0) + b.y * Bf.Get33Element(0, 2) +
b.z * Bf.Get33Element(0, 1)));
if (!r)
return false;
// A0 x B1
s = T.z * B.Get33Element(1, 1) - T.y * B.Get33Element(2, 1);
t = myfabs(s);
r &= (t <= (a.y * Bf.Get33Element(2, 1) + a.z * Bf.Get33Element(1, 1) + b.x * Bf.Get33Element(0, 2) +
b.z * Bf.Get33Element(0, 0)));
if (!r)
return false;
// A0 x B2
s = T.z * B.Get33Element(1, 2) - T.y * B.Get33Element(2, 2);
t = myfabs(s);
r &= (t <= (a.y * Bf.Get33Element(2, 2) + a.z * Bf.Get33Element(1, 2) + b.x * Bf.Get33Element(0, 1) +
b.y * Bf.Get33Element(0, 0)));
if (!r)
return false;
// A1 x B0
s = T.x * B.Get33Element(2, 0) - T.z * B.Get33Element(0, 0);
t = myfabs(s);
r &= (t <= (a.x * Bf.Get33Element(2, 0) + a.z * Bf.Get33Element(0, 0) + b.y * Bf.Get33Element(1, 2) +
b.z * Bf.Get33Element(1, 1)));
if (!r)
return false;
// A1 x B1
s = T.x * B.Get33Element(2, 1) - T.z * B.Get33Element(0, 1);
t = myfabs(s);
r &= (t <= (a.x * Bf.Get33Element(2, 1) + a.z * Bf.Get33Element(0, 1) + b.x * Bf.Get33Element(1, 2) +
b.z * Bf.Get33Element(1, 0)));
if (!r)
return false;
// A1 x B2
s = T.x * B.Get33Element(2, 2) - T.z * B.Get33Element(0, 2);
t = myfabs(s);
r &= (t <= (a.x * Bf.Get33Element(2, 2) + a.z * Bf.Get33Element(0, 2) + b.x * Bf.Get33Element(1, 1) +
b.y * Bf.Get33Element(1, 0)));
if (!r)
return false;
// A2 x B0
s = T.y * B.Get33Element(0, 0) - T.x * B.Get33Element(1, 0);
t = myfabs(s);
r &= (t <= (a.x * Bf.Get33Element(1, 0) + a.y * Bf.Get33Element(0, 0) + b.y * Bf.Get33Element(2, 2) +
b.z * Bf.Get33Element(2, 1)));
if (!r)
return false;
// A2 x B1
s = T.y * B.Get33Element(0, 1) - T.x * B.Get33Element(1, 1);
t = myfabs(s);
r &= (t <= (a.x * Bf.Get33Element(1, 1) + a.y * Bf.Get33Element(0, 1) + b.x * Bf.Get33Element(2, 2) +
b.z * Bf.Get33Element(2, 0)));
if (!r)
return false;
// A2 x B2
s = T.y * B.Get33Element(0, 2) - T.x * B.Get33Element(1, 2);
t = myfabs(s);
r &= (t <= (a.x * Bf.Get33Element(1, 2) + a.y * Bf.Get33Element(0, 2) + b.x * Bf.Get33Element(2, 1) +
b.y * Bf.Get33Element(2, 0)));
if (!r)
return false;
return true; // no separation: BV collide
}
} // END_OF_NAMESPACE____
} // END_OF_NAMESPACE____
| bsd-3-clause |
meego-tablet-ux/meego-app-browser | webkit/database/database_util_unittest.cc | 1947 | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/database/database_util.h"
using webkit_database::DatabaseUtil;
static void TestVfsFilePath(bool expected_result,
const char* vfs_file_name,
const char* expected_origin_identifier = "",
const char* expected_database_name = "",
const char* expected_sqlite_suffix = "") {
string16 origin_identifier;
string16 database_name;
string16 sqlite_suffix;
EXPECT_EQ(expected_result,
DatabaseUtil::CrackVfsFileName(ASCIIToUTF16(vfs_file_name),
&origin_identifier,
&database_name,
&sqlite_suffix));
EXPECT_EQ(ASCIIToUTF16(expected_origin_identifier), origin_identifier);
EXPECT_EQ(ASCIIToUTF16(expected_database_name), database_name);
EXPECT_EQ(ASCIIToUTF16(expected_sqlite_suffix), sqlite_suffix);
}
namespace webkit_database {
// Test DatabaseUtil::CrackVfsFilePath on various inputs.
TEST(DatabaseUtilTest, CrackVfsFilePathTest) {
TestVfsFilePath(true, "origin/#", "origin", "", "");
TestVfsFilePath(true, "origin/#suffix", "origin", "", "suffix");
TestVfsFilePath(true, "origin/db_name#", "origin", "db_name", "");
TestVfsFilePath(true, "origin/db_name#suffix", "origin", "db_name", "suffix");
TestVfsFilePath(false, "origindb_name#");
TestVfsFilePath(false, "origindb_name#suffix");
TestVfsFilePath(false, "origin/db_name");
TestVfsFilePath(false, "origin#db_name/suffix");
TestVfsFilePath(false, "/db_name#");
TestVfsFilePath(false, "/db_name#suffix");
}
} // namespace webkit_database
| bsd-3-clause |
localheinz/modules.zendframework.com | config/application.config.php | 504 | <?php
return [
'modules' => [
'DoctrineModule',
'DoctrineORMModule',
'ZF\DevelopmentMode',
'ZfcBase',
'ZfcUser',
'ScnSocialAuth',
'EdpGithub',
'Application',
'User',
'ZfModule',
],
'module_listener_options' => [
'config_glob_paths' => [
'config/autoload/{,*.}{global,local}.php',
],
'module_paths' => [
'./module',
'./vendor',
],
],
];
| bsd-3-clause |
stephens2424/php | testdata/fuzzdir/corpus/ext_ctype_tests_ctype_print_variation4.php | 767 | <?php
/* Prototype : bool ctype_print(mixed $c)
* Description: Checks for printable character(s)
* Source code: ext/ctype/ctype.c
*/
/*
* Pass octal and hexadecimal values to ctype_print() to test behaviour
*/
echo "*** Testing ctype_print() : usage variations ***\n";
$orig = setlocale(LC_CTYPE, "C");
$octal_values = array(040, 041, 042, 043);
$hex_values = array (0x20, 0x21, 0x23, 0x24);
echo "\n-- Octal Values --\n";
$iterator = 1;
foreach($octal_values as $c) {
echo "-- Iteration $iterator --\n";
var_dump(ctype_print($c));
$iterator++;
}
echo "\n-- Hexadecimal Values --\n";
$iterator = 1;
foreach($hex_values as $c) {
echo "-- Iteration $iterator --\n";
var_dump(ctype_print($c));
$iterator++;
}
setlocale(LC_CTYPE, $orig);
?>
===DONE===
| bsd-3-clause |
tyrexsoftware/ppui | vendor/kartik-v/yii2-date-range/assets/js/locales/ar-sa.js | 3478 | // moment.js locale configuration
// locale : Arabic Saudi Arabia (ar-sa)
// author : Suhail Alkowaileet : https://github.com/xsoh
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['moment'], factory); // AMD
} else if (typeof exports === 'object') {
module.exports = factory(require('../moment')); // Node
} else {
factory((typeof global !== 'undefined' ? global : this).moment); // node or other global
}
}(function (moment) {
var symbolMap = {
'1': '١',
'2': '٢',
'3': '٣',
'4': '٤',
'5': '٥',
'6': '٦',
'7': '٧',
'8': '٨',
'9': '٩',
'0': '٠'
}, numberMap = {
'١': '1',
'٢': '2',
'٣': '3',
'٤': '4',
'٥': '5',
'٦': '6',
'٧': '7',
'٨': '8',
'٩': '9',
'٠': '0'
};
return moment.defineLocale('ar-sa', {
months : 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
monthsShort : 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
weekdaysShort : 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'),
longDateFormat : {
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'DD/MM/YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY LT',
LLLL : 'dddd D MMMM YYYY LT'
},
meridiem : function (hour, minute, isLower) {
if (hour < 12) {
return 'ص';
} else {
return 'م';
}
},
calendar : {
sameDay: '[اليوم على الساعة] LT',
nextDay: '[غدا على الساعة] LT',
nextWeek: 'dddd [على الساعة] LT',
lastDay: '[أمس على الساعة] LT',
lastWeek: 'dddd [على الساعة] LT',
sameElse: 'L'
},
relativeTime : {
future : 'في %s',
past : 'منذ %s',
s : 'ثوان',
m : 'دقيقة',
mm : '%d دقائق',
h : 'ساعة',
hh : '%d ساعات',
d : 'يوم',
dd : '%d أيام',
M : 'شهر',
MM : '%d أشهر',
y : 'سنة',
yy : '%d سنوات'
},
preparse: function (string) {
return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) {
return numberMap[match];
}).replace(/،/g, ',');
},
postformat: function (string) {
return string.replace(/\d/g, function (match) {
return symbolMap[match];
}).replace(/,/g, '،');
},
week : {
dow : 6, // Saturday is the first day of the week.
doy : 12 // The week that contains Jan 1st is the first week of the year.
}
});
}));
| bsd-3-clause |
akra/alchemy_cms | lib/alchemy/hints.rb | 1179 | module Alchemy
module Hints
# Returns a hint
#
# To add a hint to a content pass +hint: true+ to the element definition in its element.yml
#
# Then the hint itself is placed in the locale yml files.
#
# Alternativly you can pass the hint itself to the hint key.
#
# == Locale Example:
#
# # elements.yml
# - name: headline
# contents:
# - name: headline
# type: EssenceText
# hint: true
#
# # config/locales/de.yml
# de:
# content_hints:
# headline: Lorem ipsum
#
# == Hint Key Example:
#
# - name: headline
# contents:
# - name: headline
# type: EssenceText
# hint: Lorem ipsum
#
# @return String
#
def hint
hint = definition['hint']
if hint == true
Alchemy.t(name, scope: hint_translation_scope)
else
hint
end
end
# Returns true if the element has a hint
def has_hint?
hint.present?
end
private
def hint_translation_scope
"#{self.class.model_name.to_s.demodulize.downcase}_hints"
end
end
end
| bsd-3-clause |
uonafya/jphes | dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-datadictionary/src/main/java/org/hisp/dhis/dd/action/category/GetDataElementCategoryListAction.java | 4483 | package org.hisp.dhis.dd.action.category;
/*
* Copyright (c) 2004-2015, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import java.util.Collections;
import java.util.List;
import org.hisp.dhis.common.comparator.IdentifiableObjectNameComparator;
import org.hisp.dhis.dataelement.DataElementCategory;
import org.hisp.dhis.dataelement.DataElementCategoryService;
import org.hisp.dhis.paging.ActionPagingSupport;
/**
* @author Abyot Asalefew
* @version $Id$
*/
public class GetDataElementCategoryListAction
extends ActionPagingSupport<DataElementCategory>
{
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
private DataElementCategoryService dataElementCategoryService;
public void setDataElementCategoryService( DataElementCategoryService dataElementCategoryService )
{
this.dataElementCategoryService = dataElementCategoryService;
}
// -------------------------------------------------------------------------
// Getters & Setters
// -------------------------------------------------------------------------
private List<DataElementCategory> dataElementCategories;
public List<DataElementCategory> getDataElementCategories()
{
return dataElementCategories;
}
private DataElementCategory defaultCategory;
public DataElementCategory getDefaultCategory()
{
return defaultCategory;
}
private String key;
public String getKey()
{
return key;
}
public void setKey( String key )
{
this.key = key;
}
// -------------------------------------------------------------------------
// Action implementation
// -------------------------------------------------------------------------
@Override
public String execute()
{
defaultCategory = dataElementCategoryService.getDataElementCategoryByName( DataElementCategory.DEFAULT_NAME );
if ( isNotBlank( key ) ) // Filter on key only if set
{
this.paging = createPaging( dataElementCategoryService.getDataElementCategoryCountByName( key ) );
dataElementCategories = dataElementCategoryService.getDataElementCategoriesBetweenByName( key, paging.getStartPos(), paging.getPageSize() );
}
else
{
this.paging = createPaging( dataElementCategoryService.getDataElementCategoryCount() );
dataElementCategories = dataElementCategoryService.getDataElementCategoriesBetween( paging.getStartPos(), paging.getPageSize() );
}
Collections.sort( dataElementCategories, IdentifiableObjectNameComparator.INSTANCE );
return SUCCESS;
}
}
| bsd-3-clause |
axinging/chromium-crosswalk | content/browser/wake_lock/wake_lock_service_context.cc | 2899 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/wake_lock/wake_lock_service_context.h"
#include <utility>
#include "base/bind.h"
#include "build/build_config.h"
#include "content/browser/power_save_blocker_impl.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/power_save_blocker.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/service_registry.h"
namespace content {
WakeLockServiceContext::WakeLockServiceContext(WebContents* web_contents)
: WebContentsObserver(web_contents), weak_factory_(this) {}
WakeLockServiceContext::~WakeLockServiceContext() {}
void WakeLockServiceContext::CreateService(
int render_process_id,
int render_frame_id,
mojo::InterfaceRequest<blink::mojom::WakeLockService> request) {
new WakeLockServiceImpl(weak_factory_.GetWeakPtr(), render_process_id,
render_frame_id, std::move(request));
}
void WakeLockServiceContext::RenderFrameDeleted(
RenderFrameHost* render_frame_host) {
CancelWakeLock(render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID());
}
void WakeLockServiceContext::RequestWakeLock(int render_process_id,
int render_frame_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!RenderFrameHost::FromID(render_process_id, render_frame_id))
return;
frames_requesting_lock_.insert(
std::pair<int, int>(render_process_id, render_frame_id));
UpdateWakeLock();
}
void WakeLockServiceContext::CancelWakeLock(int render_process_id,
int render_frame_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
frames_requesting_lock_.erase(
std::pair<int, int>(render_process_id, render_frame_id));
UpdateWakeLock();
}
bool WakeLockServiceContext::HasWakeLockForTests() const {
return !!wake_lock_;
}
void WakeLockServiceContext::CreateWakeLock() {
DCHECK(!wake_lock_);
wake_lock_ = PowerSaveBlocker::Create(
PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
PowerSaveBlocker::kReasonOther, "Wake Lock API");
#if defined(OS_ANDROID)
// On Android, additionaly associate the blocker with this WebContents.
DCHECK(web_contents());
static_cast<PowerSaveBlockerImpl*>(wake_lock_.get())
->InitDisplaySleepBlocker(web_contents());
#endif
}
void WakeLockServiceContext::RemoveWakeLock() {
DCHECK(wake_lock_);
wake_lock_.reset();
}
void WakeLockServiceContext::UpdateWakeLock() {
if (!frames_requesting_lock_.empty()) {
if (!wake_lock_)
CreateWakeLock();
} else {
if (wake_lock_)
RemoveWakeLock();
}
}
} // namespace content
| bsd-3-clause |
BiovistaInc/gwt-d3 | gwt-d3-demo/src/main/java/com/github/gwtd3/demo/client/testcases/scales/TestIdentityScale.java | 5103 | /**
* Copyright (c) 2013, Anthony Schiochet and Eric Citaire
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * The names Anthony Schiochet and Eric Citaire may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.github.gwtd3.demo.client.testcases.scales;
import com.github.gwtd3.api.D3;
import com.github.gwtd3.api.arrays.Array;
import com.github.gwtd3.api.scales.IdentityScale;
import com.github.gwtd3.demo.client.test.AbstractTestCase;
import com.google.gwt.user.client.ui.ComplexPanel;
public class TestIdentityScale extends AbstractTestCase {
@Override
public void doTest(final ComplexPanel sandbox) {
IdentityScale scale = D3.scale.identity();
// get default domain
assertEquals(2, scale.domain().length());
assertEquals(0, scale.domain().getValue(0).asInt());
assertEquals(1, scale.domain().getValue(1).asInt());
// set the domain, keep the default range [0,1]
scale.domain(0, 10);
assertEquals(2, scale.domain().length());
assertEquals(0, scale.domain().getValue(0).asInt());
assertEquals(10, scale.domain().getValue(1).asInt());
scale.domain("5", "6");
assertEquals(2, scale.domain().length());
assertEquals("5", scale.domain().getValue(0).asString());
assertEquals("6", scale.domain().getValue(1).asString());
scale.domain(-1, 0, 1).range(
Array.fromObjects(new String[] { "red", "white", "blue" }));
assertEquals(3, scale.domain().length());
assertEquals(0, scale.domain().getValue(0).asInt());
assertEquals(0, scale.domain().getValue(1).asInt());
assertEquals(0, scale.domain().getValue(2).asInt());
// default range
scale = D3.scale.identity();
assertEquals(0.0, scale.range().getNumber(0));
assertEquals(1.0, scale.range().getNumber(1));
// set the range
scale.range(0, 100);
assertEquals(0.0, scale.range().getNumber(0));
assertEquals(100.0, scale.range().getNumber(1));
scale.range(0, 100, 200);
assertEquals(0.0, scale.range().getNumber(0));
assertEquals(100.0, scale.range().getNumber(1));
assertEquals(200.0, scale.range().getNumber(2));
// ticks
scale.domain(10, 20);
assertEquals(3, scale.ticks(2).length());
assertEquals(10.0, scale.ticks(2).getNumber(0));
assertEquals(15.0, scale.ticks(2).getNumber(1));
assertEquals(20.0, scale.ticks(2).getNumber(2));
assertEquals(11, scale.ticks(11).length());
assertEquals(10.0, scale.ticks(11).getNumber(0));
assertEquals(11.0, scale.ticks(11).getNumber(1));
assertEquals(15.0, scale.ticks(11).getNumber(5));
assertEquals(20.0, scale.ticks(11).getNumber(10));
assertEquals(6, scale.ticks(4).length());
assertEquals(10.0, scale.ticks(4).getNumber(0));
assertEquals(12.0, scale.ticks(4).getNumber(1));
assertEquals(14.0, scale.ticks(4).getNumber(2));
assertEquals(16.0, scale.ticks(4).getNumber(3));
assertEquals(18.0, scale.ticks(4).getNumber(4));
assertEquals(20.0, scale.ticks(4).getNumber(5));
// tickFormat
scale.domain(10, 20);
assertEquals("10", scale.tickFormat(2).format(10));
assertEquals("20", scale.tickFormat(2).format(20));
assertEquals("10.00", scale.tickFormat(200).format(10));
assertEquals("20.00", scale.tickFormat(200).format(20));
assertEquals("015.00", scale.tickFormat(200, "06f").format(15));
// apply the function
scale.domain(0, 1).range(0, 10);
assertEquals(0, scale.apply(0).asInt());
assertEquals(15, scale.apply(15).asInt());
assertEquals(100, scale.apply(100).asInt());
assertEquals(-10, scale.apply(-10).asInt());
// invert
assertEquals(100, scale.invert(100).asInt());
assertEquals(-100, scale.invert(-100).asInt());
// copy
scale.domain(1, 2);
IdentityScale copy = scale.copy();
copy.domain(2, 3);
assertEquals(1.0, scale.domain().getNumber(0));
assertEquals(2.0, scale.domain().getNumber(1));
}
}
| bsd-3-clause |
michalczapko/rubinius-x | vm/builtin/compiled_code.hpp | 4303 | #ifndef RBX_BUILTIN_COMPILEDCODE_HPP
#define RBX_BUILTIN_COMPILEDCODE_HPP
#include "builtin/executable.hpp"
namespace rubinius {
class InstructionSequence;
class MachineCode;
class ConstantScope;
class CallSite;
namespace jit {
class RuntimeDataHolder;
}
class CompiledCode : public Executable {
public:
const static object_type type = CompiledCodeType;
private:
Object* metadata_; // slot
Symbol* name_; // slot
InstructionSequence* iseq_; // slot
Fixnum* stack_size_; // slot
Fixnum* local_count_; // slot
Fixnum* required_args_; // slot
Fixnum* post_args_; // slot
Fixnum* total_args_; // slot
Fixnum* splat_; // slot
Tuple* lines_; // slot
Tuple* local_names_; // slot
Symbol* file_; // slot
ConstantScope* scope_; // slot
LookupTable* breakpoints_; // slot
MachineCode* machine_code_;
#ifdef ENABLE_LLVM
jit::RuntimeDataHolder* jit_data_;
#endif
public:
// Access directly from assembly, so has to be public.
Tuple* literals_; // slot
/* accessors */
MachineCode* machine_code() {
return machine_code_;
}
#ifdef ENABLE_LLVM
jit::RuntimeDataHolder* jit_data() {
return jit_data_;
}
void set_jit_data(jit::RuntimeDataHolder* rds) {
jit_data_ = rds;
}
#endif
bool can_specialize_p();
void set_unspecialized(executor exec, jit::RuntimeDataHolder* rd);
void add_specialized(uint32_t class_id, uint32_t serial_id, executor exec, jit::RuntimeDataHolder* rd);
executor find_specialized(Class* cls);
attr_accessor(metadata, Object);
attr_accessor(name, Symbol);
attr_accessor(iseq, InstructionSequence);
attr_accessor(stack_size, Fixnum);
attr_accessor(local_count, Fixnum);
attr_accessor(required_args, Fixnum);
attr_accessor(post_args, Fixnum);
attr_accessor(total_args, Fixnum);
attr_accessor(splat, Fixnum);
attr_accessor(literals, Tuple);
attr_accessor(lines, Tuple);
attr_accessor(local_names, Tuple);
attr_accessor(file, Symbol);
attr_accessor(scope, ConstantScope);
attr_accessor(breakpoints, LookupTable);
/* interface */
static void init(STATE);
// Rubinius.primitive :compiledcode_allocate
static CompiledCode* create(STATE);
static Object* primitive_failed(STATE, CallFrame* call_frame, Executable* exec, Module* mod, Arguments& args);
int start_line(STATE);
int start_line();
int line(STATE, int ip);
int line(int ip);
void post_marshal(STATE);
size_t number_of_locals();
MachineCode* internalize(STATE, GCToken gct, CallFrame* call_frame, const char** failure_reason=0, int* ip=0);
void specialize(STATE, TypeInfo* ti);
static Object* default_executor(STATE, CallFrame*, Executable* exec, Module* mod, Arguments& args);
static Object* specialized_executor(STATE, CallFrame*, Executable* exec, Module* mod, Arguments& args);
// Rubinius.primitive :compiledcode_set_breakpoint
Object* set_breakpoint(STATE, GCToken gct, Fixnum* ip, Object* bp, CallFrame* calling_environment);
// Rubinius.primitive :compiledcode_clear_breakpoint
Object* clear_breakpoint(STATE, Fixnum* ip);
// Rubinius.primitive :compiledcode_is_breakpoint
Object* is_breakpoint(STATE, Fixnum* ip);
// Rubinius.primitive+ :compiledcode_of_sender
static CompiledCode* of_sender(STATE, CallFrame* calling_environment);
// Rubinius.primitive+ :compiledcode_current
static CompiledCode* current(STATE, CallFrame* calling_environment);
// Rubinius.primitive :compiledcode_dup
CompiledCode* dup(STATE);
// Rubinius.primitive :compiledcode_call_sites
Tuple* call_sites(STATE, CallFrame* calling_environment);
// Rubinius.primitive :compiledcode_constant_caches
Tuple* constant_caches(STATE, CallFrame* calling_environment);
String* full_name(STATE);
bool kernel_method(STATE);
class Info : public Executable::Info {
public:
BASIC_TYPEINFO(Executable::Info)
virtual void mark(Object* obj, ObjectMark& mark);
virtual void show(STATE, Object* self, int level);
};
friend class Info;
};
};
#endif
| bsd-3-clause |
djn21/proman | _protected/vendor/wingu/reflection/src/ReflectionParameter.php | 1729 | <?php
namespace Wingu\OctopusCore\Reflection;
/**
* Reflection about a parameter.
*/
class ReflectionParameter extends \ReflectionParameter
{
/**
* Parameter function.
*
* @var mixed
*/
private $function;
/**
* Constructor.
*
* @param string $function The function to reflect parameters from. It can be also be in the format: array('className', 'methodName').
* @param string $parameter The parameter name.
*/
public function __construct($function, $parameter)
{
$this->function = $function;
parent::__construct($function, $parameter);
}
/**
* Gets a class.
*
* @return \Wingu\OctopusCore\Reflection\ReflectionClass
*/
public function getClass()
{
$class = parent::getClass();
if ($class !== null) {
$class = new ReflectionClass($class->getName());
}
return $class;
}
/**
* Gets the declaring class.
*
* @return \Wingu\OctopusCore\Reflection\ReflectionClass
*/
public function getDeclaringClass()
{
$class = parent::getDeclaringClass();
if ($class !== null) {
$class = new ReflectionClass($class->getName());
}
return $class;
}
/**
* Gets the declaring function.
*
* @return \Wingu\OctopusCore\Reflection\ReflectionMethod|\Wingu\OctopusCore\Reflection\ReflectionFunction
*/
public function getDeclaringFunction()
{
if (is_array($this->function) === true) {
return new ReflectionMethod($this->function[0], $this->function[1]);
} else {
return new ReflectionFunction($this->function);
}
}
}
| bsd-3-clause |
heracek/django-nonrel | tests/regressiontests/views/tests/defaults.py | 3727 | from os import path
from django.conf import settings
from django.test import TestCase
from django.contrib.contenttypes.models import ContentType
from regressiontests.views.models import Author, Article, UrlArticle
class DefaultsTests(TestCase):
"""Test django views in django/views/defaults.py"""
fixtures = ['testdata.json']
non_existing_urls = ['/views/non_existing_url/', # this is in urls.py
'/views/other_non_existing_url/'] # this NOT in urls.py
def test_shortcut_with_absolute_url(self):
"Can view a shortcut for an Author object that has a get_absolute_url method"
for obj in Author.objects.all():
short_url = '/views/shortcut/%s/%s/' % (ContentType.objects.get_for_model(Author).id, obj.pk)
response = self.client.get(short_url)
self.assertRedirects(response, 'http://testserver%s' % obj.get_absolute_url(),
status_code=302, target_status_code=404)
def test_shortcut_no_absolute_url(self):
"Shortcuts for an object that has no get_absolute_url method raises 404"
for obj in Article.objects.all():
short_url = '/views/shortcut/%s/%s/' % (ContentType.objects.get_for_model(Article).id, obj.pk)
response = self.client.get(short_url)
self.assertEquals(response.status_code, 404)
def test_wrong_type_pk(self):
short_url = '/views/shortcut/%s/%s/' % (ContentType.objects.get_for_model(Author).id, 'nobody/expects')
response = self.client.get(short_url)
self.assertEquals(response.status_code, 404)
def test_shortcut_bad_pk(self):
short_url = '/views/shortcut/%s/%s/' % (ContentType.objects.get_for_model(Author).id, '42424242')
response = self.client.get(short_url)
self.assertEquals(response.status_code, 404)
def test_nonint_content_type(self):
an_author = Author.objects.all()[0]
short_url = '/views/shortcut/%s/%s/' % ('spam', an_author.pk)
response = self.client.get(short_url)
self.assertEquals(response.status_code, 404)
def test_bad_content_type(self):
an_author = Author.objects.all()[0]
short_url = '/views/shortcut/%s/%s/' % (42424242, an_author.pk)
response = self.client.get(short_url)
self.assertEquals(response.status_code, 404)
def test_page_not_found(self):
"A 404 status is returned by the page_not_found view"
for url in self.non_existing_urls:
response = self.client.get(url)
self.assertEquals(response.status_code, 404)
def test_csrf_token_in_404(self):
"""
The 404 page should have the csrf_token available in the context
"""
# See ticket #14565
for url in self.non_existing_urls:
response = self.client.get(url)
csrf_token = response.context['csrf_token']
self.assertNotEqual(str(csrf_token), 'NOTPROVIDED')
self.assertNotEqual(str(csrf_token), '')
def test_server_error(self):
"The server_error view raises a 500 status"
response = self.client.get('/views/server_error/')
self.assertEquals(response.status_code, 500)
def test_get_absolute_url_attributes(self):
"A model can set attributes on the get_absolute_url method"
self.assertTrue(getattr(UrlArticle.get_absolute_url, 'purge', False),
'The attributes of the original get_absolute_url must be added.')
article = UrlArticle.objects.get(pk=1)
self.assertTrue(getattr(article.get_absolute_url, 'purge', False),
'The attributes of the original get_absolute_url must be added.')
| bsd-3-clause |
stephenplaza/NeuTu | neurolabi/gui/dialogs/swcsizedialog.cpp | 392 | #include "swcsizedialog.h"
#include "ui_swcsizedialog.h"
SwcSizeDialog::SwcSizeDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SwcSizeDialog)
{
ui->setupUi(this);
}
SwcSizeDialog::~SwcSizeDialog()
{
delete ui;
}
double SwcSizeDialog::getAddValue()
{
return ui->doubleAddSpinBox->value();
}
double SwcSizeDialog::getMulValue()
{
return ui->doubleScaleSpinBox->value();
}
| bsd-3-clause |
tempbottle/DrizzleJDBC | src/test/java/org/drizzle/jdbc/DriverTest.java | 54132 | package org.drizzle.jdbc;
import org.junit.Assert;
import org.junit.Test;
import org.junit.After;
import org.drizzle.jdbc.internal.common.packet.buffer.WriteBuffer;
import org.drizzle.jdbc.internal.common.packet.RawPacket;
import org.drizzle.jdbc.internal.common.*;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.mock;
import java.math.BigInteger;
import java.sql.*;
import java.util.List;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
/**
* User: marcuse
* Date: Jan 14, 2009
* Time: 7:58:11 AM
*/
public class DriverTest {
public static String host = "10.100.100.50";
private Connection connection;
static { Logger.getLogger("").setLevel(Level.OFF); }
public DriverTest() throws SQLException {
connection = DriverManager.getConnection("jdbc:mysql:thin://10.100.100.50:3306/test_units_jdbc");
//connection = DriverManager.getConnection("jdbc:drizzle://root@"+host+":3307/test_units_jdbc");
//connection = DriverManager.getConnection("jdbc:mysql://10.100.100.50:3306/test_units_jdbc");
}
@After
public void close() throws SQLException {
connection.close();
}
public Connection getConnection() {
return connection;
}
@Test
public void doQuery() throws SQLException{
Statement stmt = getConnection().createStatement();
try { stmt.execute("drop table t1"); } catch (Exception e) {}
stmt.execute("create table t1 (id int not null primary key auto_increment, test varchar(20))");
stmt.execute("insert into t1 (test) values (\"hej1\")");
stmt.execute("insert into t1 (test) values (\"hej2\")");
stmt.execute("insert into t1 (test) values (\"hej3\")");
stmt.execute("insert into t1 (test) values (null)");
ResultSet rs = stmt.executeQuery("select * from t1");
for(int i=1;i<4;i++) {
rs.next();
assertEquals(String.valueOf(i),rs.getString(1));
assertEquals("hej"+i,rs.getString("test"));
}
rs.next();
assertEquals(null,rs.getString("test"));
}
@Test(expected = SQLException.class)
public void askForBadColumnTest() throws SQLException{
Statement stmt = getConnection().createStatement();
try { stmt.execute("drop table t1"); } catch (Exception e) {}
stmt.execute("create table t1 (id int not null primary key auto_increment, test varchar(20))");
stmt.execute("insert into t1 (test) values (\"hej1\")");
stmt.execute("insert into t1 (test) values (\"hej2\")");
stmt.execute("insert into t1 (test) values (\"hej3\")");
stmt.execute("insert into t1 (test) values (null)");
ResultSet rs = stmt.executeQuery("select * from t1");
rs.next();
rs.getInt("non_existing_column");
}
@Test(expected = SQLException.class)
public void askForBadColumnIndexTest() throws SQLException{
Statement stmt = getConnection().createStatement();
try { stmt.execute("drop table t1"); } catch (Exception e) {}
stmt.execute("create table t1 (id int not null primary key auto_increment, test varchar(20))");
stmt.execute("insert into t1 (test) values (\"hej1\")");
stmt.execute("insert into t1 (test) values (\"hej2\")");
stmt.execute("insert into t1 (test) values (\"hej3\")");
stmt.execute("insert into t1 (test) values (null)");
ResultSet rs = stmt.executeQuery("select * from t1");
rs.next();
rs.getInt(102);
}
@Test(expected = SQLException.class)
public void badQuery() throws SQLException {
Statement stmt = getConnection().createStatement();
stmt.executeQuery("whraoaooa");
}
@Test
public void intOperations() {
byte [] a = WriteBuffer.intToByteArray(56*256*256*256 + 11*256*256 + 77*256 + 99);
assertEquals(a[0],99);
assertEquals(a[1],77);
assertEquals(a[2],11);
assertEquals(a[3],56);
}
@Test
public void preparedTest() throws SQLException {
String query = "SELECT * FROM t1 WHERE test = ? and id = ?";
PreparedStatement prepStmt = getConnection().prepareStatement(query);
prepStmt.setString(1,"hej1");
prepStmt.setInt(2,1);
ResultSet results = prepStmt.executeQuery();
String res = "";
while(results.next()) {
res=results.getString("test");
}
assertEquals("hej1",res);
assertEquals(2, prepStmt.getParameterMetaData().getParameterCount());
}
@Test
public void preparedTest2() throws SQLException {
Statement stmt = getConnection().createStatement();
stmt.executeQuery("DROP TABLE IF EXISTS prep_test");
stmt.executeQuery("CREATE TABLE prep_test (id int not null primary key auto_increment, test varchar(20)) engine=innodb");
PreparedStatement prepStmt = getConnection().prepareStatement("insert into prep_test (test) values (?) ");
for(int i=0;i<1000;i++) {
prepStmt.setString(1,"mee");
prepStmt.execute();
}
}
@Test
public void updateTest() throws SQLException {
Statement stmt = getConnection().createStatement();
try { stmt.execute("drop table t1"); } catch (Exception e) {}
stmt.execute("create table t1 (id int not null primary key auto_increment, test varchar(20))");
stmt.execute("insert into t1 (test) values (\"hej1\")");
stmt.execute("insert into t1 (test) values (\"hej2\")");
stmt.execute("insert into t1 (test) values (\"hej3\")");
stmt.execute("insert into t1 (test) values (null)");
String query = "UPDATE t1 SET test = ? where id = ?";
PreparedStatement prepStmt = getConnection().prepareStatement(query);
prepStmt.setString(1,"updated");
prepStmt.setInt(2,3);
int updateCount = prepStmt.executeUpdate();
assertEquals(1,updateCount);
String query2 = "SELECT * FROM t1 WHERE id=?";
prepStmt = getConnection().prepareStatement(query2);
prepStmt.setInt(1,3);
ResultSet results = prepStmt.executeQuery();
String result = "";
while(results.next()) {
result = results.getString("test");
}
assertEquals("updated",result);
}
@Test
public void autoIncTest() throws SQLException {
String query = "CREATE TABLE t2 (id int not null primary key auto_increment, test varchar(10))";
Statement stmt = getConnection().createStatement();
stmt.execute("DROP TABLE IF EXISTS t2");
stmt.execute(query);
stmt.execute("INSERT INTO t2 (test) VALUES ('aa')");
ResultSet rs = stmt.getGeneratedKeys();
if(rs.next()) {
assertEquals(1,rs.getInt(1));
assertEquals(1,rs.getInt("insert_id"));
} else {
throw new SQLException("Could not get generated keys");
}
stmt.execute("INSERT INTO t2 (test) VALUES ('aa')");
rs = stmt.getGeneratedKeys();
if(rs.next()) {
assertEquals(2,rs.getInt(1));
assertEquals(2,rs.getInt("insert_id"));
} else {
throw new SQLException("Could not get generated keys");
}
}
@Test
public void autoIncPrepStmtTest() throws SQLException {
String query = "CREATE TABLE test_a_inc_prep_stmt (id int not null primary key auto_increment, test varchar(10))";
Statement stmt = getConnection().createStatement();
stmt.execute("DROP TABLE IF EXISTS test_a_inc_prep_stmt");
stmt.execute(query);
PreparedStatement ps = getConnection().prepareStatement("insert into test_a_inc_prep_stmt (test) values (?)");
ps.setString(1,"test123");
ps.execute();
ResultSet rs = ps.getGeneratedKeys();
assertTrue(rs.next());
assertEquals(1,rs.getInt(1));
assertEquals(1,rs.getInt("insert_id"));
}
@Test
public void transactionTest() throws SQLException {
Statement stmt = getConnection().createStatement();
stmt.executeQuery("DROP TABLE IF EXISTS t3");
stmt.executeQuery("CREATE TABLE t3 (id int not null primary key auto_increment, test varchar(20)) engine=innodb");
getConnection().setAutoCommit(false);
stmt.executeUpdate("INSERT INTO t3 (test) VALUES ('heja')");
stmt.executeUpdate("INSERT INTO t3 (test) VALUES ('japp')");
getConnection().commit();
ResultSet rs = stmt.executeQuery("SELECT * FROM t3");
assertEquals(true,rs.next());
assertEquals("heja",rs.getString("test"));
assertEquals(true,rs.next());
assertEquals("japp",rs.getString("test"));
assertEquals(false, rs.next());
stmt.executeUpdate("INSERT INTO t3 (test) VALUES ('rollmeback')");
ResultSet rsGen = stmt.getGeneratedKeys();
rsGen.next();
assertEquals(3,rsGen.getInt(1));
getConnection().rollback();
rs = stmt.executeQuery("SELECT * FROM t3 WHERE id=3");
assertEquals(false,rs.next());
}
@Test
public void savepointTest() throws SQLException {
Statement stmt = getConnection().createStatement();
stmt.executeUpdate("drop table if exists t4");
stmt.executeUpdate("create table t4 (id int not null primary key auto_increment, test varchar(20)) engine=innodb");
getConnection().setAutoCommit(false);
stmt.executeUpdate("INSERT INTO t4 (test) values('hej1')");
stmt.executeUpdate("INSERT INTO t4 (test) values('hej2')");
Savepoint savepoint = getConnection().setSavepoint("yep");
stmt.executeUpdate("INSERT INTO t4 (test) values('hej3')");
stmt.executeUpdate("INSERT INTO t4 (test) values('hej4')");
getConnection().rollback(savepoint);
stmt.executeUpdate("INSERT INTO t4 (test) values('hej5')");
stmt.executeUpdate("INSERT INTO t4 (test) values('hej6')");
getConnection().commit();
ResultSet rs = stmt.executeQuery("SELECT * FROM t4");
assertEquals(true, rs.next());
assertEquals("hej1",rs.getString(2));
assertEquals(true, rs.next());
assertEquals("hej2",rs.getString(2));
assertEquals(true, rs.next());
assertEquals("hej5",rs.getString(2));
assertEquals(true, rs.next());
assertEquals("hej6",rs.getString(2));
assertEquals(false,rs.next());
}
@Test
public void isolationLevel() throws SQLException {
getConnection().setTransactionIsolation(getConnection().TRANSACTION_READ_UNCOMMITTED);
assertEquals(getConnection().TRANSACTION_READ_UNCOMMITTED,getConnection().getTransactionIsolation());
getConnection().setTransactionIsolation(getConnection().TRANSACTION_READ_COMMITTED);
assertEquals(getConnection().TRANSACTION_READ_COMMITTED,getConnection().getTransactionIsolation());
getConnection().setTransactionIsolation(getConnection().TRANSACTION_SERIALIZABLE);
assertEquals(getConnection().TRANSACTION_SERIALIZABLE,getConnection().getTransactionIsolation());
getConnection().setTransactionIsolation(getConnection().TRANSACTION_REPEATABLE_READ);
assertEquals(getConnection().TRANSACTION_REPEATABLE_READ,getConnection().getTransactionIsolation());
}
@Test
public void isValidTest() throws SQLException {
assertEquals(true,getConnection().isValid(0));
}
@Test
public void conStringTest() throws SQLException {
JDBCUrl url = JDBCUrl.parse("jdbc:drizzle://www.drizzle.org:4427/mmm");
assertEquals("",url.getUsername());
assertEquals("",url.getPassword());
assertEquals("www.drizzle.org",url.getHostname());
assertEquals(4427,url.getPort());
assertEquals("mmm",url.getDatabase());
assertEquals(JDBCUrl.DBType.DRIZZLE, url.getDBType());
url = JDBCUrl.parse("jdbc:mysql:thin://www.drizzle.org:3306/mmm");
assertEquals("",url.getUsername());
assertEquals("",url.getPassword());
assertEquals("www.drizzle.org",url.getHostname());
assertEquals(3306,url.getPort());
assertEquals("mmm",url.getDatabase());
assertEquals(JDBCUrl.DBType.MYSQL, url.getDBType());
url = JDBCUrl.parse("jdbc:drizzle://whoa@www.drizzle.org:4427/mmm");
assertEquals("whoa",url.getUsername());
assertEquals("",url.getPassword());
assertEquals("www.drizzle.org",url.getHostname());
assertEquals(4427,url.getPort());
assertEquals("mmm",url.getDatabase());
assertEquals(JDBCUrl.DBType.DRIZZLE, url.getDBType());
url = JDBCUrl.parse("jdbc:mysql:thin://whoa@www.drizzle.org:4427/mmm");
assertEquals("whoa",url.getUsername());
assertEquals("",url.getPassword());
assertEquals("www.drizzle.org",url.getHostname());
assertEquals(4427,url.getPort());
assertEquals("mmm",url.getDatabase());
assertEquals(JDBCUrl.DBType.MYSQL, url.getDBType());
url = JDBCUrl.parse("jdbc:drizzle://whoa:pass@www.drizzle.org:4427/mmm");
assertEquals("whoa",url.getUsername());
assertEquals("pass",url.getPassword());
assertEquals("www.drizzle.org",url.getHostname());
assertEquals(4427,url.getPort());
assertEquals("mmm",url.getDatabase());
assertEquals(JDBCUrl.DBType.DRIZZLE, url.getDBType());
url = JDBCUrl.parse("jdbc:mysql:thin://whoa:pass@www.drizzle.org:4427/mmm");
assertEquals("whoa",url.getUsername());
assertEquals("pass",url.getPassword());
assertEquals("www.drizzle.org",url.getHostname());
assertEquals(4427,url.getPort());
assertEquals("mmm",url.getDatabase());
assertEquals(JDBCUrl.DBType.MYSQL, url.getDBType());
url = JDBCUrl.parse("jdbc:drizzle://whoa:pass@www.drizzle.org/aa");
assertEquals("whoa",url.getUsername());
assertEquals("pass",url.getPassword());
assertEquals("www.drizzle.org",url.getHostname());
assertEquals(3306,url.getPort());
assertEquals("aa",url.getDatabase());
assertEquals(JDBCUrl.DBType.DRIZZLE, url.getDBType());
url = JDBCUrl.parse("jdbc:mysql:thin://whoa:pass@www.drizzle.org/aa");
assertEquals("whoa",url.getUsername());
assertEquals("pass",url.getPassword());
assertEquals("www.drizzle.org",url.getHostname());
assertEquals(3306,url.getPort());
assertEquals("aa",url.getDatabase());
assertEquals(JDBCUrl.DBType.MYSQL, url.getDBType());
url = JDBCUrl.parse("jdbc:drizzle://whoa:pass@www.drizzle.org/cc");
assertEquals("whoa",url.getUsername());
assertEquals("pass",url.getPassword());
assertEquals("www.drizzle.org",url.getHostname());
assertEquals(3306,url.getPort());
assertEquals("cc",url.getDatabase());
assertEquals(JDBCUrl.DBType.DRIZZLE, url.getDBType());
url = JDBCUrl.parse("jdbc:mysql:thin://whoa:pass@www.drizzle.org/cc");
assertEquals("whoa",url.getUsername());
assertEquals("pass",url.getPassword());
assertEquals("www.drizzle.org",url.getHostname());
assertEquals(3306,url.getPort());
assertEquals("cc",url.getDatabase());
assertEquals(JDBCUrl.DBType.MYSQL, url.getDBType());
url = JDBCUrl.parse("jdbc:drizzle://whoa:pass@www.drizzle.org/bbb");
assertEquals("whoa",url.getUsername());
assertEquals("pass",url.getPassword());
assertEquals("www.drizzle.org",url.getHostname());
assertEquals(3306,url.getPort());
assertEquals("bbb",url.getDatabase());
assertEquals(JDBCUrl.DBType.DRIZZLE, url.getDBType());
url = JDBCUrl.parse("jdbc:mysql:thin://whoa:pass@www.drizzle.org/bbb");
assertEquals("whoa",url.getUsername());
assertEquals("pass",url.getPassword());
assertEquals("www.drizzle.org",url.getHostname());
assertEquals(3306,url.getPort());
assertEquals("bbb",url.getDatabase());
assertEquals(JDBCUrl.DBType.MYSQL, url.getDBType());
url = JDBCUrl.parse("jdbc:drizzle://whoa:pass@www.drizzle.org/bbb/");
assertEquals("whoa",url.getUsername());
assertEquals("pass",url.getPassword());
assertEquals("www.drizzle.org",url.getHostname());
assertEquals(3306,url.getPort());
assertEquals("bbb",url.getDatabase());
assertEquals(JDBCUrl.DBType.DRIZZLE, url.getDBType());
url = JDBCUrl.parse("jdbc:mysql:thin://whoa:pass@www.drizzle.org/bbb/");
assertEquals("whoa",url.getUsername());
assertEquals("pass",url.getPassword());
assertEquals("www.drizzle.org",url.getHostname());
assertEquals(3306,url.getPort());
assertEquals("bbb",url.getDatabase());
assertEquals(JDBCUrl.DBType.MYSQL, url.getDBType());
url = JDBCUrl.parse("jdbc:mysql:thin://wh-oa:pa-ss@www.driz-zle.org/bb-b/");
assertEquals("wh-oa",url.getUsername());
assertEquals("pa-ss",url.getPassword());
assertEquals("www.driz-zle.org",url.getHostname());
assertEquals(3306,url.getPort());
assertEquals("bb-b",url.getDatabase());
assertEquals(JDBCUrl.DBType.MYSQL, url.getDBType());
}
@Test
public void testEscapes() throws SQLException {
String query = "select * from t1 where test = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setString(1,"hej\"");
ResultSet rs = stmt.executeQuery();
assertEquals(false,rs.next());
}
@Test
public void testPreparedWithNull() throws SQLException {
String query = "insert into t1 (test) values (null)";
PreparedStatement pstmt = getConnection().prepareStatement(query);
pstmt.execute();
query = "select * from t1 where test is ?";
pstmt = getConnection().prepareStatement(query);
pstmt.setNull(1,1);
ResultSet rs = pstmt.executeQuery();
assertEquals(true,rs.next());
assertEquals(null,rs.getString("test"));
assertEquals(true,rs.wasNull());
}
@Test
public void batchTest() throws SQLException {
getConnection().createStatement().executeQuery("drop table if exists test_batch");
getConnection().createStatement().executeQuery("create table test_batch (id int not null primary key auto_increment, test varchar(10))");
PreparedStatement ps = getConnection().prepareStatement("insert into test_batch values (null, ?)");
ps.setString(1, "aaa");
ps.addBatch();
ps.setString(1, "bbb");
ps.addBatch();
ps.setString(1, "ccc");
ps.addBatch();
int [] a = ps.executeBatch();
for(int c : a ) assertEquals(1,c);
ps.setString(1, "aaa");
ps.addBatch();
ps.setString(1, "bbb");
ps.addBatch();
ps.setString(1, "ccc");
ps.addBatch();
a = ps.executeBatch();
for(int c : a ) assertEquals(1,c);
ResultSet rs = getConnection().createStatement().executeQuery("select * from test_batch");
assertEquals(true,rs.next());
assertEquals("aaa",rs.getString(2));
assertEquals(true,rs.next());
assertEquals("bbb",rs.getString(2));
assertEquals(true,rs.next());
assertEquals("ccc",rs.getString(2));
// test reuse of batch parameters between addBatch calls
ps.setString(1, "ddd");
ps.addBatch();
ps.addBatch();
a = ps.executeBatch();
assertEquals(2, a.length);
for(int c : a) assertEquals(1, c);
}
@Test
public void batchTestStmt() throws SQLException {
getConnection().createStatement().executeQuery("drop table if exists test_batch2");
getConnection().createStatement().executeQuery("create table test_batch2 (id int not null primary key auto_increment, test varchar(10))");
Statement stmt = getConnection().createStatement();
stmt.addBatch("insert into test_batch2 values (null, 'hej1')");
stmt.addBatch("insert into test_batch2 values (null, 'hej2')");
stmt.addBatch("insert into test_batch2 values (null, 'hej3')");
stmt.addBatch("insert into test_batch2 values (null, 'hej4')");
stmt.executeBatch();
ResultSet rs = getConnection().createStatement().executeQuery("select * from test_batch2");
for(int i=1;i<=4;i++) {
assertEquals(true,rs.next());
assertEquals(i, rs.getInt(1));
assertEquals("hej"+i,rs.getString(2));
}
assertEquals(false,rs.next());
}
@Test
public void testChangeBatchHandler() throws SQLException {
getConnection().createStatement().executeQuery("drop table if exists test_batch3");
getConnection().createStatement().executeQuery("create table test_batch3 (id int not null primary key auto_increment, test varchar(10))");
if(getConnection().isWrapperFor(DrizzleConnection.class)) {
DrizzleConnection dc = getConnection().unwrap(DrizzleConnection.class);
dc.setBatchQueryHandlerFactory(new NoopBatchHandlerFactory());
}
PreparedStatement ps = getConnection().prepareStatement("insert into test_batch3 (test) values (?)");
PreparedStatement ps2 = getConnection().prepareStatement("insert into test_batch3 (test) values (?)");
ps.setString(1,"From nr1");
ps.addBatch();
ps2.setString(1,"From nr2");
ps2.addBatch();
ps2.setString(1,"from nr2 2");
ps.setString(1,"from nr1 2");
ps.addBatch();
ps2.addBatch();
ps2.executeBatch();
ps.executeBatch();
}
@Test
public void floatingNumbersTest() throws SQLException {
getConnection().createStatement().executeQuery("drop table if exists test_float");
getConnection().createStatement().executeQuery("create table test_float (id int not null primary key auto_increment, a float )");
PreparedStatement ps = getConnection().prepareStatement("insert into test_float (a) values (?)");
ps.setDouble(1,3.99);
ps.executeUpdate();
ResultSet rs = getConnection().createStatement().executeQuery("select a from test_float");
assertEquals(true,rs.next());
assertEquals((float)3.99, rs.getFloat(1));
assertEquals((float)3.99, rs.getFloat("a"));
assertEquals(false,rs.next());
}
@Test
public void manyColumnsTest() throws SQLException {
Statement stmt = getConnection().createStatement();
stmt.executeQuery("drop table if exists test_many_columns");
String query = "create table test_many_columns (a0 int primary key not null";
for(int i=1;i<1000;i++) {
query+=",a"+i+" int";
}
query+=")";
stmt.executeQuery(query);
query="insert into test_many_columns values (0";
for(int i=1;i<1000;i++) {
query+=","+i;
}
query+=")";
stmt.executeQuery(query);
ResultSet rs = stmt.executeQuery("select * from test_many_columns");
assertEquals(true,rs.next());
for(int i=0;i<1000;i++) {
assertEquals(rs.getInt("a"+i),i);
}
}
@Test
public void bigAutoIncTest() throws SQLException {
Statement stmt = getConnection().createStatement();
stmt.executeQuery("drop table if exists test_big_autoinc2");
stmt.executeQuery("create table test_big_autoinc2 (id int not null primary key auto_increment, test varchar(10))");
stmt.executeQuery("alter table test_big_autoinc2 auto_increment = 1000");
ResultSet rs = stmt.executeQuery("insert into test_big_autoinc2 values (null, 'hej')");
ResultSet rsGen = stmt.getGeneratedKeys();
assertEquals(true,rsGen.next());
assertEquals(1000,rsGen.getInt(1));
stmt.executeQuery("alter table test_big_autoinc2 auto_increment = "+Short.MAX_VALUE);
stmt.executeQuery("insert into test_big_autoinc2 values (null, 'hej')");
rsGen = stmt.getGeneratedKeys();
assertEquals(true,rsGen.next());
assertEquals(Short.MAX_VALUE,rsGen.getInt(1));
stmt.executeQuery("alter table test_big_autoinc2 auto_increment = "+Integer.MAX_VALUE);
stmt.executeQuery("insert into test_big_autoinc2 values (null, 'hej')");
rsGen = stmt.getGeneratedKeys();
assertEquals(true,rsGen.next());
assertEquals(Integer.MAX_VALUE,rsGen.getInt(1));
}
@Test
public void bigUpdateCountTest() throws SQLException {
Statement stmt = getConnection().createStatement();
stmt.executeQuery("drop table if exists test_big_update");
stmt.executeQuery("create table test_big_update (id int primary key not null, updateme int)");
for(int i=0;i<4000;i++) {
stmt.executeQuery("insert into test_big_update values ("+i+","+i+")");
}
ResultSet rs = stmt.executeQuery("select count(*) from test_big_update");
assertEquals(true,rs.next());
assertEquals(4000,rs.getInt(1));
int updateCount = stmt.executeUpdate("update test_big_update set updateme=updateme+1");
assertEquals(4000,updateCount);
}
//@Test
public void testBinlogDumping() throws SQLException {
assertEquals(true, getConnection().isWrapperFor(ReplicationConnection.class));
ReplicationConnection rc = getConnection().unwrap(ReplicationConnection.class);
List<RawPacket> rpList = rc.startBinlogDump(891,"mysqld-bin.000001");
for(RawPacket rp : rpList) {
for(byte b:rp.getByteBuffer().array()) {
System.out.printf("%x ",b);
}
System.out.printf("\n");
}
}
@Test
public void testCharacterStreams() throws SQLException, IOException {
getConnection().createStatement().execute("drop table if exists streamtest");
getConnection().createStatement().execute("create table streamtest (id int not null primary key, strm text)");
PreparedStatement stmt = getConnection().prepareStatement("insert into streamtest (id, strm) values (?,?)");
stmt.setInt(1,2);
String toInsert = "abcdefgh\njklmn\"";
Reader reader = new StringReader(toInsert);
stmt.setCharacterStream(2, reader);
stmt.execute();
ResultSet rs = getConnection().createStatement().executeQuery("select * from streamtest");
rs.next();
Reader rdr = rs.getCharacterStream("strm");
StringBuilder sb = new StringBuilder();
int ch;
while((ch = rdr.read()) != -1) {
sb.append((char)ch);
}
assertEquals(sb.toString(),(toInsert));
rdr = rs.getCharacterStream(2);
sb = new StringBuilder();
while((ch = rdr.read()) != -1) {
sb.append((char)ch);
}
assertEquals(sb.toString(),(toInsert));
InputStream is = rs.getAsciiStream("strm");
sb = new StringBuilder();
while((ch = is.read()) != -1) {
sb.append((char)ch);
}
assertEquals(sb.toString(),(toInsert));
is = rs.getUnicodeStream("strm");
sb = new StringBuilder();
while((ch = is.read()) != -1) {
sb.append((char)ch);
}
assertEquals(sb.toString(),(toInsert));
}
@Test
public void testCharacterStreamWithLength() throws SQLException, IOException {
getConnection().createStatement().execute("drop table if exists streamtest2");
getConnection().createStatement().execute("create table streamtest2 (id int primary key not null, strm text)");
PreparedStatement stmt = getConnection().prepareStatement("insert into streamtest2 (id, strm) values (?,?)");
stmt.setInt(1,2);
String toInsert = "abcdefgh\njklmn\"";
Reader reader = new StringReader(toInsert);
stmt.setCharacterStream(2, reader, 5);
stmt.execute();
ResultSet rs = getConnection().createStatement().executeQuery("select * from streamtest2");
rs.next();
Reader rdr = rs.getCharacterStream("strm");
StringBuilder sb = new StringBuilder();
int ch;
while((ch = rdr.read()) != -1) {
sb.append((char)ch);
}
assertEquals(sb.toString(),toInsert.substring(0,5));
}
@Test
public void testBlob() throws SQLException, IOException {
getConnection().createStatement().execute("drop table if exists blobtest");
getConnection().createStatement().execute("create table blobtest (id int not null primary key, strm blob)");
PreparedStatement stmt = getConnection().prepareStatement("insert into blobtest (id, strm) values (?,?)");
byte [] theBlob = {1,2,3,4,5,6};
InputStream stream = new ByteArrayInputStream(theBlob);
stmt.setInt(1,1);
stmt.setBlob(2,stream);
stmt.execute();
ResultSet rs = getConnection().createStatement().executeQuery("select * from blobtest");
rs.next();
InputStream readStuff = rs.getBlob("strm").getBinaryStream();
int ch;
int pos=0;
while((ch = readStuff.read())!=-1) {
assertEquals(theBlob[pos++],ch);
}
readStuff = rs.getBinaryStream("strm");
pos=0;
while((ch = readStuff.read())!=-1) {
assertEquals(theBlob[pos++],ch);
}
}
@Test
public void testBlobWithLength() throws SQLException, IOException {
getConnection().createStatement().execute("drop table if exists blobtest");
getConnection().createStatement().execute("create table blobtest (id int not null primary key, strm blob)");
PreparedStatement stmt = getConnection().prepareStatement("insert into blobtest (id, strm) values (?,?)");
byte [] theBlob = {1,2,3,4,5,6};
InputStream stream = new ByteArrayInputStream(theBlob);
stmt.setInt(1,1);
stmt.setBlob(2,stream,4);
stmt.execute();
ResultSet rs = getConnection().createStatement().executeQuery("select * from blobtest");
rs.next();
InputStream readStuff = rs.getBlob("strm").getBinaryStream();
int ch;
int pos=0;
while((ch = readStuff.read())!=-1) {
assertEquals(theBlob[pos++],ch);
}
}
@Test
public void testEmptyResultSet() throws SQLException {
getConnection().createStatement().execute("drop table if exists emptytest");
getConnection().createStatement().execute("create table emptytest (id int)");
Statement stmt = getConnection().createStatement();
assertEquals(true,stmt.execute("SELECT * FROM emptytest"));
assertEquals(false,stmt.getResultSet().next());
}
@Test
public void testLongColName() throws SQLException {
getConnection().createStatement().execute("drop table if exists longcol");
DatabaseMetaData dbmd = getConnection().getMetaData();
String str="";
for(int i =0;i<dbmd.getMaxColumnNameLength();i++) {
str+="x";
}
getConnection().createStatement().execute("create table longcol ("+str+" int not null primary key)");
getConnection().createStatement().execute("insert into longcol values (1)");
ResultSet rs = getConnection().createStatement().executeQuery("select * from longcol");
assertEquals(true,rs.next());
assertEquals(1, rs.getInt(1));
assertEquals(1,rs.getInt(str));
}
@Test(expected = SQLException.class)
public void testBadParamlist() throws SQLException {
PreparedStatement ps = getConnection().prepareStatement("insert into blah values (?)");
ps.execute();
}
@Test
public void setobjectTest() throws SQLException, IOException, ClassNotFoundException {
getConnection().createStatement().execute("drop table if exists objecttest");
getConnection().createStatement().execute(
"create table objecttest (int_test int primary key not null, string_test varchar(30), timestamp_test timestamp, serial_test blob)");
PreparedStatement ps = getConnection().prepareStatement("insert into objecttest values (?,?,?,?)");
ps.setObject(1, 5);
ps.setObject(2, "aaa");
ps.setObject(3, Timestamp.valueOf("2009-01-17 15:41:01"));
ps.setObject(4, new SerializableClass("testing",8));
ps.execute();
ResultSet rs = getConnection().createStatement().executeQuery("select * from objecttest");
assertEquals(true,rs.next());
Object theInt = rs.getObject(1);
assertTrue(theInt instanceof Long);
Object theInt2 = rs.getObject("int_test");
assertTrue(theInt2 instanceof Long);
Object theString = rs.getObject(2);
assertTrue(theString instanceof String);
Object theTimestamp = rs.getObject(3);
assertTrue(theTimestamp instanceof Timestamp);
Object theBlob = rs.getObject(4);
byte [] rawBytes = rs.getBytes(4);
ByteArrayInputStream bais = new ByteArrayInputStream(rawBytes);
ObjectInputStream ois = new ObjectInputStream(bais);
SerializableClass sc = (SerializableClass)ois.readObject();
assertEquals(sc.getVal(), "testing");
assertEquals(sc.getVal2(), 8);
rawBytes = rs.getBytes("serial_test");
bais = new ByteArrayInputStream(rawBytes);
ois = new ObjectInputStream(bais);
sc = (SerializableClass)ois.readObject();
assertEquals(sc.getVal(), "testing");
assertEquals(sc.getVal2(), 8);
}
@Test
public void binTest() throws SQLException, IOException {
getConnection().createStatement().execute("drop table if exists bintest");
getConnection().createStatement().execute(
"create table bintest (id int not null primary key auto_increment, bin1 varbinary(300), bin2 varbinary(300))");
byte [] allBytes = new byte[256];
for(int i=0;i<256;i++) {
allBytes[i]=(byte) (i&0xff);
}
ByteArrayInputStream bais = new ByteArrayInputStream(allBytes);
PreparedStatement ps = getConnection().prepareStatement("insert into bintest (bin1,bin2) values (?,?)");
ps.setBytes(1,allBytes);
ps.setBinaryStream(2, bais);
ps.execute();
ResultSet rs = getConnection().createStatement().executeQuery("select bin1,bin2 from bintest");
assertTrue(rs.next());
Blob blob = rs.getBlob(1);
InputStream is = rs.getBinaryStream(1);
for(int i=0;i<256;i++) {
int read = is.read();
assertEquals(i,read);
}
is = rs.getBinaryStream(2);
for(int i=0;i<256;i++) {
int read = is.read();
assertEquals(i,read);
}
}
@Test
public void binTest2() throws SQLException, IOException {
getConnection().createStatement().execute("drop table if exists bintest2");
if(getConnection().getMetaData().getDatabaseProductName().toLowerCase().equals("mysql")) {
getConnection().createStatement().execute(
"create table bintest2 (bin1 longblob) engine=innodb");
} else {
getConnection().createStatement().execute(
"create table bintest2 (id int not null primary key auto_increment, bin1 blob)");
}
byte [] buf=new byte[1000000];
for(int i=0;i<1000000;i++) {
buf[i]=(byte)i;
}
InputStream is = new ByteArrayInputStream(buf);
PreparedStatement ps = getConnection().prepareStatement("insert into bintest2 (bin1) values (?)");
ps.setBinaryStream(1, is);
ps.execute();
ps = getConnection().prepareStatement("insert into bintest2 (bin1) values (?)");
is = new ByteArrayInputStream(buf);
ps.setBinaryStream(1, is);
ps.execute();
ResultSet rs = getConnection().createStatement().executeQuery("select bin1 from bintest2");
assertEquals(true,rs.next());
byte [] buf2 = rs.getBytes(1);
for(int i=0;i<1000000;i++) {
assertEquals((byte)i,buf2[i]);
}
assertEquals(true,rs.next());
buf2 = rs.getBytes(1);
for(int i=0;i<1000000;i++) {
assertEquals((byte)i,buf2[i]);
}
assertEquals(false,rs.next());
}
@Test(expected=SQLIntegrityConstraintViolationException.class)
public void testException1() throws SQLException {
getConnection().createStatement().execute("drop table if exists extest");
getConnection().createStatement().execute(
"create table extest (id int not null primary key)");
getConnection().createStatement().execute("insert into extest values (1)");
getConnection().createStatement().execute("insert into extest values (1)");
}
@Test
public void testExceptionDivByZero() throws SQLException {
if(getConnection().getMetaData().getDatabaseProductName().toLowerCase().equals("drizzle")) {
boolean threwException = false;
try{
ResultSet rs = getConnection().createStatement().executeQuery("select 1/0");
} catch(SQLException e) {
threwException = true;
}
assertEquals(true,threwException);
} else {
ResultSet rs = getConnection().createStatement().executeQuery("select 1/0");
assertEquals(rs.next(),true);
assertEquals(null, rs.getString(1));
}
}
@Test(expected = SQLSyntaxErrorException.class)
public void testSyntaxError() throws SQLException {
getConnection().createStatement().executeQuery("create asdf b");
}
@Test
public void testRewriteBatchHandler() throws SQLException {
getConnection().createStatement().execute("drop table if exists rewritetest");
getConnection().createStatement().execute(
"create table rewritetest (id int not null primary key, a varchar(10), b int) engine=innodb");
if(getConnection().isWrapperFor(DrizzleConnection.class)) {
DrizzleConnection dc = getConnection().unwrap(DrizzleConnection.class);
dc.setBatchQueryHandlerFactory(new RewriteParameterizedBatchHandlerFactory());
}
PreparedStatement ps = getConnection().prepareStatement("insert into rewritetest values (?,?,?)");
for(int i = 0;i<10000;i++) {
ps.setInt(1,i);
ps.setString(2,"bbb"+i);
ps.setInt(3,30+i);
ps.addBatch();
}
ps.executeBatch();
ResultSet rs = getConnection().createStatement().executeQuery("select * from rewritetest");
int i = 0;
while(rs.next()) {
assertEquals(i++, rs.getInt("id"));
}
assertEquals(10000,i);
}
@Test
public void testRewriteBatchHandlerWithDupKey() throws SQLException {
getConnection().createStatement().execute("drop table if exists rewritetest2");
getConnection().createStatement().execute(
"create table rewritetest2 (id int not null primary key, a varchar(10), b int) engine=innodb");
if(getConnection().isWrapperFor(DrizzleConnection.class)) {
DrizzleConnection dc = getConnection().unwrap(DrizzleConnection.class);
dc.setBatchQueryHandlerFactory(new RewriteParameterizedBatchHandlerFactory());
}
long startTime = System.currentTimeMillis();
PreparedStatement ps = getConnection().prepareStatement("insert into rewritetest2 values (?,?,?) on duplicate key update a=values(a)");
for(int i = 0;i<10000;i++) {
ps.setInt(1,0);
ps.setString(2,"bbb"+i);
ps.setInt(3,30+i);
ps.addBatch();
}
ps.executeBatch();
System.out.println("time: "+(System.currentTimeMillis() - startTime));
ResultSet rs = getConnection().createStatement().executeQuery("select * from rewritetest2");
int i = 0;
while(rs.next()) {
assertEquals(i++, rs.getInt("id"));
}
assertEquals(1,i);
}
@Test
public void testStripQueryWithComments() {
String q = "select 'some query without comments'";
String expectedQ = q;
assertEquals(q, Utils.stripQuery(q));
q = "select 1 /*this should be removed*/ from b";
expectedQ = "select 1 from b";
assertEquals(expectedQ,Utils.stripQuery(q));
q = "select 1 /*this should be # removed*/ from b# crap";
expectedQ = "select 1 from b";
assertEquals(expectedQ,Utils.stripQuery(q));
q = "select \"1 /*this should not be # removed*/\" from b# crap";
expectedQ = "select \"1 /*this should not be # removed*/\" from b";
assertEquals(expectedQ,Utils.stripQuery(q));
q = "/**/select \"1 /*this should not be # removed*/\" from b# crap/**/";
expectedQ = "select \"1 /*this should not be # removed*/\" from b";
assertEquals(expectedQ,Utils.stripQuery(q));
q = "/**/select '1 /*this should not be # removed*/' from b# crap/**/";
expectedQ = "select '1 /*this should not be # removed*/' from b";
assertEquals(expectedQ,Utils.stripQuery(q));
}
@Test
public void testPreparedStatementsWithComments() throws SQLException {
getConnection().createStatement().execute("drop table if exists commentPreparedStatements");
getConnection().createStatement().execute(
"create table commentPreparedStatements (id int not null primary key auto_increment, a varchar(10))");
String query = "INSERT INTO commentPreparedStatements (a) VALUES (?) # ?";
PreparedStatement pstmt = getConnection().prepareStatement(query);
pstmt.setString(1,"yeah");
pstmt.execute();
}
@Test
public void testPreparedStatementsWithQuotes() throws SQLException {
getConnection().createStatement().execute("drop table if exists quotesPreparedStatements");
getConnection().createStatement().execute(
"create table quotesPreparedStatements (id int not null primary key auto_increment, a varchar(10))");
String query = "INSERT INTO quotesPreparedStatements (a) VALUES (\"hellooo?\") # ?";
PreparedStatement pstmt = getConnection().prepareStatement(query);
pstmt.execute();
}
@Test
public void testCountChars() {
assertEquals(1, Utils.countChars("?",'?'));
assertEquals(2, Utils.countChars("??",'?'));
assertEquals(1, Utils.countChars("?'?'",'?'));
assertEquals(1, Utils.countChars("?\"?\"",'?'));
}
@Test
public void bigDecimalTest() throws SQLException {
BigDecimal bd = BigDecimal.TEN;
getConnection().createStatement().execute("drop table if exists bigdectest");
getConnection().createStatement().execute(
"create table bigdectest (id int not null primary key auto_increment, bd decimal) engine=innodb");
PreparedStatement ps = getConnection().prepareStatement("insert into bigdectest (bd) values (?)");
ps.setBigDecimal(1,bd);
ps.executeQuery();
ResultSet rs=getConnection().createStatement().executeQuery("select bd from bigdectest");
assertTrue(rs.next());
Object bb = rs.getObject(1);
assertEquals(bd, bb);
BigDecimal bigD = rs.getBigDecimal(1);
BigDecimal bigD2 = rs.getBigDecimal("bd");
assertEquals(bd,bigD);
assertEquals(bd,bigD2);
bigD = rs.getBigDecimal("bd");
assertEquals(bd,bigD);
}
@Test
public void byteTest() throws SQLException {
getConnection().createStatement().execute("drop table if exists bytetest");
getConnection().createStatement().execute(
"create table bytetest (id int not null primary key auto_increment, a int) engine=innodb");
PreparedStatement ps = getConnection().prepareStatement("insert into bytetest (a) values (?)");
ps.setByte(1,Byte.MAX_VALUE);
ps.execute();
ResultSet rs=getConnection().createStatement().executeQuery("select a from bytetest");
assertTrue(rs.next());
Byte bc = rs.getByte(1);
Byte bc2 = rs.getByte("a");
assertTrue(Byte.MAX_VALUE == bc);
assertEquals(bc2, bc);
}
@Test
public void shortTest() throws SQLException {
getConnection().createStatement().execute("drop table if exists shorttest");
getConnection().createStatement().execute(
"create table shorttest (id int not null primary key auto_increment,a int) engine=innodb");
PreparedStatement ps = getConnection().prepareStatement("insert into shorttest (a) values (?)");
ps.setShort(1,Short.MAX_VALUE);
ps.execute();
ResultSet rs=getConnection().createStatement().executeQuery("select a from shorttest");
assertTrue(rs.next());
Short bc = rs.getShort(1);
Short bc2 = rs.getShort("a");
assertTrue(Short.MAX_VALUE == bc);
assertEquals(bc2, bc);
}
@Test
public void doubleTest() throws SQLException {
getConnection().createStatement().execute("drop table if exists doubletest");
getConnection().createStatement().execute(
"create table doubletest (id int not null primary key auto_increment,a double) engine=innodb");
PreparedStatement ps = getConnection().prepareStatement("insert into doubletest (a) values (?)");
double d = 1.5;
ps.setDouble(1,d);
ps.execute();
ResultSet rs=getConnection().createStatement().executeQuery("select a from doubletest");
assertTrue(rs.next());
Object b = rs.getObject(1);
assertEquals(b.getClass(),Double.class);
Double bc = rs.getDouble(1);
Double bc2 = rs.getDouble("a");
assertTrue(d == bc);
assertEquals(bc2, bc);
}
@Test
public void testResultSetPositions() throws SQLException {
getConnection().createStatement().execute("drop table if exists ressetpos");
getConnection().createStatement().execute(
"create table ressetpos (i int not null primary key) engine=innodb");
getConnection().createStatement().execute("insert into ressetpos values (1),(2),(3),(4)");
ResultSet rs =getConnection().createStatement().executeQuery("select * from ressetpos");
assertTrue(rs.isBeforeFirst());
rs.next();
assertTrue(!rs.isBeforeFirst());
assertTrue(rs.isFirst());
rs.beforeFirst();
assertTrue(rs.isBeforeFirst());
while(rs.next());
assertTrue(rs.isAfterLast());
rs.absolute(4);
assertTrue(!rs.isAfterLast());
rs.absolute(2);
assertEquals(2,rs.getInt(1));
rs.relative(2);
assertEquals(4,rs.getInt(1));
assertTrue(!rs.next());
rs.previous();
assertEquals(4,rs.getInt(1));
rs.relative(-3);
assertEquals(1,rs.getInt(1));
assertEquals(false,rs.relative(-1));
assertEquals(1,rs.getInt(1));
rs.last();
assertEquals(4,rs.getInt(1));
assertEquals(4,rs.getRow());
assertTrue(rs.isLast());
rs.first();
assertEquals(1,rs.getInt(1));
assertEquals(1,rs.getRow());
rs.absolute(-1);
assertEquals(4,rs.getRow());
assertEquals(4,rs.getInt(1));
}
@Test(expected = SQLException.class)
public void findColumnTest() throws SQLException {
ResultSet rs = getConnection().createStatement().executeQuery("select 1 as 'hej'");
assertEquals(1,rs.findColumn("hej"));
rs.findColumn("nope");
}
@Test
public void getStatementTest() throws SQLException {
ResultSet rs = getConnection().createStatement().executeQuery("select 1 as 'hej'");
Statement stmt = rs.getStatement();
}
@Test
public void getUrlTest() throws SQLException {
ResultSet rs = getConnection().createStatement().executeQuery("select 'http://drizzle.org' as url");
rs.next();
URL url = rs.getURL(1);
assertEquals("http://drizzle.org",url.toString());
url = rs.getURL("url");
assertEquals("http://drizzle.org",url.toString());
}
@Test(expected = SQLException.class)
public void getUrlFailTest() throws SQLException {
ResultSet rs = getConnection().createStatement().executeQuery("select 'asdf' as url");
rs.next();
URL url = rs.getURL(1);
}
@Test(expected = SQLException.class)
public void getUrlFailTest2() throws SQLException {
ResultSet rs = getConnection().createStatement().executeQuery("select 'asdf' as url");
rs.next();
URL url = rs.getURL("url");
}
@Test
public void setNull() throws SQLException {
PreparedStatement ps = getConnection().prepareStatement("insert blabla (?)");
ps.setString(1,null);
}
@Test
public void testBug501452() throws SQLException {
Connection conn = getConnection();
if(conn.isWrapperFor(DrizzleConnection.class)) {
DrizzleConnection dc = conn.unwrap(DrizzleConnection.class);
dc.setBatchQueryHandlerFactory(new RewriteParameterizedBatchHandlerFactory());
}
Statement stmt = conn.createStatement();
stmt.executeUpdate("drop table if exists test_units_jdbc.bug501452");
stmt.executeUpdate("CREATE TABLE test_units_jdbc.bug501452 (id int not null primary key, value varchar(20))");
stmt.close();
PreparedStatement ps=conn.prepareStatement("insert into bug501452 (id,value) values (?,?)");
ps.setObject(1, 1);
ps.setObject(2, "value for 1");
ps.addBatch();
ps.executeBatch();
ps.setObject(1, 2);
ps.setObject(2, "value for 2");
ps.addBatch();
ps.executeBatch();
connection.commit();
}
@Test
public void testBug525946() throws SQLException {
Connection conn = getConnection();
assertTrue(conn.getAutoCommit());
conn.setAutoCommit(false);
assertFalse(conn.getAutoCommit());
}
@Test
public void testUpdateCount() throws SQLException {
Connection conn = getConnection();
Statement stmt = conn.createStatement();
stmt.execute("select 1") ;
System.out.println(stmt.getUpdateCount());
}
@Test
public void testSetObject() throws SQLException {
Connection conn = getConnection();
Statement stmt = conn.createStatement();
stmt.executeUpdate("drop table if exists test_units_jdbc.test_setobjectconv");
stmt.executeUpdate("CREATE TABLE test_units_jdbc.test_setobjectconv (id int not null primary key auto_increment, v1 varchar(40), v2 varchar(40))");
stmt.close();
PreparedStatement ps = conn.prepareStatement("insert into test_setobjectconv values (null, ?, ?)");
ps.setObject(1,"2009-01-01 00:00:00", Types.TIMESTAMP);
ps.setObject(2, "33", Types.DOUBLE);
ps.execute();
}
@Test
public void testBit() throws SQLException {
Connection conn = getConnection();
conn.createStatement().execute("drop table if exists bittest");
conn.createStatement().execute("create table bittest(id int not null primary key auto_increment, b int)");
PreparedStatement stmt = conn.prepareStatement("insert into bittest values(null, ?)");
stmt.setBoolean(1, true);
stmt.execute();
stmt.setBoolean(1, false);
stmt.execute();
ResultSet rs = conn.createStatement().executeQuery("select * from bittest");
Assert.assertTrue(rs.next());
Assert.assertTrue(rs.getBoolean("b"));
Assert.assertTrue(rs.next());
assertFalse(rs.getBoolean("b"));
assertFalse(rs.next());
}
@Test
public void testConnectWithDB() throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:mysql:thin://"+host+":3306/");
try {
conn.createStatement().executeUpdate("drop database test_units_jdbc_testdrop");
} catch (Exception e) {}
conn = DriverManager.getConnection("jdbc:mysql:thin://"+host+":3306/test_units_jdbc_testdrop?createDB=true");
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getSchemas();
boolean foundDb = false;
while(rs.next()) {
if(rs.getString("table_schem").equals("test_units_jdbc_testdrop")) foundDb = true;
}
assertTrue(foundDb);
}
@Test
public void testGithubIssue6() throws SQLException {
Connection conn = getConnection();
conn.createStatement().execute("drop table if exists github_issue6");
conn.createStatement().execute("drop table if exists github_issue6_2");
conn.createStatement().execute("create table github_issue6 (id int not null primary key auto_increment, c int)");
conn.createStatement().execute("create table github_issue6_2 (id int not null primary key auto_increment, c int)");
conn.createStatement().execute("insert into github_issue6 values (null, 100)");
conn.createStatement().execute("insert into github_issue6_2 values (null, 200)");
ResultSet rs = conn.createStatement().executeQuery("select * from github_issue6 inner join github_issue6_2 on github_issue6.id = github_issue6_2.id");
while (rs.next()) {
assertEquals(rs.getString("github_issue6.c"), "100");
assertEquals(rs.getString("github_issue6_2.c"), "200");
}
}
} | bsd-3-clause |
diox/olympia | src/olympia/files/admin.py | 1815 | from django.contrib import admin
from django.utils.html import format_html
from .models import File
@admin.register(File)
class FileAdmin(admin.ModelAdmin):
view_on_site = False
raw_id_fields = ('version',)
list_display = ('__str__', 'addon_slug', 'addon_guid')
search_fields = (
'^version__addon__guid',
'^version__addon__slug',
)
list_select_related = ('version__addon',)
readonly_fields = (
'id',
'created',
'file_download_url',
)
fieldsets = (
(
None,
{
'fields': (
'id',
'created',
'version',
'filename',
'size',
'hash',
'original_hash',
'status',
'file_download_url',
'manifest_version',
)
},
),
(
'Details',
{
'fields': ('cert_serial_num', 'original_status'),
},
),
(
'Flags',
{
'fields': (
'strict_compatibility',
'is_signed',
'is_experiment',
'is_mozilla_signed_extension',
)
},
),
)
def addon_slug(self, instance):
return instance.addon.slug
def addon_guid(self, instance):
return instance.addon.guid
def file_download_url(self, instance):
return format_html(
'<a href="{}">Download file</a>', instance.get_absolute_url(attachment=True)
)
file_download_url.short_description = 'Download this file'
file_download_url.allow_tags = True
| bsd-3-clause |
AlloVince/eva-engine | module/User/src/User/Api/Controller/RoleController.php | 553 | <?php
namespace User\Api\Controller;
use Eva\Api,
Eva\Mvc\Controller\ActionController;
class RoleController extends ActionController
{
public function multicheckboxAction($params = null)
{
$model = Api::_()->getModel('User\Model\Role');
$items = $model->getRoleList();
$valueOptions = array();
foreach($items as $item){
$valueOptions[] = array(
'label' => $item['roleName'],
'value' => $item['id'],
);
}
return $valueOptions;
}
}
| bsd-3-clause |
arrayfire/arrayfire-rust | src/core/defines.rs | 18798 | use num::Complex;
use std::fmt::Error as FmtError;
use std::fmt::{Display, Formatter};
#[cfg(feature = "afserde")]
use serde::{Deserialize, Serialize};
/// Error codes
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum AfError {
/// The function returned successfully
SUCCESS = 0,
// 100-199 Errors in environment
/// The system or device ran out of memory
ERR_NO_MEM = 101,
/// There was an error in the device driver
ERR_DRIVER = 102,
/// There was an error with the runtime environment
ERR_RUNTIME = 103,
// 200-299 Errors in input parameters
/// The input array is not a valid Array object
ERR_INVALID_ARRAY = 201,
/// One of the function arguments is incorrect
ERR_ARG = 202,
/// The size is incorrect
ERR_SIZE = 203,
/// The type is not suppported by this function
ERR_TYPE = 204,
/// The type of the input arrays are not compatible
ERR_DIFF_TYPE = 205,
/// Function does not support GFOR / batch mode
ERR_BATCH = 207,
/// Input does not belong to the current device
ERR_DEVICE = 208,
// 300-399 Errors for missing software features
/// The option is not supported
ERR_NOT_SUPPORTED = 301,
/// This build of ArrayFire does not support this feature
ERR_NOT_CONFIGURED = 302,
// 400-499 Errors for missing hardware features
/// This device does not support double
ERR_NO_DBL = 401,
/// This build of ArrayFire was not built with graphics or this device does
/// not support graphics
ERR_NO_GFX = 402,
// 900-999 Errors from upstream libraries and runtimes
/// There was an internal error either in ArrayFire or in a project
/// upstream
ERR_INTERNAL = 998,
/// Unknown Error
ERR_UNKNOWN = 999,
}
/// Compute/Acceleration Backend
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum Backend {
/// Default backend order: CUDA -> OpenCL -> CPU
DEFAULT = 0,
/// CPU a.k.a sequential algorithms
CPU = 1,
/// CUDA Compute Backend
CUDA = 2,
/// OpenCL Compute Backend
OPENCL = 4,
}
impl Display for Backend {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
let text = match *self {
Backend::OPENCL => "OpenCL",
Backend::CUDA => "Cuda",
Backend::CPU => "CPU",
Backend::DEFAULT => "Default",
};
write!(f, "{}", text)
}
}
impl Display for AfError {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
let text = match *self {
AfError::SUCCESS => "Function returned successfully",
AfError::ERR_NO_MEM => "System or Device ran out of memory",
AfError::ERR_DRIVER => "Error in the device driver",
AfError::ERR_RUNTIME => "Error with the runtime environment",
AfError::ERR_INVALID_ARRAY => "Iput Array is not a valid object",
AfError::ERR_ARG => "One of the function arguments is incorrect",
AfError::ERR_SIZE => "Size is incorrect",
AfError::ERR_TYPE => "Type is not suppported by this function",
AfError::ERR_DIFF_TYPE => "Type of the input arrays are not compatible",
AfError::ERR_BATCH => "Function does not support GFOR / batch mode",
AfError::ERR_DEVICE => "Input does not belong to the current device",
AfError::ERR_NOT_SUPPORTED => "Unsupported operation/parameter option",
AfError::ERR_NOT_CONFIGURED => "This build of ArrayFire does not support this feature",
AfError::ERR_NO_DBL => "This device does not support double",
AfError::ERR_NO_GFX => "This build of ArrayFire has no graphics support",
AfError::ERR_INTERNAL => "Error either in ArrayFire or in a project upstream",
AfError::ERR_UNKNOWN => "Unknown Error",
};
write!(f, "{}", text)
}
}
/// Types of Array data type
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum DType {
/// 32 bit float
F32 = 0,
/// 32 bit complex float
C32 = 1,
/// 64 bit float
F64 = 2,
/// 64 bit complex float
C64 = 3,
/// 8 bit boolean
B8 = 4,
/// 32 bit signed integer
S32 = 5,
/// 32 bit unsigned integer
U32 = 6,
/// 8 bit unsigned integer
U8 = 7,
/// 64 bit signed integer
S64 = 8,
/// 64 bit unsigned integer
U64 = 9,
/// 16 bit signed integer
S16 = 10,
/// 16 bit unsigned integer
U16 = 11,
/// 16 bit floating point
F16 = 12,
}
/// Dictates the interpolation method to be used by a function
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum InterpType {
/// Nearest Neighbor interpolation method
NEAREST = 0,
/// Linear interpolation method
LINEAR = 1,
/// Bilinear interpolation method
BILINEAR = 2,
/// Cubic interpolation method
CUBIC = 3,
/// Floor indexed
LOWER = 4,
/// Linear interpolation with cosine smoothing
LINEAR_COSINE = 5,
/// Bilinear interpolation with cosine smoothing
BILINEAR_COSINE = 6,
/// Bicubic interpolation
BICUBIC = 7,
/// Cubic interpolation with Catmull-Rom splines
CUBIC_SPLINE = 8,
/// Bicubic interpolation with Catmull-Rom splines
BICUBIC_SPLINE = 9,
}
/// Helps determine how to pad kernels along borders
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum BorderType {
/// Pad using zeros
ZERO = 0,
/// Pad using mirrored values along border
SYMMETRIC = 1,
/// Out of bound values are clamped to the edge
CLAMP_TO_EDGE,
/// Out of bound values are mapped to range of the dimension in cyclic fashion
PERIODIC,
}
/// Used by `regions` function to identify type of connectivity
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum Connectivity {
/// North-East-South-West (N-E-S-W) connectivity from given pixel/point
FOUR = 4,
/// N-NE-E-SE-S-SW-W-NW connectivity from given pixel/point
EIGHT = 8,
}
/// Helps determine the size of output of convolution
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum ConvMode {
/// Default convolution mode where output size is same as input size
DEFAULT = 0,
/// Output of convolution is expanded based on signal and filter sizes
EXPAND = 1,
}
/// Helps determine if convolution is in Spatial or Frequency domain
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum ConvDomain {
/// ArrayFire chooses whether the convolution will be in spatial domain or frequency domain
AUTO = 0,
/// Convoltion in spatial domain
SPATIAL = 1,
/// Convolution in frequency domain
FREQUENCY = 2,
}
/// Error metric used by `matchTemplate` function
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum MatchType {
/// Sum of Absolute Differences
SAD = 0,
/// Zero-mean Sum of Absolute Differences
ZSAD = 1,
/// Locally scaled Sum of Absolute Differences
LSAD = 2,
/// Sum of Squared Differences
SSD = 3,
/// Zero-mean Sum of Squared Differences
ZSSD = 4,
/// Localy scaled Sum of Squared Differences
LSSD = 5,
/// Normalized Cross Correlation
NCC = 6,
/// Zero-mean Normalized Cross Correlation
ZNCC = 7,
/// Sum of Hamming Distances
SHD = 8,
}
/// Identify the color space of given image(Array)
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum ColorSpace {
/// Grayscale color space
GRAY = 0,
/// Red-Green-Blue color space
RGB = 1,
/// Hue-Saturation-value color space
HSV = 2,
}
/// Helps determine the type of a Matrix
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum MatProp {
/// Default (no-op)
NONE = 0,
/// Data needs to be transposed
TRANS = 1,
/// Data needs to be conjugate transposed
CTRANS = 2,
/// Matrix is upper triangular
CONJ = 4,
/// Matrix needs to be conjugate
UPPER = 32,
/// Matrix is lower triangular
LOWER = 64,
/// Matrix diagonal has unitary values
DIAGUNIT = 128,
/// Matrix is symmetric
SYM = 512,
/// Matrix is positive definite
POSDEF = 1024,
/// Matrix is orthogonal
ORTHOG = 2048,
/// Matrix is tri-diagonal
TRIDIAG = 4096,
/// Matrix is block-diagonal
BLOCKDIAG = 8192,
}
/// Norm type
#[allow(non_camel_case_types)]
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum NormType {
/// Treats input as a vector and return sum of absolute values
VECTOR_1 = 0,
/// Treats input as vector and return max of absolute values
VECTOR_INF = 1,
/// Treats input as vector and returns euclidean norm
VECTOR_2 = 2,
/// Treats input as vector and returns the p-norm
VECTOR_P = 3,
/// Return the max of column sums
MATRIX_1 = 4,
/// Return the max of row sums
MATRIX_INF = 5,
/// Returns the max singular value (Currently not supported)
MATRIX_2 = 6,
/// Returns Lpq-norm
MATRIX_L_PQ = 7,
}
/// Dictates what color map is used for Image rendering
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum ColorMap {
/// Default color map is grayscale range [0-1]
DEFAULT = 0,
/// Visible spectrum color map
SPECTRUM = 1,
/// Colors
COLORS = 2,
/// Red hue map
RED = 3,
/// Mood color map
MOOD = 4,
/// Heat color map
HEAT = 5,
/// Blue hue map
BLUE = 6,
}
/// YCbCr Standards
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum YCCStd {
/// ITU-R BT.601 (formerly CCIR 601) standard
YCC_601 = 601,
/// ITU-R BT.709 standard
YCC_709 = 709,
/// ITU-R BT.2020 standard
YCC_2020 = 2020,
}
/// Homography type
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum HomographyType {
/// RANdom SAmple Consensus algorithm
RANSAC = 0,
/// Least Median of Squares
LMEDS = 1,
}
/// Plotting markers
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum MarkerType {
/// No marker
NONE = 0,
/// Pointer marker
POINT = 1,
/// Hollow circle marker
CIRCLE = 2,
/// Hollow Square marker
SQUARE = 3,
/// Hollow Triangle marker
TRIANGLE = 4,
/// Cross-hair marker
CROSS = 5,
/// Plus symbol marker
PLUS = 6,
/// Start symbol marker
STAR = 7,
}
/// Image moment types
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum MomentType {
/// Central moment of order (0 + 0)
M00 = 1, // 1<<0
/// Central moment of order (0 + 1)
M01 = 2, // 1<<1
/// Central moment of order (1 + 0)
M10 = 4, // 1<<2
/// Central moment of order (1 + 1)
M11 = 8, // 1<<3
/// All central moments of order (0,0), (0,1), (1,0) and (1,1)
FIRST_ORDER = 1 | 1 << 1 | 1 << 2 | 1 << 3,
}
/// Sparse storage format type
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum SparseFormat {
/// Dense format
DENSE = 0,
/// Compressed sparse row format
CSR = 1,
/// Compressed sparse coloumn format
CSC = 2,
/// Coordinate list (row, coloumn, value) tuples.
COO = 3,
}
/// Binary operation types for generalized scan functions
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum BinaryOp {
/// Addition operation
ADD = 0,
/// Multiplication operation
MUL = 1,
/// Minimum operation
MIN = 2,
/// Maximum operation
MAX = 3,
}
/// Random engine types
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum RandomEngineType {
///Philox variant with N=4, W=32 and Rounds=10
PHILOX_4X32_10 = 100,
///Threefry variant with N=2, W=32 and Rounds=16
THREEFRY_2X32_16 = 200,
///Mersenne variant with MEXP = 11213
MERSENNE_GP11213 = 300,
}
/// Default Philon RandomEngine that points to [PHILOX_4X32_10](./enum.RandomEngineType.html)
pub const PHILOX: RandomEngineType = RandomEngineType::PHILOX_4X32_10;
/// Default Threefry RandomEngine that points to [THREEFRY_2X32_16](./enum.RandomEngineType.html)
pub const THREEFRY: RandomEngineType = RandomEngineType::THREEFRY_2X32_16;
/// Default Mersenne RandomEngine that points to [MERSENNE_GP11213](./enum.RandomEngineType.html)
pub const MERSENNE: RandomEngineType = RandomEngineType::MERSENNE_GP11213;
/// Default RandomEngine that defaults to [PHILOX](./constant.PHILOX.html)
pub const DEFAULT_RANDOM_ENGINE: RandomEngineType = PHILOX;
#[cfg(feature = "afserde")]
#[derive(Serialize, Deserialize)]
#[serde(remote = "Complex")]
struct ComplexDef<T> {
re: T,
im: T,
}
/// Scalar value types
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum Scalar {
/// 32 bit float
F32(f32),
/// 32 bit complex float
#[cfg_attr(feature = "afserde", serde(with = "ComplexDef"))]
C32(Complex<f32>),
/// 64 bit float
F64(f64),
/// 64 bit complex float
#[cfg_attr(feature = "afserde", serde(with = "ComplexDef"))]
C64(Complex<f64>),
/// 8 bit boolean
B8(bool),
/// 32 bit signed integer
S32(i32),
/// 32 bit unsigned integer
U32(u32),
/// 8 bit unsigned integer
U8(u8),
/// 64 bit signed integer
S64(i64),
/// 64 bit unsigned integer
U64(u64),
/// 16 bit signed integer
S16(i16),
/// 16 bit unsigned integer
U16(u16),
}
/// Canny edge detector threshold operations types
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum CannyThresholdType {
/// User has to define canny thresholds manually
MANUAL = 0,
/// Determine canny algorithm high threshold using Otsu algorithm automatically
OTSU = 1,
}
/// Anisotropic diffusion flux equation types
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum DiffusionEq {
/// Quadratic flux function
QUADRATIC = 1,
/// Exponential flux function
EXPONENTIAL = 2,
/// Default flux function, a.k.a exponential
DEFAULT = 0,
}
/// Diffusion equation types
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum FluxFn {
/// Quadratic flux function
GRADIENT = 1,
/// Modified curvature diffusion equation
MCDE = 2,
/// Default diffusion method, Gradient
DEFAULT = 0,
}
/// topk function ordering
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum TopkFn {
/// Top k min values
MIN = 1,
/// Top k max values
MAX = 2,
/// Default option(max)
DEFAULT = 0,
}
/// Iterative Deconvolution Algorithm
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum IterativeDeconvAlgo {
/// Land-Weber Algorithm
LANDWEBER = 1,
/// Richardson-Lucy Algorithm
RICHARDSONLUCY = 2,
/// Default is Land-Weber algorithm
DEFAULT = 0,
}
/// Inverse Deconvolution Algorithm
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum InverseDeconvAlgo {
/// Tikhonov algorithm
TIKHONOV = 1,
/// Default is Tikhonov algorithm
DEFAULT = 0,
}
/// Gradient mode for convolution
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum ConvGradientType {
/// Filter Gradient
FILTER = 1,
/// Data Gradient
DATA = 2,
/// Biased Gradient
BIAS = 3,
/// Default is Data Gradient
DEFAULT = 0,
}
/// Gradient mode for convolution
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum VarianceBias {
/// Sample variance
SAMPLE = 1,
/// Population variance
POPULATION = 2,
/// Default (Population) variance
DEFAULT = 0,
}
/// Gradient mode for convolution
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
pub enum CublasMathMode {
/// To indicate use of Tensor Cores on CUDA capable GPUs
TENSOR_OP = 1,
/// Default i.e. tensor core operations will be avoided by the library
DEFAULT = 0,
}
#[cfg(test)]
mod tests {
#[cfg(feature = "afserde")]
mod serde_tests {
#[test]
fn test_enum_serde() {
use super::super::AfError;
let err_code = AfError::ERR_NO_MEM;
let serd = match serde_json::to_string(&err_code) {
Ok(serialized_str) => serialized_str,
Err(e) => e.to_string(),
};
assert_eq!(serd, "\"ERR_NO_MEM\"");
let deserd: AfError = serde_json::from_str(&serd).unwrap();
assert_eq!(deserd, AfError::ERR_NO_MEM);
}
#[test]
fn test_scalar_serde() {
use super::super::Scalar;
use num::Complex;
let scalar = Scalar::C32(Complex {
re: 1.0f32,
im: 1.0f32,
});
let serd = match serde_json::to_string(&scalar) {
Ok(serialized_str) => serialized_str,
Err(e) => e.to_string(),
};
let deserd: Scalar = serde_json::from_str(&serd).unwrap();
assert_eq!(deserd, scalar);
}
}
}
| bsd-3-clause |
JonathanLogan/mute | msgdb/messages.go | 6733 | // Copyright (c) 2015 Mute Communications Ltd.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package msgdb
import (
"database/sql"
"strings"
"github.com/mutecomm/mute/log"
"github.com/mutecomm/mute/uid/identity"
)
// AddMessage adds message between selfID and peerID to msgDB. If sent is
// true, it is a sent message. Otherwise a received message.
func (msgDB *MsgDB) AddMessage(
selfID, peerID string,
date int64,
sent bool,
message string,
sign bool,
minDelay, maxDelay int32,
) error {
if err := identity.IsMapped(selfID); err != nil {
return log.Error(err)
}
if err := identity.IsMapped(peerID); err != nil {
return log.Error(err)
}
// get self
var self int64
if err := msgDB.getNymUIDQuery.QueryRow(selfID).Scan(&self); err != nil {
return log.Error(err)
}
// get peer
var peer int64
err := msgDB.getContactUIDQuery.QueryRow(self, peerID).Scan(&peer)
if err != nil {
return log.Error(err)
}
// add message
var d int64
if sent {
d = 1
}
var s int64
if sign {
s = 1
}
var from string
var to string
if sent {
from = selfID
to = peerID
} else {
from = peerID
to = selfID
}
parts := strings.SplitN(message, "\n", 2)
subject := parts[0]
_, err = msgDB.addMsgQuery.Exec(self, peer, d, d, 0, from, to, date,
subject, message, s, minDelay, maxDelay)
if err != nil {
return log.Error(err)
}
return nil
}
// GetMessage returns the message from user myID with the given msgNum.
func (msgDB *MsgDB) GetMessage(
myID string,
msgNum int64,
) (from, to, msg string, date int64, err error) {
if err := identity.IsMapped(myID); err != nil {
return "", "", "", 0, log.Error(err)
}
var (
self int64
peer int64
direction int64
)
err = msgDB.getMsgQuery.QueryRow(msgNum).Scan(&self, &peer, &direction,
&date, &msg)
if err != nil {
return "", "", "", 0, err
}
var selfID string
err = msgDB.getNymMappedQuery.QueryRow(self).Scan(&selfID)
if err != nil {
return "", "", "", 0, log.Error(err)
}
if myID != selfID {
return "", "", "", 0, log.Error("msgdb: unknown message")
}
var peerID string
err = msgDB.getContactMappedQuery.QueryRow(self, peer).Scan(&peerID)
if err != nil {
return "", "", "", 0, log.Error(err)
}
if direction == 1 {
unmappedID, fullName, err := msgDB.GetNym(selfID)
if err != nil {
return "", "", "", 0, err
}
if fullName == "" {
from = unmappedID
} else {
from = fullName + " <" + unmappedID + ">"
}
unmappedID, fullName, _, err = msgDB.GetContact(selfID, peerID)
if err != nil {
return "", "", "", 0, err
}
if fullName == "" {
to = unmappedID
} else {
to = fullName + " <" + unmappedID + ">"
}
} else {
unmappedID, fullName, _, err := msgDB.GetContact(selfID, peerID)
if err != nil {
return "", "", "", 0, err
}
if fullName == "" {
from = unmappedID
} else {
from = fullName + " <" + unmappedID + ">"
}
unmappedID, fullName, err = msgDB.GetNym(selfID)
if err != nil {
return "", "", "", 0, err
}
if fullName == "" {
to = unmappedID
} else {
to = fullName + " <" + unmappedID + ">"
}
}
return
}
// ReadMessage sets the message with the given msgNum as read.
func (msgDB *MsgDB) ReadMessage(msgNum int64) error {
if _, err := msgDB.readMsgQuery.Exec(msgNum); err != nil {
return log.Error(err)
}
return nil
}
// DelMessage deletes the message from user myID with the given msgNum.
func (msgDB *MsgDB) DelMessage(myID string, msgNum int64) error {
if err := identity.IsMapped(myID); err != nil {
return log.Error(err)
}
var self int
if err := msgDB.getNymUIDQuery.QueryRow(myID).Scan(&self); err != nil {
return log.Error(err)
}
res, err := msgDB.delMsgQuery.Exec(msgNum, self)
if err != nil {
return log.Error(err)
}
n, err := res.RowsAffected()
if err != nil {
return log.Error(err)
}
if n < 1 {
return log.Errorf("msgdb: unknown msgnum %d for user ID %s",
msgNum, myID)
}
return nil
}
// MsgID is the info type that is returned by GetMsgIDs.
type MsgID struct {
MsgID int64 // the message ID
From string // sender
To string // recipient
Incoming bool // an incoming message, outgoing otherwise
Sent bool // outgoing message has been sent
Date int64
Subject string
Read bool
}
// GetMsgIDs returns all message IDs (sqlite row IDs) for the user ID myID.
func (msgDB *MsgDB) GetMsgIDs(myID string) ([]*MsgID, error) {
if err := identity.IsMapped(myID); err != nil {
return nil, log.Error(err)
}
var uid int
if err := msgDB.getNymUIDQuery.QueryRow(myID).Scan(&uid); err != nil {
return nil, log.Error(err)
}
rows, err := msgDB.getMsgsQuery.Query(uid)
if err != nil {
return nil, log.Error(err)
}
var msgIDs []*MsgID
defer rows.Close()
for rows.Next() {
var (
id int64
from string
to string
d int64
s int64
date int64
subject string
r int64
)
err = rows.Scan(&id, &from, &to, &d, &s, &date, &subject, &r)
if err != nil {
return nil, log.Error(err)
}
var (
incoming bool
sent bool
read bool
)
if d == 0 {
incoming = true
}
if s > 0 {
sent = true
}
if r > 0 {
read = true
}
msgIDs = append(msgIDs, &MsgID{
MsgID: id,
From: from,
To: to,
Incoming: incoming,
Sent: sent,
Date: date,
Subject: subject,
Read: read,
})
}
if err := rows.Err(); err != nil {
return nil, log.Error(err)
}
return msgIDs, nil
}
// GetUndeliveredMessage returns the oldest undelivered message for myID from
// msgDB.
func (msgDB *MsgDB) GetUndeliveredMessage(myID string) (
msgNum int64,
contactID string,
msg []byte,
sign bool,
minDelay, maxDelay int32,
err error,
) {
if err := identity.IsMapped(myID); err != nil {
return 0, "", nil, false, 0, 0, log.Error(err)
}
var mID int64
if err := msgDB.getNymUIDQuery.QueryRow(myID).Scan(&mID); err != nil {
return 0, "", nil, false, 0, 0, log.Error(err)
}
var cID int64
var s int64
err = msgDB.getUndeliveredMsgQuery.QueryRow(mID).Scan(&msgNum, &cID, &msg,
&s, &minDelay, &maxDelay)
switch {
case err == sql.ErrNoRows:
return 0, "", nil, false, 0, 0, nil
case err != nil:
return 0, "", nil, false, 0, 0, log.Error(err)
}
if s > 0 {
sign = true
}
err = msgDB.getContactMappedQuery.QueryRow(mID, cID).Scan(&contactID)
if err != nil {
return 0, "", nil, false, 0, 0, log.Error(err)
}
return
}
// numberOfMessages returns the number of messages in msgDB.
func (msgDB *MsgDB) numberOfMessages() (int64, error) {
var num int64
err := msgDB.encDB.QueryRow("SELECT COUNT(*) FROM Messages;").Scan(&num)
if err != nil {
return 0, err
}
return num, nil
}
| bsd-3-clause |
patrickm/chromium.src | ppapi/shared_impl/var_value_conversions_unittest.cc | 13555 | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/shared_impl/var_value_conversions.h"
#include <cmath>
#include <cstring>
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/values.h"
#include "ppapi/c/pp_bool.h"
#include "ppapi/c/pp_var.h"
#include "ppapi/shared_impl/array_var.h"
#include "ppapi/shared_impl/dictionary_var.h"
#include "ppapi/shared_impl/ppapi_globals.h"
#include "ppapi/shared_impl/proxy_lock.h"
#include "ppapi/shared_impl/scoped_pp_var.h"
#include "ppapi/shared_impl/test_globals.h"
#include "ppapi/shared_impl/var.h"
#include "ppapi/shared_impl/var_tracker.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace ppapi {
namespace {
bool Equals(const base::Value& value, const PP_Var& var) {
switch (value.GetType()) {
case base::Value::TYPE_NULL: {
return var.type == PP_VARTYPE_NULL || var.type == PP_VARTYPE_UNDEFINED;
}
case base::Value::TYPE_BOOLEAN: {
bool result = false;
return var.type == PP_VARTYPE_BOOL && value.GetAsBoolean(&result) &&
result == PP_ToBool(var.value.as_bool);
}
case base::Value::TYPE_INTEGER: {
int result = 0;
return var.type == PP_VARTYPE_INT32 && value.GetAsInteger(&result) &&
result == var.value.as_int;
}
case base::Value::TYPE_DOUBLE: {
double result = 0;
return var.type == PP_VARTYPE_DOUBLE && value.GetAsDouble(&result) &&
fabs(result - var.value.as_double) < 1.0e-4;
}
case base::Value::TYPE_STRING: {
std::string result;
StringVar* string_var = StringVar::FromPPVar(var);
return string_var && value.GetAsString(&result) &&
result == string_var->value();
}
case base::Value::TYPE_BINARY: {
const base::BinaryValue& binary_value =
static_cast<const base::BinaryValue&>(value);
ArrayBufferVar* array_buffer_var = ArrayBufferVar::FromPPVar(var);
if (!array_buffer_var ||
binary_value.GetSize() != array_buffer_var->ByteLength()) {
return false;
}
bool result = !memcmp(binary_value.GetBuffer(),
array_buffer_var->Map(),
binary_value.GetSize());
array_buffer_var->Unmap();
return result;
}
case base::Value::TYPE_DICTIONARY: {
const base::DictionaryValue& dict_value =
static_cast<const base::DictionaryValue&>(value);
DictionaryVar* dict_var = DictionaryVar::FromPPVar(var);
if (!dict_var)
return false;
size_t count = 0;
for (DictionaryVar::KeyValueMap::const_iterator iter =
dict_var->key_value_map().begin();
iter != dict_var->key_value_map().end();
++iter) {
if (iter->second.get().type == PP_VARTYPE_UNDEFINED ||
iter->second.get().type == PP_VARTYPE_NULL) {
continue;
}
++count;
const base::Value* sub_value = NULL;
if (!dict_value.GetWithoutPathExpansion(iter->first, &sub_value) ||
!Equals(*sub_value, iter->second.get())) {
return false;
}
}
return count == dict_value.size();
}
case base::Value::TYPE_LIST: {
const base::ListValue& list_value =
static_cast<const base::ListValue&>(value);
ArrayVar* array_var = ArrayVar::FromPPVar(var);
if (!array_var || list_value.GetSize() != array_var->elements().size())
return false;
base::ListValue::const_iterator value_iter = list_value.begin();
ArrayVar::ElementVector::const_iterator var_iter =
array_var->elements().begin();
for (; value_iter != list_value.end() &&
var_iter != array_var->elements().end();
++value_iter, ++var_iter) {
if (!Equals(**value_iter, var_iter->get()))
return false;
}
return true;
}
}
NOTREACHED();
return false;
}
bool ConvertVarAndVerify(const PP_Var& var) {
scoped_ptr<base::Value> value(CreateValueFromVar(var));
if (value.get())
return Equals(*value, var);
return false;
}
bool ConvertValueAndVerify(const base::Value& value) {
ScopedPPVar var(ScopedPPVar::PassRef(), CreateVarFromValue(value));
if (var.get().type != PP_VARTYPE_UNDEFINED)
return Equals(value, var.get());
return false;
}
class VarValueConversionsTest : public testing::Test {
public:
VarValueConversionsTest() {}
virtual ~VarValueConversionsTest() {}
// testing::Test implementation.
virtual void SetUp() {
ProxyLock::EnableLockingOnThreadForTest();
ProxyLock::Acquire();
}
virtual void TearDown() {
ASSERT_TRUE(PpapiGlobals::Get()->GetVarTracker()->GetLiveVars().empty());
ProxyLock::Release();
}
private:
TestGlobals globals_;
};
} // namespace
TEST_F(VarValueConversionsTest, CreateValueFromVar) {
{
// Var holding a ref to itself is not a valid input.
scoped_refptr<DictionaryVar> dict_var(new DictionaryVar());
ScopedPPVar var_1(ScopedPPVar::PassRef(), dict_var->GetPPVar());
scoped_refptr<ArrayVar> array_var(new ArrayVar());
ScopedPPVar var_2(ScopedPPVar::PassRef(), array_var->GetPPVar());
ASSERT_TRUE(dict_var->SetWithStringKey("key_1", var_2.get()));
ASSERT_TRUE(ConvertVarAndVerify(var_1.get()));
ASSERT_TRUE(array_var->Set(0, var_1.get()));
scoped_ptr<base::Value> value(CreateValueFromVar(var_1.get()));
ASSERT_EQ(NULL, value.get());
// Make sure |var_1| doesn't indirectly hold a ref to itself, otherwise it
// is leaked.
dict_var->DeleteWithStringKey("key_1");
}
// Vars of null or undefined type are converted to null values.
{
ASSERT_TRUE(ConvertVarAndVerify(PP_MakeNull()));
ASSERT_TRUE(ConvertVarAndVerify(PP_MakeUndefined()));
}
{
// Test empty dictionary.
scoped_refptr<DictionaryVar> dict_var(new DictionaryVar());
ScopedPPVar var(ScopedPPVar::PassRef(), dict_var->GetPPVar());
ASSERT_TRUE(ConvertVarAndVerify(var.get()));
}
{
// Key-value pairs whose value is undefined or null are ignored.
scoped_refptr<DictionaryVar> dict_var(new DictionaryVar());
ASSERT_TRUE(dict_var->SetWithStringKey("key_1", PP_MakeUndefined()));
ASSERT_TRUE(dict_var->SetWithStringKey("key_2", PP_MakeInt32(1)));
ASSERT_TRUE(dict_var->SetWithStringKey("key_3", PP_MakeNull()));
ScopedPPVar var(ScopedPPVar::PassRef(), dict_var->GetPPVar());
ASSERT_TRUE(ConvertVarAndVerify(var.get()));
}
{
// The same PP_Var is allowed to appear multiple times.
scoped_refptr<DictionaryVar> dict_var_1(new DictionaryVar());
ScopedPPVar dict_pp_var_1(ScopedPPVar::PassRef(), dict_var_1->GetPPVar());
scoped_refptr<DictionaryVar> dict_var_2(new DictionaryVar());
ScopedPPVar dict_pp_var_2(ScopedPPVar::PassRef(), dict_var_2->GetPPVar());
scoped_refptr<StringVar> string_var(new StringVar("string_value"));
ScopedPPVar string_pp_var(ScopedPPVar::PassRef(), string_var->GetPPVar());
ASSERT_TRUE(dict_var_1->SetWithStringKey("key_1", dict_pp_var_2.get()));
ASSERT_TRUE(dict_var_1->SetWithStringKey("key_2", dict_pp_var_2.get()));
ASSERT_TRUE(dict_var_1->SetWithStringKey("key_3", string_pp_var.get()));
ASSERT_TRUE(dict_var_2->SetWithStringKey("key_4", string_pp_var.get()));
ASSERT_TRUE(ConvertVarAndVerify(dict_pp_var_1.get()));
}
{
// Test basic cases for array.
scoped_refptr<ArrayVar> array_var(new ArrayVar());
ScopedPPVar var(ScopedPPVar::PassRef(), array_var->GetPPVar());
ASSERT_TRUE(ConvertVarAndVerify(var.get()));
ASSERT_TRUE(array_var->Set(0, PP_MakeDouble(1)));
ASSERT_TRUE(ConvertVarAndVerify(var.get()));
}
{
// Test more complex inputs.
scoped_refptr<DictionaryVar> dict_var_1(new DictionaryVar());
ScopedPPVar dict_pp_var_1(ScopedPPVar::PassRef(), dict_var_1->GetPPVar());
scoped_refptr<DictionaryVar> dict_var_2(new DictionaryVar());
ScopedPPVar dict_pp_var_2(ScopedPPVar::PassRef(), dict_var_2->GetPPVar());
scoped_refptr<ArrayVar> array_var(new ArrayVar());
ScopedPPVar array_pp_var(ScopedPPVar::PassRef(), array_var->GetPPVar());
scoped_refptr<StringVar> string_var(new StringVar("string_value"));
ScopedPPVar string_pp_var(ScopedPPVar::PassRef(), string_var->GetPPVar());
ASSERT_TRUE(dict_var_1->SetWithStringKey("null_key", PP_MakeNull()));
ASSERT_TRUE(
dict_var_1->SetWithStringKey("string_key", string_pp_var.get()));
ASSERT_TRUE(dict_var_1->SetWithStringKey("dict_key", dict_pp_var_2.get()));
ASSERT_TRUE(
dict_var_2->SetWithStringKey("undefined_key", PP_MakeUndefined()));
ASSERT_TRUE(dict_var_2->SetWithStringKey("double_key", PP_MakeDouble(1)));
ASSERT_TRUE(dict_var_2->SetWithStringKey("array_key", array_pp_var.get()));
ASSERT_TRUE(array_var->Set(0, PP_MakeInt32(2)));
ASSERT_TRUE(array_var->Set(1, PP_MakeBool(PP_TRUE)));
ASSERT_TRUE(array_var->SetLength(4));
ASSERT_TRUE(ConvertVarAndVerify(dict_pp_var_1.get()));
}
{
// Test that dictionary keys containing '.' are handled correctly.
scoped_refptr<DictionaryVar> dict_var(new DictionaryVar());
ScopedPPVar dict_pp_var(ScopedPPVar::PassRef(), dict_var->GetPPVar());
ASSERT_TRUE(dict_var->SetWithStringKey("double.key", PP_MakeDouble(1)));
ASSERT_TRUE(dict_var->SetWithStringKey("int.key..name", PP_MakeInt32(2)));
ASSERT_TRUE(ConvertVarAndVerify(dict_pp_var.get()));
}
}
TEST_F(VarValueConversionsTest, CreateVarFromValue) {
{
// Test basic cases for dictionary.
base::DictionaryValue dict_value;
ASSERT_TRUE(ConvertValueAndVerify(dict_value));
dict_value.SetInteger("int_key", 1);
ASSERT_TRUE(ConvertValueAndVerify(dict_value));
}
{
// Test basic cases for array.
base::ListValue list_value;
ASSERT_TRUE(ConvertValueAndVerify(list_value));
list_value.AppendInteger(1);
ASSERT_TRUE(ConvertValueAndVerify(list_value));
}
{
// Test more complex inputs.
base::DictionaryValue dict_value;
dict_value.SetString("string_key", "string_value");
dict_value.SetDouble("dict_key.double_key", 1);
scoped_ptr<base::ListValue> list_value(new base::ListValue());
list_value->AppendInteger(2);
list_value->AppendBoolean(true);
list_value->Append(base::Value::CreateNullValue());
dict_value.Set("dict_key.array_key", list_value.release());
ASSERT_TRUE(ConvertValueAndVerify(dict_value));
}
}
TEST_F(VarValueConversionsTest, CreateListValueFromVarVector) {
{
// Test empty var vector.
scoped_ptr<base::ListValue> list_value(
CreateListValueFromVarVector(std::vector<PP_Var>()));
ASSERT_TRUE(list_value.get());
ASSERT_EQ(0u, list_value->GetSize());
}
{
// Test more complex inputs.
scoped_refptr<StringVar> string_var(new StringVar("string_value"));
ScopedPPVar string_pp_var(ScopedPPVar::PassRef(), string_var->GetPPVar());
scoped_refptr<DictionaryVar> dict_var(new DictionaryVar());
ScopedPPVar dict_pp_var(ScopedPPVar::PassRef(), dict_var->GetPPVar());
ASSERT_TRUE(dict_var->SetWithStringKey("null_key", PP_MakeNull()));
ASSERT_TRUE(dict_var->SetWithStringKey("string_key", string_pp_var.get()));
scoped_refptr<ArrayVar> array_var(new ArrayVar());
ScopedPPVar array_pp_var(ScopedPPVar::PassRef(), array_var->GetPPVar());
ASSERT_TRUE(array_var->Set(0, PP_MakeInt32(2)));
ASSERT_TRUE(array_var->Set(1, PP_MakeBool(PP_TRUE)));
ASSERT_TRUE(array_var->SetLength(4));
std::vector<PP_Var> vars;
vars.push_back(dict_pp_var.get());
vars.push_back(string_pp_var.get());
vars.push_back(array_pp_var.get());
vars.push_back(PP_MakeDouble(1));
vars.push_back(PP_MakeUndefined());
vars.push_back(PP_MakeNull());
scoped_ptr<base::ListValue> list_value(CreateListValueFromVarVector(vars));
ASSERT_TRUE(list_value.get());
ASSERT_EQ(vars.size(), list_value->GetSize());
for (size_t i = 0; i < list_value->GetSize(); ++i) {
const base::Value* value = NULL;
ASSERT_TRUE(list_value->Get(i, &value));
ASSERT_TRUE(Equals(*value, vars[i]));
}
}
}
TEST_F(VarValueConversionsTest, CreateVarVectorFromListValue) {
{
// Test empty list.
base::ListValue list_value;
std::vector<PP_Var> vars;
ASSERT_TRUE(CreateVarVectorFromListValue(list_value, &vars));
ASSERT_EQ(0u, vars.size());
}
{
// Test more complex inputs.
base::ListValue list_value;
scoped_ptr<base::DictionaryValue> dict_value(new base::DictionaryValue());
dict_value->SetString("string_key", "string_value");
scoped_ptr<base::ListValue> sub_list_value(new base::ListValue());
sub_list_value->AppendInteger(2);
sub_list_value->AppendBoolean(true);
list_value.Append(dict_value.release());
list_value.AppendString("string_value");
list_value.Append(sub_list_value.release());
list_value.AppendDouble(1);
list_value.Append(base::Value::CreateNullValue());
std::vector<PP_Var> vars;
ASSERT_TRUE(CreateVarVectorFromListValue(list_value, &vars));
ASSERT_EQ(list_value.GetSize(), vars.size());
for (size_t i = 0; i < list_value.GetSize(); ++i) {
const base::Value* value = NULL;
ASSERT_TRUE(list_value.Get(i, &value));
ASSERT_TRUE(Equals(*value, vars[i]));
PpapiGlobals::Get()->GetVarTracker()->ReleaseVar(vars[i]);
}
}
}
} // namespace ppapi
| bsd-3-clause |
mxOBS/deb-pkg_trusty_chromium-browser | third_party/webrtc/base/openssladapter.cc | 24564 | /*
* Copyright 2008 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#if HAVE_OPENSSL_SSL_H
#include "webrtc/base/openssladapter.h"
#if defined(WEBRTC_POSIX)
#include <unistd.h>
#endif
// Must be included first before openssl headers.
#include "webrtc/base/win32.h" // NOLINT
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/opensslv.h>
#include <openssl/rand.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#if HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H
#include "webrtc/base/common.h"
#include "webrtc/base/logging.h"
#include "webrtc/base/openssl.h"
#include "webrtc/base/safe_conversions.h"
#include "webrtc/base/sslroots.h"
#include "webrtc/base/stringutils.h"
#include "webrtc/base/thread.h"
// TODO: Use a nicer abstraction for mutex.
#if defined(WEBRTC_WIN)
#define MUTEX_TYPE HANDLE
#define MUTEX_SETUP(x) (x) = CreateMutex(NULL, FALSE, NULL)
#define MUTEX_CLEANUP(x) CloseHandle(x)
#define MUTEX_LOCK(x) WaitForSingleObject((x), INFINITE)
#define MUTEX_UNLOCK(x) ReleaseMutex(x)
#define THREAD_ID GetCurrentThreadId()
#elif defined(WEBRTC_POSIX)
#define MUTEX_TYPE pthread_mutex_t
#define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)
#define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))
#define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
#define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
#define THREAD_ID pthread_self()
#else
#error You must define mutex operations appropriate for your platform!
#endif
struct CRYPTO_dynlock_value {
MUTEX_TYPE mutex;
};
//////////////////////////////////////////////////////////////////////
// SocketBIO
//////////////////////////////////////////////////////////////////////
static int socket_write(BIO* h, const char* buf, int num);
static int socket_read(BIO* h, char* buf, int size);
static int socket_puts(BIO* h, const char* str);
static long socket_ctrl(BIO* h, int cmd, long arg1, void* arg2);
static int socket_new(BIO* h);
static int socket_free(BIO* data);
static const BIO_METHOD methods_socket = {
BIO_TYPE_BIO,
"socket",
socket_write,
socket_read,
socket_puts,
0,
socket_ctrl,
socket_new,
socket_free,
NULL,
};
static const BIO_METHOD* BIO_s_socket2() { return(&methods_socket); }
static BIO* BIO_new_socket(rtc::AsyncSocket* socket) {
BIO* ret = BIO_new(BIO_s_socket2());
if (ret == NULL) {
return NULL;
}
ret->ptr = socket;
return ret;
}
static int socket_new(BIO* b) {
b->shutdown = 0;
b->init = 1;
b->num = 0; // 1 means socket closed
b->ptr = 0;
return 1;
}
static int socket_free(BIO* b) {
if (b == NULL)
return 0;
return 1;
}
static int socket_read(BIO* b, char* out, int outl) {
if (!out)
return -1;
rtc::AsyncSocket* socket = static_cast<rtc::AsyncSocket*>(b->ptr);
BIO_clear_retry_flags(b);
int result = socket->Recv(out, outl);
if (result > 0) {
return result;
} else if (result == 0) {
b->num = 1;
} else if (socket->IsBlocking()) {
BIO_set_retry_read(b);
}
return -1;
}
static int socket_write(BIO* b, const char* in, int inl) {
if (!in)
return -1;
rtc::AsyncSocket* socket = static_cast<rtc::AsyncSocket*>(b->ptr);
BIO_clear_retry_flags(b);
int result = socket->Send(in, inl);
if (result > 0) {
return result;
} else if (socket->IsBlocking()) {
BIO_set_retry_write(b);
}
return -1;
}
static int socket_puts(BIO* b, const char* str) {
return socket_write(b, str, rtc::checked_cast<int>(strlen(str)));
}
static long socket_ctrl(BIO* b, int cmd, long num, void* ptr) {
RTC_UNUSED(num);
RTC_UNUSED(ptr);
switch (cmd) {
case BIO_CTRL_RESET:
return 0;
case BIO_CTRL_EOF:
return b->num;
case BIO_CTRL_WPENDING:
case BIO_CTRL_PENDING:
return 0;
case BIO_CTRL_FLUSH:
return 1;
default:
return 0;
}
}
/////////////////////////////////////////////////////////////////////////////
// OpenSSLAdapter
/////////////////////////////////////////////////////////////////////////////
namespace rtc {
// This array will store all of the mutexes available to OpenSSL.
static MUTEX_TYPE* mutex_buf = NULL;
static void locking_function(int mode, int n, const char * file, int line) {
if (mode & CRYPTO_LOCK) {
MUTEX_LOCK(mutex_buf[n]);
} else {
MUTEX_UNLOCK(mutex_buf[n]);
}
}
static unsigned long id_function() { // NOLINT
// Use old-style C cast because THREAD_ID's type varies with the platform,
// in some cases requiring static_cast, and in others requiring
// reinterpret_cast.
return (unsigned long)THREAD_ID; // NOLINT
}
static CRYPTO_dynlock_value* dyn_create_function(const char* file, int line) {
CRYPTO_dynlock_value* value = new CRYPTO_dynlock_value;
if (!value)
return NULL;
MUTEX_SETUP(value->mutex);
return value;
}
static void dyn_lock_function(int mode, CRYPTO_dynlock_value* l,
const char* file, int line) {
if (mode & CRYPTO_LOCK) {
MUTEX_LOCK(l->mutex);
} else {
MUTEX_UNLOCK(l->mutex);
}
}
static void dyn_destroy_function(CRYPTO_dynlock_value* l,
const char* file, int line) {
MUTEX_CLEANUP(l->mutex);
delete l;
}
VerificationCallback OpenSSLAdapter::custom_verify_callback_ = NULL;
bool OpenSSLAdapter::InitializeSSL(VerificationCallback callback) {
if (!InitializeSSLThread() || !SSL_library_init())
return false;
#if !defined(ADDRESS_SANITIZER) || !defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
// Loading the error strings crashes mac_asan. Omit this debugging aid there.
SSL_load_error_strings();
#endif
ERR_load_BIO_strings();
OpenSSL_add_all_algorithms();
RAND_poll();
custom_verify_callback_ = callback;
return true;
}
bool OpenSSLAdapter::InitializeSSLThread() {
mutex_buf = new MUTEX_TYPE[CRYPTO_num_locks()];
if (!mutex_buf)
return false;
for (int i = 0; i < CRYPTO_num_locks(); ++i)
MUTEX_SETUP(mutex_buf[i]);
// we need to cast our id_function to return an unsigned long -- pthread_t is
// a pointer
CRYPTO_set_id_callback(id_function);
CRYPTO_set_locking_callback(locking_function);
CRYPTO_set_dynlock_create_callback(dyn_create_function);
CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
return true;
}
bool OpenSSLAdapter::CleanupSSL() {
if (!mutex_buf)
return false;
CRYPTO_set_id_callback(NULL);
CRYPTO_set_locking_callback(NULL);
CRYPTO_set_dynlock_create_callback(NULL);
CRYPTO_set_dynlock_lock_callback(NULL);
CRYPTO_set_dynlock_destroy_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks(); ++i)
MUTEX_CLEANUP(mutex_buf[i]);
delete [] mutex_buf;
mutex_buf = NULL;
return true;
}
OpenSSLAdapter::OpenSSLAdapter(AsyncSocket* socket)
: SSLAdapter(socket),
state_(SSL_NONE),
ssl_read_needs_write_(false),
ssl_write_needs_read_(false),
restartable_(false),
ssl_(NULL), ssl_ctx_(NULL),
ssl_mode_(SSL_MODE_TLS),
custom_verification_succeeded_(false) {
}
OpenSSLAdapter::~OpenSSLAdapter() {
Cleanup();
}
void
OpenSSLAdapter::SetMode(SSLMode mode) {
ASSERT(state_ == SSL_NONE);
ssl_mode_ = mode;
}
int
OpenSSLAdapter::StartSSL(const char* hostname, bool restartable) {
if (state_ != SSL_NONE)
return -1;
ssl_host_name_ = hostname;
restartable_ = restartable;
if (socket_->GetState() != Socket::CS_CONNECTED) {
state_ = SSL_WAIT;
return 0;
}
state_ = SSL_CONNECTING;
if (int err = BeginSSL()) {
Error("BeginSSL", err, false);
return err;
}
return 0;
}
int
OpenSSLAdapter::BeginSSL() {
LOG(LS_INFO) << "BeginSSL: " << ssl_host_name_;
ASSERT(state_ == SSL_CONNECTING);
int err = 0;
BIO* bio = NULL;
// First set up the context
if (!ssl_ctx_)
ssl_ctx_ = SetupSSLContext();
if (!ssl_ctx_) {
err = -1;
goto ssl_error;
}
bio = BIO_new_socket(static_cast<AsyncSocketAdapter*>(socket_));
if (!bio) {
err = -1;
goto ssl_error;
}
ssl_ = SSL_new(ssl_ctx_);
if (!ssl_) {
err = -1;
goto ssl_error;
}
SSL_set_app_data(ssl_, this);
SSL_set_bio(ssl_, bio, bio);
SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
// the SSL object owns the bio now
bio = NULL;
// Do the connect
err = ContinueSSL();
if (err != 0)
goto ssl_error;
return err;
ssl_error:
Cleanup();
if (bio)
BIO_free(bio);
return err;
}
int
OpenSSLAdapter::ContinueSSL() {
ASSERT(state_ == SSL_CONNECTING);
// Clear the DTLS timer
Thread::Current()->Clear(this, MSG_TIMEOUT);
int code = SSL_connect(ssl_);
switch (SSL_get_error(ssl_, code)) {
case SSL_ERROR_NONE:
if (!SSLPostConnectionCheck(ssl_, ssl_host_name_.c_str())) {
LOG(LS_ERROR) << "TLS post connection check failed";
// make sure we close the socket
Cleanup();
// The connect failed so return -1 to shut down the socket
return -1;
}
state_ = SSL_CONNECTED;
AsyncSocketAdapter::OnConnectEvent(this);
#if 0 // TODO: worry about this
// Don't let ourselves go away during the callbacks
PRefPtr<OpenSSLAdapter> lock(this);
LOG(LS_INFO) << " -- onStreamReadable";
AsyncSocketAdapter::OnReadEvent(this);
LOG(LS_INFO) << " -- onStreamWriteable";
AsyncSocketAdapter::OnWriteEvent(this);
#endif
break;
case SSL_ERROR_WANT_READ:
LOG(LS_VERBOSE) << " -- error want read";
struct timeval timeout;
if (DTLSv1_get_timeout(ssl_, &timeout)) {
int delay = timeout.tv_sec * 1000 + timeout.tv_usec/1000;
Thread::Current()->PostDelayed(delay, this, MSG_TIMEOUT, 0);
}
break;
case SSL_ERROR_WANT_WRITE:
break;
case SSL_ERROR_ZERO_RETURN:
default:
LOG(LS_WARNING) << "ContinueSSL -- error " << code;
return (code != 0) ? code : -1;
}
return 0;
}
void
OpenSSLAdapter::Error(const char* context, int err, bool signal) {
LOG(LS_WARNING) << "OpenSSLAdapter::Error("
<< context << ", " << err << ")";
state_ = SSL_ERROR;
SetError(err);
if (signal)
AsyncSocketAdapter::OnCloseEvent(this, err);
}
void
OpenSSLAdapter::Cleanup() {
LOG(LS_INFO) << "Cleanup";
state_ = SSL_NONE;
ssl_read_needs_write_ = false;
ssl_write_needs_read_ = false;
custom_verification_succeeded_ = false;
if (ssl_) {
SSL_free(ssl_);
ssl_ = NULL;
}
if (ssl_ctx_) {
SSL_CTX_free(ssl_ctx_);
ssl_ctx_ = NULL;
}
// Clear the DTLS timer
Thread::Current()->Clear(this, MSG_TIMEOUT);
}
//
// AsyncSocket Implementation
//
int
OpenSSLAdapter::Send(const void* pv, size_t cb) {
//LOG(LS_INFO) << "OpenSSLAdapter::Send(" << cb << ")";
switch (state_) {
case SSL_NONE:
return AsyncSocketAdapter::Send(pv, cb);
case SSL_WAIT:
case SSL_CONNECTING:
SetError(EWOULDBLOCK);
return SOCKET_ERROR;
case SSL_CONNECTED:
break;
case SSL_ERROR:
default:
return SOCKET_ERROR;
}
// OpenSSL will return an error if we try to write zero bytes
if (cb == 0)
return 0;
ssl_write_needs_read_ = false;
int code = SSL_write(ssl_, pv, checked_cast<int>(cb));
switch (SSL_get_error(ssl_, code)) {
case SSL_ERROR_NONE:
//LOG(LS_INFO) << " -- success";
return code;
case SSL_ERROR_WANT_READ:
//LOG(LS_INFO) << " -- error want read";
ssl_write_needs_read_ = true;
SetError(EWOULDBLOCK);
break;
case SSL_ERROR_WANT_WRITE:
//LOG(LS_INFO) << " -- error want write";
SetError(EWOULDBLOCK);
break;
case SSL_ERROR_ZERO_RETURN:
//LOG(LS_INFO) << " -- remote side closed";
SetError(EWOULDBLOCK);
// do we need to signal closure?
break;
default:
//LOG(LS_INFO) << " -- error " << code;
Error("SSL_write", (code ? code : -1), false);
break;
}
return SOCKET_ERROR;
}
int
OpenSSLAdapter::SendTo(const void* pv, size_t cb, const SocketAddress& addr) {
if (socket_->GetState() == Socket::CS_CONNECTED &&
addr == socket_->GetRemoteAddress()) {
return Send(pv, cb);
}
SetError(ENOTCONN);
return SOCKET_ERROR;
}
int
OpenSSLAdapter::Recv(void* pv, size_t cb) {
//LOG(LS_INFO) << "OpenSSLAdapter::Recv(" << cb << ")";
switch (state_) {
case SSL_NONE:
return AsyncSocketAdapter::Recv(pv, cb);
case SSL_WAIT:
case SSL_CONNECTING:
SetError(EWOULDBLOCK);
return SOCKET_ERROR;
case SSL_CONNECTED:
break;
case SSL_ERROR:
default:
return SOCKET_ERROR;
}
// Don't trust OpenSSL with zero byte reads
if (cb == 0)
return 0;
ssl_read_needs_write_ = false;
int code = SSL_read(ssl_, pv, checked_cast<int>(cb));
switch (SSL_get_error(ssl_, code)) {
case SSL_ERROR_NONE:
//LOG(LS_INFO) << " -- success";
return code;
case SSL_ERROR_WANT_READ:
//LOG(LS_INFO) << " -- error want read";
SetError(EWOULDBLOCK);
break;
case SSL_ERROR_WANT_WRITE:
//LOG(LS_INFO) << " -- error want write";
ssl_read_needs_write_ = true;
SetError(EWOULDBLOCK);
break;
case SSL_ERROR_ZERO_RETURN:
//LOG(LS_INFO) << " -- remote side closed";
SetError(EWOULDBLOCK);
// do we need to signal closure?
break;
default:
//LOG(LS_INFO) << " -- error " << code;
Error("SSL_read", (code ? code : -1), false);
break;
}
return SOCKET_ERROR;
}
int
OpenSSLAdapter::RecvFrom(void* pv, size_t cb, SocketAddress* paddr) {
if (socket_->GetState() == Socket::CS_CONNECTED) {
int ret = Recv(pv, cb);
*paddr = GetRemoteAddress();
return ret;
}
SetError(ENOTCONN);
return SOCKET_ERROR;
}
int
OpenSSLAdapter::Close() {
Cleanup();
state_ = restartable_ ? SSL_WAIT : SSL_NONE;
return AsyncSocketAdapter::Close();
}
Socket::ConnState
OpenSSLAdapter::GetState() const {
//if (signal_close_)
// return CS_CONNECTED;
ConnState state = socket_->GetState();
if ((state == CS_CONNECTED)
&& ((state_ == SSL_WAIT) || (state_ == SSL_CONNECTING)))
state = CS_CONNECTING;
return state;
}
void
OpenSSLAdapter::OnMessage(Message* msg) {
if (MSG_TIMEOUT == msg->message_id) {
LOG(LS_INFO) << "DTLS timeout expired";
DTLSv1_handle_timeout(ssl_);
ContinueSSL();
}
}
void
OpenSSLAdapter::OnConnectEvent(AsyncSocket* socket) {
LOG(LS_INFO) << "OpenSSLAdapter::OnConnectEvent";
if (state_ != SSL_WAIT) {
ASSERT(state_ == SSL_NONE);
AsyncSocketAdapter::OnConnectEvent(socket);
return;
}
state_ = SSL_CONNECTING;
if (int err = BeginSSL()) {
AsyncSocketAdapter::OnCloseEvent(socket, err);
}
}
void
OpenSSLAdapter::OnReadEvent(AsyncSocket* socket) {
//LOG(LS_INFO) << "OpenSSLAdapter::OnReadEvent";
if (state_ == SSL_NONE) {
AsyncSocketAdapter::OnReadEvent(socket);
return;
}
if (state_ == SSL_CONNECTING) {
if (int err = ContinueSSL()) {
Error("ContinueSSL", err);
}
return;
}
if (state_ != SSL_CONNECTED)
return;
// Don't let ourselves go away during the callbacks
//PRefPtr<OpenSSLAdapter> lock(this); // TODO: fix this
if (ssl_write_needs_read_) {
//LOG(LS_INFO) << " -- onStreamWriteable";
AsyncSocketAdapter::OnWriteEvent(socket);
}
//LOG(LS_INFO) << " -- onStreamReadable";
AsyncSocketAdapter::OnReadEvent(socket);
}
void
OpenSSLAdapter::OnWriteEvent(AsyncSocket* socket) {
//LOG(LS_INFO) << "OpenSSLAdapter::OnWriteEvent";
if (state_ == SSL_NONE) {
AsyncSocketAdapter::OnWriteEvent(socket);
return;
}
if (state_ == SSL_CONNECTING) {
if (int err = ContinueSSL()) {
Error("ContinueSSL", err);
}
return;
}
if (state_ != SSL_CONNECTED)
return;
// Don't let ourselves go away during the callbacks
//PRefPtr<OpenSSLAdapter> lock(this); // TODO: fix this
if (ssl_read_needs_write_) {
//LOG(LS_INFO) << " -- onStreamReadable";
AsyncSocketAdapter::OnReadEvent(socket);
}
//LOG(LS_INFO) << " -- onStreamWriteable";
AsyncSocketAdapter::OnWriteEvent(socket);
}
void
OpenSSLAdapter::OnCloseEvent(AsyncSocket* socket, int err) {
LOG(LS_INFO) << "OpenSSLAdapter::OnCloseEvent(" << err << ")";
AsyncSocketAdapter::OnCloseEvent(socket, err);
}
// This code is taken from the "Network Security with OpenSSL"
// sample in chapter 5
bool OpenSSLAdapter::VerifyServerName(SSL* ssl, const char* host,
bool ignore_bad_cert) {
if (!host)
return false;
// Checking the return from SSL_get_peer_certificate here is not strictly
// necessary. With our setup, it is not possible for it to return
// NULL. However, it is good form to check the return.
X509* certificate = SSL_get_peer_certificate(ssl);
if (!certificate)
return false;
// Logging certificates is extremely verbose. So it is disabled by default.
#ifdef LOG_CERTIFICATES
{
LOG(LS_INFO) << "Certificate from server:";
BIO* mem = BIO_new(BIO_s_mem());
X509_print_ex(mem, certificate, XN_FLAG_SEP_CPLUS_SPC, X509_FLAG_NO_HEADER);
BIO_write(mem, "\0", 1);
char* buffer;
BIO_get_mem_data(mem, &buffer);
LOG(LS_INFO) << buffer;
BIO_free(mem);
char* cipher_description =
SSL_CIPHER_description(SSL_get_current_cipher(ssl), NULL, 128);
LOG(LS_INFO) << "Cipher: " << cipher_description;
OPENSSL_free(cipher_description);
}
#endif
bool ok = false;
int extension_count = X509_get_ext_count(certificate);
for (int i = 0; i < extension_count; ++i) {
X509_EXTENSION* extension = X509_get_ext(certificate, i);
int extension_nid = OBJ_obj2nid(X509_EXTENSION_get_object(extension));
if (extension_nid == NID_subject_alt_name) {
const X509V3_EXT_METHOD* meth = X509V3_EXT_get(extension);
if (!meth)
break;
void* ext_str = NULL;
// We assign this to a local variable, instead of passing the address
// directly to ASN1_item_d2i.
// See http://readlist.com/lists/openssl.org/openssl-users/0/4761.html.
unsigned char* ext_value_data = extension->value->data;
const unsigned char **ext_value_data_ptr =
(const_cast<const unsigned char **>(&ext_value_data));
if (meth->it) {
ext_str = ASN1_item_d2i(NULL, ext_value_data_ptr,
extension->value->length,
ASN1_ITEM_ptr(meth->it));
} else {
ext_str = meth->d2i(NULL, ext_value_data_ptr, extension->value->length);
}
STACK_OF(CONF_VALUE)* value = meth->i2v(meth, ext_str, NULL);
// Cast to size_t to be compilable for both OpenSSL and BoringSSL.
for (size_t j = 0; j < static_cast<size_t>(sk_CONF_VALUE_num(value));
++j) {
CONF_VALUE* nval = sk_CONF_VALUE_value(value, j);
// The value for nval can contain wildcards
if (!strcmp(nval->name, "DNS") && string_match(host, nval->value)) {
ok = true;
break;
}
}
sk_CONF_VALUE_pop_free(value, X509V3_conf_free);
value = NULL;
if (meth->it) {
ASN1_item_free(reinterpret_cast<ASN1_VALUE*>(ext_str),
ASN1_ITEM_ptr(meth->it));
} else {
meth->ext_free(ext_str);
}
ext_str = NULL;
}
if (ok)
break;
}
char data[256];
X509_NAME* subject;
if (!ok
&& ((subject = X509_get_subject_name(certificate)) != NULL)
&& (X509_NAME_get_text_by_NID(subject, NID_commonName,
data, sizeof(data)) > 0)) {
data[sizeof(data)-1] = 0;
if (_stricmp(data, host) == 0)
ok = true;
}
X509_free(certificate);
// This should only ever be turned on for debugging and development.
if (!ok && ignore_bad_cert) {
LOG(LS_WARNING) << "TLS certificate check FAILED. "
<< "Allowing connection anyway.";
ok = true;
}
return ok;
}
bool OpenSSLAdapter::SSLPostConnectionCheck(SSL* ssl, const char* host) {
bool ok = VerifyServerName(ssl, host, ignore_bad_cert());
if (ok) {
ok = (SSL_get_verify_result(ssl) == X509_V_OK ||
custom_verification_succeeded_);
}
if (!ok && ignore_bad_cert()) {
LOG(LS_INFO) << "Other TLS post connection checks failed.";
ok = true;
}
return ok;
}
#if _DEBUG
// We only use this for tracing and so it is only needed in debug mode
void
OpenSSLAdapter::SSLInfoCallback(const SSL* s, int where, int ret) {
const char* str = "undefined";
int w = where & ~SSL_ST_MASK;
if (w & SSL_ST_CONNECT) {
str = "SSL_connect";
} else if (w & SSL_ST_ACCEPT) {
str = "SSL_accept";
}
if (where & SSL_CB_LOOP) {
LOG(LS_INFO) << str << ":" << SSL_state_string_long(s);
} else if (where & SSL_CB_ALERT) {
str = (where & SSL_CB_READ) ? "read" : "write";
LOG(LS_INFO) << "SSL3 alert " << str
<< ":" << SSL_alert_type_string_long(ret)
<< ":" << SSL_alert_desc_string_long(ret);
} else if (where & SSL_CB_EXIT) {
if (ret == 0) {
LOG(LS_INFO) << str << ":failed in " << SSL_state_string_long(s);
} else if (ret < 0) {
LOG(LS_INFO) << str << ":error in " << SSL_state_string_long(s);
}
}
}
#endif // _DEBUG
int
OpenSSLAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
#if _DEBUG
if (!ok) {
char data[256];
X509* cert = X509_STORE_CTX_get_current_cert(store);
int depth = X509_STORE_CTX_get_error_depth(store);
int err = X509_STORE_CTX_get_error(store);
LOG(LS_INFO) << "Error with certificate at depth: " << depth;
X509_NAME_oneline(X509_get_issuer_name(cert), data, sizeof(data));
LOG(LS_INFO) << " issuer = " << data;
X509_NAME_oneline(X509_get_subject_name(cert), data, sizeof(data));
LOG(LS_INFO) << " subject = " << data;
LOG(LS_INFO) << " err = " << err
<< ":" << X509_verify_cert_error_string(err);
}
#endif
// Get our stream pointer from the store
SSL* ssl = reinterpret_cast<SSL*>(
X509_STORE_CTX_get_ex_data(store,
SSL_get_ex_data_X509_STORE_CTX_idx()));
OpenSSLAdapter* stream =
reinterpret_cast<OpenSSLAdapter*>(SSL_get_app_data(ssl));
if (!ok && custom_verify_callback_) {
void* cert =
reinterpret_cast<void*>(X509_STORE_CTX_get_current_cert(store));
if (custom_verify_callback_(cert)) {
stream->custom_verification_succeeded_ = true;
LOG(LS_INFO) << "validated certificate using custom callback";
ok = true;
}
}
// Should only be used for debugging and development.
if (!ok && stream->ignore_bad_cert()) {
LOG(LS_WARNING) << "Ignoring cert error while verifying cert chain";
ok = 1;
}
return ok;
}
bool OpenSSLAdapter::ConfigureTrustedRootCertificates(SSL_CTX* ctx) {
// Add the root cert that we care about to the SSL context
int count_of_added_certs = 0;
for (int i = 0; i < ARRAY_SIZE(kSSLCertCertificateList); i++) {
const unsigned char* cert_buffer = kSSLCertCertificateList[i];
size_t cert_buffer_len = kSSLCertCertificateSizeList[i];
X509* cert = d2i_X509(NULL, &cert_buffer,
checked_cast<long>(cert_buffer_len));
if (cert) {
int return_value = X509_STORE_add_cert(SSL_CTX_get_cert_store(ctx), cert);
if (return_value == 0) {
LOG(LS_WARNING) << "Unable to add certificate.";
} else {
count_of_added_certs++;
}
X509_free(cert);
}
}
return count_of_added_certs > 0;
}
SSL_CTX*
OpenSSLAdapter::SetupSSLContext() {
SSL_CTX* ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
DTLSv1_client_method() : TLSv1_client_method());
if (ctx == NULL) {
unsigned long error = ERR_get_error(); // NOLINT: type used by OpenSSL.
LOG(LS_WARNING) << "SSL_CTX creation failed: "
<< '"' << ERR_reason_error_string(error) << "\" "
<< "(error=" << error << ')';
return NULL;
}
if (!ConfigureTrustedRootCertificates(ctx)) {
SSL_CTX_free(ctx);
return NULL;
}
#ifdef _DEBUG
SSL_CTX_set_info_callback(ctx, SSLInfoCallback);
#endif
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, SSLVerifyCallback);
SSL_CTX_set_verify_depth(ctx, 4);
SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
if (ssl_mode_ == SSL_MODE_DTLS) {
SSL_CTX_set_read_ahead(ctx, 1);
}
return ctx;
}
} // namespace rtc
#endif // HAVE_OPENSSL_SSL_H
| bsd-3-clause |
hybridgroup/ruby-opencv | test/test_mouseevent.rb | 371 | #!/usr/bin/env ruby
# -*- mode: ruby; coding: utf-8 -*-
require 'test/unit'
require 'opencv'
require File.expand_path(File.dirname(__FILE__)) + '/helper'
include OpenCV
include GUI
# Tests for OpenCV::MouseEvent
class TestMouseEvent < OpenCVTestCase
def test_initialize
assert_not_nil(MouseEvent.new)
assert_equal(MouseEvent, MouseEvent.new.class)
end
end
| bsd-3-clause |
msf-oca-his/dhis2-core | dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/query/Order.java | 7317 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.query;
import java.util.Date;
import java.util.Objects;
import javax.annotation.Nonnull;
import org.hisp.dhis.schema.Property;
import org.hisp.dhis.system.util.ReflectionUtils;
import com.google.common.base.MoreObjects;
/**
* @author Morten Olav Hansen <mortenoh@gmail.com>
*/
public class Order
{
private Direction direction;
private boolean ignoreCase;
private Property property;
public Order( Property property, Direction direction )
{
this.property = property;
this.direction = direction;
}
public Order ignoreCase()
{
this.ignoreCase = true;
return this;
}
public boolean isAscending()
{
return Direction.ASCENDING == direction;
}
public boolean isIgnoreCase()
{
return ignoreCase;
}
public Property getProperty()
{
return property;
}
public boolean isPersisted()
{
return property.isPersisted() && property.isSimple();
}
public boolean isNonPersisted()
{
return !property.isPersisted() && property.isSimple();
}
public int compare( Object lside, Object rside )
{
Object o1 = ReflectionUtils.invokeMethod( lside, property.getGetterMethod() );
Object o2 = ReflectionUtils.invokeMethod( rside, property.getGetterMethod() );
if ( o1 == o2 )
{
return 0;
}
// for null values use the same order like PostgreSQL in order to have
// same effect like DB ordering
// (NULLs are greater than other values)
if ( o1 == null || o2 == null )
{
if ( o1 == null )
{
return isAscending() ? 1 : -1;
}
return isAscending() ? -1 : 1;
}
if ( String.class.isInstance( o1 ) && String.class.isInstance( o2 ) )
{
String value1 = ignoreCase ? ((String) o1).toLowerCase() : (String) o1;
String value2 = ignoreCase ? ((String) o2).toLowerCase() : (String) o2;
return isAscending() ? value1.compareTo( value2 ) : value2.compareTo( value1 );
}
if ( Boolean.class.isInstance( o1 ) && Boolean.class.isInstance( o2 ) )
{
return isAscending() ? ((Boolean) o1).compareTo( (Boolean) o2 ) : ((Boolean) o2).compareTo( (Boolean) o1 );
}
else if ( Integer.class.isInstance( o1 ) && Integer.class.isInstance( o2 ) )
{
return isAscending() ? ((Integer) o1).compareTo( (Integer) o2 ) : ((Integer) o2).compareTo( (Integer) o1 );
}
else if ( Float.class.isInstance( o1 ) && Float.class.isInstance( o2 ) )
{
return isAscending() ? ((Float) o1).compareTo( (Float) o2 ) : ((Float) o2).compareTo( (Float) o1 );
}
else if ( Double.class.isInstance( o1 ) && Double.class.isInstance( o2 ) )
{
return isAscending() ? ((Double) o1).compareTo( (Double) o2 ) : ((Double) o2).compareTo( (Double) o1 );
}
else if ( Date.class.isInstance( o1 ) && Date.class.isInstance( o2 ) )
{
return isAscending() ? ((Date) o1).compareTo( (Date) o2 ) : ((Date) o2).compareTo( (Date) o1 );
}
else if ( Enum.class.isInstance( o1 ) && Enum.class.isInstance( o2 ) )
{
return isAscending() ? String.valueOf( o1 ).compareTo( String.valueOf( o2 ) )
: String.valueOf( o2 ).compareTo( String.valueOf( o1 ) );
}
return 0;
}
public static Order asc( Property property )
{
return new Order( property, Direction.ASCENDING );
}
public static Order iasc( Property property )
{
return new Order( property, Direction.ASCENDING ).ignoreCase();
}
public static Order desc( Property property )
{
return new Order( property, Direction.DESCENDING );
}
public static Order idesc( Property property )
{
return new Order( property, Direction.DESCENDING ).ignoreCase();
}
public static Order from( String direction, Property property )
{
switch ( direction )
{
case "asc":
return Order.asc( property );
case "iasc":
return Order.iasc( property );
case "desc":
return Order.desc( property );
case "idesc":
return Order.idesc( property );
default:
return Order.asc( property );
}
}
@Override
public int hashCode()
{
return Objects.hash( direction, ignoreCase, property );
}
@Override
public boolean equals( Object obj )
{
if ( this == obj )
{
return true;
}
if ( obj == null || getClass() != obj.getClass() )
{
return false;
}
final Order other = (Order) obj;
return Objects.equals( this.direction, other.direction )
&& Objects.equals( this.ignoreCase, other.ignoreCase )
&& Objects.equals( this.property, other.property );
}
/**
* @return the order string (e.g. <code>name:iasc</code>).
*/
@Nonnull
public String toOrderString()
{
final StringBuilder sb = new StringBuilder( property.getName() );
sb.append( ':' );
if ( isIgnoreCase() )
{
sb.append( 'i' );
}
sb.append( isAscending() ? "asc" : "desc" );
return sb.toString();
}
@Override
public String toString()
{
return MoreObjects.toStringHelper( this )
.add( "direction", direction )
.add( "ignoreCase", ignoreCase )
.add( "property", property )
.toString();
}
}
| bsd-3-clause |
yungsters/rain-workload-toolkit | src/radlab/rain/workload/rubbos/StoreStoryOperation.java | 4535 | /*
* Copyright (c) 2010, Regents of the University of California
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of California, Berkeley
* nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Author: Marco Guazzone (marco.guazzone@gmail.com), 2013.
*/
package radlab.rain.workload.rubbos;
import java.io.IOException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import radlab.rain.IScoreboard;
import radlab.rain.workload.rubbos.model.RubbosStory;
import radlab.rain.workload.rubbos.model.RubbosUser;
/**
* Store-Story operation.
*
* @author <a href="mailto:marco.guazzone@gmail.com">Marco Guazzone</a>
*/
public class StoreStoryOperation extends RubbosOperation
{
private static final int MAX_STORY_SUBJECT_LENGTH = 100;
public StoreStoryOperation(boolean interactive, IScoreboard scoreboard)
{
super(interactive, scoreboard);
this._operationName = "Store-Story";
this._operationIndex = RubbosGenerator.STORE_STORY_OP;
}
@Override
public void execute() throws Throwable
{
// Need a logged user
RubbosUser loggedUser = this.getUtility().getUser(this.getSessionState().getLoggedUserId());
if (!this.getUtility().isRegisteredUser(loggedUser))
{
this.getLogger().warning("No valid user has been found to log-in. Operation interrupted.");
this.setFailed(true);
return;
}
// Retrieve the story to post in the last HTML response
final String lastResponse = this.getSessionState().getLastResponse();
RubbosStory story = this.getUtility().newStory();
int[] pos = this.getUtility().findRandomLastIndexInHtml(lastResponse, "OPTION value=\"", false, false);
if (pos == null)
{
this.getLogger().warning("No 'category' parameter has been found in the last HTML response. Last response is: " + this.getSessionState().getLastResponse() + ". Operation interrupted.");
this.setFailed(true);
return;
}
story.category = Integer.parseInt(lastResponse.substring(pos[0], pos[1]));
// Post the story
StringBuilder response = null;
URIBuilder uri = new URIBuilder(this.getGenerator().getStoreStoryURL());
uri.setParameter("nickname", loggedUser.nickname);
uri.setParameter("password", loggedUser.password);
uri.setParameter("category", Integer.toString(story.category));
uri.setParameter("title", story.title);
uri.setParameter("body", story.body);
HttpGet reqGet = new HttpGet(uri.build());
response = this.getHttpTransport().fetch(reqGet);
this.trace(reqGet.getURI().toString());
if (!this.getGenerator().checkHttpResponse(response.toString()))
{
this.getLogger().severe("Problems in performing request to URL: " + reqGet.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "). Server response: " + response);
throw new IOException("Problems in performing request to URL: " + reqGet.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")");
}
// Save session data
this.getSessionState().setLastResponse(response.toString());
this.setFailed(!this.getUtility().checkRubbosResponse(response.toString()));
}
}
| bsd-3-clause |
hispindia/dhis2-Core | dhis-2/dhis-services/dhis-service-dxf2/src/test/java/org/hisp/dhis/dxf2/metadata/objectbundle/validation/DummyCheck.java | 3065 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.dxf2.metadata.objectbundle.validation;
import static org.hisp.dhis.dxf2.metadata.objectbundle.validation.ValidationUtils.createObjectReport;
import java.util.List;
import java.util.function.Consumer;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundle;
import org.hisp.dhis.feedback.ErrorCode;
import org.hisp.dhis.feedback.ErrorReport;
import org.hisp.dhis.feedback.ObjectReport;
import org.hisp.dhis.importexport.ImportStrategy;
/**
* @author Luciano Fiandesio
*/
public class DummyCheck implements ObjectValidationCheck
{
@Override
public <T extends IdentifiableObject> void check( ObjectBundle bundle, Class<T> klass,
List<T> persistedObjects, List<T> nonPersistedObjects,
ImportStrategy importStrategy, ValidationContext context, Consumer<ObjectReport> addReports )
{
for ( T nonPersistedObject : nonPersistedObjects )
{
if ( nonPersistedObject.getUid().startsWith( "u" ) )
{
ErrorReport errorReport = new ErrorReport( klass, ErrorCode.E5000, bundle.getPreheatIdentifier(),
bundle.getPreheatIdentifier().getIdentifiersWithName( nonPersistedObject ) )
.setMainId( nonPersistedObject.getUid() );
addReports.accept( createObjectReport( errorReport, nonPersistedObject, bundle ) );
context.markForRemoval( nonPersistedObject );
}
}
}
}
| bsd-3-clause |
hybridgroup/alljoyn | alljoyn/alljoyn_core/samples/windows/PhotoChat/AllJoynNET/AlljoynConnectForm.cs | 4669 | // ****************************************************************************
// Copyright (c) 2011, AllSeen Alliance. All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
// ******************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace AllJoynNET {
/// <summary>
/// a Windows Form for Connecting to the AllJoyn bus
/// </summary>
public partial class AllJoynConnectForm : Form {
#region Constructors
public AllJoynConnectForm() : this(new AllJoynBus(), null) { }
public AllJoynConnectForm(AllJoynBus bus, Form owner)
{
_ajBus = bus;
_owner = owner;
InitializeComponent();
this.Hide();
}
#endregion
#region Properties
public bool IsConnected { get { return _connected; } set { _connected = value; } }
public string SessionName { get { return txtSession.Text; } }
public string MyHandle { get { return txtHandle.Text; } }
public bool IsNameOwner { get { return rbAdvertise.Checked; } }
public AllJoynBus AJBus { get { return _ajBus; } }
public AllJoynSession AJSession { get { return _session; } }
#endregion
#region shared methods
/// <summary>
/// This function must be called before displaying the form.
/// </summary>
/// <param name="receiver">a ReceiverDelegate for handling output from the AllJoynBusConnection</param>
/// <param name="subscribe">a SubscriberDelegate that will handle adding "joiners" to the session"</param>
/// <returns></returns>
public bool InstallDelegates(ReceiverDelegate receiver, SubscriberDelegate subscribe)
{
if (_ajBus != null) {
_ajBus.SetOutputStream(receiver);
_ajBus.SetLocalListener(subscribe);
return true;
}
// else do notning
return false;
}
/// <summary>
/// override to update any local changes
/// </summary>
/// <param name="e">unused - passed to base class</param>
protected override void OnShown(EventArgs e)
{
updateUI();
base.OnShown(e);
}
#endregion
#region private variables
private Form _owner = null;
private bool _connected = false;
private AllJoynBus _ajBus;
private AllJoynSession _session;
#endregion
#region private methods
/// <summary>
/// PRIVATE update form fields when visible
/// </summary>
private void updateUI()
{
if (IsConnected) {
btnConnect.Text = "Disconnect";
txtSession.Enabled = false;
txtHandle.Enabled = false;
rbAdvertise.Enabled = false;
rbJoin.Enabled = false;
} else {
btnConnect.Text = "Connect";
txtSession.Enabled = true;
txtHandle.Enabled = true;
rbAdvertise.Enabled = true;
rbJoin.Enabled = true;
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
if (!_connected) {
if (checkInvariants()) {
bool success = rbAdvertise.Checked;
_connected = _ajBus.Connect(txtHandle.Text, ref success);
} else
MessageBox.Show("Missing input - handle or session names must not be empty",
"AllJoyn Connection", MessageBoxButtons.OK, MessageBoxIcon.Hand);
} else {
_ajBus.Disconnect();
_connected = false;
}
updateUI();
}
private bool checkInvariants()
{
return ((txtHandle.Text.Length > 0) && (txtSession.Text.Length > 0));
}
#endregion
}
}
| isc |
andybest/ShaderFiddle | ShaderFiddle/ace/ext-whitespace.js | 6877 | /* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
define('ace/ext/whitespace', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) {
var lang = require("../lib/lang");
exports.$detectIndentation = function(lines, fallback) {
var stats = [];
var changes = [];
var tabIndents = 0;
var prevSpaces = 0;
var max = Math.min(lines.length, 1000);
for (var i = 0; i < max; i++) {
var line = lines[i];
if (!/^\s*[^*+\-\s]/.test(line))
continue;
var tabs = line.match(/^\t*/)[0].length;
if (line[0] == "\t")
tabIndents++;
var spaces = line.match(/^ */)[0].length;
if (spaces && line[spaces] != "\t") {
var diff = spaces - prevSpaces;
if (diff > 0 && !(prevSpaces%diff) && !(spaces%diff))
changes[diff] = (changes[diff] || 0) + 1;
stats[spaces] = (stats[spaces] || 0) + 1;
}
prevSpaces = spaces;
while (i < max && line[line.length - 1] == "\\")
line = lines[i++];
}
if (!stats.length)
return;
function getScore(indent) {
var score = 0;
for (var i = indent; i < stats.length; i += indent)
score += stats[i] || 0;
return score;
}
var changesTotal = changes.reduce(function(a,b){return a+b}, 0);
var first = {score: 0, length: 0};
var spaceIndents = 0;
for (var i = 1; i < 12; i++) {
if (i == 1) {
spaceIndents = getScore(i);
var score = 1;
} else
var score = getScore(i) / spaceIndents;
if (changes[i])
score += changes[i] / changesTotal;
if (score > first.score)
first = {score: score, length: i};
}
if (first.score && first.score > 1.4)
var tabLength = first.length;
if (tabIndents > spaceIndents + 1)
return {ch: "\t", length: tabLength};
if (spaceIndents + 1 > tabIndents)
return {ch: " ", length: tabLength};
};
exports.detectIndentation = function(session) {
var lines = session.getLines(0, 1000);
var indent = exports.$detectIndentation(lines) || {};
if (indent.ch)
session.setUseSoftTabs(indent.ch == " ");
if (indent.length)
session.setTabSize(indent.length);
return indent;
};
exports.trimTrailingSpace = function(session, trimEmpty) {
var doc = session.getDocument();
var lines = doc.getAllLines();
var min = trimEmpty ? -1 : 0;
for (var i = 0, l=lines.length; i < l; i++) {
var line = lines[i];
var index = line.search(/\s+$/);
if (index > min)
doc.removeInLine(i, index, line.length);
}
};
exports.convertIndentation = function(session, ch, len) {
var oldCh = session.getTabString()[0];
var oldLen = session.getTabSize();
if (!len) len = oldLen;
if (!ch) ch = oldCh;
var tab = ch == "\t" ? ch: lang.stringRepeat(ch, len);
var doc = session.doc;
var lines = doc.getAllLines();
var cache = {};
var spaceCache = {};
for (var i = 0, l=lines.length; i < l; i++) {
var line = lines[i];
var match = line.match(/^\s*/)[0];
if (match) {
var w = session.$getStringScreenWidth(match)[0];
var tabCount = Math.floor(w/oldLen);
var reminder = w%oldLen;
var toInsert = cache[tabCount] || (cache[tabCount] = lang.stringRepeat(tab, tabCount));
toInsert += spaceCache[reminder] || (spaceCache[reminder] = lang.stringRepeat(" ", reminder));
if (toInsert != match) {
doc.removeInLine(i, 0, match.length);
doc.insertInLine({row: i, column: 0}, toInsert);
}
}
}
session.setTabSize(len);
session.setUseSoftTabs(ch == " ");
};
exports.$parseStringArg = function(text) {
var indent = {};
if (/t/.test(text))
indent.ch = "\t";
else if (/s/.test(text))
indent.ch = " ";
var m = text.match(/\d+/);
if (m)
indent.length = parseInt(m[0], 10);
return indent;
};
exports.$parseArg = function(arg) {
if (!arg)
return {};
if (typeof arg == "string")
return exports.$parseStringArg(arg);
if (typeof arg.text == "string")
return exports.$parseStringArg(arg.text);
return arg;
};
exports.commands = [{
name: "detectIndentation",
exec: function(editor) {
exports.detectIndentation(editor.session);
}
}, {
name: "trimTrailingSpace",
exec: function(editor) {
exports.trimTrailingSpace(editor.session);
}
}, {
name: "convertIndentation",
exec: function(editor, arg) {
var indent = exports.$parseArg(arg);
exports.convertIndentation(editor.session, indent.ch, indent.length);
}
}, {
name: "setIndentation",
exec: function(editor, arg) {
var indent = exports.$parseArg(arg);
indent.length && editor.session.setTabSize(indent.length);
indent.ch && editor.session.setUseSoftTabs(indent.ch == " ");
}
}];
});
;
(function() {
window.require(["ace/ext/whitespace"], function() {});
})();
| isc |
sujaypatel16/fear-the-repo | src/store/configureStore.js | 1059 | import rootReducer from '../reducers';
import thunk from 'redux-thunk';
import routes from '../routes';
import { reduxReactRouter } from 'redux-router';
import createHistory from 'history/lib/createBrowserHistory';
import DevTools from 'containers/DevTools';
import { applyMiddleware, compose, createStore } from 'redux';
export default function configureStore (initialState, debug = false) {
let createStoreWithMiddleware;
const middleware = applyMiddleware(thunk);
if (debug) {
createStoreWithMiddleware = compose(
middleware,
reduxReactRouter({ routes, createHistory }),
DevTools.instrument()
);
} else {
createStoreWithMiddleware = compose(
middleware,
reduxReactRouter({ routes, createHistory })
);
}
const store = createStoreWithMiddleware(createStore)(
rootReducer, initialState
);
if (module.hot) {
module.hot.accept('../reducers', () => {
const nextRootReducer = require('../reducers/index');
store.replaceReducer(nextRootReducer);
});
}
return store;
}
| mit |
gurkanuzunca/sirius-ci | admin/language/en/form_validation_lang.php | 793 | <?php
$lang['required'] = "%s";
$lang['isset'] = "%s";
$lang['valid_email'] = "%s";
$lang['valid_emails'] = "%s";
$lang['valid_url'] = "%s";
$lang['valid_ip'] = "%s";
$lang['min_length'] = "%s";
$lang['max_length'] = "%s";
$lang['exact_length'] = "%s";
$lang['alpha'] = "%s";
$lang['alpha_numeric'] = "%s";
$lang['alpha_dash'] = "%s";
$lang['numeric'] = "%s";
$lang['is_numeric'] = "%s";
$lang['integer'] = "%s";
$lang['regex_match'] = "%s";
$lang['matches'] = "%s";
$lang['is_unique'] = "%s";
$lang['is_natural'] = "%s";
$lang['is_natural_no_zero'] = "%s";
$lang['decimal'] = "%s";
$lang['less_than'] = "%s";
$lang['greater_than'] = "%s";
/* End of file form_validation_lang.php */
/* Location: ./system/language/english/form_validation_lang.php */ | mit |
andrewchart/andrewchart.co.uk-2017 | wp-content/plugins/types/library/toolset/toolset-common/toolset-forms/classes/class.fieldconfig.php | 6657 | <?php
/**
*
*
*/
if (!class_exists("FieldConfig")) {
/**
* Description of FieldConfig
*
* @author ontheGoSystem
*/
class FieldConfig {
private $id;
private $name = "cred[post_title]";
private $value;
private $type = 'textfield';
private $title = 'Post title';
private $repetitive = false;
private $display = '';
private $description = '';
private $config = array();
private $options = array();
private $default_value = '';
private $validation = array();
private $attr;
private $add_time = false;
private $form_settings;
public function __construct() {
}
public function getForm_settings() {
return $this->form_settings;
}
public function setForm_settings($form_settings) {
$this->form_settings = $form_settings;
}
public function setRepetitive($repetitive) {
$this->repetitive = $repetitive;
}
public function isRepetitive() {
return $this->repetitive;
}
public function set_add_time($addtime) {
$this->add_time = $addtime;
}
public function setAttr($attr) {
$this->attr = $attr;
}
public function getAttr() {
return $this->attr;
}
public function setDefaultValue($value) {
$this->default_value = $value;
}
public function setOptions($name, $type, $values, $attrs) {
$arr = array();
switch ($type) {
case 'checkbox':
$arr = $attrs;
break;
case 'checkboxes':
$actual_titles = isset($attrs['actual_titles']) ? $attrs['actual_titles'] : array();
foreach ($actual_titles as $refvalue => $title) {
$_value = $attrs['actual_values'][$refvalue];
$arr[$refvalue] = array('value' => $refvalue, 'title' => $title, 'name' => $name, 'data-value' => $_value);
if (in_array($refvalue, $attrs['default'])) {
$arr[$refvalue]['checked'] = true;
}
}
break;
case 'select':
$values = isset($attrs['options']) ? $attrs['options'] : array();
foreach ($values as $refvalue => $title) {
$arr[$refvalue] = array(
'value' => $refvalue,
'title' => $title,
'types-value' => $attrs['actual_options'][$refvalue],
);
}
break;
case 'radios':
$actual_titles = isset($attrs['actual_titles']) ? $attrs['actual_titles'] : array();
foreach ($actual_titles as $refvalue => $title) {
$arr[$refvalue] = array(
'value' => $attrs['actual_values'][$refvalue],
'title' => $title,
'checked' => false,
'name' => $refvalue,
'types-value' => $refvalue,
);
}
break;
default:
return;
break;
}
$this->options = $arr;
}
public function createConfig() {
$base_name = "cred";
$this->config = array(
'id' => $this->getId(),
'type' => $this->getType(),
'title' => $this->getTitle(),
'options' => $this->getOptions(),
'default_value' => $this->getDefaultValue(),
'description' => $this->getDescription(),
'repetitive' => $this->isRepetitive(),
/* 'name' => $base_name."[".$this->getType()."]", */
'name' => $this->getName(),
'value' => $this->getValue(),
'add_time' => $this->getAddTime(),
'validation' => array(),
'display' => $this->getDisplay(),
'attribute' => $this->getAttr(),
'form_settings' => $this->getForm_settings()
);
return $this->config;
}
public function getAddTime() {
return $this->add_time;
}
public function getType() {
return $this->type;
}
public function setType($type) {
$this->type = $type;
}
public function getOptions() {
return $this->options;
}
public function getDefaultValue() {
return $this->default_value;
}
public function getTitle() {
return $this->title;
}
public function getDisplay() {
return $this->display;
}
public function setTitle($title) {
$this->title = $title;
}
public function getDescription() {
return $this->description;
}
public function setDescription($description) {
$this->description = $description;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getValue() {
return $this->value;
}
public function setValue($value) {
$this->value = $value;
}
public function getValidation() {
return !empty($this->validation) ? $this->validation : array();
}
public function setValidation($validation) {
$this->validation = $validation;
}
public function getConfig() {
return $this->config;
}
public function setConfig($config) {
$this->config = $config;
}
public function getId() {
return $this->id;
}
public function setId($id) {
$this->id = $id;
}
public function setDisplay($display) {
$this->display = $display;
}
}
}
| mit |
Qinjianbo/blog | node_modules/caniuse-lite/data/features/css-text-spacing.js | 849 | module.exports={A:{A:{"2":"H D fB","161":"G E A B"},B:{"161":"1 C p J L N I"},C:{"2":"0 1 2 3 5 6 7 8 9 dB FB F K H D G E A B C p J L N I O P Q R S T U V W X Y Z a b d e f g h i j k l m n o M q r s t u v w x y z BB CB DB bB VB"},D:{"2":"0 1 2 3 5 6 7 8 9 F K H D G E A B C p J L N I O P Q R S T U V W X Y Z a b d e f g h i j k l m n o M q r s t u v w x y z BB CB DB GB PB KB IB gB LB MB NB"},E:{"2":"F K H D G E A B C OB HB QB RB SB TB UB c WB"},F:{"2":"0 3 E B C J L N I O P Q R S T U V W X Y Z a b d e f g h i j k l m n o M q r s t u v w x y z XB YB ZB aB c EB cB AB"},G:{"2":"4 G HB eB JB hB iB jB kB lB mB nB oB pB qB"},H:{"2":"rB"},I:{"2":"4 FB F GB sB tB uB vB wB xB"},J:{"2":"D A"},K:{"2":"A B C M c EB AB"},L:{"2":"IB"},M:{"2":"2"},N:{"16":"A B"},O:{"2":"yB"},P:{"2":"F K zB 0B"},Q:{"2":"1B"},R:{"2":"2B"}},B:5,C:"CSS Text 4 text-spacing"};
| mit |
JakduK/JakduK | src/main/java/com/jakduk/api/service/SearchService.java | 17159 | package com.jakduk.api.service;
import com.jakduk.api.common.Constants;
import com.jakduk.api.common.util.ObjectMapperUtils;
import com.jakduk.api.common.util.UrlGenerationUtils;
import com.jakduk.api.configuration.JakdukProperties;
import com.jakduk.api.exception.ServiceError;
import com.jakduk.api.exception.ServiceException;
import com.jakduk.api.model.elasticsearch.*;
import com.jakduk.api.restcontroller.vo.board.BoardGallerySimple;
import com.jakduk.api.restcontroller.vo.search.*;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.MultiSearchRequestBuilder;
import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.InnerHitBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.join.query.JoinQueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author <a href="mailto:phjang1983@daum.net">Jang,Pyohwan</a>
*/
@Service
public class SearchService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Resource private JakdukProperties.Elasticsearch elasticsearchProperties;
@Autowired private UrlGenerationUtils urlGenerationUtils;
@Autowired private Client client;
/**
* 통합 검색
*
* @param query 검색어
* @param from 페이지 시작 위치
* @param size 페이지 크기
* @return 검색 결과
*/
public SearchUnifiedResponse searchUnified(String query, String include, Integer from, Integer size, String preTags,
String postTags) {
SearchUnifiedResponse searchUnifiedResponse = new SearchUnifiedResponse();
Queue<Constants.SEARCH_INCLUDE_TYPE> searchOrder = new LinkedList<>();
MultiSearchRequestBuilder multiSearchRequestBuilder = client.prepareMultiSearch();
if (StringUtils.contains(include, Constants.SEARCH_INCLUDE_TYPE.ARTICLE.name())) {
SearchRequestBuilder searchRequestBuilder = getArticleSearchRequestBuilder(query, from, size, preTags, postTags);
multiSearchRequestBuilder.add(searchRequestBuilder);
searchOrder.offer(Constants.SEARCH_INCLUDE_TYPE.ARTICLE);
}
if (StringUtils.contains(include, Constants.SEARCH_INCLUDE_TYPE.COMMENT.name())) {
SearchRequestBuilder searchRequestBuilder = getCommentSearchRequestBuilder(query, from, size, preTags, postTags);
multiSearchRequestBuilder.add(searchRequestBuilder);
searchOrder.offer(Constants.SEARCH_INCLUDE_TYPE.COMMENT);
}
if (StringUtils.contains(include, Constants.SEARCH_INCLUDE_TYPE.GALLERY.name())) {
SearchRequestBuilder searchRequestBuilder = getGallerySearchRequestBuilder(query, from, size < 10 ? 4 : size, preTags, postTags);
multiSearchRequestBuilder.add(searchRequestBuilder);
searchOrder.offer(Constants.SEARCH_INCLUDE_TYPE.GALLERY);
}
MultiSearchResponse multiSearchResponse = multiSearchRequestBuilder.execute().actionGet();
for (MultiSearchResponse.Item item : multiSearchResponse.getResponses()) {
SearchResponse searchResponse = item.getResponse();
Constants.SEARCH_INCLUDE_TYPE order = searchOrder.poll();
if (item.isFailure())
continue;
if (! ObjectUtils.isEmpty(order)) {
switch (order) {
case ARTICLE:
SearchArticleResult searchArticleResult = getArticleSearchResponse(searchResponse);
searchUnifiedResponse.setArticleResult(searchArticleResult);
break;
case COMMENT:
SearchCommentResult searchCommentResult = getCommentSearchResponse(searchResponse);
searchUnifiedResponse.setCommentResult(searchCommentResult);
break;
case GALLERY:
SearchGalleryResult searchGalleryResult = getGallerySearchResponse(searchResponse);
searchUnifiedResponse.setGalleryResult(searchGalleryResult);
break;
}
}
}
return searchUnifiedResponse;
}
public PopularSearchWordResult aggregateSearchWord(LocalDate gteDate, Integer size) {
SearchRequestBuilder searchRequestBuilder = client.prepareSearch()
.setIndices(elasticsearchProperties.getIndexSearchWord())
.setTypes(Constants.ES_TYPE_SEARCH_WORD)
.setSize(0)
.setQuery(
QueryBuilders.rangeQuery("registerDate").gte(gteDate.toString())
)
.addAggregation(
AggregationBuilders
.terms("popular_word_aggs")
.field("word")
.size(size)
);
log.debug("aggregateSearchWord Query:\n{}", searchRequestBuilder);
SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
Terms popularWordTerms = searchResponse.getAggregations().get("popular_word_aggs");
List<EsTermsBucket> popularWords = popularWordTerms.getBuckets().stream()
.map(entry -> {
EsTermsBucket esTermsBucket = new EsTermsBucket();
esTermsBucket.setKey(entry.getKeyAsString());
esTermsBucket.setCount(entry.getDocCount());
return esTermsBucket;
})
.collect(Collectors.toList());
return new PopularSearchWordResult() {{
setTook(searchResponse.getTook().getMillis());
setPopularSearchWords(popularWords);
}};
}
public void indexDocumentArticle(EsArticle esArticle) {
String id = esArticle.getId();
try {
IndexResponse response = client.prepareIndex()
.setIndex(elasticsearchProperties.getIndexBoard())
.setType(Constants.ES_TYPE_ARTICLE)
.setId(id)
.setSource(ObjectMapperUtils.writeValueAsString(esArticle), XContentType.JSON)
.get();
} catch (IOException e) {
throw new ServiceException(ServiceError.ELASTICSEARCH_INDEX_FAILED, e.getCause());
}
}
public void deleteDocumentBoard(String id) {
DeleteResponse response = client.prepareDelete()
.setIndex(elasticsearchProperties.getIndexBoard())
.setType(Constants.ES_TYPE_ARTICLE)
.setId(id)
.get();
if (! response.status().equals(RestStatus.OK))
log.info("board id {} is not found. so can't delete it!", id);
}
public void indexDocumentBoardComment(EsComment esComment) {
String id = esComment.getId();
String parentBoardId = esComment.getArticle().getId();
try {
IndexResponse response = client.prepareIndex()
.setIndex(elasticsearchProperties.getIndexBoard())
.setType(Constants.ES_TYPE_COMMENT)
.setId(id)
.setParent(parentBoardId)
.setSource(ObjectMapperUtils.writeValueAsString(esComment), XContentType.JSON)
.get();
} catch (IOException e) {
throw new ServiceException(ServiceError.ELASTICSEARCH_INDEX_FAILED, e.getCause());
}
}
public void deleteDocumentBoardComment(String id) {
DeleteResponse response = client.prepareDelete()
.setIndex(elasticsearchProperties.getIndexBoard())
.setType(Constants.ES_TYPE_COMMENT)
.setId(id)
.get();
if (! response.status().equals(RestStatus.OK))
log.info("comment id {} is not found. so can't delete it!", id);
}
// TODO : 구현 해야 함
public void createDocumentJakduComment(EsJakduComment EsJakduComment) {}
public void indexDocumentGallery(EsGallery esGallery) {
String id = esGallery.getId();
try {
IndexResponse response = client.prepareIndex()
.setIndex(elasticsearchProperties.getIndexGallery())
.setType(Constants.ES_TYPE_GALLERY)
.setId(id)
.setSource(ObjectMapperUtils.writeValueAsString(esGallery), XContentType.JSON)
.get();
} catch (IOException e) {
throw new ServiceException(ServiceError.ELASTICSEARCH_INDEX_FAILED, e.getCause());
}
}
public void deleteDocumentGallery(String id) {
DeleteResponse response = client.prepareDelete()
.setIndex(elasticsearchProperties.getIndexGallery())
.setType(Constants.ES_TYPE_GALLERY)
.setId(id)
.get();
if (! response.status().equals(RestStatus.OK))
log.info("gallery id {} is not found. so can't delete it!", id);
}
public void indexDocumentSearchWord(EsSearchWord esSearchWord) {
try {
IndexRequestBuilder indexRequestBuilder = client.prepareIndex();
IndexResponse response = indexRequestBuilder
.setIndex(elasticsearchProperties.getIndexSearchWord())
.setType(Constants.ES_TYPE_SEARCH_WORD)
.setSource(ObjectMapperUtils.writeValueAsString(esSearchWord), XContentType.JSON)
.get();
log.debug("indexDocumentSearchWord Source:\n {}", indexRequestBuilder.request().getDescription());
} catch (IOException e) {
throw new ServiceException(ServiceError.ELASTICSEARCH_INDEX_FAILED, e.getCause());
}
}
private SearchRequestBuilder getArticleSearchRequestBuilder(String query, Integer from, Integer size, String preTags,
String postTags) {
HighlightBuilder highlightBuilder = new HighlightBuilder()
.noMatchSize(Constants.SEARCH_NO_MATCH_SIZE)
.fragmentSize(Constants.SEARCH_FRAGMENT_SIZE)
.field("subject", Constants.SEARCH_FRAGMENT_SIZE, 0)
.field("content", Constants.SEARCH_FRAGMENT_SIZE, 1);
SearchRequestBuilder searchRequestBuilder = client.prepareSearch()
.setIndices(elasticsearchProperties.getIndexBoard())
.setTypes(Constants.ES_TYPE_ARTICLE)
.setFetchSource(null, new String[]{"subject", "content"})
.setQuery(
QueryBuilders.boolQuery()
.should(QueryBuilders.multiMatchQuery(query, "subject", "content").field("subject", 1.5f))
)
.setFrom(from)
.setSize(size);
if (StringUtils.isNotBlank(preTags))
highlightBuilder.preTags(preTags);
if (StringUtils.isNotBlank(postTags))
highlightBuilder.postTags(postTags);
searchRequestBuilder.highlighter(highlightBuilder);
log.debug("getArticleSearchRequestBuilder Query:\n{}", searchRequestBuilder);
return searchRequestBuilder;
}
private SearchArticleResult getArticleSearchResponse(SearchResponse searchResponse) {
SearchHits searchHits = searchResponse.getHits();
List<ArticleSource> searchList = Arrays.stream(searchHits.getHits())
.map(searchHit -> {
Map<String, Object> sourceMap = searchHit.getSourceAsMap();
EsArticleSource esArticleSource = ObjectMapperUtils.convertValue(sourceMap, EsArticleSource.class);
esArticleSource.setScore(searchHit.getScore());
Map<String, List<String>> highlight = this.getHighlight(searchHit.getHighlightFields().entrySet());
esArticleSource.setHighlight(highlight);
return esArticleSource;
})
.map(esArticleSource -> {
ArticleSource articleSource = new ArticleSource();
BeanUtils.copyProperties(esArticleSource, articleSource);
if (! ObjectUtils.isEmpty(esArticleSource.getGalleries())) {
List<BoardGallerySimple> boardGalleries = esArticleSource.getGalleries().stream()
.sorted(Comparator.comparing(String::toString))
.limit(1)
.map(galleryId -> new BoardGallerySimple() {{
setId(galleryId);
setThumbnailUrl(urlGenerationUtils.generateGalleryUrl(Constants.IMAGE_SIZE_TYPE.SMALL, galleryId));
}})
.collect(Collectors.toList());
articleSource.setGalleries(boardGalleries);
}
return articleSource;
})
.collect(Collectors.toList());
return new SearchArticleResult() {{
setTook(searchResponse.getTook().getMillis());
setTotalCount(searchHits.getTotalHits());
setArticles(searchList);
}};
}
private SearchRequestBuilder getCommentSearchRequestBuilder(String query, Integer from, Integer size, String preTags,
String postTags) {
HighlightBuilder highlightBuilder = new HighlightBuilder()
.noMatchSize(Constants.SEARCH_NO_MATCH_SIZE)
.fragmentSize(Constants.SEARCH_FRAGMENT_SIZE)
.field("content", Constants.SEARCH_FRAGMENT_SIZE, 1);
SearchRequestBuilder searchRequestBuilder = client.prepareSearch()
.setIndices(elasticsearchProperties.getIndexBoard())
.setTypes(Constants.ES_TYPE_COMMENT)
.setFetchSource(null, new String[]{"content"})
.setQuery(
QueryBuilders.boolQuery()
.must(QueryBuilders.matchQuery("content", query))
.must(JoinQueryBuilders
.hasParentQuery(Constants.ES_TYPE_ARTICLE, QueryBuilders.matchAllQuery(), false)
.innerHit(new InnerHitBuilder())
)
)
.setFrom(from)
.setSize(size);
if (StringUtils.isNotBlank(preTags))
highlightBuilder.preTags(preTags);
if (StringUtils.isNotBlank(postTags))
highlightBuilder.postTags(postTags);
searchRequestBuilder.highlighter(highlightBuilder);
log.debug("getBoardCommentSearchRequestBuilder Query:\n{}", searchRequestBuilder);
return searchRequestBuilder;
}
private SearchCommentResult getCommentSearchResponse(SearchResponse searchResponse) {
SearchHits searchHits = searchResponse.getHits();
List<EsCommentSource> searchList = Arrays.stream(searchHits.getHits())
.map(searchHit -> {
Map<String, Object> sourceMap = searchHit.getSourceAsMap();
EsCommentSource esCommentSource = ObjectMapperUtils.convertValue(sourceMap, EsCommentSource.class);
esCommentSource.setScore(searchHit.getScore());
if (! searchHit.getInnerHits().isEmpty()) {
SearchHit[] innerSearchHits = searchHit.getInnerHits().get(Constants.ES_TYPE_ARTICLE).getHits();
Map<String, Object> innerSourceMap = innerSearchHits[ innerSearchHits.length - 1 ].getSourceAsMap();
EsParentArticle esParentArticle = ObjectMapperUtils.convertValue(innerSourceMap, EsParentArticle.class);
esCommentSource.setArticle(esParentArticle);
}
Map<String, List<String>> highlight = this.getHighlight(searchHit.getHighlightFields().entrySet());
esCommentSource.setHighlight(highlight);
return esCommentSource;
})
.collect(Collectors.toList());
return new SearchCommentResult() {{
setTook(searchResponse.getTook().getMillis());
setTotalCount(searchHits.getTotalHits());
setComments(searchList);
}};
}
private SearchRequestBuilder getGallerySearchRequestBuilder(String query, Integer from, Integer size, String preTags,
String postTags) {
HighlightBuilder highlightBuilder = new HighlightBuilder()
.noMatchSize(Constants.SEARCH_NO_MATCH_SIZE)
.fragmentSize(Constants.SEARCH_FRAGMENT_SIZE)
.field("name", Constants.SEARCH_FRAGMENT_SIZE, 0);
SearchRequestBuilder searchRequestBuilder = client.prepareSearch()
.setIndices(elasticsearchProperties.getIndexGallery())
.setTypes(Constants.ES_TYPE_GALLERY)
.setFetchSource(null, new String[]{"name"})
.setQuery(QueryBuilders.matchQuery("name", query))
.setFrom(from)
.setSize(size);
if (StringUtils.isNotBlank(preTags))
highlightBuilder.preTags(preTags);
if (StringUtils.isNotBlank(postTags))
highlightBuilder.postTags(postTags);
searchRequestBuilder.highlighter(highlightBuilder);
log.debug("getGallerySearchRequestBuilder Query:\n{}", searchRequestBuilder);
return searchRequestBuilder;
}
private SearchGalleryResult getGallerySearchResponse(SearchResponse searchResponse) {
SearchHits searchHits = searchResponse.getHits();
List<EsGallerySource> searchList = Arrays.stream(searchHits.getHits())
.map(searchHit -> {
Map<String, Object> sourceMap = searchHit.getSourceAsMap();
EsGallerySource esGallerySource = ObjectMapperUtils.convertValue(sourceMap, EsGallerySource.class);
esGallerySource.setScore(searchHit.getScore());
Map<String, List<String>> highlight = this.getHighlight(searchHit.getHighlightFields().entrySet());
esGallerySource.setHighlight(highlight);
return esGallerySource;
})
.collect(Collectors.toList());
return new SearchGalleryResult() {{
setTook(searchResponse.getTook().getMillis());
setTotalCount(searchHits.getTotalHits());
setGalleries(searchList);
}};
}
private Map<String, List<String>> getHighlight(Set<Map.Entry<String, HighlightField>> entrySet) {
Map<String, List<String>> highlight = new HashMap<>();
for (Map.Entry<String, HighlightField> highlightField : entrySet) {
List<String> fragments = new ArrayList<>();
for (Text text : highlightField.getValue().fragments()) {
fragments.add(text.string());
}
highlight.put(highlightField.getKey(), fragments);
}
return highlight;
}
}
| mit |
looeee/three.js | examples/jsm/postprocessing/UnrealBloomPass.js | 12447 | import {
AdditiveBlending,
Color,
LinearFilter,
MeshBasicMaterial,
RGBAFormat,
ShaderMaterial,
UniformsUtils,
Vector2,
Vector3,
WebGLRenderTarget
} from 'three';
import { Pass, FullScreenQuad } from './Pass.js';
import { CopyShader } from '../shaders/CopyShader.js';
import { LuminosityHighPassShader } from '../shaders/LuminosityHighPassShader.js';
/**
* UnrealBloomPass is inspired by the bloom pass of Unreal Engine. It creates a
* mip map chain of bloom textures and blurs them with different radii. Because
* of the weighted combination of mips, and because larger blurs are done on
* higher mips, this effect provides good quality and performance.
*
* Reference:
* - https://docs.unrealengine.com/latest/INT/Engine/Rendering/PostProcessEffects/Bloom/
*/
class UnrealBloomPass extends Pass {
constructor( resolution, strength, radius, threshold ) {
super();
this.strength = ( strength !== undefined ) ? strength : 1;
this.radius = radius;
this.threshold = threshold;
this.resolution = ( resolution !== undefined ) ? new Vector2( resolution.x, resolution.y ) : new Vector2( 256, 256 );
// create color only once here, reuse it later inside the render function
this.clearColor = new Color( 0, 0, 0 );
// render targets
const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
this.renderTargetsHorizontal = [];
this.renderTargetsVertical = [];
this.nMips = 5;
let resx = Math.round( this.resolution.x / 2 );
let resy = Math.round( this.resolution.y / 2 );
this.renderTargetBright = new WebGLRenderTarget( resx, resy, pars );
this.renderTargetBright.texture.name = 'UnrealBloomPass.bright';
this.renderTargetBright.texture.generateMipmaps = false;
for ( let i = 0; i < this.nMips; i ++ ) {
const renderTargetHorizonal = new WebGLRenderTarget( resx, resy, pars );
renderTargetHorizonal.texture.name = 'UnrealBloomPass.h' + i;
renderTargetHorizonal.texture.generateMipmaps = false;
this.renderTargetsHorizontal.push( renderTargetHorizonal );
const renderTargetVertical = new WebGLRenderTarget( resx, resy, pars );
renderTargetVertical.texture.name = 'UnrealBloomPass.v' + i;
renderTargetVertical.texture.generateMipmaps = false;
this.renderTargetsVertical.push( renderTargetVertical );
resx = Math.round( resx / 2 );
resy = Math.round( resy / 2 );
}
// luminosity high pass material
if ( LuminosityHighPassShader === undefined )
console.error( 'THREE.UnrealBloomPass relies on LuminosityHighPassShader' );
const highPassShader = LuminosityHighPassShader;
this.highPassUniforms = UniformsUtils.clone( highPassShader.uniforms );
this.highPassUniforms[ 'luminosityThreshold' ].value = threshold;
this.highPassUniforms[ 'smoothWidth' ].value = 0.01;
this.materialHighPassFilter = new ShaderMaterial( {
uniforms: this.highPassUniforms,
vertexShader: highPassShader.vertexShader,
fragmentShader: highPassShader.fragmentShader,
defines: {}
} );
// Gaussian Blur Materials
this.separableBlurMaterials = [];
const kernelSizeArray = [ 3, 5, 7, 9, 11 ];
resx = Math.round( this.resolution.x / 2 );
resy = Math.round( this.resolution.y / 2 );
for ( let i = 0; i < this.nMips; i ++ ) {
this.separableBlurMaterials.push( this.getSeperableBlurMaterial( kernelSizeArray[ i ] ) );
this.separableBlurMaterials[ i ].uniforms[ 'texSize' ].value = new Vector2( resx, resy );
resx = Math.round( resx / 2 );
resy = Math.round( resy / 2 );
}
// Composite material
this.compositeMaterial = this.getCompositeMaterial( this.nMips );
this.compositeMaterial.uniforms[ 'blurTexture1' ].value = this.renderTargetsVertical[ 0 ].texture;
this.compositeMaterial.uniforms[ 'blurTexture2' ].value = this.renderTargetsVertical[ 1 ].texture;
this.compositeMaterial.uniforms[ 'blurTexture3' ].value = this.renderTargetsVertical[ 2 ].texture;
this.compositeMaterial.uniforms[ 'blurTexture4' ].value = this.renderTargetsVertical[ 3 ].texture;
this.compositeMaterial.uniforms[ 'blurTexture5' ].value = this.renderTargetsVertical[ 4 ].texture;
this.compositeMaterial.uniforms[ 'bloomStrength' ].value = strength;
this.compositeMaterial.uniforms[ 'bloomRadius' ].value = 0.1;
this.compositeMaterial.needsUpdate = true;
const bloomFactors = [ 1.0, 0.8, 0.6, 0.4, 0.2 ];
this.compositeMaterial.uniforms[ 'bloomFactors' ].value = bloomFactors;
this.bloomTintColors = [ new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ) ];
this.compositeMaterial.uniforms[ 'bloomTintColors' ].value = this.bloomTintColors;
// copy material
if ( CopyShader === undefined ) {
console.error( 'THREE.UnrealBloomPass relies on CopyShader' );
}
const copyShader = CopyShader;
this.copyUniforms = UniformsUtils.clone( copyShader.uniforms );
this.copyUniforms[ 'opacity' ].value = 1.0;
this.materialCopy = new ShaderMaterial( {
uniforms: this.copyUniforms,
vertexShader: copyShader.vertexShader,
fragmentShader: copyShader.fragmentShader,
blending: AdditiveBlending,
depthTest: false,
depthWrite: false,
transparent: true
} );
this.enabled = true;
this.needsSwap = false;
this._oldClearColor = new Color();
this.oldClearAlpha = 1;
this.basic = new MeshBasicMaterial();
this.fsQuad = new FullScreenQuad( null );
}
dispose() {
for ( let i = 0; i < this.renderTargetsHorizontal.length; i ++ ) {
this.renderTargetsHorizontal[ i ].dispose();
}
for ( let i = 0; i < this.renderTargetsVertical.length; i ++ ) {
this.renderTargetsVertical[ i ].dispose();
}
this.renderTargetBright.dispose();
}
setSize( width, height ) {
let resx = Math.round( width / 2 );
let resy = Math.round( height / 2 );
this.renderTargetBright.setSize( resx, resy );
for ( let i = 0; i < this.nMips; i ++ ) {
this.renderTargetsHorizontal[ i ].setSize( resx, resy );
this.renderTargetsVertical[ i ].setSize( resx, resy );
this.separableBlurMaterials[ i ].uniforms[ 'texSize' ].value = new Vector2( resx, resy );
resx = Math.round( resx / 2 );
resy = Math.round( resy / 2 );
}
}
render( renderer, writeBuffer, readBuffer, deltaTime, maskActive ) {
renderer.getClearColor( this._oldClearColor );
this.oldClearAlpha = renderer.getClearAlpha();
const oldAutoClear = renderer.autoClear;
renderer.autoClear = false;
renderer.setClearColor( this.clearColor, 0 );
if ( maskActive ) renderer.state.buffers.stencil.setTest( false );
// Render input to screen
if ( this.renderToScreen ) {
this.fsQuad.material = this.basic;
this.basic.map = readBuffer.texture;
renderer.setRenderTarget( null );
renderer.clear();
this.fsQuad.render( renderer );
}
// 1. Extract Bright Areas
this.highPassUniforms[ 'tDiffuse' ].value = readBuffer.texture;
this.highPassUniforms[ 'luminosityThreshold' ].value = this.threshold;
this.fsQuad.material = this.materialHighPassFilter;
renderer.setRenderTarget( this.renderTargetBright );
renderer.clear();
this.fsQuad.render( renderer );
// 2. Blur All the mips progressively
let inputRenderTarget = this.renderTargetBright;
for ( let i = 0; i < this.nMips; i ++ ) {
this.fsQuad.material = this.separableBlurMaterials[ i ];
this.separableBlurMaterials[ i ].uniforms[ 'colorTexture' ].value = inputRenderTarget.texture;
this.separableBlurMaterials[ i ].uniforms[ 'direction' ].value = UnrealBloomPass.BlurDirectionX;
renderer.setRenderTarget( this.renderTargetsHorizontal[ i ] );
renderer.clear();
this.fsQuad.render( renderer );
this.separableBlurMaterials[ i ].uniforms[ 'colorTexture' ].value = this.renderTargetsHorizontal[ i ].texture;
this.separableBlurMaterials[ i ].uniforms[ 'direction' ].value = UnrealBloomPass.BlurDirectionY;
renderer.setRenderTarget( this.renderTargetsVertical[ i ] );
renderer.clear();
this.fsQuad.render( renderer );
inputRenderTarget = this.renderTargetsVertical[ i ];
}
// Composite All the mips
this.fsQuad.material = this.compositeMaterial;
this.compositeMaterial.uniforms[ 'bloomStrength' ].value = this.strength;
this.compositeMaterial.uniforms[ 'bloomRadius' ].value = this.radius;
this.compositeMaterial.uniforms[ 'bloomTintColors' ].value = this.bloomTintColors;
renderer.setRenderTarget( this.renderTargetsHorizontal[ 0 ] );
renderer.clear();
this.fsQuad.render( renderer );
// Blend it additively over the input texture
this.fsQuad.material = this.materialCopy;
this.copyUniforms[ 'tDiffuse' ].value = this.renderTargetsHorizontal[ 0 ].texture;
if ( maskActive ) renderer.state.buffers.stencil.setTest( true );
if ( this.renderToScreen ) {
renderer.setRenderTarget( null );
this.fsQuad.render( renderer );
} else {
renderer.setRenderTarget( readBuffer );
this.fsQuad.render( renderer );
}
// Restore renderer settings
renderer.setClearColor( this._oldClearColor, this.oldClearAlpha );
renderer.autoClear = oldAutoClear;
}
getSeperableBlurMaterial( kernelRadius ) {
return new ShaderMaterial( {
defines: {
'KERNEL_RADIUS': kernelRadius,
'SIGMA': kernelRadius
},
uniforms: {
'colorTexture': { value: null },
'texSize': { value: new Vector2( 0.5, 0.5 ) },
'direction': { value: new Vector2( 0.5, 0.5 ) }
},
vertexShader:
`varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,
fragmentShader:
`#include <common>
varying vec2 vUv;
uniform sampler2D colorTexture;
uniform vec2 texSize;
uniform vec2 direction;
float gaussianPdf(in float x, in float sigma) {
return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma;
}
void main() {
vec2 invSize = 1.0 / texSize;
float fSigma = float(SIGMA);
float weightSum = gaussianPdf(0.0, fSigma);
vec3 diffuseSum = texture2D( colorTexture, vUv).rgb * weightSum;
for( int i = 1; i < KERNEL_RADIUS; i ++ ) {
float x = float(i);
float w = gaussianPdf(x, fSigma);
vec2 uvOffset = direction * invSize * x;
vec3 sample1 = texture2D( colorTexture, vUv + uvOffset).rgb;
vec3 sample2 = texture2D( colorTexture, vUv - uvOffset).rgb;
diffuseSum += (sample1 + sample2) * w;
weightSum += 2.0 * w;
}
gl_FragColor = vec4(diffuseSum/weightSum, 1.0);
}`
} );
}
getCompositeMaterial( nMips ) {
return new ShaderMaterial( {
defines: {
'NUM_MIPS': nMips
},
uniforms: {
'blurTexture1': { value: null },
'blurTexture2': { value: null },
'blurTexture3': { value: null },
'blurTexture4': { value: null },
'blurTexture5': { value: null },
'dirtTexture': { value: null },
'bloomStrength': { value: 1.0 },
'bloomFactors': { value: null },
'bloomTintColors': { value: null },
'bloomRadius': { value: 0.0 }
},
vertexShader:
`varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,
fragmentShader:
`varying vec2 vUv;
uniform sampler2D blurTexture1;
uniform sampler2D blurTexture2;
uniform sampler2D blurTexture3;
uniform sampler2D blurTexture4;
uniform sampler2D blurTexture5;
uniform sampler2D dirtTexture;
uniform float bloomStrength;
uniform float bloomRadius;
uniform float bloomFactors[NUM_MIPS];
uniform vec3 bloomTintColors[NUM_MIPS];
float lerpBloomFactor(const in float factor) {
float mirrorFactor = 1.2 - factor;
return mix(factor, mirrorFactor, bloomRadius);
}
void main() {
gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) +
lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) +
lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) +
lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) +
lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) );
}`
} );
}
}
UnrealBloomPass.BlurDirectionX = new Vector2( 1.0, 0.0 );
UnrealBloomPass.BlurDirectionY = new Vector2( 0.0, 1.0 );
export { UnrealBloomPass };
| mit |
unaio/una | modules/boonex/forum/updates/9.0.2_9.0.3/source/classes/BxForumTemplate.php | 8344 | <?php defined('BX_DOL') or die('hack attempt');
/**
* Copyright (c) UNA, Inc - https://una.io
* MIT License - https://opensource.org/licenses/MIT
*
* @defgroup Forum Forum
* @ingroup UnaModules
*
* @{
*/
/*
* Module representation.
*/
class BxForumTemplate extends BxBaseModTextTemplate
{
/**
* Constructor
*/
function __construct(&$oConfig, &$oDb)
{
$this->MODULE = 'bx_forum';
parent::__construct($oConfig, $oDb);
}
public function entryBreadcrumb($aContentInfo, $aTmplVarsItems = array())
{
$CNF = &BxDolModule::getInstance($this->MODULE)->_oConfig->CNF;
$oPermalink = BxDolPermalinks::getInstance();
$oCategory = BxDolCategory::getObjectInstance($CNF['OBJECT_CATEGORY']);
$aTmplVarsItems = array(array(
'url' => bx_append_url_params($oPermalink->permalink('page.php?i=' . $CNF['URI_CATEGORY_ENTRIES']), array(
'category' => $aContentInfo[$CNF['FIELD_CATEGORY']]
)),
'title' => $oCategory->getCategoryTitle($aContentInfo[$CNF['FIELD_CATEGORY']])
), array(
'url' => $oPermalink->permalink('page.php?i=' . $CNF['URI_VIEW_ENTRY'] . '&id=' . $aContentInfo[$CNF['FIELD_ID']]),
'title' => $aContentInfo[$CNF['FIELD_TITLE']]
));
return parent::entryBreadcrumb($aContentInfo, $aTmplVarsItems);
}
public function entryParticipants($aContentInfo, $iMaxVisible = 2, $sFloat = 'left')
{
$oModule = BxDolModule::getInstance($this->MODULE);
$CNF = &$oModule->_oConfig->CNF;
$iAuthorId = $aContentInfo[$CNF['FIELD_AUTHOR']];
$aParticipants = $this->_oDb->getComments(array('type' => 'author_comments', 'object_id' => $aContentInfo[$CNF['FIELD_ID']]));
$aParticipants[$iAuthorId] = !empty($aParticipants[$iAuthorId]) ? $aParticipants[$iAuthorId] + 1 : 1;
// sort participants: first - current user, second - last replier, third - author, all others sorted by max number of posts
$aParticipants = $oModule->sortParticipants($aParticipants, $aContentInfo['lr_profile_id'], $iAuthorId);
$iParticipantsNum = count($aParticipants);
// prepare template variables
$aVarsPopup = array (
'float' => 'none',
'bx_repeat:participants' => array(),
'bx_if:participants_more' => array(
'condition' => false,
'content' => array(),
),
);
$aVars = array (
'float' => $sFloat,
'bx_repeat:participants' => array(),
'bx_if:participants_more' => array(
'condition' => $iParticipantsNum > $iMaxVisible,
'content' => array(
'popup' => '',
'title_more' => _t('_bx_forum_more', $iParticipantsNum - $iMaxVisible),
'float' => $sFloat,
'id' => $this->MODULE . '-popup-' . $aContentInfo[$CNF['FIELD_ID']],
),
),
);
$i = 0;
foreach ($aParticipants as $iProfileId => $iComments) {
$oProfile = BxDolProfile::getInstance($iProfileId);
if (!$oProfile)
continue;
$sInfo = '';
if ($iAuthorId == $iProfileId)
$sInfo = _t('_bx_forum_participant_author');
if ($aContentInfo['lr_profile_id'] == $iProfileId)
$sInfo .= ', ' . _t('_bx_forum_participant_last_replier');
$sInfo = trim($sInfo, ', ');
$sInfo = $sInfo ? _t('_bx_forum_participant_info', $oProfile->getDisplayName(), $sInfo) : $oProfile->getDisplayName();
$aParticipant = array (
'id' => $oProfile->id(),
'url' => $oProfile->getUrl(),
'thumb_url' => $oProfile->getThumb(),
'title' => $oProfile->getDisplayName(),
'title_attr' => bx_html_attribute($sInfo),
'float' => $sFloat,
'class' => $iAuthorId == $iProfileId ? 'bx-forum-participant-author' : '',
'bx_if:replies_count' => array(
'condition' => $iComments > 0,
'content' => array(
'count' => $iComments
)
),
'bx_if:last_replier' => array (
'condition' => ($aContentInfo['lr_profile_id'] == $iProfileId),
'content' => array (
'id' => $oProfile->id(),
),
),
'bx_if:author' => array (
'condition' => $iAuthorId == $iProfileId,
'content' => array (
'id' => $oProfile->id(),
),
),
);
if ($i < $iMaxVisible)
$aVars['bx_repeat:participants'][] = $aParticipant;
if ($i >= $iMaxVisible)
$aVarsPopup['bx_repeat:participants'][] = $aParticipant;
++$i;
}
if ($aVarsPopup['bx_repeat:participants']) {
$aVars['bx_if:participants_more']['content']['popup'] = BxTemplFunctions::getInstance()->transBox('', '<div class="bx-def-padding">' . $this->parseHtmlByName('participants.html', $aVarsPopup) . '</div>');
}
return $this->parseHtmlByName('participants.html', $aVars);
}
function getEntryAuthor($aRow)
{
$oProfileAuthor = BxDolProfile::getInstance($aRow['author']);
if(!$oProfileAuthor)
$oProfileAuthor = BxDolProfileUndefined::getInstance();
return $this->parseHtmlByName('entry-author.html', array(
'id' => $oProfileAuthor->id(),
'url' => $oProfileAuthor->getUrl(),
'title' => $oProfileAuthor->getDisplayName(),
'title_attr' => bx_html_attribute($oProfileAuthor->getDisplayName()),
'thumb_url' => $oProfileAuthor->getThumb(),
));
}
function getEntryLabel($aRow, $aParams = array())
{
$bShowCount = isset($aParams['show_count']) ? (int)$aParams['show_count'] == 1 : false;
$oProfileLast = BxDolProfile::getInstance($aRow['lr_profile_id']);
if(!$oProfileLast)
$oProfileLast = BxDolProfileUndefined::getInstance();
return $this->parseHtmlByName('entry-label.html', array(
'bx_if:show_count' => array(
'condition' => $bShowCount,
'content' => array(
'count' => (int)$aRow['comments'] + 1
)
),
'bx_if:show_viewer_is_last_replier' => array(
'condition' => $oProfileLast->id() == bx_get_logged_profile_id(),
'content' => array (),
)
));
}
function getEntryPreview($aRow)
{
$oModule = BxDolModule::getInstance($this->MODULE);
$CNF = &$oModule->_oConfig->CNF;
$oProfileLast = BxDolProfile::getInstance($aRow['lr_profile_id']);
if(!$oProfileLast)
$oProfileLast = BxDolProfileUndefined::getInstance();
$sTitle = strmaxtextlen($aRow['title'], 100);
$sText = strmaxtextlen(!empty($aRow['cmt_text']) ? $aRow['cmt_text'] : $aRow['text'], 100);
return $this->parseHtmlByName('entry-preview.html', array(
'bx_if:show_stick' => array(
'condition' => (int)$aRow[$CNF['FIELD_STICK']] == 1,
'content' => array()
),
'bx_if:show_lock' => array(
'condition' => (int)$aRow[$CNF['FIELD_LOCK']] == 1,
'content' => array()
),
'url' => BX_DOL_URL_ROOT . BxDolPermalinks::getInstance()->permalink('page.php?i=' . $oModule->_oConfig->CNF['URI_VIEW_ENTRY'] . '&id=' . $aRow['id']),
'title' => $sTitle ? $sTitle : _t('_Empty'),
'text' => $sText,
'lr_time_and_replier' => _t('_bx_forum_x_date_by_x_replier', bx_time_js($aRow['lr_timestamp'], BX_FORMAT_DATE), $oProfileLast->getDisplayName()),
));
}
function getAuthorDesc ($aData)
{
$CNF = &$this->_oConfig->CNF;
return bx_time_js($aData[$CNF['FIELD_ADDED']]);
}
function getAuthorAddon ($aData, $oProfile)
{
return '';
}
protected function getUnit ($aData, $aParams = array())
{
$aUnit = parent::getUnit($aData, $aParams);
$aUnit['label'] = $this->getEntryLabel($aData, array('show_count' => 0));
return $aUnit;
}
}
/** @} */
| mit |
pierre/active_merchant | test/unit/gateways/authorize_net_test.rb | 39533 | require 'test_helper'
class AuthorizeNetTest < Test::Unit::TestCase
include CommStub
BAD_TRACK_DATA = '%B378282246310005LONGSONLONGBOB1705101130504392?'
TRACK1_DATA = '%B378282246310005^LONGSON/LONGBOB^1705101130504392?'
TRACK2_DATA = ';4111111111111111=1803101000020000831?'
def setup
@gateway = AuthorizeNetGateway.new(
login: 'X',
password: 'Y'
)
@amount = 100
@credit_card = credit_card
@check = check
@apple_pay_payment_token = ActiveMerchant::Billing::ApplePayPaymentToken.new(
{data: 'encoded_payment_data'},
payment_instrument_name: 'SomeBank Visa',
payment_network: 'Visa',
transaction_identifier: 'transaction123'
)
@options = {
order_id: '1',
billing_address: address,
description: 'Store Purchase'
}
end
def test_add_swipe_data_with_bad_data
@credit_card.track_data = BAD_TRACK_DATA
stub_comms do
@gateway.purchase(@amount, @credit_card)
end.check_request do |endpoint, data, headers|
parse(data) do |doc|
assert_nil doc.at_xpath('//track1')
assert_nil doc.at_xpath('//track2')
assert_equal "1.00", doc.at_xpath("//transactionRequest/amount").content
end
end.respond_with(successful_purchase_response)
end
def test_add_swipe_data_with_track_1
@credit_card.track_data = TRACK1_DATA
stub_comms do
@gateway.purchase(@amount, @credit_card)
end.check_request do |endpoint, data, headers|
parse(data) do |doc|
assert_equal '%B378282246310005^LONGSON/LONGBOB^1705101130504392?', doc.at_xpath('//track1').content
assert_nil doc.at_xpath('//track2')
assert_equal "1.00", doc.at_xpath("//transactionRequest/amount").content
end
end.respond_with(successful_purchase_response)
end
def test_add_swipe_data_with_track_2
@credit_card.track_data = TRACK2_DATA
stub_comms do
@gateway.purchase(@amount, @credit_card)
end.check_request do |endpoint, data, headers|
parse(data) do |doc|
assert_nil doc.at_xpath('//track1')
assert_equal ';4111111111111111=1803101000020000831?', doc.at_xpath('//track2').content
assert_equal "1.00", doc.at_xpath("//transactionRequest/amount").content
end
end.respond_with(successful_purchase_response)
end
def test_retail_market_type_only_included_in_swipe_transactions
[BAD_TRACK_DATA, nil].each do |track|
@credit_card.track_data = track
stub_comms do
@gateway.purchase(@amount, @credit_card)
end.check_request do |endpoint, data, headers|
parse(data) do |doc|
assert_nil doc.at_xpath('//retail')
end
end.respond_with(successful_purchase_response)
end
[TRACK1_DATA, TRACK2_DATA].each do |track|
@credit_card.track_data = track
stub_comms do
@gateway.purchase(@amount, @credit_card)
end.check_request do |endpoint, data, headers|
parse(data) do |doc|
assert_not_nil doc.at_xpath('//retail')
assert_equal "2", doc.at_xpath('//retail/marketType').content
end
end.respond_with(successful_purchase_response)
end
end
def test_successful_echeck_authorization
response = stub_comms do
@gateway.authorize(@amount, @check)
end.check_request do |endpoint, data, headers|
parse(data) do |doc|
assert_not_nil doc.at_xpath("//payment/bankAccount")
assert_equal "244183602", doc.at_xpath("//routingNumber").content
assert_equal "15378535", doc.at_xpath("//accountNumber").content
assert_equal "Bank of Elbonia", doc.at_xpath("//bankName").content
assert_equal "Jim Smith", doc.at_xpath("//nameOnAccount").content
assert_equal "WEB", doc.at_xpath("//echeckType").content
assert_equal "1", doc.at_xpath("//checkNumber").content
assert_equal "1.00", doc.at_xpath("//transactionRequest/amount").content
end
end.respond_with(successful_authorize_response)
assert response
assert_instance_of Response, response
assert_success response
assert_equal '508141794', response.authorization.split('#')[0]
end
def test_successful_echeck_purchase
response = stub_comms do
@gateway.purchase(@amount, @check)
end.check_request do |endpoint, data, headers|
parse(data) do |doc|
assert_not_nil doc.at_xpath("//payment/bankAccount")
assert_equal "244183602", doc.at_xpath("//routingNumber").content
assert_equal "15378535", doc.at_xpath("//accountNumber").content
assert_equal "Bank of Elbonia", doc.at_xpath("//bankName").content
assert_equal "Jim Smith", doc.at_xpath("//nameOnAccount").content
assert_equal "WEB", doc.at_xpath("//echeckType").content
assert_equal "1", doc.at_xpath("//checkNumber").content
assert_equal "1.00", doc.at_xpath("//transactionRequest/amount").content
end
end.respond_with(successful_purchase_response)
assert response
assert_instance_of Response, response
assert_success response
assert_equal '508141795', response.authorization.split('#')[0]
end
def test_echeck_passing_recurring_flag
response = stub_comms do
@gateway.purchase(@amount, @check, recurring: true)
end.check_request do |endpoint, data, headers|
assert_equal settings_from_doc(parse(data))["recurringBilling"], "true"
end.respond_with(successful_purchase_response)
assert_success response
end
def test_failed_echeck_authorization
@gateway.expects(:ssl_post).returns(failed_authorize_response)
response = @gateway.authorize(@amount, @check)
assert_failure response
end
def test_successful_apple_pay_authorization
response = stub_comms do
@gateway.authorize(@amount, @apple_pay_payment_token)
end.check_request do |endpoint, data, headers|
parse(data) do |doc|
assert_equal @gateway.class::APPLE_PAY_DATA_DESCRIPTOR, doc.at_xpath("//opaqueData/dataDescriptor").content
assert_equal Base64.strict_encode64(@apple_pay_payment_token.payment_data.to_json), doc.at_xpath("//opaqueData/dataValue").content
end
end.respond_with(successful_authorize_response)
assert response
assert_instance_of Response, response
assert_success response
assert_equal '508141794', response.authorization.split('#')[0]
end
def test_successful_apple_pay_purchase
response = stub_comms do
@gateway.purchase(@amount, @apple_pay_payment_token)
end.check_request do |endpoint, data, headers|
parse(data) do |doc|
assert_equal @gateway.class::APPLE_PAY_DATA_DESCRIPTOR, doc.at_xpath("//opaqueData/dataDescriptor").content
assert_equal Base64.strict_encode64(@apple_pay_payment_token.payment_data.to_json), doc.at_xpath("//opaqueData/dataValue").content
end
end.respond_with(successful_purchase_response)
assert response
assert_instance_of Response, response
assert_success response
assert_equal '508141795', response.authorization.split('#')[0]
end
def test_successful_authorization
@gateway.expects(:ssl_post).returns(successful_authorize_response)
response = @gateway.authorize(@amount, @credit_card)
assert_success response
assert_equal 'M', response.cvv_result['code']
assert_equal 'CVV matches', response.cvv_result['message']
assert_equal '508141794', response.authorization.split('#')[0]
assert response.test?
end
def test_successful_purchase
@gateway.expects(:ssl_post).returns(successful_purchase_response)
response = @gateway.purchase(@amount, @credit_card)
assert_success response
assert_equal '508141795', response.authorization.split('#')[0]
assert response.test?
assert_equal 'Y', response.avs_result['code']
assert response.avs_result['street_match']
assert response.avs_result['postal_match']
assert_equal 'Street address and 5-digit postal code match.', response.avs_result['message']
assert_equal 'P', response.cvv_result['code']
assert_equal 'CVV not processed', response.cvv_result['message']
end
def test_failed_purchase
@gateway.expects(:ssl_post).returns(failed_purchase_response)
response = @gateway.purchase(@amount, @credit_card, @options)
assert_failure response
end
def test_failed_authorize
@gateway.expects(:ssl_post).returns(failed_authorize_response)
response = @gateway.authorize(@amount, @credit_card, @options)
assert_failure response
end
def test_successful_capture
@gateway.expects(:ssl_post).returns(successful_capture_response)
capture = @gateway.capture(@amount, '2214269051#XXXX1234', @options)
assert_success capture
end
def test_failed_capture
@gateway.expects(:ssl_post).returns(failed_capture_response)
assert capture = @gateway.capture(@amount, '2214269051#XXXX1234')
assert_failure capture
end
def test_failed_already_actioned_capture
@gateway.expects(:ssl_post).returns(already_actioned_capture_response)
response = @gateway.capture(50, '123456789')
assert_instance_of Response, response
assert_failure response
end
def test_successful_void
@gateway.expects(:ssl_post).returns(successful_void_response)
assert void = @gateway.void('')
assert_success void
end
def test_failed_void
@gateway.expects(:ssl_post).returns(failed_void_response)
response = @gateway.void('')
assert_failure response
end
def test_successful_verify
response = stub_comms do
@gateway.verify(@credit_card)
end.respond_with(successful_authorize_response, successful_void_response)
assert_success response
end
def test_successful_verify_failed_void
response = stub_comms do
@gateway.verify(@credit_card, @options)
end.respond_with(successful_authorize_response, failed_void_response)
assert_success response
assert_match %r{This transaction has been approved}, response.message
end
def test_unsuccessful_verify
response = stub_comms do
@gateway.verify(@credit_card, @options)
end.respond_with(failed_authorize_response, successful_void_response)
assert_failure response
assert_not_nil response.message
end
def test_address
stub_comms do
@gateway.authorize(@amount, @credit_card, billing_address: {address1: '164 Waverley Street', country: 'US', state: 'CO', phone: '(555)555-5555', fax: '(555)555-4444'})
end.check_request do |endpoint, data, headers|
parse(data) do |doc|
assert_equal "CO", doc.at_xpath("//billTo/state").content, data
assert_equal "164 Waverley Street", doc.at_xpath("//billTo/address").content, data
assert_equal "US", doc.at_xpath("//billTo/country").content, data
assert_equal "(555)555-5555", doc.at_xpath("//billTo/phoneNumber").content
assert_equal "(555)555-4444", doc.at_xpath("//billTo/faxNumber").content
end
end.respond_with(successful_authorize_response)
end
def test_address_outsite_north_america
stub_comms do
@gateway.authorize(@amount, @credit_card, billing_address: {address1: '164 Waverley Street', country: 'DE', state: ''})
end.check_request do |endpoint, data, headers|
parse(data) do |doc|
assert_equal "n/a", doc.at_xpath("//billTo/state").content, data
assert_equal "164 Waverley Street", doc.at_xpath("//billTo/address").content, data
assert_equal "DE", doc.at_xpath("//billTo/country").content, data
end
end.respond_with(successful_authorize_response)
end
def test_duplicate_window
@gateway.class.duplicate_window = 0
stub_comms do
@gateway.purchase(@amount, @credit_card)
end.check_request do |endpoint, data, headers|
assert_equal settings_from_doc(parse(data))["duplicateWindow"], "0"
end.respond_with(successful_purchase_response)
ensure
@gateway.class.duplicate_window = nil
end
def test_add_cardholder_authentication_value
stub_comms do
@gateway.purchase(@amount, @credit_card, cardholder_authentication_value: 'E0Mvq8AAABEiMwARIjNEVWZ3iJk=', authentication_indicator: "2")
end.check_request do |endpoint, data, headers|
parse(data) do |doc|
assert_equal "E0Mvq8AAABEiMwARIjNEVWZ3iJk=", doc.at_xpath("//cardholderAuthentication/cardholderAuthenticationValue").content
assert_equal "2", doc.at_xpath("//cardholderAuthentication/authenticationIndicator").content
assert_equal "1.00", doc.at_xpath("//transactionRequest/amount").content
end
end.respond_with(successful_purchase_response)
end
def test_capture_passing_extra_info
response = stub_comms do
@gateway.capture(50, '123456789', description: "Yo", order_id: "Sweetness")
end.check_request do |endpoint, data, headers|
parse(data) do |doc|
assert_not_nil doc.at_xpath("//order/description"), data
assert_equal "Yo", doc.at_xpath("//order/description").content, data
assert_equal "Sweetness", doc.at_xpath("//order/invoiceNumber").content, data
assert_equal "0.50", doc.at_xpath("//transactionRequest/amount").content
end
end.respond_with(successful_capture_response)
assert_success response
end
def test_successful_refund
@gateway.expects(:ssl_post).returns(successful_refund_response)
assert refund = @gateway.refund(36.40, '2214269051#XXXX1234')
assert_success refund
assert_equal 'This transaction has been approved', refund.message
assert_equal '2214602071#2224', refund.authorization
end
def test_refund_passing_extra_info
response = stub_comms do
@gateway.refund(50, '123456789', card_number: @credit_card.number, first_name: "Bob", last_name: "Smith", zip: "12345")
end.check_request do |endpoint, data, headers|
parse(data) do |doc|
assert_equal "Bob", doc.at_xpath("//billTo/firstName").content, data
assert_equal "Smith", doc.at_xpath("//billTo/lastName").content, data
assert_equal "12345", doc.at_xpath("//billTo/zip").content, data
assert_equal "0.50", doc.at_xpath("//transactionRequest/amount").content
end
end.respond_with(successful_purchase_response)
assert_success response
end
def test_failed_refund
@gateway.expects(:ssl_post).returns(failed_refund_response)
refund = @gateway.refund(nil, '')
assert_failure refund
assert_equal 'The sum of credits against the referenced transaction would exceed original debit amount', refund.message
assert_equal '0#2224', refund.authorization
end
def test_supported_countries
assert_equal 4, (['US', 'CA', 'AU', 'VA'] & AuthorizeNetGateway.supported_countries).size
end
def test_supported_card_types
assert_equal [:visa, :master, :american_express, :discover, :diners_club, :jcb, :maestro], AuthorizeNetGateway.supported_cardtypes
end
def test_failure_without_response_reason_text
response = stub_comms do
@gateway.purchase(@amount, @credit_card)
end.respond_with(no_message_response)
assert_equal "", response.message
end
def test_response_under_review_by_fraud_service
@gateway.expects(:ssl_post).returns(fraud_review_response)
response = @gateway.purchase(@amount, @credit_card)
assert_failure response
assert response.fraud_review?
assert_equal "Thank you! For security reasons your order is currently being reviewed", response.message
end
def test_avs_result
@gateway.expects(:ssl_post).returns(fraud_review_response)
response = @gateway.purchase(@amount, @credit_card)
assert_equal 'X', response.avs_result['code']
end
def test_cvv_result
@gateway.expects(:ssl_post).returns(fraud_review_response)
response = @gateway.purchase(@amount, @credit_card)
assert_equal 'M', response.cvv_result['code']
end
def test_message
response = stub_comms do
@gateway.purchase(@amount, @credit_card)
end.respond_with(no_match_cvv_response)
assert_equal "CVV does not match", response.message
response = stub_comms do
@gateway.purchase(@amount, @credit_card)
end.respond_with(no_match_avs_response)
assert_equal "Street address matches, but 5-digit and 9-digit postal code do not match.", response.message
response = stub_comms do
@gateway.purchase(@amount, @credit_card)
end.respond_with(failed_purchase_response)
assert_equal "The credit card number is invalid", response.message
end
def test_solution_id_is_added_to_post_data_parameters
@gateway.class.application_id = 'A1000000'
stub_comms do
@gateway.authorize(@amount, @credit_card)
end.check_request do |endpoint, data, headers|
doc = parse(data)
assert_equal "A1000000", fields_from_doc(doc)["x_solution_id"], data
assert_equal "1.00", doc.at_xpath("//transactionRequest/amount").content
end.respond_with(successful_authorize_response)
ensure
@gateway.class.application_id = nil
end
def test_alternate_currency
@gateway.expects(:ssl_post).returns(successful_purchase_response)
response = @gateway.purchase(@amount, @credit_card, currency: "GBP")
assert_success response
end
def assert_no_has_customer_id(data)
assert_no_match %r{x_cust_id}, data
end
def test_include_cust_id_for_numeric_values
stub_comms do
@gateway.purchase(@amount, @credit_card, customer: "123")
end.check_request do |endpoint, data, headers|
parse(data) do |doc|
assert_not_nil doc.at_xpath("//customer/id"), data
assert_equal "123", doc.at_xpath("//customer/id").content, data
assert_equal "1.00", doc.at_xpath("//transactionRequest/amount").content
end
end.respond_with(successful_authorize_response)
end
def test_dont_include_cust_id_for_non_numeric_values
stub_comms do
@gateway.purchase(@amount, @credit_card, customer: "bob@test.com")
end.check_request do |endpoint, data, headers|
doc = parse(data)
assert !doc.at_xpath("//customer/id"), data
assert_equal "1.00", doc.at_xpath("//transactionRequest/amount").content
end.respond_with(successful_authorize_response)
end
def test_truncation
card = credit_card('4242424242424242',
first_name: "a" * 51,
last_name: "a" * 51,
)
options = {
order_id: "a" * 21,
description: "a" * 256,
billing_address: address(
company: "a" * 51,
address1: "a" * 61,
city: "a" * 41,
state: "a" * 41,
zip: "a" * 21,
country: "a" * 61,
),
shipping_address: address(
company: "a" * 51,
address1: "a" * 61,
city: "a" * 41,
state: "a" * 41,
zip: "a" * 21,
country: "a" * 61,
)
}
stub_comms do
@gateway.purchase(@amount, card, options)
end.check_request do |endpoint, data, headers|
assert_truncated(data, 20, "//refId")
assert_truncated(data, 255, "//description")
assert_address_truncated(data, 50, "firstName")
assert_address_truncated(data, 50, "lastName")
assert_address_truncated(data, 50, "company")
assert_address_truncated(data, 60, "address")
assert_address_truncated(data, 40, "city")
assert_address_truncated(data, 40, "state")
assert_address_truncated(data, 20, "zip")
assert_address_truncated(data, 60, "country")
end.respond_with(successful_purchase_response)
end
private
def parse(data)
Nokogiri::XML(data).tap do |doc|
doc.remove_namespaces!
yield(doc) if block_given?
end
end
def fields_from_doc(doc)
assert_not_nil doc.at_xpath("//userFields/userField/name")
doc.xpath("//userFields/userField").inject({}) do |hash, element|
hash[element.at_xpath("name").content] = element.at_xpath("value").content
hash
end
end
def settings_from_doc(doc)
assert_not_nil doc.at_xpath("//transactionSettings/setting/settingName")
doc.xpath("//transactionSettings/setting").inject({}) do |hash, element|
hash[element.at_xpath("settingName").content] = element.at_xpath("settingValue").content
hash
end
end
def assert_truncated(data, expected_size, field)
assert_equal ("a" * expected_size), parse(data).at_xpath(field).text, data
end
def assert_address_truncated(data, expected_size, field)
assert_truncated(data, expected_size, "//billTo/#{field}")
assert_truncated(data, expected_size, "//shipTo/#{field}")
end
def successful_purchase_response
<<-eos
<?xml version="1.0" encoding="utf-8"?>
<createTransactionResponse
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<refId>1</refId>
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<transactionResponse>
<responseCode>1</responseCode>
<authCode>GSOFTZ</authCode>
<avsResultCode>Y</avsResultCode>
<cvvResultCode>P</cvvResultCode>
<cavvResultCode>2</cavvResultCode>
<transId>508141795</transId>
<refTransID/>
<transHash>655D049EE60E1766C9C28EB47CFAA389</transHash>
<testRequest>0</testRequest>
<accountNumber>XXXX2224</accountNumber>
<accountType>Visa</accountType>
<messages>
<message>
<code>1</code>
<description>This transaction has been approved.</description>
</message>
</messages>
</transactionResponse>
</createTransactionResponse>
eos
end
def fraud_review_response
<<-eos
<?xml version="1.0" encoding="utf-8"?>
<createTransactionResponse
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<refId>1</refId>
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<transactionResponse>
<responseCode>4</responseCode>
<authCode>GSOFTZ</authCode>
<avsResultCode>X</avsResultCode>
<cvvResultCode>M</cvvResultCode>
<cavvResultCode>2</cavvResultCode>
<transId>508141795</transId>
<refTransID/>
<transHash>655D049EE60E1766C9C28EB47CFAA389</transHash>
<testRequest>0</testRequest>
<accountNumber>XXXX2224</accountNumber>
<accountType>Visa</accountType>
<messages>
<message>
<code>1</code>
<description>Thank you! For security reasons your order is currently being reviewed</description>
</message>
</messages>
</transactionResponse>
</createTransactionResponse>
eos
end
def no_match_cvv_response
<<-eos
<?xml version="1.0" encoding="utf-8"?>
<createTransactionResponse
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<refId>1</refId>
<messages>
<resultCode>Error</resultCode>
<message>
<code>E00027</code>
<text>The transaction was unsuccessful.</text>
</message>
</messages>
<transactionResponse>
<responseCode>2</responseCode>
<authCode>GSOFTZ</authCode>
<avsResultCode>A</avsResultCode>
<cvvResultCode>N</cvvResultCode>
<cavvResultCode>2</cavvResultCode>
<transId>508141795</transId>
<refTransID/>
<transHash>655D049EE60E1766C9C28EB47CFAA389</transHash>
<testRequest>0</testRequest>
<accountNumber>XXXX2224</accountNumber>
<accountType>Visa</accountType>
<messages>
<message>
<code>1</code>
<description>Thank you! For security reasons your order is currently being reviewed</description>
</message>
</messages>
</transactionResponse>
</createTransactionResponse>
eos
end
def no_match_avs_response
<<-eos
<?xml version="1.0" encoding="utf-8"?>
<createTransactionResponse
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<refId>1</refId>
<messages>
<resultCode>Error</resultCode>
<message>
<code>E00027</code>
<text>The transaction was unsuccessful.</text>
</message>
</messages>
<transactionResponse>
<responseCode>2</responseCode>
<authCode>GSOFTZ</authCode>
<avsResultCode>A</avsResultCode>
<cvvResultCode>M</cvvResultCode>
<cavvResultCode>2</cavvResultCode>
<transId>508141795</transId>
<refTransID/>
<transHash>655D049EE60E1766C9C28EB47CFAA389</transHash>
<testRequest>0</testRequest>
<accountNumber>XXXX2224</accountNumber>
<accountType>Visa</accountType>
<errors>
<error>
<errorCode>27</errorCode>
<errorText>The transaction cannot be found.</errorText>
</error>
</errors>
</transactionResponse>
</createTransactionResponse>
eos
end
def failed_purchase_response
<<-eos
<?xml version="1.0" encoding="utf-8"?>
<createTransactionResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<refId>1234567</refId>
<messages>
<resultCode>Error</resultCode>
<message>
<code>E00027</code>
<text>The transaction was unsuccessful.</text>
</message>
</messages>
<transactionResponse>
<responseCode>3</responseCode>
<authCode/>
<avsResultCode>P</avsResultCode>
<cvvResultCode/>
<cavvResultCode/>
<transId>0</transId>
<refTransID/>
<transHash>7F9A0CB845632DCA5833D2F30ED02677</transHash>
<testRequest>0</testRequest>
<accountNumber>XXXX0001</accountNumber>
<accountType/>
<errors>
<error>
<errorCode>6</errorCode>
<errorText>The credit card number is invalid.</errorText>
</error>
</errors>
<userFields>
<userField>
<name>MerchantDefinedFieldName1</name>
<value>MerchantDefinedFieldValue1</value>
</userField>
<userField>
<name>favorite_color</name>
<value>blue</value>
</userField>
</userFields>
</transactionResponse>
</createTransactionResponse>
eos
end
def no_message_response
<<-eos
<?xml version="1.0" encoding="utf-8"?>
<createTransactionResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<refId>1234567</refId>
<messages>
<resultCode>Error</resultCode>
</messages>
<transactionResponse>
<responseCode>3</responseCode>
<authCode/>
<avsResultCode>P</avsResultCode>
<cvvResultCode/>
<cavvResultCode/>
<transId>0</transId>
<refTransID/>
<transHash>7F9A0CB845632DCA5833D2F30ED02677</transHash>
<testRequest>0</testRequest>
<accountNumber>XXXX0001</accountNumber>
<accountType/>
<userFields>
<userField>
<name>MerchantDefinedFieldName1</name>
<value>MerchantDefinedFieldValue1</value>
</userField>
<userField>
<name>favorite_color</name>
<value>blue</value>
</userField>
</userFields>
</transactionResponse>
</createTransactionResponse>
eos
end
def successful_authorize_response
<<-eos
<?xml version="1.0" encoding="utf-8"?>
<createTransactionResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<refId>123456</refId>
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<transactionResponse>
<responseCode>1</responseCode>
<authCode>A88MS0</authCode>
<avsResultCode>Y</avsResultCode>
<cvvResultCode>M</cvvResultCode>
<cavvResultCode>2</cavvResultCode>
<transId>508141794</transId>
<refTransID/>
<transHash>D0EFF3F32E5ABD14A7CE6ADF32736D57</transHash>
<testRequest>0</testRequest>
<accountNumber>XXXX0015</accountNumber>
<accountType>MasterCard</accountType>
<messages>
<message>
<code>1</code>
<description>This transaction has been approved.</description>
</message>
</messages>
<userFields>
<userField>
<name>MerchantDefinedFieldName1</name>
<value>MerchantDefinedFieldValue1</value>
</userField>
<userField>
<name>favorite_color</name>
<value>blue</value>
</userField>
</userFields>
</transactionResponse>
</createTransactionResponse>
eos
end
def failed_authorize_response
<<-eos
<?xml version="1.0" encoding="utf-8"?>
<createTransactionResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<refId>123456</refId>
<messages>
<resultCode>Error</resultCode>
<message>
<code>E00027</code>
<text>The transaction was unsuccessful.</text>
</message>
</messages>
<transactionResponse>
<responseCode>3</responseCode>
<authCode/>
<avsResultCode>P</avsResultCode>
<cvvResultCode/>
<cavvResultCode/>
<transId>0</transId>
<refTransID/>
<transHash>DA56E64108957174C5AE9BE466914741</transHash>
<testRequest>0</testRequest>
<accountNumber>XXXX0001</accountNumber>
<accountType/>
<errors>
<error>
<errorCode>6</errorCode>
<errorText>The credit card number is invalid.</errorText>
</error>
</errors>
<userFields>
<userField>
<name>MerchantDefinedFieldName1</name>
<value>MerchantDefinedFieldValue1</value>
</userField>
<userField>
<name>favorite_color</name>
<value>blue</value>
</userField>
</userFields>
</transactionResponse>
</createTransactionResponse>
eos
end
def successful_capture_response
<<-eos
<?xml version="1.0" encoding="utf-8"?>
<createTransactionResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema xmlns=AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<refId/>
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<transactionResponse>
<responseCode>1</responseCode>
<authCode>UTDVHP</authCode>
<avsResultCode>P</avsResultCode>
<cvvResultCode/>
<cavvResultCode/>
<transId>2214675515</transId>
<refTransID>2214675515</refTransID>
<transHash>6D739029E129D87F6CEFE3B3864F6D61</transHash>
<testRequest>0</testRequest>
<accountNumber>XXXX2224</accountNumber>
<accountType>Visa</accountType>
<messages>
<message>
<code>1</code>
<description>This transaction has been approved.</description>
</message>
</messages>
</transactionResponse>
</createTransactionResponse>
eos
end
def already_actioned_capture_response
<<-eos
<?xml version="1.0" encoding="utf-8"?>
<createTransactionResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema xmlns=AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<refId/>
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>This transaction has already been captured.</text>
</message>
</messages>
<transactionResponse>
<responseCode>1</responseCode>
<authCode>UTDVHP</authCode>
<avsResultCode>P</avsResultCode>
<cvvResultCode/>
<cavvResultCode/>
<transId>2214675515</transId>
<refTransID>2214675515</refTransID>
<transHash>6D739029E129D87F6CEFE3B3864F6D61</transHash>
<testRequest>0</testRequest>
<accountNumber>XXXX2224</accountNumber>
<accountType>Visa</accountType>
<messages>
<message>
<code>311</code>
<description>This transaction has already been captured.</description>
</message>
</messages>
</transactionResponse>
</createTransactionResponse>
eos
end
def failed_capture_response
<<-eos
<createTransactionResponse xmlns:xsi=
http://www.w3.org/2001/XMLSchema-instance xmlns:xsd=http://www.w3.org/2001/XMLSchema xmlns=AnetApi/xml/v1/schema/AnetApiSchema.xsd><refId/><messages>
<resultCode>Error</resultCode>
<message>
<code>E00027</code>
<text>The transaction was unsuccessful.</text>
</message>
</messages><transactionResponse>
<responseCode>3</responseCode>
<authCode/>
<avsResultCode>P</avsResultCode>
<cvvResultCode/>
<cavvResultCode/>
<transId>0</transId>
<refTransID>23124</refTransID>
<transHash>D99CC43D1B34F0DAB7F430F8F8B3249A</transHash>
<testRequest>0</testRequest>
<accountNumber/>
<accountType/>
<errors>
<error>
<errorCode>16</errorCode>
<errorText>The transaction cannot be found.</errorText>
</error>
</errors>
<shipTo/>
</transactionResponse>
</createTransactionResponse>
eos
end
def successful_refund_response
<<-eos
<createTransactionResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<transactionResponse>
<responseCode>1</responseCode>
<authCode/>
<avsResultCode>P</avsResultCode>
<cvvResultCode/>
<cavvResultCode/>
<transId>2214602071</transId>
<refTransID>2214269051</refTransID>
<transHash>A3E5982FB6789092985F2D618196A268</transHash>
<testRequest>0</testRequest>
<accountNumber>XXXX2224</accountNumber>
<accountType>Visa</accountType>
<messages>
<message>
<code>1</code>
<description>This transaction has been approved.</description>
</message>
</messages>
</transactionResponse>
</createTransactionResponse>
eos
end
def failed_refund_response
<<-eos
<createTransactionResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Error</resultCode>
<message>
<code>E00027</code>
<text>The transaction was unsuccessful.</text>
</message>
</messages>
<transactionResponse>
<responseCode>3</responseCode>
<authCode/>
<avsResultCode>P</avsResultCode>
<cvvResultCode/>
<cavvResultCode/>
<transId>0</transId>
<refTransID>2214269051</refTransID>
<transHash>63E03F4968F0874E1B41FCD79DD54717</transHash>
<testRequest>0</testRequest>
<accountNumber>XXXX2224</accountNumber>
<accountType>Visa</accountType>
<errors>
<error>
<errorCode>55</errorCode>
<errorText>The sum of credits against the referenced transaction would exceed original debit amount.</errorText>
</error>
</errors>
</transactionResponse>
</createTransactionResponse>
eos
end
def successful_void_response
<<-eos
<?xml version="1.0" encoding="utf-8"?>
<createTransactionResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<transactionResponse>
<responseCode>1</responseCode>
<authCode>GYEB3</authCode>
<avsResultCode>P</avsResultCode>
<cvvResultCode/>
<cavvResultCode/>
<transId>2213755822</transId>
<refTransID>2213755822</refTransID>
<transHash>3383BBB85FF98057D61B2D9B9A2DA79F</transHash>
<testRequest>0</testRequest>
<accountNumber>XXXX0015</accountNumber>
<accountType>MasterCard</accountType>
<messages>
<message>
<code>1</code>
<description>This transaction has been approved.</description>
</message>
</messages>
</transactionResponse>
</createTransactionResponse>
eos
end
def failed_void_response
<<-eos
<?xml version="1.0" encoding="utf-8"?>
<createTransactionResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Error</resultCode>
<message>
<code>E00027</code>
<text>The transaction was unsuccessful.</text>
</message>
</messages>
<transactionResponse>
<responseCode>3</responseCode>
<authCode/>
<avsResultCode>P</avsResultCode>
<cvvResultCode/>
<cavvResultCode/>
<transId>0</transId>
<refTransID>2213755821</refTransID>
<transHash>39DC95085A313FEF7278C40EA8A66B16</transHash>
<testRequest>0</testRequest>
<accountNumber/>
<accountType/>
<errors>
<error>
<errorCode>16</errorCode>
<errorText>The transaction cannot be found.</errorText>
</error>
</errors>
<shipTo/>
</transactionResponse>
</createTransactionResponse>
eos
end
end
| mit |
matiasmm/sfCodeSearch | src/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/TestApplication/Sensio/FooBundle/SensioFooBundle.php | 467 | <?php
namespace TestApplication\Sensio\FooBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/*
* This file is part of the Symfony framework.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* Bundle.
*
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
*/
class SensioFooBundle extends Bundle
{
}
| mit |
anudeepsharma/azure-sdk-for-java | azure-batch/src/main/java/com/microsoft/azure/batch/protocol/implementation/BatchServiceClientImpl.java | 9056 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.batch.protocol.implementation;
import com.microsoft.azure.AzureClient;
import com.microsoft.azure.AzureServiceClient;
import com.microsoft.azure.batch.protocol.Accounts;
import com.microsoft.azure.batch.protocol.Applications;
import com.microsoft.azure.batch.protocol.BatchServiceClient;
import com.microsoft.azure.batch.protocol.Certificates;
import com.microsoft.azure.batch.protocol.ComputeNodes;
import com.microsoft.azure.batch.protocol.Files;
import com.microsoft.azure.batch.protocol.Jobs;
import com.microsoft.azure.batch.protocol.JobSchedules;
import com.microsoft.azure.batch.protocol.Pools;
import com.microsoft.azure.batch.protocol.Tasks;
import com.microsoft.azure.RestClient;
import com.microsoft.rest.credentials.ServiceClientCredentials;
/**
* Initializes a new instance of the BatchServiceClientImpl class.
*/
public final class BatchServiceClientImpl extends AzureServiceClient implements BatchServiceClient {
/** the {@link AzureClient} used for long running operations. */
private AzureClient azureClient;
/**
* Gets the {@link AzureClient} used for long running operations.
* @return the azure client;
*/
public AzureClient getAzureClient() {
return this.azureClient;
}
/** Client API Version. */
private String apiVersion;
/**
* Gets Client API Version.
*
* @return the apiVersion value.
*/
public String apiVersion() {
return this.apiVersion;
}
/** Gets or sets the preferred language for the response. */
private String acceptLanguage;
/**
* Gets Gets or sets the preferred language for the response.
*
* @return the acceptLanguage value.
*/
public String acceptLanguage() {
return this.acceptLanguage;
}
/**
* Sets Gets or sets the preferred language for the response.
*
* @param acceptLanguage the acceptLanguage value.
* @return the service client itself
*/
public BatchServiceClientImpl withAcceptLanguage(String acceptLanguage) {
this.acceptLanguage = acceptLanguage;
return this;
}
/** Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. */
private int longRunningOperationRetryTimeout;
/**
* Gets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30.
*
* @return the longRunningOperationRetryTimeout value.
*/
public int longRunningOperationRetryTimeout() {
return this.longRunningOperationRetryTimeout;
}
/**
* Sets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30.
*
* @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value.
* @return the service client itself
*/
public BatchServiceClientImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) {
this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout;
return this;
}
/** When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */
private boolean generateClientRequestId;
/**
* Gets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true.
*
* @return the generateClientRequestId value.
*/
public boolean generateClientRequestId() {
return this.generateClientRequestId;
}
/**
* Sets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true.
*
* @param generateClientRequestId the generateClientRequestId value.
* @return the service client itself
*/
public BatchServiceClientImpl withGenerateClientRequestId(boolean generateClientRequestId) {
this.generateClientRequestId = generateClientRequestId;
return this;
}
/**
* The Applications object to access its operations.
*/
private Applications applications;
/**
* Gets the Applications object to access its operations.
* @return the Applications object.
*/
public Applications applications() {
return this.applications;
}
/**
* The Pools object to access its operations.
*/
private Pools pools;
/**
* Gets the Pools object to access its operations.
* @return the Pools object.
*/
public Pools pools() {
return this.pools;
}
/**
* The Accounts object to access its operations.
*/
private Accounts accounts;
/**
* Gets the Accounts object to access its operations.
* @return the Accounts object.
*/
public Accounts accounts() {
return this.accounts;
}
/**
* The Jobs object to access its operations.
*/
private Jobs jobs;
/**
* Gets the Jobs object to access its operations.
* @return the Jobs object.
*/
public Jobs jobs() {
return this.jobs;
}
/**
* The Certificates object to access its operations.
*/
private Certificates certificates;
/**
* Gets the Certificates object to access its operations.
* @return the Certificates object.
*/
public Certificates certificates() {
return this.certificates;
}
/**
* The Files object to access its operations.
*/
private Files files;
/**
* Gets the Files object to access its operations.
* @return the Files object.
*/
public Files files() {
return this.files;
}
/**
* The JobSchedules object to access its operations.
*/
private JobSchedules jobSchedules;
/**
* Gets the JobSchedules object to access its operations.
* @return the JobSchedules object.
*/
public JobSchedules jobSchedules() {
return this.jobSchedules;
}
/**
* The Tasks object to access its operations.
*/
private Tasks tasks;
/**
* Gets the Tasks object to access its operations.
* @return the Tasks object.
*/
public Tasks tasks() {
return this.tasks;
}
/**
* The ComputeNodes object to access its operations.
*/
private ComputeNodes computeNodes;
/**
* Gets the ComputeNodes object to access its operations.
* @return the ComputeNodes object.
*/
public ComputeNodes computeNodes() {
return this.computeNodes;
}
/**
* Initializes an instance of BatchServiceClient client.
*
* @param credentials the management credentials for Azure
*/
public BatchServiceClientImpl(ServiceClientCredentials credentials) {
this("https://batch.core.windows.net", credentials);
}
/**
* Initializes an instance of BatchServiceClient client.
*
* @param baseUrl the base URL of the host
* @param credentials the management credentials for Azure
*/
public BatchServiceClientImpl(String baseUrl, ServiceClientCredentials credentials) {
this(new RestClient.Builder()
.withBaseUrl(baseUrl)
.withCredentials(credentials)
.build());
}
/**
* Initializes an instance of BatchServiceClient client.
*
* @param restClient the REST client to connect to Azure.
*/
public BatchServiceClientImpl(RestClient restClient) {
super(restClient);
initialize();
}
protected void initialize() {
this.apiVersion = "2016-07-01.3.1";
this.acceptLanguage = "en-US";
this.longRunningOperationRetryTimeout = 30;
this.generateClientRequestId = true;
this.applications = new ApplicationsImpl(restClient().retrofit(), this);
this.pools = new PoolsImpl(restClient().retrofit(), this);
this.accounts = new AccountsImpl(restClient().retrofit(), this);
this.jobs = new JobsImpl(restClient().retrofit(), this);
this.certificates = new CertificatesImpl(restClient().retrofit(), this);
this.files = new FilesImpl(restClient().retrofit(), this);
this.jobSchedules = new JobSchedulesImpl(restClient().retrofit(), this);
this.tasks = new TasksImpl(restClient().retrofit(), this);
this.computeNodes = new ComputeNodesImpl(restClient().retrofit(), this);
this.azureClient = new AzureClient(this);
}
/**
* Gets the User-Agent header for the client.
*
* @return the user agent string.
*/
@Override
public String userAgent() {
return String.format("Azure-SDK-For-Java/%s (%s)",
getClass().getPackage().getImplementationVersion(),
"BatchServiceClient, 2016-07-01.3.1");
}
}
| mit |
andydandy74/ClockworkForDynamo | nodes/1.x/python/View.ResizeCropBox.py | 839 | import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc = DocumentManager.Instance.CurrentDBDocument
views = UnwrapElement(IN[0])
margin = IN[1].ToXyz()
booleans = []
TransactionManager.Instance.EnsureInTransaction(doc)
for item in views:
try:
newmax = item.CropBox.Max.Add(margin)
newmin = item.CropBox.Min.Subtract(margin)
newbox = BoundingBoxXYZ()
newbox.Max = newmax
newbox.Min = newmin
item.CropBox = newbox
booleans.append(True)
except:
booleans.append(False)
TransactionManager.Instance.TransactionTaskDone()
OUT = (views,booleans) | mit |
NaosProject/Naos.MessageBus | Naos.MessageBus.Hangfire.Sender/.recipes/Spritely.Redo/RetriableFunction.cs | 6826 | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="RetriableFunction.cs">
// Copyright (c) 2016. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <auto-generated>
// Sourced from NuGet package. Will be overwritten with package update except in Spritely.Redo source.
// </auto-generated>
// --------------------------------------------------------------------------------------------------------------------
namespace Spritely.Redo
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
/// <summary>
/// Represents a retriable operation which can accumulate terminating conditions using .Until(...)
/// or perform the execution using .Now().
/// </summary>
/// <typeparam name="T">The type of operation (must be the type of the child class).</typeparam>
#if !SpritelyRecipesProject
[System.Diagnostics.DebuggerStepThrough]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[System.CodeDom.Compiler.GeneratedCode("Spritely.Recipes", "See package version number")]
#pragma warning disable 0436
#endif
internal partial class RetriableFunction<T>
{
private readonly Func<long, TimeSpan> getDelay;
private readonly long maxRetries;
private readonly Action<Exception> report;
private readonly ICollection<Type> exceptionsToRetryOn;
private readonly ICollection<Type> exceptionsToThrowOn;
private readonly Func<T> operation;
private readonly ICollection<Func<T, bool>> untilValids = new List<Func<T, bool>>();
/// <summary>
/// Initializes a new instance of the <see cref="RetriableFunction{T}"/> class.
/// </summary>
/// <param name="getDelay">The function that determines the next delay given the current attempt number.</param>
/// <param name="maxRetries">The maximum number of retries to perform the operation before giving up and throwing the underlying exception.</param>
/// <param name="report">The function that reports on any exceptions as they occur (even if they are handled).</param>
/// <param name="exceptionsToRetryOn">The exceptions to retry on.</param>
/// <param name="exceptionsToThrowOn">The exceptions to throw on.</param>
/// <param name="operation">The operation to execute and retry as needed.</param>
public RetriableFunction(Func<long, TimeSpan> getDelay, long maxRetries, Action<Exception> report, ICollection<Type> exceptionsToRetryOn, ICollection<Type> exceptionsToThrowOn, Func<T> operation)
{
if (getDelay == null)
{
throw new ArgumentNullException("getDelay");
}
if (maxRetries < 1)
{
throw new ArgumentOutOfRangeException("maxRetries", maxRetries, "Value must be at least 1.");
}
if (report == null)
{
throw new ArgumentNullException("report");
}
if (exceptionsToRetryOn == null)
{
throw new ArgumentNullException("exceptionsToRetryOn");
}
if (exceptionsToThrowOn == null)
{
throw new ArgumentNullException("exceptionsToThrowOn");
}
if (operation == null)
{
throw new ArgumentNullException("operation");
}
this.getDelay = getDelay;
this.maxRetries = maxRetries;
this.report = report;
this.exceptionsToRetryOn = exceptionsToRetryOn;
this.exceptionsToThrowOn = exceptionsToThrowOn;
this.operation = operation;
}
/// <summary>
/// Adds a validity check the value must pass before it is considered valid.
/// If multiple Until values are provided then if Any pass the value is considered valid.
/// </summary>
/// <param name="isValid">The function to call to verify validity.</param>
/// <returns>This instance for chaining other operations.</returns>
public RetriableFunction<T> Until(Func<T, bool> isValid)
{
if (isValid == null)
{
throw new ArgumentNullException("isValid");
}
untilValids.Add(isValid);
return this;
}
/// <summary>
/// Specify that a retry should occur any time the result of Run is null.
/// </summary>
/// <returns>This instance for chaining other operations.</returns>
public RetriableFunction<T> UntilNotNull()
{
untilValids.Add(value => value != null);
return this;
}
/// <summary>
/// Performs the operation Now retrying as appropriate.
/// </summary>
/// <returns>The result of the operation.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)", Justification = "Do not want to be putting resources into client assemblies for the recipe.")]
public T Now()
{
var attempt = 0L;
while (true)
{
try
{
var result = operation();
if (!untilValids.Any() || untilValids.Any(isValid => isValid(result)))
{
return result;
}
if (attempt >= maxRetries)
{
throw new TimeoutException($"Execution timed out after {maxRetries} attempts.");
}
}
catch (Exception ex)
{
report(ex);
var shouldThrow = exceptionsToThrowOn.Any(t => t.IsInstanceOfType(ex));
// If there are no exception handlers then handle all exceptions by default
var shouldHandle = !exceptionsToRetryOn.Any() ||
exceptionsToRetryOn.Any(t => t.IsInstanceOfType(ex));
if (shouldThrow || !shouldHandle)
{
throw;
}
if (attempt >= maxRetries)
{
throw;
}
}
var delay = getDelay(attempt++);
Task.Delay(delay).Wait();
}
}
}
#if !SpritelyRecipesProject
#pragma warning restore 0436
#endif
}
| mit |
sufuf3/cdnjs | ajax/libs/froala-editor/3.0.4/js/languages/sk.js | 11499 | /*!
* froala_editor v3.0.4 (https://www.froala.com/wysiwyg-editor)
* License https://froala.com/wysiwyg-editor/terms/
* Copyright 2014-2019 Froala Labs
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) :
typeof define === 'function' && define.amd ? define(['froala-editor'], factory) :
(factory(global.FroalaEditor));
}(this, (function (FE) { 'use strict';
FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE;
/**
* Slovak
*/
FE.LANGUAGE['sk'] = {
translation: {
// Place holder
'Type something': 'Napíšte hocičo',
// Basic formatting
'Bold': 'Tučné',
'Italic': 'Kurzíva',
'Underline': 'Podčiarknuté',
'Strikethrough': 'Preškrtnuté',
// Main buttons
'Insert': 'Vložiť',
'Delete': 'Vymazať',
'Cancel': 'Zrušiť',
'OK': 'OK',
'Back': 'Späť',
'Remove': 'Odstrániť',
'More': 'Viac',
'Update': 'Aktualizovať',
'Style': 'Štýl',
// Font
'Font Family': 'Typ písma',
'Font Size': 'Veľkosť písma',
// Colors
'Colors': 'Farby',
'Background': 'Pozadie',
'Text': 'Text',
'HEX Color': 'Hex Farby',
// Paragraphs
'Paragraph Format': 'Formát odstavca',
'Normal': 'Normálne',
'Code': 'Kód',
'Heading 1': 'Nadpis 1',
'Heading 2': 'Nadpis 2',
'Heading 3': 'Nadpis 3',
'Heading 4': 'Nadpis 4',
// Style
'Paragraph Style': 'Štýl odstavca',
'Inline Style': 'Inline štýl',
// Alignment
'Align': 'Zarovnanie',
'Align Left': 'Zarovnať vľavo',
'Align Center': 'Zarovnať na stred',
'Align Right': 'Zarovnať vpravo',
'Align Justify': 'Zarovnať do bloku',
'None': 'Žiadne',
// Lists
'Ordered List': 'Číslovaný zoznam',
'Default': 'Štandardné',
'Lower Alpha': 'Nižšia alfa',
'Lower Greek': 'Nižšie grécke',
'Lower Roman': 'Nižší roman',
'Upper Alpha': 'Horná alfa',
'Upper Roman': 'Horný román',
'Unordered List': 'Nečíslovaný zoznam',
'Circle': 'Kruh',
'Disc': 'Disk',
'Square': 'Štvorec',
// Line height
'Line Height': 'Výška riadku',
'Single': 'Jednojitá',
'Double': 'Dvojitá',
// Indent
'Decrease Indent': 'Zmenšiť odsadenie',
'Increase Indent': 'Zväčšiť odsadenie',
// Links
'Insert Link': 'Vložiť odkaz',
'Open in new tab': 'Otvoriť v novom okne',
'Open Link': 'Otvoriť odkaz',
'Edit Link': 'Upraviť odkaz',
'Unlink': 'Odstrániť odkaz',
'Choose Link': 'Vyberte odkaz',
// Images
'Insert Image': 'Vložiť obrázok',
'Upload Image': 'Nahrať obrázok',
'By URL': 'Z URL adresy',
'Browse': 'Vybrať',
'Drop image': 'Pretiahnite obrázok do tohto miesta',
'or click': 'alebo kliknite a vložte',
'Manage Images': 'Správa obrázkov',
'Loading': 'Nahrávam',
'Deleting': 'Odstraňujem',
'Tags': 'Značky',
'Are you sure? Image will be deleted.': 'Ste si istý? Obrázok bude odstranený.',
'Replace': 'Vymeniť',
'Uploading': 'Nahrávam',
'Loading image': 'Obrázok se načítavá',
'Display': 'Zobraziť',
'Inline': 'Inline',
'Break Text': 'Zalomenie textu',
'Alternative Text': 'Alternatívny text',
'Change Size': 'Zmeniť veľkosť',
'Width': 'Šírka',
'Height': 'Výška',
'Something went wrong. Please try again.': 'Niečo sa pokazilo. Prosím, skúste to znova.',
'Image Caption': 'Titulok obrázka',
'Advanced Edit': 'Pokročilá úprava',
// Video
'Insert Video': 'Vložiť video',
'Embedded Code': 'Vložený kód',
'Paste in a video URL': 'Vložte do adresy URL videa',
'Drop video': 'Drop video',
'Your browser does not support HTML5 video.': 'Váš prehliadač nepodporuje video html5.',
'Upload Video': 'Nahrať video',
// Tables
'Insert Table': 'Vložiť tabuľku',
'Table Header': 'Hlavička tabuľky',
'Remove Table': 'Odstraniť tabuľku',
'Table Style': 'Štýl tabuľky',
'Horizontal Align': 'Horizontálne zarovnanie',
'Row': 'Riadok',
'Insert row above': 'Vložiť riadok nad',
'Insert row below': 'Vložiť riadok pod',
'Delete row': 'Odstraniť riadok',
'Column': 'Stĺpec',
'Insert column before': 'Vložiť stĺpec vľavo',
'Insert column after': 'Vložiť stĺpec vpravo',
'Delete column': 'Odstraniť stĺpec',
'Cell': 'Bunka',
'Merge cells': 'Zlúčiť bunky',
'Horizontal split': 'Horizontálne rozdelenie',
'Vertical split': 'Vertikálne rozdelenie',
'Cell Background': 'Pozadie bunky',
'Vertical Align': 'Vertikálne zarovnání',
'Top': 'Hore',
'Middle': 'Vstrede',
'Bottom': 'Dole',
'Align Top': 'Zarovnat na hor',
'Align Middle': 'Zarovnat na stred',
'Align Bottom': 'Zarovnat na spodok',
'Cell Style': 'Štýl bunky',
// Files
'Upload File': 'Nahrať súbor',
'Drop file': 'Vložte súbor sem',
// Emoticons
'Emoticons': 'Emotikony',
'Grinning face': 'Tvár s úsmevom',
'Grinning face with smiling eyes': 'Tvár s úsmevom a očami',
'Face with tears of joy': 'Tvár so slzamy radosti',
'Smiling face with open mouth': 'Usmievajúca sa tvár s otvorenými ústami',
'Smiling face with open mouth and smiling eyes': 'Usmievajúca sa tvár s otvorenými ústami a očami',
'Smiling face with open mouth and cold sweat': 'Usmievajúca sa tvár s otvorenými ústami a studeným potom',
'Smiling face with open mouth and tightly-closed eyes': 'Usmievajúca sa tvár s otvorenými ústami a zavretými očami',
'Smiling face with halo': 'Usmievajúca sa tvár so svätožiarou',
'Smiling face with horns': 'Usmievajúca sa tvár s rohami',
'Winking face': 'Mrkajúca tvár',
'Smiling face with smiling eyes': 'Usmievajúca sa tvár s usmievajucími očami',
'Face savoring delicious food': 'Tvár vychutnávajúca si chutné jedlo',
'Relieved face': 'Spokojná tvár',
'Smiling face with heart-shaped eyes': 'Usmievajúca sa tvár s očami v tvare srdca',
'Smiling face with sunglasses': 'Usmievajúca sa tvár so slnečnými okuliarmi',
'Smirking face': 'Uškŕňajúca sa tvár',
'Neutral face': 'Neutrálna tvaŕ',
'Expressionless face': 'Bezvýrazná tvár',
'Unamused face': 'Nepobavená tvár',
'Face with cold sweat': 'Tvár so studeným potom',
'Pensive face': 'Zamyslená tvár',
'Confused face': 'Zmetená tvár',
'Confounded face': 'Nahnevaná tvár',
'Kissing face': 'Bozkavajúca tvár',
'Face throwing a kiss': 'Tvár hadzajúca pusu',
'Kissing face with smiling eyes': 'Bozkávajúca tvár s očami a úsmevom',
'Kissing face with closed eyes': 'Bozkávajúca tvár so zavretými očami',
'Face with stuck out tongue': 'Tvár s vyplazeným jazykom',
'Face with stuck out tongue and winking eye': 'Mrkajúca tvár s vyplazeným jazykom',
'Face with stuck out tongue and tightly-closed eyes': 'Tvár s vyplazeným jazykom a privretými očami',
'Disappointed face': 'Sklamaná tvár',
'Worried face': 'Obavajúca se tvár',
'Angry face': 'Nahnevaná tvár',
'Pouting face': 'Našpulená tvár',
'Crying face': 'Plačúca tvár',
'Persevering face': 'Húževnatá tvár',
'Face with look of triumph': 'Tvár s výrazom víťaza',
'Disappointed but relieved face': 'Sklamaná ale spokojná tvár',
'Frowning face with open mouth': 'Zamračená tvár s otvorenými ústami',
'Anguished face': 'Úzkostná tvár',
'Fearful face': 'Strachujúca sa tvár',
'Weary face': 'Unavená tvár',
'Sleepy face': 'Ospalá tvár',
'Tired face': 'Unavená tvár',
'Grimacing face': 'Tvár s grimasou',
'Loudly crying face': 'Nahlas pláčúca tvár',
'Face with open mouth': 'Tvár s otvoreným ústami',
'Hushed face': 'Mlčiaca tvár',
'Face with open mouth and cold sweat': 'Tvár s otvorenými ústami a studeným potom',
'Face screaming in fear': 'Tvár kričiaca strachom',
'Astonished face': 'Tvár v úžase',
'Flushed face': 'Sčervenanie v tvári',
'Sleeping face': 'Spiaca tvár',
'Dizzy face': 'Tvár vyjadrujúca závrat',
'Face without mouth': 'Tvár bez úst',
'Face with medical mask': 'Tvár s lekárskou maskou',
// Line breaker
'Break': 'Zalomenie',
// Math
'Subscript': 'Dolný index',
'Superscript': 'Horný index',
// Full screen
'Fullscreen': 'Celá obrazovka',
// Horizontal line
'Insert Horizontal Line': 'Vložiť vodorovnú čiaru',
// Clear formatting
'Clear Formatting': 'Vymazať formátovanie',
// Save
'Save': 'Uložiť',
// Undo, redo
'Undo': 'Späť',
'Redo': 'Znova',
// Select all
'Select All': 'Vybrať všetko',
// Code view
'Code View': 'Zobraziť html kód',
// Quote
'Quote': 'Citát',
'Increase': 'Zvýšiť',
'Decrease': 'Znížiť',
// Quick Insert
'Quick Insert': 'Vložiť zrýchlene',
// Spcial Characters
'Special Characters': 'Špeciálne znaky',
'Latin': 'Latinčina',
'Greek': 'Gréčtina',
'Cyrillic': 'Cyrilika',
'Punctuation': 'Interpunkcia',
'Currency': 'Mena',
'Arrows': 'Šípky',
'Math': 'Matematika',
'Misc': 'Rôzne',
// Print.
'Print': 'Vytlačiť',
// Spell Checker.
'Spell Checker': 'Kontrola pravopisu',
// Help
'Help': 'Pomoc',
'Shortcuts': 'Skratky',
'Inline Editor': 'Inline editor',
'Show the editor': 'Zobraziť editor',
'Common actions': 'Spoločné akcie',
'Copy': 'Kópie',
'Cut': 'Rez',
'Paste': 'Vložiť',
'Basic Formatting': 'Základné formátovanie',
'Increase quote level': 'Zvýšiť úroveň cenovej ponuky',
'Decrease quote level': 'Znížiť úroveň cenovej ponuky',
'Image / Video': 'Obrázok / video',
'Resize larger': 'Zmena veľkosti',
'Resize smaller': 'Zmeniť veľkosť',
'Table': 'Tabuľka',
'Select table cell': 'Vyberte bunku tabuľky',
'Extend selection one cell': 'Rozšíriť výber o jednu bunku',
'Extend selection one row': 'Rozšíriť výber o jeden riadok',
'Navigation': 'Navigácia',
'Focus popup / toolbar': 'Predvybrať popup / panel s nástrojmi',
'Return focus to previous position': 'Vrátiť kurzor na predchádzajúcu pozíciu',
// Embed.ly
'Embed URL': 'Vložiť adresu URL',
'Paste in a URL to embed': 'Vložte adresu URL pre vloženie',
// Word Paste.
'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': 'Vložený obsah vychádza z dokumentu Microsoft Word. Chcete formát zachovať alebo ho vyčistiť?',
'Keep': 'Zachovať',
'Clean': 'Vyčistiť',
'Word Paste Detected': 'Detekované vloženie z Wordu'
},
direction: 'ltr'
};
})));
//# sourceMappingURL=sk.js.map
| mit |
davehorton/drachtio-server | deps/boost_1_77_0/libs/beast/test/beast/ssl.cpp | 547 | //
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
// If including Windows.h generates errors, it
// means that min/max macros are being substituted.
#ifdef _MSC_VER
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif
// Test that header file is self-contained.
#include <boost/beast/ssl.hpp>
| mit |
20steps/alexa | web/wp-content/plugins/bwp-google-xml-sitemaps/src/common-functions.php | 484 | <?php
function bwp_gxs_get_filename($sitemap_name)
{
global $bwp_gxs;
// cache filename, use gz all the time to save space
// @todo save both .xml version and .xml.gz version
// append home_url to be WPMS compatible
$filename = 'gxs_' . md5($sitemap_name . '_' . home_url());
$filename .= '.xml.gz';
return trailingslashit($bwp_gxs->get_cache_directory()) . $filename;
}
function bwp_gxs_format_header_time($time)
{
return gmdate('D, d M Y H:i:s \G\M\T', (int) $time);
}
| mit |
putrinolab1/node-hmd | src/platform/win/LibOVR/Src/Util/Util_LatencyTest2Reader.cpp | 3478 | /************************************************************************************
Filename : Util_LatencyTest2Reader.cpp
Content : Shared functionality for the DK2 latency tester
Created : July 8, 2014
Authors : Volga Aksoy, Chris Taylor
Copyright : Copyright 2014 Oculus VR, Inc. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.1
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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.
*************************************************************************************/
#include "Util_LatencyTest2Reader.h"
namespace OVR { namespace Util {
//// FrameTimeRecord
bool FrameTimeRecord::ColorToReadbackIndex(int *readbackIndex, unsigned char color)
{
int compareColor = color - LT2_ColorIncrement/2;
int index = color / LT2_ColorIncrement; // Use color without subtraction due to rounding.
int delta = compareColor - index * LT2_ColorIncrement;
if ((delta < LT2_PixelTestThreshold) && (delta > -LT2_PixelTestThreshold))
{
*readbackIndex = index;
return true;
}
return false;
}
unsigned char FrameTimeRecord::ReadbackIndexToColor(int readbackIndex)
{
OVR_ASSERT(readbackIndex < LT2_IncrementCount);
return (unsigned char)(readbackIndex * LT2_ColorIncrement + LT2_ColorIncrement/2);
}
//// FrameTimeRecordSet
FrameTimeRecordSet::FrameTimeRecordSet()
{
NextWriteIndex = 0;
memset(this, 0, sizeof(FrameTimeRecordSet));
}
void FrameTimeRecordSet::AddValue(int readValue, double timeSeconds)
{
Records[NextWriteIndex].ReadbackIndex = readValue;
Records[NextWriteIndex].TimeSeconds = timeSeconds;
NextWriteIndex++;
if (NextWriteIndex == RecordCount)
NextWriteIndex = 0;
}
// Matching should be done starting from NextWrite index
// until wrap-around
const FrameTimeRecord& FrameTimeRecordSet::operator [] (int i) const
{
return Records[(NextWriteIndex + i) & RecordMask];
}
const FrameTimeRecord& FrameTimeRecordSet::GetMostRecentFrame()
{
return Records[(NextWriteIndex - 1) & RecordMask];
}
// Advances I to absolute color index
bool FrameTimeRecordSet::FindReadbackIndex(int* i, int readbackIndex) const
{
for (; *i < RecordCount; (*i)++)
{
if ((*this)[*i].ReadbackIndex == readbackIndex)
return true;
}
return false;
}
bool FrameTimeRecordSet::IsAllZeroes() const
{
for (int i = 0; i < RecordCount; i++)
if (Records[i].ReadbackIndex != 0)
return false;
return true;
}
//// RecordStateReader
void RecordStateReader::GetRecordSet(FrameTimeRecordSet& recordset)
{
if(!Updater)
{
return;
}
recordset = Updater->SharedLatencyTestState.GetState();
return;
}
}} // namespace OVR::Util
| mit |
briandilley/jsonrpc4j | src/test/java/com/googlecode/jsonrpc4j/spring/serviceb/TemperatureImpl.java | 487 | package com.googlecode.jsonrpc4j.spring.serviceb;
import com.googlecode.jsonrpc4j.spring.AutoJsonRpcServiceImpl;
/**
* <p>This implementation should be picked up by the
* {@link com.googlecode.jsonrpc4j.spring.AutoJsonRpcServiceImplExporter}
* class.</p>
*/
@AutoJsonRpcServiceImpl(additionalPaths = {
"/api-web/temperature" // note the leading slash
})
public class TemperatureImpl implements Temperature {
@Override
public Integer currentTemperature() {
return 25;
}
}
| mit |
cmattoon/today-i-learned | scanner/src/menu.cpp | 18 | #include "menu.h"
| mit |
adaiguoguo/gitlab_globalserarch | app/services/issues/update_service.rb | 1326 | module Issues
class UpdateService < Issues::BaseService
def execute(issue)
state = params[:state_event]
case state
when 'reopen'
Issues::ReopenService.new(project, current_user, {}).execute(issue)
when 'close'
Issues::CloseService.new(project, current_user, {}).execute(issue)
when 'task_check'
issue.update_nth_task(params[:task_num].to_i, true)
when 'task_uncheck'
issue.update_nth_task(params[:task_num].to_i, false)
end
old_labels = issue.labels.to_a
if params.present? && issue.update_attributes(params.except(:state_event,
:task_num))
issue.reset_events_cache
if issue.labels != old_labels
create_labels_note(
issue, issue.labels - old_labels, old_labels - issue.labels)
end
if issue.previous_changes.include?('milestone_id')
create_milestone_note(issue)
end
if issue.previous_changes.include?('assignee_id')
create_assignee_note(issue)
notification_service.reassigned_issue(issue, current_user)
end
issue.notice_added_references(issue.project, current_user)
execute_hooks(issue, 'update')
end
issue
end
end
end
| mit |
ArcherSys/ArcherVMPeridot | htdocs/piwik/plugins/LanguagesManager/angularjs/translationsearch/translationsearch-controller.js | 530 | /*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
angular.module('piwikApp').controller('TranslationSearchController', function($scope, piwikApi) {
$scope.existingTranslations = [];
piwikApi.fetch({
method: 'LanguagesManager.getTranslationsForLanguage',
languageCode: 'en'
}).then(function (response) {
if (response) {
$scope.existingTranslations = response;
}
});
});
| mit |
rd-switchboard/Browser | applications/apps/spotlight/controllers/spotlight.php | 3963 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Spotlight extends MX_Controller {
function __construct()
{
parent::__construct();
$this->load->config('spotlight');
acl_enforce('PORTAL_STAFF');
}
function index(){
// $this->checkIsWriteable();
$data['js_lib'] = array('core', 'tinymce');
$data['scripts'] = array('spotlight');
$data['title'] = 'Spotlight CMS';
$data['less'] = array('spotlight');
$data['file'] = $this->read();
// $data['file'] = '{"items":[{"id":"1","title":"Sample Spotlight Data","url":"http:\/\/sample.org.au\/site\/","url_text":"","img_url":"http:\/\/www.auscope.org.au\/_lib\/img\/lnav_logo.gif","img_attr":"","new_window":"yes","content":"<p>This is a sample organisation.<\/p>","visible":"yes"}]}';
$data['items'] = $data['file']['items'];
$this->load->view('spotlight_cms', $data);
}
function add(){
$file = $this->read();
$items = $file['items'];
$new_file = array('items'=>array());
$largest_id = 0;
foreach($items as $i){
$new_file['items'][] = $this->getID($i['id'], $items);
if($i['id']>$largest_id) $largest_id = $i['id'];
}
$obj = array(
'id'=>$largest_id+1,
'title'=>$this->input->post('title'),
'url'=>$this->input->post('url'),
'url_text'=>$this->input->post('url_text'),
'img_url'=>$this->input->post('img_url'),
'img_attr'=>$this->input->post('img_attr'),
'new_window'=>$this->input->post('new_window'),
'content'=>$this->input->post('content'),
'visible'=>$this->input->post('visible')
);
$new_file['items'][] = $obj;
$this->write(json_encode($new_file));
}
function save($id){
//var_dump($this->input->post());
$obj = array(
'id'=>$id,
'title'=>$this->input->post('title'),
'url'=>$this->input->post('url'),
'url_text'=>$this->input->post('url_text'),
'img_url'=>$this->input->post('img_url'),
'img_attr'=>$this->input->post('img_attr'),
'new_window'=>$this->input->post('new_window'),
'content'=>$this->input->post('content'),
'visible'=>$this->input->post('visible')
);
$file = $this->read();
$items = $file['items'];
$new_file = array('items'=>array());
foreach($items as $i){
if($i['id']==$id){
$new_file['items'][] = $obj;
}else{
$new_file['items'][] = $this->getID($i['id'], $items);
}
}
$this->write(json_encode($new_file));
}
function saveOrder(){
$new_order = $this->input->post('data');
$file = $this->read();
$items = $file['items'];
$new_file = array('items'=>array());
foreach($new_order as $o){
if($item = $this->getID($o, $items)) $new_file['items'][] = $item;
}
$this->write(json_encode($new_file));
}
function delete($id){
$file = $this->read();
$items = $file['items'];
$items = $file['items'];
$new_file = array('items'=>array());
foreach($items as $i){
if($i['id']!=$id){
$new_file['items'][] = $this->getID($i['id'], $items);
}
}
//var_dump($new_file);
$this->write(json_encode($new_file));
}
private function checkIsWriteable()
{
if (!is_writable($this->config->item('spotlight_data_file')))
{
throw new Exception ("Spotlight Data File is not writeable - check file permission in: " . $this->config->item('spotlight_data_file'));
}
if(!file_exists($this->config->item('spotlight_data_file'))){
throw new Exception ("Spotlight Data File is not found - check file exists in: ". $this->config->item('spotlight_data_file'));
}
}
private function write($data){
$this->load->helper('file');
if(write_file($this->config->item('spotlight_data_file'), $data, 'w')){
echo 'success';
}else{
echo 'Unable to write to file. Check File Permission';
}
}
private function read(){
$this->load->helper('file');
$file = read_file($this->config->item('spotlight_data_file'));
return json_decode($file,true);
}
private function getID($id, $items){
foreach($items as $i){
if($i['id']==$id) return $i;
}
return false;
}
}
| mit |
amuniz/checkstyle-plugin | src/main/java/hudson/plugins/checkstyle/rules/TopicRule.java | 2598 | package hudson.plugins.checkstyle.rules;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.digester3.NodeCreateRule;
import org.apache.commons.lang.StringUtils;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Digester rule to parse the actual content of a DocBook subsection node. Does
* not interpret XML elements that are children of a subsection.
*
* @author Ulli Hafner
*/
public class TopicRule extends NodeCreateRule {
/**
* Instantiates a new topic rule.
*
* @throws ParserConfigurationException
* the parser configuration exception
*/
public TopicRule() throws ParserConfigurationException {
super(Node.ELEMENT_NODE);
}
@Override
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void end(final String namespace, final String name) throws Exception {
Element subsection = (Element)getDigester().pop();
String description = extractNoteContent(subsection);
MethodUtils.invokeExactMethod(getDigester().peek(), "setValue", description);
}
/**
* Extracts the node content. Basically returns every character in the
* subsection element.
*
* @param subsection
* the subsection of a rule
* @return the node content
* @throws ParserConfigurationException
* in case of an error
* @throws IOException
* in case of an error
*/
protected String extractNoteContent(final Element subsection) throws ParserConfigurationException,
IOException {
StringWriter writer = new StringWriter();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
OutputFormat format = new OutputFormat(doc);
format.setOmitXMLDeclaration(true);
XMLSerializer serializer = new XMLSerializer(writer, format);
serializer.serialize(subsection);
String serialized = writer.getBuffer().toString();
serialized = StringUtils.substringAfter(serialized, ">");
return StringUtils.substringBeforeLast(serialized, "<");
}
} | mit |
vincent-leonardo/sphero.js | Gruntfile.js | 1622 | "use strict";
var Mocha = require("mocha"),
uglify = require("uglify-js"),
ESLint = require("eslint").CLIEngine,
browserify = require("browserify");
module.exports = function(grunt) {
grunt.registerTask("default", ["lint", "test"]);
grunt.registerTask("lint", "Lints code with ESLint", function() {
var lint = new ESLint(),
files = ["index.js", "Gruntfile.js", "lib", "spec", "examples"],
formatter = lint.getFormatter();
var report = lint.executeOnFiles(files),
results = report.results;
grunt.log.write(formatter(results));
return report.errorCount === 0;
});
grunt.registerTask("test", "Runs specs with Mocha", function() {
var mocha = new Mocha({ reporter: "dot" }),
files = grunt.file.expand("spec/helper.js", "spec/lib/**/*.js"),
done = this.async();
files.forEach(mocha.addFile.bind(mocha));
mocha.run(function(errs) {
done(errs === 0);
});
});
grunt.registerTask("dist", "Builds UMD distributable", function() {
var b = browserify("index.js", { standalone: "sphero" }),
banner = "/*! Sphero.js (c) 2015 Orbotix. MIT License */\n",
done = this.async();
// don't include node-serialport, since the assumption is that this will be
// running in the browser
b.ignore("serialport");
b.bundle(function(err, buffer) {
if (err) {
console.error(err);
done(false);
}
var result = uglify.minify(buffer.toString(), { fromString: true });
grunt.file.write("dist/sphero.min.js", banner + result.code);
done(true);
});
});
};
| mit |
asonas/idobata-hooks | lib/hooks/mackerel/hook.rb | 367 | module Idobata::Hook
class Mackerel < Base
screen_name 'Mackerel'
icon_url 'https://github.com/mackerelio.png'
template_name { custom_template_name }
helper Helper
private
def custom_template_name
if payload.event == 'alert'
'alert.html.haml'
else
'default.html.haml'
end
end
end
end
| mit |
corydolphin/flask-cors | flask_cors/decorator.py | 4937 | # -*- coding: utf-8 -*-
"""
decorator
~~~~
This unit exposes a single decorator which should be used to wrap a
Flask route with. It accepts all parameters and options as
the CORS extension.
:copyright: (c) 2016 by Cory Dolphin.
:license: MIT, see LICENSE for more details.
"""
from functools import update_wrapper
from flask import make_response, request, current_app
from .core import *
LOG = logging.getLogger(__name__)
def cross_origin(*args, **kwargs):
"""
This function is the decorator which is used to wrap a Flask route with.
In the simplest case, simply use the default parameters to allow all
origins in what is the most permissive configuration. If this method
modifies state or performs authentication which may be brute-forced, you
should add some degree of protection, such as Cross Site Forgery
Request protection.
:param origins:
The origin, or list of origins to allow requests from.
The origin(s) may be regular expressions, case-sensitive strings,
or else an asterisk
Default : '*'
:type origins: list, string or regex
:param methods:
The method or list of methods which the allowed origins are allowed to
access for non-simple requests.
Default : [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]
:type methods: list or string
:param expose_headers:
The header or list which are safe to expose to the API of a CORS API
specification.
Default : None
:type expose_headers: list or string
:param allow_headers:
The header or list of header field names which can be used when this
resource is accessed by allowed origins. The header(s) may be regular
expressions, case-sensitive strings, or else an asterisk.
Default : '*', allow all headers
:type allow_headers: list, string or regex
:param supports_credentials:
Allows users to make authenticated requests. If true, injects the
`Access-Control-Allow-Credentials` header in responses. This allows
cookies and credentials to be submitted across domains.
:note: This option cannot be used in conjuction with a '*' origin
Default : False
:type supports_credentials: bool
:param max_age:
The maximum time for which this CORS request maybe cached. This value
is set as the `Access-Control-Max-Age` header.
Default : None
:type max_age: timedelta, integer, string or None
:param send_wildcard: If True, and the origins parameter is `*`, a wildcard
`Access-Control-Allow-Origin` header is sent, rather than the
request's `Origin` header.
Default : False
:type send_wildcard: bool
:param vary_header:
If True, the header Vary: Origin will be returned as per the W3
implementation guidelines.
Setting this header when the `Access-Control-Allow-Origin` is
dynamically generated (e.g. when there is more than one allowed
origin, and an Origin than '*' is returned) informs CDNs and other
caches that the CORS headers are dynamic, and cannot be cached.
If False, the Vary header will never be injected or altered.
Default : True
:type vary_header: bool
:param automatic_options:
Only applies to the `cross_origin` decorator. If True, Flask-CORS will
override Flask's default OPTIONS handling to return CORS headers for
OPTIONS requests.
Default : True
:type automatic_options: bool
"""
_options = kwargs
def decorator(f):
LOG.debug("Enabling %s for cross_origin using options:%s", f, _options)
# If True, intercept OPTIONS requests by modifying the view function,
# replicating Flask's default behavior, and wrapping the response with
# CORS headers.
#
# If f.provide_automatic_options is unset or True, Flask's route
# decorator (which is actually wraps the function object we return)
# intercepts OPTIONS handling, and requests will not have CORS headers
if _options.get('automatic_options', True):
f.required_methods = getattr(f, 'required_methods', set())
f.required_methods.add('OPTIONS')
f.provide_automatic_options = False
def wrapped_function(*args, **kwargs):
# Handle setting of Flask-Cors parameters
options = get_cors_options(current_app, _options)
if options.get('automatic_options') and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
set_cors_headers(resp, options)
setattr(resp, FLASK_CORS_EVALUATED, True)
return resp
return update_wrapper(wrapped_function, f)
return decorator
| mit |
loomnetwork/apig | _example/version/version.go | 1482 | package version
import (
"math"
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
func New(c *gin.Context) (string, error) {
ver := ""
header := c.Request.Header.Get("Accept")
header = strings.Join(strings.Fields(header), "")
if strings.Contains(header, "version=") {
ver = strings.Split(strings.SplitAfter(header, "version=")[1], ";")[0]
}
if v := c.Query("v"); v != "" {
ver = v
}
if ver == "" {
return "-1", nil
}
_, err := strconv.Atoi(strings.Join(strings.Split(ver, "."), ""))
if err != nil {
return "", err
}
return ver, nil
}
func Range(left string, op string, right string) bool {
switch op {
case "<":
return (compare(left, right) == -1)
case "<=":
return (compare(left, right) <= 0)
case ">":
return (compare(left, right) == 1)
case ">=":
return (compare(left, right) >= 0)
case "==":
return (compare(left, right) == 0)
}
return false
}
func compare(left string, right string) int {
// l > r : 1
// l == r : 0
// l < r : -1
if left == "-1" {
return 1
} else if right == "-1" {
return -1
}
lArr := strings.Split(left, ".")
rArr := strings.Split(right, ".")
lItems := len(lArr)
rItems := len(rArr)
min := int(math.Min(float64(lItems), float64(rItems)))
for i := 0; i < min; i++ {
l, _ := strconv.Atoi(lArr[i])
r, _ := strconv.Atoi(rArr[i])
if l != r {
if l > r {
return 1
}
return -1
}
}
if lItems == rItems {
return 0
}
if lItems < rItems {
return 1
}
return -1
}
| mit |
bezlio/bezlio-gallery | production-team-leader/versions/1.1/js/onDataChange.js | 11220 | define(["./employees.js"], function (employees) {
function OnDataChange (bezl) {
// Loop through the employees list and add them to bezl.vars.employees no matter what
// and to the team if the SupervisorID matches the currenly logged in user
if (bezl.data.Employees) {
bezl.vars.employees = [];
// Grab a reference to the logged in employee
var currentEmployee = bezl.data.Employees.find(e => e.EmployeeEmail == bezl.env.currentUser);
for (var i = 0; i < bezl.data.Employees.length; i++) {
bezl.vars.employees.push({ selected: false,
key: bezl.data.Employees[i].EmpID,
display: bezl.data.Employees[i].Name,
clockedIn: bezl.data.Employees[i].ClockedIn,
laborId: bezl.data.Employees[i].LaborID,
currentActivity: bezl.data.Employees[i].CurrentActivity,
laborType: bezl.data.Employees[i].LaborType,
pendingQty: bezl.data.Employees[i].PendingQty,
shift: bezl.data.Employees[i].Shift,
department: bezl.data.Employees[i].Department,
show: true
});
if ((bezl.vars.config.AssociateTeamBy == 'SupervisorEmail' && bezl.data.Employees[i].SupervisorEmail == bezl.env.currentUser)
|| (bezl.vars.config.AssociateTeamBy == 'DepartmentShift' && bezl.data.Employees[i].Department == currentEmployee.Department)
|| bezl.data.Employees[i].EmployeeEmail == bezl.env.currentUser
) {
var teamMemberFound = false;
for (var x = 0; x < bezl.vars.team.length; x++) {
if (bezl.vars.team[x].key == bezl.data.Employees[i].EmpID) {
var teamMemberFound = true;
bezl.vars.team[x].clockedIn = bezl.data.Employees[i].ClockedIn;
bezl.vars.team[x].laborId = bezl.data.Employees[i].LaborID;
bezl.vars.team[x].currentActivity = bezl.data.Employees[i].CurrentActivity;
bezl.vars.team[x].laborType = bezl.data.Employees[i].LaborType;
bezl.vars.team[x].pendingQty = bezl.data.Employees[i].PendingQty;
}
}
if (!teamMemberFound) {
bezl.vars.team.push({ selected: false,
key: bezl.data.Employees[i].EmpID,
display: bezl.data.Employees[i].Name,
clockedIn: bezl.data.Employees[i].ClockedIn,
laborId: bezl.data.Employees[i].LaborID,
currentActivity: bezl.data.Employees[i].CurrentActivity,
laborType: bezl.data.Employees[i].LaborType,
pendingQty: bezl.data.Employees[i].PendingQty,
employeeEmail: bezl.data.Employees[i].EmployeeEmail,
shift: bezl.data.Employees[i].Shift,
department: bezl.data.Employees[i].Department,
show: true
});
}
// Pull the shift from the database into bezl.vars.config.Shift
if (bezl.data.Employees[i].EmployeeEmail == bezl.env.currentUser) {
bezl.vars.shift = bezl.data.Employees[i].Shift;
}
}
}
// Custom sorting. Supervisor always first, then by shift, then by department.
bezl.vars.team.sort(function(a, b) {
var ae = a['employeeEmail'];
var be = b['employeeEmail'];
if (ae == bezl.env.currentUser) {
return -1;
} else {
// Now by shift
var as = a['shift'] || Number.MAX_SAFE_INTEGER;
var bs = b['shift'] || Number.MAX_SAFE_INTEGER;
if (be != bezl.env.currentUser && bs > as) {
return -1
} else {
// Lastly by department
var ad = a['department'];
var bd = b['department'];
if (be != bezl.env.currentUser && bs == as && bd > ad) {
return -1;
} else {
return 1;
}
}
}
});
// Configure the typeahead controls for the team search. For full documentation of
// available settings here see http://www.runningcoder.org/jquerytypeahead/documentation/
$('.js-typeahead-team').typeahead({
order: "asc",
maxItem: 8,
source: {
data: function() { return bezl.vars.employees; }
},
callback: {
onClick: function (node, a, item, event) {
employees.select(bezl, item);
}
}
});
$('.js-typeahead-team2').typeahead({
order: "asc",
maxItem: 8,
source: {
data: function() { return bezl.vars.employees; }
},
callback: {
onClick: function (node, a, item, event) {
employees.select(bezl, item);
}
}
});
// Tell the jsGrid to load up
$("#jsGridTeam").jsGrid("loadData");
employees.highlightSelected(bezl);
bezl.vars.loadingEmployees = false;
bezl.vars.refreshingTeam = false;
// Clean up Employees data subscription as we no longer need it
bezl.dataService.remove('Employees');
bezl.data.Employees = null;
}
// Populate the 'jobs' array if we got Team back
if (bezl.data.OpenJobs) {
bezl.vars.openJobs = [];
for (var i = 0; i < bezl.data.OpenJobs.length; i++) {
bezl.vars.openJobs.push({ jobId: bezl.data.OpenJobs[i].JobID,
jobDesc: bezl.data.OpenJobs[i].JobDesc,
data: bezl.data.OpenJobs[i],
pendingQty: bezl.data.OpenJobs[i].PendingQty,
show: true
});
}
bezl.vars.loadingJobs = false;
// Tell the jsGrid to load up
$("#jsGridJobs").jsGrid("loadData");
// Clean up CustList data subscription as we no longer need it
bezl.dataService.remove('OpenJobs');
bezl.data.OpenJobs = null;
}
if (bezl.data.ClockIn) {
bezl.vars.clockingIn = false;
if (bezl.vars.config.Platform == "Epicor905" || bezl.vars.config.Platform == "Epicor10") {
for (var i = 0; i < bezl.data.ClockIn.LaborHed.length; i++) {
for (var x = 0; x < bezl.vars.team.length; x++) {
if (bezl.vars.team[x].key == bezl.data.ClockIn.LaborHed[i].EmployeeNum) {
bezl.vars.team[x].LaborHed = bezl.data.ClockIn.LaborHed[i];
bezl.vars.team[x].clockedIn = 1;
}
}
}
}
bezl.dataService.remove('ClockIn');
bezl.data.ClockIn = null;
$("#jsGridTeam").jsGrid("loadData");
employees.highlightSelected(bezl);
}
if (bezl.data.ClockOut) {
bezl.vars.clockingOut = false;
switch (bezl.vars.config.Platform) {
case "Epicor905":
for (var i = 0; i < bezl.data.ClockOut.length; i++) {
for (var x = 0; x < bezl.vars.team.length; x++) {
if (bezl.vars.team[x].key == bezl.data.ClockOut[i].EmployeeNum && !bezl.data.ClockOut[i].Error) {
bezl.vars.team[x].LaborHed = [];
bezl.vars.team[x].currentActivity = '';
bezl.vars.team[x].clockedIn = 0;
}
}
}
break;
default:
break;
}
bezl.dataService.remove('ClockOut');
bezl.data.ClockOut = null;
$("#jsGridTeam").jsGrid("loadData");
employees.highlightSelected(bezl);
}
if (bezl.data.StartJob) {
bezl.vars.startingJob = false;
if (bezl.vars.config.Platform == "Epicor905" || bezl.vars.config.Platform == "Epicor10") {
for (var i = 0; i < bezl.data.StartJob.LaborHed.length; i++) {
for (var x = 0; x < bezl.vars.team.length; x++) {
if (bezl.vars.team[x].key == bezl.data.StartJob.LaborHed[i].EmployeeNum) {
bezl.vars.team[x].currentActivity = bezl.vars.selectedJob.jobId + ' (' + bezl.vars.selectedJob.laborType + ')';
bezl.vars.team[x].laborType = bezl.vars.selectedJob.laborType;
bezl.vars.team[x].pendingQty = bezl.vars.selectedJob.pendingQty;
}
}
}
}
bezl.dataService.remove('StartJob');
bezl.data.StartJob = null;
$("#jsGridTeam").jsGrid("loadData");
employees.highlightSelected(bezl);
}
if (bezl.data.EndActivities) {
bezl.vars.endingActivities = false;
if (bezl.vars.config.Platform == "Epicor905" || bezl.vars.config.Platform == "Epicor10") {
for (var i = 0; i < bezl.data.EndActivities.LaborHed.length; i++) {
for (var x = 0; x < bezl.vars.team.length; x++) {
if (bezl.vars.team[x].key == bezl.data.EndActivities.LaborHed[i].EmployeeNum) {
bezl.vars.team[x].currentActivity = '';
}
}
}
}
bezl.dataService.remove('EndActivities');
bezl.data.EndActivities = null;
$("#jsGridTeam").jsGrid("loadData");
employees.highlightSelected(bezl);
}
}
return {
onDataChange: OnDataChange
}
}); | mit |
RetroView/hecl | blender/hecl/armature.py | 1405 | import struct
def cook(writebuf, arm):
writebuf(struct.pack('I', len(arm.bones)))
for bone in arm.bones:
writebuf(struct.pack('I', len(bone.name)))
writebuf(bone.name.encode())
writebuf(struct.pack('fff', bone.head_local[0], bone.head_local[1], bone.head_local[2]))
if bone.parent:
writebuf(struct.pack('i', arm.bones.find(bone.parent.name)))
else:
writebuf(struct.pack('i', -1))
writebuf(struct.pack('I', len(bone.children)))
for child in bone.children:
writebuf(struct.pack('i', arm.bones.find(child.name)))
def draw(layout, context):
layout.prop_search(context.scene, 'hecl_arm_obj', context.scene, 'objects')
if not len(context.scene.hecl_arm_obj):
layout.label(text="Armature not specified", icon='ERROR')
elif context.scene.hecl_arm_obj not in context.scene.objects:
layout.label(text="'"+context.scene.hecl_arm_obj+"' not in scene", icon='ERROR')
else:
obj = context.scene.objects[context.scene.hecl_arm_obj]
if obj.type != 'ARMATURE':
layout.label(text="'"+context.scene.hecl_arm_obj+"' not an 'ARMATURE'", icon='ERROR')
import bpy
def register():
bpy.types.Scene.hecl_arm_obj = bpy.props.StringProperty(
name='HECL Armature Object',
description='Blender Armature Object to export during HECL\'s cook process')
| mit |
clydin/angular-cli | packages/angular_devkit/build_angular/src/utils/run-module-as-observable-fork.ts | 2586 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { BuilderOutput } from '@angular-devkit/architect';
import { ForkOptions, fork } from 'child_process';
import { resolve } from 'path';
import { Observable } from 'rxjs';
const treeKill = require('tree-kill');
export function runModuleAsObservableFork(
cwd: string,
modulePath: string,
exportName: string | undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
args: any[],
): Observable<BuilderOutput> {
return new Observable((obs) => {
const workerPath: string = resolve(__dirname, './run-module-worker.js');
const debugArgRegex = /--inspect(?:-brk|-port)?|--debug(?:-brk|-port)/;
const execArgv = process.execArgv.filter((arg) => {
// Remove debug args.
// Workaround for https://github.com/nodejs/node/issues/9435
return !debugArgRegex.test(arg);
});
const forkOptions: ForkOptions = ({
cwd,
execArgv,
} as {}) as ForkOptions;
// TODO: support passing in a logger to use as stdio streams
// if (logger) {
// (forkOptions as any).stdio = [
// 'ignore',
// logger.info, // make it a stream
// logger.error, // make it a stream
// ];
// }
const forkedProcess = fork(workerPath, undefined, forkOptions);
// Cleanup.
const killForkedProcess = () => {
if (forkedProcess && forkedProcess.pid) {
treeKill(forkedProcess.pid, 'SIGTERM');
}
};
// Handle child process exit.
const handleChildProcessExit = (code?: number) => {
killForkedProcess();
if (code && code !== 0) {
obs.error();
}
obs.next({ success: true });
obs.complete();
};
forkedProcess.once('exit', handleChildProcessExit);
forkedProcess.once('SIGINT', handleChildProcessExit);
forkedProcess.once('uncaughtException', handleChildProcessExit);
// Handle parent process exit.
const handleParentProcessExit = () => {
killForkedProcess();
};
process.once('exit', handleParentProcessExit);
process.once('SIGINT', handleParentProcessExit);
process.once('uncaughtException', handleParentProcessExit);
// Run module.
forkedProcess.send({
hash: '5d4b9a5c0a4e0f9977598437b0e85bcc',
modulePath,
exportName,
args,
});
// Teardown logic. When unsubscribing, kill the forked process.
return killForkedProcess;
});
}
| mit |
coderFirework/app | js/Cesium-Tiles/Source/Core/buildModuleUrl.js | 3106 | /*global define*/
define([
'../ThirdParty/Uri',
'./defined',
'./DeveloperError',
'./getAbsoluteUri',
'./joinUrls',
'require'
], function(
Uri,
defined,
DeveloperError,
getAbsoluteUri,
joinUrls,
require) {
'use strict';
/*global CESIUM_BASE_URL*/
var cesiumScriptRegex = /((?:.*\/)|^)cesium[\w-]*\.js(?:\W|$)/i;
function getBaseUrlFromCesiumScript() {
var scripts = document.getElementsByTagName('script');
for ( var i = 0, len = scripts.length; i < len; ++i) {
var src = scripts[i].getAttribute('src');
var result = cesiumScriptRegex.exec(src);
if (result !== null) {
return result[1];
}
}
return undefined;
}
var baseUrl;
function getCesiumBaseUrl() {
if (defined(baseUrl)) {
return baseUrl;
}
var baseUrlString;
if (typeof CESIUM_BASE_URL !== 'undefined') {
baseUrlString = CESIUM_BASE_URL;
} else {
baseUrlString = getBaseUrlFromCesiumScript();
}
//>>includeStart('debug', pragmas.debug);
if (!defined(baseUrlString)) {
throw new DeveloperError('Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL.');
}
//>>includeEnd('debug');
baseUrl = new Uri(getAbsoluteUri(baseUrlString));
return baseUrl;
}
function buildModuleUrlFromRequireToUrl(moduleID) {
//moduleID will be non-relative, so require it relative to this module, in Core.
return require.toUrl('../' + moduleID);
}
function buildModuleUrlFromBaseUrl(moduleID) {
return joinUrls(getCesiumBaseUrl(), moduleID);
}
var implementation;
var a;
/**
* Given a non-relative moduleID, returns an absolute URL to the file represented by that module ID,
* using, in order of preference, require.toUrl, the value of a global CESIUM_BASE_URL, or
* the base URL of the Cesium.js script.
*
* @private
*/
function buildModuleUrl(moduleID) {
if (!defined(implementation)) {
//select implementation
if (defined(require.toUrl)) {
implementation = buildModuleUrlFromRequireToUrl;
} else {
implementation = buildModuleUrlFromBaseUrl;
}
}
if (!defined(a)) {
a = document.createElement('a');
}
var url = implementation(moduleID);
a.href = url;
a.href = a.href; // IE only absolutizes href on get, not set
return a.href;
}
// exposed for testing
buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex;
/**
* Sets the base URL for resolving modules.
* @param {String} value The new base URL.
*/
buildModuleUrl.setBaseUrl = function(value) {
baseUrl = new Uri(value).resolve(new Uri(document.location.href));
};
return buildModuleUrl;
});
| mit |
SUSE/salt-netapi-client | src/test/java/com/suse/salt/netapi/calls/CallAsyncEventsTest.java | 10346 | package com.suse.salt.netapi.calls;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.suse.salt.netapi.client.SaltClient;
import com.suse.salt.netapi.client.impl.HttpAsyncClientImpl;
import com.suse.salt.netapi.datatypes.AuthMethod;
import com.suse.salt.netapi.datatypes.Batch;
import com.suse.salt.netapi.datatypes.Token;
import com.suse.salt.netapi.datatypes.target.Glob;
import com.suse.salt.netapi.errors.GenericError;
import com.suse.salt.netapi.errors.JsonParsingError;
import com.suse.salt.netapi.event.WebSocketEventStream;
import com.suse.salt.netapi.event.AbstractEventsTest;
import com.suse.salt.netapi.event.EventStream;
import com.suse.salt.netapi.exception.SaltException;
import com.suse.salt.netapi.results.Result;
import com.suse.salt.netapi.utils.ClientUtils;
import com.suse.salt.netapi.utils.TestUtils;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.websocket.DeploymentException;
/**
* Tests for callAsync() taking an event stream to return results as they come in.
*/
public class CallAsyncEventsTest extends AbstractEventsTest {
private static final int MOCK_HTTP_PORT = 8888;
@Rule
public WireMockRule wireMockRule = new WireMockRule(MOCK_HTTP_PORT);
static final AuthMethod AUTH = new AuthMethod(new Token());
private SaltClient client;
private CloseableHttpAsyncClient closeableHttpAsyncClient;
@Override
@Before
public void init() throws URISyntaxException, DeploymentException {
super.init();
URI uri = URI.create("http://localhost:" + MOCK_HTTP_PORT);
closeableHttpAsyncClient = TestUtils.defaultClient();
client = new SaltClient(uri, new HttpAsyncClientImpl(closeableHttpAsyncClient));
}
@After
public void cleanup() {
super.cleanup();
try {
closeableHttpAsyncClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public Class<?> config() {
return CallAsyncEventsTestMessages.class;
}
public static <T> CompletableFuture<T> completeAfter(T value, Duration duration) {
final CompletableFuture<T> promise = new CompletableFuture<>();
SCHEDULER.schedule(
() -> promise.complete(value), duration.toMillis(), MILLISECONDS
);
return promise;
}
private static final ScheduledExecutorService SCHEDULER =
Executors.newScheduledThreadPool(1);
private String json(String name) {
return ClientUtils.streamToString(CallAsyncEventsTest
.class.getResourceAsStream(name));
}
@Test
public void testAsyncCall() throws SaltException, InterruptedException {
stubFor(post(urlMatching("/"))
.withRequestBody(equalToJson(
json("/async_via_event_test_ping_request.json")
))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(json("/async_via_event_test_ping_response.json"))));
stubFor(post(urlMatching("/"))
.withRequestBody(equalToJson(
json("/async_via_event_list_job_request.json")
))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(json("/async_via_event_list_job_response.json"))));
EventStream events = new WebSocketEventStream(uri, new Token("token"), 0, 0, 0);
Map<String, CompletionStage<Result<Boolean>>> call =
com.suse.salt.netapi.calls.modules.Test.ping().callAsync(
client,
Glob.ALL,
AUTH,
events,
completeAfter(
new GenericError("canceled"),
Duration.of(7, ChronoUnit.SECONDS)
),
Optional.empty()
).toCompletableFuture().join().get();
CountDownLatch countDownLatch = new CountDownLatch(5);
Map<String, Result<Boolean>> results = new HashMap<>();
Map<String, Long> times = new HashMap<>();
call.forEach((key, value) -> {
value.whenComplete((v, e) -> {
if (v != null) {
results.put(key, v);
}
times.put(key, System.currentTimeMillis());
countDownLatch.countDown();
});
});
countDownLatch.await(10, TimeUnit.SECONDS);
assertEquals(5, results.size());
assertTrue(results.get("minion1").result().get());
assertTrue(results.get("minion2").error().get() instanceof JsonParsingError);
assertEquals("Expected BOOLEAN but was STRING at path $",
((JsonParsingError) results.get("minion2").error().get())
.getThrowable().getMessage());
long delay12 = times.get("minion2") - times.get("minion1");
assertTrue(delay12 >= 1000);
assertTrue(results.get("minion3").result().get());
long delay23 = times.get("minion3") - times.get("minion2");
assertTrue(delay23 >= 1000);
assertTrue(results.get("minion4").error().get() instanceof JsonParsingError);
assertEquals("Expected BOOLEAN but was STRING at path $", ((JsonParsingError)
results.get("minion4").error().get()).getThrowable().getMessage());
long delay42 = times.get("minion4") - times.get("minion2");
assertTrue(delay42 >= 1000);
assertTrue(results.get("minion5").error().get() instanceof GenericError);
assertEquals("canceled",
((GenericError) results.get("minion5").error().get()).getMessage());
}
@Test
public void testAsyncBatchCall() throws SaltException, InterruptedException {
stubFor(post(urlMatching("/"))
.withRequestBody(equalToJson(
json("/async_batch_via_event_test_ping_request.json")
))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(json("/async_via_event_test_ping_response.json"))));
stubFor(post(urlMatching("/"))
.withRequestBody(equalToJson(
json("/async_via_event_list_job_request.json")
))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(json("/async_via_event_list_job_response.json"))));
EventStream events = new WebSocketEventStream(uri, new Token("token"), 0, 0, 0);
Map<String, CompletionStage<Result<Boolean>>> call =
com.suse.salt.netapi.calls.modules.Test.ping().callAsync(
client,
Glob.ALL,
AUTH,
events,
completeAfter(
new GenericError("canceled"),
Duration.of(7, ChronoUnit.SECONDS)
),
Optional.of(Batch.asAmount(1))
).toCompletableFuture().join().get();
CountDownLatch countDownLatch = new CountDownLatch(5);
Map<String, Result<Boolean>> results = new HashMap<>();
Map<String, Long> times = new HashMap<>();
call.forEach((key, value) -> {
value.whenComplete((v, e) -> {
if (v != null) {
results.put(key, v);
}
times.put(key, System.currentTimeMillis());
countDownLatch.countDown();
});
});
countDownLatch.await(10, TimeUnit.SECONDS);
assertEquals(5, results.size());
assertTrue(results.get("minion1").result().get());
assertTrue(results.get("minion2").error().get() instanceof JsonParsingError);
assertEquals("Expected BOOLEAN but was STRING at path $",
((JsonParsingError) results.get("minion2").error().get())
.getThrowable().getMessage());
long delay12 = times.get("minion2") - times.get("minion1");
assertTrue(delay12 >= 1000);
assertTrue(results.get("minion3").result().get());
long delay23 = times.get("minion3") - times.get("minion2");
assertTrue(delay23 >= 1000);
assertTrue(results.get("minion4").error().get() instanceof JsonParsingError);
assertEquals("Expected BOOLEAN but was STRING at path $", ((JsonParsingError)
results.get("minion4").error().get()).getThrowable().getMessage());
long delay42 = times.get("minion4") - times.get("minion2");
assertTrue(delay42 >= 1000);
assertTrue(results.get("minion5").error().get() instanceof GenericError);
assertEquals("canceled",
((GenericError) results.get("minion5").error().get()).getMessage());
}
}
| mit |
sloria/pypi-cli | tests/test_utils.py | 148 | # -*- coding: utf-8 -*-
import pypi_cli as pypi
def test_no_division_by_zero_in_bargraph():
assert pypi.TICK not in pypi.bargraph({'foo': 0})
| mit |
Taebu/prq | application/language/korean/form_validation_lang.php | 2355 | <?php
$lang['required'] = "%s 필드가 필요합니다.";
$lang['isset'] = "%s 필드는 반드시 필요한 값입니다.";
$lang['valid_email'] = "%s 필드는 유효한 이메일 주소를 반드시 포함해야 합니다.";
$lang['valid_emails'] = "%s 필드는 모든 유효한 이메일 주소를 반드시 포함해야 합니다.";
$lang['valid_url'] = "%s 필드는 유효한 URL을 포함해야 합니다.";
$lang['valid_ip'] = "%s 필드는 유효한 IP를 포함해야 합니다.";
$lang['min_length'] = "%s 필드의 길이는 최소한 %s 개의 문자를 넘어야 합니다.";
$lang['max_length'] = "%s 필드의 길이는 최대 %s 개의 문자를 넘어서는 안됩니다.";
$lang['exact_length'] = "%s 필드의 길이는 정확히 %s 개의 문자여야 합니다.";
$lang['alpha'] = "%s 필드는 알파벳 문자만 포함할 수 있습니다.";
$lang['alpha_numeric'] = "%s 필드는 알파벳 문자와 숫자만 포함할 수 있습니다.";
$lang['alpha_dash'] = "%s 필드는 알파벳 문자와 숫자, 밑줄, 대시만 포함할 수 있습니다.";
$lang['numeric'] = "%s 필드는 반드시 숫자만 포함할 수 있습니다.";
$lang['is_numeric'] = "%s 필드는 반드시 숫자만 포함할 수 있습니다.";
$lang['integer'] = "%s 필드는 반드시 정수만 포함할 수 있습니다.";
$lang['matches'] = "%s 필드가 %s 필드와 일치하지 않습니다.";
$lang['is_natural'] = "%s 필드는 반드시 0과 자연수만 포함할 수 있습니다.";
$lang['is_natural_no_zero'] = "%s 필드는 반드시 0을 초과하는 자연수만 포함할 수 있습니다.";
$lang['regex_match'] = "The %s field is not in the correct format.";
$lang['is_unique'] = "The %s field must contain a unique value.";
$lang['decimal'] = "The %s field must contain a decimal number.";
$lang['less_than'] = "The %s field must contain a number less than %s.";
$lang['less_than_equal_to'] = "The %s field must contain a number less than or equal to %s.";
$lang['greater_than'] = "The %s field must contain a number greater than %s.";
$lang['greater_than_equal_to'] = "The %s field must contain a number greater than or equal to %s.";
/* End of file form_validation_lang.php */
/* Location: ./system/language/english/form_validation_lang.php */ | mit |
NateWardawg/godot | scene/2d/animated_sprite.cpp | 20316 | /*************************************************************************/
/* animated_sprite.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "animated_sprite.h"
#include "core/os/os.h"
#include "scene/scene_string_names.h"
#define NORMAL_SUFFIX "_normal"
Dictionary AnimatedSprite::_edit_get_state() const {
Dictionary state = Node2D::_edit_get_state();
state["offset"] = offset;
return state;
}
void AnimatedSprite::_edit_set_state(const Dictionary &p_state) {
Node2D::_edit_set_state(p_state);
set_offset(p_state["offset"]);
}
void AnimatedSprite::_edit_set_pivot(const Point2 &p_pivot) {
set_offset(get_offset() - p_pivot);
set_position(get_transform().xform(p_pivot));
}
Point2 AnimatedSprite::_edit_get_pivot() const {
return Vector2();
}
bool AnimatedSprite::_edit_use_pivot() const {
return true;
}
Rect2 AnimatedSprite::_edit_get_rect() const {
return _get_rect();
}
bool AnimatedSprite::_edit_use_rect() const {
if (!frames.is_valid() || !frames->has_animation(animation) || frame < 0 || frame >= frames->get_frame_count(animation)) {
return false;
}
Ref<Texture> t;
if (animation)
t = frames->get_frame(animation, frame);
if (t.is_null())
return false;
return true;
}
Rect2 AnimatedSprite::get_anchorable_rect() const {
return _get_rect();
}
Rect2 AnimatedSprite::_get_rect() const {
if (!frames.is_valid() || !frames->has_animation(animation) || frame < 0 || frame >= frames->get_frame_count(animation)) {
return Rect2();
}
Ref<Texture> t;
if (animation)
t = frames->get_frame(animation, frame);
if (t.is_null())
return Rect2();
Size2 s = t->get_size();
Point2 ofs = offset;
if (centered)
ofs -= s / 2;
if (s == Size2(0, 0))
s = Size2(1, 1);
return Rect2(ofs, s);
}
void SpriteFrames::add_frame(const StringName &p_anim, const Ref<Texture> &p_frame, int p_at_pos) {
Map<StringName, Anim>::Element *E = animations.find(p_anim);
ERR_FAIL_COND(!E);
if (p_at_pos >= 0 && p_at_pos < E->get().frames.size())
E->get().frames.insert(p_at_pos, p_frame);
else
E->get().frames.push_back(p_frame);
emit_changed();
}
int SpriteFrames::get_frame_count(const StringName &p_anim) const {
const Map<StringName, Anim>::Element *E = animations.find(p_anim);
ERR_FAIL_COND_V(!E, 0);
return E->get().frames.size();
}
void SpriteFrames::remove_frame(const StringName &p_anim, int p_idx) {
Map<StringName, Anim>::Element *E = animations.find(p_anim);
ERR_FAIL_COND(!E);
E->get().frames.remove(p_idx);
emit_changed();
}
void SpriteFrames::clear(const StringName &p_anim) {
Map<StringName, Anim>::Element *E = animations.find(p_anim);
ERR_FAIL_COND(!E);
E->get().frames.clear();
emit_changed();
}
void SpriteFrames::clear_all() {
animations.clear();
add_animation("default");
}
void SpriteFrames::add_animation(const StringName &p_anim) {
ERR_FAIL_COND(animations.has(p_anim));
animations[p_anim] = Anim();
animations[p_anim].normal_name = String(p_anim) + NORMAL_SUFFIX;
}
bool SpriteFrames::has_animation(const StringName &p_anim) const {
return animations.has(p_anim);
}
void SpriteFrames::remove_animation(const StringName &p_anim) {
animations.erase(p_anim);
}
void SpriteFrames::rename_animation(const StringName &p_prev, const StringName &p_next) {
ERR_FAIL_COND(!animations.has(p_prev));
ERR_FAIL_COND(animations.has(p_next));
Anim anim = animations[p_prev];
animations.erase(p_prev);
animations[p_next] = anim;
animations[p_next].normal_name = String(p_next) + NORMAL_SUFFIX;
}
Vector<String> SpriteFrames::_get_animation_list() const {
Vector<String> ret;
List<StringName> al;
get_animation_list(&al);
for (List<StringName>::Element *E = al.front(); E; E = E->next()) {
ret.push_back(E->get());
}
return ret;
}
void SpriteFrames::get_animation_list(List<StringName> *r_animations) const {
for (const Map<StringName, Anim>::Element *E = animations.front(); E; E = E->next()) {
r_animations->push_back(E->key());
}
}
Vector<String> SpriteFrames::get_animation_names() const {
Vector<String> names;
for (const Map<StringName, Anim>::Element *E = animations.front(); E; E = E->next()) {
names.push_back(E->key());
}
names.sort();
return names;
}
void SpriteFrames::set_animation_speed(const StringName &p_anim, float p_fps) {
ERR_FAIL_COND(p_fps < 0);
Map<StringName, Anim>::Element *E = animations.find(p_anim);
ERR_FAIL_COND(!E);
E->get().speed = p_fps;
}
float SpriteFrames::get_animation_speed(const StringName &p_anim) const {
const Map<StringName, Anim>::Element *E = animations.find(p_anim);
ERR_FAIL_COND_V(!E, 0);
return E->get().speed;
}
void SpriteFrames::set_animation_loop(const StringName &p_anim, bool p_loop) {
Map<StringName, Anim>::Element *E = animations.find(p_anim);
ERR_FAIL_COND(!E);
E->get().loop = p_loop;
}
bool SpriteFrames::get_animation_loop(const StringName &p_anim) const {
const Map<StringName, Anim>::Element *E = animations.find(p_anim);
ERR_FAIL_COND_V(!E, false);
return E->get().loop;
}
void SpriteFrames::_set_frames(const Array &p_frames) {
clear_all();
Map<StringName, Anim>::Element *E = animations.find(SceneStringNames::get_singleton()->_default);
ERR_FAIL_COND(!E);
E->get().frames.resize(p_frames.size());
for (int i = 0; i < E->get().frames.size(); i++)
E->get().frames.write[i] = p_frames[i];
}
Array SpriteFrames::_get_frames() const {
return Array();
}
Array SpriteFrames::_get_animations() const {
Array anims;
for (Map<StringName, Anim>::Element *E = animations.front(); E; E = E->next()) {
Dictionary d;
d["name"] = E->key();
d["speed"] = E->get().speed;
d["loop"] = E->get().loop;
Array frames;
for (int i = 0; i < E->get().frames.size(); i++) {
frames.push_back(E->get().frames[i]);
}
d["frames"] = frames;
anims.push_back(d);
}
return anims;
}
void SpriteFrames::_set_animations(const Array &p_animations) {
animations.clear();
for (int i = 0; i < p_animations.size(); i++) {
Dictionary d = p_animations[i];
ERR_CONTINUE(!d.has("name"));
ERR_CONTINUE(!d.has("speed"));
ERR_CONTINUE(!d.has("loop"));
ERR_CONTINUE(!d.has("frames"));
Anim anim;
anim.speed = d["speed"];
anim.loop = d["loop"];
Array frames = d["frames"];
for (int i = 0; i < frames.size(); i++) {
RES res = frames[i];
anim.frames.push_back(res);
}
animations[d["name"]] = anim;
}
}
void SpriteFrames::_bind_methods() {
ClassDB::bind_method(D_METHOD("add_animation", "anim"), &SpriteFrames::add_animation);
ClassDB::bind_method(D_METHOD("has_animation", "anim"), &SpriteFrames::has_animation);
ClassDB::bind_method(D_METHOD("remove_animation", "anim"), &SpriteFrames::remove_animation);
ClassDB::bind_method(D_METHOD("rename_animation", "anim", "newname"), &SpriteFrames::rename_animation);
ClassDB::bind_method(D_METHOD("get_animation_names"), &SpriteFrames::get_animation_names);
ClassDB::bind_method(D_METHOD("set_animation_speed", "anim", "speed"), &SpriteFrames::set_animation_speed);
ClassDB::bind_method(D_METHOD("get_animation_speed", "anim"), &SpriteFrames::get_animation_speed);
ClassDB::bind_method(D_METHOD("set_animation_loop", "anim", "loop"), &SpriteFrames::set_animation_loop);
ClassDB::bind_method(D_METHOD("get_animation_loop", "anim"), &SpriteFrames::get_animation_loop);
ClassDB::bind_method(D_METHOD("add_frame", "anim", "frame", "at_position"), &SpriteFrames::add_frame, DEFVAL(-1));
ClassDB::bind_method(D_METHOD("get_frame_count", "anim"), &SpriteFrames::get_frame_count);
ClassDB::bind_method(D_METHOD("get_frame", "anim", "idx"), &SpriteFrames::get_frame);
ClassDB::bind_method(D_METHOD("set_frame", "anim", "idx", "txt"), &SpriteFrames::set_frame);
ClassDB::bind_method(D_METHOD("remove_frame", "anim", "idx"), &SpriteFrames::remove_frame);
ClassDB::bind_method(D_METHOD("clear", "anim"), &SpriteFrames::clear);
ClassDB::bind_method(D_METHOD("clear_all"), &SpriteFrames::clear_all);
ClassDB::bind_method(D_METHOD("_set_frames"), &SpriteFrames::_set_frames);
ClassDB::bind_method(D_METHOD("_get_frames"), &SpriteFrames::_get_frames);
ADD_PROPERTYNZ(PropertyInfo(Variant::ARRAY, "frames", PROPERTY_HINT_NONE, "", 0), "_set_frames", "_get_frames"); //compatibility
ClassDB::bind_method(D_METHOD("_set_animations"), &SpriteFrames::_set_animations);
ClassDB::bind_method(D_METHOD("_get_animations"), &SpriteFrames::_get_animations);
ADD_PROPERTYNZ(PropertyInfo(Variant::ARRAY, "animations", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_animations", "_get_animations"); //compatibility
}
SpriteFrames::SpriteFrames() {
add_animation(SceneStringNames::get_singleton()->_default);
}
void AnimatedSprite::_validate_property(PropertyInfo &property) const {
if (!frames.is_valid())
return;
if (property.name == "animation") {
property.hint = PROPERTY_HINT_ENUM;
List<StringName> names;
frames->get_animation_list(&names);
names.sort_custom<StringName::AlphCompare>();
bool current_found = false;
for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
if (E->prev()) {
property.hint_string += ",";
}
property.hint_string += String(E->get());
if (animation == E->get()) {
current_found = true;
}
}
if (!current_found) {
if (property.hint_string == String()) {
property.hint_string = String(animation);
} else {
property.hint_string = String(animation) + "," + property.hint_string;
}
}
}
if (property.name == "frame") {
property.hint = PROPERTY_HINT_SPRITE_FRAME;
if (frames->has_animation(animation) && frames->get_frame_count(animation) > 1) {
property.hint_string = "0," + itos(frames->get_frame_count(animation) - 1) + ",1";
}
}
}
void AnimatedSprite::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_INTERNAL_PROCESS: {
if (frames.is_null())
return;
if (!frames->has_animation(animation))
return;
if (frame < 0)
return;
float speed = frames->get_animation_speed(animation) * speed_scale;
if (speed == 0)
return; //do nothing
float remaining = get_process_delta_time();
while (remaining) {
if (timeout <= 0) {
timeout = _get_frame_duration();
int fc = frames->get_frame_count(animation);
if (frame >= fc - 1) {
if (frames->get_animation_loop(animation)) {
emit_signal(SceneStringNames::get_singleton()->animation_finished);
frame = 0;
} else {
if (!is_over) {
emit_signal(SceneStringNames::get_singleton()->animation_finished);
is_over = true;
}
frame = fc - 1;
}
} else {
frame++;
}
update();
_change_notify("frame");
emit_signal(SceneStringNames::get_singleton()->frame_changed);
}
float to_process = MIN(timeout, remaining);
remaining -= to_process;
timeout -= to_process;
}
} break;
case NOTIFICATION_DRAW: {
if (frames.is_null())
return;
if (frame < 0)
return;
if (!frames->has_animation(animation))
return;
Ref<Texture> texture = frames->get_frame(animation, frame);
if (texture.is_null())
return;
Ref<Texture> normal = frames->get_normal_frame(animation, frame);
RID ci = get_canvas_item();
Size2i s;
s = texture->get_size();
Point2 ofs = offset;
if (centered)
ofs -= s / 2;
if (Engine::get_singleton()->get_use_pixel_snap()) {
ofs = ofs.floor();
}
Rect2 dst_rect(ofs, s);
if (hflip)
dst_rect.size.x = -dst_rect.size.x;
if (vflip)
dst_rect.size.y = -dst_rect.size.y;
texture->draw_rect_region(ci, dst_rect, Rect2(Vector2(), texture->get_size()), Color(1, 1, 1), false, normal);
} break;
}
}
void AnimatedSprite::set_sprite_frames(const Ref<SpriteFrames> &p_frames) {
if (frames.is_valid())
frames->disconnect("changed", this, "_res_changed");
frames = p_frames;
if (frames.is_valid())
frames->connect("changed", this, "_res_changed");
if (!frames.is_valid()) {
frame = 0;
} else {
set_frame(frame);
}
_change_notify();
_reset_timeout();
update();
update_configuration_warning();
}
Ref<SpriteFrames> AnimatedSprite::get_sprite_frames() const {
return frames;
}
void AnimatedSprite::set_frame(int p_frame) {
if (!frames.is_valid()) {
return;
}
if (frames->has_animation(animation)) {
int limit = frames->get_frame_count(animation);
if (p_frame >= limit)
p_frame = limit - 1;
}
if (p_frame < 0)
p_frame = 0;
if (frame == p_frame)
return;
frame = p_frame;
_reset_timeout();
update();
_change_notify("frame");
emit_signal(SceneStringNames::get_singleton()->frame_changed);
}
int AnimatedSprite::get_frame() const {
return frame;
}
void AnimatedSprite::set_speed_scale(float p_speed_scale) {
float elapsed = _get_frame_duration() - timeout;
speed_scale = MAX(p_speed_scale, 0.0f);
// We adapt the timeout so that the animation speed adapts as soon as the speed scale is changed
_reset_timeout();
timeout -= elapsed;
}
float AnimatedSprite::get_speed_scale() const {
return speed_scale;
}
void AnimatedSprite::set_centered(bool p_center) {
centered = p_center;
update();
item_rect_changed();
}
bool AnimatedSprite::is_centered() const {
return centered;
}
void AnimatedSprite::set_offset(const Point2 &p_offset) {
offset = p_offset;
update();
item_rect_changed();
_change_notify("offset");
}
Point2 AnimatedSprite::get_offset() const {
return offset;
}
void AnimatedSprite::set_flip_h(bool p_flip) {
hflip = p_flip;
update();
}
bool AnimatedSprite::is_flipped_h() const {
return hflip;
}
void AnimatedSprite::set_flip_v(bool p_flip) {
vflip = p_flip;
update();
}
bool AnimatedSprite::is_flipped_v() const {
return vflip;
}
void AnimatedSprite::_res_changed() {
set_frame(frame);
_change_notify("frame");
_change_notify("animation");
update();
}
void AnimatedSprite::_set_playing(bool p_playing) {
if (playing == p_playing)
return;
playing = p_playing;
_reset_timeout();
set_process_internal(playing);
}
bool AnimatedSprite::_is_playing() const {
return playing;
}
void AnimatedSprite::play(const StringName &p_animation) {
if (p_animation)
set_animation(p_animation);
_set_playing(true);
}
void AnimatedSprite::stop() {
_set_playing(false);
}
bool AnimatedSprite::is_playing() const {
return playing;
}
float AnimatedSprite::_get_frame_duration() {
if (frames.is_valid() && frames->has_animation(animation)) {
float speed = frames->get_animation_speed(animation) * speed_scale;
if (speed > 0) {
return 1.0 / speed;
}
}
return 0.0;
}
void AnimatedSprite::_reset_timeout() {
if (!playing)
return;
timeout = _get_frame_duration();
is_over = false;
}
void AnimatedSprite::set_animation(const StringName &p_animation) {
if (animation == p_animation)
return;
animation = p_animation;
_reset_timeout();
set_frame(0);
_change_notify();
update();
}
StringName AnimatedSprite::get_animation() const {
return animation;
}
String AnimatedSprite::get_configuration_warning() const {
if (frames.is_null()) {
return TTR("A SpriteFrames resource must be created or set in the 'Frames' property in order for AnimatedSprite to display frames.");
}
return String();
}
void AnimatedSprite::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_sprite_frames", "sprite_frames"), &AnimatedSprite::set_sprite_frames);
ClassDB::bind_method(D_METHOD("get_sprite_frames"), &AnimatedSprite::get_sprite_frames);
ClassDB::bind_method(D_METHOD("set_animation", "animation"), &AnimatedSprite::set_animation);
ClassDB::bind_method(D_METHOD("get_animation"), &AnimatedSprite::get_animation);
ClassDB::bind_method(D_METHOD("_set_playing", "playing"), &AnimatedSprite::_set_playing);
ClassDB::bind_method(D_METHOD("_is_playing"), &AnimatedSprite::_is_playing);
ClassDB::bind_method(D_METHOD("play", "anim"), &AnimatedSprite::play, DEFVAL(StringName()));
ClassDB::bind_method(D_METHOD("stop"), &AnimatedSprite::stop);
ClassDB::bind_method(D_METHOD("is_playing"), &AnimatedSprite::is_playing);
ClassDB::bind_method(D_METHOD("set_centered", "centered"), &AnimatedSprite::set_centered);
ClassDB::bind_method(D_METHOD("is_centered"), &AnimatedSprite::is_centered);
ClassDB::bind_method(D_METHOD("set_offset", "offset"), &AnimatedSprite::set_offset);
ClassDB::bind_method(D_METHOD("get_offset"), &AnimatedSprite::get_offset);
ClassDB::bind_method(D_METHOD("set_flip_h", "flip_h"), &AnimatedSprite::set_flip_h);
ClassDB::bind_method(D_METHOD("is_flipped_h"), &AnimatedSprite::is_flipped_h);
ClassDB::bind_method(D_METHOD("set_flip_v", "flip_v"), &AnimatedSprite::set_flip_v);
ClassDB::bind_method(D_METHOD("is_flipped_v"), &AnimatedSprite::is_flipped_v);
ClassDB::bind_method(D_METHOD("set_frame", "frame"), &AnimatedSprite::set_frame);
ClassDB::bind_method(D_METHOD("get_frame"), &AnimatedSprite::get_frame);
ClassDB::bind_method(D_METHOD("set_speed_scale", "speed_scale"), &AnimatedSprite::set_speed_scale);
ClassDB::bind_method(D_METHOD("get_speed_scale"), &AnimatedSprite::get_speed_scale);
ClassDB::bind_method(D_METHOD("_res_changed"), &AnimatedSprite::_res_changed);
ADD_SIGNAL(MethodInfo("frame_changed"));
ADD_SIGNAL(MethodInfo("animation_finished"));
ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "frames", PROPERTY_HINT_RESOURCE_TYPE, "SpriteFrames"), "set_sprite_frames", "get_sprite_frames");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "animation"), "set_animation", "get_animation");
ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "frame", PROPERTY_HINT_SPRITE_FRAME), "set_frame", "get_frame");
ADD_PROPERTYNO(PropertyInfo(Variant::REAL, "speed_scale"), "set_speed_scale", "get_speed_scale");
ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "playing"), "_set_playing", "_is_playing");
ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "centered"), "set_centered", "is_centered");
ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset");
ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "flip_h"), "set_flip_h", "is_flipped_h");
ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "flip_v"), "set_flip_v", "is_flipped_v");
}
AnimatedSprite::AnimatedSprite() {
centered = true;
hflip = false;
vflip = false;
frame = 0;
speed_scale = 1.0f;
playing = false;
animation = "default";
timeout = 0;
is_over = false;
}
| mit |
aspose-cells/Aspose.Cells-for-Cloud | SDKs/Aspose.Cells-Cloud-SDK-for-Ruby/lib/aspose_cells_cloud/models/comments_response.rb | 2132 | module AsposeCellsCloud
#
class CommentsResponse < BaseObject
attr_accessor :comments, :code, :status
# attribute mapping from ruby-style variable name to JSON key
def self.attribute_map
{
#
:'comments' => :'Comments',
#
:'code' => :'Code',
#
:'status' => :'Status'
}
end
# attribute type
def self.swagger_types
{
:'comments' => :'Comments',
:'code' => :'String',
:'status' => :'String'
}
end
def initialize(attributes = {})
return if !attributes.is_a?(Hash) || attributes.empty?
# convert string to symbol for hash key
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
if attributes[:'Comments']
self.comments = attributes[:'Comments']
end
if attributes[:'Code']
self.code = attributes[:'Code']
end
if attributes[:'Status']
self.status = attributes[:'Status']
end
end
def status=(status)
allowed_values = ["Continue", "SwitchingProtocols", "OK", "Created", "Accepted", "NonAuthoritativeInformation", "NoContent", "ResetContent", "PartialContent", "MultipleChoices", "Ambiguous", "MovedPermanently", "Moved", "Found", "Redirect", "SeeOther", "RedirectMethod", "NotModified", "UseProxy", "Unused", "TemporaryRedirect", "RedirectKeepVerb", "BadRequest", "Unauthorized", "PaymentRequired", "Forbidden", "NotFound", "MethodNotAllowed", "NotAcceptable", "ProxyAuthenticationRequired", "RequestTimeout", "Conflict", "Gone", "LengthRequired", "PreconditionFailed", "RequestEntityTooLarge", "RequestUriTooLong", "UnsupportedMediaType", "RequestedRangeNotSatisfiable", "ExpectationFailed", "UpgradeRequired", "InternalServerError", "NotImplemented", "BadGateway", "ServiceUnavailable", "GatewayTimeout", "HttpVersionNotSupported"]
if status && !allowed_values.include?(status)
fail "invalid value for 'status', must be one of #{allowed_values}"
end
@status = status
end
end
end
| mit |
stevenuray/XChange | xchange-kraken/src/main/java/org/knowm/xchange/kraken/dto/marketdata/KrakenSpreads.java | 2422 | package org.knowm.xchange.kraken.dto.marketdata;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import org.knowm.xchange.kraken.dto.marketdata.KrakenSpreads.KrakenSpreadsDeserializer;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
@JsonDeserialize(using = KrakenSpreadsDeserializer.class)
public class KrakenSpreads {
private final List<KrakenSpread> spreads;
private final long last;
public KrakenSpreads(List<KrakenSpread> spreads, long last) {
this.spreads = spreads;
this.last = last;
}
public long getLast() {
return last;
}
public List<KrakenSpread> getSpreads() {
return spreads;
}
@Override
public String toString() {
return "KrakenSpreads [spreads=" + spreads + ", last=" + last + "]";
}
static class KrakenSpreadsDeserializer extends JsonDeserializer<KrakenSpreads> {
@Override
public KrakenSpreads deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
List<KrakenSpread> krakenTrades = new ArrayList<KrakenSpread>();
long last = 0;
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
Iterator<Entry<String, JsonNode>> tradesResultIterator = node.fields();
while (tradesResultIterator.hasNext()) {
Entry<String, JsonNode> entry = tradesResultIterator.next();
String key = entry.getKey();
JsonNode value = entry.getValue();
if (key == "last") {
last = value.asLong();
} else if (value.isArray()) {
for (JsonNode jsonSpreadNode : value) {
long time = jsonSpreadNode.path(0).asLong();
BigDecimal bid = new BigDecimal(jsonSpreadNode.path(1).asText());
BigDecimal ask = new BigDecimal(jsonSpreadNode.path(2).asText());
krakenTrades.add(new KrakenSpread(time, bid, ask));
}
}
}
return new KrakenSpreads(krakenTrades, last);
}
}
}
| mit |
sufuf3/cdnjs | ajax/libs/react-trend/1.2.2/react-trend.js | 21571 | /*!
* react-trend v1.2.2
* MIT Licensed
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["Trend"] = factory(require("react"));
else
root["Trend"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_4__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(1);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _Trend = __webpack_require__(2);
Object.defineProperty(exports, 'default', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Trend).default;
}
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _Trend = __webpack_require__(3);
Object.defineProperty(exports, 'default', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_Trend).default;
}
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _jsxFileName = '/Users/josh/work/react-trend/src/components/Trend/Trend.js';
var _react = __webpack_require__(4);
var _react2 = _interopRequireDefault(_react);
var _utils = __webpack_require__(5);
var _DOM = __webpack_require__(6);
var _math = __webpack_require__(7);
var _misc = __webpack_require__(8);
var _Trend = __webpack_require__(9);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var propTypes = {
data: _react.PropTypes.arrayOf(_react.PropTypes.oneOfType([_react.PropTypes.number, _react.PropTypes.shape({
value: _react.PropTypes.number
})]).isRequired).isRequired,
smooth: _react.PropTypes.bool,
autoDraw: _react.PropTypes.bool,
autoDrawDuration: _react.PropTypes.number,
autoDrawEasing: _react.PropTypes.string,
width: _react.PropTypes.number,
height: _react.PropTypes.number,
padding: _react.PropTypes.number,
radius: _react.PropTypes.number,
gradient: _react.PropTypes.arrayOf(_react.PropTypes.string)
};
var defaultProps = {
radius: 10,
stroke: 'black',
padding: 8,
strokeWidth: 1,
autoDraw: false,
autoDrawDuration: 2000,
autoDrawEasing: 'ease'
};
var Trend = function (_Component) {
_inherits(Trend, _Component);
function Trend(props) {
_classCallCheck(this, Trend);
// Generate a random ID. This is important for distinguishing between
// Trend components on a page, so that they can have different keyframe
// animations.
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.trendId = (0, _misc.generateId)();
_this.gradientId = 'react-trend-vertical-gradient-' + _this.trendId;
return _this;
}
Trend.prototype.componentDidMount = function componentDidMount() {
var _props = this.props,
autoDraw = _props.autoDraw,
autoDrawDuration = _props.autoDrawDuration,
autoDrawEasing = _props.autoDrawEasing;
if (autoDraw) {
this.lineLength = this.path.getTotalLength();
var css = (0, _Trend.generateAutoDrawCss)({
id: this.trendId,
lineLength: this.lineLength,
duration: autoDrawDuration,
easing: autoDrawEasing
});
(0, _DOM.injectStyleTag)(css);
}
};
Trend.prototype.getDelegatedProps = function getDelegatedProps() {
return (0, _utils.omit)(this.props, Object.keys(propTypes));
};
Trend.prototype.renderGradientDefinition = function renderGradientDefinition() {
var _this2 = this;
var gradient = this.props.gradient;
return _react2.default.createElement(
'defs',
{
__source: {
fileName: _jsxFileName,
lineNumber: 79
},
__self: this
},
_react2.default.createElement(
'linearGradient',
{
id: this.gradientId,
x1: '0%',
y1: '0%',
x2: '0%',
y2: '100%',
__source: {
fileName: _jsxFileName,
lineNumber: 80
},
__self: this
},
gradient.slice().reverse().map(function (c, index) {
return _react2.default.createElement('stop', {
key: index,
offset: (0, _math.normalize)({
value: index,
min: 0,
// If we only supply a single colour, it will try to normalize
// between 0 and 0, which will create NaN. By making the `max`
// at least 1, we ensure single-color "gradients" work.
max: gradient.length - 1 || 1
}),
stopColor: c,
__source: {
fileName: _jsxFileName,
lineNumber: 88
},
__self: _this2
});
})
)
);
};
Trend.prototype.render = function render() {
var _this3 = this;
var _props2 = this.props,
data = _props2.data,
smooth = _props2.smooth,
width = _props2.width,
height = _props2.height,
padding = _props2.padding,
radius = _props2.radius,
gradient = _props2.gradient;
// We need at least 2 points to draw a graph.
if (!data || data.length < 2) {
return null;
}
// `data` can either be an array of numbers:
// [1, 2, 3]
// or, an array of objects containing a value:
// [ { value: 1 }, { value: 2 }, { value: 3 }]
//
// For now, we're just going to convert the second form to the first.
// Later on, if/when we support tooltips, we may adjust.
var plainValues = data.map(function (point) {
return typeof point === 'number' ? point : point.value;
});
// Our viewbox needs to be in absolute units, so we'll default to 300x75
// Our SVG can be a %, though; this is what makes it scalable.
// By defaulting to percentages, the SVG will grow to fill its parent
// container, preserving a 1/4 aspect ratio.
var viewBoxWidth = width || 300;
var viewBoxHeight = height || 75;
var svgWidth = width || '100%';
var svgHeight = height || '25%';
var normalizedValues = (0, _Trend.normalizeDataset)(plainValues, {
minX: padding,
maxX: viewBoxWidth - padding,
// NOTE: Because SVGs are indexed from the top left, but most data is
// indexed from the bottom left, we're inverting the Y min/max.
minY: viewBoxHeight - padding,
maxY: padding
});
var path = smooth ? (0, _DOM.buildSmoothPath)(normalizedValues, { radius: radius }) : (0, _DOM.buildLinearPath)(normalizedValues);
return _react2.default.createElement(
'svg',
_extends({
width: svgWidth,
height: svgHeight,
viewBox: '0 0 ' + viewBoxWidth + ' ' + viewBoxHeight
}, this.getDelegatedProps(), {
__source: {
fileName: _jsxFileName,
lineNumber: 156
},
__self: this
}),
gradient && this.renderGradientDefinition(),
_react2.default.createElement('path', {
ref: function ref(elem) {
_this3.path = elem;
},
id: 'react-trend-' + this.trendId,
d: path,
fill: 'none',
stroke: gradient ? 'url(#' + this.gradientId + ')' : undefined,
__source: {
fileName: _jsxFileName,
lineNumber: 164
},
__self: this
})
);
};
return Trend;
}(_react.Component);
Trend.propTypes = propTypes;
Trend.defaultProps = defaultProps;
exports.default = Trend;
/***/ },
/* 4 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_4__;
/***/ },
/* 5 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var range = exports.range = function range(to) {
return [].concat(Array(to).keys());
};
var pick = exports.pick = function pick(obj, keys) {
return keys.reduce(function (acc, key) {
var _extends2;
return _extends({}, acc, (_extends2 = {}, _extends2[key] = obj[key], _extends2));
}, {});
};
var omit = exports.omit = function omit(obj, keys) {
return Object.keys(obj).reduce(function (acc, key) {
var _extends3;
if (keys.indexOf(key) !== -1) {
return acc;
}
return _extends({}, acc, (_extends3 = {}, _extends3[key] = obj[key], _extends3));
}, {});
};
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.injectStyleTag = exports.buildSmoothPath = exports.buildLinearPath = undefined;
var _math = __webpack_require__(7);
var buildLinearPath = exports.buildLinearPath = function buildLinearPath(data) {
return data.reduce(function (path, _ref, index) {
var x = _ref.x,
y = _ref.y;
// The very first instruction needs to be a "move".
// The rest will be a "line".
var isFirstInstruction = index === 0;
var instruction = isFirstInstruction ? 'M' : 'L';
return '' + path + instruction + ' ' + x + ',' + y + '\n';
}, '');
};
var buildSmoothPath = exports.buildSmoothPath = function buildSmoothPath(data, _ref2) {
var radius = _ref2.radius;
var firstPoint = data[0],
otherPoints = data.slice(1);
return otherPoints.reduce(function (path, point, index) {
var next = otherPoints[index + 1];
var prev = otherPoints[index - 1] || firstPoint;
var isCollinear = next && (0, _math.checkForCollinearPoints)(prev, point, next);
if (!next || isCollinear) {
// The very last line in the sequence can just be a regular line.
return path + '\nL ' + point.x + ',' + point.y;
}
var distanceFromPrev = (0, _math.getDistanceBetween)(prev, point);
var distanceFromNext = (0, _math.getDistanceBetween)(next, point);
var threshold = Math.min(distanceFromPrev, distanceFromNext);
var isTooCloseForRadius = threshold / 2 < radius;
var radiusForPoint = isTooCloseForRadius ? threshold / 2 : radius;
var before = (0, _math.moveTo)(prev, point, radiusForPoint);
var after = (0, _math.moveTo)(next, point, radiusForPoint);
return [path, 'L ' + before.x + ',' + before.y, 'S ' + point.x + ',' + point.y + ' ' + after.x + ',' + after.y].join('\n');
}, 'M ' + firstPoint.x + ',' + firstPoint.y);
};
// Taken from Khan Academy's Aphrodite
// https://github.com/Khan/aphrodite/blob/master/src/inject.js
var styleTag = void 0;
var injectStyleTag = exports.injectStyleTag = function injectStyleTag(cssContents) {
if (styleTag == null) {
// Try to find a style tag with the `data-react-trend` attribute first.
styleTag = document.querySelector('style[data-react-trend]');
// If that doesn't work, generate a new style tag.
if (styleTag == null) {
// Taken from
// http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript
var head = document.head || document.getElementsByTagName('head')[0];
styleTag = document.createElement('style');
styleTag.type = 'text/css';
styleTag.setAttribute('data-react-trend', '');
head.appendChild(styleTag);
}
}
styleTag.appendChild(document.createTextNode(cssContents));
};
/***/ },
/* 7 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
/* eslint-disable no-restricted-properties */
/** normalize
* This lets us translate a value from one scale to another.
*
* @param {Number} value - Our initial value to translate
* @param {Number} min - the current minimum value possible
* @param {Number} max - the current maximum value possible
* @param {Number} scaleMin - the min value of the scale we're translating to
* @param {Number} scaleMax - the max value of the scale we're translating to
*
* @returns {Number} the value on its new scale
*/
var normalize = exports.normalize = function normalize(_ref) {
var value = _ref.value,
min = _ref.min,
max = _ref.max,
_ref$scaleMin = _ref.scaleMin,
scaleMin = _ref$scaleMin === undefined ? 0 : _ref$scaleMin,
_ref$scaleMax = _ref.scaleMax,
scaleMax = _ref$scaleMax === undefined ? 1 : _ref$scaleMax;
// If the `min` and `max` are the same value, it means our dataset is flat.
// For now, let's assume that flat data should be aligned to the bottom.
if (min === max) {
return scaleMin;
}
return scaleMin + (value - min) * (scaleMax - scaleMin) / (max - min);
};
/** moveTo
* the coordinate that lies at a midpoint between 2 lines, based on the radius
*
* @param {Object} to - Our initial point
* @param {Number} to.x - The x value of our initial point
* @param {Number} to.y - The y value of our initial point
* @param {Object} from - Our final point
* @param {Number} from.x - The x value of our final point
* @param {Number} from.y - The y value of our final point
* @param {Number} radius - The distance away from the final point
*
* @returns {Object} an object holding the x/y coordinates of the midpoint.
*/
var moveTo = exports.moveTo = function moveTo(to, from, radius) {
var vector = { x: to.x - from.x, y: to.y - from.y };
var length = Math.sqrt(vector.x * vector.x + vector.y * vector.y);
var unitVector = { x: vector.x / length, y: vector.y / length };
return {
x: from.x + unitVector.x * radius,
y: from.y + unitVector.y * radius
};
};
/** getDistanceBetween
* Simple formula derived from pythagoras to calculate the distance between
* 2 points on a plane.
*
* @param {Object} p1 - Our initial point
* @param {Number} p1.x - The x value of our initial point
* @param {Number} p1.y - The y value of our initial point
* @param {Object} p2 - Our final point
* @param {Number} p2.x - The x value of our final point
* @param {Number} p2.y - The y value of our final point
*
* @returns {Number} the distance between the points.
*/
var getDistanceBetween = exports.getDistanceBetween = function getDistanceBetween(p1, p2) {
return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
};
/** checkForCollinearPoints
* Figure out if the midpoint fits perfectly on a line between the two others.
*
* @param {Object} p1 - Our initial point
* @param {Number} p1.x - The x value of our initial point
* @param {Number} p1.y - The y value of our initial point
* @param {Object} p2 - Our mid-point
* @param {Number} p2.x - The x value of our mid-point
* @param {Number} p2.y - The y value of our mid-point
* @param {Object} p3 - Our final point
* @param {Number} p3.x - The x value of our final point
* @param {Number} p3.y - The y value of our final point
* @returns {Boolean} whether or not p2 sits on the line between p1 and p3.
*/
var checkForCollinearPoints = exports.checkForCollinearPoints = function checkForCollinearPoints(p1, p2, p3) {
return (p1.y - p2.y) * (p1.x - p3.x) === (p1.y - p3.y) * (p1.x - p2.x);
};
/***/ },
/* 8 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
// eslint-disable-next-line no-restricted-properties
var generateId = exports.generateId = function generateId() {
return Math.round(Math.random() * Math.pow(10, 16));
};
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.generateAutoDrawCss = exports.normalizeDataset = undefined;
var _math = __webpack_require__(7);
var normalizeDataset = exports.normalizeDataset = function normalizeDataset(data, _ref) {
var minX = _ref.minX,
maxX = _ref.maxX,
minY = _ref.minY,
maxY = _ref.maxY;
// For the X axis, we want to normalize it based on its index in the array.
// For the Y axis, we want to normalize it based on the element's value.
//
// X axis is easy: just evenly-space each item in the array.
// For the Y axis, we first need to find the min and max of our array,
// and then normalize those values between 0 and 1.
var boundariesX = { min: 0, max: data.length - 1 };
var boundariesY = { min: Math.min.apply(Math, data), max: Math.max.apply(Math, data) };
return data.map(function (point, index) {
return {
x: (0, _math.normalize)({
value: index,
min: boundariesX.min,
max: boundariesX.max,
scaleMin: minX,
scaleMax: maxX
}),
y: (0, _math.normalize)({
value: point,
min: boundariesY.min,
max: boundariesY.max,
scaleMin: minY,
scaleMax: maxY
})
};
});
};
var generateAutoDrawCss = exports.generateAutoDrawCss = function generateAutoDrawCss(_ref2) {
var id = _ref2.id,
lineLength = _ref2.lineLength,
duration = _ref2.duration,
easing = _ref2.easing;
// We do the animation using the dash array/offset trick
// https://css-tricks.com/svg-line-animation-works/
var autodrawKeyframeAnimation = '\n @keyframes react-trend-autodraw-' + id + ' {\n 0% {\n stroke-dasharray: ' + lineLength + ';\n stroke-dashoffset: ' + lineLength + '\n }\n 100% {\n stroke-dasharray: ' + lineLength + ';\n stroke-dashoffset: 0;\n }\n 100% {\n stroke-dashoffset: \'\';\n stroke-dasharray: \'\';\n }\n }\n ';
// One unfortunate side-effect of the auto-draw is that the line is
// actually 1 big dash, the same length as the line itself. If the
// line length changes (eg. radius change, new data), that dash won't
// be the same length anymore. We can fix that by removing those
// properties once the auto-draw is completed.
var cleanupKeyframeAnimation = '\n @keyframes react-trend-autodraw-cleanup-' + id + ' {\n to {\n stroke-dasharray: \'\';\n stroke-dashoffset: \'\';\n }\n }\n ';
return '\n ' + autodrawKeyframeAnimation + '\n\n ' + cleanupKeyframeAnimation + '\n\n #react-trend-' + id + ' {\n animation:\n react-trend-autodraw-' + id + ' ' + duration + 'ms ' + easing + ',\n react-trend-autodraw-cleanup-' + id + ' 1ms ' + duration + 'ms\n ;\n }\n ';
};
/***/ }
/******/ ])
});
; | mit |
friendsofagape/mt2414ui | node_modules/@angular/core/src/view/element.d.ts | 1737 | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { RendererType2 } from '../render/api';
import { SecurityContext } from '../sanitization/security';
import { BindingFlags, ElementData, ElementHandleEventFn, NodeDef, NodeFlags, QueryValueType, ViewData, ViewDefinitionFactory } from './types';
export declare function anchorDef(flags: NodeFlags, matchedQueriesDsl: null | [string | number, QueryValueType][], ngContentIndex: null | number, childCount: number, handleEvent?: null | ElementHandleEventFn, templateFactory?: ViewDefinitionFactory): NodeDef;
export declare function elementDef(checkIndex: number, flags: NodeFlags, matchedQueriesDsl: null | [string | number, QueryValueType][], ngContentIndex: null | number, childCount: number, namespaceAndName: string | null, fixedAttrs?: null | [string, string][], bindings?: null | [BindingFlags, string, string | SecurityContext | null][], outputs?: null | ([string, string])[], handleEvent?: null | ElementHandleEventFn, componentView?: null | ViewDefinitionFactory, componentRendererType?: RendererType2 | null): NodeDef;
export declare function createElement(view: ViewData, renderHost: any, def: NodeDef): ElementData;
export declare function listenToElementOutputs(view: ViewData, compView: ViewData, def: NodeDef, el: any): void;
export declare function checkAndUpdateElementInline(view: ViewData, def: NodeDef, v0: any, v1: any, v2: any, v3: any, v4: any, v5: any, v6: any, v7: any, v8: any, v9: any): boolean;
export declare function checkAndUpdateElementDynamic(view: ViewData, def: NodeDef, values: any[]): boolean;
| mit |
mmkassem/gitlabhq | spec/lib/gitlab/diff/diff_refs_spec.rb | 3690 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::Diff::DiffRefs do
let(:project) { create(:project, :repository) }
describe '#==' do
let(:commit) { project.commit('1a0b36b3cdad1d2ee32457c102a8c0b7056fa863') }
subject { commit.diff_refs }
context 'when shas are missing' do
let(:other) { described_class.new(base_sha: subject.base_sha, start_sha: subject.start_sha, head_sha: nil) }
it 'returns false' do
expect(subject).not_to eq(other)
end
end
context 'when shas are equal' do
let(:other) { described_class.new(base_sha: subject.base_sha, start_sha: subject.start_sha, head_sha: subject.head_sha) }
it 'returns true' do
expect(subject).to eq(other)
end
end
context 'when shas are unequal' do
let(:other) { described_class.new(base_sha: subject.base_sha, start_sha: subject.start_sha, head_sha: subject.head_sha.reverse) }
it 'returns false' do
expect(subject).not_to eq(other)
end
end
context 'when shas are truncated' do
context 'when sha prefixes are too short' do
let(:other) { described_class.new(base_sha: subject.base_sha[0, 4], start_sha: subject.start_sha[0, 4], head_sha: subject.head_sha[0, 4]) }
it 'returns false' do
expect(subject).not_to eq(other)
end
end
context 'when sha prefixes are equal' do
let(:other) { described_class.new(base_sha: subject.base_sha[0, 10], start_sha: subject.start_sha[0, 10], head_sha: subject.head_sha[0, 10]) }
it 'returns true' do
expect(subject).to eq(other)
end
end
context 'when sha prefixes are unequal' do
let(:other) { described_class.new(base_sha: subject.base_sha[0, 10], start_sha: subject.start_sha[0, 10], head_sha: subject.head_sha[0, 10].reverse) }
it 'returns false' do
expect(subject).not_to eq(other)
end
end
end
end
describe '#compare_in' do
context 'with diff refs for the initial commit' do
let(:commit) { project.commit('1a0b36b3cdad1d2ee32457c102a8c0b7056fa863') }
subject { commit.diff_refs }
it 'returns an appropriate comparison' do
compare = subject.compare_in(project)
expect(compare.diff_refs).to eq(subject)
end
end
context 'with diff refs for a commit' do
let(:commit) { project.commit('6f6d7e7ed97bb5f0054f2b1df789b39ca89b6ff9') }
subject { commit.diff_refs }
it 'returns an appropriate comparison' do
compare = subject.compare_in(project)
expect(compare.diff_refs).to eq(subject)
end
end
context 'with diff refs for a comparison through the base' do
subject do
described_class.new(
start_sha: '0b4bc9a49b562e85de7cc9e834518ea6828729b9', # feature
base_sha: 'ae73cb07c9eeaf35924a10f713b364d32b2dd34f',
head_sha: 'e63f41fe459e62e1228fcef60d7189127aeba95a' # master
)
end
it 'returns an appropriate comparison' do
compare = subject.compare_in(project)
expect(compare.diff_refs).to eq(subject)
end
end
context 'with diff refs for a straight comparison' do
subject do
described_class.new(
start_sha: '0b4bc9a49b562e85de7cc9e834518ea6828729b9', # feature
base_sha: '0b4bc9a49b562e85de7cc9e834518ea6828729b9',
head_sha: 'e63f41fe459e62e1228fcef60d7189127aeba95a' # master
)
end
it 'returns an appropriate comparison' do
compare = subject.compare_in(project)
expect(compare.diff_refs).to eq(subject)
end
end
end
end
| mit |
Liedx/fil-rouge | forum/phpBB3/phpbb/search/fulltext_postgres.php | 36411 | <?php
/**
*
* This file is part of the phpBB Forum Software package.
*
* @copyright (c) phpBB Limited <https://www.phpbb.com>
* @license GNU General Public License, version 2 (GPL-2.0)
*
* For full copyright and license information, please see
* the docs/CREDITS.txt file.
*
*/
namespace phpbb\search;
/**
* Fulltext search for PostgreSQL
*/
class fulltext_postgres extends \phpbb\search\base
{
/**
* Associative array holding index stats
* @var array
*/
protected $stats = array();
/**
* Holds the words entered by user, obtained by splitting the entered query on whitespace
* @var array
*/
protected $split_words = array();
/**
* Stores the tsearch query
* @var string
*/
protected $tsearch_query;
/**
* True if phrase search is supported.
* PostgreSQL fulltext currently doesn't support it
* @var boolean
*/
protected $phrase_search = false;
/**
* Config object
* @var \phpbb\config\config
*/
protected $config;
/**
* Database connection
* @var \phpbb\db\driver\driver_interface
*/
protected $db;
/**
* phpBB event dispatcher object
* @var \phpbb\event\dispatcher_interface
*/
protected $phpbb_dispatcher;
/**
* User object
* @var \phpbb\user
*/
protected $user;
/**
* Contains tidied search query.
* Operators are prefixed in search query and common words excluded
* @var string
*/
protected $search_query;
/**
* Contains common words.
* Common words are words with length less/more than min/max length
* @var array
*/
protected $common_words = array();
/**
* Associative array stores the min and max word length to be searched
* @var array
*/
protected $word_length = array();
/**
* Constructor
* Creates a new \phpbb\search\fulltext_postgres, which is used as a search backend
*
* @param string|bool $error Any error that occurs is passed on through this reference variable otherwise false
* @param string $phpbb_root_path Relative path to phpBB root
* @param string $phpEx PHP file extension
* @param \phpbb\auth\auth $auth Auth object
* @param \phpbb\config\config $config Config object
* @param \phpbb\db\driver\driver_interface Database object
* @param \phpbb\user $user User object
* @param \phpbb\event\dispatcher_interface $phpbb_dispatcher Event dispatcher object
*/
public function __construct(&$error, $phpbb_root_path, $phpEx, $auth, $config, $db, $user, $phpbb_dispatcher)
{
$this->config = $config;
$this->db = $db;
$this->phpbb_dispatcher = $phpbb_dispatcher;
$this->user = $user;
$this->word_length = array('min' => $this->config['fulltext_postgres_min_word_len'], 'max' => $this->config['fulltext_postgres_max_word_len']);
/**
* Load the UTF tools
*/
if (!function_exists('utf8_strlen'))
{
include($phpbb_root_path . 'includes/utf/utf_tools.' . $phpEx);
}
$error = false;
}
/**
* Returns the name of this search backend to be displayed to administrators
*
* @return string Name
*/
public function get_name()
{
return 'PostgreSQL Fulltext';
}
/**
* Returns the search_query
*
* @return string search query
*/
public function get_search_query()
{
return $this->search_query;
}
/**
* Returns the common_words array
*
* @return array common words that are ignored by search backend
*/
public function get_common_words()
{
return $this->common_words;
}
/**
* Returns the word_length array
*
* @return array min and max word length for searching
*/
public function get_word_length()
{
return $this->word_length;
}
/**
* Returns if phrase search is supported or not
*
* @return bool
*/
public function supports_phrase_search()
{
return $this->phrase_search;
}
/**
* Checks for correct PostgreSQL version and stores min/max word length in the config
*
* @return string|bool Language key of the error/incompatiblity occurred
*/
public function init()
{
if ($this->db->get_sql_layer() != 'postgres')
{
return $this->user->lang['FULLTEXT_POSTGRES_INCOMPATIBLE_DATABASE'];
}
return false;
}
/**
* Splits keywords entered by a user into an array of words stored in $this->split_words
* Stores the tidied search query in $this->search_query
*
* @param string &$keywords Contains the keyword as entered by the user
* @param string $terms is either 'all' or 'any'
* @return bool false if no valid keywords were found and otherwise true
*/
public function split_keywords(&$keywords, $terms)
{
if ($terms == 'all')
{
$match = array('#\sand\s#iu', '#\sor\s#iu', '#\snot\s#iu', '#(^|\s)\+#', '#(^|\s)-#', '#(^|\s)\|#');
$replace = array(' +', ' |', ' -', ' +', ' -', ' |');
$keywords = preg_replace($match, $replace, $keywords);
}
// Filter out as above
$split_keywords = preg_replace("#[\"\n\r\t]+#", ' ', trim(htmlspecialchars_decode($keywords)));
// Split words
$split_keywords = preg_replace('#([^\p{L}\p{N}\'*"()])#u', '$1$1', str_replace('\'\'', '\' \'', trim($split_keywords)));
$matches = array();
preg_match_all('#(?:[^\p{L}\p{N}*"()]|^)([+\-|]?(?:[\p{L}\p{N}*"()]+\'?)*[\p{L}\p{N}*"()])(?:[^\p{L}\p{N}*"()]|$)#u', $split_keywords, $matches);
$this->split_words = $matches[1];
foreach ($this->split_words as $i => $word)
{
$clean_word = preg_replace('#^[+\-|"]#', '', $word);
// check word length
$clean_len = utf8_strlen(str_replace('*', '', $clean_word));
if (($clean_len < $this->config['fulltext_postgres_min_word_len']) || ($clean_len > $this->config['fulltext_postgres_max_word_len']))
{
$this->common_words[] = $word;
unset($this->split_words[$i]);
}
}
if ($terms == 'any')
{
$this->search_query = '';
$this->tsearch_query = '';
foreach ($this->split_words as $word)
{
if ((strpos($word, '+') === 0) || (strpos($word, '-') === 0) || (strpos($word, '|') === 0))
{
$word = substr($word, 1);
}
$this->search_query .= $word . ' ';
$this->tsearch_query .= '|' . $word . ' ';
}
}
else
{
$this->search_query = '';
$this->tsearch_query = '';
foreach ($this->split_words as $word)
{
if (strpos($word, '+') === 0)
{
$this->search_query .= $word . ' ';
$this->tsearch_query .= '&' . substr($word, 1) . ' ';
}
else if (strpos($word, '-') === 0)
{
$this->search_query .= $word . ' ';
$this->tsearch_query .= '&!' . substr($word, 1) . ' ';
}
else if (strpos($word, '|') === 0)
{
$this->search_query .= $word . ' ';
$this->tsearch_query .= '|' . substr($word, 1) . ' ';
}
else
{
$this->search_query .= '+' . $word . ' ';
$this->tsearch_query .= '&' . $word . ' ';
}
}
}
$this->tsearch_query = substr($this->tsearch_query, 1);
$this->search_query = utf8_htmlspecialchars($this->search_query);
if ($this->search_query)
{
$this->split_words = array_values($this->split_words);
sort($this->split_words);
return true;
}
return false;
}
/**
* Turns text into an array of words
* @param string $text contains post text/subject
*/
public function split_message($text)
{
// Split words
$text = preg_replace('#([^\p{L}\p{N}\'*])#u', '$1$1', str_replace('\'\'', '\' \'', trim($text)));
$matches = array();
preg_match_all('#(?:[^\p{L}\p{N}*]|^)([+\-|]?(?:[\p{L}\p{N}*]+\'?)*[\p{L}\p{N}*])(?:[^\p{L}\p{N}*]|$)#u', $text, $matches);
$text = $matches[1];
// remove too short or too long words
$text = array_values($text);
for ($i = 0, $n = sizeof($text); $i < $n; $i++)
{
$text[$i] = trim($text[$i]);
if (utf8_strlen($text[$i]) < $this->config['fulltext_postgres_min_word_len'] || utf8_strlen($text[$i]) > $this->config['fulltext_postgres_max_word_len'])
{
unset($text[$i]);
}
}
return array_values($text);
}
/**
* Performs a search on keywords depending on display specific params. You have to run split_keywords() first
*
* @param string $type contains either posts or topics depending on what should be searched for
* @param string $fields contains either titleonly (topic titles should be searched), msgonly (only message bodies should be searched), firstpost (only subject and body of the first post should be searched) or all (all post bodies and subjects should be searched)
* @param string $terms is either 'all' (use query as entered, words without prefix should default to "have to be in field") or 'any' (ignore search query parts and just return all posts that contain any of the specified words)
* @param array $sort_by_sql contains SQL code for the ORDER BY part of a query
* @param string $sort_key is the key of $sort_by_sql for the selected sorting
* @param string $sort_dir is either a or d representing ASC and DESC
* @param string $sort_days specifies the maximum amount of days a post may be old
* @param array $ex_fid_ary specifies an array of forum ids which should not be searched
* @param string $post_visibility specifies which types of posts the user can view in which forums
* @param int $topic_id is set to 0 or a topic id, if it is not 0 then only posts in this topic should be searched
* @param array $author_ary an array of author ids if the author should be ignored during the search the array is empty
* @param string $author_name specifies the author match, when ANONYMOUS is also a search-match
* @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered
* @param int $start indicates the first index of the page
* @param int $per_page number of ids each page is supposed to contain
* @return boolean|int total number of results
*/
public function keyword_search($type, $fields, $terms, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, &$start, $per_page)
{
// No keywords? No posts
if (!$this->search_query)
{
return false;
}
// When search query contains queries like -foo
if (strpos($this->search_query, '+') === false)
{
return false;
}
// generate a search_key from all the options to identify the results
$search_key_array = array(
implode(', ', $this->split_words),
$type,
$fields,
$terms,
$sort_days,
$sort_key,
$topic_id,
implode(',', $ex_fid_ary),
$post_visibility,
implode(',', $author_ary)
);
/**
* Allow changing the search_key for cached results
*
* @event core.search_postgres_by_keyword_modify_search_key
* @var array search_key_array Array with search parameters to generate the search_key
* @var string type Searching type ('posts', 'topics')
* @var string fields Searching fields ('titleonly', 'msgonly', 'firstpost', 'all')
* @var string terms Searching terms ('all', 'any')
* @var int sort_days Time, in days, of the oldest possible post to list
* @var string sort_key The sort type used from the possible sort types
* @var int topic_id Limit the search to this topic_id only
* @var array ex_fid_ary Which forums not to search on
* @var string post_visibility Post visibility data
* @var array author_ary Array of user_id containing the users to filter the results to
* @since 3.1.7-RC1
*/
$vars = array(
'search_key_array',
'type',
'fields',
'terms',
'sort_days',
'sort_key',
'topic_id',
'ex_fid_ary',
'post_visibility',
'author_ary',
);
extract($this->phpbb_dispatcher->trigger_event('core.search_postgres_by_keyword_modify_search_key', compact($vars)));
$search_key = md5(implode('#', $search_key_array));
if ($start < 0)
{
$start = 0;
}
// try reading the results from cache
$result_count = 0;
if ($this->obtain_ids($search_key, $result_count, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE)
{
return $result_count;
}
$id_ary = array();
$join_topic = ($type == 'posts') ? false : true;
// Build sql strings for sorting
$sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC');
$sql_sort_table = $sql_sort_join = '';
switch ($sql_sort[0])
{
case 'u':
$sql_sort_table = USERS_TABLE . ' u, ';
$sql_sort_join = ($type == 'posts') ? ' AND u.user_id = p.poster_id ' : ' AND u.user_id = t.topic_poster ';
break;
case 't':
$join_topic = true;
break;
case 'f':
$sql_sort_table = FORUMS_TABLE . ' f, ';
$sql_sort_join = ' AND f.forum_id = p.forum_id ';
break;
}
// Build some display specific sql strings
switch ($fields)
{
case 'titleonly':
$sql_match = 'p.post_subject';
$sql_match_where = ' AND p.post_id = t.topic_first_post_id';
$join_topic = true;
break;
case 'msgonly':
$sql_match = 'p.post_text';
$sql_match_where = '';
break;
case 'firstpost':
$sql_match = 'p.post_subject, p.post_text';
$sql_match_where = ' AND p.post_id = t.topic_first_post_id';
$join_topic = true;
break;
default:
$sql_match = 'p.post_subject, p.post_text';
$sql_match_where = '';
break;
}
$tsearch_query = $this->tsearch_query;
/**
* Allow changing the query used to search for posts using fulltext_postgres
*
* @event core.search_postgres_keywords_main_query_before
* @var string tsearch_query The parsed keywords used for this search
* @var int result_count The previous result count for the format of the query.
* Set to 0 to force a re-count
* @var bool join_topic Weather or not TOPICS_TABLE should be CROSS JOIN'ED
* @var array author_ary Array of user_id containing the users to filter the results to
* @var string author_name An extra username to search on (!empty(author_ary) must be true, to be relevant)
* @var array ex_fid_ary Which forums not to search on
* @var int topic_id Limit the search to this topic_id only
* @var string sql_sort_table Extra tables to include in the SQL query.
* Used in conjunction with sql_sort_join
* @var string sql_sort_join SQL conditions to join all the tables used together.
* Used in conjunction with sql_sort_table
* @var int sort_days Time, in days, of the oldest possible post to list
* @var string sql_match Which columns to do the search on.
* @var string sql_match_where Extra conditions to use to properly filter the matching process
* @var string sort_by_sql The possible predefined sort types
* @var string sort_key The sort type used from the possible sort types
* @var string sort_dir "a" for ASC or "d" dor DESC for the sort order used
* @var string sql_sort The result SQL when processing sort_by_sql + sort_key + sort_dir
* @var int start How many posts to skip in the search results (used for pagination)
* @since 3.1.5-RC1
*/
$vars = array(
'tsearch_query',
'result_count',
'join_topic',
'author_ary',
'author_name',
'ex_fid_ary',
'topic_id',
'sql_sort_table',
'sql_sort_join',
'sort_days',
'sql_match',
'sql_match_where',
'sort_by_sql',
'sort_key',
'sort_dir',
'sql_sort',
'start',
);
extract($this->phpbb_dispatcher->trigger_event('core.search_postgres_keywords_main_query_before', compact($vars)));
$sql_select = ($type == 'posts') ? 'p.post_id' : 'DISTINCT t.topic_id';
$sql_from = ($join_topic) ? TOPICS_TABLE . ' t, ' : '';
$field = ($type == 'posts') ? 'post_id' : 'topic_id';
$sql_author = (sizeof($author_ary) == 1) ? ' = ' . $author_ary[0] : 'IN (' . implode(', ', $author_ary) . ')';
if (sizeof($author_ary) && $author_name)
{
// first one matches post of registered users, second one guests and deleted users
$sql_author = '(' . $this->db->sql_in_set('p.poster_id', array_diff($author_ary, array(ANONYMOUS)), false, true) . ' OR p.post_username ' . $author_name . ')';
}
else if (sizeof($author_ary))
{
$sql_author = ' AND ' . $this->db->sql_in_set('p.poster_id', $author_ary);
}
else
{
$sql_author = '';
}
$sql_where_options = $sql_sort_join;
$sql_where_options .= ($topic_id) ? ' AND p.topic_id = ' . $topic_id : '';
$sql_where_options .= ($join_topic) ? ' AND t.topic_id = p.topic_id' : '';
$sql_where_options .= (sizeof($ex_fid_ary)) ? ' AND ' . $this->db->sql_in_set('p.forum_id', $ex_fid_ary, true) : '';
$sql_where_options .= ' AND ' . $post_visibility;
$sql_where_options .= $sql_author;
$sql_where_options .= ($sort_days) ? ' AND p.post_time >= ' . (time() - ($sort_days * 86400)) : '';
$sql_where_options .= $sql_match_where;
$tmp_sql_match = array();
$sql_match = str_replace(',', " || ' ' ||", $sql_match);
$tmp_sql_match = "to_tsvector ('" . $this->db->sql_escape($this->config['fulltext_postgres_ts_name']) . "', " . $sql_match . ") @@ to_tsquery ('" . $this->db->sql_escape($this->config['fulltext_postgres_ts_name']) . "', '" . $this->db->sql_escape($this->tsearch_query) . "')";
$this->db->sql_transaction('begin');
$sql_from = "FROM $sql_from$sql_sort_table" . POSTS_TABLE . " p";
$sql_where = "WHERE (" . $tmp_sql_match . ")
$sql_where_options";
$sql = "SELECT $sql_select
$sql_from
$sql_where
ORDER BY $sql_sort";
$result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
while ($row = $this->db->sql_fetchrow($result))
{
$id_ary[] = $row[$field];
}
$this->db->sql_freeresult($result);
$id_ary = array_unique($id_ary);
// if the total result count is not cached yet, retrieve it from the db
if (!$result_count)
{
$sql_count = "SELECT COUNT(*) as result_count
$sql_from
$sql_where";
$result = $this->db->sql_query($sql_count);
$result_count = (int) $this->db->sql_fetchfield('result_count');
$this->db->sql_freeresult($result);
if (!$result_count)
{
return false;
}
}
$this->db->sql_transaction('commit');
if ($start >= $result_count)
{
$start = floor(($result_count - 1) / $per_page) * $per_page;
$result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
while ($row = $this->db->sql_fetchrow($result))
{
$id_ary[] = $row[$field];
}
$this->db->sql_freeresult($result);
$id_ary = array_unique($id_ary);
}
// store the ids, from start on then delete anything that isn't on the current page because we only need ids for one page
$this->save_ids($search_key, implode(' ', $this->split_words), $author_ary, $result_count, $id_ary, $start, $sort_dir);
$id_ary = array_slice($id_ary, 0, (int) $per_page);
return $result_count;
}
/**
* Performs a search on an author's posts without caring about message contents. Depends on display specific params
*
* @param string $type contains either posts or topics depending on what should be searched for
* @param boolean $firstpost_only if true, only topic starting posts will be considered
* @param array $sort_by_sql contains SQL code for the ORDER BY part of a query
* @param string $sort_key is the key of $sort_by_sql for the selected sorting
* @param string $sort_dir is either a or d representing ASC and DESC
* @param string $sort_days specifies the maximum amount of days a post may be old
* @param array $ex_fid_ary specifies an array of forum ids which should not be searched
* @param string $post_visibility specifies which types of posts the user can view in which forums
* @param int $topic_id is set to 0 or a topic id, if it is not 0 then only posts in this topic should be searched
* @param array $author_ary an array of author ids
* @param string $author_name specifies the author match, when ANONYMOUS is also a search-match
* @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered
* @param int $start indicates the first index of the page
* @param int $per_page number of ids each page is supposed to contain
* @return boolean|int total number of results
*/
public function author_search($type, $firstpost_only, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, &$start, $per_page)
{
// No author? No posts
if (!sizeof($author_ary))
{
return 0;
}
// generate a search_key from all the options to identify the results
$search_key_array = array(
'',
$type,
($firstpost_only) ? 'firstpost' : '',
'',
'',
$sort_days,
$sort_key,
$topic_id,
implode(',', $ex_fid_ary),
$post_visibility,
implode(',', $author_ary),
$author_name,
);
/**
* Allow changing the search_key for cached results
*
* @event core.search_postgres_by_author_modify_search_key
* @var array search_key_array Array with search parameters to generate the search_key
* @var string type Searching type ('posts', 'topics')
* @var boolean firstpost_only Flag indicating if only topic starting posts are considered
* @var int sort_days Time, in days, of the oldest possible post to list
* @var string sort_key The sort type used from the possible sort types
* @var int topic_id Limit the search to this topic_id only
* @var array ex_fid_ary Which forums not to search on
* @var string post_visibility Post visibility data
* @var array author_ary Array of user_id containing the users to filter the results to
* @var string author_name The username to search on
* @since 3.1.7-RC1
*/
$vars = array(
'search_key_array',
'type',
'firstpost_only',
'sort_days',
'sort_key',
'topic_id',
'ex_fid_ary',
'post_visibility',
'author_ary',
'author_name',
);
extract($this->phpbb_dispatcher->trigger_event('core.search_postgres_by_author_modify_search_key', compact($vars)));
$search_key = md5(implode('#', $search_key_array));
if ($start < 0)
{
$start = 0;
}
// try reading the results from cache
$result_count = 0;
if ($this->obtain_ids($search_key, $result_count, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE)
{
return $result_count;
}
$id_ary = array();
// Create some display specific sql strings
if ($author_name)
{
// first one matches post of registered users, second one guests and deleted users
$sql_author = '(' . $this->db->sql_in_set('p.poster_id', array_diff($author_ary, array(ANONYMOUS)), false, true) . ' OR p.post_username ' . $author_name . ')';
}
else
{
$sql_author = $this->db->sql_in_set('p.poster_id', $author_ary);
}
$sql_fora = (sizeof($ex_fid_ary)) ? ' AND ' . $this->db->sql_in_set('p.forum_id', $ex_fid_ary, true) : '';
$sql_topic_id = ($topic_id) ? ' AND p.topic_id = ' . (int) $topic_id : '';
$sql_time = ($sort_days) ? ' AND p.post_time >= ' . (time() - ($sort_days * 86400)) : '';
$sql_firstpost = ($firstpost_only) ? ' AND p.post_id = t.topic_first_post_id' : '';
// Build sql strings for sorting
$sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC');
$sql_sort_table = $sql_sort_join = '';
switch ($sql_sort[0])
{
case 'u':
$sql_sort_table = USERS_TABLE . ' u, ';
$sql_sort_join = ($type == 'posts') ? ' AND u.user_id = p.poster_id ' : ' AND u.user_id = t.topic_poster ';
break;
case 't':
$sql_sort_table = ($type == 'posts' && !$firstpost_only) ? TOPICS_TABLE . ' t, ' : '';
$sql_sort_join = ($type == 'posts' && !$firstpost_only) ? ' AND t.topic_id = p.topic_id ' : '';
break;
case 'f':
$sql_sort_table = FORUMS_TABLE . ' f, ';
$sql_sort_join = ' AND f.forum_id = p.forum_id ';
break;
}
$m_approve_fid_sql = ' AND ' . $post_visibility;
/**
* Allow changing the query used to search for posts by author in fulltext_postgres
*
* @event core.search_postgres_author_count_query_before
* @var int result_count The previous result count for the format of the query.
* Set to 0 to force a re-count
* @var string sql_sort_table CROSS JOIN'ed table to allow doing the sort chosen
* @var string sql_sort_join Condition to define how to join the CROSS JOIN'ed table specifyed in sql_sort_table
* @var array author_ary Array of user_id containing the users to filter the results to
* @var string author_name An extra username to search on
* @var string sql_author SQL WHERE condition for the post author ids
* @var int topic_id Limit the search to this topic_id only
* @var string sql_topic_id SQL of topic_id
* @var string sort_by_sql The possible predefined sort types
* @var string sort_key The sort type used from the possible sort types
* @var string sort_dir "a" for ASC or "d" dor DESC for the sort order used
* @var string sql_sort The result SQL when processing sort_by_sql + sort_key + sort_dir
* @var string sort_days Time, in days, that the oldest post showing can have
* @var string sql_time The SQL to search on the time specifyed by sort_days
* @var bool firstpost_only Wether or not to search only on the first post of the topics
* @var array ex_fid_ary Forum ids that must not be searched on
* @var array sql_fora SQL query for ex_fid_ary
* @var string m_approve_fid_sql WHERE clause condition on post_visibility restrictions
* @var int start How many posts to skip in the search results (used for pagination)
* @since 3.1.5-RC1
*/
$vars = array(
'result_count',
'sql_sort_table',
'sql_sort_join',
'author_ary',
'author_name',
'sql_author',
'topic_id',
'sql_topic_id',
'sort_by_sql',
'sort_key',
'sort_dir',
'sql_sort',
'sort_days',
'sql_time',
'firstpost_only',
'ex_fid_ary',
'sql_fora',
'm_approve_fid_sql',
'start',
);
extract($this->phpbb_dispatcher->trigger_event('core.search_postgres_author_count_query_before', compact($vars)));
// Build the query for really selecting the post_ids
if ($type == 'posts')
{
$sql = "SELECT p.post_id
FROM " . $sql_sort_table . POSTS_TABLE . ' p' . (($firstpost_only) ? ', ' . TOPICS_TABLE . ' t ' : ' ') . "
WHERE $sql_author
$sql_topic_id
$sql_firstpost
$m_approve_fid_sql
$sql_fora
$sql_sort_join
$sql_time
ORDER BY $sql_sort";
$field = 'post_id';
}
else
{
$sql = "SELECT t.topic_id
FROM " . $sql_sort_table . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p
WHERE $sql_author
$sql_topic_id
$sql_firstpost
$m_approve_fid_sql
$sql_fora
AND t.topic_id = p.topic_id
$sql_sort_join
$sql_time
GROUP BY t.topic_id, $sort_by_sql[$sort_key]
ORDER BY $sql_sort";
$field = 'topic_id';
}
$this->db->sql_transaction('begin');
// Only read one block of posts from the db and then cache it
$result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
while ($row = $this->db->sql_fetchrow($result))
{
$id_ary[] = $row[$field];
}
$this->db->sql_freeresult($result);
// retrieve the total result count if needed
if (!$result_count)
{
if ($type == 'posts')
{
$sql_count = "SELECT COUNT(*) as result_count
FROM " . $sql_sort_table . POSTS_TABLE . ' p' . (($firstpost_only) ? ', ' . TOPICS_TABLE . ' t ' : ' ') . "
WHERE $sql_author
$sql_topic_id
$sql_firstpost
$m_approve_fid_sql
$sql_fora
$sql_sort_join
$sql_time";
}
else
{
$sql_count = "SELECT COUNT(*) as result_count
FROM " . $sql_sort_table . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p
WHERE $sql_author
$sql_topic_id
$sql_firstpost
$m_approve_fid_sql
$sql_fora
AND t.topic_id = p.topic_id
$sql_sort_join
$sql_time
GROUP BY t.topic_id, $sort_by_sql[$sort_key]";
}
$result = $this->db->sql_query($sql_count);
$result_count = (int) $this->db->sql_fetchfield('result_count');
if (!$result_count)
{
return false;
}
}
$this->db->sql_transaction('commit');
if ($start >= $result_count)
{
$start = floor(($result_count - 1) / $per_page) * $per_page;
$result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
while ($row = $this->db->sql_fetchrow($result))
{
$id_ary[] = (int) $row[$field];
}
$this->db->sql_freeresult($result);
$id_ary = array_unique($id_ary);
}
if (sizeof($id_ary))
{
$this->save_ids($search_key, '', $author_ary, $result_count, $id_ary, $start, $sort_dir);
$id_ary = array_slice($id_ary, 0, $per_page);
return $result_count;
}
return false;
}
/**
* Destroys cached search results, that contained one of the new words in a post so the results won't be outdated
*
* @param string $mode contains the post mode: edit, post, reply, quote ...
* @param int $post_id contains the post id of the post to index
* @param string $message contains the post text of the post
* @param string $subject contains the subject of the post to index
* @param int $poster_id contains the user id of the poster
* @param int $forum_id contains the forum id of parent forum of the post
*/
public function index($mode, $post_id, &$message, &$subject, $poster_id, $forum_id)
{
// Split old and new post/subject to obtain array of words
$split_text = $this->split_message($message);
$split_title = ($subject) ? $this->split_message($subject) : array();
$words = array_unique(array_merge($split_text, $split_title));
unset($split_text);
unset($split_title);
// destroy cached search results containing any of the words removed or added
$this->destroy_cache($words, array($poster_id));
unset($words);
}
/**
* Destroy cached results, that might be outdated after deleting a post
*/
public function index_remove($post_ids, $author_ids, $forum_ids)
{
$this->destroy_cache(array(), $author_ids);
}
/**
* Destroy old cache entries
*/
public function tidy()
{
// destroy too old cached search results
$this->destroy_cache(array());
set_config('search_last_gc', time(), true);
}
/**
* Create fulltext index
*
* @return string|bool error string is returned incase of errors otherwise false
*/
public function create_index($acp_module, $u_action)
{
// Make sure we can actually use PostgreSQL with fulltext indexes
if ($error = $this->init())
{
return $error;
}
if (empty($this->stats))
{
$this->get_stats();
}
if (!isset($this->stats['post_subject']))
{
$this->db->sql_query("CREATE INDEX " . POSTS_TABLE . "_" . $this->config['fulltext_postgres_ts_name'] . "_post_subject ON " . POSTS_TABLE . " USING gin (to_tsvector ('" . $this->db->sql_escape($this->config['fulltext_postgres_ts_name']) . "', post_subject))");
}
if (!isset($this->stats['post_content']))
{
$this->db->sql_query("CREATE INDEX " . POSTS_TABLE . "_" . $this->config['fulltext_postgres_ts_name'] . "_post_content ON " . POSTS_TABLE . " USING gin (to_tsvector ('" . $this->db->sql_escape($this->config['fulltext_postgres_ts_name']) . "', post_text || ' ' || post_subject))");
}
$this->db->sql_query('TRUNCATE TABLE ' . SEARCH_RESULTS_TABLE);
return false;
}
/**
* Drop fulltext index
*
* @return string|bool error string is returned incase of errors otherwise false
*/
public function delete_index($acp_module, $u_action)
{
// Make sure we can actually use PostgreSQL with fulltext indexes
if ($error = $this->init())
{
return $error;
}
if (empty($this->stats))
{
$this->get_stats();
}
if (isset($this->stats['post_subject']))
{
$this->db->sql_query('DROP INDEX ' . $this->stats['post_subject']['relname']);
}
if (isset($this->stats['post_content']))
{
$this->db->sql_query('DROP INDEX ' . $this->stats['post_content']['relname']);
}
$this->db->sql_query('TRUNCATE TABLE ' . SEARCH_RESULTS_TABLE);
return false;
}
/**
* Returns true if both FULLTEXT indexes exist
*/
public function index_created()
{
if (empty($this->stats))
{
$this->get_stats();
}
return (isset($this->stats['post_subject']) && isset($this->stats['post_content'])) ? true : false;
}
/**
* Returns an associative array containing information about the indexes
*/
public function index_stats()
{
if (empty($this->stats))
{
$this->get_stats();
}
return array(
$this->user->lang['FULLTEXT_POSTGRES_TOTAL_POSTS'] => ($this->index_created()) ? $this->stats['total_posts'] : 0,
);
}
/**
* Computes the stats and store them in the $this->stats associative array
*/
protected function get_stats()
{
if ($this->db->get_sql_layer() != 'postgres')
{
$this->stats = array();
return;
}
$sql = "SELECT c2.relname, pg_catalog.pg_get_indexdef(i.indexrelid, 0, true) AS indexdef
FROM pg_catalog.pg_class c1, pg_catalog.pg_index i, pg_catalog.pg_class c2
WHERE c1.relname = '" . POSTS_TABLE . "'
AND pg_catalog.pg_table_is_visible(c1.oid)
AND c1.oid = i.indrelid
AND i.indexrelid = c2.oid";
$result = $this->db->sql_query($sql);
while ($row = $this->db->sql_fetchrow($result))
{
// deal with older PostgreSQL versions which didn't use Index_type
if (strpos($row['indexdef'], 'to_tsvector') !== false)
{
if ($row['relname'] == POSTS_TABLE . '_' . $this->config['fulltext_postgres_ts_name'] . '_post_subject' || $row['relname'] == POSTS_TABLE . '_post_subject')
{
$this->stats['post_subject'] = $row;
}
else if ($row['relname'] == POSTS_TABLE . '_' . $this->config['fulltext_postgres_ts_name'] . '_post_content' || $row['relname'] == POSTS_TABLE . '_post_content')
{
$this->stats['post_content'] = $row;
}
}
}
$this->db->sql_freeresult($result);
$this->stats['total_posts'] = $this->config['num_posts'];
}
/**
* Display various options that can be configured for the backend from the acp
*
* @return associative array containing template and config variables
*/
public function acp()
{
$tpl = '
<dl>
<dt><label>' . $this->user->lang['FULLTEXT_POSTGRES_VERSION_CHECK'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_POSTGRES_VERSION_CHECK_EXPLAIN'] . '</span></dt>
<dd>' . (($this->db->get_sql_layer() == 'postgres') ? $this->user->lang['YES'] : $this->user->lang['NO']) . '</dd>
</dl>
<dl>
<dt><label>' . $this->user->lang['FULLTEXT_POSTGRES_TS_NAME'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_POSTGRES_TS_NAME_EXPLAIN'] . '</span></dt>
<dd><select name="config[fulltext_postgres_ts_name]">';
if ($this->db->get_sql_layer() == 'postgres')
{
$sql = 'SELECT cfgname AS ts_name
FROM pg_ts_config';
$result = $this->db->sql_query($sql);
while ($row = $this->db->sql_fetchrow($result))
{
$tpl .= '<option value="' . $row['ts_name'] . '"' . ($row['ts_name'] === $this->config['fulltext_postgres_ts_name'] ? ' selected="selected"' : '') . '>' . $row['ts_name'] . '</option>';
}
$this->db->sql_freeresult($result);
}
else
{
$tpl .= '<option value="' . $this->config['fulltext_postgres_ts_name'] . '" selected="selected">' . $this->config['fulltext_postgres_ts_name'] . '</option>';
}
$tpl .= '</select></dd>
</dl>
<dl>
<dt><label for="fulltext_postgres_min_word_len">' . $this->user->lang['FULLTEXT_POSTGRES_MIN_WORD_LEN'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_POSTGRES_MIN_WORD_LEN_EXPLAIN'] . '</span></dt>
<dd><input id="fulltext_postgres_min_word_len" type="number" size="3" maxlength="3" min="0" max="255" name="config[fulltext_postgres_min_word_len]" value="' . (int) $this->config['fulltext_postgres_min_word_len'] . '" /></dd>
</dl>
<dl>
<dt><label for="fulltext_postgres_max_word_len">' . $this->user->lang['FULLTEXT_POSTGRES_MAX_WORD_LEN'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_POSTGRES_MAX_WORD_LEN_EXPLAIN'] . '</span></dt>
<dd><input id="fulltext_postgres_max_word_len" type="number" size="3" maxlength="3" min="0" max="255" name="config[fulltext_postgres_max_word_len]" value="' . (int) $this->config['fulltext_postgres_max_word_len'] . '" /></dd>
</dl>
';
// These are fields required in the config table
return array(
'tpl' => $tpl,
'config' => array('fulltext_postgres_ts_name' => 'string', 'fulltext_postgres_min_word_len' => 'integer:0:255', 'fulltext_postgres_max_word_len' => 'integer:0:255')
);
}
}
| mit |
erykpiast/appetite | node_modules/sequelize/node_modules/sql/lib/node/query.js | 8123 | 'use strict';
var assert = require('assert');
var sliced = require('sliced');
var util = require('util');
var Node = require('./');
var Select = require('./select');
var From = require('./from');
var Where = require('./where');
var OrderBy = require('./orderBy');
var GroupBy = require('./groupBy');
var Having = require('./having');
var Insert = require('./insert');
var Update = require('./update');
var Delete = require('./delete');
var Returning = require('./returning');
var Create = require('./create');
var Drop = require('./drop');
var Alter = require('./alter');
var AddColumn = require('./addColumn');
var DropColumn = require('./dropColumn');
var RenameColumn = require('./renameColumn');
var Rename = require('./rename');
var Column = require('../column');
var ParameterNode = require('./parameter');
var PrefixUnaryNode = require('./prefixUnary');
var IfExists = require('./ifExists');
var IfNotExists = require('./ifNotExists');
var Indexes = require('./indexes');
var CreateIndex = require('./createIndex');
var DropIndex = require('./dropIndex');
var Modifier = Node.define({
constructor: function(table, type, count) {
this.table = table;
this.type = type;
this.count = count;
}
});
// get the first element of an arguments if it is an array, else return arguments as an array
var getArrayOrArgsAsArray = function(args) {
if (util.isArray(args[0])) {
return args[0];
}
return sliced(args);
};
var Query = Node.define({
type: 'QUERY',
constructor: function(table) {
Node.call(this);
this.table = table;
if (table) this.sql = table.sql;
},
select: function() {
var select;
if (this._select) {
select = this._select;
} else {
select = this._select = new Select();
this.add(select);
}
var args = getArrayOrArgsAsArray(arguments);
select.addAll(args);
// if this is a subquery then add reference to this column
if (this.type === 'SUBQUERY') {
for (var j = 0; j < select.nodes.length; j++) {
var name = select.nodes[j].alias || select.nodes[j].name;
var col = new Column(select.nodes[j]);
col.name = name;
col.table = this;
if (this[name] === undefined) {
this[name] = col;
}
}
}
return this;
},
star: function() {
assert(this.type === 'SUBQUERY', 'star() can only be used on a subQuery');
return new Column({
table: this,
star: true
});
},
from: function(tableNode) {
var from = new From().add(tableNode);
return this.add(from);
},
where: function(node) {
if (arguments.length > 1) {
// allow multiple where clause arguments
var args = sliced(arguments);
for (var i = 0; i < args.length; i++) {
this.where(args[i]);
}
return this;
}
// calling #where twice functions like calling #where & then #and
if (this.whereClause) return this.and(node);
this.whereClause = new Where(this.table);
this.whereClause.add(node);
return this.add(this.whereClause);
},
or: function(node) {
this.whereClause.or(node);
return this;
},
and: function(node) {
this.whereClause.and(node);
return this;
},
order: function() {
var args = getArrayOrArgsAsArray(arguments);
var orderBy;
if (this._orderBy) {
orderBy = this._orderBy;
} else {
orderBy = this._orderBy = new OrderBy();
this.add(orderBy);
}
orderBy.addAll(args);
return this;
},
group: function() {
var args = getArrayOrArgsAsArray(arguments);
var groupBy = new GroupBy().addAll(args);
return this.add(groupBy);
},
having: function() {
var args = getArrayOrArgsAsArray(arguments);
var having = new Having().addAll(args);
return this.add(having);
},
insert: function(o) {
var self = this;
var args = sliced(arguments);
// object literal
if (arguments.length == 1 && !o.toNode && !o.forEach) {
args = Object.keys(o).map(function(key) {
return self.table.get(key).value(o[key]);
});
} else if (o.forEach) {
o.forEach(function(arg) {
return self.insert.call(self, arg);
});
return self;
}
if (self.insertClause) {
self.insertClause.add(args);
return self;
} else {
self.insertClause = new Insert();
self.insertClause.add(args);
return self.add(self.insertClause);
}
},
update: function(o) {
var self = this;
var update = new Update();
Object.keys(o).forEach(function(key) {
var val = o[key];
update.add(self.table.get(key).value(ParameterNode.getNodeOrParameterNode(val)));
});
return this.add(update);
},
delete: function(params) {
var result = this.add(new Delete());
if (params) {
result = this.where(params);
}
return result;
},
returning: function() {
var args = getArrayOrArgsAsArray(arguments);
var returning = new Returning();
returning.addAll(args);
return this.add(returning);
},
create: function(indexName) {
if (this.indexesCause) {
var createIndex = new CreateIndex(this.table, indexName);
this.add(createIndex);
return createIndex;
} else {
return this.add(new Create());
}
},
drop: function() {
if (this.indexesCause) {
var args = sliced(arguments);
var dropIndex = new DropIndex(this.table, args);
this.add(dropIndex);
return dropIndex;
} else {
return this.add(new Drop());
}
},
alter: function() {
return this.add(new Alter());
},
rename: function(newName) {
var renameClause = new Rename();
if (!newName.toNode) {
newName = new Column({
name: newName,
table: this.table
});
}
renameClause.add(newName.toNode());
this.nodes[0].add(renameClause);
return this;
},
addColumn: function(column, dataType) {
var addClause = new AddColumn();
if (!column.toNode) {
column = new Column({
name: column,
table: this.table
});
}
if (dataType) {
column.dataType = dataType;
}
addClause.add(column.toNode());
this.nodes[0].add(addClause);
return this;
},
dropColumn: function(column) {
var dropClause = new DropColumn();
if (!column.toNode) {
column = new Column({
name: column,
table: this.table
});
}
dropClause.add(column.toNode());
this.nodes[0].add(dropClause);
return this;
},
renameColumn: function(oldColumn, newColumn) {
var renameClause = new RenameColumn();
if (!oldColumn.toNode) {
oldColumn = new Column({
name: oldColumn,
table: this.table
});
}
if (!newColumn.toNode) {
newColumn = new Column({
name: newColumn,
table: this.table
});
}
renameClause.add(oldColumn.toNode());
renameClause.add(newColumn.toNode());
this.nodes[0].add(renameClause);
return this;
},
limit: function(count) {
return this.add(new Modifier(this, 'LIMIT', count));
},
offset: function(count) {
return this.add(new Modifier(this, 'OFFSET', count));
},
exists: function() {
assert(this.type === 'SUBQUERY', 'exists() can only be used on a subQuery');
return new PrefixUnaryNode({
left: this,
operator: "EXISTS"
});
},
notExists: function() {
assert(this.type === 'SUBQUERY', 'notExists() can only be used on a subQuery');
return new PrefixUnaryNode({
left: this,
operator: "NOT EXISTS"
});
},
ifExists: function() {
this.nodes[0].add(new IfExists());
return this;
},
ifNotExists: function() {
this.nodes[0].add(new IfNotExists());
return this;
},
indexes: function() {
this.indexesCause = new Indexes({
table: this.table
});
return this.add(this.indexesCause);
}
});
module.exports = Query;
| mit |
hegdekiranr/virtualreality | Assets/LeapMotion/Core/Scripts/Hands/RigidFinger.cs | 2088 | /******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2017. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using UnityEngine;
using System.Collections;
using Leap;
namespace Leap.Unity{
/** A physics finger model for our rigid hand made out of various cube Unity Colliders. */
public class RigidFinger : SkeletalFinger {
public float filtering = 0.5f;
void Start() {
for (int i = 0; i < bones.Length; ++i) {
if (bones[i] != null) {
bones[i].GetComponent<Rigidbody>().maxAngularVelocity = Mathf.Infinity;
}
}
}
public override void UpdateFinger() {
for (int i = 0; i < bones.Length; ++i) {
if (bones[i] != null) {
// Set bone dimensions.
CapsuleCollider capsule = bones[i].GetComponent<CapsuleCollider>();
if (capsule != null) {
// Initialization
capsule.direction = 2;
bones[i].localScale = new Vector3(1f/transform.lossyScale.x, 1f/transform.lossyScale.y, 1f/transform.lossyScale.z);
// Update
capsule.radius = GetBoneWidth(i) / 2f;
capsule.height = GetBoneLength(i) + GetBoneWidth(i);
}
Rigidbody boneBody = bones[i].GetComponent<Rigidbody>();
if (boneBody) {
boneBody.MovePosition(GetBoneCenter(i));
boneBody.MoveRotation(GetBoneRotation(i));
} else {
bones[i].position = GetBoneCenter(i);
bones[i].rotation = GetBoneRotation(i);
}
}
}
}
}
}
| mit |
jendewalt/jennifer_dewalt | db/migrate/20130610214126_create_one_page_pages.rb | 164 | class CreateOnePagePages < ActiveRecord::Migration
def change
create_table :one_page_pages do |t|
t.text :content
t.timestamps
end
end
end
| mit |
ceyhuno/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/utils/ImageLoadingListenerAdapter.java | 504 | package com.reactnativenavigation.utils;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import java.util.List;
public class ImageLoadingListenerAdapter implements ImageLoader.ImagesLoadingListener {
@Override
public void onComplete(@NonNull List<Drawable> drawables) {
}
@Override
public void onComplete(@NonNull Drawable drawable) {
}
@Override
public void onError(Throwable error) {
error.printStackTrace();
}
}
| mit |
evinsou/paperclip-googledrive | lib/paperclip/storage/google_drive.rb | 10246 | require 'active_support/core_ext/hash/keys'
require 'active_support/inflector/methods'
require 'active_support/core_ext/object/blank'
require 'yaml'
require 'erb'
require 'google/api_client'
require 'net/http'
module Paperclip
module Storage
# * self.extended(base) add instance variable to attachment on call
# * url return url to show on site with style options
# * path(style) return title that used to insert file to store or find it in store
# * public_url_for title return url to file if find by title or url to default image if set
# * search_for_title(title) take title, search in given folder and if it finds a file, return id of a file or nil
# * metadata_by_id(file_i get file metadata from store, used to back url or find out value of trashed
# * exists?(style) check either exists file with title or not
# * default_image return url to default url if set in option
# * find_public_folder return id of Public folder, must be in options
# return id of Public folder, must be in options
# * file_tit return base pattern of title or custom one set by user
# * parse_credentials(credenti get credentials from file, hash or path
# * assert_required_keys check either all ccredentials keys is set
# * original_extension return extension of file
module GoogleDrive
def self.extended(base)
begin
require 'google-api-client'
rescue LoadError => e
e.message << " (You may need to install the google-api-client gem)"
raise e
end unless defined?(Google)
base.instance_eval do
@google_drive_credentials = parse_credentials(@options[:google_drive_credentials] || {})
@google_drive_options = @options[:google_drive_options] || {}
google_api_client # Force validations of credentials
end
end
#
def flush_writes
@queued_for_write.each do |style, file|
if exists?(path(style))
raise FileExists, "file \"#{path(style)}\" already exists in your Google Drive"
else
#upload(style, file) #style file
client = google_api_client
drive = client.discovered_api('drive', 'v2')
result = client.execute(
:api_method => drive.files.get,
:parameters => { 'fileId' => @google_drive_options[:public_folder_id],
'fields' => ' id, title' })
client.authorization.access_token = result.request.authorization.access_token
client.authorization.refresh_token = result.request.authorization.refresh_token
title, mime_type = title_for_file(style), "#{content_type}"
parent_id = @google_drive_options[:public_folder_id] # folder_id for Public folder
metadata = drive.files.insert.request_schema.new({
'title' => title, #if it is no extension, that is a folder and another folder
'description' => 'paperclip file on google drive',
'mimeType' => mime_type })
if parent_id
metadata.parents = [{'id' => parent_id}]
end
media = Google::APIClient::UploadIO.new( file, mime_type)
result = client.execute!(
:api_method => drive.files.insert,
:body_object => metadata,
:media => media,
:parameters => {
'uploadType' => 'multipart',
'alt' => 'json' })
end
end
after_flush_writes
@queued_for_write = {}
end
#
def flush_deletes
@queued_for_delete.each do |path|
Paperclip.log("delete #{path}")
client = google_api_client
drive = client.discovered_api('drive', 'v2')
file_id = search_for_title(path)
unless file_id.nil?
folder_id = find_public_folder
parameters = {'fileId' => file_id,
'folder_id' => folder_id }
result = client.execute!(
:api_method => drive.files.delete,
:parameters => parameters)
end
end
@queued_for_delete = []
end
def copy_to_local_file(style, local_dest_path)
client = google_api_client
drive = client.discovered_api('drive', 'v2')
searched_id = search_for_title(path(style))
metadata =metadata_by_id(searched_id)
uri = URI.parse(metadata['downloadUrl'])
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
File.open(local_dest_path, "wb") do |file|
http.request_get(uri.request_uri, 'Authorization' => "Bearer #{client.authorization.access_token}") do |resp|
resp.read_body do |segment|
file.write(segment)
end
end
end
end
true
end
#
def google_api_client
@google_api_client ||= begin
assert_required_keys
# Initialize the client & Google+ API
client = Google::APIClient.new(
application_name: @google_drive_credentials[:application_name] || 'ppc-gd',
application_version: @google_drive_credentials[:application_version] || PaperclipGoogleDrive::VERSION
)
client.authorization.client_id = @google_drive_credentials[:client_id]
client.authorization.client_secret = @google_drive_credentials[:client_secret]
client.authorization.access_token = @google_drive_credentials[:access_token]
client.authorization.refresh_token = @google_drive_credentials[:refresh_token]
client
end
end
#
def google_drive
client = google_api_client
drive = client.discovered_api('drive', 'v2')
drive
end
def url(*args)
if present?
style = args.first.is_a?(Symbol) ? args.first : default_style
options = args.last.is_a?(Hash) ? args.last : {}
public_url_for(path(style))
else
default_image
end
end
def path(style)
title_for_file(style)
end
def title_for_file(style)
file_name = instance.instance_exec(style, &file_title)
style_suffix = (style != default_style ? "_#{style}" : "")
if original_extension.present? && file_name =~ /#{original_extension}$/
file_name.sub(original_extension, "#{style_suffix}#{original_extension}")
else
file_name + style_suffix + original_extension.to_s
end
end # full title
def public_url_for title
searched_id = search_for_title(title) #return id if any or style
if searched_id.nil? # it finds some file
default_image
else
metadata = metadata_by_id(searched_id)
metadata['webContentLink']
end
end # url
# take title, search in given folder and if it finds a file, return id of a file or nil
def search_for_title(title)
parameters = {
'folderId' => find_public_folder,
'q' => "title contains '#{title}'", # full_title
'fields' => 'items/id'}
client = google_api_client
drive = client.discovered_api('drive', 'v2')
result = client.execute!(:api_method => drive.children.list,
:parameters => parameters)
if result.data.items.length > 0
result.data.items[0]['id']
elsif result.data.items.length == 0
nil
else
nil
end
end # id or nil
def metadata_by_id(file_id)
if file_id.is_a? String
client = google_api_client
drive = client.discovered_api('drive', 'v2')
result = client.execute!(
:api_method => drive.files.get,
:parameters => {'fileId' => file_id,
'fields' => 'title, id, webContentLink, downloadUrl, labels/trashed' })
result.data # data.class # => Hash
end
end
def exists?(style = default_style)
return false if not present?
result_id = search_for_title(path(style))
if result_id.nil?
false
else
data_hash = metadata_by_id(result_id)
!data_hash['labels']['trashed'] # if trashed -> not exists
end
end
def default_image
if @google_drive_options[:default_url] #if default image is set
title = @google_drive_options[:default_url]
searched_id = search_for_title(title) # id
metadata = metadata_by_id(searched_id) unless searched_id.nil?
metadata['webContentLink']
else
'No picture' # ---- ?
end
end
def find_public_folder
unless @google_drive_options[:public_folder_id]
raise KeyError, "you must set a Public folder if into options"
end
@google_drive_options[:public_folder_id]
end
class FileExists < ArgumentError
end
private
def file_title
return @google_drive_options[:path] if @google_drive_options[:path] #path: proc
eval %(proc { |style| "\#{id}_\#{#{name}.original_filename}"})
end
def parse_credentials(credentials)
result =
case credentials
when File
YAML.load(ERB.new(File.read(credentials.path)).result)
when String, Pathname
YAML.load(ERB.new(File.read(credentials)).result)
when Hash
credentials
else
raise ArgumentError, ":google_drive_credentials are not a path, file, nor a hash"
end
result.symbolize_keys #or string keys
end
# check either all ccredentials keys is set
def assert_required_keys
keys_list = [:client_id, :client_secret, :access_token, :refresh_token]
keys_list.each do |key|
@google_drive_credentials.fetch(key)
end
end
# return extension of file
def original_extension
File.extname(original_filename)
end
end
end
end
| mit |
llopez/active_merchant | test/remote/gateways/remote_checkout_v2_test.rb | 4420 | require 'test_helper'
class RemoteCheckoutV2Test < Test::Unit::TestCase
def setup
@gateway = CheckoutV2Gateway.new(fixtures(:checkout_v2))
@amount = 200
@credit_card = credit_card('4242424242424242', verification_value: '100', month: '6', year: '2018')
@declined_card = credit_card('4000300011112220')
@options = {
order_id: '1',
billing_address: address,
description: 'Purchase',
email: "longbob.longsen@example.com"
}
end
def test_transcript_scrubbing
declined_card = credit_card('4000300011112220', verification_value: '423')
transcript = capture_transcript(@gateway) do
@gateway.purchase(@amount, declined_card, @options)
end
transcript = @gateway.scrub(transcript)
assert_scrubbed(declined_card.number, transcript)
assert_scrubbed(declined_card.verification_value, transcript)
assert_scrubbed(@gateway.options[:secret_key], transcript)
end
def test_successful_purchase
response = @gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert_equal 'Succeeded', response.message
end
def test_successful_purchase_with_descriptors
options = @options.merge(descriptor_name: "shop", descriptor_city: "london")
response = @gateway.purchase(@amount, @credit_card, options)
assert_success response
assert_equal 'Succeeded', response.message
end
def test_successful_purchase_with_minimal_options
response = @gateway.purchase(@amount, @credit_card, billing_address: address)
assert_success response
assert_equal 'Succeeded', response.message
end
def test_successful_purchase_without_phone_number
response = @gateway.purchase(@amount, @credit_card, billing_address: address.update(phone: ''))
assert_success response
assert_equal 'Succeeded', response.message
end
def test_successful_purchase_with_ip
response = @gateway.purchase(@amount, @credit_card, ip: "96.125.185.52")
assert_success response
assert_equal 'Succeeded', response.message
end
def test_failed_purchase
response = @gateway.purchase(@amount, @declined_card, @options)
assert_failure response
assert_equal 'Invalid Card Number', response.message
end
def test_avs_failed_purchase
response = @gateway.purchase(@amount, @credit_card, billing_address: address.update(address1: 'Test_A'))
assert_failure response
assert_equal '40111 - Street Match Only', response.message
end
def test_successful_authorize_and_capture
auth = @gateway.authorize(@amount, @credit_card, @options)
assert_success auth
assert capture = @gateway.capture(nil, auth.authorization)
assert_success capture
end
def test_failed_authorize
response = @gateway.authorize(@amount, @declined_card, @options)
assert_failure response
end
def test_partial_capture
auth = @gateway.authorize(@amount, @credit_card, @options)
assert_success auth
assert capture = @gateway.capture(@amount-1, auth.authorization)
assert_success capture
end
def test_failed_capture
response = @gateway.capture(nil, '')
assert_failure response
end
def test_successful_refund
purchase = @gateway.purchase(@amount, @credit_card, @options)
assert_success purchase
assert refund = @gateway.refund(@amount, purchase.authorization)
assert_success refund
end
def test_partial_refund
purchase = @gateway.purchase(@amount, @credit_card, @options)
assert_success purchase
assert refund = @gateway.refund(@amount-1, purchase.authorization)
assert_success refund
end
def test_failed_refund
response = @gateway.refund(nil, '')
assert_failure response
end
def test_successful_void
auth = @gateway.authorize(@amount, @credit_card, @options)
assert_success auth
assert void = @gateway.void(auth.authorization)
assert_success void
end
def test_failed_void
response = @gateway.void('')
assert_failure response
end
def test_successful_verify
response = @gateway.verify(@credit_card, @options)
assert_success response
assert_match %r{Succeeded}, response.message
end
def test_failed_verify
response = @gateway.verify(@declined_card, @options)
assert_failure response
assert_match %r{Invalid Card Number}, response.message
assert_equal Gateway::STANDARD_ERROR_CODE[:invalid_number], response.error_code
end
end
| mit |
dbollaer/angular2-starter | examples/rx-draggable/app.ts | 447 | /// <reference path="../typings/_custom.d.ts" />
// Angular 2
import {Component, View} from 'angular2/angular2';
import {DragElement} from './components/drag-element';
/*
* App Component
* our top level component that holds all of our components
*/
@Component({
selector: 'app'
})
@View({
directives: [ DragElement ],
template: `
<main>
<drag-element></drag-element>
</main>
`
})
export class App {
constructor() {
}
}
| mit |
m4ce/telegraf | plugins/inputs/openldap/openldap_test.go | 4294 | package openldap
import (
"strconv"
"testing"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/ldap.v3"
)
func TestOpenldapMockResult(t *testing.T) {
var acc testutil.Accumulator
mockSearchResult := ldap.SearchResult{
Entries: []*ldap.Entry{
{
DN: "cn=Total,cn=Connections,cn=Monitor",
Attributes: []*ldap.EntryAttribute{{Name: "monitorCounter", Values: []string{"1"}}},
},
},
Referrals: []string{},
Controls: []ldap.Control{},
}
o := &Openldap{
Host: "localhost",
Port: 389,
}
gatherSearchResult(&mockSearchResult, o, &acc)
commonTests(t, o, &acc)
}
func TestOpenldapNoConnection(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
o := &Openldap{
Host: "nosuchhost",
Port: 389,
}
var acc testutil.Accumulator
err := o.Gather(&acc)
require.NoError(t, err) // test that we didn't return an error
assert.Zero(t, acc.NFields()) // test that we didn't return any fields
assert.NotEmpty(t, acc.Errors) // test that we set an error
}
func TestOpenldapGeneratesMetrics(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
o := &Openldap{
Host: testutil.GetLocalHost(),
Port: 389,
}
var acc testutil.Accumulator
err := o.Gather(&acc)
require.NoError(t, err)
commonTests(t, o, &acc)
}
func TestOpenldapStartTLS(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
o := &Openldap{
Host: testutil.GetLocalHost(),
Port: 389,
SSL: "starttls",
InsecureSkipVerify: true,
}
var acc testutil.Accumulator
err := o.Gather(&acc)
require.NoError(t, err)
commonTests(t, o, &acc)
}
func TestOpenldapLDAPS(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
o := &Openldap{
Host: testutil.GetLocalHost(),
Port: 636,
SSL: "ldaps",
InsecureSkipVerify: true,
}
var acc testutil.Accumulator
err := o.Gather(&acc)
require.NoError(t, err)
commonTests(t, o, &acc)
}
func TestOpenldapInvalidSSL(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
o := &Openldap{
Host: testutil.GetLocalHost(),
Port: 636,
SSL: "invalid",
InsecureSkipVerify: true,
}
var acc testutil.Accumulator
err := o.Gather(&acc)
require.NoError(t, err) // test that we didn't return an error
assert.Zero(t, acc.NFields()) // test that we didn't return any fields
assert.NotEmpty(t, acc.Errors) // test that we set an error
}
func TestOpenldapBind(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
o := &Openldap{
Host: testutil.GetLocalHost(),
Port: 389,
SSL: "",
InsecureSkipVerify: true,
BindDn: "cn=manager,cn=config",
BindPassword: "secret",
}
var acc testutil.Accumulator
err := o.Gather(&acc)
require.NoError(t, err)
commonTests(t, o, &acc)
}
func commonTests(t *testing.T, o *Openldap, acc *testutil.Accumulator) {
assert.Empty(t, acc.Errors, "accumulator had no errors")
assert.True(t, acc.HasMeasurement("openldap"), "Has a measurement called 'openldap'")
assert.Equal(t, o.Host, acc.TagValue("openldap", "server"), "Has a tag value of server=o.Host")
assert.Equal(t, strconv.Itoa(o.Port), acc.TagValue("openldap", "port"), "Has a tag value of port=o.Port")
assert.True(t, acc.HasInt64Field("openldap", "total_connections"), "Has an integer field called total_connections")
}
func TestOpenldapReverseMetrics(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
o := &Openldap{
Host: testutil.GetLocalHost(),
Port: 389,
SSL: "",
InsecureSkipVerify: true,
BindDn: "cn=manager,cn=config",
BindPassword: "secret",
ReverseMetricNames: true,
}
var acc testutil.Accumulator
err := o.Gather(&acc)
require.NoError(t, err)
assert.True(t, acc.HasInt64Field("openldap", "connections_total"), "Has an integer field called connections_total")
}
| mit |
AndreaZain/dl-module | src/managers/master/comodity-manager.js | 3833 | 'use strict'
var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");
var DLModels = require('dl-models');
var map = DLModels.map;
var Comodity = DLModels.master.Comodity;
var BaseManager = require('module-toolkit').BaseManager;
var i18n = require('dl-i18n');
var generateCode = require("../../utils/code-generator");
module.exports = class ComodityManager extends BaseManager {
constructor(db, user) {
super(db, user);
this.collection = this.db.use(map.master.collection.Comodity);
}
_beforeInsert(data) {
if(!data.code)
data.code = generateCode();
return Promise.resolve(data);
}
_getQuery(paging) {
var _default = {
_deleted: false
},
pagingFilter = paging.filter || {},
keywordFilter = {},
query = {};
if (paging.keyword) {
var regex = new RegExp(paging.keyword, "i");
var codeFilter = {
'code': {
'$regex': regex
}
};
var nameFilter = {
'name': {
'$regex': regex
}
};
keywordFilter['$or'] = [codeFilter, nameFilter];
}
query["$and"] = [_default, keywordFilter, pagingFilter];
return query;
}
_validate(comodity) {
var errors = {};
var valid = comodity;
// 1. begin: Declare promises.
var getcomodityPromise = this.collection.singleOrDefault({
_id: {
'$ne': new ObjectId(valid._id)
},
// code: valid.code,
name: valid.name,
_deleted: false
});
// 2. begin: Validation.
return Promise.all([getcomodityPromise])
.then(results => {
var _comodity = results[0];
// if (!valid.code || valid.code == '')
// errors["code"] = i18n.__("Comodity.code.isRequired:%s is required", i18n.__("Comodity.code._:Code")); //"Nama Comodity Tidak Boleh Kosong";
if (_comodity) {
// errors["code"] = i18n.__("Comodity.code.isExists:%s is already exists", i18n.__("Comodity.code._:Code")); //"kode Comodity sudah terdaftar";
errors["name"] = i18n.__("Comodity.name.isExists:%s is already exists", i18n.__("Comodity.name._:Name")); //"Nama Comodity sudah terdaftar";
}
if (!valid.name || valid.name == '')
errors["name"] = i18n.__("Comodity.name.isRequired:%s is required", i18n.__("Comodity.name._:Name")); //"Nama Harus diisi";
// if (!valid.type || valid.type == '')
// errors["type"] = i18n.__("Comodity.type.isRequired:%s is required", i18n.__("Comodity.type._:Type")); //"type Harus diisi";
if (Object.getOwnPropertyNames(errors).length > 0) {
var ValidationError = require('module-toolkit').ValidationError;
return Promise.reject(new ValidationError('data does not pass validation', errors));
}
valid = new Comodity(comodity);
valid.stamp(this.user.username, 'manager');
return Promise.resolve(valid);
});
}
_createIndexes() {
var dateIndex = {
name: `ix_${map.master.collection.Comodity}__updatedDate`,
key: {
_updatedDate: -1
}
};
var codeIndex = {
name: `ix_${map.master.collection.Comodity}_code_name`,
key: {
code: 1,
name:1
}
};
return this.collection.createIndexes([dateIndex, codeIndex]);
}
}
| mit |
tsolucio/coreBOSTests | vendor/sebastian/type/src/exception/LogicException.php | 371 | <?php declare(strict_types=1);
/*
* This file is part of sebastian/type.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
final class LogicException extends \LogicException implements Exception
{
}
| mit |
AlphaModder/SpongeAPI | src/main/java/org/spongepowered/api/scoreboard/CollisionRule.java | 1639 | /*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.scoreboard;
import org.spongepowered.api.CatalogType;
import org.spongepowered.api.util.annotation.CatalogedBy;
/**
* Represents a collision rule.
*
* <p>A collision rule controls how {@link TeamMember}s on
* a {@link Team} collide with other entities.</p>
*/
@CatalogedBy(CollisionRules.class)
public interface CollisionRule extends CatalogType {
}
| mit |
shirasagi/shirasagi | app/models/concerns/opendata/harvest/shirasagi_api_importer.rb | 6728 | module Opendata::Harvest::ShirasagiApiImporter
extend ActiveSupport::Concern
private
def import_from_shirasagi_api
put_log("import from #{source_url} (Shirasagi API)")
if reports.count >= 5
reports.order_by(created: 1).first.destroy
end
@report = Opendata::Harvest::Importer::Report.new(cur_site: site, importer: self)
@report.save!
opts = {}
opts[:http_basic_authentication] = [basicauth_username, basicauth_password] if basicauth_enabled?
package = ::Opendata::Harvest::ShirasagiPackage.new(source_url, opts)
imported_dataset_ids = []
list = package.package_list
put_log("package_list #{list.size}")
list.each_with_index do |name, idx|
begin
put_log("- #{idx + 1} #{name}")
@report_dataset = @report.new_dataset
dataset_attributes = package.package_show(name)
dataset = create_dataset_from_shirasagi_api(dataset_attributes, package.package_show_url(name))
@report_dataset.set_reports(dataset, dataset_attributes, package.package_show_url(name), idx)
imported_dataset_ids << dataset.id
# resources
imported_resource_ids = []
dataset_attributes["resources"].each_with_index do |resource_attributes, idx|
begin
@report_resource = @report_dataset.new_resource
resource = create_resource_from_shirasagi_api(resource_attributes, idx, dataset)
imported_resource_ids << resource.id
@report_resource.set_reports(resource, resource_attributes, idx)
rescue => e
message = "#{e.class} (#{e.message}):\n #{e.backtrace.join("\n ")}"
put_log(message)
@report_resource.add_error(message)
ensure
@report_resource.save!
end
end
# destroy unimported resources
dataset.resources.each do |resource|
next if imported_resource_ids.include?(resource.id)
put_log("-- resource : destroy #{resource.name}")
resource.destroy
end
dataset.harvest_imported ||= Time.zone.now
set_relation_ids(dataset)
@report_dataset.set_reports(dataset, dataset_attributes, package.package_show_url(name), idx)
rescue => e
message = "#{e.class} (#{e.message}):\n #{e.backtrace.join("\n ")}"
put_log(message)
@report_dataset.add_error(message)
ensure
@report_dataset.save!
end
end
# destroy unimported datasets
dataset_ids = ::Opendata::Dataset.site(site).node(node).where(
"harvest_api_type" => api_type,
"harvest_host" => source_host
).pluck(:id)
dataset_ids -= imported_dataset_ids
dataset_ids.each do |id|
dataset = ::Opendata::Dataset.find(id) rescue nil
next unless dataset
put_log("- dataset : destroy #{dataset.name}")
dataset.destroy
end
@report.save!
end
def create_dataset_from_shirasagi_api(attributes, url)
dataset = ::Opendata::Dataset.node(node).where(uuid: attributes["uuid"]).first
dataset ||= ::Opendata::Dataset.new
dataset.cur_site = site
dataset.cur_node = node
def dataset.set_updated; end
dataset.layout = node.page_layout || node.layout
dataset.uuid = attributes["uuid"]
dataset.name = attributes["name"]
dataset.text = attributes["text"]
dataset.update_plan = attributes["update_plan"]
dataset.contact_charge = attributes["author"] if attributes["author"].present?
dataset.group_ids = group_ids
dataset.updated = Time.zone.parse(attributes["updated"])
dataset.created = Time.zone.parse(attributes["created"])
dataset.released = Time.zone.parse(attributes["released"])
dataset.harvest_importer = self
dataset.harvest_host = source_host
dataset.harvest_api_type = api_type
#dataset.harvest_imported ||= Time.zone.now
dataset.harvest_imported_url = url
dataset.harvest_imported_attributes = attributes
dataset.state = "public"
put_log("- dataset : #{dataset.new_record? ? "create" : "update"} #{dataset.name}")
dataset.save!
dataset
end
def create_resource_from_shirasagi_api(attributes, idx, dataset)
resource = dataset.resources.select { |r| r.uuid == attributes["uuid"] }.first
if resource.nil?
resource = Opendata::Resource.new
dataset.resources << resource
end
if resource.revision_id == attributes["revision_id"]
put_log("-- resource : same revision_id #{resource.name}")
return resource
end
url = attributes["url"]
filename = attributes["filename"]
format = attributes["format"]
if external_resouce?(url, format)
# set source url
resource.source_url = url
else
# download file from url
if resource.file
ss_file = SS::StreamingFile.find(resource.file_id)
ss_file.name = nil
ss_file.filename = nil
else
ss_file = SS::StreamingFile.new
ss_file.in_size_limit = resource_size_limit_mb * 1024 * 1024
end
ss_file.in_remote_url = url
if basicauth_enabled?
ss_file.in_remote_basic_authentication = [basicauth_username, basicauth_password]
end
ss_file.model = "opendata/resource"
ss_file.state = "public"
ss_file.site_id = site.id
begin
ss_file.save!
resource.file_id = ss_file.id
rescue SS::StreamingFile::SizeError => e
# set source url
resource.source_url = url
put_log("-- #{filename} : file size exceeded #{resource_size_limit_mb} MB, set source_url")
end
end
resource.order = idx
resource.uuid = attributes["uuid"]
resource.revision_id = attributes["revision_id"]
resource.name = attributes["name"]
resource.text = attributes["text"]
resource.filename = filename
resource.format = format
license = get_license_from_uid(attributes.dig("license", "uid"))
license ||= get_license_from_name(attributes.dig("license", "name"))
put_log("could not found license #{attributes.dig("license", "uid")}") if license.nil?
resource.license = license
def resource.set_updated; end
def resource.set_revision_id; end
def resource.compression_dataset; end
resource.updated = dataset.updated
resource.created = dataset.created
resource.harvest_importer = self
resource.harvest_host = source_host
resource.harvest_api_type = api_type
resource.harvest_imported ||= Time.zone.now
resource.harvest_imported_url = url
resource.harvest_imported_attributes = attributes
put_log("-- resource : #{resource.new_record? ? "create" : "update"} #{resource.name}")
resource.save!
resource
end
end
| mit |
dsebastien/DefinitelyTyped | types/node/test/fs.ts | 13581 | import * as fs from 'fs';
import * as assert from 'assert';
import * as util from 'util';
{
fs.writeFile("thebible.txt",
"Do unto others as you would have them do unto you.",
assert.ifError);
fs.write(1234, "test", () => { });
fs.writeFile("Harry Potter",
"\"You be wizzing, Harry,\" jived Dumbledore.",
{
encoding: "ascii"
},
assert.ifError);
fs.writeFile("testfile", "content", "utf8", assert.ifError);
fs.writeFileSync("testfile", "content", "utf8");
fs.writeFileSync("testfile", "content", { encoding: "utf8" });
fs.writeFileSync("testfile", new DataView(new ArrayBuffer(1)), { encoding: "utf8" });
}
{
fs.appendFile("testfile", "foobar", "utf8", assert.ifError);
fs.appendFile("testfile", "foobar", { encoding: "utf8" }, assert.ifError);
fs.appendFileSync("testfile", "foobar", "utf8");
fs.appendFileSync("testfile", "foobar", { encoding: "utf8" });
}
{
let content: string;
let buffer: Buffer;
let stringOrBuffer: string | Buffer;
const nullEncoding: BufferEncoding | null = null;
const stringEncoding: BufferEncoding | null = 'utf8';
content = fs.readFileSync('testfile', 'utf8');
content = fs.readFileSync('testfile', { encoding: 'utf8' });
stringOrBuffer = fs.readFileSync('testfile', stringEncoding);
stringOrBuffer = fs.readFileSync('testfile', { encoding: stringEncoding });
buffer = fs.readFileSync('testfile');
buffer = fs.readFileSync('testfile', null);
buffer = fs.readFileSync('testfile', { encoding: null });
stringOrBuffer = fs.readFileSync('testfile', nullEncoding);
stringOrBuffer = fs.readFileSync('testfile', { encoding: nullEncoding });
buffer = fs.readFileSync('testfile', { flag: 'r' });
fs.readFile('testfile', 'utf8', (err, data) => content = data);
fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data);
fs.readFile('testfile', stringEncoding, (err, data) => stringOrBuffer = data);
fs.readFile('testfile', { encoding: stringEncoding }, (err, data) => stringOrBuffer = data);
fs.readFile('testfile', (err, data) => buffer = data);
fs.readFile('testfile', null, (err, data) => buffer = data);
fs.readFile('testfile', { encoding: null }, (err, data) => buffer = data);
fs.readFile('testfile', nullEncoding, (err, data) => stringOrBuffer = data);
fs.readFile('testfile', { encoding: nullEncoding }, (err, data) => stringOrBuffer = data);
fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data);
}
{
fs.read(1, new DataView(new ArrayBuffer(1)), 0, 1, 0, (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: DataView) => {});
}
{
fs.readSync(1, new DataView(new ArrayBuffer(1)), 0, 1, 0);
fs.readSync(1, Buffer.from(''), {
length: 123,
offset: 456,
position: null,
});
}
{
let errno: number;
fs.readFile('testfile', (err, data) => {
if (err && err.errno) {
errno = err.errno;
}
});
}
{
let listS: string[];
listS = fs.readdirSync('path');
listS = fs.readdirSync('path', { encoding: 'utf8' });
listS = fs.readdirSync('path', { encoding: null });
listS = fs.readdirSync('path', { encoding: undefined }) as string[];
listS = fs.readdirSync('path', 'utf8');
listS = fs.readdirSync('path', null);
listS = fs.readdirSync('path', undefined);
const listDir: fs.Dirent[] = fs.readdirSync('path', { withFileTypes: true });
const listDir2: Buffer[] = fs.readdirSync('path', { withFileTypes: false, encoding: 'buffer' });
const listDir3: fs.Dirent[] = fs.readdirSync('path', { encoding: 'utf8', withFileTypes: true });
let listB: Buffer[];
listB = fs.readdirSync('path', { encoding: 'buffer' });
listB = fs.readdirSync("path", 'buffer');
const enc = 'buffer';
fs.readdirSync('path', { encoding: enc });
fs.readdirSync('path', { });
fs.readdir('path', { withFileTypes: true }, (err: NodeJS.ErrnoException | null, files: fs.Dirent[]) => {});
}
async function testPromisify() {
const rd = util.promisify(fs.readdir);
let listS: string[];
listS = await rd('path');
listS = await rd('path', 'utf8');
listS = await rd('path', null);
listS = await rd('path', undefined);
listS = await rd('path', { encoding: 'utf8' });
listS = await rd('path', { encoding: null });
listS = await rd('path', { encoding: null, withFileTypes: false });
listS = await rd('path', { encoding: 'utf8', withFileTypes: false });
const listDir: fs.Dirent[] = await rd('path', { withFileTypes: true });
const listDir2: Buffer[] = await rd('path', { withFileTypes: false, encoding: 'buffer' });
const listDir3: fs.Dirent[] = await rd('path', { encoding: 'utf8', withFileTypes: true });
const ln = util.promisify(fs.link);
// $ExpectType Promise<void>
ln("abc", "def");
}
{
fs.mkdtemp('/tmp/foo-', (err, folder) => {
console.log(folder);
// Prints: /tmp/foo-itXde2
});
}
{
let tempDir: string;
tempDir = fs.mkdtempSync('/tmp/foo-');
}
{
fs.watch('/tmp/foo-', (event, filename) => {
console.log(event, filename);
});
fs.watch('/tmp/foo-', 'utf8', (event, filename) => {
console.log(event, filename);
});
fs.watch('/tmp/foo-', {
recursive: true,
persistent: true,
encoding: 'utf8'
}, (event, filename) => {
console.log(event, filename);
});
}
{
fs.access('/path/to/folder', (err) => { });
fs.access(Buffer.from(''), (err) => { });
fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => { });
fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => { });
fs.accessSync('/path/to/folder');
fs.accessSync(Buffer.from(''));
fs.accessSync('path/to/folder', fs.constants.W_OK | fs.constants.X_OK);
fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK);
}
{
let s = '123';
let b: Buffer;
fs.readlink('/path/to/folder', (err, linkString) => s = linkString);
fs.readlink('/path/to/folder', undefined, (err, linkString) => s = linkString);
fs.readlink('/path/to/folder', 'utf8', (err, linkString) => s = linkString);
fs.readlink('/path/to/folder', 'buffer', (err, linkString) => b = linkString);
fs.readlink('/path/to/folder', s, (err, linkString) => typeof linkString === 'string' ? s = linkString : b = linkString);
fs.readlink('/path/to/folder', {}, (err, linkString) => s = linkString);
fs.readlink('/path/to/folder', { encoding: undefined }, (err, linkString) => s = linkString);
fs.readlink('/path/to/folder', { encoding: 'utf8' }, (err, linkString) => s = linkString);
fs.readlink('/path/to/folder', { encoding: 'buffer' }, (err, linkString) => b = linkString);
s = fs.readlinkSync('/path/to/folder');
s = fs.readlinkSync('/path/to/folder', undefined);
s = fs.readlinkSync('/path/to/folder', 'utf8');
b = fs.readlinkSync('/path/to/folder', 'buffer');
const v1 = fs.readlinkSync('/path/to/folder', s);
typeof v1 === "string" ? s = v1 : b = v1;
s = fs.readlinkSync('/path/to/folder', {});
s = fs.readlinkSync('/path/to/folder', { encoding: undefined });
s = fs.readlinkSync('/path/to/folder', { encoding: 'utf8' });
b = fs.readlinkSync('/path/to/folder', { encoding: 'buffer' });
}
{
let s = '123';
let b: Buffer;
fs.realpath('/path/to/folder', (err, resolvedPath) => s = resolvedPath);
fs.realpath('/path/to/folder', undefined, (err, resolvedPath) => s = resolvedPath);
fs.realpath('/path/to/folder', 'utf8', (err, resolvedPath) => s = resolvedPath);
fs.realpath('/path/to/folder', 'buffer', (err, resolvedPath) => b = resolvedPath);
fs.realpath('/path/to/folder', s, (err, resolvedPath) => typeof resolvedPath === 'string' ? s = resolvedPath : b = resolvedPath);
fs.realpath('/path/to/folder', {}, (err, resolvedPath) => s = resolvedPath);
fs.realpath('/path/to/folder', { encoding: undefined }, (err, resolvedPath) => s = resolvedPath);
fs.realpath('/path/to/folder', { encoding: 'utf8' }, (err, resolvedPath) => s = resolvedPath);
fs.realpath('/path/to/folder', { encoding: 'buffer' }, (err, resolvedPath) => b = resolvedPath);
s = fs.realpathSync('/path/to/folder');
s = fs.realpathSync('/path/to/folder', undefined);
s = fs.realpathSync('/path/to/folder', 'utf8');
b = fs.realpathSync('/path/to/folder', 'buffer');
const v1 = fs.realpathSync('/path/to/folder', s);
typeof v1 === "string" ? s = v1 : b = v1;
s = fs.realpathSync('/path/to/folder', {});
s = fs.realpathSync('/path/to/folder', { encoding: undefined });
s = fs.realpathSync('/path/to/folder', { encoding: 'utf8' });
b = fs.realpathSync('/path/to/folder', { encoding: 'buffer' });
// native
fs.realpath.native('/path/to/folder', (err, resolvedPath) => s = resolvedPath);
fs.realpath.native('/path/to/folder', undefined, (err, resolvedPath) => s = resolvedPath);
fs.realpath.native('/path/to/folder', 'utf8', (err, resolvedPath) => s = resolvedPath);
fs.realpath.native('/path/to/folder', 'buffer', (err, resolvedPath) => b = resolvedPath);
fs.realpath.native('/path/to/folder', s, (err, resolvedPath) => typeof resolvedPath === 'string' ? s = resolvedPath : b = resolvedPath);
fs.realpath.native('/path/to/folder', {}, (err, resolvedPath) => s = resolvedPath);
fs.realpath.native('/path/to/folder', { encoding: undefined }, (err, resolvedPath) => s = resolvedPath);
fs.realpath.native('/path/to/folder', { encoding: 'utf8' }, (err, resolvedPath) => s = resolvedPath);
fs.realpath.native('/path/to/folder', { encoding: 'buffer' }, (err, resolvedPath) => b = resolvedPath);
s = fs.realpathSync.native('/path/to/folder');
s = fs.realpathSync.native('/path/to/folder', undefined);
s = fs.realpathSync.native('/path/to/folder', 'utf8');
b = fs.realpathSync.native('/path/to/folder', 'buffer');
const v3 = fs.realpathSync.native('/path/to/folder', s);
typeof v3 === "string" ? s = v3 : b = v3;
s = fs.realpathSync.native('/path/to/folder', {});
s = fs.realpathSync.native('/path/to/folder', { encoding: undefined });
s = fs.realpathSync.native('/path/to/folder', { encoding: 'utf8' });
b = fs.realpathSync.native('/path/to/folder', { encoding: 'buffer' });
}
{
fs.copyFile('/path/to/src', '/path/to/dest', (err) => console.error(err));
fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL, (err) => console.error(err));
fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE, (err) => console.error(err));
fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE_FORCE, (err) => console.error(err));
fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL);
fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE);
fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE_FORCE);
const cf = util.promisify(fs.copyFile);
cf('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL).then(console.log);
}
{
fs.mkdir('some/test/path', {
recursive: true,
mode: 0o777,
}, (err, path) => {
err; // $ExpectType ErrnoException | null
path; // $ExpectType string
});
// $ExpectType string
fs.mkdirSync('some/test/path', {
recursive: true,
mode: 0o777,
});
// $ExpectType Promise<string>
util.promisify(fs.mkdir)('some/test/path', {
recursive: true,
mode: 0o777,
});
// $ExpectType Promise<string>
fs.promises.mkdir('some/test/path', {
recursive: true,
mode: 0o777,
});
}
{
let names: Promise<string[]>;
let buffers: Promise<Buffer[]>;
let entries: Promise<fs.Dirent[]>;
names = fs.promises.readdir('/path/to/dir', { encoding: 'utf8', withFileTypes: false });
buffers = fs.promises.readdir('/path/to/dir', { encoding: 'buffer', withFileTypes: false });
entries = fs.promises.readdir('/path/to/dir', { encoding: 'utf8', withFileTypes: true });
}
{
fs.writev(1, [Buffer.from('123')], (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => {
});
const bytesWritten = fs.writevSync(1, [Buffer.from('123')]);
}
(async () => {
try {
await fs.promises.rmdir('some/test/path');
await fs.promises.rmdir('some/test/path', { recursive: true, maxRetries: 123, retryDelay: 123 });
} catch (e) {}
})();
{
fs.opendir('test', async (err, dir) => {
const dirEnt: fs.Dirent | null = await dir.read();
});
const dir: fs.Dir = fs.opendirSync('test', {
encoding: 'utf8',
});
// Pending lib upgrade
// (async () => {
// for await (const thing of dir) {
// }
// });
const dirEntProm: Promise<fs.Dir> = fs.promises.opendir('test', {
encoding: 'utf8',
bufferSize: 42,
});
}
{
const writeStream = fs.createWriteStream('./index.d.ts');
const _wom = writeStream.writableObjectMode; // $ExpectType boolean
const readStream = fs.createReadStream('./index.d.ts');
const _rom = readStream.readableObjectMode; // $ExpectType boolean
}
{
fs.readvSync(123, [Buffer.from('wut')]);
fs.readv(123, [Buffer.from('wut')], 123, (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => {
});
}
| mit |
SidHarder/meetings | client/jspm_packages/npm/core-js@2.1.0/fn/function/bind.js | 114 | /* */
require('../../modules/es6.function.bind');
module.exports = require('../../modules/_core').Function.bind;
| mit |
Darkrender/raptor-ads | client/src/components/Ratings/NewRating.js | 2419 | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Container, Form, Button } from 'semantic-ui-react';
import StarRatingComponent from 'react-star-rating-component';
import { getUserDetails } from '../UserDetails/actions';
import { changeStars, changeForm, submitRatingsForm } from '../Ratings/actions';
class NewRating extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const { userId } = this.props;
this.props.dispatch(getUserDetails(userId));
this.onStarClick = this.onStarClick.bind(this);
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onStarClick(next) {
this.props.dispatch(changeStars(next));
}
onChange(e) {
this.props.dispatch(changeForm(e.target.name, e.target.value));
}
onSubmit(e) {
e.preventDefault();
const { userId, stars, content } = this.props;
const raterId = this.props.rater.id;
const payload = {
userId,
stars,
content,
raterId,
};
this.props.dispatch(submitRatingsForm(payload));
}
render() {
const {
user,
content,
stars,
} = this.props;
return (
<Container textAlign="center">
<h1>
Rate { `${user.firstName} ${user.lastName}!` }
</h1>
<Form onSubmit={(e) => this.onSubmit(e)}>
<h4>Stars</h4>
<StarRatingComponent
name={"stars"}
value={+stars}
editing={true}
starColor="#31b234"
onStarClick={(next) => { this.onStarClick(next); }}
/>
<Form.TextArea
className="ratingContent"
label="Review"
placeholder="Write a review..."
value={content}
name="content"
onChange={(e) => this.onChange(e)}
/>
<Button type="submit">Submit Rating</Button>
</Form>
</Container>
);
}
}
const mapStateToProps = (state) => {
const { pathname } = state.routing.locationBeforeTransitions;
const { content, stars } = state.ratings.ratingsForm;
const user = state.userDetails.currentUserDetails;
const { loggedInUser: rater } = state.auth;
const userId = pathname.split('/')[2];
return ({
userId,
user,
rater,
content,
stars,
});
};
export default connect(mapStateToProps)(NewRating);
| mit |
deywibkiss/jooinworld | components/com_community/templates/default/activities.actions.php | 6499 | <?php
/**
* @copyright (C) 2013 iJoomla, Inc. - All rights reserved.
* @license GNU General Public License, version 2 (http://www.gnu.org/licenses/gpl-2.0.html)
* @author iJoomla.com <webmaster@ijoomla.com>
* @url https://www.jomsocial.com/license-agreement
* The PHP code portions are distributed under the GPL license. If not otherwise stated, all images, manuals, cascading style sheets, and included JavaScript *are NOT GPL, and are released under the IJOOMLA Proprietary Use License v1.0
* More info at https://www.jomsocial.com/license-agreement
*/
// test
// $act->app can be a single word or in app.action form.
// EG:// 'event', 'event.wall'. Find the first part only
$appName = explode('.', $act->app);
$appName = $appName[0];
// Grab primary object to be used in permission checking, defined by appname
$obj = $act;
if( $appName == 'groups'){
$obj = $this->group;
}
if($appName == 'events'){
$obj = $this->event;
}
$my = CFactory::getUser();
$allowLike = !empty($my->id);
$allowComment = ($my -> authorise('community.add','activities.comment.'.$this->act->actor, $obj) );
$showLocation = !empty($this->act->location);
// @todo: delete permission shoudl be handled within ACL system
$allowDelete= ( ($act->actor == $my->id) || $isCommunityAdmin || ( $act->target == $my->id )) && ($my->id != 0);
// Allow system message deletion only for admin
if($act->app == 'users.featured'){
$allowDelete= $isCommunityAdmin;
}
//Discussion Replies shouldnt allow any commenting - 30Jan13 (http://www.ijoomla.com:8080/browse/JOM-142)
if($act->app == 'groups.discussion.reply' || $act->app == 'groups.discussion' || $act->app == 'groups.bulletin'){
$allowComment = false;
}
// Allow comment for system post
if($appName == 'system'){
$allowComment = !empty($my->id);
}
?>
<div class="cStream-Actions clearfix">
<i class="cStream-Icon com-icon-<?php echo $appName;?> <?php if( isset($act->isFeatured)) echo 'com-icon-award-gold' ;?>"></i>
<!-- Show likes -->
<?php if($allowLike) { ?>
<span>
<?php if($act->userLiked!=COMMUNITY_LIKE) { ?>
<a id="like_id<?php echo $act->id?>" href="#like" ><?php echo JText::_('COM_COMMUNITY_LIKE');?></a>
<?php } else { ?>
<a id="like_id<?php echo $act->id?>" href="#unlike" ><?php echo JText::_('COM_COMMUNITY_UNLIKE');?></a>
<?php } ?>
</span>
<?php } ?>
<!-- Show if it is explicitly allowed: -->
<?php if($allowComment ) { ?>
<span><a href="javascript:void(0);" onclick="joms.miniwall.show('<?php echo $act->id; ?>', this);return false;"><?php echo JText::_('COM_COMMUNITY_COMMENT');?></a></span>
<?php } ?>
<?php if( $showLocation ) { ?>
<span><a onclick="joms.activities.showMap(<?php echo $act->id; ?>, '<?php echo urlencode($act->location); ?>');" class="newsfeed-location" title="<?php echo JText::_('COM_COMMUNITY_VIEW_LOCATION_TIPS');?>" href="javascript: void(0)"><?php echo JText::_('COM_COMMUNITY_VIEW_LOCATION');?></a></span>
<?php } ?>
<?php /* Allow deleted */ ?>
<?php if( $allowDelete ) { ?>
<span><a href="#deletePost" class="newsfeed-location" title="<?php echo JText::_('COM_COMMUNITY_DELETE');?>" href="javascript: void(0)"><?php echo JText::_('COM_COMMUNITY_DELETE');?></a></span>
<?php } ?>
<?php
// Format created date
$config = CFactory::getConfig();
$date = JFactory::getDate($act->created);
if ( $config->get('activitydateformat') == "lapse" ) {
$createdTime = CTimeHelper::timeLapse($date);
} else {
$createdTime = $date;
}
?>
<span><?php echo $createdTime; ?></span>
<?php
// Show access class for "friends (30)" or "me only (40)"
$accessClass = 'public'; // NO need to display this
$accessClass = ($act->access == PRIVACY_FRIENDS) ? 'site' : $accessClass ;
$accessClass = ($act->access == PRIVACY_FRIENDS) ? 'friends' : $accessClass ;
$accessClass = ($act->access == PRIVACY_PRIVATE) ? 'me' : $accessClass ;
$accessTitle = "";
$accessTitle = ($accessClass == 'site') ? JText::_('COM_COMMUNITY_PRIVACY_TITLE_SITE_MEMBERS') : $accessTitle;
$accessTitle = ($accessClass == 'friends') ? JText::_('COM_COMMUNITY_PRIVACY_TITLE_FRIENDS') : $accessTitle;
$accessTitle = ($accessClass == 'me') ? JText::_('COM_COMMUNITY_PRIVACY_TITLE_ME') : $accessTitle;
if($accessClass != 'public') {
?>
<span>
<i class="com-glyph-lock-<?php echo $accessClass; ?>" title="<?php echo $accessTitle; ?>"></i>
</span>
<?php } ?>
</div>
<?php if( $allowComment || $allowLike || $showLike) { ?>
<div class="cStream-Respond wall-cocs" id="wall-cmt-<?php echo $act->id; ?>">
<?php if($act->likeCount > 0 && $showLike) { /* hide count if no one like it */?>
<div class="cStream-Likes">
<i class="stream-icon com-icon-thumbup"></i>
<a onclick="jax.call('community','system,ajaxStreamShowLikes', '<?php echo $act->id; ?>');return false;" href="#showLikes"><?php echo ($act->likeCount > 1) ? JText::sprintf('COM_COMMUNITY_LIKE_THIS_MANY', $act->likeCount) : JText::sprintf('COM_COMMUNITY_LIKE_THIS', $act->likeCount); ?></a>
</div>
<?php } ?>
<?php if( $act->commentCount > 1 ) { ?>
<div class="cStream-More" data-commentmore="true">
<i class="stream-icon com-icon-comment"></i>
<a href="#showallcomments"><?php echo JText::sprintf('COM_COMMUNITY_ACTIVITY_NO_COMMENT',$act->commentCount,'wall-cmt-count') ?></a>
</div>
<?php } ?>
<?php if( $act->commentCount > 0 ) { ?>
<?php echo $act->commentLast; ?>
<?php } ?>
<?php if($allowComment ) : ?>
<div class="cStream-Form stream-form wallform <?php if($act->commentCount == 0): echo 'wallnone'; endif; ?>" data-formblock="true">
<!-- post new comment form -->
<form class="reset-gap">
<textarea class="cStream-FormText input-block-level" cols="" rows="" style="height: 40px;" name="comment"></textarea>
<div class="cStream-FormSubmit">
<a class="cStream-FormCancel" onclick="joms.miniwall.cancel('<?php echo $act->id; ?>', this);return false;" href="#cancelPostinComment"><?php echo JText::_('COM_COMMUNITY_CANCEL_BUTTON');?></a>
<button href='javascript:void(0);' class="btn btn-primary btn-small" onclick="joms.miniwall.add('<?php echo $act->id; ?>', this);return false;"><?php echo JText::_('COM_COMMUNITY_POST_COMMENT_BUTTON');?></button>
</div>
</form>
</div>
<?php /* Hide reply button if no one has post a comment */ ?>
<?php if( $allowComment ): ?>
<div data-replyblock="true" <?php if( $act->commentCount == 0 ) { echo 'style="display:none"'; }?> >
<span class="cStream-Reply"><a href="javascript:void(0);" onclick="joms.miniwall.show('<?php echo $act->id; ?>', this)" ><?php echo JText::_('COM_COMMUNITY_REPLY');?></a></span>
</div>
<?php endif; ?>
<?php endif; ?>
</div>
<?php } ?>
| mit |
songecko/bak_b | src/Sylius/Bundle/PromotionsBundle/Controller/CouponController.php | 3001 | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\PromotionsBundle\Controller;
use Sylius\Bundle\PromotionsBundle\Generator\CouponGeneratorInterface;
use Sylius\Bundle\PromotionsBundle\Generator\Instruction;
use Sylius\Bundle\ResourceBundle\Controller\ResourceController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Coupon controller.
*
* @author Paweł Jędrzejewski <pjedrzejewski@sylius.pl>
*/
class CouponController extends ResourceController
{
/**
* @param Request $request
*
* @return Response
* @throws NotFoundHttpException
*/
public function generateAction(Request $request)
{
if (null === $promotionId = $request->get('promotionId')) {
throw new NotFoundHttpException('No promotion id given.');
}
$promotion = $this
->getPromotionController()
->findOr404($request, array('id' => $promotionId))
;
$form = $this->createForm('sylius_promotion_coupon_generate_instruction', new Instruction());
if ($request->isMethod('POST') && $form->submit($request)->isValid()) {
$this->getGenerator()->generate($promotion, $form->getData());
$this->flashHelper->setFlash('success', 'generate');
return $this->redirectHandler->redirectTo($promotion);
}
if ($this->config->isApiRequest()) {
return $this->handleView($this->view($form));
}
$view = $this
->view()
->setTemplate($this->config->getTemplate('generate.html'))
->setData(array(
'promotion' => $promotion,
'form' => $form->createView()
))
;
return $this->handleView($view);
}
/**
* {@inheritdoc}
*/
public function createNew()
{
$request = $this->getRequest();
if (null === $promotionId = $request->get('promotionId')) {
throw new NotFoundHttpException('No promotion id given');
}
$promotion = $this
->getPromotionController()
->findOr404($request, array('id' => $promotionId))
;
$coupon = parent::createNew();
$coupon->setPromotion($promotion);
return $coupon;
}
/**
* Get promotion controller.
*
* @return ResourceController
*/
protected function getPromotionController()
{
return $this->get('sylius.controller.promotion');
}
/**
* Get coupon code generator.
*
* @return CouponGeneratorInterface
*/
protected function getGenerator()
{
return $this->get('sylius.generator.promotion_coupon');
}
}
| mit |
konvenit/CASino | spec/processor/session_overview_spec.rb | 1844 | require 'spec_helper'
describe CASino::SessionOverviewProcessor do
describe '#process' do
let(:listener) { Object.new }
let(:processor) { described_class.new(listener) }
let(:other_ticket_granting_ticket) { FactoryGirl.create :ticket_granting_ticket }
let(:user) { other_ticket_granting_ticket.user }
let(:user_agent) { other_ticket_granting_ticket.user_agent }
let(:cookies) { { tgt: tgt } }
before(:each) do
listener.stub(:user_not_logged_in)
listener.stub(:ticket_granting_tickets_found)
other_ticket_granting_ticket
end
context 'with an existing ticket-granting ticket' do
let(:ticket_granting_ticket) { FactoryGirl.create :ticket_granting_ticket, user: user }
let(:tgt) { ticket_granting_ticket.ticket }
it 'calls the #ticket_granting_tickets_found method on the listener' do
listener.should_receive(:ticket_granting_tickets_found) do |tickets|
tickets.length.should == 2
end
processor.process(cookies, user_agent)
end
end
context 'with a ticket-granting ticket with same username but different authenticator' do
let(:ticket_granting_ticket) { FactoryGirl.create :ticket_granting_ticket }
let(:tgt) { ticket_granting_ticket.ticket }
it 'calls the #ticket_granting_tickets_found method on the listener' do
listener.should_receive(:ticket_granting_tickets_found) do |tickets|
tickets.length.should == 1
end
processor.process(cookies, user_agent)
end
end
context 'with an invalid ticket-granting ticket' do
let(:tgt) { 'TGT-lalala' }
it 'calls the #user_not_logged_in method on the listener' do
listener.should_receive(:user_not_logged_in).with(no_args)
processor.process(cookies, user_agent)
end
end
end
end | mit |
shayhatsor/orleans | test/TesterInternal/StreamingTests/DynamicStreamProviderConfigurationTests.cs | 15413 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans;
using Orleans.Providers;
using Orleans.Providers.Streams.Generator;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Streams;
using Orleans.TestingHost;
using Orleans.TestingHost.Utils;
using Tester;
using Tester.TestStreamProviders;
using TestExtensions;
using TestGrainInterfaces;
using TestGrains;
using UnitTests.Grains;
using Xunit;
namespace UnitTests.StreamingTests
{
// if we parallelize tests, each test should run in isolation
public class DynamicStreamProviderConfigurationTests : OrleansTestingBase, IClassFixture<DynamicStreamProviderConfigurationTests.Fixture>, IDisposable
{
private readonly Fixture fixture;
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30);
private IManagementGrain mgmtGrain;
private const string streamProviderName1 = "GeneratedStreamProvider1";
private const string streamProviderName2 = "GeneratedStreamProvider2";
public class Fixture : BaseTestClusterFixture
{
public const string StreamNamespace = GeneratedEventCollectorGrain.StreamNamespace;
public Dictionary<string, string> DefaultStreamProviderSettings = new Dictionary<string, string>();
public static readonly SimpleGeneratorConfig GeneratorConfig = new SimpleGeneratorConfig
{
StreamNamespace = StreamNamespace,
EventsInStream = 100
};
public static readonly GeneratorAdapterConfig AdapterConfig = new GeneratorAdapterConfig(GeneratedStreamTestConstants.StreamProviderName)
{
TotalQueueCount = 4,
GeneratorConfigType = GeneratorConfig.GetType()
};
protected override TestCluster CreateTestCluster()
{
var options = new TestClusterOptions(1);
// get initial settings from configs
AdapterConfig.WriteProperties(DefaultStreamProviderSettings);
GeneratorConfig.WriteProperties(DefaultStreamProviderSettings);
// add queue balancer setting
DefaultStreamProviderSettings.Add(PersistentStreamProviderConfig.QUEUE_BALANCER_TYPE, StreamQueueBalancerType.DynamicClusterConfigDeploymentBalancer.ToString());
// add pub/sub settting
DefaultStreamProviderSettings.Add(PersistentStreamProviderConfig.STREAM_PUBSUB_TYPE, StreamPubSubType.ImplicitOnly.ToString());
return new TestCluster(options);
}
}
public void Dispose()
{
RemoveAllProviders().WaitWithThrow(Timeout);
}
public DynamicStreamProviderConfigurationTests(Fixture fixture)
{
this.fixture = fixture;
RemoveAllProviders().WaitWithThrow(Timeout);
}
[Fact, TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Providers")]
public async Task DynamicStreamProviderConfigurationTests_AddAndRemoveProvidersAndCheckCounters()
{
//Making sure the initial provider list is empty.
List<string> providerNames = (await fixture.HostedCluster.Primary.TestHook.GetStreamProviderNames()).ToList();
Assert.Equal(0, providerNames.Count);
providerNames = new List<string>(new [] { GeneratedStreamTestConstants.StreamProviderName });
var reporter = GrainClient.GrainFactory.GetGrain<IGeneratedEventReporterGrain>(GeneratedStreamTestConstants.ReporterId);
try
{
await AddGeneratorStreamProviderAndVerify(providerNames);
await TestingUtils.WaitUntilAsync(CheckCounters, Timeout);
await reporter.Reset();
await RemoveProvidersAndVerify(providerNames);
await AddGeneratorStreamProviderAndVerify(providerNames);
await TestingUtils.WaitUntilAsync(CheckCounters, Timeout);
}
finally
{
await reporter.Reset();
}
}
[Fact, TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Providers")]
public async Task DynamicStreamProviderConfigurationTests_AddAndRemoveProvidersInBatch()
{
//Making sure the initial provider list is empty.
ICollection<string> providerNames = await fixture.HostedCluster.Primary.TestHook.GetStreamProviderNames();
Assert.Equal(0, providerNames.Count);
providerNames = new List<string>(new[]
{
GeneratedStreamTestConstants.StreamProviderName,
streamProviderName1,
streamProviderName2
});
await AddGeneratorStreamProviderAndVerify(providerNames);
await RemoveProvidersAndVerify(providerNames);
providerNames = new List<string>(new[]
{
streamProviderName1,
streamProviderName2
});
await AddGeneratorStreamProviderAndVerify(providerNames);
}
[Fact, TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Providers")]
public async Task DynamicStreamProviderConfigurationTests_AddAndRemoveProvidersIndividually()
{
//Making sure the initial provider list is empty.
ICollection<string> providerNames = await fixture.HostedCluster.Primary.TestHook.GetStreamProviderNames();
Assert.Equal(0, providerNames.Count);
providerNames = new List<string>(new[] { GeneratedStreamTestConstants.StreamProviderName });
await AddGeneratorStreamProviderAndVerify(providerNames);
providerNames = new List<string>(new [] { streamProviderName1 });
await AddGeneratorStreamProviderAndVerify(providerNames);
providerNames = new List<string>(new [] { streamProviderName2 });
await AddGeneratorStreamProviderAndVerify(providerNames);
providerNames = new List<string>(new[] { streamProviderName2 });
await RemoveProvidersAndVerify(providerNames);
providerNames = new List<string>(new[] { streamProviderName2 });
await AddGeneratorStreamProviderAndVerify(providerNames);
providerNames = new List<string>(new[] { streamProviderName1 });
await RemoveProvidersAndVerify(providerNames);
providerNames = new List<string>(new[] { GeneratedStreamTestConstants.StreamProviderName });
await RemoveProvidersAndVerify(providerNames);
providerNames = new List<string>(new[] { GeneratedStreamTestConstants.StreamProviderName });
await AddGeneratorStreamProviderAndVerify(providerNames);
providerNames = new List<string>(new[] { streamProviderName1 });
await AddGeneratorStreamProviderAndVerify(providerNames);
providerNames = new List<string>(new[] { streamProviderName1 });
await RemoveProvidersAndVerify(providerNames);
providerNames = new List<string>(new[] { GeneratedStreamTestConstants.StreamProviderName });
await RemoveProvidersAndVerify(providerNames);
}
[Fact, TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Providers")]
public async Task DynamicStreamProviderConfigurationTests_AddProvidersAndThrowExceptionOnInitialization()
{
//Making sure the initial provider list is empty.
ICollection<string> providerNames = await fixture.HostedCluster.Primary.TestHook.GetStreamProviderNames();
Assert.Equal(0, providerNames.Count);
Dictionary<string, string> providerSettings =
new Dictionary<string, string>(fixture.DefaultStreamProviderSettings)
{
{
FailureInjectionStreamProvider.FailureInjectionModeString,
FailureInjectionStreamProviderMode.InitializationThrowsException.ToString()
}
};
providerNames = new List<string>(new [] {"FailureInjectionStreamProvider"});
await Assert.ThrowsAsync<ProviderInitializationException>(() =>
AddFailureInjectionStreamProviderAndVerify(providerNames, providerSettings));
}
[Fact, TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Providers")]
public async Task DynamicStreamProviderConfigurationTests_AddProvidersAndThrowExceptionOnStart()
{
//Making sure the initial provider list is empty.
ICollection<string> providerNames = await fixture.HostedCluster.Primary.TestHook.GetStreamProviderNames();
Assert.Equal(0, providerNames.Count);
Dictionary<string, string> providerSettings =
new Dictionary<string, string>(fixture.DefaultStreamProviderSettings)
{
{
FailureInjectionStreamProvider.FailureInjectionModeString,
FailureInjectionStreamProviderMode.StartThrowsException.ToString()
}
};
providerNames = new List<string>(new [] { "FailureInjectionStreamProvider"});
await Assert.ThrowsAsync<ProviderStartException>(() =>
AddFailureInjectionStreamProviderAndVerify(providerNames, providerSettings));
}
private async Task RemoveAllProviders()
{
ICollection<string> providerNames = await fixture.HostedCluster.Primary.TestHook.GetStreamProviderNames();
await RemoveProvidersAndVerify(providerNames);
providerNames = await fixture.HostedCluster.Primary.TestHook.GetStreamProviderNames();
Assert.Equal(0, providerNames.Count);
}
private async Task AddFailureInjectionStreamProviderAndVerify(ICollection<string> streamProviderNames, Dictionary<string, string> ProviderSettings)
{
foreach (string providerName in streamProviderNames)
{
fixture.HostedCluster.ClusterConfiguration.Globals.RegisterStreamProvider<FailureInjectionStreamProvider>(providerName, ProviderSettings);
}
await AddProvidersAndVerify(streamProviderNames);
}
private async Task AddGeneratorStreamProviderAndVerify(ICollection<string> streamProviderNames)
{
foreach (string providerName in streamProviderNames)
{
fixture.HostedCluster.ClusterConfiguration.Globals.RegisterStreamProvider<GeneratorStreamProvider>(providerName, fixture.DefaultStreamProviderSettings);
}
await AddProvidersAndVerify(streamProviderNames);
}
private async Task AddProvidersAndVerify(ICollection<string> streamProviderNames)
{
mgmtGrain = GrainClient.GrainFactory.GetGrain<IManagementGrain>(0);
ICollection<string> names = await fixture.HostedCluster.Primary.TestHook.GetStreamProviderNames();
IDictionary<string, bool> hasNewProvider = new Dictionary<string, bool>();
int count = names.Count;
SiloAddress[] address = new SiloAddress[1];
address[0] = fixture.HostedCluster.Primary.SiloAddress;
await mgmtGrain.UpdateStreamProviders(address, fixture.HostedCluster.ClusterConfiguration.Globals.ProviderConfigurations);
names = await fixture.HostedCluster.Primary.TestHook.GetStreamProviderNames();
ICollection<string> allSiloProviderNames = await fixture.HostedCluster.Primary.TestHook.GetAllSiloProviderNames();
Assert.Equal(names.Count - count, streamProviderNames.Count);
Assert.Equal(allSiloProviderNames.Count, names.Count);
foreach (string name in names)
{
if (streamProviderNames.Contains(name))
{
Assert.DoesNotContain(name, hasNewProvider.Keys);
hasNewProvider[name] = true;
}
}
Assert.Equal(hasNewProvider.Count, streamProviderNames.Count);
hasNewProvider.Clear();
foreach (String name in allSiloProviderNames)
{
if (streamProviderNames.Contains(name))
{
Assert.DoesNotContain(name, hasNewProvider.Keys);
hasNewProvider[name] = true;
}
}
Assert.Equal(hasNewProvider.Count, streamProviderNames.Count);
}
private async Task RemoveProvidersAndVerify(ICollection<string> streamProviderNames)
{
mgmtGrain = GrainClient.GrainFactory.GetGrain<IManagementGrain>(0);
ICollection<string> names = await fixture.HostedCluster.Primary.TestHook.GetStreamProviderNames();
int Count = names.Count;
foreach (string name in streamProviderNames)
{
if(fixture.HostedCluster.ClusterConfiguration.Globals.ProviderConfigurations[ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME].Providers.ContainsKey(name))
fixture.HostedCluster.ClusterConfiguration.Globals.ProviderConfigurations[ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME].Providers.Remove(name);
}
SiloAddress[] address = new SiloAddress[1];
address[0] = fixture.HostedCluster.Primary.SiloAddress;
await mgmtGrain.UpdateStreamProviders(address, fixture.HostedCluster.ClusterConfiguration.Globals.ProviderConfigurations);
names = await fixture.HostedCluster.Primary.TestHook.GetStreamProviderNames();
ICollection<string> allSiloProviderNames = await fixture.HostedCluster.Primary.TestHook.GetAllSiloProviderNames();
Assert.Equal(Count - names.Count, streamProviderNames.Count);
Assert.Equal(allSiloProviderNames.Count, names.Count);
foreach (String name in streamProviderNames)
{
Assert.DoesNotContain(name, names);;
}
foreach (String name in streamProviderNames)
{
Assert.DoesNotContain(name, allSiloProviderNames);
}
}
private async Task<bool> CheckCounters(bool assertIsTrue)
{
var reporter = GrainClient.GrainFactory.GetGrain<IGeneratedEventReporterGrain>(GeneratedStreamTestConstants.ReporterId);
var report = await reporter.GetReport(GeneratedStreamTestConstants.StreamProviderName, Fixture.StreamNamespace);
if (assertIsTrue)
{
// one stream per queue
Assert.Equal(Fixture.AdapterConfig.TotalQueueCount, report.Count);
foreach (int eventsPerStream in report.Values)
{
Assert.Equal(Fixture.GeneratorConfig.EventsInStream, eventsPerStream);
}
}
else if (Fixture.AdapterConfig.TotalQueueCount != report.Count ||
report.Values.Any(count => count != Fixture.GeneratorConfig.EventsInStream))
{
return false;
}
return true;
}
}
}
| mit |
mafintosh/lookup-multicast-dns | index.js | 1005 | var dns = require('dns')
var mdns = require('multicast-dns')
var dnsLookup = dns.lookup.bind(dns)
module.exports = lookup
function lookup (host, type, cb) {
if (typeof type === 'function') return lookup(host, 4, type)
if (!/\.local$/.test(host)) dnsLookup(host, type, cb)
else mdnsLookup(host, type, cb)
}
function mdnsLookup (host, type, cb) {
var socket = mdns()
var recordType = type === 6 ? 'AAAA' : 'A'
var tries = 0
socket.on('response', function (response) {
for (var i = 0; i < response.answers.length; i++) {
var a = response.answers[i]
if (a.name === host && a.type === recordType) {
cleanup()
cb(null, a.data, recordType === 'A' ? 4 : 6)
}
}
})
var interval = setInterval(query, 1000)
query()
function cleanup () {
socket.destroy()
clearInterval(interval)
}
function query () {
if (++tries < 5) return socket.query([{type: recordType, name: host}])
cleanup()
cb(new Error('Query timed out'))
}
}
| mit |
shardulgo/shardulgo.github.io | site/node_modules/eslint-plugin-angular/scripts/docs.js | 7089 | 'use strict';
var fs = require('fs');
var parseComments = require('parse-comments');
var _ = require('lodash');
var eslintAngularIndex = require('../index');
var ruleCategories = require('./ruleCategories.json');
var RuleTester = require('eslint').RuleTester;
var templates = require('./templates.js');
var ruleNames = Object.keys(eslintAngularIndex.rules).filter(function(ruleName) {
// filter legacy rules
return !/^ng_/.test(ruleName);
});
// create rule documentation objects from ruleNames
var rules = ruleNames.map(_createRule);
module.exports = {
rules: rules,
createDocFiles: createDocFiles,
updateReadme: updateReadme,
testDocs: testDocs
};
/**
* Create a markdown documentation for each rule from rule comments and examples.
*
* @param cb callback
*/
function createDocFiles(cb) {
this.rules.forEach(function(rule) {
fs.writeFileSync(rule.documentationPath, _trimTrailingSpacesAndMultilineBreaks(templates.ruleDocumentationContent(rule)));
});
(cb || _.noop)();
}
/**
* Update the rules section in the readme file.
*
* @param cb callback
*/
function updateReadme(readmePath, cb) {
ruleCategories.rulesByCategory = _.groupBy(this.rules, 'category');
// filter categories without rules
ruleCategories.categoryOrder = ruleCategories.categoryOrder.filter(function(categoryName) {
var rulesForCategory = ruleCategories.rulesByCategory[categoryName];
return rulesForCategory && rulesForCategory.length > 0;
});
var readmeContent = fs.readFileSync(readmePath).toString();
var newRuleSection = templates.readmeRuleSectionContent(ruleCategories);
// use split and join to prevent the replace() and dollar sign problem (http://stackoverflow.com/questions/9423722)
readmeContent = readmeContent.split(/## Rules[\S\s]*?----\n/).join(newRuleSection);
fs.writeFileSync(readmePath, readmeContent);
(cb || _.noop)();
}
/**
* Test documentation examples.
*
* @param cb callback
*/
function testDocs(cb) {
this.rules.forEach(function(rule) {
if (rule.examples !== undefined) {
var eslintTester = new RuleTester();
eslintTester.run(rule.ruleName, rule.module, rule.examples);
}
});
(cb || _.noop)();
}
function _trimTrailingSpacesAndMultilineBreaks(content) {
return content.replace(/( )+\n/g, '\n').replace(/\n\n+\n/g, '\n\n').replace(/\n+$/g, '\n');
}
function _parseConfigLine(configLine) {
// surround config keys with quotes for json parsing
var preparedConfigLine = configLine.replace(/(\w+):/g, '"$1":').replace('\\:', ':');
var example = JSON.parse('{' + preparedConfigLine + '}');
return example;
}
function _wrapErrorMessage(errorMessage) {
return {
message: errorMessage
};
}
function _parseExample(exampleSource) {
var lines = exampleSource.split('\n');
// parse first example line as config
var example = _parseConfigLine(lines[0]);
// other lines are the example code
example.code = lines.slice(1).join('\n').trim();
// wrap the errorMessage in the format needed for the eslint rule tester.
if (example.errorMessage) {
if (_.isString(example.errorMessage)) {
example.errors = [_wrapErrorMessage(example.errorMessage)];
} else {
throw new Error('Example "errorMessage" must be a string');
}
} else if (example.errorMessages) {
if (_.isArray(example.errorMessages)) {
example.errors = example.errorMessages.map(_wrapErrorMessage);
} else {
throw new Error('Example "errorMessages" must be an array');
}
}
// invalid examples require an errorMessage
if (!example.valid && !(example.errorMessage || example.errorMessages)) {
throw new Error('Example config requires "errorMessage(s)" when valid: false');
}
// json options needed as group key
example.jsonOptions = example.options ? JSON.stringify(example.options) : '';
// use options for tests or default options of no options are configured
if (example.options) {
example.displayOptions = example.options;
}
return example;
}
function _loadExamples(rule) {
var examplesSource = fs.readFileSync(rule.examplesPath).toString();
var exampleRegex = /\s*\/\/\s*example\s*-/;
if (!exampleRegex.test(examplesSource)) {
return [];
}
return examplesSource.split(exampleRegex).slice(1).map(_parseExample.bind(rule));
}
function _filterByValidity(examples, validity) {
return _.filter(examples, {valid: validity}) || [];
}
function _appendGroupedExamplesByValidity(groupedExamples, examples, config, validity) {
var examplesByValidity = _filterByValidity(examples, validity);
if (examplesByValidity.length > 0) {
groupedExamples.push({
config: config,
valid: validity,
examples: examplesByValidity
});
}
}
function _createRule(ruleName) {
// create basic rule object
var rule = {
ruleName: ruleName
};
// add paths
rule.sourcePath = templates.ruleSourcePath(rule);
rule.documentationPath = templates.ruleDocumentationPath(rule);
rule.examplesPath = templates.ruleExamplesPath(rule);
// parse rule comments
var mainRuleComment = parseComments(fs.readFileSync(rule.sourcePath).toString())[0];
// set lead, description, linkDescription and styleguideReferences
rule.lead = mainRuleComment.lead;
rule.description = mainRuleComment.description.trim();
rule.linkDescription = mainRuleComment.linkDescription ? mainRuleComment.linkDescription : rule.lead;
rule.styleguideReferences = mainRuleComment.styleguideReferences || [];
rule.version = mainRuleComment.version;
rule.category = mainRuleComment.category || 'uncategorizedRule';
rule.deprecated = !!mainRuleComment.deprecated;
if (rule.deprecated) {
rule.deprecationReason = mainRuleComment.deprecated;
rule.category = 'deprecatedRule';
}
if (!rule.version) {
throw new Error('No @version found for ' + ruleName);
}
// load rule module for tests
rule.module = require('../rules/' + rule.ruleName); // eslint-disable-line global-require
// load examples, prepare them for the tests and group the for the template
rule.allExamples = _loadExamples(rule);
rule.examples = {
valid: _filterByValidity(rule.allExamples, true),
invalid: _filterByValidity(rule.allExamples, false)
};
rule.groupedExamples = [];
var examplesGroupedByConfig = _.groupBy(rule.allExamples, 'jsonOptions');
_.each(examplesGroupedByConfig, function(examples, config) {
// append invalid examples if existing
_appendGroupedExamplesByValidity(rule.groupedExamples, examples, config, false);
// append valid examples if existing
_appendGroupedExamplesByValidity(rule.groupedExamples, examples, config, true);
});
rule.hasOnlyOneConfig = Object.keys(examplesGroupedByConfig).length === 1;
return rule;
}
| mit |
ACOKing/ArcherSys | owncloud-serv/apps/files_sharing/l10n/de_DE.php | 2340 | <?php
$TRANSLATIONS = array(
"Server to server sharing is not enabled on this server" => "Der Server für die Serverfreigabe ist auf diesem Server nicht aktiviert",
"Couldn't add remote share" => "Entfernte Freigabe kann nicht hinzu gefügt werden",
"Shared with you" => "Mit Ihnen geteilt",
"Shared with others" => "Von Ihnen geteilt",
"Shared by link" => "Geteilt über einen Link",
"No files have been shared with you yet." => "Es wurden bis jetzt keine Dateien mit Ihnen geteilt.",
"You haven't shared any files yet." => "Sie haben bis jetzt keine Dateien mit anderen geteilt.",
"You haven't shared any files by link yet." => "Sie haben bis jetzt keine Dateien über einen Link mit anderen geteilt.",
"Add {name} from {owner}@{remote}" => "{name} wird von {owner}@{remote} hinzugefügt",
"Add Share" => "Freigabe hinzufügen",
"Password" => "Passwort",
"No ownCloud installation found at {remote}" => "Keine OwnCloud-Installation auf {remote} gefunden",
"Invalid ownCloud url" => "Ungültige OwnCloud-URL",
"Shared by {owner}" => "Geteilt von {owner}",
"Shared by" => "Geteilt von",
"This share is password-protected" => "Diese Freigabe ist durch ein Passwort geschützt",
"The password is wrong. Try again." => "Das Passwort ist falsch. Bitte versuchen Sie es erneut.",
"Name" => "Name",
"Share time" => "Zeitpunkt der Freigabe",
"Sorry, this link doesn’t seem to work anymore." => "Entschuldigung, dieser Link scheint nicht mehr zu funktionieren.",
"Reasons might be:" => "Gründe könnten sein:",
"the item was removed" => "Das Element wurde entfernt",
"the link expired" => "Der Link ist abgelaufen",
"sharing is disabled" => "Teilen ist deaktiviert",
"For more info, please ask the person who sent this link." => "Für mehr Informationen, fragen Sie bitte die Person, die Ihnen diesen Link geschickt hat.",
"Save" => "Speichern",
"Download" => "Herunterladen",
"Download %s" => "Download %s",
"Direct link" => "Direkte Verlinkung",
"Remote Shares" => "Entfernte Freigaben",
"Allow other instances to mount public links shared from this server" => "Andere Instanzen zum Hinzufügen von öffentlichen Links, die über diesen Server Freigegeben werden, erlauben",
"Allow users to mount public link shares" => "Erlaube Nutzern das Hinzufügen von freigegebenen öffentlichen Links"
);
$PLURAL_FORMS = "nplurals=2; plural=(n != 1);";
| mit |
manchester-tech-events/techevents-nw | gems/ruby/2.4.0/gems/httparty-0.15.6/examples/stream_download.rb | 535 | dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
# download file linux-4.6.4.tar.xz without using the memory
response = nil
filename = "linux-4.6.4.tar.xz"
url = "https://cdn.kernel.org/pub/linux/kernel/v4.x/#{filename}"
File.open(filename, "w") do |file|
response = HTTParty.get(url, stream_body: true) do |fragment|
print "."
file.write(fragment)
end
end
puts
pp "Success: #{response.success?}"
pp File.stat(filename).inspect
File.unlink(filename)
| mit |
andreoav/inscricoes-natura | fuel/core/classes/crypt.php | 4786 | <?php
/**
* Part of the Fuel framework.
*
* @package Fuel
* @version 1.0
* @author Fuel Development Team
* @license MIT License
* @copyright 2010 - 2012 Fuel Development Team
* @link http://fuelphp.com
*/
namespace Fuel\Core;
import('phpseclib/Crypt/AES', 'vendor');
import('phpseclib/Crypt/Hash', 'vendor');
use \PHPSecLib\Crypt_AES;
use \PHPSecLib\Crypt_Hash;
class Crypt
{
/*
* Crypto object used to encrypt/decrypt
*
* @var object
*/
private static $crypter = null;
/*
* Hash object used to generate hashes
*
* @var object
*/
private static $hasher = null;
/*
* Crypto configuration
*
* @var array
*/
private static $config = array();
/*
* initialisation and auto configuration
*/
public static function _init()
{
static::$crypter = new Crypt_AES();
static::$hasher = new Crypt_Hash('sha256');
// load the config
\Config::load('crypt', true);
static::$config = \Config::get('crypt', array ());
// generate random crypto keys if we don't have them or they are incorrect length
$update = false;
foreach(array('crypto_key', 'crypto_iv', 'crypto_hmac') as $key)
{
if ( empty(static::$config[$key]) or (strlen(static::$config[$key]) % 4) != 0)
{
$crypto = '';
for ($i = 0; $i < 8; $i++)
{
$crypto .= static::safe_b64encode(pack('n', mt_rand(0, 0xFFFF)));
}
static::$config[$key] = $crypto;
$update = true;
}
}
// update the config if needed
if ($update === true)
{
try
{
\Config::save('crypt', static::$config);
}
catch (\FileAccessException $e)
{
// failed to write the config file, inform the user
echo \View::forge('errors/crypt_keys', array(
'keys' => static::$config
));
die();
}
}
static::$crypter->enableContinuousBuffer();
static::$hasher->setKey(static::safe_b64decode(static::$config['crypto_hmac']));
}
// --------------------------------------------------------------------
/*
* encrypt a string value, optionally with a custom key
*
* @param string value to encrypt
* @param string optional custom key to be used for this encryption
* @access public
* @return string encrypted value
*/
public static function encode($value, $key = false)
{
$key ? static::$crypter->setKey($key) : static::$crypter->setKey(static::safe_b64decode(static::$config['crypto_key']));
static::$crypter->setIV(static::safe_b64decode(static::$config['crypto_iv']));
$value = static::$crypter->encrypt($value);
return static::safe_b64encode(static::add_hmac($value));
}
// --------------------------------------------------------------------
/*
* decrypt a string value, optionally with a custom key
*
* @param string value to decrypt
* @param string optional custom key to be used for this encryption
* @access public
* @return string encrypted value
*/
public static function decode($value, $key = false)
{
$key ? static::$crypter->setKey($key) : static::$crypter->setKey(static::safe_b64decode(static::$config['crypto_key']));
static::$crypter->setIV(static::safe_b64decode(static::$config['crypto_iv']));
$value = static::safe_b64decode($value);
if ($value = static::validate_hmac($value))
{
return static::$crypter->decrypt($value);
}
else
{
return false;
}
}
// --------------------------------------------------------------------
private static function safe_b64encode($value)
{
$data = base64_encode($value);
$data = str_replace(array('+','/','='), array('-','_',''), $data);
return $data;
}
private static function safe_b64decode($value)
{
$data = str_replace(array('-','_'), array('+','/'), $value);
$mod4 = strlen($data) % 4;
if ($mod4)
{
$data .= substr('====', $mod4);
}
return base64_decode($data);
}
private static function add_hmac($value)
{
// calculate the hmac-sha256 hash of this value
$hmac = static::safe_b64encode(static::$hasher->hash($value));
// append it and return the hmac protected string
return $value.$hmac;
}
private static function validate_hmac($value)
{
// strip the hmac-sha256 hash from the value
$hmac = substr($value, strlen($value)-43);
// and remove it from the value
$value = substr($value, 0, strlen($value)-43);
// only return the value if it wasn't tampered with
return (static::secure_compare(static::safe_b64encode(static::$hasher->hash($value)), $hmac)) ? $value : false;
}
private static function secure_compare($a, $b)
{
// make sure we're only comparing equal length strings
if (strlen($a) !== strlen($b))
{
return false;
}
// and that all comparisons take equal time
$result = 0;
for ($i = 0; $i < strlen($a); $i++)
{
$result |= ord($a[$i]) ^ ord($b[$i]);
}
return $result == 0;
}
}
| mit |
familiar-earth/familiar-earth.github.io | Cesium-1.8/Specs/Scene/DebugModelMatrixPrimitiveSpec.js | 2805 | /*global defineSuite*/
defineSuite([
'Scene/DebugModelMatrixPrimitive',
'Core/Cartesian2',
'Core/Cartesian3',
'Core/Matrix4',
'Specs/createScene'
], function(
DebugModelMatrixPrimitive,
Cartesian2,
Cartesian3,
Matrix4,
createScene) {
"use strict";
/*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn*/
var scene;
beforeAll(function() {
scene = createScene();
var camera = scene.camera;
camera.position = new Cartesian3(1.02, 0.0, 0.0);
camera.direction = Cartesian3.negate(Cartesian3.UNIT_X, new Cartesian3());
camera.up = Cartesian3.clone(Cartesian3.UNIT_Z);
});
afterAll(function() {
scene.destroyForSpecs();
});
afterEach(function() {
scene.primitives.removeAll();
});
it('gets the default properties', function() {
var p = new DebugModelMatrixPrimitive();
expect(p.length).toEqual(10000000.0);
expect(p.width).toEqual(2.0);
expect(p.modelMatrix).toEqual(Matrix4.IDENTITY);
expect(p.show).toEqual(true);
expect(p.id).not.toBeDefined();
p.destroy();
});
it('Constructs with options', function() {
var p = new DebugModelMatrixPrimitive({
length : 10.0,
width : 1.0,
modelMatrix : Matrix4.fromUniformScale(2.0),
show : false,
id : 'id'
});
expect(p.length).toEqual(10.0);
expect(p.width).toEqual(1.0);
expect(p.modelMatrix).toEqual(Matrix4.fromUniformScale(2.0));
expect(p.show).toEqual(false);
expect(p.id).toEqual('id');
p.destroy();
});
it('renders', function() {
var p = scene.primitives.add(new DebugModelMatrixPrimitive());
expect(scene.renderForSpecs()).not.toEqual([0, 0, 0, 255]);
// Update and render again
p.length = 100.0;
expect(scene.renderForSpecs()).not.toEqual([0, 0, 0, 255]);
});
it('does not render when show is false', function() {
scene.primitives.add(new DebugModelMatrixPrimitive({
show : false
}));
expect(scene.renderForSpecs()).toEqual([0, 0, 0, 255]);
});
it('is picked', function() {
var p = scene.primitives.add(new DebugModelMatrixPrimitive({
id : 'id'
}));
var pick = scene.pick(new Cartesian2(0, 0));
expect(pick.primitive).toEqual(p);
expect(pick.id).toEqual('id');
});
it('isDestroyed', function() {
var p = new DebugModelMatrixPrimitive();
expect(p.isDestroyed()).toEqual(false);
p.destroy();
expect(p.isDestroyed()).toEqual(true);
});
}, 'WebGL');
| mit |
spadin/coverphoto | node_modules/grunt-contrib/node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/dump/dump.js | 3240 | /*
YUI 3.7.2 (build 5639)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('dump', function (Y, NAME) {
/**
* Returns a simple string representation of the object or array.
* Other types of objects will be returned unprocessed. Arrays
* are expected to be indexed. Use object notation for
* associative arrays.
*
* If included, the dump method is added to the YUI instance.
*
* @module dump
*/
var L = Y.Lang,
OBJ = '{...}',
FUN = 'f(){...}',
COMMA = ', ',
ARROW = ' => ',
/**
* Returns a simple string representation of the object or array.
* Other types of objects will be returned unprocessed. Arrays
* are expected to be indexed.
*
* @method dump
* @param {Object} o The object to dump.
* @param {Number} d How deep to recurse child objects, default 3.
* @return {String} the dump result.
* @for YUI
*/
dump = function(o, d) {
var i, len, s = [], type = L.type(o);
// Cast non-objects to string
// Skip dates because the std toString is what we want
// Skip HTMLElement-like objects because trying to dump
// an element will cause an unhandled exception in FF 2.x
if (!L.isObject(o)) {
return o + '';
} else if (type == 'date') {
return o;
} else if (o.nodeType && o.tagName) {
return o.tagName + '#' + o.id;
} else if (o.document && o.navigator) {
return 'window';
} else if (o.location && o.body) {
return 'document';
} else if (type == 'function') {
return FUN;
}
// dig into child objects the depth specifed. Default 3
d = (L.isNumber(d)) ? d : 3;
// arrays [1, 2, 3]
if (type == 'array') {
s.push('[');
for (i = 0, len = o.length; i < len; i = i + 1) {
if (L.isObject(o[i])) {
s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ);
} else {
s.push(o[i]);
}
s.push(COMMA);
}
if (s.length > 1) {
s.pop();
}
s.push(']');
// regexp /foo/
} else if (type == 'regexp') {
s.push(o.toString());
// objects {k1 => v1, k2 => v2}
} else {
s.push('{');
for (i in o) {
if (o.hasOwnProperty(i)) {
try {
s.push(i + ARROW);
if (L.isObject(o[i])) {
s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ);
} else {
s.push(o[i]);
}
s.push(COMMA);
} catch (e) {
s.push('Error: ' + e.message);
}
}
}
if (s.length > 1) {
s.pop();
}
s.push('}');
}
return s.join('');
};
Y.dump = dump;
L.dump = dump;
}, '3.7.2', {"requires": ["yui-base"]});
| mit |
jakuza/bookmentor | vendor/symfony/src/Symfony/Bundle/DoctrineBundle/Mapping/MetadataFactory.php | 5661 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\DoctrineBundle\Mapping;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Doctrine\ORM\Tools\EntityRepositoryGenerator;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\ORMException;
/**
* This class provides methods to access Doctrine entity class metadata for a
* given bundle, namespace or entity class.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class MetadataFactory
{
private $registry;
/**
* Constructor.
*
* @param RegistryInterface $registry A RegistryInterface instance
*/
public function __construct(RegistryInterface $registry)
{
$this->registry = $registry;
}
/**
* Gets the metadata of all classes of a bundle.
*
* @param BundleInterface $bundle A BundleInterface instance
*
* @return ClassMetadataCollection A ClassMetadataCollection instance
*/
public function getBundleMetadata(BundleInterface $bundle)
{
$namespace = $bundle->getNamespace();
$metadata = $this->getMetadataForNamespace($namespace);
if (!$metadata->getMetadata()) {
throw new \RuntimeException(sprintf('Bundle "%s" does not contain any mapped entities.', $bundle->getName()));
}
$path = $this->getBasePathForClass($bundle->getName(), $bundle->getNamespace(), $bundle->getPath());
$metadata->setPath($path);
$metadata->setNamespace($bundle->getNamespace());
return $metadata;
}
/**
* Gets the metadata of a class.
*
* @param string $class A class name
* @param string $path The path where the class is stored (if known)
*
* @return ClassMetadataCollection A ClassMetadataCollection instance
*/
public function getClassMetadata($class, $path = null)
{
$metadata = $this->getMetadataForClass($class);
if (!$metadata->getMetadata()) {
throw new \RuntimeException(sprintf('Entity "%s" is not a mapped entity.', $class));
}
$all = $metadata->getMetadata();
if (class_exists($class)) {
$r = $all[0]->getReflectionClass();
$path = $this->getBasePathForClass($class, $r->getNamespacename(), dirname($r->getFilename()));
} elseif (!$path) {
throw new \RuntimeException(sprintf('Unable to determine where to save the "%s" class (use the --path option).', $class));
}
$metadata->setPath($path);
$metadata->setNamespace($r->getNamespacename());
return $metadata;
}
/**
* Gets the metadata of all classes of a namespace.
*
* @param string $namespace A namespace name
* @param string $path The path where the class is stored (if known)
*
* @return ClassMetadataCollection A ClassMetadataCollection instance
*/
public function getNamespaceMetadata($namespace, $path = null)
{
$metadata = $this->getMetadataForNamespace($namespace);
if (!$metadata->getMetadata()) {
throw new \RuntimeException(sprintf('Namespace "%s" does not contain any mapped entities.', $namespace));
}
$all = $metadata->getMetadata();
if (class_exists($all[0]->name)) {
$r = $all[0]->getReflectionClass();
$path = $this->getBasePathForClass($namespace, $r->getNamespacename(), dirname($r->getFilename()));
} elseif (!$path) {
throw new \RuntimeException(sprintf('Unable to determine where to save the "%s" class (use the --path option).', $all[0]->name));
}
$metadata->setPath($path);
$metadata->setNamespace($namespace);
return $metadata;
}
private function getBasePathForClass($name, $namespace, $path)
{
$namespace = str_replace('\\', '/', $namespace);
$search = str_replace('\\', '/', $path);
$destination = str_replace('/'.$namespace, '', $search, $c);
if ($c != 1) {
throw new \RuntimeException(sprintf('Can\'t find base path for "%s" (path: "%s", destination: "%s").', $name, $path, $destination));
}
return $destination;
}
private function getMetadataForNamespace($namespace)
{
$metadata = array();
foreach ($this->getAllMetadata() as $m) {
if (strpos($m->name, $namespace) === 0) {
$metadata[] = $m;
}
}
return new ClassMetadataCollection($metadata);
}
private function getMetadataForClass($entity)
{
foreach ($this->getAllMetadata() as $metadata) {
if ($metadata->name === $entity) {
return new ClassMetadataCollection(array($metadata));
}
}
return new ClassMetadataCollection(array());
}
private function getAllMetadata()
{
$metadata = array();
foreach ($this->registry->getEntityManagers() as $em) {
$class = $this->getClassMetadataFactoryClass();
$cmf = new $class();
$cmf->setEntityManager($em);
foreach ($cmf->getAllMetadata() as $m) {
$metadata[] = $m;
}
}
return $metadata;
}
protected function getClassMetadataFactoryClass()
{
return 'Doctrine\\ORM\\Mapping\\ClassMetadataFactory';
}
}
| mit |
gthulei/java-ssm | taotao-dubbo/taotao-dubbo-pojo/src/main/java/com/taotao/po/TbItemParamItemExample.java | 13351 | package com.taotao.po;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TbItemParamItemExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public TbItemParamItemExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Long value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Long value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Long value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Long value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Long value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Long value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Long> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Long> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Long value1, Long value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Long value1, Long value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andItemIdIsNull() {
addCriterion("item_id is null");
return (Criteria) this;
}
public Criteria andItemIdIsNotNull() {
addCriterion("item_id is not null");
return (Criteria) this;
}
public Criteria andItemIdEqualTo(Long value) {
addCriterion("item_id =", value, "itemId");
return (Criteria) this;
}
public Criteria andItemIdNotEqualTo(Long value) {
addCriterion("item_id <>", value, "itemId");
return (Criteria) this;
}
public Criteria andItemIdGreaterThan(Long value) {
addCriterion("item_id >", value, "itemId");
return (Criteria) this;
}
public Criteria andItemIdGreaterThanOrEqualTo(Long value) {
addCriterion("item_id >=", value, "itemId");
return (Criteria) this;
}
public Criteria andItemIdLessThan(Long value) {
addCriterion("item_id <", value, "itemId");
return (Criteria) this;
}
public Criteria andItemIdLessThanOrEqualTo(Long value) {
addCriterion("item_id <=", value, "itemId");
return (Criteria) this;
}
public Criteria andItemIdIn(List<Long> values) {
addCriterion("item_id in", values, "itemId");
return (Criteria) this;
}
public Criteria andItemIdNotIn(List<Long> values) {
addCriterion("item_id not in", values, "itemId");
return (Criteria) this;
}
public Criteria andItemIdBetween(Long value1, Long value2) {
addCriterion("item_id between", value1, value2, "itemId");
return (Criteria) this;
}
public Criteria andItemIdNotBetween(Long value1, Long value2) {
addCriterion("item_id not between", value1, value2, "itemId");
return (Criteria) this;
}
public Criteria andCreatedIsNull() {
addCriterion("created is null");
return (Criteria) this;
}
public Criteria andCreatedIsNotNull() {
addCriterion("created is not null");
return (Criteria) this;
}
public Criteria andCreatedEqualTo(Date value) {
addCriterion("created =", value, "created");
return (Criteria) this;
}
public Criteria andCreatedNotEqualTo(Date value) {
addCriterion("created <>", value, "created");
return (Criteria) this;
}
public Criteria andCreatedGreaterThan(Date value) {
addCriterion("created >", value, "created");
return (Criteria) this;
}
public Criteria andCreatedGreaterThanOrEqualTo(Date value) {
addCriterion("created >=", value, "created");
return (Criteria) this;
}
public Criteria andCreatedLessThan(Date value) {
addCriterion("created <", value, "created");
return (Criteria) this;
}
public Criteria andCreatedLessThanOrEqualTo(Date value) {
addCriterion("created <=", value, "created");
return (Criteria) this;
}
public Criteria andCreatedIn(List<Date> values) {
addCriterion("created in", values, "created");
return (Criteria) this;
}
public Criteria andCreatedNotIn(List<Date> values) {
addCriterion("created not in", values, "created");
return (Criteria) this;
}
public Criteria andCreatedBetween(Date value1, Date value2) {
addCriterion("created between", value1, value2, "created");
return (Criteria) this;
}
public Criteria andCreatedNotBetween(Date value1, Date value2) {
addCriterion("created not between", value1, value2, "created");
return (Criteria) this;
}
public Criteria andUpdatedIsNull() {
addCriterion("updated is null");
return (Criteria) this;
}
public Criteria andUpdatedIsNotNull() {
addCriterion("updated is not null");
return (Criteria) this;
}
public Criteria andUpdatedEqualTo(Date value) {
addCriterion("updated =", value, "updated");
return (Criteria) this;
}
public Criteria andUpdatedNotEqualTo(Date value) {
addCriterion("updated <>", value, "updated");
return (Criteria) this;
}
public Criteria andUpdatedGreaterThan(Date value) {
addCriterion("updated >", value, "updated");
return (Criteria) this;
}
public Criteria andUpdatedGreaterThanOrEqualTo(Date value) {
addCriterion("updated >=", value, "updated");
return (Criteria) this;
}
public Criteria andUpdatedLessThan(Date value) {
addCriterion("updated <", value, "updated");
return (Criteria) this;
}
public Criteria andUpdatedLessThanOrEqualTo(Date value) {
addCriterion("updated <=", value, "updated");
return (Criteria) this;
}
public Criteria andUpdatedIn(List<Date> values) {
addCriterion("updated in", values, "updated");
return (Criteria) this;
}
public Criteria andUpdatedNotIn(List<Date> values) {
addCriterion("updated not in", values, "updated");
return (Criteria) this;
}
public Criteria andUpdatedBetween(Date value1, Date value2) {
addCriterion("updated between", value1, value2, "updated");
return (Criteria) this;
}
public Criteria andUpdatedNotBetween(Date value1, Date value2) {
addCriterion("updated not between", value1, value2, "updated");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | mit |
kachick/rubyspec | core/time/localtime_spec.rb | 3702 | require File.expand_path('../../../spec_helper', __FILE__)
describe "Time#localtime" do
it "converts self to local time, modifying the receiver" do
# Testing with America/Regina here because it doesn't have DST.
with_timezone("CST", -6) do
t = Time.gm(2007, 1, 9, 12, 0, 0)
t.localtime
t.should == Time.local(2007, 1, 9, 6, 0, 0)
end
end
it "returns self" do
t = Time.gm(2007, 1, 9, 12, 0, 0)
t.localtime.should equal(t)
end
it "converts time to the UTC offset specified as an Integer number of seconds" do
t = Time.gm(2007, 1, 9, 12, 0, 0)
t.localtime(3630)
t.should == Time.new(2007, 1, 9, 13, 0, 30, 3630)
t.utc_offset.should == 3630
end
describe "with an argument that responds to #to_int" do
it "coerces using #to_int" do
o = mock('integer')
o.should_receive(:to_int).and_return(3630)
t = Time.gm(2007, 1, 9, 12, 0, 0)
t.localtime(o)
t.should == Time.new(2007, 1, 9, 13, 0, 30, 3630)
t.utc_offset.should == 3630
end
end
it "returns a Time with a UTC offset of the specified number of Rational seconds" do
t = Time.gm(2007, 1, 9, 12, 0, 0)
t.localtime(Rational(7201, 2))
t.should == Time.new(2007, 1, 9, 13, 0, Rational(1, 2), Rational(7201, 2))
t.utc_offset.should eql(Rational(7201, 2))
end
describe "with an argument that responds to #to_r" do
it "coerces using #to_r" do
o = mock_numeric('rational')
o.should_receive(:to_r).and_return(Rational(7201, 2))
t = Time.gm(2007, 1, 9, 12, 0, 0)
t.localtime(o)
t.should == Time.new(2007, 1, 9, 13, 0, Rational(1, 2), Rational(7201, 2))
t.utc_offset.should eql(Rational(7201, 2))
end
end
it "returns a Time with a UTC offset specified as +HH:MM" do
t = Time.gm(2007, 1, 9, 12, 0, 0)
t.localtime("+01:00")
t.should == Time.new(2007, 1, 9, 13, 0, 0, 3600)
t.utc_offset.should == 3600
end
it "returns a Time with a UTC offset specified as -HH:MM" do
t = Time.gm(2007, 1, 9, 12, 0, 0)
t.localtime("-01:00")
t.should == Time.new(2007, 1, 9, 11, 0, 0, -3600)
t.utc_offset.should == -3600
end
platform_is_not :windows do
it "changes the timezone according to the set one" do
t = Time.new(2005, 2, 27, 22, 50, 0, -3600)
t.utc_offset.should == -3600
with_timezone("America/New_York") do
t.localtime
end
t.utc_offset.should == -18000
end
end
describe "with an argument that responds to #to_str" do
it "coerces using #to_str" do
o = mock('string')
o.should_receive(:to_str).and_return("+01:00")
t = Time.gm(2007, 1, 9, 12, 0, 0)
t.localtime(o)
t.should == Time.new(2007, 1, 9, 13, 0, 0, 3600)
t.utc_offset.should == 3600
end
end
it "raises ArgumentError if the String argument is not of the form (+|-)HH:MM" do
t = Time.now
lambda { t.localtime("3600") }.should raise_error(ArgumentError)
end
it "raises ArgumentError if the String argument is not in an ASCII-compatible encoding" do
t = Time.now
lambda { t.localtime("-01:00".encode("UTF-16LE")) }.should raise_error(ArgumentError)
end
it "raises ArgumentError if the argument represents a value less than or equal to -86400 seconds" do
t = Time.new
t.localtime(-86400 + 1).utc_offset.should == (-86400 + 1)
lambda { t.localtime(-86400) }.should raise_error(ArgumentError)
end
it "raises ArgumentError if the argument represents a value greater than or equal to 86400 seconds" do
t = Time.new
t.localtime(86400 - 1).utc_offset.should == (86400 - 1)
lambda { t.localtime(86400) }.should raise_error(ArgumentError)
end
end
| mit |
Roustalski/router | dist/index.d.ts | 46 | export * from 'aurelia-router/aurelia-router'; | mit |
sidshetye/BouncyBench | BouncyCastle/crypto/src/asn1/ess/SigningCertificateV2.cs | 2416 | using System;
using Org.BouncyCastle.Asn1.X509;
namespace Org.BouncyCastle.Asn1.Ess
{
public class SigningCertificateV2
: Asn1Encodable
{
private readonly Asn1Sequence certs;
private readonly Asn1Sequence policies;
public static SigningCertificateV2 GetInstance(
object o)
{
if (o == null || o is SigningCertificateV2)
return (SigningCertificateV2) o;
if (o is Asn1Sequence)
return new SigningCertificateV2((Asn1Sequence) o);
throw new ArgumentException(
"unknown object in 'SigningCertificateV2' factory : "
+ o.GetType().Name + ".");
}
private SigningCertificateV2(
Asn1Sequence seq)
{
if (seq.Count < 1 || seq.Count > 2)
throw new ArgumentException("Bad sequence size: " + seq.Count, "seq");
this.certs = Asn1Sequence.GetInstance(seq[0].ToAsn1Object());
if (seq.Count > 1)
{
this.policies = Asn1Sequence.GetInstance(seq[1].ToAsn1Object());
}
}
public SigningCertificateV2(
EssCertIDv2[] certs)
{
this.certs = new DerSequence(certs);
}
public SigningCertificateV2(
EssCertIDv2[] certs,
PolicyInformation[] policies)
{
this.certs = new DerSequence(certs);
if (policies != null)
{
this.policies = new DerSequence(policies);
}
}
public EssCertIDv2[] GetCerts()
{
EssCertIDv2[] certIds = new EssCertIDv2[certs.Count];
for (int i = 0; i != certs.Count; i++)
{
certIds[i] = EssCertIDv2.GetInstance(certs[i]);
}
return certIds;
}
public PolicyInformation[] GetPolicies()
{
if (policies == null)
return null;
PolicyInformation[] policyInformations = new PolicyInformation[policies.Count];
for (int i = 0; i != policies.Count; i++)
{
policyInformations[i] = PolicyInformation.GetInstance(policies[i]);
}
return policyInformations;
}
/**
* The definition of SigningCertificateV2 is
* <pre>
* SigningCertificateV2 ::= SEQUENCE {
* certs SEQUENCE OF EssCertIDv2,
* policies SEQUENCE OF PolicyInformation OPTIONAL
* }
* </pre>
* id-aa-signingCertificateV2 OBJECT IDENTIFIER ::= { iso(1)
* member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
* smime(16) id-aa(2) 47 }
*/
public override Asn1Object ToAsn1Object()
{
Asn1EncodableVector v = new Asn1EncodableVector(certs);
if (policies != null)
{
v.Add(policies);
}
return new DerSequence(v);
}
}
}
| mit |