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 |
|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
"""
ulmo.ncdc.ghcn_daily.core
~~~~~~~~~~~~~~~~~~~~~~~~~
This module provides direct access to `National Climatic Data Center`_
`Global Historical Climate Network - Daily`_ dataset.
.. _National Climatic Data Center: http://www.ncdc.noaa.gov
.. _Global Historical Climate Network - Daily: http://www.ncdc.noaa.gov/oa/climate/ghcn-daily/
"""
import itertools
import os
import numpy as np
import pandas
from tsgettoolbox.ulmo import util
GHCN_DAILY_DIR = os.path.join(util.get_ulmo_dir(), "ncdc/ghcn_daily")
def get_data(station_id, elements=None, update=True, as_dataframe=False):
"""Retrieves data for a given station.
Parameters
----------
station_id : str
Station ID to retrieve data for.
elements : ``None``, str, or list of str
If specified, limits the query to given element code(s).
update : bool
If ``True`` (default), new data files will be downloaded if they are
newer than any previously cached files. If ``False``, then previously
downloaded files will be used and new files will only be downloaded if
there is not a previously downloaded file for a given station.
as_dataframe : bool
If ``False`` (default), a dict with element codes mapped to value dicts
is returned. If ``True``, a dict with element codes mapped to equivalent
pandas.DataFrame objects will be returned. The pandas dataframe is used
internally, so setting this to ``True`` is a little bit faster as it
skips a serialization step.
Returns
-------
site_dict : dict
A dict with element codes as keys, mapped to collections of values. See
the ``as_dataframe`` parameter for more.
"""
if isinstance(elements, str):
elements = [elements]
start_columns = [
("year", 11, 15, int),
("month", 15, 17, int),
("element", 17, 21, str),
]
value_columns = [
("value", 0, 5, float),
("mflag", 5, 6, str),
("qflag", 6, 7, str),
("sflag", 7, 8, str),
]
columns = list(
itertools.chain(
start_columns,
*[
[
(name + str(n), start + 13 + (8 * n), end + 13 + (8 * n), converter)
for name, start, end, converter in value_columns
]
for n in range(1, 32)
]
)
)
station_file_path = _get_ghcn_file(station_id + ".dly", check_modified=update)
station_data = util.parse_fwf(station_file_path, columns, na_values=[-9999])
dataframes = {}
for element_name, element_df in station_data.groupby("element"):
if not elements is None and element_name not in elements:
continue
element_df["month_period"] = element_df.apply(
lambda x: pandas.Period("{}-{}".format(x["year"], x["month"])), axis=1
)
element_df = element_df.set_index("month_period")
monthly_index = element_df.index
# here we're just using pandas' builtin resample logic to construct a daily
# index for the timespan
# 2018/11/27 johanneshorak: hotfix to get ncdc ghcn_daily working again
# new resample syntax requires resample method to generate resampled index.
daily_index = element_df.resample("D").sum().index.copy()
# XXX: hackish; pandas support for this sort of thing will probably be
# added soon
month_starts = (monthly_index - 1).asfreq("D") + 1
dataframe = pandas.DataFrame(
columns=["value", "mflag", "qflag", "sflag"], index=daily_index
)
for day_of_month in range(1, 32):
dates = [
date
for date in (month_starts + day_of_month - 1)
if date.day == day_of_month
]
if not dates:
continue
months = pandas.PeriodIndex([pandas.Period(date, "M") for date in dates])
for column_name in dataframe.columns:
col = column_name + str(day_of_month)
dataframe[column_name][dates] = element_df[col][months]
dataframes[element_name] = dataframe
if as_dataframe:
return dataframes
return {
key: util.dict_from_dataframe(dataframe)
for key, dataframe in dataframes.items()
}
def get_stations(
country=None,
state=None,
elements=None,
start_year=None,
end_year=None,
update=True,
as_dataframe=False,
):
"""Retrieves station information, optionally limited to specific parameters.
Parameters
----------
country : str
The country code to use to limit station results. If set to ``None``
(default), then stations from all countries are returned.
state : str
The state code to use to limit station results. If set to ``None``
(default), then stations from all states are returned.
elements : ``None``, str, or list of str
If specified, station results will be limited to the given element codes
and only stations that have data for any these elements will be
returned.
start_year : int
If specified, station results will be limited to contain only stations
that have data after this year. Can be combined with the ``end_year``
argument to get stations with data within a range of years.
end_year : int
If specified, station results will be limited to contain only stations
that have data before this year. Can be combined with the ``start_year``
argument to get stations with data within a range of years.
update : bool
If ``True`` (default), new data files will be downloaded if they are
newer than any previously cached files. If ``False``, then previously
downloaded files will be used and new files will only be downloaded if
there is not a previously downloaded file for a given station.
as_dataframe : bool
If ``False`` (default), a dict with station IDs keyed to station dicts
is returned. If ``True``, a single pandas.DataFrame object will be
returned. The pandas dataframe is used internally, so setting this to
``True`` is a little bit faster as it skips a serialization step.
Returns
-------
stations_dict : dict or pandas.DataFrame
A dict or pandas.DataFrame representing station information for stations
matching the arguments. See the ``as_dataframe`` parameter for more.
"""
columns = [
("country", 0, 2, None),
("network", 2, 3, None),
("network_id", 3, 11, None),
("latitude", 12, 20, None),
("longitude", 21, 30, None),
("elevation", 31, 37, None),
("state", 38, 40, None),
("name", 41, 71, None),
("gsn_flag", 72, 75, None),
("hcn_flag", 76, 79, None),
("wm_oid", 80, 85, None),
]
stations_file = _get_ghcn_file("ghcnd-stations.txt", check_modified=update)
stations = util.parse_fwf(stations_file, columns)
if not country is None:
stations = stations[stations["country"] == country]
if not state is None:
stations = stations[stations["state"] == state]
# set station id and index by it
stations["id"] = stations[["country", "network", "network_id"]].T.apply("".join)
if not elements is None or not start_year is None or not end_year is None:
inventory = _get_inventory(update=update)
if not elements is None:
if isinstance(elements, str):
elements = [elements]
mask = np.zeros(len(inventory), dtype=bool)
for element in elements:
mask += inventory["element"] == element
inventory = inventory[mask]
if not start_year is None:
inventory = inventory[inventory["last_year"] >= start_year]
if not end_year is None:
inventory = inventory[inventory["first_year"] <= end_year]
uniques = inventory["id"].unique()
ids = pandas.DataFrame(uniques, index=uniques, columns=["id"])
stations = pandas.merge(stations, ids).set_index("id", drop=False)
stations = stations.set_index("id", drop=False)
# wm_oid gets convertidsed as a float, so cast it to str manually
# pandas versions prior to 0.13.0 could use numpy's fix-width string type
# to do this but that stopped working in pandas 0.13.0 - fortunately a
# regex-based helper method was added then, too
if pandas.__version__ < "0.13.0":
stations["wm_oid"] = stations["wm_oid"].astype("|U5")
stations["wm_oid"][stations["wm_oid"] == "nan"] = np.nan
else:
stations["wm_oid"] = stations["wm_oid"].astype("|U5").map(lambda x: x[:-2])
is_nan = stations["wm_oid"] == "n"
is_empty = stations["wm_oid"] == ""
is_invalid = is_nan | is_empty
stations.loc[is_invalid, "wm_oid"] = np.nan
if as_dataframe:
return stations
return util.dict_from_dataframe(stations)
def _get_ghcn_file(filename, check_modified=True):
base_url = "http://www1.ncdc.noaa.gov/pub/data/ghcn/daily/"
if "ghcnd-" in filename:
url = base_url + filename
else:
url = base_url + "all/" + filename
path = os.path.join(GHCN_DAILY_DIR, url.split("/")[-1])
util.download_if_new(url, path, check_modified=check_modified)
return path
def _get_inventory(update=True):
columns = [
("id", 0, 11, None),
("latitude", 12, 20, None),
("longitude", 21, 30, None),
("element", 31, 35, None),
("first_year", 36, 40, None),
("last_year", 41, 45, None),
]
inventory_file = _get_ghcn_file("ghcnd-inventory.txt", check_modified=update)
return util.parse_fwf(inventory_file, columns)
| timcera/tsgettoolbox | src/tsgettoolbox/ulmo/ncdc/ghcn_daily/core.py | Python | bsd-3-clause | 9,898 |
using System.Linq;
using FatturaElettronica.Ordinaria.FatturaElettronicaBody;
using FatturaElettronica.Ordinaria.FatturaElettronicaBody.DatiBeniServizi;
using FatturaElettronica.Ordinaria.FatturaElettronicaBody.DatiGenerali;
using FatturaElettronica.Common;
using FluentValidation.TestHelper;
using Tests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Ordinaria.Tests
{
[TestClass]
public class FatturaElettronicaBodyValidator
: BaseClass<FatturaElettronicaBody, FatturaElettronica.Validators.FatturaElettronicaBodyValidator>
{
[TestMethod]
public void DatiGeneraliHasChildValidator()
{
validator.ShouldHaveChildValidator(
x => x.DatiGenerali, typeof(FatturaElettronica.Validators.DatiGeneraliValidator));
}
[TestMethod]
public void DatiBeniServiziHasChildValidator()
{
validator.ShouldHaveChildValidator(
x => x.DatiBeniServizi, typeof(FatturaElettronica.Validators.DatiBeniServiziValidator));
}
[TestMethod]
public void DatiBeniServiziCannotBeEmpty()
{
var r = validator.Validate(challenge);
Assert.AreEqual("DatiBeniServizi è obbligatorio", r.Errors.FirstOrDefault(x => x.PropertyName == "DatiBeniServizi").ErrorMessage);
}
[TestMethod]
public void DatiRitenutaValidateAgainstError00411()
{
challenge.DatiBeniServizi.DettaglioLinee.Add(new DettaglioLinee { Ritenuta = "SI" });
var r = validator.Validate(challenge);
Assert.AreEqual("00411", r.Errors.FirstOrDefault(x => x.PropertyName == "DatiGenerali.DatiGeneraliDocumento.DatiRitenuta").ErrorCode);
challenge.DatiBeniServizi.DettaglioLinee[0].Ritenuta = null;
r = validator.Validate(challenge);
Assert.IsNull(r.Errors.FirstOrDefault(x => x.PropertyName == "DatiGenerali.DatiGeneraliDocumento.DatiRitenuta"));
}
[TestMethod]
public void DatiRitenutaValidateAgainstError00422()
{
challenge.DatiBeniServizi.DettaglioLinee.Add(new DettaglioLinee { AliquotaIVA = 10m, PrezzoTotale = 100m });
challenge.DatiBeniServizi.DatiRiepilogo.Add(new DatiRiepilogo { AliquotaIVA = 10m, ImponibileImporto = 101m });
var r = validator.Validate(challenge);
Assert.AreEqual("00422", r.Errors.FirstOrDefault(x => x.PropertyName == "DatiBeniServizi.DatiRiepilogo").ErrorCode);
challenge.DatiBeniServizi.DatiRiepilogo[0].ImponibileImporto = 100m;
r = validator.Validate(challenge);
Assert.IsNull(r.Errors.FirstOrDefault(x => x.PropertyName == "DatiBeniServizi.DatiRiepilogo"));
}
[TestMethod]
public void DatiRitenutaValidateAgainstError00419()
{
challenge.DatiBeniServizi.DettaglioLinee.Add(new DettaglioLinee { AliquotaIVA = 1 });
challenge.DatiBeniServizi.DettaglioLinee.Add(new DettaglioLinee { AliquotaIVA = 2 });
challenge.DatiBeniServizi.DettaglioLinee.Add(new DettaglioLinee { AliquotaIVA = 3 });
challenge.DatiGenerali.DatiGeneraliDocumento.DatiCassaPrevidenziale.Add(new DatiCassaPrevidenziale { AliquotaIVA = 4 });
challenge.DatiBeniServizi.DatiRiepilogo.Add(new DatiRiepilogo { AliquotaIVA = 1 });
challenge.DatiBeniServizi.DatiRiepilogo.Add(new DatiRiepilogo { AliquotaIVA = 2 });
challenge.DatiBeniServizi.DatiRiepilogo.Add(new DatiRiepilogo { AliquotaIVA = 3 });
var r = validator.Validate(challenge);
Assert.AreEqual("00419", r.Errors.FirstOrDefault(x => x.PropertyName == "DatiBeniServizi.DatiRiepilogo").ErrorCode);
challenge.DatiBeniServizi.DatiRiepilogo.Add(new DatiRiepilogo { AliquotaIVA = 4 });
r = validator.Validate(challenge);
Assert.IsNull(r.Errors.FirstOrDefault(x => x.PropertyName == "DatiBeniServizi.DatiRiepilogo"));
}
[TestMethod]
public void DatiVeicoliHasChildValidator()
{
validator.ShouldHaveChildValidator(
x => x.DatiGenerali, typeof(FatturaElettronica.Validators.DatiGeneraliValidator));
}
[TestMethod]
public void DatiPagamentoHasChildValidator()
{
validator.ShouldHaveChildValidator(
x => x.DatiPagamento, typeof(FatturaElettronica.Validators.DatiPagamentoValidator));
}
[TestMethod]
public void AllegatiHasChildValidator()
{
validator.ShouldHaveChildValidator(
x => x.Allegati, typeof(FatturaElettronica.Validators.AllegatiValidator));
}
}
}
| FatturaElettronicaPA/FatturaElettronicaPA | Test/Ordinaria/FatturaElettronicaBodyValidator.cs | C# | bsd-3-clause | 4,718 |
<?php
namespace backend\controllers;
use Yii;
use common\models\Categories;
use common\models\CategoriesSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* Created By Roopan v v <yiioverflow@gmail.com>
* Date : 24-04-2015
* Time :3:00 PM
* CategoriesController implements the CRUD actions for Categories model.
*/
class CategoriesController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all Categories models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new CategoriesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Categories model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Categories model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Categories();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Categories model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Categories model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Categories model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Categories the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Categories::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
| hostkerala/yii2-test | backend/controllers/CategoriesController.php | PHP | bsd-3-clause | 3,237 |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/gpu/gpu_data_manager_impl.h"
#include "content/browser/gpu/gpu_data_manager_impl_private.h"
namespace content {
// static
GpuDataManager* GpuDataManager::GetInstance() {
return GpuDataManagerImpl::GetInstance();
}
// static
GpuDataManagerImpl* GpuDataManagerImpl::GetInstance() {
return Singleton<GpuDataManagerImpl>::get();
}
void GpuDataManagerImpl::InitializeForTesting(
const std::string& gpu_blacklist_json, const GPUInfo& gpu_info) {
base::AutoLock auto_lock(lock_);
private_->InitializeForTesting(gpu_blacklist_json, gpu_info);
}
bool GpuDataManagerImpl::IsFeatureBlacklisted(int feature) const {
base::AutoLock auto_lock(lock_);
return private_->IsFeatureBlacklisted(feature);
}
GPUInfo GpuDataManagerImpl::GetGPUInfo() const {
base::AutoLock auto_lock(lock_);
return private_->GetGPUInfo();
}
void GpuDataManagerImpl::GetGpuProcessHandles(
const GetGpuProcessHandlesCallback& callback) const {
base::AutoLock auto_lock(lock_);
private_->GetGpuProcessHandles(callback);
}
bool GpuDataManagerImpl::GpuAccessAllowed(std::string* reason) const {
base::AutoLock auto_lock(lock_);
return private_->GpuAccessAllowed(reason);
}
void GpuDataManagerImpl::RequestCompleteGpuInfoIfNeeded() {
base::AutoLock auto_lock(lock_);
private_->RequestCompleteGpuInfoIfNeeded();
}
bool GpuDataManagerImpl::IsCompleteGpuInfoAvailable() const {
base::AutoLock auto_lock(lock_);
return private_->IsCompleteGpuInfoAvailable();
}
void GpuDataManagerImpl::RequestVideoMemoryUsageStatsUpdate() const {
base::AutoLock auto_lock(lock_);
private_->RequestVideoMemoryUsageStatsUpdate();
}
bool GpuDataManagerImpl::ShouldUseSwiftShader() const {
base::AutoLock auto_lock(lock_);
return private_->ShouldUseSwiftShader();
}
void GpuDataManagerImpl::RegisterSwiftShaderPath(
const base::FilePath& path) {
base::AutoLock auto_lock(lock_);
private_->RegisterSwiftShaderPath(path);
}
void GpuDataManagerImpl::AddObserver(
GpuDataManagerObserver* observer) {
base::AutoLock auto_lock(lock_);
private_->AddObserver(observer);
}
void GpuDataManagerImpl::RemoveObserver(
GpuDataManagerObserver* observer) {
base::AutoLock auto_lock(lock_);
private_->RemoveObserver(observer);
}
void GpuDataManagerImpl::UnblockDomainFrom3DAPIs(const GURL& url) {
base::AutoLock auto_lock(lock_);
private_->UnblockDomainFrom3DAPIs(url);
}
void GpuDataManagerImpl::DisableGpuWatchdog() {
base::AutoLock auto_lock(lock_);
private_->DisableGpuWatchdog();
}
void GpuDataManagerImpl::SetGLStrings(const std::string& gl_vendor,
const std::string& gl_renderer,
const std::string& gl_version) {
base::AutoLock auto_lock(lock_);
private_->SetGLStrings(gl_vendor, gl_renderer, gl_version);
}
void GpuDataManagerImpl::GetGLStrings(std::string* gl_vendor,
std::string* gl_renderer,
std::string* gl_version) {
base::AutoLock auto_lock(lock_);
private_->GetGLStrings(gl_vendor, gl_renderer, gl_version);
}
void GpuDataManagerImpl::DisableHardwareAcceleration() {
base::AutoLock auto_lock(lock_);
private_->DisableHardwareAcceleration();
}
void GpuDataManagerImpl::Initialize() {
base::AutoLock auto_lock(lock_);
private_->Initialize();
}
void GpuDataManagerImpl::UpdateGpuInfo(const GPUInfo& gpu_info) {
base::AutoLock auto_lock(lock_);
private_->UpdateGpuInfo(gpu_info);
}
void GpuDataManagerImpl::UpdateVideoMemoryUsageStats(
const GPUVideoMemoryUsageStats& video_memory_usage_stats) {
base::AutoLock auto_lock(lock_);
private_->UpdateVideoMemoryUsageStats(video_memory_usage_stats);
}
void GpuDataManagerImpl::AppendRendererCommandLine(
CommandLine* command_line) const {
base::AutoLock auto_lock(lock_);
private_->AppendRendererCommandLine(command_line);
}
void GpuDataManagerImpl::AppendGpuCommandLine(
CommandLine* command_line) const {
base::AutoLock auto_lock(lock_);
private_->AppendGpuCommandLine(command_line);
}
void GpuDataManagerImpl::AppendPluginCommandLine(
CommandLine* command_line) const {
base::AutoLock auto_lock(lock_);
private_->AppendPluginCommandLine(command_line);
}
void GpuDataManagerImpl::UpdateRendererWebPrefs(
WebPreferences* prefs) const {
base::AutoLock auto_lock(lock_);
private_->UpdateRendererWebPrefs(prefs);
}
GpuSwitchingOption GpuDataManagerImpl::GetGpuSwitchingOption() const {
base::AutoLock auto_lock(lock_);
return private_->GetGpuSwitchingOption();
}
std::string GpuDataManagerImpl::GetBlacklistVersion() const {
base::AutoLock auto_lock(lock_);
return private_->GetBlacklistVersion();
}
base::ListValue* GpuDataManagerImpl::GetBlacklistReasons() const {
base::AutoLock auto_lock(lock_);
return private_->GetBlacklistReasons();
}
void GpuDataManagerImpl::AddLogMessage(int level,
const std::string& header,
const std::string& message) {
base::AutoLock auto_lock(lock_);
private_->AddLogMessage(level, header, message);
}
void GpuDataManagerImpl::ProcessCrashed(
base::TerminationStatus exit_code) {
base::AutoLock auto_lock(lock_);
private_->ProcessCrashed(exit_code);
}
base::ListValue* GpuDataManagerImpl::GetLogMessages() const {
base::AutoLock auto_lock(lock_);
return private_->GetLogMessages();
}
void GpuDataManagerImpl::HandleGpuSwitch() {
base::AutoLock auto_lock(lock_);
private_->HandleGpuSwitch();
}
#if defined(OS_WIN)
bool GpuDataManagerImpl::IsUsingAcceleratedSurface() const {
base::AutoLock auto_lock(lock_);
return private_->IsUsingAcceleratedSurface();
}
#endif
void GpuDataManagerImpl::BlockDomainFrom3DAPIs(
const GURL& url, DomainGuilt guilt) {
base::AutoLock auto_lock(lock_);
private_->BlockDomainFrom3DAPIs(url, guilt);
}
bool GpuDataManagerImpl::Are3DAPIsBlocked(const GURL& url,
int render_process_id,
int render_view_id,
ThreeDAPIType requester) {
base::AutoLock auto_lock(lock_);
return private_->Are3DAPIsBlocked(
url, render_process_id, render_view_id, requester);
}
void GpuDataManagerImpl::DisableDomainBlockingFor3DAPIsForTesting() {
base::AutoLock auto_lock(lock_);
private_->DisableDomainBlockingFor3DAPIsForTesting();
}
size_t GpuDataManagerImpl::GetBlacklistedFeatureCount() const {
base::AutoLock auto_lock(lock_);
return private_->GetBlacklistedFeatureCount();
}
void GpuDataManagerImpl::Notify3DAPIBlocked(const GURL& url,
int render_process_id,
int render_view_id,
ThreeDAPIType requester) {
base::AutoLock auto_lock(lock_);
private_->Notify3DAPIBlocked(
url, render_process_id, render_view_id, requester);
}
GpuDataManagerImpl::GpuDataManagerImpl()
: private_(GpuDataManagerImplPrivate::Create(this)) {
}
GpuDataManagerImpl::~GpuDataManagerImpl() {
}
} // namespace content
| loopCM/chromium | content/browser/gpu/gpu_data_manager_impl.cc | C++ | bsd-3-clause | 7,341 |
import unittest
from sympy import sympify
from nineml.abstraction import (
Dynamics, AnalogSendPort, Alias,
AnalogReceivePort, AnalogReducePort, Regime, On,
OutputEvent, EventReceivePort, Constant, StateVariable, Parameter,
OnCondition, OnEvent, Trigger)
import nineml.units as un
from nineml.exceptions import NineMLMathParseError, NineMLUsageError
from nineml.document import Document
from nineml.utils.iterables import unique_by_id
class ComponentClass_test(unittest.TestCase):
def test_aliases(self):
# Signature: name
# Forwarding function to self.dynamics.aliases
# No Aliases:
self.assertEqual(
list(Dynamics(name='C1').aliases),
[]
)
# 2 Aliases
C = Dynamics(name='C1', aliases=['G:= 0', 'H:=1'])
self.assertEqual(len(list((C.aliases))), 2)
self.assertEqual(
set(C.alias_names), set(['G', 'H'])
)
C = Dynamics(name='C1', aliases=['G:= 0', 'H:=1', Alias('I', '3')])
self.assertEqual(len(list((C.aliases))), 3)
self.assertEqual(
set(C.alias_names), set(['G', 'H', 'I'])
)
# Using DynamicsBlock Parameter:
C = Dynamics(name='C1', aliases=['G:= 0', 'H:=1'])
self.assertEqual(len(list((C.aliases))), 2)
self.assertEqual(
set(C.alias_names), set(['G', 'H'])
)
C = Dynamics(name='C1',
aliases=['G:= 0', 'H:=1', Alias('I', '3')])
self.assertEqual(len(list((C.aliases))), 3)
self.assertEqual(
set(C.alias_names), set(['G', 'H', 'I'])
)
# Invalid Construction:
# Invalid Valid String:
self.assertRaises(
NineMLUsageError,
Dynamics, name='C1', aliases=['H=0']
)
# Duplicate Alias Names:
Dynamics(name='C1', aliases=['H:=0', 'G:=1'])
self.assertRaises(
NineMLUsageError,
Dynamics, name='C1', aliases=['H:=0', 'H:=1']
)
self.assertRaises(
NineMLUsageError,
Dynamics, name='C1', aliases=['H:=0', Alias('H', '1')]
)
# Self referential aliases:
self.assertRaises(
NineMLUsageError,
Dynamics,
name='C1', aliases=['H := H +1'],
)
self.assertRaises(
NineMLUsageError,
Dynamics,
name='C1', aliases=['H := G + 1', 'G := H + 1'],
)
# Referencing none existent symbols:
self.assertRaises(
NineMLUsageError,
Dynamics,
name='C1',
aliases=['H := G + I'],
parameters=['P1'],
)
# Invalid Names:
self.assertRaises(
NineMLUsageError,
Dynamics,
name='C1', aliases=['H.2 := 0'],
)
self.assertRaises(
NineMLUsageError,
Dynamics,
name='C1', aliases=['2H := 0'],
)
self.assertRaises(
NineMLUsageError,
Dynamics,
name='C1', aliases=['E(H) := 0'],
)
self.assertRaises(
NineMLUsageError,
Dynamics,
name='C1', aliases=['tanh := 0'],
)
self.assertRaises(
NineMLUsageError,
Dynamics,
name='C1', aliases=['t := 0'],
)
def test_aliases_map(self):
# Signature: name
# Forwarding function to self.dynamics.alias_map
self.assertEqual(
Dynamics(name='C1')._aliases, {}
)
c1 = Dynamics(name='C1', aliases=['A:=3'])
self.assertEqual(c1.alias('A').rhs_as_python_func(), 3)
self.assertEqual(len(c1._aliases), 1)
c2 = Dynamics(name='C1', aliases=['A:=3', 'B:=5'])
self.assertEqual(c2.alias('A').rhs_as_python_func(), 3)
self.assertEqual(c2.alias('B').rhs_as_python_func(), 5)
self.assertEqual(len(c2._aliases), 2)
c3 = Dynamics(name='C1', aliases=['C:=13', 'Z:=15'])
self.assertEqual(c3.alias('C').rhs_as_python_func(), 13)
self.assertEqual(c3.alias('Z').rhs_as_python_func(), 15)
self.assertEqual(len(c3._aliases), 2)
def test_analog_ports(self):
# Signature: name
# No Docstring
c = Dynamics(name='C1')
self.assertEqual(len(list(c.analog_ports)), 0)
c = Dynamics(name='C1')
self.assertEqual(len(list(c.analog_ports)), 0)
c = Dynamics(name='C1', aliases=['A:=2'],
analog_ports=[AnalogSendPort('A')])
self.assertEqual(len(list(c.analog_ports)), 1)
self.assertEqual(list(c.analog_ports)[0].mode, 'send')
self.assertEqual(len(list(c.analog_send_ports)), 1)
self.assertEqual(len(list(c.analog_receive_ports)), 0)
self.assertEqual(len(list(c.analog_reduce_ports)), 0)
c = Dynamics(name='C1', analog_ports=[AnalogReceivePort('B')])
self.assertEqual(len(list(c.analog_ports)), 1)
self.assertEqual(list(c.analog_ports)[0].mode, 'recv')
self.assertEqual(len(list(c.analog_send_ports)), 0)
self.assertEqual(len(list(c.analog_receive_ports)), 1)
self.assertEqual(len(list(c.analog_reduce_ports)), 0)
c = Dynamics(name='C1',
analog_ports=[AnalogReducePort('B', operator='+')])
self.assertEqual(len(list(c.analog_ports)), 1)
self.assertEqual(list(c.analog_ports)[0].mode, 'reduce')
self.assertEqual(list(c.analog_ports)[0].operator, '+')
self.assertEqual(len(list(c.analog_send_ports)), 0)
self.assertEqual(len(list(c.analog_receive_ports)), 0)
self.assertEqual(len(list(c.analog_reduce_ports)), 1)
# Duplicate Port Names:
self.assertRaises(
NineMLUsageError,
Dynamics,
name='C1',
aliases=['A1:=1'],
analog_ports=[AnalogReducePort('B', operator='+'),
AnalogSendPort('B')]
)
self.assertRaises(
NineMLUsageError,
Dynamics,
name='C1',
aliases=['A1:=1'],
analog_ports=[AnalogSendPort('A'), AnalogSendPort('A')]
)
self.assertRaises(
NineMLUsageError,
Dynamics,
name='C1',
aliases=['A1:=1'],
analog_ports=[AnalogReceivePort('A'), AnalogReceivePort('A')]
)
self.assertRaises(
NineMLUsageError,
lambda: Dynamics(name='C1', analog_ports=[AnalogReceivePort('1')])
)
self.assertRaises(
NineMLUsageError,
lambda: Dynamics(name='C1', analog_ports=[AnalogReceivePort('?')])
)
def duplicate_port_name_event_analog(self):
# Check different names are OK:
Dynamics(
name='C1', aliases=['A1:=1'],
event_ports=[EventReceivePort('A')],
analog_ports=[AnalogSendPort('A')])
self.assertRaises(
NineMLUsageError,
Dynamics,
name='C1',
aliases=['A1:=1'],
event_ports=[EventReceivePort('A')],
analog_ports=[AnalogSendPort('A')]
)
def test_event_ports(self):
# Signature: name
# No Docstring
# Check inference of output event ports:
c = Dynamics(
name='Comp1',
regimes=Regime(
transitions=[
On('V > a', do=OutputEvent('ev_port1')),
On('V > b', do=OutputEvent('ev_port1')),
On('V < c', do=OutputEvent('ev_port2')),
]
),
)
self.assertEqual(len(list(c.event_ports)), 2)
# Check inference of output event ports:
c = Dynamics(
name='Comp1',
regimes=[
Regime(name='r1',
transitions=[
On('V > a', do=OutputEvent('ev_port1'), to='r2'),
On('V < b', do=OutputEvent('ev_port2'))]),
Regime(name='r2',
transitions=[
On('V > a', do=OutputEvent('ev_port2'), to='r1'),
On('V < b', do=OutputEvent('ev_port3'))])
]
)
self.assertEqual(len(list(c.event_ports)), 3)
# Check inference of output event ports:
c = Dynamics(
name='Comp1',
regimes=[
Regime(name='r1',
transitions=[
On('spikeinput1', do=[]),
On('spikeinput2', do=OutputEvent('ev_port2'),
to='r2')]),
Regime(name='r2',
transitions=[
On('V > a', do=OutputEvent('ev_port2')),
On('spikeinput3', do=OutputEvent('ev_port3'),
to='r1')])
]
)
self.assertEqual(len(list(c.event_ports)), 5)
def test_parameters(self):
# Signature: name
# No Docstring
# No parameters; nothing to infer
c = Dynamics(name='cl')
self.assertEqual(len(list(c.parameters)), 0)
# Mismatch between inferred and actual parameters
self.assertRaises(
NineMLUsageError,
Dynamics, name='cl', parameters=['a'])
# Single parameter inference from an alias block
c = Dynamics(name='cl', aliases=['A1:=a'])
self.assertEqual(len(list(c.parameters)), 1)
self.assertEqual(list(c.parameters)[0].name, 'a')
# More complex inference:
c = Dynamics(name='cl', aliases=['A1:=a+e', 'B1:=a+pi+b'],
constants=[Constant('pi', 3.141592653589793)])
self.assertEqual(len(list(c.parameters)), 3)
self.assertEqual(sorted([p.name for p in c.parameters]),
['a', 'b', 'e'])
# From State Assignments and Differential Equations, and Conditionals
c = Dynamics(name='cl',
aliases=['A1:=a+e', 'B1:=a+pi+b'],
regimes=Regime('dX/dt = (6 + c + sin(d))/t',
'dV/dt = 1.0/t',
transitions=On('V>Vt',
do=['X = X + f', 'V=0'])),
constants=[Constant('pi', 3.1415926535)])
self.assertEqual(len(list(c.parameters)), 7)
self.assertEqual(
sorted([p.name for p in c.parameters]),
['Vt', 'a', 'b', 'c', 'd', 'e', 'f'])
self.assertRaises(
NineMLUsageError,
Dynamics,
name='cl',
aliases=['A1:=a+e', 'B1:=a+pi+b'],
regimes=Regime('dX/dt = 6 + c + sin(d)',
'dV/dt = 1.0',
transitions=On('V>Vt', do=['X = X + f', 'V=0'])
),
parameters=['a', 'b', 'c'])
def test_regimes(self):
c = Dynamics(name='cl', )
self.assertEqual(len(list(c.regimes)), 0)
c = Dynamics(name='cl',
regimes=Regime('dX/dt=1/t',
name='r1',
transitions=On('X>X1', do=['X = X0'],
to=None)))
self.assertEqual(len(list(c.regimes)), 1)
c = Dynamics(name='cl',
regimes=[
Regime('dX/dt=1/t',
name='r1',
transitions=On('X>X1', do=['X=X0'],
to='r2')),
Regime('dX/dt=1/t',
name='r2',
transitions=On('X>X1', do=['X=X0'],
to='r3')),
Regime('dX/dt=1/t',
name='r3',
transitions=On('X>X1', do=['X=X0'],
to='r4')),
Regime('dX/dt=1/t',
name='r4',
transitions=On('X>X1', do=['X=X0'],
to='r1'))])
self.assertEqual(len(list(c.regimes)), 4)
self.assertEqual(
set(c.regime_names),
set(['r1', 'r2', 'r3', 'r4'])
)
c = Dynamics(name='cl',
regimes=[
Regime('dX/dt=1/t', name='r1',
transitions=On('X>X1', do=['X=X0'],
to='r2')),
Regime('dX/dt=1/t',
name='r2',
transitions=On('X>X1', do=['X=X0'],
to='r3')),
Regime('dX/dt=1/t',
name='r3',
transitions=On('X>X1', do=['X=X0'],
to='r4')),
Regime('dX/dt=1/t',
name='r4',
transitions=On('X>X1', do=['X=X0'],
to='r1'))])
self.assertEqual(len(list(c.regimes)), 4)
self.assertEqual(
set([r.name for r in c.regimes]),
set(['r1', 'r2', 'r3', 'r4'])
)
# Duplicate Names:
self.assertRaises(
NineMLUsageError,
Dynamics, name='cl',
regimes=[
Regime('dX/dt=1/t',
name='r',
transitions=On('X>X1', do=['X=X0'])),
Regime('dX/dt=1/t',
name='r',
transitions=On('X>X1', do=['X=X0'],)), ]
)
def test_regime_aliases(self):
a = Dynamics(
name='a',
aliases=[Alias('A', '4/t')],
regimes=[
Regime('dX/dt=1/t + A',
name='r1',
transitions=On('X>X1', do=['X=X0'], to='r2')),
Regime('dX/dt=1/t + A',
name='r2',
transitions=On('X>X1', do=['X=X0'],
to='r1'),
aliases=[Alias('A', '8 / t')])])
self.assertEqual(a.regime('r2').alias('A'), Alias('A', '8 / t'))
self.assertRaises(
NineMLUsageError,
Dynamics,
name='a',
regimes=[
Regime('dX/dt=1/t + A',
name='r1',
transitions=On('X>X1', do=['X=X0'], to='r2')),
Regime('dX/dt=1/t + A',
name='r2',
transitions=On('X>X1', do=['X=X0'],
to='r1'),
aliases=[Alias('A', '8 / t')])])
document = Document()
a_xml = a.serialize(format='xml', version=1, document=document)
b = Dynamics.unserialize(a_xml, format='xml', version=1,
document=Document(un.dimensionless.clone()))
self.assertEqual(a, b,
"Dynamics with regime-specific alias failed xml "
"roundtrip:\n{}".format(a.find_mismatch(b)))
def test_state_variables(self):
# No parameters; nothing to infer
c = Dynamics(name='cl')
self.assertEqual(len(list(c.state_variables)), 0)
# From State Assignments and Differential Equations, and Conditionals
c = Dynamics(
name='cl',
aliases=['A1:=a+e', 'B1:=a+pi+b'],
regimes=Regime('dX/dt = (6 + c + sin(d))/t',
'dV/dt = 1.0/t',
transitions=On('V>Vt', do=['X = X + f', 'V=0'])))
self.assertEqual(
set(c.state_variable_names),
set(['X', 'V']))
self.assertRaises(
NineMLUsageError,
Dynamics,
name='cl',
aliases=['A1:=a+e', 'B1:=a+pi+b'],
regimes=Regime('dX/dt = 6 + c + sin(d)',
'dV/dt = 1.0',
transitions=On('V>Vt', do=['X = X + f', 'V=0'])
),
state_variables=['X'])
# Shouldn't pick up 'e' as a parameter:
self.assertRaises(
NineMLUsageError,
Dynamics,
name='cl',
aliases=['A1:=a+e', 'B1:=a+pi+b'],
regimes=Regime('dX/dt = 6 + c + sin(d)',
'dV/dt = 1.0',
transitions=On('V>Vt', do=['X = X + f', 'V=0'])
),
state_variables=['X', 'V', 'Vt'])
c = Dynamics(name='cl',
regimes=[
Regime('dX1/dt=1/t',
name='r1',
transitions=On('X>X1', do=['X=X0'],
to='r2')),
Regime('dX1/dt=1/t',
name='r2',
transitions=On('X>X1', do=['X=X0'],
to='r3')),
Regime('dX2/dt=1/t',
name='r3',
transitions=On('X>X1', do=['X=X0'],
to='r4')),
Regime('dX2/dt=1/t',
name='r4',
transitions=On('X>X1', do=['X=X0'],
to='r1'))])
self.assertEqual(set(c.state_variable_names),
set(['X1', 'X2', 'X']))
def test_transitions(self):
c = Dynamics(name='cl',
regimes=[
Regime('dX1/dt=1/t',
name='r1',
transitions=[On('X>X1', do=['X=X0'],
to='r2'),
On('X>X2', do=['X=X0'],
to='r3'), ]
),
Regime('dX1/dt=1/t',
name='r2',
transitions=On('X>X1', do=['X=X0'],
to='r3'),),
Regime('dX2/dt=1/t',
name='r3',
transitions=[On('X>X1', do=['X=X0'],
to='r4'),
On('X>X2', do=['X=X0'],
to=None)]),
Regime('dX2/dt=1/t',
name='r4',
transitions=On('X>X1', do=['X=X0'],
to=None))])
self.assertEqual(len(list(c.all_transitions())), 6)
r1 = c.regime('r1')
r2 = c.regime('r2')
r3 = c.regime('r3')
r4 = c.regime('r4')
self.assertEqual(len(list(r1.transitions)), 2)
self.assertEqual(len(list(r2.transitions)), 1)
self.assertEqual(len(list(r3.transitions)), 2)
self.assertEqual(len(list(r4.transitions)), 1)
def target_regimes(regime):
return unique_by_id(t.target_regime for t in regime.transitions)
self.assertEqual(target_regimes(r1), [r2, r3])
self.assertEqual(target_regimes(r2), [r3])
self.assertEqual(target_regimes(r3), [r3, r4])
self.assertEqual(target_regimes(r4), [r4])
def test_all_expressions(self):
a = Dynamics(
name='A',
aliases=['A1:=P1 * SV2', 'A2 := ARP1 + SV2', 'A3 := SV1'],
state_variables=[
StateVariable('SV1', dimension=un.voltage),
StateVariable('SV2', dimension=un.current)],
regimes=[
Regime(
'dSV1/dt = -SV1 / P2',
'dSV2/dt = A3 / ARP2 + SV2 / P2',
transitions=[On('SV1 > P3', do=[OutputEvent('emit')]),
On('spikein', do=[OutputEvent('emit')])],
name='R1'
),
Regime(name='R2', transitions=On('(SV1 > C1) & (SV2 < P4)',
to='R1'))
],
analog_ports=[AnalogReceivePort('ARP1', dimension=un.current),
AnalogReceivePort('ARP2',
dimension=(un.resistance *
un.time)),
AnalogSendPort('A1',
dimension=un.voltage * un.current),
AnalogSendPort('A2', dimension=un.current)],
parameters=[Parameter('P1', dimension=un.voltage),
Parameter('P2', dimension=un.time),
Parameter('P3', dimension=un.voltage),
Parameter('P4', dimension=un.current)],
constants=[Constant('C1', value=1.0, units=un.mV)]
)
self.assertEqual(
set(a.all_expressions), set((
sympify('P1 * SV2'), sympify('ARP1 + SV2'), sympify('SV1'),
sympify('-SV1 / P2'), sympify('-SV1 / P2'),
sympify('A3 / ARP2 + SV2 / P2'), sympify('SV1 > P3'),
sympify('(SV1 > C1) & (SV2 < P4)'))),
"All expressions were not extracted from component class")
class TestOn(unittest.TestCase):
def test_On(self):
# Signature: name(trigger, do=None, to=None)
# No Docstring
# Test that we are correctly inferring OnEvents and OnConditions.
self.assertEqual(type(On('V>0')), OnCondition)
self.assertEqual(type(On('V<0')), OnCondition)
self.assertEqual(type(On('(V<0) & (K>0)')), OnCondition)
self.assertEqual(type(On('V==0')), OnCondition)
self.assertEqual(
type(On("q > 1 / (( 1 + mg_conc * eta * exp ( -1 * gamma*V)))")),
OnCondition)
self.assertEqual(type(On('SP0')), OnEvent)
self.assertEqual(type(On('SP1')), OnEvent)
# Check we can use 'do' with single and multiple values
tr = On('V>0')
self.assertEqual(len(list(tr.output_events)), 0)
self.assertEqual(len(list(tr.state_assignments)), 0)
tr = On('SP0')
self.assertEqual(len(list(tr.output_events)), 0)
self.assertEqual(len(list(tr.state_assignments)), 0)
tr = On('V>0', do=OutputEvent('spike'))
self.assertEqual(len(list(tr.output_events)), 1)
self.assertEqual(len(list(tr.state_assignments)), 0)
tr = On('SP0', do=OutputEvent('spike'))
self.assertEqual(len(list(tr.output_events)), 1)
self.assertEqual(len(list(tr.state_assignments)), 0)
tr = On('V>0', do=[OutputEvent('spike')])
self.assertEqual(len(list(tr.output_events)), 1)
self.assertEqual(len(list(tr.state_assignments)), 0)
tr = On('SP0', do=[OutputEvent('spike')])
self.assertEqual(len(list(tr.output_events)), 1)
self.assertEqual(len(list(tr.state_assignments)), 0)
tr = On('V>0', do=['y=2', OutputEvent('spike'), 'x=1'])
self.assertEqual(len(list(tr.output_events)), 1)
self.assertEqual(len(list(tr.state_assignments)), 2)
tr = On('SP0', do=['y=2', OutputEvent('spike'), 'x=1'])
self.assertEqual(len(list(tr.output_events)), 1)
self.assertEqual(len(list(tr.state_assignments)), 2)
class OnCondition_test(unittest.TestCase):
def test_trigger(self):
invalid_triggers = ['true(',
'V < (V+10',
'V (< V+10)',
'V (< V+10)',
'1 / ( 1 + mg_conc * eta * exp(-1 * gamma*V))'
'1..0'
'..0']
for tr in invalid_triggers:
self.assertRaises(NineMLMathParseError, OnCondition, tr)
# Test Come Conditions:
namespace = {
"A": 10,
"B": 5,
"tau_r": 5,
"V": 20,
"Vth": -50.0,
"t_spike": 1.0,
"q": 11.0,
"t": 0.9,
"tref": 0.1
}
cond_exprs = [
["A > -B/tau_r", ("A", "B", "tau_r"), ()],
["(V > 1.0) & !(V<10.0)", ("V",), ()],
["!!(V>10)", ("V"), ()],
["!!(V>10)", ("V"), ()],
["V>exp(Vth)", ("V", "Vth"), ('exp',)],
["!(V>Vth)", ("V", "Vth"), ()],
["!(V>Vth)", ("V", "Vth"), ()],
["exp(V)>Vth", ("V", "Vth"), ("exp",)],
["true", (), ()],
["(V < (Vth+q)) & (t > t_spike)", ("t_spike", "t", "q", "Vth",
"V"), ()],
["(V < (Vth+q)) | (t > t_spike)", ("t_spike", "Vth", "q", "V",
"t"), ()],
["(true)", (), ()],
["!true", (), ()],
["!false", (), ()],
["t >= t_spike + tref", ("t", "t_spike", "tref"), ()],
["true & !false", (), ()]
]
return_values = [
True,
True,
True,
True,
True,
False,
False,
True,
True,
False,
False,
True,
False,
True,
False,
True
]
for i, (expr, expt_vars, expt_funcs) in enumerate(cond_exprs):
c = OnCondition(trigger=expr)
self.assertEqual(set(c.trigger.rhs_symbol_names), set(expt_vars))
self.assertEqual(set(str(f) for f in c.trigger.rhs_funcs),
set(expt_funcs))
python_func = c.trigger.rhs_as_python_func
param_dict = dict([(v, namespace[v]) for v in expt_vars])
self.assertEqual(return_values[i], python_func(**param_dict))
def test_trigger_crossing_time_expr(self):
self.assertEqual(Trigger('t > t_next').crossing_time_expr.rhs,
sympify('t_next'))
self.assertEqual(Trigger('t^2 > t_next').crossing_time_expr, None)
self.assertEqual(Trigger('a < b').crossing_time_expr, None)
self.assertEqual(
Trigger('t > t_next || t > t_next2').crossing_time_expr.rhs,
sympify('Min(t_next, t_next2)'))
self.assertEqual(
Trigger('t > t_next || a < b').crossing_time_expr, None)
def test_make_strict(self):
self.assertEqual(
Trigger._make_strict(
sympify('(a >= 0.5) & ~(b < (10 * c * e)) | (c <= d)')),
sympify('(a > 0.5) & (b > (10 * c * e)) | (c < d)'))
class OnEvent_test(unittest.TestCase):
def test_Constructor(self):
pass
def test_src_port_name(self):
self.assertRaises(NineMLUsageError, OnEvent, '1MyEvent1 ')
self.assertRaises(NineMLUsageError, OnEvent, 'MyEvent1 2')
self.assertRaises(NineMLUsageError, OnEvent, 'MyEvent1* ')
self.assertEqual(OnEvent(' MyEvent1 ').src_port_name, 'MyEvent1')
self.assertEqual(OnEvent(' MyEvent2').src_port_name, 'MyEvent2')
class Regime_test(unittest.TestCase):
def test_Constructor(self):
pass
def test_add_on_condition(self):
# Signature: name(self, on_condition)
# Add an OnCondition transition which leaves this regime
#
# If the on_condition object has not had its target regime name set in
# the constructor, or by calling its ``set_target_regime_name()``, then
# the target is assumed to be this regime, and will be set
# appropriately.
#
# The source regime for this transition will be set as this regime.
r = Regime(name='R1')
self.assertEqual(unique_by_id(r.on_conditions), [])
r.add(OnCondition('sp1>0'))
self.assertEqual(len(unique_by_id(r.on_conditions)), 1)
self.assertEqual(len(unique_by_id(r.on_events)), 0)
self.assertEqual(len(unique_by_id(r.transitions)), 1)
def test_add_on_event(self):
# Signature: name(self, on_event)
# Add an OnEvent transition which leaves this regime
#
# If the on_event object has not had its target regime name set in the
# constructor, or by calling its ``set_target_regime_name()``, then the
# target is assumed to be this regime, and will be set appropriately.
#
# The source regime for this transition will be set as this regime.
# from nineml.abstraction.component.dynamics import Regime
r = Regime(name='R1')
self.assertEqual(unique_by_id(r.on_events), [])
r.add(OnEvent('sp'))
self.assertEqual(len(unique_by_id(r.on_events)), 1)
self.assertEqual(len(unique_by_id(r.on_conditions)), 0)
self.assertEqual(len(unique_by_id(r.transitions)), 1)
def test_get_next_name(self):
# Signature: name(cls)
# Return the next distinct autogenerated name
n1 = Regime.get_next_name()
n2 = Regime.get_next_name()
n3 = Regime.get_next_name()
self.assertNotEqual(n1, n2)
self.assertNotEqual(n2, n3)
def test_name(self):
self.assertRaises(NineMLUsageError, Regime, name='&Hello')
self.assertRaises(NineMLUsageError, Regime, name='2Hello')
self.assertEqual(Regime(name='Hello').name, 'Hello')
self.assertEqual(Regime(name='Hello2').name, 'Hello2')
def test_time_derivatives(self):
# Signature: name
# Returns the state-variable time-derivatives in this regime.
#
# .. note::
#
# This is not guarenteed to contain the time derivatives for all
# the state-variables specified in the component. If they are not
# defined, they are assumed to be zero in this regime.
r = Regime('dX1/dt=0',
'dX2/dt=0',
name='r1')
self.assertEqual(
set([td.variable for td in r.time_derivatives]),
set(['X1', 'X2']))
# Defining a time derivative twice:
self.assertRaises(
NineMLUsageError,
Regime, 'dX/dt=1', 'dX/dt=2')
# Assigning to a value:
self.assertRaises(
NineMLUsageError,
Regime, 'X=1')
class StateVariable_test(unittest.TestCase):
def test_name(self):
# Signature: name
# No Docstring
self.assertRaises(NineMLUsageError, StateVariable, name='&Hello')
self.assertRaises(NineMLUsageError, StateVariable, name='2Hello')
self.assertEqual(StateVariable(name='Hello').name, 'Hello')
self.assertEqual(StateVariable(name='Hello2').name, 'Hello2')
class Query_test(unittest.TestCase):
def test_event_send_receive_ports(self):
# Signature: name(self)
# Get the ``recv`` EventPorts
# from nineml.abstraction.component.componentqueryer import
# ComponentClassQueryer
# Check inference of output event ports:
c = Dynamics(
name='Comp1',
regimes=Regime(
transitions=[
On('in_ev1', do=OutputEvent('ev_port1')),
On('V < b', do=OutputEvent('ev_port1')),
On('V < c', do=OutputEvent('ev_port2')),
]
),
)
self.assertEqual(len(list(c.event_receive_ports)), 1)
self.assertEqual((list(list(c.event_receive_ports))[0]).name,
'in_ev1')
self.assertEqual(len(list(c.event_send_ports)), 2)
self.assertEqual(set(c.event_send_port_names),
set(['ev_port1', 'ev_port2']))
# Check inference of output event ports:
c = Dynamics(
name='Comp1',
regimes=[
Regime(name='r1',
transitions=[
On('V > a', do=OutputEvent('ev_port1'), to='r2'),
On('in_ev1', do=OutputEvent('ev_port2'))]),
Regime(name='r2',
transitions=[
On('V > a', do=OutputEvent('ev_port2'), to='r1'),
On('in_ev2', do=OutputEvent('ev_port3'))])
]
)
self.assertEqual(len(list(c.event_receive_ports)), 2)
self.assertEqual(set(c.event_receive_port_names),
set(['in_ev1', 'in_ev2']))
self.assertEqual(len(list(c.event_send_ports)), 3)
self.assertEqual(set(c.event_send_port_names),
set(['ev_port1', 'ev_port2', 'ev_port3']))
# Check inference of output event ports:
c = Dynamics(
name='Comp1',
regimes=[
Regime(name='r1',
transitions=[
On('spikeinput1', do=[]),
On('spikeinput2', do=[
OutputEvent('ev_port1'),
OutputEvent('ev_port2')], to='r2')]),
Regime(name='r2',
transitions=[
On('V > a', do=OutputEvent('ev_port2')),
On('spikeinput3', do=OutputEvent('ev_port3'),
to='r1')])
]
)
self.assertEqual(len(list(c.event_receive_ports)), 3)
self.assertEqual(set(c.event_receive_port_names),
set(['spikeinput1', 'spikeinput2', 'spikeinput3']))
self.assertEqual(len(list(c.event_send_ports)), 3)
self.assertEqual(set(c.event_send_port_names),
set(['ev_port1', 'ev_port2', 'ev_port3']))
def test_ports(self):
# Signature: name
# Return an iterator over all the port (Event & Analog) in the
# component
# from nineml.abstraction.component.componentqueryer import
# ComponentClassQueryer
c = Dynamics(
name='Comp1',
regimes=[
Regime(name='r1',
transitions=[
On('spikeinput1', do=[]),
On('spikeinput2', do=OutputEvent('ev_port2'),
to='r2')]),
Regime(name='r2',
transitions=[
On('V > a', do=OutputEvent('ev_port2')),
On('spikeinput3', do=OutputEvent('ev_port3'),
to='r1')])
],
aliases=['A1:=0', 'C:=0'],
analog_ports=[AnalogSendPort('A1'), AnalogReceivePort('B'),
AnalogSendPort('C')]
)
ports = list(list(c.ports))
port_names = [p.name for p in ports]
self.assertEqual(len(port_names), 8)
self.assertEqual(set(port_names),
set(['A1', 'B', 'C', 'spikeinput1', 'spikeinput2',
'spikeinput3', 'ev_port2', 'ev_port3'])
)
def test_regime(self):
# Signature: name(self, name=None)
# Find a regime in the component by name
# from nineml.abstraction.component.componentqueryer import
# ComponentClassQueryer
c = Dynamics(name='cl',
regimes=[
Regime('dX/dt=1/t',
name='r1',
transitions=On('X>X1', do=['X=X0'],
to='r2')),
Regime('dX/dt=1/t',
name='r2',
transitions=On('X>X1', do=['X=X0'],
to='r3')),
Regime('dX/dt=1/t',
name='r3',
transitions=On('X>X1', do=['X=X0'],
to='r4')),
Regime('dX/dt=1/t',
name='r4',
transitions=On('X>X1', do=['X=X0'],
to='r1'))])
self.assertEqual(c.regime(name='r1').name, 'r1')
self.assertEqual(c.regime(name='r2').name, 'r2')
self.assertEqual(c.regime(name='r3').name, 'r3')
self.assertEqual(c.regime(name='r4').name, 'r4')
| INCF/lib9ML | test/unittests/abstraction_test/dynamics_test.py | Python | bsd-3-clause | 37,676 |
using UnityEngine;
using System.Collections;
public class DestroyByContact : MonoBehaviour {
public GameObject explosion;
public GameObject playerExplosion;
public int scoreValue;
private GameController gameController;
void Start()
{
GameObject gameControllerObject = GameObject.FindWithTag("GameController");
if(gameControllerObject != null)
{
gameController = gameControllerObject.GetComponent<GameController>();
}
if(gameController == null)
{
Debug.Log("Cannot find 'GameController script");
}
}
void OnTriggerEnter(Collider other)
{
if (other.tag != "Boundary")
{
Instantiate(explosion, transform.position, transform.rotation);
if (other.tag == "Player")
{
Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
gameController.endGame();
}
Destroy(other.gameObject);
Destroy(gameObject);
gameController.AddScore(scoreValue);
}
}
}
| kkurzhal/space-shooter | Assets/Scripts/DestroyByContact.cs | C# | bsd-3-clause | 1,125 |
/*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
******************************************************************************/
package org.caleydo.data.importer.tcga;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import org.apache.commons.compress.archivers.ArchiveEntry;
//import net.java.truevfs.access.TFile;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.lang.SystemUtils;
import org.caleydo.core.util.collection.Pair;
import org.caleydo.data.importer.tcga.model.TumorType;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Table;
import com.google.common.collect.TreeBasedTable;
import com.google.common.io.Closeables;
public final class FirehoseProvider {
private static final Logger log = Logger.getLogger(FirehoseProvider.class.getName());
private static final int LEVEL = 4;
private static final int LEVEL3 = 3;
private final TumorType tumor;
private final String tumorSample;
private final Date analysisRun;
private final Date dataRun;
private final File tmpAnalysisDir;
private final File tmpDataDir;
private final Settings settings;
private final Calendar relevantDate;
FirehoseProvider(TumorType tumor, Date analysisRun, Date dataRun, Settings settings) {
this.tumor = tumor;
this.relevantDate = Calendar.getInstance();
this.relevantDate.setTime(analysisRun);
this.tumorSample = guessTumorSample(tumor, this.relevantDate, settings);
this.analysisRun = analysisRun;
this.dataRun = dataRun;
this.settings = settings;
String tmpDir = settings.getTemporaryDirectory();
this.tmpAnalysisDir = createTempDirectory(tmpDir, analysisRun, tumor.getName());
this.tmpDataDir = createTempDirectory(tmpDir, dataRun, tumor.getName());
}
/**
* logic determining the tumor sample based on the analysis run
*
* @param tumor
* @param date
* @return
*/
private static String guessTumorSample(TumorType tumor, Calendar cal, Settings settings) {
if (settings.isAwgRun())
return tumor.toString();
if (cal.get(Calendar.YEAR) >= 2013 && tumor.toString().equalsIgnoreCase("SKCM"))
return tumor + "-TM";
if (cal.get(Calendar.YEAR) >= 2013 && tumor.toString().equalsIgnoreCase("LAML"))
return tumor + "-TB";
if (cal.get(Calendar.YEAR) >= 2013)
return tumor + "-TP";
return tumor.toString();
}
/**
* @return
*/
public boolean is2014Run() {
return relevantDate.get(Calendar.YEAR) >= 2014;
}
public boolean isPost2015() {
return relevantDate.get(Calendar.YEAR) >= 2015;
}
public boolean isPost2015908() {
return relevantDate.get(Calendar.YEAR) >= 2015 && relevantDate.get(Calendar.MONTH) >= Calendar.AUGUST;
}
public boolean isPost20140416() {
return relevantDate.get(Calendar.YEAR) >= 2014 && relevantDate.get(Calendar.MONTH) >= Calendar.APRIL;
}
private String getFileName(String suffix) {
return tumorSample + suffix;
}
private File createTempDirectory(String tmpOutputDirectory, Date run, String tumor) {
String runId;
if (run == null)
runId = "unknown";
else {
runId = Settings.formatClean(run);
}
return new File(tmpOutputDirectory + runId + SystemUtils.FILE_SEPARATOR + tumor + SystemUtils.FILE_SEPARATOR);
}
private Pair<TCGAFileInfo, Boolean> findStandardSampledClusteredFile(EDataSetType type) {
return Pair.make(extractAnalysisRunFile(".expclu.gct", type.getTCGAAbbr() + "_Clustering_CNMF", LEVEL), false);
}
public Pair<TCGAFileInfo, Boolean> findRPPAMatrixFile(boolean loadFullGenes) {
return findStandardSampledClusteredFile(EDataSetType.RPPA);
}
public Pair<TCGAFileInfo, Boolean> findMethylationMatrixFile(boolean loadFullGenes) {
return findStandardSampledClusteredFile(EDataSetType.methylation);
}
public Pair<TCGAFileInfo, Boolean> findmRNAMatrixFile(boolean loadFullGenes) {
if (loadFullGenes) {
TCGAFileInfo r;
if (isPost20140416()) {
r = extractDataRunFile(".medianexp.txt", "mRNA_Preprocess_Median", isPost2015() ? LEVEL3 : LEVEL);
} else {
r = extractAnalysisRunFile(getFileName(".medianexp.txt"), "mRNA_Preprocess_Median", LEVEL);
}
if (r != null)
return Pair.make(r, true);
}
return findStandardSampledClusteredFile(EDataSetType.mRNA);
}
public Pair<TCGAFileInfo, Boolean> findmRNAseqMatrixFile(boolean loadFullGenes) {
if (loadFullGenes) {
TCGAFileInfo r = extractDataRunFile(".uncv2.mRNAseq_RSEM_normalized_log2.txt", "mRNAseq_Preprocess",
isPost20140416() ? LEVEL3 : LEVEL, isPost2015908() ? 1 : 0);
if (r == null)
r = extractDataRunFile(".uncv1.mRNAseq_RPKM_log2.txt", "mRNAseq_Preprocess", isPost20140416() ? LEVEL3
: LEVEL);
if (r == null)
r = extractDataRunFile(".mRNAseq_RPKM_log2.txt", "mRNAseq_Preprocess", isPost20140416() ? 3 : LEVEL);
if (r != null) {
r = filterColumns(r, findStandardSampledClusteredFile(EDataSetType.mRNAseq));
return Pair.make(r, true);
}
}
return findStandardSampledClusteredFile(EDataSetType.mRNAseq);
}
private TCGAFileInfo filterColumns(TCGAFileInfo full, Pair<TCGAFileInfo, Boolean> sampled) {
File in = full.getFile();
File out = new File(in.getParentFile(), "F" + in.getName());
TCGAFileInfo r = new TCGAFileInfo(out, full.getArchiveURL(), full.getSourceFileName());
if (out.exists() && !settings.isCleanCache())
return r;
assert full != null;
if (sampled == null || sampled.getFirst() == null) {
log.severe("can't filter the full gene file: " + in + " - sampled not found");
return full;
}
// full: 1row, 2col
// sampled: 3row, 3col
Set<String> good = readGoodSamples(sampled.getFirst().getFile());
if (good == null)
return full;
try (BufferedReader fin = new BufferedReader(new FileReader(in)); PrintWriter w = new PrintWriter(out)) {
String[] header = fin.readLine().split("\t");
BitSet bad = filterCols(header, good);
{
StringBuilder b = new StringBuilder();
for (int i = bad.nextSetBit(0); i >= 0; i = bad.nextSetBit(i + 1))
b.append(' ').append(header[i]);
log.warning("remove bad samples of " + in + ":" + b);
}
w.append(header[0]);
for (int i = 1; i < header.length; ++i) {
if (bad.get(i))
continue;
w.append('\t').append(header[i]);
}
String line;
while ((line = fin.readLine()) != null) {
w.println();
int t = line.indexOf('\t');
w.append(line.subSequence(0, t));
int prev = t;
int i = 1;
for (t = line.indexOf('\t', t + 1); t >= 0; t = line.indexOf('\t', t + 1), ++i) {
if (!bad.get(i))
w.append(line.subSequence(prev, t));
prev = t;
}
if (!bad.get(i))
w.append(line.subSequence(prev, line.length()));
}
} catch (IOException e) {
log.log(Level.SEVERE, "can't filter full file: " + in, e);
}
return r;
}
/**
* @param header
* @param good
* @return
*/
private static BitSet filterCols(String[] header, Set<String> good) {
BitSet r = new BitSet(header.length);
for (int i = 0; i < header.length; ++i)
if (!good.contains(header[i]))
r.set(i);
return r;
}
private static Set<String> readGoodSamples(File file) {
// sampled: 3row, >=3col
try (BufferedReader r = new BufferedReader(new FileReader(file))) {
r.readLine();
r.readLine();
String line = r.readLine();
String[] samples = line.split("\t");
return ImmutableSet.copyOf(Arrays.copyOfRange(samples, 2, samples.length));
} catch (IOException e) {
log.log(Level.SEVERE, "can't read sample header from: " + file, e);
}
return null;
}
public Pair<TCGAFileInfo, Boolean> findmicroRNAMatrixFile(boolean loadFullGenes) {
if (loadFullGenes) {
TCGAFileInfo r = extractDataRunFile(".miR_expression.txt", "miR_Preprocess", isPost20140416() ? 3 : LEVEL);
if (r != null) {
r = filterColumns(r, findStandardSampledClusteredFile(EDataSetType.microRNA));
return Pair.make(r, true);
}
}
return findStandardSampledClusteredFile(EDataSetType.microRNA);
}
public Pair<TCGAFileInfo, Boolean> findmicroRNAseqMatrixFile(boolean loadFullGenes) {
if (loadFullGenes) {
TCGAFileInfo r = extractAnalysisRunFile(getFileName(".uncv2.miRseq_RSEM_normalized_log2.txt"),
"miRseq_Preprocess", isPost20140416() ? 3 : LEVEL);
if (r == null)
r = extractAnalysisRunFile(getFileName(".miRseq_RPKM_log2.txt"), "miRseq_Preprocess", LEVEL);
if (r != null) {
r = filterColumns(r, findStandardSampledClusteredFile(EDataSetType.microRNA));
return Pair.make(r, true);
}
}
return findStandardSampledClusteredFile(EDataSetType.microRNAseq);
}
public TCGAFileInfo findHiearchicalGrouping(EDataSetType type) {
return extractAnalysisRunFile(isPost2015() ? "clus.membership.txt" : getFileName(".allclusters.txt"),
type.getTCGAAbbr() + "_Clustering_Consensus" + (isPost2015() ? "_Plus" : ""), LEVEL);
}
public TCGAFileInfo findCNMFGroupingFile(EDataSetType type) {
return extractAnalysisRunFile(".membership.txt", type.getTCGAAbbr() + "_Clustering_CNMF", LEVEL);
}
public TCGAFileInfo findCopyNumberFile() {
return extractAnalysisRunFile("all_thresholded.by_genes.txt", "CopyNumber_Gistic2", LEVEL);
}
public TCGAFileInfo findClinicalDataFile() {
return extractDataRunFile(".clin.merged.txt", "Merge_Clinical", 1);
}
public TCGAFileInfo findMutSigReport() {
return extractAnalysisRunFile(getFileName(".sig_genes.txt"), "MutSigNozzleReportCV", LEVEL);
}
public Pair<TCGAFileInfo, Integer> findMutationFile() {
int startColumn = 8;
TCGAFileInfo mutationFile = null;
if (relevantDate.get(Calendar.YEAR) < 2013) { // test only for the <= 2012
mutationFile = extractAnalysisRunFile(getFileName(".per_gene.mutation_counts.txt"),
"Mutation_Significance", LEVEL);
if (mutationFile == null)
mutationFile = extractAnalysisRunFile(getFileName(".per_gene.mutation_counts.txt"), "MutSigRun2.0",
LEVEL);
}
if (mutationFile == null) {
// TODO always the -TP version
TCGAFileInfo maf = null;
if (!this.settings.isAwgRun()) {
maf = extractAnalysisRunFile(tumor + "-TP.final_analysis_set.maf", "MutSigNozzleReport2.0", LEVEL);
} else {
maf = extractAnalysisRunFile(tumor + ".final_analysis_set.maf", "MutSigNozzleReport2.0", LEVEL);
}
if (maf != null) {
return Pair.make(
new TCGAFileInfo(parseMAF(maf.getFile()), maf.getArchiveURL(), maf.getSourceFileName()), 1);
}
}
return Pair.make(mutationFile, startColumn);
}
/**
* @return
*/
public String getReportURL() {
return settings.getReportUrl(analysisRun, tumor);
}
private TCGAFileInfo extractAnalysisRunFile(String fileName, String pipelineName, int level) {
return extractFile(fileName, pipelineName, level, true, false, 0);
}
private TCGAFileInfo extractDataRunFile(String fileName, String pipelineName, int level, int flag) {
return extractFile(fileName, pipelineName, level, false, true, flag);
}
private TCGAFileInfo extractDataRunFile(String fileName, String pipelineName, int level) {
return extractFile(fileName, pipelineName, level, false, true, 0);
}
private TCGAFileInfo extractFile(String fileName, String pipelineName, int level, boolean isAnalysisRun,
boolean hasTumor, int flag) {
Date id = isAnalysisRun ? analysisRun : dataRun;
String label = "unknown";
// extract file to temp directory and return path to file
URL url;
try {
if (isAnalysisRun)
url = settings.getAnalysisURL(id, tumor, tumorSample, pipelineName, level);
else
url = settings.getDataURL(id, tumor, tumorSample, pipelineName, level, flag);
String urlString = url.getPath();
label = urlString.substring(urlString.lastIndexOf('/') + 1, urlString.length());
File outputDir = new File(isAnalysisRun ? tmpAnalysisDir : tmpDataDir, label);
outputDir.mkdirs();
return extractFileFromTarGzArchive(url, fileName, outputDir, hasTumor);
} catch (MalformedURLException e) {
log.log(Level.SEVERE, "invalid url generated from: " + id + " " + tumor + " " + tumorSample + " "
+ pipelineName + " " + level);
return null;
}
}
private TCGAFileInfo extractFileFromTarGzArchive(URL inUrl, String fileToExtract, File outputDirectory,
boolean hasTumor) {
log.info(inUrl + " download and extract: " + fileToExtract);
File targetFile = new File(outputDirectory, fileToExtract);
// use cached
if (targetFile.exists() && !settings.isCleanCache()) {
log.fine(inUrl + " cache hit");
return new TCGAFileInfo(targetFile, inUrl, targetFile.getName());
}
File notFound = new File(outputDirectory, fileToExtract + "-notfound");
if (notFound.exists() && !settings.isCleanCache()) {
log.warning(inUrl + " marked as not found");
return null;
}
String alternativeName = fileToExtract;
if (hasTumor) {
alternativeName = "/" + tumor.getBaseName() + fileToExtract;
fileToExtract = "/" + tumor + fileToExtract;
}
TarArchiveInputStream tarIn = null;
OutputStream out = null;
try {
// copy and buffer the whole file
InputStream in = new BufferedInputStream(inUrl.openStream());
// CASE 1 we use the truevfs library
// String tmpFile = targetFile.getAbsolutePath() + ".tmp.tar.gz";
// out = new BufferedOutputStream(new FileOutputStream(tmpFile));
// ByteStreams.copy(in, out);
// out.close();
// TFile archive = new TFile(tmpFile);
// TFile act = null;
// outer: for (TFile member : archive.listFiles()) {
// for (TFile mm : member.listFiles()) {
// String name = member.getName() + '/' + mm.getName();
// System.out.println(name);
// if (name.endsWith(fileToExtract) || name.endsWith(alternativeName)) {
// act = mm;
// break outer;
// }
// }
// }
//
// if (act != null)
// act.cp(targetFile);
// if (act == null) // no entry found
// throw new FileNotFoundException("no entry named: " + fileToExtract + " found");
// CASE 2 we use apache commons
tarIn = new TarArchiveInputStream(new GZIPInputStream(in));
// search the correct entry
ArchiveEntry act = tarIn.getNextEntry();
while (act != null && !act.getName().endsWith(fileToExtract) && !act.getName().endsWith(alternativeName)) {
System.out.println(act.getName());
act = tarIn.getNextEntry();
}
if (act == null) // no entry found
throw new FileNotFoundException("no entry named: " + fileToExtract + " found");
byte[] buf = new byte[4096];
int n;
targetFile.getParentFile().mkdirs();
// use a temporary file to recognize if we have aborted between run
String tmpFile = targetFile.getAbsolutePath() + ".tmp";
out = new BufferedOutputStream(new FileOutputStream(tmpFile));
while ((n = tarIn.read(buf, 0, 4096)) > -1)
out.write(buf, 0, n);
out.close();
Files.move(new File(tmpFile).toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
log.info(inUrl + " extracted " + fileToExtract);
return new TCGAFileInfo(targetFile, inUrl, targetFile.getName());
} catch (FileNotFoundException e) {
log.log(Level.WARNING, inUrl + " can't extract" + fileToExtract + ": file not found", e);
// file was not found, create a marker to remember this for quicker checks
notFound.getParentFile().mkdirs();
try {
notFound.createNewFile();
} catch (IOException e1) {
log.log(Level.WARNING, inUrl + " can't create not-found marker", e);
}
return null;
} catch (Exception e) {
log.log(Level.SEVERE, inUrl + " can't extract" + fileToExtract + ": " + e.getMessage(), e);
return null;
} finally {
Closeables.closeQuietly(tarIn);
Closeables.closeQuietly(out);
}
}
private static File parseMAF(File maf) {
File out = new File(maf.getParentFile(), "P" + maf.getName());
if (out.exists())
return out;
log.fine(maf.getAbsolutePath() + " parsing maf file");
final String TAB = "\t";
CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
decoder.onMalformedInput(CodingErrorAction.IGNORE);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(maf.toPath()),
decoder))) {
List<String> header = Arrays.asList(reader.readLine().split(TAB));
int geneIndex = header.indexOf("Hugo_Symbol");
int sampleIndex = header.indexOf("Tumor_Sample_Barcode");
// gene x sample x mutated
Table<String, String, Boolean> mutated = TreeBasedTable.create();
String line = null;
// int i = 1;
while ((line = reader.readLine()) != null) {
String[] columns = line.split(TAB);
mutated.put(columns[geneIndex], columns[sampleIndex], Boolean.TRUE);
// System.out.println(i++);
}
File tmp = new File(out.getParentFile(), out.getName() + ".tmp");
PrintWriter w = new PrintWriter(tmp);
w.append("Hugo_Symbol");
List<String> cols = new ArrayList<>(mutated.columnKeySet());
for (String sample : cols) {
w.append(TAB).append(sample);
}
w.println();
Set<String> rows = mutated.rowKeySet();
for (String gene : rows) {
w.append(gene);
for (String sample : cols) {
w.append(TAB).append(mutated.contains(gene, sample) ? '1' : '0');
}
w.println();
}
w.close();
Files.move(tmp.toPath(), out.toPath(), StandardCopyOption.REPLACE_EXISTING);
log.fine(maf.getAbsolutePath() + " parsed maf file stats: " + mutated.size() + " " + rows.size() + " "
+ cols.size());
return out;
} catch (IOException e) {
log.log(Level.SEVERE, maf.getAbsolutePath() + " maf parsing error: " + e.getMessage(), e);
}
return null;
}
public static void main(String[] args) {
File file = new File(
"/home/alexsb/Dropbox/Caleydo/data/ccle/CCLE_hybrid_capture1650_hg19_NoCommonSNPs_CDS_2012.05.07.maf");
file = parseMAF(file);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("FirehoseProvider[");
builder.append(tumor);
builder.append("/");
builder.append(tumorSample);
builder.append("@");
builder.append(Settings.format(analysisRun));
builder.append(",");
builder.append(Settings.format(dataRun));
builder.append("]");
return builder.toString();
}
}
| Caleydo/caleydo | org.caleydo.data.importer/src/org/caleydo/data/importer/tcga/FirehoseProvider.java | Java | bsd-3-clause | 19,060 |
.pragma library
var tooltip = null
function create(name, value, meta, defaultMargins, x, y, parent) {
var component = Qt.createComponent("ToolTip.qml")
var properties = {}
properties.name = name
properties.value = value
properties.meta = meta
properties.defaultMargins = defaultMargins
properties.parentWidth = parent.width
properties.parentHeight = parent.height
tooltip = component.createObject(parent, properties);
if (tooltip === null)
console.error("error creating tooltip: " + component.errorString())
tooltip.x = x
tooltip.y = y
return tooltip
}
function createHelp(helpText, defaultMargins, x, y, parent) {
var component = Qt.createComponent("Help.qml")
var properties = {}
properties.helpText = helpText
properties.defaultMargins = defaultMargins
tooltip = component.createObject(parent, properties);
if (tooltip === null)
console.error("error creating tooltip: " + component.errorString())
tooltip.x = x
tooltip.y = y
return tooltip
}
function destroy() {
if (tooltip){
tooltip.destroy()
tooltip = null
}
}
| e1528532/libelektra | src/tools/qt-gui/qml/TooltipCreator.js | JavaScript | bsd-3-clause | 1,067 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using NServiceKit.DataAnnotations;
using NServiceKit.DesignPatterns.Model;
namespace NServiceKit.OrmLite.MySql.Tests
{
/// <summary>A date time column test.</summary>
[TestFixture]
public class DateTimeColumnTest
: OrmLiteTestBase
{
/// <summary>Can create table containing date time column.</summary>
[Test]
public void Can_create_table_containing_DateTime_column()
{
using (var db = OpenDbConnection())
{
db.CreateTable<Analyze>(true);
}
}
/// <summary>Can store date time value.</summary>
[Test]
public void Can_store_DateTime_Value()
{
using (var db = OpenDbConnection())
{
db.CreateTable<Analyze>(true);
var obj = new Analyze {
Id = 1,
Date = DateTime.Now,
Url = "http://www.google.com"
};
db.Save(obj);
}
}
/// <summary>Can store and retrieve date time value.</summary>
[Test]
public void Can_store_and_retrieve_DateTime_Value()
{
using (var db = OpenDbConnection())
{
db.CreateTable<Analyze>(true);
var obj = new Analyze {
Id = 1,
Date = DateTime.Now,
Url = "http://www.google.com"
};
db.Save(obj);
var id = (int)db.GetLastInsertId();
var target = db.QueryById<Analyze>(id);
Assert.IsNotNull(target);
Assert.AreEqual(id, target.Id);
Assert.AreEqual(obj.Date.ToString("yyyy-MM-dd HH:mm:ss"), target.Date.ToString("yyyy-MM-dd HH:mm:ss"));
Assert.AreEqual(obj.Url, target.Url);
}
}
/// <summary>
/// Provided by RyogoNA in issue #38
/// https://github.com/ServiceStack/ServiceStack.OrmLite/issues/38#issuecomment-4625178.
/// </summary>
[Alias("Analyzes")]
public class Analyze : IHasId<int>
{
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
[AutoIncrement]
[PrimaryKey]
public int Id
{
get;
set;
}
/// <summary>Gets or sets the Date/Time of the date.</summary>
/// <value>The date.</value>
[Alias("AnalyzeDate")]
public DateTime Date
{
get;
set;
}
/// <summary>Gets or sets URL of the document.</summary>
/// <value>The URL.</value>
public string Url
{
get;
set;
}
}
}
}
| NServiceKit/NServiceKit.OrmLite | src/NServiceKit.OrmLite.MySql.Tests/DateTimeColumnTest.cs | C# | bsd-3-clause | 3,031 |
#ifdef STAN_OPENCL
#include <stan/math/opencl/rev.hpp>
#include <stan/math.hpp>
#include <gtest/gtest.h>
#include <test/unit/math/opencl/util.hpp>
#include <vector>
TEST(ProbDistributionsDoubleExponential, error_checking) {
int N = 3;
Eigen::VectorXd y(N);
y << -0.3, 0.8, 1.5;
Eigen::VectorXd y_size(N - 1);
y_size << 0.3, 0.8;
Eigen::VectorXd y_value(N);
y_value << 0.3, INFINITY, 0.5;
Eigen::VectorXd mu(N);
mu << 0.3, 0.8, -1.7;
Eigen::VectorXd mu_size(N - 1);
mu_size << 0.3, 0.8;
Eigen::VectorXd mu_value(N);
mu_value << 0.3, INFINITY, 0.5;
Eigen::VectorXd sigma(N);
sigma << 0.3, 0.8, 4.2;
Eigen::VectorXd sigma_size(N - 1);
sigma_size << 0.3, 0.8;
Eigen::VectorXd sigma_value(N);
sigma_value << 0.3, -0.8, 0.5;
stan::math::matrix_cl<double> y_cl(y);
stan::math::matrix_cl<double> y_size_cl(y_size);
stan::math::matrix_cl<double> y_value_cl(y_value);
stan::math::matrix_cl<double> mu_cl(mu);
stan::math::matrix_cl<double> mu_size_cl(mu_size);
stan::math::matrix_cl<double> mu_value_cl(mu_value);
stan::math::matrix_cl<double> sigma_cl(sigma);
stan::math::matrix_cl<double> sigma_size_cl(sigma_size);
stan::math::matrix_cl<double> sigma_value_cl(sigma_value);
EXPECT_NO_THROW(stan::math::double_exponential_lpdf(y_cl, mu_cl, sigma_cl));
EXPECT_THROW(stan::math::double_exponential_lpdf(y_size_cl, mu_cl, sigma_cl),
std::invalid_argument);
EXPECT_THROW(stan::math::double_exponential_lpdf(y_cl, mu_size_cl, sigma_cl),
std::invalid_argument);
EXPECT_THROW(stan::math::double_exponential_lpdf(y_cl, mu_cl, sigma_size_cl),
std::invalid_argument);
EXPECT_THROW(stan::math::double_exponential_lpdf(y_value_cl, mu_cl, sigma_cl),
std::domain_error);
EXPECT_THROW(stan::math::double_exponential_lpdf(y_cl, mu_value_cl, sigma_cl),
std::domain_error);
EXPECT_THROW(stan::math::double_exponential_lpdf(y_cl, mu_cl, sigma_value_cl),
std::domain_error);
}
auto double_exponential_lpdf_functor
= [](const auto& n, const auto& mu, const auto& sigma) {
return stan::math::double_exponential_lpdf(n, mu, sigma);
};
auto double_exponential_lpdf_functor_propto
= [](const auto& n, const auto& mu, const auto& sigma) {
return stan::math::double_exponential_lpdf<true>(n, mu, sigma);
};
TEST(ProbDistributionsDoubleExponential, opencl_matches_cpu_small) {
int N = 3;
Eigen::VectorXd y(N);
y << -0.3, 0.8, 1.5;
Eigen::VectorXd mu(N);
mu << 0.3, 0.8, -1.7;
Eigen::VectorXd sigma(N);
sigma << 0.3, 0.8, 4.2;
stan::math::test::compare_cpu_opencl_prim_rev(double_exponential_lpdf_functor,
y, mu, sigma);
stan::math::test::compare_cpu_opencl_prim_rev(
double_exponential_lpdf_functor_propto, y, mu, sigma);
stan::math::test::compare_cpu_opencl_prim_rev(
double_exponential_lpdf_functor, y.transpose().eval(),
mu.transpose().eval(), sigma.transpose().eval());
stan::math::test::compare_cpu_opencl_prim_rev(
double_exponential_lpdf_functor_propto, y.transpose().eval(),
mu.transpose().eval(), sigma.transpose().eval());
}
TEST(ProbDistributionsDoubleExponential, opencl_broadcast_y) {
int N = 3;
double y_scal = -2.3;
Eigen::VectorXd mu(N);
mu << 0.3, 0.8, -1.7;
Eigen::VectorXd sigma(N);
sigma << 0.3, 0.8, 4.2;
stan::math::test::test_opencl_broadcasting_prim_rev<0>(
double_exponential_lpdf_functor, y_scal, mu, sigma);
stan::math::test::test_opencl_broadcasting_prim_rev<0>(
double_exponential_lpdf_functor_propto, y_scal, mu, sigma);
stan::math::test::test_opencl_broadcasting_prim_rev<0>(
double_exponential_lpdf_functor, y_scal, mu.transpose().eval(), sigma);
stan::math::test::test_opencl_broadcasting_prim_rev<0>(
double_exponential_lpdf_functor_propto, y_scal, mu,
sigma.transpose().eval());
}
TEST(ProbDistributionsDoubleExponential, opencl_broadcast_mu) {
int N = 3;
Eigen::VectorXd y(N);
y << 0.3, 0.8, -1.7;
double mu_scal = -2.3;
Eigen::VectorXd sigma(N);
sigma << 0.3, 0.8, 4.2;
stan::math::test::test_opencl_broadcasting_prim_rev<1>(
double_exponential_lpdf_functor, y, mu_scal, sigma);
stan::math::test::test_opencl_broadcasting_prim_rev<1>(
double_exponential_lpdf_functor_propto, y, mu_scal, sigma);
stan::math::test::test_opencl_broadcasting_prim_rev<1>(
double_exponential_lpdf_functor, y.transpose().eval(), mu_scal, sigma);
stan::math::test::test_opencl_broadcasting_prim_rev<1>(
double_exponential_lpdf_functor_propto, y, mu_scal,
sigma.transpose().eval());
}
TEST(ProbDistributionsDoubleExponential, opencl_broadcast_sigma) {
int N = 3;
Eigen::VectorXd y(N);
y << 0.3, 0.8, -1.7;
Eigen::VectorXd mu(N);
mu << 0.3, 0.8, 4.2;
double sigma_scal = 2.3;
stan::math::test::test_opencl_broadcasting_prim_rev<2>(
double_exponential_lpdf_functor, y, mu, sigma_scal);
stan::math::test::test_opencl_broadcasting_prim_rev<2>(
double_exponential_lpdf_functor_propto, y, mu, sigma_scal);
stan::math::test::test_opencl_broadcasting_prim_rev<2>(
double_exponential_lpdf_functor, y.transpose().eval(), mu, sigma_scal);
stan::math::test::test_opencl_broadcasting_prim_rev<2>(
double_exponential_lpdf_functor_propto, y, mu.transpose().eval(),
sigma_scal);
}
TEST(ProbDistributionsDoubleExponential, opencl_matches_cpu_big) {
int N = 153;
Eigen::Matrix<double, Eigen::Dynamic, 1> y
= Eigen::Array<double, Eigen::Dynamic, 1>::Random(N, 1);
Eigen::Matrix<double, Eigen::Dynamic, 1> mu
= Eigen::Array<double, Eigen::Dynamic, 1>::Random(N, 1);
Eigen::Matrix<double, Eigen::Dynamic, 1> sigma
= Eigen::Array<double, Eigen::Dynamic, 1>::Random(N, 1).abs();
stan::math::test::compare_cpu_opencl_prim_rev(double_exponential_lpdf_functor,
y, mu, sigma);
stan::math::test::compare_cpu_opencl_prim_rev(
double_exponential_lpdf_functor_propto, y, mu, sigma);
stan::math::test::compare_cpu_opencl_prim_rev(
double_exponential_lpdf_functor, y.transpose().eval(),
mu.transpose().eval(), sigma.transpose().eval());
stan::math::test::compare_cpu_opencl_prim_rev(
double_exponential_lpdf_functor_propto, y.transpose().eval(),
mu.transpose().eval(), sigma.transpose().eval());
}
TEST(ProbDistributionsDoubleExponential, opencl_y_mu_scalar) {
int N = 3;
double y = -0.3;
double mu = 0.8;
Eigen::VectorXd sigma(N);
sigma << 0.3, 0.8, 4.2;
stan::math::test::compare_cpu_opencl_prim_rev(double_exponential_lpdf_functor,
y, mu, sigma);
stan::math::test::compare_cpu_opencl_prim_rev(
double_exponential_lpdf_functor_propto, y, mu, sigma);
}
#endif
| stan-dev/math | test/unit/math/opencl/rev/double_exponential_lpdf_test.cpp | C++ | bsd-3-clause | 6,853 |
<?php
$I = new AcceptanceTester\AccountSteps($scenario);
$I->wantTo('log in using an existing account and see the result');
$I->amOnPage(\LoginPage::$URL);
$I->login('demo', 'demo1234');
$I->dontSee('Incorrect username or password.');
| nordsoftware/yii2-account | tests/codeception/acceptance/02-LoginCept.php | PHP | bsd-3-clause | 235 |
<?php defined('SYSPATH') or die('No direct script access.'); ?>
2012-05-21 08:47:09 --- ERROR: HTTP_Exception_404 [ 404 ]: Unable to find a route to match the URI: favicon.ico ~ SYSPATH/classes/kohana/request.php [ 1126 ]
2012-05-21 08:47:09 --- STRACE: HTTP_Exception_404 [ 404 ]: Unable to find a route to match the URI: favicon.ico ~ SYSPATH/classes/kohana/request.php [ 1126 ]
--
#0 /Volumes/Files/Sites/darth/bane/index.php(103): Kohana_Request->execute()
#1 {main}
2012-05-21 15:44:38 --- ERROR: Kohana_Exception [ 0 ]: A valid cookie salt is required. Please set Cookie::$salt. ~ SYSPATH/classes/kohana/cookie.php [ 152 ]
2012-05-21 15:44:38 --- STRACE: Kohana_Exception [ 0 ]: A valid cookie salt is required. Please set Cookie::$salt. ~ SYSPATH/classes/kohana/cookie.php [ 152 ]
--
#0 /Volumes/Files/Sites/darth/bane/system/classes/kohana/cookie.php(115): Kohana_Cookie::salt('campaign_code', '200')
#1 /Volumes/Files/Sites/darth/bane/application/classes/controller/public/solutions.php(7): Kohana_Cookie::set('campaign_code', '200')
#2 [internal function]: Controller_Public_Solutions->before()
#3 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request/client/internal.php(103): ReflectionMethod->invoke(Object(Controller_Public_Solutions))
#4 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request/client.php(64): Kohana_Request_Client_Internal->execute_request(Object(Request))
#5 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request.php(1138): Kohana_Request_Client->execute(Object(Request))
#6 /Volumes/Files/Sites/darth/bane/index.php(103): Kohana_Request->execute()
#7 {main}
2012-05-21 15:44:43 --- ERROR: Kohana_Exception [ 0 ]: A valid cookie salt is required. Please set Cookie::$salt. ~ SYSPATH/classes/kohana/cookie.php [ 152 ]
2012-05-21 15:44:43 --- STRACE: Kohana_Exception [ 0 ]: A valid cookie salt is required. Please set Cookie::$salt. ~ SYSPATH/classes/kohana/cookie.php [ 152 ]
--
#0 /Volumes/Files/Sites/darth/bane/system/classes/kohana/cookie.php(115): Kohana_Cookie::salt('campaign_code', '200')
#1 /Volumes/Files/Sites/darth/bane/application/classes/controller/public/solutions.php(7): Kohana_Cookie::set('campaign_code', '200')
#2 [internal function]: Controller_Public_Solutions->before()
#3 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request/client/internal.php(103): ReflectionMethod->invoke(Object(Controller_Public_Solutions))
#4 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request/client.php(64): Kohana_Request_Client_Internal->execute_request(Object(Request))
#5 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request.php(1138): Kohana_Request_Client->execute(Object(Request))
#6 /Volumes/Files/Sites/darth/bane/index.php(103): Kohana_Request->execute()
#7 {main}
2012-05-21 15:46:01 --- ERROR: Kohana_Exception [ 0 ]: A valid cookie salt is required. Please set Cookie::$salt. ~ SYSPATH/classes/kohana/cookie.php [ 152 ]
2012-05-21 15:46:01 --- STRACE: Kohana_Exception [ 0 ]: A valid cookie salt is required. Please set Cookie::$salt. ~ SYSPATH/classes/kohana/cookie.php [ 152 ]
--
#0 /Volumes/Files/Sites/darth/bane/application/classes/controller/public/solutions.php(7): Kohana_Cookie::salt('campaign_code', '200')
#1 [internal function]: Controller_Public_Solutions->before()
#2 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request/client/internal.php(103): ReflectionMethod->invoke(Object(Controller_Public_Solutions))
#3 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request/client.php(64): Kohana_Request_Client_Internal->execute_request(Object(Request))
#4 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request.php(1138): Kohana_Request_Client->execute(Object(Request))
#5 /Volumes/Files/Sites/darth/bane/index.php(103): Kohana_Request->execute()
#6 {main}
2012-05-21 23:27:16 --- ERROR: HTTP_Exception_404 [ 404 ]: Unable to find a route to match the URI: favicon.ico ~ SYSPATH/classes/kohana/request.php [ 1126 ]
2012-05-21 23:27:16 --- STRACE: HTTP_Exception_404 [ 404 ]: Unable to find a route to match the URI: favicon.ico ~ SYSPATH/classes/kohana/request.php [ 1126 ]
--
#0 /Volumes/Files/Sites/darth/bane/index.php(103): Kohana_Request->execute()
#1 {main}
2012-05-21 23:27:47 --- ERROR: HTTP_Exception_404 [ 404 ]: Unable to find a route to match the URI: assets/js/plugins/themes/apple/style.css ~ SYSPATH/classes/kohana/request.php [ 1126 ]
2012-05-21 23:27:47 --- STRACE: HTTP_Exception_404 [ 404 ]: Unable to find a route to match the URI: assets/js/plugins/themes/apple/style.css ~ SYSPATH/classes/kohana/request.php [ 1126 ]
--
#0 /Volumes/Files/Sites/darth/bane/index.php(103): Kohana_Request->execute()
#1 {main}
2012-05-21 23:35:43 --- ERROR: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ]
2012-05-21 23:35:43 --- STRACE: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ]
--
#0 [internal function]: Kohana_Core::shutdown_handler()
#1 {main}
2012-05-21 23:36:07 --- ERROR: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ]
2012-05-21 23:36:07 --- STRACE: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ]
--
#0 [internal function]: Kohana_Core::shutdown_handler()
#1 {main}
2012-05-21 23:36:14 --- ERROR: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ]
2012-05-21 23:36:14 --- STRACE: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ]
--
#0 [internal function]: Kohana_Core::shutdown_handler()
#1 {main}
2012-05-21 23:36:18 --- ERROR: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ]
2012-05-21 23:36:18 --- STRACE: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ]
--
#0 [internal function]: Kohana_Core::shutdown_handler()
#1 {main}
2012-05-21 23:36:22 --- ERROR: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ]
2012-05-21 23:36:22 --- STRACE: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ]
--
#0 [internal function]: Kohana_Core::shutdown_handler()
#1 {main}
2012-05-21 23:37:28 --- ERROR: HTTP_Exception_404 [ 404 ]: Unable to find a route to match the URI: assets/js/plugins/themes/apple/style.css ~ SYSPATH/classes/kohana/request.php [ 1126 ]
2012-05-21 23:37:28 --- STRACE: HTTP_Exception_404 [ 404 ]: Unable to find a route to match the URI: assets/js/plugins/themes/apple/style.css ~ SYSPATH/classes/kohana/request.php [ 1126 ]
--
#0 /Volumes/Files/Sites/darth/bane/index.php(103): Kohana_Request->execute()
#1 {main} | jneslen/matrix42 | application/logs/2012/05/21.php | PHP | bsd-3-clause | 7,013 |
<div class="container">
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\TravellerPhoto */
$this->title = Yii::t('app', 'Update Traveller Languages');
?>
<div class="traveller-photo-create">
<div class="col-md-11 col-md-offset-1">
<ul class="traveller-steps">
<li id="active-breadcrumbs">Account Info</li>
<li id="active-breadcrumbs">Profile</li>
<li id="active-breadcrumbs">About You</li>
<li>Gallery</li>
<li>Get Verified</li>
</ul>
</div>
<div class="col-md-10 col-md-offset-1">
<div class="travellers-form">
<div class="row">
<div class="col-lg-8">
<h1 class="Step-title">About You > Languages </h1>
<?=
$this->render('_form', [
'model' => $model,
'traveller_id' => $traveller_id,
'Languages' => $Languages,
])
?>
</div>
<div class="col-lg-4 join-message">
<h3> Thanks You for joining Staylance!</h3>
<p>Welcome our community,we wish you a wonderful time. Please complete your profile</p>
<br><br><br><br><br><br><br>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="form-group wrap_container">
<div class="row">
<div class="col-md-4">
<?php if (count($travellerprofile) > 0) { ?>
<a href="<?php echo Url::to(['/travellersprofile/update', 'id' => $travellerprofile->id]); ?>" class="btn btn-arrow">
<i class="fa fa-arrow-left"></i>
</a>
<a href="<?php echo Url::to(['/travellersprofile/update', 'id' => $travellerprofile->id]); ?>" class="btn btn-back-text">back</a>
<?php } else { ?>
<a href="<?php echo Url::to(['/travellersprofile/create', 'traveller_id' => $traveller_id]); ?>" class="btn btn-arrow">
<i class="fa fa-arrow-left"></i>
</a>
<a href="<?php echo Url::to(['/travellersprofile/create', 'traveller_id' => $traveller_id]); ?>" class="btn btn-back-text">back</a>
<?php } ?>
</div>
<div class="col-md-4 align-center">
<?php if (count($travellerfood) > 0) { ?>
<a href="<?php echo Url::to(['/travellersfood/update', 'id' => $travellerfood->id]); ?>" class="btn btn-success btn-skip">I will do this later</a>
<?php } else { ?>
<a href="<?php echo Url::to(['/travellersfood/create', 'traveller_id' => $traveller_id]); ?>" class="btn btn-success btn-skip">I will do this later</a>
<?php } ?>
</div>
<div class="right-align col-md-4">
<?= Html::submitButton(Yii::t('app', 'next step'), ['class' => 'btn btn-next-text btn-arrow']) ?>
<?= Html::submitButton(Yii::t('app', '<i class="fa fa-arrow-right"></i>'), ['class' => 'btn btn-arrow']) ?>
<?php ActiveForm::end(); ?>
</div>
</div>
| Junaid-Farid/staylance-new | frontend/views/travellerslanguages/update.php | PHP | bsd-3-clause | 3,419 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml.XPath;
namespace JeremyClifton.Data.TestAutomator
{
public class TestResult
{
private XElement _data;
public XElement Data
{
get { return _data; }
}
private List<string> _messages = new List<string>();
public List<string> Messages
{
get { return _messages; }
}
private string _output;
public string Output
{
get { return _output; }
}
public string RawXml
{
get { return _data.ToString(); }
}
public TestResult()
{
throw new Exception("Not implemented!");
}
public TestResult(XElement xml)
{
_data = xml;
InitMessages();
InitOutput();
}
private void InitMessages()
{
foreach (XElement el in _data.XPathSelectElements("//messages/message"))
{
_messages.Add(el.Value);
}
}
private void InitOutput()
{
XElement el = _data.XPathSelectElement("//output");
if (el != null)
{
_output = el.Value;
}
}
}
}
| jeremyclifton/sitecore-testing-automator | Data/TestAutomator/TestResult.cs | C# | bsd-3-clause | 1,373 |
<?php
/**
* StanfordDatabase is an extension of MySQLi intended to assist developers in creating secure database-enabled applications
*
* Copyright 2008,2009 Board of Trustees, Leland Stanford Jr. University
* See LICENSE for licensing terms.
*
*/
class StanfordDatabase extends MySQLi {
const VERSION = "1.0.0";
const HOST_STANDARD = "mysql-user.stanford.edu";
const HOST_ENCRYPTED = "127.0.0.1";
private $username; // Username
private $password; // Password
private $database; // Name of database
private $host; // Host
private $connected; // Connected to database?
private $mysql_sessions; // MySQL-based sessions enabled?
/**
* Create a new StanfordDatabase object and initialize mysqli
*
* @param string username The username used to connect to the database
* @param string password The password used to connect to the database
* @param string database The name of the database
* @param boolean use_encryption Use encryption? True or false. Default is false.
*/
function __construct($username='', $password='', $database='', $use_encryption=false) {
$this->username = $username;
$this->password = $password;
$this->database = $database;
// Connect using a different host address depending on the need for full encryption
if($use_encryption == true) {
$this->host = StanfordDatabase::HOST_ENCRYPTED;
}
else {
$this->host = StanfordDatabase::HOST_STANDARD;
}
// Important - initialize the mysqli object
$link = parent::init();
}
/**
* Destructor closes the database connection
*/
function __destruct() {
$this->close();
}
/**
* Gets the version number of the class
*
* @return string The version number
*/
function get_version() {
return self::VERSION;
}
/**
* Sets the name of the database
*
* @param string database The name of the database
*/
function set_database($database) {
$this->database = $database;
}
/**
* Sets the username used to connect to the database
*
* @param string username The username
*/
function set_username($username) {
$this->username = $username;
}
/**
* Sets the password used to connect to the database
*
* @param string password The password
*/
function set_password($password) {
$this->password = $password;
}
/**
* Sets the host to connect to depending on whether or not to use encryption
*
* @param boolean value Should be set to true if using encryption, false to disable encryption.
*/
function use_encryption($value=true) {
// Must call this function before connecting
if($this->is_connected() == true) {
throw new Exception("StanfordDatabase error -- call use_encryption() before connect()");
}
if($value == true) {
$this->host = StanfordDatabase::HOST_ENCRYPTED;
}
else {
$this->host = StanfordDatabase::HOST_STANDARD;
}
}
/**
* Connects to the database using the given credentials.
*/
function connect() {
// Check if already connected
if($this->is_connected() == true) return true;
// Check for necessary information
if($this->host == '' || $this->database == '' || $this->username == '') {
throw new Exception("Cannot connect to the database -- missing required information");
}
// Try to connect
$result = @parent::real_connect($this->host, $this->username, $this->password, $this->database);
// Check the result
if($result == true) {
// Connected successfully
$this->connected = true;
return true;
}
else {
// Error
throw new Exception("Cannot connect to the database -- " . mysqli_connect_error());
}
}
/**
* Closes the connection to the database
*/
function close() {
// Check if connected
if($this->is_connected()) {
// Check if disconnected successfully
if(parent::close() == true) {
// Set connected to false and return true
$this->connected = false;
return true;
}
}
// Unable to disconnect
return false;
}
/**
* Checks if MySQL is connected
*
* @return boolean True if connected, false otherwise
*/
function is_connected() {
return $this->connected;
}
/**
* Checks if the connection is encrypted
*
* @return boolean True if encrypted, false otherwise
*/
function connection_is_encrypted() {
if($this->host == self::HOST_ENCRYPTED) {
return true;
}
else {
return false;
}
}
/**
* Sets up MySQL-based sessions. Database settings must be configured before calling this function.
*
* @date December 3, 2008
*
* @throws An Exception when database cannot be connected to or when creating a new php_sessions table fails
*
* @return boolean True on success, exception on failure
*/
function setup_mysql_sessions() {
// Connect to database
$this->connect();
// Check connection
if($this->is_connected() == false) {
throw new Exception("Unable to set up MySQL-based sessions -- cannot connect to database.");
}
// Check if table exists
$sql = "SHOW TABLES LIKE 'php_sessions'";
$result = $this->query($sql);
// If not..
if(mysqli_num_rows($result) == 0) {
// Create table
$create_table = "CREATE TABLE php_sessions (
sessionid varchar(40) BINARY NOT NULL DEFAULT '',
expiry int(10) UNSIGNED NOT NULL DEFAULT '0',
value text NOT NULL,
PRIMARY KEY (sessionid)
) TYPE=MyISAM COMMENT='Sessions';";
$result = $this->query($create_table);
if($result == false) {
throw new Exception("Unable to set up MySQL-based sessions -- cannot create new table 'php_sessions.'");
}
}
// The variables below are used by an external script that enables MySQL-based sessions
// They are required so that the other script can connect to the database
global $STANFORD_DB, $STANFORD_DB_USER, $STANFORD_DB_PASS, $STANFORD_DB_HOST;
$STANFORD_DB = $this->database;
$STANFORD_DB_USER = $this->username;
$STANFORD_DB_PASS = $this->password;
$STANFORD_DB_HOST = $this->host;
// Include custom session handler functions stored on the server
require_once '/etc/php5/init/sessions.php';
// Set MySQL sessions flag to true
$this->mysql_sessions = true;
return true;
}
/**
* Checks if the script is using MySQL-based sessions (established using setup_mysql_sessions)
*
* @return boolean True or false
*/
function using_mysql_sessions() {
// Return true if the mysql_sessions flag is set to true and the session.save_handler configuration directive is set to user
return ($this->mysql_sessions == true) && (ini_get('session.save_handler') == 'user');
}
}
?> | mistermarco/swat | stanford.database.php | PHP | bsd-3-clause | 7,278 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Dojo
* @subpackage View
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: ContentPane.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @namespace
*/
namespace Zend\Dojo\View\Helper;
/** Zend_Dojo_View_Helper_DijitContainer */
require_once 'Zend/Dojo/View/Helper/DijitContainer.php';
/**
* Dojo ContentPane dijit
*
* @uses Zend_Dojo_View_Helper_DijitContainer
* @package Zend_Dojo
* @subpackage View
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class ContentPane extends DijitContainer
{
/**
* Dijit being used
* @var string
*/
protected $_dijit = 'dijit.layout.ContentPane';
/**
* Module being used
* @var string
*/
protected $_module = 'dijit.layout.ContentPane';
/**
* dijit.layout.ContentPane
*
* @param string $id
* @param string $content
* @param array $params Parameters to use for dijit creation
* @param array $attribs HTML attributes
* @return string
*/
public function contentPane($id = null, $content = '', array $params = array(), array $attribs = array())
{
if (0 === func_num_args()) {
return $this;
}
return $this->_createLayoutContainer($id, $content, $params, $attribs);
}
}
| FbN/Zend-Framework-Namespaced- | Zend/Dojo/View/Helper/ContentPane.php | PHP | bsd-3-clause | 2,024 |
// @flow
import { RNFFmpeg, RNFFprobe, RNFFmpegConfig } from 'react-native-ffmpeg';
import { getHasMultipleFramesProbeCommand } from 'lib/media/video-utils';
import type {
Dimensions,
FFmpegStatistics,
VideoInfo,
} from 'lib/types/media-types';
const maxSimultaneousCalls = {
process: 1,
probe: 1,
};
type CallCounter = typeof maxSimultaneousCalls;
type QueuedCommandType = $Keys<CallCounter>;
type QueuedCommand = {
type: QueuedCommandType,
runCommand: () => Promise<void>,
};
class FFmpeg {
queue: QueuedCommand[] = [];
currentCalls: CallCounter = { process: 0, probe: 0 };
queueCommand<R>(
type: QueuedCommandType,
wrappedCommand: () => Promise<R>,
): Promise<R> {
return new Promise((resolve, reject) => {
const runCommand = async () => {
try {
const result = await wrappedCommand();
this.currentCalls[type]--;
this.possiblyRunCommands();
resolve(result);
} catch (e) {
reject(e);
}
};
this.queue.push({ type, runCommand });
this.possiblyRunCommands();
});
}
possiblyRunCommands() {
let openSlots = {};
for (const type in this.currentCalls) {
const currentCalls = this.currentCalls[type];
const maxCalls = maxSimultaneousCalls[type];
const callsLeft = maxCalls - currentCalls;
if (!callsLeft) {
return;
} else if (currentCalls) {
openSlots = { [type]: callsLeft };
break;
} else {
openSlots[type] = callsLeft;
}
}
const toDefer = [],
toRun = [];
for (const command of this.queue) {
const type: string = command.type;
if (openSlots[type]) {
openSlots = { [type]: openSlots[type] - 1 };
this.currentCalls[type]++;
toRun.push(command);
} else {
toDefer.push(command);
}
}
this.queue = toDefer;
toRun.forEach(({ runCommand }) => runCommand());
}
transcodeVideo(
ffmpegCommand: string,
inputVideoDuration: number,
onTranscodingProgress: (percent: number) => void,
): Promise<{ rc: number, lastStats: ?FFmpegStatistics }> {
const duration = inputVideoDuration > 0 ? inputVideoDuration : 0.001;
const wrappedCommand = async () => {
RNFFmpegConfig.resetStatistics();
let lastStats;
RNFFmpegConfig.enableStatisticsCallback(
(statisticsData: FFmpegStatistics) => {
lastStats = statisticsData;
const { time } = statisticsData;
onTranscodingProgress(time / 1000 / duration);
},
);
const ffmpegResult = await RNFFmpeg.execute(ffmpegCommand);
return { ...ffmpegResult, lastStats };
};
return this.queueCommand('process', wrappedCommand);
}
generateThumbnail(videoPath: string, outputPath: string): Promise<number> {
const wrappedCommand = () =>
FFmpeg.innerGenerateThumbnail(videoPath, outputPath);
return this.queueCommand('process', wrappedCommand);
}
static async innerGenerateThumbnail(
videoPath: string,
outputPath: string,
): Promise<number> {
const thumbnailCommand = `-i ${videoPath} -frames 1 -f singlejpeg ${outputPath}`;
const { rc } = await RNFFmpeg.execute(thumbnailCommand);
return rc;
}
getVideoInfo(path: string): Promise<VideoInfo> {
const wrappedCommand = () => FFmpeg.innerGetVideoInfo(path);
return this.queueCommand('probe', wrappedCommand);
}
static async innerGetVideoInfo(path: string): Promise<VideoInfo> {
const info = await RNFFprobe.getMediaInformation(path);
const videoStreamInfo = FFmpeg.getVideoStreamInfo(info);
const codec = videoStreamInfo?.codec;
const dimensions = videoStreamInfo && videoStreamInfo.dimensions;
const format = info.format.split(',');
const duration = info.duration / 1000;
return { codec, format, dimensions, duration };
}
static getVideoStreamInfo(
info: Object,
): ?{ +codec: string, +dimensions: Dimensions } {
if (!info.streams) {
return null;
}
for (const stream of info.streams) {
if (stream.type === 'video') {
const codec: string = stream.codec;
const width: number = stream.width;
const height: number = stream.height;
return { codec, dimensions: { width, height } };
}
}
return null;
}
hasMultipleFrames(path: string): Promise<boolean> {
const wrappedCommand = () => FFmpeg.innerHasMultipleFrames(path);
return this.queueCommand('probe', wrappedCommand);
}
static async innerHasMultipleFrames(path: string): Promise<boolean> {
await RNFFprobe.execute(getHasMultipleFramesProbeCommand(path));
const probeOutput = await RNFFmpegConfig.getLastCommandOutput();
const numFrames = parseInt(probeOutput.lastCommandOutput);
return numFrames > 1;
}
}
const ffmpeg: FFmpeg = new FFmpeg();
export { ffmpeg };
| Ashoat/squadcal | native/media/ffmpeg.js | JavaScript | bsd-3-clause | 4,898 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\AuthItemChild */
$this->title = Yii::t('app', '更新: ', [
'modelClass' => 'Auth Item Child',
]) . ' ' . $model->parent;
$this->params['breadcrumbs'][] = ['label' => '权限关系', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->parent, 'url' => ['view', 'parent' => $model->parent, 'child' => $model->child]];
$this->params['breadcrumbs'][] = '更新';
?>
<div class="auth-item-child-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| v-joy/v-joy | views/authitemchild/update.php | PHP | bsd-3-clause | 640 |
from django.db import models
class Place(models.Model):
name = models.CharField(max_length=128)
url = models.URLField(max_length=256, verify_exists=False)
date = models.DateTimeField(auto_now_add=True)
class Meta(object):
topsoil_exclude = ['date']
def get_absolute_url(self):
return "/places/%i" % self.id
def get_edit_url(self):
return "/places/%i/edit" % self.id
| wooster/django-topsoil | tests/test_provider/testapp/models.py | Python | bsd-3-clause | 430 |
/* eslint-env node */
"use strict";
var fluid = require("infusion");
var gpii = fluid.registerNamespace("gpii");
fluid.registerNamespace("gpii.handlebars");
/**
*
* @typedef PrioritisedPathDef
* @property {String} [priority] - The priority for this entry in the final array, relative to other path definitions.
* @property {String} [namespace] - The namespace that other entries can use to express their priority.
* @property {String} path - A package-relative path to be resolved.
*
*/
/**
*
* A static function that uses `fluid.module.resolvePath` to resolve all paths, and return them ordered by priority.
*
* (See https://docs.fluidproject.org/infusion/development/Priorities.html)
*
* Used to consistently resolve the path to template and message bundle directories in the `handlebars`, `inline`, and
* `dispatcher` modules.
*
* Takes a string describing a single path, or an array of strings describing multiple paths. Returns an array of
* resolved paths.
*
* @param {Object<PrioritisedPathDef>|Object<String>} pathsToResolve - A map of paths to resolve.
* @return {Array<String>} - An array of resolved paths.
*
*/
gpii.handlebars.resolvePrioritisedPaths = function (pathsToResolve) {
// Make sure that any short form (string) paths are resolved to structured path defs.
var longFormPathDefs = fluid.transform(pathsToResolve, function (pathDef) {
if (fluid.get(pathDef, "path")) {
return pathDef;
}
else {
return { path: pathDef };
}
});
var prioritisedPathDefs = fluid.parsePriorityRecords(longFormPathDefs, "resource directory");
var resolvedPaths = fluid.transform(prioritisedPathDefs, function (pathDef) {
var pathToResolve = fluid.get(pathDef, "path") || pathDef;
return fluid.module.resolvePath(pathToResolve);
});
return resolvedPaths;
};
| the-t-in-rtf/gpii-handlebars | src/js/server/lib/resolver.js | JavaScript | bsd-3-clause | 1,883 |
/*
* Copyright 2015, 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.
*/
package io.grpc.testing.integration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.google.protobuf.ByteString;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.Codec;
import io.grpc.CompressorRegistry;
import io.grpc.DecompressorRegistry;
import io.grpc.ForwardingClientCall;
import io.grpc.ForwardingClientCallListener;
import io.grpc.ManagedChannel;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.ServerCall;
import io.grpc.ServerCall.Listener;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.internal.GrpcUtil;
import io.grpc.netty.NettyChannelBuilder;
import io.grpc.netty.NettyServerBuilder;
import io.grpc.testing.integration.Messages.CompressionType;
import io.grpc.testing.integration.Messages.Payload;
import io.grpc.testing.integration.Messages.PayloadType;
import io.grpc.testing.integration.Messages.SimpleRequest;
import io.grpc.testing.integration.Messages.SimpleResponse;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Tests that compression is turned on.
*/
@RunWith(JUnit4.class)
public class TransportCompressionTest extends AbstractInteropTest {
// Masquerade as identity.
private static final Fzip FZIPPER = new Fzip("gzip", new Codec.Gzip());
private volatile boolean expectFzip;
private static final DecompressorRegistry decompressors = DecompressorRegistry.emptyInstance()
.with(Codec.Identity.NONE, false)
.with(FZIPPER, true);
private static final CompressorRegistry compressors = CompressorRegistry.newEmptyInstance();
@Before
public void beforeTests() {
FZIPPER.anyRead = false;
FZIPPER.anyWritten = false;
}
/** Start server. */
@BeforeClass
public static void startServer() {
compressors.register(FZIPPER);
compressors.register(Codec.Identity.NONE);
startStaticServer(
NettyServerBuilder.forPort(0)
.maxMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
.compressorRegistry(compressors)
.decompressorRegistry(decompressors),
new ServerInterceptor() {
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
Metadata headers, ServerCallHandler<ReqT, RespT> next) {
Listener<ReqT> listener = next.startCall(call, headers);
// TODO(carl-mastrangelo): check that encoding was set.
call.setMessageCompression(true);
return listener;
}
});
}
/** Stop server. */
@AfterClass
public static void stopServer() {
stopStaticServer();
}
@Test
public void compresses() {
expectFzip = true;
final SimpleRequest request = SimpleRequest.newBuilder()
.setResponseSize(314159)
.setResponseCompression(CompressionType.GZIP)
.setResponseType(PayloadType.COMPRESSABLE)
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[271828])))
.build();
final SimpleResponse goldenResponse = SimpleResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setType(PayloadType.COMPRESSABLE)
.setBody(ByteString.copyFrom(new byte[314159])))
.build();
assertEquals(goldenResponse, blockingStub.unaryCall(request));
// Assert that compression took place
assertTrue(FZIPPER.anyRead);
assertTrue(FZIPPER.anyWritten);
}
@Override
protected ManagedChannel createChannel() {
return NettyChannelBuilder.forAddress("localhost", getPort())
.maxMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
.decompressorRegistry(decompressors)
.compressorRegistry(compressors)
.intercept(new ClientInterceptor() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
final ClientCall<ReqT, RespT> call = next.newCall(method, callOptions);
return new ForwardingClientCall<ReqT, RespT>() {
@Override
protected ClientCall<ReqT, RespT> delegate() {
return call;
}
@Override
public void start(
final ClientCall.Listener<RespT> responseListener, Metadata headers) {
ClientCall.Listener<RespT> listener = new ForwardingClientCallListener<RespT>() {
@Override
protected io.grpc.ClientCall.Listener<RespT> delegate() {
return responseListener;
}
@Override
public void onHeaders(Metadata headers) {
super.onHeaders(headers);
if (expectFzip) {
String encoding = headers.get(GrpcUtil.MESSAGE_ENCODING_KEY);
assertEquals(encoding, FZIPPER.getMessageEncoding());
}
}
};
super.start(listener, headers);
setMessageCompression(true);
}
};
}
})
.usePlaintext(true)
.build();
}
/**
* Fzip is a custom compressor.
*/
static class Fzip implements Codec {
volatile boolean anyRead;
volatile boolean anyWritten;
volatile Codec delegate;
private final String actualName;
public Fzip(String actualName, Codec delegate) {
this.actualName = actualName;
this.delegate = delegate;
}
@Override
public String getMessageEncoding() {
return actualName;
}
@Override
public OutputStream compress(OutputStream os) throws IOException {
return new FilterOutputStream(delegate.compress(os)) {
@Override
public void write(int b) throws IOException {
super.write(b);
anyWritten = true;
}
};
}
@Override
public InputStream decompress(InputStream is) throws IOException {
return new FilterInputStream(delegate.decompress(is)) {
@Override
public int read() throws IOException {
int val = super.read();
anyRead = true;
return val;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int total = super.read(b, off, len);
anyRead = true;
return total;
}
};
}
}
}
| louiscryan/grpc-java | interop-testing/src/test/java/io/grpc/testing/integration/TransportCompressionTest.java | Java | bsd-3-clause | 8,398 |
<?php
/* @var $this NewsController */
/* @var $model SBNews */
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$('#".$this->IDname."-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
?>
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
<?php echo $title;?>
<?php echo CHtml::ajaxLink(
' <i class="glyphicon glyphicon-plus"></i> Add New ',
array($this->id.'/create'),
array('update' => ".view-x",//".content-data-x",
'beforeSend' => 'function(){
loading("show");
}',
'complete' => 'function(){
/*$(".loading-x").fadeOut("slow",function(){
$(".modal-dialog").css({"width":"90%"});
});*/
//loading("hide");
$(".loading-x").fadeOut("slow",function(){
$(".modal-dialog").css({"width":"90%"});
});
return false;
}',
),
array('class'=>'btn btn-success btn-x pull-right')
);?>
<div class="clearfix"></div>
</div>
<div class="table-responsive">
<br>
<?php echo CHtml::link('<i class="glyphicon glyphicon-search"></i> Search','#',array('class'=>'search-button btn btn-default')); ?>
<div class="search-form" style="display:none">
<?php $this->renderPartial('_search',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php $this->widget('zii.widgets.grid.CGridView', array(
'pagerCssClass'=>'text-center',
'pager' => array(
'class' => 'CLinkPager',
'header' => '',
'selectedPageCssClass'=>'active',
'nextPageLabel'=>'<i class="fa fa-angle-right"></i>',
'prevPageLabel'=>'<i class="fa fa-angle-left"></i>',
'lastPageLabel'=>'<i class="fa fa-angle-double-right"></i>',
'firstPageLabel'=>'<i class="fa fa-angle-double-left"></i>',
'htmlOptions'=>array(
'class'=>'pagination pagination-sm',
'id'=>FALSE,
),
),
'id'=>$this->IDname.'-grid',
'dataProvider'=>$model->search(),
//'filter'=>$model,
'itemsCssClass'=>'table table-bordered',
'afterAjaxUpdate'=>'modal',
'columns'=>array(
'news_id',
array(
'name'=>'news_title',
'value'=>function($data){
return "<a href=\"{$data->url_link}\">{$data->news_title}</a>";
},
'type'=>'HTML',
),
array(
'name'=>'source',
'value'=>function($data){
return "<a target='_blank' href=\"{$data->url}\">{$data->source}</a>";
},
'type'=>'HTML',
),
array(
'name'=>'news_date',
'value'=>'$data->display_date_admin'
),
/*
'original_url',
*/
array(
'class'=>'CButtonColumn',
'template'=>'{update} {delete}',
'buttons'=>array(
'update' => array(
'options' => array('data-toggle'=>'tooltip','title' => 'Edit', 'class' => 'btn btn-x btn-default btn-xs'),
'label' => "<i class='fa fa-pencil-square-o'></i>",
'imageUrl' => false,
'click'=>"function(){
loading('show');
$('.view-x').load($(this).attr('href'),function(){
//loading('hide')
$('.modal-dialog').css({'width':'90%'});
});
return false;
}",
),
'delete' => array(
'options' => array('data-toggle'=>'tooltip','title' => 'Delete', 'class' => 'btn btn-danger btn-xs'),
'label' => '<i class="glyphicon glyphicon-remove"></i>',
'imageUrl' => false,
),
),
),
),
)); ?>
</div>
</div>
</div>
</div>
</div>
<script>
$(function(){
$('.datepicker23').datepicker({
format:'dd/mm/yyyy',
todayHighlight: true
});
})
</script> | akaidrive2014/persseleb | protected/views/adminosu/news/admin.php | PHP | bsd-3-clause | 4,360 |
<?php
namespace Admin\Controller;
use Sale\Model\Dao\CustomerDao;
use Sale\Model\Dao\OrderDao;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class IndexController extends AbstractActionController {
private $_user;
public function indexAction() {
$auth = $this->getService('Admin\Model\LoginAdmin');
if ($auth->isLoggedIn()) {
$this->_user = $auth->getIdentity();
// var_dump($this->_user);die;
$this->layout()->first_name = $this->_user->firstname;
$this->layout()->last_name = $this->_user->lastname;
// $this->layout()->user_id = $this->_user->user_id;
$orderTableGateway = $this->getService('OrderHydratingTableGateway');
$orderDao = new OrderDao($orderTableGateway);
$order = $orderDao->getLatest();
$order = $order->fetchAll();
$view['order'] = $order;
// var_dump($view['order']);die;
$customerTableGateway = $this->getService('CustomerTableGateway');
$customerDao = new CustomerDao($customerTableGateway);
$customer = $customerDao->getLatest();
$view['customer'] = $customer;
return new ViewModel($view);
} else {
return $this->forward()->dispatch('Admin\Controller\Login', array('action' => 'index'));
}
}
public function getService($serviceName) {
$sm = $this->getServiceLocator();
$service = $sm->get($serviceName);
return $service;
}
}
| Gimalca/piderapido | module/Admin/src/Admin/Controller/IndexController.php | PHP | bsd-3-clause | 1,586 |
#!/usr/bin/env python
import glob
import os
for f in sorted(glob.glob('*.ini')):
print 'Running ' + f + '...'
os.system('./src/engine ' + f)
| timvdm/ComputerGraphics | run_engine.py | Python | bsd-3-clause | 151 |
<?php
include __DIR__.'/includes.php';
include __DIR__.'/../../src/core/classes/Controller.php';
use PHPUnit\Framework\TestCase;
use Gila\Router;
use Gila\Request;
class RequestTest extends TestCase
{
public function test_validate()
{
$_POST = [
'one'=>1,
'two'=>'two',
];
$data = Request::validate([
'one'=>'',
'two'=>'required',
]);
$this->assertEquals([
'one'=>1,
'two'=>'two',
], $data);
}
}
| GilaCMS/gila | tests/phpunit/RequestTest.php | PHP | bsd-3-clause | 467 |
import React from 'react';
import {MetaType} from 'app/utils/discover/eventView';
import withApi from 'app/utils/withApi';
import GenericDiscoverQuery, {DiscoverQueryProps} from './genericDiscoverQuery';
/**
* An individual row in a DiscoverQuery result
*/
export type TableDataRow = {
id: string;
[key: string]: React.ReactText;
};
/**
* A DiscoverQuery result including rows and metadata.
*/
export type TableData = {
data: Array<TableDataRow>;
meta?: MetaType;
};
function DiscoverQuery(props: DiscoverQueryProps) {
return <GenericDiscoverQuery<TableData, {}> route="eventsv2" {...props} />;
}
export default withApi(DiscoverQuery);
| beeftornado/sentry | src/sentry/static/sentry/app/utils/discover/discoverQuery.tsx | TypeScript | bsd-3-clause | 656 |
<?
preg_match('@^(?:http://)?([^/]+)@i', $_SERVER['HTTP_HOST'], $matches);
$host = $matches[1];
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
$zoto_domain = $matches[0];
if(strstr(getenv('HTTP_REFERER'), "site_down")) {
$referer = $_COOKIE["zoto_down_referer"];
} else {
if (getenv('HTTP_REFERER')) {
$referer = getenv('HTTP_REFERER');
} else {
$referer = "http://www.".$zoto_domain;
}
setcookie("zoto_down_referer", $referer, time()+86400, "/", "".$zoto_domain); /* expire in a day */
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Zoto 3.0 - Zoto is Down for Maintenance</title>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"/>
<META http-equiv="refresh" content="60;URL=<?=$referer?>"/>
<link media="screen" title="" rel="stylesheet" href="site_down.css" type="text/css"/>
</head>
<body>
<div id="main_page_container">
<div>
<a href="http://www.<?=$zoto_domain?>"><img src="big_logo.png" align="left"/></a>
<br clear=all />
</div>
<div id="main_photo_container">
<div id="main_photo">
<div id="caption"></div>
</div>
<div id="well_be_back">
<img src="well_be_back.jpg"/>
</div>
</div>
<div id="main_happy_talk">
<br>
<h3>Oh No! Zoto is down.</h3>
<br>
<h3>ETA updated to at earliest late Sunday. Here's the senario - might as well be transparent. We have lost a drive in our NAS, which houses all the photos. The NAS is currently in a degraded state, but that means it's fixable at least, but it's fragile and I don't want to poke it. We need to install a new drive and recover the RAID array tomorrow. Clint is going up Saturday AM to assist us. We'll keep you posted on progress.</h3>
<br><br>
<i>Have questions? Please visit our</i> <a href="http://forum.<?=$zoto_domain?>">support forum</a>.
<br><br>
This page will attempt to access zoto every 60 seconds, or you can <a href="<?=$referer?>">manually refresh</a>.
</div>
</div>
<div id="copyright">
<br clear=all />
<br /><br />
Copyright © 2007, Zoto Inc. All rights reserved.
</div>
</div>
</body>
</html>
| kordless/zoto-server | www/static_pages/site_down/index.php | PHP | bsd-3-clause | 2,162 |
/*
* Copyright (c) 2016, Oracle and/or its affiliates.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.oracle.truffle.llvm.test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import com.oracle.truffle.llvm.runtime.LLVMLogger;
import com.oracle.truffle.llvm.runtime.LLVMOptions;
import com.oracle.truffle.llvm.runtime.LLVMParserException;
import com.oracle.truffle.llvm.runtime.LLVMUnsupportedException;
import com.oracle.truffle.llvm.runtime.LLVMUnsupportedException.UnsupportedReason;
import com.oracle.truffle.llvm.test.spec.SpecificationEntry;
import com.oracle.truffle.llvm.test.spec.SpecificationFileReader;
import com.oracle.truffle.llvm.test.spec.TestSpecification;
import com.oracle.truffle.llvm.tools.Clang.ClangOptions;
import com.oracle.truffle.llvm.tools.Clang.ClangOptions.OptimizationLevel;
import com.oracle.truffle.llvm.tools.GCC;
import com.oracle.truffle.llvm.tools.Opt;
import com.oracle.truffle.llvm.tools.Opt.OptOptions;
import com.oracle.truffle.llvm.tools.Opt.OptOptions.Pass;
import com.oracle.truffle.llvm.tools.ProgrammingLanguage;
public abstract class TestSuiteBase {
private static List<File> failingTests;
private static List<File> succeedingTests;
private static List<File> parserErrorTests;
private static Map<UnsupportedReason, List<File>> unsupportedErrorTests;
protected void recordTestCase(TestCaseFiles tuple, boolean pass) {
if (pass) {
if (!succeedingTests.contains(tuple.getOriginalFile()) && !failingTests.contains(tuple.getOriginalFile())) {
succeedingTests.add(tuple.getOriginalFile());
}
} else {
if (!failingTests.contains(tuple.getOriginalFile())) {
failingTests.add(tuple.getOriginalFile());
}
}
}
protected void recordError(TestCaseFiles tuple, Throwable error) {
Throwable currentError = error;
if (!failingTests.contains(tuple.getOriginalFile())) {
failingTests.add(tuple.getOriginalFile());
}
while (currentError != null) {
if (currentError instanceof LLVMParserException) {
if (!parserErrorTests.contains(tuple.getOriginalFile())) {
parserErrorTests.add(tuple.getOriginalFile());
}
break;
} else if (currentError instanceof LLVMUnsupportedException) {
List<File> list = unsupportedErrorTests.get(((LLVMUnsupportedException) currentError).getReason());
if (!list.contains(tuple.getOriginalFile())) {
list.add(tuple.getOriginalFile());
}
break;
}
currentError = currentError.getCause();
}
}
private static final int LIST_MIN_SIZE = 1000;
@BeforeClass
public static void beforeClass() {
succeedingTests = new ArrayList<>(LIST_MIN_SIZE);
failingTests = new ArrayList<>(LIST_MIN_SIZE);
parserErrorTests = new ArrayList<>(LIST_MIN_SIZE);
unsupportedErrorTests = new HashMap<>(LIST_MIN_SIZE);
for (UnsupportedReason reason : UnsupportedReason.values()) {
unsupportedErrorTests.put(reason, new ArrayList<>(LIST_MIN_SIZE));
}
}
protected static void printList(String header, List<File> files) {
if (files.size() != 0) {
LLVMLogger.info(header + " (" + files.size() + "):");
files.stream().forEach(t -> LLVMLogger.info(t.toString()));
}
}
@After
public void displaySummary() {
if (LLVMOptions.debugEnabled()) {
if (LLVMOptions.discoveryTestModeEnabled()) {
printList("succeeding tests:", succeedingTests);
} else {
printList("failing tests:", failingTests);
}
printList("parser error tests", parserErrorTests);
for (UnsupportedReason reason : UnsupportedReason.values()) {
printList("unsupported test " + reason, unsupportedErrorTests.get(reason));
}
}
}
@AfterClass
public static void displayEndSummary() {
if (!LLVMOptions.discoveryTestModeEnabled()) {
printList("failing tests:", failingTests);
}
}
protected interface TestCaseGenerator {
ProgrammingLanguage[] getSupportedLanguages();
TestCaseFiles getBitCodeTestCaseFiles(SpecificationEntry bitCodeFile);
List<TestCaseFiles> getCompiledTestCaseFiles(SpecificationEntry toBeCompiled);
}
public static class TestCaseGeneratorImpl implements TestCaseGenerator {
@Override
public TestCaseFiles getBitCodeTestCaseFiles(SpecificationEntry bitCodeFile) {
return TestCaseFiles.createFromBitCodeFile(bitCodeFile.getFile(), bitCodeFile.getFlags());
}
@Override
public List<TestCaseFiles> getCompiledTestCaseFiles(SpecificationEntry toBeCompiled) {
List<TestCaseFiles> files = new ArrayList<>();
File toBeCompiledFile = toBeCompiled.getFile();
File dest = TestHelper.getTempLLFile(toBeCompiledFile, "_main");
try {
if (ProgrammingLanguage.FORTRAN.isFile(toBeCompiledFile)) {
TestCaseFiles gccCompiledTestCase = TestHelper.compileToLLVMIRWithGCC(toBeCompiledFile, dest, toBeCompiled.getFlags());
files.add(gccCompiledTestCase);
} else if (ProgrammingLanguage.C_PLUS_PLUS.isFile(toBeCompiledFile)) {
ClangOptions builder = ClangOptions.builder().optimizationLevel(OptimizationLevel.NONE);
OptOptions options = OptOptions.builder().pass(Pass.LOWER_INVOKE).pass(Pass.PRUNE_EH).pass(Pass.SIMPLIFY_CFG);
TestCaseFiles compiledFiles = TestHelper.compileToLLVMIRWithClang(toBeCompiledFile, dest, toBeCompiled.getFlags(), builder);
files.add(optimize(compiledFiles, options, "opt"));
} else {
ClangOptions builder = ClangOptions.builder().optimizationLevel(OptimizationLevel.NONE);
try {
TestCaseFiles compiledFiles = TestHelper.compileToLLVMIRWithClang(toBeCompiledFile, dest, toBeCompiled.getFlags(), builder);
files.add(compiledFiles);
TestCaseFiles optimized = getOptimizedTestCase(compiledFiles);
files.add(optimized);
} catch (Exception e) {
return Collections.emptyList();
}
}
} catch (Exception e) {
return Collections.emptyList();
}
return files;
}
private static TestCaseFiles getOptimizedTestCase(TestCaseFiles compiledFiles) {
OptOptions options = OptOptions.builder().pass(Pass.MEM_TO_REG).pass(Pass.ALWAYS_INLINE).pass(Pass.JUMP_THREADING).pass(Pass.SIMPLIFY_CFG);
TestCaseFiles optimize = optimize(compiledFiles, options, "opt");
return optimize;
}
@Override
public ProgrammingLanguage[] getSupportedLanguages() {
return GCC.getSupportedLanguages();
}
}
protected static List<TestCaseFiles[]> getTestCasesFromConfigFile(File configFile, File testSuite, TestCaseGenerator gen) throws IOException, AssertionError {
TestSpecification testSpecification = SpecificationFileReader.readSpecificationFolder(configFile, testSuite);
List<SpecificationEntry> includedFiles = testSpecification.getIncludedFiles();
if (LLVMOptions.discoveryTestModeEnabled()) {
List<SpecificationEntry> excludedFiles = testSpecification.getExcludedFiles();
File absoluteDiscoveryPath = new File(testSuite.getAbsolutePath(), LLVMOptions.getTestDiscoveryPath());
assert absoluteDiscoveryPath.exists() : absoluteDiscoveryPath.toString();
LLVMLogger.info("\tcollect files");
List<File> filesToRun = getFilesRecursively(absoluteDiscoveryPath, gen);
for (SpecificationEntry alreadyCanExecute : includedFiles) {
filesToRun.remove(alreadyCanExecute.getFile());
}
for (SpecificationEntry excludedFile : excludedFiles) {
filesToRun.remove(excludedFile.getFile());
}
List<TestCaseFiles[]> discoveryTestCases = new ArrayList<>();
for (File f : filesToRun) {
if (ProgrammingLanguage.LLVM.isFile(f)) {
TestCaseFiles testCase = gen.getBitCodeTestCaseFiles(new SpecificationEntry(f));
discoveryTestCases.add(new TestCaseFiles[]{testCase});
} else {
List<TestCaseFiles> testCases = gen.getCompiledTestCaseFiles(new SpecificationEntry(f));
for (TestCaseFiles testCase : testCases) {
discoveryTestCases.add(new TestCaseFiles[]{testCase});
}
}
}
LLVMLogger.info("\tfinished collecting files");
return discoveryTestCases;
} else {
List<TestCaseFiles[]> includedFileTestCases = collectIncludedFiles(includedFiles, gen);
return includedFileTestCases;
}
}
private static List<TestCaseFiles[]> collectIncludedFiles(List<SpecificationEntry> specificationEntries, TestCaseGenerator gen) throws AssertionError {
List<TestCaseFiles[]> files = new ArrayList<>();
for (SpecificationEntry e : specificationEntries) {
File f = e.getFile();
if (f.isFile()) {
if (ProgrammingLanguage.LLVM.isFile(f)) {
files.add(new TestCaseFiles[]{gen.getBitCodeTestCaseFiles(e)});
} else {
for (TestCaseFiles testCaseFile : gen.getCompiledTestCaseFiles(e)) {
files.add(new TestCaseFiles[]{testCaseFile});
}
}
} else {
throw new AssertionError("could not find specified test file " + f);
}
}
return files;
}
public static List<File> getFilesRecursively(File currentFolder, TestCaseGenerator gen) {
List<File> allBitcodeFiles = new ArrayList<>(1000);
List<File> cFiles = TestHelper.collectFilesWithExtension(currentFolder, gen.getSupportedLanguages());
allBitcodeFiles.addAll(cFiles);
return allBitcodeFiles;
}
protected static List<TestCaseFiles> applyOpt(List<TestCaseFiles> allBitcodeFiles, OptOptions pass, String name) {
return getFilteredOptStream(allBitcodeFiles).map(f -> optimize(f, pass, name)).collect(Collectors.toList());
}
protected static Stream<TestCaseFiles> getFilteredOptStream(List<TestCaseFiles> allBitcodeFiles) {
return allBitcodeFiles.parallelStream().filter(f -> !f.getOriginalFile().getParent().endsWith(LLVMPaths.NO_OPTIMIZATIONS_FOLDER_NAME));
}
protected static TestCaseFiles optimize(TestCaseFiles toBeOptimized, OptOptions optOptions, String name) {
File destinationFile = TestHelper.getTempLLFile(toBeOptimized.getOriginalFile(), "_" + name);
Opt.optimizeBitcodeFile(toBeOptimized.getBitCodeFile(), destinationFile, optOptions);
return TestCaseFiles.createFromCompiledFile(toBeOptimized.getOriginalFile(), destinationFile, toBeOptimized.getFlags());
}
}
| grimmerm/sulong | projects/com.oracle.truffle.llvm.test/src/com/oracle/truffle/llvm/test/TestSuiteBase.java | Java | bsd-3-clause | 13,256 |
<?
//----------------------
//require("GTranslate.php");
//----------------------
?>
<html>
<head>
<title>This is the test page</title>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<style>
body {
font-family:arial;
}
div.container
{
border:4px solid green;
}
div.container div.row
{
border:0px solid green;
width:400px;
}
div.container div.row div
{
border:1px solid blue;
width:150px;
float:left;
text-align:center;
margin:2px;
height:26px;
vertical-align:middle;
}
div.container div.row div.word_en
{
background-color:#fff;
}
div.container div.row div.word_en_sel
{
background-color:#afa;
}
div.container div.row div.word_tr
{
background-color:#ddd;
}
div.container div.row div.word_tr_changed
{
background-color:#ff7;
}
div.container div.row div.title_en,
div.container div.row div.title_tr
{
font-weight:bold;
font-size:16px;
background-color:#555;
color:#fff;
}
div.container div.row div input
{
width:100px;
}
div#previewWindow
{
display:none;
position:absolute;
top:100px;
left:300px;
border:4px solid #afa;
}
div#previewWindow img
{
width:150px;
border:1px solid green;
}
</style>
<script>
function translateTable()
{
if (confirm('Do you wish to RE-TRANSLATE the whole table?')) {
var now = new Date();
//get value of hidden field, which contains the number of words in the table
$wordCount = $('#wordcount').val();
//loop thru objects
for ($x=0;$x<$wordCount;$x++)
{
//get word on this row
$thisWord = $('#en_'+$x).html();
//alert($thisWord);
//translate each word
$.ajax({
type: "POST",
url: "misc_gtranslate.php",
data: "x="+$x+"&w=" +$thisWord+ "&ms=" + now.getTime(),
success: function(sResult){
//on completion, put result (translation) into new cell editbox
//*** NOTE ***
//Due to the asynchronous nature of ajax, the results
//for each word request will come back out of order.
//So each requested word is paired with an ID (1,2,3,etc)
//and then the returned translated word also contains the same id.
//This means that the translated word can be inserted into the
//correct table cell.
// req "3 Green" ---->
// <---- rec'v "3 Vert"
//split into ID and TEXT
$aryValues=sResult.split(' ');
// [0] is ID, [1] is TEXT
$('#tr_'+$aryValues[0]).val($aryValues[1]);
//set class of newly translated cell to default
//(incase a user has manually changed the value, which changes the div class)
$('#div_tr_'+$aryValues[0]).attr('class','word_tr');
}
});
}
}
}
function showPreview($id)
{
//set image on preview window
$sEnWord = $('#en_'+$id).html().toLowerCase();
$('#previewImg').attr('src',$sEnWord+'.wmf');
//set class of english word cell, to "sel" to simulate highlighting a row
$('#en_'+$id).attr('class','word_en_sel');
//show preview window
$('#previewWindow').show();
}
function hidePreview($id)
{
//set class of english word cell back to normal
$('#en_'+$id).attr('class','word_en');
//hide window when textbox loses focus
$('#previewWindow').hide();
}
function valueChanged($id)
{
//set class of a translated cell to indicate that it's been changed manually
$('#div_tr_'+$id).attr('class','word_tr_changed');
}
</script>
</head>
<body>
<div id="previewWindow">
<img id="previewImg">
</div>
<input type="button" value="Translate Table" onClick="translateTable();">
<br/><br/>
<div class="container" onClick="james(this);">
<div class="row">
<div class="title_en">English</div><div class="title_tr">Translation</div>
<br style="clear:both;">
</div>
<?
//----------
//Simulating a PHP fetch of data (DB) for words to be translated
//----------
//simulated list of words (in an array here)
$aryWordsEn = array ("Fruit","Apple","Hello","Pear","Banana","Car","Bag","Train","Pencil","Shoe");
$x=-1;
while ($x<count($aryWordsEn)-1) {
$x++;
//----------
?>
<div class="row">
<div id="en_<?=$x;?>" class="word_en"><?=$aryWordsEn[$x]?></div><div id="div_tr_<?=$x;?>" class="word_tr"><input type="text" id="tr_<?=$x;?>" onFocus="showPreview('<?=$x;?>')" onBlur="hidePreview('<?=$x;?>')" onChange="valueChanged('<?=$x;?>')"></div>
<br style="clear:both;">
</div>
<?
//----------
}
//----------
?>
<input type="hidden" id="wordcount" value="<?=$x+1;?>">
<br style="clear:both;">
</div>
</body>
</html> | straight-street/straight-street | scratchpad/translate/index5.php | PHP | bsd-3-clause | 4,540 |
/*
* File: PowerSetItr.hpp
*
* Created on March 17, 2016, 6:07 PM
*/
#pragma once
#include <memory>
#include "pulsar/math/CombItr.hpp"
namespace pulsar{
/** \brief Class to facilitate iterating over the power set of a set
*
* Let's start with what a power set is. Given a set \f$S\f$, the
* power set of \f$S\f$, usually denoted \f$\mathbb{P}(S)\f$ is the
* set of all subsets of \f$S\f$. In particular this means the
* empty set and \f$S\f$ itself are in \f$\mathbb{P}(S)\f$. In
* terms of combinatorics, there is a deep symmetry between the
* power set of \f$S\f$ and a row of Pascal's triangle, hence
* iterating over (at least part of) a power set typically arises
* when one is iterating over say all ways of picking one, two ,
* and three objects from a set.
*
* Note for posterity, I had coded this iterator up in terms of counting in
* binary, which is based on the realization that the binary
* representation of \f$2^N-1\f$ contains \f$N\f$ 1's. So counting
* from 0 to \f$2^N-1\f$, in binary will generate all of the
* \f$2^N\f$ subsets of \f$S\f$ if we associate a 1 in the \f$i\f$-th
* place with \f$S_i\f$ being in the current subset and a 0 with its
* absence. Unfortunately this generates the subsets in a weird
* order, something akin to (assuming \f$S=\{1,2,3,\cdots,N\}\f$):
* \verbatim
(empty set)
1
2
1 2
3
1 3
2 3
1 2 3
...
1 2 3...N
\endverbatim
*
* It's more natural to instead iterate in the order:
* \verbatim
* (empty set)
* 1
* 2
* 3
* ...
* N
* 1 2
* 1 3
* ...
* 1 2 3
* ...
* 1 2 ...N
* \endverbatim
* this is the order the current generation loops in.
*
* The implementation for this is straightforward, either by
* examining the intended order, or again by analogy to Pascal's
* triangle, one sees that we simply want to iterate over all
* combinations of our current set. Hence we call CombItr \f$N\f$
* times. I suspect this is not as effecient as the counting in binary, but
* I haven't timed it.
*
* Usage of this class is similar to its cousin class CombItr:
* \code
///Typedef of container
typedef std::set<size_t> Set_t;
///Declare and fill a set of integers
Set_t TestSet;
for(size_t i=0;i<5;i++)TestSet.insert(i);
///Declare a power set iterator that runs over the whole set
PowerSetItr<Set_t> MyItr(TestSet);
///Iterate until done
for(;!MyItr.done();++MyItr){
Set_t::const_iterator elem=MyItr->begin(),elemEnd=MyItr->end();
for(;elem!=elemEnd;++elem)
std::cout<<*elem<<" ";
std::cout<<std::endl;
}
\endcode
The output should be:
\verbatim
0
1
2
3
4
0 1
0 2
0 3
0 4
1 2
1 3
1 4
2 3
2 4
3 4
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
0 1 2 3
0 1 2 4
0 1 3 4
0 2 3 4
1 2 3 4
0 1 2 3 4
\endverbatim
*
*
* \param T The type of the set we are iterating over, will also be
* the type of susbsets returned by the iterator.
*
* \note This class is not exported to Python and itertools does not provide a
* direct equivalent, but one can easily use chain()
*/
template<typename T>
class PowerSetItr{
private:
///The set we are generating the power set of
const T& Set_;
///The maximum order this iterator is going up to
size_t MaxOrder_;
///The first order we are considering
size_t MinOrder_;
///The current order
size_t Order_;
typedef typename pulsar::CombItr<T> CombItr_t;
typedef typename std::shared_ptr<CombItr_t> SharedItr_t;
SharedItr_t CurrentIt_;
///Have we iterated over the entire range yet?
bool Done_;
///Implementation for getting the next element
void next();
public:
/** \brief Given a set, iterates over all subsets containing Min
* number of elements to Max number of elements
*
* Often one only wants to iterate over part of the power set, which
* is what this function does. Specifically it iterates from sets
* containing \p Min elements to those containing \p Max elements
* inclusively. Note that this is not usual C++ counting (Min=1 really
* gives you sets with 1 element and not 2).
*/
PowerSetItr(const T& Set, size_t Min, size_t Max);
///Iterates over the entire power set
PowerSetItr(const T& Set):PowerSetItr(Set,0,Set.size()){}
///Deep copies other iterator
PowerSetItr(const PowerSetItr&);
///Returns true if we have iterated over the whole range
bool done()const{return Done_;}
///Returns true if there are combinations left
operator bool()const{return !Done_;}
///Moves on to the next subset and returns it
PowerSetItr<T>& operator++(){next();return *this;}
///Moves to next, returns current
PowerSetItr<T> operator++(int);
///Returns the current subset
const T& operator*()const{return CurrentIt_->operator*();}
///Allows access of the subset's container's members
const T* operator->()const{return CurrentIt_->operator->();}
};
/******************** Implementations ******************/
template<typename T>
PowerSetItr<T>::PowerSetItr(const PowerSetItr<T>& other)
: Set_(other.Set_),MaxOrder_(other.MaxOrder_),MinOrder_(other.MinOrder_),
Order_(other.Order_),
CurrentIt_(other.CurrentIt_?std::make_shared<CombItr_t>(*other.CurrentIt_):nullptr),
Done_(other.Done_)
{
}
template<typename T>
PowerSetItr<T> PowerSetItr<T>::operator++(int)
{
PowerSetItr<T> temp(*this);
next();
return temp;
}
template<typename T>
PowerSetItr<T>::PowerSetItr(const T& Set, size_t Min,size_t Max):
Set_(Set),
MaxOrder_(Max),
MinOrder_(Min),
Order_(MinOrder_),
CurrentIt_(std::make_shared<CombItr_t>(Set_,Order_++)),
//Can't iterate under this condition (it occurs quite naturally in
//recursion)
Done_(MaxOrder_<MinOrder_||Max==0){}
template<typename T>
void PowerSetItr<T>::next(){
++(*CurrentIt_);
if(!CurrentIt_->done())return;
else if(Order_<=MaxOrder_)
CurrentIt_=std::make_shared<CombItr_t>(Set_,Order_++);
else Done_=true;
}
}//End namespace
| pulsar-chem/Pulsar-Core | pulsar/math/PowerSetItr.hpp | C++ | bsd-3-clause | 6,364 |
/*L
* Copyright SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/i-spy/LICENSE.txt for details.
*/
package gov.nih.nci.ispy.service.common;
import java.awt.Color;
import java.io.Serializable;
public enum TimepointType implements Serializable {
T1 { public Color getColor() { return Color.GREEN; }},
T2 { public Color getColor() { return Color.YELLOW; }},
T3 { public Color getColor() { return Color.RED; }},
T4 { public Color getColor() { return Color.BLUE; }};
public abstract Color getColor();
}
| NCIP/i-spy | src/gov/nih/nci/ispy/service/common/TimepointType.java | Java | bsd-3-clause | 568 |
/* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2010 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o 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://www.gnu.org/licenses/. */
package com.db4o.internal.activation;
public interface ModifiedObjectQuery {
boolean isModified(Object obj);
}
| mural/spm | db4oj/src/main/java/com/db4o/internal/activation/ModifiedObjectQuery.java | Java | bsd-3-clause | 795 |
from django.conf.urls import patterns, url
urlpatterns = patterns('ietf.secr.drafts.views',
url(r'^$', 'search', name='drafts'),
url(r'^add/$', 'add', name='drafts_add'),
url(r'^approvals/$', 'approvals', name='drafts_approvals'),
url(r'^dates/$', 'dates', name='drafts_dates'),
url(r'^nudge-report/$', 'nudge_report', name='drafts_nudge_report'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/$', 'view', name='drafts_view'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/abstract/$', 'abstract', name='drafts_abstract'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/announce/$', 'announce', name='drafts_announce'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/authors/$', 'authors', name='drafts_authors'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/author_delete/(?P<oid>\d{1,6})$',
'author_delete', name='drafts_author_delete'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/confirm/$', 'confirm', name='drafts_confirm'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/edit/$', 'edit', name='drafts_edit'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/extend/$', 'extend', name='drafts_extend'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/email/$', 'email', name='drafts_email'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/makerfc/$', 'makerfc', name='drafts_makerfc'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/replace/$', 'replace', name='drafts_replace'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/resurrect/$', 'resurrect', name='drafts_resurrect'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/revision/$', 'revision', name='drafts_revision'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/update/$', 'update', name='drafts_update'),
url(r'^(?P<id>[A-Za-z0-9._\-\+]+)/withdraw/$', 'withdraw', name='drafts_withdraw'),
)
| wpjesus/codematch | ietf/secr/drafts/urls.py | Python | bsd-3-clause | 1,671 |
# -*- coding: utf-8 -*-
import os
from time import sleep
import nipype.interfaces.base as nib
import pytest
import nipype.pipeline.engine as pe
from nipype.pipeline.plugins.somaflow import soma_not_loaded
class InputSpec(nib.TraitedSpec):
input1 = nib.traits.Int(desc='a random int')
input2 = nib.traits.Int(desc='a random int')
class OutputSpec(nib.TraitedSpec):
output1 = nib.traits.List(nib.traits.Int, desc='outputs')
class SomaTestInterface(nib.BaseInterface):
input_spec = InputSpec
output_spec = OutputSpec
def _run_interface(self, runtime):
runtime.returncode = 0
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs['output1'] = [1, self.inputs.input1]
return outputs
@pytest.mark.skipif(soma_not_loaded, reason="soma not loaded")
def test_run_somaflow(tmpdir):
os.chdir(str(tmpdir))
pipe = pe.Workflow(name='pipe')
mod1 = pe.Node(interface=SomaTestInterface(), name='mod1')
mod2 = pe.MapNode(interface=SomaTestInterface(),
iterfield=['input1'],
name='mod2')
pipe.connect([(mod1, mod2, [('output1', 'input1')])])
pipe.base_dir = os.getcwd()
mod1.inputs.input1 = 1
execgraph = pipe.run(plugin="SomaFlow")
names = ['.'.join((node._hierarchy, node.name)) for node in execgraph.nodes()]
node = list(execgraph.nodes())[names.index('pipe.mod1')]
result = node.get_output('output1')
assert result == [1, 1]
| mick-d/nipype | nipype/pipeline/plugins/tests/test_somaflow.py | Python | bsd-3-clause | 1,509 |
// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function f(){ log.history = log.history || []; log.history.push(arguments); if(this.console) { var args = arguments, newarr; args.callee = args.callee.caller; newarr = [].slice.call(args); if (typeof console.log === 'object') log.apply.call(console.log, console, newarr); else console.log.apply(console, newarr);}};
// make it safe to use console.log always
(function(a){function b(){}for(var c="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),d;!!(d=c.pop());){a[d]=a[d]||b;}})
(function(){try{console.log();return window.console;}catch(a){return (window.console={});}}());
// place any jQuery/helper plugins in here, instead of separate, slower script files.
// Bootstrap Dropdown
/* ============================================================
* bootstrap-dropdown.js v2.0.0
* http://twitter.github.com/bootstrap/javascript.html#dropdowns
* ============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
!function( $ ){
"use strict"
/* DROPDOWN CLASS DEFINITION
* ========================= */
var toggle = '[data-toggle="dropdown"]'
, Dropdown = function ( element ) {
var $el = $(element).on('click.dropdown.data-api', this.toggle)
$('html').on('click.dropdown.data-api', function () {
$el.parent().removeClass('open')
})
}
Dropdown.prototype = {
constructor: Dropdown
, toggle: function ( e ) {
var $this = $(this)
, selector = $this.attr('data-target')
, $parent
, isActive
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
$parent = $(selector)
$parent.length || ($parent = $this.parent())
isActive = $parent.hasClass('open')
clearMenus()
!isActive && $parent.toggleClass('open')
return false
}
}
function clearMenus() {
$(toggle).parent().removeClass('open')
}
/* DROPDOWN PLUGIN DEFINITION
* ========================== */
$.fn.dropdown = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('dropdown')
if (!data) $this.data('dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
$.fn.dropdown.Constructor = Dropdown
/* APPLY TO STANDARD DROPDOWN ELEMENTS
* =================================== */
$(function () {
$('html').on('click.dropdown.data-api', clearMenus)
$('body').on('click.dropdown.data-api', toggle, Dropdown.prototype.toggle)
})
}( window.jQuery )
| inkasjasonk/rs | research/base/static/js/plugins.js | JavaScript | bsd-3-clause | 3,480 |
/**
* Pimcore
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.pimcore.org/license
*
* @copyright Copyright (c) 2009-2010 elements.at New Media Solutions GmbH (http://www.elements.at)
* @license http://www.pimcore.org/license New BSD License
*/
pimcore.registerNS("pimcore.object.tags.checkbox");
pimcore.object.tags.checkbox = Class.create(pimcore.object.tags.abstract, {
type: "checkbox",
initialize: function (data, fieldConfig) {
this.data = "";
if (data) {
this.data = data;
}
this.fieldConfig = fieldConfig;
},
getGridColumnConfig: function(field) {
return new Ext.grid.CheckColumn({
header: ts(field.label),
dataIndex: field.key,
renderer: function (key, value, metaData, record, rowIndex, colIndex, store) {
if(record.data.inheritedFields[key] && record.data.inheritedFields[key].inherited == true) {
metaData.css += " grid_value_inherited";
}
metaData.css += ' x-grid3-check-col-td';
return String.format('<div class="x-grid3-check-col{0}"> </div>', value ? '-on' : '');
}.bind(this, field.key)
});
},
getGridColumnFilter: function(field) {
return {type: 'boolean', dataIndex: field.key};
},
getLayoutEdit: function () {
var checkbox = {
fieldLabel: this.fieldConfig.title,
name: this.fieldConfig.name,
itemCls: "object_field"
};
if (this.fieldConfig.width) {
checkbox.width = this.fieldConfig.width;
}
this.component = new Ext.form.Checkbox(checkbox);
this.component.setValue(this.data);
return this.component;
},
getLayoutShow: function () {
this.component = this.getLayoutEdit();
this.component.disable();
return this.component;
},
getValue: function () {
return this.component.getValue();
},
getName: function () {
return this.fieldConfig.name;
},
isInvalidMandatory: function () {
return false;
}
}); | clime/pimcore-custom | static/js/pimcore/object/tags/checkbox.js | JavaScript | bsd-3-clause | 2,339 |
<?php
namespace WbBase\WbTrait\ServiceManager;
use \Zend\ServiceManager\ServiceManager;
/**
* ServiceManagerAwareTrait
*
* @package WbBase\WbTrait\ServiceManager
* @author Źmicier Hryškieivič <zmicier@webbison.com>
*/
trait ServiceManagerAwareTrait
{
/**
* @var ServiceManager
*/
protected $serviceManager;
/**
* ServiceManager setter
*
* @param ServiceManager $serviceManager Service manager.
*
* @return void
*/
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
return $this;
}
/**
* ServiceManager getter
*
* @return ServiceManager
*/
public function getServiceManager()
{
return $this->serviceManager;
}
}
| zmicier/WbBase | src/WbBase/WbTrait/ServiceManager/ServiceManagerAwareTrait.php | PHP | bsd-3-clause | 808 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Media;
namespace GameFramework.Implementation
{
public class WPMusic : Music
{
#region Fields
private Song song;
#endregion
#region Properties
public Boolean IsPlaying
{
get
{
return (MediaPlayer.State == MediaState.Playing);
}
}
public Boolean IsStopped
{
get
{
return (MediaPlayer.State == MediaState.Stopped);
}
}
public bool IsLooping
{
get
{
return MediaPlayer.IsRepeating;
}
}
#endregion
#region Constructors
public WPMusic(Song song)
{
this.song = song;
}
#endregion
#region Methods
public void Play()
{
if (MediaPlayer.State == MediaState.Playing)
return;
MediaPlayer.Play(song);
}
public void Pause()
{
if (MediaPlayer.State == MediaState.Playing)
MediaPlayer.Pause();
}
public void Resume()
{
if (MediaPlayer.State == MediaState.Paused)
MediaPlayer.Resume();
if (MediaPlayer.State == MediaState.Stopped)
Play();
}
public void Stop()
{
if (MediaPlayer.State == MediaState.Playing)
MediaPlayer.Stop();
}
public void SetLooping(bool looping)
{
MediaPlayer.IsRepeating = looping;
}
public void SetVolume(float volume)
{
MediaPlayer.Volume = volume;
}
public void Dispose()
{
song.Dispose();
}
#endregion
}
} | tommus/XNAGameWrapper | Implementation/WPMusic.cs | C# | bsd-3-clause | 2,056 |
// Box sizing in JavaScript
// Copyright 2011 Google Inc.
// see Purple/license.txt for BSD license
// johnjbarton@google.com
define(['lib/nodelist/nodelist'], function (nodelist){
var Flexor = {};
Flexor.getChildernByClassName = function(parentBox, classname) {
var hboxes = [];
parentBox.childNodes.forEach(function (child) {
if (child.classList && child.classList.contains(classname)) {
hboxes.push(child);
}
});
return hboxes;
};
Flexor.sizeHBoxes = function(boxes) {
if (!boxes.length) {
return;
}
var flexibles = this.flexibleBoxes(boxes);
var remainingHeight = this.remainingHeight(boxes);
if (remainingHeight <= 0) {
console.error("Purple.Flexor: no remaining height");
return;
}
var remainder = 0;
flexibles.forEach(function convertToHeight(box) {
var flexible = parseInt(box.dataset.flexible);
var floatingHeight = remainingHeight * (flexible / flexibles.totalFlexible) + remainder;
var height = Math.floor(floatingHeight);
remainder = floatingHeight - height;
box.style.height = height+"px";
});
};
// return an array of boxes all having valid, non-zero data-flexible attributes
Flexor.flexibleBoxes = function(boxes) {
var flexibles = [];
flexibles.totalFlexible = 0;
boxes.forEach(function gatherFlexible(box) {
var flexibleString = box.dataset.flexible;
if (flexibleString) {
var flexible = parseInt(flexibleString);
if (!flexible) {
console.error("Purple.Flexor: invalid flexible value "+flexibleString, box);
box.removeAttribute('data-flexible');
return;
}
flexibles.push(box);
flexibles.totalFlexible += flexible;
}
});
if (flexibles.length) {
if (!flexibles.totalFlexible) {
console.error("Purple.Flexor: no valid flexible values", flexibles);
return [];
}
}
return flexibles;
};
// return the parent height minus all of the inflexible box heights
Flexor.remainingHeight = function(boxes) {
var remainingHeight = boxes[0].parentNode.getBoundingClientRect().height;
boxes.forEach(function decrement(box) {
if (!box.dataset.flexible) {
remainingHeight -= box.getBoundingClientRect().height;
}
});
return remainingHeight;
};
return Flexor;
}); | johnjbarton/Purple | ui/flexor.js | JavaScript | bsd-3-clause | 2,344 |
<?php
// $Id: AbstractTemplateEngine.php 477 2008-05-19 08:10:31Z aurelian $
abstract class AbstractTemplateEngine extends Object implements ITemplateEngine {
protected $vars;
protected $context;
protected $controller;
public function __construct(ContextManager $context, ActionController $controller) {
$this->context= $context;
$this->controller= $controller;
$this->vars= array();
}
public function assign($name, $value) {
$this->vars[$name]= $value;
}
}
| aurelian/medick2 | lib/action/view/AbstractTemplateEngine.php | PHP | bsd-3-clause | 497 |
/**
* @license
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This class ensures the packets from the server arrive in order
* This class takes data from the server and ensures it gets passed into the callbacks in order.
* @constructor
*/
export declare class PacketReceiver {
private onMessage_;
pendingResponses: any[];
currentResponseNum: number;
closeAfterResponse: number;
onClose: (() => void) | null;
/**
* @param onMessage_
*/
constructor(onMessage_: (a: Object) => void);
closeAfter(responseNum: number, callback: () => void): void;
/**
* Each message from the server comes with a response number, and an array of data. The responseNumber
* allows us to ensure that we process them in the right order, since we can't be guaranteed that all
* browsers will respond in the same order as the requests we sent
* @param {number} requestNum
* @param {Array} data
*/
handleResponse(requestNum: number, data: any[]): void;
}
| PolymerLabs/arcs-live | concrete-storage/node_modules/@firebase/database/dist/src/realtime/polling/PacketReceiver.d.ts | TypeScript | bsd-3-clause | 1,601 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\Refill */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="refill-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'id_printer')->textInput() ?>
<?= $form->field($model, 'comment')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'date')->textInput(['maxlength' => 255]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| annushara/diplom | views/refill/_form.php | PHP | bsd-3-clause | 673 |
<?php
class Autor
{
private $nome;
private $data_nascimento;
private $email;
private $id;
/**
*
* @return the $nome
*/
public function getNome()
{
return $this->nome;
}
/**
*
* @return the $data_nascimento
*/
public function getData_nascimento()
{
return $this->data_nascimento;
}
/**
*
* @return the $email
*/
public function getEmail()
{
return $this->email;
}
/**
*
* @return the $id
*/
public function getId()
{
return $this->id;
}
/**
*
* @param field_type $nome
*/
public function setNome($nome)
{
$this->nome = $nome;
}
/**
*
* @param field_type $data_nascimento
*/
public function setData_nascimento($data_nascimento)
{
$this->data_nascimento = $data_nascimento;
}
/**
*
* @param field_type $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
*
* @param field_type $id
*/
public function setId($id)
{
$this->id = $id;
}
public function toArray()
{
return array('nome' => $this->nome,
'data_nascimento' => $this->data_nascimento,
'email' => $this->email
);
}
}
| ajzuse/PHPOrientadoAObjetos | module/Application/src/Application/Model/Autor.php | PHP | bsd-3-clause | 1,429 |
require File.expand_path('../shared/conjugate', __FILE__)
ruby_version_is "1.9" do
describe "Matrix#conj" do
it_behaves_like(:matrix_conjugate, :conj)
end
end
| rubysl/rubysl-matrix | spec/conj_spec.rb | Ruby | bsd-3-clause | 168 |
<?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "fields".
*
* @property integer $field_id
* @property string $arabic_name
* @property string $english_name
* @property string $field_type
* @property integer $is_required
* @property integer $field_order
* @property integer $list_page
* @property integer $filter_page
*
* @property CategoriesFields[] $categoriesFields
* @property FieldListData[] $fieldListDatas
*/
class Fields extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'fields';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['arabic_name', 'english_name', 'field_type', 'is_required', 'field_order', 'list_page', 'filter_page'], 'required'],
[['field_type'], 'string'],
[['is_required', 'field_order', 'list_page', 'filter_page'], 'integer'],
[['arabic_name', 'english_name'], 'string', 'max' => 255],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'field_id' => 'Field ID',
'arabic_name' => 'Arabic Name',
'english_name' => 'English Name',
'field_type' => 'Field Type',
'is_required' => 'Is Required',
'field_order' => 'Field Order',
'list_page' => 'List Page',
'filter_page' => 'Filter Page',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCategoriesFields()
{
return $this->hasMany(CategoriesFields::className(), ['field_id' => 'field_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getFieldListDatas()
{
return $this->hasMany(FieldListData::className(), ['field_id' => 'field_id']);
}
}
| haya-hammoud/advanced | backend/models/Fields.php | PHP | bsd-3-clause | 1,895 |
// 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 "components/error_page/renderer/net_error_helper_core.h"
#include <set>
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/callback.h"
#include "base/debug/alias.h"
#include "base/debug/dump_without_crashing.h"
#include "base/i18n/rtl.h"
#include "base/json/json_reader.h"
#include "base/json/json_value_converter.h"
#include "base/json/json_writer.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/scoped_vector.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/sparse_histogram.h"
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "components/error_page/common/error_page_params.h"
#include "components/url_formatter/url_formatter.h"
#include "content/public/common/url_constants.h"
#include "grit/components_strings.h"
#include "net/base/escape.h"
#include "net/base/net_errors.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebURLError.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/gurl.h"
#include "url/url_constants.h"
namespace error_page {
namespace {
#define MAX_DEBUG_HISTORY_EVENTS 50
struct CorrectionTypeToResourceTable {
int resource_id;
const char* correction_type;
};
const CorrectionTypeToResourceTable kCorrectionResourceTable[] = {
{IDS_ERRORPAGES_SUGGESTION_VISIT_GOOGLE_CACHE, "cachedPage"},
// "reloadPage" is has special handling.
{IDS_ERRORPAGES_SUGGESTION_CORRECTED_URL, "urlCorrection"},
{IDS_ERRORPAGES_SUGGESTION_ALTERNATE_URL, "siteDomain"},
{IDS_ERRORPAGES_SUGGESTION_ALTERNATE_URL, "host"},
{IDS_ERRORPAGES_SUGGESTION_ALTERNATE_URL, "sitemap"},
{IDS_ERRORPAGES_SUGGESTION_ALTERNATE_URL, "pathParentFolder"},
// "siteSearchQuery" is not yet supported.
// TODO(mmenke): Figure out what format "siteSearchQuery" uses for its
// suggestions.
// "webSearchQuery" has special handling.
{IDS_ERRORPAGES_SUGGESTION_ALTERNATE_URL, "contentOverlap"},
{IDS_ERRORPAGES_SUGGESTION_CORRECTED_URL, "emphasizedUrlCorrection"},
};
struct NavigationCorrection {
NavigationCorrection() : is_porn(false), is_soft_porn(false) {
}
static void RegisterJSONConverter(
base::JSONValueConverter<NavigationCorrection>* converter) {
converter->RegisterStringField("correctionType",
&NavigationCorrection::correction_type);
converter->RegisterStringField("urlCorrection",
&NavigationCorrection::url_correction);
converter->RegisterStringField("clickType",
&NavigationCorrection::click_type);
converter->RegisterStringField("clickData",
&NavigationCorrection::click_data);
converter->RegisterBoolField("isPorn", &NavigationCorrection::is_porn);
converter->RegisterBoolField("isSoftPorn",
&NavigationCorrection::is_soft_porn);
}
std::string correction_type;
std::string url_correction;
std::string click_type;
std::string click_data;
bool is_porn;
bool is_soft_porn;
};
struct NavigationCorrectionResponse {
std::string event_id;
std::string fingerprint;
ScopedVector<NavigationCorrection> corrections;
static void RegisterJSONConverter(
base::JSONValueConverter<NavigationCorrectionResponse>* converter) {
converter->RegisterStringField("result.eventId",
&NavigationCorrectionResponse::event_id);
converter->RegisterStringField("result.fingerprint",
&NavigationCorrectionResponse::fingerprint);
converter->RegisterRepeatedMessage(
"result.UrlCorrections",
&NavigationCorrectionResponse::corrections);
}
};
base::TimeDelta GetAutoReloadTime(size_t reload_count) {
static const int kDelaysMs[] = {
0, 5000, 30000, 60000, 300000, 600000, 1800000
};
if (reload_count >= arraysize(kDelaysMs))
reload_count = arraysize(kDelaysMs) - 1;
return base::TimeDelta::FromMilliseconds(kDelaysMs[reload_count]);
}
// Returns whether |net_error| is a DNS-related error (and therefore whether
// the tab helper should start a DNS probe after receiving it.)
bool IsDnsError(const blink::WebURLError& error) {
return error.domain.utf8() == net::kErrorDomain &&
(error.reason == net::ERR_NAME_NOT_RESOLVED ||
error.reason == net::ERR_NAME_RESOLUTION_FAILED);
}
GURL SanitizeURL(const GURL& url) {
GURL::Replacements remove_params;
remove_params.ClearUsername();
remove_params.ClearPassword();
remove_params.ClearQuery();
remove_params.ClearRef();
return url.ReplaceComponents(remove_params);
}
// Sanitizes and formats a URL for upload to the error correction service.
std::string PrepareUrlForUpload(const GURL& url) {
// TODO(yuusuke): Change to url_formatter::FormatUrl when Link Doctor becomes
// unicode-capable.
std::string spec_to_send = SanitizeURL(url).spec();
// Notify navigation correction service of the url truncation by sending of
// "?" at the end.
if (url.has_query())
spec_to_send.append("?");
return spec_to_send;
}
// Given a WebURLError, returns true if the FixURL service should be used
// for that error. Also sets |error_param| to the string that should be sent to
// the FixURL service to identify the error type.
bool ShouldUseFixUrlServiceForError(const blink::WebURLError& error,
std::string* error_param) {
error_param->clear();
// Don't use the correction service for HTTPS (for privacy reasons).
GURL unreachable_url(error.unreachableURL);
if (GURL(unreachable_url).SchemeIsCryptographic())
return false;
std::string domain = error.domain.utf8();
if (domain == url::kHttpScheme && error.reason == 404) {
*error_param = "http404";
return true;
}
if (IsDnsError(error)) {
*error_param = "dnserror";
return true;
}
if (domain == net::kErrorDomain &&
(error.reason == net::ERR_CONNECTION_FAILED ||
error.reason == net::ERR_CONNECTION_REFUSED ||
error.reason == net::ERR_ADDRESS_UNREACHABLE ||
error.reason == net::ERR_CONNECTION_TIMED_OUT)) {
*error_param = "connectionFailure";
return true;
}
return false;
}
// Creates a request body for use with the fixurl service. Sets parameters
// shared by all types of requests to the service. |correction_params| must
// contain the parameters specific to the actual request type.
std::string CreateRequestBody(
const std::string& method,
const std::string& error_param,
const NetErrorHelperCore::NavigationCorrectionParams& correction_params,
scoped_ptr<base::DictionaryValue> params_dict) {
// Set params common to all request types.
params_dict->SetString("key", correction_params.api_key);
params_dict->SetString("clientName", "chrome");
params_dict->SetString("error", error_param);
if (!correction_params.language.empty())
params_dict->SetString("language", correction_params.language);
if (!correction_params.country_code.empty())
params_dict->SetString("originCountry", correction_params.country_code);
base::DictionaryValue request_dict;
request_dict.SetString("method", method);
request_dict.SetString("apiVersion", "v1");
request_dict.Set("params", params_dict.release());
std::string request_body;
bool success = base::JSONWriter::Write(request_dict, &request_body);
DCHECK(success);
return request_body;
}
// If URL correction information should be retrieved remotely for a main frame
// load that failed with |error|, returns true and sets
// |correction_request_body| to be the body for the correction request.
std::string CreateFixUrlRequestBody(
const blink::WebURLError& error,
const NetErrorHelperCore::NavigationCorrectionParams& correction_params) {
std::string error_param;
bool result = ShouldUseFixUrlServiceForError(error, &error_param);
DCHECK(result);
// TODO(mmenke): Investigate open sourcing the relevant protocol buffers and
// using those directly instead.
scoped_ptr<base::DictionaryValue> params(new base::DictionaryValue());
params->SetString("urlQuery", PrepareUrlForUpload(error.unreachableURL));
return CreateRequestBody("linkdoctor.fixurl.fixurl", error_param,
correction_params, params.Pass());
}
std::string CreateClickTrackingUrlRequestBody(
const blink::WebURLError& error,
const NetErrorHelperCore::NavigationCorrectionParams& correction_params,
const NavigationCorrectionResponse& response,
const NavigationCorrection& correction) {
std::string error_param;
bool result = ShouldUseFixUrlServiceForError(error, &error_param);
DCHECK(result);
scoped_ptr<base::DictionaryValue> params(new base::DictionaryValue());
params->SetString("originalUrlQuery",
PrepareUrlForUpload(error.unreachableURL));
params->SetString("clickedUrlCorrection", correction.url_correction);
params->SetString("clickType", correction.click_type);
params->SetString("clickData", correction.click_data);
params->SetString("eventId", response.event_id);
params->SetString("fingerprint", response.fingerprint);
return CreateRequestBody("linkdoctor.fixurl.clicktracking", error_param,
correction_params, params.Pass());
}
base::string16 FormatURLForDisplay(const GURL& url, bool is_rtl,
const std::string accept_languages) {
// Translate punycode into UTF8, unescape UTF8 URLs.
base::string16 url_for_display(url_formatter::FormatUrl(
url, accept_languages, url_formatter::kFormatUrlOmitNothing,
net::UnescapeRule::NORMAL, nullptr, nullptr, nullptr));
// URLs are always LTR.
if (is_rtl)
base::i18n::WrapStringWithLTRFormatting(&url_for_display);
return url_for_display;
}
scoped_ptr<NavigationCorrectionResponse> ParseNavigationCorrectionResponse(
const std::string raw_response) {
// TODO(mmenke): Open source related protocol buffers and use them directly.
scoped_ptr<base::Value> parsed = base::JSONReader::Read(raw_response);
scoped_ptr<NavigationCorrectionResponse> response(
new NavigationCorrectionResponse());
base::JSONValueConverter<NavigationCorrectionResponse> converter;
if (!parsed || !converter.Convert(*parsed, response.get()))
response.reset();
return response.Pass();
}
scoped_ptr<ErrorPageParams> CreateErrorPageParams(
const NavigationCorrectionResponse& response,
const blink::WebURLError& error,
const NetErrorHelperCore::NavigationCorrectionParams& correction_params,
const std::string& accept_languages,
bool is_rtl) {
// Version of URL for display in suggestions. It has to be sanitized first
// because any received suggestions will be relative to the sanitized URL.
base::string16 original_url_for_display =
FormatURLForDisplay(SanitizeURL(GURL(error.unreachableURL)), is_rtl,
accept_languages);
scoped_ptr<ErrorPageParams> params(new ErrorPageParams());
params->override_suggestions.reset(new base::ListValue());
scoped_ptr<base::ListValue> parsed_corrections(new base::ListValue());
for (ScopedVector<NavigationCorrection>::const_iterator it =
response.corrections.begin();
it != response.corrections.end(); ++it) {
// Doesn't seem like a good idea to show these.
if ((*it)->is_porn || (*it)->is_soft_porn)
continue;
int tracking_id = it - response.corrections.begin();
if ((*it)->correction_type == "reloadPage") {
params->suggest_reload = true;
params->reload_tracking_id = tracking_id;
continue;
}
if ((*it)->correction_type == "webSearchQuery") {
// If there are mutliple searches suggested, use the first suggestion.
if (params->search_terms.empty()) {
params->search_url = correction_params.search_url;
params->search_terms = (*it)->url_correction;
params->search_tracking_id = tracking_id;
}
continue;
}
// Allow reload page and web search query to be empty strings, but not
// links.
if ((*it)->url_correction.empty())
continue;
size_t correction_index;
for (correction_index = 0;
correction_index < arraysize(kCorrectionResourceTable);
++correction_index) {
if ((*it)->correction_type !=
kCorrectionResourceTable[correction_index].correction_type) {
continue;
}
base::DictionaryValue* suggest = new base::DictionaryValue();
suggest->SetString("header",
l10n_util::GetStringUTF16(
kCorrectionResourceTable[correction_index].resource_id));
suggest->SetString("urlCorrection", (*it)->url_correction);
suggest->SetString(
"urlCorrectionForDisplay",
FormatURLForDisplay(GURL((*it)->url_correction), is_rtl,
accept_languages));
suggest->SetString("originalUrlForDisplay", original_url_for_display);
suggest->SetInteger("trackingId", tracking_id);
suggest->SetInteger("type", static_cast<int>(correction_index));
params->override_suggestions->Append(suggest);
break;
}
}
if (params->override_suggestions->empty() && !params->search_url.is_valid())
params.reset();
return params.Pass();
}
void ReportAutoReloadSuccess(const blink::WebURLError& error, size_t count) {
if (error.domain.utf8() != net::kErrorDomain)
return;
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.AutoReload.ErrorAtSuccess", -error.reason);
UMA_HISTOGRAM_COUNTS("Net.AutoReload.CountAtSuccess",
static_cast<base::HistogramBase::Sample>(count));
if (count == 1) {
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.AutoReload.ErrorAtFirstSuccess",
-error.reason);
}
}
void ReportAutoReloadFailure(const blink::WebURLError& error, size_t count) {
if (error.domain.utf8() != net::kErrorDomain)
return;
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.AutoReload.ErrorAtStop", -error.reason);
UMA_HISTOGRAM_COUNTS("Net.AutoReload.CountAtStop",
static_cast<base::HistogramBase::Sample>(count));
}
} // namespace
struct NetErrorHelperCore::ErrorPageInfo {
ErrorPageInfo(blink::WebURLError error,
bool was_failed_post,
bool was_ignoring_cache)
: error(error),
was_failed_post(was_failed_post),
was_ignoring_cache(was_ignoring_cache),
needs_dns_updates(false),
needs_load_navigation_corrections(false),
reload_button_in_page(false),
show_saved_copy_button_in_page(false),
show_cached_copy_button_in_page(false),
show_offline_pages_button_in_page(false),
show_offline_copy_button_in_page(false),
is_finished_loading(false),
auto_reload_triggered(false) {}
// Information about the failed page load.
blink::WebURLError error;
bool was_failed_post;
bool was_ignoring_cache;
// Information about the status of the error page.
// True if a page is a DNS error page and has not yet received a final DNS
// probe status.
bool needs_dns_updates;
// True if a blank page was loaded, and navigation corrections need to be
// loaded to generate the real error page.
bool needs_load_navigation_corrections;
// Navigation correction service paramers, which will be used in response to
// certain types of network errors. They are all stored here in case they
// change over the course of displaying the error page.
scoped_ptr<NetErrorHelperCore::NavigationCorrectionParams>
navigation_correction_params;
scoped_ptr<NavigationCorrectionResponse> navigation_correction_response;
// All the navigation corrections that have been clicked, for tracking
// purposes.
std::set<int> clicked_corrections;
// Track if specific buttons are included in an error page, for statistics.
bool reload_button_in_page;
bool show_saved_copy_button_in_page;
bool show_cached_copy_button_in_page;
bool show_offline_pages_button_in_page;
bool show_offline_copy_button_in_page;
// True if a page has completed loading, at which point it can receive
// updates.
bool is_finished_loading;
// True if the auto-reload timer has fired and a reload is or has been in
// flight.
bool auto_reload_triggered;
};
NetErrorHelperCore::NavigationCorrectionParams::NavigationCorrectionParams() {
}
NetErrorHelperCore::NavigationCorrectionParams::~NavigationCorrectionParams() {
}
bool NetErrorHelperCore::IsReloadableError(
const NetErrorHelperCore::ErrorPageInfo& info) {
GURL url = info.error.unreachableURL;
return info.error.domain.utf8() == net::kErrorDomain &&
info.error.reason != net::ERR_ABORTED &&
// For now, net::ERR_UNKNOWN_URL_SCHEME is only being displayed on
// Chrome for Android.
info.error.reason != net::ERR_UNKNOWN_URL_SCHEME &&
// Do not trigger if the server rejects a client certificate.
// https://crbug.com/431387
!net::IsClientCertificateError(info.error.reason) &&
// Some servers reject client certificates with a generic
// handshake_failure alert.
// https://crbug.com/431387
info.error.reason != net::ERR_SSL_PROTOCOL_ERROR &&
!info.was_failed_post &&
// Don't auto-reload non-http/https schemas.
// https://crbug.com/471713
url.SchemeIsHTTPOrHTTPS();
}
NetErrorHelperCore::NetErrorHelperCore(Delegate* delegate,
bool auto_reload_enabled,
bool auto_reload_visible_only,
bool is_visible)
: delegate_(delegate),
last_probe_status_(DNS_PROBE_POSSIBLE),
can_show_network_diagnostics_dialog_(false),
auto_reload_enabled_(auto_reload_enabled),
auto_reload_visible_only_(auto_reload_visible_only),
auto_reload_timer_(new base::Timer(false, false)),
auto_reload_paused_(false),
auto_reload_in_flight_(false),
uncommitted_load_started_(false),
// TODO(ellyjones): Make online_ accurate at object creation.
online_(true),
visible_(is_visible),
auto_reload_count_(0),
#if defined(OS_ANDROID)
offline_page_status_(OfflinePageStatus::NONE),
#endif // defined(OS_ANDROID)
navigation_from_button_(NO_BUTTON) {
}
NetErrorHelperCore::~NetErrorHelperCore() {
if (committed_error_page_info_ &&
committed_error_page_info_->auto_reload_triggered) {
ReportAutoReloadFailure(committed_error_page_info_->error,
auto_reload_count_);
}
}
void NetErrorHelperCore::CancelPendingFetches() {
RecordHistoryDebugEvent(HistoryDebugEvent::CANCEL_PENDING_FETCHES);
// Cancel loading the alternate error page, and prevent any pending error page
// load from starting a new error page load. Swapping in the error page when
// it's finished loading could abort the navigation, otherwise.
if (committed_error_page_info_)
committed_error_page_info_->needs_load_navigation_corrections = false;
if (pending_error_page_info_)
pending_error_page_info_->needs_load_navigation_corrections = false;
delegate_->CancelFetchNavigationCorrections();
auto_reload_timer_->Stop();
auto_reload_paused_ = false;
}
void NetErrorHelperCore::OnStop() {
RecordHistoryDebugEvent(HistoryDebugEvent::ON_STOP);
if (committed_error_page_info_ &&
committed_error_page_info_->auto_reload_triggered) {
ReportAutoReloadFailure(committed_error_page_info_->error,
auto_reload_count_);
}
CancelPendingFetches();
uncommitted_load_started_ = false;
auto_reload_count_ = 0;
auto_reload_in_flight_ = false;
}
void NetErrorHelperCore::OnWasShown() {
RecordHistoryDebugEvent(HistoryDebugEvent::ON_WAS_SHOWN);
visible_ = true;
if (!auto_reload_visible_only_)
return;
if (auto_reload_paused_)
MaybeStartAutoReloadTimer();
}
void NetErrorHelperCore::OnWasHidden() {
RecordHistoryDebugEvent(HistoryDebugEvent::ON_WAS_HIDDEN);
visible_ = false;
if (!auto_reload_visible_only_)
return;
PauseAutoReloadTimer();
}
void NetErrorHelperCore::OnStartLoad(FrameType frame_type, PageType page_type) {
if (frame_type != MAIN_FRAME)
return;
RecordHistoryDebugEvent(HistoryDebugEvent::ON_START_LOAD);
uncommitted_load_started_ = true;
// If there's no pending error page information associated with the page load,
// or the new page is not an error page, then reset pending error page state.
if (!pending_error_page_info_ || page_type != ERROR_PAGE)
CancelPendingFetches();
}
void NetErrorHelperCore::OnCommitLoad(FrameType frame_type, const GURL& url) {
if (frame_type != MAIN_FRAME)
return;
RecordHistoryDebugEvent(HistoryDebugEvent::ON_COMMIT_LOAD);
// If a page is committing, either it's an error page and autoreload will be
// started again below, or it's a success page and we need to clear autoreload
// state.
auto_reload_in_flight_ = false;
// uncommitted_load_started_ could already be false, since RenderFrameImpl
// calls OnCommitLoad once for each in-page navigation (like a fragment
// change) with no corresponding OnStartLoad.
uncommitted_load_started_ = false;
// Track if an error occurred due to a page button press.
// This isn't perfect; if (for instance), the server is slow responding
// to a request generated from the page reload button, and the user hits
// the browser reload button, this code will still believe the
// result is from the page reload button.
if (committed_error_page_info_ && pending_error_page_info_ &&
navigation_from_button_ != NO_BUTTON &&
committed_error_page_info_->error.unreachableURL ==
pending_error_page_info_->error.unreachableURL) {
DCHECK(navigation_from_button_ == RELOAD_BUTTON ||
navigation_from_button_ == SHOW_SAVED_COPY_BUTTON);
RecordEvent(navigation_from_button_ == RELOAD_BUTTON ?
NETWORK_ERROR_PAGE_RELOAD_BUTTON_ERROR :
NETWORK_ERROR_PAGE_SHOW_SAVED_COPY_BUTTON_ERROR);
}
navigation_from_button_ = NO_BUTTON;
if (committed_error_page_info_ && !pending_error_page_info_ &&
committed_error_page_info_->auto_reload_triggered) {
const blink::WebURLError& error = committed_error_page_info_->error;
const GURL& error_url = error.unreachableURL;
if (url == error_url)
ReportAutoReloadSuccess(error, auto_reload_count_);
else if (url != GURL(content::kUnreachableWebDataURL))
ReportAutoReloadFailure(error, auto_reload_count_);
}
committed_error_page_info_.reset(pending_error_page_info_.release());
RecordHistoryDebugEvent(HistoryDebugEvent::ON_COMMIT_LOAD_END);
}
void NetErrorHelperCore::OnFinishLoad(FrameType frame_type) {
if (frame_type != MAIN_FRAME)
return;
RecordHistoryDebugEvent(HistoryDebugEvent::ON_FINISH_LOAD);
if (!committed_error_page_info_) {
auto_reload_count_ = 0;
RecordHistoryDebugEvent(
HistoryDebugEvent::ON_FINISH_LOAD_END_NOT_ERROR_PAGE);
return;
}
committed_error_page_info_->is_finished_loading = true;
RecordEvent(NETWORK_ERROR_PAGE_SHOWN);
if (committed_error_page_info_->reload_button_in_page) {
RecordEvent(NETWORK_ERROR_PAGE_RELOAD_BUTTON_SHOWN);
}
if (committed_error_page_info_->show_saved_copy_button_in_page) {
RecordEvent(NETWORK_ERROR_PAGE_SHOW_SAVED_COPY_BUTTON_SHOWN);
}
if (committed_error_page_info_->show_offline_pages_button_in_page) {
RecordEvent(NETWORK_ERROR_PAGE_SHOW_OFFLINE_PAGES_BUTTON_SHOWN);
}
if (committed_error_page_info_->show_offline_copy_button_in_page) {
RecordEvent(NETWORK_ERROR_PAGE_SHOW_OFFLINE_COPY_BUTTON_SHOWN);
}
if (committed_error_page_info_->reload_button_in_page &&
committed_error_page_info_->show_saved_copy_button_in_page) {
RecordEvent(NETWORK_ERROR_PAGE_BOTH_BUTTONS_SHOWN);
}
if (committed_error_page_info_->show_cached_copy_button_in_page) {
RecordEvent(NETWORK_ERROR_PAGE_CACHED_COPY_BUTTON_SHOWN);
}
delegate_->EnablePageHelperFunctions();
if (committed_error_page_info_->needs_load_navigation_corrections) {
// If there is another pending error page load, |fix_url| should have been
// cleared.
DCHECK(!pending_error_page_info_);
DCHECK(!committed_error_page_info_->needs_dns_updates);
delegate_->FetchNavigationCorrections(
committed_error_page_info_->navigation_correction_params->url,
CreateFixUrlRequestBody(
committed_error_page_info_->error,
*committed_error_page_info_->navigation_correction_params));
} else if (auto_reload_enabled_ &&
IsReloadableError(*committed_error_page_info_)) {
MaybeStartAutoReloadTimer();
}
if (!committed_error_page_info_->needs_dns_updates ||
last_probe_status_ == DNS_PROBE_POSSIBLE) {
RecordHistoryDebugEvent(HistoryDebugEvent::ON_FINISH_LOAD_END_DNS_PROBE);
return;
}
DVLOG(1) << "Error page finished loading; sending saved status.";
UpdateErrorPage();
RecordHistoryDebugEvent(HistoryDebugEvent::ON_FINISH_LOAD_END_NO_DNS_PROBE);
}
void NetErrorHelperCore::GetErrorHTML(FrameType frame_type,
const blink::WebURLError& error,
bool is_failed_post,
bool is_ignoring_cache,
std::string* error_html) {
if (frame_type == MAIN_FRAME) {
// If navigation corrections were needed before, that should have been
// cancelled earlier by starting a new page load (Which has now failed).
DCHECK(!committed_error_page_info_ ||
!committed_error_page_info_->needs_load_navigation_corrections);
RecordHistoryDebugEvent(HistoryDebugEvent::GET_ERROR_HTML);
pending_error_page_info_.reset(
new ErrorPageInfo(error, is_failed_post, is_ignoring_cache));
pending_error_page_info_->navigation_correction_params.reset(
new NavigationCorrectionParams(navigation_correction_params_));
GetErrorHtmlForMainFrame(pending_error_page_info_.get(), error_html);
} else {
// These values do not matter, as error pages in iframes hide the buttons.
bool reload_button_in_page;
bool show_saved_copy_button_in_page;
bool show_cached_copy_button_in_page;
bool show_offline_pages_button_in_page;
bool show_offline_copy_button_in_page;
delegate_->GenerateLocalizedErrorPage(
error, is_failed_post,
false /* No diagnostics dialogs allowed for subframes. */,
OfflinePageStatus::NONE /* No offline button provided in subframes */,
scoped_ptr<ErrorPageParams>(), &reload_button_in_page,
&show_saved_copy_button_in_page, &show_cached_copy_button_in_page,
&show_offline_pages_button_in_page,
&show_offline_copy_button_in_page, error_html);
}
}
void NetErrorHelperCore::OnNetErrorInfo(DnsProbeStatus status) {
DCHECK_NE(DNS_PROBE_POSSIBLE, status);
RecordHistoryDebugEvent(HistoryDebugEvent::NET_ERROR_INFO_RECEIVED);
last_probe_status_ = status;
if (!committed_error_page_info_ ||
!committed_error_page_info_->needs_dns_updates ||
!committed_error_page_info_->is_finished_loading) {
return;
}
UpdateErrorPage();
}
void NetErrorHelperCore::OnSetCanShowNetworkDiagnosticsDialog(
bool can_show_network_diagnostics_dialog) {
can_show_network_diagnostics_dialog_ = can_show_network_diagnostics_dialog;
}
void NetErrorHelperCore::OnSetNavigationCorrectionInfo(
const GURL& navigation_correction_url,
const std::string& language,
const std::string& country_code,
const std::string& api_key,
const GURL& search_url) {
navigation_correction_params_.url = navigation_correction_url;
navigation_correction_params_.language = language;
navigation_correction_params_.country_code = country_code;
navigation_correction_params_.api_key = api_key;
navigation_correction_params_.search_url = search_url;
}
void NetErrorHelperCore::OnSetOfflinePageInfo(
OfflinePageStatus offline_page_status) {
#if defined(OS_ANDROID)
offline_page_status_ = offline_page_status;
#endif // defined(OS_ANDROID)
}
void NetErrorHelperCore::GetErrorHtmlForMainFrame(
ErrorPageInfo* pending_error_page_info,
std::string* error_html) {
std::string error_param;
blink::WebURLError error = pending_error_page_info->error;
if (pending_error_page_info->navigation_correction_params &&
pending_error_page_info->navigation_correction_params->url.is_valid() &&
ShouldUseFixUrlServiceForError(error, &error_param)) {
pending_error_page_info->needs_load_navigation_corrections = true;
return;
}
if (IsDnsError(pending_error_page_info->error)) {
// The last probe status needs to be reset if this is a DNS error. This
// means that if a DNS error page is committed but has not yet finished
// loading, a DNS probe status scheduled to be sent to it may be thrown
// out, but since the new error page should trigger a new DNS probe, it
// will just get the results for the next page load.
last_probe_status_ = DNS_PROBE_POSSIBLE;
pending_error_page_info->needs_dns_updates = true;
error = GetUpdatedError(error);
}
delegate_->GenerateLocalizedErrorPage(
error, pending_error_page_info->was_failed_post,
can_show_network_diagnostics_dialog_,
GetOfflinePageStatus(),
scoped_ptr<ErrorPageParams>(),
&pending_error_page_info->reload_button_in_page,
&pending_error_page_info->show_saved_copy_button_in_page,
&pending_error_page_info->show_cached_copy_button_in_page,
&pending_error_page_info->show_offline_pages_button_in_page,
&pending_error_page_info->show_offline_copy_button_in_page,
error_html);
}
void NetErrorHelperCore::UpdateErrorPage() {
DCHECK(committed_error_page_info_->needs_dns_updates);
DCHECK(committed_error_page_info_->is_finished_loading);
DCHECK_NE(DNS_PROBE_POSSIBLE, last_probe_status_);
RecordHistoryDebugEvent(HistoryDebugEvent::UPDATE_ERROR_PAGE);
UMA_HISTOGRAM_ENUMERATION("DnsProbe.ErrorPageUpdateStatus",
last_probe_status_,
DNS_PROBE_MAX);
// Every status other than DNS_PROBE_POSSIBLE and DNS_PROBE_STARTED is a
// final status code. Once one is reached, the page does not need further
// updates.
if (last_probe_status_ != DNS_PROBE_STARTED)
committed_error_page_info_->needs_dns_updates = false;
// There is no need to worry about the button display statistics here because
// the presentation of the reload and show saved copy buttons can't be changed
// by a DNS error update.
delegate_->UpdateErrorPage(
GetUpdatedError(committed_error_page_info_->error),
committed_error_page_info_->was_failed_post,
can_show_network_diagnostics_dialog_,
GetOfflinePageStatus());
}
void NetErrorHelperCore::OnNavigationCorrectionsFetched(
const std::string& corrections,
const std::string& accept_languages,
bool is_rtl) {
// Loading suggestions only starts when a blank error page finishes loading,
// and is cancelled with a new load.
DCHECK(!pending_error_page_info_);
DCHECK(committed_error_page_info_->is_finished_loading);
DCHECK(committed_error_page_info_->needs_load_navigation_corrections);
DCHECK(committed_error_page_info_->navigation_correction_params);
RecordHistoryDebugEvent(HistoryDebugEvent::NAVIGATION_CORRECTIONS_FETCHED);
pending_error_page_info_.reset(new ErrorPageInfo(
committed_error_page_info_->error,
committed_error_page_info_->was_failed_post,
committed_error_page_info_->was_ignoring_cache));
pending_error_page_info_->navigation_correction_response =
ParseNavigationCorrectionResponse(corrections);
std::string error_html;
scoped_ptr<ErrorPageParams> params;
if (pending_error_page_info_->navigation_correction_response) {
// Copy navigation correction parameters used for the request, so tracking
// requests can still be sent if the configuration changes.
pending_error_page_info_->navigation_correction_params.reset(
new NavigationCorrectionParams(
*committed_error_page_info_->navigation_correction_params));
params = CreateErrorPageParams(
*pending_error_page_info_->navigation_correction_response,
pending_error_page_info_->error,
*pending_error_page_info_->navigation_correction_params,
accept_languages, is_rtl);
delegate_->GenerateLocalizedErrorPage(
pending_error_page_info_->error,
pending_error_page_info_->was_failed_post,
can_show_network_diagnostics_dialog_,
GetOfflinePageStatus(),
params.Pass(),
&pending_error_page_info_->reload_button_in_page,
&pending_error_page_info_->show_saved_copy_button_in_page,
&pending_error_page_info_->show_cached_copy_button_in_page,
&pending_error_page_info_->show_offline_pages_button_in_page,
&pending_error_page_info_->show_offline_copy_button_in_page,
&error_html);
} else {
// Since |navigation_correction_params| in |pending_error_page_info_| is
// NULL, this won't trigger another attempt to load corrections.
GetErrorHtmlForMainFrame(pending_error_page_info_.get(), &error_html);
}
// TODO(mmenke): Once the new API is in place, look into replacing this
// double page load by just updating the error page, like DNS
// probes do.
delegate_->LoadErrorPage(error_html,
pending_error_page_info_->error.unreachableURL);
}
blink::WebURLError NetErrorHelperCore::GetUpdatedError(
const blink::WebURLError& error) const {
// If a probe didn't run or wasn't conclusive, restore the original error.
if (last_probe_status_ == DNS_PROBE_NOT_RUN ||
last_probe_status_ == DNS_PROBE_FINISHED_INCONCLUSIVE) {
return error;
}
blink::WebURLError updated_error;
updated_error.domain = blink::WebString::fromUTF8(kDnsProbeErrorDomain);
updated_error.reason = last_probe_status_;
updated_error.unreachableURL = error.unreachableURL;
updated_error.staleCopyInCache = error.staleCopyInCache;
return updated_error;
}
void NetErrorHelperCore::Reload(bool ignore_cache) {
RecordHistoryDebugEvent(HistoryDebugEvent::RELOAD);
if (!committed_error_page_info_) {
return;
}
delegate_->ReloadPage(ignore_cache);
}
bool NetErrorHelperCore::MaybeStartAutoReloadTimer() {
RecordHistoryDebugEvent(HistoryDebugEvent::MAYBE_RELOAD);
if (!committed_error_page_info_ ||
!committed_error_page_info_->is_finished_loading ||
pending_error_page_info_ ||
uncommitted_load_started_) {
return false;
}
StartAutoReloadTimer();
return true;
}
void NetErrorHelperCore::StartAutoReloadTimer() {
DCHECK(committed_error_page_info_);
DCHECK(IsReloadableError(*committed_error_page_info_));
RecordHistoryDebugEvent(HistoryDebugEvent::START_RELOAD_TIMER);
committed_error_page_info_->auto_reload_triggered = true;
if (!online_ || (!visible_ && auto_reload_visible_only_)) {
RecordHistoryDebugEvent(HistoryDebugEvent::START_RELOAD_TIMER_PAUSED);
auto_reload_paused_ = true;
return;
}
auto_reload_paused_ = false;
base::TimeDelta delay = GetAutoReloadTime(auto_reload_count_);
auto_reload_timer_->Stop();
auto_reload_timer_->Start(FROM_HERE, delay,
base::Bind(&NetErrorHelperCore::AutoReloadTimerFired,
base::Unretained(this)));
}
void NetErrorHelperCore::AutoReloadTimerFired() {
// AutoReloadTimerFired only runs if:
// 1. StartAutoReloadTimer was previously called, which requires that
// committed_error_page_info_ is populated;
// 2. No other page load has started since (1), since OnStartLoad stops the
// auto-reload timer.
DCHECK(committed_error_page_info_);
RecordHistoryDebugEvent(HistoryDebugEvent::RELOAD_TIMER_FIRED);
auto_reload_count_++;
auto_reload_in_flight_ = true;
if (!committed_error_page_info_) {
HistoryDebugEvent history_debug_events[MAX_DEBUG_HISTORY_EVENTS];
size_t num_history_debug_events = history_debug_events_.size();
for (size_t i = 0; i < num_history_debug_events; ++i) {
history_debug_events[i] = history_debug_events_[i];
}
base::debug::Alias(history_debug_events);
base::debug::Alias(&num_history_debug_events);
base::debug::DumpWithoutCrashing();
return;
}
Reload(committed_error_page_info_->was_ignoring_cache);
}
void NetErrorHelperCore::PauseAutoReloadTimer() {
RecordHistoryDebugEvent(HistoryDebugEvent::PAUSE_RELOAD_TIMER);
if (!auto_reload_timer_->IsRunning())
return;
DCHECK(committed_error_page_info_);
DCHECK(!auto_reload_paused_);
DCHECK(committed_error_page_info_->auto_reload_triggered);
auto_reload_timer_->Stop();
auto_reload_paused_ = true;
}
void NetErrorHelperCore::NetworkStateChanged(bool online) {
RecordHistoryDebugEvent(HistoryDebugEvent::NETWORK_STATE_CHANGED);
bool was_online = online_;
online_ = online;
if (!was_online && online) {
// Transitioning offline -> online
if (auto_reload_paused_)
MaybeStartAutoReloadTimer();
} else if (was_online && !online) {
// Transitioning online -> offline
if (auto_reload_timer_->IsRunning())
auto_reload_count_ = 0;
PauseAutoReloadTimer();
}
}
bool NetErrorHelperCore::ShouldSuppressErrorPage(FrameType frame_type,
const GURL& url) {
// Don't suppress child frame errors.
if (frame_type != MAIN_FRAME)
return false;
RecordHistoryDebugEvent(HistoryDebugEvent::SHOULD_SUPPRESS_ERROR_PAGE);
// If there's no auto reload attempt in flight, this error page didn't come
// from auto reload, so don't suppress it.
if (!auto_reload_in_flight_)
return false;
uncommitted_load_started_ = false;
// This serves to terminate the auto-reload in flight attempt. If
// ShouldSuppressErrorPage is called, the auto-reload yielded an error, which
// means the request was already sent.
auto_reload_in_flight_ = false;
MaybeStartAutoReloadTimer();
return true;
}
void NetErrorHelperCore::ExecuteButtonPress(Button button) {
// If there's no committed error page, should not be invoked.
DCHECK(committed_error_page_info_);
RecordHistoryDebugEvent(HistoryDebugEvent::EXECUTE_BUTTON_PRESS);
switch (button) {
case RELOAD_BUTTON:
RecordEvent(NETWORK_ERROR_PAGE_RELOAD_BUTTON_CLICKED);
if (committed_error_page_info_->show_saved_copy_button_in_page) {
RecordEvent(NETWORK_ERROR_PAGE_BOTH_BUTTONS_RELOAD_CLICKED);
}
navigation_from_button_ = RELOAD_BUTTON;
Reload(false);
return;
case SHOW_SAVED_COPY_BUTTON:
RecordEvent(NETWORK_ERROR_PAGE_SHOW_SAVED_COPY_BUTTON_CLICKED);
navigation_from_button_ = SHOW_SAVED_COPY_BUTTON;
if (committed_error_page_info_->reload_button_in_page) {
RecordEvent(NETWORK_ERROR_PAGE_BOTH_BUTTONS_SHOWN_SAVED_COPY_CLICKED);
}
delegate_->LoadPageFromCache(
committed_error_page_info_->error.unreachableURL);
return;
case MORE_BUTTON:
// Visual effects on page are handled in Javascript code.
RecordEvent(NETWORK_ERROR_PAGE_MORE_BUTTON_CLICKED);
return;
case EASTER_EGG:
RecordEvent(NETWORK_ERROR_EASTER_EGG_ACTIVATED);
return;
case SHOW_CACHED_COPY_BUTTON:
RecordEvent(NETWORK_ERROR_PAGE_CACHED_COPY_BUTTON_CLICKED);
return;
case DIAGNOSE_ERROR:
RecordEvent(NETWORK_ERROR_DIAGNOSE_BUTTON_CLICKED);
delegate_->DiagnoseError(
committed_error_page_info_->error.unreachableURL);
return;
case SHOW_OFFLINE_PAGES_BUTTON:
RecordEvent(NETWORK_ERROR_PAGE_SHOW_OFFLINE_PAGES_BUTTON_CLICKED);
delegate_->ShowOfflinePages();
return;
case SHOW_OFFLINE_COPY_BUTTON:
RecordEvent(NETWORK_ERROR_PAGE_SHOW_OFFLINE_COPY_BUTTON_CLICKED);
delegate_->LoadOfflineCopy(
committed_error_page_info_->error.unreachableURL);
return;
case NO_BUTTON:
NOTREACHED();
return;
}
}
void NetErrorHelperCore::TrackClick(int tracking_id) {
// It's technically possible for |navigation_correction_params| to be NULL but
// for |navigation_correction_response| not to be NULL, if the paramters
// changed between loading the original error page and loading the error page
if (!committed_error_page_info_ ||
!committed_error_page_info_->navigation_correction_response) {
return;
}
NavigationCorrectionResponse* response =
committed_error_page_info_->navigation_correction_response.get();
// |tracking_id| is less than 0 when the error page was not generated by the
// navigation correction service. |tracking_id| should never be greater than
// the array size, but best to be safe, since it contains data from a remote
// site, though none of that data should make it into Javascript callbacks.
if (tracking_id < 0 ||
static_cast<size_t>(tracking_id) >= response->corrections.size()) {
return;
}
// Only report a clicked link once.
if (committed_error_page_info_->clicked_corrections.count(tracking_id))
return;
committed_error_page_info_->clicked_corrections.insert(tracking_id);
std::string request_body = CreateClickTrackingUrlRequestBody(
committed_error_page_info_->error,
*committed_error_page_info_->navigation_correction_params,
*response,
*response->corrections[tracking_id]);
delegate_->SendTrackingRequest(
committed_error_page_info_->navigation_correction_params->url,
request_body);
}
OfflinePageStatus NetErrorHelperCore::GetOfflinePageStatus() const {
#if defined(OS_ANDROID)
return offline_page_status_;
#else
return OfflinePageStatus::NONE;
#endif // defined(OS_ANDROID)
}
void NetErrorHelperCore::RecordHistoryDebugEvent(
HistoryDebugEvent::EventType event_type) {
if (history_debug_events_.size() > MAX_DEBUG_HISTORY_EVENTS)
history_debug_events_.erase(history_debug_events_.begin());
HistoryDebugEvent event;
event.event_type = event_type;
event.pending_error_page_info_exists = !!pending_error_page_info_;
event.committed_error_page_info_exists = !!committed_error_page_info_;
event.timer_running = auto_reload_timer_->IsRunning();
history_debug_events_.push_back(event);
}
} // namespace error_page
| Workday/OpenFrame | components/error_page/renderer/net_error_helper_core.cc | C++ | bsd-3-clause | 42,701 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
from datetime import datetime
import doctest
import os
import os.path
import shutil
from StringIO import StringIO
import time
import tempfile
import threading
import unittest
import urlparse
from couchdb import client, http
from couchdb.tests import testutil
from schematics.validation import validate_instance
class ServerTestCase(testutil.TempDatabaseMixin, unittest.TestCase):
def test_init_with_resource(self):
sess = http.Session()
res = http.Resource(client.DEFAULT_BASE_URL, sess)
serv = client.Server(url=res)
serv.config()
def test_init_with_session(self):
sess = http.Session()
serv = client.Server(client.DEFAULT_BASE_URL, session=sess)
serv.config()
self.assertTrue(serv.resource.session is sess)
def test_exists(self):
self.assertTrue(client.Server(client.DEFAULT_BASE_URL))
self.assertFalse(client.Server('http://localhost:9999'))
def test_repr(self):
repr(self.server)
def test_server_vars(self):
version = self.server.version()
self.assertTrue(isinstance(version, basestring))
config = self.server.config()
self.assertTrue(isinstance(config, dict))
tasks = self.server.tasks()
self.assertTrue(isinstance(tasks, list))
def test_server_stats(self):
stats = self.server.stats()
self.assertTrue(isinstance(stats, dict))
stats = self.server.stats('httpd/requests')
self.assertTrue(isinstance(stats, dict))
self.assertTrue(len(stats) == 1 and len(stats['httpd']) == 1)
def test_get_db_missing(self):
self.assertRaises(http.ResourceNotFound,
lambda: self.server['couchdb-python/missing'])
def test_create_db_conflict(self):
name, db = self.temp_db()
self.assertRaises(http.PreconditionFailed, self.server.create,
name)
def test_delete_db(self):
name, db = self.temp_db()
assert name in self.server
self.del_db(name)
assert name not in self.server
def test_delete_db_missing(self):
self.assertRaises(http.ResourceNotFound, self.server.delete,
'couchdb-python/missing')
def test_replicate(self):
aname, a = self.temp_db()
bname, b = self.temp_db()
id, rev = a.save({'test': 'a'})
result = self.server.replicate(aname, bname)
self.assertEquals(result['ok'], True)
self.assertEquals(b[id]['test'], 'a')
doc = b[id]
doc['test'] = 'b'
b.update([doc],validate=False)
self.server.replicate(bname, aname)
self.assertEquals(a[id]['test'], 'b')
self.assertEquals(b[id]['test'], 'b')
def test_replicate_continuous(self):
aname, a = self.temp_db()
bname, b = self.temp_db()
result = self.server.replicate(aname, bname, continuous=True)
self.assertEquals(result['ok'], True)
version = tuple(int(i) for i in self.server.version().split('.')[:2])
if version >= (0, 10):
self.assertTrue('_local_id' in result)
def test_iter(self):
aname, a = self.temp_db()
bname, b = self.temp_db()
dbs = list(self.server)
self.assertTrue(aname in dbs)
self.assertTrue(bname in dbs)
def test_len(self):
self.temp_db()
self.temp_db()
self.assertTrue(len(self.server) >= 2)
def test_uuids(self):
ls = self.server.uuids()
assert type(ls) == list
ls = self.server.uuids(count=10)
assert type(ls) == list and len(ls) == 10
class DatabaseTestCase(testutil.TempDatabaseMixin, unittest.TestCase):
def test_save_new(self):
doc = {'foo': 'bar'}
id, rev = self.db.save(doc)
self.assertTrue(id is not None)
self.assertTrue(rev is not None)
self.assertEqual((id, rev), (doc['_id'], doc['_rev']))
doc = self.db.get(id)
self.assertEqual(doc['foo'], 'bar')
def test_save_new_with_id(self):
doc = {'_id': 'foo'}
id, rev = self.db.save(doc)
self.assertTrue(doc['_id'] == id == 'foo')
self.assertEqual(doc['_rev'], rev)
def test_save_existing(self):
doc = {}
id_rev_old = self.db.save(doc)
doc['foo'] = True
id_rev_new = self.db.save(doc)
self.assertTrue(doc['_rev'] == id_rev_new[1])
self.assertTrue(id_rev_old[1] != id_rev_new[1])
def test_save_new_batch(self):
doc = {'_id': 'foo'}
id, rev = self.db.save(doc, batch='ok')
self.assertTrue(rev is None)
self.assertTrue('_rev' not in doc)
def test_save_existing_batch(self):
doc = {'_id': 'foo'}
self.db.save(doc)
id_rev_old = self.db.save(doc)
id_rev_new = self.db.save(doc, batch='ok')
self.assertTrue(id_rev_new[1] is None)
self.assertEqual(id_rev_old[1], doc['_rev'])
def test_exists(self):
self.assertTrue(self.db)
self.assertFalse(client.Database('couchdb-python/missing'))
def test_name(self):
# Access name assigned during creation.
name, db = self.temp_db()
self.assertTrue(db.name == name)
# Access lazily loaded name,
self.assertTrue(client.Database(db.resource.url).name == name)
def test_commit(self):
self.assertTrue(self.db.commit()['ok'] == True)
def test_create_large_doc(self):
self.db['foo'] = {'data': '0123456789' * 110 * 1024} # 10 MB
self.assertEqual('foo', self.db['foo']['_id'])
def test_doc_id_quoting(self):
self.db['foo/bar'] = {'foo': 'bar'}
self.assertEqual('bar', self.db['foo/bar']['foo'])
del self.db['foo/bar']
self.assertEqual(None, self.db.get('foo/bar'))
def test_unicode(self):
self.db[u'føø'] = {u'bår': u'Iñtërnâtiônàlizætiøn', 'baz': 'ASCII'}
self.assertEqual(u'Iñtërnâtiônàlizætiøn', self.db[u'føø'][u'bår'])
self.assertEqual(u'ASCII', self.db[u'føø'][u'baz'])
def test_disallow_nan(self):
try:
self.db['foo'] = {u'number': float('nan')}
self.fail('Expected ValueError')
except ValueError:
pass
def test_disallow_none_id(self):
deldoc = lambda: self.db.delete({'_id': None, '_rev': None})
self.assertRaises(ValueError, deldoc)
def test_doc_revs(self):
doc = {'bar': 42}
self.db['foo'] = doc
old_rev = doc['_rev']
doc['bar'] = 43
self.db['foo'] = doc
new_rev = doc['_rev']
new_doc = self.db.get('foo')
self.assertEqual(new_rev, new_doc['_rev'])
new_doc = self.db.get('foo', rev=new_rev)
self.assertEqual(new_rev, new_doc['_rev'])
old_doc = self.db.get('foo', rev=old_rev)
self.assertEqual(old_rev, old_doc['_rev'])
revs = [i for i in self.db.revisions('foo')]
self.assertEqual(revs[0]['_rev'], new_rev)
self.assertEqual(revs[1]['_rev'], old_rev)
gen = self.db.revisions('crap')
self.assertRaises(StopIteration, lambda: gen.next())
self.assertTrue(self.db.compact())
while self.db.info()['compact_running']:
pass
# 0.10 responds with 404, 0.9 responds with 500, same content
doc = 'fail'
try:
doc = self.db.get('foo', rev=old_rev)
except http.ServerError:
doc = None
assert doc is None
def test_attachment_crud(self):
doc = {'bar': 42}
self.db['foo'] = doc
old_rev = doc['_rev']
self.db.put_attachment(doc, 'Foo bar', 'foo.txt', 'text/plain')
self.assertNotEquals(old_rev, doc['_rev'])
doc = self.db['foo']
attachment = doc['_attachments']['foo.txt']
self.assertEqual(len('Foo bar'), attachment['length'])
self.assertEqual('text/plain', attachment['content_type'])
self.assertEqual('Foo bar',
self.db.get_attachment(doc, 'foo.txt').read())
self.assertEqual('Foo bar',
self.db.get_attachment('foo', 'foo.txt').read())
old_rev = doc['_rev']
self.db.delete_attachment(doc, 'foo.txt')
self.assertNotEquals(old_rev, doc['_rev'])
self.assertEqual(None, self.db['foo'].get('_attachments'))
def test_attachment_crud_with_files(self):
doc = {'bar': 42}
self.db['foo'] = doc
old_rev = doc['_rev']
fileobj = StringIO('Foo bar baz')
self.db.put_attachment(doc, fileobj, 'foo.txt')
self.assertNotEquals(old_rev, doc['_rev'])
doc = self.db['foo']
attachment = doc['_attachments']['foo.txt']
self.assertEqual(len('Foo bar baz'), attachment['length'])
self.assertEqual('text/plain', attachment['content_type'])
self.assertEqual('Foo bar baz',
self.db.get_attachment(doc, 'foo.txt').read())
self.assertEqual('Foo bar baz',
self.db.get_attachment('foo', 'foo.txt').read())
old_rev = doc['_rev']
self.db.delete_attachment(doc, 'foo.txt')
self.assertNotEquals(old_rev, doc['_rev'])
self.assertEqual(None, self.db['foo'].get('_attachments'))
def test_empty_attachment(self):
doc = {}
self.db['foo'] = doc
old_rev = doc['_rev']
self.db.put_attachment(doc, '', 'empty.txt')
self.assertNotEquals(old_rev, doc['_rev'])
doc = self.db['foo']
attachment = doc['_attachments']['empty.txt']
self.assertEqual(0, attachment['length'])
def test_default_attachment(self):
doc = {}
self.db['foo'] = doc
self.assertTrue(self.db.get_attachment(doc, 'missing.txt') is None)
sentinel = object()
self.assertTrue(self.db.get_attachment(doc, 'missing.txt', sentinel) is sentinel)
def test_attachment_from_fs(self):
tmpdir = tempfile.mkdtemp()
tmpfile = os.path.join(tmpdir, 'test.txt')
f = open(tmpfile, 'w')
f.write('Hello!')
f.close()
doc = {}
self.db['foo'] = doc
self.db.put_attachment(doc, open(tmpfile))
doc = self.db.get('foo')
self.assertTrue(doc['_attachments']['test.txt']['content_type'] == 'text/plain')
shutil.rmtree(tmpdir)
def test_attachment_no_filename(self):
doc = {}
self.db['foo'] = doc
self.assertRaises(ValueError, self.db.put_attachment, doc, '')
def test_json_attachment(self):
doc = {}
self.db['foo'] = doc
self.db.put_attachment(doc, '{}', 'test.json', 'application/json')
self.assertEquals(self.db.get_attachment(doc, 'test.json').read(), '{}')
def test_include_docs(self):
doc = {'foo': 42, 'bar': 40}
self.db['foo'] = doc
rows = list(self.db.query(
'function(doc) { emit(doc._id, null); }',
include_docs=True
))
self.assertEqual(1, len(rows))
self.assertEqual(doc, rows[0].doc)
def test_query_multi_get(self):
for i in range(1, 6):
self.db.save({'i': i})
res = list(self.db.query('function(doc) { emit(doc.i, null); }',
keys=range(1, 6, 2)))
self.assertEqual(3, len(res))
for idx, i in enumerate(range(1, 6, 2)):
self.assertEqual(i, res[idx].key)
def test_bulk_update_conflict(self):
docs = [
dict(type='Person', name='John Doe'),
dict(type='Person', name='Mary Jane'),
dict(type='City', name='Gotham City')
]
self.db.update(docs)
# update the first doc to provoke a conflict in the next bulk update
doc = docs[0].copy()
self.db[doc['_id']] = doc
results = self.db.update(docs)
self.assertEqual(False, results[0][0])
assert isinstance(results[0][2], http.ResourceConflict)
def test_bulk_update_all_or_nothing(self):
docs = [
dict(type='Person', name='John Doe'),
dict(type='Person', name='Mary Jane'),
dict(type='City', name='Gotham City')
]
self.db.update(docs)
# update the first doc to provoke a conflict in the next bulk update
doc = docs[0].copy()
doc['name'] = 'Jane Doe'
self.db[doc['_id']] = doc
results = self.db.update(docs, all_or_nothing=True)
self.assertEqual(True, results[0][0])
doc = self.db.get(doc['_id'], conflicts=True)
assert '_conflicts' in doc
revs = self.db.get(doc['_id'], open_revs='all')
assert len(revs) == 2
def test_bulk_update_bad_doc(self):
self.assertRaises(TypeError, self.db.update, [object()])
def test_copy_doc(self):
self.db['foo'] = {'status': 'testing'}
result = self.db.copy('foo', 'bar')
self.assertEqual(result, self.db['bar'].rev)
def test_copy_doc_conflict(self):
self.db['bar'] = {'status': 'idle'}
self.db['foo'] = {'status': 'testing'}
self.assertRaises(http.ResourceConflict, self.db.copy, 'foo', 'bar')
def test_copy_doc_overwrite(self):
self.db['bar'] = {'status': 'idle'}
self.db['foo'] = {'status': 'testing'}
result = self.db.copy('foo', self.db['bar'])
doc = self.db['bar']
self.assertEqual(result, doc.rev)
self.assertEqual('testing', doc['status'])
def test_copy_doc_srcobj(self):
self.db['foo'] = {'status': 'testing'}
self.db.copy(self.db['foo'], 'bar')
self.assertEqual('testing', self.db['bar']['status'])
def test_copy_doc_destobj_norev(self):
self.db['foo'] = {'status': 'testing'}
self.db.copy('foo', {'_id': 'bar'})
self.assertEqual('testing', self.db['bar']['status'])
def test_copy_doc_src_dictlike(self):
class DictLike(object):
def __init__(self, doc):
self.doc = doc
def items(self):
return self.doc.items()
self.db['foo'] = {'status': 'testing'}
self.db.copy(DictLike(self.db['foo']), 'bar')
self.assertEqual('testing', self.db['bar']['status'])
def test_copy_doc_dest_dictlike(self):
class DictLike(object):
def __init__(self, doc):
self.doc = doc
def items(self):
return self.doc.items()
self.db['foo'] = {'status': 'testing'}
self.db['bar'] = {}
self.db.copy('foo', DictLike(self.db['bar']))
self.assertEqual('testing', self.db['bar']['status'])
def test_copy_doc_src_baddoc(self):
self.assertRaises(TypeError, self.db.copy, object(), 'bar')
def test_copy_doc_dest_baddoc(self):
self.assertRaises(TypeError, self.db.copy, 'foo', object())
def test_changes(self):
self.db['foo'] = {'bar': True}
self.assertEqual(self.db.changes(since=0)['last_seq'], 1)
first = self.db.changes(feed='continuous').next()
self.assertEqual(first['seq'], 1)
self.assertEqual(first['id'], 'foo')
def test_changes_releases_conn(self):
# Consume an entire changes feed to read the whole response, then check
# that the HTTP connection made it to the pool.
list(self.db.changes(feed='continuous', timeout=0))
scheme, netloc = urlparse.urlsplit(client.DEFAULT_BASE_URL)[:2]
self.assertTrue(self.db.resource.session.connection_pool.conns[(scheme, netloc)])
def test_changes_releases_conn_when_lastseq(self):
# Consume a changes feed, stopping at the 'last_seq' item, i.e. don't
# let the generator run any further, then check the connection made it
# to the pool.
for obj in self.db.changes(feed='continuous', timeout=0):
if 'last_seq' in obj:
break
scheme, netloc = urlparse.urlsplit(client.DEFAULT_BASE_URL)[:2]
self.assertTrue(self.db.resource.session.connection_pool.conns[(scheme, netloc)])
def test_changes_conn_usable(self):
# Consume a changes feed to get a used connection in the pool.
list(self.db.changes(feed='continuous', timeout=0))
# Try using the connection again to make sure the connection was left
# in a good state from the previous request.
self.assertTrue(self.db.info()['doc_count'] == 0)
def test_changes_heartbeat(self):
def wakeup():
time.sleep(.3)
self.db.save({})
threading.Thread(target=wakeup).start()
for change in self.db.changes(feed='continuous', heartbeat=100):
break
def test_purge(self):
doc = {'a': 'b'}
self.db['foo'] = doc
self.assertEqual(self.db.purge([doc])['purge_seq'], 1)
def test_json_encoding_error(self):
doc = {'now': datetime.now()}
self.assertRaises(TypeError, self.db.save, doc)
class ViewTestCase(testutil.TempDatabaseMixin, unittest.TestCase):
def test_row_object(self):
row = list(self.db.view('_all_docs', keys=['blah']))[0]
self.assertEqual(repr(row), "<Row key=u'blah', error=u'not_found'>")
self.assertEqual(row.id, None)
self.assertEqual(row.key, 'blah')
self.assertEqual(row.value, None)
self.assertEqual(row.error, 'not_found')
self.db.save({'_id': 'xyz', 'foo': 'bar'})
row = list(self.db.view('_all_docs', keys=['xyz']))[0]
self.assertEqual(row.id, 'xyz')
self.assertEqual(row.key, 'xyz')
self.assertEqual(row.value.keys(), ['rev'])
self.assertEqual(row.error, None)
def test_view_multi_get(self):
for i in range(1, 6):
self.db.save({'i': i})
self.db['_design/test'] = {
'language': 'javascript',
'views': {
'multi_key': {'map': 'function(doc) { emit(doc.i, null); }'}
}
}
res = list(self.db.view('test/multi_key', keys=range(1, 6, 2)))
self.assertEqual(3, len(res))
for idx, i in enumerate(range(1, 6, 2)):
self.assertEqual(i, res[idx].key)
def test_ddoc_info(self):
self.db['_design/test'] = {
'language': 'javascript',
'views': {
'test': {'map': 'function(doc) { emit(doc.type, null); }'}
}
}
info = self.db.info('test')
self.assertEqual(info['view_index']['compact_running'], False)
def test_view_compaction(self):
for i in range(1, 6):
self.db.save({'i': i})
self.db['_design/test'] = {
'language': 'javascript',
'views': {
'multi_key': {'map': 'function(doc) { emit(doc.i, null); }'}
}
}
self.db.view('test/multi_key')
self.assertTrue(self.db.compact('test'))
def test_view_cleanup(self):
for i in range(1, 6):
self.db.save({'i': i})
self.db['_design/test'] = {
'language': 'javascript',
'views': {
'multi_key': {'map': 'function(doc) { emit(doc.i, null); }'}
}
}
self.db.view('test/multi_key')
ddoc = self.db['_design/test']
ddoc['views'] = {
'ids': {'map': 'function(doc) { emit(doc._id, null); }'}
}
self.db.update([ddoc])
self.db.view('test/ids')
self.assertTrue(self.db.cleanup())
def test_view_function_objects(self):
if 'python' not in self.server.config()['query_servers']:
return
for i in range(1, 4):
self.db.save({'i': i, 'j':2*i})
def map_fun(doc):
yield doc['i'], doc['j']
res = list(self.db.query(map_fun, language='python'))
self.assertEqual(3, len(res))
for idx, i in enumerate(range(1,4)):
self.assertEqual(i, res[idx].key)
self.assertEqual(2*i, res[idx].value)
def reduce_fun(keys, values):
return sum(values)
res = list(self.db.query(map_fun, reduce_fun, 'python'))
self.assertEqual(1, len(res))
self.assertEqual(12, res[0].value)
def test_init_with_resource(self):
self.db['foo'] = {}
view = client.PermanentView(self.db.resource('_all_docs').url, '_all_docs')
self.assertEquals(len(list(view())), 1)
def test_iter_view(self):
self.db['foo'] = {}
view = client.PermanentView(self.db.resource('_all_docs').url, '_all_docs')
self.assertEquals(len(list(view)), 1)
def test_tmpview_repr(self):
mapfunc = "function(doc) {emit(null, null);}"
view = client.TemporaryView(self.db.resource('_temp_view'), mapfunc)
self.assertTrue('TemporaryView' in repr(view))
self.assertTrue(mapfunc in repr(view))
def test_wrapper_iter(self):
class Wrapper(object):
def __init__(self, doc):
pass
self.db['foo'] = {}
self.assertTrue(isinstance(list(self.db.view('_all_docs', wrapper=Wrapper))[0], Wrapper))
def test_wrapper_rows(self):
class Wrapper(object):
def __init__(self, doc):
pass
self.db['foo'] = {}
self.assertTrue(isinstance(self.db.view('_all_docs', wrapper=Wrapper).rows[0], Wrapper))
def test_properties(self):
for attr in ['rows', 'total_rows', 'offset']:
self.assertTrue(getattr(self.db.view('_all_docs'), attr) is not None)
def test_rowrepr(self):
self.db['foo'] = {}
rows = list(self.db.query("function(doc) {emit(null, 1);}"))
self.assertTrue('Row' in repr(rows[0]))
self.assertTrue('id' in repr(rows[0]))
rows = list(self.db.query("function(doc) {emit(null, 1);}", "function(keys, values, combine) {return sum(values);}"))
self.assertTrue('Row' in repr(rows[0]))
self.assertTrue('id' not in repr(rows[0]))
class ShowListTestCase(testutil.TempDatabaseMixin, unittest.TestCase):
show_func = """
function(doc, req) {
return {"body": req.id + ":" + (req.query.r || "<default>")};
}
"""
list_func = """
function(head, req) {
start({headers: {'Content-Type': 'text/csv'}});
if (req.query.include_header) {
send('id' + '\\r\\n');
}
var row;
while (row = getRow()) {
send(row.id + '\\r\\n');
}
}
"""
design_doc = {'_id': '_design/foo',
'shows': {'bar': show_func},
'views': {'by_id': {'map': "function(doc) {emit(doc._id, null)}"},
'by_name': {'map': "function(doc) {emit(doc.name, null)}"}},
'lists': {'list': list_func}}
def setUp(self):
super(ShowListTestCase, self).setUp()
# Workaround for possible bug in CouchDB. Adding a timestamp avoids a
# 409 Conflict error when pushing the same design doc that existed in a
# now deleted database.
design_doc = dict(self.design_doc)
design_doc['timestamp'] = time.time()
self.db.save(design_doc)
self.db.update([{'_id': '1', 'name': 'one'}, {'_id': '2', 'name': 'two'}])
def test_show_urls(self):
self.assertEqual(self.db.show('_design/foo/_show/bar')[1].read(), 'null:<default>')
self.assertEqual(self.db.show('foo/bar')[1].read(), 'null:<default>')
def test_show_docid(self):
self.assertEqual(self.db.show('foo/bar')[1].read(), 'null:<default>')
self.assertEqual(self.db.show('foo/bar', '1')[1].read(), '1:<default>')
self.assertEqual(self.db.show('foo/bar', '2')[1].read(), '2:<default>')
def test_show_params(self):
self.assertEqual(self.db.show('foo/bar', r='abc')[1].read(), 'null:abc')
def test_list(self):
self.assertEqual(self.db.list('foo/list', 'foo/by_id')[1].read(), '1\r\n2\r\n')
self.assertEqual(self.db.list('foo/list', 'foo/by_id', include_header='true')[1].read(), 'id\r\n1\r\n2\r\n')
def test_list_keys(self):
self.assertEqual(self.db.list('foo/list', 'foo/by_id', keys=['1'])[1].read(), '1\r\n')
def test_list_view_params(self):
self.assertEqual(self.db.list('foo/list', 'foo/by_name', startkey='o', endkey='p')[1].read(), '1\r\n')
self.assertEqual(self.db.list('foo/list', 'foo/by_name', descending=True)[1].read(), '2\r\n1\r\n')
class UpdateHandlerTestCase(testutil.TempDatabaseMixin, unittest.TestCase):
update_func = """
function(doc, req) {
if (!doc) {
if (req.id) {
return [{_id : req.id}, "new doc"]
}
return [null, "empty doc"];
}
doc.name = "hello";
return [doc, "hello doc"];
}
"""
design_doc = {'_id': '_design/foo',
'language': 'javascript',
'updates': {'bar': update_func}}
def setUp(self):
super(UpdateHandlerTestCase, self).setUp()
# Workaround for possible bug in CouchDB. Adding a timestamp avoids a
# 409 Conflict error when pushing the same design doc that existed in a
# now deleted database.
design_doc = dict(self.design_doc)
design_doc['timestamp'] = time.time()
self.db.save(design_doc)
self.db.update([{'_id': 'existed', 'name': 'bar'}])
def test_empty_doc(self):
self.assertEqual(self.db.update_doc('foo/bar')[1].read(), 'empty doc')
def test_new_doc(self):
self.assertEqual(self.db.update_doc('foo/bar', 'new')[1].read(), 'new doc')
def test_update_doc(self):
self.assertEqual(self.db.update_doc('foo/bar', 'existed')[1].read(), 'hello doc')
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(ServerTestCase, 'test'))
suite.addTest(unittest.makeSuite(DatabaseTestCase, 'test'))
suite.addTest(unittest.makeSuite(ViewTestCase, 'test'))
suite.addTest(unittest.makeSuite(ShowListTestCase, 'test'))
suite.addTest(unittest.makeSuite(UpdateHandlerTestCase, 'test'))
suite.addTest(doctest.DocTestSuite(client))
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| ryanolson/couchdb-python | couchdb/tests/client.py | Python | bsd-3-clause | 26,584 |
#!/usr/bin/env python
"""
heatsequer plot window gui (2nd plot window) module
imported from plotwin.py when you plotexp() and set usegui=True
"""
# amnonscript
__version__ = "0.91"
import heatsequer as hs
import os
import sys
import numpy as np
import matplotlib as mpl
mpl.use('Qt5Agg')
import matplotlib.pyplot as plt
from matplotlib.pyplot import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from PyQt5 import QtGui, QtCore, QtWidgets, uic
from PyQt5.QtCore import Qt
#from PyQt4 import QtGui
from PyQt5.QtWidgets import QCompleter,QMessageBox,QListWidgetItem
from PyQt5.QtCore import QStringListModel
import pickle
# for debugging - use XXX()
from pdb import set_trace as XXX
""""
for the GUI
"""
class SListWindow(QtWidgets.QDialog):
def __init__(self,listdata=[],listname=''):
"""
create a list window with items in the list and the listname as specified
input:
listdata - the data to show in the list (a list)
listname - name to display above the list
"""
super(SListWindow, self).__init__()
# uic.loadUi('./ui/listwindow.py', self)
uic.loadUi(os.path.join(hs.heatsequerdir,'ui/listwindow.py'), self)
# uic.loadUi(hs.get_data_path('listwindow.py','ui'), self)
for citem in listdata:
self.lList.addItem(citem)
if listname:
self.lLabel.setText(listname)
class MyMplCanvas(FigureCanvas):
"""Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
def __init__(self, parent=None, width=5, height=4, dpi=100):
self.fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = self.fig.add_subplot(111)
# We want the axes cleared every time plot() is called
# self.axes.hold(False)
FigureCanvas.__init__(self, self.fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
class PlotGUIWindow(QtWidgets.QDialog):
cexp=[]
def __init__(self,expdat):
super(PlotGUIWindow, self).__init__()
hs.Debug(1,hs.get_data_path('plotguiwindow.py','ui'))
uic.loadUi(os.path.join(hs.heatsequerdir,'ui/plotguiwindow.py'), self)
self.bGetSequence.clicked.connect(self.getsequence)
self.bExport.clicked.connect(self.export)
self.bView.clicked.connect(self.view)
self.bSave.clicked.connect(self.save)
self.bDBSave.clicked.connect(self.dbsave)
self.bEnrich.clicked.connect(self.enrich)
self.bExpInfo.clicked.connect(self.expinfo)
self.bSampleInfo.clicked.connect(self.sampleinfo)
self.lCoolDB.doubleClicked.connect(self.showannotation)
self.cSampleField.activated.connect(self.samplefield)
self.FigureTab.currentChanged.connect(self.tabchange)
self.cSampleField.setCurrentIndex(0)
self.cexp=expdat
self.selectionlines={}
self.selection=[]
self.setWindowTitle(self.cexp.studyname)
for cfield in self.cexp.fields:
self.cSampleField.addItem(cfield)
self.cPlotXField.addItem(cfield)
if self.cexp.seqdb:
ontofields,ontonames=hs.bactdb.getontonames(self.cexp.seqdb)
for conto in ontofields:
# for conto in self.cexp.seqdb.OntoGraph.keys():
self.cOntology.addItem(conto)
self.dc=None
self.createaddplot(useqt=True)
# right click menu
self.lCoolDB.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.lCoolDB.customContextMenuRequested.connect(self.listItemRightClicked)
def listItemRightClicked(self, QPos):
self.listMenu= QtWidgets.QMenu()
menuitem = self.listMenu.addAction("Delete annotation")
menuitem.triggered.connect(self.menuDeleteAnnotation)
parentPosition = self.lCoolDB.mapToGlobal(QtCore.QPoint(0, 0))
self.listMenu.move(parentPosition + QPos)
self.listMenu.show()
def menuDeleteAnnotation(self):
if len(self.lCoolDB.selectedItems())>1:
print('more than 1 item')
for citem in self.lCoolDB.selectedItems():
cdetails=citem.data(Qt.UserRole)
if cdetails is None:
print('no details')
return
annotationid=cdetails['annotationid']
qres=QtWidgets.QMessageBox.warning(self,"Delete annotation","Are you sure you want to delete annotation %d?\nThis cannot be undone" % annotationid,QtWidgets.QMessageBox.Yes,QtWidgets.QMessageBox.Cancel)
if qres==QtWidgets.QMessageBox.Cancel:
return
hs.supercooldb.delete_annotation(hs.scdb,annotationid)
def showannotation(self):
citem=self.lCoolDB.currentItem()
cdetails=citem.data(Qt.UserRole)
print('-----')
print(cdetails)
showannotationdata(cdetails)
def createaddplot(self,useqt=True):
"""
create the additional figure for the ontology/line plots
input:
useqt : boolean
True to embed the plot in the qtgui window, false to open a new figure window (so don't need the qtagg)
"""
if useqt:
# add the matplotlib figure
self.frame = QtWidgets.QWidget(self)
self.dc = MyMplCanvas(self.frame, width=5, height=4, dpi=100)
# add it to an hboxlayout to make it resize with window
layout = QtWidgets.QHBoxLayout(self)
layout.insertSpacing(0,250)
# layout.addWidget(self.dc)
# self.setLayout(layout)
layout2 = QtWidgets.QVBoxLayout()
layout.addLayout(layout2)
layout2.addWidget(self.dc)
self.mpl_toolbar = NavigationToolbar(self.dc, self)
layout2.addWidget(self.mpl_toolbar)
self.setLayout(layout)
else:
addfig=plt.figure()
addax=addfig.add_subplot(1,1,1)
# addax.hold(False)
self.dc=addax
def sampleinfo(self):
if not self.csamp:
return
csamp=self.cexp.samples[self.csamp]
cmap=self.cexp.smap[csamp]
info=[]
for k,v in cmap.items():
info.append(k+':'+v)
slistwin = SListWindow(info,cmap['#SampleID'])
slistwin.exec_()
def tabchange(self,newtab):
hs.Debug(0,"new tab",newtab)
if newtab==2:
self.plotxgraph()
if newtab==1:
self.plotontology()
def plotontology(self):
if self.cexp.seqdb:
self.dc.axes.clear()
hs.Debug(2,"plotting taxonomy for seq %s onto %s" % (self.cexp.seqs[self.cseq],self.cexp.ontofigname))
hs.bactdb.PlotOntologyGraph(self.cexp.seqdb,self.cexp.seqs[self.cseq],field=str(self.cOntology.currentText()),toax=self.dc.axes)
self.dc.draw()
def plotxgraph(self):
if self.dc is None:
self.createaddplot()
self.dc.axes.clear()
seqs=self.getselectedseqs()
if self.cPlotNormalizeY.checkState()==0:
normalizey=False
else:
normalizey=True
if self.cPlotXNumeric.checkState()==0:
xfield=False
else:
xfield=str(self.cPlotXField.currentText())
hs.plotseqfreq(self.cexp,seqs=seqs,toaxis=self.dc.axes,normalizey=normalizey,xfield=xfield)
# is this needed?
# self.dc.draw()
self.dc.figure.canvas.draw_idle()
def samplefield(self,qstr):
cfield=str(qstr)
self.lSampleFieldVal.setText(self.cexp.smap[self.cexp.samples[self.csamp]][cfield])
def getsequence(self):
seq=self.cexp.seqs[self.cseq]
val,ok=QtWidgets.QInputDialog.getText(self,'Sequence',self.cexp.tax[self.cseq],text=seq)
def view(self):
slist=[]
for cseq in self.selection:
slist.append(self.cexp.tax[cseq]+'-'+str(self.cexp.sids[cseq]))
val,ok=QtWidgets.QInputDialog.getItem(self,'Selected bacteria','',slist)
def getselectedseqs(self):
slist=[]
for cseq in self.selection:
slist.append(self.cexp.seqs[cseq])
return slist
def dbsave(self):
"""
save the selected list to the coolseq database
"""
val,ok=QtWidgets.QInputDialog.getText(self,'Save %d bacteria to coolseqDB' % len(self.selection),'Enter description')
hs.Debug(1,ok)
if ok:
seqs=[]
for cid in self.selection:
seqs.append(self.cexp.seqs[cid])
hs.cooldb.savecoolseqs(self.cexp,self.cexp.cdb,seqs,val)
def enrich(self):
"""
check for annotation enrichment for selected sequences (compared to other sequences in this experiment)
"""
if not self.cexp.cdb:
hs.Debug(8,'No cooldb loaded')
return
selseqs=[]
for cid in self.selection:
selseqs.append(self.cexp.seqs[cid])
bmd=hs.cooldb.testenrichment(self.cexp.cdb,self.cexp.seqs,selseqs)
# bmd=hs.annotationenrichment(self.cexp,selseqs)
hs.Debug(6,'found %d items' % len(bmd))
if len(bmd)>0:
slistwin = SListWindow(listname='Enrichment')
bmd=hs.sortenrichment(bmd)
for cbmd in bmd:
if cbmd['observed']<cbmd['expected']:
ccolor=QtGui.QColor(155,0,0)
else:
ccolor=QtGui.QColor(0,155,0)
item = QtWidgets.QListWidgetItem()
item.setText("%s (p:%f o:%d e:%f)" % (cbmd['description'],cbmd['pval'],cbmd['observed'],cbmd['expected']))
item.setForeground(ccolor)
slistwin.lList.addItem(item)
print("%s (p:%f o:%d e:%f)" % (cbmd['description'],cbmd['pval'],cbmd['observed'],cbmd['expected']))
slistwin.exec_()
def save(self):
"""
save the selected list to a fasta file
"""
fname = str(QtWidgets.QFileDialog.getSaveFileName(self, 'Save selection fasta file name','pita'))
slist=[]
for cseq in self.selection:
slist.append(self.cexp.seqs[cseq])
hs.saveseqsfasta(self.cexp,slist,fname)
hs.Debug(6,'Saved %d sequences to file %s' % (len(slist),fname))
def export(self):
"""
export the selected bacteria list to the global variable 'selectlist'
"""
global selectlist
hs.Debug(0,'exporting')
selectlist=[]
for cseq in self.selection:
selectlist.append(self.cexp.seqs[cseq])
def updateinfo(self,csamp,cseq):
"""
update the information about the sample/bacteria
"""
self.csamp=csamp
self.cseq=cseq
self.lSample.setText(self.cexp.samples[self.csamp])
self.lTaxonomy.setText(self.cexp.tax[self.cseq])
self.lID.setText(str(self.cexp.sids[self.cseq]))
self.lReads.setText('%f' % (float(self.cexp.data[self.cseq,self.csamp])/100))
self.lSampleFieldVal.setText(self.cexp.smap[self.cexp.samples[self.csamp]][str(self.cSampleField.currentText())])
# update the stats about the database:
if self.cexp.seqdb:
self.lStudies.clear()
totappear,numstudies,allstudies,studysamples,totdbsamples=hs.bactdb.GetSeqInfo(self.cexp.seqdb,self.cexp.seqs[self.cseq])
if totappear>0:
self.lNumSamples.setText(str('%d/%dK' % (totappear,int(totdbsamples/1000))))
self.lNumStudies.setText(str(numstudies))
res=list(studysamples.items())
vlens=[]
for cv in res:
totsamps=hs.bactdb.SamplesInStudy(self.cexp.seqdb,cv[0])
vlens.append(float(len(cv[1]))/len(totsamps))
sv,si=hs.isort(vlens,reverse=True)
for cind in si:
studyname=hs.bactdb.StudyNameFromID(self.cexp.seqdb,res[cind][0])
self.lStudies.addItem('%s (%f)' % (studyname,vlens[cind]))
else:
self.lNumSamples.setText(str('%d/%dK' % (0,int(totdbsamples/1000))))
self.lNumStudies.setText("0")
if self.FigureTab.currentIndex()==2:
self.plotxgraph()
if self.FigureTab.currentIndex()==1:
self.plotontology()
def updatecdb(self,info):
"""
update the coolseq database info for the bacteria
by adding all lines in list to the listbox
"""
self.lCoolDB.clear()
self.addtocdblist(info)
def addtocdblist(self,info):
"""
add to cdb list without clearing
"""
for cinfo in info:
# test if the supercooldb annotation
if type(cinfo)==tuple:
details=cinfo[0]
newitem=QListWidgetItem(cinfo[1])
newitem.setData(Qt.UserRole,details)
if details['annotationtype']=='diffexp':
ccolor=QtGui.QColor(0,0,200)
elif details['annotationtype']=='contamination':
ccolor=QtGui.QColor(200,0,0)
elif details['annotationtype']=='common':
ccolor=QtGui.QColor(0,200,0)
elif details['annotationtype']=='highfreq':
ccolor=QtGui.QColor(0,200,0)
else:
ccolor=QtGui.QColor(0,0,0)
newitem.setForeground(ccolor)
self.lCoolDB.addItem(newitem)
else:
self.lCoolDB.addItem(cinfo)
def selectbact(self,bactlist,flip=True):
"""
add bacteria from the list bactlist (position in exp) to the selection
flip - if true, if bacteria from list is already in selection, remove it
"""
for cseq in bactlist:
# if already in list and can flip, remove from list instead
if flip:
if cseq in self.selectionlines:
self.clearselection([cseq])
hs.Debug(0,'Flip')
continue
if cseq in self.selectionlines:
continue
cline=self.plotax.plot([-0.5,len(self.cexp.samples)-0.5],[cseq,cseq],':w')
self.selectionlines[cseq]=cline
self.selection.append(cseq)
self.plotfig.canvas.draw()
self.lSelection.setText('%d bacteria' % len(self.selection))
def clearselection(self,seqlist=False):
if not seqlist:
seqlist=list(self.selectionlines.keys())
for cseq in seqlist:
cline=self.selectionlines[cseq]
self.plotax.lines.remove(cline[0])
del self.selectionlines[cseq]
self.selection.remove(cseq)
self.plotfig.canvas.draw()
self.lSelection.setText('%d bacteria' % len(self.selection))
def expinfo(self):
# get the selected sequences
sequences=[]
for cid in self.selection:
sequences.append(self.cexp.seqs[cid])
self.cexp.selectedseqs=sequences
dbs = DBAnnotateSave(self.cexp)
res=dbs.exec_()
if res==QtWidgets.QDialog.Accepted:
# fl=open('/Users/amnon/Python/git/heatsequer/db/ontologyfromid.pickle','rb')
# ontologyfromid=pickle.load(fl)
# fl.close()
ontologyfromid=hs.scdb.ontologyfromid
description=str(dbs.bdescription.text())
# TODO: need to get primer region!!!!
primerid='V4'
method=str(dbs.bmethod.text())
if method=='':
method='na'
submittername='Amnon Amir'
curations=[]
# if it is differential abundance
for citem in qtlistiteritems(dbs.blistall):
cdat=qtlistgetdata(citem)
cval=cdat['value']
ctype=cdat['type']
if cval in ontologyfromid:
cval=ontologyfromid[cval]
else:
hs.Debug(1,"item %s not found in ontologyfromid" % cval)
curations.append((ctype,cval))
if dbs.bdiffpres.isChecked():
curtype='DIFFEXP'
elif dbs.bisa.isChecked():
curtypeval=dbs.bisatype.currentText()
if 'Common' in curtypeval:
curtype='COMMON'
elif 'Contam' in curtypeval:
curtype='CONTAMINATION'
elif 'High' in curtypeval:
curtype='HIGHFREQ'
else:
curtype='OTHER'
else:
hs.Debug(9,"No annotation type selected")
return
scdb=hs.scdb
cdata=hs.supercooldb.finddataid(scdb,datamd5=self.cexp.datamd5,mapmd5=self.cexp.mapmd5)
# if study not in database, ask to add some metadata for it
if cdata is None:
okcontinue=False
while not okcontinue:
hs.Debug(6,'study data info not found based on datamd5, mapmd5. need to add one!!!')
qres=QtWidgets.QMessageBox.warning(self,"No study data","No information added about study data. Add info?",QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No,QtWidgets.QMessageBox.Cancel)
if qres==QtWidgets.QMessageBox.Cancel:
return
if qres==QtWidgets.QMessageBox.No:
cdata=hs.supercooldb.addexpdata(scdb,( ('DataMD5',self.cexp.datamd5), ('MapMD5',self.cexp.mapmd5) ) )
okcontinue=True
if qres==QtWidgets.QMessageBox.Yes:
okcontinue=getstudydata(self.cexp)
cdata=hs.supercooldb.finddataid(scdb,datamd5=self.cexp.datamd5,mapmd5=self.cexp.mapmd5)
hs.Debug(1,'new cdata is %s' % cdata)
hs.Debug(6,'Data found. id is %s' % cdata)
hs.supercooldb.addannotations(scdb,expid=cdata,sequences=sequences,annotationtype=curtype,annotations=curations,submittername=submittername,description=description,method=method,primerid=primerid)
# store the history
try:
hs.lastcurations.append(curations)
except:
hs.lastcurations=[curations]
hs.lastdatamd5=self.cexp.datamd5
class DBStudyAnnotations(QtWidgets.QDialog):
def __init__(self,studyid):
super(DBStudyAnnotations, self).__init__()
uic.loadUi(os.path.join(hs.heatsequerdir,'ui/annotationlist.py'), self)
scdb=hs.scdb
self.scdb=scdb
self.studyid=studyid
info=hs.supercooldb.getexpannotations(scdb,studyid)
for cinfo in info:
self.blist.addItem(cinfo)
self.bdetails.clicked.connect(self.details)
def details(self):
items=self.blist.selectedItems()
if len(items)==0:
return
print(str(items[0].text()))
class DBStudyInfo(QtWidgets.QDialog):
def __init__(self,expdat):
super(DBStudyInfo, self).__init__()
uic.loadUi(os.path.join(hs.heatsequerdir,'ui/studyinfo.py'), self)
scdb=hs.scdb
self.scdb=scdb
self.dataid=0
dataid=hs.supercooldb.finddataid(scdb,datamd5=expdat.datamd5,mapmd5=expdat.mapmd5)
if dataid is not None:
info=hs.supercooldb.getexperimentinfo(scdb,dataid)
for cinfo in info:
qtlistadd(self.blist,cinfo[0]+':'+cinfo[1],{'fromdb':True,'type':cinfo[0],'value':cinfo[1]},color='grey')
self.dataid=dataid
else:
qtlistadd(self.blist,"DataMD5:%s" % expdat.datamd5,{'fromdb':False,'type':"DataMD5",'value':expdat.datamd5},color='black')
qtlistadd(self.blist,"MapMD5:%s" % expdat.mapmd5,{'fromdb':False,'type':"MapMD5",'value':expdat.mapmd5},color='black')
self.bplus.clicked.connect(self.plus)
self.bvalue.returnPressed.connect(self.plus)
self.bminus.clicked.connect(self.minus)
self.bannotations.clicked.connect(self.annotations)
self.cexp=expdat
self.setWindowTitle(self.cexp.studyname)
self.prepstudyinfo()
self.bvalue.setFocus()
def keyPressEvent(self, e):
"""
override the enter event so will not close dialog
"""
e.ignore()
def addentry(self,fromdb,ctype,value,color='black'):
if len(ctype)>0 and len(value)>0:
newentry='%s:%s' % (ctype,value)
for citem in getqtlistitems(self.blist):
if citem==newentry:
hs.Debug(2,'item already in list %s' % newentry)
return
qtlistadd(self.blist,newentry,{'fromdb':False,'type':ctype,'value':value},color="black")
def plus(self):
ctype=str(self.btype.currentText())
cval=str(self.bvalue.text())
self.addentry(fromdb=False,ctype=ctype,value=cval,color='black')
self.bvalue.setText('')
def minus(self):
items=self.blist.selectedItems()
for citem in items:
cdata=qtlistgetdata(citem)
if cdata['fromdb']:
print('delete from db')
self.blist.takeItem(self.blist.row(citem))
def annotations(self):
dbsa = DBStudyAnnotations(self.dataid)
dbsa.exec_()
def prepstudyinfo(self):
"""
add the study info from the mapping file if available
"""
fieldlist=[('SRA_Study_s','sra'),('project_name_s','name'),('experiment_title','name'),('experiment_design_description','name'),('BioProject_s','sra')]
cexp=self.cexp
for (cfield,infofield) in fieldlist:
if cfield in cexp.fields:
uvals=hs.getfieldvals(cexp,cfield,ounique=True)
if len(uvals)==1:
self.addentry(fromdb=False,ctype=infofield,value=uvals[0].lower(),color='black')
class DBAnnotateSave(QtWidgets.QDialog):
def __init__(self,expdat):
super(DBAnnotateSave, self).__init__()
print("DBAnnotateSave")
uic.loadUi(os.path.join(hs.heatsequerdir,'ui/manualdata.py'), self)
self.bplus.clicked.connect(self.plus)
self.bminus.clicked.connect(self.minus)
self.bontoinput.returnPressed.connect(self.plus)
self.bstudyinfo.clicked.connect(self.studyinfo)
self.bisa.toggled.connect(self.radiotoggle)
self.bdiffpres.toggled.connect(self.radiotoggle)
self.bisatype.currentIndexChanged.connect(self.isatypechanged)
self.bhistory.clicked.connect(self.history)
self.cexp=expdat
self.lnumbact.setText(str(len(expdat.selectedseqs)))
completer = QCompleter()
self.bontoinput.setCompleter(completer)
scdb=hs.scdb
self.scdb=scdb
self.dataid=hs.supercooldb.finddataid(scdb,datamd5=self.cexp.datamd5,mapmd5=self.cexp.mapmd5)
model = QStringListModel()
completer.setModel(model)
# completer.setCompletionMode(QCompleter.InlineCompletion)
completer.maxVisibleItems=10
completer.setCaseSensitivity(Qt.CaseInsensitive)
# make the completer selection also erase the text edit
completer.activated.connect(self.cleartext,type=Qt.QueuedConnection)
# in qt5 should work with middle complete as well...
# completer.setFilterMode(Qt.MatchContains)
if not hs.scdb.ontologyfromid:
hs.scdb=hs.supercooldb.loaddbonto(hs.scdb)
self.ontology=hs.scdb.ontology
self.ontologyfromid=hs.scdb.ontologyfromid
nlist=list(self.ontology.keys())
# nlist=sorted(nlist)
nlist=sorted(nlist, key=lambda s: s.lower())
print("sorted ontology")
model.setStringList(nlist)
self.setWindowTitle(self.cexp.studyname)
try:
tt=hs.lastdatamd5
except:
hs.lastdatamd5=''
if self.cexp.datamd5==hs.lastdatamd5:
self.fillfromcuration(hs.lastcurations[-1],onlyall=True)
self.prefillinfo()
self.bontoinput.setFocus()
def history(self):
curtext=[]
for cur in hs.lastcurations:
ct=''
for dat in cur:
ct+=dat[0]+'-'+dat[1]+','
curtext.append(ct)
slistwin = SListWindow(curtext,'select curation from history')
res=slistwin.exec_()
if res:
items=slistwin.lList.selectedItems()
for citem in items:
print(citem)
spos=slistwin.lList.row(citem)
print(spos)
self.fillfromcuration(hs.lastcurations[spos],onlyall=False)
def fillfromcuration(self,curation,onlyall=True,clearit=True):
"""
fill gui list from curation
input:
curation : from hs.lastcurations
onlyall : bool
True to show only curations which have ALL, False to show also HIGH/LOW
clearit : bool
True to remove previous curations from list, False to keep
"""
if clearit:
self.blistall.clear()
for cdat in curation:
if onlyall:
if cdat[0]!='ALL':
continue
self.addtolist(cdat[0],cdat[1])
def radiotoggle(self):
if self.bisa.isChecked():
self.blow.setDisabled(True)
self.bhigh.setDisabled(True)
if self.bdiffpres.isChecked():
self.blow.setEnabled(True)
self.bhigh.setEnabled(True)
def isatypechanged(self):
"""
changed the selection of isatype combobox so need to activate the isa radio button
"""
self.bisa.setChecked(True)
def studyinfo(self):
getstudydata(self.cexp)
def keyPressEvent(self, e):
"""
override the enter event so will not close dialog
"""
# print(e.key())
e.ignore()
def minus(self):
"""
delete selected item from current list
"""
items=self.blistall.selectedItems()
for citem in items:
self.blistall.takeItem(self.blistall.row(citem))
def cleartext(self):
self.bontoinput.setText('')
def plus(self):
conto=str(self.bontoinput.text())
cgroup=self.getontogroup()
self.addtolist(cgroup,conto)
self.cleartext()
def addtolist(self,cgroup,conto):
"""
add an ontology term to the list
input:
cgroup : str
the group (i.e. 'low/high/all')
conto : str
the ontology term to add
"""
if conto=='':
hs.Debug(2,'no string to add to list')
return
print('addtolist %s %s' % (cgroup,conto))
if conto in self.ontology:
conto=self.ontologyfromid[self.ontology[conto]]
else:
hs.Debug(1,'Not in ontology!!!')
# TODO: add are you sure... not in ontology list....
# if item already in list, don't do anything
for citem in qtlistiteritems(self.blistall):
cdata=qtlistgetdata(citem)
if cdata['value']==conto:
hs.Debug(2,'item already in list')
return
if cgroup=='LOW':
ctext="LOW:%s" % conto
qtlistadd(self.blistall,ctext, {'type':'LOW','value':conto},color='red')
if cgroup=='HIGH':
ctext="HIGH:%s" % conto
qtlistadd(self.blistall,ctext, {'type':'HIGH','value':conto},color='blue')
if cgroup=='ALL':
ctext="ALL:%s" % conto
qtlistadd(self.blistall,ctext, {'type':'ALL','value':conto},color='black')
def getontogroup(self):
if self.ball.isChecked():
return('ALL')
if self.blow.isChecked():
return('LOW')
if self.bhigh.isChecked():
return('HIGH')
def prefillinfo(self):
"""
prefill "ALL" data fields based on mapping file
if all samples have same info
"""
hs.Debug(1,'prefill info')
ontologyfromid=self.ontologyfromid
# fl=open('/Users/amnon/Python/git/heatsequer/db/ncbitaxontofromid.pickle','rb')
fl=open(os.path.join(hs.heatsequerdir,'db/ncbitaxontofromid.pickle'),'rb')
ncbitax=pickle.load(fl)
fl.close()
cexp=self.cexp
for cfield in cexp.fields:
uvals=[]
if cfield in cexp.fields:
uvals=hs.getfieldvals(cexp,cfield,ounique=True)
# if we have 1 value
if len(uvals)==1:
cval=uvals[0]
hs.Debug(1,'found 1 value %s' % cval)
if cfield=='HOST_TAXID' or cfield=='host_taxid':
hs.Debug(2,'%s field has 1 value %s' % (cfield,cval))
# if ncbi taxonomy (field used differently)
cval='NCBITaxon:'+cval
if cval in ncbitax:
hs.Debug(2,'found in ncbitax %s' % cval)
cval=ncbitax[cval]
else:
# get the XXX from ENVO:XXX value
uvalspl=cval.split(':',1)
if len(uvalspl)>1:
cval=uvalspl[1]
cval=uvalspl[1]+' :'+uvalspl[0]
if cval in self.ontology:
cval=ontologyfromid[self.ontology[cval]]
hs.Debug(2,'term %s found in ontologyfromid' % cval)
conto=cval
hs.Debug(1,'add prefill %s' % conto)
self.addtolist('ALL',conto)
else:
hs.Debug(3,'term %s NOT found in ontologyfromid' % uvals[0])
else:
hs.Debug(1,'found %d values' % len(uvals))
def getqtlistitems(qtlist):
"""
get a list of strings of the qtlist
input:
qtlist : QTListWidget
output:
item : list of str
"""
items = []
for index in range(qtlist.count()):
items.append(str(qtlist.item(index).text()))
return items
def qtlistadd(qtlist,text,data,color="black"):
"""
Add an entry (text) to qtlist and associaxte metadata data
input:
qtlist : QTListWidget
text : str
string to add to list
data : arbitrary python var
the data to associate with the item (get it by qtlistgetdata)
color : (R,G,B)
the color of the text in the list
"""
item = QtWidgets.QListWidgetItem()
item.setText(text)
ccol=QtGui.QColor()
ccol.setNamedColor(color)
item.setForeground(ccol)
item.setData(Qt.UserRole,data)
qtlist.addItem(item)
def qtlistgetdata(item):
"""
Get the metadata associated with item as position pos
input:
qtlist : QtListWidget
index : QtListWidgetItem
the item to get the info about
output:
data : arbitrary
the data associated with the item (using qtlistadd)
"""
# item=qtlist.item(index)
if sys.version_info[0] < 3:
# QVariant version 1 API (python2 default)
data=item.data(Qt.UserRole).toPyObject()
else:
# QVariant version 2 API (python3 default)
data=item.data(Qt.UserRole)
return data
def qtlistiteritems(qtlist):
"""
iterate all items in a list
input:
qtlist : QtListWidget
"""
for i in range(qtlist.count()):
yield qtlist.item(i)
def getstudydata(cexp):
"""
open the study info window and show/get new references for the study data
input:
cexp : Experiment
the experiment for which to show the data (uses the datamd5 and mapmd5)
output:
hasdata : Bool
True if the study has data, False if not
"""
dbsi = DBStudyInfo(cexp)
res=dbsi.exec_()
if res==QtWidgets.QDialog.Accepted:
newstudydata=[]
allstudydata=[]
for citem in qtlistiteritems(dbsi.blist):
cdata=qtlistgetdata(citem)
allstudydata.append( (cdata['type'],cdata['value']) )
if cdata['fromdb']==False:
newstudydata.append( (cdata['type'],cdata['value']) )
if len(newstudydata)==0:
hs.Debug(6,'No new items. not saving anything')
return True
# look if study already in table
cid=hs.supercooldb.finddataid(dbsi.scdb,datamd5=cexp.datamd5,mapmd5=cexp.mapmd5)
if cid is None:
hs.Debug(6,'no studyid found for datamd5 %s, mapmd5 %s' % (cexp.datamd5,cexp.mapmd5))
# cdata=hs.supercooldb.addexpdata(scdb,( ('DataMD5',cexp.datamd5), ('MapMD5',cexp.mapmd5) ) )
hs.Debug(3,'Adding to new experiment')
dataid=hs.supercooldb.addexpdata(dbsi.scdb,newstudydata,studyid=cid)
hs.Debug(6,'Study data saved to id %d' % dataid)
if len(allstudydata)>2:
return True
return False
def showannotationdata(annotationdetails):
"""
show the list of annotation details and the sequences associated with it
intput:
annotationdetails : dict
dict of various fields of the annotation (includeing annotationid)
from scdb.getannotationstrings()
cexp : experiment
the experiment (for rhe scdb pointer)
"""
info=[]
if annotationdetails is None:
return
for k,v in annotationdetails.items():
if type(v)==list:
for cv in v:
info.append('%s:%s' % (k,cv))
else:
info.append('%s:%s' % (k,v))
# get the annotation sequences:
if 'annotationid' in annotationdetails:
seqs=hs.supercooldb.getannotationseqs(hs.scdb,annotationdetails['annotationid'])
info.append('sequences: %d' % len(seqs))
# get the experiment details:
if 'expid' in annotationdetails:
expinfo=hs.supercooldb.getexperimentinfo(hs.scdb,annotationdetails['expid'])
for cinfo in expinfo:
info.append('experiment %s:%s' % (cinfo[0],cinfo[1]))
slistwin = SListWindow(info,'Annotation details')
slistwin.exec_()
| amnona/heatsequer | heatsequer/plots/plotwingui.py | Python | bsd-3-clause | 28,472 |
/**
* marked - a markdown parser
* Copyright (c) 2011-2013, Christopher Jeffrey. (MIT Licensed)
* https://github.com/chjj/marked
*
* @providesModule Marked
* @jsx React.DOM
*/
/* eslint-disable sort-keys */
const React = require('React');
const Prism = require('Prism');
const Header = require('Header');
/**
* Block-Level Grammar
*/
const block = {
newline: /^\n+/,
code: /^( {4}[^\n]+\n*)+/,
fences: noop,
hr: /^( *[-*_]){3,} *(?:\n+|$)/,
heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
nptable: noop,
lheading: /^([^\n]+)\n *(=|-){3,} *\n*/,
blockquote: /^( *>[^\n]+(\n[^\n]+)*\n*)+/,
list: /^( *)(bull) [\s\S]+?(?:hr|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
html: /^ *(?:comment|closed|closing) *(?:\n{2,}|\s*$)/,
def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
table: noop,
paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
text: /^[^\n]+/,
};
block.bullet = /(?:[*+-]|\d+\.)/;
block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
block.item = replace(block.item, 'gm')(/bull/g, block.bullet)();
block.list = replace(block.list)(/bull/g, block.bullet)('hr', /\n+(?=(?: *[-*_]){3,} *(?:\n+|$))/)();
block._tag = '(?!(?:'
+ 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
+ '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
+ '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|@)\\b';
block.html = replace(block.html)('comment', /<!--[\s\S]*?-->/)('closed', /<(tag)[\s\S]+?<\/\1>/)('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)(/tag/g, block._tag)();
block.paragraph = replace(block.paragraph)('hr', block.hr)('heading', block.heading)('lheading', block.lheading)('blockquote', block.blockquote)('tag', '<' + block._tag)('def', block.def)();
/**
* Normal Block Grammar
*/
block.normal = merge({}, block);
/**
* GFM Block Grammar
*/
block.gfm = merge({}, block.normal, {
fences: /^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/,
paragraph: /^/,
});
block.gfm.paragraph = replace(block.paragraph)('(?!', '(?!' + block.gfm.fences.source.replace('\\1', '\\2') + '|')();
/**
* GFM + Tables Block Grammar
*/
block.tables = merge({}, block.gfm, {
nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/,
});
/**
* Block Lexer
*/
function Lexer(options) {
this.tokens = [];
this.tokens.links = {};
this.options = options || marked.defaults;
this.rules = block.normal;
if (this.options.gfm) {
if (this.options.tables) {
this.rules = block.tables;
} else {
this.rules = block.gfm;
}
}
}
/**
* Expose Block Rules
*/
Lexer.rules = block;
/**
* Static Lex Method
*/
Lexer.lex = function(src, options) {
const lexer = new Lexer(options);
return lexer.lex(src);
};
/**
* Preprocessing
*/
Lexer.prototype.lex = function(src) {
src = src
.replace(/\r\n|\r/g, '\n')
.replace(/\t/g, ' ')
.replace(/\u00a0/g, ' ')
.replace(/\u2424/g, '\n');
return this.token(src, true);
};
/**
* Lexing
*/
Lexer.prototype.token = function(_src, top) {
let src = _src.replace(/^ +$/gm, '');
let next;
let loose;
let cap;
let bull;
let b;
let item;
let space;
let i;
let l;
while (src) {
// newline
if (cap = this.rules.newline.exec(src)) {
src = src.substring(cap[0].length);
if (cap[0].length > 1) {
this.tokens.push({
type: 'space',
});
}
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
cap = cap[0].replace(/^ {4}/gm, '');
this.tokens.push({
type: 'code',
text: !this.options.pedantic
? cap.replace(/\n+$/, '')
: cap,
});
continue;
}
// fences (gfm)
if (cap = this.rules.fences.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'code',
lang: cap[2],
text: cap[3],
});
continue;
}
// heading
if (cap = this.rules.heading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[1].length,
text: cap[2],
});
continue;
}
// table no leading pipe (gfm)
if (top && (cap = this.rules.nptable.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/\n$/, '').split('\n'),
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i].split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// lheading
if (cap = this.rules.lheading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[2] === '=' ? 1 : 2,
text: cap[1],
});
continue;
}
// hr
if (cap = this.rules.hr.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'hr',
});
continue;
}
// blockquote
if (cap = this.rules.blockquote.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'blockquote_start',
});
cap = cap[0].replace(/^ *> ?/gm, '');
// Pass `top` to keep the current
// "toplevel" state. This is exactly
// how markdown.pl works.
this.token(cap, top);
this.tokens.push({
type: 'blockquote_end',
});
continue;
}
// list
if (cap = this.rules.list.exec(src)) {
src = src.substring(cap[0].length);
bull = cap[2];
this.tokens.push({
type: 'list_start',
ordered: bull.length > 1,
});
// Get each top-level item.
cap = cap[0].match(this.rules.item);
next = false;
l = cap.length;
i = 0;
for (; i < l; i++) {
item = cap[i];
// Remove the list item's bullet
// so it is seen as the next token.
space = item.length;
item = item.replace(/^ *([*+-]|\d+\.) +/, '');
// Outdent whatever the
// list item contains. Hacky.
if (~item.indexOf('\n ')) { // eslint-disable-line
space -= item.length;
item = !this.options.pedantic
? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
: item.replace(/^ {1,4}/gm, '');
}
// Determine whether the next list item belongs here.
// Backpedal if it does not belong in this list.
if (this.options.smartLists && i !== l - 1) {
b = block.bullet.exec(cap[i + 1])[0];
if (bull !== b && !(bull.length > 1 && b.length > 1)) {
src = cap.slice(i + 1).join('\n') + src;
i = l - 1;
}
}
// Determine whether item is loose or not.
// Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
// for discount behavior.
loose = next || /\n\n(?!\s*$)/.test(item);
if (i !== l - 1) {
next = item[item.length - 1] === '\n';
if (!loose) {loose = next;}
}
this.tokens.push({
type: loose
? 'loose_item_start'
: 'list_item_start',
});
// Recurse.
this.token(item, false);
this.tokens.push({
type: 'list_item_end',
});
}
this.tokens.push({
type: 'list_end',
});
continue;
}
// html
if (cap = this.rules.html.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: this.options.sanitize
? 'paragraph'
: 'html',
pre: cap[1] === 'pre' || cap[1] === 'script',
text: cap[0],
});
continue;
}
// def
if (top && (cap = this.rules.def.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.links[cap[1].toLowerCase()] = {
href: cap[2],
title: cap[3],
};
continue;
}
// table (gfm)
if (top && (cap = this.rules.table.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n'),
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i]
.replace(/^ *\| *| *\| *$/g, '')
.split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// top-level paragraph
if (top && (cap = this.rules.paragraph.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'paragraph',
text: cap[1][cap[1].length - 1] === '\n'
? cap[1].slice(0, -1)
: cap[1],
});
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
// Top-level should never reach here.
src = src.substring(cap[0].length);
this.tokens.push({
type: 'text',
text: cap[0],
});
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return this.tokens;
};
/**
* Inline-Level Grammar
*/
const inline = {
escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
url: noop,
tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
link: /^!?\[(inside)\]\(href\)/,
reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
br: /^ {2,}\n(?!\s*$)/,
del: noop,
text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/,
};
inline._inside = /(?:\[[^\]]*\]|[^\]]|\](?=[^\[]*\]))*/;
inline._href = /\s*<?([^\s]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
inline.link = replace(inline.link)('inside', inline._inside)('href', inline._href)();
inline.reflink = replace(inline.reflink)('inside', inline._inside)();
/**
* Normal Inline Grammar
*/
inline.normal = merge({}, inline);
/**
* Pedantic Inline Grammar
*/
inline.pedantic = merge({}, inline.normal, {
strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/,
});
/**
* GFM Inline Grammar
*/
inline.gfm = merge({}, inline.normal, {
escape: replace(inline.escape)('])', '~|])')(),
url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
del: /^~~(?=\S)([\s\S]*?\S)~~/,
text: replace(inline.text)(']|', '~]|')('|', '|https?://|')(),
});
/**
* GFM + Line Breaks Inline Grammar
*/
inline.breaks = merge({}, inline.gfm, {
br: replace(inline.br)('{2,}', '*')(),
text: replace(inline.gfm.text)('{2,}', '*')(),
});
/**
* Inline Lexer & Compiler
*/
function InlineLexer(links, options) {
this.options = options || marked.defaults;
this.links = links;
this.rules = inline.normal;
if (!this.links) {
throw new
Error('Tokens array requires a `links` property.');
}
if (this.options.gfm) {
if (this.options.breaks) {
this.rules = inline.breaks;
} else {
this.rules = inline.gfm;
}
} else if (this.options.pedantic) {
this.rules = inline.pedantic;
}
}
/**
* Expose Inline Rules
*/
InlineLexer.rules = inline;
/**
* Static Lexing/Compiling Method
*/
InlineLexer.output = function(src, links, options) {
const inline = new InlineLexer(links, options);
return inline.output(src);
};
/**
* Lexing/Compiling
*/
InlineLexer.prototype.output = function(src) {
const out = [];
let link;
let text;
let href;
let cap;
while (src) {
// escape
if (cap = this.rules.escape.exec(src)) {
src = src.substring(cap[0].length);
out.push(cap[1]);
continue;
}
// autolink
if (cap = this.rules.autolink.exec(src)) {
src = src.substring(cap[0].length);
if (cap[2] === '@') {
text = cap[1][6] === ':'
? cap[1].substring(7)
: cap[1];
href = 'mailto:' + text;
} else {
text = cap[1];
href = text;
}
out.push(React.DOM.a({href: this.sanitizeUrl(href)}, text));
continue;
}
// url (gfm)
if (cap = this.rules.url.exec(src)) {
src = src.substring(cap[0].length);
text = cap[1];
href = text;
out.push(React.DOM.a({href: this.sanitizeUrl(href)}, text));
continue;
}
// tag
if (cap = this.rules.tag.exec(src)) {
src = src.substring(cap[0].length);
// TODO(alpert): Don't escape if sanitize is false
out.push(cap[0]);
continue;
}
// link
if (cap = this.rules.link.exec(src)) {
src = src.substring(cap[0].length);
out.push(this.outputLink(cap, {
href: cap[2],
title: cap[3],
}));
continue;
}
// reflink, nolink
if ((cap = this.rules.reflink.exec(src))
|| (cap = this.rules.nolink.exec(src))) {
src = src.substring(cap[0].length);
link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
link = this.links[link.toLowerCase()];
if (!link || !link.href) {
out.push.apply(out, this.output(cap[0][0]));
src = cap[0].substring(1) + src;
continue;
}
out.push(this.outputLink(cap, link));
continue;
}
// strong
if (cap = this.rules.strong.exec(src)) {
src = src.substring(cap[0].length);
out.push(React.DOM.strong(null, this.output(cap[2] || cap[1])));
continue;
}
// em
if (cap = this.rules.em.exec(src)) {
src = src.substring(cap[0].length);
out.push(React.DOM.em(null, this.output(cap[2] || cap[1])));
continue;
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
out.push(React.DOM.code(null, cap[2]));
continue;
}
// br
if (cap = this.rules.br.exec(src)) {
src = src.substring(cap[0].length);
out.push(React.DOM.br(null, null));
continue;
}
// del (gfm)
if (cap = this.rules.del.exec(src)) {
src = src.substring(cap[0].length);
out.push(React.DOM.del(null, this.output(cap[1])));
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
src = src.substring(cap[0].length);
out.push(this.smartypants(cap[0]));
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return out;
};
/**
* Sanitize a URL for a link or image
*/
InlineLexer.prototype.sanitizeUrl = function(url) {
if (this.options.sanitize) {
try {
const prot = decodeURIComponent(url)
.replace(/[^A-Za-z0-9:]/g, '')
.toLowerCase();
if (prot.indexOf('javascript:') === 0) { // eslint-disable-line
return '#';
}
} catch (e) {
return '#';
}
}
return url;
};
/**
* Compile Link
*/
InlineLexer.prototype.outputLink = function(cap, link) {
if (cap[0][0] !== '!') {
const shouldOpenInNewWindow =
link.href.charAt(0) !== '/'
&& link.href.charAt(0) !== '#';
return React.DOM.a({
href: this.sanitizeUrl(link.href),
title: link.title,
target: shouldOpenInNewWindow ? '_blank' : '',
}, this.output(cap[1]));
} else {
return React.DOM.img({
src: this.sanitizeUrl(link.href),
alt: cap[1],
title: link.title,
}, null);
}
};
/**
* Smartypants Transformations
*/
InlineLexer.prototype.smartypants = function(text) {
if (!this.options.smartypants) {return text;}
return text
.replace(/--/g, '\u2014')
.replace(/'([^']*)'/g, '\u2018$1\u2019')
.replace(/"([^"]*)"/g, '\u201C$1\u201D')
.replace(/\.{3}/g, '\u2026');
};
/**
* Parsing & Compiling
*/
function Parser(options) {
this.tokens = [];
this.token = null;
this.options = options || marked.defaults;
}
/**
* Static Parse Method
*/
Parser.parse = function(src, options) {
const parser = new Parser(options);
return parser.parse(src);
};
/**
* Parse Loop
*/
Parser.prototype.parse = function(src) {
this.inline = new InlineLexer(src.links, this.options);
this.tokens = src.reverse();
const out = [];
while (this.next()) {
out.push(this.tok());
}
return out;
};
/**
* Next Token
*/
Parser.prototype.next = function() {
return this.token = this.tokens.pop();
};
/**
* Preview Next Token
*/
Parser.prototype.peek = function() {
return this.tokens[this.tokens.length - 1] || 0;
};
/**
* Parse Text Tokens
*/
Parser.prototype.parseText = function() {
let body = this.token.text;
while (this.peek().type === 'text') {
body += '\n' + this.next().text;
}
return this.inline.output(body);
};
/**
* Parse Current Token
*/
Parser.prototype.tok = function() { // eslint-disable-line
switch (this.token.type) {
case 'space': {
return [];
}
case 'hr': {
return React.DOM.hr(null, null);
}
case 'heading': {
return (
<Header level={this.token.depth} toSlug={this.token.text}>
{this.inline.output(this.token.text)}
</Header>
);
}
case 'code': {
return <Prism>{this.token.text}</Prism>;
}
case 'table': {
const table = [];
const body = [];
let row = [];
let heading;
let i;
let cells;
let j;
// header
for (i = 0; i < this.token.header.length; i++) {
heading = this.inline.output(this.token.header[i]);
row.push(React.DOM.th(
this.token.align[i]
? {style: {textAlign: this.token.align[i]}}
: null,
heading
));
}
table.push(React.DOM.thead(null, React.DOM.tr(null, row)));
// body
for (i = 0; i < this.token.cells.length; i++) {
row = [];
cells = this.token.cells[i];
for (j = 0; j < cells.length; j++) {
row.push(React.DOM.td(
this.token.align[j]
? {style: {textAlign: this.token.align[j]}}
: null,
this.inline.output(cells[j])
));
}
body.push(React.DOM.tr(null, row));
}
table.push(React.DOM.thead(null, body));
return React.DOM.table(null, table);
}
case 'blockquote_start': {
const body = [];
while (this.next().type !== 'blockquote_end') {
body.push(this.tok());
}
return React.DOM.blockquote(null, body);
}
case 'list_start': {
const type = this.token.ordered ? 'ol' : 'ul';
const body = [];
while (this.next().type !== 'list_end') {
body.push(this.tok());
}
return React.DOM[type](null, body);
}
case 'list_item_start': {
const body = [];
while (this.next().type !== 'list_item_end') {
body.push(this.token.type === 'text'
? this.parseText()
: this.tok());
}
return React.DOM.li(null, body);
}
case 'loose_item_start': {
const body = [];
while (this.next().type !== 'list_item_end') {
body.push(this.tok());
}
return React.DOM.li(null, body);
}
case 'html': {
return React.DOM.div({
dangerouslySetInnerHTML: {
__html: this.token.text,
},
});
}
case 'paragraph': {
return this.options.paragraphFn
? this.options.paragraphFn.call(null, this.inline.output(this.token.text))
: React.DOM.p(null, this.inline.output(this.token.text));
}
case 'text': {
return this.options.paragraphFn
? this.options.paragraphFn.call(null, this.parseText())
: React.DOM.p(null, this.parseText());
}
}
};
/**
* Helpers
*/
function replace(regex, opt) {
regex = regex.source;
opt = opt || '';
return function self(name, val) {
if (!name) {return new RegExp(regex, opt);}
val = val.source || val;
val = val.replace(/(^|[^\[])\^/g, '$1');
regex = regex.replace(name, val);
return self;
};
}
function noop() {}
noop.exec = noop;
function merge(obj) {
let i = 1;
let target;
let key;
for (; i < arguments.length; i++) {
target = arguments[i];
for (key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
obj[key] = target[key];
}
}
}
return obj;
}
/**
* Marked
*/
function marked(src, opt, callback) {
if (callback || typeof opt === 'function') {
if (!callback) {
callback = opt;
opt = null;
}
if (opt) {opt = merge({}, marked.defaults, opt);}
const highlight = opt.highlight;
let tokens;
let pending;
let i = 0;
try {
tokens = Lexer.lex(src, opt);
} catch (e) {
return callback(e);
}
pending = tokens.length;
const done = function(hi) {
let out, err;
if (hi !== true) {
delete opt.highlight;
}
try {
out = Parser.parse(tokens, opt);
} catch (e) {
err = e;
}
opt.highlight = highlight;
return err
? callback(err)
: callback(null, out);
};
if (!highlight || highlight.length < 3) {
return done(true);
}
if (!pending) {return done();}
for (; i < tokens.length; i++) {
(function(token) {
if (token.type !== 'code') {
return --pending || done();
}
return highlight(token.text, token.lang, (err, code) => {
if (code == null || code === token.text) {
return --pending || done();
}
token.text = code;
token.escaped = true;
--pending || done();
return undefined;
});
})(tokens[i]);
}
return undefined;
}
try {
if (opt) {opt = merge({}, marked.defaults, opt);}
return Parser.parse(Lexer.lex(src, opt), opt);
} catch (e) {
e.message += '\nPlease report this to https://github.com/chjj/marked.';
if ((opt || marked.defaults).silent) {
return [React.DOM.p(null, 'An error occurred:'),
React.DOM.pre(null, e.message)];
}
throw e;
}
}
/**
* Options
*/
marked.options =
marked.setOptions = function(opt) {
merge(marked.defaults, opt);
return marked;
};
marked.defaults = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: false,
silent: false,
highlight: null,
langPrefix: 'lang-',
smartypants: false,
paragraphFn: null,
};
/**
* Expose
*/
marked.Parser = Parser;
marked.parser = Parser.parse;
marked.Lexer = Lexer;
marked.lexer = Lexer.lex;
marked.InlineLexer = InlineLexer;
marked.inlineLexer = InlineLexer.output;
marked.parse = marked;
const Marked = React.createClass({
render() {
return <div>{marked(this.props.children, this.props)}</div>;
},
});
module.exports = Marked;
| mpontus/jest | website/core/Marked.js | JavaScript | bsd-3-clause | 23,888 |
import sys
import time
import traceback
import dis
from browser import document as doc, window, alert
from javascript import JSObject
# set height of container to 66% of screen
_height = doc.documentElement.clientHeight
_s = doc['container']
_s.style.height = '%spx' % int(_height * 0.66)
has_ace = True
try:
editor = window.ace.edit("editor")
session = editor.getSession()
session.setMode("ace/mode/python")
editor.setOptions({
'enableLiveAutocompletion': True,
'enableSnippets': True,
'highlightActiveLine': False,
'highlightSelectedWord': True
})
except:
from browser import html
editor = html.TEXTAREA(rows=20, cols=70)
doc["editor"] <= editor
def get_value(): return editor.value
def set_value(x):editor.value = x
editor.getValue = get_value
editor.setValue = set_value
has_ace = False
if sys.has_local_storage:
from browser.local_storage import storage
else:
storage = None
if 'set_debug' in doc:
__BRYTHON__.debug = int(doc['set_debug'].checked)
def reset_src():
if storage is not None and "py_src" in storage:
editor.setValue(storage["py_src"])
else:
editor.setValue('for i in range(10):\n\tprint(i)')
editor.scrollToRow(0)
editor.gotoLine(0)
def reset_src_area():
if storage and "py_src" in storage:
editor.value = storage["py_src"]
else:
editor.value = 'for i in range(10):\n\tprint(i)'
class cOutput:
def write(self, data):
doc["console"].value += str(data)
def flush(self):
pass
sys.stdout = cOutput()
sys.stderr = cOutput()
def to_str(xx):
return str(xx)
info = sys.implementation.version
doc['version'].text = '%s.%s.%s' % (info.major, info.minor, info.micro)
output = ''
def show_console(ev):
doc["console"].value = output
doc["console"].cols = 60
# load a Python script
def load_script(evt):
_name = evt.target.value + '?foo=%s' % time.time()
editor.setValue(open(_name).read())
# run a script, in global namespace if in_globals is True
def run(in_globals=False):
global output
doc["console"].value = ''
src = editor.getValue()
if storage is not None:
storage["py_src"] = src
t0 = time.perf_counter()
try:
if(in_globals):
exec(src)
else:
ns = {}
exec(src, ns)
state = 1
except Exception as exc:
traceback.print_exc(file=sys.stderr)
state = 0
output = doc["console"].value
print('<completed in %6.2f ms>' % ((time.perf_counter() - t0) * 1000.0))
return state
def show_js(ev):
src = editor.getValue()
doc["console"].value = dis.dis(src)
if has_ace:
reset_src()
else:
reset_src_area()
| firmlyjin/brython | www/tests/editor.py | Python | bsd-3-clause | 2,743 |
<?php
namespace backend\models\forms;
use backend\models\User;
use Yii;
use yii\base\Model;
use yii\behaviors\TimestampBehavior;
/**
* Login form
*/
class LoginForm extends Model
{
public $email;
public $password;
public $rememberMe = TRUE;
private $_user;
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'timestamp' => [
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => time(),
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
// email and password are both required
[['email', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'email' => Yii::t('admin-side', 'Email'),
'password' => Yii::t('admin-side', 'Password'),
'rememberMe' => Yii::t('admin-side', 'Remember Me'),
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, Yii::t('admin-side', 'Incorrect login or password'));
}
}
}
/**
* Finds user by [[email]]
*
* @return User|null
*/
protected function getUser()
{
if ($this->_user === NULL) {
$this->_user = User::findByEmail($this->email);
}
return $this->_user;
}
/**
* Logs in a user using the provided email and password.
*
* @return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
if (Yii::$app->user->login($this->getUser(), $this->rememberMe ? (3600 * 24 * 30) : 0)) {
if (
Yii::$app->user->cannot([
User::ROLE_ROOT,
User::ROLE_ADMIN,
User::ROLE_MANAGER,
User::ROLE_SELLER,
])
) {
Yii::$app->user->logout();
Yii::$app->session->addFlash('error', Yii::t('admin-side', 'You have insufficient privileges!'));
return FALSE;
}
return TRUE;
}
}
return FALSE;
}
}
| xZ1mEFx/y2shop | backend/models/forms/LoginForm.php | PHP | bsd-3-clause | 3,073 |
<?php
/**
* Backend Object Controller.
*
* @package backend.controllers
*
*/
class BepujapurposeController extends BeController
{
public function __construct($id,$module=null)
{
parent::__construct($id,$module);
$this->menu=array(
array('label'=>t('Add Puja Purpose'), 'url'=>array('create'),'linkOptions'=>array('class'=>'btn btn-mini')),
);
}
/**
* The function that do Create new Object
*
*/
public function actionCreate()
{
$this->render('purpose_create');
}
/**
* The function that do Update Object
*
*/
public function actionUpdate()
{
$id=isset($_GET['id']) ? (int) ($_GET['id']) : 0 ;
$this->render('purpose_update');
}
/**
* The function that do View User
*
*/
public function actionView()
{
$id=isset($_GET['id']) ? (int) ($_GET['id']) : 0 ;
$this->render('purpose_view');
}
/**
* The function that do Manage Object
*
*/
public function actionAdmin()
{
$this->render('purpose_admin');
}
public function actionDelete($id)
{
GxcHelpers::deleteModel('Pujapurpose', $id);
}
} | troikaitsulutions/templeadvisor | protected/controllers/BepujapurposeController.php | PHP | bsd-3-clause | 1,386 |
<?php
/* @var $this ActividadesController */
/* @var $data Actividades */
?>
<div class="view" style="width: inherit;border: 2px solid #949494;background-color: white;padding: 10px;">
<h4><?php echo CHtml::encode($data->act_nombre); ?></h4>
Se realizara el <?php echo CHtml::encode($data->act_fecha); ?> entre las <?php echo CHtml::encode($data->act_horaInicio); ?> y las <?php echo CHtml::encode($data->act_horaFin); ?>.
<br>
Lugar: <?php echo CHtml::encode($data->act_lugar); ?>.
<br>
Descripción: <?php echo CHtml::encode($data->act_descripcion); ?>.
</div> | leo14/EPI_TESIS | EPI/protected/views/actividades/_view.php | PHP | bsd-3-clause | 572 |
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013-2015, 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.
//
//////////////////////////////////////////////////////////////////////////
#include <cassert>
#include "IECoreMaya/SceneShapeInterface.h"
#include "IECoreMaya/SceneShapeInterfaceComponentBoundIterator.h"
#include "boost/python.hpp"
#include "boost/tokenizer.hpp"
#include "OpenEXR/ImathMatrixAlgo.h"
#include "OpenEXR/ImathBoxAlgo.h"
#include "IECoreGL/Renderer.h"
#include "IECoreGL/Scene.h"
#include "IECoreGL/TypedStateComponent.h"
#include "IECoreGL/NameStateComponent.h"
#include "IECoreGL/State.h"
#include "IECoreGL/Camera.h"
#include "IECoreGL/Renderable.h"
#include "IECoreGL/Group.h"
#include "IECoreMaya/Convert.h"
#include "IECoreMaya/ToMayaMeshConverter.h"
#include "IECoreMaya/ToMayaCurveConverter.h"
#include "IECoreMaya/MayaTypeIds.h"
#include "IECoreMaya/PostLoadCallback.h"
#include "IECorePython/ScopedGILLock.h"
#include "IECorePython/ScopedGILRelease.h"
#include "IECore/VectorOps.h"
#include "IECore/MessageHandler.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/CompoundParameter.h"
#include "IECore/AngleConversion.h"
#include "IECore/VisibleRenderable.h"
#include "IECore/TransformBlock.h"
#include "IECore/AttributeBlock.h"
#include "IECore/SampledSceneInterface.h"
#include "IECore/CurvesPrimitive.h"
#include "IECore/TransformOp.h"
#include "IECore/CoordinateSystem.h"
#include "IECore/Transform.h"
#include "IECore/MatrixAlgo.h"
#include "IECore/LinkedScene.h"
#include "maya/MArrayDataBuilder.h"
#include "maya/MFnNumericAttribute.h"
#include "maya/MFnEnumAttribute.h"
#include "maya/MFnTypedAttribute.h"
#include "maya/MFnGenericAttribute.h"
#include "maya/MFnUnitAttribute.h"
#include "maya/MFnCompoundAttribute.h"
#include "maya/MFnSingleIndexedComponent.h"
#include "maya/MSelectionList.h"
#include "maya/MAttributeSpec.h"
#include "maya/MAttributeIndex.h"
#include "maya/MAttributeSpecArray.h"
#include "maya/MDagPath.h"
#include "maya/MFnStringData.h"
#include "maya/MFnMeshData.h"
#include "maya/MFnNurbsCurveData.h"
#include "maya/MFnGeometryData.h"
#include "maya/MPlugArray.h"
#include "maya/MFileIO.h"
#if MAYA_API_VERSION >= 201600
#include "maya/MEvaluationNode.h"
#endif
using namespace Imath;
using namespace IECore;
using namespace IECoreMaya;
MTypeId SceneShapeInterface::id = SceneShapeInterfaceId;
MObject SceneShapeInterface::aObjectOnly;
MObject SceneShapeInterface::aDrawGeometry;
MObject SceneShapeInterface::aDrawRootBound;
MObject SceneShapeInterface::aDrawChildBounds;
MObject SceneShapeInterface::aDrawTagsFilter;
MObject SceneShapeInterface::aQuerySpace;
MObject SceneShapeInterface::aTime;
MObject SceneShapeInterface::aOutTime;
MObject SceneShapeInterface::aSceneQueries;
MObject SceneShapeInterface::aAttributeQueries;
MObject SceneShapeInterface::aConvertParamQueries;
MObject SceneShapeInterface::aOutputObjects;
MObject SceneShapeInterface::aObjectDependency;
MObject SceneShapeInterface::aAttributes;
MObject SceneShapeInterface::aAttributeValues;
MObject SceneShapeInterface::aTransform;
MObject SceneShapeInterface::aTranslate;
MObject SceneShapeInterface::aTranslateX;
MObject SceneShapeInterface::aTranslateY;
MObject SceneShapeInterface::aTranslateZ;
MObject SceneShapeInterface::aRotate;
MObject SceneShapeInterface::aRotateX;
MObject SceneShapeInterface::aRotateY;
MObject SceneShapeInterface::aRotateZ;
MObject SceneShapeInterface::aScale;
MObject SceneShapeInterface::aScaleX;
MObject SceneShapeInterface::aScaleY;
MObject SceneShapeInterface::aScaleZ;
MObject SceneShapeInterface::aBound;
MObject SceneShapeInterface::aBoundMin;
MObject SceneShapeInterface::aBoundMinX;
MObject SceneShapeInterface::aBoundMinY;
MObject SceneShapeInterface::aBoundMinZ;
MObject SceneShapeInterface::aBoundMax;
MObject SceneShapeInterface::aBoundMaxX;
MObject SceneShapeInterface::aBoundMaxY;
MObject SceneShapeInterface::aBoundMaxZ;
MObject SceneShapeInterface::aBoundCenter;
MObject SceneShapeInterface::aBoundCenterX;
MObject SceneShapeInterface::aBoundCenterY;
MObject SceneShapeInterface::aBoundCenterZ;
// This post load callback is used to dirty the aOutputObjects elements
// following loading - see further comments in initialize.
class SceneShapeInterface::PostLoadCallback : public IECoreMaya::PostLoadCallback
{
public :
PostLoadCallback( SceneShapeInterface *node ) : m_node( node )
{
}
protected :
SceneShapeInterface *m_node;
virtual void postLoad()
{
MFnDependencyNode fnDN( m_node->thisMObject() );
MPlug plug = fnDN.findPlug( aObjectDependency );
plug.setValue( 1 );
m_node->m_postLoadCallback = 0; // remove this callback
}
};
SceneShapeInterface::SceneShapeInterface()
: m_previewSceneDirty( true )
{
// We only create the post load callback when Maya is reading a scene,
// so that it does not effect nodes as they are created by users.
m_postLoadCallback = ( MFileIO::isReadingFile() ) ? new PostLoadCallback( this ) : NULL;
}
SceneShapeInterface::~SceneShapeInterface()
{
}
void *SceneShapeInterface::creator()
{
return new SceneShapeInterface;
}
void SceneShapeInterface::postConstructor()
{
setExistWithoutInConnections(true);
setExistWithoutOutConnections(true);
}
MStatus SceneShapeInterface::initialize()
{
MFnNumericAttribute nAttr;
MFnTypedAttribute tAttr;
MFnCompoundAttribute cAttr;
MFnGenericAttribute gAttr;
MFnUnitAttribute uAttr;
MFnEnumAttribute eAttr;
MStatus s;
aObjectOnly = nAttr.create( "objectOnly", "obj", MFnNumericData::kBoolean, 0 );
nAttr.setReadable( true );
nAttr.setWritable( true );
nAttr.setStorable( true );
nAttr.setConnectable( true );
nAttr.setHidden( false );
addAttribute( aObjectOnly );
aDrawGeometry = nAttr.create( "drawGeometry", "drg", MFnNumericData::kBoolean, 0, &s );
nAttr.setReadable( true );
nAttr.setWritable( true );
nAttr.setStorable( true );
nAttr.setConnectable( true );
nAttr.setHidden( false );
nAttr.setChannelBox( true );
s = addAttribute( aDrawGeometry );
aDrawRootBound = nAttr.create( "drawRootBound", "drbd", MFnNumericData::kBoolean, 1, &s );
nAttr.setReadable( true );
nAttr.setWritable( true );
nAttr.setStorable( true );
nAttr.setConnectable( true );
nAttr.setHidden( false );
nAttr.setChannelBox( true );
s = addAttribute( aDrawRootBound );
aDrawChildBounds = nAttr.create( "drawChildBounds", "dchd", MFnNumericData::kBoolean, 0, &s );
nAttr.setReadable( true );
nAttr.setWritable( true );
nAttr.setStorable( true );
nAttr.setConnectable( true );
nAttr.setHidden( false );
nAttr.setChannelBox( true );
s = addAttribute( aDrawChildBounds );
aDrawTagsFilter = tAttr.create( "drawTagsFilter", "dtf", MFnData::kString, MFnStringData().create( "" ), &s );
assert( s );
s = addAttribute( aDrawTagsFilter );
assert( s );
aQuerySpace = eAttr.create( "querySpace", "qsp", 0);
eAttr.addField( "World", World );
eAttr.addField( "Local", Local );
s = addAttribute( aQuerySpace );
aTime = uAttr.create( "time", "tim", MFnUnitAttribute::kTime, 0.0, &s );
uAttr.setConnectable( true );
uAttr.setHidden( false );
uAttr.setReadable( true );
uAttr.setWritable( true );
uAttr.setStorable( true );
s = addAttribute( aTime );
aOutTime = uAttr.create( "outTime", "otm", MFnUnitAttribute::kTime, 0.0, &s );
uAttr.setReadable( true );
uAttr.setWritable( false );
uAttr.setStorable( false );
s = addAttribute( aOutTime );
// Queries
aSceneQueries = tAttr.create( "queryPaths", "qpa", MFnData::kString, &s );
tAttr.setReadable( true );
tAttr.setWritable( true );
tAttr.setStorable( true );
tAttr.setConnectable( true );
tAttr.setHidden( false );
tAttr.setArray( true );
tAttr.setIndexMatters( true );
s = addAttribute( aSceneQueries );
aAttributeQueries = tAttr.create( "queryAttributes", "qat", MFnData::kString, &s );
tAttr.setReadable( true );
tAttr.setWritable( true );
tAttr.setStorable( true );
tAttr.setConnectable( true );
tAttr.setHidden( false );
tAttr.setArray( true );
tAttr.setIndexMatters( true );
s = addAttribute( aAttributeQueries );
aConvertParamQueries = tAttr.create( "queryConvertParameters", "qcp", MFnData::kString, &s );
tAttr.setReadable( true );
tAttr.setWritable( true );
tAttr.setStorable( true );
tAttr.setConnectable( true );
tAttr.setHidden( false );
tAttr.setArray( true );
tAttr.setIndexMatters( true );
s = addAttribute( aConvertParamQueries );
// Output objects
aOutputObjects = gAttr.create( "outObjects", "oob", &s );
gAttr.addDataAccept( MFnMeshData::kMesh );
gAttr.addDataAccept( MFnNurbsCurveData::kNurbsCurve );
gAttr.addNumericDataAccept( MFnNumericData::k3Double );
gAttr.setReadable( true );
gAttr.setWritable( false );
gAttr.setArray( true );
gAttr.setIndexMatters( true );
gAttr.setUsesArrayDataBuilder( true );
gAttr.setStorable( false );
s = addAttribute( aOutputObjects );
// A Maya bug causes mesh attributes to compute on scene open, even when nothing should be
// pulling on them. While dynamic attributes can work around this issue for single meshes,
// arrays of meshes suffer from the erroneous compute as either static or dynamic attributes.
//
// We work around the problem by adding a PostLoadCallback if the node was created while the
// scene is being read from disk. This callback is used to short circuit the compute which
// was triggered on scene open. Since the compute may have actually been necessary, we use
// this dummy dependency attribute to dirty the output object attributes immediately following
// load. At this point the callback deletes itself, and the newly dirtied output objects will
// re-compute if something was actually pulling on them.
aObjectDependency = nAttr.create( "objectDependency", "objDep", MFnNumericData::kInt, 0 );
nAttr.setStorable( false );
nAttr.setHidden( true );
s = addAttribute( aObjectDependency );
// Transform
aTranslateX = nAttr.create( "outTranslateX", "otx", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aTranslateY = nAttr.create( "outTranslateY", "oty", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aTranslateZ = nAttr.create( "outTranslateZ", "otz", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aTranslate = nAttr.create( "outTranslate", "obt", aTranslateX, aTranslateY, aTranslateZ, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aRotateX = uAttr.create( "outRotateX", "orx", MFnUnitAttribute::kAngle, 0.0, &s );
uAttr.setWritable( false );
uAttr.setStorable( false );
aRotateY = uAttr.create( "outRotateY", "ory", MFnUnitAttribute::kAngle, 0.0, &s );
uAttr.setWritable( false );
uAttr.setStorable( false );
aRotateZ = uAttr.create( "outRotateZ", "orz", MFnUnitAttribute::kAngle, 0.0, &s );
uAttr.setWritable( false );
uAttr.setStorable( false );
aRotate = nAttr.create( "outRotate", "obr", aRotateX, aRotateY, aRotateZ, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aScaleX = nAttr.create( "outScaleX", "osx", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aScaleY = nAttr.create( "outScaleY", "osy", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aScaleZ = nAttr.create( "outScaleZ", "osz", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aScale = nAttr.create( "outScale", "obs", aScaleX, aScaleY, aScaleZ, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aTransform = cAttr.create( "outTransform", "otr" );
cAttr.addChild( aTranslate );
cAttr.addChild( aRotate );
cAttr.addChild( aScale );
cAttr.setReadable( true );
cAttr.setWritable( false );
cAttr.setArray( true );
cAttr.setIndexMatters( true );
cAttr.setUsesArrayDataBuilder( true );
cAttr.setStorable( false );
s = addAttribute( aTransform );
// Bounding box
aBoundMinX = nAttr.create( "outBoundMinX", "obminx", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundMinY = nAttr.create( "outBoundMinY", "cobminy", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundMinZ = nAttr.create( "outBoundMinZ", "obminz", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundMin = nAttr.create( "outBoundMin", "obmin", aBoundMinX, aBoundMinY, aBoundMinZ, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundMaxX = nAttr.create( "outBoundMaxX", "obmaxx", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundMaxY = nAttr.create( "outBoundMaxY", "cobmaxy", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundMaxZ = nAttr.create( "outBoundMaxZ", "obmaxz", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundMax = nAttr.create( "outBoundMax", "obmax", aBoundMaxX, aBoundMaxY, aBoundMaxZ, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundCenterX = nAttr.create( "outBoundCenterX", "obcx", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundCenterY = nAttr.create( "outBoundCenterY", "obcy", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundCenterZ = nAttr.create( "outBoundCenterZ", "obcz", MFnNumericData::kFloat, 0, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBoundCenter = nAttr.create( "outBoundCenter", "obc", aBoundCenterX, aBoundCenterY, aBoundCenterZ, &s );
nAttr.setWritable( false );
nAttr.setStorable( false );
aBound = cAttr.create( "outBound", "obd" );
cAttr.addChild( aBoundMin );
cAttr.addChild( aBoundMax );
cAttr.addChild( aBoundCenter );
cAttr.setReadable( true );
cAttr.setWritable( false );
cAttr.setArray( true );
cAttr.setIndexMatters( true );
cAttr.setUsesArrayDataBuilder( true );
cAttr.setStorable( false );
s = addAttribute( aBound );
assert( s );
// Attributes
MFnGenericAttribute genAttr;
aAttributeValues = genAttr.create( "attributeValues", "atv", &s );
genAttr.addNumericDataAccept( MFnNumericData::kBoolean );
genAttr.addNumericDataAccept( MFnNumericData::kInt );
genAttr.addNumericDataAccept( MFnNumericData::kFloat );
genAttr.addNumericDataAccept( MFnNumericData::kDouble );
genAttr.addDataAccept( MFnData::kString );
genAttr.setReadable( true );
genAttr.setWritable( false );
genAttr.setStorable( false );
genAttr.setConnectable( true );
genAttr.setArray( true );
genAttr.setIndexMatters( true );
genAttr.setUsesArrayDataBuilder( true );
addAttribute( aAttributeValues );
aAttributes = cAttr.create( "attributes", "ott" );
cAttr.addChild( aAttributeValues );
cAttr.setReadable( true );
cAttr.setWritable( false );
cAttr.setArray( true );
cAttr.setIndexMatters( true );
cAttr.setUsesArrayDataBuilder( true );
cAttr.setReadable( true );
cAttr.setStorable( false );
s = addAttribute( aAttributes );
attributeAffects( aSceneQueries, aTransform );
attributeAffects( aSceneQueries, aBound );
attributeAffects( aSceneQueries, aOutputObjects );
attributeAffects( aSceneQueries, aAttributes );
attributeAffects( aAttributeQueries, aAttributes );
attributeAffects( aConvertParamQueries, aOutputObjects );
attributeAffects( aQuerySpace, aTransform );
attributeAffects( aQuerySpace, aBound );
attributeAffects( aQuerySpace, aOutputObjects );
attributeAffects( aTime, aOutTime );
return s;
}
ConstSceneInterfacePtr SceneShapeInterface::getSceneInterface( )
{
throw Exception( "SceneShapeInterface: getSceneInterface not implemented!" );
}
bool SceneShapeInterface::isBounded() const
{
return true;
}
double SceneShapeInterface::time() const
{
MPlug pTime( thisMObject(), aTime );
MTime time;
pTime.getValue( time );
return time.as( MTime::kSeconds );
}
MBoundingBox SceneShapeInterface::boundingBox() const
{
MBoundingBox bound( MPoint( -1, -1, -1 ), MPoint( 1, 1, 1 ) );
ConstSceneInterfacePtr scn = const_cast<SceneShapeInterface*>(this)->getSceneInterface();
if( scn )
{
try
{
MPlug pTime( thisMObject(), aTime );
MTime time;
pTime.getValue( time );
// Check what bounding box we need. If objectOnly we want the objectBound, else the scene bound.
// If objectOnly and no object, return the scene bound to have something sensible. It won't be drawn.
MPlug pObjectOnly( thisMObject(), aObjectOnly );
bool objectOnly;
pObjectOnly.getValue( objectOnly );
bool objectBound = objectOnly;
if( objectOnly )
{
// Check for an object
if( scn->hasObject() )
{
ConstObjectPtr object = scn->readObject( time.as( MTime::kSeconds ) );
const VisibleRenderable *obj = runTimeCast< const VisibleRenderable >( object.get() );
if( obj )
{
Box3f objBox = obj->bound();
if( !objBox.isEmpty() )
{
bound = convert<MBoundingBox>( objBox );
}
}
}
else
{
objectBound = false;
}
}
if( !objectBound )
{
Box3d b = scn->readBound( time.as( MTime::kSeconds ) );
if( !b.isEmpty() )
{
bound = convert<MBoundingBox>( b );
}
}
}
catch( std::exception &e )
{
msg( Msg::Error, "SceneShapeInterface::boundingBox", e.what() );
}
catch( ... )
{
msg( Msg::Error, "SceneShapeInterface::boundingBox", "Exception thrown in SceneShapeInterface::bound" );
}
}
return bound;
}
MStatus SceneShapeInterface::setDependentsDirty( const MPlug &plug, MPlugArray &plugArray )
{
if( plug == aTime )
{
// Check if sceneInterface is animated. If not, plugs are not dependent on time
if( animatedScene() )
{
m_previewSceneDirty = true;
childChanged( kBoundingBoxChanged ); // needed to tell maya the bounding box has changed
// Need to go through all output plugs, since Maya doesn't propagate dirtiness from parent plug to the children in setDependentsDirty
MPlug pObjects( thisMObject(), aOutputObjects );
for( unsigned i=0; i<pObjects.numElements(); i++ )
{
MPlug p = pObjects[i];
plugArray.append( p );
}
MPlug pTransform( thisMObject(), aTransform );
for( unsigned i=0; i<pTransform.numElements(); i++ )
{
MPlug p = pTransform[i];
for( unsigned j=0; j<p.numChildren(); j++ )
{
plugArray.append( p.child( j ) );
plugArray.append( p.child( j ).child( 0 ) );
plugArray.append( p.child( j ).child( 1 ) );
plugArray.append( p.child( j ).child( 2 ) );
}
}
MPlug pBound( thisMObject(), aBound);
for( unsigned i=0; i<pBound.numElements(); i++ )
{
MPlug p = pBound[i];
for( unsigned j=0; j<p.numChildren(); j++ )
{
plugArray.append( p.child( j ) );
plugArray.append( p.child( j ).child( 0 ) );
plugArray.append( p.child( j ).child( 1 ) );
plugArray.append( p.child( j ).child( 2 ) );
}
}
MPlug pAttributes( thisMObject(), aAttributes);
for( unsigned i=0; i<pAttributes.numElements(); i++ )
{
MPlug p = pAttributes[i];
MPlug pChild = p.child(0);
plugArray.append( pChild );
for( unsigned j=0; j<pChild.numElements(); j++ )
{
plugArray.append( pChild[j] );
}
}
}
}
else if( plug == aDrawGeometry || plug == aDrawChildBounds || plug == aObjectOnly || plug == aDrawTagsFilter )
{
// Preview plug values have changed, GL Scene is dirty
m_previewSceneDirty = true;
}
else if ( plug == aObjectDependency )
{
MPlug pObjects( thisMObject(), aOutputObjects );
for( unsigned i=0; i<pObjects.numElements(); i++ )
{
MPlug p = pObjects[i];
plugArray.append( p );
}
}
return MS::kSuccess;
}
#if MAYA_API_VERSION >= 201600
MStatus SceneShapeInterface::preEvaluation( const MDGContext &context, const MEvaluationNode &evaluationNode )
{
// this is in the Maya devkit simpleEvaluationNode example so
// I'm including it here, though I'm not sure when/why we'd
// be called with a non-normal context.
if( !context.isNormal() )
{
return MStatus::kFailure;
}
if(
( evaluationNode.dirtyPlugExists( aTime ) && animatedScene() ) ||
evaluationNode.dirtyPlugExists( aDrawGeometry ) ||
evaluationNode.dirtyPlugExists( aDrawChildBounds ) ||
evaluationNode.dirtyPlugExists( aObjectOnly ) ||
evaluationNode.dirtyPlugExists( aDrawTagsFilter )
)
{
m_previewSceneDirty = true;
}
return MS::kSuccess;
}
#endif
MStatus SceneShapeInterface::compute( const MPlug &plug, MDataBlock &dataBlock )
{
MStatus s;
MPlug topLevelPlug = plug;
int index = -1;
// Look for parent plug index
while( topLevelPlug.isChild() || topLevelPlug.isElement() )
{
if( topLevelPlug.isChild() )
{
topLevelPlug = topLevelPlug.parent();
}
if( topLevelPlug.isElement() )
{
index = topLevelPlug.logicalIndex();
topLevelPlug = topLevelPlug.array();
}
}
if ( topLevelPlug == aOutputObjects && m_postLoadCallback )
{
return MS::kFailure;
}
if( topLevelPlug == aOutputObjects || topLevelPlug == aTransform || topLevelPlug == aBound || topLevelPlug == aAttributes )
{
MIntArray indices;
if( index == -1 )
{
// in parallel evaluation mode, we may receive the top level plug
// directly, which means we need to compute all child plugs.
topLevelPlug.getExistingArrayAttributeIndices( indices );
}
else
{
// we still get the direct element if we're in DG mode.
indices.append( index );
}
MDataHandle timeHandle = dataBlock.inputValue( aTime );
MTime time = timeHandle.asTime();
MPlug pQuerySpace( thisMObject(), aQuerySpace );
int querySpace;
pQuerySpace.getValue( querySpace );
MString name;
SceneInterface::Path path;
MPlug pSceneQueries( thisMObject(), aSceneQueries );
ConstSceneInterfacePtr sc = getSceneInterface();
if( !sc )
{
// Scene Interface isn't valid
MFnDagNode dag(thisMObject());
msg( Msg::Error, dag.fullPathName().asChar(), "Input values are invalid." );
return MS::kFailure;
}
unsigned numIndices = indices.length();
for( unsigned i = 0; i < numIndices; ++i )
{
MPlug pQuery = pSceneQueries.elementByLogicalIndex( indices[i] );
pQuery.getValue( name );
path = fullPathName( name.asChar() );
ConstSceneInterfacePtr scene = sc->scene( path, SceneInterface::NullIfMissing );
if( !scene )
{
// Queried element doesn't exist
MFnDagNode dag(thisMObject());
msg( Msg::Warning, dag.fullPathName().asChar(), boost::format( "Queried element '%s' at index '%s' does not exist " ) % name.asChar() % indices[i] );
return MS::kFailure;
}
s = computeOutputPlug( plug, topLevelPlug, dataBlock, scene.get(), indices[i], querySpace, time );
if( !s )
{
return s;
}
}
}
else if( topLevelPlug == aOutTime )
{
MDataHandle timeHandle = dataBlock.inputValue( aTime );
MTime time = timeHandle.asTime();
MDataHandle outTimeHandle = dataBlock.outputValue( aOutTime );
outTimeHandle.setMTime( time );
}
return MS::kSuccess;
}
MStatus SceneShapeInterface::computeOutputPlug( const MPlug &plug, const MPlug &topLevelPlug, MDataBlock &dataBlock, const IECore::SceneInterface *scene, int topLevelIndex, int querySpace, MTime &time )
{
MStatus s;
if( topLevelPlug == aTransform )
{
MArrayDataHandle transformHandle = dataBlock.outputArrayValue( aTransform );
MArrayDataBuilder transformBuilder = transformHandle.builder();
M44d transformd;
if( querySpace == World )
{
// World Space (starting from scene root)
transformd = worldTransform( scene, time.as( MTime::kSeconds ) );
}
else if( querySpace == Local )
{
// Local space
transformd = scene->readTransformAsMatrix( time.as( MTime::kSeconds ) );
}
V3f translate( 0 ), shear( 0 ), rotate( 0 ), scale( 1 );
extractSHRT( convert<M44f>( transformd ), scale, shear, rotate, translate );
MDataHandle transformElementHandle = transformBuilder.addElement( topLevelIndex );
transformElementHandle.child( aTranslate ).set3Float( translate[0], translate[1], translate[2] );
transformElementHandle.child( aRotate ).child( aRotateX ).setMAngle( MAngle( rotate[0] ) );
transformElementHandle.child( aRotate ).child( aRotateY ).setMAngle( MAngle( rotate[1] ) );
transformElementHandle.child( aRotate ).child( aRotateZ ).setMAngle( MAngle( rotate[2] ) );
transformElementHandle.child( aScale ).set3Float( scale[0], scale[1], scale[2] );
}
else if( topLevelPlug == aOutputObjects && scene->hasObject() )
{
MArrayDataHandle outputDataHandle = dataBlock.outputArrayValue( aOutputObjects, &s );
MArrayDataBuilder outputBuilder = outputDataHandle.builder();
ConstObjectPtr object = scene->readObject( time.as( MTime::kSeconds ) );
if( querySpace == World )
{
// If world space, need to transform the object using the concatenated matrix from the sceneInterface path to the query path
M44d transformd;
transformd = worldTransform( scene, time.as( MTime::kSeconds ) );
TransformOpPtr transformer = new TransformOp();
transformer->inputParameter()->setValue( const_cast< Object *>(object.get()) ); /// safe const_cast because the op will duplicate the Object.
transformer->copyParameter()->setTypedValue( true );
transformer->matrixParameter()->setValue( new M44dData( transformd ) );
object = transformer->operate();
}
IECore::TypeId type = object->typeId();
if( type == CoordinateSystemTypeId )
{
IECore::ConstCoordinateSystemPtr coordSys = IECore::runTimeCast<const CoordinateSystem>( object );
Imath::M44f m;
if( coordSys->getTransform() )
{
m = coordSys->getTransform()->transform();
}
Imath::V3f s(0), h(0), r(0), t(0);
Imath::extractSHRT(m, s, h, r, t);
MFnNumericData fnData;
MObject data = fnData.create( MFnNumericData::k3Double );
fnData.setData( (double)t[0], (double)t[1], (double)t[2] );
MDataHandle handle = outputBuilder.addElement( topLevelIndex );
handle.set( data );
}
else
{
ToMayaObjectConverterPtr converter = ToMayaObjectConverter::create( object );
if( converter )
{
bool isParamRead = readConvertParam( converter->parameters(), topLevelIndex );
if( ! isParamRead )
{
return MS::kFailure;
}
MObject data;
// Check the type for now, because a dag node is created if you pass an empty MObject to the converter
// Won't be needed anymore when the related todo is addressed in the converter
if( type == MeshPrimitiveTypeId )
{
MFnMeshData fnData;
data = fnData.create();
}
else if( type == CurvesPrimitiveTypeId )
{
MFnNurbsCurveData fnData;
data = fnData.create();
}
if( !data.isNull() )
{
bool conversionSuccess = converter->convert( data );
if ( conversionSuccess )
{
MDataHandle h = outputBuilder.addElement( topLevelIndex, &s );
s = h.set( data );
}
else
{
MFnDagNode dag(thisMObject());
msg( Msg::Warning, dag.fullPathName().asChar(), boost::format( "Convert object failed! index=" ) % topLevelIndex );
}
}
}
}
}
else if( topLevelPlug == aBound )
{
MArrayDataHandle boundHandle = dataBlock.outputArrayValue( aBound );
MArrayDataBuilder boundBuilder = boundHandle.builder();
Box3d bboxd = scene->readBound( time.as( MTime::kSeconds ) );
if( querySpace == World )
{
// World Space (from root path)
M44d transformd = worldTransform( scene, time.as( MTime::kSeconds ) );
bboxd = transform( bboxd, transformd );
}
Box3f bound( bboxd.min, bboxd.max );
MDataHandle boundElementHandle = boundBuilder.addElement( topLevelIndex );
boundElementHandle.child( aBoundMin ).set3Float( bound.min[0], bound.min[1], bound.min[2] );
boundElementHandle.child( aBoundMax ).set3Float( bound.max[0], bound.max[1], bound.max[2] );
V3f boundCenter = bound.center();
boundElementHandle.child( aBoundCenter ).set3Float( boundCenter[0], boundCenter[1], boundCenter[2] );
}
else if( topLevelPlug == aAttributes )
{
MIntArray attrIndices;
if( plug.isElement() && !plug.isCompound() )
{
attrIndices.append( plug.logicalIndex() );
}
else
{
// in parallel evaluation mode, we may receive the top level plug
// directly, which means we need to compute all child plugs.
topLevelPlug.elementByLogicalIndex( topLevelIndex ).getExistingArrayAttributeIndices( attrIndices );
}
MPlug pAttributeQueries( thisMObject(), aAttributeQueries );
unsigned numAttrs = attrIndices.length();
for( unsigned i = 0; i < numAttrs; ++i )
{
MPlug pAttributeQuery = pAttributeQueries.elementByLogicalIndex( attrIndices[i] );
MString attrName;
pAttributeQuery.getValue( attrName );
if( !scene->hasAttribute( attrName.asChar() ) )
{
// Queried attribute doesn't exist
MFnDagNode dag(thisMObject());
msg( Msg::Warning, dag.fullPathName().asChar(), boost::format( "Queried attribute '%s' at index '%s' does not exist " ) % attrName.asChar() % attrIndices[i] );
return MS::kFailure;
}
// Attribute query results are returned as attributes[ sceneQuery index ].attributeValues[ attributeQuery index ]
MArrayDataHandle attributesHandle = dataBlock.outputArrayValue( aAttributes );
MArrayDataBuilder builder = attributesHandle.builder();
MDataHandle elementHandle = builder.addElement( topLevelIndex );
MDataHandle attributeValuesHandle = elementHandle.child( aAttributeValues );
MArrayDataHandle arrayHandle( attributeValuesHandle );
arrayHandle.jumpToElement( attrIndices[i] );
MDataHandle currentElement = arrayHandle.outputValue();
ConstObjectPtr attrValue = scene->readAttribute( attrName.asChar(), time.as( MTime::kSeconds ) );
/// \todo Use a generic data converter that would be compatible with a generic attribute.
IECore::TypeId type = attrValue->typeId();
if( type == BoolDataTypeId )
{
bool value = static_cast< const BoolData * >(attrValue.get())->readable();
currentElement.setGenericBool( value, true);
}
else if( type == FloatDataTypeId )
{
float value = static_cast< const FloatData * >(attrValue.get())->readable();
currentElement.setGenericFloat( value, true);
}
else if( type == DoubleDataTypeId )
{
float value = static_cast< const DoubleData * >(attrValue.get())->readable();
currentElement.setGenericDouble( value, true);
}
else if( type == IntDataTypeId )
{
int value = static_cast< const IntData * >(attrValue.get())->readable();
currentElement.setGenericInt( value, true);
}
else if( type == StringDataTypeId )
{
MString value( static_cast< const StringData * >(attrValue.get())->readable().c_str() );
currentElement.setString( value );
}
}
}
return s;
}
M44d SceneShapeInterface::worldTransform( ConstSceneInterfacePtr scene, double time )
{
SceneInterface::Path p;
scene->path( p );
ConstSceneInterfacePtr tmpScene = getSceneInterface();
SceneInterface::Path pRoot;
tmpScene->path( pRoot );
M44d result;
for ( SceneInterface::Path::const_iterator it = p.begin()+pRoot.size(); tmpScene && it != p.end(); ++it )
{
tmpScene = tmpScene->child( *it, SceneInterface::NullIfMissing );
if ( !tmpScene )
{
break;
}
result = tmpScene->readTransformAsMatrix( time ) * result;
}
return result;
}
MPxSurfaceShape::MatchResult SceneShapeInterface::matchComponent( const MSelectionList &item, const MAttributeSpecArray &spec, MSelectionList &list )
{
if( spec.length() == 1 )
{
MAttributeSpec attrSpec = spec[0];
MStatus s;
int dim = attrSpec.dimensions();
if ( (dim > 0) && attrSpec.name() == "f" )
{
int numElements = m_nameToGroupMap.size();
MAttributeIndex attrIndex = attrSpec[0];
if ( attrIndex.type() != MAttributeIndex::kInteger )
{
return MPxSurfaceShape::kMatchInvalidAttributeRange;
}
int upper = numElements - 1;
int lower = 0;
if ( attrIndex.hasLowerBound() )
{
attrIndex.getLower( lower );
}
if ( attrIndex.hasUpperBound() )
{
attrIndex.getUpper( upper );
}
// Check the attribute index range is valid
if ( (attrIndex.hasRange() && !attrIndex.hasValidRange() ) || (upper >= numElements) || (lower < 0 ) )
{
return MPxSurfaceShape::kMatchInvalidAttributeRange;
}
MDagPath path;
item.getDagPath( 0, path );
MFnSingleIndexedComponent fnComp;
MObject comp = fnComp.create( MFn::kMeshPolygonComponent, &s );
for ( int i=lower; i<=upper; i++ )
{
fnComp.addElement( i );
}
list.add( path, comp );
return MPxSurfaceShape::kMatchOk;
}
}
return MPxSurfaceShape::matchComponent( item, spec, list );
}
/// Blank implementation of this method. This is to avoid a crash when you try and use the rotation manipulator maya gives
/// you when you've selected procedural components in rotation mode (maya 2013)
void SceneShapeInterface::transformUsing( const MMatrix &mat, const MObjectArray &componentList, MPxSurfaceShape::MVertexCachingMode cachingMode, MPointArray *pointCache )
{
}
/// This method is overridden to supply a geometry iterator, which maya uses to work out
/// the bounding boxes of the components you've selected in the viewport
MPxGeometryIterator* SceneShapeInterface::geometryIteratorSetup( MObjectArray& componentList, MObject& components, bool forReadOnly )
{
if ( components.isNull() )
{
return new SceneShapeInterfaceComponentBoundIterator( this, componentList );
}
else
{
return new SceneShapeInterfaceComponentBoundIterator( this, components );
}
}
Imath::Box3d SceneShapeInterface::componentBound( int idx )
{
// get relative path name from index
IECore::InternedString name = selectionName( idx );
SceneInterface::Path path;
path = fullPathName( name.value() );
ConstSceneInterfacePtr scene = getSceneInterface()->scene( path, SceneInterface::NullIfMissing );
if( !scene )
{
msg( Msg::Warning, "SceneShapeInterface::componentBound", boost::format( "no scene for component %s" ) % name.value() );
return Imath::Box3d( Imath::V3d(-1), Imath::V3d(1) );
}
MPlug pTime( thisMObject(), aTime );
MTime time;
pTime.getValue( time );
// read bound from scene interface and return it in world space
Imath::Box3d componentBound = scene->readBound( time.as( MTime::kSeconds ) );
M44d transformd = worldTransform( scene, time.as( MTime::kSeconds ) );
componentBound = transform( componentBound, transformd );
return componentBound;
}
void SceneShapeInterface::buildScene( IECoreGL::RendererPtr renderer, ConstSceneInterfacePtr subSceneInterface )
{
// Grab plug values to know what we need to render
MPlug pTime( thisMObject(), aTime );
MTime time;
pTime.getValue( time );
MPlug pDrawBounds( thisMObject(), aDrawChildBounds );
bool drawBounds;
pDrawBounds.getValue( drawBounds );
MPlug pDrawGeometry( thisMObject(), aDrawGeometry );
bool drawGeometry;
pDrawGeometry.getValue( drawGeometry );
MPlug pObjectOnly( thisMObject(), aObjectOnly );
bool objectOnly;
pObjectOnly.getValue( objectOnly );
if( !drawGeometry && !drawBounds )
{
return;
}
MPlug pDrawTagsFilter( thisMObject(), aDrawTagsFilter );
MString drawTagsFilter;
pDrawTagsFilter.getValue( drawTagsFilter );
typedef boost::tokenizer<boost::char_separator<char> > Tokenizer;
std::string txt(drawTagsFilter.asChar());
Tokenizer tokens( txt, boost::char_separator<char>(" "));
Tokenizer::iterator t = tokens.begin();
SceneInterface::NameList drawTags;
for ( ; t != tokens.end(); t++ )
{
if ( t->size() )
{
/// test if the scene location has the tag to start with..
if ( subSceneInterface->hasTag( *t, SceneInterface::EveryTag ) )
{
drawTags.push_back( *t );
}
else
{
msg( Msg::Warning, name().asChar(), std::string("Tag '") + *t + "'does not exist in scene. Ignoring it for filtering.");
}
}
}
renderer->concatTransform( convert<M44f>( worldTransform( subSceneInterface, time.as( MTime::kSeconds ) ) ) );
recurseBuildScene( renderer.get(), subSceneInterface.get(), time.as( MTime::kSeconds ), drawBounds, drawGeometry, objectOnly, drawTags );
}
void SceneShapeInterface::recurseBuildScene( IECoreGL::Renderer * renderer, const SceneInterface *subSceneInterface, double time, bool drawBounds, bool drawGeometry, bool objectOnly, const SceneInterface::NameList &drawTags )
{
if ( drawTags.size() )
{
SceneInterface::NameList::const_iterator it;
for ( it = drawTags.begin(); it != drawTags.end(); it++ )
{
if ( subSceneInterface->hasTag( *it, SceneInterface::EveryTag ) )
{
break;
}
}
/// stop drawing if the current scene location does not have the required tags.
if ( it == drawTags.end() )
{
return;
}
}
if ( subSceneInterface->hasAttribute( "scene:visible" ) )
{
if( ConstBoolDataPtr vis = runTimeCast<const BoolData>( subSceneInterface->readAttribute( "scene:visible", time ) ) )
{
if( !vis->readable() )
{
return;
}
}
}
AttributeBlock a(renderer);
SceneInterface::Path pathName;
subSceneInterface->path( pathName );
std::string pathStr = relativePathName( pathName );
renderer->setAttribute( "name", new StringData( pathStr ) );
renderer->setAttribute( "gl:curvesPrimitive:useGLLines", new BoolData( true ) );
if(pathStr != "/")
{
// Path space
renderer->concatTransform( convert<M44f>( subSceneInterface->readTransformAsMatrix( time ) ) );
}
// Need to add this attribute block to get a parent group with that name that includes the object and/or bound
AttributeBlock aNew(renderer);
if ( subSceneInterface->hasAttribute( LinkedScene::fileNameLinkAttribute ) )
{
// we are at a link location... create a hash to uniquely identify it.
MurmurHash hash;
subSceneInterface->readAttribute( LinkedScene::fileNameLinkAttribute, time )->hash( hash );
subSceneInterface->readAttribute( LinkedScene::rootLinkAttribute, time )->hash( hash );
subSceneInterface->readAttribute( LinkedScene::timeLinkAttribute, time )->hash( hash );
/// register the hash mapped to the name of the group
InternedString pathInternedStr(pathStr);
std::pair< HashToName::iterator, bool > ret = m_hashToName.insert( HashToName::value_type( hash, pathInternedStr ) );
if ( !ret.second )
{
/// the same location was already rendered, so we store the current location for instanting later...
m_instances.push_back( InstanceInfo(pathInternedStr, ret.first->second) );
return;
}
}
if( drawGeometry && subSceneInterface->hasObject() )
{
ConstObjectPtr object = subSceneInterface->readObject( time );
if( runTimeCast< const CoordinateSystem >(object.get()) )
{
// manually draw coordinate systems so they don't override the gl name state:
AttributeBlock a(renderer);
renderer->setAttribute( "gl:curvesPrimitive:useGLLines", new IECore::BoolData( true ) );
renderer->setAttribute( "gl:curvesPrimitive:glLineWidth", new IECore::FloatData( 2 ) );
IECore::V3fVectorDataPtr p = new IECore::V3fVectorData;
p->writable().push_back( Imath::V3f( 0, 0, 0 ) );
p->writable().push_back( Imath::V3f( 1, 0, 0 ) );
p->writable().push_back( Imath::V3f( 0, 0, 0 ) );
p->writable().push_back( Imath::V3f( 0, 1, 0 ) );
p->writable().push_back( Imath::V3f( 0, 0, 0 ) );
p->writable().push_back( Imath::V3f( 0, 0, 1 ) );
IECore::IntVectorDataPtr inds = new IECore::IntVectorData;
inds->writable().resize( 3, 2 );
CurvesPrimitivePtr curves = new IECore::CurvesPrimitive( inds, IECore::CubicBasisf::linear(), false, p );
curves->render( renderer );
}
else if( const Renderable *o = runTimeCast< const Renderable >(object.get()) )
{
o->render(renderer);
}
}
if( drawBounds && pathStr != "/" )
{
Box3d b = subSceneInterface->readBound( time );
Box3f bbox( b.min, b.max );
if( !bbox.isEmpty() )
{
CurvesPrimitive::createBox( bbox )->render( renderer );
}
}
if( !objectOnly )
{
// We need the entire hierarchy, iterate through all the sceneInterface children
SceneInterface::NameList childNames;
subSceneInterface->childNames( childNames );
for ( SceneInterface::NameList::const_iterator it = childNames.begin(); it != childNames.end(); ++it )
{
ConstSceneInterfacePtr childScene = subSceneInterface->child( *it );
recurseBuildScene( renderer, childScene.get(), time, drawBounds, drawGeometry, objectOnly, drawTags );
}
}
}
void SceneShapeInterface::createInstances()
{
for ( InstanceArray::iterator it = m_instances.begin(); it != m_instances.end(); it++ )
{
const InternedString &instanceName = it->first;
const InternedString &instanceSourceName = it->second;
NameToGroupMap::const_iterator srcIt = m_nameToGroupMap.find( instanceSourceName );
assert ( srcIt != m_nameToGroupMap.end() );
const IECoreGL::Group *srcGroup = srcIt->second.second.get();
NameToGroupMap::iterator trgIt = m_nameToGroupMap.find( instanceName );
IECoreGL::Group *trgGroup = trgIt->second.second.get();
// copy the src group to the trg group (empty instance group)
recurseCopyGroup( srcGroup, trgGroup, instanceName.value() );
}
/// clear the maps we don't need them.
m_hashToName.clear();
m_instances.clear();
}
void SceneShapeInterface::recurseCopyGroup( const IECoreGL::Group *srcGroup, IECoreGL::Group *trgGroup, const std::string &namePrefix )
{
const IECoreGL::Group::ChildContainer &children = srcGroup->children();
for ( IECoreGL::Group::ChildContainer::const_iterator it = children.begin(); it != children.end(); ++it )
{
IECoreGL::Group *group = runTimeCast< IECoreGL::Group >( it->get() );
if ( group )
{
IECoreGL::GroupPtr newGroup = new IECoreGL::Group();
// copy state, including the name state component
IECoreGL::StatePtr newState = new IECoreGL::State( *group->getState() );
newGroup->setState( newState );
std::string newName;
const IECoreGL::NameStateComponent *nameState = newState->get< IECoreGL::NameStateComponent >();
/// now override the name state component
if ( nameState )
{
const std::string &srcName = nameState->name();
size_t found = srcName.rfind('/');
if (found!=std::string::npos)
{
// we take the current "directory" and prepend it with the namePrefix
newName = namePrefix;
newName.append( srcName, found, std::string::npos );
newState->add( new IECoreGL::NameStateComponent( newName ) );
// we also need to register the group in the selection maps...
registerGroup( newName, newGroup );
}
}
newGroup->setTransform( group->getTransform() );
recurseCopyGroup( group, newGroup.get(), newName.size() ? newName.c_str() : namePrefix );
trgGroup->addChild( newGroup );
}
else
{
trgGroup->addChild( *it );
}
}
}
IECoreGL::ConstScenePtr SceneShapeInterface::glScene()
{
if(!m_previewSceneDirty)
{
return m_scene;
}
ConstSceneInterfacePtr sceneInterface = getSceneInterface();
if( sceneInterface )
{
SceneInterface::NameList childNames;
sceneInterface->childNames( childNames );
IECoreGL::RendererPtr renderer = new IECoreGL::Renderer();
renderer->setOption( "gl:mode", new StringData( "deferred" ) );
renderer->worldBegin();
{
buildScene( renderer, sceneInterface );
}
renderer->worldEnd();
m_scene = renderer->scene();
m_scene->setCamera( 0 );
}
// Update component name to group map
m_nameToGroupMap.clear();
m_indexToNameMap.clear();
IECoreGL::ConstStatePtr defaultState = IECoreGL::State::defaultState();
buildGroups( defaultState->get<const IECoreGL::NameStateComponent>(), m_scene->root() );
createInstances();
m_previewSceneDirty = false;
return m_scene;
}
void SceneShapeInterface::registerGroup( const std::string &name, IECoreGL::GroupPtr &group )
{
int index = m_nameToGroupMap.size();
std::pair< NameToGroupMap::iterator, bool> ret;
ret = m_nameToGroupMap.insert( std::pair< InternedString, NameToGroupMap::mapped_type > (name, NameToGroupMap::mapped_type( index, group )) );
if( ret.second )
{
m_indexToNameMap.push_back( name );
}
}
void SceneShapeInterface::buildGroups( IECoreGL::ConstNameStateComponentPtr nameState, IECoreGL::GroupPtr group )
{
assert( nameState );
assert( group );
assert( group->getState() );
if ( group->getState()->get< IECoreGL::NameStateComponent >() )
{
nameState = group->getState()->get< IECoreGL::NameStateComponent >();
}
const std::string &name = nameState->name();
if( name != "unnamed" )
{
registerGroup( name, group );
}
const IECoreGL::Group::ChildContainer &children = group->children();
for ( IECoreGL::Group::ChildContainer::const_iterator it = children.begin(); it != children.end(); ++it )
{
assert( *it );
group = runTimeCast< IECoreGL::Group >( *it );
if ( group )
{
buildGroups( nameState, group );
}
}
}
void SceneShapeInterface::setDirty()
{
m_previewSceneDirty = true;
}
IECoreGL::GroupPtr SceneShapeInterface::glGroup( const IECore::InternedString &name )
{
NameToGroupMap::const_iterator elementIt = m_nameToGroupMap.find( name );
if( elementIt != m_nameToGroupMap.end() )
{
return elementIt->second.second;
}
else
{
return 0;
}
}
int SceneShapeInterface::selectionIndex( const IECore::InternedString &name )
{
NameToGroupMap::const_iterator elementIt = m_nameToGroupMap.find( name );
if( elementIt != m_nameToGroupMap.end() )
{
return elementIt->second.first;
}
else
{
return -1;
}
}
IECore::InternedString SceneShapeInterface::selectionName( int index )
{
// make sure the gl scene's been built, as this keeps m_indexToNameMap up to date
const_cast<SceneShapeInterface*>( this )->glScene();
return m_indexToNameMap[index];
}
const std::vector< InternedString > & SceneShapeInterface::componentNames() const
{
// make sure the gl scene's been built, as this keeps m_indexToNameMap up to date
const_cast<SceneShapeInterface*>( this )->glScene();
return m_indexToNameMap;
}
std::string SceneShapeInterface::relativePathName( SceneInterface::Path path )
{
SceneInterface::Path root;
getSceneInterface()->path( root );
assert( root.size() <= path.size() );
if( root == path )
{
return "/";
}
std::string pathName;
SceneInterface::Path::const_iterator it = path.begin();
it += root.size();
for ( ; it != path.end(); it++ )
{
pathName += '/';
pathName += it->value();
}
return pathName;
}
SceneInterface::Path SceneShapeInterface::fullPathName( std::string relativeName )
{
SceneInterface::Path root;
getSceneInterface()->path( root );
SceneInterface::Path relativePath;
SceneInterface::stringToPath( relativeName, relativePath );
SceneInterface::Path fullPath( root );
fullPath.insert( fullPath.end(), relativePath.begin(), relativePath.end() );
return fullPath;
}
bool SceneShapeInterface::readConvertParam( CompoundParameterPtr parameters, int attrIndex ) const
{
IECorePython::ScopedGILLock gilLock;
boost::python::list parserArgList;
{
MPlug pConvertParamQueries( thisMObject(), aConvertParamQueries );
MPlug pConvertParamQuery = pConvertParamQueries.elementByLogicalIndex( attrIndex );
MString paramsStr;
pConvertParamQuery.getValue( paramsStr );
const std::string pstr = paramsStr.asChar();
boost::tokenizer<boost::char_separator<char> > t( pstr, boost::char_separator<char>( " " ) );
boost::tokenizer<boost::char_separator<char> >::const_iterator it, endIt;
for ( it = t.begin(), endIt = t.end(); it != endIt; ++it )
{
parserArgList.append( *it );
}
}
try
{
boost::python::import( "IECore" ).attr( "ParameterParser" )().attr( "parse" )( parserArgList, parameters );
}
catch( const std::exception& e )
{
MFnDagNode dag( thisMObject() );
msg( Msg::Error, dag.fullPathName().asChar(), boost::format( "Convert parameter parse error %s. %d" ) % e.what() % attrIndex );
return false;
}
return true;
}
bool SceneShapeInterface::animatedScene()
{
ConstSampledSceneInterfacePtr scene = runTimeCast< const SampledSceneInterface >( getSceneInterface() );
return ( !scene || scene->numBoundSamples() > 1 );
}
| hradec/cortex | src/IECoreMaya/SceneShapeInterface.cpp | C++ | bsd-3-clause | 49,682 |
'use strict';
angular.module('authApp')
.controller('LogoutCtrl', function ($scope, $location, djangoAuth) {
djangoAuth.logout();
});
| LABETE/TestYourProject | staticfiles/js/controllers/logout.js | JavaScript | bsd-3-clause | 143 |
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\helpers\ArrayHelper;
use kartik\select2\Select2;
$this->title = 'Lembrete';
?>
<div class="login-box ">
<div class="login-logo">
<a href="../../index2.html"><i><b>Consultorio</b></i> <b>Médico</b></a>
</div>
<!-- /.login-logo -->
<div class="login-box-body">
<p class="login-box-msg"><b>Senha do Usuario <br> Informe os Dados para Envio de Senha:</b></p>
<?php $form = ActiveForm::begin([
'id' => 'lembrete-form',
'enableClientValidation' => false,
'options' => ['validateOnSubmit' => false,'class' => 'form-horizontal'],
]); ?>
<div class="col-xs-12">
<div class="row">
<?= $form->field($model, 'username',
[
'inputOptions' => [
'placeholder' => $model->getAttributeLabel('username'),
],
'options' => [
'tag' => 'div',
'class' => 'form-group has-feedback'
],
'template' => '{input} <span class="glyphicon glyphicon-user form-control-feedback"></span><div class="col-lg-10">{error}</div>',
])->textInput() ?>
<?= $form->field($model, 'email')->textInput(['maxlength' => true, 'placeholder' => 'email@email.com'])->label(false) ?>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<?php echo Html::submitButton('Enviar Senha', ['class' => 'btn btn-primary btn-block btn-flat', 'name' => 'login-button']) ?>
<?php echo Html::button('Voltar Login', ['onclick'=>'cancelar()','class' => 'btn btn-danger btn-block btn-flat', 'name' => 'cancelar-button']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</div> <!-- /.login-box-body -->
</div> <!-- /.login-box -->
<?php
$script = <<< JS
loading.turn.off('.loading-fog-login','.cssload-loader');
function mostrar_campo(valor) {
if (valor == 3) {
bb = '#dv_cpf';
$(bb).hide();
bb = '#dv_inscricao';
$(bb).hide();
bb = '#dv_cnpj';
$(bb).show();
}
if (valor == 2) {
bb = '#dv_cnpj';
$(bb).hide();
bb = '#dv_inscricao';
$(bb).hide();
bb = '#dv_cpf';
$(bb).show();
}
if (valor == 1) {
bb = '#dv_cpf';
$(bb).hide();
bb = '#dv_cnpj';
$(bb).hide();
bb = '#dv_inscricao';
$(bb).show();
}
}
function cancelar() {
var url = BASE_PATH + "site/login";
location.href = url;
}
JS;
if($model->hasErrors() )
{
$this->registerJs($script,\yii\web\View::POS_END);
}
$this->registerJs($script,\yii\web\View::POS_END);
?> | paulorobto11/consultorioWeb | modules/auth/views/auth-user/lembrete.php | PHP | bsd-3-clause | 2,659 |
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class StaticgenAppConfig(AppConfig):
name = 'staticgen'
verbose_name = _('StaticGen')
| mishbahr/django-staticgen | staticgen/apps.py | Python | bsd-3-clause | 186 |
// This file was generated by silverstripe/cow from javascript/lang/src/fi.js.
// See https://github.com/tractorcow/cow for details
if(typeof(ss) == 'undefined' || typeof(ss.i18n) == 'undefined') {
if(typeof(console) != 'undefined') console.error('Class ss.i18n not defined');
} else {
ss.i18n.addDictionary('fi', {
"Workflow.DeleteQuestion": "Are you sure you want to permanently delete this?",
"Workflow.EMBARGOMESSAGETIME": "Saved drafts of this page will auto publish today at <a>%s</a>",
"Workflow.EMBARGOMESSAGEDATE": "Saved drafts of this page will auto publish on <a>%s</a>",
"Workflow.EMBARGOMESSAGEDATETIME": "Saved drafts of this page will auto publish on <a>%s at %s</a>",
"Workflow.ProcessError": "Could not process workflow"
});
} | icecaster/advancedworkflow | javascript/lang/fi.js | JavaScript | bsd-3-clause | 766 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# polyencoder
# Copyright 2015 Neil Freeman contact@fakeisthenewreal.org
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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.
from __future__ import print_function
import sys
import csv
from urllib import quote_plus
import fiona
from .polyencoder import polyencode
def getproperties(feature, keys):
'''Return a list of properties from feature'''
return [feature['properties'].get(k) for k in keys]
def encodelayer(infile, keys, encode=None, delimiter=None):
keys = keys.split(',')
writer = csv.writer(sys.stdout, delimiter=delimiter or '\t')
with fiona.drivers():
with fiona.open(infile, 'r') as layer:
for feature in layer:
if feature['geometry']['type'] == 'MultiPolygon':
# list of list of lists of tuples
coords = feature['geometry']['coordinates'][0][0]
elif feature['geometry']['type'] == 'Polygon' or feature['geometry']['type'] == 'MultiLineString':
# list of lists of tuples
coords = feature['geometry']['coordinates'][0]
elif feature['geometry']['type'] == 'Linestring':
# list of tuples
coords = feature['geometry']['coordinates']
else:
raise NotImplementedError(
"Polyencode not available for geometry type: {}".format(feature['geometry']['type']))
try:
encoded = polyencode(coords)
except TypeError:
print("Unexpected issue with {}".format(feature['properties'].get(keys[0])), file=sys.stderr)
raise
if encode:
encoded = quote_plus(encoded)
props = getproperties(feature, keys) + [encoded]
writer.writerow(props)
| fitnr/polyencoder | polyencoder/polyencode_layer.py | Python | bsd-3-clause | 3,370 |
import { findOrCreateWorkspace, findOrCreateWorkspaceCard, signInWithAccessToken } from 'utils/test-utils';
import { MenuOption } from 'app/text-labels';
import WorkspaceDataPage from 'app/page/workspace-data-page';
import Navigation, { NavLink } from 'app/component/navigation';
import WorkspaceCard from 'app/component/card/workspace-card';
import WorkspaceEditPage from 'app/page/workspace-edit-page';
import WorkspacesPage from 'app/page/workspaces-page';
import { config } from 'resources/workbench-config';
import OldCdrVersionModal from 'app/modal/old-cdr-version-modal';
describe('Duplicate workspace', () => {
beforeEach(async () => {
await signInWithAccessToken(page);
});
const workspaceName = 'e2eCloneWorkspaceTest';
/**
* Test:
* - Find an existing workspace. Create a new workspace if none exists.
* - Select "Duplicate" thru the Ellipsis menu located inside the Workspace card.
* - Enter a new workspace name and save the duplicate.
* - Delete duplicate workspace.
*/
test('Duplicate workspace', async () => {
await findOrCreateWorkspace(page, { workspaceName });
// Access Workspace Duplicate page via Workspace action menu.
const dataPage = new WorkspaceDataPage(page);
await dataPage.selectWorkspaceAction(MenuOption.Duplicate);
// Fill out Workspace Name should be just enough for successful duplication
const workspaceEditPage = new WorkspaceEditPage(page);
await workspaceEditPage.getWorkspaceNameTextbox().clear();
const duplicateWorkspaceName = await workspaceEditPage.fillOutWorkspaceName();
// observe that we cannot change the Data Access Tier.
const accessTierSelect = workspaceEditPage.getDataAccessTierSelect();
expect(await accessTierSelect.isDisabled()).toEqual(true);
const finishButton = workspaceEditPage.getDuplicateWorkspaceButton();
await workspaceEditPage.requestForReviewRadiobutton(false);
await finishButton.waitUntilEnabled();
await workspaceEditPage.clickCreateFinishButton(finishButton);
// Duplicate workspace Data page is loaded.
await dataPage.waitForLoad();
expect(page.url()).toContain(duplicateWorkspaceName.replace(/-/g, '')); // Remove dash from workspace name
// Delete duplicate workspace via Workspace card in Your Workspaces page.
await Navigation.navMenu(page, NavLink.YOUR_WORKSPACES);
const workspacesPage = new WorkspacesPage(page);
await workspacesPage.waitForLoad();
await new WorkspaceCard(page).delete({ name: duplicateWorkspaceName });
});
test('Cannot duplicate workspace with older CDR version without consent to restrictions', async () => {
const workspaceCard = await findOrCreateWorkspaceCard(page, { workspaceName });
await (await workspaceCard.asElement()).hover();
await workspaceCard.selectSnowmanMenu(MenuOption.Duplicate, { waitForNav: true });
const workspaceEditPage = new WorkspaceEditPage(page);
// Fill out the fields required for duplication and observe that duplication is enabled
const duplicateWorkspaceName = await workspaceEditPage.fillOutRequiredDuplicationFields();
const duplicateButton = workspaceEditPage.getDuplicateWorkspaceButton();
await duplicateButton.waitUntilEnabled();
// Change CDR version to an old CDR version.
await workspaceEditPage.selectCdrVersion(config.OLD_CDR_VERSION_NAME);
expect(await duplicateButton.isCursorNotAllowed()).toBe(true);
const modal = new OldCdrVersionModal(page);
const cancelButton = modal.getCancelButton();
await cancelButton.click();
// The CDR version is forcibly reverted back to the default
const cdrVersionSelect = workspaceEditPage.getCdrVersionSelect();
expect(await cdrVersionSelect.getSelectedValue()).toBe(config.DEFAULT_CDR_VERSION_NAME);
// Try again. This time consent to restriction.
// Duplicate workspace with an older CDR Version can proceed after consenting to restrictions.
await workspaceEditPage.selectCdrVersion(config.OLD_CDR_VERSION_NAME);
await modal.consentToOldCdrRestrictions();
// Finish creation of workspace.
await workspaceEditPage.requestForReviewRadiobutton(false);
await duplicateButton.waitUntilEnabled();
await workspaceEditPage.clickCreateFinishButton(duplicateButton);
// Duplicate workspace Data page is loaded.
const dataPage = new WorkspaceDataPage(page);
await dataPage.waitForLoad();
expect(page.url()).toContain(`/${duplicateWorkspaceName.toLowerCase()}/data`);
// Delete duplicate workspace via Workspace card in Your Workspaces page.
await Navigation.navMenu(page, NavLink.YOUR_WORKSPACES);
const workspacesPage = new WorkspacesPage(page);
await workspacesPage.waitForLoad();
await new WorkspaceCard(page).delete({ name: duplicateWorkspaceName });
});
});
| all-of-us/workbench | e2e/tests/workspace/workspace-duplicate.spec.ts | TypeScript | bsd-3-clause | 4,823 |
<?php
class CategoryController extends AdminController {
public function actionSave() {
if (Yii::app()->getRequest()->getIsPostRequest()) {
$category = Yii::app()->getRequest()->getPost('Category', array());
if(Yii::app()->session['id']) {
$model = $this->loadModel(Yii::app()->session['id'], 'Category');
} else {
$model = new Category();
//pushing newly added item to last
$maxRight = $model->getMaxRight();
$model->lft = $maxRight + 1;
$model->rgt = $maxRight + 2;
}
$model->setAttributes($_POST['Category']);
if (isset($_POST['Category']['parent_id']) && $_POST['Category']['parent_id'] > 0) {
$modelCategory = $this->loadModel($_POST['Category']['parent_id'], 'Category');
$model->level = $modelCategory->level + 1;
$model->lft = $modelCategory->rgt + 1;
$model->rgt = $modelCategory->rgt + 2;
} else {
$model->level = 1;
}
$model->image = str_replace(Yii::getPathOfAlias('webroot'), '', $model->image);
if ($model->save()) {
Yii::app()->user->setFlash('success', $this->t('Save successfull.'));
} else {
Yii::app()->user->setFlash('success', $this->t('Save can\'t successfull.'));
}
}
unset(Yii::app()->session['id']);
$this->redirect(array('index'));
}
public function actionEdit($id = 0) {
if ($id || Yii::app()->getRequest()->getIsPostRequest()) {
$cid = Yii::app()->getRequest()->getPost('cid', array());
if(count($cid)) {
$id = $cid[0];
}
if($id){
$model = $this->loadModel($id, 'Category');
Yii::app()->session['id'] = $id;
} else {
$model = new Category();
Yii::app()->session['id'] = 0;
}
$this->render('edit', array(
'model' => $model,
));
} else {
Yii::app()->user->setFlash('warning', $this->t('Access denied.'));
$this->redirect(array('index'));
}
}
public function actionNew() {
$model = new Category();
Yii::app()->session['id'] = 0;
$this->render('edit', array(
'model' => $model,
));
}
public function actionDelete() {
if (Yii::app()->getRequest()->getIsPostRequest()) {
$cid = Yii::app()->getRequest()->getPost('cid', array());
$model = new Category();
$model->deleteAll('id IN ('. implode($cid, ',') .')');
Yii::app()->user->setFlash('success', 'Delete successfull.');
} else {
Yii::app()->user->setFlash('error', 'Please select at least one record to delete.');
}
$this->redirect(array('index'));
}
public function actionIndex() {
$viewDefault = 'index';
if($this->pageAjax) {
$viewDefault = 'model_'.$viewDefault;
}
$model = new Category('search');
$model->unsetAttributes();
$this->setPageTitle(yii::t('app', 'Category Manager'));
if (isset($_GET['Category']))
$model->setAttributes($_GET['Category']);
$this->render($viewDefault, array(
'model' => $model,
'function' => $this->function,
'pageAjax' => $this->pageAjax,
));
}
public function actionToggle($id, $attribute, $model) {
if (Yii::app()->request->isPostRequest) {
// we only allow deletion via POST request
$model = $this->loadModel($id, $model);
//loadModel($id, $model) from giix
($model->$attribute == 1) ? $model->$attribute = 0 : $model->$attribute = 1;
$model->save();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if (!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('/index'));
}
return false;
}
} | hieutrieu/hiva1 | protected/modules/admin/controllers/CategoryController.php | PHP | bsd-3-clause | 3,692 |
<?php
return [
'id' =>'ID',
'en_name' =>'En Name',
'iso639_1' =>'Iso639 1',
'native_name' =>'Native Name',
'native_name_short' =>'Native Name Short',
'created_at' =>'Created At',
'updated_at' =>'Updated At',
];
| Winkelor/yii2store | common/messages/en-US/languages.php | PHP | bsd-3-clause | 240 |
/*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "core/html/HTMLProgressElement.h"
#include "bindings/core/v8/ExceptionMessages.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ExceptionStatePlaceholder.h"
#include "core/HTMLNames.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/frame/UseCounter.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/html/shadow/ProgressShadowElement.h"
#include "core/layout/LayoutProgress.h"
namespace blink {
using namespace HTMLNames;
const double HTMLProgressElement::IndeterminatePosition = -1;
const double HTMLProgressElement::InvalidPosition = -2;
HTMLProgressElement::HTMLProgressElement(Document& document)
: LabelableElement(progressTag, document)
, m_value(nullptr)
{
UseCounter::count(document, UseCounter::ProgressElement);
}
HTMLProgressElement::~HTMLProgressElement()
{
}
PassRefPtrWillBeRawPtr<HTMLProgressElement> HTMLProgressElement::create(Document& document)
{
RefPtrWillBeRawPtr<HTMLProgressElement> progress = adoptRefWillBeNoop(new HTMLProgressElement(document));
progress->ensureUserAgentShadowRoot();
return progress.release();
}
LayoutObject* HTMLProgressElement::createLayoutObject(const ComputedStyle& style)
{
if (!style.hasAppearance() || openShadowRoot())
return LayoutObject::createObject(this, style);
return new LayoutProgress(this);
}
LayoutProgress* HTMLProgressElement::layoutProgress() const
{
if (layoutObject() && layoutObject()->isProgress())
return toLayoutProgress(layoutObject());
LayoutObject* layoutObject = userAgentShadowRoot()->firstChild()->layoutObject();
ASSERT_WITH_SECURITY_IMPLICATION(!layoutObject || layoutObject->isProgress());
return toLayoutProgress(layoutObject);
}
void HTMLProgressElement::parseAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& value)
{
if (name == valueAttr)
didElementStateChange();
else if (name == maxAttr)
didElementStateChange();
else
LabelableElement::parseAttribute(name, oldValue, value);
}
void HTMLProgressElement::attach(const AttachContext& context)
{
LabelableElement::attach(context);
if (LayoutProgress* layoutObject = layoutProgress())
layoutObject->updateFromElement();
}
double HTMLProgressElement::value() const
{
double value = getFloatingPointAttribute(valueAttr);
// Otherwise, if the parsed value was greater than or equal to the maximum
// value, then the current value of the progress bar is the maximum value
// of the progress bar. Otherwise, if parsing the value attribute's value
// resulted in an error, or a number less than or equal to zero, then the
// current value of the progress bar is zero.
return !std::isfinite(value) || value < 0 ? 0 : std::min(value, max());
}
void HTMLProgressElement::setValue(double value)
{
setFloatingPointAttribute(valueAttr, std::max(value, 0.));
}
double HTMLProgressElement::max() const
{
double max = getFloatingPointAttribute(maxAttr);
// Otherwise, if the element has no max attribute, or if it has one but
// parsing it resulted in an error, or if the parsed value was less than or
// equal to zero, then the maximum value of the progress bar is 1.0.
return !std::isfinite(max) || max <= 0 ? 1 : max;
}
void HTMLProgressElement::setMax(double max)
{
// FIXME: The specification says we should ignore the input value if it is inferior or equal to 0.
setFloatingPointAttribute(maxAttr, max > 0 ? max : 1);
}
double HTMLProgressElement::position() const
{
if (!isDeterminate())
return HTMLProgressElement::IndeterminatePosition;
return value() / max();
}
bool HTMLProgressElement::isDeterminate() const
{
return fastHasAttribute(valueAttr);
}
void HTMLProgressElement::didElementStateChange()
{
m_value->setWidthPercentage(position() * 100);
if (LayoutProgress* layoutObject = layoutProgress()) {
bool wasDeterminate = layoutObject->isDeterminate();
layoutObject->updateFromElement();
if (wasDeterminate != isDeterminate())
pseudoStateChanged(CSSSelector::PseudoIndeterminate);
}
}
void HTMLProgressElement::didAddUserAgentShadowRoot(ShadowRoot& root)
{
ASSERT(!m_value);
RefPtrWillBeRawPtr<ProgressInnerElement> inner = ProgressInnerElement::create(document());
inner->setShadowPseudoId(AtomicString("-webkit-progress-inner-element", AtomicString::ConstructFromLiteral));
root.appendChild(inner);
RefPtrWillBeRawPtr<ProgressBarElement> bar = ProgressBarElement::create(document());
bar->setShadowPseudoId(AtomicString("-webkit-progress-bar", AtomicString::ConstructFromLiteral));
RefPtrWillBeRawPtr<ProgressValueElement> value = ProgressValueElement::create(document());
m_value = value.get();
m_value->setShadowPseudoId(AtomicString("-webkit-progress-value", AtomicString::ConstructFromLiteral));
m_value->setWidthPercentage(HTMLProgressElement::IndeterminatePosition * 100);
bar->appendChild(m_value);
inner->appendChild(bar);
}
bool HTMLProgressElement::shouldAppearIndeterminate() const
{
return !isDeterminate();
}
void HTMLProgressElement::willAddFirstAuthorShadowRoot()
{
ASSERT(RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled());
lazyReattachIfAttached();
}
DEFINE_TRACE(HTMLProgressElement)
{
visitor->trace(m_value);
LabelableElement::trace(visitor);
}
} // namespace
| Workday/OpenFrame | third_party/WebKit/Source/core/html/HTMLProgressElement.cpp | C++ | bsd-3-clause | 6,371 |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information -----------------------------------------------------
project = 'ostap'
copyright = '2019, Ostap developers'
author = 'Ostap developers'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'breathe' ,
'sphinx.ext.autodoc' ,
'sphinx.ext.mathjax' ,
]
breathe_default_project = 'ostap'
breathe_domain_by_extension = {
"h" : "cpp" ,
"C" : "cpp" ,
"py" : "python" ,
}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
## html_theme = 'sphinx_rtd_theme'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
| OstapHEP/ostap | docs/conf.py | Python | bsd-3-clause | 2,147 |
"use strict";
const debug = require('debug')('ipc-stream');
const EventEmitter = require('events');
class IPCStream extends EventEmitter {
// otherWindowId is the id of the window
// channelId is the id of the service you want to communicate wth
// running in that other window
constructor(closeFn, remote, localStreamId, channelId) {
super();
this._closeFn = closeFn; // so we can close
this._remote = remote;
this._localStreamId = localStreamId;
this._remoteStreamId;
this._channelId = channelId; // this is for debugging only
}
// DO NOT CALL this (it is called by IPChannel
setRemoteStreamId(remoteStreamId) {
debug("setRemoteStream:", remoteStreamId);
if (this._remoteStreamId) {
throw new Error("remoteStreamId already set");
}
this._remoteStreamId = remoteStreamId;
}
send(...args) {
if (!this._remoteStreamId) {
throw new Error("remoteStreamId not set");
}
this._remote.send('relay', this._remoteStreamId, ...args);
}
// do not call this directly
disconnect() {
debug("disconnect stream:", this._remoteStreamId, this._channelId);
this.emit('disconnect');
this._remoteStreamId = null;
}
close() {
debug("close:", this._localStreamId, this._channelId);
if (this._remoteStreamId) {
this._closeFn();
this._remote.send('disconnect', this._remoteStreamId);
this._remoteStreamId = null;
}
}
}
module.exports = IPCStream;
| greggman/other-window-ipc | lib/ipc-stream.js | JavaScript | bsd-3-clause | 1,463 |
<?php
/*=========================================================================
Program: CDash - Cross-Platform Dashboard System
Module: $Id: buildupdatefile.php 3179 2012-02-13 08:59:24Z jjomier $
Language: PHP
Date: $Date: 2012-02-13 08:59:24 +0000 (Mon, 13 Feb 2012) $
Version: $Revision: 3179 $
Copyright (c) 2002 Kitware, Inc. All rights reserved.
See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// It is assumed that appropriate headers should be included before including this file
class BuildUpdateFile
{
var $Filename;
var $CheckinDate;
var $Author;
var $Email;
var $Committer;
var $CommitterEmail;
var $Log;
var $Revision;
var $PriorRevision;
var $Status; //MODIFIED | CONFLICTING | UPDATED
var $UpdateId;
// Insert the update
function Insert()
{
if(strlen($this->UpdateId)==0)
{
echo "BuildUpdateFile:Insert UpdateId not set";
return false;
}
$this->Filename = pdo_real_escape_string($this->Filename);
// Sometimes the checkin date is not found in that case we put the usual date
if($this->CheckinDate == "Unknown")
{
$this->CheckinDate = "1980-01-01";
}
if(strtotime($this->CheckinDate) === false && is_numeric($this->CheckinDate))
{
$this->CheckinDate = date(FMT_DATETIME,$this->CheckinDate);
}
else if(strtotime($this->CheckinDate) !== false)
{
$this->CheckinDate = date(FMT_DATETIME,strtotime($this->CheckinDate));
}
else
{
$this->CheckinDate = "1980-01-01";
}
$this->Author = pdo_real_escape_string($this->Author);
$this->UpdateId = pdo_real_escape_string($this->UpdateId);
// Check if we have a robot file for this build
$robot = pdo_query("SELECT authorregex FROM projectrobot,build,build2update
WHERE projectrobot.projectid=build.projectid
AND build2update.buildid=build.id
AND build2update.updateid=".qnum($this->UpdateId)." AND robotname='".$this->Author."'");
if(pdo_num_rows($robot)>0)
{
$robot_array = pdo_fetch_array($robot);
$regex = $robot_array['authorregex'];
preg_match($regex,$this->Log,$matches);
if(isset($matches[1]))
{
$this->Author = $matches[1];
}
}
$this->Email = pdo_real_escape_string($this->Email);
$this->Committer = pdo_real_escape_string($this->Committer);
$this->CommitterEmail = pdo_real_escape_string($this->CommitterEmail);
$this->Log = pdo_real_escape_string($this->Log);
$this->Revision = pdo_real_escape_string($this->Revision);
$this->PriorRevision = pdo_real_escape_string($this->PriorRevision);
$query = "INSERT INTO updatefile (updateid,filename,checkindate,author,email,log,revision,priorrevision,status,committer,committeremail)
VALUES (".qnum($this->UpdateId).",'$this->Filename','$this->CheckinDate','$this->Author','$this->Email',
'$this->Log','$this->Revision','$this->PriorRevision','$this->Status','$this->Committer','$this->CommitterEmail')";
if(!pdo_query($query))
{
add_last_sql_error("BuildUpdateFile Insert",0,$this->UpdateId);
return false;
}
} // end function insert
}
?>
| zackgalbreath/CDash | models/buildupdatefile.php | PHP | bsd-3-clause | 3,579 |
// 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 "config.h"
#include "core/inspector/AsyncCallChain.h"
#include "wtf/text/WTFString.h"
namespace blink {
AsyncCallStack::AsyncCallStack(const String& description, v8::Local<v8::Object> callFrames)
: m_description(description)
, m_callFrames(callFrames->GetIsolate(), callFrames)
{
}
AsyncCallStack::~AsyncCallStack()
{
}
PassRefPtr<AsyncCallChain> AsyncCallChain::create(PassRefPtr<AsyncCallStack> stack, AsyncCallChain* prevChain, unsigned asyncCallChainMaxLength)
{
return adoptRef(new AsyncCallChain(stack, prevChain, asyncCallChainMaxLength));
}
AsyncCallChain::AsyncCallChain(PassRefPtr<AsyncCallStack> stack, AsyncCallChain* prevChain, unsigned asyncCallChainMaxLength)
{
if (stack)
m_callStacks.append(stack);
if (prevChain) {
const AsyncCallStackVector& other = prevChain->m_callStacks;
for (size_t i = 0; i < other.size() && m_callStacks.size() < asyncCallChainMaxLength; i++)
m_callStacks.append(other[i]);
}
}
AsyncCallChain::~AsyncCallChain()
{
}
} // namespace blink
| Bysmyyr/chromium-crosswalk | third_party/WebKit/Source/core/inspector/AsyncCallChain.cpp | C++ | bsd-3-clause | 1,222 |
import base64
import os
import tempfile
import zipfile
from cumulusci.core.utils import process_bool_arg
from cumulusci.salesforce_api.metadata import ApiDeploy
from cumulusci.tasks.salesforce import BaseSalesforceMetadataApiTask
from cumulusci.utils import zip_clean_metaxml
from cumulusci.utils import zip_inject_namespace
from cumulusci.utils import zip_strip_namespace
from cumulusci.utils import zip_tokenize_namespace
class Deploy(BaseSalesforceMetadataApiTask):
api_class = ApiDeploy
task_options = {
'path': {
'description': 'The path to the metadata source to be deployed',
'required': True,
},
'unmanaged': {
'description': "If True, changes namespace_inject to replace tokens with a blank string",
},
'namespace_inject': {
'description': "If set, the namespace tokens in files and filenames are replaced with the namespace's prefix",
},
'namespace_strip': {
'description': "If set, all namespace prefixes for the namespace specified are stripped from files and filenames",
},
'namespace_tokenize': {
'description': "If set, all namespace prefixes for the namespace specified are replaced with tokens for use with namespace_inject",
},
'namespaced_org': {
'description': "If True, the tokens %%%NAMESPACED_ORG%%% and ___NAMESPACED_ORG___ will get replaced with the namespace. The default is false causing those tokens to get stripped and replaced with an empty string. Set this if deploying to a namespaced scratch org or packaging org.",
},
'clean_meta_xml': {
'description': "Defaults to True which strips the <packageVersions/> element from all meta.xml files. The packageVersion element gets added automatically by the target org and is set to whatever version is installed in the org. To disable this, set this option to False",
},
}
def _get_api(self, path=None):
if not path:
path = self.task_config.options__path
# Build the zip file
zip_file = tempfile.TemporaryFile()
zipf = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED)
pwd = os.getcwd()
os.chdir(path)
for root, dirs, files in os.walk('.'):
for f in files:
self._write_zip_file(zipf, root, f)
zipf.close()
zipf_processed = self._process_zip_file(zipfile.ZipFile(zip_file))
zipf_processed.fp.seek(0)
package_zip = base64.b64encode(zipf_processed.fp.read())
os.chdir(pwd)
return self.api_class(self, package_zip, purge_on_delete=False)
def _process_zip_file(self, zipf):
zipf = self._process_namespace(zipf)
zipf = self._process_meta_xml(zipf)
return zipf
def _process_namespace(self, zipf):
if self.options.get('namespace_tokenize'):
self.logger.info(
'Tokenizing namespace prefix {}__'.format(
self.options['namespace_tokenize'],
)
)
zipf = zip_tokenize_namespace(zipf, self.options['namespace_tokenize'], logger=self.logger)
if self.options.get('namespace_inject'):
kwargs = {}
kwargs['managed'] = not process_bool_arg(self.options.get('unmanaged', True))
kwargs['namespaced_org'] = process_bool_arg(self.options.get('namespaced_org', False))
kwargs['logger'] = self.logger
if kwargs['managed']:
self.logger.info(
'Replacing namespace tokens from metadata with namespace prefix {}__'.format(
self.options['namespace_inject'],
)
)
else:
self.logger.info(
'Stripping namespace tokens from metadata for unmanaged deployment'
)
zipf = zip_inject_namespace(zipf, self.options['namespace_inject'], **kwargs)
if self.options.get('namespace_strip'):
zipf = zip_strip_namespace(zipf, self.options['namespace_strip'], logger=self.logger)
return zipf
def _process_meta_xml(self, zipf):
if not process_bool_arg(self.options.get('clean_meta_xml', True)):
return zipf
self.logger.info(
'Cleaning meta.xml files of packageVersion elements for deploy'
)
zipf = zip_clean_metaxml(zipf, logger=self.logger)
return zipf
def _write_zip_file(self, zipf, root, path):
zipf.write(os.path.join(root, path))
| e02d96ec16/CumulusCI | cumulusci/tasks/salesforce/Deploy.py | Python | bsd-3-clause | 4,641 |
<?php
use kartik\helpers\Html;
use yii\widgets\DetailView;
use kartik\grid\GridView;
use yii\helpers\Url;
use yii\widgets\Pjax;
use yii\bootstrap\Modal;
use yii\bootstrap\ActiveForm;
use kartik\tabs\TabsX;
use yii\helpers\Json;
use yii\web\Response;
use yii\helpers\ArrayHelper;
use yii\web\Request;
use kartik\daterange\DateRangePicker;
use yii\db\ActiveRecord;
use yii\data\ArrayDataProvider;
use lukisongroup\master\models\Customers;
use lukisongroup\master\models\Termcustomers;
use lukisongroup\master\models\Distributor;
use lukisongroup\hrd\models\Corp;
$this->sideCorp = 'ESM-Trading Terms'; /* Title Select Company pada header pasa sidemenu/menu samping kiri */
$this->sideMenu = 'esm_trading_term'; /* kd_menu untuk list menu pada sidemenu, get from table of database */
$this->title = Yii::t('app', 'Trading Terms ');
//print_r($model[0]);
//echo $model[0]->NmDis;
?>
<div class="content" >
<!-- HEADER !-->
<div class="row">
<div class="col-lg-12">
<!-- HEADER !-->
<div class="col-md-1" style="float:left;">
<?php echo Html::img('@web/upload/lukison.png', ['class' => 'pnjg', 'style'=>'width:100px;height:70px;']); ?>
</div>
<div class="col-md-9" style="padding-top:15px;">
<h3 class="text-center"><b> <?php echo 'TERM - '.ucwords($model[0]->NmCustomer) ?> </b></h3>
</div>
<div class="col-md-12">
<hr style="height:10px;margin-top: 1px; margin-bottom: 1px;color:#94cdf0">
</div>
<!-- DATA !-->
<?php
$contentData=$this->render('_reviewData',[
'model'=>$model,
'dataProvider'=>$dataProvider,
'dataProviderBudget'=>$dataProviderBudget
]);
$contentChart=$this->render('_reviewChart');
$items=[
[
'label'=>'<i class="fa fa-mortar-board fa-lg"></i> TERM DATA','content'=>$contentData,
// 'active'=>true,
'options' => ['id' => 'term-data'],
],
[
'label'=>'<i class="fa fa-bar-chart fa-lg"></i> TERM CHART','content'=>'',
'options' => ['id' => 'term-chart'],
]
];
echo TabsX::widget([
'id'=>'tab-term-plan',
'items'=>$items,
'position'=>TabsX::POS_ABOVE,
'encodeLabels'=>false
]);
?>
</div>
</div>
</div><!-- Body !--> | adem-team/advanced | lukisongroup/purchasing/views/plan-term/review.php | PHP | bsd-3-clause | 2,360 |
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\models\OlxstatisticSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Olxstatistics';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="olxstatistic-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Olxstatistic', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'shorturl:url',
'fullurl:url',
'someelse',
'someelse2',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
| samwolf1982/timutparserolxdomria_yii2 | backend/views/olxstatistic/index.php | PHP | bsd-3-clause | 919 |
// This file has been generated by Py++.
#include "boost/python.hpp"
#include "wrap_osg.h"
#include "wrap_referenced.h"
#include "node.pypp.hpp"
namespace bp = boost::python;
struct Node_wrapper : osg::Node, bp::wrapper< osg::Node > {
Node_wrapper( )
: osg::Node( )
, bp::wrapper< osg::Node >(){
// null constructor
}
virtual void accept( ::osg::NodeVisitor & nv ) {
if( bp::override func_accept = this->get_override( "accept" ) )
func_accept( boost::ref(nv) );
else{
this->osg::Node::accept( boost::ref(nv) );
}
}
void default_accept( ::osg::NodeVisitor & nv ) {
osg::Node::accept( boost::ref(nv) );
}
virtual ::osg::Camera * asCamera( ) {
if( bp::override func_asCamera = this->get_override( "asCamera" ) )
return func_asCamera( );
else{
return this->osg::Node::asCamera( );
}
}
::osg::Camera * default_asCamera( ) {
return osg::Node::asCamera( );
}
virtual ::osg::Camera const * asCamera( ) const {
if( bp::override func_asCamera = this->get_override( "asCamera" ) )
return func_asCamera( );
else{
return this->osg::Node::asCamera( );
}
}
::osg::Camera const * default_asCamera( ) const {
return osg::Node::asCamera( );
}
virtual ::osg::Geode * asGeode( ) {
if( bp::override func_asGeode = this->get_override( "asGeode" ) )
return func_asGeode( );
else{
return this->osg::Node::asGeode( );
}
}
::osg::Geode * default_asGeode( ) {
return osg::Node::asGeode( );
}
virtual ::osg::Geode const * asGeode( ) const {
if( bp::override func_asGeode = this->get_override( "asGeode" ) )
return func_asGeode( );
else{
return this->osg::Node::asGeode( );
}
}
::osg::Geode const * default_asGeode( ) const {
return osg::Node::asGeode( );
}
virtual ::osg::Group * asGroup( ) {
if( bp::override func_asGroup = this->get_override( "asGroup" ) )
return func_asGroup( );
else{
return this->osg::Node::asGroup( );
}
}
::osg::Group * default_asGroup( ) {
return osg::Node::asGroup( );
}
virtual ::osg::Group const * asGroup( ) const {
if( bp::override func_asGroup = this->get_override( "asGroup" ) )
return func_asGroup( );
else{
return this->osg::Node::asGroup( );
}
}
::osg::Group const * default_asGroup( ) const {
return osg::Node::asGroup( );
}
virtual ::osg::Switch * asSwitch( ) {
if( bp::override func_asSwitch = this->get_override( "asSwitch" ) )
return func_asSwitch( );
else{
return this->osg::Node::asSwitch( );
}
}
::osg::Switch * default_asSwitch( ) {
return osg::Node::asSwitch( );
}
virtual ::osg::Switch const * asSwitch( ) const {
if( bp::override func_asSwitch = this->get_override( "asSwitch" ) )
return func_asSwitch( );
else{
return this->osg::Node::asSwitch( );
}
}
::osg::Switch const * default_asSwitch( ) const {
return osg::Node::asSwitch( );
}
virtual ::osg::Transform * asTransform( ) {
if( bp::override func_asTransform = this->get_override( "asTransform" ) )
return func_asTransform( );
else{
return this->osg::Node::asTransform( );
}
}
::osg::Transform * default_asTransform( ) {
return osg::Node::asTransform( );
}
virtual ::osg::Transform const * asTransform( ) const {
if( bp::override func_asTransform = this->get_override( "asTransform" ) )
return func_asTransform( );
else{
return this->osg::Node::asTransform( );
}
}
::osg::Transform const * default_asTransform( ) const {
return osg::Node::asTransform( );
}
virtual void ascend( ::osg::NodeVisitor & nv ) {
if( bp::override func_ascend = this->get_override( "ascend" ) )
func_ascend( boost::ref(nv) );
else{
this->osg::Node::ascend( boost::ref(nv) );
}
}
void default_ascend( ::osg::NodeVisitor & nv ) {
osg::Node::ascend( boost::ref(nv) );
}
virtual char const * className( ) const {
if( bp::override func_className = this->get_override( "className" ) )
return func_className( );
else{
return this->osg::Node::className( );
}
}
char const * default_className( ) const {
return osg::Node::className( );
}
virtual ::osg::Object * clone( ::osg::CopyOp const & copyop ) const {
if( bp::override func_clone = this->get_override( "clone" ) )
return func_clone( boost::ref(copyop) );
else{
return this->osg::Node::clone( boost::ref(copyop) );
}
}
::osg::Object * default_clone( ::osg::CopyOp const & copyop ) const {
return osg::Node::clone( boost::ref(copyop) );
}
virtual ::osg::Object * cloneType( ) const {
if( bp::override func_cloneType = this->get_override( "cloneType" ) )
return func_cloneType( );
else{
return this->osg::Node::cloneType( );
}
}
::osg::Object * default_cloneType( ) const {
return osg::Node::cloneType( );
}
virtual ::osg::BoundingSphere computeBound( ) const {
if( bp::override func_computeBound = this->get_override( "computeBound" ) )
return func_computeBound( );
else{
return this->osg::Node::computeBound( );
}
}
::osg::BoundingSphere default_computeBound( ) const {
return osg::Node::computeBound( );
}
virtual bool isSameKindAs( ::osg::Object const * obj ) const {
if( bp::override func_isSameKindAs = this->get_override( "isSameKindAs" ) )
return func_isSameKindAs( boost::python::ptr(obj) );
else{
return this->osg::Node::isSameKindAs( boost::python::ptr(obj) );
}
}
bool default_isSameKindAs( ::osg::Object const * obj ) const {
return osg::Node::isSameKindAs( boost::python::ptr(obj) );
}
virtual char const * libraryName( ) const {
if( bp::override func_libraryName = this->get_override( "libraryName" ) )
return func_libraryName( );
else{
return this->osg::Node::libraryName( );
}
}
char const * default_libraryName( ) const {
return osg::Node::libraryName( );
}
virtual void resizeGLObjectBuffers( unsigned int arg0 ) {
if( bp::override func_resizeGLObjectBuffers = this->get_override( "resizeGLObjectBuffers" ) )
func_resizeGLObjectBuffers( arg0 );
else{
this->osg::Node::resizeGLObjectBuffers( arg0 );
}
}
void default_resizeGLObjectBuffers( unsigned int arg0 ) {
osg::Node::resizeGLObjectBuffers( arg0 );
}
virtual void setThreadSafeRefUnref( bool threadSafe ) {
if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) )
func_setThreadSafeRefUnref( threadSafe );
else{
this->osg::Node::setThreadSafeRefUnref( threadSafe );
}
}
void default_setThreadSafeRefUnref( bool threadSafe ) {
osg::Node::setThreadSafeRefUnref( threadSafe );
}
virtual void traverse( ::osg::NodeVisitor & arg0 ) {
if( bp::override func_traverse = this->get_override( "traverse" ) )
func_traverse( boost::ref(arg0) );
else{
this->osg::Node::traverse( boost::ref(arg0) );
}
}
void default_traverse( ::osg::NodeVisitor & arg0 ) {
osg::Node::traverse( boost::ref(arg0) );
}
virtual void computeDataVariance( ) {
if( bp::override func_computeDataVariance = this->get_override( "computeDataVariance" ) )
func_computeDataVariance( );
else{
this->osg::Object::computeDataVariance( );
}
}
void default_computeDataVariance( ) {
osg::Object::computeDataVariance( );
}
virtual ::osg::Referenced * getUserData( ) {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced * default_getUserData( ) {
return osg::Object::getUserData( );
}
virtual ::osg::Referenced const * getUserData( ) const {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced const * default_getUserData( ) const {
return osg::Object::getUserData( );
}
virtual void setName( ::std::string const & name ) {
if( bp::override func_setName = this->get_override( "setName" ) )
func_setName( name );
else{
this->osg::Object::setName( name );
}
}
void default_setName( ::std::string const & name ) {
osg::Object::setName( name );
}
virtual void setUserData( ::osg::Referenced * obj ) {
if( bp::override func_setUserData = this->get_override( "setUserData" ) )
func_setUserData( boost::python::ptr(obj) );
else{
this->osg::Object::setUserData( boost::python::ptr(obj) );
}
}
void default_setUserData( ::osg::Referenced * obj ) {
osg::Object::setUserData( boost::python::ptr(obj) );
}
};
void register_Node_class(){
{ //::osg::Node
typedef bp::class_< Node_wrapper, bp::bases< osg::Object >, osg::ref_ptr< ::osg::Node >, boost::noncopyable > Node_exposer_t;
Node_exposer_t Node_exposer = Node_exposer_t( "Node", "\n Base class for all internal nodes in the scene graph.\n Provides interface for most common node operations (Composite Pattern).\n", bp::no_init );
bp::scope Node_scope( Node_exposer );
Node_exposer.def( bp::init< >("\n Construct a node.\n Initialize the parent list to empty, node name to and\n bounding sphere dirty flag to true.\n") );
{ //::osg::Node::accept
typedef void ( ::osg::Node::*accept_function_type)( ::osg::NodeVisitor & ) ;
typedef void ( Node_wrapper::*default_accept_function_type)( ::osg::NodeVisitor & ) ;
Node_exposer.def(
"accept"
, accept_function_type(&::osg::Node::accept)
, default_accept_function_type(&Node_wrapper::default_accept)
, ( bp::arg("nv") ) );
}
{ //::osg::Node::addCullCallback
typedef void ( ::osg::Node::*addCullCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"addCullCallback"
, addCullCallback_function_type( &::osg::Node::addCullCallback )
, ( bp::arg("nc") )
, " Convenience method that sets the cull callback of the node if it doesnt exist, or nest it into the existing one." );
}
{ //::osg::Node::addDescription
typedef void ( ::osg::Node::*addDescription_function_type)( ::std::string const & ) ;
Node_exposer.def(
"addDescription"
, addDescription_function_type( &::osg::Node::addDescription )
, ( bp::arg("desc") )
, " Add a description string to the node." );
}
{ //::osg::Node::addEventCallback
typedef void ( ::osg::Node::*addEventCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"addEventCallback"
, addEventCallback_function_type( &::osg::Node::addEventCallback )
, ( bp::arg("nc") )
, " Convenience method that sets the event callback of the node if it doesnt exist, or nest it into the existing one." );
}
{ //::osg::Node::addUpdateCallback
typedef void ( ::osg::Node::*addUpdateCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"addUpdateCallback"
, addUpdateCallback_function_type( &::osg::Node::addUpdateCallback )
, ( bp::arg("nc") )
, " Convenience method that sets the update callback of the node if it doesnt exist, or nest it into the existing one." );
}
{ //::osg::Node::asCamera
typedef ::osg::Camera * ( ::osg::Node::*asCamera_function_type)( ) ;
typedef ::osg::Camera * ( Node_wrapper::*default_asCamera_function_type)( ) ;
Node_exposer.def(
"asCamera"
, asCamera_function_type(&::osg::Node::asCamera)
, default_asCamera_function_type(&Node_wrapper::default_asCamera)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asCamera
typedef ::osg::Camera const * ( ::osg::Node::*asCamera_function_type)( ) const;
typedef ::osg::Camera const * ( Node_wrapper::*default_asCamera_function_type)( ) const;
Node_exposer.def(
"asCamera"
, asCamera_function_type(&::osg::Node::asCamera)
, default_asCamera_function_type(&Node_wrapper::default_asCamera)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asGeode
typedef ::osg::Geode * ( ::osg::Node::*asGeode_function_type)( ) ;
typedef ::osg::Geode * ( Node_wrapper::*default_asGeode_function_type)( ) ;
Node_exposer.def(
"asGeode"
, asGeode_function_type(&::osg::Node::asGeode)
, default_asGeode_function_type(&Node_wrapper::default_asGeode)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asGeode
typedef ::osg::Geode const * ( ::osg::Node::*asGeode_function_type)( ) const;
typedef ::osg::Geode const * ( Node_wrapper::*default_asGeode_function_type)( ) const;
Node_exposer.def(
"asGeode"
, asGeode_function_type(&::osg::Node::asGeode)
, default_asGeode_function_type(&Node_wrapper::default_asGeode)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asGroup
typedef ::osg::Group * ( ::osg::Node::*asGroup_function_type)( ) ;
typedef ::osg::Group * ( Node_wrapper::*default_asGroup_function_type)( ) ;
Node_exposer.def(
"asGroup"
, asGroup_function_type(&::osg::Node::asGroup)
, default_asGroup_function_type(&Node_wrapper::default_asGroup)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asGroup
typedef ::osg::Group const * ( ::osg::Node::*asGroup_function_type)( ) const;
typedef ::osg::Group const * ( Node_wrapper::*default_asGroup_function_type)( ) const;
Node_exposer.def(
"asGroup"
, asGroup_function_type(&::osg::Node::asGroup)
, default_asGroup_function_type(&Node_wrapper::default_asGroup)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asSwitch
typedef ::osg::Switch * ( ::osg::Node::*asSwitch_function_type)( ) ;
typedef ::osg::Switch * ( Node_wrapper::*default_asSwitch_function_type)( ) ;
Node_exposer.def(
"asSwitch"
, asSwitch_function_type(&::osg::Node::asSwitch)
, default_asSwitch_function_type(&Node_wrapper::default_asSwitch)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asSwitch
typedef ::osg::Switch const * ( ::osg::Node::*asSwitch_function_type)( ) const;
typedef ::osg::Switch const * ( Node_wrapper::*default_asSwitch_function_type)( ) const;
Node_exposer.def(
"asSwitch"
, asSwitch_function_type(&::osg::Node::asSwitch)
, default_asSwitch_function_type(&Node_wrapper::default_asSwitch)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asTransform
typedef ::osg::Transform * ( ::osg::Node::*asTransform_function_type)( ) ;
typedef ::osg::Transform * ( Node_wrapper::*default_asTransform_function_type)( ) ;
Node_exposer.def(
"asTransform"
, asTransform_function_type(&::osg::Node::asTransform)
, default_asTransform_function_type(&Node_wrapper::default_asTransform)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asTransform
typedef ::osg::Transform const * ( ::osg::Node::*asTransform_function_type)( ) const;
typedef ::osg::Transform const * ( Node_wrapper::*default_asTransform_function_type)( ) const;
Node_exposer.def(
"asTransform"
, asTransform_function_type(&::osg::Node::asTransform)
, default_asTransform_function_type(&Node_wrapper::default_asTransform)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::ascend
typedef void ( ::osg::Node::*ascend_function_type)( ::osg::NodeVisitor & ) ;
typedef void ( Node_wrapper::*default_ascend_function_type)( ::osg::NodeVisitor & ) ;
Node_exposer.def(
"ascend"
, ascend_function_type(&::osg::Node::ascend)
, default_ascend_function_type(&Node_wrapper::default_ascend)
, ( bp::arg("nv") ) );
}
{ //::osg::Node::className
typedef char const * ( ::osg::Node::*className_function_type)( ) const;
typedef char const * ( Node_wrapper::*default_className_function_type)( ) const;
Node_exposer.def(
"className"
, className_function_type(&::osg::Node::className)
, default_className_function_type(&Node_wrapper::default_className) );
}
{ //::osg::Node::clone
typedef ::osg::Object * ( ::osg::Node::*clone_function_type)( ::osg::CopyOp const & ) const;
typedef ::osg::Object * ( Node_wrapper::*default_clone_function_type)( ::osg::CopyOp const & ) const;
Node_exposer.def(
"clone"
, clone_function_type(&::osg::Node::clone)
, default_clone_function_type(&Node_wrapper::default_clone)
, ( bp::arg("copyop") )
, bp::return_value_policy< bp::reference_existing_object >() );
}
{ //::osg::Node::cloneType
typedef ::osg::Object * ( ::osg::Node::*cloneType_function_type)( ) const;
typedef ::osg::Object * ( Node_wrapper::*default_cloneType_function_type)( ) const;
Node_exposer.def(
"cloneType"
, cloneType_function_type(&::osg::Node::cloneType)
, default_cloneType_function_type(&Node_wrapper::default_cloneType)
, bp::return_value_policy< bp::reference_existing_object >() );
}
{ //::osg::Node::computeBound
typedef ::osg::BoundingSphere ( ::osg::Node::*computeBound_function_type)( ) const;
typedef ::osg::BoundingSphere ( Node_wrapper::*default_computeBound_function_type)( ) const;
Node_exposer.def(
"computeBound"
, computeBound_function_type(&::osg::Node::computeBound)
, default_computeBound_function_type(&Node_wrapper::default_computeBound) );
}
{ //::osg::Node::containsOccluderNodes
typedef bool ( ::osg::Node::*containsOccluderNodes_function_type)( ) const;
Node_exposer.def(
"containsOccluderNodes"
, containsOccluderNodes_function_type( &::osg::Node::containsOccluderNodes )
, " return true if this node is an OccluderNode or the subgraph below this node are OccluderNodes." );
}
{ //::osg::Node::dirtyBound
typedef void ( ::osg::Node::*dirtyBound_function_type)( ) ;
Node_exposer.def(
"dirtyBound"
, dirtyBound_function_type( &::osg::Node::dirtyBound )
, " Mark this nodes bounding sphere dirty.\n Forcing it to be computed on the next call to getBound()." );
}
{ //::osg::Node::getBound
typedef ::osg::BoundingSphere const & ( ::osg::Node::*getBound_function_type)( ) const;
Node_exposer.def(
"getBound"
, getBound_function_type( &::osg::Node::getBound )
, bp::return_internal_reference< >()
, " Get the bounding sphere of node.\n Using lazy evaluation computes the bounding sphere if it is dirty." );
}
{ //::osg::Node::getComputeBoundingSphereCallback
typedef ::osg::Node::ComputeBoundingSphereCallback * ( ::osg::Node::*getComputeBoundingSphereCallback_function_type)( ) ;
Node_exposer.def(
"getComputeBoundingSphereCallback"
, getComputeBoundingSphereCallback_function_type( &::osg::Node::getComputeBoundingSphereCallback )
, bp::return_internal_reference< >()
, " Get the compute bound callback." );
}
{ //::osg::Node::getComputeBoundingSphereCallback
typedef ::osg::Node::ComputeBoundingSphereCallback const * ( ::osg::Node::*getComputeBoundingSphereCallback_function_type)( ) const;
Node_exposer.def(
"getComputeBoundingSphereCallback"
, getComputeBoundingSphereCallback_function_type( &::osg::Node::getComputeBoundingSphereCallback )
, bp::return_internal_reference< >()
, " Get the const compute bound callback." );
}
{ //::osg::Node::getCullCallback
typedef ::osg::NodeCallback * ( ::osg::Node::*getCullCallback_function_type)( ) ;
Node_exposer.def(
"getCullCallback"
, getCullCallback_function_type( &::osg::Node::getCullCallback )
, bp::return_internal_reference< >()
, " Get cull node callback, called during cull traversal." );
}
{ //::osg::Node::getCullCallback
typedef ::osg::NodeCallback const * ( ::osg::Node::*getCullCallback_function_type)( ) const;
Node_exposer.def(
"getCullCallback"
, getCullCallback_function_type( &::osg::Node::getCullCallback )
, bp::return_internal_reference< >()
, " Get const cull node callback, called during cull traversal." );
}
{ //::osg::Node::getCullingActive
typedef bool ( ::osg::Node::*getCullingActive_function_type)( ) const;
Node_exposer.def(
"getCullingActive"
, getCullingActive_function_type( &::osg::Node::getCullingActive )
, " Get the view frustum/small feature _cullingActive flag for this node. Used as a guide\n to the cull traversal." );
}
{ //::osg::Node::getDescription
typedef ::std::string const & ( ::osg::Node::*getDescription_function_type)( unsigned int ) const;
Node_exposer.def(
"getDescription"
, getDescription_function_type( &::osg::Node::getDescription )
, ( bp::arg("i") )
, bp::return_value_policy< bp::copy_const_reference >()
, " Get a single const description of the const node." );
}
{ //::osg::Node::getDescription
typedef ::std::string & ( ::osg::Node::*getDescription_function_type)( unsigned int ) ;
Node_exposer.def(
"getDescription"
, getDescription_function_type( &::osg::Node::getDescription )
, ( bp::arg("i") )
, bp::return_internal_reference< >()
, " Get a single description of the node." );
}
{ //::osg::Node::getDescriptions
typedef ::std::vector< std::string > & ( ::osg::Node::*getDescriptions_function_type)( ) ;
Node_exposer.def(
"getDescriptions"
, getDescriptions_function_type( &::osg::Node::getDescriptions )
, bp::return_internal_reference< >()
, " Get the description list of the node." );
}
{ //::osg::Node::getDescriptions
typedef ::std::vector< std::string > const & ( ::osg::Node::*getDescriptions_function_type)( ) const;
Node_exposer.def(
"getDescriptions"
, getDescriptions_function_type( &::osg::Node::getDescriptions )
, bp::return_internal_reference< >()
, " Get the const description list of the const node." );
}
{ //::osg::Node::getEventCallback
typedef ::osg::NodeCallback * ( ::osg::Node::*getEventCallback_function_type)( ) ;
Node_exposer.def(
"getEventCallback"
, getEventCallback_function_type( &::osg::Node::getEventCallback )
, bp::return_internal_reference< >()
, " Get event node callback, called during event traversal." );
}
{ //::osg::Node::getEventCallback
typedef ::osg::NodeCallback const * ( ::osg::Node::*getEventCallback_function_type)( ) const;
Node_exposer.def(
"getEventCallback"
, getEventCallback_function_type( &::osg::Node::getEventCallback )
, bp::return_internal_reference< >()
, " Get const event node callback, called during event traversal." );
}
{ //::osg::Node::getInitialBound
typedef ::osg::BoundingSphere const & ( ::osg::Node::*getInitialBound_function_type)( ) const;
Node_exposer.def(
"getInitialBound"
, getInitialBound_function_type( &::osg::Node::getInitialBound )
, bp::return_internal_reference< >()
, " Set the initial bounding volume to use when computing the overall bounding volume." );
}
{ //::osg::Node::getNodeMask
typedef unsigned int ( ::osg::Node::*getNodeMask_function_type)( ) const;
Node_exposer.def(
"getNodeMask"
, getNodeMask_function_type( &::osg::Node::getNodeMask )
, " Get the node Mask." );
}
{ //::osg::Node::getNumChildrenRequiringEventTraversal
typedef unsigned int ( ::osg::Node::*getNumChildrenRequiringEventTraversal_function_type)( ) const;
Node_exposer.def(
"getNumChildrenRequiringEventTraversal"
, getNumChildrenRequiringEventTraversal_function_type( &::osg::Node::getNumChildrenRequiringEventTraversal )
, " Get the number of Children of this node which require Event traversal,\n since they have an Event Callback attached to them or their children." );
}
{ //::osg::Node::getNumChildrenRequiringUpdateTraversal
typedef unsigned int ( ::osg::Node::*getNumChildrenRequiringUpdateTraversal_function_type)( ) const;
Node_exposer.def(
"getNumChildrenRequiringUpdateTraversal"
, getNumChildrenRequiringUpdateTraversal_function_type( &::osg::Node::getNumChildrenRequiringUpdateTraversal )
, " Get the number of Children of this node which require Update traversal,\n since they have an Update Callback attached to them or their children." );
}
{ //::osg::Node::getNumChildrenWithCullingDisabled
typedef unsigned int ( ::osg::Node::*getNumChildrenWithCullingDisabled_function_type)( ) const;
Node_exposer.def(
"getNumChildrenWithCullingDisabled"
, getNumChildrenWithCullingDisabled_function_type( &::osg::Node::getNumChildrenWithCullingDisabled )
, " Get the number of Children of this node which have culling disabled." );
}
{ //::osg::Node::getNumChildrenWithOccluderNodes
typedef unsigned int ( ::osg::Node::*getNumChildrenWithOccluderNodes_function_type)( ) const;
Node_exposer.def(
"getNumChildrenWithOccluderNodes"
, getNumChildrenWithOccluderNodes_function_type( &::osg::Node::getNumChildrenWithOccluderNodes )
, " Get the number of Children of this node which are or have OccluderNodes." );
}
{ //::osg::Node::getNumDescriptions
typedef unsigned int ( ::osg::Node::*getNumDescriptions_function_type)( ) const;
Node_exposer.def(
"getNumDescriptions"
, getNumDescriptions_function_type( &::osg::Node::getNumDescriptions )
, " Get the number of descriptions of the node." );
}
{ //::osg::Node::getNumParents
typedef unsigned int ( ::osg::Node::*getNumParents_function_type)( ) const;
Node_exposer.def(
"getNumParents"
, getNumParents_function_type( &::osg::Node::getNumParents )
, " Get the number of parents of node.\n Return: the number of parents of this node." );
}
{ //::osg::Node::getOrCreateStateSet
typedef ::osg::StateSet * ( ::osg::Node::*getOrCreateStateSet_function_type)( ) ;
Node_exposer.def(
"getOrCreateStateSet"
, getOrCreateStateSet_function_type( &::osg::Node::getOrCreateStateSet )
, bp::return_internal_reference< >()
, " return the nodes StateSet, if one does not already exist create it\n set the node and return the newly created StateSet. This ensures\n that a valid StateSet is always returned and can be used directly." );
}
{ //::osg::Node::getParent
typedef ::osg::Group * ( ::osg::Node::*getParent_function_type)( unsigned int ) ;
Node_exposer.def(
"getParent"
, getParent_function_type( &::osg::Node::getParent )
, ( bp::arg("i") )
, bp::return_internal_reference< >() );
}
{ //::osg::Node::getParent
typedef ::osg::Group const * ( ::osg::Node::*getParent_function_type)( unsigned int ) const;
Node_exposer.def(
"getParent"
, getParent_function_type( &::osg::Node::getParent )
, ( bp::arg("i") )
, bp::return_internal_reference< >()
, " Get a single const parent of node.\n @param i: index of the parent to get.\n Return: the parent i." );
}
{ //::osg::Node::getParentalNodePaths
typedef ::osg::NodePathList ( ::osg::Node::*getParentalNodePaths_function_type)( ::osg::Node * ) const;
Node_exposer.def(
"getParentalNodePaths"
, getParentalNodePaths_function_type( &::osg::Node::getParentalNodePaths )
, ( bp::arg("haltTraversalAtNode")=bp::object() )
, " Get the list of node paths parent paths.\n The optional Node* haltTraversalAtNode allows the user to prevent traversal beyond a specifed node." );
}
{ //::osg::Node::getParents
typedef ::std::vector< osg::Group* > const & ( ::osg::Node::*getParents_function_type)( ) const;
Node_exposer.def(
"getParents"
, getParents_function_type( &::osg::Node::getParents )
, bp::return_internal_reference< >()
, " Get the parent list of node." );
}
{ //::osg::Node::getParents
typedef ::std::vector< osg::Group* > ( ::osg::Node::*getParents_function_type)( ) ;
Node_exposer.def(
"getParents"
, getParents_function_type( &::osg::Node::getParents )
, " Get the a copy of parent list of node. A copy is returned to\n prevent modification of the parent list." );
}
{ //::osg::Node::getStateSet
typedef ::osg::StateSet * ( ::osg::Node::*getStateSet_function_type)( ) ;
Node_exposer.def(
"getStateSet"
, getStateSet_function_type( &::osg::Node::getStateSet )
, bp::return_internal_reference< >()
, " Return the nodes StateSet. returns NULL if a stateset is not attached." );
}
{ //::osg::Node::getStateSet
typedef ::osg::StateSet const * ( ::osg::Node::*getStateSet_function_type)( ) const;
Node_exposer.def(
"getStateSet"
, getStateSet_function_type( &::osg::Node::getStateSet )
, bp::return_internal_reference< >()
, " Return the nodes const StateSet. Returns NULL if a stateset is not attached." );
}
{ //::osg::Node::getUpdateCallback
typedef ::osg::NodeCallback * ( ::osg::Node::*getUpdateCallback_function_type)( ) ;
Node_exposer.def(
"getUpdateCallback"
, getUpdateCallback_function_type( &::osg::Node::getUpdateCallback )
, bp::return_internal_reference< >()
, " Get update node callback, called during update traversal." );
}
{ //::osg::Node::getUpdateCallback
typedef ::osg::NodeCallback const * ( ::osg::Node::*getUpdateCallback_function_type)( ) const;
Node_exposer.def(
"getUpdateCallback"
, getUpdateCallback_function_type( &::osg::Node::getUpdateCallback )
, bp::return_internal_reference< >()
, " Get const update node callback, called during update traversal." );
}
{ //::osg::Node::getWorldMatrices
typedef ::osg::MatrixList ( ::osg::Node::*getWorldMatrices_function_type)( ::osg::Node const * ) const;
Node_exposer.def(
"getWorldMatrices"
, getWorldMatrices_function_type( &::osg::Node::getWorldMatrices )
, ( bp::arg("haltTraversalAtNode")=bp::object() )
, " Get the list of matrices that transform this node from local coordinates to world coordinates.\n The optional Node* haltTraversalAtNode allows the user to prevent traversal beyond a specifed node." );
}
{ //::osg::Node::isCullingActive
typedef bool ( ::osg::Node::*isCullingActive_function_type)( ) const;
Node_exposer.def(
"isCullingActive"
, isCullingActive_function_type( &::osg::Node::isCullingActive )
, " Return true if this node can be culled by view frustum, occlusion or small feature culling during the cull traversal.\n Note, returns true only if no children have culling disabled, and the local _cullingActive flag is true." );
}
{ //::osg::Node::isSameKindAs
typedef bool ( ::osg::Node::*isSameKindAs_function_type)( ::osg::Object const * ) const;
typedef bool ( Node_wrapper::*default_isSameKindAs_function_type)( ::osg::Object const * ) const;
Node_exposer.def(
"isSameKindAs"
, isSameKindAs_function_type(&::osg::Node::isSameKindAs)
, default_isSameKindAs_function_type(&Node_wrapper::default_isSameKindAs)
, ( bp::arg("obj") ) );
}
{ //::osg::Node::libraryName
typedef char const * ( ::osg::Node::*libraryName_function_type)( ) const;
typedef char const * ( Node_wrapper::*default_libraryName_function_type)( ) const;
Node_exposer.def(
"libraryName"
, libraryName_function_type(&::osg::Node::libraryName)
, default_libraryName_function_type(&Node_wrapper::default_libraryName) );
}
{ //::osg::Node::removeCullCallback
typedef void ( ::osg::Node::*removeCullCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"removeCullCallback"
, removeCullCallback_function_type( &::osg::Node::removeCullCallback )
, ( bp::arg("nc") )
, " Convenience method that removes a given callback from a node, even if that callback is nested. There is no error return in case the given callback is not found." );
}
{ //::osg::Node::removeEventCallback
typedef void ( ::osg::Node::*removeEventCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"removeEventCallback"
, removeEventCallback_function_type( &::osg::Node::removeEventCallback )
, ( bp::arg("nc") )
, " Convenience method that removes a given callback from a node, even if that callback is nested. There is no error return in case the given callback is not found." );
}
{ //::osg::Node::removeUpdateCallback
typedef void ( ::osg::Node::*removeUpdateCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"removeUpdateCallback"
, removeUpdateCallback_function_type( &::osg::Node::removeUpdateCallback )
, ( bp::arg("nc") )
, " Convenience method that removes a given callback from a node, even if that callback is nested. There is no error return in case the given callback is not found." );
}
{ //::osg::Node::resizeGLObjectBuffers
typedef void ( ::osg::Node::*resizeGLObjectBuffers_function_type)( unsigned int ) ;
typedef void ( Node_wrapper::*default_resizeGLObjectBuffers_function_type)( unsigned int ) ;
Node_exposer.def(
"resizeGLObjectBuffers"
, resizeGLObjectBuffers_function_type(&::osg::Node::resizeGLObjectBuffers)
, default_resizeGLObjectBuffers_function_type(&Node_wrapper::default_resizeGLObjectBuffers)
, ( bp::arg("arg0") ) );
}
{ //::osg::Node::setComputeBoundingSphereCallback
typedef void ( ::osg::Node::*setComputeBoundingSphereCallback_function_type)( ::osg::Node::ComputeBoundingSphereCallback * ) ;
Node_exposer.def(
"setComputeBoundingSphereCallback"
, setComputeBoundingSphereCallback_function_type( &::osg::Node::setComputeBoundingSphereCallback )
, ( bp::arg("callback") )
, " Set the compute bound callback to override the default computeBound." );
}
{ //::osg::Node::setCullCallback
typedef void ( ::osg::Node::*setCullCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"setCullCallback"
, setCullCallback_function_type( &::osg::Node::setCullCallback )
, ( bp::arg("nc") )
, " Set cull node callback, called during cull traversal." );
}
{ //::osg::Node::setCullingActive
typedef void ( ::osg::Node::*setCullingActive_function_type)( bool ) ;
Node_exposer.def(
"setCullingActive"
, setCullingActive_function_type( &::osg::Node::setCullingActive )
, ( bp::arg("active") )
, " Set the view frustum/small feature culling of this node to be active or inactive.\n The default value is true for _cullingActive. Used as a guide\n to the cull traversal." );
}
{ //::osg::Node::setDescriptions
typedef void ( ::osg::Node::*setDescriptions_function_type)( ::std::vector< std::string > const & ) ;
Node_exposer.def(
"setDescriptions"
, setDescriptions_function_type( &::osg::Node::setDescriptions )
, ( bp::arg("descriptions") )
, " Set the list of string descriptions." );
}
{ //::osg::Node::setEventCallback
typedef void ( ::osg::Node::*setEventCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"setEventCallback"
, setEventCallback_function_type( &::osg::Node::setEventCallback )
, ( bp::arg("nc") )
, " Set event node callback, called during event traversal." );
}
{ //::osg::Node::setInitialBound
typedef void ( ::osg::Node::*setInitialBound_function_type)( ::osg::BoundingSphere const & ) ;
Node_exposer.def(
"setInitialBound"
, setInitialBound_function_type( &::osg::Node::setInitialBound )
, ( bp::arg("bsphere") )
, " Set the initial bounding volume to use when computing the overall bounding volume." );
}
{ //::osg::Node::setNodeMask
typedef void ( ::osg::Node::*setNodeMask_function_type)( unsigned int ) ;
Node_exposer.def(
"setNodeMask"
, setNodeMask_function_type( &::osg::Node::setNodeMask )
, ( bp::arg("nm") )
, " Set the node mask." );
}
{ //::osg::Node::setStateSet
typedef void ( ::osg::Node::*setStateSet_function_type)( ::osg::StateSet * ) ;
Node_exposer.def(
"setStateSet"
, setStateSet_function_type( &::osg::Node::setStateSet )
, ( bp::arg("stateset") )
, " Set the nodes StateSet." );
}
{ //::osg::Node::setThreadSafeRefUnref
typedef void ( ::osg::Node::*setThreadSafeRefUnref_function_type)( bool ) ;
typedef void ( Node_wrapper::*default_setThreadSafeRefUnref_function_type)( bool ) ;
Node_exposer.def(
"setThreadSafeRefUnref"
, setThreadSafeRefUnref_function_type(&::osg::Node::setThreadSafeRefUnref)
, default_setThreadSafeRefUnref_function_type(&Node_wrapper::default_setThreadSafeRefUnref)
, ( bp::arg("threadSafe") ) );
}
{ //::osg::Node::setUpdateCallback
typedef void ( ::osg::Node::*setUpdateCallback_function_type)( ::osg::NodeCallback * ) ;
Node_exposer.def(
"setUpdateCallback"
, setUpdateCallback_function_type( &::osg::Node::setUpdateCallback )
, ( bp::arg("nc") )
, " Set update node callback, called during update traversal." );
}
{ //::osg::Node::traverse
typedef void ( ::osg::Node::*traverse_function_type)( ::osg::NodeVisitor & ) ;
typedef void ( Node_wrapper::*default_traverse_function_type)( ::osg::NodeVisitor & ) ;
Node_exposer.def(
"traverse"
, traverse_function_type(&::osg::Node::traverse)
, default_traverse_function_type(&Node_wrapper::default_traverse)
, ( bp::arg("arg0") ) );
}
{ //::osg::Object::computeDataVariance
typedef void ( ::osg::Object::*computeDataVariance_function_type)( ) ;
typedef void ( Node_wrapper::*default_computeDataVariance_function_type)( ) ;
Node_exposer.def(
"computeDataVariance"
, computeDataVariance_function_type(&::osg::Object::computeDataVariance)
, default_computeDataVariance_function_type(&Node_wrapper::default_computeDataVariance) );
}
{ //::osg::Object::getUserData
typedef ::osg::Referenced * ( ::osg::Object::*getUserData_function_type)( ) ;
typedef ::osg::Referenced * ( Node_wrapper::*default_getUserData_function_type)( ) ;
Node_exposer.def(
"getUserData"
, getUserData_function_type(&::osg::Object::getUserData)
, default_getUserData_function_type(&Node_wrapper::default_getUserData)
, bp::return_internal_reference< >() );
}
{ //::osg::Object::getUserData
typedef ::osg::Referenced const * ( ::osg::Object::*getUserData_function_type)( ) const;
typedef ::osg::Referenced const * ( Node_wrapper::*default_getUserData_function_type)( ) const;
Node_exposer.def(
"getUserData"
, getUserData_function_type(&::osg::Object::getUserData)
, default_getUserData_function_type(&Node_wrapper::default_getUserData)
, bp::return_internal_reference< >() );
}
{ //::osg::Object::setName
typedef void ( ::osg::Object::*setName_function_type)( ::std::string const & ) ;
typedef void ( Node_wrapper::*default_setName_function_type)( ::std::string const & ) ;
Node_exposer.def(
"setName"
, setName_function_type(&::osg::Object::setName)
, default_setName_function_type(&Node_wrapper::default_setName)
, ( bp::arg("name") ) );
}
{ //::osg::Object::setName
typedef void ( ::osg::Object::*setName_function_type)( char const * ) ;
Node_exposer.def(
"setName"
, setName_function_type( &::osg::Object::setName )
, ( bp::arg("name") )
, " Set the name of object using a C style string." );
}
{ //::osg::Object::setUserData
typedef void ( ::osg::Object::*setUserData_function_type)( ::osg::Referenced * ) ;
typedef void ( Node_wrapper::*default_setUserData_function_type)( ::osg::Referenced * ) ;
Node_exposer.def(
"setUserData"
, setUserData_function_type(&::osg::Object::setUserData)
, default_setUserData_function_type(&Node_wrapper::default_setUserData)
, ( bp::arg("obj") ) );
}
{ //property "stateSet"[fget=::osg::Node::getOrCreateStateSet, fset=::osg::Node::setStateSet]
typedef ::osg::StateSet * ( ::osg::Node::*fget)( ) ;
typedef void ( ::osg::Node::*fset)( ::osg::StateSet * ) ;
Node_exposer.add_property(
"stateSet"
, bp::make_function(
fget( &::osg::Node::getOrCreateStateSet )
, bp::return_internal_reference< >() )
, fset( &::osg::Node::setStateSet ) );
}
}
}
| JaneliaSciComp/osgpyplusplus | src/modules/osg/generated_code/Node.pypp.cpp | C++ | bsd-3-clause | 49,800 |
/*** Copyright (c), The Unregents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/* chkObjPermAndStat.h
*/
#ifndef CHK_OBJ_PERM_AND_STAT_HPP
#define CHK_OBJ_PERM_AND_STAT_HPP
/* This is Object File I/O type API call */
#include "rods.hpp"
#include "rcMisc.hpp"
#include "procApiRequest.hpp"
#include "apiNumber.hpp"
#include "initServer.hpp"
#include "dataObjInpOut.hpp"
/* definition for flags */
#define CHK_COLL_FOR_BUNDLE_OPR 0x1
#
typedef struct {
char objPath[MAX_NAME_LEN];
char permission[NAME_LEN];
int flags;
int status;
keyValPair_t condInput;
} chkObjPermAndStat_t;
#define ChkObjPermAndStat_PI "str objPath[MAX_NAME_LEN]; str permission[NAME_LEN]; int flags; int status; struct KeyValPair_PI;"
#if defined(RODS_SERVER)
#define RS_CHK_OBJ_PERM_AND_STAT rsChkObjPermAndStat
/* prototype for the server handler */
int
rsChkObjPermAndStat( rsComm_t *rsComm,
chkObjPermAndStat_t *chkObjPermAndStatInp );
int
_rsChkObjPermAndStat( rsComm_t *rsComm,
chkObjPermAndStat_t *chkObjPermAndStatInp );
int
chkCollForBundleOpr( rsComm_t *rsComm,
chkObjPermAndStat_t *chkObjPermAndStatInp );
#else
#define RS_CHK_OBJ_PERM_AND_STAT NULL
#endif
/* prototype for the client call */
int
rcChkObjPermAndStat( rcComm_t *conn, chkObjPermAndStat_t *chkObjPermAndStatInp );
/* rcChkObjPermAndStat - Unregister a iRODS dataObject.
* Input -
* rcComm_t *conn - The client connection handle.
* chkObjPermAndStat_t *chkObjPermAndStatInp - the dataObjInfo to unregister
*
* OutPut -
* int status - status of the operation.
*/
#endif /* CHK_OBJ_PERM_AND_STAT_H */
| leesab/irods | iRODS/lib/api/include/chkObjPermAndStat.hpp | C++ | bsd-3-clause | 1,734 |
from .store import (
Command, Store, RemoteStore, PubSub, PubSubClient,
parse_store_url, create_store, register_store, data_stores,
NoSuchStore
)
from .channels import Channels
from . import redis # noqa
from .pulsards.startds import start_store
__all__ = [
'Command',
'Store',
'RemoteStore',
'PubSub',
'PubSubClient',
'parse_store_url',
'create_store',
'register_store',
'data_stores',
'NoSuchStore',
'start_store',
'Channels'
]
| quantmind/pulsar | pulsar/apps/data/__init__.py | Python | bsd-3-clause | 496 |
import { Link as GatsbyLink } from 'gatsby';
import React from 'react';
interface LinkProps {
children?: React.ReactNode;
className?: string;
external?: boolean;
sameTab?: boolean;
state?: Record<string, unknown>;
to: string;
}
const Link = ({
children,
to,
external,
sameTab,
...other
}: LinkProps): JSX.Element => {
if (!external && /^\/(?!\/)/.test(to)) {
return (
<GatsbyLink to={to} {...other}>
{children}
</GatsbyLink>
);
} else if (sameTab && external) {
return (
<a href={to} {...other}>
{children}
</a>
);
}
return (
<a href={to} {...other} rel='noopener noreferrer' target='_blank'>
{children}
</a>
);
};
export default Link;
| raisedadead/FreeCodeCamp | client/src/components/helpers/link.tsx | TypeScript | bsd-3-clause | 742 |
package cz.vsb.resbill.web.contracts;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import cz.vsb.resbill.criteria.ContractPersonCriteria;
import cz.vsb.resbill.criteria.PersonCriteria;
import cz.vsb.resbill.criteria.PersonCriteria.OrderBy;
import cz.vsb.resbill.dto.ContractPersonEditDTO;
import cz.vsb.resbill.exception.ContractPersonServiceException;
import cz.vsb.resbill.model.ContractPerson;
import cz.vsb.resbill.model.Person;
import cz.vsb.resbill.service.ContractPersonService;
import cz.vsb.resbill.service.PersonService;
import cz.vsb.resbill.util.WebUtils;
/**
* A controller for handling requests for/from contracts/contractPersonEdit.html page template.
*
* @author HAL191
*
*/
@Controller
@RequestMapping("/contracts/persons/edit")
@SessionAttributes("contractPersonEditDTO")
public class ContractPersonEditController extends AbstractContractController {
private static final Logger log = LoggerFactory.getLogger(ContractPersonEditController.class);
private static final String CONTRACT_PERSON_EDIT_DTO_MODEL_KEY = "contractPersonEditDTO";
@Inject
private ContractPersonService contractPersonService;
@Inject
private PersonService personService;
@InitBinder
public void initBinder(WebDataBinder binder, Locale locale) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
@ModelAttribute("persons")
public List<Person> getPersons() {
try {
PersonCriteria criteria = new PersonCriteria();
criteria.setOrderBy(OrderBy.NAME);
return personService.findPersons(criteria, null, null);
} catch (Exception e) {
log.error("Cannot load persons", e);
return null;
}
}
private void loadContractPersonEditDTO(Integer personId, Integer contractId, ModelMap model) {
if (log.isDebugEnabled()) {
log.debug("Requested person.id=" + personId);
}
ContractPersonEditDTO cpEditDTO = null;
try {
if (personId != null) {
ContractPersonCriteria cpCriteria = new ContractPersonCriteria();
cpCriteria.setContractId(contractId);
cpCriteria.setPersonId(personId);
List<ContractPerson> cps = contractPersonService.findContractPersons(cpCriteria, null, Integer.valueOf(1));
cpEditDTO = new ContractPersonEditDTO(DataAccessUtils.singleResult(cps));
} else {
ContractPerson ct = new ContractPerson();
if (contractId != null) {
ct.setContract(contractService.findContract(contractId));
}
cpEditDTO = new ContractPersonEditDTO(ct);
}
model.addAttribute(CONTRACT_PERSON_EDIT_DTO_MODEL_KEY, cpEditDTO);
} catch (Exception e) {
log.error("Cannot load contract person with person.id: " + personId, e);
model.addAttribute(CONTRACT_PERSON_EDIT_DTO_MODEL_KEY, cpEditDTO);
WebUtils.addGlobalError(model, CONTRACT_PERSON_EDIT_DTO_MODEL_KEY, "error.load.contract.person");
}
if (log.isDebugEnabled()) {
log.debug("Loaded contractPersonEditDTO: " + cpEditDTO);
}
}
/**
* Handles all GET requests. Binds loaded {@link ContractPersonEditDTO} entity with the key "contractPersonEditDTO" into a model.
*
* @param contractPersonId
* key of a {@link ContractPersonEditDTO} to view/edit
* @param model
* @return
*/
@RequestMapping(value = "", method = RequestMethod.GET)
public String view(@RequestParam(value = "personId", required = false) Integer personId, @RequestParam(value = CONTRACT_ID_PARAM_KEY, required = false) Integer contractId, ModelMap model) {
loadContractPersonEditDTO(personId, contractId, model);
return "contracts/contractPersonEdit";
}
/**
* Handles POST requests for saving edited {@link ContractPersonEditDTO} instance.
*
* @param contractPersonEditDTO
* @param bindingResult
* @return
*/
@RequestMapping(value = "", method = RequestMethod.POST, params = "save")
public String save(@Valid @ModelAttribute(CONTRACT_PERSON_EDIT_DTO_MODEL_KEY) ContractPersonEditDTO contractPersonEditDTO, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
if (log.isDebugEnabled()) {
log.debug("ContractPersonEditDTO to save: " + contractPersonEditDTO);
}
if (!bindingResult.hasErrors()) {
try {
ContractPerson ct = contractPersonEditDTO.getContractPerson();
if (ct.getId() == null) {
ct.setPerson(personService.findPerson(contractPersonEditDTO.getPersonId()));
}
ct = contractPersonService.saveContractPerson(ct);
if (log.isDebugEnabled()) {
log.debug("Saved contract person: " + ct);
}
redirectAttributes.addAttribute(CONTRACT_ID_PARAM_KEY, ct.getContract().getId());
return "redirect:/contracts/overview";
} catch (ContractPersonServiceException e) {
switch (e.getReason()) {
case NONUNIQUE_CONTRACT_PERSON:
bindingResult.reject("error.save.contract.person.nonunique");
break;
case CONTRACT_PERSON_MODIFICATION:
bindingResult.reject("error.save.contract.person.modified");
break;
default:
log.warn("Unsupported reason: " + e);
bindingResult.reject("error.save.contract.person");
break;
}
} catch (Exception e) {
log.error("Cannot save ContractPersonEditDTO: " + contractPersonEditDTO, e);
bindingResult.reject("error.save.contract.person");
}
} else {
bindingResult.reject("error.save.contract.person.validation");
}
return "contracts/contractPersonEdit";
}
/**
* Handle POST requests for deleting {@link ContractPersonEditDTO} instance.
*
* @param contractPersonEditDTO
* @param bindingResult
* @return
*/
@RequestMapping(value = "", method = RequestMethod.POST, params = "delete")
public String delete(@ModelAttribute(CONTRACT_PERSON_EDIT_DTO_MODEL_KEY) ContractPersonEditDTO contractPersonEditDTO, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
if (log.isDebugEnabled()) {
log.debug("ContractPersonEditDTO to delete: " + contractPersonEditDTO);
}
try {
ContractPerson ct = contractPersonService.deleteContractPerson(contractPersonEditDTO.getContractPerson().getId());
if (log.isDebugEnabled()) {
log.debug("Deleted ContractPerson: " + ct);
}
redirectAttributes.addAttribute(CONTRACT_ID_PARAM_KEY, ct.getContract().getId());
return "redirect:/contracts/overview";
} catch (ContractPersonServiceException e) {
log.warn("Unsupported cause: " + e);
bindingResult.reject("error.delete.contract.person");
} catch (Exception e) {
log.error("Cannot delete ContractPersonEditDTO: " + contractPersonEditDTO, e);
bindingResult.reject("error.delete.contract.person");
}
return "contracts/contractPersonEdit";
}
}
| CIT-VSB-TUO/ResBill | resbill/src/main/java/cz/vsb/resbill/web/contracts/ContractPersonEditController.java | Java | bsd-3-clause | 7,614 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAudio.Wave;
using Blaze.SoundPlayer.Sounds;
namespace Blaze.SoundPlayer.WaveProviders
{
internal class SimpleSoundProvider : WaveProvider32, ISoundProvider
{
int sample;
SimpleSound mSound;
public SimpleSoundProvider(SimpleSound sound)
{
mSound = sound;
AmplitudeMultiplier = 1;// WaveProviderCommon.DefaultAmplitude;
}
public int Resolution
{
get;
private set;
}
public float Frequency
{
get;
set;
}
public float AmplitudeMultiplier
{
get;
set;
}
public override int Read(float[] buffer, int offset, int sampleCount)
{
int sampleRate = WaveFormat.SampleRate;
for (int n = 0; n < sampleCount; n++)
{
buffer[n + offset] = (AmplitudeMultiplier * mSound.Get(sampleRate, sample, Frequency));
sample++;
}
return sampleCount;
}
}
}
| GKBelmonte/SoundPlayer | Blaze.SoundPlayer/WaveProviders/SimpleSoundProvider.cs | C# | bsd-3-clause | 1,241 |
/*
* Copyright (c) 2008-2013, Matthias Mann
*
* 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 Matthias Mann nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package de.matthiasmann.twl.textarea;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Data model for the TextArea widget.
*
* @author Matthias Mann
*/
public interface TextAreaModel extends Iterable<TextAreaModel.Element> {
public enum HAlignment {
LEFT, RIGHT, CENTER, JUSTIFY
}
public enum Display {
INLINE, BLOCK
}
public enum VAlignment {
TOP, MIDDLE, BOTTOM, FILL
}
public enum Clear {
NONE, LEFT, RIGHT, BOTH
}
public enum FloatPosition {
NONE, LEFT, RIGHT
}
public abstract class Element {
private Style style;
protected Element(Style style) {
notNull(style, "style");
this.style = style;
}
/**
* Returns the style associated with this element
*
* @return the style associated with this element
*/
public Style getStyle() {
return style;
}
/**
* Replaces the style associated with this element. This method does not
* cause the model callback to be fired.
*
* @param style
* the new style. Must not be null.
*/
public void setStyle(Style style) {
notNull(style, "style");
this.style = style;
}
static void notNull(Object o, String name) {
if (o == null) {
throw new NullPointerException(name);
}
}
}
public class LineBreakElement extends Element {
public LineBreakElement(Style style) {
super(style);
}
};
public class TextElement extends Element {
private String text;
public TextElement(Style style, String text) {
super(style);
notNull(text, "text");
this.text = text;
}
/**
* Returns ths text.
*
* @return the text.
*/
public String getText() {
return text;
}
/**
* Replaces the text of this element. This method does not cause the
* model callback to be fired.
*
* @param text
* the new text. Must not be null.
*/
public void setText(String text) {
notNull(text, "text");
this.text = text;
}
}
public class ImageElement extends Element {
private final String imageName;
private final String tooltip;
public ImageElement(Style style, String imageName, String tooltip) {
super(style);
this.imageName = imageName;
this.tooltip = tooltip;
}
public ImageElement(Style style, String imageName) {
this(style, imageName, null);
}
/**
* Returns the image name for this image element.
*
* @return the image name for this image element.
*/
public String getImageName() {
return imageName;
}
/**
* Returns the tooltip or null for this image.
*
* @return the tooltip or null for this image. Can be null.
*/
public String getToolTip() {
return tooltip;
}
}
public class WidgetElement extends Element {
private final String widgetName;
private final String widgetParam;
public WidgetElement(Style style, String widgetName, String widgetParam) {
super(style);
this.widgetName = widgetName;
this.widgetParam = widgetParam;
}
public String getWidgetName() {
return widgetName;
}
public String getWidgetParam() {
return widgetParam;
}
}
public class ContainerElement extends Element implements Iterable<Element> {
protected final ArrayList<Element> children;
public ContainerElement(Style style) {
super(style);
this.children = new ArrayList<Element>();
}
public Iterator<Element> iterator() {
return children.iterator();
}
public Element getElement(int index) {
return children.get(index);
}
public int getNumElements() {
return children.size();
}
public void add(Element element) {
this.children.add(element);
}
}
public class ParagraphElement extends ContainerElement {
public ParagraphElement(Style style) {
super(style);
}
}
public class LinkElement extends ContainerElement {
private String href;
public LinkElement(Style style, String href) {
super(style);
this.href = href;
}
/**
* Returns the href of the link.
*
* @return the href of the link. Can be null.
*/
public String getHREF() {
return href;
}
/**
* Replaces the href of this link. This method does not cause the model
* callback to be fired.
*
* @param href
* the new href of the link, can be null.
*/
public void setHREF(String href) {
this.href = href;
}
}
/**
* A list item in an unordered list
*/
public class ListElement extends ContainerElement {
public ListElement(Style style) {
super(style);
}
}
/**
* An ordered list. All contained elements are treated as list items.
*/
public class OrderedListElement extends ContainerElement {
private final int start;
public OrderedListElement(Style style, int start) {
super(style);
this.start = start;
}
public int getStart() {
return start;
}
}
public class BlockElement extends ContainerElement {
public BlockElement(Style style) {
super(style);
}
}
public class TableCellElement extends ContainerElement {
private final int colspan;
public TableCellElement(Style style) {
this(style, 1);
}
public TableCellElement(Style style, int colspan) {
super(style);
this.colspan = colspan;
}
public int getColspan() {
return colspan;
}
}
public class TableElement extends Element {
private final int numColumns;
private final int numRows;
private final int cellSpacing;
private final int cellPadding;
private final TableCellElement[] cells;
private final Style[] rowStyles;
public TableElement(Style style, int numColumns, int numRows,
int cellSpacing, int cellPadding) {
super(style);
if (numColumns < 0) {
throw new IllegalArgumentException("numColumns");
}
if (numRows < 0) {
throw new IllegalArgumentException("numRows");
}
this.numColumns = numColumns;
this.numRows = numRows;
this.cellSpacing = cellSpacing;
this.cellPadding = cellPadding;
this.cells = new TableCellElement[numRows * numColumns];
this.rowStyles = new Style[numRows];
}
public int getNumColumns() {
return numColumns;
}
public int getNumRows() {
return numRows;
}
public int getCellPadding() {
return cellPadding;
}
public int getCellSpacing() {
return cellSpacing;
}
public TableCellElement getCell(int row, int column) {
if (column < 0 || column >= numColumns) {
throw new IndexOutOfBoundsException("column");
}
if (row < 0 || row >= numRows) {
throw new IndexOutOfBoundsException("row");
}
return cells[row * numColumns + column];
}
public Style getRowStyle(int row) {
return rowStyles[row];
}
public void setCell(int row, int column, TableCellElement cell) {
if (column < 0 || column >= numColumns) {
throw new IndexOutOfBoundsException("column");
}
if (row < 0 || row >= numRows) {
throw new IndexOutOfBoundsException("row");
}
cells[row * numColumns + column] = cell;
}
public void setRowStyle(int row, Style style) {
rowStyles[row] = style;
}
}
/**
* Adds a model change callback which is called when the model is modified.
*
* @param cb
* the callback - must not be null.
*/
public void addCallback(Runnable cb);
/**
* Removes the specific callback.
*
* @param cb
* the callback that should be removed.
*/
public void removeCallback(Runnable cb);
}
| ShadowLordAlpha/TWL | src/main/java/de/matthiasmann/twl/textarea/TextAreaModel.java | Java | bsd-3-clause | 8,925 |
# -*- coding:utf-8 -*-
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
from unittest import mock, skipIf
import django
import pytest
from django.core.management import CommandError, call_command
from django.db.utils import ConnectionHandler
from django.test import SimpleTestCase
from django.utils.six.moves import StringIO
# Can't use @override_settings to swap out DATABASES, instead just mock.patch
# a new ConnectionHandler into the command module
command_connections = 'django_mysql.management.commands.dbparams.connections'
sqlite = ConnectionHandler({
'default': {'ENGINE': 'django.db.backends.sqlite3'}
})
full_db = ConnectionHandler({'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabase',
'USER': 'ausername',
'PASSWORD': 'apassword',
'HOST': 'ahost.example.com',
'PORT': '12345',
'OPTIONS': {
'read_default_file': '/tmp/defaults.cnf',
'ssl': {'ca': '/tmp/mysql.cert'}
}
}})
socket_db = ConnectionHandler({'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '/etc/mydb.sock',
}})
class DBParamsTests(SimpleTestCase):
@skipIf(django.VERSION[:2] >= (1, 10),
'argument parsing uses a fixed single argument in Django 1.10+')
def test_invalid_number_of_databases(self):
with pytest.raises(CommandError) as excinfo:
call_command('dbparams', 'default', 'default', skip_checks=True)
assert "more than one connection" in str(excinfo.value)
def test_invalid_database(self):
with pytest.raises(CommandError) as excinfo:
call_command('dbparams', 'nonexistent', skip_checks=True)
assert "does not exist" in str(excinfo.value)
def test_invalid_both(self):
with pytest.raises(CommandError):
call_command('dbparams', dsn=True, mysql=True, skip_checks=True)
@mock.patch(command_connections, sqlite)
def test_invalid_not_mysql(self):
with pytest.raises(CommandError) as excinfo:
call_command('dbparams', skip_checks=True)
assert "not a MySQL database connection" in str(excinfo.value)
@mock.patch(command_connections, full_db)
def test_mysql_full(self):
out = StringIO()
call_command('dbparams', stdout=out, skip_checks=True)
output = out.getvalue()
assert (
output ==
"--defaults-file=/tmp/defaults.cnf --user=ausername "
"--password=apassword --host=ahost.example.com --port=12345 "
"--ssl-ca=/tmp/mysql.cert mydatabase"
)
@mock.patch(command_connections, socket_db)
def test_mysql_socket(self):
out = StringIO()
call_command('dbparams', stdout=out, skip_checks=True)
output = out.getvalue()
assert output == "--socket=/etc/mydb.sock"
@mock.patch(command_connections, full_db)
def test_dsn_full(self):
out = StringIO()
err = StringIO()
call_command('dbparams', 'default', dsn=True,
stdout=out, stderr=err, skip_checks=True)
output = out.getvalue()
assert (
output ==
"F=/tmp/defaults.cnf,u=ausername,p=apassword,h=ahost.example.com,"
"P=12345,D=mydatabase"
)
errors = err.getvalue()
assert "SSL params can't be" in errors
@mock.patch(command_connections, socket_db)
def test_dsn_socket(self):
out = StringIO()
err = StringIO()
call_command('dbparams', dsn=True,
stdout=out, stderr=err, skip_checks=True)
output = out.getvalue()
assert output == 'S=/etc/mydb.sock'
errors = err.getvalue()
assert errors == ""
| nickmeharry/django-mysql | tests/testapp/management/commands/test_dbparams.py | Python | bsd-3-clause | 3,738 |
<?php
namespace app\components;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Country;
/**
* countryService represents the model behind the search form about `app\models\Country`.
*/
class countryService extends Country
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['code', 'name'], 'safe'],
[['population'], 'integer'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Country::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'population' => $this->population,
]);
$query->andFilterWhere(['like', 'code', $this->code])
->andFilterWhere(['like', 'name', $this->name]);
return $dataProvider;
}
}
| GarenGoh/yii | components/countryService.php | PHP | bsd-3-clause | 1,552 |
<?php
/**
* @version 0.0.0.1
*/
function callback($callback) {
$callback();
}
//输出: This is a anonymous function.<br />\n
//这里是直接定义一个匿名函数进行传递, 在以往的版本中, 这是不可用的.
//现在, 这种语法非常舒服, 和javascript语法基本一致, 之所以说基本呢, 需要继续向下看
//结论: 一个舒服的语法必然会受欢迎的.
$obj = (object) "Hello, everyone";
$callback = function () use ($obj) {
print "This is a closure use object, msg is: {$obj->scalar}. <br />\n";
};
$obj = (object) "Hello, everybody";
callback($callback);
echo $obj->toString();
| VampireMe/admin-9939-com | tests/Common_Test.php | PHP | bsd-3-clause | 634 |
# -*- coding: utf-8 -*-
"""
Django settings for djangocali-portal project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from __future__ import absolute_import, unicode_literals
import environ
ROOT_DIR = environ.Path(__file__) - 3 # (/a/b/myfile.py - 3 = /)
APPS_DIR = ROOT_DIR.path('djangocali-portal')
env = environ.Env()
environ.Env.read_env()
# APP CONFIGURATION
# ------------------------------------------------------------------------------
DJANGO_APPS = (
# Default Django apps:
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Useful template tags:
# 'django.contrib.humanize',
# Admin
'django.contrib.admin',
)
THIRD_PARTY_APPS = (
'crispy_forms', # Form layouts
'allauth', # registration
'allauth.account', # registration
'allauth.socialaccount', # registration
)
# Apps specific for this project go here.
LOCAL_APPS = (
'djangocali-portal.users', # custom users app
# Your stuff: custom apps go here
)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
# MIDDLEWARE CONFIGURATION
# ------------------------------------------------------------------------------
MIDDLEWARE_CLASSES = (
# Make sure djangosecure.middleware.SecurityMiddleware is listed first
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
# MIGRATIONS CONFIGURATION
# ------------------------------------------------------------------------------
MIGRATION_MODULES = {
'sites': 'djangocali-portal.contrib.sites.migrations'
}
# DEBUG
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = env.bool("DJANGO_DEBUG", False)
# FIXTURE CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS
FIXTURE_DIRS = (
str(APPS_DIR.path('fixtures')),
)
# EMAIL CONFIGURATION
# ------------------------------------------------------------------------------
EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend')
# MANAGER CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins
ADMINS = (
("""djangocali""", 'dev@swapps.co'),
)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers
MANAGERS = ADMINS
# DATABASE CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
# Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ
'default': env.db("DATABASE_URL", default="postgres:///djangocali-portal"),
}
DATABASES['default']['ATOMIC_REQUESTS'] = True
# GENERAL CONFIGURATION
# ------------------------------------------------------------------------------
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'UTC'
# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code
LANGUAGE_CODE = 'en-us'
# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
SITE_ID = 1
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
USE_I18N = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
USE_L10N = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
USE_TZ = True
# TEMPLATE CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#templates
TEMPLATES = [
{
# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
'DIRS': [
str(APPS_DIR.path('templates')),
],
'OPTIONS': {
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
'debug': DEBUG,
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders
# https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
],
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
# Your stuff: custom template context processors go here
],
},
},
]
# See: http://django-crispy-forms.readthedocs.org/en/latest/install.html#template-packs
CRISPY_TEMPLATE_PACK = 'bootstrap3'
# STATIC FILE CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = str(ROOT_DIR('staticfiles'))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = '/static/'
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = (
str(APPS_DIR.path('static')),
)
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
# MEDIA CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = str(APPS_DIR('media'))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = '/media/'
# URL Configuration
# ------------------------------------------------------------------------------
ROOT_URLCONF = 'config.urls'
# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = 'config.wsgi.application'
# AUTHENTICATION CONFIGURATION
# ------------------------------------------------------------------------------
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)
# Some really nice defaults
ACCOUNT_AUTHENTICATION_METHOD = 'username'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
# Custom user app defaults
# Select the correct user model
AUTH_USER_MODEL = 'users.User'
LOGIN_REDIRECT_URL = 'users:redirect'
LOGIN_URL = 'account_login'
# SLUGLIFIER
AUTOSLUG_SLUGIFY_FUNCTION = 'slugify.slugify'
# LOGGING CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
########## CELERY
INSTALLED_APPS += ('djangocali-portal.taskapp.celery.CeleryConfig',)
# if you are not using the django database broker (e.g. rabbitmq, redis, memcached), you can remove the next line.
INSTALLED_APPS += ('kombu.transport.django',)
BROKER_URL = env("CELERY_BROKER_URL", default='django://')
########## END CELERY
# Your common stuff: Below this line define 3rd party library settings
| Swappsco/portal | config/settings/common.py | Python | bsd-3-clause | 9,483 |
// Copyright (c) 2010 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.
function onCursor()
{
var cursor = event.target.result;
if (cursor === null) {
debug('Reached end of object cursor.');
if (!gotObjectThroughCursor) {
fail('Did not get object through cursor.');
return;
}
done();
return;
}
debug('Got object through cursor.');
shouldBe('event.target.result.key', '55');
shouldBe('event.target.result.value.aValue', '"foo"');
gotObjectThroughCursor = true;
cursor.continue();
}
function onKeyCursor()
{
var cursor = event.target.result;
if (cursor === null) {
debug('Reached end of key cursor.');
if (!gotKeyThroughCursor) {
fail('Did not get key through cursor.');
return;
}
var request = index.openCursor(IDBKeyRange.only(55));
request.onsuccess = onCursor;
request.onerror = unexpectedErrorCallback;
gotObjectThroughCursor = false;
return;
}
debug('Got key through cursor.');
shouldBe('event.target.result.key', '55');
shouldBe('event.target.result.primaryKey', '1');
gotKeyThroughCursor = true;
cursor.continue();
}
function getSuccess()
{
debug('Successfully got object through key in index.');
shouldBe('event.target.result.aKey', '55');
shouldBe('event.target.result.aValue', '"foo"');
var request = index.openKeyCursor(IDBKeyRange.only(55));
request.onsuccess = onKeyCursor;
request.onerror = unexpectedErrorCallback;
gotKeyThroughCursor = false;
}
function getKeySuccess()
{
debug('Successfully got key.');
shouldBe('event.target.result', '1');
var request = index.get(55);
request.onsuccess = getSuccess;
request.onerror = unexpectedErrorCallback;
}
function moreDataAdded()
{
debug('Successfully added more data.');
var request = index.getKey(55);
request.onsuccess = getKeySuccess;
request.onerror = unexpectedErrorCallback;
}
function indexErrorExpected()
{
debug('Existing index triggered on error as expected.');
var request = objectStore.put({'aKey': 55, 'aValue': 'foo'}, 1);
request.onsuccess = moreDataAdded;
request.onerror = unexpectedErrorCallback;
}
function indexSuccess()
{
debug('Index created successfully.');
shouldBe("index.name", "'myIndex'");
shouldBe("index.objectStore.name", "'test'");
shouldBe("index.keyPath", "'aKey'");
shouldBe("index.unique", "true");
try {
request = objectStore.createIndex('myIndex', 'aKey', {unique: true});
fail('Re-creating an index must throw an exception');
} catch (e) {
indexErrorExpected();
}
}
function createIndex(expect_error)
{
debug('Creating an index.');
try {
window.index = objectStore.createIndex('myIndex', 'aKey', {unique: true});
indexSuccess();
} catch (e) {
unexpectedErrorCallback();
}
}
function dataAddedSuccess()
{
debug('Data added');
createIndex(false);
}
function populateObjectStore()
{
debug('Populating object store');
deleteAllObjectStores(db);
window.objectStore = db.createObjectStore('test');
var myValue = {'aKey': 21, 'aValue': '!42'};
var request = objectStore.add(myValue, 0);
request.onsuccess = dataAddedSuccess;
request.onerror = unexpectedErrorCallback;
}
function setVersion()
{
debug('setVersion');
window.db = event.target.result;
var request = db.setVersion('new version');
request.onsuccess = populateObjectStore;
request.onerror = unexpectedErrorCallback;
}
function test()
{
if ('webkitIndexedDB' in window) {
indexedDB = webkitIndexedDB;
IDBCursor = webkitIDBCursor;
IDBKeyRange = webkitIDBKeyRange;
IDBTransaction = webkitIDBTransaction;
}
debug('Connecting to indexedDB');
var request = indexedDB.open('name');
request.onsuccess = setVersion;
request.onerror = unexpectedErrorCallback;
}
| aYukiSekiguchi/ACCESS-Chromium | chrome/test/data/indexeddb/index_test.js | JavaScript | bsd-3-clause | 3,877 |
# -*- coding: utf-8 -*-
#
# Smisk documentation build configuration file, created by
# sphinx-quickstart on Sun Oct 26 20:24:33 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed automatically).
#
# All configuration values have a default value; values that are commented out
# serve to show the default value.
import sys, os
# If your extensions are in another directory, add it here. If the directory
# is relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
# Load release info
exec(open(os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', 'lib', 'tc', 'release.py'))).read())
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General substitutions.
project = 'tc'
copyright = 'Rasmus Andersson'
# The default replacements for |version| and |release|, also used in various
# other places throughout the built documents.
#
# The short X.Y version.
version = __version__
# The full version, including alpha/beta/rc tags.
release = version
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directories, that shouldn't be searched
# for source files.
#exclude_dirs = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'trac'
#todo_include_todos = True
# Options for HTML output
# -----------------------
# The style sheet to use for HTML and HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
# given in html_static_path.
html_style = 'screen.css'
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (within the static path) to place at the top of
# the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, the reST sources are included in the HTML build as _sources/<name>.
#html_copy_source = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'tcdoc'
# Options for LaTeX output
# ------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
latex_documents = [
('index', 'tc.tex', 'tc documentation',
'Rasmus Andersson', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
| rsms/tc | docs/source/conf.py | Python | bsd-3-clause | 5,778 |
package unit;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import bio.terra.cli.serialization.userfacing.UFClonedResource;
import bio.terra.cli.serialization.userfacing.UFClonedWorkspace;
import bio.terra.cli.serialization.userfacing.UFResource;
import bio.terra.cli.serialization.userfacing.UFWorkspace;
import bio.terra.cli.serialization.userfacing.resource.UFBqDataset;
import bio.terra.cli.serialization.userfacing.resource.UFGcsBucket;
import bio.terra.cli.serialization.userfacing.resource.UFGitRepo;
import bio.terra.workspace.model.CloneResourceResult;
import bio.terra.workspace.model.StewardshipType;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.api.services.bigquery.model.DatasetReference;
import harness.TestCommand;
import harness.TestContext;
import harness.TestUser;
import harness.baseclasses.ClearContextUnit;
import harness.utils.Auth;
import harness.utils.ExternalBQDatasets;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Tag("unit")
public class CloneWorkspace extends ClearContextUnit {
private static final TestUser workspaceCreator = TestUser.chooseTestUserWithSpendAccess();
private static final Logger logger = LoggerFactory.getLogger(CloneWorkspace.class);
private static final String GIT_REPO_HTTPS_URL =
"https://github.com/DataBiosphere/terra-workspace-manager.git";
private static final String GIT_REPO_REF_NAME = "gitrepo_ref";
private static final int SOURCE_RESOURCE_NUM = 5;
private static final int DESTINATION_RESOURCE_NUM = 4;
private static DatasetReference externalDataset;
private UFWorkspace sourceWorkspace;
private UFWorkspace destinationWorkspace;
@BeforeAll
public static void setupOnce() throws IOException {
TestContext.clearGlobalContextDir();
resetContext();
workspaceCreator.login(); // login needed to get user's proxy group
// create an external dataset to use for a referenced resource
externalDataset = ExternalBQDatasets.createDataset();
// grant the workspace creator access to the dataset
ExternalBQDatasets.grantReadAccess(
externalDataset, workspaceCreator.email, ExternalBQDatasets.IamMemberType.USER);
// grant the user's proxy group access to the dataset so that it will pass WSM's access check
// when adding it as a referenced resource
ExternalBQDatasets.grantReadAccess(
externalDataset, Auth.getProxyGroupEmail(), ExternalBQDatasets.IamMemberType.GROUP);
}
@AfterEach
public void cleanupEachTime() throws IOException {
workspaceCreator.login();
if (sourceWorkspace != null) {
TestCommand.Result result =
TestCommand.runCommand(
"workspace", "delete", "--quiet", "--workspace=" + sourceWorkspace.id);
sourceWorkspace = null;
if (0 != result.exitCode) {
logger.error("Failed to delete source workspace. exit code = {}", result.exitCode);
}
}
if (destinationWorkspace != null) {
TestCommand.Result result =
TestCommand.runCommand(
"workspace", "delete", "--quiet", "--workspace=" + destinationWorkspace.id);
destinationWorkspace = null;
if (0 != result.exitCode) {
logger.error("Failed to delete destination workspace. exit code = {}", result.exitCode);
}
}
}
@AfterAll
public static void cleanupOnce() throws IOException {
if (externalDataset != null) {
ExternalBQDatasets.deleteDataset(externalDataset);
externalDataset = null;
}
}
@Test
public void cloneWorkspace(TestInfo testInfo) throws Exception {
workspaceCreator.login();
// create a workspace
// `terra workspace create --format=json`
sourceWorkspace =
TestCommand.runAndParseCommandExpectSuccess(UFWorkspace.class, "workspace", "create");
// Add a bucket resource
UFGcsBucket sourceBucket =
TestCommand.runAndParseCommandExpectSuccess(
UFGcsBucket.class,
"resource",
"create",
"gcs-bucket",
"--name=" + "bucket_1",
"--bucket-name=" + UUID.randomUUID(),
"--cloning=COPY_RESOURCE");
// Add another bucket resource with COPY_NOTHING
UFGcsBucket copyNothingBucket =
TestCommand.runAndParseCommandExpectSuccess(
UFGcsBucket.class,
"resource",
"create",
"gcs-bucket",
"--name=" + "bucket_2",
"--bucket-name=" + UUID.randomUUID(),
"--cloning=COPY_NOTHING");
// Add a dataset resource
UFBqDataset sourceDataset =
TestCommand.runAndParseCommandExpectSuccess(
UFBqDataset.class,
"resource",
"create",
"bq-dataset",
"--name=dataset_1",
"--dataset-id=dataset_1",
"--description=The first dataset.",
"--cloning=COPY_RESOURCE");
UFBqDataset datasetReference =
TestCommand.runAndParseCommandExpectSuccess(
UFBqDataset.class,
"resource",
"add-ref",
"bq-dataset",
"--name=dataset_ref",
"--project-id=" + externalDataset.getProjectId(),
"--dataset-id=" + externalDataset.getDatasetId(),
"--cloning=COPY_REFERENCE");
UFGitRepo gitRepositoryReference =
TestCommand.runAndParseCommandExpectSuccess(
UFGitRepo.class,
"resource",
"add-ref",
"git-repo",
"--name=" + GIT_REPO_REF_NAME,
"--repo-url=" + GIT_REPO_HTTPS_URL,
"--cloning=COPY_REFERENCE");
// Clone the workspace
UFClonedWorkspace clonedWorkspace =
TestCommand.runAndParseCommandExpectSuccess(
UFClonedWorkspace.class,
"workspace",
"clone",
"--name=cloned_workspace",
"--description=A clone.");
assertEquals(
sourceWorkspace.id,
clonedWorkspace.sourceWorkspace.id,
"Correct source workspace ID for clone.");
destinationWorkspace = clonedWorkspace.destinationWorkspace;
assertThat(
"There are 5 cloned resources", clonedWorkspace.resources, hasSize(SOURCE_RESOURCE_NUM));
UFClonedResource bucketClonedResource =
getOrFail(
clonedWorkspace.resources.stream()
.filter(cr -> sourceBucket.id.equals(cr.sourceResource.id))
.findFirst());
assertEquals(
CloneResourceResult.SUCCEEDED, bucketClonedResource.result, "bucket clone succeeded");
assertNotNull(
bucketClonedResource.destinationResource, "Destination bucket resource was created");
UFClonedResource copyNothingBucketClonedResource =
getOrFail(
clonedWorkspace.resources.stream()
.filter(cr -> copyNothingBucket.id.equals(cr.sourceResource.id))
.findFirst());
assertEquals(
CloneResourceResult.SKIPPED,
copyNothingBucketClonedResource.result,
"COPY_NOTHING resource was skipped.");
assertNull(
copyNothingBucketClonedResource.destinationResource,
"Skipped resource has no destination resource.");
UFClonedResource datasetRefClonedResource =
getOrFail(
clonedWorkspace.resources.stream()
.filter(cr -> datasetReference.id.equals(cr.sourceResource.id))
.findFirst());
assertEquals(
CloneResourceResult.SUCCEEDED,
datasetRefClonedResource.result,
"Dataset reference clone succeeded.");
assertEquals(
StewardshipType.REFERENCED,
datasetRefClonedResource.destinationResource.stewardshipType,
"Dataset reference has correct stewardship type.");
UFClonedResource datasetClonedResource =
getOrFail(
clonedWorkspace.resources.stream()
.filter(cr -> sourceDataset.id.equals(cr.sourceResource.id))
.findFirst());
assertEquals(
CloneResourceResult.SUCCEEDED, datasetClonedResource.result, "Dataset clone succeeded.");
assertEquals(
"The first dataset.",
datasetClonedResource.destinationResource.description,
"Dataset description matches.");
UFClonedResource gitRepoClonedResource =
getOrFail(
clonedWorkspace.resources.stream()
.filter(cr -> gitRepositoryReference.id.equals(cr.sourceResource.id))
.findFirst());
assertEquals(
CloneResourceResult.SUCCEEDED, gitRepoClonedResource.result, "Git repo clone succeeded");
assertEquals(
GIT_REPO_REF_NAME,
gitRepoClonedResource.destinationResource.name,
"Resource type matches GIT_REPO");
// Switch to the new workspace from the clone
TestCommand.runCommandExpectSuccess(
"workspace", "set", "--id=" + clonedWorkspace.destinationWorkspace.id);
// Validate resources
List<UFResource> resources =
TestCommand.runAndParseCommandExpectSuccess(new TypeReference<>() {}, "resource", "list");
assertThat(
"Destination workspace has three resources.", resources, hasSize(DESTINATION_RESOURCE_NUM));
}
/**
* Check Optional's value is present and return it, or else fail an assertion.
*
* @param optional - Optional expression
* @param <T> - value type of optional
* @return - value of optional, if present
*/
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static <T> T getOrFail(Optional<T> optional) {
assertTrue(optional.isPresent(), "Optional value was empty.");
return optional.get();
}
}
| DataBiosphere/terra-cli | src/test/java/unit/CloneWorkspace.java | Java | bsd-3-clause | 10,217 |
<?php
/**
* Scripts for PHPUnit
*
* PHP version 5.3
*
* Copyright (c) 2010-2012 Shinya Ohyanagi, 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 Shinya Ohyanagi nor the names of his
* 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.
*
* @category Net
* @package Net\KyotoTycoon
* @version $id$
* @copyright (c) 2010-2012 Shinya Ohyanagi
* @author Shinya Ohyanagi <sohyanagi@gmail.com>
* @license New BSD License
*/
error_reporting(E_ALL | E_STRICT);
$src = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'src';
set_include_path(get_include_path()
. PATH_SEPARATOR . $src
);
require_once 'PHPUnit/Framework/TestCase.php';
| heavenshell/php-net-kyototycoon | tests/prepare.php | PHP | bsd-3-clause | 2,061 |
# -*- coding: utf-8 -*-
# /etl/database.py
"""Database module, including the SQLAlchemy database object and DB-related utilities."""
from sqlalchemy.orm import relationship
from .compat import basestring
from .extensions import db
# Alias common SQLAlchemy names
Column = db.Column
relationship = relationship
class CRUDMixin(object):
"""Mixin that adds convenience methods for CRUD (create, read, update, delete) operations."""
@classmethod
def create(cls, **kwargs):
"""Create a new record and save it the database."""
instance = cls(**kwargs)
return instance.save()
def update(self, commit=True, **kwargs):
"""Update specific fields of a record."""
for attr, value in kwargs.items():
setattr(self, attr, value)
return commit and self.save() or self
def save(self, commit=True):
"""Save the record."""
db.session.add(self)
if commit:
db.session.commit()
return self
def delete(self, commit=True):
"""Remove the record from the database."""
db.session.delete(self)
return commit and db.session.commit()
class Model(CRUDMixin, db.Model):
"""Base model class that includes CRUD convenience methods."""
__abstract__ = True
# From Mike Bayer's "Building the app" talk
# https://speakerdeck.com/zzzeek/building-the-app
class SurrogatePK(object):
"""A mixin that adds a surrogate integer 'primary key' column named ``id`` to any declarative-mapped class."""
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True)
@classmethod
def get_by_id(cls, record_id):
"""Get record by ID."""
if any(
(isinstance(record_id, basestring) and record_id.isdigit(),
isinstance(record_id, (int, float))),
):
return cls.query.get(int(record_id))
return None
def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
"""Column that adds primary key foreign key reference.
Usage: ::
category_id = reference_col('category')
category = relationship('Category', backref='categories')
"""
return db.Column(
db.ForeignKey('{0}.{1}'.format(tablename, pk_name)),
nullable=nullable, **kwargs)
| tomtom92/etl | etl/database.py | Python | bsd-3-clause | 2,331 |
<?php
namespace ZFDebug\Controller\Plugin\Debug\Plugin;
interface PluginInterface
{
/**
* Has to return html code for the menu tab
*
* @return string
*/
public function getTab();
/**
* Has to return html code for the content panel
*
* @return string
*/
public function getPanel();
/**
* Has to return a unique identifier for the specific plugin
*
* @return string
*/
public function getIdentifier();
/**
* Return the path to an icon
*
* @return string
*/
public function getIconData();
} | vox-tecnologia/ZFDebug | src/ZFDebug/Controller/Plugin/Debug/Plugin/PluginInterface.php | PHP | bsd-3-clause | 604 |
// 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 "sky/engine/config.h"
#include "sky/engine/core/dom/WeakNodeMap.h"
#include "sky/engine/core/dom/Node.h"
namespace blink {
#if !ENABLE(OILPAN)
class NodeToWeakNodeMaps {
public:
bool addedToMap(Node*, WeakNodeMap*);
bool removedFromMap(Node*, WeakNodeMap*);
void nodeDestroyed(Node*);
static NodeToWeakNodeMaps& instance()
{
DEFINE_STATIC_LOCAL(NodeToWeakNodeMaps, self, ());
return self;
}
private:
typedef Vector<WeakNodeMap*, 1> MapList;
typedef HashMap<Node*, OwnPtr<MapList> > NodeToMapList;
NodeToMapList m_nodeToMapList;
};
bool NodeToWeakNodeMaps::addedToMap(Node* node, WeakNodeMap* map)
{
NodeToMapList::AddResult result = m_nodeToMapList.add(node, nullptr);
if (result.isNewEntry)
result.storedValue->value = adoptPtr(new MapList());
result.storedValue->value->append(map);
return result.isNewEntry;
}
bool NodeToWeakNodeMaps::removedFromMap(Node* node, WeakNodeMap* map)
{
NodeToMapList::iterator it = m_nodeToMapList.find(node);
ASSERT(it != m_nodeToMapList.end());
MapList* mapList = it->value.get();
size_t position = mapList->find(map);
ASSERT(position != kNotFound);
mapList->remove(position);
if (mapList->size() == 0) {
m_nodeToMapList.remove(it);
return true;
}
return false;
}
void NodeToWeakNodeMaps::nodeDestroyed(Node* node)
{
OwnPtr<NodeToWeakNodeMaps::MapList> maps = m_nodeToMapList.take(node);
for (size_t i = 0; i < maps->size(); i++)
(*maps)[i]->nodeDestroyed(node);
}
WeakNodeMap::~WeakNodeMap()
{
NodeToWeakNodeMaps& allMaps = NodeToWeakNodeMaps::instance();
for (NodeToValue::iterator it = m_nodeToValue.begin(); it != m_nodeToValue.end(); ++it) {
Node* node = it->key;
if (allMaps.removedFromMap(node, this))
node->clearFlag(Node::HasWeakReferencesFlag);
}
}
void WeakNodeMap::put(Node* node, int value)
{
ASSERT(node && !m_nodeToValue.contains(node));
m_nodeToValue.set(node, value);
m_valueToNode.set(value, node);
NodeToWeakNodeMaps& maps = NodeToWeakNodeMaps::instance();
if (maps.addedToMap(node, this))
node->setFlag(Node::HasWeakReferencesFlag);
}
int WeakNodeMap::value(Node* node)
{
return m_nodeToValue.get(node);
}
Node* WeakNodeMap::node(int value)
{
return m_valueToNode.get(value);
}
void WeakNodeMap::nodeDestroyed(Node* node)
{
int value = m_nodeToValue.take(node);
ASSERT(value);
m_valueToNode.remove(value);
}
void WeakNodeMap::notifyNodeDestroyed(Node* node)
{
NodeToWeakNodeMaps::instance().nodeDestroyed(node);
}
#endif
}
| collinjackson/mojo | sky/engine/core/dom/WeakNodeMap.cpp | C++ | bsd-3-clause | 2,804 |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
from __future__ import division
import re
from ... import gloo
class Compiler(object):
"""
Compiler is used to convert Function and Variable instances into
ready-to-use GLSL code. This class handles name mangling to ensure that
there are no name collisions amongst global objects. The final name of
each object may be retrieved using ``Compiler.__getitem__(obj)``.
Accepts multiple root Functions as keyword arguments. ``compile()`` then
returns a dict of GLSL strings with the same keys.
Example::
# initialize with two main functions
compiler = Compiler(vert=v_func, frag=f_func)
# compile and extract shaders
code = compiler.compile()
v_code = code['vert']
f_code = code['frag']
# look up name of some object
name = compiler[obj]
"""
def __init__(self, **shaders):
# cache of compilation results for each function and variable
self._object_names = {} # {object: name}
self.shaders = shaders
def __getitem__(self, item):
"""
Return the name of the specified object, if it has been assigned one.
"""
return self._object_names[item]
def compile(self, pretty=True):
""" Compile all code and return a dict {name: code} where the keys
are determined by the keyword arguments passed to __init__().
Parameters
----------
pretty : bool
If True, use a slower method to mangle object names. This produces
GLSL that is more readable.
If False, then the output is mostly unreadable GLSL, but is about
10x faster to compile.
"""
# Authoritative mapping of {obj: name}
self._object_names = {}
#
# 1. collect list of dependencies for each shader
#
# maps {shader_name: [deps]}
self._shader_deps = {}
for shader_name, shader in self.shaders.items():
this_shader_deps = []
self._shader_deps[shader_name] = this_shader_deps
dep_set = set()
for dep in shader.dependencies(sort=True):
# visit each object no more than once per shader
if dep.name is None or dep in dep_set:
continue
this_shader_deps.append(dep)
dep_set.add(dep)
#
# 2. Assign names to all objects.
#
if pretty:
self._rename_objects_pretty()
else:
self._rename_objects_fast()
#
# 3. Now we have a complete namespace; concatenate all definitions
# together in topological order.
#
compiled = {}
obj_names = self._object_names
for shader_name, shader in self.shaders.items():
code = []
for dep in self._shader_deps[shader_name]:
dep_code = dep.definition(obj_names)
if dep_code is not None:
# strip out version pragma if present;
regex = r'#version (\d+)'
m = re.search(regex, dep_code)
if m is not None:
# check requested version
if m.group(1) != '120':
raise RuntimeError("Currently only GLSL #version "
"120 is supported.")
dep_code = re.sub(regex, '', dep_code)
code.append(dep_code)
compiled[shader_name] = '\n'.join(code)
self.code = compiled
return compiled
def _rename_objects_fast(self):
""" Rename all objects quickly to guaranteed-unique names using the
id() of each object.
This produces mostly unreadable GLSL, but is about 10x faster to
compile.
"""
for shader_name, deps in self._shader_deps.items():
for dep in deps:
name = dep.name
if name != 'main':
ext = '_%x' % id(dep)
name = name[:32-len(ext)] + ext
self._object_names[dep] = name
def _rename_objects_pretty(self):
""" Rename all objects like "name_1" to avoid conflicts. Objects are
only renamed if necessary.
This method produces more readable GLSL, but is rather slow.
"""
#
# 1. For each object, add its static names to the global namespace
# and make a list of the shaders used by the object.
#
# {name: obj} mapping for finding unique names
# initialize with reserved keywords.
self._global_ns = dict([(kwd, None) for kwd in gloo.util.KEYWORDS])
# functions are local per-shader
self._shader_ns = dict([(shader, {}) for shader in self.shaders])
# for each object, keep a list of shaders the object appears in
obj_shaders = {}
for shader_name, deps in self._shader_deps.items():
for dep in deps:
# Add static names to namespace
for name in dep.static_names():
self._global_ns[name] = None
obj_shaders.setdefault(dep, []).append(shader_name)
#
# 2. Assign new object names
#
name_index = {}
for obj, shaders in obj_shaders.items():
name = obj.name
if self._name_available(obj, name, shaders):
# hooray, we get to keep this name
self._assign_name(obj, name, shaders)
else:
# boo, find a new name
while True:
index = name_index.get(name, 0) + 1
name_index[name] = index
ext = '_%d' % index
new_name = name[:32-len(ext)] + ext
if self._name_available(obj, new_name, shaders):
self._assign_name(obj, new_name, shaders)
break
def _is_global(self, obj):
""" Return True if *obj* should be declared in the global namespace.
Some objects need to be declared only in per-shader namespaces:
functions, static variables, and const variables may all be given
different definitions in each shader.
"""
# todo: right now we assume all Variables are global, and all
# Functions are local. Is this actually correct? Are there any
# global functions? Are there any local variables?
from .variable import Variable
return isinstance(obj, Variable)
def _name_available(self, obj, name, shaders):
""" Return True if *name* is available for *obj* in *shaders*.
"""
if name in self._global_ns:
return False
shaders = self.shaders if self._is_global(obj) else shaders
for shader in shaders:
if name in self._shader_ns[shader]:
return False
return True
def _assign_name(self, obj, name, shaders):
""" Assign *name* to *obj* in *shaders*.
"""
if self._is_global(obj):
assert name not in self._global_ns
self._global_ns[name] = obj
else:
for shader in shaders:
ns = self._shader_ns[shader]
assert name not in ns
ns[name] = obj
self._object_names[obj] = name
| hronoses/vispy | vispy/visuals/shaders/compiler.py | Python | bsd-3-clause | 7,604 |
webpack = require('webpack')
const path = require('path');
var CompressionPlugin = require("compression-webpack-plugin");
module.exports = {
context: __dirname + '/source',
entry: {
javascript: './application.js',
html: './index.html'
},
loader: {
appSettings: {
env: "production"
},
},
output: {
path: __dirname + '/build',
filename: '/application.js'
},
resolve: {
root: __dirname,
extensions: ['', '.js'],
modulesDirectories: ['node_modules', 'source', 'source/images'],
fallback: __dirname
},
module: {
loaders: [
{
test: /\.css$/,
loaders: [
'style?sourceMap',
'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]'
]
},
{
test: /\.js$/,
loaders: ['babel-loader', 'eslint-loader'],
include: [new RegExp(path.join(__dirname, 'source')), new RegExp(path.join(__dirname, 'tests'))]
},
{
test: /\.html$/,
loader: 'file?name=[name].[ext]',
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
}
],
},
preLoaders: [
{
test: /\.js$/,
loaders: ['eslint'],
include: [new RegExp(path.join(__dirname, 'source'))]
}
],
eslint: {
failOnError: false,
failOnWarning: false
},
plugins: [
new webpack.ProvidePlugin({
'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch'
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.UglifyJsPlugin({
sourceMap: false,
compress: {
sequences: true,
dead_code: true,
conditionals: true,
booleans: true,
unused: true,
if_return: true,
join_vars: true,
drop_console: true
},
mangle: {
except: ['$super', '$', 'exports', 'require']
},
output: {
comments: false
}
}),
new CompressionPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.html$/,
minRatio: 0.8
})
]
};
| phorque/ac2-frontend | webpack-prod.config.js | JavaScript | bsd-3-clause | 2,933 |
/*================================================================================
Copyright (c) 2008 VMware, 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 VMware, 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 VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25.mo;
import java.rmi.RemoteException;
import com.vmware.vim25.*;
/**
* The managed object class corresponding to the one defined in VI SDK API reference.
* @author Steve JIN (sjin@vmware.com)
*/
public class HostDatastoreBrowser extends ManagedObject
{
public HostDatastoreBrowser(ServerConnection serverConnection, ManagedObjectReference mor)
{
super(serverConnection, mor);
}
public Datastore[] getDatastores()
{
return getDatastores("datastore");
}
public FileQuery[] getSupportedType()
{
return (FileQuery[]) this.getCurrentProperty("supportedType");
}
/**
* @deprecated, use FileManager.DeleteDatastoreFile_Task
* @throws RemoteException
* @throws RuntimeFault
* @throws InvalidDatastore
* @throws FileFault
* @
*/
public void deleteFile(String datastorePath) throws FileFault, InvalidDatastore, RuntimeFault, RemoteException
{
getVimService().deleteFile(getMOR(), datastorePath);
}
public Task searchDatastore_Task(String datastorePath, HostDatastoreBrowserSearchSpec searchSpec) throws FileFault, InvalidDatastore, RuntimeFault, RemoteException
{
return new Task(getServerConnection(),
getVimService().searchDatastore_Task(getMOR(), datastorePath, searchSpec));
}
public Task searchDatastoreSubFolders_Task(String datastorePath, HostDatastoreBrowserSearchSpec searchSpec) throws FileFault, InvalidDatastore, RuntimeFault, RemoteException
{
return new Task(getServerConnection(),
getVimService().searchDatastoreSubFolders_Task(getMOR(), datastorePath, searchSpec));
}
}
| mikem2005/vijava | src/com/vmware/vim25/mo/HostDatastoreBrowser.java | Java | bsd-3-clause | 3,309 |
/**
* echarts图表类:仪表盘
*
* @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
* @author Kener (@Kener-林峰, linzhifeng@baidu.com)
*
*/
define(function (require) {
var ComponentBase = require('../component/base');
var ChartBase = require('./base');
// 图形依赖
var GaugePointerShape = require('../util/shape/GaugePointer');
var TextShape = require('zrender/shape/Text');
var LineShape = require('zrender/shape/Line');
var RectangleShape = require('zrender/shape/Rectangle');
var CircleShape = require('zrender/shape/Circle');
var SectorShape = require('zrender/shape/Sector');
var ecConfig = require('../config');
var ecData = require('../util/ecData');
var zrUtil = require('zrender/tool/util');
/**
* 构造函数
* @param {Object} messageCenter echart消息中心
* @param {ZRender} zr zrender实例
* @param {Object} series 数据
* @param {Object} component 组件
*/
function Gauge(ecTheme, messageCenter, zr, option, myChart){
// 基类
ComponentBase.call(this, ecTheme, messageCenter, zr, option, myChart);
// 图表基类
ChartBase.call(this);
this.refresh(option);
}
Gauge.prototype = {
type : ecConfig.CHART_TYPE_GAUGE,
/**
* 绘制图形
*/
_buildShape : function () {
var series = this.series;
// 复用参数索引
this._paramsMap = {};
for (var i = 0, l = series.length; i < l; i++) {
if (series[i].type == ecConfig.CHART_TYPE_GAUGE) {
series[i] = this.reformOption(series[i]);
this._buildSingleGauge(i);
this.buildMark(i);
}
}
this.addShapeList();
},
/**
* 构建单个仪表盘
*
* @param {number} seriesIndex 系列索引
*/
_buildSingleGauge : function (seriesIndex) {
var serie = this.series[seriesIndex];
this._paramsMap[seriesIndex] = {
center : this.parseCenter(this.zr, serie.center),
radius : this.parseRadius(this.zr, serie.radius),
startAngle : serie.startAngle.toFixed(2) - 0,
endAngle : serie.endAngle.toFixed(2) - 0
};
this._paramsMap[seriesIndex].totalAngle = this._paramsMap[seriesIndex].startAngle
- this._paramsMap[seriesIndex].endAngle;
this._colorMap(seriesIndex);
this._buildAxisLine(seriesIndex);
this._buildSplitLine(seriesIndex);
this._buildAxisTick(seriesIndex);
this._buildAxisLabel(seriesIndex);
this._buildPointer(seriesIndex);
this._buildTitle(seriesIndex);
this._buildDetail(seriesIndex);
},
// 轴线
_buildAxisLine : function (seriesIndex) {
var serie = this.series[seriesIndex];
if (!serie.axisLine.show) {
return;
}
var min = serie.min;
var total = serie.max - min;
var params = this._paramsMap[seriesIndex];
var center = params.center;
var startAngle = params.startAngle;
var totalAngle = params.totalAngle;
var colorArray = params.colorArray;
var lineStyle = serie.axisLine.lineStyle;
var lineWidth = this.parsePercent(lineStyle.width, params.radius[1]);
var r = params.radius[1];
var r0 = r - lineWidth;
var sectorShape;
var lastAngle = startAngle;
var newAngle;
for (var i = 0, l = colorArray.length; i < l; i++) {
newAngle = startAngle - totalAngle * (colorArray[i][0] - min) / total;
sectorShape = this._getSector(
center, r0, r,
newAngle, // startAngle
lastAngle, // endAngle
colorArray[i][1], // color
lineStyle
);
lastAngle = newAngle;
sectorShape._animationAdd = 'r';
ecData.set(sectorShape, 'seriesIndex', seriesIndex);
ecData.set(sectorShape, 'dataIndex', i);
this.shapeList.push(sectorShape);
}
},
// 坐标轴分割线
_buildSplitLine : function (seriesIndex) {
var serie = this.series[seriesIndex];
if (!serie.splitLine.show) {
return;
}
var params = this._paramsMap[seriesIndex];
var splitNumber = serie.splitNumber;
var min = serie.min;
var total = serie.max - min;
var splitLine = serie.splitLine;
var length = this.parsePercent(
splitLine.length, params.radius[1]
);
var lineStyle = splitLine.lineStyle;
var color = lineStyle.color;
var center = params.center;
var startAngle = params.startAngle * Math.PI / 180;
var totalAngle = params.totalAngle * Math.PI / 180;
var r = params.radius[1];
var r0 = r - length;
var angle;
var sinAngle;
var cosAngle;
for (var i = 0; i <= splitNumber; i++) {
angle = startAngle - totalAngle / splitNumber * i;
sinAngle = Math.sin(angle);
cosAngle = Math.cos(angle);
this.shapeList.push(new LineShape({
zlevel : this._zlevelBase + 1,
hoverable : false,
style : {
xStart : center[0] + cosAngle * r,
yStart : center[1] - sinAngle * r,
xEnd : center[0] + cosAngle * r0,
yEnd : center[1] - sinAngle * r0,
strokeColor : color == 'auto'
? this._getColor(seriesIndex, min + total / splitNumber * i)
: color,
lineType : lineStyle.type,
lineWidth : lineStyle.width,
shadowColor : lineStyle.shadowColor,
shadowBlur: lineStyle.shadowBlur,
shadowOffsetX: lineStyle.shadowOffsetX,
shadowOffsetY: lineStyle.shadowOffsetY
}
}));
}
},
// 小标记
_buildAxisTick : function (seriesIndex) {
var serie = this.series[seriesIndex];
if (!serie.axisTick.show) {
return;
}
var params = this._paramsMap[seriesIndex];
var splitNumber = serie.splitNumber;
var min = serie.min;
var total = serie.max - min;
var axisTick = serie.axisTick;
var tickSplit = axisTick.splitNumber;
var length = this.parsePercent(
axisTick.length, params.radius[1]
);
var lineStyle = axisTick.lineStyle;
var color = lineStyle.color;
var center = params.center;
var startAngle = params.startAngle * Math.PI / 180;
var totalAngle = params.totalAngle * Math.PI / 180;
var r = params.radius[1];
var r0 = r - length;
var angle;
var sinAngle;
var cosAngle;
for (var i = 0, l = splitNumber * tickSplit; i <= l; i++) {
if (i % tickSplit === 0) { // 同splitLine
continue;
}
angle = startAngle - totalAngle / l * i;
sinAngle = Math.sin(angle);
cosAngle = Math.cos(angle);
this.shapeList.push(new LineShape({
zlevel : this._zlevelBase + 1,
hoverable : false,
style : {
xStart : center[0] + cosAngle * r,
yStart : center[1] - sinAngle * r,
xEnd : center[0] + cosAngle * r0,
yEnd : center[1] - sinAngle * r0,
strokeColor : color == 'auto'
? this._getColor(seriesIndex, min + total / l * i)
: color,
lineType : lineStyle.type,
lineWidth : lineStyle.width,
shadowColor : lineStyle.shadowColor,
shadowBlur: lineStyle.shadowBlur,
shadowOffsetX: lineStyle.shadowOffsetX,
shadowOffsetY: lineStyle.shadowOffsetY
}
}));
}
},
// 坐标轴文本
_buildAxisLabel : function (seriesIndex) {
var serie = this.series[seriesIndex];
if (!serie.axisLabel.show) {
return;
}
var splitNumber = serie.splitNumber;
var min = serie.min;
var total = serie.max - min;
var textStyle = serie.axisLabel.textStyle;
var textFont = this.getFont(textStyle);
var color = textStyle.color;
var params = this._paramsMap[seriesIndex];
var center = params.center;
var startAngle = params.startAngle;
var totalAngle = params.totalAngle;
var r0 = params.radius[1]
- this.parsePercent(
serie.splitLine.length, params.radius[1]
) - 10;
var angle;
var sinAngle;
var cosAngle;
var value;
for (var i = 0; i <= splitNumber; i++) {
value = min + total / splitNumber * i;
angle = startAngle - totalAngle / splitNumber * i;
sinAngle = Math.sin(angle * Math.PI / 180);
cosAngle = Math.cos(angle * Math.PI / 180);
angle = (angle + 360) % 360;
this.shapeList.push(new TextShape({
zlevel : this._zlevelBase + 1,
hoverable : false,
style : {
x : center[0] + cosAngle * r0,
y : center[1] - sinAngle * r0,
color : color == 'auto' ? this._getColor(seriesIndex, value) : color,
text : this._getLabelText(serie.axisLabel.formatter, value),
textAlign : (angle >= 110 && angle <= 250)
? 'left'
: (angle <= 70 || angle >= 290)
? 'right'
: 'center',
textBaseline : (angle >= 10 && angle <= 170)
? 'top'
: (angle >= 190 && angle <= 350)
? 'bottom'
: 'middle',
textFont : textFont,
shadowColor : textStyle.shadowColor,
shadowBlur: textStyle.shadowBlur,
shadowOffsetX: textStyle.shadowOffsetX,
shadowOffsetY: textStyle.shadowOffsetY
}
}));
}
},
_buildPointer : function (seriesIndex) {
var serie = this.series[seriesIndex];
if (!serie.pointer.show) {
return;
}
var total = serie.max - serie.min;
var pointer = serie.pointer;
var params = this._paramsMap[seriesIndex];
var length = this.parsePercent(pointer.length, params.radius[1]);
var width = this.parsePercent(pointer.width, params.radius[1]);
var center = params.center;
var value = this._getValue(seriesIndex);
value = value < serie.max ? value : serie.max;
var angle = (params.startAngle - params.totalAngle / total * (value - serie.min)) * Math.PI / 180;
var color = pointer.color == 'auto'
? this._getColor(seriesIndex, value) : pointer.color;
var pointShape = new GaugePointerShape({
zlevel : this._zlevelBase + 1,
style : {
x : center[0],
y : center[1],
r : length,
startAngle : params.startAngle * Math.PI / 180,
angle : angle,
color : color,
width : width,
shadowColor : pointer.shadowColor,
shadowBlur: pointer.shadowBlur,
shadowOffsetX: pointer.shadowOffsetX,
shadowOffsetY: pointer.shadowOffsetY
},
highlightStyle : {
brushType : 'fill',
width : width > 2 ? 2 : (width / 2),
color : '#fff'
}
});
ecData.pack(
pointShape,
this.series[seriesIndex], seriesIndex,
this.series[seriesIndex].data[0], 0,
this.series[seriesIndex].data[0].name,
value
);
this.shapeList.push(pointShape);
this.shapeList.push(new CircleShape({
zlevel : this._zlevelBase + 2,
hoverable : false,
style : {
x : center[0],
y : center[1],
r : pointer.width / 2.5,
color : '#fff'
}
}));
},
_buildTitle : function(seriesIndex) {
var serie = this.series[seriesIndex];
if (!serie.title.show) {
return;
}
var data = serie.data[0];
var name = typeof data.name != 'undefined' ? data.name : '';
if (name !== '') {
var title = serie.title;
var offsetCenter = title.offsetCenter;
var textStyle = title.textStyle;
var textColor = textStyle.color;
var params = this._paramsMap[seriesIndex];
var x = params.center[0] + this.parsePercent(offsetCenter[0], params.radius[1]);
var y = params.center[1] + this.parsePercent(offsetCenter[1], params.radius[1]);
this.shapeList.push(new TextShape({
zlevel : this._zlevelBase
+ (Math.abs(x - params.center[0]) + Math.abs(y - params.center[1]))
< textStyle.fontSize * 2 ? 2 : 1,
hoverable : false,
style : {
x : x,
y : y,
color: textColor == 'auto' ? this._getColor(seriesIndex) : textColor,
text: name,
textAlign: 'center',
textFont : this.getFont(textStyle),
shadowColor : textStyle.shadowColor,
shadowBlur: textStyle.shadowBlur,
shadowOffsetX: textStyle.shadowOffsetX,
shadowOffsetY: textStyle.shadowOffsetY
}
}));
}
},
_buildDetail : function(seriesIndex) {
var serie = this.series[seriesIndex];
if (!serie.detail.show) {
return;
}
var detail = serie.detail;
var offsetCenter = detail.offsetCenter;
var color = detail.backgroundColor;
var textStyle = detail.textStyle;
var textColor = textStyle.color;
var params = this._paramsMap[seriesIndex];
var value = this._getValue(seriesIndex);
var x = params.center[0] - detail.width / 2
+ this.parsePercent(offsetCenter[0], params.radius[1]);
var y = params.center[1]
+ this.parsePercent(offsetCenter[1], params.radius[1]);
this.shapeList.push(new RectangleShape({
zlevel : this._zlevelBase
+ (Math.abs(x+detail.width/2 - params.center[0])
+ Math.abs(y+detail.height/2 - params.center[1]))
< textStyle.fontSize ? 2 : 1,
hoverable : false,
style : {
x : x,
y : y,
width : detail.width,
height : detail.height,
brushType: 'both',
color: color == 'auto' ? this._getColor(seriesIndex, value) : color,
lineWidth : detail.borderWidth,
strokeColor : detail.borderColor,
shadowColor : detail.shadowColor,
shadowBlur: detail.shadowBlur,
shadowOffsetX: detail.shadowOffsetX,
shadowOffsetY: detail.shadowOffsetY,
text: this._getLabelText(detail.formatter, value),
textFont: this.getFont(textStyle),
textPosition: 'inside',
textColor : textColor == 'auto' ? this._getColor(seriesIndex, value) : textColor
}
}));
},
_getValue : function(seriesIndex) {
var data = this.series[seriesIndex].data[0];
return typeof data.value != 'undefined' ? data.value : data;
},
/**
* 颜色索引
*/
_colorMap : function (seriesIndex) {
var serie = this.series[seriesIndex];
var min = serie.min;
var total = serie.max - min;
var color = serie.axisLine.lineStyle.color;
if (!(color instanceof Array)) {
color = [[1, color]];
}
var colorArray = [];
for (var i = 0, l = color.length; i < l; i++) {
colorArray.push([color[i][0] * total + min, color[i][1]]);
}
this._paramsMap[seriesIndex].colorArray = colorArray;
},
/**
* 自动颜色
*/
_getColor : function (seriesIndex, value) {
if (typeof value == 'undefined') {
value = this._getValue(seriesIndex);
}
var colorArray = this._paramsMap[seriesIndex].colorArray;
for (var i = 0, l = colorArray.length; i < l; i++) {
if (colorArray[i][0] >= value) {
return colorArray[i][1];
}
}
return colorArray[colorArray.length - 1][1];
},
/**
* 构建扇形
*/
_getSector : function (center, r0, r, startAngle, endAngle, color, lineStyle) {
return new SectorShape ({
zlevel : this._zlevelBase,
hoverable : false,
style : {
x : center[0], // 圆心横坐标
y : center[1], // 圆心纵坐标
r0 : r0, // 圆环内半径
r : r, // 圆环外半径
startAngle : startAngle,
endAngle : endAngle,
brushType : 'fill',
color : color,
shadowColor : lineStyle.shadowColor,
shadowBlur: lineStyle.shadowBlur,
shadowOffsetX: lineStyle.shadowOffsetX,
shadowOffsetY: lineStyle.shadowOffsetY
}
});
},
/**
* 根据lable.format计算label text
*/
_getLabelText : function (formatter, value) {
if (formatter) {
if (typeof formatter == 'function') {
return formatter(value);
}
else if (typeof formatter == 'string') {
return formatter.replace('{value}', value);
}
}
return value;
},
/**
* 刷新
*/
refresh : function (newOption) {
if (newOption) {
this.option = newOption;
this.series = newOption.series;
}
this.backupShapeList();
this._buildShape();
}
};
zrUtil.inherits(Gauge, ChartBase);
zrUtil.inherits(Gauge, ComponentBase);
// 图表注册
require('../chart').define('gauge', Gauge);
return Gauge;
}); | shaisxx/echarts | src/chart/gauge.js | JavaScript | bsd-3-clause | 21,902 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace Kooboo.CMS.Content.Models
{
/// <summary>
/// 可持久化的对象接口
///
/// </summary>
public interface IPersistable
{
/// <summary>
/// 是否为不完整对象
/// </summary>
/// <value>
/// <c>true</c> if this instance is dummy; otherwise, <c>false</c>.
/// </value>
bool IsDummy { get; }
/// <summary>
/// 在反序列化对象后会调用的初始化方法
/// </summary>
/// <param name="source">The source.</param>
void Init(IPersistable source);
/// <summary>
/// Called when [saved].
/// </summary>
void OnSaved();
/// <summary>
/// Called when [saving].
/// </summary>
void OnSaving();
}
}
| Epitomy/CMS | Kooboo.CMS/Kooboo.CMS.Content/Kooboo.CMS.Content/Models/IPersistable.cs | C# | bsd-3-clause | 933 |
// 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 "base/test/launcher/test_launcher.h"
#if defined(OS_POSIX)
#include <fcntl.h>
#endif
#include "base/at_exit.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/files/scoped_file.h"
#include "base/format_macros.h"
#include "base/hash.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/process/kill.h"
#include "base/process/launch.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringize_macros.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/launcher/test_results_tracker.h"
#include "base/test/sequenced_worker_pool_owner.h"
#include "base/test/test_switches.h"
#include "base/test/test_timeouts.h"
#include "base/threading/thread_checker.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#endif
namespace base {
// Launches a child process using |command_line|. If the child process is still
// running after |timeout|, it is terminated and |*was_timeout| is set to true.
// Returns exit code of the process.
int LaunchChildTestProcessWithOptions(const CommandLine& command_line,
const LaunchOptions& options,
bool use_job_objects,
base::TimeDelta timeout,
bool* was_timeout);
// See https://groups.google.com/a/chromium.org/d/msg/chromium-dev/nkdTP7sstSc/uT3FaE_sgkAJ .
using ::operator<<;
// The environment variable name for the total number of test shards.
const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
// The environment variable name for the test shard index.
const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
namespace {
// Global tag for test runs where the results are incomplete or unreliable
// for any reason, e.g. early exit because of too many broken tests.
const char kUnreliableResultsTag[] = "UNRELIABLE_RESULTS";
// Maximum time of no output after which we print list of processes still
// running. This deliberately doesn't use TestTimeouts (which is otherwise
// a recommended solution), because they can be increased. This would defeat
// the purpose of this timeout, which is 1) to avoid buildbot "no output for
// X seconds" timeout killing the process 2) help communicate status of
// the test launcher to people looking at the output (no output for a long
// time is mysterious and gives no info about what is happening) 3) help
// debugging in case the process hangs anyway.
const int kOutputTimeoutSeconds = 15;
// Limit of output snippet lines when printing to stdout.
// Avoids flooding the logs with amount of output that gums up
// the infrastructure.
const size_t kOutputSnippetLinesLimit = 5000;
// Set of live launch test processes with corresponding lock (it is allowed
// for callers to launch processes on different threads).
LazyInstance<std::map<ProcessHandle, CommandLine> > g_live_processes
= LAZY_INSTANCE_INITIALIZER;
LazyInstance<Lock> g_live_processes_lock = LAZY_INSTANCE_INITIALIZER;
#if defined(OS_POSIX)
// Self-pipe that makes it possible to do complex shutdown handling
// outside of the signal handler.
int g_shutdown_pipe[2] = { -1, -1 };
void ShutdownPipeSignalHandler(int signal) {
HANDLE_EINTR(write(g_shutdown_pipe[1], "q", 1));
}
void KillSpawnedTestProcesses() {
// Keep the lock until exiting the process to prevent further processes
// from being spawned.
AutoLock lock(g_live_processes_lock.Get());
fprintf(stdout,
"Sending SIGTERM to %" PRIuS " child processes... ",
g_live_processes.Get().size());
fflush(stdout);
for (std::map<ProcessHandle, CommandLine>::iterator i =
g_live_processes.Get().begin();
i != g_live_processes.Get().end();
++i) {
// Send the signal to entire process group.
kill((-1) * (i->first), SIGTERM);
}
fprintf(stdout,
"done.\nGiving processes a chance to terminate cleanly... ");
fflush(stdout);
PlatformThread::Sleep(TimeDelta::FromMilliseconds(500));
fprintf(stdout, "done.\n");
fflush(stdout);
fprintf(stdout,
"Sending SIGKILL to %" PRIuS " child processes... ",
g_live_processes.Get().size());
fflush(stdout);
for (std::map<ProcessHandle, CommandLine>::iterator i =
g_live_processes.Get().begin();
i != g_live_processes.Get().end();
++i) {
// Send the signal to entire process group.
kill((-1) * (i->first), SIGKILL);
}
fprintf(stdout, "done.\n");
fflush(stdout);
}
// I/O watcher for the reading end of the self-pipe above.
// Terminates any launched child processes and exits the process.
class SignalFDWatcher : public MessageLoopForIO::Watcher {
public:
SignalFDWatcher() {
}
virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE {
fprintf(stdout, "\nCaught signal. Killing spawned test processes...\n");
fflush(stdout);
KillSpawnedTestProcesses();
// The signal would normally kill the process, so exit now.
exit(1);
}
virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE {
NOTREACHED();
}
private:
DISALLOW_COPY_AND_ASSIGN(SignalFDWatcher);
};
#endif // defined(OS_POSIX)
// Parses the environment variable var as an Int32. If it is unset, returns
// true. If it is set, unsets it then converts it to Int32 before
// returning it in |result|. Returns true on success.
bool TakeInt32FromEnvironment(const char* const var, int32* result) {
scoped_ptr<Environment> env(Environment::Create());
std::string str_val;
if (!env->GetVar(var, &str_val))
return true;
if (!env->UnSetVar(var)) {
LOG(ERROR) << "Invalid environment: we could not unset " << var << ".\n";
return false;
}
if (!StringToInt(str_val, result)) {
LOG(ERROR) << "Invalid environment: " << var << " is not an integer.\n";
return false;
}
return true;
}
// Unsets the environment variable |name| and returns true on success.
// Also returns true if the variable just doesn't exist.
bool UnsetEnvironmentVariableIfExists(const std::string& name) {
scoped_ptr<Environment> env(Environment::Create());
std::string str_val;
if (!env->GetVar(name.c_str(), &str_val))
return true;
return env->UnSetVar(name.c_str());
}
// Returns true if bot mode has been requested, i.e. defaults optimized
// for continuous integration bots. This way developers don't have to remember
// special command-line flags.
bool BotModeEnabled() {
scoped_ptr<Environment> env(Environment::Create());
return CommandLine::ForCurrentProcess()->HasSwitch(
switches::kTestLauncherBotMode) ||
env->HasVar("CHROMIUM_TEST_LAUNCHER_BOT_MODE");
}
void RunCallback(
const TestLauncher::LaunchChildGTestProcessCallback& callback,
int exit_code,
const TimeDelta& elapsed_time,
bool was_timeout,
const std::string& output) {
callback.Run(exit_code, elapsed_time, was_timeout, output);
}
void DoLaunchChildTestProcess(
const CommandLine& command_line,
base::TimeDelta timeout,
bool use_job_objects,
bool redirect_stdio,
scoped_refptr<MessageLoopProxy> message_loop_proxy,
const TestLauncher::LaunchChildGTestProcessCallback& callback) {
TimeTicks start_time = TimeTicks::Now();
// Redirect child process output to a file.
base::FilePath output_file;
CHECK(base::CreateTemporaryFile(&output_file));
LaunchOptions options;
#if defined(OS_WIN)
win::ScopedHandle handle;
if (redirect_stdio) {
// Make the file handle inheritable by the child.
SECURITY_ATTRIBUTES sa_attr;
sa_attr.nLength = sizeof(SECURITY_ATTRIBUTES);
sa_attr.lpSecurityDescriptor = NULL;
sa_attr.bInheritHandle = TRUE;
handle.Set(CreateFile(output_file.value().c_str(),
GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_DELETE,
&sa_attr,
OPEN_EXISTING,
FILE_ATTRIBUTE_TEMPORARY,
NULL));
CHECK(handle.IsValid());
options.inherit_handles = true;
options.stdin_handle = INVALID_HANDLE_VALUE;
options.stdout_handle = handle.Get();
options.stderr_handle = handle.Get();
}
#elif defined(OS_POSIX)
options.new_process_group = true;
base::FileHandleMappingVector fds_mapping;
base::ScopedFD output_file_fd;
if (redirect_stdio) {
output_file_fd.reset(open(output_file.value().c_str(), O_RDWR));
CHECK(output_file_fd.is_valid());
fds_mapping.push_back(std::make_pair(output_file_fd.get(), STDOUT_FILENO));
fds_mapping.push_back(std::make_pair(output_file_fd.get(), STDERR_FILENO));
options.fds_to_remap = &fds_mapping;
}
#endif
bool was_timeout = false;
int exit_code = LaunchChildTestProcessWithOptions(
command_line, options, use_job_objects, timeout, &was_timeout);
if (redirect_stdio) {
#if defined(OS_WIN)
FlushFileBuffers(handle.Get());
handle.Close();
#elif defined(OS_POSIX)
output_file_fd.reset();
#endif
}
std::string output_file_contents;
CHECK(base::ReadFileToString(output_file, &output_file_contents));
if (!base::DeleteFile(output_file, false)) {
// This needs to be non-fatal at least for Windows.
LOG(WARNING) << "Failed to delete " << output_file.AsUTF8Unsafe();
}
// Run target callback on the thread it was originating from, not on
// a worker pool thread.
message_loop_proxy->PostTask(
FROM_HERE,
Bind(&RunCallback,
callback,
exit_code,
TimeTicks::Now() - start_time,
was_timeout,
output_file_contents));
}
} // namespace
const char kGTestFilterFlag[] = "gtest_filter";
const char kGTestHelpFlag[] = "gtest_help";
const char kGTestListTestsFlag[] = "gtest_list_tests";
const char kGTestRepeatFlag[] = "gtest_repeat";
const char kGTestRunDisabledTestsFlag[] = "gtest_also_run_disabled_tests";
const char kGTestOutputFlag[] = "gtest_output";
TestLauncherDelegate::~TestLauncherDelegate() {
}
TestLauncher::TestLauncher(TestLauncherDelegate* launcher_delegate,
size_t parallel_jobs)
: launcher_delegate_(launcher_delegate),
total_shards_(1),
shard_index_(0),
cycles_(1),
test_started_count_(0),
test_finished_count_(0),
test_success_count_(0),
test_broken_count_(0),
retry_count_(0),
retry_limit_(0),
run_result_(true),
watchdog_timer_(FROM_HERE,
TimeDelta::FromSeconds(kOutputTimeoutSeconds),
this,
&TestLauncher::OnOutputTimeout),
parallel_jobs_(parallel_jobs) {
if (BotModeEnabled()) {
fprintf(stdout,
"Enabling defaults optimized for continuous integration bots.\n");
fflush(stdout);
// Enable test retries by default for bots. This can be still overridden
// from command line using --test-launcher-retry-limit flag.
retry_limit_ = 3;
} else {
// Default to serial test execution if not running on a bot. This makes it
// possible to disable stdio redirection and can still be overridden with
// --test-launcher-jobs flag.
parallel_jobs_ = 1;
}
}
TestLauncher::~TestLauncher() {
if (worker_pool_owner_)
worker_pool_owner_->pool()->Shutdown();
}
bool TestLauncher::Run() {
if (!Init())
return false;
// Value of |cycles_| changes after each iteration. Keep track of the
// original value.
int requested_cycles = cycles_;
#if defined(OS_POSIX)
CHECK_EQ(0, pipe(g_shutdown_pipe));
struct sigaction action;
memset(&action, 0, sizeof(action));
sigemptyset(&action.sa_mask);
action.sa_handler = &ShutdownPipeSignalHandler;
CHECK_EQ(0, sigaction(SIGINT, &action, NULL));
CHECK_EQ(0, sigaction(SIGQUIT, &action, NULL));
CHECK_EQ(0, sigaction(SIGTERM, &action, NULL));
MessageLoopForIO::FileDescriptorWatcher controller;
SignalFDWatcher watcher;
CHECK(MessageLoopForIO::current()->WatchFileDescriptor(
g_shutdown_pipe[0],
true,
MessageLoopForIO::WATCH_READ,
&controller,
&watcher));
#endif // defined(OS_POSIX)
// Start the watchdog timer.
watchdog_timer_.Reset();
MessageLoop::current()->PostTask(
FROM_HERE,
Bind(&TestLauncher::RunTestIteration, Unretained(this)));
MessageLoop::current()->Run();
if (requested_cycles != 1)
results_tracker_.PrintSummaryOfAllIterations();
MaybeSaveSummaryAsJSON();
return run_result_;
}
void TestLauncher::LaunchChildGTestProcess(
const CommandLine& command_line,
const std::string& wrapper,
base::TimeDelta timeout,
bool use_job_objects,
const LaunchChildGTestProcessCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
// Record the exact command line used to launch the child.
CommandLine new_command_line(
PrepareCommandLineForGTest(command_line, wrapper));
// When running in parallel mode we need to redirect stdio to avoid mixed-up
// output. We also always redirect on the bots to get the test output into
// JSON summary.
bool redirect_stdio = (parallel_jobs_ > 1) || BotModeEnabled();
worker_pool_owner_->pool()->PostWorkerTask(
FROM_HERE,
Bind(&DoLaunchChildTestProcess,
new_command_line,
timeout,
use_job_objects,
redirect_stdio,
MessageLoopProxy::current(),
Bind(&TestLauncher::OnLaunchTestProcessFinished,
Unretained(this),
callback)));
}
void TestLauncher::OnTestFinished(const TestResult& result) {
++test_finished_count_;
bool print_snippet = false;
std::string print_test_stdio("auto");
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kTestLauncherPrintTestStdio)) {
print_test_stdio = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kTestLauncherPrintTestStdio);
}
if (print_test_stdio == "auto") {
print_snippet = (result.status != TestResult::TEST_SUCCESS);
} else if (print_test_stdio == "always") {
print_snippet = true;
} else if (print_test_stdio == "never") {
print_snippet = false;
} else {
LOG(WARNING) << "Invalid value of " << switches::kTestLauncherPrintTestStdio
<< ": " << print_test_stdio;
}
if (print_snippet) {
std::vector<std::string> snippet_lines;
SplitString(result.output_snippet, '\n', &snippet_lines);
if (snippet_lines.size() > kOutputSnippetLinesLimit) {
size_t truncated_size = snippet_lines.size() - kOutputSnippetLinesLimit;
snippet_lines.erase(
snippet_lines.begin(),
snippet_lines.begin() + truncated_size);
snippet_lines.insert(snippet_lines.begin(), "<truncated>");
}
fprintf(stdout, "%s", JoinString(snippet_lines, "\n").c_str());
fflush(stdout);
}
if (result.status == TestResult::TEST_SUCCESS) {
++test_success_count_;
} else {
tests_to_retry_.insert(result.full_name);
}
results_tracker_.AddTestResult(result);
// TODO(phajdan.jr): Align counter (padding).
std::string status_line(
StringPrintf("[%" PRIuS "/%" PRIuS "] %s ",
test_finished_count_,
test_started_count_,
result.full_name.c_str()));
if (result.completed()) {
status_line.append(StringPrintf("(%" PRId64 " ms)",
result.elapsed_time.InMilliseconds()));
} else if (result.status == TestResult::TEST_TIMEOUT) {
status_line.append("(TIMED OUT)");
} else if (result.status == TestResult::TEST_CRASH) {
status_line.append("(CRASHED)");
} else if (result.status == TestResult::TEST_SKIPPED) {
status_line.append("(SKIPPED)");
} else if (result.status == TestResult::TEST_UNKNOWN) {
status_line.append("(UNKNOWN)");
} else {
// Fail very loudly so it's not ignored.
CHECK(false) << "Unhandled test result status: " << result.status;
}
fprintf(stdout, "%s\n", status_line.c_str());
fflush(stdout);
// We just printed a status line, reset the watchdog timer.
watchdog_timer_.Reset();
// Do not waste time on timeouts. We include tests with unknown results here
// because sometimes (e.g. hang in between unit tests) that's how a timeout
// gets reported.
if (result.status == TestResult::TEST_TIMEOUT ||
result.status == TestResult::TEST_UNKNOWN) {
test_broken_count_++;
}
size_t broken_threshold =
std::max(static_cast<size_t>(20), test_started_count_ / 10);
if (test_broken_count_ >= broken_threshold) {
fprintf(stdout, "Too many badly broken tests (%" PRIuS "), exiting now.\n",
test_broken_count_);
fflush(stdout);
#if defined(OS_POSIX)
KillSpawnedTestProcesses();
#endif // defined(OS_POSIX)
results_tracker_.AddGlobalTag("BROKEN_TEST_EARLY_EXIT");
results_tracker_.AddGlobalTag(kUnreliableResultsTag);
MaybeSaveSummaryAsJSON();
exit(1);
}
if (test_finished_count_ != test_started_count_)
return;
if (tests_to_retry_.empty() || retry_count_ >= retry_limit_) {
OnTestIterationFinished();
return;
}
if (tests_to_retry_.size() >= broken_threshold) {
fprintf(stdout,
"Too many failing tests (%" PRIuS "), skipping retries.\n",
tests_to_retry_.size());
fflush(stdout);
results_tracker_.AddGlobalTag("BROKEN_TEST_SKIPPED_RETRIES");
results_tracker_.AddGlobalTag(kUnreliableResultsTag);
OnTestIterationFinished();
return;
}
retry_count_++;
std::vector<std::string> test_names(tests_to_retry_.begin(),
tests_to_retry_.end());
tests_to_retry_.clear();
size_t retry_started_count = launcher_delegate_->RetryTests(this, test_names);
if (retry_started_count == 0) {
// Signal failure, but continue to run all requested test iterations.
// With the summary of all iterations at the end this is a good default.
run_result_ = false;
OnTestIterationFinished();
return;
}
fprintf(stdout, "Retrying %" PRIuS " test%s (retry #%" PRIuS ")\n",
retry_started_count,
retry_started_count > 1 ? "s" : "",
retry_count_);
fflush(stdout);
test_started_count_ += retry_started_count;
}
bool TestLauncher::Init() {
const CommandLine* command_line = CommandLine::ForCurrentProcess();
// Initialize sharding. Command line takes precedence over legacy environment
// variables.
if (command_line->HasSwitch(switches::kTestLauncherTotalShards) &&
command_line->HasSwitch(switches::kTestLauncherShardIndex)) {
if (!StringToInt(
command_line->GetSwitchValueASCII(
switches::kTestLauncherTotalShards),
&total_shards_)) {
LOG(ERROR) << "Invalid value for " << switches::kTestLauncherTotalShards;
return false;
}
if (!StringToInt(
command_line->GetSwitchValueASCII(
switches::kTestLauncherShardIndex),
&shard_index_)) {
LOG(ERROR) << "Invalid value for " << switches::kTestLauncherShardIndex;
return false;
}
fprintf(stdout,
"Using sharding settings from command line. This is shard %d/%d\n",
shard_index_, total_shards_);
fflush(stdout);
} else {
if (!TakeInt32FromEnvironment(kTestTotalShards, &total_shards_))
return false;
if (!TakeInt32FromEnvironment(kTestShardIndex, &shard_index_))
return false;
fprintf(stdout,
"Using sharding settings from environment. This is shard %d/%d\n",
shard_index_, total_shards_);
fflush(stdout);
}
if (shard_index_ < 0 ||
total_shards_ < 0 ||
shard_index_ >= total_shards_) {
LOG(ERROR) << "Invalid sharding settings: we require 0 <= "
<< kTestShardIndex << " < " << kTestTotalShards
<< ", but you have " << kTestShardIndex << "=" << shard_index_
<< ", " << kTestTotalShards << "=" << total_shards_ << ".\n";
return false;
}
// Make sure we don't pass any sharding-related environment to the child
// processes. This test launcher implements the sharding completely.
CHECK(UnsetEnvironmentVariableIfExists("GTEST_TOTAL_SHARDS"));
CHECK(UnsetEnvironmentVariableIfExists("GTEST_SHARD_INDEX"));
if (command_line->HasSwitch(kGTestRepeatFlag) &&
!StringToInt(command_line->GetSwitchValueASCII(kGTestRepeatFlag),
&cycles_)) {
LOG(ERROR) << "Invalid value for " << kGTestRepeatFlag;
return false;
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kTestLauncherRetryLimit)) {
int retry_limit = -1;
if (!StringToInt(CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kTestLauncherRetryLimit), &retry_limit) ||
retry_limit < 0) {
LOG(ERROR) << "Invalid value for " << switches::kTestLauncherRetryLimit;
return false;
}
retry_limit_ = retry_limit;
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kTestLauncherJobs)) {
int jobs = -1;
if (!StringToInt(CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kTestLauncherJobs), &jobs) ||
jobs < 0) {
LOG(ERROR) << "Invalid value for " << switches::kTestLauncherJobs;
return false;
}
parallel_jobs_ = jobs;
}
fprintf(stdout, "Using %" PRIuS " parallel jobs.\n", parallel_jobs_);
fflush(stdout);
worker_pool_owner_.reset(
new SequencedWorkerPoolOwner(parallel_jobs_, "test_launcher"));
if (command_line->HasSwitch(switches::kTestLauncherFilterFile) &&
command_line->HasSwitch(kGTestFilterFlag)) {
LOG(ERROR) << "Only one of --test-launcher-filter-file and --gtest_filter "
<< "at a time is allowed.";
return false;
}
if (command_line->HasSwitch(switches::kTestLauncherFilterFile)) {
std::string filter;
if (!ReadFileToString(
command_line->GetSwitchValuePath(switches::kTestLauncherFilterFile),
&filter)) {
LOG(ERROR) << "Failed to read the filter file.";
return false;
}
std::vector<std::string> filter_lines;
SplitString(filter, '\n', &filter_lines);
for (size_t i = 0; i < filter_lines.size(); i++) {
if (filter_lines[i].empty())
continue;
if (filter_lines[i][0] == '-')
negative_test_filter_.push_back(filter_lines[i].substr(1));
else
positive_test_filter_.push_back(filter_lines[i]);
}
} else {
// Split --gtest_filter at '-', if there is one, to separate into
// positive filter and negative filter portions.
std::string filter = command_line->GetSwitchValueASCII(kGTestFilterFlag);
size_t dash_pos = filter.find('-');
if (dash_pos == std::string::npos) {
SplitString(filter, ':', &positive_test_filter_);
} else {
// Everything up to the dash.
SplitString(filter.substr(0, dash_pos), ':', &positive_test_filter_);
// Everything after the dash.
SplitString(filter.substr(dash_pos + 1), ':', &negative_test_filter_);
}
}
if (!results_tracker_.Init(*command_line)) {
LOG(ERROR) << "Failed to initialize test results tracker.";
return 1;
}
#if defined(NDEBUG)
results_tracker_.AddGlobalTag("MODE_RELEASE");
#else
results_tracker_.AddGlobalTag("MODE_DEBUG");
#endif
// Operating systems (sorted alphabetically).
// Note that they can deliberately overlap, e.g. OS_LINUX is a subset
// of OS_POSIX.
#if defined(OS_ANDROID)
results_tracker_.AddGlobalTag("OS_ANDROID");
#endif
#if defined(OS_BSD)
results_tracker_.AddGlobalTag("OS_BSD");
#endif
#if defined(OS_FREEBSD)
results_tracker_.AddGlobalTag("OS_FREEBSD");
#endif
#if defined(OS_IOS)
results_tracker_.AddGlobalTag("OS_IOS");
#endif
#if defined(OS_LINUX)
results_tracker_.AddGlobalTag("OS_LINUX");
#endif
#if defined(OS_MACOSX)
results_tracker_.AddGlobalTag("OS_MACOSX");
#endif
#if defined(OS_NACL)
results_tracker_.AddGlobalTag("OS_NACL");
#endif
#if defined(OS_OPENBSD)
results_tracker_.AddGlobalTag("OS_OPENBSD");
#endif
#if defined(OS_POSIX)
results_tracker_.AddGlobalTag("OS_POSIX");
#endif
#if defined(OS_SOLARIS)
results_tracker_.AddGlobalTag("OS_SOLARIS");
#endif
#if defined(OS_WIN)
results_tracker_.AddGlobalTag("OS_WIN");
#endif
// CPU-related tags.
#if defined(ARCH_CPU_32_BITS)
results_tracker_.AddGlobalTag("CPU_32_BITS");
#endif
#if defined(ARCH_CPU_64_BITS)
results_tracker_.AddGlobalTag("CPU_64_BITS");
#endif
return true;
}
void TestLauncher::RunTests() {
testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
std::vector<std::string> test_names;
for (int i = 0; i < unit_test->total_test_case_count(); ++i) {
const testing::TestCase* test_case = unit_test->GetTestCase(i);
for (int j = 0; j < test_case->total_test_count(); ++j) {
const testing::TestInfo* test_info = test_case->GetTestInfo(j);
std::string test_name = test_info->test_case_name();
test_name.append(".");
test_name.append(test_info->name());
results_tracker_.AddTest(test_name);
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (test_name.find("DISABLED") != std::string::npos) {
results_tracker_.AddDisabledTest(test_name);
// Skip disabled tests unless explicitly requested.
if (!command_line->HasSwitch(kGTestRunDisabledTestsFlag))
continue;
}
// Skip the test that doesn't match the filter (if given).
if (!positive_test_filter_.empty()) {
bool found = false;
for (size_t k = 0; k < positive_test_filter_.size(); ++k) {
if (MatchPattern(test_name, positive_test_filter_[k])) {
found = true;
break;
}
}
if (!found)
continue;
}
bool excluded = false;
for (size_t k = 0; k < negative_test_filter_.size(); ++k) {
if (MatchPattern(test_name, negative_test_filter_[k])) {
excluded = true;
break;
}
}
if (excluded)
continue;
if (!launcher_delegate_->ShouldRunTest(test_case, test_info))
continue;
if (base::Hash(test_name) % total_shards_ !=
static_cast<uint32>(shard_index_)) {
continue;
}
test_names.push_back(test_name);
}
}
test_started_count_ = launcher_delegate_->RunTests(this, test_names);
if (test_started_count_ == 0) {
fprintf(stdout, "0 tests run\n");
fflush(stdout);
// No tests have actually been started, so kick off the next iteration.
MessageLoop::current()->PostTask(
FROM_HERE,
Bind(&TestLauncher::RunTestIteration, Unretained(this)));
}
}
void TestLauncher::RunTestIteration() {
if (cycles_ == 0) {
MessageLoop::current()->Quit();
return;
}
// Special value "-1" means "repeat indefinitely".
cycles_ = (cycles_ == -1) ? cycles_ : cycles_ - 1;
test_started_count_ = 0;
test_finished_count_ = 0;
test_success_count_ = 0;
test_broken_count_ = 0;
retry_count_ = 0;
tests_to_retry_.clear();
results_tracker_.OnTestIterationStarting();
MessageLoop::current()->PostTask(
FROM_HERE, Bind(&TestLauncher::RunTests, Unretained(this)));
}
void TestLauncher::MaybeSaveSummaryAsJSON() {
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kTestLauncherSummaryOutput)) {
FilePath summary_path(command_line->GetSwitchValuePath(
switches::kTestLauncherSummaryOutput));
if (!results_tracker_.SaveSummaryAsJSON(summary_path)) {
LOG(ERROR) << "Failed to save test launcher output summary.";
}
}
}
void TestLauncher::OnLaunchTestProcessFinished(
const LaunchChildGTestProcessCallback& callback,
int exit_code,
const TimeDelta& elapsed_time,
bool was_timeout,
const std::string& output) {
DCHECK(thread_checker_.CalledOnValidThread());
callback.Run(exit_code, elapsed_time, was_timeout, output);
}
void TestLauncher::OnTestIterationFinished() {
TestResultsTracker::TestStatusMap tests_by_status(
results_tracker_.GetTestStatusMapForCurrentIteration());
if (!tests_by_status[TestResult::TEST_UNKNOWN].empty())
results_tracker_.AddGlobalTag(kUnreliableResultsTag);
// When we retry tests, success is determined by having nothing more
// to retry (everything eventually passed), as opposed to having
// no failures at all.
if (tests_to_retry_.empty()) {
fprintf(stdout, "SUCCESS: all tests passed.\n");
fflush(stdout);
} else {
// Signal failure, but continue to run all requested test iterations.
// With the summary of all iterations at the end this is a good default.
run_result_ = false;
}
results_tracker_.PrintSummaryOfCurrentIteration();
// Kick off the next iteration.
MessageLoop::current()->PostTask(
FROM_HERE,
Bind(&TestLauncher::RunTestIteration, Unretained(this)));
}
void TestLauncher::OnOutputTimeout() {
DCHECK(thread_checker_.CalledOnValidThread());
AutoLock lock(g_live_processes_lock.Get());
fprintf(stdout, "Still waiting for the following processes to finish:\n");
for (std::map<ProcessHandle, CommandLine>::iterator i =
g_live_processes.Get().begin();
i != g_live_processes.Get().end();
++i) {
#if defined(OS_WIN)
fwprintf(stdout, L"\t%s\n", i->second.GetCommandLineString().c_str());
#else
fprintf(stdout, "\t%s\n", i->second.GetCommandLineString().c_str());
#endif
}
fflush(stdout);
// Arm the timer again - otherwise it would fire only once.
watchdog_timer_.Reset();
}
std::string GetTestOutputSnippet(const TestResult& result,
const std::string& full_output) {
size_t run_pos = full_output.find(std::string("[ RUN ] ") +
result.full_name);
if (run_pos == std::string::npos)
return std::string();
size_t end_pos = full_output.find(std::string("[ FAILED ] ") +
result.full_name,
run_pos);
// Only clip the snippet to the "OK" message if the test really
// succeeded. It still might have e.g. crashed after printing it.
if (end_pos == std::string::npos &&
result.status == TestResult::TEST_SUCCESS) {
end_pos = full_output.find(std::string("[ OK ] ") +
result.full_name,
run_pos);
}
if (end_pos != std::string::npos) {
size_t newline_pos = full_output.find("\n", end_pos);
if (newline_pos != std::string::npos)
end_pos = newline_pos + 1;
}
std::string snippet(full_output.substr(run_pos));
if (end_pos != std::string::npos)
snippet = full_output.substr(run_pos, end_pos - run_pos);
return snippet;
}
CommandLine PrepareCommandLineForGTest(const CommandLine& command_line,
const std::string& wrapper) {
CommandLine new_command_line(command_line.GetProgram());
CommandLine::SwitchMap switches = command_line.GetSwitches();
// Strip out gtest_repeat flag - this is handled by the launcher process.
switches.erase(kGTestRepeatFlag);
// Don't try to write the final XML report in child processes.
switches.erase(kGTestOutputFlag);
for (CommandLine::SwitchMap::const_iterator iter = switches.begin();
iter != switches.end(); ++iter) {
new_command_line.AppendSwitchNative((*iter).first, (*iter).second);
}
// Prepend wrapper after last CommandLine quasi-copy operation. CommandLine
// does not really support removing switches well, and trying to do that
// on a CommandLine with a wrapper is known to break.
// TODO(phajdan.jr): Give it a try to support CommandLine removing switches.
#if defined(OS_WIN)
new_command_line.PrependWrapper(ASCIIToWide(wrapper));
#elif defined(OS_POSIX)
new_command_line.PrependWrapper(wrapper);
#endif
return new_command_line;
}
// TODO(phajdan.jr): Move to anonymous namespace.
int LaunchChildTestProcessWithOptions(const CommandLine& command_line,
const LaunchOptions& options,
bool use_job_objects,
base::TimeDelta timeout,
bool* was_timeout) {
#if defined(OS_POSIX)
// Make sure an option we rely on is present - see LaunchChildGTestProcess.
DCHECK(options.new_process_group);
#endif
LaunchOptions new_options(options);
#if defined(OS_WIN)
DCHECK(!new_options.job_handle);
win::ScopedHandle job_handle;
if (use_job_objects) {
job_handle.Set(CreateJobObject(NULL, NULL));
if (!job_handle.IsValid()) {
LOG(ERROR) << "Could not create JobObject.";
return -1;
}
// Allow break-away from job since sandbox and few other places rely on it
// on Windows versions prior to Windows 8 (which supports nested jobs).
// TODO(phajdan.jr): Do not allow break-away on Windows 8.
if (!SetJobObjectLimitFlags(job_handle.Get(),
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE |
JOB_OBJECT_LIMIT_BREAKAWAY_OK)) {
LOG(ERROR) << "Could not SetJobObjectLimitFlags.";
return -1;
}
new_options.job_handle = job_handle.Get();
}
#endif // defined(OS_WIN)
#if defined(OS_LINUX)
// To prevent accidental privilege sharing to an untrusted child, processes
// are started with PR_SET_NO_NEW_PRIVS. Do not set that here, since this
// new child will be privileged and trusted.
new_options.allow_new_privs = true;
#endif
base::ProcessHandle process_handle;
{
// Note how we grab the lock before the process possibly gets created.
// This ensures that when the lock is held, ALL the processes are registered
// in the set.
AutoLock lock(g_live_processes_lock.Get());
if (!base::LaunchProcess(command_line, new_options, &process_handle))
return -1;
g_live_processes.Get().insert(std::make_pair(process_handle, command_line));
}
int exit_code = 0;
if (!base::WaitForExitCodeWithTimeout(process_handle,
&exit_code,
timeout)) {
*was_timeout = true;
exit_code = -1; // Set a non-zero exit code to signal a failure.
// Ensure that the process terminates.
base::KillProcess(process_handle, -1, true);
}
{
// Note how we grab the log before issuing a possibly broad process kill.
// Other code parts that grab the log kill processes, so avoid trying
// to do that twice and trigger all kinds of log messages.
AutoLock lock(g_live_processes_lock.Get());
#if defined(OS_POSIX)
if (exit_code != 0) {
// On POSIX, in case the test does not exit cleanly, either due to a crash
// or due to it timing out, we need to clean up any child processes that
// it might have created. On Windows, child processes are automatically
// cleaned up using JobObjects.
base::KillProcessGroup(process_handle);
}
#endif
g_live_processes.Get().erase(process_handle);
}
base::CloseProcessHandle(process_handle);
return exit_code;
}
} // namespace base
| chromium2014/src | base/test/launcher/test_launcher.cc | C++ | bsd-3-clause | 35,866 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\BspPerlanjutan */
$this->title = 'Update Bsp Perlanjutan: ' . ' ' . $model->bsp_perlanjutan_id;
$this->params['breadcrumbs'][] = ['label' => 'Bsp Perlanjutans', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->bsp_perlanjutan_id, 'url' => ['view', 'id' => $model->bsp_perlanjutan_id]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="bsp-perlanjutan-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| hung101/kbs | frontend/views/BspPerlanjutan/update.php | PHP | bsd-3-clause | 608 |
/*L
* Copyright SAIC
* Copyright SAIC-Frederick
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/camod/LICENSE.txt for details.
*/
/**
*
* $Id: RadiationAction.java,v 1.16 2008-08-14 16:55:34 pandyas Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.15 2007/10/31 17:12:46 pandyas
* Modified comments for #8355 Add comments field to every submission page
*
* Revision 1.14 2006/10/27 16:31:51 pandyas
* fixed printout on error - typo
*
* Revision 1.13 2006/04/17 19:09:41 pandyas
* caMod 2.1 OM changes
*
* Revision 1.12 2005/11/09 00:17:26 georgeda
* Fixed delete w/ constraints
*
* Revision 1.11 2005/11/02 21:48:09 georgeda
* Fixed validate
*
* Revision 1.10 2005/11/02 19:02:08 pandyas
* Added e-mail functionality
*
* Revision 1.9 2005/10/28 14:50:55 georgeda
* Fixed null pointer problem
*
* Revision 1.8 2005/10/28 12:47:26 georgeda
* Added delete functionality
*
* Revision 1.7 2005/10/20 20:39:32 pandyas
* added javadocs
*
*
*/
package gov.nih.nci.camod.webapp.action;
import gov.nih.nci.camod.Constants;
import gov.nih.nci.camod.domain.AnimalModel;
import gov.nih.nci.camod.domain.CarcinogenExposure;
import gov.nih.nci.camod.service.AnimalModelManager;
import gov.nih.nci.camod.service.CarcinogenExposureManager;
import gov.nih.nci.camod.webapp.form.RadiationForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.*;
/**
* RadiationAction Class
*/
public class RadiationAction extends BaseAction {
/**
* Edit
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
if (log.isDebugEnabled()) {
log.debug("Entering 'edit' method");
}
if (!isTokenValid(request)) {
return mapping.findForward("failure");
}
// Grab the current CarcinogenExposure we are working with related to this animalModel
String aCarcinogenExposureID = request.getParameter("aCarcinogenExposureID");
// Create a form to edit
RadiationForm radiationForm = (RadiationForm) form;
log.info("<EnvironmentalFactorAction save> following Characteristics:" + "\n\t name: "
+ radiationForm.getName() + "\n\t otherName: " + radiationForm.getOtherName() + "\n\t dosage: "
+ radiationForm.getDosage()
+ "\n\t dosageUnit: " + radiationForm.getDosageUnit()
+ "\n\t administrativeRoute: " + radiationForm.getAdministrativeRoute()
+ "\n\t regimen: " + radiationForm.getRegimen() + "\n\t ageAtTreatment: "
+ radiationForm.getAgeAtTreatment()
+ radiationForm.getAgeAtTreatmentUnit()
+ "\n\t type: " + radiationForm.getType() + "\n\t user: "
+ (String) request.getSession().getAttribute("camod.loggedon.username"));
CarcinogenExposureManager carcinogenExposureManager = (CarcinogenExposureManager) getBean("carcinogenExposureManager");
String theAction = (String) request.getParameter(Constants.Parameters.ACTION);
try {
// Grab the current modelID from the session
String theModelId = (String) request.getSession().getAttribute(Constants.MODELID);
AnimalModelManager theAnimalModelManager = (AnimalModelManager) getBean("animalModelManager");
AnimalModel theAnimalModel = theAnimalModelManager.get(theModelId);
if ("Delete".equals(theAction)) {
carcinogenExposureManager.remove(aCarcinogenExposureID, theAnimalModel);
ActionMessages msg = new ActionMessages();
msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("radiation.delete.successful"));
saveErrors(request, msg);
} else {
CarcinogenExposure theCarcinogenExposure = carcinogenExposureManager.get(aCarcinogenExposureID);
carcinogenExposureManager.update(theAnimalModel, radiationForm, theCarcinogenExposure);
// Add a message to be displayed in submitOverview.jsp saying
// you've
// created a new model successfully
ActionMessages msg = new ActionMessages();
msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("radiation.edit.successful"));
saveErrors(request, msg);
}
} catch (Exception e) {
log.error("Unable to get add a radiation action: ", e);
ActionMessages theMsg = new ActionMessages();
theMsg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.admin.message"));
saveErrors(request, theMsg);
}
resetToken(request);
return mapping.findForward("AnimalModelTreePopulateAction");
}
/**
* Save
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
if (log.isDebugEnabled()) {
log.debug("Entering 'save' method");
}
if (!isTokenValid(request)) {
return mapping.findForward("failure");
}
RadiationForm radiationForm = (RadiationForm) form;
log.info("<EnvironmentalFactorAction save> following Characteristics:" + "\n\t name: "
+ radiationForm.getName() + "\n\t otherName: " + radiationForm.getOtherName() + "\n\t dosage: "
+ radiationForm.getDosage()
+ "\n\t dosageUnit: " + radiationForm.getDosageUnit()
+ "\n\t administrativeRoute: " + radiationForm.getAdministrativeRoute()
+ "\n\t regimen: " + radiationForm.getRegimen() + "\n\t ageAtTreatment: "
+ radiationForm.getAgeAtTreatment() + radiationForm.getAgeAtTreatmentUnit()
+ "\n\t type: " + radiationForm.getType()
+ "\n\t Comments: " + radiationForm.getComments()+ "\n\t user: "
+ (String) request.getSession().getAttribute("camod.loggedon.username"));
/* Grab the current modelID from the session */
String modelID = (String) request.getSession().getAttribute(Constants.MODELID);
/* Create all the manager objects needed for Screen */
AnimalModelManager animalModelManager = (AnimalModelManager) getBean("animalModelManager");
/* Set modelID in AnimalModel object */
AnimalModel animalModel = animalModelManager.get(modelID);
try {
animalModelManager.addCarcinogenExposure(animalModel, radiationForm);
// Add a message to be displayed in submitOverview.jsp saying you've
// created a new model successfully
ActionMessages msg = new ActionMessages();
msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("radiation.creation.successful"));
saveErrors(request, msg);
} catch (Exception e) {
log.error("Unable to get add a radiation action: ", e);
ActionMessages theMsg = new ActionMessages();
theMsg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.admin.message"));
saveErrors(request, theMsg);
}
resetToken(request);
return mapping.findForward("AnimalModelTreePopulateAction");
}
}
| NCIP/camod | software/camod/src/gov/nih/nci/camod/webapp/action/RadiationAction.java | Java | bsd-3-clause | 7,161 |
<?php
namespace IntraLibrary\Service;
use \IntraLibrary\IntraLibraryException;
use \DOMDocument;
use \DOMXPath;
use \DOMNode;
/**
* IntraLibrary XML Response base class
*
* @package IntraLibrary_PHP
* @author Janek Lasocki-Biczysko, <j.lasocki-biczysko@intrallect.com>
*/
abstract class XMLResponse
{
protected $xPath;
/**
* Load XML into the response object
*
* @param string $xmlResponse the XML response
* @return void
*/
public function load($xmlResponse)
{
if (empty($xmlResponse)) {
return;
}
$xmlDocument = new DOMDocument();
$xmlDocument->loadXML($xmlResponse);
$this->xPath = new DOMXPath($xmlDocument);
$this->consumeDom();
}
/**
* Run an xPath query
*
* @param string $expression the xpath expression
* @param DOMNode $contextNode the context node
* @return DOMNodeList
*/
public function xQuery($expression, DOMNode $contextNode = null)
{
if ($this->xPath) {
return $this->xPath->query($expression, $contextNode);
}
return new \DOMNodeList();
}
/**
* Get the text value of a node (or an array of values if multiple nodes are matched
* by the expression)
*
* @param string $expression the xpath expression targeting the text node
* element (without the trailing '/text()' function)
* @param DOMNode $contextNode the context node used in the xpath query
* @param boolean $wrap if true, single results will be wrapped in an array
* @return string | array
*/
public function getText($expression, DOMNode $contextNode = null, $wrap = false)
{
if (!$this->xPath) {
return null;
}
// XXX: PHP 5.3.2 seems to require $contextNode to be omitted
// from the function's arguments if it is null
// 5.3.6 seems to handle this naturally...
if ($contextNode === null) {
$domNodeList = $this->xPath->query($expression . '/text()');
} else {
$domNodeList = $this->xPath->query($expression . '/text()', $contextNode);
}
if ($domNodeList && $domNodeList->length > 0) {
if ($domNodeList->length == 1 && !$wrap) {
return $domNodeList->item(0)->wholeText;
}
$text = array();
foreach ($domNodeList as $item) {
$text[] = $item->wholeText;
}
return $text;
}
return null;
}
/**
* Subclasses should use this function to traverse the dom using xpath
* and store any data for future access.
*
* @return void
*/
abstract protected function consumeDom();
}
| intrallect/intraLibrary-PHP | src/IntraLibrary/Service/XMLResponse.php | PHP | bsd-3-clause | 2,807 |
<?php
/*
$Rev: 285 $ | $LastChangedBy: brieb $
$LastChangedDate: 2007-08-27 14:05:27 -0600 (Mon, 27 Aug 2007) $
+-------------------------------------------------------------------------+
| Copyright (c) 2004 - 2007, Kreotek LLC |
| 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 Kreotek LLC nor the names of its contributore 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. |
| |
+-------------------------------------------------------------------------+
*/
include("../../include/session.php");
include("include/fields.php");
include("include/tables.php");
$tax = new phpbmstable($db,6);
$therecord = $tax->processAddEditPage();
if(isset($therecord["phpbmsStatus"]))
$statusmessage = $therecord["phpbmsStatus"];
$phpbms->cssIncludes[] = "pages/tax.css";
//Form Elements
//==============================================================
$theform = new phpbmsForm();
$theinput = new inputCheckbox("inactive",$therecord["inactive"]);
$theform->addField($theinput);
$theinput = new inputField("name",$therecord["name"],NULL,true,NULL,28,64);
$theinput->setAttribute("class","important");
$theform->addField($theinput);
$theinput = new inputPercentage("percentage",$therecord["percentage"],NULL,5,true,28,64);
$theform->addField($theinput);
$theform->jsMerge();
//==============================================================
//End Form Elements
$pageTitle="Tax Area";
include("header.php");
?><div class="bodyline">
<?php $theform->startForm($pageTitle)?>
<fieldset id="fsAttributes">
<legend>attribues</legend>
<p>
<label for="id">id</label><br />
<input name="id" id="id" type="text" value="<?php echo $therecord["id"]; ?>" size="5" maxlength="5" readonly="readonly" class="uneditable" />
</p>
<p><?php $theform->showField("inactive");?></p>
</fieldset>
<div id="nameDiv">
<fieldset >
<legend>name / percentage</legend>
<p><?php $theform->showField("name"); ?></p>
<p><?php $theform->showField("percentage"); ?></p>
</fieldset>
</div>
<?php
$theform->showCreateModify($phpbms,$therecord);
$theform->endForm();
?>
</div>
<?php include("footer.php");?> | eandbsoftware/phpbms | modules/bms/tax_addedit.php | PHP | bsd-3-clause | 4,359 |
import {IFormSelectElement, IFormSelectOptionGroup, IFormSelectOption} from '../form/elements/FormSelect';
import {FormElementType, IFormElement, IFormElementDesc} from '../form/interfaces';
import {ISelection} from '../base/interfaces';
import {IDType, IDTypeLike, IDTypeManager} from '../idtype';
import {BaseUtils} from '../base';
import {I18nextManager} from '../i18n';
export interface ISelectionChooserOptions {
/**
* Readable IDType the selection is being mapped to. If there is a 1:n mapping or in case of different readable and target IDTypes this IDType is used as the options group
*/
readableIDType: IDTypeLike;
/**
* In case of 1:n mappings between the selection's IDType and the readableIDType (or in case of different readable and target IDTypes) the readableSubOptionIDType can be used map the n options to readable names
*/
readableTargetIDType: IDTypeLike;
label: string;
appendOriginalLabel: boolean;
selectNewestByDefault: boolean;
}
/**
* helper class for chooser logic
*/
export class SelectionChooser {
private static readonly INVALID_MAPPING = {
name: 'Invalid',
id: -1,
label: ''
};
private readonly target: IDType | null;
private readonly readAble: IDType | null;
private readonly readableTargetIDType: IDType | null;
readonly desc: IFormElementDesc;
private readonly formID: string;
private readonly options: Readonly<ISelectionChooserOptions> = {
appendOriginalLabel: true,
selectNewestByDefault: true,
readableIDType: null,
readableTargetIDType: null,
label: 'Show'
};
private currentOptions: IFormSelectOption[];
constructor(private readonly accessor: (id: string) => IFormElement, targetIDType?: IDTypeLike, options: Partial<ISelectionChooserOptions> = {}) {
Object.assign(this.options, options);
this.target = targetIDType ? IDTypeManager.getInstance().resolveIdType(targetIDType) : null;
this.readAble = options.readableIDType ? IDTypeManager.getInstance().resolveIdType(options.readableIDType) : null;
this.readableTargetIDType = options.readableTargetIDType ? IDTypeManager.getInstance().resolveIdType(options.readableTargetIDType) : null;
this.formID = `forms.chooser.select.${this.target ? this.target.id : BaseUtils.randomId(4)}`;
this.desc = {
type: FormElementType.SELECT,
label: this.options.label,
id: this.formID,
options: {
optionsData: [],
},
useSession: true
};
}
init(selection: ISelection) {
return this.updateImpl(selection, false);
}
update(selection: ISelection) {
return this.updateImpl(selection, true);
}
chosen(): {id: number, name: string, label: string} | null {
const s = this.accessor(this.formID).value;
if (!s || s.data === SelectionChooser.INVALID_MAPPING) {
return null;
}
if (s.data) {
return s.data;
}
return {id: parseInt(s.id, 10), name: s.name, label: s.name};
}
private async toItems(selection: ISelection): Promise<(IFormSelectOption | IFormSelectOptionGroup)[]> {
const source = selection.idtype;
const sourceIds = selection.range.dim(0).asList();
const sourceNames = await source.unmap(sourceIds);
const readAble = this.readAble || null;
const readAbleNames = !readAble || readAble === source ? null : await IDTypeManager.getInstance().mapToFirstName(source, sourceIds, readAble);
const labels = readAbleNames ? (this.options.appendOriginalLabel ? readAbleNames.map((d, i) => `${d} (${sourceNames[i]})`) : readAbleNames) : sourceNames;
const target = this.target || source;
if (target === source) {
return sourceIds.map((d, i) => ({
value: String(d),
name: labels[i],
data: {id: d, name: sourceNames[i], label: labels[i]}
}));
}
const targetIds = await IDTypeManager.getInstance().mapToID(source, sourceIds, target);
const targetIdsFlat = (<number[]>[]).concat(...targetIds);
const targetNames = await target.unmap(targetIdsFlat);
if (target === readAble && targetIds.every((d) => d.length === 1)) {
// keep it simple target = readable and single hit - so just show flat
return targetIds.map((d, i) => ({
value: String(d[0]),
name: labels[i],
data: {id: d[0], name: targetNames[i], label: labels[i]}
}));
}
// in case of either 1:n mappings or when the target IDType and the readable IDType are different the readableIDType maps to the groups, the actual options would be mapped to the target IDType (e.g. some unreadable IDs).
// the readableTargetIDType provides the possibility to add an extra IDType to map the actual options to instead of the target IDs
const readAbleSubOptions: string[] = [];
if (this.readableTargetIDType) {
const optionsIDs: string[] = await IDTypeManager.getInstance().mapNameToFirstName(target, targetNames, this.readableTargetIDType);
readAbleSubOptions.push(...optionsIDs);
}
const subOptions = readAbleSubOptions && readAbleSubOptions.length > 0 ? readAbleSubOptions : targetNames;
let acc = 0;
const base = labels.map((name, i) => {
const group = targetIds[i];
const groupNames = subOptions.slice(acc, acc + group.length);
const originalTargetNames = targetNames.slice(acc, acc + group.length);
acc += group.length;
if (group.length === 0) {
// fake option with null value
return <IFormSelectOptionGroup>{
name,
children: [{
name: I18nextManager.getInstance().i18n.t('tdp:core.views.formSelectName'),
value: '',
data: SelectionChooser.INVALID_MAPPING
}]
};
}
return <IFormSelectOptionGroup>{
name,
children: group.map((d, j) => ({
name: groupNames[j], // either the original ID of the target or the readableTargetID is shown as an option if the readableTargetIDType is available
value: String(d),
data: {
id: d,
name: originalTargetNames[j], // this is the original ID from the target's idType to be used internally in the detail view
label: groupNames[j]
}
}))
};
});
return base.length === 1 ? base[0].children : base;
}
private updateImpl(selection: ISelection, reuseOld: boolean): Promise<boolean> {
return this.toItems(selection).then((r) => this.updateItems(r, reuseOld));
}
private updateItems(options: (IFormSelectOption | IFormSelectOptionGroup)[], reuseOld: boolean) {
const element = <IFormSelectElement>this.accessor(this.formID);
const flatOptions = options.reduce((acc, d) => {
if ((<any>d).children) {
acc.push(...(<IFormSelectOptionGroup>d).children);
} else {
acc.push(<IFormSelectOption>d);
}
return acc;
}, <IFormSelectOption[]>[]);
// backup entry and restore the selectedIndex by value afterwards again,
// because the position of the selected element might change
const bak = element.value || flatOptions[element.getSelectedIndex()];
let changed = true;
let newValue = bak;
// select last item from incoming `selection.range`
if (this.options.selectNewestByDefault) {
// find the first newest entries
const newOne = flatOptions.find((d) => !this.currentOptions || this.currentOptions.every((e) => e.value !== d.value));
if (newOne) {
newValue = newOne;
} else {
newValue = flatOptions[flatOptions.length - 1];
}
} else if (!reuseOld) {
newValue = flatOptions[flatOptions.length - 1];
// otherwise try to restore the backup
} else if (bak !== null) {
newValue = bak;
changed = false;
}
this.currentOptions = flatOptions;
element.updateOptionElements(options);
element.value = newValue;
// just show if there is more than one
element.setVisible(options.length > 1);
return changed;
}
/**
* change the selected value programmatically
*/
setSelection(value: any) {
const element = <IFormSelectElement>this.accessor(this.formID);
element.value = value;
}
}
| datavisyn/tdp_core | src/views/SelectionChooser.ts | TypeScript | bsd-3-clause | 8,165 |
package com.gc.iotools.stream.os.inspection;
/*
* Copyright (c) 2008, 2014 Gabriele Contini. This source code is released
* under the BSD License.
*/
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;
import com.gc.iotools.stream.utils.StreamUtils;
/**
* <p>
* Gather some statistics on the <code>OutputStream</code> passed in the
* constructor.
* </p>
* <p>
* It can be used to read:
* <ul>
* <li>The size of the data written to the underlying stream.</li>
* <li>The time spent writing the bytes.</li>
* <li>The bandwidth of the underlying stream.</li>
* </ul>
* </p>
* <p>
* Full statistics are available after the stream has been fully processed (by
* other parts of the application), or after invoking the method
* {@linkplain #close()} while partial statistics are available on the fly.
* </p>
*
* @author dvd.smnt
* @since 1.2.6
* @version $Id$
*/
public class StatsOutputStream extends OutputStream {
private boolean closeCalled;
private final OutputStream innerOs;
private long size = 0;
private long time = 0;
/**
* Creates a new <code>SizeRecorderOutputStream</code> with the given
* destination stream.
*
* @param destination
* Destination stream where data are written.
*/
public StatsOutputStream(final OutputStream destination) {
this.innerOs = destination;
}
/** {@inheritDoc} */
@Override
public void close() throws IOException {
if (!this.closeCalled) {
this.closeCalled = true;
final long start = System.currentTimeMillis();
this.innerOs.close();
this.time += System.currentTimeMillis() - start;
}
}
/** {@inheritDoc} */
@Override
public void flush() throws IOException {
final long start = System.currentTimeMillis();
this.innerOs.flush();
this.time += System.currentTimeMillis() - start;
}
/**
* <p>
* Returns a string representation of the writing bit rate formatted with
* a convenient unit. The unit will change trying to keep not more than 3
* digits.
* </p>
*
* @return The bitRate of the stream.
* @since 1.2.2
*/
public String getBitRateString() {
return StreamUtils.getRateString(this.size, this.time);
}
/**
* Returns the number of bytes written until now.
*
* @return return the number of bytes written until now.
*/
public long getSize() {
return this.size;
}
/**
* <p>
* Returns the time spent waiting for the internal stream to write the
* data.
* </p>
*
* @param tu
* Unit to measure the time.
* @return time spent in waiting.
*/
public long getTime(final TimeUnit tu) {
return tu.convert(this.time, TimeUnit.MILLISECONDS);
}
/** {@inheritDoc} */
@Override
public void write(final byte[] b) throws IOException {
final long start = System.currentTimeMillis();
this.innerOs.write(b);
this.time += System.currentTimeMillis() - start;
this.size += b.length;
}
/** {@inheritDoc} */
@Override
public void write(final byte[] b, final int off, final int len)
throws IOException {
final long start = System.currentTimeMillis();
this.innerOs.write(b, off, len);
this.time += System.currentTimeMillis() - start;
this.size += len;
}
/** {@inheritDoc} */
@Override
public void write(final int b) throws IOException {
final long start = System.currentTimeMillis();
this.innerOs.write(b);
this.time += System.currentTimeMillis() - start;
this.size++;
}
}
| helderfpires/io-tools | easystream/src/main/java/com/gc/iotools/stream/os/inspection/StatsOutputStream.java | Java | bsd-3-clause | 3,428 |