code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <af/features.h>
#include <af/array.h>
#include "error.hpp"
namespace af
{
features::features()
{
AF_THROW(af_create_features(&feat, 0));
}
features::features(const size_t n)
{
AF_THROW(af_create_features(&feat, (int)n));
}
features::features(af_features f) : feat(f)
{
}
features& features::operator= (const features& other)
{
if (this != &other) {
AF_THROW(af_release_features(feat));
AF_THROW(af_retain_features(&feat, other.get()));
}
return *this;
}
features::~features()
{
// THOU SHALL NOT THROW IN DESTRUCTORS
if (feat) {
af_release_features(feat);
}
}
size_t features::getNumFeatures() const
{
dim_t n = 0;
AF_THROW(af_get_features_num(&n, feat));
return n;
}
array features::getX() const
{
af_array x = 0;
AF_THROW(af_get_features_xpos(&x, feat));
af_array tmp = 0;
AF_THROW(af_retain_array(&tmp, x));
return array(tmp);
}
array features::getY() const
{
af_array y = 0;
AF_THROW(af_get_features_ypos(&y, feat));
af_array tmp = 0;
AF_THROW(af_retain_array(&tmp, y));
return array(tmp);
}
array features::getScore() const
{
af_array s = 0;
AF_THROW(af_get_features_score(&s, feat));
af_array tmp = 0;
AF_THROW(af_retain_array(&tmp, s));
return array(tmp);
}
array features::getOrientation() const
{
af_array ori = 0;
AF_THROW(af_get_features_orientation(&ori, feat));
af_array tmp = 0;
AF_THROW(af_retain_array(&tmp, ori));
return array(tmp);
}
array features::getSize() const
{
af_array s = 0;
AF_THROW(af_get_features_size(&s, feat));
af_array tmp = 0;
AF_THROW(af_retain_array(&tmp, s));
return array(tmp);
}
af_features features::get() const
{
return feat;
}
};
| ghisvail/arrayfire | src/api/cpp/features.cpp | C++ | bsd-3-clause | 2,405 |
package org.javasimon.jdbcx4;
import java.sql.SQLException;
import javax.sql.StatementEventListener;
import javax.sql.XAConnection;
import javax.transaction.xa.XAResource;
/**
* Simon implementation of <code>XAConnection</code>, needed for
* Simon XADataSource implementation.
* <p/>
* All method invokes its real implementation.
* <p/>
* See the {@link org.javasimon.jdbcx4 package description} for more
* information.
*
* @author Radovan Sninsky
* @author <a href="mailto:virgo47@gmail.com">Richard "Virgo" Richter</a>
* @since 2.4
*/
public final class SimonXAConnection extends SimonPooledConnection implements XAConnection {
private final XAConnection realConn;
/**
* Class constructor.
*
* @param connection real xa connection
* @param prefix Simon prefix
*/
public SimonXAConnection(XAConnection connection, String prefix) {
super(connection, prefix);
this.realConn = connection;
}
@Override
public XAResource getXAResource() throws SQLException {
return realConn.getXAResource();
}
@Override
public void addStatementEventListener(StatementEventListener listener) {
realConn.addStatementEventListener(listener);
}
@Override
public void removeStatementEventListener(StatementEventListener listener) {
realConn.removeStatementEventListener(listener);
}
}
| karouani/javasimon | jdbc41/src/main/java/org/javasimon/jdbcx4/SimonXAConnection.java | Java | bsd-3-clause | 1,312 |
// Copyright 2014 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 "tools/gn/parse_tree.h"
#include <stdint.h>
#include <utility>
#include "testing/gtest/include/gtest/gtest.h"
#include "tools/gn/input_file.h"
#include "tools/gn/scope.h"
#include "tools/gn/test_with_scope.h"
TEST(ParseTree, Accessor) {
TestWithScope setup;
// Make a pretend parse node with proper tracking that we can blame for the
// given value.
InputFile input_file(SourceFile("//foo"));
Token base_token(Location(&input_file, 1, 1, 1), Token::IDENTIFIER, "a");
Token member_token(Location(&input_file, 1, 1, 1), Token::IDENTIFIER, "b");
AccessorNode accessor;
accessor.set_base(base_token);
scoped_ptr<IdentifierNode> member_identifier(
new IdentifierNode(member_token));
accessor.set_member(std::move(member_identifier));
// The access should fail because a is not defined.
Err err;
Value result = accessor.Execute(setup.scope(), &err);
EXPECT_TRUE(err.has_error());
EXPECT_EQ(Value::NONE, result.type());
// Define a as a Scope. It should still fail because b isn't defined.
err = Err();
setup.scope()->SetValue(
"a", Value(nullptr, scoped_ptr<Scope>(new Scope(setup.scope()))),
nullptr);
result = accessor.Execute(setup.scope(), &err);
EXPECT_TRUE(err.has_error());
EXPECT_EQ(Value::NONE, result.type());
// Define b, accessor should succeed now.
const int64_t kBValue = 42;
err = Err();
setup.scope()
->GetMutableValue("a", false)
->scope_value()
->SetValue("b", Value(nullptr, kBValue), nullptr);
result = accessor.Execute(setup.scope(), &err);
EXPECT_FALSE(err.has_error());
ASSERT_EQ(Value::INTEGER, result.type());
EXPECT_EQ(kBValue, result.int_value());
}
TEST(ParseTree, BlockUnusedVars) {
TestWithScope setup;
// Printing both values should be OK.
//
// The crazy template definition here is a way to execute a block without
// defining a target. Templates require that both the target_name and the
// invoker be used, which is what the assertion statement inside the template
// does.
TestParseInput input_all_used(
"template(\"foo\") { assert(target_name != 0 && invoker != 0) }\n"
"foo(\"a\") {\n"
" a = 12\n"
" b = 13\n"
" print(\"$a $b\")\n"
"}");
EXPECT_FALSE(input_all_used.has_error());
Err err;
input_all_used.parsed()->Execute(setup.scope(), &err);
EXPECT_FALSE(err.has_error());
// Skipping one should throw an unused var error.
TestParseInput input_unused(
"foo(\"a\") {\n"
" a = 12\n"
" b = 13\n"
" print(\"$a\")\n"
"}");
EXPECT_FALSE(input_unused.has_error());
input_unused.parsed()->Execute(setup.scope(), &err);
EXPECT_TRUE(err.has_error());
// Also verify that the unused variable has the correct origin set. The
// origin will point to the value assigned to the variable (in this case, the
// "13" assigned to "b".
EXPECT_EQ(3, err.location().line_number());
EXPECT_EQ(7, err.location().column_number());
}
TEST(ParseTree, OriginForDereference) {
TestWithScope setup;
TestParseInput input(
"a = 6\n"
"get_target_outputs(a)");
EXPECT_FALSE(input.has_error());
Err err;
input.parsed()->Execute(setup.scope(), &err);
EXPECT_TRUE(err.has_error());
// The origin for the "not a string" error message should be where the value
// was dereferenced (the "a" on the second line).
EXPECT_EQ(2, err.location().line_number());
EXPECT_EQ(20, err.location().column_number());
}
TEST(ParseTree, SortRangeExtraction) {
TestWithScope setup;
// Ranges are [begin, end).
{
TestParseInput input(
"sources = [\n"
" \"a\",\n"
" \"b\",\n"
" \n"
" #\n"
" # Block\n"
" #\n"
" \n"
" \"c\","
" \"d\","
"]\n");
EXPECT_FALSE(input.has_error());
ASSERT_TRUE(input.parsed()->AsBlock());
ASSERT_TRUE(input.parsed()->AsBlock()->statements()[0]->AsBinaryOp());
const BinaryOpNode* binop =
input.parsed()->AsBlock()->statements()[0]->AsBinaryOp();
ASSERT_TRUE(binop->right()->AsList());
const ListNode* list = binop->right()->AsList();
EXPECT_EQ(5u, list->contents().size());
auto ranges = list->GetSortRanges();
ASSERT_EQ(2u, ranges.size());
EXPECT_EQ(0u, ranges[0].begin);
EXPECT_EQ(2u, ranges[0].end);
EXPECT_EQ(3u, ranges[1].begin);
EXPECT_EQ(5u, ranges[1].end);
}
{
TestParseInput input(
"sources = [\n"
" \"a\",\n"
" \"b\",\n"
" \n"
" # Attached comment.\n"
" \"c\","
" \"d\","
"]\n");
EXPECT_FALSE(input.has_error());
ASSERT_TRUE(input.parsed()->AsBlock());
ASSERT_TRUE(input.parsed()->AsBlock()->statements()[0]->AsBinaryOp());
const BinaryOpNode* binop =
input.parsed()->AsBlock()->statements()[0]->AsBinaryOp();
ASSERT_TRUE(binop->right()->AsList());
const ListNode* list = binop->right()->AsList();
EXPECT_EQ(4u, list->contents().size());
auto ranges = list->GetSortRanges();
ASSERT_EQ(2u, ranges.size());
EXPECT_EQ(0u, ranges[0].begin);
EXPECT_EQ(2u, ranges[0].end);
EXPECT_EQ(2u, ranges[1].begin);
EXPECT_EQ(4u, ranges[1].end);
}
{
TestParseInput input(
"sources = [\n"
" # At end of list.\n"
" \"zzzzzzzzzzz.cc\","
"]\n");
EXPECT_FALSE(input.has_error());
ASSERT_TRUE(input.parsed()->AsBlock());
ASSERT_TRUE(input.parsed()->AsBlock()->statements()[0]->AsBinaryOp());
const BinaryOpNode* binop =
input.parsed()->AsBlock()->statements()[0]->AsBinaryOp();
ASSERT_TRUE(binop->right()->AsList());
const ListNode* list = binop->right()->AsList();
EXPECT_EQ(1u, list->contents().size());
auto ranges = list->GetSortRanges();
ASSERT_EQ(1u, ranges.size());
EXPECT_EQ(0u, ranges[0].begin);
EXPECT_EQ(1u, ranges[0].end);
}
{
TestParseInput input(
"sources = [\n"
" # Block at start.\n"
" \n"
" \"z.cc\","
" \"y.cc\","
"]\n");
EXPECT_FALSE(input.has_error());
ASSERT_TRUE(input.parsed()->AsBlock());
ASSERT_TRUE(input.parsed()->AsBlock()->statements()[0]->AsBinaryOp());
const BinaryOpNode* binop =
input.parsed()->AsBlock()->statements()[0]->AsBinaryOp();
ASSERT_TRUE(binop->right()->AsList());
const ListNode* list = binop->right()->AsList();
EXPECT_EQ(3u, list->contents().size());
auto ranges = list->GetSortRanges();
ASSERT_EQ(1u, ranges.size());
EXPECT_EQ(1u, ranges[0].begin);
EXPECT_EQ(3u, ranges[0].end);
}
}
TEST(ParseTree, Integers) {
static const char* const kGood[] = {
"0",
"10",
"-54321",
"9223372036854775807", // INT64_MAX
"-9223372036854775808", // INT64_MIN
};
for (auto s : kGood) {
TestParseInput input(std::string("x = ") + s);
EXPECT_FALSE(input.has_error());
TestWithScope setup;
Err err;
input.parsed()->Execute(setup.scope(), &err);
EXPECT_FALSE(err.has_error());
}
static const char* const kBad[] = {
"-0",
"010",
"-010",
"9223372036854775808", // INT64_MAX + 1
"-9223372036854775809", // INT64_MIN - 1
};
for (auto s : kBad) {
TestParseInput input(std::string("x = ") + s);
EXPECT_FALSE(input.has_error());
TestWithScope setup;
Err err;
input.parsed()->Execute(setup.scope(), &err);
EXPECT_TRUE(err.has_error());
}
}
| js0701/chromium-crosswalk | tools/gn/parse_tree_unittest.cc | C++ | bsd-3-clause | 7,635 |
// 2005-04-26 Paolo Carlini <pcarlini@suse.de>
// Copyright (C) 2005 Free Software Foundation
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
// 22.2.2.1.1 num_get members
#include <locale>
#include <sstream>
#include <limits>
#include <testsuite_hooks.h>
void test01()
{
using namespace std;
typedef istreambuf_iterator<wchar_t> iterator_type;
bool test __attribute__((unused)) = true;
wstringstream ss;
const num_get<wchar_t>& ng = use_facet<num_get<wchar_t> >(ss.getloc());
ios_base::iostate err;
iterator_type end;
unsigned short us0, us1 = numeric_limits<unsigned short>::max();
unsigned int ui0, ui1 = numeric_limits<unsigned int>::max();
unsigned long ul0, ul1 = numeric_limits<unsigned long>::max();
long l01, l1 = numeric_limits<long>::max();
long l02, l2 = numeric_limits<long>::min();
#ifdef _GLIBCXX_USE_LONG_LONG
unsigned long long ull0, ull1 = numeric_limits<unsigned long long>::max();
long long ll01, ll1 = numeric_limits<long long>::max();
long long ll02, ll2 = numeric_limits<long long>::min();
#endif
const wstring empty;
us0 = 0;
ss << us1;
err = ios_base::goodbit;
end = ng.get(ss.rdbuf(), 0, ss, err, us0);
VERIFY( err == ios_base::eofbit );
VERIFY( us0 == us1 );
us0 = 0;
ss.clear();
ss.str(empty);
ss << us1 << L'0';
err = ios_base::goodbit;
end = ng.get(ss.rdbuf(), 0, ss, err, us0);
VERIFY( err == (ios_base::failbit | ios_base::eofbit) );
VERIFY( us0 == 0 );
ui0 = 0U;
ss.clear();
ss.str(empty);
ss << ui1 << ' ';
err = ios_base::goodbit;
end = ng.get(ss.rdbuf(), 0, ss, err, ui0);
VERIFY( err == ios_base::goodbit );
VERIFY( ui0 == ui1 );
ui0 = 0U;
ss.clear();
ss.str(empty);
ss << ui1 << L'1';
err = ios_base::goodbit;
end = ng.get(ss.rdbuf(), 0, ss, err, ui0);
VERIFY( err == (ios_base::failbit | ios_base::eofbit) );
VERIFY( ui0 == 0U );
ul0 = 0UL;
ss.clear();
ss.str(empty);
ss << ul1;
err = ios_base::goodbit;
end = ng.get(ss.rdbuf(), 0, ss, err, ul0);
VERIFY( err == ios_base::eofbit );
VERIFY( ul0 == ul1 );
ul0 = 0UL;
ss.clear();
ss.str(empty);
ss << ul1 << L'2';
err = ios_base::goodbit;
end = ng.get(ss.rdbuf(), 0, ss, err, ul0);
VERIFY( err == (ios_base::failbit | ios_base::eofbit) );
VERIFY( ul0 == 0UL );
l01 = 0L;
ss.clear();
ss.str(empty);
ss << l1 << L' ';
err = ios_base::goodbit;
end = ng.get(ss.rdbuf(), 0, ss, err, l01);
VERIFY( err == ios_base::goodbit );
VERIFY( l01 == l1 );
l01 = 0L;
ss.clear();
ss.str(empty);
ss << l1 << L'3';
err = ios_base::goodbit;
end = ng.get(ss.rdbuf(), 0, ss, err, l01);
VERIFY( err == (ios_base::failbit | ios_base::eofbit) );
VERIFY( l01 == 0L );
l02 = 0L;
ss.clear();
ss.str(empty);
ss << l2;
err = ios_base::goodbit;
end = ng.get(ss.rdbuf(), 0, ss, err, l02);
VERIFY( err == ios_base::eofbit );
VERIFY( l02 == l2 );
l02 = 0L;
ss.clear();
ss.str(empty);
ss << l2 << L'4';
err = ios_base::goodbit;
end = ng.get(ss.rdbuf(), 0, ss, err, l02);
VERIFY( err == (ios_base::failbit | ios_base::eofbit) );
VERIFY( l02 == 0L );
#ifdef _GLIBCXX_USE_LONG_LONG
ull0 = 0ULL;
ss.clear();
ss.str(empty);
ss << ull1 << L' ';
err = ios_base::goodbit;
end = ng.get(ss.rdbuf(), 0, ss, err, ull0);
VERIFY( err == ios_base::goodbit );
VERIFY( ull0 == ull1 );
ull0 = 0ULL;
ss.clear();
ss.str(empty);
ss << ull1 << L'5';
err = ios_base::goodbit;
end = ng.get(ss.rdbuf(), 0, ss, err, ull0);
VERIFY( err == (ios_base::failbit | ios_base::eofbit) );
VERIFY( ull0 == 0ULL );
ll01 = 0LL;
ss.clear();
ss.str(empty);
ss << ll1;
err = ios_base::goodbit;
end = ng.get(ss.rdbuf(), 0, ss, err, ll01);
VERIFY( err == ios_base::eofbit );
VERIFY( ll01 == ll1 );
ll01 = 0LL;
ss.clear();
ss.str(empty);
ss << ll1 << L'6';
err = ios_base::goodbit;
end = ng.get(ss.rdbuf(), 0, ss, err, ll01);
VERIFY( err == (ios_base::failbit | ios_base::eofbit) );
VERIFY( ll01 == 0LL );
ll02 = 0LL;
ss.clear();
ss.str(empty);
ss << ll2 << L' ';
err = ios_base::goodbit;
end = ng.get(ss.rdbuf(), 0, ss, err, ll02);
VERIFY( err == ios_base::goodbit );
VERIFY( ll02 == ll2 );
ll02 = 0LL;
ss.clear();
ss.str(empty);
ss << ll2 << L'7';
err = ios_base::goodbit;
end = ng.get(ss.rdbuf(), 0, ss, err, ll02);
VERIFY( err == (ios_base::failbit | ios_base::eofbit) );
VERIFY( ll02 == 0LL );
#endif
}
int main()
{
test01();
return 0;
}
| shaotuanchen/sunflower_exp | tools/source/gcc-4.2.4/libstdc++-v3/testsuite/22_locale/num_get/get/wchar_t/16.cc | C++ | bsd-3-clause | 5,193 |
<?php
/**
* Copyright 2011-2017 Anthon Pang. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @package WebDriver
*
* @author Anthon Pang <apang@softwaredevelopment.ca>
*/
namespace Test\WebDriver;
use WebDriver\Exception;
/**
* Test WebDriver\Exception class
*
* @package WebDriver
*
* @group Unit
*/
class ExceptionTest extends \PHPUnit_Framework_TestCase
{
/**
* test factory()
*/
public function testFactory()
{
$out = Exception::factory(255, 'wtf');
$this->assertTrue(get_class($out) === 'Exception');
$this->assertTrue($out->getMessage() === 'wtf');
$out = Exception::factory(Exception::SUCCESS);
$this->assertTrue(get_class($out) === 'Exception');
$this->assertTrue($out->getMessage() === 'Unknown Error');
$out = Exception::factory(Exception::CURL_EXEC);
$this->assertTrue($out instanceof Exception\CurlExec);
$this->assertTrue($out->getMessage() === 'curl_exec() error.');
}
}
| rainlike/justshop | vendor/instaclick/php-webdriver/test/Test/WebDriver/ExceptionTest.php | PHP | mit | 1,534 |
# Quantify coverage
require "codeclimate-test-reporter"
CodeClimate::TestReporter.start
# load the library
require 'koala'
# Support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
# set up our testing environment
# load testing data and (if needed) create test users or validate real users
KoalaTest.setup_test_environment!
BEACH_BALL_PATH = File.join(File.dirname(__FILE__), "fixtures", "beach.jpg")
| sancopanco/koala | spec/spec_helper.rb | Ruby | mit | 436 |
import { Component, Input } from '@angular/core';
import { AllReadyEvent } from "../../pages/events/events";
import { NavController } from "ionic-angular";
import { EventDetailsPage } from "../../pages/eventdetails/eventdetails";
import { DateFilterPipe } from "../../pipes/datefilter/datefilter";
@Component({
selector: 'event-card',
templateUrl: 'event-card.html'
})
export class EventCardComponent {
@Input('event') event: AllReadyEvent;
private formattedStartDateTime: string;
constructor(public navCtrl: NavController, public dateFilterPipe: DateFilterPipe) {
this.dateFilterPipe = new DateFilterPipe();
}
ngOnChanges() {
this.formattedStartDateTime =
this.dateFilterPipe.transform(this.event.StartDateTime.toString(), null);
}
showEventDetails(event: AllReadyEvent) {
this.navCtrl.push(EventDetailsPage, { event: event });
}
}
| stevejgordon/allReady | AllReadyApp/Mobile-App/src/components/event-card/event-card.ts | TypeScript | mit | 897 |
version https://git-lfs.github.com/spec/v1
oid sha256:d57f539203e9219f4c43532d12ca16d51ce822bf08d658cabd06aa84fc61dda2
size 661
| yogeshsaroya/new-cdnjs | ajax/libs/dojo/1.5.4/cldr/nls/sv/number.js | JavaScript | mit | 128 |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Runtime.Remoting.Channels.BaseChannelSinkWithProperties.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Runtime.Remoting.Channels
{
abstract public partial class BaseChannelSinkWithProperties : BaseChannelObjectWithProperties
{
#region Methods and constructors
protected BaseChannelSinkWithProperties()
{
}
#endregion
}
}
| Microsoft/CodeContracts | Microsoft.Research/Contracts/MsCorlib/Sources/System.Runtime.Remoting.Channels.BaseChannelSinkWithProperties.cs | C# | mit | 2,271 |
using System;
using System.Diagnostics;
using System.Net;
using System.Web;
using Umbraco.Core;
using Umbraco.Core.Logging;
namespace umbraco.presentation
{
/// <summary>
/// Makes a call to /umbraco/ping.aspx which is used to keep the web app alive
/// </summary>
public class keepAliveService
{
//NOTE: sender will be the umbraco ApplicationContext
public static void PingUmbraco(object sender)
{
if (sender == null || !(sender is ApplicationContext))
return;
var appContext = (ApplicationContext) sender;
var url = string.Format("http://{0}/ping.aspx", appContext.OriginalRequestUrl);
try
{
using (var wc = new WebClient())
{
wc.DownloadString(url);
}
}
catch(Exception ee)
{
LogHelper.Debug<keepAliveService>(string.Format("Error in ping({0}) -> {1}", url, ee));
}
}
}
} | Shazwazza/Umbraco-CMS | src/Umbraco.Web/umbraco.presentation/keepAliveService.cs | C# | mit | 909 |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Net.NetworkInformation.IPv4InterfaceProperties.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Net.NetworkInformation
{
abstract public partial class IPv4InterfaceProperties
{
#region Methods and constructors
protected IPv4InterfaceProperties()
{
}
#endregion
#region Properties and indexers
public abstract int Index
{
get;
}
public abstract bool IsAutomaticPrivateAddressingActive
{
get;
}
public abstract bool IsAutomaticPrivateAddressingEnabled
{
get;
}
public abstract bool IsDhcpEnabled
{
get;
}
public abstract bool IsForwardingEnabled
{
get;
}
public abstract int Mtu
{
get;
}
public abstract bool UsesWins
{
get;
}
#endregion
}
}
| Microsoft/CodeContracts | Microsoft.Research/Contracts/System/Sources/System.Net.NetworkInformation.IPv4InterfaceProperties.cs | C# | mit | 2,729 |
'use strict';
var Promise = require('../../lib/ext/promise');
var conf = require('ember-cli-internal-test-helpers/lib/helpers/conf');
var ember = require('../helpers/ember');
var fs = require('fs-extra');
var outputFile = Promise.denodeify(fs.outputFile);
var path = require('path');
var remove = Promise.denodeify(fs.remove);
var replaceFile = require('ember-cli-internal-test-helpers/lib/helpers/file-utils').replaceFile;
var root = process.cwd();
var tmproot = path.join(root, 'tmp');
var Blueprint = require('../../lib/models/blueprint');
var BlueprintNpmTask = require('ember-cli-internal-test-helpers/lib/helpers/disable-npm-on-blueprint');
var mkTmpDirIn = require('../../lib/utilities/mk-tmp-dir-in');
var chai = require('../chai');
var expect = chai.expect;
var file = chai.file;
describe('Acceptance: ember generate', function() {
this.timeout(20000);
var tmpdir;
before(function() {
BlueprintNpmTask.disableNPM(Blueprint);
conf.setup();
});
after(function() {
BlueprintNpmTask.restoreNPM(Blueprint);
conf.restore();
});
beforeEach(function() {
return mkTmpDirIn(tmproot).then(function(dir) {
tmpdir = dir;
process.chdir(tmpdir);
});
});
afterEach(function() {
process.chdir(root);
return remove(tmproot);
});
function initApp() {
return ember([
'init',
'--name=my-app',
'--skip-npm',
'--skip-bower'
]);
}
function generate(args) {
var generateArgs = ['generate'].concat(args);
return initApp().then(function() {
return ember(generateArgs);
});
}
it('component x-foo', function() {
return generate(['component', 'x-foo']).then(function() {
expect(file('app/components/x-foo.js'))
.to.contain("import Ember from 'ember';")
.to.contain("export default Ember.Component.extend({")
.to.contain("});");
expect(file('app/templates/components/x-foo.hbs'))
.to.contain("{{yield}}");
expect(file('tests/integration/components/x-foo-test.js'))
.to.contain("import { moduleForComponent, test } from 'ember-qunit';")
.to.contain("import hbs from 'htmlbars-inline-precompile';")
.to.contain("moduleForComponent('x-foo'")
.to.contain("integration: true")
.to.contain("{{x-foo}}")
.to.contain("{{#x-foo}}");
});
});
it('component foo/x-foo', function() {
return generate(['component', 'foo/x-foo']).then(function() {
expect(file('app/components/foo/x-foo.js'))
.to.contain("import Ember from 'ember';")
.to.contain("export default Ember.Component.extend({")
.to.contain("});");
expect(file('app/templates/components/foo/x-foo.hbs'))
.to.contain("{{yield}}");
expect(file('tests/integration/components/foo/x-foo-test.js'))
.to.contain("import { moduleForComponent, test } from 'ember-qunit';")
.to.contain("import hbs from 'htmlbars-inline-precompile';")
.to.contain("moduleForComponent('foo/x-foo'")
.to.contain("integration: true")
.to.contain("{{foo/x-foo}}")
.to.contain("{{#foo/x-foo}}");
});
});
it('component x-foo ignores --path option', function() {
return generate(['component', 'x-foo', '--path', 'foo']).then(function() {
expect(file('app/components/x-foo.js'))
.to.contain("import Ember from 'ember';")
.to.contain("export default Ember.Component.extend({")
.to.contain("});");
expect(file('app/templates/components/x-foo.hbs'))
.to.contain("{{yield}}");
expect(file('tests/integration/components/x-foo-test.js'))
.to.contain("import { moduleForComponent, test } from 'ember-qunit';")
.to.contain("import hbs from 'htmlbars-inline-precompile';")
.to.contain("moduleForComponent('x-foo'")
.to.contain("integration: true")
.to.contain("{{x-foo}}")
.to.contain("{{#x-foo}}");
});
});
it('blueprint foo', function() {
return generate(['blueprint', 'foo']).then(function() {
expect(file('blueprints/foo/index.js'))
.to.contain("module.exports = {\n" +
" description: ''\n" +
"\n" +
" // locals: function(options) {\n" +
" // // Return custom template variables here.\n" +
" // return {\n" +
" // foo: options.entity.options.foo\n" +
" // };\n" +
" // }\n" +
"\n" +
" // afterInstall: function(options) {\n" +
" // // Perform extra work here.\n" +
" // }\n" +
"};");
});
});
it('blueprint foo/bar', function() {
return generate(['blueprint', 'foo/bar']).then(function() {
expect(file('blueprints/foo/bar/index.js'))
.to.contain("module.exports = {\n" +
" description: ''\n" +
"\n" +
" // locals: function(options) {\n" +
" // // Return custom template variables here.\n" +
" // return {\n" +
" // foo: options.entity.options.foo\n" +
" // };\n" +
" // }\n" +
"\n" +
" // afterInstall: function(options) {\n" +
" // // Perform extra work here.\n" +
" // }\n" +
"};");
});
});
it('http-mock foo', function() {
return generate(['http-mock', 'foo']).then(function() {
expect(file('server/index.js'))
.to.contain("mocks.forEach(function(route) { route(app); });");
expect(file('server/mocks/foo.js'))
.to.contain("module.exports = function(app) {\n" +
" var express = require('express');\n" +
" var fooRouter = express.Router();\n" +
"\n" +
" fooRouter.get('/', function(req, res) {\n" +
" res.send({\n" +
" 'foo': []\n" +
" });\n" +
" });\n" +
"\n" +
" fooRouter.post('/', function(req, res) {\n" +
" res.status(201).end();\n" +
" });\n" +
"\n" +
" fooRouter.get('/:id', function(req, res) {\n" +
" res.send({\n" +
" 'foo': {\n" +
" id: req.params.id\n" +
" }\n" +
" });\n" +
" });\n" +
"\n" +
" fooRouter.put('/:id', function(req, res) {\n" +
" res.send({\n" +
" 'foo': {\n" +
" id: req.params.id\n" +
" }\n" +
" });\n" +
" });\n" +
"\n" +
" fooRouter.delete('/:id', function(req, res) {\n" +
" res.status(204).end();\n" +
" });\n" +
"\n" +
" // The POST and PUT call will not contain a request body\n" +
" // because the body-parser is not included by default.\n" +
" // To use req.body, run:\n" +
"\n" +
" // npm install --save-dev body-parser\n" +
"\n" +
" // After installing, you need to `use` the body-parser for\n" +
" // this mock uncommenting the following line:\n" +
" //\n" +
" //app.use('/api/foo', require('body-parser').json());\n" +
" app.use('/api/foo', fooRouter);\n" +
"};");
expect(file('server/.jshintrc'))
.to.contain('{\n "node": true\n}');
});
});
it('http-mock foo-bar', function() {
return generate(['http-mock', 'foo-bar']).then(function() {
expect(file('server/index.js'))
.to.contain("mocks.forEach(function(route) { route(app); });");
expect(file('server/mocks/foo-bar.js'))
.to.contain("module.exports = function(app) {\n" +
" var express = require('express');\n" +
" var fooBarRouter = express.Router();\n" +
"\n" +
" fooBarRouter.get('/', function(req, res) {\n" +
" res.send({\n" +
" 'foo-bar': []\n" +
" });\n" +
" });\n" +
"\n" +
" fooBarRouter.post('/', function(req, res) {\n" +
" res.status(201).end();\n" +
" });\n" +
"\n" +
" fooBarRouter.get('/:id', function(req, res) {\n" +
" res.send({\n" +
" 'foo-bar': {\n" +
" id: req.params.id\n" +
" }\n" +
" });\n" +
" });\n" +
"\n" +
" fooBarRouter.put('/:id', function(req, res) {\n" +
" res.send({\n" +
" 'foo-bar': {\n" +
" id: req.params.id\n" +
" }\n" +
" });\n" +
" });\n" +
"\n" +
" fooBarRouter.delete('/:id', function(req, res) {\n" +
" res.status(204).end();\n" +
" });\n" +
"\n" +
" // The POST and PUT call will not contain a request body\n" +
" // because the body-parser is not included by default.\n" +
" // To use req.body, run:\n" +
"\n" +
" // npm install --save-dev body-parser\n" +
"\n" +
" // After installing, you need to `use` the body-parser for\n" +
" // this mock uncommenting the following line:\n" +
" //\n" +
" //app.use('/api/foo-bar', require('body-parser').json());\n" +
" app.use('/api/foo-bar', fooBarRouter);\n" +
"};");
expect(file('server/.jshintrc'))
.to.contain('{\n "node": true\n}');
});
});
it('http-proxy foo', function() {
return generate(['http-proxy', 'foo', 'http://localhost:5000']).then(function() {
expect(file('server/index.js'))
.to.contain("proxies.forEach(function(route) { route(app); });");
expect(file('server/proxies/foo.js'))
.to.contain("var proxyPath = '/foo';\n" +
"\n" +
"module.exports = function(app) {\n" +
" // For options, see:\n" +
" // https://github.com/nodejitsu/node-http-proxy\n" +
" var proxy = require('http-proxy').createProxyServer({});\n" +
"\n" +
" proxy.on('error', function(err, req) {\n" +
" console.error(err, req.url);\n" +
" });\n" +
"\n" +
" app.use(proxyPath, function(req, res, next){\n" +
" // include root path in proxied request\n" +
" req.url = proxyPath + '/' + req.url;\n" +
" proxy.web(req, res, { target: 'http://localhost:5000' });\n" +
" });\n" +
"};");
expect(file('server/.jshintrc'))
.to.contain('{\n "node": true\n}');
});
});
it('uses blueprints from the project directory', function() {
return initApp()
.then(function() {
return outputFile(
'blueprints/foo/files/app/foos/__name__.js',
"import Ember from 'ember';\n" +
'export default Ember.Object.extend({ foo: true });\n'
);
})
.then(function() {
return ember(['generate', 'foo', 'bar']);
})
.then(function() {
expect(file('app/foos/bar.js')).to.contain('foo: true');
});
});
it('allows custom blueprints to override built-ins', function() {
return initApp()
.then(function() {
return outputFile(
'blueprints/controller/files/app/controllers/__name__.js',
"import Ember from 'ember';\n\n" +
"export default Ember.Controller.extend({ custom: true });\n"
);
})
.then(function() {
return ember(['generate', 'controller', 'foo']);
})
.then(function() {
expect(file('app/controllers/foo.js')).to.contain('custom: true');
});
});
it('passes custom cli arguments to blueprint options', function() {
return initApp()
.then(function() {
outputFile(
'blueprints/customblue/files/app/__name__.js',
"Q: Can I has custom command? A: <%= hasCustomCommand %>"
);
return outputFile(
'blueprints/customblue/index.js',
"module.exports = {\n" +
" locals: function(options) {\n" +
" var loc = {};\n" +
" loc.hasCustomCommand = (options.customCommand) ? 'Yes!' : 'No. :C';\n" +
" return loc;\n" +
" },\n" +
"};\n"
);
})
.then(function() {
return ember(['generate', 'customblue', 'foo', '--custom-command']);
})
.then(function() {
expect(file('app/foo.js')).to.contain('A: Yes!');
});
});
it('correctly identifies the root of the project', function() {
return initApp()
.then(function() {
return outputFile(
'blueprints/controller/files/app/controllers/__name__.js',
"import Ember from 'ember';\n\n" +
"export default Ember.Controller.extend({ custom: true });\n"
);
})
.then(function() {
process.chdir(path.join(tmpdir, 'app'));
})
.then(function() {
return ember(['generate', 'controller', 'foo']);
})
.then(function() {
process.chdir(tmpdir);
})
.then(function() {
expect(file('app/controllers/foo.js')).to.contain('custom: true');
});
});
it('route foo --dry-run does not change router.js', function() {
return generate(['route', 'foo', '--dry-run']).then(function() {
expect(file('app/router.js')).to.not.contain("route('foo')");
});
});
it('server', function() {
return generate(['server']).then(function() {
expect(file('server/index.js')).to.exist;
expect(file('server/.jshintrc')).to.exist;
});
});
it('availableOptions work with aliases.', function() {
return generate(['route', 'foo', '-d']).then(function() {
expect(file('app/router.js')).to.not.contain("route('foo')");
});
});
it('lib', function() {
return generate(['lib']).then(function() {
expect(file('lib/.jshintrc')).to.exist;
});
});
it('custom blueprint availableOptions', function() {
return initApp().then(function() {
return ember(['generate', 'blueprint', 'foo']).then(function() {
replaceFile('blueprints/foo/index.js', 'module.exports = {',
'module.exports = {\navailableOptions: [ \n' +
'{ name: \'foo\',\ntype: String, \n' +
'values: [\'one\', \'two\'],\n' +
'default: \'one\',\n' +
'aliases: [ {\'one\': \'one\'}, {\'two\': \'two\'} ] } ],\n' +
'locals: function(options) {\n' +
'return { foo: options.foo };\n' +
'},');
return outputFile(
'blueprints/foo/files/app/foos/__name__.js',
"import Ember from 'ember';\n" +
'export default Ember.Object.extend({ foo: <%= foo %> });\n'
).then(function() {
return ember(['generate','foo','bar','-two']);
});
});
}).then(function() {
expect(file('app/foos/bar.js')).to.contain('export default Ember.Object.extend({ foo: two });');
});
});
});
| lazybensch/ember-cli | tests/acceptance/generate-test.js | JavaScript | mit | 16,507 |
import Ember from 'ember';
import { module, test } from 'qunit';
import Confirmation from 'ember-validations/validators/local/confirmation';
import Mixin from 'ember-validations/mixin';
import buildContainer from '../../../helpers/build-container';
var model, Model, options, validator;
var get = Ember.get;
var set = Ember.set;
var run = Ember.run;
module('Confirmation Validator', {
setup: function() {
Model = Ember.Object.extend(Mixin, {
container: buildContainer()
});
run(function() {
model = Model.create();
});
}
});
test('when values match', function(assert) {
options = { message: 'failed validation' };
run(function() {
validator = Confirmation.create({model: model, property: 'attribute', options: options});
set(model, 'attribute', 'test');
set(model, 'attributeConfirmation', 'test');
});
assert.deepEqual(validator.errors, []);
run(function() {
set(model, 'attributeConfirmation', 'newTest');
});
assert.deepEqual(validator.errors, ['failed validation']);
run(function() {
set(model, 'attribute', 'newTest');
});
assert.deepEqual(validator.errors, []);
});
test('when values do not match', function(assert) {
options = { message: 'failed validation' };
run(function() {
validator = Confirmation.create({model: model, property: 'attribute', options: options});
set(model, 'attribute', 'test');
});
assert.deepEqual(validator.errors, ['failed validation']);
});
test('when original is null', function(assert) {
run(function() {
validator = Confirmation.create({model: model, property: 'attribute'});
model.set('attribute', null);
});
assert.ok(Ember.isEmpty(validator.errors));
});
test('when confirmation is null', function(assert) {
run(function() {
validator = Confirmation.create({model: model, property: 'attribute'});
model.set('attributeConfirmation', null);
});
assert.ok(Ember.isEmpty(validator.errors));
});
test('when options is true', function(assert) {
options = true;
run(function() {
validator = Confirmation.create({model: model, property: 'attribute', options: options});
set(model, 'attribute', 'test');
});
assert.deepEqual(validator.errors, ["doesn't match attribute"]);
});
test('message integration on model, prints message on Confirmation property', function(assert) {
var otherModel, OtherModel = Model.extend({
validations: {
attribute: {
confirmation: true
}
}
});
run(function() {
otherModel = OtherModel.create();
set(otherModel, 'attribute', 'test');
});
assert.deepEqual(get(otherModel, 'errors.attributeConfirmation'), ["doesn't match attribute"]);
assert.deepEqual(get(otherModel, 'errors.attribute'), []);
});
| meszike123/ember-validations | tests/unit/validators/local/confirmation-test.js | JavaScript | mit | 2,746 |
<?php
namespace Oro\Bundle\IntegrationBundle\Exception;
interface IntegrationException
{
}
| MarkThink/OROCRM | vendor/oro/platform/src/Oro/Bundle/IntegrationBundle/Exception/IntegrationException.php | PHP | mit | 93 |
<?php
namespace Sirius\Validation\Rule;
class RequiredWhen extends Required
{
const OPTION_ITEM = 'item';
const OPTION_RULE = 'rule';
const OPTION_RULE_OPTIONS = 'rule_options';
protected static $defaultMessageTemplate = 'This field is required';
public function getItemRule()
{
/* @var $rule AbstractValidator */
$rule = false;
$ruleOptions = (isset($this->options[self::OPTION_RULE_OPTIONS])) ? (array)$this->options[self::OPTION_RULE_OPTIONS] : array();
if (is_string($this->options[self::OPTION_RULE])) {
$ruleClass = $this->options[self::OPTION_RULE];
if (class_exists($ruleClass)) {
$rule = new $ruleClass($ruleOptions);
} elseif (class_exists('Sirius\\Validation\\Rule\\' . $ruleClass)) {
$ruleClass = 'Sirius\\Validation\\Rule\\' . $ruleClass;
$rule = new $ruleClass($ruleOptions);
}
} elseif (is_object(
$this->options[self::OPTION_RULE]
) && $this->options[self::OPTION_RULE] instanceof AbstractValidator
) {
$rule = $this->options[self::OPTION_RULE];
}
if (!$rule) {
throw new \InvalidArgumentException(
'Validator for the other item is not valid or cannot be constructed based on the data provided'
);
}
$context = $this->context ? $this->context : array();
$rule->setContext($context);
return $rule;
}
public function validate($value, $valueIdentifier = null)
{
$this->value = $value;
if (!isset($this->options[self::OPTION_ITEM])) {
$this->success = true;
} else {
$itemRule = $this->getItemRule();
$itemValue = $this->context->getItemValue($this->options[self::OPTION_ITEM]);
if ($itemRule->validate($itemValue, $this->options[self::OPTION_ITEM])) {
$this->success = ($value !== null || trim($value) !== '');
} else {
$this->success = true;
}
}
return $this->success;
}
}
| frisbeesport/frisbeesport.nl | vendor/siriusphp/validation/src/Rule/RequiredWhen.php | PHP | mit | 2,149 |
<?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\PromotionBundle\Form\Type;
use Sylius\Bundle\PromotionBundle\Form\EventListener\BuildActionFormSubscriber;
use Sylius\Bundle\PromotionBundle\Form\Type\Core\AbstractConfigurationType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* @author Saša Stamenković <umpirsky@gmail.com>
* @author Arnaud Langlade <arn0d.dev@gmail.com>
*/
class ActionType extends AbstractConfigurationType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options = [])
{
$builder
->add('type', 'sylius_promotion_action_choice', [
'label' => 'sylius.form.action.type',
'attr' => [
'data-form-collection' => 'update',
],
])
->addEventSubscriber(
new BuildActionFormSubscriber(
$this->registry,
$builder->getFormFactory(),
(isset($options['configuration_type'])) ? $options['configuration_type'] : null
)
)
;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'sylius_promotion_action';
}
}
| Ejobs/Sylius | src/Sylius/Bundle/PromotionBundle/Form/Type/ActionType.php | PHP | mit | 1,453 |
'use strict';
const existsSync = require('exists-sync');
const path = require('path');
const LiveReloadServer = require('./server/livereload-server');
const ExpressServer = require('./server/express-server');
const RSVP = require('rsvp');
const Task = require('../models/task');
const Watcher = require('../models/watcher');
const ServerWatcher = require('../models/server-watcher');
const Builder = require('../models/builder');
const Promise = RSVP.Promise;
class ServeTask extends Task {
constructor(options) {
super(options);
this._runDeferred = null;
this._builder = null;
}
run(options) {
let builder = this._builder = options._builder || new Builder({
ui: this.ui,
outputPath: options.outputPath,
project: this.project,
environment: options.environment,
});
let watcher = options._watcher || new Watcher({
ui: this.ui,
builder,
analytics: this.analytics,
options,
serving: true,
});
let serverRoot = './server';
let serverWatcher = null;
if (existsSync(serverRoot)) {
serverWatcher = new ServerWatcher({
ui: this.ui,
analytics: this.analytics,
watchedDir: path.resolve(serverRoot),
options,
});
}
let expressServer = options._expressServer || new ExpressServer({
ui: this.ui,
project: this.project,
watcher,
serverRoot,
serverWatcher,
});
let liveReloadServer = options._liveReloadServer || new LiveReloadServer({
ui: this.ui,
analytics: this.analytics,
project: this.project,
watcher,
expressServer,
});
/* hang until the user exits */
this._runDeferred = RSVP.defer();
return Promise.all([
liveReloadServer.start(options),
expressServer.start(options),
]).then(() => this._runDeferred.promise);
}
/**
* Exit silently
*
* @private
* @method onInterrupt
*/
onInterrupt() {
return this._builder.cleanup().then(() => this._runDeferred.resolve());
}
}
module.exports = ServeTask;
| gabz75/ember-cli-deploy-redis-publish | node_modules/ember-cli/lib/tasks/serve.js | JavaScript | mit | 2,076 |
<?php
/**
* @package Joomla.Platform
* @subpackage String
*
* @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
use Joomla\Uri\UriHelper;
JLoader::register('idna_convert', JPATH_LIBRARIES . '/idna_convert/idna_convert.class.php');
/**
* Joomla Platform String Punycode Class
*
* Class for handling UTF-8 URLs
* Wraps the Punycode library
* All functions assume the validity of utf-8 URLs.
*
* @since 3.1.2
*/
abstract class JStringPunycode
{
/**
* Transforms a UTF-8 string to a Punycode string
*
* @param string $utfString The UTF-8 string to transform
*
* @return string The punycode string
*
* @since 3.1.2
*/
public static function toPunycode($utfString)
{
$idn = new idna_convert;
return $idn->encode($utfString);
}
/**
* Transforms a Punycode string to a UTF-8 string
*
* @param string $punycodeString The Punycode string to transform
*
* @return string The UF-8 URL
*
* @since 3.1.2
*/
public static function fromPunycode($punycodeString)
{
$idn = new idna_convert;
return $idn->decode($punycodeString);
}
/**
* Transforms a UTF-8 URL to a Punycode URL
*
* @param string $uri The UTF-8 URL to transform
*
* @return string The punycode URL
*
* @since 3.1.2
*/
public static function urlToPunycode($uri)
{
$parsed = UriHelper::parse_url($uri);
if (!isset($parsed['host']) || $parsed['host'] == '')
{
// If there is no host we do not need to convert it.
return $uri;
}
$host = $parsed['host'];
$hostExploded = explode('.', $host);
$newhost = '';
foreach ($hostExploded as $hostex)
{
$hostex = static::toPunycode($hostex);
$newhost .= $hostex . '.';
}
$newhost = substr($newhost, 0, -1);
$newuri = '';
if (!empty($parsed['scheme']))
{
// Assume :// is required although it is not always.
$newuri .= $parsed['scheme'] . '://';
}
if (!empty($newhost))
{
$newuri .= $newhost;
}
if (!empty($parsed['port']))
{
$newuri .= ':' . $parsed['port'];
}
if (!empty($parsed['path']))
{
$newuri .= $parsed['path'];
}
if (!empty($parsed['query']))
{
$newuri .= '?' . $parsed['query'];
}
if (!empty($parsed['fragment']))
{
$newuri .= '#' . $parsed['fragment'];
}
return $newuri;
}
/**
* Transforms a Punycode URL to a UTF-8 URL
*
* @param string $uri The Punycode URL to transform
*
* @return string The UTF-8 URL
*
* @since 3.1.2
*/
public static function urlToUTF8($uri)
{
if (empty($uri))
{
return;
}
$parsed = UriHelper::parse_url($uri);
if (!isset($parsed['host']) || $parsed['host'] == '')
{
// If there is no host we do not need to convert it.
return $uri;
}
$host = $parsed['host'];
$hostExploded = explode('.', $host);
$newhost = '';
foreach ($hostExploded as $hostex)
{
$hostex = self::fromPunycode($hostex);
$newhost .= $hostex . '.';
}
$newhost = substr($newhost, 0, -1);
$newuri = '';
if (!empty($parsed['scheme']))
{
// Assume :// is required although it is not always.
$newuri .= $parsed['scheme'] . '://';
}
if (!empty($newhost))
{
$newuri .= $newhost;
}
if (!empty($parsed['port']))
{
$newuri .= ':' . $parsed['port'];
}
if (!empty($parsed['path']))
{
$newuri .= $parsed['path'];
}
if (!empty($parsed['query']))
{
$newuri .= '?' . $parsed['query'];
}
if (!empty($parsed['fragment']))
{
$newuri .= '#' . $parsed['fragment'];
}
return $newuri;
}
/**
* Transforms a UTF-8 email to a Punycode email
* This assumes a valid email address
*
* @param string $email The UTF-8 email to transform
*
* @return string The punycode email
*
* @since 3.1.2
*/
public static function emailToPunycode($email)
{
$explodedAddress = explode('@', $email);
// Not addressing UTF-8 user names
$newEmail = $explodedAddress[0];
if (!empty($explodedAddress[1]))
{
$domainExploded = explode('.', $explodedAddress[1]);
$newdomain = '';
foreach ($domainExploded as $domainex)
{
$domainex = static::toPunycode($domainex);
$newdomain .= $domainex . '.';
}
$newdomain = substr($newdomain, 0, -1);
$newEmail = $newEmail . '@' . $newdomain;
}
return $newEmail;
}
/**
* Transforms a Punycode email to a UTF-8 email
* This assumes a valid email address
*
* @param string $email The punycode email to transform
*
* @return string The punycode email
*
* @since 3.1.2
*/
public static function emailToUTF8($email)
{
$explodedAddress = explode('@', $email);
// Not addressing UTF-8 user names
$newEmail = $explodedAddress[0];
if (!empty($explodedAddress[1]))
{
$domainExploded = explode('.', $explodedAddress[1]);
$newdomain = '';
foreach ($domainExploded as $domainex)
{
$domainex = static::fromPunycode($domainex);
$newdomain .= $domainex . '.';
}
$newdomain = substr($newdomain, 0, -1);
$newEmail = $newEmail . '@' . $newdomain;
}
return $newEmail;
}
}
| demis-palma/joomla-cms | libraries/joomla/string/punycode.php | PHP | gpl-2.0 | 5,195 |
<?php
/**
* File containing the URLAliasCreate parser class.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*
* @version //autogentag//
*/
namespace eZ\Publish\Core\REST\Server\Input\Parser;
use eZ\Publish\Core\REST\Common\Input\BaseParser;
use eZ\Publish\Core\REST\Common\Input\ParsingDispatcher;
use eZ\Publish\Core\REST\Common\Input\ParserTools;
use eZ\Publish\Core\REST\Common\Exceptions;
/**
* Parser for URLAliasCreate.
*/
class URLAliasCreate extends BaseParser
{
/**
* Parser tools.
*
* @var \eZ\Publish\Core\REST\Common\Input\ParserTools
*/
protected $parserTools;
/**
* Construct.
*
* @param \eZ\Publish\Core\REST\Common\Input\ParserTools $parserTools
*/
public function __construct(ParserTools $parserTools)
{
$this->parserTools = $parserTools;
}
/**
* Parse input structure.
*
* @param array $data
* @param \eZ\Publish\Core\REST\Common\Input\ParsingDispatcher $parsingDispatcher
*
* @return array
*/
public function parse(array $data, ParsingDispatcher $parsingDispatcher)
{
if (!array_key_exists('_type', $data)) {
throw new Exceptions\Parser("Missing '_type' value for URLAliasCreate.");
}
if ($data['_type'] == 'LOCATION') {
if (!array_key_exists('location', $data)) {
throw new Exceptions\Parser("Missing 'location' value for URLAliasCreate.");
}
if (!is_array($data['location']) || !array_key_exists('_href', $data['location'])) {
throw new Exceptions\Parser("Missing 'location' > '_href' attribute for URLAliasCreate.");
}
} else {
if (!array_key_exists('resource', $data)) {
throw new Exceptions\Parser("Missing 'resource' value for URLAliasCreate.");
}
}
if (!array_key_exists('path', $data)) {
throw new Exceptions\Parser("Missing 'path' value for URLAliasCreate.");
}
if (!array_key_exists('languageCode', $data)) {
throw new Exceptions\Parser("Missing 'languageCode' value for URLAliasCreate.");
}
if (array_key_exists('alwaysAvailable', $data)) {
$data['alwaysAvailable'] = $this->parserTools->parseBooleanValue($data['alwaysAvailable']);
} else {
$data['alwaysAvailable'] = false;
}
if (array_key_exists('forward', $data)) {
$data['forward'] = $this->parserTools->parseBooleanValue($data['forward']);
} else {
$data['forward'] = false;
}
return $data;
}
}
| flovntp/BikeTutorialWebsite | vendor/ezsystems/ezpublish-kernel/eZ/Publish/Core/REST/Server/Input/Parser/URLAliasCreate.php | PHP | gpl-2.0 | 2,782 |
__version_info__ = (0, 6, 1)
__version__ = '.'.join(map(str, __version_info__))
| NeuPhysics/NumSolTUn | docs/_themes/alabaster/_version.py | Python | gpl-2.0 | 80 |
<?php
/**
* @package Joomla.Site
* @subpackage Layout
*
* @copyright (C) 2016 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
use Joomla\CMS\Form\Form;
extract($displayData);
/**
* Layout variables
* -----------------
* @var Form $tmpl The Empty form for template
* @var array $forms Array of JForm instances for render the rows
* @var bool $multiple The multiple state for the form field
* @var int $min Count of minimum repeating in multiple mode
* @var int $max Count of maximum repeating in multiple mode
* @var string $name Name of the input field.
* @var string $fieldname The field name
* @var string $fieldId The field ID
* @var string $control The forms control
* @var string $label The field label
* @var string $description The field description
* @var array $buttons Array of the buttons that will be rendered
* @var bool $groupByFieldset Whether group the subform fields by it`s fieldset
*/
$form = $forms[0];
?>
<div class="subform-wrapper">
<?php foreach ($form->getGroup('') as $field) : ?>
<?php echo $field->renderField(); ?>
<?php endforeach; ?>
</div>
| brianteeman/joomla-cms | layouts/joomla/form/field/subform/default.php | PHP | gpl-2.0 | 1,390 |
package org.ezsystems.solr.handler.ezfind;
// ## BEGIN COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
// SOFTWARE NAME: eZ Find
// SOFTWARE RELEASE: 2.0.x
// COPYRIGHT NOTICE: Copyright (C) 1999-2012 eZ Systems AS
// SOFTWARE LICENSE: GNU General Public License v2.0
// NOTICE: >
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2.0 of the GNU General
// Public License as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of version 2.0 of the GNU General
// Public License along with this program; if not, write to the Free
// Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.
//
//
// ## END COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
import org.apache.solr.util.plugin.*;
import org.apache.solr.handler.*;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.core.SolrCore;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.Config;
import org.apache.solr.core.SolrCore;
import org.apache.solr.core.SolrDeletionPolicy;
import org.apache.solr.handler.component.SearchComponent;
import org.apache.solr.handler.component.QueryElevationComponent;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.HashMap;
import java.util.logging.Logger;
import java.net.URL;
/**
* Multi purposer handler, extending Solr's features for <a href="http://ez.no/ezfind/">eZ Find</a>, technological bridge
* between the Enterprise Open Source CMS <a href="http://ez.no/ezpublish/">eZ Publish</a> and <a href="http://lucene.apache.org/solr/">Solr</a>
* <p/>
*/
public class eZFindRequestHandler extends RequestHandlerBase implements SolrCoreAware {
/**
* Storing the current core.
*/
private SolrCore core = null;
/**
* Storing the core's first elevation Component encountered.
* Will be used to update the configuration dynamically.
*/
private QueryElevationComponent elevationComponent = null;
/**
* Used to dynamically update the configuration file, usually named "elevate.xml".
* Is populated once at initialization.
*
* @see init
*/
private String elevateConfigurationFileName = null;
private transient static Logger log = Logger.getLogger( eZFindRequestHandler.class + "" );
/**
* Constant storing the name of the POST/GET variable ( request parameter )
* containing the update configuration XML for the QueryElevation component.
*/
public static final String CONF_PARAM_NAME = "elevate-configuration";
/** <code>init</code> will be called just once, immediately after creation.
* <p>The args are user-level initialization parameters that
* may be specified when declaring a request handler in
* solrconfig.xml
*/
public void init( NamedList args )
{}
/**
* Returns the name of the QueryElevation component's configuration file.
*
* Is assumed here that the QueryElevation component's configuration is correct ( hence the absence of sanity checks ).
* It would have triggered exceptions at startup otherwise.
*/
private String getElevateConfigurationFileName()
{
if ( this.elevateConfigurationFileName == null )
{
// Issue accessing the initArgs property of a QueryElevationComponent object, it is private. Need to directly access the config.
// String f = this.elevationComponent.initArgs.get( QueryElevationComponent.CONFIG_FILE );
// FIXME: the XML attribute name ( "config-file" ) is only visible from the package in QueryElevationComponent,
// hence the impossibility to use QueryElevationComponent.CONFIG_FILE ( which would be way cleaner ). This issue appears again a few lines below.
this.elevateConfigurationFileName = this.core.getSolrConfig().get( "searchComponent[@class=\"solr.QueryElevationComponent\"]/str[@name=\"" + "config-file" + "\"]", "elevate.xml" );
}
return this.elevateConfigurationFileName;
}
/**
* Handles a query request, this method must be thread safe.
* <p>
* Information about the request may be obtained from <code>req</code> and
* response information may be set using <code>rsp</code>.
* <p>
* There are no mandatory actions that handleRequest must perform.
* An empty handleRequest implementation would fulfill
* all interface obligations.
*/
//@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp)
{
String newElevateConfiguration = req.getParams().get( eZFindRequestHandler.CONF_PARAM_NAME );
if ( newElevateConfiguration != null )
{
String f = this.getElevateConfigurationFileName();
File fC = new File( this.core.getResourceLoader().getConfigDir(), f );
//File fD = new File( this.core.getDataDir(), f );
// updating files below.
// TODO : Need for concurrency management / thread safety
// TODO : Need for XML validation here
if( fC.exists() ) {
// Update fC.
try
{
this.log.info( "Updating " + fC );
FileWriter fw = new FileWriter( fC );
BufferedWriter out = new BufferedWriter( fw );
out.write( newElevateConfiguration );
out.close();
// reinitialize the QueryElevation component. Is there another way to take the new configuration into account ?
this.elevationComponent.inform( this.core );
}
catch (Exception e) {
this.log.info( "Exception when updating " + fC.getAbsolutePath() + " : " + e.getMessage() );
rsp.add( "error", "Error when updating " + fC.getAbsolutePath() + " : " + e.getMessage() );
}
}
/**
* Although the QueryElevationComponent supports having elevate.xml both in the dataDir and in the conf dir,
* this requestHandler will not support having elevate.xml in the dataDir. In fact, the replication feature, being on his way at the moment
* is not able to replicate configuration files placed in the dataDir.
*/
/*
else if( fD.exists() )
{
// Update fD.
try
{
this.log.info( "Updating " + fD );
FileWriter fw = new FileWriter( fD );
BufferedWriter out = new BufferedWriter( fw );
out.write( newElevateConfiguration );
out.close();
// reinitialize the QueryElevation component. Is there another way to take the new configuration into account ?
this.elevationComponent.inform( this.core );
}
catch (Exception e) {
this.log.info( "Exception when updating " + fD.getAbsolutePath() + " : " + e.getMessage());
rsp.add( "error", "Error when updating " + fD.getAbsolutePath() + " : " + e.getMessage() );
}
}
*/
}
}
// SolrCoreAware interface implementation - Start
public void inform(SolrCore core)
{
this.core = core;
Map<String,SearchComponent> availableSearchComponents = core.getSearchComponents();
for ( Iterator i=availableSearchComponents.entrySet().iterator(); i.hasNext(); )
{
Map.Entry e = (Map.Entry) i.next();
// Ugly hard-coded fully-qualified class name. Any workaround ?
if ( e.getValue().getClass().getName() == "org.apache.solr.handler.component.QueryElevationComponent" )
{
// Found the Query Elevation Component, store it as local property.
this.elevationComponent = (QueryElevationComponent) e.getValue();
break;
}
}
}
// SolrCoreAware interface implementation - End
// ////////////////////// SolrInfoMBeans methods //////////////////////
public String getDescription() {
return "eZFind's dedicated request Handler.";
}
public String getVersion() {
return "$Revision:$";
}
/** CVS Id, SVN Id, etc */
public String getSourceId() {
return "$Id:$";
}
/** CVS Source, SVN Source, etc */
public String getSource() {
return "$URL:$";
}
/**
* Simple common usage name, e.g. BasicQueryHandler,
* or fully qualified clas name.
*/
public String getName()
{
return "eZFindQueryHandler";
}
/** Purpose of this Class */
public Category getCategory()
{
return null;
}
/**
* Documentation URL list.
*
* <p>
* Suggested documentation URLs: Homepage for sponsoring project,
* FAQ on class usage, Design doc for class, Wiki, bug reporting URL, etc...
* </p>
*/
public URL[] getDocs()
{
return null;
}
/**
* Any statistics this instance would like to be publicly available via
* the Solr Administration interface.
*
* <p>
* Any Object type may be stored in the list, but only the
* <code>toString()</code> representation will be used.
* </p>
*/
public NamedList getStatistics()
{
return null;
}
}
| medbenhenda/migration-ez5 | ezpublish_legacy/extension/ezfind/java/src/ezfind/src/main/java/org/ezsystems/solr/handler/ezfind/eZFindRequestHandler.java | Java | gpl-2.0 | 9,623 |
class AddIncludeTl0InDigestsToUserOptions < ActiveRecord::Migration[4.2]
def change
add_column :user_options, :include_tl0_in_digests, :boolean, default: false
end
end
| gfvcastro/discourse | db/migrate/20160317201955_add_include_tl0_in_digests_to_user_options.rb | Ruby | gpl-2.0 | 176 |
<?php
/**
* @file
* Contains \Drupal\Console\Command\Generate\PluginTypeYamlCommand.
*/
namespace Drupal\Console\Command\Generate;
use Drupal\Console\Generator\PluginTypeYamlGenerator;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Drupal\Console\Command\ServicesTrait;
use Drupal\Console\Command\ModuleTrait;
use Drupal\Console\Command\FormTrait;
use Drupal\Console\Command\ConfirmationTrait;
use Drupal\Console\Command\GeneratorCommand;
use Drupal\Console\Style\DrupalStyle;
class PluginTypeYamlCommand extends GeneratorCommand
{
use ServicesTrait;
use ModuleTrait;
use FormTrait;
use ConfirmationTrait;
protected function configure()
{
$this
->setName('generate:plugin:type:yaml')
->setDescription($this->trans('commands.generate.plugin.type.yaml.description'))
->setHelp($this->trans('commands.generate.plugin.type.yaml.help'))
->addOption('module', '', InputOption::VALUE_REQUIRED, $this->trans('commands.common.options.module'))
->addOption(
'class',
'',
InputOption::VALUE_OPTIONAL,
$this->trans('commands.generate.plugin.type.yaml.options.class')
)
->addOption(
'plugin-name',
'',
InputOption::VALUE_OPTIONAL,
$this->trans('commands.generate.plugin.type.yaml.options.plugin-name')
)
->addOption(
'plugin-file-name',
'',
InputOption::VALUE_OPTIONAL,
$this->trans('commands.generate.plugin.type.yaml.options.plugin-file-name')
);
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$module = $input->getOption('module');
$class_name = $input->getOption('class');
$plugin_name = $input->getOption('plugin-name');
$plugin_file_name = $input->getOption('plugin-file-name');
$generator = $this->getGenerator();
$generator->generate($module, $class_name, $plugin_name, $plugin_file_name);
}
protected function interact(InputInterface $input, OutputInterface $output)
{
$io = new DrupalStyle($input, $output);
// --module option
$module = $input->getOption('module');
if (!$module) {
// @see Drupal\Console\Command\ModuleTrait::moduleQuestion
$module = $this->moduleQuestion($output);
$input->setOption('module', $module);
}
// --class option
$class_name = $input->getOption('class');
if (!$class_name) {
$class_name = $io->ask(
$this->trans('commands.generate.plugin.type.yaml.options.class'),
'ExamplePlugin'
);
$input->setOption('class', $class_name);
}
// --plugin-name option
$plugin_name = $input->getOption('plugin-name');
if (!$plugin_name) {
$plugin_name = $io->ask(
$this->trans('commands.generate.plugin.type.yaml.options.plugin-name'),
$this->getStringHelper()->camelCaseToUnderscore($class_name)
);
$input->setOption('plugin-name', $plugin_name);
}
// --plugin-file-name option
$plugin_file_name = $input->getOption('plugin-file-name');
if (!$plugin_file_name) {
$plugin_file_name = $io->ask(
$this->trans('commands.generate.plugin.type.yaml.options.plugin-file-name'),
strtr($plugin_name, '_-', '..')
);
$input->setOption('plugin-file-name', $plugin_file_name);
}
}
protected function createGenerator()
{
return new PluginTypeYamlGenerator();
}
}
| sgrichards/BrightonDrupal | vendor/drupal/console/src/Command/Generate/PluginTypeYamlCommand.php | PHP | gpl-2.0 | 3,969 |
<?php
use Action_Scheduler\WP_CLI\Migration_Command;
use Action_Scheduler\Migration\Controller;
/**
* Class ActionScheduler
* @codeCoverageIgnore
*/
abstract class ActionScheduler {
private static $plugin_file = '';
/** @var ActionScheduler_ActionFactory */
private static $factory = NULL;
/** @var bool */
private static $data_store_initialized = false;
public static function factory() {
if ( !isset(self::$factory) ) {
self::$factory = new ActionScheduler_ActionFactory();
}
return self::$factory;
}
public static function store() {
return ActionScheduler_Store::instance();
}
public static function lock() {
return ActionScheduler_Lock::instance();
}
public static function logger() {
return ActionScheduler_Logger::instance();
}
public static function runner() {
return ActionScheduler_QueueRunner::instance();
}
public static function admin_view() {
return ActionScheduler_AdminView::instance();
}
/**
* Get the absolute system path to the plugin directory, or a file therein
* @static
* @param string $path
* @return string
*/
public static function plugin_path( $path ) {
$base = dirname(self::$plugin_file);
if ( $path ) {
return trailingslashit($base).$path;
} else {
return untrailingslashit($base);
}
}
/**
* Get the absolute URL to the plugin directory, or a file therein
* @static
* @param string $path
* @return string
*/
public static function plugin_url( $path ) {
return plugins_url($path, self::$plugin_file);
}
public static function autoload( $class ) {
$d = DIRECTORY_SEPARATOR;
$classes_dir = self::plugin_path( 'classes' . $d );
$separator = strrpos( $class, '\\' );
if ( false !== $separator ) {
if ( 0 !== strpos( $class, 'Action_Scheduler' ) ) {
return;
}
$class = substr( $class, $separator + 1 );
}
if ( 'Deprecated' === substr( $class, -10 ) ) {
$dir = self::plugin_path( 'deprecated' . $d );
} elseif ( self::is_class_abstract( $class ) ) {
$dir = $classes_dir . 'abstracts' . $d;
} elseif ( self::is_class_migration( $class ) ) {
$dir = $classes_dir . 'migration' . $d;
} elseif ( 'Schedule' === substr( $class, -8 ) ) {
$dir = $classes_dir . 'schedules' . $d;
} elseif ( 'Action' === substr( $class, -6 ) ) {
$dir = $classes_dir . 'actions' . $d;
} elseif ( 'Schema' === substr( $class, -6 ) ) {
$dir = $classes_dir . 'schema' . $d;
} elseif ( strpos( $class, 'ActionScheduler' ) === 0 ) {
$segments = explode( '_', $class );
$type = isset( $segments[ 1 ] ) ? $segments[ 1 ] : '';
switch ( $type ) {
case 'WPCLI':
$dir = $classes_dir . 'WP_CLI' . $d;
break;
case 'DBLogger':
case 'DBStore':
case 'HybridStore':
case 'wpPostStore':
case 'wpCommentLogger':
$dir = $classes_dir . 'data-stores' . $d;
break;
default:
$dir = $classes_dir;
break;
}
} elseif ( self::is_class_cli( $class ) ) {
$dir = $classes_dir . 'WP_CLI' . $d;
} elseif ( strpos( $class, 'CronExpression' ) === 0 ) {
$dir = self::plugin_path( 'lib' . $d . 'cron-expression' . $d );
} elseif ( strpos( $class, 'WP_Async_Request' ) === 0 ) {
$dir = self::plugin_path( 'lib' . $d );
} else {
return;
}
if ( file_exists( "{$dir}{$class}.php" ) ) {
include( "{$dir}{$class}.php" );
return;
}
}
/**
* Initialize the plugin
*
* @static
* @param string $plugin_file
*/
public static function init( $plugin_file ) {
self::$plugin_file = $plugin_file;
spl_autoload_register( array( __CLASS__, 'autoload' ) );
/**
* Fires in the early stages of Action Scheduler init hook.
*/
do_action( 'action_scheduler_pre_init' );
require_once( self::plugin_path( 'functions.php' ) );
ActionScheduler_DataController::init();
$store = self::store();
$logger = self::logger();
$runner = self::runner();
$admin_view = self::admin_view();
// Ensure initialization on plugin activation.
if ( ! did_action( 'init' ) ) {
add_action( 'init', array( $admin_view, 'init' ), 0, 0 ); // run before $store::init()
add_action( 'init', array( $store, 'init' ), 1, 0 );
add_action( 'init', array( $logger, 'init' ), 1, 0 );
add_action( 'init', array( $runner, 'init' ), 1, 0 );
} else {
$admin_view->init();
$store->init();
$logger->init();
$runner->init();
}
if ( apply_filters( 'action_scheduler_load_deprecated_functions', true ) ) {
require_once( self::plugin_path( 'deprecated/functions.php' ) );
}
if ( defined( 'WP_CLI' ) && WP_CLI ) {
WP_CLI::add_command( 'action-scheduler', 'ActionScheduler_WPCLI_Scheduler_command' );
if ( ! ActionScheduler_DataController::is_migration_complete() && Controller::instance()->allow_migration() ) {
$command = new Migration_Command();
$command->register();
}
}
self::$data_store_initialized = true;
/**
* Handle WP comment cleanup after migration.
*/
if ( is_a( $logger, 'ActionScheduler_DBLogger' ) && ActionScheduler_DataController::is_migration_complete() && ActionScheduler_WPCommentCleaner::has_logs() ) {
ActionScheduler_WPCommentCleaner::init();
}
add_action( 'action_scheduler/migration_complete', 'ActionScheduler_WPCommentCleaner::maybe_schedule_cleanup' );
}
/**
* Check whether the AS data store has been initialized.
*
* @param string $function_name The name of the function being called. Optional. Default `null`.
* @return bool
*/
public static function is_initialized( $function_name = null ) {
if ( ! self::$data_store_initialized && ! empty( $function_name ) ) {
$message = sprintf( __( '%s() was called before the Action Scheduler data store was initialized', 'action-scheduler' ), esc_attr( $function_name ) );
error_log( $message, E_WARNING );
}
return self::$data_store_initialized;
}
/**
* Determine if the class is one of our abstract classes.
*
* @since 3.0.0
*
* @param string $class The class name.
*
* @return bool
*/
protected static function is_class_abstract( $class ) {
static $abstracts = array(
'ActionScheduler' => true,
'ActionScheduler_Abstract_ListTable' => true,
'ActionScheduler_Abstract_QueueRunner' => true,
'ActionScheduler_Abstract_Schedule' => true,
'ActionScheduler_Abstract_RecurringSchedule' => true,
'ActionScheduler_Lock' => true,
'ActionScheduler_Logger' => true,
'ActionScheduler_Abstract_Schema' => true,
'ActionScheduler_Store' => true,
'ActionScheduler_TimezoneHelper' => true,
);
return isset( $abstracts[ $class ] ) && $abstracts[ $class ];
}
/**
* Determine if the class is one of our migration classes.
*
* @since 3.0.0
*
* @param string $class The class name.
*
* @return bool
*/
protected static function is_class_migration( $class ) {
static $migration_segments = array(
'ActionMigrator' => true,
'BatchFetcher' => true,
'DBStoreMigrator' => true,
'DryRun' => true,
'LogMigrator' => true,
'Config' => true,
'Controller' => true,
'Runner' => true,
'Scheduler' => true,
);
$segments = explode( '_', $class );
$segment = isset( $segments[ 1 ] ) ? $segments[ 1 ] : $class;
return isset( $migration_segments[ $segment ] ) && $migration_segments[ $segment ];
}
/**
* Determine if the class is one of our WP CLI classes.
*
* @since 3.0.0
*
* @param string $class The class name.
*
* @return bool
*/
protected static function is_class_cli( $class ) {
static $cli_segments = array(
'QueueRunner' => true,
'Command' => true,
'ProgressBar' => true,
);
$segments = explode( '_', $class );
$segment = isset( $segments[ 1 ] ) ? $segments[ 1 ] : $class;
return isset( $cli_segments[ $segment ] ) && $cli_segments[ $segment ];
}
final public function __clone() {
trigger_error("Singleton. No cloning allowed!", E_USER_ERROR);
}
final public function __wakeup() {
trigger_error("Singleton. No serialization allowed!", E_USER_ERROR);
}
final private function __construct() {}
/** Deprecated **/
public static function get_datetime_object( $when = null, $timezone = 'UTC' ) {
_deprecated_function( __METHOD__, '2.0', 'wcs_add_months()' );
return as_get_datetime_object( $when, $timezone );
}
/**
* Issue deprecated warning if an Action Scheduler function is called in the shutdown hook.
*
* @param string $function_name The name of the function being called.
* @deprecated 3.1.6.
*/
public static function check_shutdown_hook( $function_name ) {
_deprecated_function( __FUNCTION__, '3.1.6' );
}
}
| rasken2003/fuga-it-business | wp-content/plugins/wp-mail-smtp/vendor/woocommerce/action-scheduler/classes/abstracts/ActionScheduler.php | PHP | gpl-2.0 | 8,752 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file defines the quiz overview report class.
*
* @package quiz_overview
* @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/mod/quiz/report/attemptsreport.php');
require_once($CFG->dirroot . '/mod/quiz/report/overview/overview_options.php');
require_once($CFG->dirroot . '/mod/quiz/report/overview/overview_form.php');
require_once($CFG->dirroot . '/mod/quiz/report/overview/overview_table.php');
/**
* Quiz report subclass for the overview (grades) report.
*
* @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class quiz_overview_report extends quiz_attempts_report {
/**
* @var bool whether there are actually students to show, given the options.
*/
protected $hasgroupstudents;
public function display($quiz, $cm, $course) {
global $DB, $OUTPUT, $PAGE;
list($currentgroup, $studentsjoins, $groupstudentsjoins, $allowedjoins) = $this->init(
'overview', 'quiz_overview_settings_form', $quiz, $cm, $course);
$options = new quiz_overview_options('overview', $quiz, $cm, $course);
if ($fromform = $this->form->get_data()) {
$options->process_settings_from_form($fromform);
} else {
$options->process_settings_from_params();
}
$this->form->set_data($options->get_initial_form_data());
// Load the required questions.
$questions = quiz_report_get_significant_questions($quiz);
// Prepare for downloading, if applicable.
$courseshortname = format_string($course->shortname, true,
array('context' => context_course::instance($course->id)));
$table = new quiz_overview_table($quiz, $this->context, $this->qmsubselect,
$options, $groupstudentsjoins, $studentsjoins, $questions, $options->get_url());
$filename = quiz_report_download_filename(get_string('overviewfilename', 'quiz_overview'),
$courseshortname, $quiz->name);
$table->is_downloading($options->download, $filename,
$courseshortname . ' ' . format_string($quiz->name, true));
if ($table->is_downloading()) {
raise_memory_limit(MEMORY_EXTRA);
}
$this->hasgroupstudents = false;
if (!empty($groupstudentsjoins->joins)) {
$sql = "SELECT DISTINCT u.id
FROM {user} u
$groupstudentsjoins->joins
WHERE $groupstudentsjoins->wheres";
$this->hasgroupstudents = $DB->record_exists_sql($sql, $groupstudentsjoins->params);
}
$hasstudents = false;
if (!empty($studentsjoins->joins)) {
$sql = "SELECT DISTINCT u.id
FROM {user} u
$studentsjoins->joins
WHERE $studentsjoins->wheres";
$hasstudents = $DB->record_exists_sql($sql, $studentsjoins->params);
}
if ($options->attempts == self::ALL_WITH) {
// This option is only available to users who can access all groups in
// groups mode, so setting allowed to empty (which means all quiz attempts
// are accessible, is not a security porblem.
$allowedjoins = new \core\dml\sql_join();
}
$this->course = $course; // Hack to make this available in process_actions.
$this->process_actions($quiz, $cm, $currentgroup, $groupstudentsjoins, $allowedjoins, $options->get_url());
$hasquestions = quiz_has_questions($quiz->id);
// Start output.
if (!$table->is_downloading()) {
// Only print headers if not asked to download data.
$this->print_standard_header_and_messages($cm, $course, $quiz,
$options, $currentgroup, $hasquestions, $hasstudents);
// Print the display options.
$this->form->display();
}
$hasstudents = $hasstudents && (!$currentgroup || $this->hasgroupstudents);
if ($hasquestions && ($hasstudents || $options->attempts == self::ALL_WITH)) {
// Construct the SQL.
$table->setup_sql_queries($allowedjoins);
if (!$table->is_downloading()) {
// Output the regrade buttons.
if (has_capability('mod/quiz:regrade', $this->context)) {
$regradesneeded = $this->count_question_attempts_needing_regrade(
$quiz, $groupstudentsjoins);
if ($currentgroup) {
$a= new stdClass();
$a->groupname = groups_get_group_name($currentgroup);
$a->coursestudents = get_string('participants');
$a->countregradeneeded = $regradesneeded;
$regradealldrydolabel =
get_string('regradealldrydogroup', 'quiz_overview', $a);
$regradealldrylabel =
get_string('regradealldrygroup', 'quiz_overview', $a);
$regradealllabel =
get_string('regradeallgroup', 'quiz_overview', $a);
} else {
$regradealldrydolabel =
get_string('regradealldrydo', 'quiz_overview', $regradesneeded);
$regradealldrylabel =
get_string('regradealldry', 'quiz_overview');
$regradealllabel =
get_string('regradeall', 'quiz_overview');
}
$displayurl = new moodle_url($options->get_url(), array('sesskey' => sesskey()));
echo '<div class="mdl-align">';
echo '<form action="'.$displayurl->out_omit_querystring().'">';
echo '<div>';
echo html_writer::input_hidden_params($displayurl);
echo '<input type="submit" class="btn btn-secondary" name="regradeall" value="'.$regradealllabel.'"/>';
echo '<input type="submit" class="btn btn-secondary ml-1" name="regradealldry" value="' .
$regradealldrylabel . '"/>';
if ($regradesneeded) {
echo '<input type="submit" class="btn btn-secondary ml-1" name="regradealldrydo" value="' .
$regradealldrydolabel . '"/>';
}
echo '</div>';
echo '</form>';
echo '</div>';
}
// Print information on the grading method.
if ($strattempthighlight = quiz_report_highlighting_grading_method(
$quiz, $this->qmsubselect, $options->onlygraded)) {
echo '<div class="quizattemptcounts">' . $strattempthighlight . '</div>';
}
}
// Define table columns.
$columns = array();
$headers = array();
if (!$table->is_downloading() && $options->checkboxcolumn) {
$columnname = 'checkbox';
$columns[] = $columnname;
$headers[] = $table->checkbox_col_header($columnname);
}
$this->add_user_columns($table, $columns, $headers);
$this->add_state_column($columns, $headers);
$this->add_time_columns($columns, $headers);
$this->add_grade_columns($quiz, $options->usercanseegrades, $columns, $headers, false);
if (!$table->is_downloading() && has_capability('mod/quiz:regrade', $this->context) &&
$this->has_regraded_questions($table->sql->from, $table->sql->where, $table->sql->params)) {
$columns[] = 'regraded';
$headers[] = get_string('regrade', 'quiz_overview');
}
if ($options->slotmarks) {
foreach ($questions as $slot => $question) {
// Ignore questions of zero length.
$columns[] = 'qsgrade' . $slot;
$header = get_string('qbrief', 'quiz', $question->number);
if (!$table->is_downloading()) {
$header .= '<br />';
} else {
$header .= ' ';
}
$header .= '/' . quiz_rescale_grade($question->maxmark, $quiz, 'question');
$headers[] = $header;
}
}
$this->set_up_table_columns($table, $columns, $headers, $this->get_base_url(), $options, false);
$table->set_attribute('class', 'generaltable generalbox grades');
$table->out($options->pagesize, true);
}
if (!$table->is_downloading() && $options->usercanseegrades) {
$output = $PAGE->get_renderer('mod_quiz');
list($bands, $bandwidth) = self::get_bands_count_and_width($quiz);
$labels = self::get_bands_labels($bands, $bandwidth, $quiz);
if ($currentgroup && $this->hasgroupstudents) {
$sql = "SELECT qg.id
FROM {quiz_grades} qg
JOIN {user} u on u.id = qg.userid
{$groupstudentsjoins->joins}
WHERE qg.quiz = $quiz->id AND {$groupstudentsjoins->wheres}";
if ($DB->record_exists_sql($sql, $groupstudentsjoins->params)) {
$data = quiz_report_grade_bands($bandwidth, $bands, $quiz->id, $groupstudentsjoins);
$chart = self::get_chart($labels, $data);
$graphname = get_string('overviewreportgraphgroup', 'quiz_overview', groups_get_group_name($currentgroup));
echo $output->chart($chart, $graphname);
}
}
if ($DB->record_exists('quiz_grades', array('quiz'=> $quiz->id))) {
$data = quiz_report_grade_bands($bandwidth, $bands, $quiz->id, new \core\dml\sql_join());
$chart = self::get_chart($labels, $data);
$graphname = get_string('overviewreportgraph', 'quiz_overview');
echo $output->chart($chart, $graphname);
}
}
return true;
}
/**
* Extends parent function processing any submitted actions.
*
* @param object $quiz
* @param object $cm
* @param int $currentgroup
* @param \core\dml\sql_join $groupstudentsjoins (joins, wheres, params)
* @param \core\dml\sql_join $allowedjoins (joins, wheres, params)
* @param moodle_url $redirecturl
*/
protected function process_actions($quiz, $cm, $currentgroup, \core\dml\sql_join $groupstudentsjoins,
\core\dml\sql_join $allowedjoins, $redirecturl) {
parent::process_actions($quiz, $cm, $currentgroup, $groupstudentsjoins, $allowedjoins, $redirecturl);
if (empty($currentgroup) || $this->hasgroupstudents) {
if (optional_param('regrade', 0, PARAM_BOOL) && confirm_sesskey()) {
if ($attemptids = optional_param_array('attemptid', array(), PARAM_INT)) {
$this->start_regrade($quiz, $cm);
$this->regrade_attempts($quiz, false, $groupstudentsjoins, $attemptids);
$this->finish_regrade($redirecturl);
}
}
}
if (optional_param('regradeall', 0, PARAM_BOOL) && confirm_sesskey()) {
$this->start_regrade($quiz, $cm);
$this->regrade_attempts($quiz, false, $groupstudentsjoins);
$this->finish_regrade($redirecturl);
} else if (optional_param('regradealldry', 0, PARAM_BOOL) && confirm_sesskey()) {
$this->start_regrade($quiz, $cm);
$this->regrade_attempts($quiz, true, $groupstudentsjoins);
$this->finish_regrade($redirecturl);
} else if (optional_param('regradealldrydo', 0, PARAM_BOOL) && confirm_sesskey()) {
$this->start_regrade($quiz, $cm);
$this->regrade_attempts_needing_it($quiz, $groupstudentsjoins);
$this->finish_regrade($redirecturl);
}
}
/**
* Check necessary capabilities, and start the display of the regrade progress page.
* @param object $quiz the quiz settings.
* @param object $cm the cm object for the quiz.
*/
protected function start_regrade($quiz, $cm) {
require_capability('mod/quiz:regrade', $this->context);
$this->print_header_and_tabs($cm, $this->course, $quiz, $this->mode);
}
/**
* Finish displaying the regrade progress page.
* @param moodle_url $nexturl where to send the user after the regrade.
* @uses exit. This method never returns.
*/
protected function finish_regrade($nexturl) {
global $OUTPUT;
\core\notification::success(get_string('regradecomplete', 'quiz_overview'));
echo $OUTPUT->continue_button($nexturl);
echo $OUTPUT->footer();
die();
}
/**
* Unlock the session and allow the regrading process to run in the background.
*/
protected function unlock_session() {
\core\session\manager::write_close();
ignore_user_abort(true);
}
/**
* Regrade a particular quiz attempt. Either for real ($dryrun = false), or
* as a pretend regrade to see which fractions would change. The outcome is
* stored in the quiz_overview_regrades table.
*
* Note, $attempt is not upgraded in the database. The caller needs to do that.
* However, $attempt->sumgrades is updated, if this is not a dry run.
*
* @param object $attempt the quiz attempt to regrade.
* @param bool $dryrun if true, do a pretend regrade, otherwise do it for real.
* @param array $slots if null, regrade all questions, otherwise, just regrade
* the quetsions with those slots.
*/
protected function regrade_attempt($attempt, $dryrun = false, $slots = null) {
global $DB;
// Need more time for a quiz with many questions.
core_php_time_limit::raise(300);
$transaction = $DB->start_delegated_transaction();
$quba = question_engine::load_questions_usage_by_activity($attempt->uniqueid);
if (is_null($slots)) {
$slots = $quba->get_slots();
}
$finished = $attempt->state == quiz_attempt::FINISHED;
foreach ($slots as $slot) {
$qqr = new stdClass();
$qqr->oldfraction = $quba->get_question_fraction($slot);
$quba->regrade_question($slot, $finished);
$qqr->newfraction = $quba->get_question_fraction($slot);
if (abs($qqr->oldfraction - $qqr->newfraction) > 1e-7) {
$qqr->questionusageid = $quba->get_id();
$qqr->slot = $slot;
$qqr->regraded = empty($dryrun);
$qqr->timemodified = time();
$DB->insert_record('quiz_overview_regrades', $qqr, false);
}
}
if (!$dryrun) {
question_engine::save_questions_usage_by_activity($quba);
}
$transaction->allow_commit();
// Really, PHP should not need this hint, but without this, we just run out of memory.
$quba = null;
$transaction = null;
gc_collect_cycles();
}
/**
* Regrade attempts for this quiz, exactly which attempts are regraded is
* controlled by the parameters.
* @param object $quiz the quiz settings.
* @param bool $dryrun if true, do a pretend regrade, otherwise do it for real.
* @param \core\dml\sql_join|array $groupstudentsjoins empty for all attempts, otherwise regrade attempts
* for these users.
* @param array $attemptids blank for all attempts, otherwise only regrade
* attempts whose id is in this list.
*/
protected function regrade_attempts($quiz, $dryrun = false,
\core\dml\sql_join$groupstudentsjoins = null, $attemptids = array()) {
global $DB;
$this->unlock_session();
$sql = "SELECT quiza.*, " . get_all_user_name_fields(true, 'u') . "
FROM {quiz_attempts} quiza
JOIN {user} u ON u.id = quiza.userid";
$where = "quiz = :qid AND preview = 0";
$params = array('qid' => $quiz->id);
if ($this->hasgroupstudents && !empty($groupstudentsjoins->joins)) {
$sql .= "\n{$groupstudentsjoins->joins}";
$where .= " AND {$groupstudentsjoins->wheres}";
$params += $groupstudentsjoins->params;
}
if ($attemptids) {
list($attemptidcondition, $attemptidparams) = $DB->get_in_or_equal($attemptids, SQL_PARAMS_NAMED);
$where .= " AND quiza.id $attemptidcondition";
$params += $attemptidparams;
}
$sql .= "\nWHERE {$where}";
$attempts = $DB->get_records_sql($sql, $params);
if (!$attempts) {
return;
}
$this->regrade_batch_of_attempts($quiz, $attempts, $dryrun, $groupstudentsjoins);
}
/**
* Regrade those questions in those attempts that are marked as needing regrading
* in the quiz_overview_regrades table.
* @param object $quiz the quiz settings.
* @param \core\dml\sql_join $groupstudentsjoins empty for all attempts, otherwise regrade attempts
* for these users.
*/
protected function regrade_attempts_needing_it($quiz, \core\dml\sql_join $groupstudentsjoins) {
global $DB;
$this->unlock_session();
$join = '{quiz_overview_regrades} qqr ON qqr.questionusageid = quiza.uniqueid';
$where = "quiza.quiz = :qid AND quiza.preview = 0 AND qqr.regraded = 0";
$params = array('qid' => $quiz->id);
// Fetch all attempts that need regrading.
if ($this->hasgroupstudents && !empty($groupstudentsjoins->joins)) {
$join .= "\nJOIN {user} u ON u.id = quiza.userid
{$groupstudentsjoins->joins}";
$where .= " AND {$groupstudentsjoins->wheres}";
$params += $groupstudentsjoins->params;
}
$toregrade = $DB->get_recordset_sql("
SELECT quiza.uniqueid, qqr.slot
FROM {quiz_attempts} quiza
JOIN $join
WHERE $where", $params);
$attemptquestions = array();
foreach ($toregrade as $row) {
$attemptquestions[$row->uniqueid][] = $row->slot;
}
$toregrade->close();
if (!$attemptquestions) {
return;
}
list($uniqueidcondition, $params) = $DB->get_in_or_equal(array_keys($attemptquestions));
$attempts = $DB->get_records_sql("
SELECT quiza.*, " . get_all_user_name_fields(true, 'u') . "
FROM {quiz_attempts} quiza
JOIN {user} u ON u.id = quiza.userid
WHERE quiza.uniqueid $uniqueidcondition
", $params);
foreach ($attempts as $attempt) {
$attempt->regradeonlyslots = $attemptquestions[$attempt->uniqueid];
}
$this->regrade_batch_of_attempts($quiz, $attempts, false, $groupstudentsjoins);
}
/**
* This is a helper used by {@link regrade_attempts()} and
* {@link regrade_attempts_needing_it()}.
*
* Given an array of attempts, it regrades them all, or does a dry run.
* Each object in the attempts array must be a row from the quiz_attempts
* table, with the get_all_user_name_fields from the user table joined in.
* In addition, if $attempt->regradeonlyslots is set, then only those slots
* are regraded, otherwise all slots are regraded.
*
* @param object $quiz the quiz settings.
* @param array $attempts of data from the quiz_attempts table, with extra data as above.
* @param bool $dryrun if true, do a pretend regrade, otherwise do it for real.
* @param \core\dml\sql_join $groupstudentsjoins empty for all attempts, otherwise regrade attempts
*/
protected function regrade_batch_of_attempts($quiz, array $attempts,
bool $dryrun, \core\dml\sql_join $groupstudentsjoins) {
$this->clear_regrade_table($quiz, $groupstudentsjoins);
$progressbar = new progress_bar('quiz_overview_regrade', 500, true);
$a = array(
'count' => count($attempts),
'done' => 0,
);
foreach ($attempts as $attempt) {
$a['done']++;
$a['attemptnum'] = $attempt->attempt;
$a['name'] = fullname($attempt);
$a['attemptid'] = $attempt->id;
if (!isset($attempt->regradeonlyslots)) {
$attempt->regradeonlyslots = null;
}
$progressbar->update($a['done'], $a['count'],
get_string('regradingattemptxofywithdetails', 'quiz_overview', $a));
$this->regrade_attempt($attempt, $dryrun, $attempt->regradeonlyslots);
}
$progressbar->update($a['done'], $a['count'],
get_string('regradedsuccessfullyxofy', 'quiz_overview', $a));
if (!$dryrun) {
$this->update_overall_grades($quiz);
}
}
/**
* Count the number of attempts in need of a regrade.
*
* @param object $quiz the quiz settings.
* @param \core\dml\sql_join $groupstudentsjoins (joins, wheres, params) If this is given, only data relating
* to these users is cleared.
* @return int the number of attempts.
*/
protected function count_question_attempts_needing_regrade($quiz, \core\dml\sql_join $groupstudentsjoins) {
global $DB;
$userjoin = '';
$usertest = '';
$params = array();
if ($this->hasgroupstudents) {
$userjoin = "JOIN {user} u ON u.id = quiza.userid
{$groupstudentsjoins->joins}";
$usertest = "{$groupstudentsjoins->wheres} AND u.id = quiza.userid AND ";
$params = $groupstudentsjoins->params;
}
$params['cquiz'] = $quiz->id;
$sql = "SELECT COUNT(DISTINCT quiza.id)
FROM {quiz_attempts} quiza
JOIN {quiz_overview_regrades} qqr ON quiza.uniqueid = qqr.questionusageid
$userjoin
WHERE
$usertest
quiza.quiz = :cquiz AND
quiza.preview = 0 AND
qqr.regraded = 0";
return $DB->count_records_sql($sql, $params);
}
/**
* Are there any pending regrades in the table we are going to show?
* @param string $from tables used by the main query.
* @param string $where where clause used by the main query.
* @param array $params required by the SQL.
* @return bool whether there are pending regrades.
*/
protected function has_regraded_questions($from, $where, $params) {
global $DB;
return $DB->record_exists_sql("
SELECT 1
FROM {$from}
JOIN {quiz_overview_regrades} qor ON qor.questionusageid = quiza.uniqueid
WHERE {$where}", $params);
}
/**
* Remove all information about pending/complete regrades from the database.
* @param object $quiz the quiz settings.
* @param \core\dml\sql_join $groupstudentsjoins (joins, wheres, params). If this is given, only data relating
* to these users is cleared.
*/
protected function clear_regrade_table($quiz, \core\dml\sql_join $groupstudentsjoins) {
global $DB;
// Fetch all attempts that need regrading.
$select = "questionusageid IN (
SELECT uniqueid
FROM {quiz_attempts} quiza";
$where = "WHERE quiza.quiz = :qid";
$params = array('qid' => $quiz->id);
if ($this->hasgroupstudents && !empty($groupstudentsjoins->joins)) {
$select .= "\nJOIN {user} u ON u.id = quiza.userid
{$groupstudentsjoins->joins}";
$where .= " AND {$groupstudentsjoins->wheres}";
$params += $groupstudentsjoins->params;
}
$select .= "\n$where)";
$DB->delete_records_select('quiz_overview_regrades', $select, $params);
}
/**
* Update the final grades for all attempts. This method is used following
* a regrade.
* @param object $quiz the quiz settings.
* @param array $userids only update scores for these userids.
* @param array $attemptids attemptids only update scores for these attempt ids.
*/
protected function update_overall_grades($quiz) {
quiz_update_all_attempt_sumgrades($quiz);
quiz_update_all_final_grades($quiz);
quiz_update_grades($quiz);
}
/**
* Get the bands configuration for the quiz.
*
* This returns the configuration for having between 11 and 20 bars in
* a chart based on the maximum grade to be given on a quiz. The width of
* a band is the number of grade points it encapsulates.
*
* @param object $quiz The quiz object.
* @return array Contains the number of bands, and their width.
*/
public static function get_bands_count_and_width($quiz) {
$bands = $quiz->grade;
while ($bands > 20 || $bands <= 10) {
if ($bands > 50) {
$bands /= 5;
} else if ($bands > 20) {
$bands /= 2;
}
if ($bands < 4) {
$bands *= 5;
} else if ($bands <= 10) {
$bands *= 2;
}
}
// See MDL-34589. Using doubles as array keys causes problems in PHP 5.4, hence the explicit cast to int.
$bands = (int) ceil($bands);
return [$bands, $quiz->grade / $bands];
}
/**
* Get the bands labels.
*
* @param int $bands The number of bands.
* @param int $bandwidth The band width.
* @param object $quiz The quiz object.
* @return string[] The labels.
*/
public static function get_bands_labels($bands, $bandwidth, $quiz) {
$bandlabels = [];
for ($i = 1; $i <= $bands; $i++) {
$bandlabels[] = quiz_format_grade($quiz, ($i - 1) * $bandwidth) . ' - ' . quiz_format_grade($quiz, $i * $bandwidth);
}
return $bandlabels;
}
/**
* Get a chart.
*
* @param string[] $labels Chart labels.
* @param int[] $data The data.
* @return \core\chart_base
*/
protected static function get_chart($labels, $data) {
$chart = new \core\chart_bar();
$chart->set_labels($labels);
$chart->get_xaxis(0, true)->set_label(get_string('grade'));
$yaxis = $chart->get_yaxis(0, true);
$yaxis->set_label(get_string('participants'));
$yaxis->set_stepsize(max(1, round(max($data) / 10)));
$series = new \core\chart_series(get_string('participants'), $data);
$chart->add_series($series);
return $chart;
}
}
| evltuma/moodle | mod/quiz/report/overview/report.php | PHP | gpl-3.0 | 28,104 |
import { ElementRef, EventEmitter, NgZone, Renderer } from '@angular/core';
import { Config } from '../../config/config';
import { Ion } from '../ion';
import { Platform } from '../../platform/platform';
import { SlideContainer, SlideElement, SlideTouchEvents, SlideTouches, SlideZoom } from './swiper/swiper-interfaces';
import { ViewController } from '../../navigation/view-controller';
/**
* @name Slides
* @description
* The Slides component is a multi-section container. Each section can be swiped
* or dragged between. It contains any number of [Slide](../Slide) components.
*
*
* ### Creating
* You should use a template to create slides and listen to slide events. The template
* should contain the slide container, an `<ion-slides>` element, and any number of
* [Slide](../Slide) components, written as `<ion-slide>`. Basic configuration
* values can be set as input properties, which are listed below. Slides events
* can also be listened to such as the slide changing by placing the event on the
* `<ion-slides>` element. See [Usage](#usage) below for more information.
*
*
* ### Navigating
* After creating and configuring the slides, you can navigate between them
* by swiping or calling methods on the `Slides` instance. You can call `slideTo()` to
* navigate to a specific slide, or `slideNext()` to change to the slide that follows
* the active slide. All of the [methods](#instance-members) provided by the `Slides`
* instance are listed below. See [Usage](#usage) below for more information on
* navigating between slides.
*
*
* @usage
*
* You can add slides to a `@Component` using the following template:
*
* ```html
* <ion-slides>
* <ion-slide>
* <h1>Slide 1</h1>
* </ion-slide>
* <ion-slide>
* <h1>Slide 2</h1>
* </ion-slide>
* <ion-slide>
* <h1>Slide 3</h1>
* </ion-slide>
* </ion-slides>
* ```
*
* Next, we can use `ViewChild` to assign the Slides instance to
* your `slides` property. Now we can call any of the `Slides`
* [methods](#instance-members), for example we can use the Slide's
* `slideTo()` method in order to navigate to a specific slide on
* a button click. Below we call the `goToSlide()` method and it
* navigates to the 3rd slide:
*
* ```ts
* import { ViewChild } from '@angular/core';
*
* class MyPage {
* @ViewChild(Slides) slides: Slides;
*
* goToSlide() {
* this.slides.slideTo(2, 500);
* }
* }
* ```
*
* We can also add events to listen to on the `<ion-slides>` element.
* Let's add the `ionSlideDidChange` event and call a method when the slide changes:
*
* ```html
* <ion-slides (ionSlideDidChange)="slideChanged()">
* ```
*
* In our class, we add the `slideChanged()` method which gets the active
* index and prints it:
*
* ```ts
* class MyPage {
* ...
*
* slideChanged() {
* let currentIndex = this.slides.getActiveIndex();
* console.log("Current index is", currentIndex);
* }
* }
* ```
*
* @demo /docs/v2/demos/src/slides/
* @see {@link /docs/v2/components#slides Slides Component Docs}
*
* Adopted from Swiper.js:
* The most modern mobile touch slider and framework with
* hardware accelerated transitions.
*
* http://www.idangero.us/swiper/
*
* Copyright 2016, Vladimir Kharlampidi
* The iDangero.us
* http://www.idangero.us/
*
* Licensed under MIT
*/
export declare class Slides extends Ion {
private _plt;
/**
* @input {number} Delay between transitions (in milliseconds). If this
* parameter is not passed, autoplay is disabled. Default does
* not have a value and does not autoplay.
* Default: `null`.
*/
autoplay: any;
private _autoplayMs;
/**
* @input {string} Could be `slide`, `fade`, `cube`, `coverflow` or `flip`.
* Default: `slide`.
*/
effect: string;
private _effectName;
/**
* @input {string} Swipe direction: 'horizontal' or 'vertical'.
* Default: `horizontal`.
*/
direction: string;
private _direction;
/**
* @input {number} Index number of initial slide. Default: `0`.
*/
initialSlide: any;
private _initialSlide;
/**
* @input {boolean} Whether to continuously loop from the last slide to the
* first slide. Default: `false`.
*/
loop: boolean;
private _isLoop;
/**
* @input {boolean} String with type of pagination. Can be
* `bullets`, `fraction`, `progress`. Default does not have
* pagination set.
*/
pager: boolean;
private _pager;
/**
* @input {boolean} String with type of pagination. Can be
* `bullets`, `fraction`, `progress`. Default: `bullets`.
* (Note that the pager will not show unless `pager` input
* is set to true).
*/
paginationType: string;
private _paginationType;
/**
* @input {boolean} Enable, if you want to use "parallaxed" elements inside of
* slider. Default: `false`.
*/
parallax: boolean;
private _isParallax;
/**
* @input {number} Duration of transition between slides
* (in milliseconds). Default: `300`.
*/
speed: any;
private _speedMs;
/**
* @input {boolean} Set to `true` to enable zooming functionality.
* Default: `false`.
*/
zoom: boolean;
private _isZoom;
/**
* @private
* Height of container.
*/
height: number;
/**
* @private
* Width of container.
*/
width: number;
/**
* @private
* Enabled this option and swiper will be operated as usual except it will
* not move, real translate values on wrapper will not be set. Useful when
* you may need to create custom slide transition.
*/
virtualTranslate: boolean;
/**
* @private
* Set to true to round values of slides width and height to prevent blurry
* texts on usual resolution screens (if you have such)
*/
roundLengths: boolean;
/**
* @private
*/
spaceBetween: number;
/**
* @private
*/
slidesPerView: number | string;
/**
* @private
*/
slidesPerColumn: number;
/**
* @private
*/
slidesPerColumnFill: string;
/**
* @private
*/
slidesPerGroup: number;
/**
* @private
*/
centeredSlides: boolean;
/**
* @private
*/
slidesOffsetBefore: number;
/**
* @private
*/
slidesOffsetAfter: number;
/**
* @private
*/
touchEventsTarget: 'container';
/**
* @private
*/
autoplayDisableOnInteraction: boolean;
/**
* @private
*/
autoplayStopOnLast: boolean;
/**
* @private
*/
freeMode: boolean;
/**
* @private
*/
freeModeMomentum: boolean;
/**
* @private
*/
freeModeMomentumRatio: number;
/**
* @private
*/
freeModeMomentumBounce: boolean;
/**
* @private
*/
freeModeMomentumBounceRatio: number;
/**
* @private
*/
freeModeMomentumVelocityRatio: number;
/**
* @private
*/
freeModeSticky: boolean;
/**
* @private
*/
freeModeMinimumVelocity: number;
/**
* @private
*/
autoHeight: boolean;
/**
* @private
*/
setWrapperSize: boolean;
/**
* @private
*/
zoomMax: number;
/**
* @private
*/
zoomMin: number;
/**
* @private
*/
zoomToggle: boolean;
/**
* @private
*/
touchRatio: number;
/**
* @private
*/
touchAngle: number;
/**
* @private
*/
simulateTouch: boolean;
/**
* @private
*/
shortSwipes: boolean;
/**
* @private
*/
longSwipes: boolean;
/**
* @private
*/
longSwipesRatio: number;
/**
* @private
*/
longSwipesMs: number;
/**
* @private
*/
followFinger: boolean;
/**
* @private
*/
onlyExternal: boolean;
/**
* @private
*/
threshold: number;
/**
* @private
*/
touchMoveStopPropagation: boolean;
/**
* @private
*/
touchReleaseOnEdges: boolean;
/**
* @private
*/
iOSEdgeSwipeDetection: boolean;
/**
* @private
*/
iOSEdgeSwipeThreshold: number;
/**
* @private
*/
paginationClickable: boolean;
/**
* @private
*/
paginationHide: boolean;
resistance: boolean;
resistanceRatio: number;
watchSlidesProgress: boolean;
watchSlidesVisibility: boolean;
/**
* @private
*/
preventClicks: boolean;
/**
* @private
*/
preventClicksPropagation: boolean;
/**
* @private
*/
slideToClickedSlide: boolean;
/**
* @private
*/
loopAdditionalSlides: number;
/**
* @private
*/
loopedSlides: any;
/**
* @private
*/
swipeHandler: any;
/**
* @private
*/
noSwiping: boolean;
runCallbacksOnInit: boolean;
/**
* @private
*/
keyboardControl: boolean;
/**
* @private
*/
coverflow: {
rotate: number;
stretch: number;
depth: number;
modifier: number;
slideShadows: boolean;
};
/**
* @private
*/
flip: {
slideShadows: boolean;
limitRotation: boolean;
};
/**
* @private
*/
cube: {
slideShadows: boolean;
shadow: boolean;
shadowOffset: number;
shadowScale: number;
};
/**
* @private
*/
fade: {
crossFade: boolean;
};
/**
* @private
*/
prevSlideMessage: string;
/**
* @private
*/
nextSlideMessage: string;
/**
* @private
*/
firstSlideMessage: string;
/**
* @private
*/
lastSlideMessage: string;
/**
* @private
*/
originalEvent: any;
/**
* @output {Slides} Expression to evaluate when a slide change starts.
*/
ionSlideWillChange: EventEmitter<Slides>;
/**
* @output {Slides} Expression to evaluate when a slide change ends.
*/
ionSlideDidChange: EventEmitter<Slides>;
/**
* @output {Slides} Expression to evaluate when a slide moves.
*/
ionSlideDrag: EventEmitter<Slides>;
/**
* @output {Slides} When slides reach its beginning (initial position).
*/
ionSlideReachStart: EventEmitter<Slides>;
/**
* @output {Slides} When slides reach its last slide.
*/
ionSlideReachEnd: EventEmitter<Slides>;
/**
* @output {Slides} Expression to evaluate when a slide moves.
*/
ionSlideAutoplay: EventEmitter<Slides>;
/**
* @output {Slides} Same as `ionSlideWillChange` but caused by autoplay.
*/
ionSlideAutoplayStart: EventEmitter<Slides>;
/**
* @output {Slides} Expression to evaluate when a autoplay stops.
*/
ionSlideAutoplayStop: EventEmitter<Slides>;
/**
* @output {Slides} Same as `ionSlideWillChange` but for "forward" direction only.
*/
ionSlideNextStart: EventEmitter<Slides>;
/**
* @output {Slides} Same as `ionSlideWillChange` but for "backward" direction only.
*/
ionSlidePrevStart: EventEmitter<Slides>;
/**
* @output {Slides} Same as `ionSlideDidChange` but for "forward" direction only.
*/
ionSlideNextEnd: EventEmitter<Slides>;
/**
* @output {Slides} Same as `ionSlideDidChange` but for "backward" direction only.
*/
ionSlidePrevEnd: EventEmitter<Slides>;
/**
* @output {Slides} When the user taps/clicks on the slide's container.
*/
ionSlideTap: EventEmitter<Slides>;
/**
* @output {Slides} When the user double taps on the slide's container.
*/
ionSlideDoubleTap: EventEmitter<Slides>;
/** @private */
ionSlideProgress: EventEmitter<number>;
/** @private */
ionSlideTransitionStart: EventEmitter<Slides>;
/** @private */
ionSlideTransitionEnd: EventEmitter<Slides>;
/** @private */
ionSlideTouchStart: EventEmitter<TouchEvent>;
/** @private */
ionSlideTouchEnd: EventEmitter<TouchEvent>;
/**
* @private
* Deprecated
*/
options: any;
/**
* @private
* Deprecated: Use "ionSlideWillChange" instead.
* Added 2016-12-29
*/
readonly ionWillChange: EventEmitter<{}>;
/**
* @private
* Deprecated: Use "ionSlideDidChange" instead.
* Added 2016-12-29
*/
readonly ionDidChange: EventEmitter<{}>;
/**
* @private
* Deprecated: Use "ionSlideDrag" instead.
* Added 2016-12-29
*/
readonly ionDrag: EventEmitter<{}>;
/**
* Private properties only useful to this class.
* ------------------------------------
*/
private _init;
private _tmr;
private _unregs;
/**
* Properties that are exposed publically but no docs.
* ------------------------------------
*/
/** @private */
clickedIndex: number;
/** @private */
clickedSlide: SlideElement;
/** @private */
container: SlideContainer;
/** @private */
id: number;
/** @private */
progress: number;
/** @private */
realIndex: number;
/** @private */
renderedHeight: number;
/** @private */
renderedWidth: number;
/** @private */
slideId: string;
/** @private */
swipeDirection: string;
/** @private */
velocity: number;
/**
* Properties which are for internal use only
* and not exposed to the public
* ------------------------------------
*/
/** @internal */
_activeIndex: number;
/** @internal */
_allowClick: boolean;
/** @internal */
_allowSwipeToNext: boolean;
/** @internal */
_allowSwipeToPrev: boolean;
/** @internal */
_animating: boolean;
/** @internal */
_autoplaying: boolean;
/** @internal */
_autoplayPaused: boolean;
/** @internal */
_autoplayTimeoutId: number;
/** @internal */
_bullets: HTMLElement[];
/** @internal */
_classNames: string[];
/** @internal */
_isBeginning: boolean;
/** @internal */
_isEnd: boolean;
/** @internal */
_keyboardUnReg: Function;
/** @internal */
_liveRegion: HTMLElement;
/** @internal */
_paginationContainer: HTMLElement;
/** @internal */
_previousIndex: number;
/** @internal */
_renderedSize: number;
/** @internal */
_rtl: boolean;
/** @internal */
_slides: SlideElement[];
/** @internal */
_snapGrid: any;
/** @internal */
_slidesGrid: any;
/** @internal */
_snapIndex: number;
/** @internal */
_slidesSizesGrid: any;
/** @internal */
_supportTouch: boolean;
/** @internal */
_supportGestures: boolean;
/** @internal */
_touches: SlideTouches;
/** @internal */
_touchEvents: SlideTouchEvents;
/** @internal */
_touchEventsDesktop: SlideTouchEvents;
/** @internal */
_translate: number;
/** @internal */
_virtualSize: any;
/** @internal */
_wrapper: HTMLElement;
/** @internal */
_zone: NgZone;
/** @internal */
_zoom: SlideZoom;
nextButton: HTMLElement;
prevButton: HTMLElement;
constructor(config: Config, _plt: Platform, zone: NgZone, viewCtrl: ViewController, elementRef: ElementRef, renderer: Renderer);
private _initSlides();
/**
* @private
*/
ngAfterContentInit(): void;
/**
* @private
* Update the underlying slider implementation. Call this if you've added or removed
* child slides.
*/
update(debounce?: number): void;
/**
* Transition to the specified slide.
*
* @param {number} index The index number of the slide.
* @param {number} [speed] Transition duration (in ms).
* @param {boolean} [runCallbacks] Whether or not to emit the `ionWillChange`/`ionDidChange` events. Default true.
*/
slideTo(index: number, speed?: number, runCallbacks?: boolean): void;
/**
* Transition to the next slide.
*
* @param {number} [speed] Transition duration (in ms).
* @param {boolean} [runCallbacks] Whether or not to emit the `ionWillChange`/`ionDidChange` events. Default true.
*/
slideNext(speed?: number, runCallbacks?: boolean): void;
/**
* Transition to the previous slide.
*
* @param {number} [speed] Transition duration (in ms).
* @param {boolean} [runCallbacks] Whether or not to emit the `ionWillChange`/`ionDidChange` events. Default true.
*/
slidePrev(speed?: number, runCallbacks?: boolean): void;
/**
* Get the index of the active slide.
*
* @returns {number} The index number of the current slide.
*/
getActiveIndex(): number;
/**
* Get the index of the previous slide.
*
* @returns {number} The index number of the previous slide.
*/
getPreviousIndex(): number;
/**
* Get the total number of slides.
*
* @returns {number} The total number of slides.
*/
length(): number;
/**
* Get whether or not the current slide is the last slide.
*
* @returns {boolean} If the slide is the last slide or not.
*/
isEnd(): boolean;
/**
* Get whether or not the current slide is the first slide.
*
* @returns {boolean} If the slide is the first slide or not.
*/
isBeginning(): boolean;
/**
* Start auto play.
*/
startAutoplay(): void;
/**
* Stop auto play.
*/
stopAutoplay(): void;
/**
* Lock or unlock the ability to slide to the next slides.
*/
lockSwipeToNext(shouldLockSwipeToNext: boolean): void;
/**
* Lock or unlock the ability to slide to the previous slides.
*/
lockSwipeToPrev(shouldLockSwipeToPrev: boolean): void;
/**
* Lock or unlock the ability to slide to change slides.
*/
lockSwipes(shouldLockSwipes: boolean): void;
/**
* Enable or disable keyboard control.
*/
enableKeyboardControl(shouldEnableKeyboard: boolean): void;
/**
* @private
*/
ngOnDestroy(): void;
/**
* @private
* Deprecated, please use the instance of ion-slides.
*/
getSlider(): void;
}
| chitranshi21/home_service_ionic | node_modules/ionic-angular/umd/components/slides/slides.d.ts | TypeScript | gpl-3.0 | 18,338 |
<?php
/**
* interface/therapy_groups/therapy_groups_controllers/participants_controller.php contains the participants controller for therapy groups.
*
* This is the controller for the groups' participant view.
*
* Copyright (C) 2016 Shachar Zilbershlag <shaharzi@matrix.co.il>
* Copyright (C) 2016 Amiel Elboim <amielel@matrix.co.il>
*
* LICENSE: This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>;.
*
* @package OpenEMR
* @author Shachar Zilbershlag <shaharzi@matrix.co.il>
* @author Amiel Elboim <amielel@matrix.co.il>
* @link http://www.open-emr.org
*/
require_once dirname(__FILE__) . '/base_controller.php';
require_once dirname(__FILE__) . '/therapy_groups_controller.php';
require_once("{$GLOBALS['srcdir']}/pid.inc");
class ParticipantsController extends BaseController
{
public function __construct()
{
$this->groupParticipantsModel = $this->loadModel('therapy_groups_participants');
$this->groupEventsModel = $this->loadModel('Therapy_Groups_Events');
$this->groupModel = $this->loadModel('therapy_groups');
}
public function index($groupId, $data = array())
{
if (isset($_POST['save'])) {
for ($k = 0; $k < count($_POST['pid']); $k++) {
$patient['pid'] = $_POST['pid'][$k];
$patient['group_patient_status'] = $_POST['group_patient_status'][$k];
$patient['group_patient_start'] = DateToYYYYMMDD($_POST['group_patient_start'][$k]);
$patient['group_patient_end'] = DateToYYYYMMDD($_POST['group_patient_end'][$k]);
$patient['group_patient_comment'] = $_POST['group_patient_comment'][$k];
$filters = array(
'group_patient_status' => FILTER_VALIDATE_INT,
'group_patient_start' => FILTER_DEFAULT,
'group_patient_end' => FILTER_SANITIZE_SPECIAL_CHARS,
'group_patient_comment' => FILTER_DEFAULT,
);
//filter and sanitize all post data.
$participant = filter_var_array($patient, $filters);
$this->groupParticipantsModel->updateParticipant($participant, $patient['pid'], $_POST['group_id']);
unset($_GET['editParticipants']);
}
}
if (isset($_GET['deleteParticipant'])) {
$this->groupParticipantsModel->removeParticipant($_GET['group_id'], $_GET['pid']);
}
$data['events'] = $this->groupEventsModel->getGroupEvents($groupId);
$data['readonly'] = 'disabled';
$data['participants'] = $this->groupParticipantsModel->getParticipants($groupId);
$statuses = array();
$names = array();
foreach ($data['participants'] as $key => $row) {
$statuses[$key] = $row['group_patient_status'];
$names[$key] = $row['lname'] . ' ' . $row['fname'];
}
array_multisort($statuses, SORT_ASC, $names, SORT_ASC, $data['participants']);
$data['statuses'] = TherapyGroupsController::prepareParticipantStatusesList();
$data['groupId'] = $groupId;
$groupData = $this->groupModel->getGroup($groupId);
$data['groupName'] = $groupData['group_name'];
if (isset($_GET['editParticipants'])) {
$data['readonly'] = '';
}
TherapyGroupsController::setSession($groupId);
$this->loadView('groupDetailsParticipants', $data);
}
public function add($groupId)
{
if (isset($_POST['save_new'])) {
$_POST['group_patient_start'] = DateToYYYYMMDD($_POST['group_patient_start']);
$alreadyRegistered = $this->groupParticipantsModel->isAlreadyRegistered($_POST['pid'], $groupId);
if ($alreadyRegistered) {
$this->index($groupId, array('participant_data' => $_POST, 'addStatus' => 'failed','message' => xlt('The patient already registered to the group')));
}
// adding group id to $_POST
$_POST = array('group_id' => $groupId) + $_POST;
$filters = array(
'group_id' => FILTER_VALIDATE_INT,
'pid' => FILTER_VALIDATE_INT,
'group_patient_start' => FILTER_DEFAULT,
'group_patient_comment' => FILTER_DEFAULT,
);
$participant_data = filter_var_array($_POST, $filters);
$participant_data['group_patient_status'] = 10;
$participant_data['group_patient_end'] = 'NULL';
$this->groupParticipantsModel->saveParticipant($participant_data);
}
$this->index($groupId, array('participant_data' => null));
}
}
| vaibhavgupta3110/openemr | interface/therapy_groups/therapy_groups_controllers/participants_controller.php | PHP | gpl-3.0 | 5,277 |
// { dg-do compile }
// { dg-options "-D__STDCPP_WANT_MATH_SPEC_FUNCS__" }
// Copyright (C) 2016 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 8.1.11 ellint_1
#include <math.h>
void
test01()
{
float kf = 0.5F, phif = atan2(1.0F, 1.0F);
double kd = 0.5, phid = atan2(1.0, 1.0);
long double kl = 0.5L, phil = atan2(1.0L, 1.0L);
ellint_1(kf, phif);
ellint_1f(kf, phif);
ellint_1(kd, phid);
ellint_1(kl, phil);
ellint_1l(kl, phil);
return;
}
| selmentdev/selment-toolchain | source/gcc-latest/libstdc++-v3/testsuite/special_functions/11_ellint_1/compile_2.cc | C++ | gpl-3.0 | 1,160 |
package terraform
import (
"log"
"github.com/hashicorp/terraform/dag"
"github.com/hashicorp/terraform/tfdiags"
)
// NodePlannableResource represents a resource that is "plannable":
// it is ready to be planned in order to create a diff.
type NodePlannableResource struct {
*NodeAbstractResource
// ForceCreateBeforeDestroy might be set via our GraphNodeDestroyerCBD
// during graph construction, if dependencies require us to force this
// on regardless of what the configuration says.
ForceCreateBeforeDestroy *bool
}
var (
_ GraphNodeSubPath = (*NodePlannableResource)(nil)
_ GraphNodeDestroyerCBD = (*NodePlannableResource)(nil)
_ GraphNodeDynamicExpandable = (*NodePlannableResource)(nil)
_ GraphNodeReferenceable = (*NodePlannableResource)(nil)
_ GraphNodeReferencer = (*NodePlannableResource)(nil)
_ GraphNodeResource = (*NodePlannableResource)(nil)
_ GraphNodeAttachResourceConfig = (*NodePlannableResource)(nil)
)
// GraphNodeEvalable
func (n *NodePlannableResource) EvalTree() EvalNode {
addr := n.ResourceAddr()
config := n.Config
if config == nil {
// Nothing to do, then.
log.Printf("[TRACE] NodeApplyableResource: no configuration present for %s", addr)
return &EvalNoop{}
}
// this ensures we can reference the resource even if the count is 0
return &EvalWriteResourceState{
Addr: addr.Resource,
Config: config,
ProviderAddr: n.ResolvedProvider,
}
}
// GraphNodeDestroyerCBD
func (n *NodePlannableResource) CreateBeforeDestroy() bool {
if n.ForceCreateBeforeDestroy != nil {
return *n.ForceCreateBeforeDestroy
}
// If we have no config, we just assume no
if n.Config == nil || n.Config.Managed == nil {
return false
}
return n.Config.Managed.CreateBeforeDestroy
}
// GraphNodeDestroyerCBD
func (n *NodePlannableResource) ModifyCreateBeforeDestroy(v bool) error {
n.ForceCreateBeforeDestroy = &v
return nil
}
// GraphNodeDynamicExpandable
func (n *NodePlannableResource) DynamicExpand(ctx EvalContext) (*Graph, error) {
var diags tfdiags.Diagnostics
count, countDiags := evaluateResourceCountExpression(n.Config.Count, ctx)
diags = diags.Append(countDiags)
if countDiags.HasErrors() {
return nil, diags.Err()
}
// Next we need to potentially rename an instance address in the state
// if we're transitioning whether "count" is set at all.
fixResourceCountSetTransition(ctx, n.ResourceAddr(), count != -1)
// Our graph transformers require access to the full state, so we'll
// temporarily lock it while we work on this.
state := ctx.State().Lock()
defer ctx.State().Unlock()
// The concrete resource factory we'll use
concreteResource := func(a *NodeAbstractResourceInstance) dag.Vertex {
// Add the config and state since we don't do that via transforms
a.Config = n.Config
a.ResolvedProvider = n.ResolvedProvider
a.Schema = n.Schema
a.ProvisionerSchemas = n.ProvisionerSchemas
return &NodePlannableResourceInstance{
NodeAbstractResourceInstance: a,
// By the time we're walking, we've figured out whether we need
// to force on CreateBeforeDestroy due to dependencies on other
// nodes that have it.
ForceCreateBeforeDestroy: n.CreateBeforeDestroy(),
}
}
// The concrete resource factory we'll use for orphans
concreteResourceOrphan := func(a *NodeAbstractResourceInstance) dag.Vertex {
// Add the config and state since we don't do that via transforms
a.Config = n.Config
a.ResolvedProvider = n.ResolvedProvider
a.Schema = n.Schema
a.ProvisionerSchemas = n.ProvisionerSchemas
return &NodePlannableResourceInstanceOrphan{
NodeAbstractResourceInstance: a,
}
}
// Start creating the steps
steps := []GraphTransformer{
// Expand the count.
&ResourceCountTransformer{
Concrete: concreteResource,
Schema: n.Schema,
Count: count,
Addr: n.ResourceAddr(),
},
// Add the count orphans
&OrphanResourceCountTransformer{
Concrete: concreteResourceOrphan,
Count: count,
Addr: n.ResourceAddr(),
State: state,
},
// Attach the state
&AttachStateTransformer{State: state},
// Targeting
&TargetsTransformer{Targets: n.Targets},
// Connect references so ordering is correct
&ReferenceTransformer{},
// Make sure there is a single root
&RootTransformer{},
}
// Build the graph
b := &BasicGraphBuilder{
Steps: steps,
Validate: true,
Name: "NodePlannableResource",
}
graph, diags := b.Build(ctx.Path())
return graph, diags.ErrWithWarnings()
}
| hashicorp/terraform-provider-template | vendor/github.com/hashicorp/terraform/terraform/node_resource_plan.go | GO | mpl-2.0 | 4,536 |
/**
* Copyright © 2002 Instituto Superior Técnico
*
* This file is part of FenixEdu Academic.
*
* FenixEdu Academic is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FenixEdu Academic is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fenixedu.academic.domain.reports;
import java.util.Collections;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.fenixedu.academic.domain.ExecutionYear;
import org.fenixedu.academic.domain.Person;
import org.fenixedu.academic.domain.SchoolLevelType;
import org.fenixedu.academic.domain.contacts.PhysicalAddress;
import org.fenixedu.academic.domain.student.Registration;
import org.fenixedu.academic.domain.student.curriculum.ConclusionProcess;
import org.fenixedu.commons.spreadsheet.Spreadsheet;
import org.fenixedu.commons.spreadsheet.Spreadsheet.Row;
import org.joda.time.LocalDate;
public class GraduationReportFile extends GraduationReportFile_Base {
public GraduationReportFile() {
super();
}
@Override
public String getJobName() {
return "Listagem de diplomados";
}
@Override
protected String getPrefix() {
return "diplomados";
}
@Override
public void renderReport(Spreadsheet spreadsheet) {
spreadsheet.setHeader("número aluno");
spreadsheet.setHeader("nome");
setDegreeHeaders(spreadsheet);
spreadsheet.setHeader("ciclo");
spreadsheet.setHeader("Nota Conclusão Secundário");
spreadsheet.setHeader("Nota Seriação");
spreadsheet.setHeader("ano de ingresso");
spreadsheet.setHeader("ano lectivo conclusão");
spreadsheet.setHeader("data conclusão");
spreadsheet.setHeader("número de anos para conclusão");
spreadsheet.setHeader("média final");
spreadsheet.setHeader("morada");
spreadsheet.setHeader("código postal");
spreadsheet.setHeader("cidade");
spreadsheet.setHeader("país");
spreadsheet.setHeader("telefone");
spreadsheet.setHeader("telemovel");
spreadsheet.setHeader("email");
spreadsheet.setHeader("sexo");
spreadsheet.setHeader("data nascimento");
final Set<ExecutionYear> toInspectSet =
getExecutionYear() == null ? getRootDomainObject().getExecutionYearsSet() : Collections
.singleton(getExecutionYear());
for (final ExecutionYear toInspect : toInspectSet) {
for (final ConclusionProcess conclusionProcess : toInspect.getConclusionProcessesConcludedSet()) {
if (checkDegreeType(getDegreeType(), conclusionProcess)) {
reportGraduate(spreadsheet, conclusionProcess);
}
}
}
}
private void reportGraduate(final Spreadsheet sheet, final ConclusionProcess conclusionProcess) {
final Row row = sheet.addRow();
final Registration registration = conclusionProcess.getRegistration();
final ExecutionYear ingression = conclusionProcess.getIngressionYear();
final ExecutionYear conclusion = conclusionProcess.getConclusionYear();
final LocalDate conclusionDate = conclusionProcess.getConclusionDate();
row.setCell(registration.getNumber());
row.setCell(registration.getName());
setDegreeCells(row, registration.getDegree());
row.setCell(conclusionProcess.getName().getContent());
row.setCell(registration.getPrecedentDegreeConclusionGrade(SchoolLevelType.SECOND_CYCLE_BASIC_SCHOOL));
row.setCell(registration.getEntryGrade() != null ? registration.getEntryGrade().toString() : StringUtils.EMPTY);
row.setCell(ingression.getYear());
row.setCell(conclusion == null ? StringUtils.EMPTY : conclusion.getYear());
row.setCell(conclusionDate == null ? StringUtils.EMPTY : conclusionDate.toString("yyyy-MM-dd"));
row.setCell(conclusion == null ? StringUtils.EMPTY : String.valueOf(ingression.getDistanceInCivilYears(conclusion) + 1));
row.setCell(conclusionProcess.getFinalGrade().getValue());
setPersonCells(registration, row);
}
private void setPersonCells(final Registration registration, final Row row) {
final Person person = registration.getPerson();
final PhysicalAddress defaultPhysicalAddress = person.getDefaultPhysicalAddress();
if (defaultPhysicalAddress != null) {
row.setCell(defaultPhysicalAddress.getAddress());
row.setCell(defaultPhysicalAddress.getPostalCode());
row.setCell(defaultPhysicalAddress.getArea());
row.setCell(defaultPhysicalAddress.getCountryOfResidence() == null ? StringUtils.EMPTY : defaultPhysicalAddress
.getCountryOfResidence().getName());
} else {
row.setCell(StringUtils.EMPTY);
row.setCell(StringUtils.EMPTY);
row.setCell(StringUtils.EMPTY);
row.setCell(StringUtils.EMPTY);
}
row.setCell(person.getDefaultPhoneNumber());
row.setCell(person.getDefaultMobilePhoneNumber());
row.setCell(person.getInstitutionalOrDefaultEmailAddressValue());
row.setCell(person.getGender().toLocalizedString());
row.setCell(person.getDateOfBirthYearMonthDay() != null ? person.getDateOfBirthYearMonthDay().toString("yyyy-MM-dd") : StringUtils.EMPTY);
}
}
| jcarvalho/fenixedu-academic | src/main/java/org/fenixedu/academic/domain/reports/GraduationReportFile.java | Java | lgpl-3.0 | 5,943 |
/**
*
*/
package org.sword.wechat4j;
import javax.servlet.http.HttpServletRequest;
/**
* @author ChengNing
* @date 2014年12月7日
*/
public class Wechat extends WechatSupport{
public Wechat(HttpServletRequest request) {
super(request);
}
@Override
protected void onText() {
// TODO Auto-generated method stub
}
@Override
protected void onImage() {
// TODO Auto-generated method stub
}
@Override
protected void onVoice() {
// TODO Auto-generated method stub
}
@Override
protected void onVideo() {
// TODO Auto-generated method stub
}
@Override
protected void onLocation() {
// TODO Auto-generated method stub
}
@Override
protected void onLink() {
// TODO Auto-generated method stub
}
@Override
protected void onUnknown() {
// TODO Auto-generated method stub
}
@Override
protected void click() {
// TODO Auto-generated method stub
}
@Override
protected void subscribe() {
// TODO Auto-generated method stub
}
@Override
protected void unSubscribe() {
// TODO Auto-generated method stub
}
@Override
protected void scan() {
// TODO Auto-generated method stub
}
@Override
protected void location() {
// TODO Auto-generated method stub
}
@Override
protected void view() {
// TODO Auto-generated method stub
}
@Override
protected void templateMsgCallback() {
// TODO Auto-generated method stub
}
@Override
protected void scanCodePush() {
// TODO Auto-generated method stub
}
@Override
protected void scanCodeWaitMsg() {
// TODO Auto-generated method stub
}
@Override
protected void picSysPhoto() {
// TODO Auto-generated method stub
}
@Override
protected void picPhotoOrAlbum() {
// TODO Auto-generated method stub
}
@Override
protected void picWeixin() {
// TODO Auto-generated method stub
}
@Override
protected void locationSelect() {
// TODO Auto-generated method stub
}
@Override
protected void onShortVideo() {
// TODO Auto-generated method stub
}
@Override
protected void kfCreateSession() {
// TODO Auto-generated method stub
}
@Override
protected void kfCloseSession() {
// TODO Auto-generated method stub
}
@Override
protected void kfSwitchSession() {
// TODO Auto-generated method stub
}
}
| liwanwei/wechat4j | test/org/sword/wechat4j/Wechat.java | Java | apache-2.0 | 2,327 |
/*
Copyright (c) 2011 Eli Grey, http://eligrey.com
This file is based on:
https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.js ,
licensed under X11/MIT.
See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
This file is part of SwitchySharp.
SwitchySharp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SwitchySharp is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with SwitchySharp. If not, see <http://www.gnu.org/licenses/>.
*/
var saveAs = saveAs || (function (view) {
"use strict";
var
doc = view.document
// only get URL when necessary in case BlobBuilder.js hasn't overridden it yet
, get_URL = function () {
return view.URL || view.webkitURL || view;
}
, URL = view.URL || view.webkitURL || view
, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
, can_use_save_link = "download" in save_link
, click = function (node) {
var event = doc.createEvent("MouseEvents");
event.initMouseEvent(
"click", true, false, view, 0, 0, 0, 0, 0
, false, false, false, false, 0, null
);
return node.dispatchEvent(event); // false if event was cancelled
}
, webkit_req_fs = view.webkitRequestFileSystem
, req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
, throw_outside = function (ex) {
(view.setImmediate || view.setTimeout)(function () {
throw ex;
}, 0);
}
, force_saveable_type = "application/octet-stream"
, fs_min_size = 0
, deletion_queue = []
, process_deletion_queue = function () {
var i = deletion_queue.length;
while (i--) {
var file = deletion_queue[i];
if (typeof file === "string") { // file is an object URL
URL.revokeObjectURL(file);
} else { // file is a File
file.remove();
}
}
deletion_queue.length = 0; // clear queue
}
, dispatch = function (filesaver, event_types, event) {
event_types = [].concat(event_types);
var i = event_types.length;
while (i--) {
var listener = filesaver["on" + event_types[i]];
if (typeof listener === "function") {
try {
listener.call(filesaver, event || filesaver);
} catch (ex) {
throw_outside(ex);
}
}
}
}
, FileSaver = function (blob, name) {
// First try a.download, then web filesystem, then object URLs
var
filesaver = this
, type = blob.type
, blob_changed = false
, object_url
, target_view
, get_object_url = function (blob) {
var object_url = get_URL().createObjectURL(blob);
deletion_queue.push(object_url);
return object_url;
}
, dispatch_all = function () {
dispatch(filesaver, "writestart progress write writeend".split(" "));
}
// on any filesys errors revert to saving with object URLs
, fs_error = function () {
// don't create more object URLs than needed
if (blob_changed || !object_url) {
object_url = get_object_url(blob);
}
target_view.location.href = object_url;
filesaver.readyState = filesaver.DONE;
dispatch_all();
}
, abortable = function (func) {
return function () {
if (filesaver.readyState !== filesaver.DONE) {
return func.apply(this, arguments);
}
};
}
, create_if_not_found = {create:true, exclusive:false}
, slice
;
filesaver.readyState = filesaver.INIT;
if (!name) {
name = "download";
}
if (can_use_save_link) {
object_url = get_object_url(blob);
save_link.href = object_url;
save_link.download = name;
if (click(save_link)) {
filesaver.readyState = filesaver.DONE;
dispatch_all();
return;
}
}
// Object and web filesystem URLs have a problem saving in Google Chrome when
// viewed in a tab, so I force save with application/octet-stream
// http://code.google.com/p/chromium/issues/detail?id=91158
if (view.chrome && type && type !== force_saveable_type) {
slice = blob.slice || blob.webkitSlice;
blob = slice.call(blob, 0, blob.size, force_saveable_type);
blob_changed = true;
}
// Since I can't be sure that the guessed media type will trigger a download
// in WebKit, I append .download to the filename.
// https://bugs.webkit.org/show_bug.cgi?id=65440
//if (webkit_req_fs && name !== "download") {
// name += ".download";
//}
if (type === force_saveable_type || webkit_req_fs) {
target_view = view;
} else {
target_view = view.open();
}
if (!req_fs) {
fs_error();
return;
}
fs_min_size += blob.size;
req_fs(view.TEMPORARY, fs_min_size, abortable(function (fs) {
fs.root.getDirectory("saved", create_if_not_found, abortable(function (dir) {
var save = function () {
dir.getFile(name, create_if_not_found, abortable(function (file) {
file.createWriter(abortable(function (writer) {
writer.onwriteend = function (event) {
target_view.location.href = file.toURL();
deletion_queue.push(file);
filesaver.readyState = filesaver.DONE;
dispatch(filesaver, "writeend", event);
};
writer.onerror = function () {
var error = writer.error;
if (error.code !== error.ABORT_ERR) {
fs_error();
}
};
"writestart progress write abort".split(" ").forEach(function (event) {
writer["on" + event] = filesaver["on" + event];
});
writer.write(blob);
filesaver.abort = function () {
writer.abort();
filesaver.readyState = filesaver.DONE;
};
filesaver.readyState = filesaver.WRITING;
}), fs_error);
}), fs_error);
};
dir.getFile(name, {create:false}, abortable(function (file) {
// delete file if it already exists
file.remove();
save();
}), abortable(function (ex) {
if (ex.code === ex.NOT_FOUND_ERR) {
save();
} else {
fs_error();
}
}));
}), fs_error);
}), fs_error);
}
, FS_proto = FileSaver.prototype
, saveAs = function (blob, name) {
return new FileSaver(blob, name);
}
;
FS_proto.abort = function () {
var filesaver = this;
filesaver.readyState = filesaver.DONE;
dispatch(filesaver, "abort");
};
FS_proto.readyState = FS_proto.INIT = 0;
FS_proto.WRITING = 1;
FS_proto.DONE = 2;
FS_proto.error =
FS_proto.onwritestart =
FS_proto.onprogress =
FS_proto.onwrite =
FS_proto.onabort =
FS_proto.onerror =
FS_proto.onwriteend =
null;
view.addEventListener("unload", process_deletion_queue, false);
return saveAs;
}(self));
| FrankLiu/nscrapy | plugin/SwitchySharp/assets/libs/FileSaver.js | JavaScript | apache-2.0 | 9,450 |
/*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.dmn.model.v1_3;
import java.util.ArrayList;
import org.kie.dmn.model.api.InformationItem;
import org.kie.dmn.model.api.List;
import org.kie.dmn.model.api.Relation;
public class TRelation extends TExpression implements Relation {
protected java.util.List<InformationItem> column;
protected java.util.List<List> row;
@Override
public java.util.List<InformationItem> getColumn() {
if (column == null) {
column = new ArrayList<InformationItem>();
}
return this.column;
}
@Override
public java.util.List<List> getRow() {
if (row == null) {
row = new ArrayList<List>();
}
return this.row;
}
}
| droolsjbpm/drools | kie-dmn/kie-dmn-model/src/main/java/org/kie/dmn/model/v1_3/TRelation.java | Java | apache-2.0 | 1,338 |
// +build linux
package main
import (
"os"
"path/filepath"
"strings"
"syscall"
"github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/pkg/mount"
icmd "github.com/docker/docker/pkg/testutil/cmd"
"github.com/go-check/check"
)
// TestDaemonRestartWithPluginEnabled tests state restore for an enabled plugin
func (s *DockerDaemonSuite) TestDaemonRestartWithPluginEnabled(c *check.C) {
testRequires(c, IsAmd64, Network)
s.d.Start(c)
if out, err := s.d.Cmd("plugin", "install", "--grant-all-permissions", pName); err != nil {
c.Fatalf("Could not install plugin: %v %s", err, out)
}
defer func() {
if out, err := s.d.Cmd("plugin", "disable", pName); err != nil {
c.Fatalf("Could not disable plugin: %v %s", err, out)
}
if out, err := s.d.Cmd("plugin", "remove", pName); err != nil {
c.Fatalf("Could not remove plugin: %v %s", err, out)
}
}()
s.d.Restart(c)
out, err := s.d.Cmd("plugin", "ls")
if err != nil {
c.Fatalf("Could not list plugins: %v %s", err, out)
}
c.Assert(out, checker.Contains, pName)
c.Assert(out, checker.Contains, "true")
}
// TestDaemonRestartWithPluginDisabled tests state restore for a disabled plugin
func (s *DockerDaemonSuite) TestDaemonRestartWithPluginDisabled(c *check.C) {
testRequires(c, IsAmd64, Network)
s.d.Start(c)
if out, err := s.d.Cmd("plugin", "install", "--grant-all-permissions", pName, "--disable"); err != nil {
c.Fatalf("Could not install plugin: %v %s", err, out)
}
defer func() {
if out, err := s.d.Cmd("plugin", "remove", pName); err != nil {
c.Fatalf("Could not remove plugin: %v %s", err, out)
}
}()
s.d.Restart(c)
out, err := s.d.Cmd("plugin", "ls")
if err != nil {
c.Fatalf("Could not list plugins: %v %s", err, out)
}
c.Assert(out, checker.Contains, pName)
c.Assert(out, checker.Contains, "false")
}
// TestDaemonKillLiveRestoreWithPlugins SIGKILLs daemon started with --live-restore.
// Plugins should continue to run.
func (s *DockerDaemonSuite) TestDaemonKillLiveRestoreWithPlugins(c *check.C) {
testRequires(c, IsAmd64, Network)
s.d.Start(c, "--live-restore")
if out, err := s.d.Cmd("plugin", "install", "--grant-all-permissions", pName); err != nil {
c.Fatalf("Could not install plugin: %v %s", err, out)
}
defer func() {
s.d.Restart(c, "--live-restore")
if out, err := s.d.Cmd("plugin", "disable", pName); err != nil {
c.Fatalf("Could not disable plugin: %v %s", err, out)
}
if out, err := s.d.Cmd("plugin", "remove", pName); err != nil {
c.Fatalf("Could not remove plugin: %v %s", err, out)
}
}()
if err := s.d.Kill(); err != nil {
c.Fatalf("Could not kill daemon: %v", err)
}
icmd.RunCommand("pgrep", "-f", pluginProcessName).Assert(c, icmd.Success)
}
// TestDaemonShutdownLiveRestoreWithPlugins SIGTERMs daemon started with --live-restore.
// Plugins should continue to run.
func (s *DockerDaemonSuite) TestDaemonShutdownLiveRestoreWithPlugins(c *check.C) {
testRequires(c, IsAmd64, Network)
s.d.Start(c, "--live-restore")
if out, err := s.d.Cmd("plugin", "install", "--grant-all-permissions", pName); err != nil {
c.Fatalf("Could not install plugin: %v %s", err, out)
}
defer func() {
s.d.Restart(c, "--live-restore")
if out, err := s.d.Cmd("plugin", "disable", pName); err != nil {
c.Fatalf("Could not disable plugin: %v %s", err, out)
}
if out, err := s.d.Cmd("plugin", "remove", pName); err != nil {
c.Fatalf("Could not remove plugin: %v %s", err, out)
}
}()
if err := s.d.Interrupt(); err != nil {
c.Fatalf("Could not kill daemon: %v", err)
}
icmd.RunCommand("pgrep", "-f", pluginProcessName).Assert(c, icmd.Success)
}
// TestDaemonShutdownWithPlugins shuts down running plugins.
func (s *DockerDaemonSuite) TestDaemonShutdownWithPlugins(c *check.C) {
testRequires(c, IsAmd64, Network, SameHostDaemon)
s.d.Start(c)
if out, err := s.d.Cmd("plugin", "install", "--grant-all-permissions", pName); err != nil {
c.Fatalf("Could not install plugin: %v %s", err, out)
}
defer func() {
s.d.Restart(c)
if out, err := s.d.Cmd("plugin", "disable", pName); err != nil {
c.Fatalf("Could not disable plugin: %v %s", err, out)
}
if out, err := s.d.Cmd("plugin", "remove", pName); err != nil {
c.Fatalf("Could not remove plugin: %v %s", err, out)
}
}()
if err := s.d.Interrupt(); err != nil {
c.Fatalf("Could not kill daemon: %v", err)
}
for {
if err := syscall.Kill(s.d.Pid(), 0); err == syscall.ESRCH {
break
}
}
icmd.RunCommand("pgrep", "-f", pluginProcessName).Assert(c, icmd.Expected{
ExitCode: 1,
Error: "exit status 1",
})
s.d.Start(c, "--live-restore")
icmd.RunCommand("pgrep", "-f", pluginProcessName).Assert(c, icmd.Success)
}
// TestVolumePlugin tests volume creation using a plugin.
func (s *DockerDaemonSuite) TestVolumePlugin(c *check.C) {
testRequires(c, IsAmd64, Network)
volName := "plugin-volume"
destDir := "/tmp/data/"
destFile := "foo"
s.d.Start(c)
out, err := s.d.Cmd("plugin", "install", pName, "--grant-all-permissions")
if err != nil {
c.Fatalf("Could not install plugin: %v %s", err, out)
}
pluginID, err := s.d.Cmd("plugin", "inspect", "-f", "{{.Id}}", pName)
pluginID = strings.TrimSpace(pluginID)
if err != nil {
c.Fatalf("Could not retrieve plugin ID: %v %s", err, pluginID)
}
mountpointPrefix := filepath.Join(s.d.RootDir(), "plugins", pluginID, "rootfs")
defer func() {
if out, err := s.d.Cmd("plugin", "disable", pName); err != nil {
c.Fatalf("Could not disable plugin: %v %s", err, out)
}
if out, err := s.d.Cmd("plugin", "remove", pName); err != nil {
c.Fatalf("Could not remove plugin: %v %s", err, out)
}
exists, err := existsMountpointWithPrefix(mountpointPrefix)
c.Assert(err, checker.IsNil)
c.Assert(exists, checker.Equals, false)
}()
out, err = s.d.Cmd("volume", "create", "-d", pName, volName)
if err != nil {
c.Fatalf("Could not create volume: %v %s", err, out)
}
defer func() {
if out, err := s.d.Cmd("volume", "remove", volName); err != nil {
c.Fatalf("Could not remove volume: %v %s", err, out)
}
}()
out, err = s.d.Cmd("volume", "ls")
if err != nil {
c.Fatalf("Could not list volume: %v %s", err, out)
}
c.Assert(out, checker.Contains, volName)
c.Assert(out, checker.Contains, pName)
mountPoint, err := s.d.Cmd("volume", "inspect", volName, "--format", "{{.Mountpoint}}")
if err != nil {
c.Fatalf("Could not inspect volume: %v %s", err, mountPoint)
}
mountPoint = strings.TrimSpace(mountPoint)
out, err = s.d.Cmd("run", "--rm", "-v", volName+":"+destDir, "busybox", "touch", destDir+destFile)
c.Assert(err, checker.IsNil, check.Commentf(out))
path := filepath.Join(s.d.RootDir(), "plugins", pluginID, "rootfs", mountPoint, destFile)
_, err = os.Lstat(path)
c.Assert(err, checker.IsNil)
exists, err := existsMountpointWithPrefix(mountpointPrefix)
c.Assert(err, checker.IsNil)
c.Assert(exists, checker.Equals, true)
}
func (s *DockerDaemonSuite) TestGraphdriverPlugin(c *check.C) {
testRequires(c, Network, IsAmd64, DaemonIsLinux, overlay2Supported, ExperimentalDaemon)
s.d.Start(c)
// install the plugin
plugin := "cpuguy83/docker-overlay2-graphdriver-plugin"
out, err := s.d.Cmd("plugin", "install", "--grant-all-permissions", plugin)
c.Assert(err, checker.IsNil, check.Commentf(out))
// restart the daemon with the plugin set as the storage driver
s.d.Restart(c, "-s", plugin, "--storage-opt", "overlay2.override_kernel_check=1")
// run a container
out, err = s.d.Cmd("run", "--rm", "busybox", "true") // this will pull busybox using the plugin
c.Assert(err, checker.IsNil, check.Commentf(out))
}
func (s *DockerDaemonSuite) TestPluginVolumeRemoveOnRestart(c *check.C) {
testRequires(c, DaemonIsLinux, Network, IsAmd64)
s.d.Start(c, "--live-restore=true")
out, err := s.d.Cmd("plugin", "install", "--grant-all-permissions", pName)
c.Assert(err, checker.IsNil, check.Commentf(out))
c.Assert(strings.TrimSpace(out), checker.Contains, pName)
out, err = s.d.Cmd("volume", "create", "--driver", pName, "test")
c.Assert(err, checker.IsNil, check.Commentf(out))
s.d.Restart(c, "--live-restore=true")
out, err = s.d.Cmd("plugin", "disable", pName)
c.Assert(err, checker.NotNil, check.Commentf(out))
c.Assert(out, checker.Contains, "in use")
out, err = s.d.Cmd("volume", "rm", "test")
c.Assert(err, checker.IsNil, check.Commentf(out))
out, err = s.d.Cmd("plugin", "disable", pName)
c.Assert(err, checker.IsNil, check.Commentf(out))
out, err = s.d.Cmd("plugin", "rm", pName)
c.Assert(err, checker.IsNil, check.Commentf(out))
}
func existsMountpointWithPrefix(mountpointPrefix string) (bool, error) {
mounts, err := mount.GetMounts()
if err != nil {
return false, err
}
for _, mnt := range mounts {
if strings.HasPrefix(mnt.Mountpoint, mountpointPrefix) {
return true, nil
}
}
return false, nil
}
| jgsqware/clairctl | vendor/github.com/docker/docker/integration-cli/docker_cli_daemon_plugins_test.go | GO | apache-2.0 | 8,839 |
from lib.mmonit import MmonitBaseAction
class MmonitGetUptimeHost(MmonitBaseAction):
def run(self, host_id, uptime_range=0, datefrom=0, dateto=0):
self.login()
if datefrom != 0 and uptime_range != 12:
raise Exception("If datefrom is set, range should be 12")
data = {"id": host_id, "range": uptime_range, "datefrom": datefrom, "dateto": dateto}
req = self.session.post("{}/reports/uptime/get".format(self.url), data=data)
try:
return req.json()
except Exception:
raise
finally:
self.logout()
| meirwah/st2contrib | packs/mmonit/actions/get_uptime_host.py | Python | apache-2.0 | 604 |
/**
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.portal.rest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.jasig.portal.fragment.subscribe.IUserFragmentSubscription;
import org.jasig.portal.fragment.subscribe.dao.IUserFragmentSubscriptionDao;
import org.jasig.portal.layout.dlm.ConfigurationLoader;
import org.jasig.portal.layout.dlm.Evaluator;
import org.jasig.portal.layout.dlm.FragmentDefinition;
import org.jasig.portal.layout.dlm.providers.SubscribedTabEvaluatorFactory;
import org.jasig.portal.security.IAuthorizationPrincipal;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.services.AuthorizationService;
import org.jasig.portal.user.IUserInstance;
import org.jasig.portal.user.IUserInstanceManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;
/**
* Returns JSON representing the list of subscribable fragments for the
* currently-authenticated user.
*
* @author Mary Hunt
* @author Jen Bourey
* @version $Revision$ $Date$
*/
@Controller
public class SubscribableTabsRESTController {
@Autowired
@Qualifier("userInstanceManager")
private IUserInstanceManager userInstanceManager;
public void setUserInstanceManager(IUserInstanceManager userInstanceManager) {
this.userInstanceManager = userInstanceManager;
}
private IUserFragmentSubscriptionDao userFragmentSubscriptionDao;
@Autowired(required = true)
public void setUserFragmentSubscriptionDao(IUserFragmentSubscriptionDao userFragmentSubscriptionDao) {
this.userFragmentSubscriptionDao = userFragmentSubscriptionDao;
}
@Autowired
@Qualifier("dlmConfigurationLoader")
private ConfigurationLoader configurationLoader;
@Autowired
private MessageSource messageSource;
@RequestMapping(value="/subscribableTabs.json", method = RequestMethod.GET)
public ModelAndView getSubscriptionList(HttpServletRequest request) {
Map<String, Object> model = new HashMap<String, Object>();
/**
* Retrieve the IPerson and IAuthorizationPrincipal for the currently
* authenticated user
*/
IUserInstance userInstance = userInstanceManager.getUserInstance(request);
IPerson person = userInstance.getPerson();
AuthorizationService authService = AuthorizationService.instance();
IAuthorizationPrincipal principal = authService.newPrincipal(person.getUserName(), IPerson.class);
/**
* Build a collection of owner IDs for the fragments to which the
* authenticated user is subscribed
*/
// get the list of current subscriptions for this user
List<IUserFragmentSubscription> subscriptions = userFragmentSubscriptionDao
.getUserFragmentInfo(person);
// transform it into the set of owners
Set<String> subscribedOwners = new HashSet<String>();
for (IUserFragmentSubscription subscription : subscriptions){
if (subscription.isActive()) {
subscribedOwners.add(subscription.getFragmentOwner());
}
}
/**
* Iterate through the list of all currently defined DLM fragments and
* determine if the current user has permissions to subscribe to each.
* Any subscribable fragments will be transformed into a JSON-friendly
* bean and added to the model.
*/
final List<SubscribableFragment> jsonFragments = new ArrayList<SubscribableFragment>();
// get the list of fragment definitions from DLM
final List<FragmentDefinition> fragmentDefinitions = configurationLoader.getFragments();
final Locale locale = RequestContextUtils.getLocale(request);
// iterate through the list
for (FragmentDefinition fragmentDefinition : fragmentDefinitions) {
if (isSubscribable(fragmentDefinition, principal)) {
String owner = fragmentDefinition.getOwnerId();
// check to see if the current user has permission to subscribe to
// this fragment
if (principal.hasPermission("UP_FRAGMENT", "FRAGMENT_SUBSCRIBE", owner)) {
// create a JSON fragment bean and add it to our list
boolean subscribed = subscribedOwners.contains(owner);
final String name = getMessage("fragment." + owner + ".name", fragmentDefinition.getName(), locale);
final String description = getMessage("fragment." + owner + ".description", fragmentDefinition.getDescription(), locale);
SubscribableFragment jsonFragment = new SubscribableFragment(name, description, owner, subscribed);
jsonFragments.add(jsonFragment);
}
}
}
model.put("fragments", jsonFragments);
return new ModelAndView("json", model);
}
protected boolean isSubscribable(FragmentDefinition definition, IAuthorizationPrincipal principal) {
String owner = definition.getOwnerId();
for (Evaluator evaluator : definition.getEvaluators()) {
if (evaluator.getFactoryClass().equals(SubscribedTabEvaluatorFactory.class)) {
return principal.hasPermission("UP_FRAGMENT", "FRAGMENT_SUBSCRIBE", owner);
}
}
return false;
}
protected String getMessage(String key, String defaultName, Locale locale) {
return messageSource.getMessage(key, new Object[] {}, defaultName, locale);
}
/**
* Convenience class for representing fragment information in JSON
*/
public class SubscribableFragment {
private String name = null;
private String ownerID = null;
private String description;
private boolean subscribed;
public SubscribableFragment(String name, String description, String ownerId, boolean subscribed) {
this.name = name;
this.description = description;
this.ownerID = ownerId;
this.subscribed = subscribed;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOwnerID() {
return ownerID;
}
public void setOwnerID(String ownerID) {
this.ownerID = ownerID;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isSubscribed() {
return subscribed;
}
public void setSubscribed(boolean subscribed) {
this.subscribed = subscribed;
}
}
}
| ASU-Capstone/uPortal-Forked | uportal-war/src/main/java/org/jasig/portal/rest/SubscribableTabsRESTController.java | Java | apache-2.0 | 8,245 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.text;
import com.intellij.openapi.util.text.CharSequenceWithStringHash;
import com.intellij.openapi.util.text.Strings;
import org.jetbrains.annotations.NotNull;
public class CharArrayCharSequence implements CharSequenceBackedByArray, CharSequenceWithStringHash {
protected final char[] myChars;
protected final int myStart;
protected final int myEnd;
public CharArrayCharSequence(char @NotNull ... chars) {
this(chars, 0, chars.length);
}
public CharArrayCharSequence(char @NotNull [] chars, int start, int end) {
if (start < 0 || end > chars.length || start > end) {
throw new IndexOutOfBoundsException("chars.length:" + chars.length + ", start:" + start + ", end:" + end);
}
myChars = chars;
myStart = start;
myEnd = end;
}
@Override
public final int length() {
return myEnd - myStart;
}
@Override
public final char charAt(int index) {
return myChars[index + myStart];
}
@NotNull
@Override
public CharSequence subSequence(int start, int end) {
return start == 0 && end == length() ? this : new CharArrayCharSequence(myChars, myStart + start, myStart + end);
}
@Override
@NotNull
public String toString() {
return new String(myChars, myStart, myEnd - myStart); //TODO StringFactory
}
@Override
public char @NotNull [] getChars() {
if (myStart == 0) return myChars;
char[] chars = new char[length()];
getChars(chars, 0);
return chars;
}
@Override
public void getChars(char @NotNull [] dst, int dstOffset) {
System.arraycopy(myChars, myStart, dst, dstOffset, length());
}
@Override
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject == null || getClass() != anObject.getClass() || length() != ((CharSequence)anObject).length()) {
return false;
}
return CharArrayUtil.regionMatches(myChars, myStart, myEnd, (CharSequence)anObject);
}
/**
* See {@link java.io.Reader#read(char[], int, int)};
*/
public int readCharsTo(int start, char[] cbuf, int off, int len) {
final int readChars = Math.min(len, length() - start);
if (readChars <= 0) return -1;
System.arraycopy(myChars, myStart + start, cbuf, off, readChars);
return readChars;
}
private transient int hash;
@Override
public int hashCode() {
int h = hash;
if (h == 0) {
hash = h = Strings.stringHashCode(myChars, myStart, myEnd);
}
return h;
}
}
| siosio/intellij-community | platform/util/strings/src/com/intellij/util/text/CharArrayCharSequence.java | Java | apache-2.0 | 2,636 |
module Api
class TenantsController < BaseController
INVALID_TENANT_ATTRS = %w(id href ancestry).freeze
include Subcollections::Tags
include Subcollections::Quotas
def create_resource(_type, _id, data)
bad_attrs = data_includes_invalid_attrs(data)
if bad_attrs.present?
raise BadRequestError,
"Attribute(s) #{bad_attrs} should not be specified for creating a new tenant resource"
end
parse_set_parent(data)
tenant = Tenant.create(data)
if tenant.invalid?
raise BadRequestError, "Failed to add a new tenant resource - #{tenant.errors.full_messages.join(', ')}"
end
tenant
end
def edit_resource(type, id, data)
bad_attrs = data_includes_invalid_attrs(data)
if bad_attrs.present?
raise BadRequestError, "Attributes #{bad_attrs} should not be specified for updating a tenant resource"
end
parse_set_parent(data)
super
end
private
def parse_set_parent(data)
parent = parse_fetch_tenant(data.delete("parent"))
data["parent"] = parent if parent
end
def data_includes_invalid_attrs(data)
data.keys.select { |k| INVALID_TENANT_ATTRS.include?(k) }.compact.join(", ") if data
end
end
end
| fbladilo/manageiq | app/controllers/api/tenants_controller.rb | Ruby | apache-2.0 | 1,268 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.source.xml;
import com.intellij.lang.html.HTMLLanguage;
import com.intellij.lang.xhtml.XHTMLLanguage;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeRegistry;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.html.ScriptSupportUtil;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.ProjectScope;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.xml.XmlDocument;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import org.jetbrains.annotations.NotNull;
public class XmlFileImpl extends PsiFileImpl implements XmlFile {
public XmlFileImpl(FileViewProvider viewProvider, IElementType elementType) {
super(elementType, elementType, viewProvider);
}
@Override
public XmlDocument getDocument() {
PsiElement child = getFirstChild();
while (child != null) {
if (child instanceof XmlDocument) return (XmlDocument)child;
child = child.getNextSibling();
}
return null;
}
@Override
public XmlTag getRootTag() {
XmlDocument document = getDocument();
return document == null ? null : document.getRootTag();
}
@Override
public boolean processElements(PsiElementProcessor processor, PsiElement place){
final XmlDocument document = getDocument();
return document == null || document.processElements(processor, place);
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof XmlElementVisitor) {
((XmlElementVisitor)visitor).visitXmlFile(this);
}
else {
visitor.visitFile(this);
}
}
@Override
public String toString() {
return "XmlFile:" + getName();
}
private FileType myType = null;
@Override
@NotNull
public FileType getFileType() {
if (myType == null) {
myType = getLanguage().getAssociatedFileType();
if (myType == null) {
VirtualFile virtualFile = getOriginalFile().getVirtualFile();
myType = virtualFile == null ? FileTypeRegistry.getInstance().getFileTypeByFileName(getName()) : virtualFile.getFileType();
}
}
return myType;
}
@Override
public void clearCaches() {
super.clearCaches();
if (isWebFileType()) {
ScriptSupportUtil.clearCaches(this);
}
}
private boolean isWebFileType() {
return getLanguage() == XHTMLLanguage.INSTANCE || getLanguage() == HTMLLanguage.INSTANCE;
}
@Override
public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) {
return super.processDeclarations(processor, state, lastParent, place) &&
(!isWebFileType() || ScriptSupportUtil.processDeclarations(this, processor, state, lastParent, place));
}
@NotNull
@Override
public GlobalSearchScope getFileResolveScope() {
return ProjectScope.getAllScope(getProject());
}
@Override
public boolean ignoreReferencedElementAccessibility() {
return true;
}
}
| smmribeiro/intellij-community | xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlFileImpl.java | Java | apache-2.0 | 3,408 |
package fs
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
)
const (
cgroupFile = "cgroup.file"
floatValue = 2048.0
floatString = "2048"
)
func TestGetCgroupParamsFloat64(t *testing.T) {
// Setup tempdir.
tempDir, err := ioutil.TempDir("", "cgroup_utils_test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tempDir)
tempFile := filepath.Join(tempDir, cgroupFile)
// Success.
err = ioutil.WriteFile(tempFile, []byte(floatString), 0755)
if err != nil {
t.Fatal(err)
}
value, err := getCgroupParamFloat64(tempDir, cgroupFile)
if err != nil {
t.Fatal(err)
} else if value != floatValue {
t.Fatalf("Expected %f to equal %f", value, floatValue)
}
// Success with new line.
err = ioutil.WriteFile(tempFile, []byte(floatString+"\n"), 0755)
if err != nil {
t.Fatal(err)
}
value, err = getCgroupParamFloat64(tempDir, cgroupFile)
if err != nil {
t.Fatal(err)
} else if value != floatValue {
t.Fatalf("Expected %f to equal %f", value, floatValue)
}
// Not a float.
err = ioutil.WriteFile(tempFile, []byte("not-a-float"), 0755)
if err != nil {
t.Fatal(err)
}
_, err = getCgroupParamFloat64(tempDir, cgroupFile)
if err == nil {
t.Fatal("Expecting error, got none")
}
// Unknown file.
err = os.Remove(tempFile)
if err != nil {
t.Fatal(err)
}
_, err = getCgroupParamFloat64(tempDir, cgroupFile)
if err == nil {
t.Fatal("Expecting error, got none")
}
}
| cgwalters/docker | pkg/libcontainer/cgroups/fs/utils_test.go | GO | apache-2.0 | 1,418 |
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package scheduler
import (
"context"
"fmt"
"strings"
"testing"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
utilfeature "k8s.io/apiserver/pkg/util/feature"
featuregatetesting "k8s.io/component-base/featuregate/testing"
"k8s.io/kubernetes/pkg/features"
st "k8s.io/kubernetes/pkg/scheduler/testing"
testutils "k8s.io/kubernetes/test/integration/util"
"k8s.io/kubernetes/test/utils"
imageutils "k8s.io/kubernetes/test/utils/image"
)
// This file tests the scheduler priority functions.
// TestNodeAffinity verifies that scheduler's node affinity priority function
// works correctly.
func TestNodeAffinity(t *testing.T) {
testCtx := initTest(t, "node-affinity")
defer testutils.CleanupTest(t, testCtx)
// Add a few nodes.
nodes, err := createNodes(testCtx.ClientSet, "testnode", nil, 5)
if err != nil {
t.Fatalf("Cannot create nodes: %v", err)
}
// Add a label to one of the nodes.
labeledNode := nodes[1]
labelKey := "kubernetes.io/node-topologyKey"
labelValue := "topologyvalue"
labels := map[string]string{
labelKey: labelValue,
}
if err = utils.AddLabelsToNode(testCtx.ClientSet, labeledNode.Name, labels); err != nil {
t.Fatalf("Cannot add labels to node: %v", err)
}
if err = waitForNodeLabels(testCtx.ClientSet, labeledNode.Name, labels); err != nil {
t.Fatalf("Adding labels to node didn't succeed: %v", err)
}
// Create a pod with node affinity.
podName := "pod-with-node-affinity"
pod, err := runPausePod(testCtx.ClientSet, initPausePod(testCtx.ClientSet, &pausePodConfig{
Name: podName,
Namespace: testCtx.NS.Name,
Affinity: &v1.Affinity{
NodeAffinity: &v1.NodeAffinity{
PreferredDuringSchedulingIgnoredDuringExecution: []v1.PreferredSchedulingTerm{
{
Preference: v1.NodeSelectorTerm{
MatchExpressions: []v1.NodeSelectorRequirement{
{
Key: labelKey,
Operator: v1.NodeSelectorOpIn,
Values: []string{labelValue},
},
},
},
Weight: 20,
},
},
},
},
}))
if err != nil {
t.Fatalf("Error running pause pod: %v", err)
}
if pod.Spec.NodeName != labeledNode.Name {
t.Errorf("Pod %v got scheduled on an unexpected node: %v. Expected node: %v.", podName, pod.Spec.NodeName, labeledNode.Name)
} else {
t.Logf("Pod %v got successfully scheduled on node %v.", podName, pod.Spec.NodeName)
}
}
// TestPodAffinity verifies that scheduler's pod affinity priority function
// works correctly.
func TestPodAffinity(t *testing.T) {
testCtx := initTest(t, "pod-affinity")
defer testutils.CleanupTest(t, testCtx)
// Add a few nodes.
nodesInTopology, err := createNodes(testCtx.ClientSet, "in-topology", nil, 5)
if err != nil {
t.Fatalf("Cannot create nodes: %v", err)
}
topologyKey := "node-topologykey"
topologyValue := "topologyvalue"
nodeLabels := map[string]string{
topologyKey: topologyValue,
}
for _, node := range nodesInTopology {
// Add topology key to all the nodes.
if err = utils.AddLabelsToNode(testCtx.ClientSet, node.Name, nodeLabels); err != nil {
t.Fatalf("Cannot add labels to node %v: %v", node.Name, err)
}
if err = waitForNodeLabels(testCtx.ClientSet, node.Name, nodeLabels); err != nil {
t.Fatalf("Adding labels to node %v didn't succeed: %v", node.Name, err)
}
}
// Add a pod with a label and wait for it to schedule.
labelKey := "service"
labelValue := "S1"
_, err = runPausePod(testCtx.ClientSet, initPausePod(testCtx.ClientSet, &pausePodConfig{
Name: "attractor-pod",
Namespace: testCtx.NS.Name,
Labels: map[string]string{labelKey: labelValue},
}))
if err != nil {
t.Fatalf("Error running the attractor pod: %v", err)
}
// Add a few more nodes without the topology label.
_, err = createNodes(testCtx.ClientSet, "other-node", nil, 5)
if err != nil {
t.Fatalf("Cannot create the second set of nodes: %v", err)
}
// Add a new pod with affinity to the attractor pod.
podName := "pod-with-podaffinity"
pod, err := runPausePod(testCtx.ClientSet, initPausePod(testCtx.ClientSet, &pausePodConfig{
Name: podName,
Namespace: testCtx.NS.Name,
Affinity: &v1.Affinity{
PodAffinity: &v1.PodAffinity{
PreferredDuringSchedulingIgnoredDuringExecution: []v1.WeightedPodAffinityTerm{
{
PodAffinityTerm: v1.PodAffinityTerm{
LabelSelector: &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{
Key: labelKey,
Operator: metav1.LabelSelectorOpIn,
Values: []string{labelValue, "S3"},
},
{
Key: labelKey,
Operator: metav1.LabelSelectorOpNotIn,
Values: []string{"S2"},
}, {
Key: labelKey,
Operator: metav1.LabelSelectorOpExists,
},
},
},
TopologyKey: topologyKey,
Namespaces: []string{testCtx.NS.Name},
},
Weight: 50,
},
},
},
},
}))
if err != nil {
t.Fatalf("Error running pause pod: %v", err)
}
// The new pod must be scheduled on one of the nodes with the same topology
// key-value as the attractor pod.
for _, node := range nodesInTopology {
if node.Name == pod.Spec.NodeName {
t.Logf("Pod %v got successfully scheduled on node %v.", podName, pod.Spec.NodeName)
return
}
}
t.Errorf("Pod %v got scheduled on an unexpected node: %v.", podName, pod.Spec.NodeName)
}
// TestImageLocality verifies that the scheduler's image locality priority function
// works correctly, i.e., the pod gets scheduled to the node where its container images are ready.
func TestImageLocality(t *testing.T) {
testCtx := initTest(t, "image-locality")
defer testutils.CleanupTest(t, testCtx)
// We use a fake large image as the test image used by the pod, which has relatively large image size.
image := v1.ContainerImage{
Names: []string{
"fake-large-image:v1",
},
SizeBytes: 3000 * 1024 * 1024,
}
// Create a node with the large image.
nodeWithLargeImage, err := createNodeWithImages(testCtx.ClientSet, "testnode-large-image", nil, []v1.ContainerImage{image})
if err != nil {
t.Fatalf("cannot create node with a large image: %v", err)
}
// Add a few nodes.
_, err = createNodes(testCtx.ClientSet, "testnode", nil, 10)
if err != nil {
t.Fatalf("cannot create nodes: %v", err)
}
// Create a pod with containers each having the specified image.
podName := "pod-using-large-image"
pod, err := runPodWithContainers(testCtx.ClientSet, initPodWithContainers(testCtx.ClientSet, &podWithContainersConfig{
Name: podName,
Namespace: testCtx.NS.Name,
Containers: makeContainersWithImages(image.Names),
}))
if err != nil {
t.Fatalf("error running pod with images: %v", err)
}
if pod.Spec.NodeName != nodeWithLargeImage.Name {
t.Errorf("pod %v got scheduled on an unexpected node: %v. Expected node: %v.", podName, pod.Spec.NodeName, nodeWithLargeImage.Name)
} else {
t.Logf("pod %v got successfully scheduled on node %v.", podName, pod.Spec.NodeName)
}
}
// makeContainerWithImage returns a list of v1.Container objects for each given image. Duplicates of an image are ignored,
// i.e., each image is used only once.
func makeContainersWithImages(images []string) []v1.Container {
var containers []v1.Container
usedImages := make(map[string]struct{})
for _, image := range images {
if _, ok := usedImages[image]; !ok {
containers = append(containers, v1.Container{
Name: strings.Replace(image, ":", "-", -1) + "-container",
Image: image,
})
usedImages[image] = struct{}{}
}
}
return containers
}
// TestEvenPodsSpreadPriority verifies that EvenPodsSpread priority functions well.
func TestEvenPodsSpreadPriority(t *testing.T) {
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.EvenPodsSpread, true)()
testCtx := initTest(t, "eps-priority")
cs := testCtx.ClientSet
ns := testCtx.NS.Name
defer testutils.CleanupTest(t, testCtx)
// Add 4 nodes.
nodes, err := createNodes(cs, "node", nil, 4)
if err != nil {
t.Fatalf("Cannot create nodes: %v", err)
}
for i, node := range nodes {
// Apply labels "zone: zone-{0,1}" and "node: <node name>" to each node.
labels := map[string]string{
"zone": fmt.Sprintf("zone-%d", i/2),
"node": node.Name,
}
if err = utils.AddLabelsToNode(cs, node.Name, labels); err != nil {
t.Fatalf("Cannot add labels to node: %v", err)
}
if err = waitForNodeLabels(cs, node.Name, labels); err != nil {
t.Fatalf("Adding labels to node failed: %v", err)
}
}
// Taint the 0th node
taint := v1.Taint{
Key: "k1",
Value: "v1",
Effect: v1.TaintEffectNoSchedule,
}
if err = testutils.AddTaintToNode(cs, nodes[0].Name, taint); err != nil {
t.Fatalf("Adding taint to node failed: %v", err)
}
if err = testutils.WaitForNodeTaints(cs, nodes[0], []v1.Taint{taint}); err != nil {
t.Fatalf("Taint not seen on node: %v", err)
}
pause := imageutils.GetPauseImageName()
tests := []struct {
name string
incomingPod *v1.Pod
existingPods []*v1.Pod
fits bool
want []string // nodes expected to schedule onto
}{
// note: naming starts at index 0
// the symbol ~X~ means that node is infeasible
{
name: "place pod on a ~0~/1/2/3 cluster with MaxSkew=1, node-1 is the preferred fit",
incomingPod: st.MakePod().Namespace(ns).Name("p").Label("foo", "").Container(pause).
SpreadConstraint(1, "node", softSpread, st.MakeLabelSelector().Exists("foo").Obj()).
Obj(),
existingPods: []*v1.Pod{
st.MakePod().Namespace(ns).Name("p1").Node("node-1").Label("foo", "").Container(pause).Obj(),
st.MakePod().Namespace(ns).Name("p2a").Node("node-2").Label("foo", "").Container(pause).Obj(),
st.MakePod().Namespace(ns).Name("p2b").Node("node-2").Label("foo", "").Container(pause).Obj(),
st.MakePod().Namespace(ns).Name("p3a").Node("node-3").Label("foo", "").Container(pause).Obj(),
st.MakePod().Namespace(ns).Name("p3b").Node("node-3").Label("foo", "").Container(pause).Obj(),
st.MakePod().Namespace(ns).Name("p3c").Node("node-3").Label("foo", "").Container(pause).Obj(),
},
fits: true,
want: []string{"node-1"},
},
{
name: "combined with hardSpread constraint on a ~4~/0/1/2 cluster",
incomingPod: st.MakePod().Namespace(ns).Name("p").Label("foo", "").Container(pause).
SpreadConstraint(1, "node", softSpread, st.MakeLabelSelector().Exists("foo").Obj()).
SpreadConstraint(1, "zone", hardSpread, st.MakeLabelSelector().Exists("foo").Obj()).
Obj(),
existingPods: []*v1.Pod{
st.MakePod().Namespace(ns).Name("p0a").Node("node-0").Label("foo", "").Container(pause).Obj(),
st.MakePod().Namespace(ns).Name("p0b").Node("node-0").Label("foo", "").Container(pause).Obj(),
st.MakePod().Namespace(ns).Name("p0c").Node("node-0").Label("foo", "").Container(pause).Obj(),
st.MakePod().Namespace(ns).Name("p0d").Node("node-0").Label("foo", "").Container(pause).Obj(),
st.MakePod().Namespace(ns).Name("p2").Node("node-2").Label("foo", "").Container(pause).Obj(),
st.MakePod().Namespace(ns).Name("p3a").Node("node-3").Label("foo", "").Container(pause).Obj(),
st.MakePod().Namespace(ns).Name("p3b").Node("node-3").Label("foo", "").Container(pause).Obj(),
},
fits: true,
want: []string{"node-2"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
allPods := append(tt.existingPods, tt.incomingPod)
defer testutils.CleanupPods(cs, t, allPods)
for _, pod := range tt.existingPods {
createdPod, err := cs.CoreV1().Pods(pod.Namespace).Create(context.TODO(), pod, metav1.CreateOptions{})
if err != nil {
t.Fatalf("Test Failed: error while creating pod during test: %v", err)
}
err = wait.Poll(pollInterval, wait.ForeverTestTimeout, testutils.PodScheduled(cs, createdPod.Namespace, createdPod.Name))
if err != nil {
t.Errorf("Test Failed: error while waiting for pod during test: %v", err)
}
}
testPod, err := cs.CoreV1().Pods(tt.incomingPod.Namespace).Create(context.TODO(), tt.incomingPod, metav1.CreateOptions{})
if err != nil && !apierrors.IsInvalid(err) {
t.Fatalf("Test Failed: error while creating pod during test: %v", err)
}
if tt.fits {
err = wait.Poll(pollInterval, wait.ForeverTestTimeout, podScheduledIn(cs, testPod.Namespace, testPod.Name, tt.want))
} else {
err = wait.Poll(pollInterval, wait.ForeverTestTimeout, podUnschedulable(cs, testPod.Namespace, testPod.Name))
}
if err != nil {
t.Errorf("Test Failed: %v", err)
}
})
}
}
| Miciah/origin | vendor/k8s.io/kubernetes/test/integration/scheduler/priorities_test.go | GO | apache-2.0 | 13,219 |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.stunner.core.processors;
public class ProcessingEntity {
private final String className;
private final String id;
public ProcessingEntity(final String className,
final String id) {
this.className = className;
this.id = id;
}
public String getClassName() {
return className;
}
public String getId() {
return id;
}
}
| romartin/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-processors/src/main/java/org/kie/workbench/common/stunner/core/processors/ProcessingEntity.java | Java | apache-2.0 | 1,066 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.history.integration;
import com.intellij.history.LocalHistoryAction;
import com.intellij.openapi.util.NlsContexts;
public class LocalHistoryActionImpl implements LocalHistoryAction {
private final @NlsContexts.Label String myName;
private final LocalHistoryEventDispatcher myDispatcher;
public LocalHistoryActionImpl(LocalHistoryEventDispatcher l, @NlsContexts.Label String name) {
myName = name;
myDispatcher = l;
}
public void start() {
myDispatcher.startAction();
}
@Override
public void finish() {
myDispatcher.finishAction(myName);
}
}
| siosio/intellij-community | platform/lvcs-impl/src/com/intellij/history/integration/LocalHistoryActionImpl.java | Java | apache-2.0 | 743 |
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.query.lookup;
import com.google.common.collect.ImmutableMap;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.core.ClassNamesResourceConfig;
import com.sun.jersey.spi.container.servlet.WebComponent;
import com.sun.jersey.spi.inject.SingletonTypeInjectableProvider;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.WebAppDescriptor;
import com.sun.jersey.test.framework.spi.container.TestContainerFactory;
import com.sun.jersey.test.framework.spi.container.grizzly2.GrizzlyTestContainerFactory;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
public class LookupIntrospectionResourceImplTest extends JerseyTest
{
static LookupReferencesManager lookupReferencesManager = EasyMock.createMock(LookupReferencesManager.class);
@Before
public void setUp() throws Exception
{
super.setUp();
EasyMock.reset(lookupReferencesManager);
LookupExtractorFactory lookupExtractorFactory1 = new MapLookupExtractorFactory(ImmutableMap.of(
"key",
"value",
"key2",
"value2"
), false);
EasyMock.expect(lookupReferencesManager.get("lookupId1")).andReturn(lookupExtractorFactory1).anyTimes();
EasyMock.replay(lookupReferencesManager);
}
@Provider
public static class MockTodoServiceProvider extends
SingletonTypeInjectableProvider<Context, LookupReferencesManager>
{
public MockTodoServiceProvider()
{
super(LookupReferencesManager.class, lookupReferencesManager);
}
}
public LookupIntrospectionResourceImplTest()
{
super(new WebAppDescriptor.Builder().initParam(
WebComponent.RESOURCE_CONFIG_CLASS,
ClassNamesResourceConfig.class.getName()
)
.initParam(
ClassNamesResourceConfig.PROPERTY_CLASSNAMES,
LookupIntrospectionResource.class.getName()
+ ';'
+ MockTodoServiceProvider.class.getName()
+ ';'
+ LookupIntrospectHandler.class.getName()
)
.build());
}
@Override
protected TestContainerFactory getTestContainerFactory()
{
return new GrizzlyTestContainerFactory();
}
@Test
public void testGetKey()
{
WebResource r = resource().path("/druid/v1/lookups/introspect/lookupId1/keys");
String s = r.get(String.class);
Assert.assertEquals("[key, key2]", s);
}
@Test
public void testGetValue()
{
WebResource r = resource().path("/druid/v1/lookups/introspect/lookupId1/values");
String s = r.get(String.class);
Assert.assertEquals("[value, value2]", s);
}
@Test
public void testGetMap()
{
WebResource r = resource().path("/druid/v1/lookups/introspect/lookupId1/");
String s = r.get(String.class);
Assert.assertEquals("{\"key\":\"value\",\"key2\":\"value2\"}", s);
}
}
| tubemogul/druid | server/src/test/java/io/druid/query/lookup/LookupIntrospectionResourceImplTest.java | Java | apache-2.0 | 4,150 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.documentation.docstrings;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.jetbrains.python.psi.PyIndentUtil;
import com.jetbrains.python.toolbox.Substring;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Mikhail Golubev
*/
public abstract class DocStringUpdater<T extends DocStringLineParser> {
protected final T myOriginalDocString;
private final StringBuilder myBuilder;
private final List<Modification> myUpdates = new ArrayList<>();
protected final String myMinContentIndent;
public DocStringUpdater(@NotNull T docString, @NotNull String minContentIndent) {
myBuilder = new StringBuilder(docString.getDocStringContent().getSuperString());
myOriginalDocString = docString;
myMinContentIndent = minContentIndent;
}
protected final void replace(@NotNull TextRange range, @NotNull String text) {
myUpdates.add(new Modification(range, text));
}
protected final void replace(int startOffset, int endOffset, @NotNull String text) {
replace(new TextRange(startOffset, endOffset), text);
}
protected final void insert(int offset, @NotNull String text) {
replace(offset, offset, text);
}
protected final void insertAfterLine(int lineNumber, @NotNull String text) {
final Substring line = myOriginalDocString.getLines().get(lineNumber);
insert(line.getEndOffset(), '\n' + text);
}
protected final void remove(int startOffset, int endOffset) {
replace(startOffset, endOffset, "");
}
/**
* @param startLine inclusive
* @param endLine exclusive
*/
protected final void removeLines(int startLine, int endLine) {
final List<Substring> lines = myOriginalDocString.getLines();
final int startOffset = lines.get(startLine).getStartOffset();
final int endOffset = endLine < lines.size() ? lines.get(endLine).getStartOffset() : lines.get(endLine - 1).getEndOffset();
remove(startOffset, endOffset);
}
protected final void removeLinesAndSpacesAfter(int startLine, int endLine) {
removeLines(startLine, skipEmptyLines(endLine));
}
private int skipEmptyLines(int startLine) {
return Math.min(myOriginalDocString.consumeEmptyLines(startLine), myOriginalDocString.getLineCount() - 1);
}
protected final void removeLine(int line) {
removeLines(line, line + 1);
}
protected final void insertBeforeLine(int lineNumber, @NotNull String text) {
final Substring line = myOriginalDocString.getLines().get(lineNumber);
insert(line.getStartOffset(), text + '\n');
}
@NotNull
public final String getDocStringText() {
beforeApplyingModifications();
// Move closing quotes to the next line, if new lines are going to be inserted
if (myOriginalDocString.getLineCount() == 1 && !myUpdates.isEmpty()) {
insertAfterLine(0, myMinContentIndent);
}
// If several updates insert in one place (e.g. new field), insert them in backward order,
// so the first added is placed above
Collections.reverse(myUpdates);
myUpdates.sort(Collections.reverseOrder());
for (final Modification update : myUpdates) {
final TextRange updateRange = update.range;
if (updateRange.getStartOffset() == updateRange.getEndOffset()) {
myBuilder.insert(updateRange.getStartOffset(), update.text);
}
else {
myBuilder.replace(updateRange.getStartOffset(), updateRange.getEndOffset(), update.text);
}
}
return myBuilder.toString();
}
protected void beforeApplyingModifications() {
}
@NotNull
public T getOriginalDocString() {
return myOriginalDocString;
}
@NotNull
protected String getLineIndent(int lineNum) {
final String lastLineIndent = myOriginalDocString.getLineIndent(lineNum);
if (PyIndentUtil.getLineIndentSize(lastLineIndent) < PyIndentUtil.getLineIndentSize(myMinContentIndent)) {
return myMinContentIndent;
}
return lastLineIndent;
}
protected int getLineIndentSize(int lineNum) {
return PyIndentUtil.getLineIndentSize(getLineIndent(lineNum));
}
protected int findLastNonEmptyLine() {
for (int i = myOriginalDocString.getLineCount() - 1; i >= 0; i--) {
if (!StringUtil.isEmptyOrSpaces(myOriginalDocString.getLine(i))) {
return i;
}
}
return 0;
}
public abstract void addParameter(@NotNull String name, @Nullable String type);
public abstract void addReturnValue(@Nullable String type);
public abstract void removeParameter(@NotNull String name);
private static class Modification implements Comparable<Modification> {
@NotNull final TextRange range;
@NotNull final String text;
Modification(@NotNull TextRange range, @NotNull String newText) {
this.range = range;
this.text = newText;
}
@Override
public int compareTo(Modification o) {
return range.getStartOffset() - o.range.getStartOffset();
}
}
}
| jwren/intellij-community | python/python-psi-impl/src/com/jetbrains/python/documentation/docstrings/DocStringUpdater.java | Java | apache-2.0 | 5,669 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.tasks.jira.jql;
import com.intellij.lang.ASTNode;
import com.intellij.lang.ParserDefinition;
import com.intellij.lang.PsiParser;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IFileElementType;
import com.intellij.psi.tree.TokenSet;
import org.jetbrains.annotations.NotNull;
/**
* @author Mikhail Golubev
*/
public class JqlParserDefinition implements ParserDefinition {
private static final Logger LOG = Logger.getInstance(JqlParserDefinition.class);
@NotNull
@Override
public Lexer createLexer(Project project) {
return new JqlLexer();
}
@Override
public @NotNull PsiParser createParser(Project project) {
return new JqlParser();
}
@Override
public @NotNull IFileElementType getFileNodeType() {
return JqlElementTypes.FILE;
}
@NotNull
@Override
public TokenSet getWhitespaceTokens() {
return JqlTokenTypes.WHITESPACES;
}
@NotNull
@Override
public TokenSet getCommentTokens() {
return TokenSet.EMPTY;
}
@NotNull
@Override
public TokenSet getStringLiteralElements() {
return TokenSet.create(JqlTokenTypes.STRING_LITERAL);
}
@NotNull
@Override
public PsiElement createElement(ASTNode node) {
return JqlElementTypes.Factory.createElement(node);
}
@Override
public @NotNull PsiFile createFile(@NotNull FileViewProvider viewProvider) {
return new JqlFile(viewProvider);
}
@Override
public @NotNull SpaceRequirements spaceExistenceTypeBetweenTokens(ASTNode left, ASTNode right) {
return SpaceRequirements.MAY;
}
}
| smmribeiro/intellij-community | plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/jql/JqlParserDefinition.java | Java | apache-2.0 | 1,904 |
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.scope;
import com.intellij.openapi.util.Key;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
/**
* Base processor which stores hints in a map
*/
public abstract class ProcessorWithHints implements PsiScopeProcessor {
private final Map<Key<?>, Object> myHints = new HashMap<>();
protected final <H> void hint(@NotNull Key<H> key, @NotNull H hint) {
myHints.put(key, hint);
}
@Nullable
@Override
public <T> T getHint(@NotNull Key<T> hintKey) {
return (T)myHints.get(hintKey);
}
}
| siosio/intellij-community | platform/core-impl/src/com/intellij/psi/scope/ProcessorWithHints.java | Java | apache-2.0 | 758 |
<?php
class ezcWebdavLockPluginClientTestAssertions074
{
public function assertCollectionNotCreated( ezcWebdavMemoryBackend $backend )
{
PHPUnit_Framework_Assert::assertFalse(
$backend->nodeExists( '/collection/newresource' )
);
}
}
return new ezcWebdavLockPluginClientTestAssertions074();
?>
| Melody/Webdav | tests/lock_plugin/074_put_parent_locked_other_failure_assertions.php | PHP | apache-2.0 | 336 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.jps.devkit.threadingModelHelper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.incremental.BuilderService;
import org.jetbrains.jps.incremental.ModuleLevelBuilder;
import java.util.Collections;
import java.util.List;
public class TMHBuilderService extends BuilderService {
@NotNull
@Override
public List<? extends ModuleLevelBuilder> createModuleLevelBuilders() {
return Collections.singletonList(new TMHInstrumentingBuilder());
}
}
| jwren/intellij-community | plugins/devkit/jps-plugin/src/org/jetbrains/jps/devkit/threadingModelHelper/TMHBuilderService.java | Java | apache-2.0 | 632 |
#!/usr/bin/env python
#
# Copyright (c) 2016 Intel Corporation.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of works must retain the original copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the original 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 Intel Corporation nor the names of its contributors
# may be used to endorse or promote products derived from this work without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "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 INTEL CORPORATION 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.
#
# Authors:
# Yun, Liu<yunx.liu@intel.com>
import os
import sys
import stat
import shutil
import urllib2
import subprocess
import time
import json
SCRIPT_PATH = os.path.realpath(__file__)
ConstPath = os.path.dirname(SCRIPT_PATH)
DEFAULT_CMD_TIMEOUT = 600
def setUp():
global device_x86, device_arm, crosswalkVersion, ARCH_ARM, ARCH_X86, PLATFORMS, HOST_PREFIX, SHELL_FLAG, MODE, ANDROID_MODE, BIT, TARGETS, apptools, apktype
ARCH_ARM = ""
ARCH_X86 = ""
BIT = "32"
device_x86 = ""
device_arm = ""
TARGETS = ""
host = open(ConstPath + "/platforms.txt", 'r')
PLATFORMS = host.read().strip("\n\t")
if PLATFORMS != "windows":
HOST_PREFIX = ""
SHELL_FLAG = "True"
else:
HOST_PREFIX = "node "
SHELL_FLAG = "False"
host.close()
if HOST_PREFIX != "":
apptools = "%crosswalk-pkg%"
else:
apptools = "crosswalk-pkg"
if os.system(HOST_PREFIX + apptools) != 0:
print "crosswalk-pkg is not work, Please set the env"
sys.exit(1)
if PLATFORMS == "android":
apktype = ".apk"
elif PLATFORMS == "ios":
apktype = ".ipa"
elif PLATFORMS == "deb":
apktype = ".deb"
else:
apktype = ".msi"
if PLATFORMS == "android":
fp = open(ConstPath + "/arch.txt", 'r')
fp_arch = fp.read().strip("\n\t")
if "x86" in fp_arch:
ARCH_X86 = "x86"
if "arm" in fp_arch:
ARCH_ARM = "arm"
if "64" in fp_arch:
BIT = "64"
fp.close()
if BIT == "32":
if ARCH_X86 == "x86" and ARCH_ARM == "":
TARGETS = "x86"
elif ARCH_ARM == "arm" and ARCH_X86 == "":
TARGETS = "armeabi-v7a"
elif ARCH_ARM == "arm" and ARCH_X86 == "x86":
TARGETS = "armeabi-v7a x86"
else:
if ARCH_X86 == "x86" and ARCH_ARM == "":
TARGETS = "x86_64"
elif ARCH_ARM == "arm" and ARCH_X86 == "":
TARGETS = "arm64-v8a"
elif ARCH_ARM == "arm" and ARCH_X86 == "x86":
TARGETS = "arm64-v8a x86_64"
mode = open(ConstPath + "/mode.txt", 'r')
mode_type = mode.read().strip("\n\t")
if mode_type == "embedded":
MODE = ""
ANDROID_MODE = "embedded"
elif mode_type == "shared":
MODE = " --android-shared"
ANDROID_MODE = "shared"
else:
MODE = " --android-lite"
ANDROID_MODE = "lite"
mode.close()
device = ""
if PLATFORMS == "android":
#device = "Medfield61809467,066e11baf0ecb889"
device = os.environ.get('DEVICE_ID')
if not device:
print ("Get DEVICE_ID env error\n")
sys.exit(1)
if device:
if ARCH_ARM != "" and ARCH_X86 != "":
if "," in device:
if getDeviceCpuAbi(device.split(',')[0]) == "x86":
device_x86 = device.split(',')[0]
else:
device_arm = device.split(',')[0]
if getDeviceCpuAbi(device.split(',')[1]) == "x86":
device_x86 = device.split(',')[1]
else:
device_arm = device.split(',')[1]
if not device_x86 or not device_arm:
print ("Need x86 and arm architecture devices id\n")
sys.exit(1)
else:
print ("Need x86 and arm architecture devices id\n")
sys.exit(1)
elif ARCH_ARM != "" and ARCH_X86 == "":
if getDeviceCpuAbi(device) == "arm":
device_arm = device
if not device_arm:
print ("Need arm architecture devices id\n")
sys.exit(1)
elif ARCH_ARM == "" and ARCH_X86 != "":
if getDeviceCpuAbi(device) == "x86":
device_x86 = device
if not device_x86:
print ("Need x86 architecture devices id\n")
sys.exit(1)
if PLATFORMS == "android" or PLATFORMS == "windows":
if not os.path.exists(ConstPath + "/VERSION"):
version_path = ConstPath + "/../../VERSION"
else:
version_path = ConstPath + "/VERSION"
with open(version_path) as json_file:
data = json.load(json_file)
crosswalkVersion = data['main-version'].strip(os.linesep)
def getstatusoutput(cmd, time_out=DEFAULT_CMD_TIMEOUT):
pre_time = time.time()
output = []
cmd_return_code = 1
cmd_proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=SHELL_FLAG)
while True:
output_line = cmd_proc.stdout.read()
cmd_return_code = cmd_proc.poll()
elapsed_time = time.time() - pre_time
if cmd_return_code is None:
if elapsed_time >= time_out:
killProcesses(ppid=cmd_proc.pid)
return False
elif output_line == '' and cmd_return_code is not None:
break
sys.stdout.write(output_line)
sys.stdout.flush()
output.append(output_line)
return (cmd_return_code, output)
def getDeviceCpuAbi(device):
cmd = 'adb -s ' + device + ' shell getprop'
(return_code, output) = getstatusoutput(cmd)
for line in output[0].split('/n'):
if "[ro.product.cpu.abi]" in line and "x86" in line:
return "x86"
else:
return "arm"
def overwriteCopy(src, dest, symlinks=False, ignore=None):
if not os.path.exists(dest):
os.makedirs(dest)
shutil.copystat(src, dest)
sub_list = os.listdir(src)
if ignore:
excl = ignore(src, sub_list)
sub_list = [x for x in sub_list if x not in excl]
for i_sub in sub_list:
s_path = os.path.join(src, i_sub)
d_path = os.path.join(dest, i_sub)
if symlinks and os.path.islink(s_path):
if os.path.lexists(d_path):
os.remove(d_path)
os.symlink(os.readlink(s_path), d_path)
try:
s_path_s = os.lstat(s_path)
s_path_mode = stat.S_IMODE(s_path_s.st_mode)
os.lchmod(d_path, s_path_mode)
except Exception:
pass
elif os.path.isdir(s_path):
overwriteCopy(s_path, d_path, symlinks, ignore)
else:
shutil.copy2(s_path, d_path)
def doCopy(src_item=None, dest_item=None):
try:
if os.path.isdir(src_item):
overwriteCopy(src_item, dest_item, symlinks=True)
else:
if not os.path.exists(os.path.dirname(dest_item)):
os.makedirs(os.path.dirname(dest_item))
shutil.copy2(src_item, dest_item)
except Exception as e:
return False
return True
| ibelem/crosswalk-test-suite | apptools/apptools-manifest-tests/comm.py | Python | bsd-3-clause | 8,359 |
##########################################################################
#
# Copyright (c) 2011, Image Engine Design Inc. 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 Image Engine Design nor the names of any
# other contributors to this software 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 unittest
import IECore
class DataConvertOpTest( unittest.TestCase ) :
def testScaling( self ) :
o = IECore.DataConvertOp()(
data = IECore.FloatVectorData( [ 0, 0.5, 1 ] ),
targetType = IECore.UCharVectorData.staticTypeId()
)
self.assertEqual(
o,
IECore.UCharVectorData( [ 0, 128, 255 ] )
)
def testDimensionUpConversion( self ) :
o = IECore.DataConvertOp()(
data = IECore.FloatVectorData( [ 0, 0.5, 1, 0.1, 2, 10 ] ),
targetType = IECore.V3fVectorData.staticTypeId()
)
self.assertEqual(
o,
IECore.V3fVectorData( [ IECore.V3f( 0, 0.5, 1 ), IECore.V3f( 0.1, 2, 10 ) ] )
)
def testDimensionDownConversion( self ) :
o = IECore.DataConvertOp()(
data = IECore.V3iVectorData( [ IECore.V3i( 1, 2, 3 ), IECore.V3i( 4, 5, 6 ) ] ),
targetType = IECore.IntVectorData.staticTypeId()
)
self.assertEqual(
o,
IECore.IntVectorData( [ 1, 2, 3, 4, 5, 6 ] )
)
def testWrongSizeForDimensions( self ) :
self.assertRaises(
RuntimeError,
IECore.DataConvertOp(),
data = IECore.FloatVectorData( [ 1, 2 ] ),
targetType = IECore.V3fVectorData.staticTypeId()
)
if __name__ == "__main__":
unittest.main()
| lento/cortex | test/IECore/DataConvertOpTest.py | Python | bsd-3-clause | 3,033 |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.webui.jsptag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.TagSupport;
/**
* Tag for including a "sidebar" - a column on the right-hand side of the page.
* Must be used within a dspace:layout tag.
*
* @author Peter Breton
* @version $Revision$
*/
public class SidebarTag extends BodyTagSupport
{
public SidebarTag()
{
super();
}
public int doAfterBody() throws JspException
{
LayoutTag tag = (LayoutTag) TagSupport.findAncestorWithClass(this,
LayoutTag.class);
if (tag == null)
{
throw new JspException(
"Sidebar tag must be in an enclosing Layout tag");
}
tag.setSidebar(getBodyContent().getString());
return SKIP_BODY;
}
}
| jamie-dryad/dryad-repo | dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/jsptag/SidebarTag.java | Java | bsd-3-clause | 1,080 |
<?php
/**
* Base static class for performing query and update operations on the 'plugin_data' table.
*
*
*
* @package propel.generator.datawrapper.om
*/
abstract class BasePluginDataPeer
{
/** the default database name for this class */
const DATABASE_NAME = 'datawrapper';
/** the table name for this class */
const TABLE_NAME = 'plugin_data';
/** the related Propel class for this table */
const OM_CLASS = 'PluginData';
/** the related TableMap class for this table */
const TM_CLASS = 'PluginDataTableMap';
/** The total number of columns. */
const NUM_COLUMNS = 5;
/** The number of lazy-loaded columns. */
const NUM_LAZY_LOAD_COLUMNS = 0;
/** The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */
const NUM_HYDRATE_COLUMNS = 5;
/** the column name for the id field */
const ID = 'plugin_data.id';
/** the column name for the plugin_id field */
const PLUGIN_ID = 'plugin_data.plugin_id';
/** the column name for the stored_at field */
const STORED_AT = 'plugin_data.stored_at';
/** the column name for the key field */
const KEY = 'plugin_data.key';
/** the column name for the data field */
const DATA = 'plugin_data.data';
/** The default string format for model objects of the related table **/
const DEFAULT_STRING_FORMAT = 'YAML';
/**
* An identiy map to hold any loaded instances of PluginData objects.
* This must be public so that other peer classes can access this when hydrating from JOIN
* queries.
* @var array PluginData[]
*/
public static $instances = array();
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. PluginDataPeer::$fieldNames[PluginDataPeer::TYPE_PHPNAME][0] = 'Id'
*/
protected static $fieldNames = array (
BasePeer::TYPE_PHPNAME => array ('Id', 'PluginId', 'StoredAt', 'Key', 'Data', ),
BasePeer::TYPE_STUDLYPHPNAME => array ('id', 'pluginId', 'storedAt', 'key', 'data', ),
BasePeer::TYPE_COLNAME => array (PluginDataPeer::ID, PluginDataPeer::PLUGIN_ID, PluginDataPeer::STORED_AT, PluginDataPeer::KEY, PluginDataPeer::DATA, ),
BasePeer::TYPE_RAW_COLNAME => array ('ID', 'PLUGIN_ID', 'STORED_AT', 'KEY', 'DATA', ),
BasePeer::TYPE_FIELDNAME => array ('id', 'plugin_id', 'stored_at', 'key', 'data', ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, )
);
/**
* holds an array of keys for quick access to the fieldnames array
*
* first dimension keys are the type constants
* e.g. PluginDataPeer::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0
*/
protected static $fieldKeys = array (
BasePeer::TYPE_PHPNAME => array ('Id' => 0, 'PluginId' => 1, 'StoredAt' => 2, 'Key' => 3, 'Data' => 4, ),
BasePeer::TYPE_STUDLYPHPNAME => array ('id' => 0, 'pluginId' => 1, 'storedAt' => 2, 'key' => 3, 'data' => 4, ),
BasePeer::TYPE_COLNAME => array (PluginDataPeer::ID => 0, PluginDataPeer::PLUGIN_ID => 1, PluginDataPeer::STORED_AT => 2, PluginDataPeer::KEY => 3, PluginDataPeer::DATA => 4, ),
BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'PLUGIN_ID' => 1, 'STORED_AT' => 2, 'KEY' => 3, 'DATA' => 4, ),
BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'plugin_id' => 1, 'stored_at' => 2, 'key' => 3, 'data' => 4, ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, )
);
/**
* Translates a fieldname to another type
*
* @param string $name field name
* @param string $fromType One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
* BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM
* @param string $toType One of the class type constants
* @return string translated name of the field.
* @throws PropelException - if the specified name could not be found in the fieldname mappings.
*/
public static function translateFieldName($name, $fromType, $toType)
{
$toNames = PluginDataPeer::getFieldNames($toType);
$key = isset(PluginDataPeer::$fieldKeys[$fromType][$name]) ? PluginDataPeer::$fieldKeys[$fromType][$name] : null;
if ($key === null) {
throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(PluginDataPeer::$fieldKeys[$fromType], true));
}
return $toNames[$key];
}
/**
* Returns an array of field names.
*
* @param string $type The type of fieldnames to return:
* One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
* BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM
* @return array A list of field names
* @throws PropelException - if the type is not valid.
*/
public static function getFieldNames($type = BasePeer::TYPE_PHPNAME)
{
if (!array_key_exists($type, PluginDataPeer::$fieldNames)) {
throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. ' . $type . ' was given.');
}
return PluginDataPeer::$fieldNames[$type];
}
/**
* Convenience method which changes table.column to alias.column.
*
* Using this method you can maintain SQL abstraction while using column aliases.
* <code>
* $c->addAlias("alias1", TablePeer::TABLE_NAME);
* $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN);
* </code>
* @param string $alias The alias for the current table.
* @param string $column The column name for current table. (i.e. PluginDataPeer::COLUMN_NAME).
* @return string
*/
public static function alias($alias, $column)
{
return str_replace(PluginDataPeer::TABLE_NAME.'.', $alias.'.', $column);
}
/**
* Add all the columns needed to create a new object.
*
* Note: any columns that were marked with lazyLoad="true" in the
* XML schema will not be added to the select list and only loaded
* on demand.
*
* @param Criteria $criteria object containing the columns to add.
* @param string $alias optional table alias
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function addSelectColumns(Criteria $criteria, $alias = null)
{
if (null === $alias) {
$criteria->addSelectColumn(PluginDataPeer::ID);
$criteria->addSelectColumn(PluginDataPeer::PLUGIN_ID);
$criteria->addSelectColumn(PluginDataPeer::STORED_AT);
$criteria->addSelectColumn(PluginDataPeer::KEY);
$criteria->addSelectColumn(PluginDataPeer::DATA);
} else {
$criteria->addSelectColumn($alias . '.id');
$criteria->addSelectColumn($alias . '.plugin_id');
$criteria->addSelectColumn($alias . '.stored_at');
$criteria->addSelectColumn($alias . '.key');
$criteria->addSelectColumn($alias . '.data');
}
}
/**
* Returns the number of rows matching criteria.
*
* @param Criteria $criteria
* @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead.
* @param PropelPDO $con
* @return int Number of matching rows.
*/
public static function doCount(Criteria $criteria, $distinct = false, PropelPDO $con = null)
{
// we may modify criteria, so copy it first
$criteria = clone $criteria;
// We need to set the primary table name, since in the case that there are no WHERE columns
// it will be impossible for the BasePeer::createSelectSql() method to determine which
// tables go into the FROM clause.
$criteria->setPrimaryTableName(PluginDataPeer::TABLE_NAME);
if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->setDistinct();
}
if (!$criteria->hasSelectClause()) {
PluginDataPeer::addSelectColumns($criteria);
}
$criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count
$criteria->setDbName(PluginDataPeer::DATABASE_NAME); // Set the correct dbName
if ($con === null) {
$con = Propel::getConnection(PluginDataPeer::DATABASE_NAME, Propel::CONNECTION_READ);
}
// BasePeer returns a PDOStatement
$stmt = BasePeer::doCount($criteria, $con);
if ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$count = (int) $row[0];
} else {
$count = 0; // no rows returned; we infer that means 0 matches.
}
$stmt->closeCursor();
return $count;
}
/**
* Selects one object from the DB.
*
* @param Criteria $criteria object used to create the SELECT statement.
* @param PropelPDO $con
* @return PluginData
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectOne(Criteria $criteria, PropelPDO $con = null)
{
$critcopy = clone $criteria;
$critcopy->setLimit(1);
$objects = PluginDataPeer::doSelect($critcopy, $con);
if ($objects) {
return $objects[0];
}
return null;
}
/**
* Selects several row from the DB.
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param PropelPDO $con
* @return array Array of selected Objects
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelect(Criteria $criteria, PropelPDO $con = null)
{
return PluginDataPeer::populateObjects(PluginDataPeer::doSelectStmt($criteria, $con));
}
/**
* Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement.
*
* Use this method directly if you want to work with an executed statement directly (for example
* to perform your own object hydration).
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param PropelPDO $con The connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return PDOStatement The executed PDOStatement object.
* @see BasePeer::doSelect()
*/
public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null)
{
if ($con === null) {
$con = Propel::getConnection(PluginDataPeer::DATABASE_NAME, Propel::CONNECTION_READ);
}
if (!$criteria->hasSelectClause()) {
$criteria = clone $criteria;
PluginDataPeer::addSelectColumns($criteria);
}
// Set the correct dbName
$criteria->setDbName(PluginDataPeer::DATABASE_NAME);
// BasePeer returns a PDOStatement
return BasePeer::doSelect($criteria, $con);
}
/**
* Adds an object to the instance pool.
*
* Propel keeps cached copies of objects in an instance pool when they are retrieved
* from the database. In some cases -- especially when you override doSelect*()
* methods in your stub classes -- you may need to explicitly add objects
* to the cache in order to ensure that the same objects are always returned by doSelect*()
* and retrieveByPK*() calls.
*
* @param PluginData $obj A PluginData object.
* @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally).
*/
public static function addInstanceToPool($obj, $key = null)
{
if (Propel::isInstancePoolingEnabled()) {
if ($key === null) {
$key = (string) $obj->getId();
} // if key === null
PluginDataPeer::$instances[$key] = $obj;
}
}
/**
* Removes an object from the instance pool.
*
* Propel keeps cached copies of objects in an instance pool when they are retrieved
* from the database. In some cases -- especially when you override doDelete
* methods in your stub classes -- you may need to explicitly remove objects
* from the cache in order to prevent returning objects that no longer exist.
*
* @param mixed $value A PluginData object or a primary key value.
*
* @return void
* @throws PropelException - if the value is invalid.
*/
public static function removeInstanceFromPool($value)
{
if (Propel::isInstancePoolingEnabled() && $value !== null) {
if (is_object($value) && $value instanceof PluginData) {
$key = (string) $value->getId();
} elseif (is_scalar($value)) {
// assume we've been passed a primary key
$key = (string) $value;
} else {
$e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or PluginData object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true)));
throw $e;
}
unset(PluginDataPeer::$instances[$key]);
}
} // removeInstanceFromPool()
/**
* Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table.
*
* For tables with a single-column primary key, that simple pkey value will be returned. For tables with
* a multi-column primary key, a serialize()d version of the primary key will be returned.
*
* @param string $key The key (@see getPrimaryKeyHash()) for this instance.
* @return PluginData Found object or null if 1) no instance exists for specified key or 2) instance pooling has been disabled.
* @see getPrimaryKeyHash()
*/
public static function getInstanceFromPool($key)
{
if (Propel::isInstancePoolingEnabled()) {
if (isset(PluginDataPeer::$instances[$key])) {
return PluginDataPeer::$instances[$key];
}
}
return null; // just to be explicit
}
/**
* Clear the instance pool.
*
* @return void
*/
public static function clearInstancePool($and_clear_all_references = false)
{
if ($and_clear_all_references)
{
foreach (PluginDataPeer::$instances as $instance)
{
$instance->clearAllReferences(true);
}
}
PluginDataPeer::$instances = array();
}
/**
* Method to invalidate the instance pool of all tables related to plugin_data
* by a foreign key with ON DELETE CASCADE
*/
public static function clearRelatedInstancePool()
{
}
/**
* Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table.
*
* For tables with a single-column primary key, that simple pkey value will be returned. For tables with
* a multi-column primary key, a serialize()d version of the primary key will be returned.
*
* @param array $row PropelPDO resultset row.
* @param int $startcol The 0-based offset for reading from the resultset row.
* @return string A string version of PK or null if the components of primary key in result array are all null.
*/
public static function getPrimaryKeyHashFromRow($row, $startcol = 0)
{
// If the PK cannot be derived from the row, return null.
if ($row[$startcol] === null) {
return null;
}
return (string) $row[$startcol];
}
/**
* Retrieves the primary key from the DB resultset row
* For tables with a single-column primary key, that simple pkey value will be returned. For tables with
* a multi-column primary key, an array of the primary key columns will be returned.
*
* @param array $row PropelPDO resultset row.
* @param int $startcol The 0-based offset for reading from the resultset row.
* @return mixed The primary key of the row
*/
public static function getPrimaryKeyFromRow($row, $startcol = 0)
{
return (int) $row[$startcol];
}
/**
* The returned array will contain objects of the default type or
* objects that inherit from the default.
*
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function populateObjects(PDOStatement $stmt)
{
$results = array();
// set the class once to avoid overhead in the loop
$cls = PluginDataPeer::getOMClass();
// populate the object(s)
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$key = PluginDataPeer::getPrimaryKeyHashFromRow($row, 0);
if (null !== ($obj = PluginDataPeer::getInstanceFromPool($key))) {
// We no longer rehydrate the object, since this can cause data loss.
// See http://www.propelorm.org/ticket/509
// $obj->hydrate($row, 0, true); // rehydrate
$results[] = $obj;
} else {
$obj = new $cls();
$obj->hydrate($row);
$results[] = $obj;
PluginDataPeer::addInstanceToPool($obj, $key);
} // if key exists
}
$stmt->closeCursor();
return $results;
}
/**
* Populates an object of the default type or an object that inherit from the default.
*
* @param array $row PropelPDO resultset row.
* @param int $startcol The 0-based offset for reading from the resultset row.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return array (PluginData object, last column rank)
*/
public static function populateObject($row, $startcol = 0)
{
$key = PluginDataPeer::getPrimaryKeyHashFromRow($row, $startcol);
if (null !== ($obj = PluginDataPeer::getInstanceFromPool($key))) {
// We no longer rehydrate the object, since this can cause data loss.
// See http://www.propelorm.org/ticket/509
// $obj->hydrate($row, $startcol, true); // rehydrate
$col = $startcol + PluginDataPeer::NUM_HYDRATE_COLUMNS;
} else {
$cls = PluginDataPeer::OM_CLASS;
$obj = new $cls();
$col = $obj->hydrate($row, $startcol);
PluginDataPeer::addInstanceToPool($obj, $key);
}
return array($obj, $col);
}
/**
* Returns the number of rows matching criteria, joining the related Plugin table
*
* @param Criteria $criteria
* @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead.
* @param PropelPDO $con
* @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN
* @return int Number of matching rows.
*/
public static function doCountJoinPlugin(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN)
{
// we're going to modify criteria, so copy it first
$criteria = clone $criteria;
// We need to set the primary table name, since in the case that there are no WHERE columns
// it will be impossible for the BasePeer::createSelectSql() method to determine which
// tables go into the FROM clause.
$criteria->setPrimaryTableName(PluginDataPeer::TABLE_NAME);
if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->setDistinct();
}
if (!$criteria->hasSelectClause()) {
PluginDataPeer::addSelectColumns($criteria);
}
$criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count
// Set the correct dbName
$criteria->setDbName(PluginDataPeer::DATABASE_NAME);
if ($con === null) {
$con = Propel::getConnection(PluginDataPeer::DATABASE_NAME, Propel::CONNECTION_READ);
}
$criteria->addJoin(PluginDataPeer::PLUGIN_ID, PluginPeer::ID, $join_behavior);
$stmt = BasePeer::doCount($criteria, $con);
if ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$count = (int) $row[0];
} else {
$count = 0; // no rows returned; we infer that means 0 matches.
}
$stmt->closeCursor();
return $count;
}
/**
* Selects a collection of PluginData objects pre-filled with their Plugin objects.
* @param Criteria $criteria
* @param PropelPDO $con
* @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN
* @return array Array of PluginData objects.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectJoinPlugin(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN)
{
$criteria = clone $criteria;
// Set the correct dbName if it has not been overridden
if ($criteria->getDbName() == Propel::getDefaultDB()) {
$criteria->setDbName(PluginDataPeer::DATABASE_NAME);
}
PluginDataPeer::addSelectColumns($criteria);
$startcol = PluginDataPeer::NUM_HYDRATE_COLUMNS;
PluginPeer::addSelectColumns($criteria);
$criteria->addJoin(PluginDataPeer::PLUGIN_ID, PluginPeer::ID, $join_behavior);
$stmt = BasePeer::doSelect($criteria, $con);
$results = array();
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$key1 = PluginDataPeer::getPrimaryKeyHashFromRow($row, 0);
if (null !== ($obj1 = PluginDataPeer::getInstanceFromPool($key1))) {
// We no longer rehydrate the object, since this can cause data loss.
// See http://www.propelorm.org/ticket/509
// $obj1->hydrate($row, 0, true); // rehydrate
} else {
$cls = PluginDataPeer::getOMClass();
$obj1 = new $cls();
$obj1->hydrate($row);
PluginDataPeer::addInstanceToPool($obj1, $key1);
} // if $obj1 already loaded
$key2 = PluginPeer::getPrimaryKeyHashFromRow($row, $startcol);
if ($key2 !== null) {
$obj2 = PluginPeer::getInstanceFromPool($key2);
if (!$obj2) {
$cls = PluginPeer::getOMClass();
$obj2 = new $cls();
$obj2->hydrate($row, $startcol);
PluginPeer::addInstanceToPool($obj2, $key2);
} // if obj2 already loaded
// Add the $obj1 (PluginData) to $obj2 (Plugin)
$obj2->addPluginData($obj1);
} // if joined row was not null
$results[] = $obj1;
}
$stmt->closeCursor();
return $results;
}
/**
* Returns the number of rows matching criteria, joining all related tables
*
* @param Criteria $criteria
* @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead.
* @param PropelPDO $con
* @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN
* @return int Number of matching rows.
*/
public static function doCountJoinAll(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN)
{
// we're going to modify criteria, so copy it first
$criteria = clone $criteria;
// We need to set the primary table name, since in the case that there are no WHERE columns
// it will be impossible for the BasePeer::createSelectSql() method to determine which
// tables go into the FROM clause.
$criteria->setPrimaryTableName(PluginDataPeer::TABLE_NAME);
if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->setDistinct();
}
if (!$criteria->hasSelectClause()) {
PluginDataPeer::addSelectColumns($criteria);
}
$criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count
// Set the correct dbName
$criteria->setDbName(PluginDataPeer::DATABASE_NAME);
if ($con === null) {
$con = Propel::getConnection(PluginDataPeer::DATABASE_NAME, Propel::CONNECTION_READ);
}
$criteria->addJoin(PluginDataPeer::PLUGIN_ID, PluginPeer::ID, $join_behavior);
$stmt = BasePeer::doCount($criteria, $con);
if ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$count = (int) $row[0];
} else {
$count = 0; // no rows returned; we infer that means 0 matches.
}
$stmt->closeCursor();
return $count;
}
/**
* Selects a collection of PluginData objects pre-filled with all related objects.
*
* @param Criteria $criteria
* @param PropelPDO $con
* @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN
* @return array Array of PluginData objects.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectJoinAll(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN)
{
$criteria = clone $criteria;
// Set the correct dbName if it has not been overridden
if ($criteria->getDbName() == Propel::getDefaultDB()) {
$criteria->setDbName(PluginDataPeer::DATABASE_NAME);
}
PluginDataPeer::addSelectColumns($criteria);
$startcol2 = PluginDataPeer::NUM_HYDRATE_COLUMNS;
PluginPeer::addSelectColumns($criteria);
$startcol3 = $startcol2 + PluginPeer::NUM_HYDRATE_COLUMNS;
$criteria->addJoin(PluginDataPeer::PLUGIN_ID, PluginPeer::ID, $join_behavior);
$stmt = BasePeer::doSelect($criteria, $con);
$results = array();
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$key1 = PluginDataPeer::getPrimaryKeyHashFromRow($row, 0);
if (null !== ($obj1 = PluginDataPeer::getInstanceFromPool($key1))) {
// We no longer rehydrate the object, since this can cause data loss.
// See http://www.propelorm.org/ticket/509
// $obj1->hydrate($row, 0, true); // rehydrate
} else {
$cls = PluginDataPeer::getOMClass();
$obj1 = new $cls();
$obj1->hydrate($row);
PluginDataPeer::addInstanceToPool($obj1, $key1);
} // if obj1 already loaded
// Add objects for joined Plugin rows
$key2 = PluginPeer::getPrimaryKeyHashFromRow($row, $startcol2);
if ($key2 !== null) {
$obj2 = PluginPeer::getInstanceFromPool($key2);
if (!$obj2) {
$cls = PluginPeer::getOMClass();
$obj2 = new $cls();
$obj2->hydrate($row, $startcol2);
PluginPeer::addInstanceToPool($obj2, $key2);
} // if obj2 loaded
// Add the $obj1 (PluginData) to the collection in $obj2 (Plugin)
$obj2->addPluginData($obj1);
} // if joined row not null
$results[] = $obj1;
}
$stmt->closeCursor();
return $results;
}
/**
* Returns the TableMap related to this peer.
* This method is not needed for general use but a specific application could have a need.
* @return TableMap
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getTableMap()
{
return Propel::getDatabaseMap(PluginDataPeer::DATABASE_NAME)->getTable(PluginDataPeer::TABLE_NAME);
}
/**
* Add a TableMap instance to the database for this peer class.
*/
public static function buildTableMap()
{
$dbMap = Propel::getDatabaseMap(BasePluginDataPeer::DATABASE_NAME);
if (!$dbMap->hasTable(BasePluginDataPeer::TABLE_NAME)) {
$dbMap->addTableObject(new PluginDataTableMap());
}
}
/**
* The class that the Peer will make instances of.
*
*
* @return string ClassName
*/
public static function getOMClass($row = 0, $colnum = 0)
{
return PluginDataPeer::OM_CLASS;
}
/**
* Performs an INSERT on the database, given a PluginData or Criteria object.
*
* @param mixed $values Criteria or PluginData object containing data that is used to create the INSERT statement.
* @param PropelPDO $con the PropelPDO connection to use
* @return mixed The new primary key.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doInsert($values, PropelPDO $con = null)
{
if ($con === null) {
$con = Propel::getConnection(PluginDataPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} else {
$criteria = $values->buildCriteria(); // build Criteria from PluginData object
}
if ($criteria->containsKey(PluginDataPeer::ID) && $criteria->keyContainsValue(PluginDataPeer::ID) ) {
throw new PropelException('Cannot insert a value for auto-increment primary key ('.PluginDataPeer::ID.')');
}
// Set the correct dbName
$criteria->setDbName(PluginDataPeer::DATABASE_NAME);
try {
// use transaction because $criteria could contain info
// for more than one table (I guess, conceivably)
$con->beginTransaction();
$pk = BasePeer::doInsert($criteria, $con);
$con->commit();
} catch (PropelException $e) {
$con->rollBack();
throw $e;
}
return $pk;
}
/**
* Performs an UPDATE on the database, given a PluginData or Criteria object.
*
* @param mixed $values Criteria or PluginData object containing data that is used to create the UPDATE statement.
* @param PropelPDO $con The connection to use (specify PropelPDO connection object to exert more control over transactions).
* @return int The number of affected rows (if supported by underlying database driver).
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doUpdate($values, PropelPDO $con = null)
{
if ($con === null) {
$con = Propel::getConnection(PluginDataPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
}
$selectCriteria = new Criteria(PluginDataPeer::DATABASE_NAME);
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
$comparison = $criteria->getComparison(PluginDataPeer::ID);
$value = $criteria->remove(PluginDataPeer::ID);
if ($value) {
$selectCriteria->add(PluginDataPeer::ID, $value, $comparison);
} else {
$selectCriteria->setPrimaryTableName(PluginDataPeer::TABLE_NAME);
}
} else { // $values is PluginData object
$criteria = $values->buildCriteria(); // gets full criteria
$selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s)
}
// set the correct dbName
$criteria->setDbName(PluginDataPeer::DATABASE_NAME);
return BasePeer::doUpdate($selectCriteria, $criteria, $con);
}
/**
* Deletes all rows from the plugin_data table.
*
* @param PropelPDO $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver).
* @throws PropelException
*/
public static function doDeleteAll(PropelPDO $con = null)
{
if ($con === null) {
$con = Propel::getConnection(PluginDataPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
}
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->beginTransaction();
$affectedRows += BasePeer::doDeleteAll(PluginDataPeer::TABLE_NAME, $con, PluginDataPeer::DATABASE_NAME);
// Because this db requires some delete cascade/set null emulation, we have to
// clear the cached instance *after* the emulation has happened (since
// instances get re-added by the select statement contained therein).
PluginDataPeer::clearInstancePool();
PluginDataPeer::clearRelatedInstancePool();
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollBack();
throw $e;
}
}
/**
* Performs a DELETE on the database, given a PluginData or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or PluginData object or primary key or array of primary keys
* which is used to create the DELETE statement
* @param PropelPDO $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows
* if supported by native driver or if emulated using Propel.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doDelete($values, PropelPDO $con = null)
{
if ($con === null) {
$con = Propel::getConnection(PluginDataPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
}
if ($values instanceof Criteria) {
// invalidate the cache for all objects of this type, since we have no
// way of knowing (without running a query) what objects should be invalidated
// from the cache based on this Criteria.
PluginDataPeer::clearInstancePool();
// rename for clarity
$criteria = clone $values;
} elseif ($values instanceof PluginData) { // it's a model object
// invalidate the cache for this single object
PluginDataPeer::removeInstanceFromPool($values);
// create criteria based on pk values
$criteria = $values->buildPkeyCriteria();
} else { // it's a primary key, or an array of pks
$criteria = new Criteria(PluginDataPeer::DATABASE_NAME);
$criteria->add(PluginDataPeer::ID, (array) $values, Criteria::IN);
// invalidate the cache for this object(s)
foreach ((array) $values as $singleval) {
PluginDataPeer::removeInstanceFromPool($singleval);
}
}
// Set the correct dbName
$criteria->setDbName(PluginDataPeer::DATABASE_NAME);
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->beginTransaction();
$affectedRows += BasePeer::doDelete($criteria, $con);
PluginDataPeer::clearRelatedInstancePool();
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollBack();
throw $e;
}
}
/**
* Validates all modified columns of given PluginData object.
* If parameter $columns is either a single column name or an array of column names
* than only those columns are validated.
*
* NOTICE: This does not apply to primary or foreign keys for now.
*
* @param PluginData $obj The object to validate.
* @param mixed $cols Column name or array of column names.
*
* @return mixed TRUE if all columns are valid or the error message of the first invalid column.
*/
public static function doValidate($obj, $cols = null)
{
$columns = array();
if ($cols) {
$dbMap = Propel::getDatabaseMap(PluginDataPeer::DATABASE_NAME);
$tableMap = $dbMap->getTable(PluginDataPeer::TABLE_NAME);
if (! is_array($cols)) {
$cols = array($cols);
}
foreach ($cols as $colName) {
if ($tableMap->hasColumn($colName)) {
$get = 'get' . $tableMap->getColumn($colName)->getPhpName();
$columns[$colName] = $obj->$get();
}
}
} else {
}
return BasePeer::doValidate(PluginDataPeer::DATABASE_NAME, PluginDataPeer::TABLE_NAME, $columns);
}
/**
* Retrieve a single object by pkey.
*
* @param int $pk the primary key.
* @param PropelPDO $con the connection to use
* @return PluginData
*/
public static function retrieveByPK($pk, PropelPDO $con = null)
{
if (null !== ($obj = PluginDataPeer::getInstanceFromPool((string) $pk))) {
return $obj;
}
if ($con === null) {
$con = Propel::getConnection(PluginDataPeer::DATABASE_NAME, Propel::CONNECTION_READ);
}
$criteria = new Criteria(PluginDataPeer::DATABASE_NAME);
$criteria->add(PluginDataPeer::ID, $pk);
$v = PluginDataPeer::doSelect($criteria, $con);
return !empty($v) > 0 ? $v[0] : null;
}
/**
* Retrieve multiple objects by pkey.
*
* @param array $pks List of primary keys
* @param PropelPDO $con the connection to use
* @return PluginData[]
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function retrieveByPKs($pks, PropelPDO $con = null)
{
if ($con === null) {
$con = Propel::getConnection(PluginDataPeer::DATABASE_NAME, Propel::CONNECTION_READ);
}
$objs = null;
if (empty($pks)) {
$objs = array();
} else {
$criteria = new Criteria(PluginDataPeer::DATABASE_NAME);
$criteria->add(PluginDataPeer::ID, $pks, Criteria::IN);
$objs = PluginDataPeer::doSelect($criteria, $con);
}
return $objs;
}
} // BasePluginDataPeer
// This is the static code needed to register the TableMap for this table with the main Propel class.
//
BasePluginDataPeer::buildTableMap();
| kendrick-k/datawrapper | lib/core/build/classes/datawrapper/om/BasePluginDataPeer.php | PHP | mit | 40,214 |
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Models\Role, App\Models\User, App\Models\Contact, App\Models\Post, App\Models\Tag, App\Models\PostTag, App\Models\Comment;
use App\Services\LoremIpsumGenerator;
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Model::unguard();
$lipsum = new LoremIpsumGenerator;
Role::create([
'title' => 'Administrator',
'slug' => 'admin'
]);
Role::create([
'title' => 'Redactor',
'slug' => 'redac'
]);
Role::create([
'title' => 'User',
'slug' => 'user'
]);
User::create([
'username' => 'GreatAdmin',
'email' => 'admin@la.fr',
'password' => bcrypt('admin'),
'seen' => true,
'role_id' => 1,
'confirmed' => true
]);
User::create([
'username' => 'GreatRedactor',
'email' => 'redac@la.fr',
'password' => bcrypt('redac'),
'seen' => true,
'role_id' => 2,
'valid' => true,
'confirmed' => true
]);
User::create([
'username' => 'Walker',
'email' => 'walker@la.fr',
'password' => bcrypt('walker'),
'role_id' => 3,
'confirmed' => true
]);
User::create([
'username' => 'Slacker',
'email' => 'slacker@la.fr',
'password' => bcrypt('slacker'),
'role_id' => 3,
'confirmed' => true
]);
Contact::create([
'name' => 'Dupont',
'email' => 'dupont@la.fr',
'text' => 'Lorem ipsum inceptos malesuada leo fusce tortor sociosqu semper, facilisis semper class tempus faucibus tristique duis eros, cubilia quisque habitasse aliquam fringilla orci non. Vel laoreet dolor enim justo facilisis neque accumsan, in ad venenatis hac per dictumst nulla ligula, donec mollis massa porttitor ullamcorper risus. Eu platea fringilla, habitasse.'
]);
Contact::create([
'name' => 'Durand',
'email' => 'durand@la.fr',
'text' => ' Lorem ipsum erat non elit ultrices placerat, netus metus feugiat non conubia fusce porttitor, sociosqu diam commodo metus in. Himenaeos vitae aptent consequat luctus purus eleifend enim, sollicitudin eleifend porta malesuada ac class conubia, condimentum mauris facilisis conubia quis scelerisque. Lacinia tempus nullam felis fusce ac potenti netus ornare semper molestie, iaculis fermentum ornare curabitur tincidunt imperdiet scelerisque imperdiet euismod.'
]);
Contact::create([
'name' => 'Martin',
'email' => 'martin@la.fr',
'text' => 'Lorem ipsum tempor netus aenean ligula habitant vehicula tempor ultrices, placerat sociosqu ultrices consectetur ullamcorper tincidunt quisque tellus, ante nostra euismod nec suspendisse sem curabitur elit. Malesuada lacus viverra sagittis sit ornare orci, augue nullam adipiscing pulvinar libero aliquam vestibulum, platea cursus pellentesque leo dui. Lectus curabitur euismod ad, erat.',
'seen' => true
]);
Tag::create([
'tag' => 'Tag1'
]);
Tag::create([
'tag' => 'Tag2'
]);
Tag::create([
'tag' => 'Tag3'
]);
Tag::create([
'tag' => 'Tag4'
]);
Post::create([
'title' => 'Post 1',
'slug' => 'post-1',
'summary' => '<img alt="" src="/filemanager/userfiles/greatredactor/mega-champignon-icone-8453-128.png" style="float:left; height:128px; width:128px" />' . $lipsum->getContent(50),
'content' => $lipsum->getContent(500),
'active' => true,
'user_id' => 1
]);
Post::create([
'title' => 'Post 2',
'slug' => 'post-2',
'summary' => '<img alt="" src="/filemanager/userfiles/greatredactor/goomba-icone-7704-128.png" style="float:left; height:128px; width:128px" />' . $lipsum->getContent(50),
'content' => '<p>Lorem ipsum convallis ac curae non elit ultrices placerat netus metus feugiat, non conubia fusce porttitor sociosqu diam commodo metus in himenaeos, vitae aptent consequat luctus purus eleifend enim sollicitudin eleifend porta. Malesuada ac class conubia condimentum mauris facilisis conubia quis scelerisque lacinia, tempus nullam felis fusce ac potenti netus ornare semper. Molestie iaculis fermentum ornare curabitur tincidunt imperdiet scelerisque, imperdiet euismod scelerisque torquent curae rhoncus, sollicitudin tortor placerat aptent hac nec. Posuere suscipit sed tortor neque urna hendrerit vehicula duis litora tristique congue nec auctor felis libero, ornare habitasse nec elit felis inceptos tellus inceptos cubilia quis mattis faucibus sem non.</p>
<p>Odio fringilla class aliquam metus ipsum lorem luctus pharetra dictum, vehicula tempus in venenatis gravida ut gravida proin orci, quis sed platea mi quisque hendrerit semper hendrerit. Facilisis ante sapien faucibus ligula commodo vestibulum rutrum pretium, varius sem aliquet himenaeos dolor cursus nunc habitasse, aliquam ut curabitur ipsum luctus ut rutrum. Odio condimentum donec suscipit molestie est etiam sit rutrum dui nostra, sem aliquet conubia nullam sollicitudin rhoncus venenatis vivamus rhoncus netus, risus tortor non mauris turpis eget integer nibh dolor. Commodo venenatis ut molestie semper adipiscing amet cras, class donec sapien malesuada auctor sapien arcu inceptos, aenean consequat metus litora mattis vivamus.</p>
<pre>
<code class="language-php">protected function getUserByRecaller($recaller)
{
if ($this->validRecaller($recaller) && ! $this->tokenRetrievalAttempted)
{
$this->tokenRetrievalAttempted = true;
list($id, $token) = explode("|", $recaller, 2);
$this->viaRemember = ! is_null($user = $this->provider->retrieveByToken($id, $token));
return $user;
}
}</code></pre>
<p>Feugiat arcu adipiscing mauris primis ante ullamcorper ad nisi, lobortis arcu per orci malesuada blandit metus tortor, urna turpis consectetur porttitor egestas sed eleifend. Eget tincidunt pharetra varius tincidunt morbi malesuada elementum mi torquent mollis, eu lobortis curae purus amet vivamus amet nulla torquent, nibh eu diam aliquam pretium donec aliquam tempus lacus. Tempus feugiat lectus cras non velit mollis sit et integer, egestas habitant auctor integer sem at nam massa himenaeos, netus vel dapibus nibh malesuada leo fusce tortor. Sociosqu semper facilisis semper class tempus faucibus tristique duis eros, cubilia quisque habitasse aliquam fringilla orci non vel, laoreet dolor enim justo facilisis neque accumsan in.</p>
<p>Ad venenatis hac per dictumst nulla ligula donec, mollis massa porttitor ullamcorper risus eu platea, fringilla habitasse suscipit pellentesque donec est. Habitant vehicula tempor ultrices placerat sociosqu ultrices consectetur ullamcorper tincidunt quisque tellus, ante nostra euismod nec suspendisse sem curabitur elit malesuada lacus. Viverra sagittis sit ornare orci augue nullam adipiscing pulvinar libero aliquam vestibulum platea cursus pellentesque leo dui lectus, curabitur euismod ad erat curae non elit ultrices placerat netus metus feugiat non conubia fusce porttitor. Sociosqu diam commodo metus in himenaeos vitae aptent consequat luctus purus eleifend enim sollicitudin eleifend, porta malesuada ac class conubia condimentum mauris facilisis conubia quis scelerisque lacinia.</p>
<p>Tempus nullam felis fusce ac potenti netus ornare semper molestie iaculis, fermentum ornare curabitur tincidunt imperdiet scelerisque imperdiet euismod. Scelerisque torquent curae rhoncus sollicitudin tortor placerat aptent hac, nec posuere suscipit sed tortor neque urna hendrerit, vehicula duis litora tristique congue nec auctor. Felis libero ornare habitasse nec elit felis, inceptos tellus inceptos cubilia quis mattis, faucibus sem non odio fringilla. Class aliquam metus ipsum lorem luctus pharetra dictum vehicula, tempus in venenatis gravida ut gravida proin orci, quis sed platea mi quisque hendrerit semper.</p>
',
'active' => true,
'user_id' => 2
]);
Post::create([
'title' => 'Post 3',
'slug' => 'post-3',
'summary' => '<img alt="" src="/filemanager/userfiles/greatredactor/rouge-shell--icone-5599-128.png" style="float:left; height:128px; width:128px" />' . $lipsum->getContent(50),
'content' => $lipsum->getContent(500),
'active' => true,
'user_id' => 2
]);
Post::create([
'title' => 'Post 4',
'slug' => 'post-4',
'summary' => '<img alt="" src="/filemanager/userfiles/greatredactor/rouge-shyguy-icone-6870-128.png" style="float:left; height:128px; width:128px" />' . $lipsum->getContent(50),
'content' => $lipsum->getContent(500),
'active' => true,
'user_id' => 2
]);
PostTag::create([
'post_id' => 1,
'tag_id' => 1
]);
PostTag::create([
'post_id' => 1,
'tag_id' => 2
]);
PostTag::create([
'post_id' => 2,
'tag_id' => 1
]);
PostTag::create([
'post_id' => 2,
'tag_id' => 2
]);
PostTag::create([
'post_id' => 2,
'tag_id' => 3
]);
PostTag::create([
'post_id' => 3,
'tag_id' => 1
]);
PostTag::create([
'post_id' => 3,
'tag_id' => 2
]);
PostTag::create([
'post_id' => 3,
'tag_id' => 4
]);
Comment::create([
'content' => $lipsum->getContent(200),
'user_id' => 2,
'post_id' => 1
]);
Comment::create([
'content' => $lipsum->getContent(200),
'user_id' => 2,
'post_id' => 2
]);
Comment::create([
'content' => $lipsum->getContent(200),
'user_id' => 3,
'post_id' => 1
]);
}
}
| sdlyhu/laravel5-example | database/seeds/DatabaseSeeder.php | PHP | mit | 9,256 |
(function(__global) {
var isWorker = typeof window == 'undefined' && typeof self != 'undefined' && typeof importScripts != 'undefined';
var isBrowser = typeof window != 'undefined' && typeof document != 'undefined';
var isWindows = typeof process != 'undefined' && typeof process.platform != 'undefined' && !!process.platform.match(/^win/);
if (!__global.console)
__global.console = { assert: function() {} };
// IE8 support
var indexOf = Array.prototype.indexOf || function(item) {
for (var i = 0, thisLen = this.length; i < thisLen; i++) {
if (this[i] === item) {
return i;
}
}
return -1;
};
var defineProperty;
(function () {
try {
if (!!Object.defineProperty({}, 'a', {}))
defineProperty = Object.defineProperty;
}
catch (e) {
defineProperty = function(obj, prop, opt) {
try {
obj[prop] = opt.value || opt.get.call(obj);
}
catch(e) {}
}
}
})();
function addToError(err, msg) {
var newErr;
if (err instanceof Error) {
newErr = new Error(err.message, err.fileName, err.lineNumber);
if (isBrowser) {
newErr.message = err.message + '\n\t' + msg;
newErr.stack = err.stack;
}
else {
// node errors only look correct with the stack modified
newErr.message = err.message;
newErr.stack = err.stack + '\n\t' + msg;
}
}
else {
newErr = err + '\n\t' + msg;
}
return newErr;
}
function __eval(source, debugName, context) {
try {
new Function(source).call(context);
}
catch(e) {
throw addToError(e, 'Evaluating ' + debugName);
}
}
var baseURI;
// environent baseURI detection
if (typeof document != 'undefined' && document.getElementsByTagName) {
baseURI = document.baseURI;
if (!baseURI) {
var bases = document.getElementsByTagName('base');
baseURI = bases[0] && bases[0].href || window.location.href;
}
// sanitize out the hash and querystring
baseURI = baseURI.split('#')[0].split('?')[0];
baseURI = baseURI.substr(0, baseURI.lastIndexOf('/') + 1);
}
else if (typeof process != 'undefined' && process.cwd) {
baseURI = 'file://' + (isWindows ? '/' : '') + process.cwd() + '/';
if (isWindows)
baseURI = baseURI.replace(/\\/g, '/');
}
else if (typeof location != 'undefined') {
baseURI = __global.location.href;
}
else {
throw new TypeError('No environment baseURI');
}
var URL = __global.URLPolyfill || __global.URL;
| ApprecieOpenSource/Apprecie | public/a/node_modules/es6-module-loader/src/wrapper-start.js | JavaScript | mit | 2,575 |
import { Animation } from '../animations/animation';
import { isPresent } from '../util/util';
import { PageTransition } from './page-transition';
const /** @type {?} */ DURATION = 500;
const /** @type {?} */ EASING = 'cubic-bezier(0.36,0.66,0.04,1)';
const /** @type {?} */ OPACITY = 'opacity';
const /** @type {?} */ TRANSFORM = 'transform';
const /** @type {?} */ TRANSLATEX = 'translateX';
const /** @type {?} */ OFF_RIGHT = '99.5%';
const /** @type {?} */ OFF_LEFT = '-33%';
const /** @type {?} */ CENTER = '0%';
const /** @type {?} */ OFF_OPACITY = 0.8;
const /** @type {?} */ SHOW_BACK_BTN_CSS = 'show-back-button';
export class IOSTransition extends PageTransition {
/**
* @return {?}
*/
init() {
super.init();
const /** @type {?} */ plt = this.plt;
const /** @type {?} */ enteringView = this.enteringView;
const /** @type {?} */ leavingView = this.leavingView;
const /** @type {?} */ opts = this.opts;
this.duration(isPresent(opts.duration) ? opts.duration : DURATION);
this.easing(isPresent(opts.easing) ? opts.easing : EASING);
const /** @type {?} */ backDirection = (opts.direction === 'back');
const /** @type {?} */ enteringHasNavbar = (enteringView && enteringView.hasNavbar());
const /** @type {?} */ leavingHasNavbar = (leavingView && leavingView.hasNavbar());
if (enteringView) {
// get the native element for the entering page
const /** @type {?} */ enteringPageEle = enteringView.pageRef().nativeElement;
// entering content
const /** @type {?} */ enteringContent = new Animation(plt, enteringView.contentRef());
enteringContent.element(enteringPageEle.querySelectorAll('ion-header > *:not(ion-navbar),ion-footer > *'));
this.add(enteringContent);
if (backDirection) {
// entering content, back direction
enteringContent
.fromTo(TRANSLATEX, OFF_LEFT, CENTER, true)
.fromTo(OPACITY, OFF_OPACITY, 1, true);
}
else {
// entering content, forward direction
enteringContent
.beforeClearStyles([OPACITY])
.fromTo(TRANSLATEX, OFF_RIGHT, CENTER, true);
}
if (enteringHasNavbar) {
// entering page has a navbar
const /** @type {?} */ enteringNavbarEle = enteringPageEle.querySelector('ion-navbar');
const /** @type {?} */ enteringNavBar = new Animation(plt, enteringNavbarEle);
this.add(enteringNavBar);
const /** @type {?} */ enteringTitle = new Animation(plt, enteringNavbarEle.querySelector('ion-title'));
const /** @type {?} */ enteringNavbarItems = new Animation(plt, enteringNavbarEle.querySelectorAll('ion-buttons,[menuToggle]'));
const /** @type {?} */ enteringNavbarBg = new Animation(plt, enteringNavbarEle.querySelector('.toolbar-background'));
const /** @type {?} */ enteringBackButton = new Animation(plt, enteringNavbarEle.querySelector('.back-button'));
enteringNavBar
.add(enteringTitle)
.add(enteringNavbarItems)
.add(enteringNavbarBg)
.add(enteringBackButton);
enteringTitle.fromTo(OPACITY, 0.01, 1, true);
enteringNavbarItems.fromTo(OPACITY, 0.01, 1, true);
// set properties depending on direction
if (backDirection) {
// entering navbar, back direction
enteringTitle.fromTo(TRANSLATEX, OFF_LEFT, CENTER, true);
if (enteringView.enableBack()) {
// back direction, entering page has a back button
enteringBackButton
.beforeAddClass(SHOW_BACK_BTN_CSS)
.fromTo(OPACITY, 0.01, 1, true);
}
}
else {
// entering navbar, forward direction
enteringTitle.fromTo(TRANSLATEX, OFF_RIGHT, CENTER, true);
enteringNavbarBg
.beforeClearStyles([OPACITY])
.fromTo(TRANSLATEX, OFF_RIGHT, CENTER, true);
if (enteringView.enableBack()) {
// forward direction, entering page has a back button
enteringBackButton
.beforeAddClass(SHOW_BACK_BTN_CSS)
.fromTo(OPACITY, 0.01, 1, true);
const /** @type {?} */ enteringBackBtnText = new Animation(plt, enteringNavbarEle.querySelector('.back-button-text'));
enteringBackBtnText.fromTo(TRANSLATEX, '100px', '0px');
enteringNavBar.add(enteringBackBtnText);
}
else {
enteringBackButton.beforeRemoveClass(SHOW_BACK_BTN_CSS);
}
}
}
}
// setup leaving view
if (leavingView && leavingView.pageRef()) {
// leaving content
const /** @type {?} */ leavingPageEle = leavingView.pageRef().nativeElement;
const /** @type {?} */ leavingContent = new Animation(plt, leavingView.contentRef());
leavingContent.element(leavingPageEle.querySelectorAll('ion-header > *:not(ion-navbar),ion-footer > *'));
this.add(leavingContent);
if (backDirection) {
// leaving content, back direction
leavingContent
.beforeClearStyles([OPACITY])
.fromTo(TRANSLATEX, CENTER, '100%');
}
else {
// leaving content, forward direction
leavingContent
.fromTo(TRANSLATEX, CENTER, OFF_LEFT)
.fromTo(OPACITY, 1, OFF_OPACITY)
.afterClearStyles([TRANSFORM, OPACITY]);
}
if (leavingHasNavbar) {
// leaving page has a navbar
const /** @type {?} */ leavingNavbarEle = leavingPageEle.querySelector('ion-navbar');
const /** @type {?} */ leavingNavBar = new Animation(plt, leavingNavbarEle);
const /** @type {?} */ leavingTitle = new Animation(plt, leavingNavbarEle.querySelector('ion-title'));
const /** @type {?} */ leavingNavbarItems = new Animation(plt, leavingNavbarEle.querySelectorAll('ion-buttons,[menuToggle]'));
const /** @type {?} */ leavingNavbarBg = new Animation(plt, leavingNavbarEle.querySelector('.toolbar-background'));
const /** @type {?} */ leavingBackButton = new Animation(plt, leavingNavbarEle.querySelector('.back-button'));
leavingNavBar
.add(leavingTitle)
.add(leavingNavbarItems)
.add(leavingBackButton)
.add(leavingNavbarBg);
this.add(leavingNavBar);
// fade out leaving navbar items
leavingBackButton.fromTo(OPACITY, 0.99, 0);
leavingTitle.fromTo(OPACITY, 0.99, 0);
leavingNavbarItems.fromTo(OPACITY, 0.99, 0);
if (backDirection) {
// leaving navbar, back direction
leavingTitle.fromTo(TRANSLATEX, CENTER, '100%');
// leaving navbar, back direction, and there's no entering navbar
// should just slide out, no fading out
leavingNavbarBg
.beforeClearStyles([OPACITY])
.fromTo(TRANSLATEX, CENTER, '100%');
let /** @type {?} */ leavingBackBtnText = new Animation(plt, leavingNavbarEle.querySelector('.back-button-text'));
leavingBackBtnText.fromTo(TRANSLATEX, CENTER, (300) + 'px');
leavingNavBar.add(leavingBackBtnText);
}
else {
// leaving navbar, forward direction
leavingTitle
.fromTo(TRANSLATEX, CENTER, OFF_LEFT)
.afterClearStyles([TRANSFORM]);
leavingBackButton.afterClearStyles([OPACITY]);
leavingTitle.afterClearStyles([OPACITY]);
leavingNavbarItems.afterClearStyles([OPACITY]);
}
}
}
}
}
//# sourceMappingURL=transition-ios.js.map | ortroyaner/GithubFinder | node_modules/ionic-angular/es2015/transitions/transition-ios.js | JavaScript | mit | 8,705 |
// <copyright file="SparseMatrix.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2013 Math.NET
//
// 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using MathNet.Numerics.LinearAlgebra.Storage;
namespace MathNet.Numerics.LinearAlgebra.Double
{
/// <summary>
/// A Matrix with sparse storage, intended for very large matrices where most of the cells are zero.
/// The underlying storage scheme is 3-array compressed-sparse-row (CSR) Format.
/// <a href="http://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_row_.28CSR_or_CRS.29">Wikipedia - CSR</a>.
/// </summary>
[Serializable]
[DebuggerDisplay("SparseMatrix {RowCount}x{ColumnCount}-Double {NonZerosCount}-NonZero")]
public class SparseMatrix : Matrix
{
readonly SparseCompressedRowMatrixStorage<double> _storage;
/// <summary>
/// Gets the number of non zero elements in the matrix.
/// </summary>
/// <value>The number of non zero elements.</value>
public int NonZerosCount
{
get { return _storage.ValueCount; }
}
/// <summary>
/// Create a new sparse matrix straight from an initialized matrix storage instance.
/// The storage is used directly without copying.
/// Intended for advanced scenarios where you're working directly with
/// storage for performance or interop reasons.
/// </summary>
public SparseMatrix(SparseCompressedRowMatrixStorage<double> storage)
: base(storage)
{
_storage = storage;
}
/// <summary>
/// Create a new square sparse matrix with the given number of rows and columns.
/// All cells of the matrix will be initialized to zero.
/// Zero-length matrices are not supported.
/// </summary>
/// <exception cref="ArgumentException">If the order is less than one.</exception>
public SparseMatrix(int order)
: this(order, order)
{
}
/// <summary>
/// Create a new sparse matrix with the given number of rows and columns.
/// All cells of the matrix will be initialized to zero.
/// Zero-length matrices are not supported.
/// </summary>
/// <exception cref="ArgumentException">If the row or column count is less than one.</exception>
public SparseMatrix(int rows, int columns)
: this(new SparseCompressedRowMatrixStorage<double>(rows, columns))
{
}
/// <summary>
/// Create a new sparse matrix as a copy of the given other matrix.
/// This new matrix will be independent from the other matrix.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfMatrix(Matrix<double> matrix)
{
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfMatrix(matrix.Storage));
}
/// <summary>
/// Create a new sparse matrix as a copy of the given two-dimensional array.
/// This new matrix will be independent from the provided array.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfArray(double[,] array)
{
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfArray(array));
}
/// <summary>
/// Create a new sparse matrix as a copy of the given indexed enumerable.
/// Keys must be provided at most once, zero is assumed if a key is omitted.
/// This new matrix will be independent from the enumerable.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfIndexed(int rows, int columns, IEnumerable<Tuple<int, int, double>> enumerable)
{
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfIndexedEnumerable(rows, columns, enumerable));
}
/// <summary>
/// Create a new sparse matrix as a copy of the given enumerable.
/// The enumerable is assumed to be in row-major order (row by row).
/// This new matrix will be independent from the enumerable.
/// A new memory block will be allocated for storing the vector.
/// </summary>
/// <seealso href="http://en.wikipedia.org/wiki/Row-major_order"/>
public static SparseMatrix OfRowMajor(int rows, int columns, IEnumerable<double> rowMajor)
{
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfRowMajorEnumerable(rows, columns, rowMajor));
}
/// <summary>
/// Create a new sparse matrix with the given number of rows and columns as a copy of the given array.
/// The array is assumed to be in column-major order (column by column).
/// This new matrix will be independent from the provided array.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
/// <seealso href="http://en.wikipedia.org/wiki/Row-major_order"/>
public static SparseMatrix OfColumnMajor(int rows, int columns, IList<double> columnMajor)
{
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfColumnMajorList(rows, columns, columnMajor));
}
/// <summary>
/// Create a new sparse matrix as a copy of the given enumerable of enumerable columns.
/// Each enumerable in the master enumerable specifies a column.
/// This new matrix will be independent from the enumerables.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfColumns(IEnumerable<IEnumerable<double>> data)
{
return OfColumnArrays(data.Select(v => v.ToArray()).ToArray());
}
/// <summary>
/// Create a new sparse matrix as a copy of the given enumerable of enumerable columns.
/// Each enumerable in the master enumerable specifies a column.
/// This new matrix will be independent from the enumerables.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfColumns(int rows, int columns, IEnumerable<IEnumerable<double>> data)
{
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfColumnEnumerables(rows, columns, data));
}
/// <summary>
/// Create a new sparse matrix as a copy of the given column arrays.
/// This new matrix will be independent from the arrays.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfColumnArrays(params double[][] columns)
{
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfColumnArrays(columns));
}
/// <summary>
/// Create a new sparse matrix as a copy of the given column arrays.
/// This new matrix will be independent from the arrays.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfColumnArrays(IEnumerable<double[]> columns)
{
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfColumnArrays((columns as double[][]) ?? columns.ToArray()));
}
/// <summary>
/// Create a new sparse matrix as a copy of the given column vectors.
/// This new matrix will be independent from the vectors.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfColumnVectors(params Vector<double>[] columns)
{
var storage = new VectorStorage<double>[columns.Length];
for (int i = 0; i < columns.Length; i++)
{
storage[i] = columns[i].Storage;
}
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfColumnVectors(storage));
}
/// <summary>
/// Create a new sparse matrix as a copy of the given column vectors.
/// This new matrix will be independent from the vectors.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfColumnVectors(IEnumerable<Vector<double>> columns)
{
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfColumnVectors(columns.Select(c => c.Storage).ToArray()));
}
/// <summary>
/// Create a new sparse matrix as a copy of the given enumerable of enumerable rows.
/// Each enumerable in the master enumerable specifies a row.
/// This new matrix will be independent from the enumerables.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfRows(IEnumerable<IEnumerable<double>> data)
{
return OfRowArrays(data.Select(v => v.ToArray()).ToArray());
}
/// <summary>
/// Create a new sparse matrix as a copy of the given enumerable of enumerable rows.
/// Each enumerable in the master enumerable specifies a row.
/// This new matrix will be independent from the enumerables.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfRows(int rows, int columns, IEnumerable<IEnumerable<double>> data)
{
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfRowEnumerables(rows, columns, data));
}
/// <summary>
/// Create a new sparse matrix as a copy of the given row arrays.
/// This new matrix will be independent from the arrays.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfRowArrays(params double[][] rows)
{
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfRowArrays(rows));
}
/// <summary>
/// Create a new sparse matrix as a copy of the given row arrays.
/// This new matrix will be independent from the arrays.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfRowArrays(IEnumerable<double[]> rows)
{
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfRowArrays((rows as double[][]) ?? rows.ToArray()));
}
/// <summary>
/// Create a new sparse matrix as a copy of the given row vectors.
/// This new matrix will be independent from the vectors.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfRowVectors(params Vector<double>[] rows)
{
var storage = new VectorStorage<double>[rows.Length];
for (int i = 0; i < rows.Length; i++)
{
storage[i] = rows[i].Storage;
}
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfRowVectors(storage));
}
/// <summary>
/// Create a new sparse matrix as a copy of the given row vectors.
/// This new matrix will be independent from the vectors.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfRowVectors(IEnumerable<Vector<double>> rows)
{
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfRowVectors(rows.Select(r => r.Storage).ToArray()));
}
/// <summary>
/// Create a new sparse matrix with the diagonal as a copy of the given vector.
/// This new matrix will be independent from the vector.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfDiagonalVector(Vector<double> diagonal)
{
var m = new SparseMatrix(diagonal.Count, diagonal.Count);
m.SetDiagonal(diagonal);
return m;
}
/// <summary>
/// Create a new sparse matrix with the diagonal as a copy of the given vector.
/// This new matrix will be independent from the vector.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfDiagonalVector(int rows, int columns, Vector<double> diagonal)
{
var m = new SparseMatrix(rows, columns);
m.SetDiagonal(diagonal);
return m;
}
/// <summary>
/// Create a new sparse matrix with the diagonal as a copy of the given array.
/// This new matrix will be independent from the array.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfDiagonalArray(double[] diagonal)
{
var m = new SparseMatrix(diagonal.Length, diagonal.Length);
m.SetDiagonal(diagonal);
return m;
}
/// <summary>
/// Create a new sparse matrix with the diagonal as a copy of the given array.
/// This new matrix will be independent from the array.
/// A new memory block will be allocated for storing the matrix.
/// </summary>
public static SparseMatrix OfDiagonalArray(int rows, int columns, double[] diagonal)
{
var m = new SparseMatrix(rows, columns);
m.SetDiagonal(diagonal);
return m;
}
/// <summary>
/// Create a new sparse matrix and initialize each value to the same provided value.
/// </summary>
public static SparseMatrix Create(int rows, int columns, double value)
{
if (value == 0d) return new SparseMatrix(rows, columns);
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfValue(rows, columns, value));
}
/// <summary>
/// Create a new sparse matrix and initialize each value using the provided init function.
/// </summary>
public static SparseMatrix Create(int rows, int columns, Func<int, int, double> init)
{
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfInit(rows, columns, init));
}
/// <summary>
/// Create a new diagonal sparse matrix and initialize each diagonal value to the same provided value.
/// </summary>
public static SparseMatrix CreateDiagonal(int rows, int columns, double value)
{
if (value == 0d) return new SparseMatrix(rows, columns);
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfDiagonalInit(rows, columns, i => value));
}
/// <summary>
/// Create a new diagonal sparse matrix and initialize each diagonal value using the provided init function.
/// </summary>
public static SparseMatrix CreateDiagonal(int rows, int columns, Func<int, double> init)
{
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfDiagonalInit(rows, columns, init));
}
/// <summary>
/// Create a new square sparse identity matrix where each diagonal value is set to One.
/// </summary>
public static SparseMatrix CreateIdentity(int order)
{
return new SparseMatrix(SparseCompressedRowMatrixStorage<double>.OfDiagonalInit(order, order, i => One));
}
/// <summary>
/// Returns a new matrix containing the lower triangle of this matrix.
/// </summary>
/// <returns>The lower triangle of this matrix.</returns>
public override Matrix<double> LowerTriangle()
{
var result = Build.SameAs(this);
LowerTriangleImpl(result);
return result;
}
/// <summary>
/// Puts the lower triangle of this matrix into the result matrix.
/// </summary>
/// <param name="result">Where to store the lower triangle.</param>
/// <exception cref="ArgumentNullException">If <paramref name="result"/> is <see langword="null" />.</exception>
/// <exception cref="ArgumentException">If the result matrix's dimensions are not the same as this matrix.</exception>
public override void LowerTriangle(Matrix<double> result)
{
if (result == null)
{
throw new ArgumentNullException("result");
}
if (result.RowCount != RowCount || result.ColumnCount != ColumnCount)
{
throw DimensionsDontMatch<ArgumentException>(this, result, "result");
}
if (ReferenceEquals(this, result))
{
var tmp = Build.SameAs(result);
LowerTriangle(tmp);
tmp.CopyTo(result);
}
else
{
result.Clear();
LowerTriangleImpl(result);
}
}
/// <summary>
/// Puts the lower triangle of this matrix into the result matrix.
/// </summary>
/// <param name="result">Where to store the lower triangle.</param>
private void LowerTriangleImpl(Matrix<double> result)
{
var rowPointers = _storage.RowPointers;
var columnIndices = _storage.ColumnIndices;
var values = _storage.Values;
for (var row = 0; row < result.RowCount; row++)
{
var endIndex = rowPointers[row + 1];
for (var j = rowPointers[row]; j < endIndex; j++)
{
if (row >= columnIndices[j])
{
result.At(row, columnIndices[j], values[j]);
}
}
}
}
/// <summary>
/// Returns a new matrix containing the upper triangle of this matrix.
/// </summary>
/// <returns>The upper triangle of this matrix.</returns>
public override Matrix<double> UpperTriangle()
{
var result = Build.SameAs(this);
UpperTriangleImpl(result);
return result;
}
/// <summary>
/// Puts the upper triangle of this matrix into the result matrix.
/// </summary>
/// <param name="result">Where to store the lower triangle.</param>
/// <exception cref="ArgumentNullException">If <paramref name="result"/> is <see langword="null" />.</exception>
/// <exception cref="ArgumentException">If the result matrix's dimensions are not the same as this matrix.</exception>
public override void UpperTriangle(Matrix<double> result)
{
if (result == null)
{
throw new ArgumentNullException("result");
}
if (result.RowCount != RowCount || result.ColumnCount != ColumnCount)
{
throw DimensionsDontMatch<ArgumentException>(this, result, "result");
}
if (ReferenceEquals(this, result))
{
var tmp = Build.SameAs(result);
UpperTriangle(tmp);
tmp.CopyTo(result);
}
else
{
result.Clear();
UpperTriangleImpl(result);
}
}
/// <summary>
/// Puts the upper triangle of this matrix into the result matrix.
/// </summary>
/// <param name="result">Where to store the lower triangle.</param>
private void UpperTriangleImpl(Matrix<double> result)
{
var rowPointers = _storage.RowPointers;
var columnIndices = _storage.ColumnIndices;
var values = _storage.Values;
for (var row = 0; row < result.RowCount; row++)
{
var endIndex = rowPointers[row + 1];
for (var j = rowPointers[row]; j < endIndex; j++)
{
if (row <= columnIndices[j])
{
result.At(row, columnIndices[j], values[j]);
}
}
}
}
/// <summary>
/// Returns a new matrix containing the lower triangle of this matrix. The new matrix
/// does not contain the diagonal elements of this matrix.
/// </summary>
/// <returns>The lower triangle of this matrix.</returns>
public override Matrix<double> StrictlyLowerTriangle()
{
var result = Build.SameAs(this);
StrictlyLowerTriangleImpl(result);
return result;
}
/// <summary>
/// Puts the strictly lower triangle of this matrix into the result matrix.
/// </summary>
/// <param name="result">Where to store the lower triangle.</param>
/// <exception cref="ArgumentNullException">If <paramref name="result"/> is <see langword="null" />.</exception>
/// <exception cref="ArgumentException">If the result matrix's dimensions are not the same as this matrix.</exception>
public override void StrictlyLowerTriangle(Matrix<double> result)
{
if (result == null)
{
throw new ArgumentNullException("result");
}
if (result.RowCount != RowCount || result.ColumnCount != ColumnCount)
{
throw DimensionsDontMatch<ArgumentException>(this, result, "result");
}
if (ReferenceEquals(this, result))
{
var tmp = Build.SameAs(result);
StrictlyLowerTriangle(tmp);
tmp.CopyTo(result);
}
else
{
result.Clear();
StrictlyLowerTriangleImpl(result);
}
}
/// <summary>
/// Puts the strictly lower triangle of this matrix into the result matrix.
/// </summary>
/// <param name="result">Where to store the lower triangle.</param>
private void StrictlyLowerTriangleImpl(Matrix<double> result)
{
var rowPointers = _storage.RowPointers;
var columnIndices = _storage.ColumnIndices;
var values = _storage.Values;
for (var row = 0; row < result.RowCount; row++)
{
var endIndex = rowPointers[row + 1];
for (var j = rowPointers[row]; j < endIndex; j++)
{
if (row > columnIndices[j])
{
result.At(row, columnIndices[j], values[j]);
}
}
}
}
/// <summary>
/// Returns a new matrix containing the upper triangle of this matrix. The new matrix
/// does not contain the diagonal elements of this matrix.
/// </summary>
/// <returns>The upper triangle of this matrix.</returns>
public override Matrix<double> StrictlyUpperTriangle()
{
var result = Build.SameAs(this);
StrictlyUpperTriangleImpl(result);
return result;
}
/// <summary>
/// Puts the strictly upper triangle of this matrix into the result matrix.
/// </summary>
/// <param name="result">Where to store the lower triangle.</param>
/// <exception cref="ArgumentNullException">If <paramref name="result"/> is <see langword="null" />.</exception>
/// <exception cref="ArgumentException">If the result matrix's dimensions are not the same as this matrix.</exception>
public override void StrictlyUpperTriangle(Matrix<double> result)
{
if (result == null)
{
throw new ArgumentNullException("result");
}
if (result.RowCount != RowCount || result.ColumnCount != ColumnCount)
{
throw DimensionsDontMatch<ArgumentException>(this, result, "result");
}
if (ReferenceEquals(this, result))
{
var tmp = Build.SameAs(result);
StrictlyUpperTriangle(tmp);
tmp.CopyTo(result);
}
else
{
result.Clear();
StrictlyUpperTriangleImpl(result);
}
}
/// <summary>
/// Puts the strictly upper triangle of this matrix into the result matrix.
/// </summary>
/// <param name="result">Where to store the lower triangle.</param>
private void StrictlyUpperTriangleImpl(Matrix<double> result)
{
var rowPointers = _storage.RowPointers;
var columnIndices = _storage.ColumnIndices;
var values = _storage.Values;
for (var row = 0; row < result.RowCount; row++)
{
var endIndex = rowPointers[row + 1];
for (var j = rowPointers[row]; j < endIndex; j++)
{
if (row < columnIndices[j])
{
result.At(row, columnIndices[j], values[j]);
}
}
}
}
/// <summary>
/// Negate each element of this matrix and place the results into the result matrix.
/// </summary>
/// <param name="result">The result of the negation.</param>
protected override void DoNegate(Matrix<double> result)
{
CopyTo(result);
DoMultiply(-1, result);
}
/// <summary>Calculates the induced infinity norm of this matrix.</summary>
/// <returns>The maximum absolute row sum of the matrix.</returns>
public override double InfinityNorm()
{
var rowPointers = _storage.RowPointers;
var values = _storage.Values;
var norm = 0d;
for (var i = 0; i < RowCount; i++)
{
var startIndex = rowPointers[i];
var endIndex = rowPointers[i + 1];
if (startIndex == endIndex)
{
// Begin and end are equal. There are no values in the row, Move to the next row
continue;
}
var s = 0d;
for (var j = startIndex; j < endIndex; j++)
{
s += Math.Abs(values[j]);
}
norm = Math.Max(norm, s);
}
return norm;
}
/// <summary>Calculates the entry-wise Frobenius norm of this matrix.</summary>
/// <returns>The square root of the sum of the squared values.</returns>
public override double FrobeniusNorm()
{
var aat = (SparseCompressedRowMatrixStorage<double>) (this*Transpose()).Storage;
var norm = 0d;
for (var i = 0; i < aat.RowCount; i++)
{
var startIndex = aat.RowPointers[i];
var endIndex = aat.RowPointers[i + 1];
if (startIndex == endIndex)
{
// Begin and end are equal. There are no values in the row, Move to the next row
continue;
}
for (var j = startIndex; j < endIndex; j++)
{
if (i == aat.ColumnIndices[j])
{
norm += Math.Abs(aat.Values[j]);
}
}
}
return Math.Sqrt(norm);
}
/// <summary>
/// Adds another matrix to this matrix.
/// </summary>
/// <param name="other">The matrix to add to this matrix.</param>
/// <param name="result">The matrix to store the result of the addition.</param>
/// <exception cref="ArgumentNullException">If the other matrix is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException">If the two matrices don't have the same dimensions.</exception>
protected override void DoAdd(Matrix<double> other, Matrix<double> result)
{
var sparseOther = other as SparseMatrix;
var sparseResult = result as SparseMatrix;
if (sparseOther == null || sparseResult == null)
{
base.DoAdd(other, result);
return;
}
if (ReferenceEquals(this, other))
{
if (!ReferenceEquals(this, result))
{
CopyTo(result);
}
Control.LinearAlgebraProvider.ScaleArray(2.0, _storage.Values, _storage.Values);
return;
}
SparseMatrix left;
if (ReferenceEquals(sparseOther, sparseResult))
{
left = this;
}
else if (ReferenceEquals(this, sparseResult))
{
left = sparseOther;
}
else
{
CopyTo(sparseResult);
left = sparseOther;
}
var leftStorage = left._storage;
for (var i = 0; i < leftStorage.RowCount; i++)
{
var endIndex = leftStorage.RowPointers[i + 1];
for (var j = leftStorage.RowPointers[i]; j < endIndex; j++)
{
var columnIndex = leftStorage.ColumnIndices[j];
var resVal = leftStorage.Values[j] + result.At(i, columnIndex);
result.At(i, columnIndex, resVal);
}
}
}
/// <summary>
/// Subtracts another matrix from this matrix.
/// </summary>
/// <param name="other">The matrix to subtract to this matrix.</param>
/// <param name="result">The matrix to store the result of subtraction.</param>
/// <exception cref="ArgumentNullException">If the other matrix is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException">If the two matrices don't have the same dimensions.</exception>
protected override void DoSubtract(Matrix<double> other, Matrix<double> result)
{
var sparseOther = other as SparseMatrix;
var sparseResult = result as SparseMatrix;
if (sparseOther == null || sparseResult == null)
{
base.DoSubtract(other, result);
return;
}
if (ReferenceEquals(this, other))
{
result.Clear();
return;
}
var otherStorage = sparseOther._storage;
if (ReferenceEquals(this, sparseResult))
{
for (var i = 0; i < otherStorage.RowCount; i++)
{
var endIndex = otherStorage.RowPointers[i + 1];
for (var j = otherStorage.RowPointers[i]; j < endIndex; j++)
{
var columnIndex = otherStorage.ColumnIndices[j];
var resVal = sparseResult.At(i, columnIndex) - otherStorage.Values[j];
result.At(i, columnIndex, resVal);
}
}
}
else
{
if (!ReferenceEquals(sparseOther, sparseResult))
{
sparseOther.CopyTo(sparseResult);
}
sparseResult.Negate(sparseResult);
var rowPointers = _storage.RowPointers;
var columnIndices = _storage.ColumnIndices;
var values = _storage.Values;
for (var i = 0; i < RowCount; i++)
{
var endIndex = rowPointers[i + 1];
for (var j = rowPointers[i]; j < endIndex; j++)
{
var columnIndex = columnIndices[j];
var resVal = sparseResult.At(i, columnIndex) + values[j];
result.At(i, columnIndex, resVal);
}
}
}
}
/// <summary>
/// Multiplies each element of the matrix by a scalar and places results into the result matrix.
/// </summary>
/// <param name="scalar">The scalar to multiply the matrix with.</param>
/// <param name="result">The matrix to store the result of the multiplication.</param>
protected override void DoMultiply(double scalar, Matrix<double> result)
{
if (scalar == 1.0)
{
CopyTo(result);
return;
}
if (scalar == 0.0 || NonZerosCount == 0)
{
result.Clear();
return;
}
var sparseResult = result as SparseMatrix;
if (sparseResult == null)
{
result.Clear();
var rowPointers = _storage.RowPointers;
var columnIndices = _storage.ColumnIndices;
var values = _storage.Values;
for (var row = 0; row < RowCount; row++)
{
var start = rowPointers[row];
var end = rowPointers[row + 1];
if (start == end)
{
continue;
}
for (var index = start; index < end; index++)
{
var column = columnIndices[index];
result.At(row, column, values[index] * scalar);
}
}
}
else
{
if (!ReferenceEquals(this, result))
{
CopyTo(sparseResult);
}
Control.LinearAlgebraProvider.ScaleArray(scalar, sparseResult._storage.Values, sparseResult._storage.Values);
}
}
/// <summary>
/// Multiplies this matrix with another matrix and places the results into the result matrix.
/// </summary>
/// <param name="other">The matrix to multiply with.</param>
/// <param name="result">The result of the multiplication.</param>
protected override void DoMultiply(Matrix<double> other, Matrix<double> result)
{
var sparseOther = other as SparseMatrix;
var sparseResult = result as SparseMatrix;
if (sparseOther != null && sparseResult != null)
{
DoMultiplySparse(sparseOther, sparseResult);
return;
}
var diagonalOther = other.Storage as DiagonalMatrixStorage<double>;
if (diagonalOther != null && sparseResult != null)
{
var diagonal = diagonalOther.Data;
if (other.ColumnCount == other.RowCount)
{
Storage.MapIndexedTo(result.Storage, (i, j, x) => x*diagonal[j], Zeros.AllowSkip, ExistingData.Clear);
}
else
{
result.Storage.Clear();
Storage.MapSubMatrixIndexedTo(result.Storage, (i, j, x) => x*diagonal[j], 0, 0, RowCount, 0, 0, ColumnCount, Zeros.AllowSkip, ExistingData.AssumeZeros);
}
return;
}
result.Clear();
var columnVector = new DenseVector(other.RowCount);
var rowPointers = _storage.RowPointers;
var columnIndices = _storage.ColumnIndices;
var values = _storage.Values;
for (var row = 0; row < RowCount; row++)
{
var startIndex = rowPointers[row];
var endIndex = rowPointers[row + 1];
if (startIndex == endIndex)
{
continue;
}
for (var column = 0; column < other.ColumnCount; column++)
{
// Multiply row of matrix A on column of matrix B
other.Column(column, columnVector);
var sum = 0d;
for (var index = startIndex; index < endIndex; index++)
{
sum += values[index] * columnVector[columnIndices[index]];
}
result.At(row, column, sum);
}
}
}
void DoMultiplySparse(SparseMatrix other, SparseMatrix result)
{
result.Clear();
var ax = _storage.Values;
var ap = _storage.RowPointers;
var ai = _storage.ColumnIndices;
var bx = other._storage.Values;
var bp = other._storage.RowPointers;
var bi = other._storage.ColumnIndices;
int rows = RowCount;
int cols = other.ColumnCount;
int[] cp = result._storage.RowPointers;
var marker = new int[cols];
for (int ib = 0; ib < cols; ib++)
{
marker[ib] = -1;
}
int count = 0;
for (int i = 0; i < rows; i++)
{
// For each row of A
for (int j = ap[i]; j < ap[i + 1]; j++)
{
// Row number to be added
int a = ai[j];
for (int k = bp[a]; k < bp[a + 1]; k++)
{
int b = bi[k];
if (marker[b] != i)
{
marker[b] = i;
count++;
}
}
}
// Record non-zero count.
cp[i + 1] = count;
}
var ci = new int[count];
var cx = new double[count];
for (int ib = 0; ib < cols; ib++)
{
marker[ib] = -1;
}
count = 0;
for (int i = 0; i < rows; i++)
{
int rowStart = cp[i];
for (int j = ap[i]; j < ap[i + 1]; j++)
{
int a = ai[j];
double aEntry = ax[j];
for (int k = bp[a]; k < bp[a + 1]; k++)
{
int b = bi[k];
double bEntry = bx[k];
if (marker[b] < rowStart)
{
marker[b] = count;
ci[marker[b]] = b;
cx[marker[b]] = aEntry * bEntry;
count++;
}
else
{
cx[marker[b]] += aEntry * bEntry;
}
}
}
}
result._storage.Values = cx;
result._storage.ColumnIndices = ci;
result._storage.Normalize();
}
/// <summary>
/// Multiplies this matrix with a vector and places the results into the result vector.
/// </summary>
/// <param name="rightSide">The vector to multiply with.</param>
/// <param name="result">The result of the multiplication.</param>
protected override void DoMultiply(Vector<double> rightSide, Vector<double> result)
{
var rowPointers = _storage.RowPointers;
var columnIndices = _storage.ColumnIndices;
var values = _storage.Values;
for (var row = 0; row < RowCount; row++)
{
var startIndex = rowPointers[row];
var endIndex = rowPointers[row + 1];
if (startIndex == endIndex)
{
continue;
}
var sum = 0d;
for (var index = startIndex; index < endIndex; index++)
{
sum += values[index] * rightSide[columnIndices[index]];
}
result[row] = sum;
}
}
/// <summary>
/// Multiplies this matrix with transpose of another matrix and places the results into the result matrix.
/// </summary>
/// <param name="other">The matrix to multiply with.</param>
/// <param name="result">The result of the multiplication.</param>
protected override void DoTransposeAndMultiply(Matrix<double> other, Matrix<double> result)
{
var otherSparse = other as SparseMatrix;
var resultSparse = result as SparseMatrix;
if (otherSparse == null || resultSparse == null)
{
base.DoTransposeAndMultiply(other, result);
return;
}
resultSparse.Clear();
var rowPointers = _storage.RowPointers;
var values = _storage.Values;
var otherStorage = otherSparse._storage;
for (var j = 0; j < RowCount; j++)
{
var startIndexOther = otherStorage.RowPointers[j];
var endIndexOther = otherStorage.RowPointers[j + 1];
if (startIndexOther == endIndexOther)
{
continue;
}
for (var i = 0; i < RowCount; i++)
{
var startIndexThis = rowPointers[i];
var endIndexThis = rowPointers[i + 1];
if (startIndexThis == endIndexThis)
{
continue;
}
var sum = 0d;
for (var index = startIndexOther; index < endIndexOther; index++)
{
var ind = _storage.FindItem(i, otherStorage.ColumnIndices[index]);
if (ind >= 0)
{
sum += otherStorage.Values[index]*values[ind];
}
}
resultSparse._storage.At(i, j, sum + result.At(i, j));
}
}
}
/// <summary>
/// Pointwise multiplies this matrix with another matrix and stores the result into the result matrix.
/// </summary>
/// <param name="other">The matrix to pointwise multiply with this one.</param>
/// <param name="result">The matrix to store the result of the pointwise multiplication.</param>
protected override void DoPointwiseMultiply(Matrix<double> other, Matrix<double> result)
{
result.Clear();
var rowPointers = _storage.RowPointers;
var columnIndices = _storage.ColumnIndices;
var values = _storage.Values;
for (var i = 0; i < RowCount; i++)
{
var endIndex = rowPointers[i + 1];
for (var j = rowPointers[i]; j < endIndex; j++)
{
var resVal = values[j]*other.At(i, columnIndices[j]);
if (resVal != 0d)
{
result.At(i, columnIndices[j], resVal);
}
}
}
}
/// <summary>
/// Pointwise divide this matrix by another matrix and stores the result into the result matrix.
/// </summary>
/// <param name="divisor">The matrix to pointwise divide this one by.</param>
/// <param name="result">The matrix to store the result of the pointwise division.</param>
protected override void DoPointwiseDivide(Matrix<double> divisor, Matrix<double> result)
{
result.Clear();
var rowPointers = _storage.RowPointers;
var columnIndices = _storage.ColumnIndices;
var values = _storage.Values;
for (var i = 0; i < RowCount; i++)
{
var endIndex = rowPointers[i + 1];
for (var j = rowPointers[i]; j < endIndex; j++)
{
if (values[j] != 0d)
{
result.At(i, columnIndices[j], values[j]/divisor.At(i, columnIndices[j]));
}
}
}
}
public override void KroneckerProduct(Matrix<double> other, Matrix<double> result)
{
if (other == null)
{
throw new ArgumentNullException("other");
}
if (result == null)
{
throw new ArgumentNullException("result");
}
if (result.RowCount != (RowCount*other.RowCount) || result.ColumnCount != (ColumnCount*other.ColumnCount))
{
throw DimensionsDontMatch<ArgumentOutOfRangeException>(this, other, result);
}
var rowPointers = _storage.RowPointers;
var columnIndices = _storage.ColumnIndices;
var values = _storage.Values;
for (var i = 0; i < RowCount; i++)
{
var endIndex = rowPointers[i + 1];
for (var j = rowPointers[i]; j < endIndex; j++)
{
if (values[j] != 0d)
{
result.SetSubMatrix(i*other.RowCount, other.RowCount, columnIndices[j]*other.ColumnCount, other.ColumnCount, values[j]*other);
}
}
}
}
/// <summary>
/// Computes the canonical modulus, where the result has the sign of the divisor,
/// for the given divisor each element of the matrix.
/// </summary>
/// <param name="divisor">The scalar denominator to use.</param>
/// <param name="result">Matrix to store the results in.</param>
protected override void DoModulus(double divisor, Matrix<double> result)
{
var sparseResult = result as SparseMatrix;
if (sparseResult == null)
{
base.DoModulus(divisor, result);
return;
}
if (!ReferenceEquals(this, result))
{
CopyTo(result);
}
var resultStorage = sparseResult._storage;
for (var index = 0; index < resultStorage.Values.Length; index++)
{
resultStorage.Values[index] = Euclid.Modulus(resultStorage.Values[index], divisor);
}
}
/// <summary>
/// Computes the remainder (% operator), where the result has the sign of the dividend,
/// for the given divisor each element of the matrix.
/// </summary>
/// <param name="divisor">The scalar denominator to use.</param>
/// <param name="result">Matrix to store the results in.</param>
protected override void DoRemainder(double divisor, Matrix<double> result)
{
var sparseResult = result as SparseMatrix;
if (sparseResult == null)
{
base.DoRemainder(divisor, result);
return;
}
if (!ReferenceEquals(this, result))
{
CopyTo(result);
}
var resultStorage = sparseResult._storage;
for (var index = 0; index < resultStorage.Values.Length; index++)
{
resultStorage.Values[index] %= divisor;
}
}
/// <summary>
/// Evaluates whether this matrix is symmetric.
/// </summary>
public override bool IsSymmetric()
{
if (RowCount != ColumnCount)
{
return false;
}
var rowPointers = _storage.RowPointers;
var columnIndices = _storage.ColumnIndices;
var values = _storage.Values;
for (var row = 0; row < RowCount; row++)
{
var start = rowPointers[row];
var end = rowPointers[row + 1];
if (start == end)
{
continue;
}
for (var index = start; index < end; index++)
{
var column = columnIndices[index];
if (!values[index].Equals(At(column, row)))
{
return false;
}
}
}
return true;
}
/// <summary>
/// Adds two matrices together and returns the results.
/// </summary>
/// <remarks>This operator will allocate new memory for the result. It will
/// choose the representation of either <paramref name="leftSide"/> or <paramref name="rightSide"/> depending on which
/// is denser.</remarks>
/// <param name="leftSide">The left matrix to add.</param>
/// <param name="rightSide">The right matrix to add.</param>
/// <returns>The result of the addition.</returns>
/// <exception cref="ArgumentOutOfRangeException">If <paramref name="leftSide"/> and <paramref name="rightSide"/> don't have the same dimensions.</exception>
/// <exception cref="ArgumentNullException">If <paramref name="leftSide"/> or <paramref name="rightSide"/> is <see langword="null" />.</exception>
public static SparseMatrix operator +(SparseMatrix leftSide, SparseMatrix rightSide)
{
if (rightSide == null)
{
throw new ArgumentNullException("rightSide");
}
if (leftSide == null)
{
throw new ArgumentNullException("leftSide");
}
if (leftSide.RowCount != rightSide.RowCount || leftSide.ColumnCount != rightSide.ColumnCount)
{
throw DimensionsDontMatch<ArgumentOutOfRangeException>(leftSide, rightSide);
}
return (SparseMatrix)leftSide.Add(rightSide);
}
/// <summary>
/// Returns a <strong>Matrix</strong> containing the same values of <paramref name="rightSide"/>.
/// </summary>
/// <param name="rightSide">The matrix to get the values from.</param>
/// <returns>A matrix containing a the same values as <paramref name="rightSide"/>.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="rightSide"/> is <see langword="null" />.</exception>
public static SparseMatrix operator +(SparseMatrix rightSide)
{
if (rightSide == null)
{
throw new ArgumentNullException("rightSide");
}
return (SparseMatrix)rightSide.Clone();
}
/// <summary>
/// Subtracts two matrices together and returns the results.
/// </summary>
/// <remarks>This operator will allocate new memory for the result. It will
/// choose the representation of either <paramref name="leftSide"/> or <paramref name="rightSide"/> depending on which
/// is denser.</remarks>
/// <param name="leftSide">The left matrix to subtract.</param>
/// <param name="rightSide">The right matrix to subtract.</param>
/// <returns>The result of the addition.</returns>
/// <exception cref="ArgumentOutOfRangeException">If <paramref name="leftSide"/> and <paramref name="rightSide"/> don't have the same dimensions.</exception>
/// <exception cref="ArgumentNullException">If <paramref name="leftSide"/> or <paramref name="rightSide"/> is <see langword="null" />.</exception>
public static SparseMatrix operator -(SparseMatrix leftSide, SparseMatrix rightSide)
{
if (rightSide == null)
{
throw new ArgumentNullException("rightSide");
}
if (leftSide == null)
{
throw new ArgumentNullException("leftSide");
}
if (leftSide.RowCount != rightSide.RowCount || leftSide.ColumnCount != rightSide.ColumnCount)
{
throw DimensionsDontMatch<ArgumentException>(leftSide, rightSide);
}
return (SparseMatrix)leftSide.Subtract(rightSide);
}
/// <summary>
/// Negates each element of the matrix.
/// </summary>
/// <param name="rightSide">The matrix to negate.</param>
/// <returns>A matrix containing the negated values.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="rightSide"/> is <see langword="null" />.</exception>
public static SparseMatrix operator -(SparseMatrix rightSide)
{
if (rightSide == null)
{
throw new ArgumentNullException("rightSide");
}
return (SparseMatrix)rightSide.Negate();
}
/// <summary>
/// Multiplies a <strong>Matrix</strong> by a constant and returns the result.
/// </summary>
/// <param name="leftSide">The matrix to multiply.</param>
/// <param name="rightSide">The constant to multiply the matrix by.</param>
/// <returns>The result of the multiplication.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="leftSide"/> is <see langword="null" />.</exception>
public static SparseMatrix operator *(SparseMatrix leftSide, double rightSide)
{
if (leftSide == null)
{
throw new ArgumentNullException("leftSide");
}
return (SparseMatrix)leftSide.Multiply(rightSide);
}
/// <summary>
/// Multiplies a <strong>Matrix</strong> by a constant and returns the result.
/// </summary>
/// <param name="leftSide">The matrix to multiply.</param>
/// <param name="rightSide">The constant to multiply the matrix by.</param>
/// <returns>The result of the multiplication.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="rightSide"/> is <see langword="null" />.</exception>
public static SparseMatrix operator *(double leftSide, SparseMatrix rightSide)
{
if (rightSide == null)
{
throw new ArgumentNullException("rightSide");
}
return (SparseMatrix)rightSide.Multiply(leftSide);
}
/// <summary>
/// Multiplies two matrices.
/// </summary>
/// <remarks>This operator will allocate new memory for the result. It will
/// choose the representation of either <paramref name="leftSide"/> or <paramref name="rightSide"/> depending on which
/// is denser.</remarks>
/// <param name="leftSide">The left matrix to multiply.</param>
/// <param name="rightSide">The right matrix to multiply.</param>
/// <returns>The result of multiplication.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="leftSide"/> or <paramref name="rightSide"/> is <see langword="null" />.</exception>
/// <exception cref="ArgumentException">If the dimensions of <paramref name="leftSide"/> or <paramref name="rightSide"/> don't conform.</exception>
public static SparseMatrix operator *(SparseMatrix leftSide, SparseMatrix rightSide)
{
if (leftSide == null)
{
throw new ArgumentNullException("leftSide");
}
if (rightSide == null)
{
throw new ArgumentNullException("rightSide");
}
if (leftSide.ColumnCount != rightSide.RowCount)
{
throw DimensionsDontMatch<ArgumentException>(leftSide, rightSide);
}
return (SparseMatrix)leftSide.Multiply(rightSide);
}
/// <summary>
/// Multiplies a <strong>Matrix</strong> and a Vector.
/// </summary>
/// <param name="leftSide">The matrix to multiply.</param>
/// <param name="rightSide">The vector to multiply.</param>
/// <returns>The result of multiplication.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="leftSide"/> or <paramref name="rightSide"/> is <see langword="null" />.</exception>
public static SparseVector operator *(SparseMatrix leftSide, SparseVector rightSide)
{
if (leftSide == null)
{
throw new ArgumentNullException("leftSide");
}
return (SparseVector)leftSide.Multiply(rightSide);
}
/// <summary>
/// Multiplies a Vector and a <strong>Matrix</strong>.
/// </summary>
/// <param name="leftSide">The vector to multiply.</param>
/// <param name="rightSide">The matrix to multiply.</param>
/// <returns>The result of multiplication.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="leftSide"/> or <paramref name="rightSide"/> is <see langword="null" />.</exception>
public static SparseVector operator *(SparseVector leftSide, SparseMatrix rightSide)
{
if (rightSide == null)
{
throw new ArgumentNullException("rightSide");
}
return (SparseVector)rightSide.LeftMultiply(leftSide);
}
/// <summary>
/// Multiplies a <strong>Matrix</strong> by a constant and returns the result.
/// </summary>
/// <param name="leftSide">The matrix to multiply.</param>
/// <param name="rightSide">The constant to multiply the matrix by.</param>
/// <returns>The result of the multiplication.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="leftSide"/> is <see langword="null" />.</exception>
public static SparseMatrix operator %(SparseMatrix leftSide, double rightSide)
{
if (leftSide == null)
{
throw new ArgumentNullException("leftSide");
}
return (SparseMatrix)leftSide.Remainder(rightSide);
}
public override string ToTypeString()
{
return string.Format("SparseMatrix {0}x{1}-Double {2:P2} Filled", RowCount, ColumnCount, NonZerosCount / (RowCount * (double)ColumnCount));
}
}
}
| grovesNL/mathnet-numerics | src/Numerics/LinearAlgebra/Double/SparseMatrix.cs | C# | mit | 60,299 |
using System;
using System.Reflection;
class Program {
static void PrintFieldValues (FieldInfo[] fields, object obj) {
foreach (FieldInfo field in fields) {
// not printing field names because automatic property backing field names differ between .NET and JSIL
Console.WriteLine(field.GetValue(obj));
}
}
static void AssertThrows (Action action) {
try {
action();
Console.WriteLine("Not OK: exception was not thrown");
} catch (Exception) {
Console.WriteLine("OK: exception was thrown");
}
}
public static void Main () {
BindingFlags all = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
BindingFlags allStatic = all ^ BindingFlags.Instance;
PrintFieldValues(typeof(MyStruct).GetFields(all), new MyStruct(1, 2, "3"));
PrintFieldValues(typeof(MyEnum).GetFields(allStatic), null);
PrintFieldValues(typeof(MyClass).GetFields(all), new MyClass());
PrintFieldValues(typeof(MyClass).GetFields(all), new MySubclass());
PrintFieldValues(typeof(MyClass).GetFields(allStatic), null);
AssertThrows(() => PrintFieldValues(typeof(MyClass).GetFields(all), null));
AssertThrows(() => PrintFieldValues(typeof(MyStruct).GetFields(all), new MyClass()));
}
}
struct MyStruct {
public int Field1;
public long Field2;
public string Field3;
public MyStruct (byte field1, int field2, string field3) {
Field1 = field1;
Field2 = field2;
Field3 = field3;
}
}
enum MyEnum {
A = 3,
B = 5,
C = 7
}
class MyClass {
public int Field1 = 4;
public long Field2 = 8;
public string Field3 = "15";
public static uint StaticField1 = 16;
public static ulong StaticField2 = 23;
public static string AutomaticProperty1 { get; set; }
static MyClass() {
AutomaticProperty1 = "42";
}
}
class MySubclass : MyClass {
}
| TukekeSoft/JSIL | Tests/ReflectionTestCases/FieldGetValue.cs | C# | mit | 2,066 |
'use strict';
var gulp = tars.packages.gulp;
var cache = tars.packages.cache;
var plumber = tars.packages.plumber;
var notifier = tars.helpers.notifier;
var browserSync = tars.packages.browserSync;
var staticFolderName = tars.config.fs.staticFolderName;
/**
* Move fonts-files to dev directory
*/
module.exports = function () {
return gulp.task('other:move-fonts', function () {
return gulp.src('./markup/' + staticFolderName + '/fonts/**/*.*')
.pipe(plumber({
errorHandler: function (error) {
notifier.error('An error occurred while moving fonts.', error);
}
}))
.pipe(cache('move-fonts'))
.pipe(gulp.dest('./dev/' + staticFolderName + '/fonts'))
.pipe(browserSync.reload({ stream: true }))
.pipe(
notifier.success('Fonts\'ve been moved')
);
});
};
| mik639/TZA | tars/tasks/other/move-fonts.js | JavaScript | mit | 923 |
# require 'analytic/response_analytic'
module AssignmentTeamAnalytic
#======= general ==========#
def num_participants
self.participants.count
end
def num_reviews
self.responses.count
end
#========== score ========#
def average_review_score
if self.num_reviews == 0
return 0
else
review_scores.inject(:+).to_f / num_reviews
end
end
def max_review_score
review_scores.max
end
def min_review_score
review_scores.min
end
#======= word count =======#
def total_review_word_count
review_word_counts.inject(:+)
end
def average_review_word_count
if self.num_reviews == 0
return 0
else
total_review_word_count.to_f / num_reviews
end
end
def max_review_word_count
review_word_counts.max
end
def min_review_word_count
review_word_counts.min
end
#===== character count ====#
def total_review_character_count
review_character_counts.inject(:+)
end
def average_review_character_count
if num_reviews == 0
0
else
total_review_character_count.to_f / num_reviews
end
end
def max_review_character_count
review_character_counts.max
end
def min_review_character_count
review_character_counts.min
end
def review_character_counts
list = []
self.responses.each do |response|
list << response.total_character_count
end
if list.empty?
[0]
else
list
end
end
# return an array containing the score of all the reviews
def review_scores
list = []
self.responses.each do |response|
list << response.average_score
end
if list.empty?
[0]
else
list
end
end
def review_word_counts
list = []
self.responses.each do |response|
list << response.total_word_count
end
if list.empty?
[0]
else
list
end
end
#======= unused ============#
# #return students in the participants
# def student_list
# students = Array.new
# self.participants.each do |participant|
# if participant.user.role_id == Role.student.id
# students << participant
# end
# end
# students
# end
#
# def num_students
# self.students.count
# end
end
| akshayjain114/expertiza | expertiza-master/app/models/analytic/assignment_team_analytic.rb | Ruby | mit | 2,250 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autofac.Builder;
using Autofac.Core.Registration;
using Autofac.Core.Lifetime;
using Autofac.Core.Activators.Reflection;
using Autofac.Core;
using System.Reflection;
using Autofac.Core.Activators.ProvidedInstance;
namespace Autofac.Test
{
static class Factory
{
public static IComponentRegistration CreateSingletonRegistration(IEnumerable<Service> services, IInstanceActivator activator)
{
return CreateRegistration(services, activator, new RootScopeLifetime(), InstanceSharing.Shared);
}
public static IComponentRegistration CreateSingletonRegistration(Type implementation)
{
return CreateSingletonRegistration(
new Service[] { new TypedService(implementation) },
CreateReflectionActivator(implementation));
}
public static IComponentRegistration CreateRegistration(IEnumerable<Service> services, IInstanceActivator activator, IComponentLifetime lifetime, InstanceSharing sharing)
{
return new ComponentRegistration(
Guid.NewGuid(),
activator,
lifetime,
sharing,
InstanceOwnership.OwnedByLifetimeScope,
services,
NoMetadata);
}
public static IComponentRegistration CreateSingletonObjectRegistration(object instance)
{
return RegistrationBuilder
.ForDelegate((c, p) => instance)
.SingleInstance()
.CreateRegistration();
}
public static IComponentRegistration CreateSingletonObjectRegistration()
{
return CreateSingletonRegistration(
new Service[] { new TypedService(typeof(object)) },
CreateReflectionActivator(typeof(object)));
}
public static ReflectionActivator CreateReflectionActivator(Type implementation)
{
return CreateReflectionActivator(
implementation,
NoParameters);
}
public static ReflectionActivator CreateReflectionActivator(Type implementation, IEnumerable<Parameter> parameters)
{
return CreateReflectionActivator(
implementation,
parameters,
NoProperties);
}
public static ReflectionActivator CreateReflectionActivator(Type implementation, IEnumerable<Parameter> parameters, IEnumerable<Parameter> properties)
{
return new ReflectionActivator(
implementation,
new DefaultConstructorFinder(),
new MostParametersConstructorSelector(),
parameters,
properties);
}
public static ProvidedInstanceActivator CreateProvidedInstanceActivator(object instance)
{
return new ProvidedInstanceActivator(instance);
}
public static readonly IContainer EmptyContainer = new Container();
public static readonly IComponentContext EmptyContext = new Container();
public static readonly IEnumerable<Parameter> NoParameters = Enumerable.Empty<Parameter>();
public static readonly IEnumerable<Parameter> NoProperties = Enumerable.Empty<Parameter>();
public static readonly IDictionary<string, object> NoMetadata = new Dictionary<string, object>();
}
}
| oconics/Autofac | test/Autofac.Test/Factory.cs | C# | mit | 3,512 |
/******************************************************************************
*
*
*
* Copyright (C) 1997-2015 by Dimitri van Heesch.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation under the terms of the GNU General Public License is hereby
* granted. No representations are made about the suitability of this software
* for any purpose. It is provided "as is" without express or implied warranty.
* See the GNU General Public License for more details.
*
* Documents produced by Doxygen are derivative works derived from the
* input used in their production; they are not affected by this license.
*
*/
#include "define.h"
#include "config.h"
Define::Define()
{
fileDef=0;
lineNr=1;
columnNr=1;
nargs=-1;
undef=FALSE;
varArgs=FALSE;
isPredefined=FALSE;
nonRecursive=FALSE;
}
Define::Define(const Define &d)
: name(d.name),definition(d.definition),fileName(d.fileName)
{
//name=d.name; definition=d.definition; fileName=d.fileName;
lineNr=d.lineNr;
columnNr=d.columnNr;
nargs=d.nargs;
undef=d.undef;
varArgs=d.varArgs;
isPredefined=d.isPredefined;
nonRecursive=d.nonRecursive;
fileDef=0;
}
Define::~Define()
{
}
bool Define::hasDocumentation()
{
return definition && (doc || Config_getBool("EXTRACT_ALL"));
}
| chintal/doxygen | src/define.cpp | C++ | gpl-2.0 | 1,325 |
<?php
namespace Drupal\jsonapi\JsonApiResource;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Drupal\Core\Url;
use Drupal\jsonapi\JsonApiSpec;
use Drupal\jsonapi\ResourceType\ResourceType;
use Drupal\jsonapi\Routing\Routes;
/**
* Represents references from one resource object to other resource object(s).
*
* @internal JSON:API maintains no PHP API since its API is the HTTP API. This
* class may change at any time and this will break any dependencies on it.
*
* @see https://www.drupal.org/project/drupal/issues/3032787
* @see jsonapi.api.php
*/
class Relationship implements TopLevelDataInterface {
/**
* The context resource object of the relationship.
*
* A relationship object represents references from a resource object in
* which it’s defined to other resource objects. Respectively, the "context"
* of the relationship and the "target(s)" of the relationship.
*
* A relationship object's context either comes from the resource object that
* contains it or, in the case that the relationship object is accessed
* directly via a relationship URL, from its `self` URL, which should identify
* the resource to which it belongs.
*
* @var \Drupal\jsonapi\JsonApiResource\ResourceObject
*
* @see https://jsonapi.org/format/#document-resource-object-relationships
* @see https://jsonapi.org/recommendations/#urls-relationships
*/
protected $context;
/**
* The data of the relationship object.
*
* @var \Drupal\jsonapi\JsonApiResource\RelationshipData
*/
protected $data;
/**
* The relationship's public field name.
*
* @var string
*/
protected $fieldName;
/**
* The relationship object's links.
*
* @var \Drupal\jsonapi\JsonApiResource\LinkCollection
*/
protected $links;
/**
* The relationship object's meta member.
*
* @var array
*/
protected $meta;
/**
* Relationship constructor.
*
* This constructor is protected by design. To create a new relationship, use
* static::createFromEntityReferenceField().
*
* @param string $public_field_name
* The public field name of the relationship field.
* @param \Drupal\jsonapi\JsonApiResource\RelationshipData $data
* The relationship data.
* @param \Drupal\jsonapi\JsonApiResource\LinkCollection $links
* Any links for the resource object, if a `self` link is not
* provided, one will be automatically added if the resource is locatable
* and is not internal.
* @param array $meta
* Any relationship metadata.
* @param \Drupal\jsonapi\JsonApiResource\ResourceObject $context
* The relationship's context resource object. Use the
* self::withContext() method to establish a context.
*
* @see \Drupal\jsonapi\JsonApiResource\Relationship::createFromEntityReferenceField()
*/
protected function __construct($public_field_name, RelationshipData $data, LinkCollection $links, array $meta, ResourceObject $context) {
$this->fieldName = $public_field_name;
$this->data = $data;
$this->links = $links->withContext($this);
$this->meta = $meta;
$this->context = $context;
}
/**
* Creates a new Relationship from an entity reference field.
*
* @param \Drupal\jsonapi\JsonApiResource\ResourceObject $context
* The context resource object of the relationship to be created.
* @param \Drupal\Core\Field\EntityReferenceFieldItemListInterface $field
* The entity reference field from which to create the relationship.
* @param \Drupal\jsonapi\JsonApiResource\LinkCollection $links
* (optional) Any extra links for the Relationship, if a `self` link is not
* provided, one will be automatically added if the context resource is
* locatable and is not internal.
* @param array $meta
* (optional) Any relationship metadata.
*
* @return static
* An instantiated relationship object.
*/
public static function createFromEntityReferenceField(ResourceObject $context, EntityReferenceFieldItemListInterface $field, LinkCollection $links = NULL, array $meta = []) {
$context_resource_type = $context->getResourceType();
$resource_field = $context_resource_type->getFieldByInternalName($field->getName());
return new static(
$resource_field->getPublicName(),
new RelationshipData(ResourceIdentifier::toResourceIdentifiers($field), $resource_field->hasOne() ? 1 : -1),
static::buildLinkCollectionFromEntityReferenceField($context, $field, $links ?: new LinkCollection([])),
$meta,
$context
);
}
/**
* Gets context resource object of the relationship.
*
* @return \Drupal\jsonapi\JsonApiResource\ResourceObject
* The context ResourceObject.
*
* @see \Drupal\jsonapi\JsonApiResource\Relationship::$context
*/
public function getContext() {
return $this->context;
}
/**
* Gets the relationship object's public field name.
*
* @return string
* The relationship's field name.
*/
public function getFieldName() {
return $this->fieldName;
}
/**
* Gets the relationship object's data.
*
* @return \Drupal\jsonapi\JsonApiResource\RelationshipData
* The relationship's data.
*/
public function getData() {
return $this->data;
}
/**
* Gets the relationship object's links.
*
* @return \Drupal\jsonapi\JsonApiResource\LinkCollection
* The relationship object's links.
*/
public function getLinks() {
return $this->links;
}
/**
* Gets the relationship object's metadata.
*
* @return array
* The relationship object's metadata.
*/
public function getMeta() {
return $this->meta;
}
/**
* {@inheritdoc}
*/
public function getOmissions() {
return new OmittedData([]);
}
/**
* {@inheritdoc}
*/
public function getMergedLinks(LinkCollection $top_level_links) {
// When directly fetching a relationship object, the relationship object's
// links become the top-level object's links unless they've been
// overridden. Overrides are especially important for the `self` link, which
// must match the link that generated the response. For example, the
// top-level `self` link might have an `include` query parameter that would
// be lost otherwise.
// See https://jsonapi.org/format/#fetching-relationships-responses-200 and
// https://jsonapi.org/format/#document-top-level.
return LinkCollection::merge($top_level_links, $this->getLinks()->filter(function ($key) use ($top_level_links) {
return !$top_level_links->hasLinkWithKey($key);
})->withContext($top_level_links->getContext()));
}
/**
* {@inheritdoc}
*/
public function getMergedMeta(array $top_level_meta) {
return NestedArray::mergeDeep($top_level_meta, $this->getMeta());
}
/**
* Builds a LinkCollection for the given entity reference field.
*
* @param \Drupal\jsonapi\JsonApiResource\ResourceObject $context
* The context resource object of the relationship object.
* @param \Drupal\Core\Field\EntityReferenceFieldItemListInterface $field
* The entity reference field from which to create the links.
* @param \Drupal\jsonapi\JsonApiResource\LinkCollection $links
* Any extra links for the Relationship, if a `self` link is not provided,
* one will be automatically added if the context resource is locatable and
* is not internal.
*
* @return \Drupal\jsonapi\JsonApiResource\LinkCollection
* The built links.
*/
protected static function buildLinkCollectionFromEntityReferenceField(ResourceObject $context, EntityReferenceFieldItemListInterface $field, LinkCollection $links) {
$context_resource_type = $context->getResourceType();
$public_field_name = $context_resource_type->getPublicName($field->getName());
if ($context_resource_type->isLocatable() && !$context_resource_type->isInternal()) {
$context_is_versionable = $context_resource_type->isVersionable();
if (!$links->hasLinkWithKey('self')) {
$route_name = Routes::getRouteName($context_resource_type, "$public_field_name.relationship.get");
$self_link = Url::fromRoute($route_name, ['entity' => $context->getId()]);
if ($context_is_versionable) {
$self_link->setOption('query', [JsonApiSpec::VERSION_QUERY_PARAMETER => $context->getVersionIdentifier()]);
}
$links = $links->withLink('self', new Link(new CacheableMetadata(), $self_link, 'self'));
}
$has_non_internal_resource_type = array_reduce($context_resource_type->getRelatableResourceTypesByField($public_field_name), function ($carry, ResourceType $target) {
return $carry ?: !$target->isInternal();
}, FALSE);
// If a `related` link was not provided, automatically generate one from
// the relationship object to the collection resource with all of the
// resources targeted by this relationship. However, that link should
// *not* be generated if all of the relatable resources are internal.
// That's because, in that case, a route will not exist for it.
if (!$links->hasLinkWithKey('related') && $has_non_internal_resource_type) {
$route_name = Routes::getRouteName($context_resource_type, "$public_field_name.related");
$related_link = Url::fromRoute($route_name, ['entity' => $context->getId()]);
if ($context_is_versionable) {
$related_link->setOption('query', [JsonApiSpec::VERSION_QUERY_PARAMETER => $context->getVersionIdentifier()]);
}
$links = $links->withLink('related', new Link(new CacheableMetadata(), $related_link, 'related'));
}
}
return $links;
}
}
| maskedjellybean/tee-prop | web/core/modules/jsonapi/src/JsonApiResource/Relationship.php | PHP | gpl-2.0 | 9,807 |
/*___Generated_by_IDEA___*/
package com.facebook.android;
/* This stub is only used by the IDE. It is NOT the R class actually packed into the APK */
public final class R {
} | TharinduKetipe/easywish | libraries/facebook/gen/com/facebook/android/R.java | Java | gpl-2.0 | 176 |
#!/usr/bin/env python
"""Execute the tests for the razers3 program.
The golden test outputs are generated by the script generate_outputs.sh.
You have to give the root paths to the source and the binaries as arguments to
the program. These are the paths to the directory that contains the 'projects'
directory.
Usage: run_tests.py SOURCE_ROOT_PATH BINARY_ROOT_PATH
"""
import logging
import os.path
import sys
# Automagically add util/py_lib to PYTHONPATH environment variable.
path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..',
'..', '..', 'util', 'py_lib'))
sys.path.insert(0, path)
import seqan.app_tests as app_tests
class RemovePairIdColumn(object):
"""Transformation to remove pair id column."""
def __init__(self, col_no=8, min_cols=8):
# The index of the column to remove.
self.col_no = col_no
# If there are less than min_col columns then we don't remove.
self.min_cols = min_cols
def apply(self, text, is_left):
lines = text.splitlines(True)
lines2 = []
for line in lines:
cols = line.split('\t')
if len(cols) > self.min_cols:
cols = cols[0:self.col_no] + cols[self.col_no + 1:]
lines2.append('\t'.join(cols))
return ''.join(lines2)
def main(source_base, binary_base, num_threads=1):
"""Main entry point of the script."""
print 'Executing test for razers3'
print '==========================='
print
ph = app_tests.TestPathHelper(
source_base, binary_base,
'apps/razers3/tests') # tests dir
# ============================================================
# Auto-detect the binary path.
# ============================================================
path_to_program = app_tests.autolocateBinary(
binary_base, 'bin', 'razers3')
# ============================================================
# Built TestConf list.
# ============================================================
# Build list with TestConf objects, analoguely to how the output
# was generated in generate_outputs.sh.
conf_list = []
# We prepare a list of transforms to apply to the output files. This is
# used to strip the input/output paths from the programs' output to
# make it more canonical and host independent.
ph.outFile('-') # To ensure that the out path is set.
transforms = [
app_tests.ReplaceTransform(os.path.join(ph.source_base_path, 'apps/razers3/tests') + os.sep, '', right=True),
app_tests.ReplaceTransform(ph.temp_dir + os.sep, '', right=True),
]
# Transforms for SAM output format only. Make VN field of @PG header canonical.
sam_transforms = [app_tests.RegexpReplaceTransform(r'\tVN:[^\t]*', r'\tVN:VERSION', right=True, left=True)]
# Transforms for RazerS output format only. Remove pair id column.
razers_transforms = [RemovePairIdColumn()]
# ============================================================
# Run Adeno Single-End Tests
# ============================================================
# We run the following for all read lengths we have reads for.
for rl in [36, 100]:
# Run with default options.
conf = app_tests.TestConf(
program=path_to_program,
redir_stdout=ph.outFile('se-adeno-reads%d_1-tc%d.stdout' % (rl, num_threads)),
args=['-tc', str(num_threads),
ph.inFile('adeno-genome.fa'),
ph.inFile('adeno-reads%d_1.fa' % rl),
'-o', ph.outFile('se-adeno-reads%d_1-tc%d.razers' % (rl, num_threads))],
to_diff=[(ph.inFile('se-adeno-reads%d_1-tc%d.razers' % (rl, num_threads)),
ph.outFile('se-adeno-reads%d_1-tc%d.razers' % (rl, num_threads))),
(ph.inFile('se-adeno-reads%d_1-tc%d.stdout' % (rl, num_threads)),
ph.outFile('se-adeno-reads%d_1-tc%d.stdout' % (rl, num_threads)))])
conf_list.append(conf)
# Allow indels.
conf = app_tests.TestConf(
program=path_to_program,
redir_stdout=ph.outFile('se-adeno-reads%d_1-ng-tc%d.stdout' % (rl, num_threads)),
args=['-tc', str(num_threads),
'-ng',
ph.inFile('adeno-genome.fa'),
ph.inFile('adeno-reads%d_1.fa' % rl),
'-o', ph.outFile('se-adeno-reads%d_1-ng-tc%d.razers' % (rl, num_threads))],
to_diff=[(ph.inFile('se-adeno-reads%d_1-ng-tc%d.razers' % (rl, num_threads)),
ph.outFile('se-adeno-reads%d_1-ng-tc%d.razers' % (rl, num_threads))),
(ph.inFile('se-adeno-reads%d_1-ng-tc%d.stdout' % (rl, num_threads)),
ph.outFile('se-adeno-reads%d_1-ng-tc%d.stdout' % (rl, num_threads)))])
conf_list.append(conf)
# Compute forward/reverse matches only.
for o in ['-r', '-f']:
conf = app_tests.TestConf(
program=path_to_program,
redir_stdout=ph.outFile('se-adeno-reads%d_1%s-tc%d.stdout' % (rl, o, num_threads)),
args=['-tc', str(num_threads),
o,
ph.inFile('adeno-genome.fa'),
ph.inFile('adeno-reads%d_1.fa' % rl),
'-o', ph.outFile('se-adeno-reads%d_1%s-tc%d.razers' % (rl, o, num_threads))],
to_diff=[(ph.inFile('se-adeno-reads%d_1%s-tc%d.razers' % (rl, o, num_threads)),
ph.outFile('se-adeno-reads%d_1%s-tc%d.razers' % (rl, o, num_threads))),
(ph.inFile('se-adeno-reads%d_1%s-tc%d.stdout' % (rl, o, num_threads)),
ph.outFile('se-adeno-reads%d_1%s-tc%d.stdout' % (rl, o, num_threads)))])
conf_list.append(conf)
# Compute with different identity rates.
for i in range(90, 101):
conf = app_tests.TestConf(
program=path_to_program,
redir_stdout=ph.outFile('se-adeno-reads%d_1-i%d-tc%d.stdout' % (rl, i, num_threads)),
args=['-tc', str(num_threads),
'-i', str(i),
ph.inFile('adeno-genome.fa'),
ph.inFile('adeno-reads%d_1.fa' % rl),
'-o', ph.outFile('se-adeno-reads%d_1-i%d-tc%d.razers' % (rl, i, num_threads))],
to_diff=[(ph.inFile('se-adeno-reads%d_1-i%d-tc%d.razers' % (rl, i, num_threads)),
ph.outFile('se-adeno-reads%d_1-i%d-tc%d.razers' % (rl, i, num_threads))),
(ph.inFile('se-adeno-reads%d_1-i%d-tc%d.stdout' % (rl, i, num_threads)),
ph.outFile('se-adeno-reads%d_1-i%d-tc%d.stdout' % (rl, i, num_threads)))])
conf_list.append(conf)
# Compute with different output formats.
for of, suffix in enumerate(['razers', 'fa', 'eland', 'gff', 'sam', 'afg']):
this_transforms = list(transforms)
if suffix == 'razers':
this_transforms += razers_transforms
elif suffix == 'sam':
this_transforms += sam_transforms
conf = app_tests.TestConf(
program=path_to_program,
redir_stdout=ph.outFile('se-adeno-reads%d_1-of%d-tc%d.stdout' % (rl, of, num_threads)),
args=['-tc', str(num_threads),
ph.inFile('adeno-genome.fa'),
ph.inFile('adeno-reads%d_1.fa' % rl),
'-o', ph.outFile('se-adeno-reads%d_1-of%d-tc%d.%s' % (rl, of, num_threads, suffix))],
to_diff=[(ph.inFile('se-adeno-reads%d_1-of%d-tc%d.%s' % (rl, of, num_threads, suffix)),
ph.outFile('se-adeno-reads%d_1-of%d-tc%d.%s' % (rl, of, num_threads, suffix)),
this_transforms),
(ph.inFile('se-adeno-reads%d_1-of%d-tc%d.stdout' % (rl, of, num_threads)),
ph.outFile('se-adeno-reads%d_1-of%d-tc%d.stdout' % (rl, of, num_threads)),
transforms)])
conf_list.append(conf)
# Compute with different sort orders.
for so in [0, 1]:
conf = app_tests.TestConf(
program=path_to_program,
redir_stdout=ph.outFile('se-adeno-reads%d_1-so%d-tc%d.stdout' % (rl, so, num_threads)),
args=['-tc', str(num_threads),
'-so', str(so),
ph.inFile('adeno-genome.fa'),
ph.inFile('adeno-reads%d_1.fa' % rl),
'-o', ph.outFile('se-adeno-reads%d_1-so%d-tc%d.razers' % (rl, so, num_threads))],
to_diff=[(ph.inFile('se-adeno-reads%d_1-so%d-tc%d.razers' % (rl, so, num_threads)),
ph.outFile('se-adeno-reads%d_1-so%d-tc%d.razers' % (rl, so, num_threads))),
(ph.inFile('se-adeno-reads%d_1-so%d-tc%d.stdout' % (rl, so, num_threads)),
ph.outFile('se-adeno-reads%d_1-so%d-tc%d.stdout' % (rl, so, num_threads)))])
conf_list.append(conf)
# ============================================================
# Run Adeno Paired-End Tests
# ============================================================
# We run the following for all read lengths we have reads for.
for rl in [36, 100]:
# Run with default options.
conf = app_tests.TestConf(
program=path_to_program,
redir_stdout=ph.outFile('pe-adeno-reads%d_2-tc%d.stdout' % (rl, num_threads)),
args=['-tc', str(num_threads),
ph.inFile('adeno-genome.fa'),
ph.inFile('adeno-reads%d_1.fa' % rl),
ph.inFile('adeno-reads%d_2.fa' % rl),
'-o', ph.outFile('pe-adeno-reads%d_2-tc%d.razers' % (rl, num_threads))],
to_diff=[(ph.inFile('pe-adeno-reads%d_2-tc%d.razers' % (rl, num_threads)),
ph.outFile('pe-adeno-reads%d_2-tc%d.razers' % (rl, num_threads)),
razers_transforms),
(ph.inFile('pe-adeno-reads%d_2-tc%d.stdout' % (rl, num_threads)),
ph.outFile('pe-adeno-reads%d_2-tc%d.stdout' % (rl, num_threads)))])
conf_list.append(conf)
# Allow indels.
conf = app_tests.TestConf(
program=path_to_program,
redir_stdout=ph.outFile('pe-adeno-reads%d_2-tc%d.stdout' % (rl, num_threads)),
args=['-tc', str(num_threads),
ph.inFile('adeno-genome.fa'),
ph.inFile('adeno-reads%d_1.fa' % rl),
ph.inFile('adeno-reads%d_2.fa' % rl),
'-o', ph.outFile('pe-adeno-reads%d_2-tc%d.razers' % (rl, num_threads))],
to_diff=[(ph.inFile('pe-adeno-reads%d_2-tc%d.razers' % (rl, num_threads)),
ph.outFile('pe-adeno-reads%d_2-tc%d.razers' % (rl, num_threads)),
razers_transforms),
(ph.inFile('pe-adeno-reads%d_2-tc%d.stdout' % (rl, num_threads)),
ph.outFile('pe-adeno-reads%d_2-tc%d.stdout' % (rl, num_threads)))])
conf_list.append(conf)
# Compute forward/reverse matches only.
for o in ['-r', '-f']:
conf = app_tests.TestConf(
program=path_to_program,
redir_stdout=ph.outFile('pe-adeno-reads%d_2%s-tc%d.stdout' % (rl, o, num_threads)),
args=['-tc', str(num_threads),
o,
ph.inFile('adeno-genome.fa'),
ph.inFile('adeno-reads%d_1.fa' % rl),
ph.inFile('adeno-reads%d_2.fa' % rl),
'-o', ph.outFile('pe-adeno-reads%d_2%s-tc%d.razers' % (rl, o, num_threads))],
to_diff=[(ph.inFile('pe-adeno-reads%d_2%s-tc%d.razers' % (rl, o, num_threads)),
ph.outFile('pe-adeno-reads%d_2%s-tc%d.razers' % (rl, o, num_threads)),
razers_transforms),
(ph.inFile('pe-adeno-reads%d_2%s-tc%d.stdout' % (rl, o, num_threads)),
ph.outFile('pe-adeno-reads%d_2%s-tc%d.stdout' % (rl, o, num_threads)))])
conf_list.append(conf)
# Compute with different identity rates.
for i in range(90, 101):
conf = app_tests.TestConf(
program=path_to_program,
redir_stdout=ph.outFile('pe-adeno-reads%d_2-i%d-tc%d.stdout' % (rl, i, num_threads)),
args=['-tc', str(num_threads),
'-i', str(i),
ph.inFile('adeno-genome.fa'),
ph.inFile('adeno-reads%d_1.fa' % rl),
ph.inFile('adeno-reads%d_2.fa' % rl),
'-o', ph.outFile('pe-adeno-reads%d_2-i%d-tc%d.razers' % (rl, i, num_threads))],
to_diff=[(ph.inFile('pe-adeno-reads%d_2-i%d-tc%d.razers' % (rl, i, num_threads)),
ph.outFile('pe-adeno-reads%d_2-i%d-tc%d.razers' % (rl, i, num_threads)),
razers_transforms),
(ph.inFile('pe-adeno-reads%d_2-i%d-tc%d.stdout' % (rl, i, num_threads)),
ph.outFile('pe-adeno-reads%d_2-i%d-tc%d.stdout' % (rl, i, num_threads)))])
conf_list.append(conf)
# Compute with different output formats.
for of, suffix in enumerate(['razers', 'fa', 'eland', 'gff', 'sam', 'afg']):
this_transforms = list(transforms)
if suffix == 'razers':
this_transforms += razers_transforms
elif suffix == 'sam':
this_transforms += sam_transforms
conf = app_tests.TestConf(
program=path_to_program,
redir_stdout=ph.outFile('pe-adeno-reads%d_2-of%d-tc%d.stdout' % (rl, of, num_threads)),
args=['-tc', str(num_threads),
ph.inFile('adeno-genome.fa'),
ph.inFile('adeno-reads%d_1.fa' % rl),
ph.inFile('adeno-reads%d_2.fa' % rl),
'-o', ph.outFile('pe-adeno-reads%d_2-of%d-tc%d.%s' % (rl, of, num_threads, suffix))],
to_diff=[(ph.inFile('pe-adeno-reads%d_2-of%d-tc%d.%s' % (rl, of, num_threads, suffix)),
ph.outFile('pe-adeno-reads%d_2-of%d-tc%d.%s' % (rl, of, num_threads, suffix)),
this_transforms),
(ph.inFile('pe-adeno-reads%d_2-of%d-tc%d.stdout' % (rl, of, num_threads)),
ph.outFile('pe-adeno-reads%d_2-of%d-tc%d.stdout' % (rl, of, num_threads)),
this_transforms)])
conf_list.append(conf)
# Compute with different sort orders.
for so in [0, 1]:
conf = app_tests.TestConf(
program=path_to_program,
redir_stdout=ph.outFile('pe-adeno-reads%d_2-so%d-tc%d.stdout' % (rl, so, num_threads)),
args=['-tc', str(num_threads),
'-so', str(so),
ph.inFile('adeno-genome.fa'),
ph.inFile('adeno-reads%d_1.fa' % rl),
ph.inFile('adeno-reads%d_2.fa' % rl),
'-o', ph.outFile('pe-adeno-reads%d_2-so%d-tc%d.razers' % (rl, so, num_threads))],
to_diff=[(ph.inFile('pe-adeno-reads%d_2-so%d-tc%d.razers' % (rl, so, num_threads)),
ph.outFile('pe-adeno-reads%d_2-so%d-tc%d.razers' % (rl, so, num_threads)),
razers_transforms),
(ph.inFile('pe-adeno-reads%d_2-so%d-tc%d.stdout' % (rl, so, num_threads)),
ph.outFile('pe-adeno-reads%d_2-so%d-tc%d.stdout' % (rl, so, num_threads)))])
conf_list.append(conf)
# Execute the tests.
failures = 0
for conf in conf_list:
res = app_tests.runTest(conf)
# Output to the user.
print ' '.join(['razers3'] + conf.args),
if res:
print 'OK'
else:
failures += 1
print 'FAILED'
# Cleanup.
ph.deleteTempDir()
print '=============================='
print ' total tests: %d' % len(conf_list)
print ' failed tests: %d' % failures
print 'successful tests: %d' % (len(conf_list) - failures)
print '=============================='
# Compute and return return code.
return failures != 0
if __name__ == '__main__':
sys.exit(app_tests.main(main))
| rrahn/jst_bench | include/seqan/apps/razers3/tests/run_tests.py | Python | gpl-3.0 | 16,681 |
t = db.capped1;
t.drop();
db.createCollection("capped1" , {capped:true, size:1024 });
v = t.validate();
assert( v.valid , "A : " + tojson( v ) ); // SERVER-485
t.save( { x : 1 } )
assert( t.validate().valid , "B" )
| barakav/robomongo | src/third-party/mongodb/jstests/capped1.js | JavaScript | gpl-3.0 | 220 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains tests for the repository_nextcloud class.
*
* @package repository_nextcloud
* @copyright 2017 Project seminar (Learnweb, University of Münster)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/repository/lib.php');
require_once($CFG->libdir . '/webdavlib.php');
/**
* Class repository_nextcloud_lib_testcase
* @group repository_nextcloud
* @copyright 2017 Project seminar (Learnweb, University of Münster)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class repository_nextcloud_lib_testcase extends advanced_testcase {
/** @var null|\repository_nextcloud the repository_nextcloud object, which the tests are run on. */
private $repo = null;
/** @var null|\core\oauth2\issuer which belongs to the repository_nextcloud object.*/
private $issuer = null;
/**
* SetUp to create an repository instance.
*/
protected function setUp(): void {
$this->resetAfterTest(true);
// Admin is neccessary to create api and issuer objects.
$this->setAdminUser();
/** @var repository_nextcloud_generator $generator */
$generator = $this->getDataGenerator()->get_plugin_generator('repository_nextcloud');
$this->issuer = $generator->test_create_issuer();
// Create Endpoints for issuer.
$generator->test_create_endpoints($this->issuer->get('id'));
// Params for the config form.
$reptype = $generator->create_type([
'visible' => 1,
'enableuserinstances' => 0,
'enablecourseinstances' => 0,
]);
$instance = $generator->create_instance([
'issuerid' => $this->issuer->get('id'),
'pluginname' => 'Nextcloud',
'controlledlinkfoldername' => 'Moodlefiles',
'supportedreturntypes' => 'both',
'defaultreturntype' => FILE_INTERNAL,
]);
// At last, create a repository_nextcloud object from the instance id.
$this->repo = new repository_nextcloud($instance->id);
$this->repo->options['typeid'] = $reptype->id;
$this->repo->options['sortorder'] = 1;
$this->resetAfterTest(true);
}
/**
* Checks the is_visible method in case the repository is set to hidden in the database.
*/
public function test_is_visible_parent_false() {
global $DB;
$id = $this->repo->options['typeid'];
// Check, if the method returns false, when the repository is set to visible in the database
// and the client configuration data is complete.
$DB->update_record('repository', (object) array('id' => $id, 'visible' => 0));
$this->assertFalse($this->repo->is_visible());
}
/**
* Test whether the repo is disabled.
*/
public function test_repo_creation() {
$issuerid = $this->repo->get_option('issuerid');
// Config saves the right id.
$this->assertEquals($this->issuer->get('id'), $issuerid);
// Function that is used in construct method returns the right id.
$constructissuer = \core\oauth2\api::get_issuer($issuerid);
$this->assertEquals($this->issuer->get('id'), $constructissuer->get('id'));
$this->assertEquals(true, $constructissuer->get('enabled'));
$this->assertFalse($this->repo->disabled);
}
/**
* Returns an array of endpoints or null.
* @param string $endpointname
* @return array|null
*/
private function get_endpoint_id($endpointname) {
$endpoints = \core\oauth2\api::get_endpoints($this->issuer);
$id = array();
foreach ($endpoints as $endpoint) {
$name = $endpoint->get('name');
if ($name === $endpointname) {
$id[$endpoint->get('id')] = $endpoint->get('id');
}
}
if (empty($id)) {
return null;
}
return $id;
}
/**
* Test if repository is disabled when webdav_endpoint is deleted.
*/
public function test_issuer_webdav() {
$idwebdav = $this->get_endpoint_id('webdav_endpoint');
if (!empty($idwebdav)) {
foreach ($idwebdav as $id) {
\core\oauth2\api::delete_endpoint($id);
}
}
$this->assertFalse(\repository_nextcloud\issuer_management::is_valid_issuer($this->issuer));
}
/**
* Test if repository is disabled when ocs_endpoint is deleted.
*/
public function test_issuer_ocs() {
$idocs = $this->get_endpoint_id('ocs_endpoint');
if (!empty($idocs)) {
foreach ($idocs as $id) {
\core\oauth2\api::delete_endpoint($id);
}
}
$this->assertFalse(\repository_nextcloud\issuer_management::is_valid_issuer($this->issuer));
}
/**
* Test if repository is disabled when userinfo_endpoint is deleted.
*/
public function test_issuer_userinfo() {
$idtoken = $this->get_endpoint_id('userinfo_endpoint');
if (!empty($idtoken)) {
foreach ($idtoken as $id) {
\core\oauth2\api::delete_endpoint($id);
}
}
$this->assertFalse(\repository_nextcloud\issuer_management::is_valid_issuer($this->issuer));
}
/**
* Test if repository is disabled when token_endpoint is deleted.
*/
public function test_issuer_token() {
$idtoken = $this->get_endpoint_id('token_endpoint');
if (!empty($idtoken)) {
foreach ($idtoken as $id) {
\core\oauth2\api::delete_endpoint($id);
}
}
$this->assertFalse(\repository_nextcloud\issuer_management::is_valid_issuer($this->issuer));
}
/**
* Test if repository is disabled when auth_endpoint is deleted.
*/
public function test_issuer_authorization() {
$idauth = $this->get_endpoint_id('authorization_endpoint');
if (!empty($idauth)) {
foreach ($idauth as $id) {
\core\oauth2\api::delete_endpoint($id);
}
}
$this->assertFalse(\repository_nextcloud\issuer_management::is_valid_issuer($this->issuer));
}
/**
* Test if repository throws an error when endpoint does not exist.
*/
public function test_parse_endpoint_url_error() {
$this->expectException(\repository_nextcloud\configuration_exception::class);
\repository_nextcloud\issuer_management::parse_endpoint_url('notexisting', $this->issuer);
}
/**
* Test get_listing method with an example directory. Tests error cases.
*/
public function test_get_listing_error() {
$ret = $this->get_initialised_return_array();
$this->setUser();
// WebDAV socket is not opened.
$mock = $this->createMock(\webdav_client::class);
$mock->expects($this->once())->method('open')->will($this->returnValue(false));
$private = $this->set_private_property($mock, 'dav');
$this->assertEquals($ret, $this->repo->get_listing('/'));
// Response is not an array.
$mock = $this->createMock(\webdav_client::class);
$mock->expects($this->once())->method('open')->will($this->returnValue(true));
$mock->expects($this->once())->method('ls')->will($this->returnValue('notanarray'));
$private->setValue($this->repo, $mock);
$this->assertEquals($ret, $this->repo->get_listing('/'));
}
/**
* Test get_listing method with an example directory. Tests the root directory.
*/
public function test_get_listing_root() {
$this->setUser();
$ret = $this->get_initialised_return_array();
// This is the expected response from the ls method.
$response = array(
array(
'href' => 'remote.php/webdav/',
'lastmodified' => 'Thu, 08 Dec 2016 16:06:26 GMT',
'resourcetype' => 'collection',
'status' => 'HTTP/1.1 200 OK',
'getcontentlength' => ''
),
array(
'href' => 'remote.php/webdav/Documents/',
'lastmodified' => 'Thu, 08 Dec 2016 16:06:26 GMT',
'resourcetype' => 'collection',
'status' => 'HTTP/1.1 200 OK',
'getcontentlength' => ''
),
array(
'href' => 'remote.php/webdav/welcome.txt',
'lastmodified' => 'Thu, 08 Dec 2016 16:06:26 GMT',
'status' => 'HTTP/1.1 200 OK',
'getcontentlength' => '163'
)
);
// The expected result from the get_listing method in the repository_nextcloud class.
$ret['list'] = array(
'DOCUMENTS/' => array(
'title' => 'Documents',
'thumbnail' => null,
'children' => array(),
'datemodified' => 1481213186,
'path' => '/Documents/'
),
'WELCOME.TXT' => array(
'title' => 'welcome.txt',
'thumbnail' => null,
'size' => '163',
'datemodified' => 1481213186,
'source' => '/welcome.txt'
)
);
// Valid response from the client.
$mock = $this->createMock(\webdav_client::class);
$mock->expects($this->once())->method('open')->will($this->returnValue(true));
$mock->expects($this->once())->method('ls')->will($this->returnValue($response));
$this->set_private_property($mock, 'dav');
$ls = $this->repo->get_listing('/');
// Those attributes can not be tested properly.
$ls['list']['DOCUMENTS/']['thumbnail'] = null;
$ls['list']['WELCOME.TXT']['thumbnail'] = null;
$this->assertEquals($ret, $ls);
}
/**
* Test get_listing method with an example directory. Tests a different directory than the root
* directory.
*/
public function test_get_listing_directory() {
$ret = $this->get_initialised_return_array();
$this->setUser();
// An additional directory path has to be added to the 'path' field within the returned array.
$ret['path'][1] = array(
'name' => 'dir',
'path' => '/dir/'
);
// This is the expected response from the get_listing method in the Nextcloud client.
$response = array(
array(
'href' => 'remote.php/webdav/dir/',
'lastmodified' => 'Thu, 08 Dec 2016 16:06:26 GMT',
'resourcetype' => 'collection',
'status' => 'HTTP/1.1 200 OK',
'getcontentlength' => ''
),
array(
'href' => 'remote.php/webdav/dir/Documents/',
'lastmodified' => null,
'resourcetype' => 'collection',
'status' => 'HTTP/1.1 200 OK',
'getcontentlength' => ''
),
array(
'href' => 'remote.php/webdav/dir/welcome.txt',
'lastmodified' => 'Thu, 08 Dec 2016 16:06:26 GMT',
'status' => 'HTTP/1.1 200 OK',
'getcontentlength' => '163'
)
);
// The expected result from the get_listing method in the repository_nextcloud class.
$ret['list'] = array(
'DOCUMENTS/' => array(
'title' => 'Documents',
'thumbnail' => null,
'children' => array(),
'datemodified' => null,
'path' => '/dir/Documents/'
),
'WELCOME.TXT' => array(
'title' => 'welcome.txt',
'thumbnail' => null,
'size' => '163',
'datemodified' => 1481213186,
'source' => '/dir/welcome.txt'
)
);
// Valid response from the client.
$mock = $this->createMock(\webdav_client::class);
$mock->expects($this->once())->method('open')->will($this->returnValue(true));
$mock->expects($this->once())->method('ls')->will($this->returnValue($response));
$this->set_private_property($mock, 'dav');
$ls = $this->repo->get_listing('/dir/');
// Can not be tested properly.
$ls['list']['DOCUMENTS/']['thumbnail'] = null;
$ls['list']['WELCOME.TXT']['thumbnail'] = null;
$this->assertEquals($ret, $ls);
}
/**
* Test the get_link method.
*/
public function test_get_link_success() {
$mock = $this->getMockBuilder(\repository_nextcloud\ocs_client::class)->disableOriginalConstructor()->disableOriginalClone(
)->getMock();
$file = '/datei';
$expectedresponse = <<<XML
<?xml version="1.0"?>
<ocs>
<meta>
<status>ok</status>
<statuscode>100</statuscode>
<message/>
</meta>
<data>
<id>2</id>
<share_type>3</share_type>
<uid_owner>admin</uid_owner>
<displayname_owner>admin</displayname_owner>
<permissions>1</permissions>
<stime>1502883721</stime>
<parent/>
<expiration/>
<token>QXbqrJj8DcMaXen</token>
<uid_file_owner>admin</uid_file_owner>
<displayname_file_owner>admin</displayname_file_owner>
<path>/somefile</path>
<item_type>file</item_type>
<mimetype>application/pdf</mimetype>
<storage_id>home::admin</storage_id>
<storage>1</storage>
<item_source>6</item_source>
<file_source>6</file_source>
<file_parent>4</file_parent>
<file_target>/somefile</file_target>
<share_with/>
<share_with_displayname/>
<name/>
<url>https://www.default.test/somefile</url>
<mail_send>0</mail_send>
</data>
</ocs>
XML;
// Expected Parameters.
$ocsquery = [
'path' => $file,
'shareType' => \repository_nextcloud\ocs_client::SHARE_TYPE_PUBLIC,
'publicUpload' => false,
'permissions' => \repository_nextcloud\ocs_client::SHARE_PERMISSION_READ
];
// With test whether mock is called with right parameters.
$mock->expects($this->once())->method('call')->with('create_share', $ocsquery)->will($this->returnValue($expectedresponse));
$this->set_private_property($mock, 'ocsclient');
// Method does extract the link from the xml format.
$this->assertEquals('https://www.default.test/somefile/download', $this->repo->get_link($file));
}
/**
* get_link can get OCS failure responses. Test that this is handled appropriately.
*/
public function test_get_link_failure() {
$mock = $this->getMockBuilder(\repository_nextcloud\ocs_client::class)->disableOriginalConstructor()->disableOriginalClone(
)->getMock();
$file = '/datei';
$expectedresponse = <<<XML
<?xml version="1.0"?>
<ocs>
<meta>
<status>failure</status>
<statuscode>404</statuscode>
<message>Msg</message>
</meta>
<data/>
</ocs>
XML;
// Expected Parameters.
$ocsquery = [
'path' => $file,
'shareType' => \repository_nextcloud\ocs_client::SHARE_TYPE_PUBLIC,
'publicUpload' => false,
'permissions' => \repository_nextcloud\ocs_client::SHARE_PERMISSION_READ
];
// With test whether mock is called with right parameters.
$mock->expects($this->once())->method('call')->with('create_share', $ocsquery)->will($this->returnValue($expectedresponse));
$this->set_private_property($mock, 'ocsclient');
// Suppress (expected) XML parse error... Nextcloud sometimes returns JSON on extremely bad errors.
libxml_use_internal_errors(true);
// Method get_link correctly raises an exception that contains error code and message.
$this->expectException(\repository_nextcloud\request_exception::class);
$params = array('instance' => $this->repo->get_name(), 'errormessage' => sprintf('(%s) %s', '404', 'Msg'));
$this->expectExceptionMessage(get_string('request_exception', 'repository_nextcloud', $params));
$this->repo->get_link($file);
}
/**
* get_link can get OCS responses that are not actually XML. Test that this is handled appropriately.
*/
public function test_get_link_problem() {
$mock = $this->getMockBuilder(\repository_nextcloud\ocs_client::class)->disableOriginalConstructor()->disableOriginalClone(
)->getMock();
$file = '/datei';
$expectedresponse = <<<JSON
{"message":"CSRF check failed"}
JSON;
// Expected Parameters.
$ocsquery = [
'path' => $file,
'shareType' => \repository_nextcloud\ocs_client::SHARE_TYPE_PUBLIC,
'publicUpload' => false,
'permissions' => \repository_nextcloud\ocs_client::SHARE_PERMISSION_READ
];
// With test whether mock is called with right parameters.
$mock->expects($this->once())->method('call')->with('create_share', $ocsquery)->will($this->returnValue($expectedresponse));
$this->set_private_property($mock, 'ocsclient');
// Suppress (expected) XML parse error... Nextcloud sometimes returns JSON on extremely bad errors.
libxml_use_internal_errors(true);
// Method get_link correctly raises an exception.
$this->expectException(\repository_nextcloud\request_exception::class);
$this->repo->get_link($file);
}
/**
* Test get_file reference, merely returns the input if no optional_param is set.
*/
public function test_get_file_reference_withoutoptionalparam() {
$this->assertEquals('/somefile', $this->repo->get_file_reference('/somefile'));
}
/**
* Test logout.
*/
public function test_logout() {
$mock = $this->createMock(\core\oauth2\client::class);
$mock->expects($this->exactly(2))->method('log_out');
$this->set_private_property($mock, 'client');
$this->repo->options['ajax'] = false;
$this->expectOutputString('<a target="_blank" rel="noopener noreferrer">Log in to your account</a>' .
'<a target="_blank" rel="noopener noreferrer">Log in to your account</a>');
$this->assertEquals($this->repo->print_login(), $this->repo->logout());
$mock->expects($this->exactly(2))->method('get_login_url')->will($this->returnValue(new moodle_url('url')));
$this->repo->options['ajax'] = true;
$this->assertEquals($this->repo->print_login(), $this->repo->logout());
}
/**
* Test for the get_file method from the repository_nextcloud class.
*/
public function test_get_file() {
// WebDAV socket is not open.
$mock = $this->createMock(\webdav_client::class);
$mock->expects($this->once())->method('open')->will($this->returnValue(false));
$private = $this->set_private_property($mock, 'dav');
$this->assertFalse($this->repo->get_file('path'));
// WebDAV socket is open and the request successful.
$mock = $this->createMock(\webdav_client::class);
$mock->expects($this->once())->method('open')->will($this->returnValue(true));
$mock->expects($this->once())->method('get_file')->will($this->returnValue(true));
$private->setValue($this->repo, $mock);
$result = $this->repo->get_file('path', 'file');
$this->assertNotNull($result['path']);
}
/**
* Test callback.
*/
public function test_callback() {
$mock = $this->createMock(\core\oauth2\client::class);
// Should call check_login exactly once.
$mock->expects($this->once())->method('log_out');
$mock->expects($this->once())->method('is_logged_in');
$this->set_private_property($mock, 'client');
$this->repo->callback();
}
/**
* Test check_login.
*/
public function test_check_login() {
$mock = $this->createMock(\core\oauth2\client::class);
$mock->expects($this->once())->method('is_logged_in')->will($this->returnValue(true));
$this->set_private_property($mock, 'client');
$this->assertTrue($this->repo->check_login());
}
/**
* Test print_login.
*/
public function test_print_login() {
$mock = $this->createMock(\core\oauth2\client::class);
$mock->expects($this->exactly(2))->method('get_login_url')->will($this->returnValue(new moodle_url('url')));
$this->set_private_property($mock, 'client');
// Test with ajax activated.
$this->repo->options['ajax'] = true;
$url = new moodle_url('url');
$ret = array();
$btn = new \stdClass();
$btn->type = 'popup';
$btn->url = $url->out(false);
$ret['login'] = array($btn);
$this->assertEquals($ret, $this->repo->print_login());
// Test without ajax.
$this->repo->options['ajax'] = false;
$output = html_writer::link($url, get_string('login', 'repository'),
array('target' => '_blank', 'rel' => 'noopener noreferrer'));
$this->expectOutputString($output);
$this->repo->print_login();
}
/**
* Test the initiate_webdavclient function.
*/
public function test_initiate_webdavclient() {
global $CFG;
$idwebdav = $this->get_endpoint_id('webdav_endpoint');
if (!empty($idwebdav)) {
foreach ($idwebdav as $id) {
\core\oauth2\api::delete_endpoint($id);
}
}
$generator = $this->getDataGenerator()->get_plugin_generator('repository_nextcloud');
$generator->test_create_single_endpoint($this->issuer->get('id'), "webdav_endpoint",
"https://www.default.test:8080/webdav/index.php");
$fakeaccesstoken = new stdClass();
$fakeaccesstoken->token = "fake access token";
$oauthmock = $this->createMock(\core\oauth2\client::class);
$oauthmock->expects($this->once())->method('get_accesstoken')->will($this->returnValue($fakeaccesstoken));
$this->set_private_property($oauthmock, 'client');
$dav = phpunit_util::call_internal_method($this->repo, "initiate_webdavclient", [], 'repository_nextcloud');
// Verify that port is set correctly (private property).
$refclient = new ReflectionClass($dav);
$property = $refclient->getProperty('_port');
$property->setAccessible(true);
$port = $property->getValue($dav);
$this->assertEquals('8080', $port);
}
/**
* Test supported_returntypes.
* FILE_INTERNAL | FILE_REFERENCE when no system account is connected.
* FILE_INTERNAL | FILE_CONTROLLED_LINK | FILE_REFERENCE when a system account is connected.
*/
public function test_supported_returntypes() {
global $DB;
$this->assertEquals(FILE_INTERNAL | FILE_REFERENCE, $this->repo->supported_returntypes());
$dataobject = new stdClass();
$dataobject->timecreated = time();
$dataobject->timemodified = time();
$dataobject->usermodified = 2;
$dataobject->issuerid = $this->issuer->get('id');
$dataobject->refreshtoken = 'sometokenthatwillnotbeused';
$dataobject->grantedscopes = 'openid profile email';
$dataobject->email = 'some.email@some.de';
$dataobject->username = 'someusername';
$DB->insert_record('oauth2_system_account', $dataobject);
// When a system account is registered the file_type FILE_CONTROLLED_LINK is supported.
$this->assertEquals(FILE_INTERNAL | FILE_CONTROLLED_LINK | FILE_REFERENCE,
$this->repo->supported_returntypes());
}
/**
* The reference_file_selected() method is called every time a FILE_CONTROLLED_LINK is chosen for upload.
* Since the function is very long the private function are tested separately, and merely the abortion of the
* function are tested.
*
*/
public function test_reference_file_selected_error() {
$this->repo->disabled = true;
$this->expectException(\repository_exception::class);
$this->repo->reference_file_selected('', context_system::instance(), '', '', '');
$this->repo->disabled = false;
$this->expectException(\repository_exception::class);
$this->expectExceptionMessage('Cannot connect as system user');
$this->repo->reference_file_selected('', context_system::instance(), '', '', '');
$mock = $this->createMock(\core\oauth2\client::class);
$mock->expects($this->once())->method('get_system_oauth_client')->with($this->issuer)->willReturn(true);
$this->expectException(\repository_exception::class);
$this->expectExceptionMessage('Cannot connect as current user');
$this->repo->reference_file_selected('', context_system::instance(), '', '', '');
$this->repo->expects($this->once())->method('get_user_oauth_client')->willReturn(true);
$this->expectException(\repository_exception::class);
$this->expectExceptionMessage('cannotdownload');
$this->repo->reference_file_selected('', context_system::instance(), '', '', '');
$this->repo->expects($this->once())->method('get_user_oauth_client')->willReturn(true);
$this->expectException(\repository_exception::class);
$this->expectExceptionMessage('cannotdownload');
$this->repo->reference_file_selected('', context_system::instance(), '', '', '');
$this->repo->expects($this->once())->method('get_user_oauth_client')->willReturn(true);
$this->repo->expects($this->once())->method('copy_file_to_path')->willReturn(array('statuscode' =>
array('success' => 400)));
$this->expectException(\repository_exception::class);
$this->expectExceptionMessage('Could not copy file');
$this->repo->reference_file_selected('', context_system::instance(), '', '', '');
$this->repo->expects($this->once())->method('get_user_oauth_client')->willReturn(true);
$this->repo->expects($this->once())->method('copy_file_to_path')->willReturn(array('statuscode' =>
array('success' => 201)));
$this->repo->expects($this->once())->method('delete_share_dataowner_sysaccount')->willReturn(
array('statuscode' => array('success' => 400)));
$this->expectException(\repository_exception::class);
$this->expectExceptionMessage('Share is still present');
$this->repo->reference_file_selected('', context_system::instance(), '', '', '');
$this->repo->expects($this->once())->method('get_user_oauth_client')->willReturn(true);
$this->repo->expects($this->once())->method('copy_file_to_path')->willReturn(array('statuscode' =>
array('success' => 201)));
$this->repo->expects($this->once())->method('delete_share_dataowner_sysaccount')->willReturn(
array('statuscode' => array('success' => 100)));
$filereturn = array();
$filereturn->link = 'some/fullpath' . 'some/target/path';
$filereturn->name = 'mysource';
$filereturn->usesystem = true;
$filereturn = json_encode($filereturn);
$return = $this->repo->reference_file_selected('mysource', context_system::instance(), '', '', '');
$this->assertEquals($filereturn, $return);
}
/**
* Test the send_file function for access controlled links.
*/
public function test_send_file_errors() {
$fs = get_file_storage();
$storedfile = $fs->create_file_from_reference([
'contextid' => context_system::instance()->id,
'component' => 'core',
'filearea' => 'unittest',
'itemid' => 0,
'filepath' => '/',
'filename' => 'testfile.txt',
], $this->repo->id, json_encode([
'type' => 'FILE_CONTROLLED_LINK',
'link' => 'https://test.local/fakelink/',
'usesystem' => true,
]));
$this->set_private_property('', 'client');
$this->expectException(repository_nextcloud\request_exception::class);
$this->expectExceptionMessage(get_string('contactadminwith', 'repository_nextcloud',
'The OAuth clients could not be connected.'));
$this->repo->send_file($storedfile, '', '', '');
// Testing whether the mock up appears is topic to behat.
$mock = $this->createMock(\core\oauth2\client::class);
$mock->expects($this->once())->method('is_logged_in')->willReturn(true);
$this->repo->send_file($storedfile, '', '', '');
// Checks that setting for foldername are used.
$mock->expects($this->once())->method('is_dir')->with('Moodlefiles')->willReturn(false);
// In case of false as return value mkcol is called to create the folder.
$parsedwebdavurl = parse_url($this->issuer->get_endpoint_url('webdav'));
$webdavprefix = $parsedwebdavurl['path'];
$mock->expects($this->once())->method('mkcol')->with(
$webdavprefix . 'Moodlefiles')->willReturn(400);
$this->expectException(\repository_nextcloud\request_exception::class);
$this->expectExceptionMessage(get_string('requestnotexecuted', 'repository_nextcloud'));
$this->repo->send_file($storedfile, '', '', '');
$expectedresponse = <<<XML
<?xml version="1.0"?>
<ocs>
<meta>
<status>ok</status>
<statuscode>100</statuscode>
<message/>
</meta>
<data>
<element>
<id>6</id>
<share_type>0</share_type>
<uid_owner>tech</uid_owner>
<displayname_owner>tech</displayname_owner>
<permissions>19</permissions>
<stime>1511877999</stime>
<parent/>
<expiration/>
<token/>
<uid_file_owner>tech</uid_file_owner>
<displayname_file_owner>tech</displayname_file_owner>
<path>/System/Category Category 1/Course Example Course/File morefiles/mod_resource/content/0/merge.txt</path>
<item_type>file</item_type>
<mimetype>text/plain</mimetype>
<storage_id>home::tech</storage_id>
<storage>4</storage>
<item_source>824</item_source>
<file_source>824</file_source>
<file_parent>823</file_parent>
<file_target>/merge (3).txt</file_target>
<share_with>user2</share_with>
<share_with_displayname>user1</share_with_displayname>
<mail_send>0</mail_send>
</element>
<element>
<id>5</id>
<share_type>0</share_type>
<uid_owner>tech</uid_owner>
<displayname_owner>tech</displayname_owner>
<permissions>19</permissions>
<stime>1511877999</stime>
<parent/>
<expiration/>
<token/>
<uid_file_owner>tech</uid_file_owner>
<displayname_file_owner>tech</displayname_file_owner>
<path>/System/Category Category 1/Course Example Course/File morefiles/mod_resource/content/0/merge.txt</path>
<item_type>file</item_type>
<mimetype>text/plain</mimetype>
<storage_id>home::tech</storage_id>
<storage>4</storage>
<item_source>824</item_source>
<file_source>824</file_source>
<file_parent>823</file_parent>
<file_target>/merged (3).txt</file_target>
<share_with>user1</share_with>
<share_with_displayname>user1</share_with_displayname>
<mail_send>0</mail_send>
</element>
</data>
</ocs>
XML;
// Checks that setting for foldername are used.
$mock->expects($this->once())->method('is_dir')->with('Moodlefiles')->willReturn(true);
// In case of true as return value mkcol is not called to create the folder.
$shareid = 5;
$mockocsclient = $this->getMockBuilder(
\repository_nextcloud\ocs_client::class)->disableOriginalConstructor()->disableOriginalClone()->getMock();
$mockocsclient->expects($this->exactly(2))->method('call')->with('get_information_of_share',
array('share_id' => $shareid))->will($this->returnValue($expectedresponse));
$this->set_private_property($mock, 'ocsclient');
$this->repo->expects($this->once())->method('move_file_to_folder')->with('/merged (3).txt', 'Moodlefiles',
$mock)->willReturn(array('success' => 201));
$this->repo->send_file('', '', '', '');
// Create test for statuscode 403.
// Checks that setting for foldername are used.
$mock->expects($this->once())->method('is_dir')->with('Moodlefiles')->willReturn(true);
// In case of true as return value mkcol is not called to create the folder.
$shareid = 5;
$mockocsclient = $this->getMockBuilder(\repository_nextcloud\ocs_client::class
)->disableOriginalConstructor()->disableOriginalClone()->getMock();
$mockocsclient->expects($this->exactly(1))->method('call')->with('get_shares',
array('path' => '/merged (3).txt', 'reshares' => true))->will($this->returnValue($expectedresponse));
$mockocsclient->expects($this->exactly(1))->method('call')->with('get_information_of_share',
array('share_id' => $shareid))->will($this->returnValue($expectedresponse));
$this->set_private_property($mock, 'ocsclient');
$this->repo->expects($this->once())->method('move_file_to_folder')->with('/merged (3).txt', 'Moodlefiles',
$mock)->willReturn(array('success' => 201));
$this->repo->send_file('', '', '', '');
}
/**
* This function provides the data for test_sync_reference
*
* @return array[]
*/
public function sync_reference_provider():array {
return [
'referecncelastsync done recently' => [
[
'storedfile_record' => [
'contextid' => context_system::instance()->id,
'component' => 'core',
'filearea' => 'unittest',
'itemid' => 0,
'filepath' => '/',
'filename' => 'testfile.txt',
],
'storedfile_reference' => json_encode(
[
'type' => 'FILE_REFERENCE',
'link' => 'https://test.local/fakelink/',
'usesystem' => true,
'referencelastsync' => DAYSECS + time()
]
),
],
'mockfunctions' => ['get_referencelastsync'],
'expectedresult' => false
],
'file without link' => [
[
'storedfile_record' => [
'contextid' => context_system::instance()->id,
'component' => 'core',
'filearea' => 'unittest',
'itemid' => 0,
'filepath' => '/',
'filename' => 'testfile.txt',
],
'storedfile_reference' => json_encode(
[
'type' => 'FILE_REFERENCE',
'usesystem' => true,
]
),
],
'mockfunctions' => [],
'expectedresult' => false
],
'file extenstion to exclude' => [
[
'storedfile_record' => [
'contextid' => context_system::instance()->id,
'component' => 'core',
'filearea' => 'unittest',
'itemid' => 0,
'filepath' => '/',
'filename' => 'testfile.txt',
],
'storedfile_reference' => json_encode(
[
'link' => 'https://test.local/fakelink/',
'type' => 'FILE_REFERENCE',
'usesystem' => true,
]
),
],
'mockfunctions' => [],
'expectedresult' => false
],
'file extenstion for image' => [
[
'storedfile_record' => [
'contextid' => context_system::instance()->id,
'component' => 'core',
'filearea' => 'unittest',
'itemid' => 0,
'filepath' => '/',
'filename' => 'testfile.png',
],
'storedfile_reference' => json_encode(
[
'link' => 'https://test.local/fakelink/',
'type' => 'FILE_REFERENCE',
'usesystem' => true,
]
),
'mock_curl' => true,
],
'mockfunctions' => [''],
'expectedresult' => true
],
];
}
/**
* Testing sync_reference
*
* @dataProvider sync_reference_provider
* @param array $storedfileargs
* @param array $storedfilemethodsmock
* @param bool $expectedresult
* @return void
*/
public function test_sync_reference(array $storedfileargs, $storedfilemethodsmock, bool $expectedresult):void {
$this->resetAfterTest(true);
if (isset($storedfilemethodsmock[0])) {
$storedfile = $this->createMock(stored_file::class);
if ($storedfilemethodsmock[0] === 'get_referencelastsync') {
if (!$expectedresult) {
$storedfile->method('get_referencelastsync')->willReturn(DAYSECS + time());
}
} else {
$storedfile->method('get_referencelastsync')->willReturn(null);
}
$storedfile->method('get_reference')->willReturn($storedfileargs['storedfile_reference']);
$storedfile->method('get_filepath')->willReturn($storedfileargs['storedfile_record']['filepath']);
$storedfile->method('get_filename')->willReturn($storedfileargs['storedfile_record']['filename']);
if ((isset($storedfileargs['mock_curl']) && $storedfileargs)) {
// Lets mock curl, else it would not serve the purpose here.
$curl = $this->createMock(curl::class);
$curl->method('download_one')->willReturn(true);
$curl->method('get_info')->willReturn(['http_code' => 200]);
$reflectionproperty = new \ReflectionProperty($this->repo, 'curl');
$reflectionproperty->setAccessible(true);
$reflectionproperty->setValue($this->repo, $curl);
}
} else {
$fs = get_file_storage();
$storedfile = $fs->create_file_from_reference(
$storedfileargs['storedfile_record'],
$this->repo->id,
$storedfileargs['storedfile_reference']);
}
$actualresult = $this->repo->sync_reference($storedfile);
$this->assertEquals($expectedresult, $actualresult);
}
/**
* Helper method, which inserts a given mock value into the repository_nextcloud object.
*
* @param mixed $value mock value that will be inserted.
* @param string $propertyname name of the private property.
* @return ReflectionProperty the resulting reflection property.
*/
protected function set_private_property($value, $propertyname) {
$refclient = new ReflectionClass($this->repo);
$private = $refclient->getProperty($propertyname);
$private->setAccessible(true);
$private->setValue($this->repo, $value);
return $private;
}
/**
* Helper method to set required return parameters for get_listing.
*
* @return array array, which contains the parameters.
*/
protected function get_initialised_return_array() {
$ret = array();
$ret['dynload'] = true;
$ret['nosearch'] = true;
$ret['nologin'] = false;
$ret['path'] = [
[
'name' => $this->repo->get_meta()->name,
'path' => '',
]
];
$ret['manage'] = '';
$ret['defaultreturntype'] = FILE_INTERNAL;
$ret['list'] = array();
$ret['filereferencewarning'] = get_string('externalpubliclinkwarning', 'repository_nextcloud');
return $ret;
}
}
| michael-milette/moodle | repository/nextcloud/tests/lib_test.php | PHP | gpl-3.0 | 41,264 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Data/PokemonData.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Data {
/// <summary>Holder for reflection information generated from POGOProtos/Data/PokemonData.proto</summary>
public static partial class PokemonDataReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Data/PokemonData.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PokemonDataReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiFQT0dPUHJvdG9zL0RhdGEvUG9rZW1vbkRhdGEucHJvdG8SD1BPR09Qcm90",
"b3MuRGF0YRogUE9HT1Byb3Rvcy9FbnVtcy9Qb2tlbW9uSWQucHJvdG8aIlBP",
"R09Qcm90b3MvRW51bXMvUG9rZW1vbk1vdmUucHJvdG8aJlBPR09Qcm90b3Mv",
"SW52ZW50b3J5L0l0ZW0vSXRlbUlkLnByb3RvIpgGCgtQb2tlbW9uRGF0YRIK",
"CgJpZBgBIAEoBhIvCgpwb2tlbW9uX2lkGAIgASgOMhsuUE9HT1Byb3Rvcy5F",
"bnVtcy5Qb2tlbW9uSWQSCgoCY3AYAyABKAUSDwoHc3RhbWluYRgEIAEoBRIT",
"CgtzdGFtaW5hX21heBgFIAEoBRItCgZtb3ZlXzEYBiABKA4yHS5QT0dPUHJv",
"dG9zLkVudW1zLlBva2Vtb25Nb3ZlEi0KBm1vdmVfMhgHIAEoDjIdLlBPR09Q",
"cm90b3MuRW51bXMuUG9rZW1vbk1vdmUSGAoQZGVwbG95ZWRfZm9ydF9pZBgI",
"IAEoCRISCgpvd25lcl9uYW1lGAkgASgJEg4KBmlzX2VnZxgKIAEoCBIcChRl",
"Z2dfa21fd2Fsa2VkX3RhcmdldBgLIAEoARIbChNlZ2dfa21fd2Fsa2VkX3N0",
"YXJ0GAwgASgBEg4KBm9yaWdpbhgOIAEoBRIQCghoZWlnaHRfbRgPIAEoAhIR",
"Cgl3ZWlnaHRfa2cYECABKAISGQoRaW5kaXZpZHVhbF9hdHRhY2sYESABKAUS",
"GgoSaW5kaXZpZHVhbF9kZWZlbnNlGBIgASgFEhoKEmluZGl2aWR1YWxfc3Rh",
"bWluYRgTIAEoBRIVCg1jcF9tdWx0aXBsaWVyGBQgASgCEjMKCHBva2ViYWxs",
"GBUgASgOMiEuUE9HT1Byb3Rvcy5JbnZlbnRvcnkuSXRlbS5JdGVtSWQSGAoQ",
"Y2FwdHVyZWRfY2VsbF9pZBgWIAEoBBIYChBiYXR0bGVzX2F0dGFja2VkGBcg",
"ASgFEhgKEGJhdHRsZXNfZGVmZW5kZWQYGCABKAUSGAoQZWdnX2luY3ViYXRv",
"cl9pZBgZIAEoCRIYChBjcmVhdGlvbl90aW1lX21zGBogASgEEhQKDG51bV91",
"cGdyYWRlcxgbIAEoBRIgChhhZGRpdGlvbmFsX2NwX211bHRpcGxpZXIYHCAB",
"KAISEAoIZmF2b3JpdGUYHSABKAUSEAoIbmlja25hbWUYHiABKAkSEQoJZnJv",
"bV9mb3J0GB8gASgFYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::POGOProtos.Enums.PokemonIdReflection.Descriptor, global::POGOProtos.Enums.PokemonMoveReflection.Descriptor, global::POGOProtos.Inventory.Item.ItemIdReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Data.PokemonData), global::POGOProtos.Data.PokemonData.Parser, new[]{ "Id", "PokemonId", "Cp", "Stamina", "StaminaMax", "Move1", "Move2", "DeployedFortId", "OwnerName", "IsEgg", "EggKmWalkedTarget", "EggKmWalkedStart", "Origin", "HeightM", "WeightKg", "IndividualAttack", "IndividualDefense", "IndividualStamina", "CpMultiplier", "Pokeball", "CapturedCellId", "BattlesAttacked", "BattlesDefended", "EggIncubatorId", "CreationTimeMs", "NumUpgrades", "AdditionalCpMultiplier", "Favorite", "Nickname", "FromFort" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class PokemonData : pb::IMessage<PokemonData> {
private static readonly pb::MessageParser<PokemonData> _parser = new pb::MessageParser<PokemonData>(() => new PokemonData());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PokemonData> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Data.PokemonDataReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PokemonData() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PokemonData(PokemonData other) : this() {
id_ = other.id_;
pokemonId_ = other.pokemonId_;
cp_ = other.cp_;
stamina_ = other.stamina_;
staminaMax_ = other.staminaMax_;
move1_ = other.move1_;
move2_ = other.move2_;
deployedFortId_ = other.deployedFortId_;
ownerName_ = other.ownerName_;
isEgg_ = other.isEgg_;
eggKmWalkedTarget_ = other.eggKmWalkedTarget_;
eggKmWalkedStart_ = other.eggKmWalkedStart_;
origin_ = other.origin_;
heightM_ = other.heightM_;
weightKg_ = other.weightKg_;
individualAttack_ = other.individualAttack_;
individualDefense_ = other.individualDefense_;
individualStamina_ = other.individualStamina_;
cpMultiplier_ = other.cpMultiplier_;
pokeball_ = other.pokeball_;
capturedCellId_ = other.capturedCellId_;
battlesAttacked_ = other.battlesAttacked_;
battlesDefended_ = other.battlesDefended_;
eggIncubatorId_ = other.eggIncubatorId_;
creationTimeMs_ = other.creationTimeMs_;
numUpgrades_ = other.numUpgrades_;
additionalCpMultiplier_ = other.additionalCpMultiplier_;
favorite_ = other.favorite_;
nickname_ = other.nickname_;
fromFort_ = other.fromFort_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PokemonData Clone() {
return new PokemonData(this);
}
/// <summary>Field number for the "id" field.</summary>
public const int IdFieldNumber = 1;
private ulong id_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong Id {
get { return id_; }
set {
id_ = value;
}
}
/// <summary>Field number for the "pokemon_id" field.</summary>
public const int PokemonIdFieldNumber = 2;
private global::POGOProtos.Enums.PokemonId pokemonId_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.PokemonId PokemonId {
get { return pokemonId_; }
set {
pokemonId_ = value;
}
}
/// <summary>Field number for the "cp" field.</summary>
public const int CpFieldNumber = 3;
private int cp_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Cp {
get { return cp_; }
set {
cp_ = value;
}
}
/// <summary>Field number for the "stamina" field.</summary>
public const int StaminaFieldNumber = 4;
private int stamina_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Stamina {
get { return stamina_; }
set {
stamina_ = value;
}
}
/// <summary>Field number for the "stamina_max" field.</summary>
public const int StaminaMaxFieldNumber = 5;
private int staminaMax_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int StaminaMax {
get { return staminaMax_; }
set {
staminaMax_ = value;
}
}
/// <summary>Field number for the "move_1" field.</summary>
public const int Move1FieldNumber = 6;
private global::POGOProtos.Enums.PokemonMove move1_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.PokemonMove Move1 {
get { return move1_; }
set {
move1_ = value;
}
}
/// <summary>Field number for the "move_2" field.</summary>
public const int Move2FieldNumber = 7;
private global::POGOProtos.Enums.PokemonMove move2_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.PokemonMove Move2 {
get { return move2_; }
set {
move2_ = value;
}
}
/// <summary>Field number for the "deployed_fort_id" field.</summary>
public const int DeployedFortIdFieldNumber = 8;
private string deployedFortId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string DeployedFortId {
get { return deployedFortId_; }
set {
deployedFortId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "owner_name" field.</summary>
public const int OwnerNameFieldNumber = 9;
private string ownerName_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string OwnerName {
get { return ownerName_; }
set {
ownerName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "is_egg" field.</summary>
public const int IsEggFieldNumber = 10;
private bool isEgg_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool IsEgg {
get { return isEgg_; }
set {
isEgg_ = value;
}
}
/// <summary>Field number for the "egg_km_walked_target" field.</summary>
public const int EggKmWalkedTargetFieldNumber = 11;
private double eggKmWalkedTarget_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double EggKmWalkedTarget {
get { return eggKmWalkedTarget_; }
set {
eggKmWalkedTarget_ = value;
}
}
/// <summary>Field number for the "egg_km_walked_start" field.</summary>
public const int EggKmWalkedStartFieldNumber = 12;
private double eggKmWalkedStart_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double EggKmWalkedStart {
get { return eggKmWalkedStart_; }
set {
eggKmWalkedStart_ = value;
}
}
/// <summary>Field number for the "origin" field.</summary>
public const int OriginFieldNumber = 14;
private int origin_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Origin {
get { return origin_; }
set {
origin_ = value;
}
}
/// <summary>Field number for the "height_m" field.</summary>
public const int HeightMFieldNumber = 15;
private float heightM_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float HeightM {
get { return heightM_; }
set {
heightM_ = value;
}
}
/// <summary>Field number for the "weight_kg" field.</summary>
public const int WeightKgFieldNumber = 16;
private float weightKg_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float WeightKg {
get { return weightKg_; }
set {
weightKg_ = value;
}
}
/// <summary>Field number for the "individual_attack" field.</summary>
public const int IndividualAttackFieldNumber = 17;
private int individualAttack_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int IndividualAttack {
get { return individualAttack_; }
set {
individualAttack_ = value;
}
}
/// <summary>Field number for the "individual_defense" field.</summary>
public const int IndividualDefenseFieldNumber = 18;
private int individualDefense_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int IndividualDefense {
get { return individualDefense_; }
set {
individualDefense_ = value;
}
}
/// <summary>Field number for the "individual_stamina" field.</summary>
public const int IndividualStaminaFieldNumber = 19;
private int individualStamina_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int IndividualStamina {
get { return individualStamina_; }
set {
individualStamina_ = value;
}
}
/// <summary>Field number for the "cp_multiplier" field.</summary>
public const int CpMultiplierFieldNumber = 20;
private float cpMultiplier_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float CpMultiplier {
get { return cpMultiplier_; }
set {
cpMultiplier_ = value;
}
}
/// <summary>Field number for the "pokeball" field.</summary>
public const int PokeballFieldNumber = 21;
private global::POGOProtos.Inventory.Item.ItemId pokeball_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Inventory.Item.ItemId Pokeball {
get { return pokeball_; }
set {
pokeball_ = value;
}
}
/// <summary>Field number for the "captured_cell_id" field.</summary>
public const int CapturedCellIdFieldNumber = 22;
private ulong capturedCellId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong CapturedCellId {
get { return capturedCellId_; }
set {
capturedCellId_ = value;
}
}
/// <summary>Field number for the "battles_attacked" field.</summary>
public const int BattlesAttackedFieldNumber = 23;
private int battlesAttacked_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int BattlesAttacked {
get { return battlesAttacked_; }
set {
battlesAttacked_ = value;
}
}
/// <summary>Field number for the "battles_defended" field.</summary>
public const int BattlesDefendedFieldNumber = 24;
private int battlesDefended_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int BattlesDefended {
get { return battlesDefended_; }
set {
battlesDefended_ = value;
}
}
/// <summary>Field number for the "egg_incubator_id" field.</summary>
public const int EggIncubatorIdFieldNumber = 25;
private string eggIncubatorId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string EggIncubatorId {
get { return eggIncubatorId_; }
set {
eggIncubatorId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "creation_time_ms" field.</summary>
public const int CreationTimeMsFieldNumber = 26;
private ulong creationTimeMs_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong CreationTimeMs {
get { return creationTimeMs_; }
set {
creationTimeMs_ = value;
}
}
/// <summary>Field number for the "num_upgrades" field.</summary>
public const int NumUpgradesFieldNumber = 27;
private int numUpgrades_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int NumUpgrades {
get { return numUpgrades_; }
set {
numUpgrades_ = value;
}
}
/// <summary>Field number for the "additional_cp_multiplier" field.</summary>
public const int AdditionalCpMultiplierFieldNumber = 28;
private float additionalCpMultiplier_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float AdditionalCpMultiplier {
get { return additionalCpMultiplier_; }
set {
additionalCpMultiplier_ = value;
}
}
/// <summary>Field number for the "favorite" field.</summary>
public const int FavoriteFieldNumber = 29;
private int favorite_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Favorite {
get { return favorite_; }
set {
favorite_ = value;
}
}
/// <summary>Field number for the "nickname" field.</summary>
public const int NicknameFieldNumber = 30;
private string nickname_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Nickname {
get { return nickname_; }
set {
nickname_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "from_fort" field.</summary>
public const int FromFortFieldNumber = 31;
private int fromFort_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FromFort {
get { return fromFort_; }
set {
fromFort_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PokemonData);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PokemonData other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Id != other.Id) return false;
if (PokemonId != other.PokemonId) return false;
if (Cp != other.Cp) return false;
if (Stamina != other.Stamina) return false;
if (StaminaMax != other.StaminaMax) return false;
if (Move1 != other.Move1) return false;
if (Move2 != other.Move2) return false;
if (DeployedFortId != other.DeployedFortId) return false;
if (OwnerName != other.OwnerName) return false;
if (IsEgg != other.IsEgg) return false;
if (EggKmWalkedTarget != other.EggKmWalkedTarget) return false;
if (EggKmWalkedStart != other.EggKmWalkedStart) return false;
if (Origin != other.Origin) return false;
if (HeightM != other.HeightM) return false;
if (WeightKg != other.WeightKg) return false;
if (IndividualAttack != other.IndividualAttack) return false;
if (IndividualDefense != other.IndividualDefense) return false;
if (IndividualStamina != other.IndividualStamina) return false;
if (CpMultiplier != other.CpMultiplier) return false;
if (Pokeball != other.Pokeball) return false;
if (CapturedCellId != other.CapturedCellId) return false;
if (BattlesAttacked != other.BattlesAttacked) return false;
if (BattlesDefended != other.BattlesDefended) return false;
if (EggIncubatorId != other.EggIncubatorId) return false;
if (CreationTimeMs != other.CreationTimeMs) return false;
if (NumUpgrades != other.NumUpgrades) return false;
if (AdditionalCpMultiplier != other.AdditionalCpMultiplier) return false;
if (Favorite != other.Favorite) return false;
if (Nickname != other.Nickname) return false;
if (FromFort != other.FromFort) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Id != 0UL) hash ^= Id.GetHashCode();
if (PokemonId != 0) hash ^= PokemonId.GetHashCode();
if (Cp != 0) hash ^= Cp.GetHashCode();
if (Stamina != 0) hash ^= Stamina.GetHashCode();
if (StaminaMax != 0) hash ^= StaminaMax.GetHashCode();
if (Move1 != 0) hash ^= Move1.GetHashCode();
if (Move2 != 0) hash ^= Move2.GetHashCode();
if (DeployedFortId.Length != 0) hash ^= DeployedFortId.GetHashCode();
if (OwnerName.Length != 0) hash ^= OwnerName.GetHashCode();
if (IsEgg != false) hash ^= IsEgg.GetHashCode();
if (EggKmWalkedTarget != 0D) hash ^= EggKmWalkedTarget.GetHashCode();
if (EggKmWalkedStart != 0D) hash ^= EggKmWalkedStart.GetHashCode();
if (Origin != 0) hash ^= Origin.GetHashCode();
if (HeightM != 0F) hash ^= HeightM.GetHashCode();
if (WeightKg != 0F) hash ^= WeightKg.GetHashCode();
if (IndividualAttack != 0) hash ^= IndividualAttack.GetHashCode();
if (IndividualDefense != 0) hash ^= IndividualDefense.GetHashCode();
if (IndividualStamina != 0) hash ^= IndividualStamina.GetHashCode();
if (CpMultiplier != 0F) hash ^= CpMultiplier.GetHashCode();
if (Pokeball != 0) hash ^= Pokeball.GetHashCode();
if (CapturedCellId != 0UL) hash ^= CapturedCellId.GetHashCode();
if (BattlesAttacked != 0) hash ^= BattlesAttacked.GetHashCode();
if (BattlesDefended != 0) hash ^= BattlesDefended.GetHashCode();
if (EggIncubatorId.Length != 0) hash ^= EggIncubatorId.GetHashCode();
if (CreationTimeMs != 0UL) hash ^= CreationTimeMs.GetHashCode();
if (NumUpgrades != 0) hash ^= NumUpgrades.GetHashCode();
if (AdditionalCpMultiplier != 0F) hash ^= AdditionalCpMultiplier.GetHashCode();
if (Favorite != 0) hash ^= Favorite.GetHashCode();
if (Nickname.Length != 0) hash ^= Nickname.GetHashCode();
if (FromFort != 0) hash ^= FromFort.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Id != 0UL) {
output.WriteRawTag(9);
output.WriteFixed64(Id);
}
if (PokemonId != 0) {
output.WriteRawTag(16);
output.WriteEnum((int) PokemonId);
}
if (Cp != 0) {
output.WriteRawTag(24);
output.WriteInt32(Cp);
}
if (Stamina != 0) {
output.WriteRawTag(32);
output.WriteInt32(Stamina);
}
if (StaminaMax != 0) {
output.WriteRawTag(40);
output.WriteInt32(StaminaMax);
}
if (Move1 != 0) {
output.WriteRawTag(48);
output.WriteEnum((int) Move1);
}
if (Move2 != 0) {
output.WriteRawTag(56);
output.WriteEnum((int) Move2);
}
if (DeployedFortId.Length != 0) {
output.WriteRawTag(66);
output.WriteString(DeployedFortId);
}
if (OwnerName.Length != 0) {
output.WriteRawTag(74);
output.WriteString(OwnerName);
}
if (IsEgg != false) {
output.WriteRawTag(80);
output.WriteBool(IsEgg);
}
if (EggKmWalkedTarget != 0D) {
output.WriteRawTag(89);
output.WriteDouble(EggKmWalkedTarget);
}
if (EggKmWalkedStart != 0D) {
output.WriteRawTag(97);
output.WriteDouble(EggKmWalkedStart);
}
if (Origin != 0) {
output.WriteRawTag(112);
output.WriteInt32(Origin);
}
if (HeightM != 0F) {
output.WriteRawTag(125);
output.WriteFloat(HeightM);
}
if (WeightKg != 0F) {
output.WriteRawTag(133, 1);
output.WriteFloat(WeightKg);
}
if (IndividualAttack != 0) {
output.WriteRawTag(136, 1);
output.WriteInt32(IndividualAttack);
}
if (IndividualDefense != 0) {
output.WriteRawTag(144, 1);
output.WriteInt32(IndividualDefense);
}
if (IndividualStamina != 0) {
output.WriteRawTag(152, 1);
output.WriteInt32(IndividualStamina);
}
if (CpMultiplier != 0F) {
output.WriteRawTag(165, 1);
output.WriteFloat(CpMultiplier);
}
if (Pokeball != 0) {
output.WriteRawTag(168, 1);
output.WriteEnum((int) Pokeball);
}
if (CapturedCellId != 0UL) {
output.WriteRawTag(176, 1);
output.WriteUInt64(CapturedCellId);
}
if (BattlesAttacked != 0) {
output.WriteRawTag(184, 1);
output.WriteInt32(BattlesAttacked);
}
if (BattlesDefended != 0) {
output.WriteRawTag(192, 1);
output.WriteInt32(BattlesDefended);
}
if (EggIncubatorId.Length != 0) {
output.WriteRawTag(202, 1);
output.WriteString(EggIncubatorId);
}
if (CreationTimeMs != 0UL) {
output.WriteRawTag(208, 1);
output.WriteUInt64(CreationTimeMs);
}
if (NumUpgrades != 0) {
output.WriteRawTag(216, 1);
output.WriteInt32(NumUpgrades);
}
if (AdditionalCpMultiplier != 0F) {
output.WriteRawTag(229, 1);
output.WriteFloat(AdditionalCpMultiplier);
}
if (Favorite != 0) {
output.WriteRawTag(232, 1);
output.WriteInt32(Favorite);
}
if (Nickname.Length != 0) {
output.WriteRawTag(242, 1);
output.WriteString(Nickname);
}
if (FromFort != 0) {
output.WriteRawTag(248, 1);
output.WriteInt32(FromFort);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Id != 0UL) {
size += 1 + 8;
}
if (PokemonId != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) PokemonId);
}
if (Cp != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Cp);
}
if (Stamina != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Stamina);
}
if (StaminaMax != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(StaminaMax);
}
if (Move1 != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Move1);
}
if (Move2 != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Move2);
}
if (DeployedFortId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DeployedFortId);
}
if (OwnerName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(OwnerName);
}
if (IsEgg != false) {
size += 1 + 1;
}
if (EggKmWalkedTarget != 0D) {
size += 1 + 8;
}
if (EggKmWalkedStart != 0D) {
size += 1 + 8;
}
if (Origin != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Origin);
}
if (HeightM != 0F) {
size += 1 + 4;
}
if (WeightKg != 0F) {
size += 2 + 4;
}
if (IndividualAttack != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(IndividualAttack);
}
if (IndividualDefense != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(IndividualDefense);
}
if (IndividualStamina != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(IndividualStamina);
}
if (CpMultiplier != 0F) {
size += 2 + 4;
}
if (Pokeball != 0) {
size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) Pokeball);
}
if (CapturedCellId != 0UL) {
size += 2 + pb::CodedOutputStream.ComputeUInt64Size(CapturedCellId);
}
if (BattlesAttacked != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(BattlesAttacked);
}
if (BattlesDefended != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(BattlesDefended);
}
if (EggIncubatorId.Length != 0) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(EggIncubatorId);
}
if (CreationTimeMs != 0UL) {
size += 2 + pb::CodedOutputStream.ComputeUInt64Size(CreationTimeMs);
}
if (NumUpgrades != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(NumUpgrades);
}
if (AdditionalCpMultiplier != 0F) {
size += 2 + 4;
}
if (Favorite != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(Favorite);
}
if (Nickname.Length != 0) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(Nickname);
}
if (FromFort != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(FromFort);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PokemonData other) {
if (other == null) {
return;
}
if (other.Id != 0UL) {
Id = other.Id;
}
if (other.PokemonId != 0) {
PokemonId = other.PokemonId;
}
if (other.Cp != 0) {
Cp = other.Cp;
}
if (other.Stamina != 0) {
Stamina = other.Stamina;
}
if (other.StaminaMax != 0) {
StaminaMax = other.StaminaMax;
}
if (other.Move1 != 0) {
Move1 = other.Move1;
}
if (other.Move2 != 0) {
Move2 = other.Move2;
}
if (other.DeployedFortId.Length != 0) {
DeployedFortId = other.DeployedFortId;
}
if (other.OwnerName.Length != 0) {
OwnerName = other.OwnerName;
}
if (other.IsEgg != false) {
IsEgg = other.IsEgg;
}
if (other.EggKmWalkedTarget != 0D) {
EggKmWalkedTarget = other.EggKmWalkedTarget;
}
if (other.EggKmWalkedStart != 0D) {
EggKmWalkedStart = other.EggKmWalkedStart;
}
if (other.Origin != 0) {
Origin = other.Origin;
}
if (other.HeightM != 0F) {
HeightM = other.HeightM;
}
if (other.WeightKg != 0F) {
WeightKg = other.WeightKg;
}
if (other.IndividualAttack != 0) {
IndividualAttack = other.IndividualAttack;
}
if (other.IndividualDefense != 0) {
IndividualDefense = other.IndividualDefense;
}
if (other.IndividualStamina != 0) {
IndividualStamina = other.IndividualStamina;
}
if (other.CpMultiplier != 0F) {
CpMultiplier = other.CpMultiplier;
}
if (other.Pokeball != 0) {
Pokeball = other.Pokeball;
}
if (other.CapturedCellId != 0UL) {
CapturedCellId = other.CapturedCellId;
}
if (other.BattlesAttacked != 0) {
BattlesAttacked = other.BattlesAttacked;
}
if (other.BattlesDefended != 0) {
BattlesDefended = other.BattlesDefended;
}
if (other.EggIncubatorId.Length != 0) {
EggIncubatorId = other.EggIncubatorId;
}
if (other.CreationTimeMs != 0UL) {
CreationTimeMs = other.CreationTimeMs;
}
if (other.NumUpgrades != 0) {
NumUpgrades = other.NumUpgrades;
}
if (other.AdditionalCpMultiplier != 0F) {
AdditionalCpMultiplier = other.AdditionalCpMultiplier;
}
if (other.Favorite != 0) {
Favorite = other.Favorite;
}
if (other.Nickname.Length != 0) {
Nickname = other.Nickname;
}
if (other.FromFort != 0) {
FromFort = other.FromFort;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 9: {
Id = input.ReadFixed64();
break;
}
case 16: {
pokemonId_ = (global::POGOProtos.Enums.PokemonId) input.ReadEnum();
break;
}
case 24: {
Cp = input.ReadInt32();
break;
}
case 32: {
Stamina = input.ReadInt32();
break;
}
case 40: {
StaminaMax = input.ReadInt32();
break;
}
case 48: {
move1_ = (global::POGOProtos.Enums.PokemonMove) input.ReadEnum();
break;
}
case 56: {
move2_ = (global::POGOProtos.Enums.PokemonMove) input.ReadEnum();
break;
}
case 66: {
DeployedFortId = input.ReadString();
break;
}
case 74: {
OwnerName = input.ReadString();
break;
}
case 80: {
IsEgg = input.ReadBool();
break;
}
case 89: {
EggKmWalkedTarget = input.ReadDouble();
break;
}
case 97: {
EggKmWalkedStart = input.ReadDouble();
break;
}
case 112: {
Origin = input.ReadInt32();
break;
}
case 125: {
HeightM = input.ReadFloat();
break;
}
case 133: {
WeightKg = input.ReadFloat();
break;
}
case 136: {
IndividualAttack = input.ReadInt32();
break;
}
case 144: {
IndividualDefense = input.ReadInt32();
break;
}
case 152: {
IndividualStamina = input.ReadInt32();
break;
}
case 165: {
CpMultiplier = input.ReadFloat();
break;
}
case 168: {
pokeball_ = (global::POGOProtos.Inventory.Item.ItemId) input.ReadEnum();
break;
}
case 176: {
CapturedCellId = input.ReadUInt64();
break;
}
case 184: {
BattlesAttacked = input.ReadInt32();
break;
}
case 192: {
BattlesDefended = input.ReadInt32();
break;
}
case 202: {
EggIncubatorId = input.ReadString();
break;
}
case 208: {
CreationTimeMs = input.ReadUInt64();
break;
}
case 216: {
NumUpgrades = input.ReadInt32();
break;
}
case 229: {
AdditionalCpMultiplier = input.ReadFloat();
break;
}
case 232: {
Favorite = input.ReadInt32();
break;
}
case 242: {
Nickname = input.ReadString();
break;
}
case 248: {
FromFort = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| zzdragonjaizz/RocketBot | src/POGOProtos/Data/PokemonData.cs | C# | gpl-3.0 | 33,667 |
// Copyright 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 <sys/socket.h>
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "base/posix/eintr_wrapper.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "ipc/unix_domain_socket_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class SocketAcceptor : public base::MessageLoopForIO::Watcher {
public:
SocketAcceptor(int fd, base::MessageLoopProxy* target_thread)
: server_fd_(-1),
target_thread_(target_thread),
started_watching_event_(false, false),
accepted_event_(false, false) {
target_thread->PostTask(FROM_HERE,
base::Bind(&SocketAcceptor::StartWatching, base::Unretained(this), fd));
}
~SocketAcceptor() override {
Close();
}
int server_fd() const { return server_fd_; }
void WaitUntilReady() {
started_watching_event_.Wait();
}
void WaitForAccept() {
accepted_event_.Wait();
}
void Close() {
if (watcher_.get()) {
target_thread_->PostTask(FROM_HERE,
base::Bind(&SocketAcceptor::StopWatching, base::Unretained(this),
watcher_.release()));
}
}
private:
void StartWatching(int fd) {
watcher_.reset(new base::MessageLoopForIO::FileDescriptorWatcher);
base::MessageLoopForIO::current()->WatchFileDescriptor(
fd, true, base::MessageLoopForIO::WATCH_READ, watcher_.get(), this);
started_watching_event_.Signal();
}
void StopWatching(base::MessageLoopForIO::FileDescriptorWatcher* watcher) {
watcher->StopWatchingFileDescriptor();
delete watcher;
}
void OnFileCanReadWithoutBlocking(int fd) override {
ASSERT_EQ(-1, server_fd_);
IPC::ServerAcceptConnection(fd, &server_fd_);
watcher_->StopWatchingFileDescriptor();
accepted_event_.Signal();
}
void OnFileCanWriteWithoutBlocking(int fd) override {}
int server_fd_;
base::MessageLoopProxy* target_thread_;
scoped_ptr<base::MessageLoopForIO::FileDescriptorWatcher> watcher_;
base::WaitableEvent started_watching_event_;
base::WaitableEvent accepted_event_;
DISALLOW_COPY_AND_ASSIGN(SocketAcceptor);
};
const base::FilePath GetChannelDir() {
#if defined(OS_ANDROID)
base::FilePath tmp_dir;
PathService::Get(base::DIR_CACHE, &tmp_dir);
return tmp_dir;
#else
return base::FilePath("/var/tmp");
#endif
}
class TestUnixSocketConnection {
public:
TestUnixSocketConnection()
: worker_("WorkerThread"),
server_listen_fd_(-1),
server_fd_(-1),
client_fd_(-1) {
socket_name_ = GetChannelDir().Append("TestSocket");
base::Thread::Options options;
options.message_loop_type = base::MessageLoop::TYPE_IO;
worker_.StartWithOptions(options);
}
bool CreateServerSocket() {
IPC::CreateServerUnixDomainSocket(socket_name_, &server_listen_fd_);
if (server_listen_fd_ < 0)
return false;
struct stat socket_stat;
stat(socket_name_.value().c_str(), &socket_stat);
EXPECT_TRUE(S_ISSOCK(socket_stat.st_mode));
acceptor_.reset(new SocketAcceptor(server_listen_fd_,
worker_.message_loop_proxy().get()));
acceptor_->WaitUntilReady();
return true;
}
bool CreateClientSocket() {
DCHECK(server_listen_fd_ >= 0);
IPC::CreateClientUnixDomainSocket(socket_name_, &client_fd_);
if (client_fd_ < 0)
return false;
acceptor_->WaitForAccept();
server_fd_ = acceptor_->server_fd();
return server_fd_ >= 0;
}
virtual ~TestUnixSocketConnection() {
if (client_fd_ >= 0)
close(client_fd_);
if (server_fd_ >= 0)
close(server_fd_);
if (server_listen_fd_ >= 0) {
close(server_listen_fd_);
unlink(socket_name_.value().c_str());
}
}
int client_fd() const { return client_fd_; }
int server_fd() const { return server_fd_; }
private:
base::Thread worker_;
base::FilePath socket_name_;
int server_listen_fd_;
int server_fd_;
int client_fd_;
scoped_ptr<SocketAcceptor> acceptor_;
};
// Ensure that IPC::CreateServerUnixDomainSocket creates a socket that
// IPC::CreateClientUnixDomainSocket can successfully connect to.
TEST(UnixDomainSocketUtil, Connect) {
TestUnixSocketConnection connection;
ASSERT_TRUE(connection.CreateServerSocket());
ASSERT_TRUE(connection.CreateClientSocket());
}
// Ensure that messages can be sent across the resulting socket.
TEST(UnixDomainSocketUtil, SendReceive) {
TestUnixSocketConnection connection;
ASSERT_TRUE(connection.CreateServerSocket());
ASSERT_TRUE(connection.CreateClientSocket());
const char buffer[] = "Hello, server!";
size_t buf_len = sizeof(buffer);
size_t sent_bytes =
HANDLE_EINTR(send(connection.client_fd(), buffer, buf_len, 0));
ASSERT_EQ(buf_len, sent_bytes);
char recv_buf[sizeof(buffer)];
size_t received_bytes =
HANDLE_EINTR(recv(connection.server_fd(), recv_buf, buf_len, 0));
ASSERT_EQ(buf_len, received_bytes);
ASSERT_EQ(0, memcmp(recv_buf, buffer, buf_len));
}
} // namespace
| michaelforfxhelp/fxhelprepo | third_party/chromium/ipc/unix_domain_socket_util_unittest.cc | C++ | mpl-2.0 | 5,234 |
// ---------------------------------------------------------------------
//
// Copyright (C) 2004 - 2014 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// this test used to check for Vector::clear(). However, this
// function has since been removed, so we test for v=0 instead, although that
// may be covered by one of the other tests
#include "../tests.h"
#include <deal.II/lac/vector.h>
#include <fstream>
#include <iomanip>
#include <vector>
void test (Vector<std::complex<double> > &v)
{
// set some entries of the vector
for (unsigned int i=0; i<v.size(); ++i)
if (i%3 == 0)
v(i) = std::complex<double> (i+1., i+2.);
v.compress ();
// then clear it again and make sure the
// vector is really empty
const unsigned int sz = v.size();
v = 0;
Assert (v.size() == sz, ExcInternalError());
Assert (v.l2_norm() == 0, ExcInternalError());
deallog << "OK" << std::endl;
}
int main ()
{
std::ofstream logfile("output");
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
try
{
Vector<std::complex<double> > v (100);
test (v);
}
catch (std::exception &exc)
{
deallog << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
deallog << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
catch (...)
{
deallog << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
deallog << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
};
}
| johntfoster/dealii | tests/bits/complex_vector_24.cc | C++ | lgpl-2.1 | 2,443 |
/*
* Copyright 2015-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.ui.topo;
import org.junit.Test;
import org.onosproject.ui.topo.NodeBadge.Status;
import static org.junit.Assert.assertEquals;
/**
* Unit tests for {@link NodeBadge}.
*/
public class NodeBadgeTest {
private static final String MSG = "a msg";
private static final String TXT = "text";
private static final String GID = "glyph-id";
private static final int NUM = 42;
private static final String NUM_STR = Integer.toString(NUM);
private static final String WR_S = "wrong status";
private static final String WR_B = "wrong boolean";
private static final String WR_T = "wrong text";
private static final String WR_M = "wrong message";
private static final String WR_SF = "wrong string format";
private NodeBadge badge;
private void checkFields(NodeBadge b, Status s, boolean g,
String txt, String msg) {
assertEquals(WR_S, s, b.status());
assertEquals(WR_B, g, b.isGlyph());
assertEquals(WR_T, txt, b.text());
assertEquals(WR_M, msg, b.message());
}
@Test
public void badgeTypes() {
assertEquals(WR_SF, "i", Status.INFO.code());
assertEquals(WR_SF, "w", Status.WARN.code());
assertEquals(WR_SF, "e", Status.ERROR.code());
assertEquals("unexpected size", 3, Status.values().length);
}
@Test
public void textOnly() {
badge = NodeBadge.text(TXT);
checkFields(badge, Status.INFO, false, TXT, null);
}
@Test
public void glyphOnly() {
badge = NodeBadge.glyph(GID);
checkFields(badge, Status.INFO, true, GID, null);
}
@Test
public void numberOnly() {
badge = NodeBadge.number(NUM);
checkFields(badge, Status.INFO, false, NUM_STR, null);
}
@Test
public void textInfo() {
badge = NodeBadge.text(Status.INFO, TXT);
checkFields(badge, Status.INFO, false, TXT, null);
}
@Test
public void glyphWarn() {
badge = NodeBadge.glyph(Status.WARN, GID);
checkFields(badge, Status.WARN, true, GID, null);
}
@Test
public void numberError() {
badge = NodeBadge.number(Status.ERROR, NUM);
checkFields(badge, Status.ERROR, false, NUM_STR, null);
}
@Test
public void textInfoMsg() {
badge = NodeBadge.text(Status.INFO, TXT, MSG);
checkFields(badge, Status.INFO, false, TXT, MSG);
}
@Test
public void glyphWarnMsg() {
badge = NodeBadge.glyph(Status.WARN, GID, MSG);
checkFields(badge, Status.WARN, true, GID, MSG);
}
@Test
public void numberErrorMsg() {
badge = NodeBadge.number(Status.ERROR, NUM, MSG);
checkFields(badge, Status.ERROR, false, NUM_STR, MSG);
}
}
| donNewtonAlpha/onos | core/api/src/test/java/org/onosproject/ui/topo/NodeBadgeTest.java | Java | apache-2.0 | 3,410 |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.codeInsight.imports;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileSystemItem;
import com.intellij.psi.util.QualifiedName;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.python.psi.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* An immutable holder of information for one auto-import candidate.
* <p/>
* There can be do different flavors of such candidates:
* <ul>
* <li>Candidates based on existing imports in module. In this case {@link #getImportElement()} must return not {@code null}.</li>
* <li>Candidates not yet imported. In this case {@link #getPath()} must return not {@code null}.</li>
* </ul>
* <p/>
*
* @author dcheryasov
*/
// visibility is intentionally package-level
public class ImportCandidateHolder implements Comparable<ImportCandidateHolder> {
private final PsiElement myImportable;
private final PyImportElement myImportElement;
private final PsiFileSystemItem myFile;
private final QualifiedName myPath;
@Nullable private final String myAsName;
/**
* Creates new instance.
*
* @param importable an element that could be imported either from import element or from file.
* @param file the file which is the source of the importable (module for symbols, containing directory for modules and packages)
* @param importElement an existing import element that can be a source for the importable.
* @param path import path for the file, as a qualified name (a.b.c)
* For top-level imported symbols it's <em>qualified name of containing module</em> (or package for __init__.py).
* For modules and packages it should be <em>qualified name of their parental package</em>
* (empty for modules and packages located at source roots).
*
*/
public ImportCandidateHolder(@NotNull PsiElement importable, @NotNull PsiFileSystemItem file,
@Nullable PyImportElement importElement, @Nullable QualifiedName path, @Nullable String asName) {
myFile = file;
myImportable = importable;
myImportElement = importElement;
myPath = path;
myAsName = asName;
assert importElement != null || path != null; // one of these must be present
}
public ImportCandidateHolder(@NotNull PsiElement importable, @NotNull PsiFileSystemItem file,
@Nullable PyImportElement importElement, @Nullable QualifiedName path) {
this(importable, file, importElement, path, null);
}
@NotNull
public PsiElement getImportable() {
return myImportable;
}
@Nullable
public PyImportElement getImportElement() {
return myImportElement;
}
@NotNull
public PsiFileSystemItem getFile() {
return myFile;
}
@Nullable
public QualifiedName getPath() {
return myPath;
}
/**
* Helper method that builds an import path, handling all these "import foo", "import foo as bar", "from bar import foo", etc.
* Either importPath or importSource must be not null.
*
* @param name what is ultimately imported.
* @param importPath known path to import the name.
* @param source known ImportElement to import the name; its 'as' clause is used if present.
* @return a properly qualified name.
*/
@NotNull
public static String getQualifiedName(@NotNull String name, @Nullable QualifiedName importPath, @Nullable PyImportElement source) {
final StringBuilder sb = new StringBuilder();
if (source != null) {
final PsiElement parent = source.getParent();
if (parent instanceof PyFromImportStatement) {
sb.append(name);
}
else {
sb.append(source.getVisibleName()).append(".").append(name);
}
}
else {
if (importPath != null && importPath.getComponentCount() > 0) {
sb.append(importPath).append(".");
}
sb.append(name);
}
return sb.toString();
}
@NotNull
public String getPresentableText(@NotNull String myName) {
final StringBuilder sb = new StringBuilder(getQualifiedName(myName, myPath, myImportElement));
PsiElement parent = null;
if (myImportElement != null) {
parent = myImportElement.getParent();
}
if (myImportable instanceof PyFunction) {
sb.append("()");
}
else if (myImportable instanceof PyClass) {
final List<String> supers = ContainerUtil.mapNotNull(((PyClass)myImportable).getSuperClasses(null),
cls -> PyUtil.isObjectClass(cls) ? null : cls.getName());
if (!supers.isEmpty()) {
sb.append("(");
StringUtil.join(supers, ", ", sb);
sb.append(")");
}
}
if (parent instanceof PyFromImportStatement) {
sb.append(" from ");
final PyFromImportStatement fromImportStatement = (PyFromImportStatement)parent;
sb.append(StringUtil.repeat(".", fromImportStatement.getRelativeLevel()));
final PyReferenceExpression source = fromImportStatement.getImportSource();
if (source != null) {
sb.append(source.getReferencedName());
}
}
return sb.toString();
}
public int compareTo(@NotNull ImportCandidateHolder other) {
final int lRelevance = getRelevance();
final int rRelevance = other.getRelevance();
if (rRelevance != lRelevance) {
return rRelevance - lRelevance;
}
if (myPath != null && other.myPath != null) {
// prefer shorter paths
final int lengthDiff = myPath.getComponentCount() - other.myPath.getComponentCount();
if (lengthDiff != 0) {
return lengthDiff;
}
}
return Comparing.compare(myPath, other.myPath);
}
int getRelevance() {
final Project project = myImportable.getProject();
final PsiFile psiFile = myImportable.getContainingFile();
final VirtualFile vFile = psiFile == null ? null : psiFile.getVirtualFile();
if (vFile == null) return 0;
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
// files under project source are most relevant
final Module module = fileIndex.getModuleForFile(vFile);
if (module != null) return 3;
// then come files directly under Lib
if (vFile.getParent().getName().equals("Lib")) return 2;
// tests we don't want
if (vFile.getParent().getName().equals("test")) return 0;
return 1;
}
@Nullable
public String getAsName() {
return myAsName;
}
}
| ThiagoGarciaAlves/intellij-community | python/src/com/jetbrains/python/codeInsight/imports/ImportCandidateHolder.java | Java | apache-2.0 | 7,544 |
/*
* #%L
* Native ARchive plugin for Maven
* %%
* Copyright (C) 2002 - 2014 NAR Maven Plugin developers.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.maven_nar.cpptasks.types;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Path;
import com.github.maven_nar.cpptasks.CUtil;
/**
* An Ant Path object augmented with if and unless conditionals
*
* @author Curt Arnold
*/
public class ConditionalPath extends Path {
private String ifCond;
private String unlessCond;
public ConditionalPath(final Project project) {
super(project);
}
public ConditionalPath(final Project p, final String path) {
super(p, path);
}
/**
* Returns true if the Path's if and unless conditions (if any) are
* satisfied.
*/
public boolean isActive(final org.apache.tools.ant.Project p) throws BuildException {
return CUtil.isActive(p, this.ifCond, this.unlessCond);
}
/**
* Sets the property name for the 'if' condition.
*
* The path will be ignored unless the property is defined.
*
* The value of the property is insignificant, but values that would imply
* misinterpretation ("false", "no") will throw an exception when
* evaluated.
*
* @param propName
* property name
*/
public void setIf(final String propName) {
this.ifCond = propName;
}
/**
* Set the property name for the 'unless' condition.
*
* If named property is set, the path will be ignored.
*
* The value of the property is insignificant, but values that would imply
* misinterpretation ("false", "no") of the behavior will throw an
* exception when evaluated.
*
* @param propName
* name of property
*/
public void setUnless(final String propName) {
this.unlessCond = propName;
}
}
| dugilos/nar-maven-plugin | src/main/java/com/github/maven_nar/cpptasks/types/ConditionalPath.java | Java | apache-2.0 | 2,393 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.ml.dataframe.evaluation.regression;
import org.elasticsearch.client.ml.dataframe.evaluation.MlEvaluationNamedXContentProvider;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.test.AbstractXContentTestCase;
import java.io.IOException;
public class MeanSquaredErrorMetricResultTests extends AbstractXContentTestCase<MeanSquaredErrorMetric.Result> {
public static MeanSquaredErrorMetric.Result randomResult() {
return new MeanSquaredErrorMetric.Result(randomDouble());
}
@Override
protected MeanSquaredErrorMetric.Result createTestInstance() {
return randomResult();
}
@Override
protected MeanSquaredErrorMetric.Result doParseInstance(XContentParser parser) throws IOException {
return MeanSquaredErrorMetric.Result.fromXContent(parser);
}
@Override
protected boolean supportsUnknownFields() {
return true;
}
@Override
protected NamedXContentRegistry xContentRegistry() {
return new NamedXContentRegistry(new MlEvaluationNamedXContentProvider().getNamedXContentParsers());
}
}
| gingerwizard/elasticsearch | client/rest-high-level/src/test/java/org/elasticsearch/client/ml/dataframe/evaluation/regression/MeanSquaredErrorMetricResultTests.java | Java | apache-2.0 | 1,999 |
module MiqReport::Generator::Html
def build_html_rows(clickable_rows = false)
tz = get_time_zone(Time.zone.name) if Time.zone
html_rows = []
group_counter = 0
row = 0
self.rpt_options ||= {}
self.col_formats ||= [] # Backward compat - create empty array for formats
group_limit = self.rpt_options[:group_limit]
in_a_widget = self.rpt_options[:in_a_widget] || false
unless table.nil? || table.data.empty?
# Following line commented for now - for not showing repeating column values
# prev_data = String.new # Initialize the prev_data variable
hide_detail_rows = self.rpt_options.fetch_path(:summary, :hide_detail_rows) || false
row_limit = self.rpt_options && self.rpt_options[:row_limit] ? self.rpt_options[:row_limit] : 0
save_val = :_undefined_ # Hang on to the current group value
break_label = col_options.fetch_path(sortby[0], :break_label) unless sortby.nil? || col_options.nil? || in_a_widget
group_text = nil # Optionally override what gets displayed for the group (i.e. Chargeback)
use_table = sub_table ? sub_table : table
use_table.data.each_with_index do |d, d_idx|
break if row_limit != 0 && d_idx > row_limit - 1
output = ""
if ["y", "c"].include?(group) && !sortby.nil? && save_val != d.data[sortby[0]].to_s
unless d_idx == 0 # If not the first row, we are at a group break
unless group_limit && group_counter >= group_limit # If not past the limit
html_rows += build_group_html_rows(save_val, col_order.length, break_label, group_text)
group_counter += 1
end
end
save_val = d.data[sortby[0]].to_s
# Chargeback, sort by date, but show range
group_text = d.data["display_range"] if Chargeback.db_is_chargeback?(db) && sortby[0] == "start_date"
end
# Build click thru if string can be created
if clickable_rows && onclick = build_row_onclick(d.data)
output << "<tr class='row#{row}' #{onclick}>"
else
output << "<tr class='row#{row}-nocursor'>"
end
row = 1 - row
col_order.each_with_index do |c, c_idx|
build_html_col(output, c, self.col_formats[c_idx], d.data)
end
output << "</tr>"
html_rows << output unless hide_detail_rows
end
if ["y", "c"].include?(group) && !sortby.nil?
unless group_limit && group_counter >= group_limit
html_rows += build_group_html_rows(save_val, col_order.length, break_label, group_text)
html_rows += build_group_html_rows(:_total_, col_order.length)
end
end
end
html_rows
end
def build_html_col(output, col_name, col_format, row_data)
style = get_style_class(col_name, row_data, tz)
style_class = !style.nil? ? " class='#{style}'" : nil
if col_name == 'resource_type'
output << "<td#{style_class}>"
output << ui_lookup(:model => row_data[col_name]) # Lookup models in resource_type col
elsif db == 'Tenant' && TenantQuota.can_format_field?(col_name, row_data['tenant_quotas.name'])
output << "<td#{style_class} " + 'style="text-align:right">'
output << CGI.escapeHTML(TenantQuota.format_quota_value(col_name, row_data[col_name], row_data['tenant_quotas.name']))
elsif ['<compare>', '<drift>'].include?(db.to_s)
output << "<td#{style_class}>"
output << CGI.escapeHTML(row_data[col_name].to_s)
else
if row_data[col_name].kind_of?(Time)
output << "<td#{style_class} " + 'style="text-align:center">'
elsif row_data[col_name].kind_of?(Bignum) || row_data[col_name].kind_of?(Fixnum) || row_data[col_name].kind_of?(Float)
output << "<td#{style_class} " + 'style="text-align:right">'
else
output << "<td#{style_class}>"
end
output << CGI.escapeHTML(format(col_name.split("__").first, row_data[col_name],
:format => col_format || :_default_, :tz => tz))
end
output << '</td>'
end
# Depending on the model the table is based on, return the onclick string for the report row
def build_row_onclick(data_row)
onclick = nil
# Handle CI based report rows
if ['EmsCluster', 'ExtManagementSystem', 'Host', 'Storage', 'Vm', 'Service'].include?(db) && data_row['id']
controller = db == "ExtManagementSystem" ? "management_system" : db.underscore
donav = "DoNav('/#{controller}/show/#{data_row['id']}');"
title = data_row['name'] ?
"View #{ui_lookup(:model => db)} \"#{data_row['name']}\"" :
"View this #{ui_lookup(:model => db)}"
onclick = "onclick=\"#{donav}\" style='cursor:hand' title='#{title}'"
end
# Handle CI performance report rows
if db.ends_with?("Performance")
if data_row['resource_id'] && data_row['resource_type'] # Base click thru on the related resource
donav = "DoNav('/#{data_row['resource_type'].underscore}/show/#{data_row['resource_id']}');"
onclick = "onclick=\"#{donav}\" style='cursor:hand' title='View #{ui_lookup(:model => data_row['resource_type'])} \"#{data_row['resource_name']}\"'"
end
end
onclick
end
# Generate grouping rows for the passed in grouping value
def build_group_html_rows(group, col_count, label = nil, group_text = nil)
in_a_widget = self.rpt_options[:in_a_widget] || false
html_rows = []
content =
if group == :_total_
"All Rows"
else
group_label = group_text || group
group_label = "<Empty>" if group_label.blank?
"#{label}#{group_label}"
end
if (self.group == 'c') && extras && extras[:grouping] && extras[:grouping][group]
display_count = _("Count: %{number}") % {:number => extras[:grouping][group][:count]}
end
content << " | #{display_count}" unless display_count.blank?
html_rows << "<tr><td class='group' colspan='#{col_count}'>#{CGI.escapeHTML(content)}</td></tr>"
if extras && extras[:grouping] && extras[:grouping][group] # See if group key exists
MiqReport::GROUPINGS.each do |calc| # Add an output row for each group calculation
if extras[:grouping][group].key?(calc.first) # Only add a row if there are calcs of this type for this group value
grp_output = ""
grp_output << "<tr>"
grp_output << "<td#{in_a_widget ? "" : " class='group'"} style='text-align:right'>#{calc.last.pluralize}:</td>"
col_order.each_with_index do |c, c_idx| # Go through the columns
next if c_idx == 0 # Skip first column
grp_output << "<td#{in_a_widget ? "" : " class='group'"} style='text-align:right'>"
grp_output << CGI.escapeHTML(
format(
c.split("__").first, extras[:grouping][group][calc.first][c],
:format => self.col_formats[c_idx] ? self.col_formats[c_idx] : :_default_
)
) if extras[:grouping][group].key?(calc.first)
grp_output << "</td>"
end
grp_output << "</tr>"
html_rows << grp_output
end
end
end
html_rows << "<tr><td class='group_spacer' colspan='#{col_count}'> </td></tr>" unless group == :_total_
html_rows
end
def get_style_class(col, row, tz = nil)
atoms = col_options.fetch_path(col, :style) unless col_options.nil?
return if atoms.nil?
nh = {}; row.each { |k, v| nh[col_to_expression_col(k).sub(/-/, ".")] = v } # Convert keys to match expression fields
field = col_to_expression_col(col)
atoms.each do |atom|
return atom[:class] if atom[:operator].downcase == "default"
exp = expression_for_style_class(field, atom)
return atom[:class] if exp.evaluate(nh, tz)
end
nil
end
def expression_for_style_class(field, atom)
@expression_for_style_class ||= {}
@expression_for_style_class[field] ||= {}
value = atom[:value]
value = [value, atom[:value_suffix]].join(".").to_f_with_method if atom[:value_suffix] && value.to_f.respond_to?(atom[:value_suffix])
@expression_for_style_class[field][atom] ||= MiqExpression.new({atom[:operator] => {"field" => field, "value" => value}}, "hash")
end
end
| mfeifer/manageiq | app/models/miq_report/generator/html.rb | Ruby | apache-2.0 | 8,450 |
/**
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
*/
package com.typesafe.config.impl;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import com.typesafe.config.*;
final class ConfigParser {
static AbstractConfigValue parse(ConfigNodeRoot document,
ConfigOrigin origin, ConfigParseOptions options,
ConfigIncludeContext includeContext) {
ParseContext context = new ParseContext(options.getSyntax(), origin, document,
SimpleIncluder.makeFull(options.getIncluder()), includeContext);
return context.parse();
}
static private final class ParseContext {
private int lineNumber;
final private ConfigNodeRoot document;
final private FullIncluder includer;
final private ConfigIncludeContext includeContext;
final private ConfigSyntax flavor;
final private ConfigOrigin baseOrigin;
final private LinkedList<Path> pathStack;
// the number of lists we are inside; this is used to detect the "cannot
// generate a reference to a list element" problem, and once we fix that
// problem we should be able to get rid of this variable.
int arrayCount;
ParseContext(ConfigSyntax flavor, ConfigOrigin origin, ConfigNodeRoot document,
FullIncluder includer, ConfigIncludeContext includeContext) {
lineNumber = 1;
this.document = document;
this.flavor = flavor;
this.baseOrigin = origin;
this.includer = includer;
this.includeContext = includeContext;
this.pathStack = new LinkedList<Path>();
this.arrayCount = 0;
}
// merge a bunch of adjacent values into one
// value; change unquoted text into a string
// value.
private AbstractConfigValue parseConcatenation(ConfigNodeConcatenation n) {
// this trick is not done in JSON
if (flavor == ConfigSyntax.JSON)
throw new ConfigException.BugOrBroken("Found a concatenation node in JSON");
List<AbstractConfigValue> values = new ArrayList<AbstractConfigValue>();
for (AbstractConfigNode node : n.children()) {
AbstractConfigValue v = null;
if (node instanceof AbstractConfigNodeValue) {
v = parseValue((AbstractConfigNodeValue)node, null);
values.add(v);
}
}
return ConfigConcatenation.concatenate(values);
}
private SimpleConfigOrigin lineOrigin() {
return ((SimpleConfigOrigin) baseOrigin).withLineNumber(lineNumber);
}
private ConfigException parseError(String message) {
return parseError(message, null);
}
private ConfigException parseError(String message, Throwable cause) {
return new ConfigException.Parse(lineOrigin(), message, cause);
}
private Path fullCurrentPath() {
// pathStack has top of stack at front
if (pathStack.isEmpty())
throw new ConfigException.BugOrBroken("Bug in parser; tried to get current path when at root");
else
return new Path(pathStack.descendingIterator());
}
private AbstractConfigValue parseValue(AbstractConfigNodeValue n, List<String> comments) {
AbstractConfigValue v;
int startingArrayCount = arrayCount;
if (n instanceof ConfigNodeSimpleValue) {
v = ((ConfigNodeSimpleValue) n).value();
} else if (n instanceof ConfigNodeObject) {
v = parseObject((ConfigNodeObject)n);
} else if (n instanceof ConfigNodeArray) {
v = parseArray((ConfigNodeArray)n);
} else if (n instanceof ConfigNodeConcatenation) {
v = parseConcatenation((ConfigNodeConcatenation)n);
} else {
throw parseError("Expecting a value but got wrong node type: " + n.getClass());
}
if (comments != null && !comments.isEmpty()) {
v = v.withOrigin(v.origin().prependComments(new ArrayList<String>(comments)));
comments.clear();
}
if (arrayCount != startingArrayCount)
throw new ConfigException.BugOrBroken("Bug in config parser: unbalanced array count");
return v;
}
private static AbstractConfigObject createValueUnderPath(Path path,
AbstractConfigValue value) {
// for path foo.bar, we are creating
// { "foo" : { "bar" : value } }
List<String> keys = new ArrayList<String>();
String key = path.first();
Path remaining = path.remainder();
while (key != null) {
keys.add(key);
if (remaining == null) {
break;
} else {
key = remaining.first();
remaining = remaining.remainder();
}
}
// the withComments(null) is to ensure comments are only
// on the exact leaf node they apply to.
// a comment before "foo.bar" applies to the full setting
// "foo.bar" not also to "foo"
ListIterator<String> i = keys.listIterator(keys.size());
String deepest = i.previous();
AbstractConfigObject o = new SimpleConfigObject(value.origin().withComments(null),
Collections.<String, AbstractConfigValue> singletonMap(
deepest, value));
while (i.hasPrevious()) {
Map<String, AbstractConfigValue> m = Collections.<String, AbstractConfigValue> singletonMap(
i.previous(), o);
o = new SimpleConfigObject(value.origin().withComments(null), m);
}
return o;
}
private void parseInclude(Map<String, AbstractConfigValue> values, ConfigNodeInclude n) {
AbstractConfigObject obj;
switch (n.kind()) {
case URL:
URL url;
try {
url = new URL(n.name());
} catch (MalformedURLException e) {
throw parseError("include url() specifies an invalid URL: " + n.name(), e);
}
obj = (AbstractConfigObject) includer.includeURL(includeContext, url);
break;
case FILE:
obj = (AbstractConfigObject) includer.includeFile(includeContext,
new File(n.name()));
break;
case CLASSPATH:
obj = (AbstractConfigObject) includer.includeResources(includeContext, n.name());
break;
case HEURISTIC:
obj = (AbstractConfigObject) includer
.include(includeContext, n.name());
break;
default:
throw new ConfigException.BugOrBroken("should not be reached");
}
// we really should make this work, but for now throwing an
// exception is better than producing an incorrect result.
// See https://github.com/typesafehub/config/issues/160
if (arrayCount > 0 && obj.resolveStatus() != ResolveStatus.RESOLVED)
throw parseError("Due to current limitations of the config parser, when an include statement is nested inside a list value, "
+ "${} substitutions inside the included file cannot be resolved correctly. Either move the include outside of the list value or "
+ "remove the ${} statements from the included file.");
if (!pathStack.isEmpty()) {
Path prefix = fullCurrentPath();
obj = obj.relativized(prefix);
}
for (String key : obj.keySet()) {
AbstractConfigValue v = obj.get(key);
AbstractConfigValue existing = values.get(key);
if (existing != null) {
values.put(key, v.withFallback(existing));
} else {
values.put(key, v);
}
}
}
private AbstractConfigObject parseObject(ConfigNodeObject n) {
Map<String, AbstractConfigValue> values = new HashMap<String, AbstractConfigValue>();
SimpleConfigOrigin objectOrigin = lineOrigin();
boolean lastWasNewline = false;
ArrayList<AbstractConfigNode> nodes = new ArrayList<AbstractConfigNode>(n.children());
List<String> comments = new ArrayList<String>();
for (int i = 0; i < nodes.size(); i++) {
AbstractConfigNode node = nodes.get(i);
if (node instanceof ConfigNodeComment) {
lastWasNewline = false;
comments.add(((ConfigNodeComment) node).commentText());
} else if (node instanceof ConfigNodeSingleToken && Tokens.isNewline(((ConfigNodeSingleToken) node).token())) {
lineNumber++;
if (lastWasNewline) {
// Drop all comments if there was a blank line and start a new comment block
comments.clear();
}
lastWasNewline = true;
} else if (flavor != ConfigSyntax.JSON && node instanceof ConfigNodeInclude) {
parseInclude(values, (ConfigNodeInclude)node);
lastWasNewline = false;
} else if (node instanceof ConfigNodeField) {
lastWasNewline = false;
Path path = ((ConfigNodeField) node).path().value();
comments.addAll(((ConfigNodeField) node).comments());
// path must be on-stack while we parse the value
pathStack.push(path);
if (((ConfigNodeField) node).separator() == Tokens.PLUS_EQUALS) {
// we really should make this work, but for now throwing
// an exception is better than producing an incorrect
// result. See
// https://github.com/typesafehub/config/issues/160
if (arrayCount > 0)
throw parseError("Due to current limitations of the config parser, += does not work nested inside a list. "
+ "+= expands to a ${} substitution and the path in ${} cannot currently refer to list elements. "
+ "You might be able to move the += outside of the list and then refer to it from inside the list with ${}.");
// because we will put it in an array after the fact so
// we want this to be incremented during the parseValue
// below in order to throw the above exception.
arrayCount += 1;
}
AbstractConfigNodeValue valueNode;
AbstractConfigValue newValue;
valueNode = ((ConfigNodeField) node).value();
// comments from the key token go to the value token
newValue = parseValue(valueNode, comments);
if (((ConfigNodeField) node).separator() == Tokens.PLUS_EQUALS) {
arrayCount -= 1;
List<AbstractConfigValue> concat = new ArrayList<AbstractConfigValue>(2);
AbstractConfigValue previousRef = new ConfigReference(newValue.origin(),
new SubstitutionExpression(fullCurrentPath(), true /* optional */));
AbstractConfigValue list = new SimpleConfigList(newValue.origin(),
Collections.singletonList(newValue));
concat.add(previousRef);
concat.add(list);
newValue = ConfigConcatenation.concatenate(concat);
}
// Grab any trailing comments on the same line
if (i < nodes.size() - 1) {
i++;
while (i < nodes.size()) {
if (nodes.get(i) instanceof ConfigNodeComment) {
ConfigNodeComment comment = (ConfigNodeComment) nodes.get(i);
newValue = newValue.withOrigin(newValue.origin().appendComments(
Collections.singletonList(comment.commentText())));
break;
} else if (nodes.get(i) instanceof ConfigNodeSingleToken) {
ConfigNodeSingleToken curr = (ConfigNodeSingleToken) nodes.get(i);
if (curr.token() == Tokens.COMMA || Tokens.isIgnoredWhitespace(curr.token())) {
// keep searching, as there could still be a comment
} else {
i--;
break;
}
} else {
i--;
break;
}
i++;
}
}
pathStack.pop();
String key = path.first();
Path remaining = path.remainder();
if (remaining == null) {
AbstractConfigValue existing = values.get(key);
if (existing != null) {
// In strict JSON, dups should be an error; while in
// our custom config language, they should be merged
// if the value is an object (or substitution that
// could become an object).
if (flavor == ConfigSyntax.JSON) {
throw parseError("JSON does not allow duplicate fields: '"
+ key
+ "' was already seen at "
+ existing.origin().description());
} else {
newValue = newValue.withFallback(existing);
}
}
values.put(key, newValue);
} else {
if (flavor == ConfigSyntax.JSON) {
throw new ConfigException.BugOrBroken(
"somehow got multi-element path in JSON mode");
}
AbstractConfigObject obj = createValueUnderPath(
remaining, newValue);
AbstractConfigValue existing = values.get(key);
if (existing != null) {
obj = obj.withFallback(existing);
}
values.put(key, obj);
}
}
}
return new SimpleConfigObject(objectOrigin, values);
}
private SimpleConfigList parseArray(ConfigNodeArray n) {
arrayCount += 1;
SimpleConfigOrigin arrayOrigin = lineOrigin();
List<AbstractConfigValue> values = new ArrayList<AbstractConfigValue>();
boolean lastWasNewLine = false;
List<String> comments = new ArrayList<String>();
AbstractConfigValue v = null;
for (AbstractConfigNode node : n.children()) {
if (node instanceof ConfigNodeComment) {
comments.add(((ConfigNodeComment) node).commentText());
lastWasNewLine = false;
} else if (node instanceof ConfigNodeSingleToken && Tokens.isNewline(((ConfigNodeSingleToken) node).token())) {
lineNumber++;
if (lastWasNewLine && v == null) {
comments.clear();
} else if (v != null) {
values.add(v.withOrigin(v.origin().appendComments(new ArrayList<String>(comments))));
comments.clear();
v = null;
}
lastWasNewLine = true;
} else if (node instanceof AbstractConfigNodeValue) {
lastWasNewLine = false;
if (v != null) {
values.add(v.withOrigin(v.origin().appendComments(new ArrayList<String>(comments))));
comments.clear();
}
v = parseValue((AbstractConfigNodeValue)node, comments);
}
}
// There shouldn't be any comments at this point, but add them just in case
if (v != null) {
values.add(v.withOrigin(v.origin().appendComments(new ArrayList<String>(comments))));
}
arrayCount -= 1;
return new SimpleConfigList(arrayOrigin, values);
}
AbstractConfigValue parse() {
AbstractConfigValue result = null;
ArrayList<String> comments = new ArrayList<String>();
boolean lastWasNewLine = false;
for (AbstractConfigNode node : document.children()) {
if (node instanceof ConfigNodeComment) {
comments.add(((ConfigNodeComment) node).commentText());
lastWasNewLine = false;
} else if (node instanceof ConfigNodeSingleToken) {
Token t = ((ConfigNodeSingleToken) node).token();
if (Tokens.isNewline(t)) {
lineNumber++;
if (lastWasNewLine && result == null) {
comments.clear();
} else if (result != null) {
result = result.withOrigin(result.origin().appendComments(new ArrayList<String>(comments)));
comments.clear();
break;
}
lastWasNewLine = true;
}
} else if (node instanceof ConfigNodeComplexValue) {
result = parseValue((ConfigNodeComplexValue)node, comments);
lastWasNewLine = false;
}
}
return result;
}
}
}
| fpringvaldsen/config | config/src/main/java/com/typesafe/config/impl/ConfigParser.java | Java | apache-2.0 | 19,298 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 4.3.2 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2010, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* System Front Controller
*
* Loads the base classes and executes the request.
*
* @package CodeIgniter
* @subpackage codeigniter
* @category Front-controller
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/
*/
// CI Version
define('CI_VERSION', '1.7.3');
/*
* ------------------------------------------------------
* Load the global functions
* ------------------------------------------------------
*/
require(BASEPATH.'codeigniter/Common'.EXT);
/*
* ------------------------------------------------------
* Load the compatibility override functions
* ------------------------------------------------------
*/
require(BASEPATH.'codeigniter/Compat'.EXT);
/*
* ------------------------------------------------------
* Load the framework constants
* ------------------------------------------------------
*/
require(APPPATH.'config/constants'.EXT);
/*
* ------------------------------------------------------
* Define a custom error handler so we can log PHP errors
* ------------------------------------------------------
*/
set_error_handler('_exception_handler');
if ( ! is_php('5.3'))
{
@set_magic_quotes_runtime(0); // Kill magic quotes
}
/*
* ------------------------------------------------------
* Start the timer... tick tock tick tock...
* ------------------------------------------------------
*/
$BM =& load_class('Benchmark');
$BM->mark('total_execution_time_start');
$BM->mark('loading_time_base_classes_start');
/*
* ------------------------------------------------------
* Instantiate the hooks class
* ------------------------------------------------------
*/
$EXT =& load_class('Hooks');
/*
* ------------------------------------------------------
* Is there a "pre_system" hook?
* ------------------------------------------------------
*/
$EXT->_call_hook('pre_system');
/*
* ------------------------------------------------------
* Instantiate the base classes
* ------------------------------------------------------
*/
$CFG =& load_class('Config');
$URI =& load_class('URI');
$RTR =& load_class('Router');
$OUT =& load_class('Output');
/*
* ------------------------------------------------------
* Is there a valid cache file? If so, we're done...
* ------------------------------------------------------
*/
if ($EXT->_call_hook('cache_override') === FALSE)
{
if ($OUT->_display_cache($CFG, $URI) == TRUE)
{
exit;
}
}
/*
* ------------------------------------------------------
* Load the remaining base classes
* ------------------------------------------------------
*/
$IN =& load_class('Input');
$LANG =& load_class('Language');
/*
* ------------------------------------------------------
* Load the app controller and local controller
* ------------------------------------------------------
*
* Note: Due to the poor object handling in PHP 4 we'll
* conditionally load different versions of the base
* class. Retaining PHP 4 compatibility requires a bit of a hack.
*
* Note: The Loader class needs to be included first
*
*/
if ( ! is_php('5.0.0'))
{
load_class('Loader', FALSE);
require(BASEPATH.'codeigniter/Base4'.EXT);
}
else
{
require(BASEPATH.'codeigniter/Base5'.EXT);
}
// Load the base controller class
load_class('Controller', FALSE);
// Load the local application controller
// Note: The Router class automatically validates the controller path. If this include fails it
// means that the default controller in the Routes.php file is not resolving to something valid.
if ( ! file_exists(APPPATH.'controllers/'.$RTR->fetch_directory().$RTR->fetch_class().EXT))
{
show_error('Unable to load your default controller. Please make sure the controller specified in your Routes.php file is valid.');
}
include(APPPATH.'controllers/'.$RTR->fetch_directory().$RTR->fetch_class().EXT);
// Set a mark point for benchmarking
$BM->mark('loading_time_base_classes_end');
/*
* ------------------------------------------------------
* Security check
* ------------------------------------------------------
*
* None of the functions in the app controller or the
* loader class can be called via the URI, nor can
* controller functions that begin with an underscore
*/
$class = $RTR->fetch_class();
$method = $RTR->fetch_method();
if ( ! class_exists($class)
OR $method == 'controller'
OR strncmp($method, '_', 1) == 0
OR in_array(strtolower($method), array_map('strtolower', get_class_methods('Controller')))
)
{
show_404("{$class}/{$method}");
}
/*
* ------------------------------------------------------
* Is there a "pre_controller" hook?
* ------------------------------------------------------
*/
$EXT->_call_hook('pre_controller');
/*
* ------------------------------------------------------
* Instantiate the controller and call requested method
* ------------------------------------------------------
*/
// Mark a start point so we can benchmark the controller
$BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start');
$CI = new $class();
// Is this a scaffolding request?
if ($RTR->scaffolding_request === TRUE)
{
if ($EXT->_call_hook('scaffolding_override') === FALSE)
{
$CI->_ci_scaffolding();
}
}
else
{
/*
* ------------------------------------------------------
* Is there a "post_controller_constructor" hook?
* ------------------------------------------------------
*/
$EXT->_call_hook('post_controller_constructor');
// Is there a "remap" function?
if (method_exists($CI, '_remap'))
{
$CI->_remap($method);
}
else
{
// is_callable() returns TRUE on some versions of PHP 5 for private and protected
// methods, so we'll use this workaround for consistent behavior
if ( ! in_array(strtolower($method), array_map('strtolower', get_class_methods($CI))))
{
show_404("{$class}/{$method}");
}
// Call the requested method.
// Any URI segments present (besides the class/function) will be passed to the method for convenience
call_user_func_array(array(&$CI, $method), array_slice($URI->rsegments, 2));
}
}
// Mark a benchmark end point
$BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end');
/*
* ------------------------------------------------------
* Is there a "post_controller" hook?
* ------------------------------------------------------
*/
$EXT->_call_hook('post_controller');
/*
* ------------------------------------------------------
* Send the final rendered output to the browser
* ------------------------------------------------------
*/
if ($EXT->_call_hook('display_override') === FALSE)
{
$OUT->_display();
}
/*
* ------------------------------------------------------
* Is there a "post_system" hook?
* ------------------------------------------------------
*/
$EXT->_call_hook('post_system');
/*
* ------------------------------------------------------
* Close the DB connection if one exists
* ------------------------------------------------------
*/
if (class_exists('CI_DB') AND isset($CI->db))
{
$CI->db->close();
}
/* End of file CodeIgniter.php */
/* Location: ./system/codeigniter/CodeIgniter.php */ | prashants/webzash-v1-defunct | system/codeigniter/CodeIgniter.php | PHP | apache-2.0 | 7,665 |
// Copyright 2015 the V8 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.
// Flags: --allow-natives-syntax --harmony-do-expressions
function f(x) {
switch (x) {
case 1: return "one";
case 2: return "two";
case do { for (var i = 0; i < 10; i++) { if (i == 5) %OptimizeOsr(); } }:
case 3: return "WAT";
}
}
assertEquals("one", f(1));
assertEquals("two", f(2));
assertEquals("WAT", f(3));
| macchina-io/macchina.io | platform/JS/V8/v8/test/mjsunit/regress/regress-osr-in-case-label.js | JavaScript | apache-2.0 | 502 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.language;
import java.net.URLEncoder;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;
public class LanguageScriptInHeaderRouteTakePrecedenceTest extends ContextTestSupport {
@Test
public void testLanguageWithHeader() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
template.sendBodyAndHeader("direct:start", "World", Exchange.LANGUAGE_SCRIPT, "Hello ${body}");
assertMockEndpointsSatisfied();
}
@Test
public void testLanguageNoHeader() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("Bye World");
template.sendBody("direct:start", "World");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
String script = URLEncoder.encode("Bye ${body}", "UTF-8");
from("direct:start").to("language:simple:" + script).to("mock:result");
}
};
}
}
| tdiesler/camel | core/camel-core/src/test/java/org/apache/camel/component/language/LanguageScriptInHeaderRouteTakePrecedenceTest.java | Java | apache-2.0 | 2,063 |
/*******************************************************************************
* Copyright (c) 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Zend Technologies
*******************************************************************************/
package org.eclipse.php.internal.core.preferences;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* A base class for all the preferences propagators.
*
* @author shalom
*/
public abstract class AbstractPreferencesPropagator {
protected HashMap listenersMap;
protected boolean isInstalled;
protected Object lock = new Object();
/**
* Constructs an AbstractPreferencesPropagator.
*/
public AbstractPreferencesPropagator() {
}
/**
* Adds an IPreferencesPropagatorListener with a preferences key to listen
* to.
*
* @param listener
* An IPreferencesPropagatorListener.
* @param preferencesKey
* The preferences key that will screen the relevant changes.
*/
public void addPropagatorListener(IPreferencesPropagatorListener listener,
String preferencesKey) {
List list = (List) listenersMap.get(preferencesKey);
if (list == null) {
list = new ArrayList(5);
listenersMap.put(preferencesKey, list);
}
if (!list.contains(listener)) {
list.add(listener);
}
}
/**
* Removes an IPreferencesPropagatorListener that was assigned to listen to
* the given preferences key.
*
* @param listener
* An IPreferencesPropagatorListener.
* @param preferencesKey
* The preferences key that is the screening key for the
* IPreferencesPropagatorListener.
*/
public void removePropagatorListener(
IPreferencesPropagatorListener listener, String preferencesKey) {
List list = (List) listenersMap.get(preferencesKey);
if (list != null) {
list.remove(listener);
}
}
/**
* Sets a list of listeners for the given preferences key. This list will
* replace any previous list of listeners for the key.
*
* @param listeners
* A List of listeners.
* @param preferencesKey
* The preferences key that will screen the relevant changes.
*/
public void setPropagatorListeners(List listeners, String preferencesKey) {
listenersMap.put(preferencesKey, listeners);
}
/**
* Returns the list of listeners assigned to the preferences key, or null if
* non exists.
*
* @param preferencesKey
* The key that the listeners listen to.
* @return The list of listeners assigned for the key, or null if non
* exists.
*/
protected List getPropagatorListeners(String preferencesKey) {
synchronized (lock) {
return (List) listenersMap.get(preferencesKey);
}
}
/**
* Install the preferences propagator.
*/
protected synchronized void install() {
if (isInstalled) {
return;
}
listenersMap = new HashMap();
isInstalled = true;
}
/**
* Uninstall the preferences propagator.
*/
protected synchronized void uninstall() {
if (!isInstalled) {
return;
}
listenersMap = null;
isInstalled = false;
}
}
| nwnpallewela/developer-studio | jaggery/plugins/org.eclipse.php.core/src/org/eclipse/php/internal/core/preferences/AbstractPreferencesPropagator.java | Java | apache-2.0 | 3,408 |
/*
* Copyright 2009-2010 WSO2, Inc. (http://wso2.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.eclipse.ds.presentation.custom;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider;
import org.eclipse.ui.views.properties.IPropertySource;
/**
* Custom {@link AdapterFactoryContentProvider} class.
*/
public class CustomAdapterFactoryContentProvider extends AdapterFactoryContentProvider {
/**
* Creates a new {@link CustomAdapterFactoryContentProvider} instance.
*
* @param factory
* {@link AdapterFactory} instance.
*/
public CustomAdapterFactoryContentProvider(AdapterFactory factory) {
super(factory);
}
/**
* {@inheritDoc}
*/
protected IPropertySource createPropertySource(Object object,
IItemPropertySource itemPropertySource) {
return new CustomPropertySource(object, itemPropertySource);
}
}
| nwnpallewela/developer-studio | data-services/plugins/org.wso2.developerstudio.eclipse.ds.editor/src/org/wso2/developerstudio/eclipse/ds/presentation/custom/CustomAdapterFactoryContentProvider.java | Java | apache-2.0 | 1,569 |
/*
* Copyright 2016-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.cpman.cli;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.apache.karaf.shell.console.completer.ArgumentCompleter;
import org.apache.karaf.shell.console.completer.StringsCompleter;
import org.onosproject.cli.AbstractCompleter;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.cluster.NodeId;
import org.onosproject.cpman.ControlPlaneMonitorService;
import org.onosproject.cpman.ControlResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
/**
* Resource name completer.
*/
public class ResourceNameCompleter extends AbstractCompleter {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final String NETWORK = "network";
private static final String DISK = "disk";
private static final String CONTROL_MESSAGE = "control_message";
private final Set<String> resourceTypes = ImmutableSet.of(NETWORK, DISK, CONTROL_MESSAGE);
private static final String INVALID_MSG = "Invalid type name";
@Override
public int complete(String buffer, int cursor, List<String> candidates) {
// delegate string completer
StringsCompleter delegate = new StringsCompleter();
// Resource type is the second argument.
ArgumentCompleter.ArgumentList list = getArgumentList();
String nodeId = list.getArguments()[1];
String type = list.getArguments()[2];
if (resourceTypes.contains(type)) {
ControlPlaneMonitorService monitorService =
AbstractShellCommand.get(ControlPlaneMonitorService.class);
Set<String> set = Sets.newHashSet();
switch (type) {
case NETWORK:
set = monitorService.availableResourcesSync(NodeId.nodeId(nodeId),
ControlResource.Type.NETWORK);
break;
case DISK:
set = monitorService.availableResourcesSync(NodeId.nodeId(nodeId),
ControlResource.Type.DISK);
break;
case CONTROL_MESSAGE:
set = monitorService.availableResourcesSync(NodeId.nodeId(nodeId),
ControlResource.Type.CONTROL_MESSAGE);
break;
default:
log.warn(INVALID_MSG);
break;
}
SortedSet<String> strings = delegate.getStrings();
if (!set.isEmpty()) {
set.forEach(strings::add);
}
}
return delegate.complete(buffer, cursor, candidates);
}
}
| donNewtonAlpha/onos | apps/cpman/app/src/main/java/org/onosproject/cpman/cli/ResourceNameCompleter.java | Java | apache-2.0 | 3,366 |
/*
* Copyright 2014-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.net.provider;
/**
* Base provider implementation.
*/
public abstract class AbstractProvider implements Provider {
private final ProviderId providerId;
/**
* Creates a provider with the supplied identifier.
*
* @param id provider id
*/
protected AbstractProvider(ProviderId id) {
this.providerId = id;
}
@Override
public ProviderId id() {
return providerId;
}
}
| donNewtonAlpha/onos | core/api/src/main/java/org/onosproject/net/provider/AbstractProvider.java | Java | apache-2.0 | 1,074 |
package com.thinkaurelius.titan.graphdb.types.system;
import com.thinkaurelius.titan.graphdb.internal.InternalVertexLabel;
import org.apache.tinkerpop.gremlin.structure.Vertex;
/**
* @author Matthias Broecheler (me@matthiasb.com)
*/
public class BaseVertexLabel extends EmptyVertex implements InternalVertexLabel {
public static final BaseVertexLabel DEFAULT_VERTEXLABEL = new BaseVertexLabel(Vertex.DEFAULT_LABEL);
private final String name;
public BaseVertexLabel(String name) {
this.name = name;
}
@Override
public boolean isPartitioned() {
return false;
}
@Override
public boolean isStatic() {
return false;
}
@Override
public String name() {
return name;
}
@Override
public boolean hasDefaultConfiguration() {
return true;
}
@Override
public int getTTL() {
return 0;
}
@Override
public String toString() {
return name();
}
}
| CYPP/titan | titan-core/src/main/java/com/thinkaurelius/titan/graphdb/types/system/BaseVertexLabel.java | Java | apache-2.0 | 987 |
/*1*/ try /*2*/ { /*3*/
/*4*/ throw /*5*/ "no" /*6*/;
/*7*/} /*8*/ catch /*9*/ ( /*10*/ e /*11*/ ) /*12*/ { /*13*/
/*14*/} /*15*/ finally /*16*/ { /*17*/
/*18*/} /*19*/ | basarat/TypeScript | tests/cases/compiler/tryStatementInternalComments.ts | TypeScript | apache-2.0 | 180 |
package com.vaadin.tests.components.grid;
import java.util.ArrayList;
import java.util.List;
import com.vaadin.data.ValueProvider;
import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.components.AbstractTestUIWithLog;
import com.vaadin.ui.Button;
import com.vaadin.ui.Grid;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
public class MoveGridAndAddRow extends AbstractTestUIWithLog {
@Override
protected void setup(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
final VerticalLayout anotherLayout = new VerticalLayout();
anotherLayout.addComponent(new Label("This is another layout"));
final Grid<String> grid = new Grid<>();
grid.addColumn(ValueProvider.identity()).setCaption("A");
List<String> items = new ArrayList<>();
items.add("1");
grid.setItems(items);
final Button button = new Button("Add row and remove this button");
button.setId("add");
button.addClickListener(event -> {
items.add("2");
grid.setItems(items);
button.setVisible(false);
});
Button move = new Button("Move grid to other layout");
move.setId("move");
move.addClickListener(event -> anotherLayout.addComponent(grid));
layout.addComponents(button, move, grid);
addComponent(new HorizontalLayout(layout, anotherLayout));
}
}
| Darsstar/framework | uitest/src/main/java/com/vaadin/tests/components/grid/MoveGridAndAddRow.java | Java | apache-2.0 | 1,491 |
<?php
/**
* Tests for MediaWiki api.php?action=edit.
*
* @author Daniel Kinzler
*
* @group API
* @group Database
* @group medium
*/
class ApiEditPageTest extends ApiTestCase {
public function setUp() {
global $wgExtraNamespaces, $wgNamespaceContentModels, $wgContentHandlers, $wgContLang;
parent::setUp();
$wgExtraNamespaces[12312] = 'Dummy';
$wgExtraNamespaces[12313] = 'Dummy_talk';
$wgNamespaceContentModels[12312] = "testing";
$wgContentHandlers["testing"] = 'DummyContentHandlerForTesting';
MWNamespace::getCanonicalNamespaces( true ); # reset namespace cache
$wgContLang->resetNamespaces(); # reset namespace cache
$this->doLogin();
}
public function tearDown() {
global $wgExtraNamespaces, $wgNamespaceContentModels, $wgContentHandlers, $wgContLang;
unset( $wgExtraNamespaces[12312] );
unset( $wgExtraNamespaces[12313] );
unset( $wgNamespaceContentModels[12312] );
unset( $wgContentHandlers["testing"] );
MWNamespace::getCanonicalNamespaces( true ); # reset namespace cache
$wgContLang->resetNamespaces(); # reset namespace cache
parent::tearDown();
}
public function testEdit() {
$name = 'Help:ApiEditPageTest_testEdit'; // assume Help namespace to default to wikitext
// -- test new page --------------------------------------------
$apiResult = $this->doApiRequestWithToken( array(
'action' => 'edit',
'title' => $name,
'text' => 'some text',
) );
$apiResult = $apiResult[0];
// Validate API result data
$this->assertArrayHasKey( 'edit', $apiResult );
$this->assertArrayHasKey( 'result', $apiResult['edit'] );
$this->assertEquals( 'Success', $apiResult['edit']['result'] );
$this->assertArrayHasKey( 'new', $apiResult['edit'] );
$this->assertArrayNotHasKey( 'nochange', $apiResult['edit'] );
$this->assertArrayHasKey( 'pageid', $apiResult['edit'] );
// -- test existing page, no change ----------------------------
$data = $this->doApiRequestWithToken( array(
'action' => 'edit',
'title' => $name,
'text' => 'some text',
) );
$this->assertEquals( 'Success', $data[0]['edit']['result'] );
$this->assertArrayNotHasKey( 'new', $data[0]['edit'] );
$this->assertArrayHasKey( 'nochange', $data[0]['edit'] );
// -- test existing page, with change --------------------------
$data = $this->doApiRequestWithToken( array(
'action' => 'edit',
'title' => $name,
'text' => 'different text'
) );
$this->assertEquals( 'Success', $data[0]['edit']['result'] );
$this->assertArrayNotHasKey( 'new', $data[0]['edit'] );
$this->assertArrayNotHasKey( 'nochange', $data[0]['edit'] );
$this->assertArrayHasKey( 'oldrevid', $data[0]['edit'] );
$this->assertArrayHasKey( 'newrevid', $data[0]['edit'] );
$this->assertNotEquals(
$data[0]['edit']['newrevid'],
$data[0]['edit']['oldrevid'],
"revision id should change after edit"
);
}
public function testNonTextEdit() {
$name = 'Dummy:ApiEditPageTest_testNonTextEdit';
$data = serialize( 'some bla bla text' );
// -- test new page --------------------------------------------
$apiResult = $this->doApiRequestWithToken( array(
'action' => 'edit',
'title' => $name,
'text' => $data, ) );
$apiResult = $apiResult[0];
// Validate API result data
$this->assertArrayHasKey( 'edit', $apiResult );
$this->assertArrayHasKey( 'result', $apiResult['edit'] );
$this->assertEquals( 'Success', $apiResult['edit']['result'] );
$this->assertArrayHasKey( 'new', $apiResult['edit'] );
$this->assertArrayNotHasKey( 'nochange', $apiResult['edit'] );
$this->assertArrayHasKey( 'pageid', $apiResult['edit'] );
// validate resulting revision
$page = WikiPage::factory( Title::newFromText( $name ) );
$this->assertEquals( "testing", $page->getContentModel() );
$this->assertEquals( $data, $page->getContent()->serialize() );
}
public static function provideEditAppend() {
return array(
array( #0: append
'foo', 'append', 'bar', "foobar"
),
array( #1: prepend
'foo', 'prepend', 'bar', "barfoo"
),
array( #2: append to empty page
'', 'append', 'foo', "foo"
),
array( #3: prepend to empty page
'', 'prepend', 'foo', "foo"
),
array( #4: append to non-existing page
null, 'append', 'foo', "foo"
),
array( #5: prepend to non-existing page
null, 'prepend', 'foo', "foo"
),
);
}
/**
* @dataProvider provideEditAppend
*/
public function testEditAppend( $text, $op, $append, $expected ) {
static $count = 0;
$count++;
// assume NS_HELP defaults to wikitext
$name = "Help:ApiEditPageTest_testEditAppend_$count";
// -- create page (or not) -----------------------------------------
if ( $text !== null ) {
if ( $text === '' ) {
// can't create an empty page, so create it with some content
$this->doApiRequestWithToken( array(
'action' => 'edit',
'title' => $name,
'text' => '(dummy)', ) );
}
list( $re ) = $this->doApiRequestWithToken( array(
'action' => 'edit',
'title' => $name,
'text' => $text, ) );
$this->assertEquals( 'Success', $re['edit']['result'] ); // sanity
}
// -- try append/prepend --------------------------------------------
list( $re ) = $this->doApiRequestWithToken( array(
'action' => 'edit',
'title' => $name,
$op . 'text' => $append, ) );
$this->assertEquals( 'Success', $re['edit']['result'] );
// -- validate -----------------------------------------------------
$page = new WikiPage( Title::newFromText( $name ) );
$content = $page->getContent();
$this->assertNotNull( $content, 'Page should have been created' );
$text = $content->getNativeData();
$this->assertEquals( $expected, $text );
}
/**
* Test editing of sections
*/
public function testEditSection() {
$name = 'Help:ApiEditPageTest_testEditSection';
$page = WikiPage::factory( Title::newFromText( $name ) );
$text = "==section 1==\ncontent 1\n==section 2==\ncontent2";
// Preload the page with some text
$page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ), 'summary' );
list( $re ) = $this->doApiRequestWithToken( array(
'action' => 'edit',
'title' => $name,
'section' => '1',
'text' => "==section 1==\nnew content 1",
) );
$this->assertEquals( 'Success', $re['edit']['result'] );
$newtext = WikiPage::factory( Title::newFromText( $name) )->getContent( Revision::RAW )->getNativeData();
$this->assertEquals( $newtext, "==section 1==\nnew content 1\n\n==section 2==\ncontent2" );
// Test that we raise a 'nosuchsection' error
try {
$this->doApiRequestWithToken( array(
'action' => 'edit',
'title' => $name,
'section' => '9999',
'text' => 'text',
) );
$this->fail( "Should have raised a UsageException" );
} catch ( UsageException $e ) {
$this->assertEquals( $e->getCodeString(), 'nosuchsection' );
}
}
/**
* Test action=edit§ion=new
* Run it twice so we test adding a new section on a
* page that doesn't exist (bug 52830) and one that
* does exist
*/
public function testEditNewSection() {
$name = 'Help:ApiEditPageTest_testEditNewSection';
// Test on a page that does not already exist
$this->assertFalse( Title::newFromText( $name )->exists() );
list( $re ) = $this->doApiRequestWithToken( array(
'action' => 'edit',
'title' => $name,
'section' => 'new',
'text' => 'test',
'summary' => 'header',
));
$this->assertEquals( 'Success', $re['edit']['result'] );
// Check the page text is correct
$text = WikiPage::factory( Title::newFromText( $name ) )->getContent( Revision::RAW )->getNativeData();
$this->assertEquals( $text, "== header ==\n\ntest" );
// Now on one that does
$this->assertTrue( Title::newFromText( $name )->exists() );
list( $re2 ) = $this->doApiRequestWithToken( array(
'action' => 'edit',
'title' => $name,
'section' => 'new',
'text' => 'test',
'summary' => 'header',
));
$this->assertEquals( 'Success', $re2['edit']['result'] );
$text = WikiPage::factory( Title::newFromText( $name ) )->getContent( Revision::RAW )->getNativeData();
$this->assertEquals( $text, "== header ==\n\ntest\n\n== header ==\n\ntest" );
}
public function testEditConflict() {
static $count = 0;
$count++;
// assume NS_HELP defaults to wikitext
$name = "Help:ApiEditPageTest_testEditConflict_$count";
$title = Title::newFromText( $name );
$page = WikiPage::factory( $title );
// base edit
$page->doEditContent( new WikitextContent( "Foo" ),
"testing 1", EDIT_NEW, false, self::$users['sysop']->user );
$this->forceRevisionDate( $page, '20120101000000' );
$baseTime = $page->getRevision()->getTimestamp();
// conflicting edit
$page->doEditContent( new WikitextContent( "Foo bar" ),
"testing 2", EDIT_UPDATE, $page->getLatest(), self::$users['uploader']->user );
$this->forceRevisionDate( $page, '20120101020202' );
// try to save edit, expect conflict
try {
$this->doApiRequestWithToken( array(
'action' => 'edit',
'title' => $name,
'text' => 'nix bar!',
'basetimestamp' => $baseTime,
), null, self::$users['sysop']->user );
$this->fail( 'edit conflict expected' );
} catch ( UsageException $ex ) {
$this->assertEquals( 'editconflict', $ex->getCodeString() );
}
}
public function testEditConflict_redirect() {
static $count = 0;
$count++;
// assume NS_HELP defaults to wikitext
$name = "Help:ApiEditPageTest_testEditConflict_redirect_$count";
$title = Title::newFromText( $name );
$page = WikiPage::factory( $title );
$rname = "Help:ApiEditPageTest_testEditConflict_redirect_r$count";
$rtitle = Title::newFromText( $rname );
$rpage = WikiPage::factory( $rtitle );
// base edit for content
$page->doEditContent( new WikitextContent( "Foo" ),
"testing 1", EDIT_NEW, false, self::$users['sysop']->user );
$this->forceRevisionDate( $page, '20120101000000' );
$baseTime = $page->getRevision()->getTimestamp();
// base edit for redirect
$rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
"testing 1", EDIT_NEW, false, self::$users['sysop']->user );
$this->forceRevisionDate( $rpage, '20120101000000' );
// conflicting edit to redirect
$rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]\n\n[[Category:Test]]" ),
"testing 2", EDIT_UPDATE, $page->getLatest(), self::$users['uploader']->user );
$this->forceRevisionDate( $rpage, '20120101020202' );
// try to save edit; should work, because we follow the redirect
list( $re, , ) = $this->doApiRequestWithToken( array(
'action' => 'edit',
'title' => $rname,
'text' => 'nix bar!',
'basetimestamp' => $baseTime,
'redirect' => true,
), null, self::$users['sysop']->user );
$this->assertEquals( 'Success', $re['edit']['result'],
"no edit conflict expected when following redirect" );
// try again, without following the redirect. Should fail.
try {
$this->doApiRequestWithToken( array(
'action' => 'edit',
'title' => $rname,
'text' => 'nix bar!',
'basetimestamp' => $baseTime,
), null, self::$users['sysop']->user );
$this->fail( 'edit conflict expected' );
} catch ( UsageException $ex ) {
$this->assertEquals( 'editconflict', $ex->getCodeString() );
}
}
public function testEditConflict_bug41990() {
static $count = 0;
$count++;
/*
* bug 41990: if the target page has a newer revision than the redirect, then editing the
* redirect while specifying 'redirect' and *not* specifying 'basetimestamp' erroneously
* caused an edit conflict to be detected.
*/
// assume NS_HELP defaults to wikitext
$name = "Help:ApiEditPageTest_testEditConflict_redirect_bug41990_$count";
$title = Title::newFromText( $name );
$page = WikiPage::factory( $title );
$rname = "Help:ApiEditPageTest_testEditConflict_redirect_bug41990_r$count";
$rtitle = Title::newFromText( $rname );
$rpage = WikiPage::factory( $rtitle );
// base edit for content
$page->doEditContent( new WikitextContent( "Foo" ),
"testing 1", EDIT_NEW, false, self::$users['sysop']->user );
$this->forceRevisionDate( $page, '20120101000000' );
// base edit for redirect
$rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
"testing 1", EDIT_NEW, false, self::$users['sysop']->user );
$this->forceRevisionDate( $rpage, '20120101000000' );
$baseTime = $rpage->getRevision()->getTimestamp();
// new edit to content
$page->doEditContent( new WikitextContent( "Foo bar" ),
"testing 2", EDIT_UPDATE, $page->getLatest(), self::$users['uploader']->user );
$this->forceRevisionDate( $rpage, '20120101020202' );
// try to save edit; should work, following the redirect.
list( $re, , ) = $this->doApiRequestWithToken( array(
'action' => 'edit',
'title' => $rname,
'text' => 'nix bar!',
'redirect' => true,
), null, self::$users['sysop']->user );
$this->assertEquals( 'Success', $re['edit']['result'],
"no edit conflict expected here" );
}
protected function forceRevisionDate( WikiPage $page, $timestamp ) {
$dbw = wfGetDB( DB_MASTER );
$dbw->update( 'revision',
array( 'rev_timestamp' => $dbw->timestamp( $timestamp ) ),
array( 'rev_id' => $page->getLatest() ) );
$page->clear();
}
}
| BRL-CAD/web | wiki/tests/phpunit/includes/api/ApiEditPageTest.php | PHP | bsd-2-clause | 13,254 |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'OrderAndItemCharges.code'
db.alter_column(u'shipping_orderanditemcharges', 'code', self.gf('oscar.models.fields.autoslugfield.AutoSlugField')(allow_duplicates=False, max_length=128, separator=u'-', unique=True, populate_from='name', overwrite=False))
# Changing field 'WeightBased.code'
db.alter_column(u'shipping_weightbased', 'code', self.gf('oscar.models.fields.autoslugfield.AutoSlugField')(allow_duplicates=False, max_length=128, separator=u'-', unique=True, populate_from='name', overwrite=False))
def backwards(self, orm):
# Changing field 'OrderAndItemCharges.code'
db.alter_column(u'shipping_orderanditemcharges', 'code', self.gf('django.db.models.fields.SlugField')(max_length=128, unique=True))
# Changing field 'WeightBased.code'
db.alter_column(u'shipping_weightbased', 'code', self.gf('django.db.models.fields.SlugField')(max_length=128, unique=True))
models = {
u'address.country': {
'Meta': {'ordering': "('-display_order', 'name')", 'object_name': 'Country'},
'display_order': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0', 'db_index': 'True'}),
'is_shipping_country': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'iso_3166_1_a2': ('django.db.models.fields.CharField', [], {'max_length': '2', 'primary_key': 'True'}),
'iso_3166_1_a3': ('django.db.models.fields.CharField', [], {'max_length': '3', 'null': 'True', 'db_index': 'True'}),
'iso_3166_1_numeric': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'db_index': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'printable_name': ('django.db.models.fields.CharField', [], {'max_length': '128'})
},
u'shipping.orderanditemcharges': {
'Meta': {'object_name': 'OrderAndItemCharges'},
'code': ('oscar.models.fields.autoslugfield.AutoSlugField', [], {'allow_duplicates': 'False', 'max_length': '128', 'separator': "u'-'", 'blank': 'True', 'unique': 'True', 'populate_from': "'name'", 'overwrite': 'False'}),
'countries': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['address.Country']", 'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'free_shipping_threshold': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '12', 'decimal_places': '2', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}),
'price_per_item': ('django.db.models.fields.DecimalField', [], {'default': "'0.00'", 'max_digits': '12', 'decimal_places': '2'}),
'price_per_order': ('django.db.models.fields.DecimalField', [], {'default': "'0.00'", 'max_digits': '12', 'decimal_places': '2'})
},
u'shipping.weightband': {
'Meta': {'ordering': "['upper_limit']", 'object_name': 'WeightBand'},
'charge': ('django.db.models.fields.DecimalField', [], {'max_digits': '12', 'decimal_places': '2'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'method': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'bands'", 'to': u"orm['shipping.WeightBased']"}),
'upper_limit': ('django.db.models.fields.FloatField', [], {})
},
u'shipping.weightbased': {
'Meta': {'object_name': 'WeightBased'},
'code': ('oscar.models.fields.autoslugfield.AutoSlugField', [], {'allow_duplicates': 'False', 'max_length': '128', 'separator': "u'-'", 'blank': 'True', 'unique': 'True', 'populate_from': "'name'", 'overwrite': 'False'}),
'countries': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['address.Country']", 'null': 'True', 'blank': 'True'}),
'default_weight': ('django.db.models.fields.DecimalField', [], {'default': "'0.00'", 'max_digits': '12', 'decimal_places': '2'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}),
'upper_charge': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '12', 'decimal_places': '2'})
}
}
complete_apps = ['shipping'] | jinnykoo/christmas | src/oscar/apps/shipping/south_migrations/0006_auto__chg_field_orderanditemcharges_code__chg_field_weightbased_code.py | Python | bsd-3-clause | 5,032 |
import imghdr
import json
import logging
from django.conf import settings
from django.db.models import Q
from django.http import (HttpResponse, HttpResponseRedirect,
HttpResponseBadRequest, Http404)
from django.shortcuts import get_object_or_404, render
from django.views.decorators.clickjacking import xframe_options_sameorigin
from django.views.decorators.http import require_POST
from tower import ugettext as _
from kitsune.access.decorators import login_required
from kitsune.gallery import ITEMS_PER_PAGE
from kitsune.gallery.forms import ImageForm
from kitsune.gallery.models import Image, Video
from kitsune.gallery.utils import upload_image, check_media_permissions
from kitsune.sumo.urlresolvers import reverse
from kitsune.sumo.utils import paginate
from kitsune.upload.tasks import compress_image, generate_thumbnail
from kitsune.upload.utils import FileTooLargeError
from kitsune.wiki.tasks import schedule_rebuild_kb
log = logging.getLogger('k.gallery')
def gallery(request, media_type='image'):
"""The media gallery.
Filter can be set to 'images' or 'videos'.
"""
if media_type == 'image':
media_qs = Image.objects.filter(locale=request.LANGUAGE_CODE)
elif media_type == 'video':
media_qs = Video.objects.filter(locale=request.LANGUAGE_CODE)
else:
raise Http404
media = paginate(request, media_qs, per_page=ITEMS_PER_PAGE)
drafts = _get_drafts(request.user)
image = drafts['image'][0] if drafts['image'] else None
image_form = _init_media_form(ImageForm, request, image)
if request.method == 'POST':
image_form.is_valid()
return render(request, 'gallery/gallery.html', {
'media': media,
'media_type': media_type,
'image_form': image_form,
'submitted': request.method == 'POST'})
@login_required
@require_POST
def upload(request, media_type='image'):
"""Finalizes an uploaded draft."""
drafts = _get_drafts(request.user)
if media_type == 'image' and drafts['image']:
# We're publishing an image draft!
image_form = _init_media_form(ImageForm, request, drafts['image'][0])
if image_form.is_valid():
img = image_form.save(is_draft=None)
generate_thumbnail.delay(img, 'file', 'thumbnail')
compress_image.delay(img, 'file')
# Rebuild KB
schedule_rebuild_kb()
return HttpResponseRedirect(img.get_absolute_url())
else:
return gallery(request, media_type='image')
return HttpResponseBadRequest(u'Unrecognized POST request.')
@login_required
@require_POST
def cancel_draft(request, media_type='image'):
"""Delete an existing draft for the user."""
drafts = _get_drafts(request.user)
if media_type == 'image' and drafts['image']:
drafts['image'].delete()
drafts['image'] = None
else:
msg = _(u'Unrecognized request or nothing to cancel.')
content_type = None
if request.is_ajax():
msg = json.dumps({'status': 'error', 'message': msg})
content_type = 'application/json'
return HttpResponseBadRequest(msg, content_type=content_type)
if request.is_ajax():
return HttpResponse(json.dumps({'status': 'success'}),
content_type='application/json')
return HttpResponseRedirect(reverse('gallery.gallery', args=[media_type]))
def gallery_async(request):
"""AJAX endpoint to media gallery.
Returns an HTML list representation of the media.
"""
# Maybe refactor this into existing views and check request.is_ajax?
media_type = request.GET.get('type', 'image')
term = request.GET.get('q')
media_locale = request.GET.get('locale', settings.WIKI_DEFAULT_LANGUAGE)
if media_type == 'image':
media_qs = Image.objects
elif media_type == 'video':
media_qs = Video.objects
else:
raise Http404
media_qs = media_qs.filter(locale=media_locale)
if term:
media_qs = media_qs.filter(Q(title__icontains=term) |
Q(description__icontains=term))
media = paginate(request, media_qs, per_page=ITEMS_PER_PAGE)
return render(request, 'gallery/includes/media_list.html', {
'media_list': media})
def search(request, media_type):
"""Search the media gallery."""
term = request.GET.get('q')
if not term:
url = reverse('gallery.gallery', args=[media_type])
return HttpResponseRedirect(url)
filter = Q(title__icontains=term) | Q(description__icontains=term)
if media_type == 'image':
media_qs = Image.objects.filter(filter, locale=request.LANGUAGE_CODE)
elif media_type == 'video':
media_qs = Video.objects.filter(filter, locale=request.LANGUAGE_CODE)
else:
raise Http404
media = paginate(request, media_qs, per_page=ITEMS_PER_PAGE)
return render(request, 'gallery/search.html', {
'media': media,
'media_type': media_type,
'q': term})
@login_required
def delete_media(request, media_id, media_type='image'):
"""Delete media and redirect to gallery view."""
media, media_format = _get_media_info(media_id, media_type)
check_media_permissions(media, request.user, 'delete')
if request.method == 'GET':
# Render the confirmation page
return render(request, 'gallery/confirm_media_delete.html', {
'media': media,
'media_type': media_type,
'media_format': media_format})
# Handle confirm delete form POST
log.warning('User %s is deleting %s with id=%s' %
(request.user, media_type, media.id))
media.delete()
# Rebuild KB
schedule_rebuild_kb()
return HttpResponseRedirect(reverse('gallery.gallery', args=[media_type]))
@login_required
def edit_media(request, media_id, media_type='image'):
"""Edit media means only changing the description, for now."""
media, media_format = _get_media_info(media_id, media_type)
check_media_permissions(media, request.user, 'change')
if media_type == 'image':
media_form = _init_media_form(ImageForm, request, media,
('locale', 'title'))
else:
raise Http404
if request.method == 'POST' and media_form.is_valid():
media = media_form.save(update_user=request.user, is_draft=False)
return HttpResponseRedirect(
reverse('gallery.media', args=[media_type, media_id]))
return render(request, 'gallery/edit_media.html', {
'media': media,
'media_format': media_format,
'form': media_form,
'media_type': media_type})
def media(request, media_id, media_type='image'):
"""The media page."""
media, media_format = _get_media_info(media_id, media_type)
return render(request, 'gallery/media.html', {
'media': media,
'media_format': media_format,
'media_type': media_type})
@login_required
@require_POST
@xframe_options_sameorigin
def upload_async(request, media_type='image'):
"""Upload images or videos from request.FILES."""
# TODO(paul): validate the Submit File on upload modal async
# even better, use JS validation for title length.
try:
if media_type == 'image':
file_info = upload_image(request)
else:
msg = _(u'Unrecognized media type.')
return HttpResponseBadRequest(
json.dumps({'status': 'error', 'message': msg}))
except FileTooLargeError as e:
return HttpResponseBadRequest(
json.dumps({'status': 'error', 'message': e.args[0]}))
if isinstance(file_info, dict) and 'thumbnail_url' in file_info:
schedule_rebuild_kb()
return HttpResponse(
json.dumps({'status': 'success', 'file': file_info}))
message = _(u'Could not upload your image.')
return HttpResponseBadRequest(
json.dumps({'status': 'error',
'message': unicode(message),
'errors': file_info}))
def _get_media_info(media_id, media_type):
"""Returns an image or video along with media format for the image."""
media_format = None
if media_type == 'image':
media = get_object_or_404(Image, pk=media_id)
try:
media_format = imghdr.what(media.file.path)
except UnicodeEncodeError:
pass
elif media_type == 'video':
media = get_object_or_404(Video, pk=media_id)
else:
raise Http404
return (media, media_format)
def _get_drafts(user):
"""Get video and image drafts for a given user."""
drafts = {'image': None, 'video': None}
if user.is_authenticated():
drafts['image'] = Image.objects.filter(creator=user, is_draft=True)
drafts['video'] = Video.objects.filter(creator=user, is_draft=True)
return drafts
def _init_media_form(form_cls, request=None, obj=None,
ignore_fields=()):
"""Initializes the media form with an Image/Video instance and POSTed data.
form_cls is a django ModelForm
Request method must be POST for POST data to be bound.
exclude_fields contains the list of fields to default to their current
value from the Image/Video object.
"""
post_data = None
initial = None
if request:
initial = {'locale': request.LANGUAGE_CODE}
file_data = None
if request.method == 'POST':
file_data = request.FILES
post_data = request.POST.copy()
if obj and ignore_fields:
for f in ignore_fields:
post_data[f] = getattr(obj, f)
return form_cls(post_data, file_data, instance=obj, initial=initial,
is_ajax=False)
| orvi2014/kitsune | kitsune/gallery/views.py | Python | bsd-3-clause | 9,805 |
// Squarified Treemaps by Mark Bruls, Kees Huizing, and Jarke J. van Wijk
// Modified to support a target aspect ratio by Jeff Heer
d3.layout.treemap = function() {
var hierarchy = d3.layout.hierarchy(),
round = Math.round,
size = [1, 1], // width, height
padding = null,
pad = d3_layout_treemapPadNull,
sticky = false,
stickies,
mode = "squarify",
ratio = 0.5 * (1 + Math.sqrt(5)); // golden ratio
// Compute the area for each child based on value & scale.
function scale(children, k) {
var i = -1,
n = children.length,
child,
area;
while (++i < n) {
area = (child = children[i]).value * (k < 0 ? 0 : k);
child.area = isNaN(area) || area <= 0 ? 0 : area;
}
}
// Recursively arranges the specified node's children into squarified rows.
function squarify(node) {
var children = node.children;
if (children && children.length) {
var rect = pad(node),
row = [],
remaining = children.slice(), // copy-on-write
child,
best = Infinity, // the best row score so far
score, // the current row score
u = mode === "slice" ? rect.dx
: mode === "dice" ? rect.dy
: mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx
: Math.min(rect.dx, rect.dy), // initial orientation
n;
scale(remaining, rect.dx * rect.dy / node.value);
row.area = 0;
while ((n = remaining.length) > 0) {
row.push(child = remaining[n - 1]);
row.area += child.area;
if (mode !== "squarify" || (score = worst(row, u)) <= best) { // continue with this orientation
remaining.pop();
best = score;
} else { // abort, and try a different orientation
row.area -= row.pop().area;
position(row, u, rect, false);
u = Math.min(rect.dx, rect.dy);
row.length = row.area = 0;
best = Infinity;
}
}
if (row.length) {
position(row, u, rect, true);
row.length = row.area = 0;
}
children.forEach(squarify);
}
}
// Recursively resizes the specified node's children into existing rows.
// Preserves the existing layout!
function stickify(node) {
var children = node.children;
if (children && children.length) {
var rect = pad(node),
remaining = children.slice(), // copy-on-write
child,
row = [];
scale(remaining, rect.dx * rect.dy / node.value);
row.area = 0;
while (child = remaining.pop()) {
row.push(child);
row.area += child.area;
if (child.z != null) {
position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length);
row.length = row.area = 0;
}
}
children.forEach(stickify);
}
}
// Computes the score for the specified row, as the worst aspect ratio.
function worst(row, u) {
var s = row.area,
r,
rmax = 0,
rmin = Infinity,
i = -1,
n = row.length;
while (++i < n) {
if (!(r = row[i].area)) continue;
if (r < rmin) rmin = r;
if (r > rmax) rmax = r;
}
s *= s;
u *= u;
return s
? Math.max((u * rmax * ratio) / s, s / (u * rmin * ratio))
: Infinity;
}
// Positions the specified row of nodes. Modifies `rect`.
function position(row, u, rect, flush) {
var i = -1,
n = row.length,
x = rect.x,
y = rect.y,
v = u ? round(row.area / u) : 0,
o;
if (u == rect.dx) { // horizontal subdivision
if (flush || v > rect.dy) v = rect.dy; // over+underflow
while (++i < n) {
o = row[i];
o.x = x;
o.y = y;
o.dy = v;
x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
}
o.z = true;
o.dx += rect.x + rect.dx - x; // rounding error
rect.y += v;
rect.dy -= v;
} else { // vertical subdivision
if (flush || v > rect.dx) v = rect.dx; // over+underflow
while (++i < n) {
o = row[i];
o.x = x;
o.y = y;
o.dx = v;
y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
}
o.z = false;
o.dy += rect.y + rect.dy - y; // rounding error
rect.x += v;
rect.dx -= v;
}
}
function treemap(d) {
var nodes = stickies || hierarchy(d),
root = nodes[0];
root.x = 0;
root.y = 0;
root.dx = size[0];
root.dy = size[1];
if (stickies) hierarchy.revalue(root);
scale([root], root.dx * root.dy / root.value);
(stickies ? stickify : squarify)(root);
if (sticky) stickies = nodes;
return nodes;
}
treemap.size = function(x) {
if (!arguments.length) return size;
size = x;
return treemap;
};
treemap.padding = function(x) {
if (!arguments.length) return padding;
function padFunction(node) {
var p = x.call(treemap, node, node.depth);
return p == null
? d3_layout_treemapPadNull(node)
: d3_layout_treemapPad(node, typeof p === "number" ? [p, p, p, p] : p);
}
function padConstant(node) {
return d3_layout_treemapPad(node, x);
}
var type;
pad = (padding = x) == null ? d3_layout_treemapPadNull
: (type = typeof x) === "function" ? padFunction
: type === "number" ? (x = [x, x, x, x], padConstant)
: padConstant;
return treemap;
};
treemap.round = function(x) {
if (!arguments.length) return round != Number;
round = x ? Math.round : Number;
return treemap;
};
treemap.sticky = function(x) {
if (!arguments.length) return sticky;
sticky = x;
stickies = null;
return treemap;
};
treemap.ratio = function(x) {
if (!arguments.length) return ratio;
ratio = x;
return treemap;
};
treemap.mode = function(x) {
if (!arguments.length) return mode;
mode = x + "";
return treemap;
};
return d3_layout_hierarchyRebind(treemap, hierarchy);
};
function d3_layout_treemapPadNull(node) {
return {x: node.x, y: node.y, dx: node.dx, dy: node.dy};
}
function d3_layout_treemapPad(node, padding) {
var x = node.x + padding[3],
y = node.y + padding[0],
dx = node.dx - padding[1] - padding[3],
dy = node.dy - padding[0] - padding[2];
if (dx < 0) { x += dx / 2; dx = 0; }
if (dy < 0) { y += dy / 2; dy = 0; }
return {x: x, y: y, dx: dx, dy: dy};
}
| zziuni/d3 | src/layout/treemap.js | JavaScript | bsd-3-clause | 6,511 |
#!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# 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 Google Inc. 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.
"""Unit test utilities for gtest_xml_output"""
__author__ = 'eefacm@gmail.com (Sean Mcafee)'
import re
from xml.dom import minidom, Node
import gtest_test_utils
GTEST_OUTPUT_FLAG = '--gtest_output'
GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.xml'
class GTestXMLTestCase(gtest_test_utils.TestCase):
"""
Base class for tests of Google Test's XML output functionality.
"""
def AssertEquivalentNodes(self, expected_node, actual_node):
"""
Asserts that actual_node (a DOM node object) is equivalent to
expected_node (another DOM node object), in that either both of
them are CDATA nodes and have the same value, or both are DOM
elements and actual_node meets all of the following conditions:
* It has the same tag name as expected_node.
* It has the same set of attributes as expected_node, each with
the same value as the corresponding attribute of expected_node.
Exceptions are any attribute named "time", which needs only be
convertible to a floating-point number and any attribute named
"type_param" which only has to be non-empty.
* It has an equivalent set of child nodes (including elements and
CDATA sections) as expected_node. Note that we ignore the
order of the children as they are not guaranteed to be in any
particular order.
"""
if expected_node.nodeType == Node.CDATA_SECTION_NODE:
self.assertEquals(Node.CDATA_SECTION_NODE, actual_node.nodeType)
self.assertEquals(expected_node.nodeValue, actual_node.nodeValue)
return
self.assertEquals(Node.ELEMENT_NODE, actual_node.nodeType)
self.assertEquals(Node.ELEMENT_NODE, expected_node.nodeType)
self.assertEquals(expected_node.tagName, actual_node.tagName)
expected_attributes = expected_node.attributes
actual_attributes = actual_node .attributes
self.assertEquals(
expected_attributes.length, actual_attributes.length,
'attribute numbers differ in element %s:\nExpected: %r\nActual: %r' % (
actual_node.tagName, expected_attributes.keys(),
actual_attributes.keys()))
for i in range(expected_attributes.length):
expected_attr = expected_attributes.item(i)
actual_attr = actual_attributes.get(expected_attr.name)
self.assert_(
actual_attr is not None,
'expected attribute %s not found in element %s' %
(expected_attr.name, actual_node.tagName))
self.assertEquals(
expected_attr.value, actual_attr.value,
' values of attribute %s in element %s differ: %s vs %s' %
(expected_attr.name, actual_node.tagName,
expected_attr.value, actual_attr.value))
expected_children = self._GetChildren(expected_node)
actual_children = self._GetChildren(actual_node)
self.assertEquals(
len(expected_children), len(actual_children),
'number of child elements differ in element ' + actual_node.tagName)
for child_id, child in expected_children.iteritems():
self.assert_(child_id in actual_children,
'<%s> is not in <%s> (in element %s)' %
(child_id, actual_children, actual_node.tagName))
self.AssertEquivalentNodes(child, actual_children[child_id])
identifying_attribute = {
'testsuites': 'name',
'testsuite': 'name',
'testcase': 'name',
'failure': 'message',
}
def _GetChildren(self, element):
"""
Fetches all of the child nodes of element, a DOM Element object.
Returns them as the values of a dictionary keyed by the IDs of the
children. For <testsuites>, <testsuite> and <testcase> elements, the ID
is the value of their "name" attribute; for <failure> elements, it is
the value of the "message" attribute; CDATA sections and non-whitespace
text nodes are concatenated into a single CDATA section with ID
"detail". An exception is raised if any element other than the above
four is encountered, if two child elements with the same identifying
attributes are encountered, or if any other type of node is encountered.
"""
children = {}
for child in element.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
self.assert_(child.tagName in self.identifying_attribute,
'Encountered unknown element <%s>' % child.tagName)
childID = child.getAttribute(self.identifying_attribute[child.tagName])
self.assert_(childID not in children)
children[childID] = child
elif child.nodeType in [Node.TEXT_NODE, Node.CDATA_SECTION_NODE]:
if 'detail' not in children:
if (child.nodeType == Node.CDATA_SECTION_NODE or
not child.nodeValue.isspace()):
children['detail'] = child.ownerDocument.createCDATASection(
child.nodeValue)
else:
children['detail'].nodeValue += child.nodeValue
else:
self.fail('Encountered unexpected node type %d' % child.nodeType)
return children
def NormalizeXml(self, element):
"""
Normalizes Google Test's XML output to eliminate references to transient
information that may change from run to run.
* The "time" attribute of <testsuites>, <testsuite> and <testcase>
elements is replaced with a single asterisk, if it contains
only digit characters.
* The "timestamp" attribute of <testsuites> elements is replaced with a
single asterisk, if it contains a valid ISO8601 datetime value.
* The "type_param" attribute of <testcase> elements is replaced with a
single asterisk (if it sn non-empty) as it is the type name returned
by the compiler and is platform dependent.
* The line info reported in the first line of the "message"
attribute and CDATA section of <failure> elements is replaced with the
file's basename and a single asterisk for the line number.
* The directory names in file paths are removed.
* The stack traces are removed.
"""
if element.tagName == 'testsuites':
timestamp = element.getAttributeNode('timestamp')
timestamp.value = re.sub(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d$',
'*', timestamp.value)
if element.tagName in ('testsuites', 'testsuite', 'testcase'):
time = element.getAttributeNode('time')
time.value = re.sub(r'^\d+(\.\d+)?$', '*', time.value)
type_param = element.getAttributeNode('type_param')
if type_param and type_param.value:
type_param.value = '*'
elif element.tagName == 'failure':
source_line_pat = r'^.*[/\\](.*:)\d+\n'
# Replaces the source line information with a normalized form.
message = element.getAttributeNode('message')
message.value = re.sub(source_line_pat, '\\1*\n', message.value)
for child in element.childNodes:
if child.nodeType == Node.CDATA_SECTION_NODE:
# Replaces the source line information with a normalized form.
cdata = re.sub(source_line_pat, '\\1*\n', child.nodeValue)
# Removes the actual stack trace.
child.nodeValue = re.sub(r'\nStack trace:\n(.|\n)*',
'', cdata)
for child in element.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
self.NormalizeXml(child)
| paoloach/zdomus | zigbee_lib/googletest/googletest/test/gtest_xml_test_utils.py | Python | gpl-2.0 | 8,876 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
namespace System.Text.Json
{
public ref partial struct Utf8JsonWriter
{
/// <summary>
/// Writes the <see cref="double"/> value (as a JSON number) as an element of a JSON array.
/// </summary>
/// <param name="value">The value to be written as a JSON number as an element of a JSON array.</param>
/// <exception cref="InvalidOperationException">
/// Thrown if this would result in an invalid JSON to be written (while validation is enabled).
/// </exception>
/// <remarks>
/// Writes the <see cref="double"/> using the default <see cref="StandardFormat"/> (i.e. 'G').
/// </remarks>
public void WriteNumberValue(double value)
{
JsonWriterHelper.ValidateDouble(value);
ValidateWritingValue();
if (_writerOptions.Indented)
{
WriteNumberValueIndented(value);
}
else
{
WriteNumberValueMinimized(value);
}
SetFlagToAddListSeparatorBeforeNextItem();
_tokenType = JsonTokenType.Number;
}
private void WriteNumberValueMinimized(double value)
{
int idx = 0;
WriteListSeparator(ref idx);
WriteNumberValueFormatLoop(value, ref idx);
Advance(idx);
}
private void WriteNumberValueIndented(double value)
{
int idx = WriteCommaAndFormattingPreamble();
WriteNumberValueFormatLoop(value, ref idx);
Advance(idx);
}
}
}
| ptoonen/corefx | src/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Double.cs | C# | mit | 1,839 |
// Type definitions for non-npm package @ember/component 3.0
// Project: https://emberjs.com/api/ember/3.4/modules/@ember%2Fcomponent
// Definitions by: Mike North <https://github.com/mike-north>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
/// <reference types="jquery" />
import CoreView from "@ember/component/-private/core-view";
import ClassNamesSupport from "@ember/component/-private/class-names-support";
import ViewMixin from "@ember/component/-private/view-mixin";
import ActionSupport from "@ember/component/-private/action-support";
// tslint:disable-next-line:strict-export-declare-modifiers
interface TemplateFactory {
__htmlbars_inline_precompile_template_factory: any;
}
/**
* A view that is completely isolated. Property access in its templates go to the view object
* and actions are targeted at the view object. There is no access to the surrounding context or
* outer controller; all contextual information is passed in.
*/
export default class Component extends CoreView.extend(
ViewMixin,
ActionSupport,
ClassNamesSupport
) {
// methods
readDOMAttr(name: string): string;
// properties
/**
* The WAI-ARIA role of the control represented by this view. For example, a button may have a
* role of type 'button', or a pane may have a role of type 'alertdialog'. This property is
* used by assistive software to help visually challenged users navigate rich web applications.
*/
ariaRole: string;
/**
* The HTML id of the component's element in the DOM. You can provide this value yourself but
* it must be unique (just as in HTML):
*
* If not manually set a default value will be provided by the framework. Once rendered an
* element's elementId is considered immutable and you should never change it. If you need
* to compute a dynamic value for the elementId, you should do this when the component or
* element is being instantiated:
*/
elementId: string;
/**
* If false, the view will appear hidden in DOM.
*/
isVisible: boolean;
/**
* A component may contain a layout. A layout is a regular template but supersedes the template
* property during rendering. It is the responsibility of the layout template to retrieve the
* template property from the component (or alternatively, call Handlebars.helpers.yield,
* {{yield}}) to render it in the correct location. This is useful for a component that has a
* shared wrapper, but which delegates the rendering of the contents of the wrapper to the
* template property on a subclass.
*/
layout: TemplateFactory | string;
/**
* Enables components to take a list of parameters as arguments.
*/
static positionalParams: string[] | string;
// events
/**
* Called when the attributes passed into the component have been updated. Called both during the
* initial render of a container and during a rerender. Can be used in place of an observer; code
* placed here will be executed every time any attribute updates.
*/
didReceiveAttrs(): void;
/**
* Called after a component has been rendered, both on initial render and in subsequent rerenders.
*/
didRender(): void;
/**
* Called when the component has updated and rerendered itself. Called only during a rerender,
* not during an initial render.
*/
didUpdate(): void;
/**
* Called when the attributes passed into the component have been changed. Called only during a
* rerender, not during an initial render.
*/
didUpdateAttrs(): void;
/**
* Called before a component has been rendered, both on initial render and in subsequent rerenders.
*/
willRender(): void;
/**
* Called when the component is about to update and rerender itself. Called only during a rerender,
* not during an initial render.
*/
willUpdate(): void;
}
| borisyankov/DefinitelyTyped | types/ember__component/index.d.ts | TypeScript | mit | 4,009 |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""ExportStrategy class that provides strategies to export model so later it
can be used for TensorFlow serving."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
__all__ = ['ExportStrategy']
class ExportStrategy(collections.namedtuple('ExportStrategy',
['name', 'export_fn'])):
def export(self, estimator, export_path):
return self.export_fn(estimator, export_path)
| jjas0nn/solvem | tensorflow/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/export_strategy.py | Python | mit | 1,195 |
version https://git-lfs.github.com/spec/v1
oid sha256:cdaff690080dec73e2f9044eb89e1426fd2645ea6d8b253cd51cd992717b8a06
size 1772
| yogeshsaroya/new-cdnjs | ajax/libs/codemirror/5.1.0/mode/shell/test.js | JavaScript | mit | 129 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
namespace System.Net.NetworkInformation
{
internal class LinuxIPGlobalStatistics : IPGlobalStatistics
{
// MIB-II statistics data.
private readonly IPGlobalStatisticsTable _table;
// Miscellaneous IP information, not defined in MIB-II.
private int _numRoutes;
private int _numInterfaces;
private int _numIPAddresses;
public LinuxIPGlobalStatistics(bool ipv4)
{
if (ipv4)
{
_table = StringParsingHelpers.ParseIPv4GlobalStatisticsFromSnmpFile(NetworkFiles.SnmpV4StatsFile);
_numRoutes = StringParsingHelpers.ParseNumRoutesFromRouteFile(NetworkFiles.Ipv4RouteFile);
_numInterfaces = StringParsingHelpers.ParseNumIPInterfaces(NetworkFiles.Ipv4ConfigFolder);
}
else
{
_table = StringParsingHelpers.ParseIPv6GlobalStatisticsFromSnmp6File(NetworkFiles.SnmpV6StatsFile);
_numRoutes = StringParsingHelpers.ParseNumRoutesFromRouteFile(NetworkFiles.Ipv6RouteFile);
_numInterfaces = StringParsingHelpers.ParseNumIPInterfaces(NetworkFiles.Ipv6ConfigFolder);
// /proc/sys/net/ipv6/conf/default/forwarding
string forwardingConfigFile = Path.Combine(NetworkFiles.Ipv6ConfigFolder,
NetworkFiles.DefaultNetworkInterfaceFileName,
NetworkFiles.ForwardingFileName);
_table.Forwarding = StringParsingHelpers.ParseRawIntFile(forwardingConfigFile) == 1;
// snmp6 does not include Default TTL info. Read it from snmp.
_table.DefaultTtl = StringParsingHelpers.ParseDefaultTtlFromFile(NetworkFiles.SnmpV4StatsFile);
}
_numIPAddresses = GetNumIPAddresses();
}
public override int DefaultTtl { get { return _table.DefaultTtl; } }
public override bool ForwardingEnabled { get { return _table.Forwarding; } }
public override int NumberOfInterfaces { get { return _numInterfaces; } }
public override int NumberOfIPAddresses { get { return _numIPAddresses; } }
public override int NumberOfRoutes { get { return _numRoutes; } }
public override long OutputPacketRequests { get { return _table.OutRequests; } }
public override long OutputPacketRoutingDiscards { get { throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); } }
public override long OutputPacketsDiscarded { get { return _table.OutDiscards; } }
public override long OutputPacketsWithNoRoute { get { return _table.OutNoRoutes; } }
public override long PacketFragmentFailures { get { return _table.FragmentFails; } }
public override long PacketReassembliesRequired { get { return _table.ReassemblyRequireds; } }
public override long PacketReassemblyFailures { get { return _table.ReassemblyFails; } }
public override long PacketReassemblyTimeout { get { return _table.ReassemblyTimeout; } }
public override long PacketsFragmented { get { return _table.FragmentCreates; } }
public override long PacketsReassembled { get { return _table.ReassemblyOKs; } }
public override long ReceivedPackets { get { return _table.InReceives; } }
public override long ReceivedPacketsDelivered { get { return _table.InDelivers; } }
public override long ReceivedPacketsDiscarded { get { return _table.InDiscards; } }
public override long ReceivedPacketsForwarded { get { return _table.ForwardedDatagrams; } }
public override long ReceivedPacketsWithAddressErrors { get { return _table.InAddressErrors; } }
public override long ReceivedPacketsWithHeadersErrors { get { return _table.InHeaderErrors; } }
public override long ReceivedPacketsWithUnknownProtocol { get { return _table.InUnknownProtocols; } }
private static unsafe int GetNumIPAddresses()
{
int count = 0;
Interop.Sys.EnumerateInterfaceAddresses(
(name, ipAddressInfo) =>
{
count++;
},
(name, ipAddressInfo, scopeId) =>
{
count++;
},
// Ignore link-layer addresses that are discovered; don't create a callback.
null);
return count;
}
}
}
| shimingsg/corefx | src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/LinuxIPGlobalStatistics.cs | C# | mit | 4,754 |
package com.wirelesspienetwork.overview.views;
import android.animation.ValueAnimator;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.view.animation.Interpolator;
/* The transform state for a task view */
public class OverviewCardTransform {
public int startDelay = 0;
public int translationY = 0;
public float translationZ = 0;
public float scale = 1f;
public float alpha = 1f;
public boolean visible = false;
public Rect rect = new Rect();
float p = 0f;
public OverviewCardTransform() {
// Do nothing
}
public OverviewCardTransform(OverviewCardTransform o) {
startDelay = o.startDelay;
translationY = o.translationY;
translationZ = o.translationZ;
scale = o.scale;
alpha = o.alpha;
visible = o.visible;
rect.set(o.rect);
p = o.p;
}
/** Resets the current transform */
public void reset() {
startDelay = 0;
translationY = 0;
translationZ = 0;
scale = 1f;
alpha = 1f;
visible = false;
rect.setEmpty();
p = 0f;
}
/** Convenience functions to compare against current property values */
public boolean hasAlphaChangedFrom(float v) {
return (Float.compare(alpha, v) != 0);
}
public boolean hasScaleChangedFrom(float v) {
return (Float.compare(scale, v) != 0);
}
public boolean hasTranslationYChangedFrom(float v) {
return (Float.compare(translationY, v) != 0);
}
public boolean hasTranslationZChangedFrom(float v) {
return (Float.compare(translationZ, v) != 0);
}
/** Applies this transform to a view. */
public void applyToTaskView(View v, int duration, Interpolator interp, boolean allowLayers,
boolean allowShadows, ValueAnimator.AnimatorUpdateListener updateCallback) {
// Check to see if any properties have changed, and update the task view
if (duration > 0) {
ViewPropertyAnimator anim = v.animate();
boolean requiresLayers = false;
// Animate to the final state
if (hasTranslationYChangedFrom(v.getTranslationY())) {
anim.translationY(translationY);
}
if (hasScaleChangedFrom(v.getScaleX())) {
anim.scaleX(scale)
.scaleY(scale);
requiresLayers = true;
}
if (hasAlphaChangedFrom(v.getAlpha())) {
// Use layers if we animate alpha
anim.alpha(alpha);
requiresLayers = true;
}
if (requiresLayers && allowLayers) {
anim.withLayer();
}
anim.setStartDelay(startDelay)
.setDuration(duration)
.setInterpolator(interp)
.start();
} else {
// Set the changed properties
if (hasTranslationYChangedFrom(v.getTranslationY())) {
v.setTranslationY(translationY);
}
if (hasScaleChangedFrom(v.getScaleX())) {
v.setScaleX(scale);
v.setScaleY(scale);
}
if (hasAlphaChangedFrom(v.getAlpha())) {
v.setAlpha(alpha);
}
}
}
/** Reset the transform on a view. */
public static void reset(View v) {
v.setTranslationX(0f);
v.setTranslationY(0f);
v.setScaleX(1f);
v.setScaleY(1f);
v.setAlpha(1f);
}
@Override
public String toString() {
return "TaskViewTransform delay: " + startDelay + " y: " + translationY + " z: " + translationZ +
" scale: " + scale + " alpha: " + alpha + " visible: " + visible + " rect: " + rect +
" p: " + p;
}
}
| ppamorim/StackOverView | lib/src/main/java/com/wirelesspienetwork/overview/views/OverviewCardTransform.java | Java | mit | 3,895 |
#!/usr/bin/env python
import sys
import re
from helpers import *
PROGRAM_USAGE = """
SeqAn script to replace invalid identifiers (previously collected) in the SeqAn
codebase.
USAGE: replace_identifiers.py BASE_PATH [REPLACEMENTS]
BASE_PATH is the root path of all the folders to be searched.
REPLACEMENTS is a file of ``"key:value"`` pairs which contain the invalid
identifier and the replacement string.
If this file is not given, it is attemped to read the replacements from the
standard input stream.
""".strip()
def replace_all(text, subst):
"""
Perform the substitutions given by the dictionary ``subst`` on ``text``.
"""
for old in subst.keys():
text = old.sub(subst[old], text)
return text
def validate_file(file, subst):
"""
Perform the substitutions given by the dictionary ``subst`` on ``file``.
"""
#print file
code = ''
try:
f = open(file, 'r')
finally:
code = f.read()
old_len = len(code)
replaced = replace_all(code, subst)
#assert old_len == len(replaced)
open(file, 'w').write(replaced)
def build_subst_table(file):
"""
Read the substitutions defined in ``file`` and build a substitution table.
"""
table = {}
for line in file:
old, new = line.rstrip('\r\n').split(':')
table[re.compile(r'\b%s\b' % old.strip())] = new.strip()
return table
def main():
# Either read from stdin or expect a file path in the second argument.
# Since there is no reliable way of checking for an attached stdin on
# Windows, just assume good faith if the file name isn't given.
use_stdin = len(sys.argv) == 2
if not (len(sys.argv) == 3 or use_stdin):
print >>sys.stderr, 'ERROR: Invalid number of arguments.'
print >>sys.stderr, PROGRAM_USAGE
return 1
if use_stdin:
print >>sys.stderr, "Attempting to read from stdin ..."
project_path = sys.argv[1]
replacements_file = sys.stdin if use_stdin else open(sys.argv[2], 'r')
substitutions = build_subst_table(replacements_file)
for file in all_files(project_path):
validate_file(file, substitutions)
return 0
if __name__ == '__main__':
sys.exit(main())
| bkahlert/seqan-research | raw/workshop13/workshop2013-data-20130926/trunk/misc/renaming/replace_identifiers.py | Python | mit | 2,256 |
/* This file was generated by SableCC (http://www.sablecc.org/). */
package wolf.node;
import wolf.analysis.*;
@SuppressWarnings("nls")
public final class TStringBody extends Token
{
public TStringBody(String text)
{
setText(text);
}
public TStringBody(String text, int line, int pos)
{
setText(text);
setLine(line);
setPos(pos);
}
@Override
public Object clone()
{
return new TStringBody(getText(), getLine(), getPos());
}
@Override
public void apply(Switch sw)
{
((Analysis) sw).caseTStringBody(this);
}
}
| dittma75/compiler-design | wolf_compiler/wolf/src/wolf/node/TStringBody.java | Java | mit | 616 |