repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
situx/POSTagger | src/main/java/com/github/situx/postagger/dict/chars/asian/JapaneseChar.java | 2740 | /*
* Copyright (C) 2017. Timo Homburg
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package com.github.situx.postagger.dict.chars.asian;
import com.github.situx.postagger.util.enums.methods.CharTypes;
/**
* Created by timo on 17.06.14.
* Class representing a Japanese word/char.
*/
public class JapaneseChar extends AsianChar {
public Boolean hiragana,katakana,kanji,romaji;
public JapaneseChar(String character){
super(character);this.charlength= CharTypes.JAPANESE.getChar_length();
}
/**
* Indicates if this character is a hiragana character.
* @return true if it is false otherwise
*/
public Boolean getHiragana() {
return hiragana;
}
/**
* Sets if this character is a hiragana character.
* @param hiragana hiragana indicator
*/
public void setHiragana(final Boolean hiragana) {
this.hiragana = hiragana;
}
/**
* Indicates if this character is a kanji character.
* @return true if it is false otherwise
*/
public Boolean getKanji() {
return kanji;
}
/**
* Sets if this chracter is a kanji character.
* @param kanji kanji indicator
*/
public void setKanji(final Boolean kanji) {
this.kanji = kanji;
}
/**
* Indicates if this character is a katakana character.
* @return true if it is false otherwise
*/
public Boolean getKatakana() {
return katakana;
}
/**
* Sets if this character is a katakana character.
* @param katakana katakana indicator
*/
public void setKatakana(final Boolean katakana) {
this.katakana = katakana;
}
/**
* Indicates if this character is a romaji character.
* @return true if it is false otherwise
*/
public Boolean getRomaji() {
return romaji;
}
/**
* Sets if this character is a romaji character.
* @param romaji romaji indicator
*/
public void setRomaji(final Boolean romaji) {
this.romaji = romaji;
}
}
| gpl-3.0 |
bishalgautam/CodePathII | week6/globitek 4/public/index.php | 642 | <?php
require_once('../private/initialize.php');
?>
<?php $page_title = 'Globitek'; ?>
<?php include(SHARED_PATH . '/header.php'); ?>
<?php include(SHARED_PATH . '/public_menu.php'); ?>
<div id="main-content">
<div id="home">
<h1>Welcome to Globitek!</h1>
<p style="width: 500px;">
Globitek is a world-wide industry leader with many award-winning products which have become well-known household names. Our staff of experts are dedicated to finding synergies across a wide variety of vertical markets and integrating technology into everyday life.
</p>
</div>
</div>
<?php include(SHARED_PATH . '/footer.php'); ?>
| gpl-3.0 |
illya13/ethermint | vendor/github.com/tendermint/abci/example/chain_aware/chain_aware_test.go | 1249 | package main
import (
"strconv"
"strings"
"testing"
. "github.com/tendermint/go-common"
"github.com/tendermint/abci/client"
"github.com/tendermint/abci/server"
"github.com/tendermint/abci/types"
)
func TestChainAware(t *testing.T) {
app := NewChainAwareApplication()
// Start the listener
srv, err := server.NewServer("unix://test.sock", "socket", app)
if err != nil {
t.Fatal(err)
}
defer srv.Stop()
// Connect to the socket
client, err := abcicli.NewSocketClient("unix://test.sock", false)
if err != nil {
Exit(Fmt("Error starting socket client: %v", err.Error()))
}
client.Start()
defer client.Stop()
n := uint64(5)
hash := []byte("fake block hash")
header := &types.Header{}
for i := uint64(0); i < n; i++ {
client.BeginBlockSync(hash, header)
client.EndBlockSync(i)
client.CommitSync()
}
r := app.Query(nil)
spl := strings.Split(string(r.Data), ",")
if len(spl) != 2 {
t.Fatal("expected %d,%d ; got %s", n, n, string(r.Data))
}
beginCount, _ := strconv.Atoi(spl[0])
endCount, _ := strconv.Atoi(spl[1])
if uint64(beginCount) != n {
t.Fatalf("expected beginCount of %d, got %d", n, beginCount)
} else if uint64(endCount) != n {
t.Fatalf("expected endCount of %d, got %d", n, endCount)
}
}
| gpl-3.0 |
kenshay/ImageScripter | ProgramData/SystemFiles/Python/Lib/site-packages/skimage/measure/tests/test_regionprops.py | 15332 | import math
import functools
import numpy as np
from skimage.measure._regionprops import (regionprops as regionprops_default,
PROPS, perimeter, _parse_docs)
from skimage._shared import testing
from skimage._shared.testing import (assert_array_equal, assert_almost_equal,
assert_array_almost_equal, assert_equal)
regionprops = functools.partial(regionprops_default, coordinates='rc')
SAMPLE = np.array(
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1],
[0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]]
)
INTENSITY_SAMPLE = SAMPLE.copy()
INTENSITY_SAMPLE[1, 9:11] = 2
SAMPLE_3D = np.zeros((6, 6, 6), dtype=np.uint8)
SAMPLE_3D[1:3, 1:3, 1:3] = 1
SAMPLE_3D[3, 2, 2] = 1
INTENSITY_SAMPLE_3D = SAMPLE_3D.copy()
def test_all_props():
region = regionprops(SAMPLE, INTENSITY_SAMPLE)[0]
for prop in PROPS:
assert_almost_equal(region[prop], getattr(region, PROPS[prop]))
def test_all_props_3d():
region = regionprops(SAMPLE_3D, INTENSITY_SAMPLE_3D)[0]
for prop in PROPS:
try:
assert_almost_equal(region[prop], getattr(region, PROPS[prop]))
except NotImplementedError:
pass
def test_dtype():
regionprops(np.zeros((10, 10), dtype=np.int))
regionprops(np.zeros((10, 10), dtype=np.uint))
with testing.raises(TypeError):
regionprops(np.zeros((10, 10), dtype=np.float))
with testing.raises(TypeError):
regionprops(np.zeros((10, 10), dtype=np.double))
def test_ndim():
regionprops(np.zeros((10, 10), dtype=np.int))
regionprops(np.zeros((10, 10, 1), dtype=np.int))
regionprops(np.zeros((10, 10, 1, 1), dtype=np.int))
regionprops(np.zeros((10, 10, 10), dtype=np.int))
with testing.raises(TypeError):
regionprops(np.zeros((10, 10, 10, 2), dtype=np.int))
def test_area():
area = regionprops(SAMPLE)[0].area
assert area == np.sum(SAMPLE)
area = regionprops(SAMPLE_3D)[0].area
assert area == np.sum(SAMPLE_3D)
def test_bbox():
bbox = regionprops(SAMPLE)[0].bbox
assert_array_almost_equal(bbox, (0, 0, SAMPLE.shape[0], SAMPLE.shape[1]))
SAMPLE_mod = SAMPLE.copy()
SAMPLE_mod[:, -1] = 0
bbox = regionprops(SAMPLE_mod)[0].bbox
assert_array_almost_equal(bbox, (0, 0, SAMPLE.shape[0], SAMPLE.shape[1]-1))
bbox = regionprops(SAMPLE_3D)[0].bbox
assert_array_almost_equal(bbox, (1, 1, 1, 4, 3, 3))
def test_bbox_area():
padded = np.pad(SAMPLE, 5, mode='constant')
bbox_area = regionprops(padded)[0].bbox_area
assert_array_almost_equal(bbox_area, SAMPLE.size)
def test_moments_central():
mu = regionprops(SAMPLE)[0].moments_central
# determined with OpenCV
assert_almost_equal(mu[2, 0], 436.00000000000045)
# different from OpenCV results, bug in OpenCV
assert_almost_equal(mu[3, 0], -737.333333333333)
assert_almost_equal(mu[1, 1], -87.33333333333303)
assert_almost_equal(mu[2, 1], -127.5555555555593)
assert_almost_equal(mu[0, 2], 1259.7777777777774)
assert_almost_equal(mu[1, 2], 2000.296296296291)
assert_almost_equal(mu[0, 3], -760.0246913580195)
def test_centroid():
centroid = regionprops(SAMPLE)[0].centroid
# determined with MATLAB
assert_array_almost_equal(centroid, (5.66666666666666, 9.444444444444444))
def test_centroid_3d():
centroid = regionprops(SAMPLE_3D)[0].centroid
# determined by mean along axis 1 of SAMPLE_3D.nonzero()
assert_array_almost_equal(centroid, (1.66666667, 1.55555556, 1.55555556))
def test_convex_area():
area = regionprops(SAMPLE)[0].convex_area
# determined with MATLAB
assert area == 124
def test_convex_image():
img = regionprops(SAMPLE)[0].convex_image
# determined with MATLAB
ref = np.array(
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
)
assert_array_equal(img, ref)
def test_coordinates():
sample = np.zeros((10, 10), dtype=np.int8)
coords = np.array([[3, 2], [3, 3], [3, 4]])
sample[coords[:, 0], coords[:, 1]] = 1
prop_coords = regionprops(sample)[0].coords
assert_array_equal(prop_coords, coords)
sample = np.zeros((6, 6, 6), dtype=np.int8)
coords = np.array([[1, 1, 1], [1, 2, 1], [1, 3, 1]])
sample[coords[:, 0], coords[:, 1], coords[:, 2]] = 1
prop_coords = regionprops(sample)[0].coords
assert_array_equal(prop_coords, coords)
def test_eccentricity():
eps = regionprops(SAMPLE)[0].eccentricity
assert_almost_equal(eps, 0.814629313427)
img = np.zeros((5, 5), dtype=np.int)
img[2, 2] = 1
eps = regionprops(img)[0].eccentricity
assert_almost_equal(eps, 0)
def test_equiv_diameter():
diameter = regionprops(SAMPLE)[0].equivalent_diameter
# determined with MATLAB
assert_almost_equal(diameter, 9.57461472963)
def test_euler_number():
en = regionprops(SAMPLE)[0].euler_number
assert en == 1
SAMPLE_mod = SAMPLE.copy()
SAMPLE_mod[7, -3] = 0
en = regionprops(SAMPLE_mod)[0].euler_number
assert en == 0
def test_extent():
extent = regionprops(SAMPLE)[0].extent
assert_almost_equal(extent, 0.4)
def test_moments_hu():
hu = regionprops(SAMPLE)[0].moments_hu
ref = np.array([
3.27117627e-01,
2.63869194e-02,
2.35390060e-02,
1.23151193e-03,
1.38882330e-06,
-2.72586158e-05,
-6.48350653e-06
])
# bug in OpenCV caused in Central Moments calculation?
assert_array_almost_equal(hu, ref)
def test_image():
img = regionprops(SAMPLE)[0].image
assert_array_equal(img, SAMPLE)
img = regionprops(SAMPLE_3D)[0].image
assert_array_equal(img, SAMPLE_3D[1:4, 1:3, 1:3])
def test_label():
label = regionprops(SAMPLE)[0].label
assert_array_equal(label, 1)
label = regionprops(SAMPLE_3D)[0].label
assert_array_equal(label, 1)
def test_filled_area():
area = regionprops(SAMPLE)[0].filled_area
assert area == np.sum(SAMPLE)
SAMPLE_mod = SAMPLE.copy()
SAMPLE_mod[7, -3] = 0
area = regionprops(SAMPLE_mod)[0].filled_area
assert area == np.sum(SAMPLE)
def test_filled_image():
img = regionprops(SAMPLE)[0].filled_image
assert_array_equal(img, SAMPLE)
def test_major_axis_length():
length = regionprops(SAMPLE)[0].major_axis_length
# MATLAB has different interpretation of ellipse than found in literature,
# here implemented as found in literature
assert_almost_equal(length, 16.7924234999)
def test_max_intensity():
intensity = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE
)[0].max_intensity
assert_almost_equal(intensity, 2)
def test_mean_intensity():
intensity = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE
)[0].mean_intensity
assert_almost_equal(intensity, 1.02777777777777)
def test_min_intensity():
intensity = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE
)[0].min_intensity
assert_almost_equal(intensity, 1)
def test_minor_axis_length():
length = regionprops(SAMPLE)[0].minor_axis_length
# MATLAB has different interpretation of ellipse than found in literature,
# here implemented as found in literature
assert_almost_equal(length, 9.739302807263)
def test_moments():
m = regionprops(SAMPLE)[0].moments.T # test was written with x/y coords
# determined with OpenCV
assert_almost_equal(m[0, 0], 72.0)
assert_almost_equal(m[0, 1], 408.0)
assert_almost_equal(m[0, 2], 2748.0)
assert_almost_equal(m[0, 3], 19776.0)
assert_almost_equal(m[1, 0], 680.0)
assert_almost_equal(m[1, 1], 3766.0)
assert_almost_equal(m[1, 2], 24836.0)
assert_almost_equal(m[2, 0], 7682.0)
assert_almost_equal(m[2, 1], 43882.0)
assert_almost_equal(m[3, 0], 95588.0)
def test_moments_normalized():
# test was written with x/y coords
nu = regionprops(SAMPLE)[0].moments_normalized.T
# determined with OpenCV
assert_almost_equal(nu[0, 2], 0.08410493827160502)
assert_almost_equal(nu[1, 1], -0.016846707818929982)
assert_almost_equal(nu[1, 2], -0.002899800614433943)
assert_almost_equal(nu[2, 0], 0.24301268861454037)
assert_almost_equal(nu[2, 1], 0.045473992910668816)
assert_almost_equal(nu[3, 0], -0.017278118992041805)
def test_orientation():
orientation = regionprops(SAMPLE, coordinates='xy')[0].orientation
# determined with MATLAB
assert_almost_equal(orientation, 0.10446844651921)
# test correct quadrant determination
orientation2 = regionprops(SAMPLE, coordinates='rc')[0].orientation
assert_almost_equal(orientation2, -math.pi / 2 + orientation)
# test diagonal regions
diag = np.eye(10, dtype=int)
orientation_diag = regionprops(diag, coordinates='xy')[0].orientation
assert_almost_equal(orientation_diag, -math.pi / 4)
orientation_diag = regionprops(np.flipud(diag))[0].orientation
assert_almost_equal(orientation_diag, math.pi / 4)
orientation_diag = regionprops(np.fliplr(diag))[0].orientation
assert_almost_equal(orientation_diag, math.pi / 4)
orientation_diag = regionprops(np.fliplr(np.flipud(diag)))[0].orientation
assert_almost_equal(orientation_diag, -math.pi / 4)
def test_perimeter():
per = regionprops(SAMPLE)[0].perimeter
assert_almost_equal(per, 55.2487373415)
per = perimeter(SAMPLE.astype('double'), neighbourhood=8)
assert_almost_equal(per, 46.8284271247)
def test_solidity():
solidity = regionprops(SAMPLE)[0].solidity
# determined with MATLAB
assert_almost_equal(solidity, 0.580645161290323)
def test_weighted_moments_central():
wmu = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE
)[0].weighted_moments_central.T # test used x/y coords
ref = np.array(
[[ 7.4000000000e+01, -2.1316282073e-13, 4.7837837838e+02,
-7.5943608473e+02],
[ 3.7303493627e-14, -8.7837837838e+01, -1.4801314828e+02,
-1.2714707125e+03],
[ 1.2602837838e+03, 2.1571526662e+03, 6.6989799420e+03,
1.5304076361e+04],
[ -7.6561796932e+02, -4.2385971907e+03, -9.9501164076e+03,
-3.3156729271e+04]]
)
np.set_printoptions(precision=10)
assert_array_almost_equal(wmu, ref)
def test_weighted_centroid():
centroid = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE
)[0].weighted_centroid
assert_array_almost_equal(centroid, (5.540540540540, 9.445945945945))
def test_weighted_moments_hu():
whu = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE
)[0].weighted_moments_hu
ref = np.array([
3.1750587329e-01,
2.1417517159e-02,
2.3609322038e-02,
1.2565683360e-03,
8.3014209421e-07,
-3.5073773473e-05,
-6.7936409056e-06
])
assert_array_almost_equal(whu, ref)
def test_weighted_moments():
wm = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE
)[0].weighted_moments.T # test used x/y coords
ref = np.array(
[[ 7.4000000000e+01, 4.1000000000e+02, 2.7500000000e+03,
1.9778000000e+04],
[ 6.9900000000e+02, 3.7850000000e+03, 2.4855000000e+04,
1.7500100000e+05],
[ 7.8630000000e+03, 4.4063000000e+04, 2.9347700000e+05,
2.0810510000e+06],
[ 9.7317000000e+04, 5.7256700000e+05, 3.9007170000e+06,
2.8078871000e+07]]
)
assert_array_almost_equal(wm, ref)
def test_weighted_moments_normalized():
wnu = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE
)[0].weighted_moments_normalized.T # test used x/y coord
ref = np.array(
[[ np.nan, np.nan, 0.0873590903, -0.0161217406],
[ np.nan, -0.0160405109, -0.0031421072, -0.0031376984],
[ 0.230146783, 0.0457932622, 0.0165315478, 0.0043903193],
[-0.0162529732, -0.0104598869, -0.0028544152, -0.0011057191]]
)
assert_array_almost_equal(wnu, ref)
def test_label_sequence():
a = np.empty((2, 2), dtype=np.int)
a[:, :] = 2
ps = regionprops(a)
assert len(ps) == 1
assert ps[0].label == 2
def test_pure_background():
a = np.zeros((2, 2), dtype=np.int)
ps = regionprops(a)
assert len(ps) == 0
def test_invalid():
ps = regionprops(SAMPLE)
def get_intensity_image():
ps[0].intensity_image
with testing.raises(AttributeError):
get_intensity_image()
def test_invalid_size():
wrong_intensity_sample = np.array([[1], [1]])
with testing.raises(ValueError):
regionprops(SAMPLE, wrong_intensity_sample)
def test_equals():
arr = np.zeros((100, 100), dtype=np.int)
arr[0:25, 0:25] = 1
arr[50:99, 50:99] = 2
regions = regionprops(arr)
r1 = regions[0]
regions = regionprops(arr)
r2 = regions[0]
r3 = regions[1]
assert_equal(r1 == r2, True, "Same regionprops are not equal")
assert_equal(r1 != r3, True, "Different regionprops are equal")
def test_iterate_all_props():
region = regionprops(SAMPLE)[0]
p0 = dict((p, region[p]) for p in region)
region = regionprops(SAMPLE, intensity_image=INTENSITY_SAMPLE)[0]
p1 = dict((p, region[p]) for p in region)
assert len(p0) < len(p1)
def test_cache():
region = regionprops(SAMPLE)[0]
f0 = region.filled_image
region._label_image[:10] = 1
f1 = region.filled_image
# Changed underlying image, but cache keeps result the same
assert_array_equal(f0, f1)
# Now invalidate cache
region._cache_active = False
f1 = region.filled_image
assert np.any(f0 != f1)
def test_docstrings_and_props():
region = regionprops(SAMPLE)[0]
docs = _parse_docs()
props = [m for m in dir(region) if not m.startswith('_')]
nr_docs_parsed = len(docs)
nr_props = len(props)
assert_equal(nr_docs_parsed, nr_props)
ds = docs['weighted_moments_normalized']
assert 'iteration' not in ds
assert len(ds.split('\n')) > 3
def test_incorrect_coordinate_convention():
with testing.raises(ValueError):
regionprops_default(SAMPLE, coordinates='xyz')[0]
| gpl-3.0 |
grapefruitinc/grapefruit | spec/factories/assignment_types.rb | 594 | # == Schema Information
#
# Table name: assignment_types
#
# id :integer not null, primary key
# name :string(255)
# default_point_value :float(24)
# drops_lowest :boolean
# percentage :float(24)
# course_id :integer
# created_at :datetime
# updated_at :datetime
#
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :assignment_type do
name "MyString"
default_point_value 1.5
drops_lowest ""
percentage 1.5
course_id 1
end
end
| gpl-3.0 |
AlexTMjugador/mtasa-blue | MTA10/core/CMainMenu.cpp | 42701 | /*****************************************************************************
*
* PROJECT: Multi Theft Auto v1.0
* LICENSE: See LICENSE in the top level directory
* FILE: core/CMainMenu.cpp
* PURPOSE: 2D Main menu graphical user interface
* DEVELOPERS: Cecill Etheredge <ijsf@gmx.net>
* Christian Myhre Lundheim <>
* Sebas Lamers <sebasdevelopment@gmx.com>
*
* Multi Theft Auto is available from http://www.multitheftauto.com/
*
*****************************************************************************/
#include "StdInc.h"
#include <game/CGame.h>
#include "CNewsBrowser.h"
#define NATIVE_RES_X 1280.0f
#define NATIVE_RES_Y 1024.0f
#define NATIVE_BG_X 1280.0f
#define NATIVE_BG_Y 649.0f
#define NATIVE_LOGO_X 1058.0f
#define NATIVE_LOGO_Y 540.0f
#define CORE_MTA_MENUITEMS_START_X 0.168
#define CORE_MTA_BG_MAX_ALPHA 1.00f //ACHTUNG: Set to 1 for now due to GTA main menu showing through (no delay inserted between Entering game... and loading screen)
#define CORE_MTA_BG_INGAME_ALPHA 0.90f
#define CORE_MTA_FADER 0.05f // 1/20
#define CORE_MTA_FADER_CREDITS 0.01f
#define CORE_MTA_HOVER_SCALE 1.0f
#define CORE_MTA_NORMAL_SCALE 0.6f
#define CORE_MTA_HOVER_ALPHA 1.0f
#define CORE_MTA_NORMAL_ALPHA 0.6f
#define CORE_MTA_HIDDEN_ALPHA 0.0f
#define CORE_MTA_DISABLED_ALPHA 0.4f
#define CORE_MTA_ENABLED_ALPHA 1.0f
#define CORE_MTA_ANIMATION_TIME 200
#define CORE_MTA_MOVE_ANIM_TIME 600
#define CORE_MTA_STATIC_BG "cgui\\images\\background.png"
#define CORE_MTA_LOGO "cgui\\images\\background_logo.png"
#define CORE_MTA_FILLER "cgui\\images\\mta_filler.png"
#define CORE_MTA_VERSION "cgui\\images\\version.png"
#define CORE_MTA_LATEST_NEWS "cgui\\images\\latest_news.png"
static int WaitForMenu = 0;
static const SColor headlineColors [] = { SColorRGBA ( 233, 234, 106, 255 ), SColorRGBA ( 233/6*4, 234/6*4, 106/6*4, 255 ), SColorRGBA ( 233/7*3, 234/7*3, 106/7*3, 255 ) };
// Improve alignment with magical mystery values!
static const int BODGE_FACTOR_1 = -5;
static const int BODGE_FACTOR_2 = 5;
static const int BODGE_FACTOR_3 = -5;
static const int BODGE_FACTOR_4 = 5;
static const CVector2D BODGE_FACTOR_5 ( 0,-50 );
static const CVector2D BODGE_FACTOR_6 ( 0,100 );
CMainMenu::CMainMenu ( CGUI* pManager )
{
m_pNewsBrowser = new CNewsBrowser ();
ulPreviousTick = GetTickCount32 ();
m_pHoveredItem = NULL;
m_iMoveStartPos = 0;
// Initialize
m_pManager = pManager;
m_bIsVisible = false;
m_bIsFullyVisible = false;
m_bIsIngame = true;
// m_bIsInSubWindow = false;
m_bStarted = false;
m_fFader = 0;
m_ucFade = FADE_INVISIBLE;
// Adjust window size to resolution
CVector2D ScreenSize = m_pManager->GetResolution ();
m_ScreenSize = ScreenSize;
int iBackgroundX = 0; int iBackgroundY = 0;
int iBackgroundSizeX = ScreenSize.fX; int iBackgroundSizeY;
// First let's work out our x and y offsets
if ( ScreenSize.fX > ScreenSize.fY ) //If the monitor is a normal landscape one
{
float iRatioSizeY = ScreenSize.fY / NATIVE_RES_Y;
m_iMenuSizeX = NATIVE_RES_X * iRatioSizeY;
m_iMenuSizeY = ScreenSize.fY;
m_iXOff = (ScreenSize.fX - m_iMenuSizeX)*0.5f;
m_iYOff = 0;
float iRatioSizeX = ScreenSize.fX / NATIVE_RES_X;
iBackgroundSizeX = ScreenSize.fX;
iBackgroundSizeY = NATIVE_BG_Y * iRatioSizeX;
}
else //Otherwise our monitor is in a portrait resolution, so we cant fill the background by y
{
float iRatioSizeX = ScreenSize.fX / NATIVE_RES_X;
m_iMenuSizeY = NATIVE_RES_Y * iRatioSizeX;
m_iMenuSizeX = ScreenSize.fX;
m_iXOff = 0;
m_iYOff = (ScreenSize.fY - m_iMenuSizeY)*0.5f;
iBackgroundY = m_iYOff;
iBackgroundSizeX = m_iMenuSizeX;
iBackgroundSizeY = NATIVE_BG_Y * iRatioSizeX;
}
// First create our filler black background image, which covers the whole screen
m_pFiller = reinterpret_cast < CGUIStaticImage* > ( pManager->CreateStaticImage () );
m_pFiller->LoadFromFile ( CORE_MTA_FILLER );
m_pFiller->SetVisible ( false );
m_pFiller->MoveToBack ();
m_pFiller->SetZOrderingEnabled ( false );
m_pFiller->SetAlwaysOnTop ( true );
m_pFiller->MoveToBack ();
m_pFiller->SetSize(CVector2D(ScreenSize.fX,iBackgroundY),false);
// Background image
m_pBackground = reinterpret_cast < CGUIStaticImage* > ( pManager->CreateStaticImage () );
m_pBackground->LoadFromFile ( CORE_MTA_STATIC_BG );
m_pBackground->SetProperty("InheritsAlpha", "False" );
m_pBackground->SetPosition ( CVector2D(iBackgroundX,iBackgroundY), false);
m_pBackground->SetSize ( CVector2D(iBackgroundSizeX,iBackgroundSizeY), false);
m_pBackground->SetZOrderingEnabled ( false );
m_pBackground->SetAlwaysOnTop ( true );
m_pBackground->MoveToBack ();
m_pBackground->SetAlpha(0);
m_pBackground->SetVisible ( false );
m_pFiller2 = reinterpret_cast < CGUIStaticImage* > ( pManager->CreateStaticImage () );
m_pFiller2->LoadFromFile ( CORE_MTA_FILLER );
m_pFiller2->SetVisible ( false );
m_pFiller2->SetZOrderingEnabled ( false );
m_pFiller2->SetAlwaysOnTop ( true );
m_pFiller2->MoveToBack ();
m_pFiller2->SetPosition(CVector2D(0,iBackgroundY + iBackgroundSizeY));
m_pFiller2->SetSize(ScreenSize,false);
m_pCanvas = reinterpret_cast < CGUIScrollPane* > ( pManager->CreateScrollPane () );
m_pCanvas->SetProperty ( "ContentPaneAutoSized", "False" );
m_pCanvas->SetPosition ( CVector2D(m_iXOff,m_iYOff), false);
m_pCanvas->SetSize ( CVector2D(m_iMenuSizeX,m_iMenuSizeY), false);
m_pCanvas->SetZOrderingEnabled ( false );
m_pCanvas->SetAlwaysOnTop ( true );
m_pCanvas->MoveToBack ();
m_pCanvas->SetVisible (false);
// Create our MTA logo
CVector2D logoSize = CVector2D( (NATIVE_LOGO_X/NATIVE_RES_X)*m_iMenuSizeX, (NATIVE_LOGO_Y/NATIVE_RES_Y)*m_iMenuSizeY );
m_pLogo = reinterpret_cast < CGUIStaticImage* > ( pManager->CreateStaticImage ( m_pCanvas ) );
m_pLogo->LoadFromFile ( CORE_MTA_LOGO );
m_pLogo->SetProperty("InheritsAlpha", "False" );
m_pLogo->SetSize ( logoSize, false);
m_pLogo->SetPosition ( CVector2D( 0.5f*m_iMenuSizeX - logoSize.fX/2, 0.365f*m_iMenuSizeY - logoSize.fY/2 ), false );
m_pLogo->SetZOrderingEnabled ( false );
// Create the image showing the version number
m_pVersion = reinterpret_cast < CGUIStaticImage* > ( pManager->CreateStaticImage () );
m_pVersion->LoadFromFile ( CORE_MTA_VERSION );
m_pVersion->SetParent ( m_pCanvas );
m_pVersion->SetPosition ( CVector2D(0.845f,0.528f), true);
m_pVersion->SetSize ( CVector2D((32/NATIVE_RES_X)*m_iMenuSizeX,(32/NATIVE_RES_Y)*m_iMenuSizeY), false);
m_pVersion->SetProperty("InheritsAlpha", "False" );
m_pCommunityLabel = reinterpret_cast < CGUILabel* > ( pManager->CreateLabel ( m_pFiller, "Not logged in" ) );
m_pCommunityLabel->AutoSize ( "Not logged in" );
m_pCommunityLabel->SetAlwaysOnTop ( true );
m_pCommunityLabel->SetAlpha ( 0 ); // disabled, previous alpha was 0.7f
m_pCommunityLabel->SetVisible ( false );
m_pCommunityLabel->SetPosition ( CVector2D ( 40.0f, ScreenSize.fY - 20.0f ) );
std::string strUsername;
CCore::GetSingleton().GetCommunity()->GetUsername ( strUsername );
if ( CCore::GetSingleton().GetCommunity()->IsLoggedIn() && !strUsername.empty() )
ChangeCommunityState ( true, strUsername );
float fBase = 0.613f;
float fGap = 0.043f;
// Our disconnect item is shown/hidden dynamically, so we store it seperately
m_pDisconnect = CreateItem ( MENU_ITEM_DISCONNECT, "menu_disconnect.png", CVector2D ( 0.168f, fBase + fGap * 0 ) );
m_pDisconnect->image->SetVisible(false);
// Create the menu items
//Filepath, Relative position, absolute native size
// And the font for the graphics is ?
m_menuItems.push_back ( CreateItem ( MENU_ITEM_QUICK_CONNECT, "menu_quick_connect.png", CVector2D ( 0.168f, fBase + fGap * 0 ) ) );
m_menuItems.push_back ( CreateItem ( MENU_ITEM_BROWSE_SERVERS, "menu_browse_servers.png", CVector2D ( 0.168f, fBase + fGap * 1 ) ) );
m_menuItems.push_back ( CreateItem ( MENU_ITEM_HOST_GAME, "menu_host_game.png", CVector2D ( 0.168f, fBase + fGap * 2 ) ) );
m_menuItems.push_back ( CreateItem ( MENU_ITEM_MAP_EDITOR, "menu_map_editor.png", CVector2D ( 0.168f, fBase + fGap * 3 ) ) );
m_menuItems.push_back ( CreateItem ( MENU_ITEM_SETTINGS, "menu_settings.png", CVector2D ( 0.168f, fBase + fGap * 4 ) ) );
m_menuItems.push_back ( CreateItem ( MENU_ITEM_ABOUT, "menu_about.png", CVector2D ( 0.168f, fBase + fGap * 5 ) ) );
m_menuItems.push_back ( CreateItem ( MENU_ITEM_QUIT, "menu_quit.png", CVector2D ( 0.168f, fBase + fGap * 6 ) ) );
// We store the position of the top item, and the second item. These will be useful later
float fFirstItemSize = m_menuItems.front()->image->GetSize(false).fY;
float fSecondItemSize = m_menuItems[1]->image->GetSize(false).fY;
m_iFirstItemCentre = (m_menuItems.front()->image)->GetPosition().fY + fFirstItemSize*0.5f;
m_iSecondItemCentre = (m_menuItems[1]->image)->GetPosition().fY + fSecondItemSize*0.5f;
// Store some mouse over bounding box positions
m_menuAX = (0.168f*m_iMenuSizeX) + m_iXOff; //Left side of the items
m_menuAY = m_iFirstItemCentre - fFirstItemSize*(CORE_MTA_HOVER_SCALE/CORE_MTA_NORMAL_SCALE)*0.5f; //Top side of the items
m_menuBX = m_menuAX + ((390/NATIVE_RES_X)*m_iMenuSizeX); //Right side of the items. We add the longest picture (browse_servers)
m_menuAY += BODGE_FACTOR_1;
m_pMenuArea = reinterpret_cast < CGUIStaticImage* > ( pManager->CreateStaticImage(m_pCanvas) );
m_pMenuArea->LoadFromFile ( CORE_MTA_FILLER );
m_pMenuArea->SetPosition ( CVector2D(m_menuAX-m_iXOff,m_menuAY-m_iYOff) + BODGE_FACTOR_5 , false);
m_pMenuArea->SetSize ( CVector2D(m_menuBX-m_menuAX,m_menuBY-m_menuAY) + BODGE_FACTOR_6, false);
m_pMenuArea->SetAlpha(0);
m_pMenuArea->SetZOrderingEnabled(false);
m_pMenuArea->SetClickHandler ( GUI_CALLBACK ( &CMainMenu::OnMenuClick, this ) );
m_pMenuArea->SetMouseEnterHandler ( GUI_CALLBACK ( &CMainMenu::OnMenuEnter, this ) );
m_pMenuArea->SetMouseLeaveHandler ( GUI_CALLBACK ( &CMainMenu::OnMenuExit, this ) );
float fDrawSizeX = (365/NATIVE_RES_X)*m_iMenuSizeX; //Right aligned
float fDrawSizeY = (52/NATIVE_RES_Y)*m_iMenuSizeY;
float fDrawPosX = 0.83f*m_iMenuSizeX - fDrawSizeX;
float fDrawPosY = 0.60f*m_iMenuSizeY;
m_pLatestNews = reinterpret_cast < CGUIStaticImage* > ( pManager->CreateStaticImage () );
m_pLatestNews->LoadFromFile ( CORE_MTA_LATEST_NEWS );
m_pLatestNews->SetParent ( m_pCanvas );
m_pLatestNews->SetPosition ( CVector2D(fDrawPosX,fDrawPosY), false);
m_pLatestNews->SetSize ( CVector2D(fDrawSizeX,fDrawSizeY), false);
m_pLatestNews->SetProperty("InheritsAlpha", "False" );
m_pLatestNews->SetVisible(false);
// Create news item stuff
fDrawPosX -= 25;
fDrawPosY += fDrawSizeY - 8;
for ( uint i = 0 ; i < CORE_MTA_NEWS_ITEMS ; i++ )
{
fDrawPosY += 20;
// Create our shadow and item
CGUILabel * pItemShadow = reinterpret_cast < CGUILabel* > ( m_pManager->CreateLabel ( m_pCanvas, " " ) );
CGUILabel * pItem = reinterpret_cast < CGUILabel* > ( m_pManager->CreateLabel ( m_pCanvas, " " ) );
pItem->SetFont ( "sans" );
pItemShadow->SetFont ( "sans" );
pItem->SetHorizontalAlign ( CGUI_ALIGN_RIGHT );
pItemShadow->SetHorizontalAlign ( CGUI_ALIGN_RIGHT );
pItem->SetSize( CVector2D (fDrawSizeX, 14), false );
pItemShadow->SetSize( CVector2D (fDrawSizeX, 15), false );
pItem->SetPosition( CVector2D (fDrawPosX, fDrawPosY), false );
pItemShadow->SetPosition( CVector2D (fDrawPosX + 1, fDrawPosY + 1), false );
pItemShadow->SetTextColor ( 112, 112, 112 );
// Set the handlers
pItem->SetClickHandler ( GUI_CALLBACK ( &CMainMenu::OnNewsButtonClick, this ) );
// Store the item in the array
m_pNewsItemLabels[i] = pItem;
m_pNewsItemShadowLabels[i] = pItemShadow;
// Create our date label
fDrawPosY += 15;
CGUILabel * pItemDate = reinterpret_cast < CGUILabel* > ( m_pManager->CreateLabel ( m_pCanvas, " " ) );
pItemDate->SetFont ( "default-small" );
pItemDate->SetHorizontalAlign ( CGUI_ALIGN_RIGHT );
pItemDate->SetSize( CVector2D (fDrawSizeX, 13), false );
pItemDate->SetPosition( CVector2D (fDrawPosX, fDrawPosY), false );
m_pNewsItemDateLabels[i] = pItemDate;
// Create 'NEW' sticker
CGUILabel*& pLabel = m_pNewsItemNEWLabels[i];
pLabel = reinterpret_cast < CGUILabel* > ( pManager->CreateLabel ( m_pCanvas, "NEW" ) );
pLabel->SetFont ( "default-small" );
pLabel->SetTextColor ( 255, 0, 0 );
pLabel->AutoSize ( pLabel->GetText ().c_str () );
pLabel->SetAlpha ( 0.7f );
pLabel->SetVisible ( false );
}
m_pLogo->MoveToBack ();
// Submenus
m_QuickConnect.SetVisible ( false );
m_ServerBrowser.SetVisible ( false );
m_ServerInfo.Hide ( );
m_Settings.SetVisible ( false );
m_Credits.SetVisible ( false );
m_pNewsBrowser->SetVisible ( false );
// We're not ingame
SetIsIngame ( false );
// Store the pointer to the graphics subsystem
m_pGraphics = CGraphics::GetSingletonPtr ();
// Load the server lists
CXMLNode* pConfig = CCore::GetSingletonPtr ()->GetConfig ();
m_ServerBrowser.LoadServerList ( pConfig->FindSubNode ( CONFIG_NODE_SERVER_FAV ),
CONFIG_FAVOURITE_LIST_TAG, m_ServerBrowser.GetFavouritesList () );
m_ServerBrowser.LoadServerList ( pConfig->FindSubNode ( CONFIG_NODE_SERVER_REC ),
CONFIG_RECENT_LIST_TAG, m_ServerBrowser.GetRecentList () );
m_ServerBrowser.LoadServerList ( pConfig->FindSubNode ( CONFIG_NODE_SERVER_HISTORY ),
CONFIG_HISTORY_LIST_TAG, m_ServerBrowser.GetHistoryList () );
// Remove unused node
if ( CXMLNode* pOldNode = pConfig->FindSubNode ( CONFIG_NODE_SERVER_INT ) )
pConfig->DeleteSubNode ( pOldNode );
}
CMainMenu::~CMainMenu ( void )
{
// Destroy GUI items
delete m_pBackground;
delete m_pCanvas;
delete m_pFiller;
delete m_pFiller2;
delete m_pLogo;
delete m_pLatestNews;
delete m_pVersion;
delete m_pMenuArea;
// Destroy community label
delete m_pCommunityLabel;
// Destroy the menu items. Note: The disconnect item isn't always in the
// list of menu items (it's only in there when we're in game). This means we
// don't delete it when we iterate the list and delete it separately - the
// menu item itself still exists even when it's no in the list of menu
// items. Perhaps there should be a separate list of loaded items really.
for ( std::deque<sMenuItem*>::iterator it = m_menuItems.begin(); it != m_menuItems.end(); ++it )
{
if ( (*it) != m_pDisconnect )
{
delete (*it)->image;
delete (*it);
}
}
delete m_pDisconnect->image;
delete m_pDisconnect;
}
void CMainMenu::SetMenuVerticalPosition ( int iPosY )
{
if ( m_pHoveredItem )
{
m_unhoveredItems.insert ( m_pHoveredItem );
m_pHoveredItem = NULL;
}
float fFirstItemSize = m_menuItems.front()->image->GetSize(false).fY;
int iMoveY = iPosY - m_menuItems.front()->image->GetPosition(false).fY - fFirstItemSize*0.5f;
std::deque<sMenuItem*>::iterator it = m_menuItems.begin();
for ( it; it != m_menuItems.end(); it++ )
{
CVector2D vOrigPos = (*it)->image->GetPosition(false);
(*it)->drawPositionY = (*it)->drawPositionY + iMoveY;
(*it)->image->SetPosition( CVector2D(vOrigPos.fX,vOrigPos.fY + iMoveY), false);
}
m_menuAY = m_menuAY + iMoveY;
m_menuBY = m_menuBY + iMoveY;
m_pMenuArea->SetPosition ( CVector2D(m_menuAX-m_iXOff,m_menuAY-m_iYOff) + BODGE_FACTOR_5 , false);
m_pMenuArea->SetSize ( CVector2D(m_menuBX-m_menuAX,m_menuBY-m_menuAY) + BODGE_FACTOR_6, false);
}
void CMainMenu::SetMenuUnhovered () //Dehighlight all our items
{
if ( m_bIsIngame ) //CEGUI hack
{
float fAlpha = m_pDisconnect->image->GetAlpha();
m_pDisconnect->image->SetAlpha(0.35f);
m_pDisconnect->image->SetAlpha(fAlpha);
SetItemHoverProgress ( m_pDisconnect, 0, false );
}
m_pHoveredItem = NULL;
std::deque<sMenuItem*>::iterator it = m_menuItems.begin();
for ( it; it != m_menuItems.end(); it++ )
{
SetItemHoverProgress ( (*it), 0, false );
}
}
void CMainMenu::Update ( void )
{
if ( g_pCore->GetDiagnosticDebug () == EDiagnosticDebug::JOYSTICK_0000 )
{
m_pFiller->SetVisible(false);
m_pFiller2->SetVisible(false);
m_pBackground->SetVisible(false);
m_bHideGame = false;
}
if ( m_bFrameDelay )
{
m_bFrameDelay = false;
return;
}
// Get the game interface and the system state
CGame* pGame = CCore::GetSingleton ().GetGame ();
eSystemState SystemState = pGame->GetSystemState ();
m_Credits.Update ();
m_Settings.Update ();
unsigned long ulCurrentTick = GetTickCount32();
unsigned long ulTimePassed = ulCurrentTick - ulPreviousTick;
if ( m_bHideGame )
m_pGraphics->DrawRectangle(0,0,m_ScreenSize.fX,m_ScreenSize.fY,0xFF000000);
if ( m_bIsIngame ) //CEGUI hack
{
float fAlpha = m_pDisconnect->image->GetAlpha();
m_pDisconnect->image->SetAlpha(0.35f);
m_pDisconnect->image->SetAlpha(fAlpha);
}
if ( m_bIsFullyVisible )
{
// Grab our cursor position
tagPOINT cursor;
GetCursorPos ( &cursor );
HWND hookedWindow = CCore::GetSingleton().GetHookedWindow();
tagPOINT windowPos = { 0 };
ClientToScreen( hookedWindow, &windowPos );
CVector2D vecResolution = CCore::GetSingleton ().GetGUI ()->GetResolution ();
cursor.x -= windowPos.x;
cursor.y -= windowPos.y;
if ( cursor.x < 0 )
cursor.x = 0;
else if ( cursor.x > ( long ) vecResolution.fX )
cursor.x = ( long ) vecResolution.fX;
if ( cursor.y < 0 )
cursor.y = 0;
else if ( cursor.y > ( long ) vecResolution.fY )
cursor.y = ( long ) vecResolution.fY;
// If we're within our highlight bounding box
if ( m_bMouseOverMenu && ( cursor.x > m_menuAX ) && ( cursor.y > m_menuAY + BODGE_FACTOR_3 ) && ( cursor.x < m_menuBX ) && ( cursor.y < m_menuBY + BODGE_FACTOR_4 ) )
{
float fHoveredIndex = ((cursor.y-m_menuAY) / (float)(m_menuBY-m_menuAY) * m_menuItems.size());
fHoveredIndex = Clamp <float> ( 0, fHoveredIndex, m_menuItems.size()-1 );
sMenuItem* pItem = m_menuItems[(int)floor(fHoveredIndex)];
int iSizeX = (pItem->nativeSizeX/NATIVE_RES_X)*m_iMenuSizeX;
if (cursor.x < (iSizeX + m_menuAX) )
{
if ( ( m_pHoveredItem ) && ( m_pHoveredItem != pItem ) )
{
m_unhoveredItems.insert(m_pHoveredItem);
m_pHoveredItem = pItem;
}
else
{
m_pHoveredItem = NULL;
}
m_pHoveredItem = pItem;
}
else if ( m_pHoveredItem )
{
m_unhoveredItems.insert(m_pHoveredItem);
m_pHoveredItem = NULL;
}
if ( m_pHoveredItem )
{
float fProgress = (m_pHoveredItem->image->GetAlpha()-CORE_MTA_NORMAL_ALPHA)/(CORE_MTA_HOVER_ALPHA - CORE_MTA_NORMAL_ALPHA);
// Let's work out what the target progress should be by working out the time passed
fProgress = ((float)ulTimePassed/CORE_MTA_ANIMATION_TIME)*(CORE_MTA_HOVER_ALPHA-CORE_MTA_NORMAL_ALPHA) + fProgress;
MapRemove ( m_unhoveredItems, m_pHoveredItem );
SetItemHoverProgress ( m_pHoveredItem, fProgress, true );
}
}
else if ( m_pHoveredItem )
{
m_unhoveredItems.insert(m_pHoveredItem);
m_pHoveredItem = NULL;
}
// Let's unhover our recently un-moused over items
std::set<sMenuItem*>::iterator it = m_unhoveredItems.begin();
while (it != m_unhoveredItems.end())
{
float fProgress = ((*it)->image->GetAlpha()-CORE_MTA_NORMAL_ALPHA)/(CORE_MTA_HOVER_ALPHA - CORE_MTA_NORMAL_ALPHA);
// Let's work out what the target progress should be by working out the time passed
// Min of 0.5 progress fixes occasional graphical glitchekal
fProgress = fProgress - Min ( 0.5f, ((float)ulTimePassed/CORE_MTA_ANIMATION_TIME)*(CORE_MTA_HOVER_ALPHA-CORE_MTA_NORMAL_ALPHA) );
if ( SetItemHoverProgress ( (*it), fProgress, false ) )
{
std::set<sMenuItem*>::iterator itToErase = it++;
m_unhoveredItems.erase(itToErase);
}
else
it++;
}
}
if ( m_iMoveStartPos )
{
float fTickDifference = ulCurrentTick - m_ulMoveStartTick;
float fMoveTime = (fTickDifference/CORE_MTA_MOVE_ANIM_TIME);
fMoveTime = Clamp <float> ( 0, fMoveTime, 1 );
// Use OutQuad easing to smoothen the movement
fMoveTime = -fMoveTime*(fMoveTime-2);
SetMenuVerticalPosition ( fMoveTime*(m_iMoveTargetPos - m_iMoveStartPos) + m_iMoveStartPos );
m_pDisconnect->image->SetAlpha ( m_bIsIngame ? fMoveTime*CORE_MTA_NORMAL_ALPHA : (1-fMoveTime)*CORE_MTA_NORMAL_ALPHA );
if ( fMoveTime == 1 )
{
m_iMoveStartPos = 0;
if ( !m_bIsIngame )
m_pDisconnect->image->SetVisible(false);
else
{
m_menuItems.push_front(m_pDisconnect);
m_pDisconnect->image->SetVisible(true);
float fTopItemSize = m_pDisconnect->image->GetSize(false).fY;
float fTopItemCentre = m_pDisconnect->image->GetPosition(false).fY + fTopItemSize*0.5f;
m_menuAY = fTopItemCentre - fTopItemSize*(CORE_MTA_HOVER_SCALE/CORE_MTA_NORMAL_SCALE)*0.5f; //Top side of the items
m_menuAY += BODGE_FACTOR_1;
m_pMenuArea->SetPosition ( CVector2D(m_menuAX-m_iXOff,m_menuAY-m_iYOff) + BODGE_FACTOR_5 , false);
m_pMenuArea->SetSize ( CVector2D(m_menuBX-m_menuAX,m_menuBY-m_menuAY) + BODGE_FACTOR_6, false);
}
}
}
// Fade in
if ( m_ucFade == FADE_IN ) {
// Increment the fader (use the other define if we're fading to the credits)
m_fFader += CORE_MTA_FADER;
float fFadeTarget = m_bIsIngame ? CORE_MTA_BG_INGAME_ALPHA : CORE_MTA_BG_MAX_ALPHA;
m_pFiller->SetAlpha ( Clamp <float> ( 0.f, m_fFader, CORE_MTA_BG_MAX_ALPHA ) );
m_pFiller2->SetAlpha ( Clamp <float> ( 0.f, m_fFader, CORE_MTA_BG_MAX_ALPHA ) );
m_pCanvas->SetAlpha ( Clamp <float> ( 0.f, m_fFader, CORE_MTA_BG_MAX_ALPHA ) );
m_pBackground->SetAlpha ( Clamp <float> ( 0.f, m_fFader, CORE_MTA_BG_MAX_ALPHA ) );
if ( m_fFader > 0.0f )
{
m_bIsVisible = true; // Make cursor appear faster
}
// If the fade is complete
if ( m_fFader >= fFadeTarget ) {
m_ucFade = FADE_VISIBLE;
m_bIsVisible = true;
m_bIsFullyVisible = true;
}
}
// Fade out
else if ( m_ucFade == FADE_OUT ) {
m_fFader -= CORE_MTA_FADER;
m_pFiller->SetAlpha ( Clamp ( 0.f, m_fFader, CORE_MTA_BG_MAX_ALPHA ) );
m_pFiller2->SetAlpha ( Clamp ( 0.f, m_fFader, CORE_MTA_BG_MAX_ALPHA ) );
m_pCanvas->SetAlpha ( Clamp ( 0.f, m_fFader, CORE_MTA_BG_MAX_ALPHA ) );
m_pBackground->SetAlpha ( Clamp ( 0.f, m_fFader, CORE_MTA_BG_MAX_ALPHA ) );
if ( m_fFader < 1.0f )
m_bIsVisible = false; // Make cursor disappear faster
// If the fade is complete
if ( m_fFader <= 0 ) {
m_bIsFullyVisible = false;
m_ucFade = FADE_INVISIBLE;
m_bIsVisible = false;
// Turn the widgets invisible
m_pFiller->SetVisible ( false );
m_pFiller2->SetVisible ( false );
m_pCanvas->SetVisible(false);
m_pBackground->SetVisible(false);
}
}
// Force the mainmenu on if we're at GTA's mainmenu or not ingame
if ( ( SystemState == 7 || SystemState == 9 ) && !m_bIsIngame )
{
// Cope with early finish
if ( pGame->HasCreditScreenFadedOut () )
WaitForMenu = Max ( WaitForMenu, 250 );
// Fade up
if ( WaitForMenu >= 250 )
{
m_bIsVisible = true;
m_bStarted = true;
}
// Create headlines while the screen is still black
if ( WaitForMenu == 250 )
m_pNewsBrowser->CreateHeadlines ();
// Start updater after fade up is complete
if ( WaitForMenu == 275 )
GetVersionUpdater ()->EnableChecking ( true );
if ( WaitForMenu < 300 )
WaitForMenu++;
}
// If we're visible
if ( m_bIsVisible && SystemState != 8 )
{
// If we're at the game's mainmenu, or ingame when m_bIsIngame is true show the background
if ( SystemState == 7 || // GS_FRONTEND
SystemState == 9 && !m_bIsIngame ) // GS_PLAYING_GAME
{
if ( m_ucFade == FADE_INVISIBLE )
Show ( false );
}
else
{
if ( m_ucFade == FADE_INVISIBLE )
Show ( true );
}
}
else
{
if ( m_ucFade == FADE_VISIBLE )
Hide ();
}
ulPreviousTick = GetTickCount32();
// Call subdialog pulses
m_ServerBrowser.Update ();
m_ServerInfo.DoPulse ();
}
void CMainMenu::Show ( bool bOverlay )
{
SetVisible ( true, bOverlay );
}
void CMainMenu::Hide ( void )
{
SetVisible ( false );
}
// When escape key pressed and not connected, hide these windows
void CMainMenu::OnEscapePressedOffLine ( void )
{
m_ServerBrowser.SetVisible ( false );
m_Credits.SetVisible ( false );
m_pNewsBrowser->SetVisible ( false );
}
void CMainMenu::SetVisible ( bool bVisible, bool bOverlay, bool bFrameDelay )
{
CMultiplayer* pMultiplayer = CCore::GetSingleton ().GetMultiplayer ();
pMultiplayer->DisablePadHandler ( bVisible );
if ( ( m_ucFade == FADE_VISIBLE || m_ucFade == FADE_IN ) && bVisible == false ) {
m_ucFade = FADE_OUT;
} else if ( ( m_ucFade == FADE_INVISIBLE || m_ucFade == FADE_OUT ) && bVisible == true ) {
m_ucFade = FADE_IN;
}
// If we're hiding, hide any subwindows we might've had (prevent escaping hiding mousecursor issue)
if ( !bVisible )
{
m_bFrameDelay = bFrameDelay;
SetMenuUnhovered ();
m_QuickConnect.SetVisible ( false );
m_ServerBrowser.SetVisible ( false );
m_Settings.SetVisible ( false );
m_Credits.SetVisible ( false );
m_pCommunityLabel->SetVisible ( false );
m_pNewsBrowser->SetVisible ( false );
// m_bIsInSubWindow = false;
} else {
m_bFrameDelay = bFrameDelay;
SetMenuUnhovered ();
m_pFiller->SetVisible ( true );
m_pFiller2->SetVisible ( true );
m_pCanvas->SetVisible( true );
m_pBackground->SetVisible ( true );
m_pCommunityLabel->SetVisible ( true );
}
m_bHideGame = !bOverlay;
}
bool CMainMenu::IsVisible ( void )
{
return m_bIsVisible;
}
void CMainMenu::SetIsIngame ( bool bIsIngame )
{
// Save some performance by making sure we don't do all this if the new state == old
if ( m_bIsIngame != bIsIngame )
{
m_bIsIngame = bIsIngame;
m_Settings.SetIsModLoaded ( bIsIngame );
m_ulMoveStartTick = GetTickCount32();
if ( bIsIngame )
{
m_iMoveTargetPos = m_iSecondItemCentre;
}
else
{
if ( m_menuItems.front() == m_pDisconnect )
m_menuItems.pop_front();
float fTopItemSize = m_menuItems.front()->image->GetSize(false).fY;
float fTopItemCentre = m_menuItems.front()->image->GetPosition(false).fY + fTopItemSize*0.5f;
m_menuAY = fTopItemCentre - fTopItemSize*(CORE_MTA_HOVER_SCALE/CORE_MTA_NORMAL_SCALE)*0.5f;
m_menuAY += BODGE_FACTOR_1;
m_pMenuArea->SetPosition ( CVector2D(m_menuAX-m_iXOff,m_menuAY-m_iYOff) + BODGE_FACTOR_5 , false);
m_pMenuArea->SetSize ( CVector2D(m_menuBX-m_menuAX,m_menuBY-m_menuAY) + BODGE_FACTOR_6, false);
m_iMoveTargetPos = m_iFirstItemCentre;
}
m_iMoveStartPos = m_menuAY;
}
}
bool CMainMenu::GetIsIngame ( void )
{
return m_bIsIngame;
}
bool CMainMenu::OnMenuEnter ( CGUIElement* pElement )
{
m_bMouseOverMenu = true;
return true;
}
bool CMainMenu::OnMenuExit ( CGUIElement* pElement )
{
m_bMouseOverMenu = false;
return true;
}
bool CMainMenu::OnMenuClick ( CGUIElement* pElement )
{
// Handle all our clicks to the menu from here
if ( m_pHoveredItem )
{
// For detecting startup problems
WatchDogUserDidInteractWithMenu();
// Possible disconnect question for user
if ( g_pCore->IsConnected() )
{
switch (m_pHoveredItem->menuType)
{
case MENU_ITEM_HOST_GAME:
case MENU_ITEM_MAP_EDITOR:
AskUserIfHeWantsToDisconnect( m_pHoveredItem->menuType );
return true;
default: break;
}
}
switch (m_pHoveredItem->menuType)
{
case MENU_ITEM_DISCONNECT: OnDisconnectButtonClick (pElement); break;
case MENU_ITEM_QUICK_CONNECT: OnQuickConnectButtonClick (pElement); break;
case MENU_ITEM_BROWSE_SERVERS: OnBrowseServersButtonClick(pElement); break;
case MENU_ITEM_HOST_GAME: OnHostGameButtonClick (); break;
case MENU_ITEM_MAP_EDITOR: OnEditorButtonClick (); break;
case MENU_ITEM_SETTINGS: OnSettingsButtonClick (pElement); break;
case MENU_ITEM_ABOUT: OnAboutButtonClick (pElement); break;
case MENU_ITEM_QUIT: OnQuitButtonClick (pElement); break;
default: break;
}
}
return true;
}
bool CMainMenu::OnQuickConnectButtonClick ( CGUIElement* pElement )
{
// Return if we haven't faded in yet
if ( m_ucFade != FADE_VISIBLE ) return false;
m_ServerBrowser.SetVisible ( true );
m_ServerBrowser.OnQuickConnectButtonClick ();
/*
// if ( !m_bIsInSubWindow )
{
m_QuickConnect.SetVisible ( true );
// m_bIsInSubWindow = true;
}
*/
return true;
}
bool CMainMenu::OnResumeButtonClick ( CGUIElement* pElement )
{
// Return if we haven't faded in yet
if ( m_ucFade != FADE_VISIBLE ) return false;
SetVisible ( false );
return true;
}
bool CMainMenu::OnBrowseServersButtonClick ( CGUIElement* pElement )
{
// Return if we haven't faded in yet
if ( m_ucFade != FADE_VISIBLE ) return false;
// if ( !m_bIsInSubWindow )
{
m_ServerBrowser.SetVisible ( true );
// m_bIsInSubWindow = true;
}
return true;
}
void CMainMenu::HideServerInfo ( void )
{
m_ServerInfo.Hide ( );
}
bool CMainMenu::OnDisconnectButtonClick ( CGUIElement* pElement )
{
// Return if we haven't faded in yet
if ( m_ucFade != FADE_VISIBLE ) return false;
// Send "disconnect" command to the command handler
CCommands::GetSingleton ().Execute ( "disconnect", "" );
return true;
}
bool CMainMenu::OnHostGameButtonClick ( void )
{
// Return if we haven't faded in yet
if ( m_ucFade != FADE_VISIBLE ) return false;
// Load deathmatch, but with local play
CModManager::GetSingleton ().RequestLoad ( "deathmatch", "local" );
return true;
}
bool CMainMenu::OnEditorButtonClick ( void )
{
// Return if we haven't faded in yet
if ( m_ucFade != FADE_VISIBLE ) return false;
// Load deathmatch, but with local play
CModManager::GetSingleton ().RequestLoad ( "deathmatch", "editor" );
return true;
}
bool CMainMenu::OnSettingsButtonClick ( CGUIElement* pElement )
{
// Return if we haven't faded in yet
if ( m_ucFade != FADE_VISIBLE ) return false;
// if ( !m_bIsInSubWindow )
{
m_Settings.SetVisible ( true );
// Jax: not sure why this was commented, need it here if our main-menu is set to AlwaysOnTop
// m_bIsInSubWindow = true;
}
return true;
}
bool CMainMenu::OnAboutButtonClick ( CGUIElement* pElement )
{
// Return if we haven't faded in yet
if ( m_ucFade != FADE_VISIBLE ) return false;
// Determine if we're ingame or if the background is set to static
// If so, show the old credits dialog
m_Credits.SetVisible ( true );
return true;
}
bool CMainMenu::OnQuitButtonClick ( CGUIElement* pElement )
{
// Return if we haven't faded in yet
if ( m_ucFade != FADE_VISIBLE ) return false;
// Send "exit" command to the command handler
CCommands::GetSingleton ().Execute ( "exit", "" );
return true;
}
bool CMainMenu::OnNewsButtonClick ( CGUIElement* pElement )
{
// Return if we haven't faded in yet
if ( m_ucFade != FADE_VISIBLE ) return false;
int iIndex = 0;
if ( pElement )
{
// Calc index from color
CGUIColor color = dynamic_cast < CGUILabel* > ( pElement )->GetTextColor ();
for ( uint i = 0 ; i < NUMELMS ( headlineColors ) ; i++ )
if ( color.R == headlineColors[i].R )
iIndex = i;
}
m_pNewsBrowser->SetVisible ( true );
m_pNewsBrowser->SwitchToTab ( iIndex );
return true;
}
sMenuItem* CMainMenu::CreateItem ( unsigned char menuType, const char* szFilename, CVector2D vecRelPosition )
{
CGUIStaticImage* pImage = reinterpret_cast < CGUIStaticImage* > ( m_pManager->CreateStaticImage () );
if ( g_pCore->GetLocalization()->IsLocalized() )
{
if ( !pImage->LoadFromFile ( PathJoin(g_pCore->GetLocalization()->GetLanguageDirectory(),szFilename) ) )
pImage->LoadFromFile ( PathJoin("cgui/images",szFilename) );
}
else
pImage->LoadFromFile ( PathJoin("cgui/images",szFilename) );
// Make our positions absolute
int iPosX = vecRelPosition.fX*m_iMenuSizeX;
int iPosY = vecRelPosition.fY*m_iMenuSizeY;
// Make our sizes relative to the size of menu, but in absolute coordinates
CVector2D vecNativeSize;
pImage->GetNativeSize(vecNativeSize);
int iSizeX = (vecNativeSize.fX/NATIVE_RES_X)*m_iMenuSizeX;
int iSizeY = (vecNativeSize.fY/NATIVE_RES_Y)*m_iMenuSizeY;
// Mark our bounding box's bottom value.
m_menuBY = (iPosY + (iSizeY*CORE_MTA_HOVER_SCALE)/2) + m_iYOff;
m_menuBY += BODGE_FACTOR_2;
// Reduced their size down to unhovered size.
iSizeX = iSizeX*CORE_MTA_NORMAL_SCALE;
iSizeY = iSizeY*CORE_MTA_NORMAL_SCALE;
// Grab our draw position from which we enlarge from
iPosY = iPosY - (iSizeY/2);
pImage->SetParent ( m_pCanvas );
pImage->SetPosition ( CVector2D(iPosX,iPosY), false);
pImage->SetSize ( CVector2D(iSizeX,iSizeY), false);
pImage->SetProperty("InheritsAlpha", "False" );
pImage->SetAlpha ( CORE_MTA_NORMAL_ALPHA );
sMenuItem* s = new sMenuItem();
s->menuType = menuType;
s->drawPositionX = vecRelPosition.fX*m_iMenuSizeX;
s->drawPositionY = vecRelPosition.fY*m_iMenuSizeY;
s->nativeSizeX = vecNativeSize.fX;
s->nativeSizeY = vecNativeSize.fY;
s->image = pImage;
return s;
}
bool CMainMenu::SetItemHoverProgress ( sMenuItem* pItem, float fProgress, bool bHovering )
{
fProgress = Clamp <float> ( 0, fProgress, 1 );
// Use OutQuad equation for easing, or OutQuad for unhovering
fProgress = bHovering ? -fProgress*(fProgress-2) : fProgress*fProgress;
// Work out the target scale
float fTargetScale = (CORE_MTA_HOVER_SCALE-CORE_MTA_NORMAL_SCALE)*(fProgress) + CORE_MTA_NORMAL_SCALE;
// Work out our current progress based upon the alpha value now
pItem->image->SetAlpha ( (CORE_MTA_HOVER_ALPHA-CORE_MTA_NORMAL_ALPHA)*(fProgress) + CORE_MTA_NORMAL_ALPHA );
int iSizeX = (pItem->nativeSizeX/NATIVE_RES_X)*m_iMenuSizeX*fTargetScale;
int iSizeY = (pItem->nativeSizeY/NATIVE_RES_Y)*m_iMenuSizeY*fTargetScale;
// Aligned to the left horizontally, aligned to the centre vertically
int iPosX = pItem->drawPositionX;
int iPosY = (pItem->drawPositionY) - (iSizeY*0.5);
pItem->image->SetPosition ( CVector2D(iPosX, iPosY), false );
pItem->image->SetSize ( CVector2D(iSizeX, iSizeY), false );
//Return whether the hovering has maxed out
return bHovering ? (fProgress == 1) : (fProgress == 0);
}
void CMainMenu::ChangeCommunityState ( bool bIn, const std::string& strUsername )
{
if ( bIn )
{
SString strText ( "Logged in as: %s", strUsername.c_str () );
m_pCommunityLabel->SetText ( strText );
m_pCommunityLabel->AutoSize ( strText );
return;
}
m_pCommunityLabel->SetText ( "Not logged in" );
m_pCommunityLabel->AutoSize ( "Not logged in" );
}
void CMainMenu::SetNewsHeadline ( int iIndex, const SString& strHeadline, const SString& strDate, bool bIsNew )
{
if ( iIndex < 0 || iIndex > 2 )
return;
m_pLatestNews->SetVisible(true);
// Headline
CGUILabel* pItem = m_pNewsItemLabels[ iIndex ];
CGUILabel* pItemShadow = m_pNewsItemShadowLabels[ iIndex ];
SColor color = headlineColors[ iIndex ];
pItem->SetTextColor ( color.R, color.G, color.B );
pItem->SetText ( strHeadline );
pItemShadow->SetText ( strHeadline );
// Switch font if it's too big
if ( pItem->GetSize(false).fX < pItem->GetTextExtent() )
{
const char* szFontName = "default-bold-small";
for ( char i=0; i < CORE_MTA_NEWS_ITEMS; i++ )
{
// Try default-bold-small first, if that's too big use default-small
m_pNewsItemLabels[ i ]->SetFont ( szFontName );
m_pNewsItemShadowLabels[ i ]->SetFont ( szFontName );
if ( strcmp(szFontName,"default-small") && ( m_pNewsItemLabels[ i ]->GetSize(false).fX < m_pNewsItemLabels[ i ]->GetTextExtent() ) )
{
szFontName = "default-small";
i = -1;
}
}
}
// Set our Date labels
CGUILabel* pItemDate = m_pNewsItemDateLabels[ iIndex ];
pItemDate->SetText ( strDate );
// 'NEW' sticker
CGUILabel* pNewLabel = m_pNewsItemNEWLabels[ iIndex ];
pNewLabel->SetVisible ( bIsNew );
pNewLabel->SetPosition ( CVector2D ( pItem->GetPosition ().fX + 4, pItem->GetPosition ().fY - 4 ) );
}
/////////////////////////////////////////////////////////////
//
// CMainMenu::AskUserIfHeWantsToDisconnect
//
// Ask user if he wants to disconnect
//
/////////////////////////////////////////////////////////////
void CMainMenu::AskUserIfHeWantsToDisconnect ( uchar menuType )
{
SStringX strMessage ( _("This will disconnect you from the current server."
"\n\nAre you sure you want to disconnect?" ) );
CQuestionBox* pQuestionBox = CCore::GetSingleton ().GetLocalGUI ()->GetMainMenu ()->GetQuestionWindow ();
pQuestionBox->Reset ();
pQuestionBox->SetTitle ( _("DISCONNECT WARNING") );
pQuestionBox->SetMessage ( strMessage );
pQuestionBox->SetButton ( 0, _("No") );
pQuestionBox->SetButton ( 1, _("Yes") );
pQuestionBox->SetCallback ( StaticWantsToDisconnectCallBack, (void*)menuType );
pQuestionBox->Show ();
}
/////////////////////////////////////////////////////////////
//
// CMainMenu::StaticWantsToDisconnectCallBack
//
// Callback from disconnect question
//
/////////////////////////////////////////////////////////////
void CMainMenu::StaticWantsToDisconnectCallBack( void* pData, uint uiButton )
{
CLocalGUI::GetSingleton ().GetMainMenu ()->WantsToDisconnectCallBack( pData, uiButton );
}
/////////////////////////////////////////////////////////////
//
// CMainMenu::WantsToDisconnectCallBack
//
// Callback from disconnect question.
// If user says it's ok, continue with menu item selection
//
/////////////////////////////////////////////////////////////
void CMainMenu::WantsToDisconnectCallBack( void* pData, uint uiButton )
{
CCore::GetSingleton ().GetLocalGUI ()->GetMainMenu ()->GetQuestionWindow ()->Reset ();
if ( uiButton == 1 )
{
uchar menuType = (uchar)pData;
switch( menuType )
{
case MENU_ITEM_HOST_GAME: OnHostGameButtonClick (); break;
case MENU_ITEM_MAP_EDITOR: OnEditorButtonClick (); break;
default: break;
}
}
}
| gpl-3.0 |
cppisfun/GameEngine | foreign/boost/libs/mpl/preprocessed/list/list50.cpp | 518 |
// Copyright Aleksey Gurtovoy 2002-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: list50.cpp 49268 2008-10-11 06:26:17Z agurtovoy $
// $Date: 2008-10-10 23:26:17 -0700 (Fri, 10 Oct 2008) $
// $Revision: 49268 $
#define BOOST_MPL_PREPROCESSING_MODE
#include <boost/config.hpp>
#include <boost/mpl/list/list50.hpp>
| gpl-3.0 |
Radarr/Radarr | src/NzbDrone.Core.Test/MovieTests/MovieIsAvailableFixture.cs | 6227 | using System;
using FizzWare.NBuilder;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Core.Movies;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.MovieTests
{
[TestFixture]
public class MovieIsAvailableFixture : CoreTest
{
private Movie _movie;
[SetUp]
public void Setup()
{
_movie = Builder<Movie>.CreateNew()
.Build();
}
private void SetMovieProperties(DateTime? cinema, DateTime? physical, DateTime? digital, MovieStatusType minimumAvailability)
{
_movie.InCinemas = cinema;
_movie.PhysicalRelease = physical;
_movie.DigitalRelease = digital;
_movie.MinimumAvailability = minimumAvailability;
}
//minAvail = TBA
[TestCase(null, null, null, MovieStatusType.TBA, true)]
[TestCase("2000/01/01 21:10:42", null, null, MovieStatusType.TBA, true)]
[TestCase("2100/01/01 21:10:42", null, null, MovieStatusType.TBA, true)]
[TestCase(null, "2000/01/01 21:10:42", null, MovieStatusType.TBA, true)]
[TestCase(null, "2100/01/01 21:10:42", null, MovieStatusType.TBA, true)]
[TestCase(null, null, "2000/01/01 21:10:42", MovieStatusType.TBA, true)]
[TestCase(null, null, "2100/01/01 21:10:42", MovieStatusType.TBA, true)]
//minAvail = Announced
[TestCase(null, null, null, MovieStatusType.Announced, true)]
[TestCase("2000/01/01 21:10:42", null, null, MovieStatusType.Announced, true)]
[TestCase("2100/01/01 21:10:42", null, null, MovieStatusType.Announced, true)]
[TestCase(null, "2000/01/01 21:10:42", null, MovieStatusType.Announced, true)]
[TestCase(null, "2100/01/01 21:10:42", null, MovieStatusType.Announced, true)]
[TestCase(null, null, "2000/01/01 21:10:42", MovieStatusType.Announced, true)]
[TestCase(null, null, "2100/01/01 21:10:42", MovieStatusType.Announced, true)]
//minAvail = InCinemas
//InCinemas is known and in the past others are not known or in future
[TestCase("2000/01/01 21:10:42", null, null, MovieStatusType.InCinemas, true)]
[TestCase("2000/01/01 21:10:42", "2100/01/01 21:10:42", null, MovieStatusType.InCinemas, true)]
[TestCase("2000/01/01 21:10:42", "2100/01/01 21:10:42", "2100/01/01 21:10:42", MovieStatusType.InCinemas, true)]
[TestCase("2000/01/01 21:10:42", null, "2100/01/01 21:10:42", MovieStatusType.InCinemas, true)]
//InCinemas is known and in the future others are not known or in future
[TestCase("2100/01/01 21:10:42", null, null, MovieStatusType.InCinemas, false)]
[TestCase("2100/01/01 21:10:42", "2100/01/01 21:10:42", null, MovieStatusType.InCinemas, false)]
[TestCase("2100/01/01 21:10:42", "2100/01/01 21:10:42", "2100/01/01 21:10:42", MovieStatusType.InCinemas, false)]
[TestCase("2100/01/01 21:10:42", null, "2100/01/01 21:10:42", MovieStatusType.InCinemas, false)]
//handle the cases where InCinemas date is not known but Digital/Physical are and passed -- this refers to the issue being fixed along with these tests
[TestCase(null, "2000/01/01 21:10:42", null, MovieStatusType.InCinemas, true)]
[TestCase(null, "2000/01/01 21:10:42", "2000/01/01 21:10:42", MovieStatusType.InCinemas, true)]
[TestCase(null, null, "2000/01/01 21:10:42", MovieStatusType.InCinemas, true)]
//same as previous but digital/physical are in future
[TestCase(null, "2100/01/01 21:10:42", null, MovieStatusType.InCinemas, false)]
[TestCase(null, "2100/01/01 21:10:42", "2100/01/01 21:10:42", MovieStatusType.InCinemas, false)]
[TestCase(null, null, "2100/01/01 21:10:42", MovieStatusType.InCinemas, false)]
//no date values
[TestCase(null, null, null, MovieStatusType.InCinemas, false)]
//minAvail = Released
[TestCase(null, null, null, MovieStatusType.Released, false)]
[TestCase("2000/01/01 21:10:42", null, null, MovieStatusType.Released, true)]
[TestCase("2100/01/01 21:10:42", null, null, MovieStatusType.Released, false)]
[TestCase(null, "2000/01/01 21:10:42", null, MovieStatusType.Released, true)]
[TestCase(null, "2100/01/01 21:10:42", null, MovieStatusType.Released, false)]
[TestCase(null, null, "2000/01/01 21:10:42", MovieStatusType.Released, true)]
[TestCase(null, null, "2100/01/01 21:10:42", MovieStatusType.Released, false)]
public void should_have_correct_availability(DateTime? cinema, DateTime? physical, DateTime? digital, MovieStatusType minimumAvailability, bool result)
{
SetMovieProperties(cinema, physical, digital, minimumAvailability);
_movie.IsAvailable().Should().Be(result);
}
[Test]
public void positive_delay_should_effect_availability()
{
SetMovieProperties(null, DateTime.Now.AddDays(-5), null, MovieStatusType.Released);
_movie.IsAvailable().Should().BeTrue();
_movie.IsAvailable(6).Should().BeFalse();
}
[Test]
public void negative_delay_should_effect_availability()
{
SetMovieProperties(null, DateTime.Now.AddDays(5), null, MovieStatusType.Released);
_movie.IsAvailable().Should().BeFalse();
_movie.IsAvailable(-6).Should().BeTrue();
}
[Test]
public void minimum_availability_released_no_date_but_ninety_days_after_cinemas()
{
SetMovieProperties(DateTime.Now.AddDays(-91), null, null, MovieStatusType.Released);
_movie.IsAvailable().Should().BeTrue();
SetMovieProperties(DateTime.Now.AddDays(-89), null, null, MovieStatusType.Released);
_movie.IsAvailable().Should().BeFalse();
SetMovieProperties(DateTime.Now.AddDays(-89), DateTime.Now.AddDays(-40), null, MovieStatusType.Released);
_movie.IsAvailable().Should().BeTrue();
SetMovieProperties(DateTime.Now.AddDays(-91), DateTime.Now.AddDays(40), null, MovieStatusType.Released);
_movie.IsAvailable().Should().BeFalse();
}
}
}
| gpl-3.0 |
vincentleon/MEPP | src/components/Analysis/Correspondence/src/libicp/matrix.cpp | 23182 | /*
Copyright 2011. All rights reserved.
Institute of Measurement and Control Systems
Karlsruhe Institute of Technology, Germany
Authors: Andreas Geiger
matrix is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or any later version.
matrix 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
matrix; if not, write to the Free Software Foundation, Inc., 51 Franklin
Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "matrix.h"
#include <math.h>
#define SWAP(a,b) {temp=a;a=b;b=temp;}
#define SIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a))
static FLOAT sqrarg;
#define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 : sqrarg*sqrarg)
static FLOAT maxarg1,maxarg2;
#define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1) > (maxarg2) ? (maxarg1) : (maxarg2))
static int32_t iminarg1,iminarg2;
#define IMIN(a,b) (iminarg1=(a),iminarg2=(b),(iminarg1) < (iminarg2) ? (iminarg1) : (iminarg2))
using namespace std;
Matrix::Matrix () {
m = 0;
n = 0;
val = 0;
}
Matrix::Matrix (const int32_t m_,const int32_t n_) {
allocateMemory(m_,n_);
}
Matrix::Matrix (const int32_t m_,const int32_t n_,const FLOAT* val_) {
allocateMemory(m_,n_);
int32_t k=0;
for (int32_t i=0; i<m_; i++)
for (int32_t j=0; j<n_; j++)
val[i][j] = val_[k++];
}
Matrix::Matrix (const Matrix &M) {
allocateMemory(M.m,M.n);
for (int32_t i=0; i<M.m; i++)
memcpy(val[i],M.val[i],M.n*sizeof(FLOAT));
}
Matrix::~Matrix () {
releaseMemory();
}
Matrix& Matrix::operator= (const Matrix &M) {
if (this!=&M) {
if (M.m!=m || M.n!=n) {
releaseMemory();
allocateMemory(M.m,M.n);
}
if (M.n>0)
for (int32_t i=0; i<M.m; i++)
memcpy(val[i],M.val[i],M.n*sizeof(FLOAT));
}
return *this;
}
void Matrix::getData(FLOAT* val_,int32_t i1,int32_t j1,int32_t i2,int32_t j2) {
if (i2==-1) i2 = m-1;
if (j2==-1) j2 = n-1;
int32_t k=0;
for (int32_t i=i1; i<=i2; i++)
for (int32_t j=j1; j<=j2; j++)
val_[k++] = val[i][j];
}
Matrix Matrix::getMat(int32_t i1,int32_t j1,int32_t i2,int32_t j2) {
if (i2==-1) i2 = m-1;
if (j2==-1) j2 = n-1;
if (i1<0 || i2>=m || j1<0 || j2>=n || i2<i1 || j2<j1) {
cerr << "ERROR: Cannot get submatrix [" << i1 << ".." << i2 <<
"] x [" << j1 << ".." << j2 << "]" <<
" of a (" << m << "x" << n << ") matrix." << endl;
exit(0);
}
Matrix M(i2-i1+1,j2-j1+1);
for (int32_t i=0; i<M.m; i++)
for (int32_t j=0; j<M.n; j++)
M.val[i][j] = val[i1+i][j1+j];
return M;
}
void Matrix::setMat(const Matrix &M,const int32_t i1,const int32_t j1) {
if (i1<0 || j1<0 || i1+M.m>m || j1+M.n>n) {
cerr << "ERROR: Cannot set submatrix [" << i1 << ".." << i1+M.m-1 <<
"] x [" << j1 << ".." << j1+M.n-1 << "]" <<
" of a (" << m << "x" << n << ") matrix." << endl;
exit(0);
}
for (int32_t i=0; i<M.m; i++)
for (int32_t j=0; j<M.n; j++)
val[i1+i][j1+j] = M.val[i][j];
}
void Matrix::setVal(FLOAT s,int32_t i1,int32_t j1,int32_t i2,int32_t j2) {
if (i2==-1) i2 = m-1;
if (j2==-1) j2 = n-1;
if (i2<i1 || j2<j1) {
cerr << "ERROR in setVal: Indices must be ordered (i1<=i2, j1<=j2)." << endl;
exit(0);
}
for (int32_t i=i1; i<=i2; i++)
for (int32_t j=j1; j<=j2; j++)
val[i][j] = s;
}
void Matrix::setDiag(FLOAT s,int32_t i1,int32_t i2) {
if (i2==-1) i2 = min(m-1,n-1);
for (int32_t i=i1; i<=i2; i++)
val[i][i] = s;
}
void Matrix::zero() {
setVal(0);
}
Matrix Matrix::extractCols (vector<int> idx) {
Matrix M(m,idx.size());
for (int32_t j=0; j<M.n; j++)
if (idx[j]<n)
for (int32_t i=0; i<m; i++)
M.val[i][j] = val[i][idx[j]];
return M;
}
Matrix Matrix::eye (const int32_t m) {
Matrix M(m,m);
for (int32_t i=0; i<m; i++)
M.val[i][i] = 1;
return M;
}
void Matrix::eye () {
for (int32_t i=0; i<m; i++)
for (int32_t j=0; j<n; j++)
val[i][j] = 0;
for (int32_t i=0; i<min(m,n); i++)
val[i][i] = 1;
}
Matrix Matrix::ones (const int32_t m,const int32_t n) {
Matrix M(m,n);
for (int32_t i=0; i<m; i++)
for (int32_t j=0; j<n; j++)
M.val[i][j] = 1;
return M;
}
Matrix Matrix::diag (const Matrix &M) {
if (M.m>1 && M.n==1) {
Matrix D(M.m,M.m);
for (int32_t i=0; i<M.m; i++)
D.val[i][i] = M.val[i][0];
return D;
} else if (M.m==1 && M.n>1) {
Matrix D(M.n,M.n);
for (int32_t i=0; i<M.n; i++)
D.val[i][i] = M.val[0][i];
return D;
}
cout << "ERROR: Trying to create diagonal matrix from vector of size (" << M.m << "x" << M.n << ")" << endl;
exit(0);
}
Matrix Matrix::reshape(const Matrix &M,int32_t m_,int32_t n_) {
if (M.m*M.n != m_*n_) {
cerr << "ERROR: Trying to reshape a matrix of size (" << M.m << "x" << M.n <<
") to size (" << m_ << "x" << n_ << ")" << endl;
exit(0);
}
Matrix M2(m_,n_);
for (int32_t k=0; k<m_*n_; k++) {
int32_t i1 = k/M.n;
int32_t j1 = k%M.n;
int32_t i2 = k/n_;
int32_t j2 = k%n_;
M2.val[i2][j2] = M.val[i1][j1];
}
return M2;
}
Matrix Matrix::rotMatX (const FLOAT &angle) {
FLOAT s = sin(angle);
FLOAT c = cos(angle);
Matrix R(3,3);
R.val[0][0] = +1;
R.val[1][1] = +c;
R.val[1][2] = -s;
R.val[2][1] = +s;
R.val[2][2] = +c;
return R;
}
Matrix Matrix::rotMatY (const FLOAT &angle) {
FLOAT s = sin(angle);
FLOAT c = cos(angle);
Matrix R(3,3);
R.val[0][0] = +c;
R.val[0][2] = +s;
R.val[1][1] = +1;
R.val[2][0] = -s;
R.val[2][2] = +c;
return R;
}
Matrix Matrix::rotMatZ (const FLOAT &angle) {
FLOAT s = sin(angle);
FLOAT c = cos(angle);
Matrix R(3,3);
R.val[0][0] = +c;
R.val[0][1] = -s;
R.val[1][0] = +s;
R.val[1][1] = +c;
R.val[2][2] = +1;
return R;
}
Matrix Matrix::operator+ (const Matrix &M) {
const Matrix &A = *this;
const Matrix &B = M;
if (A.m!=B.m || A.n!=B.n) {
cerr << "ERROR: Trying to add matrices of size (" << A.m << "x" << A.n <<
") and (" << B.m << "x" << B.n << ")" << endl;
exit(0);
}
Matrix C(A.m,A.n);
for (int32_t i=0; i<m; i++)
for (int32_t j=0; j<n; j++)
C.val[i][j] = A.val[i][j]+B.val[i][j];
return C;
}
Matrix Matrix::operator- (const Matrix &M) {
const Matrix &A = *this;
const Matrix &B = M;
if (A.m!=B.m || A.n!=B.n) {
cerr << "ERROR: Trying to subtract matrices of size (" << A.m << "x" << A.n <<
") and (" << B.m << "x" << B.n << ")" << endl;
exit(0);
}
Matrix C(A.m,A.n);
for (int32_t i=0; i<m; i++)
for (int32_t j=0; j<n; j++)
C.val[i][j] = A.val[i][j]-B.val[i][j];
return C;
}
Matrix Matrix::operator* (const Matrix &M) {
const Matrix &A = *this;
const Matrix &B = M;
if (A.n!=B.m) {
cerr << "ERROR: Trying to multiply matrices of size (" << A.m << "x" << A.n <<
") and (" << B.m << "x" << B.n << ")" << endl;
exit(0);
}
Matrix C(A.m,B.n);
for (int32_t i=0; i<A.m; i++)
for (int32_t j=0; j<B.n; j++)
for (int32_t k=0; k<A.n; k++)
C.val[i][j] += A.val[i][k]*B.val[k][j];
return C;
}
Matrix Matrix::operator* (const FLOAT &s) {
Matrix C(m,n);
for (int32_t i=0; i<m; i++)
for (int32_t j=0; j<n; j++)
C.val[i][j] = val[i][j]*s;
return C;
}
Matrix Matrix::operator/ (const Matrix &M) {
const Matrix &A = *this;
const Matrix &B = M;
if (A.m==B.m && A.n==B.n) {
Matrix C(A.m,A.n);
for (int32_t i=0; i<A.m; i++)
for (int32_t j=0; j<A.n; j++)
if (B.val[i][j]!=0)
C.val[i][j] = A.val[i][j]/B.val[i][j];
return C;
} else if (A.m==B.m && B.n==1) {
Matrix C(A.m,A.n);
for (int32_t i=0; i<A.m; i++)
for (int32_t j=0; j<A.n; j++)
if (B.val[i][0]!=0)
C.val[i][j] = A.val[i][j]/B.val[i][0];
return C;
} else if (A.n==B.n && B.m==1) {
Matrix C(A.m,A.n);
for (int32_t i=0; i<A.m; i++)
for (int32_t j=0; j<A.n; j++)
if (B.val[0][j]!=0)
C.val[i][j] = A.val[i][j]/B.val[0][j];
return C;
} else {
cerr << "ERROR: Trying to divide matrices of size (" << A.m << "x" << A.n <<
") and (" << B.m << "x" << B.n << ")" << endl;
exit(0);
}
}
Matrix Matrix::operator/ (const FLOAT &s) {
if (fabs(s)<1e-20) {
cerr << "ERROR: Trying to divide by zero!" << endl;
exit(0);
}
Matrix C(m,n);
for (int32_t i=0; i<m; i++)
for (int32_t j=0; j<n; j++)
C.val[i][j] = val[i][j]/s;
return C;
}
Matrix Matrix::operator- () {
Matrix C(m,n);
for (int32_t i=0; i<m; i++)
for (int32_t j=0; j<n; j++)
C.val[i][j] = -val[i][j];
return C;
}
Matrix Matrix::operator~ () {
Matrix C(n,m);
for (int32_t i=0; i<m; i++)
for (int32_t j=0; j<n; j++)
C.val[j][i] = val[i][j];
return C;
}
FLOAT Matrix::l2norm () {
FLOAT norm = 0;
for (int32_t i=0; i<m; i++)
for (int32_t j=0; j<n; j++)
norm += val[i][j]*val[i][j];
return sqrt(norm);
}
FLOAT Matrix::mean () {
FLOAT mean = 0;
for (int32_t i=0; i<m; i++)
for (int32_t j=0; j<n; j++)
mean += val[i][j];
return mean/(FLOAT)(m*n);
}
Matrix Matrix::cross (const Matrix &a, const Matrix &b) {
if (a.m!=3 || a.n!=1 || b.m!=3 || b.n!=1) {
cerr << "ERROR: Cross product vectors must be of size (3x1)" << endl;
exit(0);
}
Matrix c(3,1);
c.val[0][0] = a.val[1][0]*b.val[2][0]-a.val[2][0]*b.val[1][0];
c.val[1][0] = a.val[2][0]*b.val[0][0]-a.val[0][0]*b.val[2][0];
c.val[2][0] = a.val[0][0]*b.val[1][0]-a.val[1][0]*b.val[0][0];
return c;
}
Matrix Matrix::inv (const Matrix &M) {
if (M.m!=M.n) {
cerr << "ERROR: Trying to invert matrix of size (" << M.m << "x" << M.n << ")" << endl;
exit(0);
}
Matrix A(M);
Matrix B = eye(M.m);
B.solve(A);
return B;
}
bool Matrix::inv () {
if (m!=n) {
cerr << "ERROR: Trying to invert matrix of size (" << m << "x" << n << ")" << endl;
exit(0);
}
Matrix A(*this);
eye();
solve(A);
return true;
}
FLOAT Matrix::det () {
if (m != n) {
cerr << "ERROR: Trying to compute determinant of a matrix of size (" << m << "x" << n << ")" << endl;
exit(0);
}
Matrix A(*this);
int32_t *idx = (int32_t*)malloc(m*sizeof(int32_t));
FLOAT d;
A.lu(idx,d);
for( int32_t i=0; i<m; i++)
d *= A.val[i][i];
free(idx);
return d;
}
bool Matrix::solve (const Matrix &M, FLOAT eps) {
// substitutes
const Matrix &A = M;
Matrix &B = *this;
if (A.m != A.n || A.m != B.m || A.m<1 || B.n<1) {
cerr << "ERROR: Trying to eliminate matrices of size (" << A.m << "x" << A.n <<
") and (" << B.m << "x" << B.n << ")" << endl;
exit(0);
}
// index vectors for bookkeeping on the pivoting
int32_t* indxc = new int32_t[m];
int32_t* indxr = new int32_t[m];
int32_t* ipiv = new int32_t[m];
// loop variables
int32_t i, icol, irow, j, k, l, ll;
FLOAT big, dum, pivinv, temp;
// initialize pivots to zero
for (j=0;j<m;j++) ipiv[j]=0;
// main loop over the columns to be reduced
for (i=0;i<m;i++) {
big=0.0;
// search for a pivot element
for (j=0;j<m;j++)
if (ipiv[j]!=1)
for (k=0;k<m;k++)
if (ipiv[k]==0)
if (fabs(A.val[j][k])>=big) {
big=fabs(A.val[j][k]);
irow=j;
icol=k;
}
++(ipiv[icol]);
// We now have the pivot element, so we interchange rows, if needed, to put the pivot
// element on the diagonal. The columns are not physically interchanged, only relabeled.
if (irow != icol) {
for (l=0;l<m;l++) SWAP(A.val[irow][l], A.val[icol][l])
for (l=0;l<n;l++) SWAP(B.val[irow][l], B.val[icol][l])
}
indxr[i]=irow; // We are now ready to divide the pivot row by the
indxc[i]=icol; // pivot element, located at irow and icol.
// check for singularity
if (fabs(A.val[icol][icol]) < eps) {
delete[] indxc;
delete[] indxr;
delete[] ipiv;
return false;
}
pivinv=1.0/A.val[icol][icol];
A.val[icol][icol]=1.0;
for (l=0;l<m;l++) A.val[icol][l] *= pivinv;
for (l=0;l<n;l++) B.val[icol][l] *= pivinv;
// Next, we reduce the rows except for the pivot one
for (ll=0;ll<m;ll++)
if (ll!=icol) {
dum = A.val[ll][icol];
A.val[ll][icol] = 0.0;
for (l=0;l<m;l++) A.val[ll][l] -= A.val[icol][l]*dum;
for (l=0;l<n;l++) B.val[ll][l] -= B.val[icol][l]*dum;
}
}
// This is the end of the main loop over columns of the reduction. It only remains to unscramble
// the solution in view of the column interchanges. We do this by interchanging pairs of
// columns in the reverse order that the permutation was built up.
for (l=m-1;l>=0;l--) {
if (indxr[l]!=indxc[l])
for (k=0;k<m;k++)
SWAP(A.val[k][indxr[l]], A.val[k][indxc[l]])
}
// success
delete[] indxc;
delete[] indxr;
delete[] ipiv;
return true;
}
// Given a matrix a[1..n][1..n], this routine replaces it by the LU decomposition of a rowwise
// permutation of itself. a and n are input. a is output, arranged as in equation (2.3.14) above;
// indx[1..n] is an output vector that records the row permutation effected by the partial
// pivoting; d is output as ยฑ1 depending on whether the number of row interchanges was even
// or odd, respectively. This routine is used in combination with lubksb to solve linear equations
// or invert a matrix.
bool Matrix::lu(int32_t *idx, FLOAT &d, FLOAT eps) {
if (m != n) {
cerr << "ERROR: Trying to LU decompose a matrix of size (" << m << "x" << n << ")" << endl;
exit(0);
}
int32_t i,imax,j,k;
FLOAT big,dum,sum,temp;
FLOAT* vv = (FLOAT*)malloc(n*sizeof(FLOAT)); // vv stores the implicit scaling of each row.
d = 1.0;
for (i=0; i<n; i++) { // Loop over rows to get the implicit scaling information.
big = 0.0;
for (j=0; j<n; j++)
if ((temp=fabs(val[i][j]))>big)
big = temp;
if (big == 0.0) { // No nonzero largest element.
free(vv);
return false;
}
vv[i] = 1.0/big; // Save the scaling.
}
for (j=0; j<n; j++) { // This is the loop over columns of Croutโs method.
for (i=0; i<j; i++) { // This is equation (2.3.12) except for i = j.
sum = val[i][j];
for (k=0; k<i; k++)
sum -= val[i][k]*val[k][j];
val[i][j] = sum;
}
big = 0.0; // Initialize the search for largest pivot element.
for (i=j; i<n; i++) {
sum = val[i][j];
for (k=0; k<j; k++)
sum -= val[i][k]*val[k][j];
val[i][j] = sum;
if ( (dum=vv[i]*fabs(sum))>=big) {
big = dum;
imax = i;
}
}
if (j!=imax) { // Do we need to interchange rows?
for (k=0; k<n; k++) { // Yes, do so...
dum = val[imax][k];
val[imax][k] = val[j][k];
val[j][k] = dum;
}
d = -d; // ...and change the parity of d.
vv[imax]=vv[j]; // Also interchange the scale factor.
}
idx[j] = imax;
if (j!=n-1) { // Now, finally, divide by the pivot element.
dum = 1.0/val[j][j];
for (i=j+1; i<n; i++)
val[i][j] *= dum;
}
} // Go back for the next column in the reduction.
// success
free(vv);
return true;
}
// Given a matrix M/A[1..m][1..n], this routine computes its singular value decomposition, M/A =
// UยทWยทV T. Thematrix U replaces a on output. The diagonal matrix of singular values W is output
// as a vector w[1..n]. Thematrix V (not the transpose V T ) is output as v[1..n][1..n].
void Matrix::svd(Matrix &U2,Matrix &W,Matrix &V) {
Matrix U = Matrix(*this);
U2 = Matrix(m,m);
V = Matrix(n,n);
FLOAT* w = (FLOAT*)malloc(n*sizeof(FLOAT));
FLOAT* rv1 = (FLOAT*)malloc(n*sizeof(FLOAT));
int32_t flag,i,its,j,jj,k,l,nm;
FLOAT anorm,c,f,g,h,s,scale,x,y,z;
g = scale = anorm = 0.0; // Householder reduction to bidiagonal form.
for (i=0;i<n;i++) {
l = i+1;
rv1[i] = scale*g;
g = s = scale = 0.0;
if (i < m) {
for (k=i;k<m;k++) scale += fabs(U.val[k][i]);
if (scale) {
for (k=i;k<m;k++) {
U.val[k][i] /= scale;
s += U.val[k][i]*U.val[k][i];
}
f = U.val[i][i];
g = -SIGN(sqrt(s),f);
h = f*g-s;
U.val[i][i] = f-g;
for (j=l;j<n;j++) {
for (s=0.0,k=i;k<m;k++) s += U.val[k][i]*U.val[k][j];
f = s/h;
for (k=i;k<m;k++) U.val[k][j] += f*U.val[k][i];
}
for (k=i;k<m;k++) U.val[k][i] *= scale;
}
}
w[i] = scale*g;
g = s = scale = 0.0;
if (i<m && i!=n-1) {
for (k=l;k<n;k++) scale += fabs(U.val[i][k]);
if (scale) {
for (k=l;k<n;k++) {
U.val[i][k] /= scale;
s += U.val[i][k]*U.val[i][k];
}
f = U.val[i][l];
g = -SIGN(sqrt(s),f);
h = f*g-s;
U.val[i][l] = f-g;
for (k=l;k<n;k++) rv1[k] = U.val[i][k]/h;
for (j=l;j<m;j++) {
for (s=0.0,k=l;k<n;k++) s += U.val[j][k]*U.val[i][k];
for (k=l;k<n;k++) U.val[j][k] += s*rv1[k];
}
for (k=l;k<n;k++) U.val[i][k] *= scale;
}
}
anorm = FMAX(anorm,(fabs(w[i])+fabs(rv1[i])));
}
for (i=n-1;i>=0;i--) { // Accumulation of right-hand transformations.
if (i<n-1) {
if (g) {
for (j=l;j<n;j++) // Double division to avoid possible underflow.
V.val[j][i]=(U.val[i][j]/U.val[i][l])/g;
for (j=l;j<n;j++) {
for (s=0.0,k=l;k<n;k++) s += U.val[i][k]*V.val[k][j];
for (k=l;k<n;k++) V.val[k][j] += s*V.val[k][i];
}
}
for (j=l;j<n;j++) V.val[i][j] = V.val[j][i] = 0.0;
}
V.val[i][i] = 1.0;
g = rv1[i];
l = i;
}
for (i=IMIN(m,n)-1;i>=0;i--) { // Accumulation of left-hand transformations.
l = i+1;
g = w[i];
for (j=l;j<n;j++) U.val[i][j] = 0.0;
if (g) {
g = 1.0/g;
for (j=l;j<n;j++) {
for (s=0.0,k=l;k<m;k++) s += U.val[k][i]*U.val[k][j];
f = (s/U.val[i][i])*g;
for (k=i;k<m;k++) U.val[k][j] += f*U.val[k][i];
}
for (j=i;j<m;j++) U.val[j][i] *= g;
} else for (j=i;j<m;j++) U.val[j][i]=0.0;
++U.val[i][i];
}
for (k=n-1;k>=0;k--) { // Diagonalization of the bidiagonal form: Loop over singular values,
for (its=0;its<30;its++) { // and over allowed iterations.
flag = 1;
for (l=k;l>=0;l--) { // Test for splitting.
nm = l-1;
if ((FLOAT)(fabs(rv1[l])+anorm) == anorm) { flag = 0; break; }
if ((FLOAT)(fabs( w[nm])+anorm) == anorm) { break; }
}
if (flag) {
c = 0.0; // Cancellation of rv1[l], if l > 1.
s = 1.0;
for (i=l;i<=k;i++) {
f = s*rv1[i];
rv1[i] = c*rv1[i];
if ((FLOAT)(fabs(f)+anorm) == anorm) break;
g = w[i];
h = pythag(f,g);
w[i] = h;
h = 1.0/h;
c = g*h;
s = -f*h;
for (j=0;j<m;j++) {
y = U.val[j][nm];
z = U.val[j][i];
U.val[j][nm] = y*c+z*s;
U.val[j][i] = z*c-y*s;
}
}
}
z = w[k];
if (l==k) { // Convergence.
if (z<0.0) { // Singular value is made nonnegative.
w[k] = -z;
for (j=0;j<n;j++) V.val[j][k] = -V.val[j][k];
}
break;
}
if (its == 29)
cerr << "ERROR in SVD: No convergence in 30 iterations" << endl;
x = w[l]; // Shift from bottom 2-by-2 minor.
nm = k-1;
y = w[nm];
g = rv1[nm];
h = rv1[k];
f = ((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y);
g = pythag(f,1.0);
f = ((x-z)*(x+z)+h*((y/(f+SIGN(g,f)))-h))/x;
c = s = 1.0; // Next QR transformation:
for (j=l;j<=nm;j++) {
i = j+1;
g = rv1[i];
y = w[i];
h = s*g;
g = c*g;
z = pythag(f,h);
rv1[j] = z;
c = f/z;
s = h/z;
f = x*c+g*s;
g = g*c-x*s;
h = y*s;
y *= c;
for (jj=0;jj<n;jj++) {
x = V.val[jj][j];
z = V.val[jj][i];
V.val[jj][j] = x*c+z*s;
V.val[jj][i] = z*c-x*s;
}
z = pythag(f,h);
w[j] = z; // Rotation can be arbitrary if z = 0.
if (z) {
z = 1.0/z;
c = f*z;
s = h*z;
}
f = c*g+s*y;
x = c*y-s*g;
for (jj=0;jj<m;jj++) {
y = U.val[jj][j];
z = U.val[jj][i];
U.val[jj][j] = y*c+z*s;
U.val[jj][i] = z*c-y*s;
}
}
rv1[l] = 0.0;
rv1[k] = f;
w[k] = x;
}
}
// sort singular values and corresponding columns of u and v
// by decreasing magnitude. Also, signs of corresponding columns are
// flipped so as to maximize the number of positive elements.
int32_t s2,inc=1;
FLOAT sw;
FLOAT* su = (FLOAT*)malloc(m*sizeof(FLOAT));
FLOAT* sv = (FLOAT*)malloc(n*sizeof(FLOAT));
do { inc *= 3; inc++; } while (inc <= n);
do {
inc /= 3;
for (i=inc;i<n;i++) {
sw = w[i];
for (k=0;k<m;k++) su[k] = U.val[k][i];
for (k=0;k<n;k++) sv[k] = V.val[k][i];
j = i;
while (w[j-inc] < sw) {
w[j] = w[j-inc];
for (k=0;k<m;k++) U.val[k][j] = U.val[k][j-inc];
for (k=0;k<n;k++) V.val[k][j] = V.val[k][j-inc];
j -= inc;
if (j < inc) break;
}
w[j] = sw;
for (k=0;k<m;k++) U.val[k][j] = su[k];
for (k=0;k<n;k++) V.val[k][j] = sv[k];
}
} while (inc > 1);
for (k=0;k<n;k++) { // flip signs
s2=0;
for (i=0;i<m;i++) if (U.val[i][k] < 0.0) s2++;
for (j=0;j<n;j++) if (V.val[j][k] < 0.0) s2++;
if (s2 > (m+n)/2) {
for (i=0;i<m;i++) U.val[i][k] = -U.val[i][k];
for (j=0;j<n;j++) V.val[j][k] = -V.val[j][k];
}
}
// create vector and copy singular values
W = Matrix(min(m,n),1,w);
// extract mxm submatrix U
U2.setMat(U.getMat(0,0,m-1,min(m-1,n-1)),0,0);
// release temporary memory
free(w);
free(rv1);
free(su);
free(sv);
}
ostream& operator<< (ostream& out,const Matrix& M) {
if (M.m==0 || M.n==0) {
out << "[empty matrix]";
} else {
char buffer[1024];
for (int32_t i=0; i<M.m; i++) {
for (int32_t j=0; j<M.n; j++) {
sprintf(buffer,"%12.7f ",M.val[i][j]);
out << buffer;
}
if (i<M.m-1)
out << endl;
}
}
return out;
}
void Matrix::allocateMemory (const int32_t m_,const int32_t n_) {
m = abs(m_); n = abs(n_);
if (m==0 || n==0) {
val = 0;
return;
}
val = (FLOAT**)malloc(m*sizeof(FLOAT*));
val[0] = (FLOAT*)calloc(m*n,sizeof(FLOAT));
for(int32_t i=1; i<m; i++)
val[i] = val[i-1]+n;
}
void Matrix::releaseMemory () {
if (val!=0) {
free(val[0]);
free(val);
}
}
FLOAT Matrix::pythag(FLOAT a,FLOAT b) {
FLOAT absa,absb;
absa = fabs(a);
absb = fabs(b);
if (absa > absb)
return absa*sqrt(1.0+SQR(absb/absa));
else
return (absb == 0.0 ? 0.0 : absb*sqrt(1.0+SQR(absa/absb)));
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | packages/apps/Gallery2/src_pd/com/android/gallery3d/util/IntentHelper.java | 1162 | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.gallery3d.util;
import android.content.Context;
import android.content.Intent;
public class IntentHelper {
public static Intent getCameraIntent(Context context) {
return new Intent(Intent.ACTION_MAIN)
.setClassName("com.android.camera2", "com.android.camera.CameraLauncher");
}
public static Intent getGalleryIntent(Context context) {
return new Intent(Intent.ACTION_MAIN)
.setClassName("com.android.gallery3d", "com.android.gallery3d.app.GalleryActivity");
}
}
| gpl-3.0 |
crazyhottommy/manta | src/c++/lib/svgraph/EdgeInfoUtil.cpp | 2106 | // -*- mode: c++; indent-tabs-mode: nil; -*-
//
// Manta - Structural Variant and Indel Caller
// Copyright (c) 2013-2015 Illumina, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//
///
/// \author Chris Saunders
///
#include "svgraph/EdgeInfoUtil.hh"
bool
testIsolatedEdge(
const SVLocusSet& cset,
const EdgeInfo& edge)
{
if (edge.nodeIndex1 != edge.nodeIndex2) return false;
const SVLocus& locus(cset.getLocus(edge.locusIndex));
#if 0
// simple criteria -- make sure there are no other nodes in locus
return (locus.size() == 1);
#endif
// search to check to see if any bidirectional edges extend from this node (other than the self-edge):
const SVLocusNode& node1(locus.getNode(edge.nodeIndex1));
const SVLocusEdgeManager node1Manager(node1.getEdgeManager());
typedef SVLocusEdgesType::const_iterator edgeiter_t;
edgeiter_t edgeIter(node1Manager.getMap().begin());
const edgeiter_t edgeIterEnd(node1Manager.getMap().end());
EdgeInfo testEdge(edge);
unsigned edgeCount(0);
unsigned biEdgeCount(0);
for (; edgeIter != edgeIterEnd; ++edgeIter)
{
testEdge.nodeIndex2 = (edgeIter->first);
if (testEdge.nodeIndex1 == testEdge.nodeIndex2) continue;
edgeCount++;
if (isBidirectionalEdge(cset, testEdge)) biEdgeCount++;
}
const bool isLowBiEdge((biEdgeCount >= 1) && (biEdgeCount <= 2));
const bool isLowTotalEdge(edgeCount <= 4);
return (! (isLowBiEdge && isLowTotalEdge));
}
| gpl-3.0 |
lambdablocks/blocks-front-react | src/components/Brick.js | 2407 | import React, { PropTypes, Component } from 'react'
import { Group, Text } from 'react-art'
import Rectangle from 'react-art/lib/Rectangle.art'
import composeBrick from './composeBrick'
import { getConstant } from './constants'
import { getFillColor } from '../utils'
import {
BindingPropTypes,
PositionPropTypes,
SizePropTypes,
SlotPropTypes
} from '../propTypes'
import { ERROR } from '../utils/evalUtils'
class Brick extends Component {
constructor(props) {
super(props)
this.startDrag = this.startDrag.bind(this)
}
startDrag(mouseEvent) {
const { handleMouseDown, id, position } = this.props
handleMouseDown(id, mouseEvent, position)
}
render() {
const {
componentName,
binding,
name,
outputSlots,
size
} = this.props
const midHeight = size.height / 2 - 7
const outputSlotId = Object.keys(outputSlots)[0]
const { outputElementIds } = outputSlots[outputSlotId]
const slotHeight = getConstant(componentName, 'slotHeight')
const slotWidth = getConstant(componentName, 'slotWidth')
return (
<Group
onMouseDown={ this.startDrag }
y={ slotHeight }
>
<Rectangle
height={ size.height }
width={ size.width }
stroke={ getConstant(componentName, 'strokeColor') }
fill={ getConstant(componentName, 'fillColor') }
/>
<Text
alignment={ getConstant(componentName, 'alignment') }
fill={ getConstant(componentName, 'textColor') }
font={ getConstant(componentName, 'font') }
x={ size.width / 2 }
y={ midHeight }
>
{ name }
</Text>
{ outputElementIds.length == 0 && binding.type &&
<Text
fill={ getFillColor(binding.type, binding.value) }
font={ getConstant(componentName, 'outputFont') }
x={ ((size.width - slotWidth) / 2) + slotWidth + 3 }
y={ size.height + 2 }
>
{ binding.value }
</Text>
}
</Group>
)
}
}
Brick.propTypes = {
componentName: PropTypes.string.isRequired,
binding: BindingPropTypes,
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
position: PositionPropTypes.isRequired,
outputSlots: SlotPropTypes.isRequired,
size: SizePropTypes.isRequired
}
export default composeBrick(Brick)
| gpl-3.0 |
jasonehines/mycroft-core | mycroft/skills/container.py | 3372 | # Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycroft Core 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 Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
import argparse
import sys
from os.path import dirname, exists, isdir
from mycroft.configuration import ConfigurationManager
from mycroft.messagebus.client.ws import WebsocketClient
from mycroft.skills.core import create_skill_descriptor, load_skill
from mycroft.skills.intent import Intent
from mycroft.util.log import getLogger
__author__ = 'seanfitz'
LOG = getLogger("SkillContainer")
class SkillContainer(object):
def __init__(self, args):
params = self.__build_params(args)
if params.config:
ConfigurationManager.load_local([params.config])
if exists(params.lib) and isdir(params.lib):
sys.path.append(params.lib)
sys.path.append(params.dir)
self.dir = params.dir
self.enable_intent = params.enable_intent
self.__init_client(params)
@staticmethod
def __build_params(args):
parser = argparse.ArgumentParser()
parser.add_argument("--config", default="./mycroft.conf")
parser.add_argument("dir", nargs='?', default=dirname(__file__))
parser.add_argument("--lib", default="./lib")
parser.add_argument("--host", default=None)
parser.add_argument("--port", default=None)
parser.add_argument("--use-ssl", action='store_true', default=False)
parser.add_argument("--enable-intent", action='store_true',
default=False)
return parser.parse_args(args)
def __init_client(self, params):
config = ConfigurationManager.get().get("websocket")
if not params.host:
params.host = config.get('host')
if not params.port:
params.port = config.get('port')
self.ws = WebsocketClient(host=params.host,
port=params.port,
ssl=params.use_ssl)
def load_skill(self):
if self.enable_intent:
Intent(self.ws)
skill_descriptor = create_skill_descriptor(self.dir)
self.skill = load_skill(skill_descriptor, self.ws)
def run(self):
try:
self.ws.on('message', LOG.debug)
self.ws.on('open', self.load_skill)
self.ws.on('error', LOG.error)
self.ws.run_forever()
except Exception as e:
LOG.error("Error: {0}".format(e))
self.stop()
def stop(self):
if self.skill:
self.skill.shutdown()
def main():
container = SkillContainer(sys.argv[1:])
try:
container.run()
except KeyboardInterrupt:
container.stop()
finally:
sys.exit()
if __name__ == "__main__":
main()
| gpl-3.0 |
ProjectTegano/Tegano | src/libwolframe_langbind/input.cpp | 3149 | /************************************************************************
Copyright (C) 2011 - 2014 Project Wolframe.
All rights reserved.
This file is part of Project Wolframe.
Commercial Usage
Licensees holding valid Project Wolframe Commercial licenses may
use this file in accordance with the Project Wolframe
Commercial License Agreement provided with the Software or,
alternatively, in accordance with the terms contained
in a written agreement between the licensee and Project Wolframe.
GNU General Public License Usage
Alternatively, you can redistribute this file and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Wolframe 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 Wolframe. If not, see <http://www.gnu.org/licenses/>.
If you have questions regarding the use of this file, please contact
Project Wolframe.
************************************************************************/
///\file input.cpp
///\brief Implementation of input for scripting language binding
#include "langbind/input.hpp"
#include <stdexcept>
using namespace _Wolframe;
using namespace langbind;
Input::Input( const Input& o)
:m_used(o.m_used)
,m_inputfilter(o.m_inputfilter)
,m_docformat(o.m_docformat)
,m_content(o.m_content)
,m_contentsize(o.m_contentsize)
,m_unconsumedInput(o.m_unconsumedInput)
,m_gotEoD(o.m_gotEoD)
{}
Input::Input( const std::string& docformat_)
:m_used(false)
,m_docformat(docformat_)
,m_contentsize(0)
,m_gotEoD(false)
{}
Input::Input( const std::string& docformat_, const std::string& content_)
:m_used(false)
,m_docformat(docformat_)
,m_contentsize(0)
,m_gotEoD(false)
{
char* mem = (char*)std::malloc( content_.size());
if (!mem) throw std::bad_alloc();
m_content = boost::shared_ptr<char>( mem, std::free);
m_contentsize = content_.size();
std::memcpy( mem, content_.c_str(), content_.size());
}
void Input::putInput( const void* data, std::size_t datasize, bool eod)
{
m_gotEoD |= eod;
if (m_inputfilter.get())
{
m_inputfilter->putInput( data, datasize, eod);
}
else
{
m_unconsumedInput.append( (const char*)data, datasize);
}
}
void Input::setInputFilter( const InputFilterR& filter)
{
if (m_inputfilter.get() && m_inputfilter->state() != InputFilter::Start)
{
throw std::runtime_error( "cannot reset input filter already used");
}
else
{
m_inputfilter.reset( filter->copy());
if (m_unconsumedInput.size() || m_gotEoD)
{
m_inputfilter->putInput( m_unconsumedInput.c_str(), m_unconsumedInput.size(), m_gotEoD);
}
else if (isDocument())
{
m_inputfilter->putInput( documentptr(), documentsize(), true);
}
}
}
InputFilterR& Input::getIterator()
{
if (m_used) throw std::runtime_error( "try to use iterator for input/document twice");
m_used = true;
return m_inputfilter;
}
| gpl-3.0 |
benlo06/dolibarr | htdocs/websites/class/websitepage.class.php | 18875 | <?php
/* Copyright (C) 2007-2012 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2014 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2015 Florian Henry <florian.henry@open-concept.pro>
* Copyright (C) 2015 Raphaรซl Doursenaud <rdoursenaud@gpcsolutions.fr>
* Copyright (C) ---Put here your own copyright and developer email---
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file websites/websitepage.class.php
* \ingroup websites
* \brief This file is an example for a CRUD class file (Create/Read/Update/Delete)
* Put some comments here
*/
// Put here all includes required by your class file
require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
/**
* Class Websitepage
*/
class WebsitePage extends CommonObject
{
/**
* @var string Id to identify managed objects
*/
public $element = 'websitepage';
/**
* @var string Name of table without prefix where object is stored
*/
public $table_element = 'website_page';
/**
*/
public $fk_website;
public $pageurl;
public $title;
public $description;
public $keywords;
public $content;
public $status;
public $date_creation;
public $date_modification;
/**
*/
/**
* Constructor
*
* @param DoliDb $db Database handler
*/
public function __construct(DoliDB $db)
{
$this->db = $db;
}
/**
* Create object into database
*
* @param User $user User that creates
* @param bool $notrigger false=launch triggers after, true=disable triggers
*
* @return int <0 if KO, Id of created object if OK
*/
public function create(User $user, $notrigger = false)
{
dol_syslog(__METHOD__, LOG_DEBUG);
$error = 0;
$now=dol_now();
// Clean parameters
if (isset($this->fk_website)) {
$this->fk_website = trim($this->fk_website);
}
if (isset($this->pageurl)) {
$this->pageurl = trim($this->pageurl);
}
if (isset($this->title)) {
$this->title = trim($this->title);
}
if (isset($this->description)) {
$this->description = trim($this->description);
}
if (isset($this->keywords)) {
$this->keywords = trim($this->keywords);
}
if (isset($this->content)) {
$this->content = trim($this->content);
}
if (isset($this->status)) {
$this->status = trim($this->status);
}
if (isset($this->date_creation)) {
$this->date_creation = $now;
}
if (isset($this->date_modification)) {
$this->date_modification = $now;
}
// Check parameters
// Put here code to add control on parameters values
// Insert request
$sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '(';
$sql.= 'fk_website,';
$sql.= 'pageurl,';
$sql.= 'title,';
$sql.= 'description,';
$sql.= 'keywords,';
$sql.= 'content,';
$sql.= 'status,';
$sql.= 'date_creation,';
$sql.= 'date_modification';
$sql .= ') VALUES (';
$sql .= ' '.(! isset($this->fk_website)?'NULL':$this->fk_website).',';
$sql .= ' '.(! isset($this->pageurl)?'NULL':"'".$this->db->escape($this->pageurl)."'").',';
$sql .= ' '.(! isset($this->title)?'NULL':"'".$this->db->escape($this->title)."'").',';
$sql .= ' '.(! isset($this->description)?'NULL':"'".$this->db->escape($this->description)."'").',';
$sql .= ' '.(! isset($this->keywords)?'NULL':"'".$this->db->escape($this->keywords)."'").',';
$sql .= ' '.(! isset($this->content)?'NULL':"'".$this->db->escape($this->content)."'").',';
$sql .= ' '.(! isset($this->status)?'NULL':$this->status).',';
$sql .= ' '.(! isset($this->date_creation) || dol_strlen($this->date_creation)==0?'NULL':"'".$this->db->idate($this->date_creation)."'").',';
$sql .= ' '.(! isset($this->date_modification) || dol_strlen($this->date_modification)==0?'NULL':"'".$this->db->idate($this->date_modification)."'");
$sql .= ')';
$this->db->begin();
$resql = $this->db->query($sql);
if (! $resql) {
$error++;
$this->errors[] = 'Error ' . $this->db->lasterror();
dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
}
if (! $error) {
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
if (!$notrigger) {
// Uncomment this and change MYOBJECT to your own tag if you
// want this action to call a trigger.
//// Call triggers
//$result=$this->call_trigger('MYOBJECT_CREATE',$user);
//if ($result < 0) $error++;
//// End call triggers
}
}
// Commit or rollback
if ($error)
{
$this->db->rollback();
return - 1 * $error;
} else {
$this->db->commit();
return $this->id;
}
}
/**
* Load object in memory from the database
*
* @param int $id Id object. If this is 0, the default page of website_id will be used, if not defined, the first one. found
* @param string $website_id Web site id
* @param string $page Page name
*
* @return int <0 if KO, 0 if not found, >0 if OK
*/
public function fetch($id, $website_id = null, $page = null)
{
dol_syslog(__METHOD__, LOG_DEBUG);
$sql = 'SELECT';
$sql .= ' t.rowid,';
$sql .= " t.fk_website,";
$sql .= " t.pageurl,";
$sql .= " t.title,";
$sql .= " t.description,";
$sql .= " t.keywords,";
$sql .= " t.content,";
$sql .= " t.status,";
$sql .= " t.date_creation,";
$sql .= " t.tms as date_modification";
$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
//$sql .= ' WHERE entity IN ('.getEntity('website', 1).')'; // entity is on website level
$sql .= ' WHERE 1 = 1';
if (null !== $website_id) {
$sql .= " AND t.fk_website = '" . $this->db->escape($website_id) . "'";
if ($page) $sql .= " AND t.pageurl = '" . $this->db->escape($page) . "'";
} else {
$sql .= ' AND t.rowid = ' . $id;
}
$sql .= $this->db->plimit(1);
$resql = $this->db->query($sql);
if ($resql) {
$numrows = $this->db->num_rows($resql);
if ($numrows) {
$obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid;
$this->fk_website = $obj->fk_website;
$this->pageurl = $obj->pageurl;
$this->title = $obj->title;
$this->description = $obj->description;
$this->keywords = $obj->keywords;
$this->content = $obj->content;
$this->status = $obj->status;
$this->date_creation = $this->db->jdate($obj->date_creation);
$this->date_modification = $this->db->jdate($obj->date_modification);
}
$this->db->free($resql);
if ($numrows) {
return 1;
} else {
return 0;
}
} else {
$this->errors[] = 'Error ' . $this->db->lasterror();
dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
return - 1;
}
}
/**
* Load object in memory from the database
*
* @param string $websiteid Web site
* @param string $sortorder Sort Order
* @param string $sortfield Sort field
* @param int $limit limit
* @param int $offset Offset
* @param array $filter Filter array
* @param string $filtermode Filter mode (AND or OR)
* @return array|int int <0 if KO, array of pages if OK
*/
public function fetchAll($websiteid, $sortorder='', $sortfield='', $limit=0, $offset=0, array $filter = array(), $filtermode='AND')
{
dol_syslog(__METHOD__, LOG_DEBUG);
$records=array();
$sql = 'SELECT';
$sql .= ' t.rowid,';
$sql .= " t.fk_website,";
$sql .= " t.pageurl,";
$sql .= " t.title,";
$sql .= " t.description,";
$sql .= " t.keywords,";
$sql .= " t.content,";
$sql .= " t.status,";
$sql .= " t.date_creation,";
$sql .= " t.tms as date_modification";
$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t';
$sql .= ' WHERE t.fk_website = '.$websiteid;
// Manage filter
$sqlwhere = array();
if (count($filter) > 0) {
foreach ($filter as $key => $value) {
if ($key=='t.rowid' || $key=='t.fk_website') {
$sqlwhere[] = $key . '='. $value;
} else {
$sqlwhere[] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\'';
}
}
}
if (count($sqlwhere) > 0) {
$sql .= ' AND ' . implode(' '.$filtermode.' ', $sqlwhere);
}
if (!empty($sortfield)) {
$sql .= $this->db->order($sortfield,$sortorder);
}
if (!empty($limit)) {
$sql .= ' ' . $this->db->plimit($limit, $offset);
}
$resql = $this->db->query($sql);
if ($resql) {
$num = $this->db->num_rows($resql);
while ($obj = $this->db->fetch_object($resql))
{
$record = new self($this->db);
$record->id = $obj->rowid;
$record->fk_website = $obj->fk_website;
$record->pageurl = $obj->pageurl;
$record->title = $obj->title;
$record->description = $obj->description;
$record->keywords = $obj->keywords;
$record->content = $obj->content;
$record->status = $obj->status;
$record->date_creation = $this->db->jdate($obj->date_creation);
$record->date_modification = $this->db->jdate($obj->date_modification);
//var_dump($record->id);
$records[$record->id] = $record;
}
$this->db->free($resql);
return $records;
} else {
$this->errors[] = 'Error ' . $this->db->lasterror();
dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
return -1;
}
}
/**
* Update object into database
*
* @param User $user User that modifies
* @param bool $notrigger false=launch triggers after, true=disable triggers
*
* @return int <0 if KO, >0 if OK
*/
public function update(User $user, $notrigger = false)
{
$error = 0;
dol_syslog(__METHOD__, LOG_DEBUG);
// Clean parameters
if (isset($this->fk_website)) {
$this->fk_website = trim($this->fk_website);
}
if (isset($this->pageurl)) {
$this->pageurl = trim($this->pageurl);
}
if (isset($this->title)) {
$this->title = trim($this->title);
}
if (isset($this->description)) {
$this->description = trim($this->description);
}
if (isset($this->keywords)) {
$this->keywords = trim($this->keywords);
}
if (isset($this->content)) {
$this->content = trim($this->content);
}
if (isset($this->status)) {
$this->status = trim($this->status);
}
// Check parameters
// Put here code to add a control on parameters values
// Update request
$sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . ' SET';
$sql .= ' fk_website = '.(isset($this->fk_website)?$this->fk_website:"null").',';
$sql .= ' pageurl = '.(isset($this->pageurl)?"'".$this->db->escape($this->pageurl)."'":"null").',';
$sql .= ' title = '.(isset($this->title)?"'".$this->db->escape($this->title)."'":"null").',';
$sql .= ' description = '.(isset($this->description)?"'".$this->db->escape($this->description)."'":"null").',';
$sql .= ' keywords = '.(isset($this->keywords)?"'".$this->db->escape($this->keywords)."'":"null").',';
$sql .= ' content = '.(isset($this->content)?"'".$this->db->escape($this->content)."'":"null").',';
$sql .= ' status = '.(isset($this->status)?$this->status:"null").',';
$sql .= ' date_creation = '.(! isset($this->date_creation) || dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').',';
$sql .= ' tms = '.(dol_strlen($this->date_modification) != 0 ? "'".$this->db->idate($this->date_modification)."'" : "'".$this->db->idate(dol_now())."'");
$sql .= ' WHERE rowid=' . $this->id;
$this->db->begin();
$resql = $this->db->query($sql);
if (!$resql) {
$error ++;
$this->errors[] = 'Error ' . $this->db->lasterror();
dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
}
if ($this->old_object->pageurl != $this->pageurl)
{
dol_syslog("The alias was changed, we must rename/recreate the page file into document");
}
if (!$error && !$notrigger) {
// Uncomment this and change MYOBJECT to your own tag if you
// want this action calls a trigger.
//// Call triggers
//$result=$this->call_trigger('MYOBJECT_MODIFY',$user);
//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
//// End call triggers
}
// Commit or rollback
if ($error) {
$this->db->rollback();
return - 1 * $error;
} else {
$this->db->commit();
return 1;
}
}
/**
* Delete object in database
*
* @param User $user User that deletes
* @param bool $notrigger false=launch triggers after, true=disable triggers
*
* @return int <0 if KO, >0 if OK
*/
public function delete(User $user, $notrigger = false)
{
dol_syslog(__METHOD__, LOG_DEBUG);
$error = 0;
$this->db->begin();
if (!$error) {
if (!$notrigger) {
// Uncomment this and change MYOBJECT to your own tag if you
// want this action calls a trigger.
//// Call triggers
//$result=$this->call_trigger('MYOBJECT_DELETE',$user);
//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
//// End call triggers
}
}
if (!$error) {
$sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element;
$sql .= ' WHERE rowid=' . $this->id;
$resql = $this->db->query($sql);
if (!$resql) {
$error ++;
$this->errors[] = 'Error ' . $this->db->lasterror();
dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
}
}
// Commit or rollback
if ($error) {
$this->db->rollback();
return - 1 * $error;
} else {
$this->db->commit();
return 1;
}
}
/**
* Load an object from its id and create a new one in database
*
* @param int $fromid Id of object to clone
*
* @return int New id of clone
*/
public function createFromClone($fromid)
{
dol_syslog(__METHOD__, LOG_DEBUG);
global $user;
$error = 0;
$object = new Websitepage($this->db);
$this->db->begin();
// Load source object
$object->fetch($fromid);
// Reset object
$object->id = 0;
// Clear fields
// ...
// Create clone
$result = $object->create($user);
// Other options
if ($result < 0) {
$error ++;
$this->errors = $object->errors;
dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
}
// End
if (!$error) {
$this->db->commit();
return $object->id;
} else {
$this->db->rollback();
return - 1;
}
}
/**
* Return a link to the user card (with optionaly the picto)
* Use this->id,this->lastname, this->firstname
*
* @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
* @param string $option On what the link point to
* @param integer $notooltip 1=Disable tooltip
* @param int $maxlen Max length of visible user name
* @param string $morecss Add more css on link
* @return string String with URL
*/
function getNomUrl($withpicto=0, $option='', $notooltip=0, $maxlen=24, $morecss='')
{
global $langs, $conf, $db;
global $dolibarr_main_authentication, $dolibarr_main_demo;
global $menumanager;
$result = '';
$companylink = '';
$label = '<u>' . $langs->trans("Page") . '</u>';
$label.= '<div width="100%">';
$label.= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
$link = '<a href="'.DOL_URL_ROOT.'/websites/card.php?id='.$this->id.'"';
$link.= ($notooltip?'':' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip'.($morecss?' '.$morecss:'').'"');
$link.= '>';
$linkend='</a>';
if ($withpicto)
{
$result.=($link.img_object(($notooltip?'':$label), 'label', ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
if ($withpicto != 2) $result.=' ';
}
$result.= $link . $this->ref . $linkend;
return $result;
}
/**
* Retourne le libelle du status d'un user (actif, inactif)
*
* @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
* @return string Label of status
*/
function getLibStatut($mode=0)
{
return $this->LibStatut($this->status,$mode);
}
/**
* Renvoi le libelle d'un status donne
*
* @param int $status Id status
* @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
* @return string Label of status
*/
function LibStatut($status,$mode=0)
{
global $langs;
if ($mode == 0)
{
$prefix='';
if ($status == 1) return $langs->trans('Enabled');
if ($status == 0) return $langs->trans('Disabled');
}
if ($mode == 1)
{
if ($status == 1) return $langs->trans('Enabled');
if ($status == 0) return $langs->trans('Disabled');
}
if ($mode == 2)
{
if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
}
if ($mode == 3)
{
if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4');
if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5');
}
if ($mode == 4)
{
if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
}
if ($mode == 5)
{
if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
}
}
/**
* Initialise object with example values
* Id must be 0 if object instance is a specimen
*
* @return void
*/
public function initAsSpecimen()
{
$this->id = 0;
$now=dol_now();
$this->fk_website = '';
$this->pageurl = '';
$this->title = 'My Page';
$this->description = 'This is my page';
$this->keywords = 'keyword1, keyword2';
$this->content = '<html><body>This is a html content</body></html>';
$this->status = '';
$this->date_creation = $now - (24 * 30 * 3600);
$this->date_modification = $now - (24 * 7 * 3600);
}
}
| gpl-3.0 |
carlpulley/chs2580-assignment | db/schema.rb | 3983 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20101104164943) do
create_table "apache_accesses", :force => true do |t|
t.string "remote"
t.string "host"
t.string "user"
t.string "http_method"
t.string "http_url"
t.string "http_version"
t.integer "result"
t.integer "bytes"
t.string "referer"
t.string "user_agent"
t.string "unknown"
t.string "local"
t.integer "timestamp"
t.integer "pid"
t.integer "counter"
t.integer "thread_index"
t.integer "processing_time"
t.datetime "observed_at"
t.datetime "created_at"
t.datetime "updated_at"
t.string "name"
t.integer "file_object_id"
t.integer "parent_id"
t.integer "lft"
t.integer "rgt"
t.integer "depth"
t.integer "archive_content_id"
t.integer "ip_address_id"
end
create_table "apache_errors", :force => true do |t|
t.datetime "observed_at"
t.string "level"
t.string "client"
t.string "message"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "ip_address_id"
end
create_table "archive_contents", :force => true do |t|
t.string "type"
t.string "archive"
t.string "name"
t.integer "size"
t.boolean "directory"
t.datetime "observed_at"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "auths", :force => true do |t|
t.datetime "observed_at"
t.string "host"
t.string "process"
t.integer "pid"
t.text "message"
t.string "type"
t.datetime "created_at"
t.datetime "updated_at"
t.string "state"
end
create_table "blacklists", :force => true do |t|
t.integer "ip_address_id"
t.integer "web_page_id"
t.string "reference"
t.string "site"
t.string "status"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "file_objects", :force => true do |t|
t.string "name"
t.integer "lft"
t.integer "rgt"
t.integer "parent_id"
t.integer "depth"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "ip_addresses", :force => true do |t|
t.string "value"
t.string "cc"
t.integer "asn"
t.string "bgp_prefix"
t.string "registry"
t.datetime "allocated_at"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "matches", :force => true do |t|
t.integer "archive_content_id"
t.integer "apache_access_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "taggings", :force => true do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
t.integer "tagger_id"
t.string "tagger_type"
t.string "context"
t.datetime "created_at"
end
add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id"
add_index "taggings", ["taggable_id", "taggable_type", "context"], :name => "index_taggings_on_taggable_id_and_taggable_type_and_context"
create_table "tags", :force => true do |t|
t.string "name"
end
create_table "web_pages", :force => true do |t|
t.string "url"
t.text "page"
t.datetime "created_at"
t.datetime "updated_at"
end
end
| gpl-3.0 |
ded-zamkad/wp-flickr-embed-plus | include/class.flickr.php | 22785 | <?php
/**
* Flickr API Kit with support for OAuth 1.0a for PHP >= 5.3.0. Requires curl.
*
* Author: David Wilkinson
* Web: http://dopiaza.org/
*
* Copyright (c) 2012 David Wilkinson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
class WpFlickrEmbed_Flickr
{
const VERSION = '1.2.3';
/**
* Session variable name used to store authentication data
*/
const SESSION_OAUTH_DATA = 'FlickrSessionOauthData';
/**
* Key names for various authentication data items
*/
const OAUTH_REQUEST_TOKEN = 'oauth_request_token';
const OAUTH_REQUEST_TOKEN_SECRET = 'oauth_request_token_secret';
const OAUTH_VERIFIER = 'oauth_verifier';
const OAUTH_ACCESS_TOKEN = 'oauth_access_token';
const OAUTH_ACCESS_TOKEN_SECRET = 'oauth_access_token_secret';
const USER_NSID = 'user_nsid';
const USER_NAME = 'user_name';
const USER_FULL_NAME = 'user_full_name';
const PERMISSIONS = 'permissions';
const IS_AUTHENTICATING = 'is_authenticating';
/**
* Default timeout in seconds for HTTP requests
*/
const DEFAULT_HTTP_TIMEOUT = 30;
/**
* Various API endpoints
*/
const REQUEST_TOKEN_ENDPOINT = 'https://www.flickr.com/services/oauth/request_token';
const AUTH_ENDPOINT = 'https://www.flickr.com/services/oauth/authorize';
const ACCESS_TOKEN_ENDPOINT = 'https://www.flickr.com/services/oauth/access_token';
const API_ENDPOINT = 'https://www.flickr.com/services/rest';
const SECURE_API_ENDPOINT = 'https://secure.flickr.com/services/rest';
const UPLOAD_ENDPOINT = 'https://www.flickr.com/services/upload/';
const REPLACE_ENDPOINT = 'https://www.flickr.com/services/replace/';
/**
* @var string Flickr API key
*/
private $consumerKey;
/**
* @var string Flickr API secret
*/
private $consumerSecret;
/**
* @var string Callback URI for authentication
*/
private $callback;
/**
* @var string HTTP Method to use for API calls
*/
private $method = 'POST';
/**
* @var int HTTP Response code for last call made
*/
private $lastHttpResponseCode;
/**
* @var int Timeout in seconds for HTTP calls
*/
private $httpTimeout;
/**
* Create a new Flickr object
*
* @param string $key The Flickr API key
* @param string $secret The Flickr API secret
* @param string $callback The callback URL for authentication
*/
public function __construct($key, $secret = NULL, $callback = NULL)
{
session_start();
$this->consumerKey = $key;
$this->consumerSecret = $secret;
$this->callback = $callback;
$this->httpTimeout = self::DEFAULT_HTTP_TIMEOUT;
}
/**
* Call a Flickr API method
*
* @param string $method The FLickr API method name
* @param array $parameters The method parameters
* @return mixed|null The response object
*/
public function call($method, $parameters = NULL)
{
$signed = $this->getSignedUrlParams($method, $parameters);
$response = $this->httpRequest($signed['url'], $signed['params']);
return empty($response) ? NULL : unserialize($response);
}
/**
* Get the signed URL and params needed to call a Flickr API method
*
* If not authenticated then unsigned version is returned.
*
* @param string $method The FLickr API method name
* @param array $parameters The method parameters
* @param array $options additional options:
* use_secure_api = true|false (default)
*
* @return array('url' => string, 'params' => array)
*/
public function getSignedUrlParams($method, $parameters = NULL, $options = array())
{
if (!empty($options['use_secure_api'])) {
$api_url = self::SECURE_API_ENDPOINT;
} else {
$api_url = self::API_ENDPOINT;
}
$requestParams = ($parameters == NULL ? array() : $parameters);
$requestParams['method'] = $method;
if (empty($requestParams['format']))
$requestParams['format'] = 'php_serial';
// if authenticated then add in authentication
if ($this->isAuthenticated()) {
$requestParams = array_merge($requestParams, $this->getOauthParams());
$requestParams['oauth_token'] = $this->getOauthData(self::OAUTH_ACCESS_TOKEN);
$this->sign($api_url, $requestParams);
}
return array(
'url' => $api_url,
'params' => $requestParams
);
}
/**
* Upload a photo
* @param $parameters
* @return mixed|null
*/
public function upload($parameters)
{
$requestParams = ($parameters == NULL ? array() : $parameters);
$requestParams = array_merge($requestParams, $this->getOauthParams());
$requestParams['oauth_token'] = $this->getOauthData(self::OAUTH_ACCESS_TOKEN);
// We don't want to include the photo when signing the request
// so temporarily remove it whilst we sign
$photo = $requestParams['photo'];
unset($requestParams['photo']);
$this->sign(self::UPLOAD_ENDPOINT, $requestParams);
$requestParams['photo'] = $photo;
$xml = $this->httpRequest(self::UPLOAD_ENDPOINT, $requestParams);
$response = $this->getResponseFromXML($xml);
return empty($response) ? NULL : $response;
}
/**
* Replace a photo
* @param $parameters
* @return mixed|null
*/
public function replace($parameters)
{
$requestParams = ($parameters == NULL ? array() : $parameters);
$requestParams = array_merge($requestParams, $this->getOauthParams());
$requestParams['oauth_token'] = $this->getOauthData(self::OAUTH_ACCESS_TOKEN);
// We don't want to include the photo when signing the request
// so temporarily remove it whilst we sign
$photo = $requestParams['photo'];
unset($requestParams['photo']);
$this->sign(self::REPLACE_ENDPOINT, $requestParams);
$requestParams['photo'] = $photo;
$xml = $this->httpRequest(self::REPLACE_ENDPOINT, $requestParams);
$response = $this->getResponseFromXML($xml);
return empty($response) ? NULL : $response;
}
/**
* Initiate the authentication process. Note that this method might not return - the user may get redirected to
* Flickr to approve the request.
*
* @param string $permissions The permissions requested: read, write or delete
*/
public function authenticate($permissions = 'read')
{
$ok = false;
// First of all, check to see if we're part way through the authentication process
if ($this->getOauthData(self::IS_AUTHENTICATING))
{
$oauthToken = @$_GET['oauth_token'];
$oauthVerifier = @$_GET['oauth_verifier'];
if (!empty($oauthToken) && !empty($oauthVerifier))
{
// Looks like we're in the callback
$this->setOauthData(self::OAUTH_REQUEST_TOKEN, $oauthToken);
$this->setOauthData(self::OAUTH_VERIFIER, $oauthVerifier);
$ok = $this->obtainAccessToken();
// if we had problems getting the access token then quit now
if (!$ok)
return false;
}
$this->setOauthData(self::IS_AUTHENTICATING, false);
}
$ok = ($this->isAuthenticated() && $this->doWeHaveGoodEnoughPermissions($permissions));
if (!$ok)
{
// We're authenticating afresh, clear out the session just in case there are remnants of a
// previous authentication in there
$this->signout();
if ($this->obtainRequestToken())
{
// We've got the request token, redirect to Flickr for authentication/authorisation
// Make a note in the session of where we are first
$this->setOauthData(self::IS_AUTHENTICATING, true);
$this->setOauthData(self::PERMISSIONS, $permissions);
header(sprintf('Location: %s?oauth_token=%s&perms=%s',
self::AUTH_ENDPOINT,
$this->getOauthData(self::OAUTH_REQUEST_TOKEN),
$permissions
));
exit(0);
}
}
return $ok;
}
/**
* Sign the current user out of the current Flickr session. Note this doesn't affect the user's state on the
* Flickr web site itself, it merely removes the current request/access tokens from the session.
*
*/
public function signout()
{
unset($_SESSION[self::SESSION_OAUTH_DATA]);
}
/**
* Is the current session authenticated on Flickr
*
* @return bool the current authentication status
*/
public function isAuthenticated()
{
$authNSID = $this->getOauthData(self::USER_NSID);
return !empty($authNSID);
}
/**
* Return a value from the OAuth session data
*
* @param string $key
* @return string value
*/
public function getOauthData($key)
{
$val = NULL;
$data = @$_SESSION[self::SESSION_OAUTH_DATA];
if (is_array($data))
{
$val = @$data[$key];
}
return $val;
}
/**
* Return the HTTP Response code for the last HTTP call made
*
* @return int
*/
public function getLastHttpResponseCode()
{
return $this->lastHttpResponseCode;
}
/**
* Set the timeout for HTTP requests
*
* @param int $timeout
*/
public function setHttpTimeout($timeout)
{
$this->httpTimeout = $timeout;
}
/**
* Convert an old authentication token into an OAuth access token
*
* @param string $token
*/
public function convertOldToken($token)
{
$param = array(
'method' => 'flickr.auth.oauth.getAccessToken',
'format' => 'php_serial',
'api_key' => $this->consumerKey,
'auth_token' => $token
);
$this->signUsingOldStyleAuth($param);
$rsp = $this->httpRequest(self::API_ENDPOINT, $param);
$response = unserialize($rsp);
if (@$response['stat'] == 'ok')
{
$accessToken = @$response['auth']['access_token']['oauth_token'];
$accessTokenSecret = @$response['auth']['access_token']['oauth_token_secret'];
$this->setOauthData(self::OAUTH_ACCESS_TOKEN, $accessToken);
$this->setOauthData(self::OAUTH_ACCESS_TOKEN_SECRET, $accessTokenSecret);
$response = $this->call('flickr.auth.oauth.checkToken');
if (@$response['stat'] == 'ok')
{
$this->setOauthData(self::USER_NSID, @$response['oauth']['user']['nsid']);
$this->setOauthData(self::USER_NAME, @$response['oauth']['user']['username']);
$this->setOauthData(self::USER_FULL_NAME, @$response['oauth']['user']['fullname']);
}
}
}
/**
* Sign an array of parameters using the old-style auth method
*
* @param array $parameters
*/
private function signUsingOldStyleAuth(&$parameters)
{
$keys = array_keys($parameters);
sort($keys, SORT_STRING);
$s = $this->consumerSecret;
foreach ($keys as $k)
{
$s .= $k . $parameters[$k];
}
$parameters['api_sig'] = md5($s);
}
private function setOauthData($key, $value)
{
$data = @$_SESSION[self::SESSION_OAUTH_DATA];
if (!is_array($data))
{
$data = array();
}
$data[$key] = $value;
$_SESSION[self::SESSION_OAUTH_DATA] = $data;
}
/**
* Override the current OAuth API access credentials with the given ones.
*
* @param $credentials
*/
public function useOAuthAccessCredentials($credentials) {
$this->setOauthData(self::USER_FULL_NAME, $credentials[self::USER_FULL_NAME]);
$this->setOauthData(self::USER_NAME, $credentials[self::USER_NAME]);
$this->setOauthData(self::USER_NSID, $credentials[self::USER_NSID]);
$this->setOauthData(self::OAUTH_ACCESS_TOKEN, $credentials[self::OAUTH_ACCESS_TOKEN]);
$this->setOauthData(self::OAUTH_ACCESS_TOKEN_SECRET, $credentials[self::OAUTH_ACCESS_TOKEN_SECRET]);
}
/**
* Check whether the current permission satisfy those requested
*
* @param string $permissionsRequired
* @return bool
*/
private function doWeHaveGoodEnoughPermissions($permissionsRequired)
{
$ok = false;
$currentPermissions = $this->getOauthData(self::PERMISSIONS);
switch($permissionsRequired)
{
case 'read':
$ok = preg_match('/^(read|write|delete)$/', $currentPermissions);
break;
case 'write':
$ok = preg_match('/^(write|delete)$/', $currentPermissions);
break;
case 'delete':
$ok = ($currentPermissions == 'delete');
break;
}
return $ok;
}
/**
* Get a request token from Flickr
*
* @return bool
*/
private function obtainRequestToken()
{
$params = $this->getOauthParams();
$params['oauth_callback'] = $this->callback;
$this->sign(self::REQUEST_TOKEN_ENDPOINT, $params);
$rsp = $this->httpRequest(self::REQUEST_TOKEN_ENDPOINT, $params);
$responseParameters = $this->splitParameters($rsp);
$callbackOK = (@$responseParameters['oauth_callback_confirmed'] == 'true');
if ($callbackOK)
{
$this->setOauthData(self::OAUTH_REQUEST_TOKEN, @$responseParameters['oauth_token']);
$this->setOauthData(self::OAUTH_REQUEST_TOKEN_SECRET, @$responseParameters['oauth_token_secret']);
}
return $callbackOK;
}
/**
* Get an access token from Flickr
*
* @return bool
*/
private function obtainAccessToken()
{
$params = $this->getOauthParams();
$params['oauth_token'] = $this->getOauthData(self::OAUTH_REQUEST_TOKEN);
$params['oauth_verifier'] = $this->getOauthData(self::OAUTH_VERIFIER);
$this->sign(self::ACCESS_TOKEN_ENDPOINT, $params);
$rsp = $this->httpRequest(self::ACCESS_TOKEN_ENDPOINT, $params);
$responseParameters = $this->splitParameters($rsp);
$ok = !empty($responseParameters['oauth_token']);
if ($ok)
{
$this->setOauthData(self::OAUTH_ACCESS_TOKEN, @$responseParameters['oauth_token']);
$this->setOauthData(self::OAUTH_ACCESS_TOKEN_SECRET, @$responseParameters['oauth_token_secret']);
$this->setOauthData(self::USER_NSID, @$responseParameters['user_nsid']);
$this->setOauthData(self::USER_NAME, @$responseParameters['username']);
$this->setOauthData(self::USER_FULL_NAME, @$responseParameters['fullname']);
}
return $ok;
}
/**
* Split a string into an array of key-value pairs
*
* @param string $string
* @return array
*/
private function splitParameters($string)
{
$parameters = array();
$keyValuePairs = explode('&', $string);
foreach ($keyValuePairs as $kvp)
{
$pieces = explode('=', $kvp);
if (count($pieces) == 2)
{
$parameters[rawurldecode($pieces[0])] = rawurldecode($pieces[1]);
}
}
return $parameters;
}
/**
* Join an array of parameters together into a URL-encoded string
*
* @param array $parameters
* @return string
*/
private function joinParameters($parameters)
{
$keys = array_keys($parameters);
sort($keys, SORT_STRING);
$keyValuePairs = array();
foreach ($keys as $k)
{
array_push($keyValuePairs, rawurlencode($k) . "=" . rawurlencode($parameters[$k]));
}
return implode("&", $keyValuePairs);
}
/**
* Get the base string for creating an OAuth signature
*
* @param string $method
* @param string $url
* @param array $parameters
* @return string
*/
private function getBaseString($method, $url, $parameters)
{
$components = array(
rawurlencode($method),
rawurlencode($url),
rawurlencode($this->joinParameters($parameters))
);
$baseString = implode("&", $components);
return $baseString;
}
/**
* Sign an array of parameters with an OAuth signature
*
* @param string $url
* @param array $parameters
*/
private function sign($url, &$parameters)
{
$baseString = $this->getBaseString($this->method, $url, $parameters);
$signature = $this->getSignature($baseString);
$parameters['oauth_signature'] = $signature;
}
/**
* Calculate the signature for a string
*
* @param string $string
* @return string
*/
private function getSignature($string)
{
$keyPart1 = $this->consumerSecret;
$keyPart2 = $this->getOauthData(self::OAUTH_ACCESS_TOKEN_SECRET);
if (empty($keyPart2))
{
$keyPart2 = $this->getOauthData(self::OAUTH_REQUEST_TOKEN_SECRET);
}
if (empty($keyPart2))
{
$keyPart2 = '';
}
$key = "$keyPart1&$keyPart2";
return base64_encode(hash_hmac('sha1', $string, $key, true));
}
/**
* Get the standard OAuth parameters
*
* @return array
*/
private function getOauthParams()
{
$params = array (
'oauth_nonce' => $this->makeNonce(),
'oauth_timestamp' => time(),
'oauth_consumer_key' => $this->consumerKey,
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_version' => '1.0',
);
return $params;
}
/**
* Create a nonce
*
* @return string
*/
private function makeNonce()
{
// Create a string that will be unique for this app and this user at this time
$reasonablyDistinctiveString = implode(':',
array(
$this->consumerKey,
$this->getOauthData(self::USER_NSID),
microtime()
)
);
return md5($reasonablyDistinctiveString);
}
/**
* Get the response structure from an XML response.
* Annoyingly, upload and replace returns XML rather than serialised PHP.
* The responses are pretty simple, so rather than depend on an XML parser we'll fake it and
* decode using regexps
* @param $xml
* @return mixed
*/
private function getResponseFromXML($xml)
{
$rsp = array();
$stat = 'fail';
$matches = array();
preg_match('/<rsp stat="(ok|fail)">/s', $xml, $matches);
if (count($matches) > 0)
{
$stat = $matches[1];
}
if ($stat == 'ok')
{
// do this in individual steps in case the order of the attributes ever changes
$rsp['stat'] = $stat;
$photoid = array();
$matches = array();
preg_match('/<photoid.*>(\d+)<\/photoid>/s', $xml, $matches);
if (count($matches) > 0)
{
$photoid['_content'] = $matches[1];
}
$matches = array();
preg_match('/<photoid.* secret="(\w+)".*>/s', $xml, $matches);
if (count($matches) > 0)
{
$photoid['secret'] = $matches[1];
}
$matches = array();
preg_match('/<photoid.* originalsecret="(\w+)".*>/s', $xml, $matches);
if (count($matches) > 0)
{
$photoid['originalsecret'] = $matches[1];
}
$rsp['photoid'] = $photoid;
}
else
{
$rsp['stat'] = 'fail';
$err = array();
$matches = array();
preg_match('/<err.* code="([^"]*)".*>/s', $xml, $matches);
if (count($matches) > 0)
{
$err['code'] = $matches[1];
}
$matches = array();
preg_match('/<err.* msg="([^"]*)".*>/s', $xml, $matches);
if (count($matches) > 0)
{
$err['msg'] = $matches[1];
}
$rsp['err'] = $err;
}
return $rsp;
}
/**
* Make an HTTP request
*
* @param string $url
* @param array $parameters
* @return mixed
*/
private function httpRequest($url, $parameters)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_TIMEOUT, $this->httpTimeout);
if ($this->method == 'POST')
{
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $parameters);
}
else
{
// Assume GET
curl_setopt($curl, CURLOPT_URL, "$url?" . $this->joinParameters($parameters));
}
$response = curl_exec($curl);
$headers = curl_getinfo($curl);
curl_close($curl);
$this->lastHttpResponseCode = $headers['http_code'];
return $response;
}
}
| gpl-3.0 |
stevenvandervalk/aodn-portal | web-app/js/portal/utils/ObservableUtils.js | 694 | Ext.namespace('Portal.utils');
Portal.utils.ObservableUtils = {
FUNCTIONS_TO_FORWARD: [
'addEvents',
'addListener',
'enableBubble',
'fireEvent',
'hasListener',
'on',
'purgeListeners',
'relayEvents',
'removeListener',
'resumeEvents',
'suspendEvents',
'un'
],
makeObservable: function(target) {
target._observable = new Ext.util.Observable();
Ext.each(this.FUNCTIONS_TO_FORWARD, function(funcName) {
target[funcName] = function() {
return this._observable[funcName].apply(target._observable, arguments);
};
});
}
};
| gpl-3.0 |
tgvaughan/bacter | src/bacter/util/parsers/ExtendedNewickVisitor.java | 2686 | // Generated from /Users/vaughant/code/beast_and_friends/bacter/src/bacter/util/parsers/ExtendedNewick.g4 by ANTLR 4.7
package bacter.util.parsers;
import org.antlr.v4.runtime.tree.ParseTreeVisitor;
/**
* This interface defines a complete generic visitor for a parse tree produced
* by {@link ExtendedNewickParser}.
*
* @param <T> The return type of the visit operation. Use {@link Void} for
* operations with no return type.
*/
public interface ExtendedNewickVisitor<T> extends ParseTreeVisitor<T> {
/**
* Visit a parse tree produced by {@link ExtendedNewickParser#tree}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitTree(ExtendedNewickParser.TreeContext ctx);
/**
* Visit a parse tree produced by {@link ExtendedNewickParser#node}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitNode(ExtendedNewickParser.NodeContext ctx);
/**
* Visit a parse tree produced by {@link ExtendedNewickParser#post}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitPost(ExtendedNewickParser.PostContext ctx);
/**
* Visit a parse tree produced by {@link ExtendedNewickParser#label}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitLabel(ExtendedNewickParser.LabelContext ctx);
/**
* Visit a parse tree produced by {@link ExtendedNewickParser#hybrid}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitHybrid(ExtendedNewickParser.HybridContext ctx);
/**
* Visit a parse tree produced by {@link ExtendedNewickParser#meta}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitMeta(ExtendedNewickParser.MetaContext ctx);
/**
* Visit a parse tree produced by {@link ExtendedNewickParser#attrib}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitAttrib(ExtendedNewickParser.AttribContext ctx);
/**
* Visit a parse tree produced by {@link ExtendedNewickParser#attribValue}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitAttribValue(ExtendedNewickParser.AttribValueContext ctx);
/**
* Visit a parse tree produced by {@link ExtendedNewickParser#number}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitNumber(ExtendedNewickParser.NumberContext ctx);
/**
* Visit a parse tree produced by {@link ExtendedNewickParser#vector}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitVector(ExtendedNewickParser.VectorContext ctx);
/**
* Visit a parse tree produced by {@link ExtendedNewickParser#string}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitString(ExtendedNewickParser.StringContext ctx);
} | gpl-3.0 |
Nivl/www.melvin.re | nivls_website/seo/admin.py | 327 | from django.contrib import admin
from django.contrib.contenttypes import generic
from models import *
class InlineSeo(generic.GenericTabularInline):
model = SeoEverywhere
max_num = 1
extra = 0
class InlineMicroData(generic.GenericTabularInline):
model = SeoMicroData
extra = 1
admin.site.register(SEO)
| gpl-3.0 |
ekansa/open-context-py | opencontext_py/apps/edit/modlinkentities.py | 10148 | import os
import codecs
from django.conf import settings
from django.db import models
from django.db.models import Q
from opencontext_py.apps.entities.uri.models import URImanagement
from opencontext_py.apps.ldata.linkentities.models import LinkEntity
from opencontext_py.apps.ocitems.manifest.models import Manifest
from opencontext_py.apps.ldata.linkannotations.models import LinkAnnotation
from opencontext_py.apps.ldata.linkannotations.manage import LinkAnnoManagement
# This class is used for the mass editing of category data
class ModifyLinkEntities():
REVISION_LIST = [
{'new': 'oc-zoo:B', 'old': 'oc-zoo:zoo-0001'},
{'new': 'oc-zoo:BF', 'old': 'oc-zoo:zoo-0002'},
{'new': 'oc-zoo:BFd', 'old': 'oc-zoo:zoo-0003'},
{'new': 'oc-zoo:BFp', 'old': 'oc-zoo:zoo-0004'},
{'new': 'oc-zoo:BG', 'old': 'oc-zoo:zoo-0005'},
{'new': 'oc-zoo:BPC', 'old': 'oc-zoo:zoo-0006'},
{'new': 'oc-zoo:BT', 'old': 'oc-zoo:zoo-0007'},
{'new': 'oc-zoo:BTr', 'old': 'oc-zoo:zoo-0008'},
{'new': 'oc-zoo:Bd', 'old': 'oc-zoo:zoo-0009'},
{'new': 'oc-zoo:Bp', 'old': 'oc-zoo:zoo-0010'},
{'new': 'oc-zoo:CD', 'old': 'oc-zoo:zoo-0011'},
{'new': 'oc-zoo:DC', 'old': 'oc-zoo:zoo-0012'},
{'new': 'oc-zoo:DD', 'old': 'oc-zoo:zoo-0013'},
{'new': 'oc-zoo:DHA', 'old': 'oc-zoo:zoo-0014'},
{'new': 'oc-zoo:DLS', 'old': 'oc-zoo:zoo-0015'},
{'new': 'oc-zoo:DPA', 'old': 'oc-zoo:zoo-0016'},
{'new': 'oc-zoo:Dd', 'old': 'oc-zoo:zoo-0017'},
{'new': 'oc-zoo:Dl', 'old': 'oc-zoo:zoo-0018'},
{'new': 'oc-zoo:Dm', 'old': 'oc-zoo:zoo-0019'},
{'new': 'oc-zoo:Dp', 'old': 'oc-zoo:zoo-0020'},
{'new': 'oc-zoo:GB', 'old': 'oc-zoo:zoo-0021'},
{'new': 'oc-zoo:GBA', 'old': 'oc-zoo:zoo-0022'},
{'new': 'oc-zoo:GBTc', 'old': 'oc-zoo:zoo-0023'},
{'new': 'oc-zoo:GBTi', 'old': 'oc-zoo:zoo-0024'},
{'new': 'oc-zoo:GH', 'old': 'oc-zoo:zoo-0025'},
{'new': 'oc-zoo:GL', 'old': 'oc-zoo:zoo-0026'},
{'new': 'oc-zoo:GLC', 'old': 'oc-zoo:zoo-0027'},
{'new': 'oc-zoo:GLP', 'old': 'oc-zoo:zoo-0028'},
{'new': 'oc-zoo:GLl', 'old': 'oc-zoo:zoo-0029'},
{'new': 'oc-zoo:GLm', 'old': 'oc-zoo:zoo-0030'},
{'new': 'oc-zoo:GLpe', 'old': 'oc-zoo:zoo-0031'},
{'new': 'oc-zoo:HP', 'old': 'oc-zoo:zoo-0032'},
{'new': 'oc-zoo:HS', 'old': 'oc-zoo:zoo-0033'},
{'new': 'oc-zoo:LA', 'old': 'oc-zoo:zoo-0034'},
{'new': 'oc-zoo:LAR', 'old': 'oc-zoo:zoo-0035'},
{'new': 'oc-zoo:LF', 'old': 'oc-zoo:zoo-0036'},
{'new': 'oc-zoo:LFo', 'old': 'oc-zoo:zoo-0037'},
{'new': 'oc-zoo:LG', 'old': 'oc-zoo:zoo-0038'},
{'new': 'oc-zoo:LO', 'old': 'oc-zoo:zoo-0039'},
{'new': 'oc-zoo:LS', 'old': 'oc-zoo:zoo-0040'},
{'new': 'oc-zoo:Ld', 'old': 'oc-zoo:zoo-0041'},
{'new': 'oc-zoo:LeP', 'old': 'oc-zoo:zoo-0042'},
{'new': 'oc-zoo:Ll', 'old': 'oc-zoo:zoo-0043'},
{'new': 'oc-zoo:LmT', 'old': 'oc-zoo:zoo-0044'},
{'new': 'oc-zoo:MBS', 'old': 'oc-zoo:zoo-0045'},
{'new': 'oc-zoo:PL', 'old': 'oc-zoo:zoo-0046'},
{'new': 'oc-zoo:SB', 'old': 'oc-zoo:zoo-0047'},
{'new': 'oc-zoo:SBI', 'old': 'oc-zoo:zoo-0048'},
{'new': 'oc-zoo:SC', 'old': 'oc-zoo:zoo-0049'},
{'new': 'oc-zoo:SD', 'old': 'oc-zoo:zoo-0050'},
{'new': 'oc-zoo:SDO', 'old': 'oc-zoo:zoo-0051'},
{'new': 'oc-zoo:SH', 'old': 'oc-zoo:zoo-0052'},
{'new': 'oc-zoo:SLC', 'old': 'oc-zoo:zoo-0053'},
{'new': 'oc-zoo:anatomical-meas', 'old': 'oc-zoo:zoo-0054'},
{'new': 'oc-zoo:astragalus-talus-meas', 'old': 'oc-zoo:zoo-0055'},
{'new': 'oc-zoo:calcaneus-meas', 'old': 'oc-zoo:zoo-0056'},
{'new': 'oc-zoo:dist-epi-fused', 'old': 'oc-zoo:zoo-0057'},
{'new': 'oc-zoo:dist-epi-unfused', 'old': 'oc-zoo:zoo-0058'},
{'new': 'oc-zoo:dist-epi-fusing', 'old': 'oc-zoo:zoo-0059'},
{'new': 'oc-zoo:femur-meas', 'old': 'oc-zoo:zoo-0060'},
{'new': 'oc-zoo:fusion-characterization', 'old': 'oc-zoo:zoo-0061'},
{'new': 'oc-zoo:humerus-meas', 'old': 'oc-zoo:zoo-0062'},
{'new': 'oc-zoo:von-den-driesch-bone-meas', 'old': 'oc-zoo:zoo-0063'},
{'new': 'oc-zoo:metapodial-meas', 'old': 'oc-zoo:zoo-0064'},
{'new': 'oc-zoo:pelvis-meas', 'old': 'oc-zoo:zoo-0065'},
{'new': 'oc-zoo:phalanx-1-meas', 'old': 'oc-zoo:zoo-0066'},
{'new': 'oc-zoo:phalanx-2-meas', 'old': 'oc-zoo:zoo-0067'},
{'new': 'oc-zoo:phalanx-3-meas', 'old': 'oc-zoo:zoo-0068'},
{'new': 'oc-zoo:prox-epi-fused', 'old': 'oc-zoo:zoo-0069'},
{'new': 'oc-zoo:prox-epi-unfused', 'old': 'oc-zoo:zoo-0070'},
{'new': 'oc-zoo:prox-epi-fusing', 'old': 'oc-zoo:zoo-0071'},
{'new': 'oc-zoo:radius-meas', 'old': 'oc-zoo:zoo-0072'},
{'new': 'oc-zoo:scapula-meas', 'old': 'oc-zoo:zoo-0073'},
{'new': 'oc-zoo:tarsal-meas', 'old': 'oc-zoo:zoo-0074'},
{'new': 'oc-zoo:tibia-meas', 'old': 'oc-zoo:zoo-0075'},
{'new': 'oc-zoo:ulna-meas', 'old': 'oc-zoo:zoo-0076'},
{'new': 'oc-zoo:has-fusion-char', 'old': 'oc-zoo:zoo-0077'},
{'new': 'oc-zoo:has-phys-sex-det', 'old': 'oc-zoo:zoo-0078'},
{'new': 'oc-zoo:has-anat-id', 'old': 'oc-zoo:zoo-0079'},
{'new': 'oc-zoo:tibiotarsus-meas', 'old': 'oc-zoo:zoo-0080'},
{'new': 'oc-zoo:Dip', 'old': 'oc-zoo:zoo-0081'},
{'new': 'oc-zoo:Dic', 'old': 'oc-zoo:zoo-0082'},
{'new': 'oc-zoo:malleolus-meas', 'old': 'oc-zoo:zoo-0083'},
{'new': 'oc-zoo:GD', 'old': 'oc-zoo:zoo-0084'},
{'new': 'oc-zoo:axis-meas', 'old': 'oc-zoo:zoo-0085'},
{'new': 'oc-zoo:SBV', 'old': 'oc-zoo:zoo-0086'},
{'new': 'oc-zoo:other-meas', 'old': 'oc-zoo:zoo-0087'},
{'new': 'oc-zoo:HT', 'old': 'oc-zoo:zoo-0088'},
{'new': 'oc-zoo:humerus-meas', 'old': 'oc-zoo:zoo-0089'},
{'new': 'oc-zoo:HT', 'old': 'oc-zoo:zoo-0090'},
{'new': 'oc-zoo:H', 'old': 'oc-zoo:zoo-0092'},
{'new': 'oc-zoo:LCDe', 'old': 'oc-zoo:zoo-0093'},
{'new': 'oc-zoo:LAPa', 'old': 'oc-zoo:zoo-0094'},
{'new': 'oc-zoo:atlas-meas', 'old': 'oc-zoo:zoo-0095'},
{'new': 'oc-zoo:BFcr', 'old': 'oc-zoo:zoo-0096'},
{'new': 'oc-zoo:BFcd', 'old': 'oc-zoo:zoo-0097'},
{'new': 'oc-zoo:LAd', 'old': 'oc-zoo:zoo-0098'},
{'new': 'oc-zoo:BPacd', 'old': 'oc-zoo:zoo-0099'},
{'new': 'oc-zoo:BPtr', 'old': 'oc-zoo:zoo-0100'},
{'new': 'oc-zoo:has-anat-id', 'old': 'oc-zoo:zoo-0079'},
{'new': 'oc-zoo:Dip', 'old': 'oc-zoo:zoo-0081'},
{'new': 'oc-zoo:Dic', 'old': 'oc-zoo:zoo-0082'},
{'new': 'oc-zoo:GD', 'old': 'oc-zoo:zoo-0084'},
{'new': 'oc-zoo:SBV', 'old': 'oc-zoo:zoo-0086'},
{'new': 'oc-zoo:HT', 'old': 'oc-zoo:zoo-0088'},
{'new': 'oc-zoo:HT', 'old': 'oc-zoo:zoo-0090'},
{'new': 'oc-zoo:H', 'old': 'oc-zoo:zoo-0092'},
{'new': 'oc-zoo:LCDe', 'old': 'oc-zoo:zoo-0093'},
{'new': 'oc-zoo:LAPa', 'old': 'oc-zoo:zoo-0094'},
{'new': 'oc-zoo:BFcr', 'old': 'oc-zoo:zoo-0096'},
{'new': 'oc-zoo:BPacd', 'old': 'oc-zoo:zoo-0099'},
{'new': 'oc-zoo:BPtr', 'old': 'oc-zoo:zoo-0100'}
]
def __init__(self):
self.root_export_dir = settings.STATIC_EXPORTS_ROOT + 'categories'
self.temp_prefix = 'oc-zoo:'
self.root_uri = 'http://opencontext.org/vocabularies/open-context-zooarch/'
def validate_revisions(self):
""" checks to make sure revisions lead to unique uris """
valid = True
old_uris = []
unique_uris = []
for revision in self.REVISION_LIST:
old_short = revision['old']
replace_short = revision['new']
old_uri = old_short.replace(self.temp_prefix, self.root_uri)
new_uri = replace_short.replace(self.temp_prefix, self.root_uri)
if old_uri not in old_uris:
old_uris.append(old_uri)
if new_uri not in unique_uris:
unique_uris.append(new_uri)
else:
new_uri += '-2'
if new_uri not in unique_uris:
unique_uris.append(new_uri)
else:
print('Crap! Too many: ' + replace_short)
return valid
def mass_revise_uris(self):
""" Revises category uris in a mass edit
"""
old_uris = []
unique_uris = []
for revision in self.REVISION_LIST:
ok = False
old_short = revision['old']
replace_short = revision['new']
old_uri = old_short.replace(self.temp_prefix, self.root_uri)
new_uri = replace_short.replace(self.temp_prefix, self.root_uri)
if old_uri not in old_uris:
old_uris.append(old_uri)
ok = True
if ok:
lam = LinkAnnoManagement()
lam.replace_object_uri(old_uri, new_uri)
LinkEntity.objects\
.filter(uri=old_uri)\
.update(uri=new_uri)
def update_ontology_doc(self, filename):
""" Changes categories in the ontology document
"""
filepath = self.root_export_dir + '/' + filename
newfilepath = self.root_export_dir + '/rev-' + filename
if os.path.isfile(filepath):
print('Found: ' + filepath)
with open(filepath, 'r') as myfile:
data = myfile.read()
for revision in self.REVISION_LIST:
old_short = revision['old']
replace_short = revision['new']
old_uri = old_short.replace(self.temp_prefix, self.root_uri)
new_uri = replace_short.replace(self.temp_prefix, self.root_uri)
data = data.replace(old_uri, new_uri)
file = codecs.open(newfilepath, 'w', 'utf-8')
file.write(data)
file.close()
else:
print('Ouch! Cannot find: '+ filepath)
| gpl-3.0 |
ucsf-ckm/moodle | course/tests/behat/behat_course.php | 86163 | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Behat course-related steps definitions.
*
* @package core_course
* @category test
* @copyright 2012 David Monllaรณ
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
require_once(__DIR__ . '/../../../lib/behat/behat_base.php');
use Behat\Gherkin\Node\TableNode as TableNode,
Behat\Mink\Exception\ExpectationException as ExpectationException,
Behat\Mink\Exception\DriverException as DriverException,
Behat\Mink\Exception\ElementNotFoundException as ElementNotFoundException;
/**
* Course-related steps definitions.
*
* @package core_course
* @category test
* @copyright 2012 David Monllaรณ
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class behat_course extends behat_base {
/**
* Return the list of partial named selectors.
*
* @return array
*/
public static function get_partial_named_selectors(): array {
return [
new behat_component_named_selector(
'Activity chooser screen', [
"%core_course/activityChooser%//*[@data-region=%locator%][contains(concat(' ', @class, ' '), ' carousel-item ')]"
]
),
new behat_component_named_selector(
'Activity chooser tab', [
"%core_course/activityChooser%//*[@data-region=%locator%][contains(concat(' ', @class, ' '), ' tab-pane ')]"
]
),
];
}
/**
* Return a list of the Mink named replacements for the component.
*
* Named replacements allow you to define parts of an xpath that can be reused multiple times, or in multiple
* xpaths.
*
* This method should return a list of {@link behat_component_named_replacement} and the docs on that class explain
* how it works.
*
* @return behat_component_named_replacement[]
*/
public static function get_named_replacements(): array {
return [
new behat_component_named_replacement(
'activityChooser',
".//*[contains(concat(' ', @class, ' '), ' modchooser ')][contains(concat(' ', @class, ' '), ' modal-dialog ')]"
),
];
}
/**
* Turns editing mode on.
* @Given /^I turn editing mode on$/
*/
public function i_turn_editing_mode_on() {
try {
$this->execute("behat_forms::press_button", get_string('turneditingon'));
} catch (Exception $e) {
$this->execute("behat_navigation::i_navigate_to_in_current_page_administration", [get_string('turneditingon')]);
}
}
/**
* Turns editing mode off.
* @Given /^I turn editing mode off$/
*/
public function i_turn_editing_mode_off() {
try {
$this->execute("behat_forms::press_button", get_string('turneditingoff'));
} catch (Exception $e) {
$this->execute("behat_navigation::i_navigate_to_in_current_page_administration", [get_string('turneditingoff')]);
}
}
/**
* Creates a new course with the provided table data matching course settings names with the desired values.
*
* @Given /^I create a course with:$/
* @param TableNode $table The course data
*/
public function i_create_a_course_with(TableNode $table) {
// Go to course management page.
$this->i_go_to_the_courses_management_page();
// Ensure you are on course management page.
$this->execute("behat_course::i_should_see_the_courses_management_page", get_string('categories'));
// Select Miscellaneous category.
$this->i_click_on_category_in_the_management_interface(get_string('miscellaneous'));
$this->execute("behat_course::i_should_see_the_courses_management_page", get_string('categoriesandcourses'));
// Click create new course.
$this->execute('behat_general::i_click_on_in_the',
array(get_string('createnewcourse'), "link", "#course-listing", "css_element")
);
// If the course format is one of the fields we change how we
// fill the form as we need to wait for the form to be set.
$rowshash = $table->getRowsHash();
$formatfieldrefs = array(get_string('format'), 'format', 'id_format');
foreach ($formatfieldrefs as $fieldref) {
if (!empty($rowshash[$fieldref])) {
$formatfield = $fieldref;
}
}
// Setting the format separately.
if (!empty($formatfield)) {
// Removing the format field from the TableNode.
$rows = $table->getRows();
$formatvalue = $rowshash[$formatfield];
foreach ($rows as $key => $row) {
if ($row[0] == $formatfield) {
unset($rows[$key]);
}
}
$table = new TableNode($rows);
// Adding a forced wait until editors are loaded as otherwise selenium sometimes tries clicks on the
// format field when the editor is being rendered and the click misses the field coordinates.
$this->execute("behat_forms::i_expand_all_fieldsets");
$this->execute("behat_forms::i_set_the_field_to", array($formatfield, $formatvalue));
}
// Set form fields.
$this->execute("behat_forms::i_set_the_following_fields_to_these_values", $table);
// Save course settings.
$this->execute("behat_forms::press_button", get_string('savechangesanddisplay'));
}
/**
* Goes to the system courses/categories management page.
*
* @Given /^I go to the courses management page$/
*/
public function i_go_to_the_courses_management_page() {
$parentnodes = get_string('courses', 'admin');
// Go to home page.
$this->execute("behat_general::i_am_on_homepage");
// Navigate to course management via system administration.
$this->execute("behat_navigation::i_navigate_to_in_site_administration",
array($parentnodes . ' > ' . get_string('coursemgmt', 'admin'))
);
}
/**
* Adds the selected activity/resource filling the form data with the specified field/value pairs. Sections 0 and 1 are also allowed on frontpage.
*
* @When /^I add a "(?P<activity_or_resource_name_string>(?:[^"]|\\")*)" to section "(?P<section_number>\d+)" and I fill the form with:$/
* @param string $activity The activity name
* @param int $section The section number
* @param TableNode $data The activity field/value data
*/
public function i_add_to_section_and_i_fill_the_form_with($activity, $section, TableNode $data) {
// Add activity to section.
$this->execute("behat_course::i_add_to_section",
array($this->escape($activity), $this->escape($section))
);
// Wait to be redirected.
$this->execute('behat_general::wait_until_the_page_is_ready');
// Set form fields.
$this->execute("behat_forms::i_set_the_following_fields_to_these_values", $data);
// Save course settings.
$this->execute("behat_forms::press_button", get_string('savechangesandreturntocourse'));
}
/**
* Opens the activity chooser and opens the activity/resource form page. Sections 0 and 1 are also allowed on frontpage.
*
* @Given /^I add a "(?P<activity_or_resource_name_string>(?:[^"]|\\")*)" to section "(?P<section_number>\d+)"$/
* @throws ElementNotFoundException Thrown by behat_base::find
* @param string $activity
* @param int $section
*/
public function i_add_to_section($activity, $section) {
if ($this->getSession()->getPage()->find('css', 'body#page-site-index') && (int)$section <= 1) {
// We are on the frontpage.
if ($section) {
// Section 1 represents the contents on the frontpage.
$sectionxpath = "//body[@id='page-site-index']" .
"/descendant::div[contains(concat(' ',normalize-space(@class),' '),' sitetopic ')]";
} else {
// Section 0 represents "Site main menu" block.
$sectionxpath = "//*[contains(concat(' ',normalize-space(@class),' '),' block_site_main_menu ')]";
}
} else {
// We are inside the course.
$sectionxpath = "//li[@id='section-" . $section . "']";
}
$activityliteral = behat_context_helper::escape(ucfirst($activity));
if ($this->running_javascript()) {
// Clicks add activity or resource section link.
$sectionxpath = $sectionxpath . "/descendant::div" .
"[contains(concat(' ', normalize-space(@class) , ' '), ' section-modchooser ')]/button";
$this->execute('behat_general::i_click_on', [$sectionxpath, 'xpath']);
// Clicks the selected activity if it exists.
$activityxpath = "//div[contains(concat(' ', normalize-space(@class), ' '), ' modchooser ')]" .
"/descendant::div[contains(concat(' ', normalize-space(@class), ' '), ' optioninfo ')]" .
"/descendant::div[contains(concat(' ', normalize-space(@class), ' '), ' optionname ')]" .
"[normalize-space(.)=$activityliteral]" .
"/parent::a";
$this->execute('behat_general::i_click_on', [$activityxpath, 'xpath']);
} else {
// Without Javascript.
// Selecting the option from the select box which contains the option.
$selectxpath = $sectionxpath . "/descendant::div" .
"[contains(concat(' ', normalize-space(@class), ' '), ' section_add_menus ')]" .
"/descendant::select[option[normalize-space(.)=$activityliteral]]";
$selectnode = $this->find('xpath', $selectxpath);
$selectnode->selectOption($activity);
// Go button.
$gobuttonxpath = $selectxpath . "/ancestor::form/descendant::input[@type='submit']";
$gobutton = $this->find('xpath', $gobuttonxpath);
$gobutton->click();
}
}
/**
* Opens a section edit menu if it is not already opened.
*
* @Given /^I open section "(?P<section_number>\d+)" edit menu$/
* @throws DriverException The step is not available when Javascript is disabled
* @param string $sectionnumber
*/
public function i_open_section_edit_menu($sectionnumber) {
if (!$this->running_javascript()) {
throw new DriverException('Section edit menu not available when Javascript is disabled');
}
// Wait for section to be available, before clicking on the menu.
$this->i_wait_until_section_is_available($sectionnumber);
// If it is already opened we do nothing.
$xpath = $this->section_exists($sectionnumber);
$xpath .= "/descendant::div[contains(@class, 'section-actions')]/descendant::a[contains(@data-toggle, 'dropdown')]";
$exception = new ExpectationException('Section "' . $sectionnumber . '" was not found', $this->getSession());
$menu = $this->find('xpath', $xpath, $exception);
$menu->click();
$this->i_wait_until_section_is_available($sectionnumber);
}
/**
* Deletes course section.
*
* @Given /^I delete section "(?P<section_number>\d+)"$/
* @param int $sectionnumber The section number
*/
public function i_delete_section($sectionnumber) {
// Ensures the section exists.
$xpath = $this->section_exists($sectionnumber);
// We need to know the course format as the text strings depends on them.
$courseformat = $this->get_course_format();
if (get_string_manager()->string_exists('deletesection', $courseformat)) {
$strdelete = get_string('deletesection', $courseformat);
} else {
$strdelete = get_string('deletesection');
}
// If javascript is on, link is inside a menu.
if ($this->running_javascript()) {
$this->i_open_section_edit_menu($sectionnumber);
}
// Click on delete link.
$this->execute('behat_general::i_click_on_in_the',
array($strdelete, "link", $this->escape($xpath), "xpath_element")
);
}
/**
* Turns course section highlighting on.
*
* @Given /^I turn section "(?P<section_number>\d+)" highlighting on$/
* @param int $sectionnumber The section number
*/
public function i_turn_section_highlighting_on($sectionnumber) {
// Ensures the section exists.
$xpath = $this->section_exists($sectionnumber);
// If javascript is on, link is inside a menu.
if ($this->running_javascript()) {
$this->i_open_section_edit_menu($sectionnumber);
}
// Click on highlight topic link.
$this->execute('behat_general::i_click_on_in_the',
array(get_string('highlight'), "link", $this->escape($xpath), "xpath_element")
);
}
/**
* Turns course section highlighting off.
*
* @Given /^I turn section "(?P<section_number>\d+)" highlighting off$/
* @param int $sectionnumber The section number
*/
public function i_turn_section_highlighting_off($sectionnumber) {
// Ensures the section exists.
$xpath = $this->section_exists($sectionnumber);
// If javascript is on, link is inside a menu.
if ($this->running_javascript()) {
$this->i_open_section_edit_menu($sectionnumber);
}
// Click on un-highlight topic link.
$this->execute('behat_general::i_click_on_in_the',
array(get_string('highlightoff'), "link", $this->escape($xpath), "xpath_element")
);
}
/**
* Shows the specified hidden section. You need to be in the course page and on editing mode.
*
* @Given /^I show section "(?P<section_number>\d+)"$/
* @param int $sectionnumber
*/
public function i_show_section($sectionnumber) {
$showlink = $this->show_section_link_exists($sectionnumber);
// Ensure section edit menu is open before interacting with it.
if ($this->running_javascript()) {
$this->i_open_section_edit_menu($sectionnumber);
}
$showlink->click();
if ($this->running_javascript()) {
$this->getSession()->wait(self::get_timeout() * 1000, self::PAGE_READY_JS);
$this->i_wait_until_section_is_available($sectionnumber);
}
}
/**
* Hides the specified visible section. You need to be in the course page and on editing mode.
*
* @Given /^I hide section "(?P<section_number>\d+)"$/
* @param int $sectionnumber
*/
public function i_hide_section($sectionnumber) {
// Ensures the section exists.
$xpath = $this->section_exists($sectionnumber);
// We need to know the course format as the text strings depends on them.
$courseformat = $this->get_course_format();
if (get_string_manager()->string_exists('hidefromothers', $courseformat)) {
$strhide = get_string('hidefromothers', $courseformat);
} else {
$strhide = get_string('hidesection');
}
// If javascript is on, link is inside a menu.
if ($this->running_javascript()) {
$this->i_open_section_edit_menu($sectionnumber);
}
// Click on delete link.
$this->execute('behat_general::i_click_on_in_the',
array($strhide, "link", $this->escape($xpath), "xpath_element")
);
if ($this->running_javascript()) {
$this->getSession()->wait(self::get_timeout() * 1000, self::PAGE_READY_JS);
$this->i_wait_until_section_is_available($sectionnumber);
}
}
/**
* Go to editing section page for specified section number. You need to be in the course page and on editing mode.
*
* @Given /^I edit the section "(?P<section_number>\d+)"$/
* @param int $sectionnumber
*/
public function i_edit_the_section($sectionnumber) {
// If javascript is on, link is inside a menu.
if ($this->running_javascript()) {
$this->i_open_section_edit_menu($sectionnumber);
}
// We need to know the course format as the text strings depends on them.
$courseformat = $this->get_course_format();
if ($sectionnumber > 0 && get_string_manager()->string_exists('editsection', $courseformat)) {
$stredit = get_string('editsection', $courseformat);
} else {
$stredit = get_string('editsection');
}
// Click on un-highlight topic link.
$this->execute('behat_general::i_click_on_in_the',
array($stredit, "link", "#section-" . $sectionnumber, "css_element")
);
}
/**
* Edit specified section and fill the form data with the specified field/value pairs.
*
* @When /^I edit the section "(?P<section_number>\d+)" and I fill the form with:$/
* @param int $sectionnumber The section number
* @param TableNode $data The activity field/value data
*/
public function i_edit_the_section_and_i_fill_the_form_with($sectionnumber, TableNode $data) {
// Edit given section.
$this->execute("behat_course::i_edit_the_section", $sectionnumber);
// Set form fields.
$this->execute("behat_forms::i_set_the_following_fields_to_these_values", $data);
// Save section settings.
$this->execute("behat_forms::press_button", get_string('savechanges'));
}
/**
* Checks if the specified course section hightlighting is turned on. You need to be in the course page on editing mode.
*
* @Then /^section "(?P<section_number>\d+)" should be highlighted$/
* @throws ExpectationException
* @param int $sectionnumber The section number
*/
public function section_should_be_highlighted($sectionnumber) {
// Ensures the section exists.
$xpath = $this->section_exists($sectionnumber);
// The important checking, we can not check the img.
$this->execute('behat_general::should_exist_in_the', ['Remove highlight', 'link', $xpath, 'xpath_element']);
}
/**
* Checks if the specified course section highlighting is turned off. You need to be in the course page on editing mode.
*
* @Then /^section "(?P<section_number>\d+)" should not be highlighted$/
* @throws ExpectationException
* @param int $sectionnumber The section number
*/
public function section_should_not_be_highlighted($sectionnumber) {
// We only catch ExpectationException, ElementNotFoundException should be thrown if the specified section does not exist.
try {
$this->section_should_be_highlighted($sectionnumber);
} catch (ExpectationException $e) {
// ExpectedException means that it is not highlighted.
return;
}
throw new ExpectationException('The "' . $sectionnumber . '" section is highlighted', $this->getSession());
}
/**
* Checks that the specified section is visible. You need to be in the course page. It can be used being logged as a student and as a teacher on editing mode.
*
* @Then /^section "(?P<section_number>\d+)" should be hidden$/
* @throws ExpectationException
* @throws ElementNotFoundException Thrown by behat_base::find
* @param int $sectionnumber
*/
public function section_should_be_hidden($sectionnumber) {
$sectionxpath = $this->section_exists($sectionnumber);
// Preventive in case there is any action in progress.
// Adding it here because we are interacting (click) with
// the elements, not necessary when we just find().
$this->i_wait_until_section_is_available($sectionnumber);
// Section should be hidden.
$exception = new ExpectationException('The section is not hidden', $this->getSession());
$this->find('xpath', $sectionxpath . "[contains(concat(' ', normalize-space(@class), ' '), ' hidden ')]", $exception);
}
/**
* Checks that all actiities in the specified section are hidden. You need to be in the course page. It can be used being logged as a student and as a teacher on editing mode.
*
* @Then /^all activities in section "(?P<section_number>\d+)" should be hidden$/
* @throws ExpectationException
* @throws ElementNotFoundException Thrown by behat_base::find
* @param int $sectionnumber
*/
public function section_activities_should_be_hidden($sectionnumber) {
$sectionxpath = $this->section_exists($sectionnumber);
// Preventive in case there is any action in progress.
// Adding it here because we are interacting (click) with
// the elements, not necessary when we just find().
$this->i_wait_until_section_is_available($sectionnumber);
// The checking are different depending on user permissions.
if ($this->is_course_editor()) {
// The section must be hidden.
$this->show_section_link_exists($sectionnumber);
// If there are activities they should be hidden and the visibility icon should not be available.
if ($activities = $this->get_section_activities($sectionxpath)) {
$dimmedexception = new ExpectationException('There are activities that are not dimmed', $this->getSession());
foreach ($activities as $activity) {
// Dimmed.
$this->find('xpath', "//div[contains(concat(' ', normalize-space(@class), ' '), ' activityinstance ')]" .
"//a[contains(concat(' ', normalize-space(@class), ' '), ' dimmed ')]", $dimmedexception, $activity);
}
}
} else {
// There shouldn't be activities.
if ($this->get_section_activities($sectionxpath)) {
throw new ExpectationException('There are activities in the section and they should be hidden', $this->getSession());
}
}
}
/**
* Checks that the specified section is visible. You need to be in the course page. It can be used being logged as a student and as a teacher on editing mode.
*
* @Then /^section "(?P<section_number>\d+)" should be visible$/
* @throws ExpectationException
* @param int $sectionnumber
*/
public function section_should_be_visible($sectionnumber) {
$sectionxpath = $this->section_exists($sectionnumber);
// Section should not be hidden.
$xpath = $sectionxpath . "[not(contains(concat(' ', normalize-space(@class), ' '), ' hidden '))]";
if (!$this->getSession()->getPage()->find('xpath', $xpath)) {
throw new ExpectationException('The section is hidden', $this->getSession());
}
// Edit menu should be visible.
if ($this->is_course_editor()) {
$xpath = $sectionxpath .
"/descendant::div[contains(@class, 'section-actions')]" .
"/descendant::a[contains(@data-toggle, 'dropdown')]";
if (!$this->getSession()->getPage()->find('xpath', $xpath)) {
throw new ExpectationException('The section edit menu is not available', $this->getSession());
}
}
}
/**
* Moves up the specified section, this step only works with Javascript disabled. Editing mode should be on.
*
* @Given /^I move up section "(?P<section_number>\d+)"$/
* @throws DriverException Step not available when Javascript is enabled
* @param int $sectionnumber
*/
public function i_move_up_section($sectionnumber) {
if ($this->running_javascript()) {
throw new DriverException('Move a section up step is not available with Javascript enabled');
}
// Ensures the section exists.
$sectionxpath = $this->section_exists($sectionnumber);
// If javascript is on, link is inside a menu.
if ($this->running_javascript()) {
$this->i_open_section_edit_menu($sectionnumber);
}
// Follows the link
$moveuplink = $this->get_node_in_container('link', get_string('moveup'), 'xpath_element', $sectionxpath);
$moveuplink->click();
}
/**
* Moves down the specified section, this step only works with Javascript disabled. Editing mode should be on.
*
* @Given /^I move down section "(?P<section_number>\d+)"$/
* @throws DriverException Step not available when Javascript is enabled
* @param int $sectionnumber
*/
public function i_move_down_section($sectionnumber) {
if ($this->running_javascript()) {
throw new DriverException('Move a section down step is not available with Javascript enabled');
}
// Ensures the section exists.
$sectionxpath = $this->section_exists($sectionnumber);
// If javascript is on, link is inside a menu.
if ($this->running_javascript()) {
$this->i_open_section_edit_menu($sectionnumber);
}
// Follows the link
$movedownlink = $this->get_node_in_container('link', get_string('movedown'), 'xpath_element', $sectionxpath);
$movedownlink->click();
}
/**
* Checks that the specified activity is visible. You need to be in the course page. It can be used being logged as a student and as a teacher on editing mode.
*
* @Then /^"(?P<activity_or_resource_string>(?:[^"]|\\")*)" activity should be visible$/
* @param string $activityname
* @throws ExpectationException
*/
public function activity_should_be_visible($activityname) {
// The activity must exists and be visible.
$activitynode = $this->get_activity_node($activityname);
if ($this->is_course_editor()) {
// The activity should not be dimmed.
try {
$xpath = "/descendant-or-self::a[contains(concat(' ', normalize-space(@class), ' '), ' dimmed ')] | ".
"/descendant-or-self::div[contains(concat(' ', normalize-space(@class), ' '), ' dimmed_text ')]";
$this->find('xpath', $xpath, false, $activitynode);
throw new ExpectationException('"' . $activityname . '" is hidden', $this->getSession());
} catch (ElementNotFoundException $e) {
// All ok.
}
// Additional check if this is a teacher in editing mode.
if ($this->is_editing_on()) {
// The 'Hide' button should be available.
$nohideexception = new ExpectationException('"' . $activityname . '" doesn\'t have a "' .
get_string('hide') . '" icon', $this->getSession());
$this->find('named_partial', array('link', get_string('hide')), $nohideexception, $activitynode);
}
}
}
/**
* Checks that the specified activity is visible. You need to be in the course page.
* It can be used being logged as a student and as a teacher on editing mode.
*
* @Then /^"(?P<activity_or_resource_string>(?:[^"]|\\")*)" activity should be available but hidden from course page$/
* @param string $activityname
* @throws ExpectationException
*/
public function activity_should_be_available_but_hidden_from_course_page($activityname) {
if ($this->is_course_editor()) {
// The activity must exists and be visible.
$activitynode = $this->get_activity_node($activityname);
// The activity should not be dimmed.
try {
$xpath = "/descendant-or-self::a[contains(concat(' ', normalize-space(@class), ' '), ' dimmed ')] | " .
"/descendant-or-self::div[contains(concat(' ', normalize-space(@class), ' '), ' dimmed_text ')]";
$this->find('xpath', $xpath, false, $activitynode);
throw new ExpectationException('"' . $activityname . '" is hidden', $this->getSession());
} catch (ElementNotFoundException $e) {
// All ok.
}
// Should has "stealth" class.
$exception = new ExpectationException('"' . $activityname . '" does not have CSS class "stealth"', $this->getSession());
$xpath = "/descendant-or-self::a[contains(concat(' ', normalize-space(@class), ' '), ' stealth ')]";
$this->find('xpath', $xpath, $exception, $activitynode);
// Additional check if this is a teacher in editing mode.
if ($this->is_editing_on()) {
// Also has either 'Hide' or 'Make unavailable' edit control.
$nohideexception = new ExpectationException('"' . $activityname . '" has neither "' . get_string('hide') .
'" nor "' . get_string('makeunavailable') . '" icons', $this->getSession());
try {
$this->find('named_partial', array('link', get_string('hide')), false, $activitynode);
} catch (ElementNotFoundException $e) {
$this->find('named_partial', array('link', get_string('makeunavailable')), $nohideexception, $activitynode);
}
}
} else {
// Student should not see the activity at all.
try {
$this->get_activity_node($activityname);
throw new ExpectationException('The "' . $activityname . '" should not appear', $this->getSession());
} catch (ElementNotFoundException $e) {
// This is good, the activity should not be there.
}
}
}
/**
* Checks that the specified activity is hidden. You need to be in the course page. It can be used being logged as a student and as a teacher on editing mode.
*
* @Then /^"(?P<activity_or_resource_string>(?:[^"]|\\")*)" activity should be hidden$/
* @param string $activityname
* @throws ExpectationException
*/
public function activity_should_be_hidden($activityname) {
if ($this->is_course_editor()) {
// The activity should exist.
$activitynode = $this->get_activity_node($activityname);
// Should be hidden.
$exception = new ExpectationException('"' . $activityname . '" is not dimmed', $this->getSession());
$xpath = "/descendant-or-self::a[contains(concat(' ', normalize-space(@class), ' '), ' dimmed ')] | ".
"/descendant-or-self::div[contains(concat(' ', normalize-space(@class), ' '), ' dimmed_text ')]";
$this->find('xpath', $xpath, $exception, $activitynode);
// Additional check if this is a teacher in editing mode.
if ($this->is_editing_on()) {
// Also has either 'Show' or 'Make available' edit control.
$noshowexception = new ExpectationException('"' . $activityname . '" has neither "' . get_string('show') .
'" nor "' . get_string('makeavailable') . '" icons', $this->getSession());
try {
$this->find('named_partial', array('link', get_string('show')), false, $activitynode);
} catch (ElementNotFoundException $e) {
$this->find('named_partial', array('link', get_string('makeavailable')), $noshowexception, $activitynode);
}
}
} else {
// It should not exist at all.
try {
$this->get_activity_node($activityname);
throw new ExpectationException('The "' . $activityname . '" should not appear', $this->getSession());
} catch (ElementNotFoundException $e) {
// This is good, the activity should not be there.
}
}
}
/**
* Checks that the specified activity is dimmed. You need to be in the course page.
*
* @Then /^"(?P<activity_or_resource_string>(?:[^"]|\\")*)" activity should be dimmed$/
* @param string $activityname
* @throws ExpectationException
*/
public function activity_should_be_dimmed($activityname) {
// The activity should exist.
$activitynode = $this->get_activity_node($activityname);
// Should be hidden.
$exception = new ExpectationException('"' . $activityname . '" is not dimmed', $this->getSession());
$xpath = "/descendant-or-self::a[contains(concat(' ', normalize-space(@class), ' '), ' dimmed ')] | ".
"/descendant-or-self::div[contains(concat(' ', normalize-space(@class), ' '), ' dimmed_text ')]";
$this->find('xpath', $xpath, $exception, $activitynode);
}
/**
* Moves the specified activity to the first slot of a section. This step is experimental when using it in Javascript tests. Editing mode should be on.
*
* @Given /^I move "(?P<activity_name_string>(?:[^"]|\\")*)" activity to section "(?P<section_number>\d+)"$/
* @param string $activityname The activity name
* @param int $sectionnumber The number of section
*/
public function i_move_activity_to_section($activityname, $sectionnumber) {
// Ensure the destination is valid.
$sectionxpath = $this->section_exists($sectionnumber);
// JS enabled.
if ($this->running_javascript()) {
$activitynode = $this->get_activity_element('Move', 'icon', $activityname);
$destinationxpath = $sectionxpath . "/descendant::ul[contains(concat(' ', normalize-space(@class), ' '), ' yui3-dd-drop ')]";
$this->execute("behat_general::i_drag_and_i_drop_it_in",
array($this->escape($activitynode->getXpath()), "xpath_element",
$this->escape($destinationxpath), "xpath_element")
);
} else {
// Following links with no-JS.
// Moving to the fist spot of the section (before all other section's activities).
$this->execute('behat_course::i_click_on_in_the_activity',
array("a.editing_move", "css_element", $this->escape($activityname))
);
$this->execute('behat_general::i_click_on_in_the',
array("li.movehere a", "css_element", $this->escape($sectionxpath), "xpath_element")
);
}
}
/**
* Edits the activity name through the edit activity; this step only works with Javascript enabled. Editing mode should be on.
*
* @Given /^I change "(?P<activity_name_string>(?:[^"]|\\")*)" activity name to "(?P<new_name_string>(?:[^"]|\\")*)"$/
* @throws DriverException Step not available when Javascript is disabled
* @param string $activityname
* @param string $newactivityname
*/
public function i_change_activity_name_to($activityname, $newactivityname) {
$this->execute('behat_forms::i_set_the_field_in_container_to', [
get_string('edittitle'),
$activityname,
'activity',
$newactivityname
]);
}
/**
* Opens an activity actions menu if it is not already opened.
*
* @Given /^I open "(?P<activity_name_string>(?:[^"]|\\")*)" actions menu$/
* @throws DriverException The step is not available when Javascript is disabled
* @param string $activityname
*/
public function i_open_actions_menu($activityname) {
if (!$this->running_javascript()) {
throw new DriverException('Activities actions menu not available when Javascript is disabled');
}
// If it is already opened we do nothing.
$activitynode = $this->get_activity_node($activityname);
// Find the menu.
$menunode = $activitynode->find('css', 'a[data-toggle=dropdown]');
if (!$menunode) {
throw new ExpectationException(sprintf('Could not find actions menu for the activity "%s"', $activityname),
$this->getSession());
}
$expanded = $menunode->getAttribute('aria-expanded');
if ($expanded == 'true') {
return;
}
$this->execute('behat_course::i_click_on_in_the_activity',
array("a[data-toggle='dropdown']", "css_element", $this->escape($activityname))
);
$this->actions_menu_should_be_open($activityname);
}
/**
* Closes an activity actions menu if it is not already closed.
*
* @Given /^I close "(?P<activity_name_string>(?:[^"]|\\")*)" actions menu$/
* @throws DriverException The step is not available when Javascript is disabled
* @param string $activityname
*/
public function i_close_actions_menu($activityname) {
if (!$this->running_javascript()) {
throw new DriverException('Activities actions menu not available when Javascript is disabled');
}
// If it is already closed we do nothing.
$activitynode = $this->get_activity_node($activityname);
// Find the menu.
$menunode = $activitynode->find('css', 'a[data-toggle=dropdown]');
if (!$menunode) {
throw new ExpectationException(sprintf('Could not find actions menu for the activity "%s"', $activityname),
$this->getSession());
}
$expanded = $menunode->getAttribute('aria-expanded');
if ($expanded != 'true') {
return;
}
$this->execute('behat_course::i_click_on_in_the_activity',
array("a[data-toggle='dropdown']", "css_element", $this->escape($activityname))
);
}
/**
* Checks that the specified activity's action menu is open.
*
* @Then /^"(?P<activity_name_string>(?:[^"]|\\")*)" actions menu should be open$/
* @throws DriverException The step is not available when Javascript is disabled
* @param string $activityname
*/
public function actions_menu_should_be_open($activityname) {
if (!$this->running_javascript()) {
throw new DriverException('Activities actions menu not available when Javascript is disabled');
}
$activitynode = $this->get_activity_node($activityname);
// Find the menu.
$menunode = $activitynode->find('css', 'a[data-toggle=dropdown]');
if (!$menunode) {
throw new ExpectationException(sprintf('Could not find actions menu for the activity "%s"', $activityname),
$this->getSession());
}
$expanded = $menunode->getAttribute('aria-expanded');
if ($expanded != 'true') {
throw new ExpectationException(sprintf("The action menu for '%s' is not open", $activityname), $this->getSession());
}
}
/**
* Checks that the specified activity's action menu contains an item.
*
* @Then /^"(?P<activity_name_string>(?:[^"]|\\")*)" actions menu should have "(?P<menu_item_string>(?:[^"]|\\")*)" item$/
* @throws DriverException The step is not available when Javascript is disabled
* @param string $activityname
* @param string $menuitem
*/
public function actions_menu_should_have_item($activityname, $menuitem) {
$activitynode = $this->get_activity_node($activityname);
$notfoundexception = new ExpectationException('"' . $activityname . '" doesn\'t have a "' .
$menuitem . '" item', $this->getSession());
$this->find('named_partial', array('link', $menuitem), $notfoundexception, $activitynode);
}
/**
* Checks that the specified activity's action menu does not contains an item.
*
* @Then /^"(?P<activity_name_string>(?:[^"]|\\")*)" actions menu should not have "(?P<menu_item_string>(?:[^"]|\\")*)" item$/
* @throws DriverException The step is not available when Javascript is disabled
* @param string $activityname
* @param string $menuitem
*/
public function actions_menu_should_not_have_item($activityname, $menuitem) {
$activitynode = $this->get_activity_node($activityname);
try {
$this->find('named_partial', array('link', $menuitem), false, $activitynode);
throw new ExpectationException('"' . $activityname . '" has a "' . $menuitem .
'" item when it should not', $this->getSession());
} catch (ElementNotFoundException $e) {
// This is good, the menu item should not be there.
}
}
/**
* Indents to the right the activity or resource specified by it's name. Editing mode should be on.
*
* @Given /^I indent right "(?P<activity_name_string>(?:[^"]|\\")*)" activity$/
* @param string $activityname
*/
public function i_indent_right_activity($activityname) {
$activity = $this->escape($activityname);
if ($this->running_javascript()) {
$this->i_open_actions_menu($activity);
}
$this->execute('behat_course::i_click_on_in_the_activity',
array(get_string('moveright'), "link", $this->escape($activity))
);
}
/**
* Indents to the left the activity or resource specified by it's name. Editing mode should be on.
*
* @Given /^I indent left "(?P<activity_name_string>(?:[^"]|\\")*)" activity$/
* @param string $activityname
*/
public function i_indent_left_activity($activityname) {
$activity = $this->escape($activityname);
if ($this->running_javascript()) {
$this->i_open_actions_menu($activity);
}
$this->execute('behat_course::i_click_on_in_the_activity',
array(get_string('moveleft'), "link", $this->escape($activity))
);
}
/**
* Deletes the activity or resource specified by it's name. This step is experimental when using it in Javascript tests. You should be in the course page with editing mode on.
*
* @Given /^I delete "(?P<activity_name_string>(?:[^"]|\\")*)" activity$/
* @param string $activityname
*/
public function i_delete_activity($activityname) {
$steps = array();
$activity = $this->escape($activityname);
if ($this->running_javascript()) {
$this->i_open_actions_menu($activity);
}
$this->execute('behat_course::i_click_on_in_the_activity',
array(get_string('delete'), "link", $this->escape($activity))
);
// JS enabled.
// Not using chain steps here because the exceptions catcher have problems detecting
// JS modal windows and avoiding interacting them at the same time.
if ($this->running_javascript()) {
$this->execute('behat_general::i_click_on_in_the',
array(get_string('yes'), "button", "Confirm", "dialogue")
);
} else {
$this->execute("behat_forms::press_button", get_string('yes'));
}
return $steps;
}
/**
* Duplicates the activity or resource specified by it's name. You should be in the course page with editing mode on.
*
* @Given /^I duplicate "(?P<activity_name_string>(?:[^"]|\\")*)" activity$/
* @param string $activityname
*/
public function i_duplicate_activity($activityname) {
$steps = array();
$activity = $this->escape($activityname);
if ($this->running_javascript()) {
$this->i_open_actions_menu($activity);
}
$this->execute('behat_course::i_click_on_in_the_activity',
array(get_string('duplicate'), "link", $activity)
);
}
/**
* Duplicates the activity or resource and modifies the new activity with the provided data. You should be in the course page with editing mode on.
*
* @Given /^I duplicate "(?P<activity_name_string>(?:[^"]|\\")*)" activity editing the new copy with:$/
* @param string $activityname
* @param TableNode $data
*/
public function i_duplicate_activity_editing_the_new_copy_with($activityname, TableNode $data) {
$activity = $this->escape($activityname);
$activityliteral = behat_context_helper::escape($activityname);
$this->execute("behat_course::i_duplicate_activity", $activity);
// Determine the future new activity xpath from the former one.
$duplicatedxpath = "//li[contains(concat(' ', normalize-space(@class), ' '), ' activity ')]" .
"[contains(., $activityliteral)]/following-sibling::li";
$duplicatedactionsmenuxpath = $duplicatedxpath . "/descendant::a[@data-toggle='dropdown']";
if ($this->running_javascript()) {
// We wait until the AJAX request finishes and the section is visible again.
$hiddenlightboxxpath = "//li[contains(concat(' ', normalize-space(@class), ' '), ' activity ')]" .
"[contains(., $activityliteral)]" .
"/ancestor::li[contains(concat(' ', normalize-space(@class), ' '), ' section ')]" .
"/descendant::div[contains(concat(' ', @class, ' '), ' lightbox ')][contains(@style, 'display: none')]";
$this->execute("behat_general::wait_until_exists",
array($this->escape($hiddenlightboxxpath), "xpath_element")
);
// Close the original activity actions menu.
$this->i_close_actions_menu($activity);
// The next sibling of the former activity will be the duplicated one, so we click on it from it's xpath as, at
// this point, it don't even exists in the DOM (the steps are executed when we return them).
$this->execute('behat_general::i_click_on',
array($this->escape($duplicatedactionsmenuxpath), "xpath_element")
);
}
// We force the xpath as otherwise mink tries to interact with the former one.
$this->execute('behat_general::i_click_on_in_the',
array(get_string('editsettings'), "link", $this->escape($duplicatedxpath), "xpath_element")
);
$this->execute("behat_forms::i_set_the_following_fields_to_these_values", $data);
$this->execute("behat_forms::press_button", get_string('savechangesandreturntocourse'));
}
/**
* Waits until the section is available to interact with it. Useful when the section is performing an action and the section is overlayed with a loading layout.
*
* Using the protected method as this method will be usually
* called by other methods which are not returning a set of
* steps and performs the actions directly, so it would not
* be executed if it returns another step.
*
* Hopefully we would not require test writers to use this step
* and we will manage it from other step definitions.
*
* @Given /^I wait until section "(?P<section_number>\d+)" is available$/
* @param int $sectionnumber
* @return void
*/
public function i_wait_until_section_is_available($sectionnumber) {
// Looks for a hidden lightbox or a non-existent lightbox in that section.
$sectionxpath = $this->section_exists($sectionnumber);
$hiddenlightboxxpath = $sectionxpath . "/descendant::div[contains(concat(' ', @class, ' '), ' lightbox ')][contains(@style, 'display: none')]" .
" | " .
$sectionxpath . "[count(child::div[contains(@class, 'lightbox')]) = 0]";
$this->ensure_element_exists($hiddenlightboxxpath, 'xpath_element');
}
/**
* Clicks on the specified element of the activity. You should be in the course page with editing mode turned on.
*
* @Given /^I click on "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>(?:[^"]|\\")*)" in the "(?P<activity_name_string>(?:[^"]|\\")*)" activity$/
* @param string $element
* @param string $selectortype
* @param string $activityname
*/
public function i_click_on_in_the_activity($element, $selectortype, $activityname) {
$element = $this->get_activity_element($element, $selectortype, $activityname);
$element->click();
}
/**
* Clicks on the specified element inside the activity container.
*
* @throws ElementNotFoundException
* @param string $element
* @param string $selectortype
* @param string $activityname
* @return NodeElement
*/
protected function get_activity_element($element, $selectortype, $activityname) {
$activitynode = $this->get_activity_node($activityname);
$exception = new ElementNotFoundException($this->getSession(), "'{$element}' '{$selectortype}' in '${activityname}'");
return $this->find($selectortype, $element, $exception, $activitynode);
}
/**
* Checks if the course section exists.
*
* @throws ElementNotFoundException Thrown by behat_base::find
* @param int $sectionnumber
* @return string The xpath of the section.
*/
protected function section_exists($sectionnumber) {
// Just to give more info in case it does not exist.
$xpath = "//li[@id='section-" . $sectionnumber . "']";
$exception = new ElementNotFoundException($this->getSession(), "Section $sectionnumber ");
$this->find('xpath', $xpath, $exception);
return $xpath;
}
/**
* Returns the show section icon or throws an exception.
*
* @throws ElementNotFoundException Thrown by behat_base::find
* @param int $sectionnumber
* @return NodeElement
*/
protected function show_section_link_exists($sectionnumber) {
// Gets the section xpath and ensure it exists.
$xpath = $this->section_exists($sectionnumber);
// We need to know the course format as the text strings depends on them.
$courseformat = $this->get_course_format();
// Checking the show button alt text and show icon.
$showtext = get_string('showfromothers', $courseformat);
$linkxpath = $xpath . "//a[*[contains(text(), " . behat_context_helper::escape($showtext) . ")]]";
$exception = new ElementNotFoundException($this->getSession(), 'Show section link');
// Returing the link so both Non-JS and JS browsers can interact with it.
return $this->find('xpath', $linkxpath, $exception);
}
/**
* Returns the hide section icon link if it exists or throws exception.
*
* @throws ElementNotFoundException Thrown by behat_base::find
* @param int $sectionnumber
* @return NodeElement
*/
protected function hide_section_link_exists($sectionnumber) {
// Gets the section xpath and ensure it exists.
$xpath = $this->section_exists($sectionnumber);
// We need to know the course format as the text strings depends on them.
$courseformat = $this->get_course_format();
// Checking the hide button alt text and hide icon.
$hidetext = behat_context_helper::escape(get_string('hidefromothers', $courseformat));
$linkxpath = $xpath . "/descendant::a[@title=$hidetext]";
$exception = new ElementNotFoundException($this->getSession(), 'Hide section icon ');
$this->find('icon', 'Hide', $exception);
// Returing the link so both Non-JS and JS browsers can interact with it.
return $this->find('xpath', $linkxpath, $exception);
}
/**
* Gets the current course format.
*
* @throws ExpectationException If we are not in the course view page.
* @return string The course format in a frankenstyled name.
*/
protected function get_course_format() {
$exception = new ExpectationException('You are not in a course page', $this->getSession());
// The moodle body's id attribute contains the course format.
$node = $this->getSession()->getPage()->find('css', 'body');
if (!$node) {
throw $exception;
}
if (!$bodyid = $node->getAttribute('id')) {
throw $exception;
}
if (strstr($bodyid, 'page-course-view-') === false) {
throw $exception;
}
return 'format_' . str_replace('page-course-view-', '', $bodyid);
}
/**
* Gets the section's activites DOM nodes.
*
* @param string $sectionxpath
* @return array NodeElement instances
*/
protected function get_section_activities($sectionxpath) {
$xpath = $sectionxpath . "/descendant::li[contains(concat(' ', normalize-space(@class), ' '), ' activity ')]";
// We spin here, as activities usually require a lot of time to load.
try {
$activities = $this->find_all('xpath', $xpath);
} catch (ElementNotFoundException $e) {
return false;
}
return $activities;
}
/**
* Returns the DOM node of the activity from <li>.
*
* @throws ElementNotFoundException Thrown by behat_base::find
* @param string $activityname The activity name
* @return NodeElement
*/
protected function get_activity_node($activityname) {
$activityname = behat_context_helper::escape($activityname);
$xpath = "//li[contains(concat(' ', normalize-space(@class), ' '), ' activity ')][contains(., $activityname)]";
return $this->find('xpath', $xpath);
}
/**
* Gets the activity instance name from the activity node.
*
* @throws ElementNotFoundException
* @param NodeElement $activitynode
* @return string
*/
protected function get_activity_name($activitynode) {
$instancenamenode = $this->find('xpath', "//span[contains(concat(' ', normalize-space(@class), ' '), ' instancename ')]", false, $activitynode);
return $instancenamenode->getText();
}
/**
* Returns whether the user can edit the course contents or not.
*
* @return bool
*/
protected function is_course_editor() {
// We don't need to behat_base::spin() here as all is already loaded.
if (!$this->getSession()->getPage()->findButton(get_string('turneditingoff')) &&
!$this->getSession()->getPage()->findButton(get_string('turneditingon'))) {
return false;
}
return true;
}
/**
* Returns whether the user can edit the course contents and the editing mode is on.
*
* @return bool
*/
protected function is_editing_on() {
return $this->getSession()->getPage()->findButton(get_string('turneditingoff')) ? true : false;
}
/**
* Returns the category node from within the listing on the management page.
*
* @param string $idnumber
* @return \Behat\Mink\Element\NodeElement
*/
protected function get_management_category_listing_node_by_idnumber($idnumber) {
$id = $this->get_category_id($idnumber);
$selector = sprintf('#category-listing .listitem-category[data-id="%d"] > div', $id);
return $this->find('css', $selector);
}
/**
* Returns a category node from within the management interface.
*
* @param string $name The name of the category.
* @param bool $link If set to true we'll resolve to the link rather than just the node.
* @return \Behat\Mink\Element\NodeElement
*/
protected function get_management_category_listing_node_by_name($name, $link = false) {
$selector = "//div[@id='category-listing']//li[contains(concat(' ', normalize-space(@class), ' '), ' listitem-category ')]//a[text()='{$name}']";
if ($link === false) {
$selector .= "/ancestor::li[@data-id][1]";
}
return $this->find('xpath', $selector);
}
/**
* Returns a course node from within the management interface.
*
* @param string $name The name of the course.
* @param bool $link If set to true we'll resolve to the link rather than just the node.
* @return \Behat\Mink\Element\NodeElement
*/
protected function get_management_course_listing_node_by_name($name, $link = false) {
$selector = "//div[@id='course-listing']//li[contains(concat(' ', @class, ' '), ' listitem-course ')]//a[text()='{$name}']";
if ($link === false) {
$selector .= "/ancestor::li[@data-id]";
}
return $this->find('xpath', $selector);
}
/**
* Returns the course node from within the listing on the management page.
*
* @param string $idnumber
* @return \Behat\Mink\Element\NodeElement
*/
protected function get_management_course_listing_node_by_idnumber($idnumber) {
$id = $this->get_course_id($idnumber);
$selector = sprintf('#course-listing .listitem-course[data-id="%d"] > div', $id);
return $this->find('css', $selector);
}
/**
* Clicks on a category in the management interface.
*
* @Given /^I click on category "(?P<name_string>(?:[^"]|\\")*)" in the management interface$/
* @param string $name
*/
public function i_click_on_category_in_the_management_interface($name) {
$node = $this->get_management_category_listing_node_by_name($name, true);
$node->click();
}
/**
* Clicks on a course in the management interface.
*
* @Given /^I click on course "(?P<name_string>(?:[^"]|\\")*)" in the management interface$/
* @param string $name
*/
public function i_click_on_course_in_the_management_interface($name) {
$node = $this->get_management_course_listing_node_by_name($name, true);
$node->click();
}
/**
* Clicks on a category checkbox in the management interface, if not checked.
*
* @Given /^I select category "(?P<name_string>(?:[^"]|\\")*)" in the management interface$/
* @param string $name
*/
public function i_select_category_in_the_management_interface($name) {
$node = $this->get_management_category_listing_node_by_name($name);
$node = $node->findField('bcat[]');
if (!$node->isChecked()) {
$node->click();
}
}
/**
* Clicks on a category checkbox in the management interface, if checked.
*
* @Given /^I unselect category "(?P<name_string>(?:[^"]|\\")*)" in the management interface$/
* @param string $name
*/
public function i_unselect_category_in_the_management_interface($name) {
$node = $this->get_management_category_listing_node_by_name($name);
$node = $node->findField('bcat[]');
if ($node->isChecked()) {
$node->click();
}
}
/**
* Clicks course checkbox in the management interface, if not checked.
*
* @Given /^I select course "(?P<name_string>(?:[^"]|\\")*)" in the management interface$/
* @param string $name
*/
public function i_select_course_in_the_management_interface($name) {
$node = $this->get_management_course_listing_node_by_name($name);
$node = $node->findField('bc[]');
if (!$node->isChecked()) {
$node->click();
}
}
/**
* Clicks course checkbox in the management interface, if checked.
*
* @Given /^I unselect course "(?P<name_string>(?:[^"]|\\")*)" in the management interface$/
* @param string $name
*/
public function i_unselect_course_in_the_management_interface($name) {
$node = $this->get_management_course_listing_node_by_name($name);
$node = $node->findField('bc[]');
if ($node->isChecked()) {
$node->click();
}
}
/**
* Move selected categories to top level in the management interface.
*
* @Given /^I move category "(?P<name_string>(?:[^"]|\\")*)" to top level in the management interface$/
* @param string $name
*/
public function i_move_category_to_top_level_in_the_management_interface($name) {
$this->i_select_category_in_the_management_interface($name);
$this->execute('behat_forms::i_set_the_field_to',
array('menumovecategoriesto', core_course_category::get(0)->get_formatted_name())
);
// Save event.
$this->execute("behat_forms::press_button", "bulkmovecategories");
}
/**
* Checks that a category is a subcategory of specific category.
*
* @Given /^I should see category "(?P<subcatidnumber_string>(?:[^"]|\\")*)" as subcategory of "(?P<catidnumber_string>(?:[^"]|\\")*)" in the management interface$/
* @throws ExpectationException
* @param string $subcatidnumber
* @param string $catidnumber
*/
public function i_should_see_category_as_subcategory_of_in_the_management_interface($subcatidnumber, $catidnumber) {
$categorynodeid = $this->get_category_id($catidnumber);
$subcategoryid = $this->get_category_id($subcatidnumber);
$exception = new ExpectationException('The category '.$subcatidnumber.' is not a subcategory of '.$catidnumber, $this->getSession());
$selector = sprintf('#category-listing .listitem-category[data-id="%d"] .listitem-category[data-id="%d"]', $categorynodeid, $subcategoryid);
$this->find('css', $selector, $exception);
}
/**
* Checks that a category is not a subcategory of specific category.
*
* @Given /^I should not see category "(?P<subcatidnumber_string>(?:[^"]|\\")*)" as subcategory of "(?P<catidnumber_string>(?:[^"]|\\")*)" in the management interface$/
* @throws ExpectationException
* @param string $subcatidnumber
* @param string $catidnumber
*/
public function i_should_not_see_category_as_subcategory_of_in_the_management_interface($subcatidnumber, $catidnumber) {
try {
$this->i_should_see_category_as_subcategory_of_in_the_management_interface($subcatidnumber, $catidnumber);
} catch (ExpectationException $e) {
// ExpectedException means that it is not highlighted.
return;
}
throw new ExpectationException('The category '.$subcatidnumber.' is a subcategory of '.$catidnumber, $this->getSession());
}
/**
* Click to expand a category revealing its sub categories within the management UI.
*
* @Given /^I click to expand category "(?P<idnumber_string>(?:[^"]|\\")*)" in the management interface$/
* @param string $idnumber
*/
public function i_click_to_expand_category_in_the_management_interface($idnumber) {
$categorynode = $this->get_management_category_listing_node_by_idnumber($idnumber);
$exception = new ExpectationException('Category "' . $idnumber . '" does not contain an expand or collapse toggle.', $this->getSession());
$togglenode = $this->find('css', 'a[data-action=collapse],a[data-action=expand]', $exception, $categorynode);
$togglenode->click();
}
/**
* Checks that a category within the management interface is visible.
*
* @Given /^category in management listing should be visible "(?P<idnumber_string>(?:[^"]|\\")*)"$/
* @param string $idnumber
*/
public function category_in_management_listing_should_be_visible($idnumber) {
$id = $this->get_category_id($idnumber);
$exception = new ExpectationException('The category '.$idnumber.' is not visible.', $this->getSession());
$selector = sprintf('#category-listing .listitem-category[data-id="%d"][data-visible="1"]', $id);
$this->find('css', $selector, $exception);
}
/**
* Checks that a category within the management interface is dimmed.
*
* @Given /^category in management listing should be dimmed "(?P<idnumber_string>(?:[^"]|\\")*)"$/
* @param string $idnumber
*/
public function category_in_management_listing_should_be_dimmed($idnumber) {
$id = $this->get_category_id($idnumber);
$selector = sprintf('#category-listing .listitem-category[data-id="%d"][data-visible="0"]', $id);
$exception = new ExpectationException('The category '.$idnumber.' is visible.', $this->getSession());
$this->find('css', $selector, $exception);
}
/**
* Checks that a course within the management interface is visible.
*
* @Given /^course in management listing should be visible "(?P<idnumber_string>(?:[^"]|\\")*)"$/
* @param string $idnumber
*/
public function course_in_management_listing_should_be_visible($idnumber) {
$id = $this->get_course_id($idnumber);
$exception = new ExpectationException('The course '.$idnumber.' is not visible.', $this->getSession());
$selector = sprintf('#course-listing .listitem-course[data-id="%d"][data-visible="1"]', $id);
$this->find('css', $selector, $exception);
}
/**
* Checks that a course within the management interface is dimmed.
*
* @Given /^course in management listing should be dimmed "(?P<idnumber_string>(?:[^"]|\\")*)"$/
* @param string $idnumber
*/
public function course_in_management_listing_should_be_dimmed($idnumber) {
$id = $this->get_course_id($idnumber);
$exception = new ExpectationException('The course '.$idnumber.' is visible.', $this->getSession());
$selector = sprintf('#course-listing .listitem-course[data-id="%d"][data-visible="0"]', $id);
$this->find('css', $selector, $exception);
}
/**
* Toggles the visibility of a course in the management UI.
*
* If it was visible it will be hidden. If it is hidden it will be made visible.
*
* @Given /^I toggle visibility of course "(?P<idnumber_string>(?:[^"]|\\")*)" in management listing$/
* @param string $idnumber
*/
public function i_toggle_visibility_of_course_in_management_listing($idnumber) {
$id = $this->get_course_id($idnumber);
$selector = sprintf('#course-listing .listitem-course[data-id="%d"][data-visible]', $id);
$node = $this->find('css', $selector);
$exception = new ExpectationException('Course listing "' . $idnumber . '" does not contain a show or hide toggle.', $this->getSession());
if ($node->getAttribute('data-visible') === '1') {
$toggle = $this->find('css', '.action-hide', $exception, $node);
} else {
$toggle = $this->find('css', '.action-show', $exception, $node);
}
$toggle->click();
}
/**
* Toggles the visibility of a category in the management UI.
*
* If it was visible it will be hidden. If it is hidden it will be made visible.
*
* @Given /^I toggle visibility of category "(?P<idnumber_string>(?:[^"]|\\")*)" in management listing$/
*/
public function i_toggle_visibility_of_category_in_management_listing($idnumber) {
$id = $this->get_category_id($idnumber);
$selector = sprintf('#category-listing .listitem-category[data-id="%d"][data-visible]', $id);
$node = $this->find('css', $selector);
$exception = new ExpectationException('Category listing "' . $idnumber . '" does not contain a show or hide toggle.', $this->getSession());
if ($node->getAttribute('data-visible') === '1') {
$toggle = $this->find('css', '.action-hide', $exception, $node);
} else {
$toggle = $this->find('css', '.action-show', $exception, $node);
}
$toggle->click();
}
/**
* Moves a category displayed in the management interface up or down one place.
*
* @Given /^I click to move category "(?P<idnumber_string>(?:[^"]|\\")*)" (?P<direction>up|down) one$/
*
* @param string $idnumber The category idnumber
* @param string $direction The direction to move in, either up or down
*/
public function i_click_to_move_category_by_one($idnumber, $direction) {
$node = $this->get_management_category_listing_node_by_idnumber($idnumber);
$this->user_moves_listing_by_one('category', $node, $direction);
}
/**
* Moves a course displayed in the management interface up or down one place.
*
* @Given /^I click to move course "(?P<idnumber_string>(?:[^"]|\\")*)" (?P<direction>up|down) one$/
*
* @param string $idnumber The course idnumber
* @param string $direction The direction to move in, either up or down
*/
public function i_click_to_move_course_by_one($idnumber, $direction) {
$node = $this->get_management_course_listing_node_by_idnumber($idnumber);
$this->user_moves_listing_by_one('course', $node, $direction);
}
/**
* Moves a course or category listing within the management interface up or down by one.
*
* @param string $listingtype One of course or category
* @param \Behat\Mink\Element\NodeElement $listingnode
* @param string $direction One of up or down.
* @param bool $highlight If set to false we don't check the node has been highlighted.
*/
protected function user_moves_listing_by_one($listingtype, $listingnode, $direction, $highlight = true) {
$up = (strtolower($direction) === 'up');
if ($up) {
$exception = new ExpectationException($listingtype.' listing does not contain a moveup button.', $this->getSession());
$button = $this->find('css', 'a.action-moveup', $exception, $listingnode);
} else {
$exception = new ExpectationException($listingtype.' listing does not contain a movedown button.', $this->getSession());
$button = $this->find('css', 'a.action-movedown', $exception, $listingnode);
}
$button->click();
if ($this->running_javascript() && $highlight) {
$listitem = $listingnode->getParent();
$exception = new ExpectationException('Nothing was highlighted, ajax didn\'t occur or didn\'t succeed.', $this->getSession());
$this->spin(array($this, 'listing_is_highlighted'), $listitem->getTagName().'#'.$listitem->getAttribute('id'), 2, $exception, true);
}
}
/**
* Used by spin to determine the callback has been highlighted.
*
* @param behat_course $self A self reference (default first arg from a spin callback)
* @param \Behat\Mink\Element\NodeElement $selector
* @return bool
*/
protected function listing_is_highlighted($self, $selector) {
$listitem = $this->find('css', $selector);
return $listitem->hasClass('highlight');
}
/**
* Check that one course appears before another in the course category management listings.
*
* @Given /^I should see course listing "(?P<preceedingcourse_string>(?:[^"]|\\")*)" before "(?P<followingcourse_string>(?:[^"]|\\")*)"$/
*
* @param string $preceedingcourse The first course to find
* @param string $followingcourse The second course to find (should be AFTER the first course)
* @throws ExpectationException
*/
public function i_should_see_course_listing_before($preceedingcourse, $followingcourse) {
$xpath = "//div[@id='course-listing']//li[contains(concat(' ', @class, ' '), ' listitem-course ')]//a[text()='{$preceedingcourse}']/ancestor::li[@data-id]//following::a[text()='{$followingcourse}']";
$msg = "{$preceedingcourse} course does not appear before {$followingcourse} course";
if (!$this->getSession()->getDriver()->find($xpath)) {
throw new ExpectationException($msg, $this->getSession());
}
}
/**
* Check that one category appears before another in the course category management listings.
*
* @Given /^I should see category listing "(?P<preceedingcategory_string>(?:[^"]|\\")*)" before "(?P<followingcategory_string>(?:[^"]|\\")*)"$/
*
* @param string $preceedingcategory The first category to find
* @param string $followingcategory The second category to find (should be after the first category)
* @throws ExpectationException
*/
public function i_should_see_category_listing_before($preceedingcategory, $followingcategory) {
$xpath = "//div[@id='category-listing']//li[contains(concat(' ', @class, ' '), ' listitem-category ')]//a[text()='{$preceedingcategory}']/ancestor::li[@data-id]//following::a[text()='{$followingcategory}']";
$msg = "{$preceedingcategory} category does not appear before {$followingcategory} category";
if (!$this->getSession()->getDriver()->find($xpath)) {
throw new ExpectationException($msg, $this->getSession());
}
}
/**
* Checks that we are on the course management page that we expect to be on and that no course has been selected.
*
* @Given /^I should see the "(?P<mode_string>(?:[^"]|\\")*)" management page$/
* @param string $mode The mode to expected. One of 'Courses', 'Course categories' or 'Course categories and courses'
*/
public function i_should_see_the_courses_management_page($mode) {
$this->execute("behat_general::assert_element_contains_text",
array("Course and category management", "h2", "css_element")
);
switch ($mode) {
case "Courses":
$this->execute("behat_general::should_not_exist", array("#category-listing", "css_element"));
$this->execute("behat_general::should_exist", array("#course-listing", "css_element"));
break;
case "Course categories":
$this->execute("behat_general::should_exist", array("#category-listing", "css_element"));
$this->execute("behat_general::should_exist", array("#course-listing", "css_element"));
break;
case "Courses categories and courses":
default:
$this->execute("behat_general::should_exist", array("#category-listing", "css_element"));
$this->execute("behat_general::should_exist", array("#course-listing", "css_element"));
break;
}
$this->execute("behat_general::should_not_exist", array("#course-detail", "css_element"));
}
/**
* Checks that we are on the course management page that we expect to be on and that a course has been selected.
*
* @Given /^I should see the "(?P<mode_string>(?:[^"]|\\")*)" management page with a course selected$/
* @param string $mode The mode to expected. One of 'Courses', 'Course categories' or 'Course categories and courses'
*/
public function i_should_see_the_courses_management_page_with_a_course_selected($mode) {
$this->execute("behat_general::assert_element_contains_text",
array("Course and category management", "h2", "css_element"));
switch ($mode) {
case "Courses":
$this->execute("behat_general::should_not_exist", array("#category-listing", "css_element"));
$this->execute("behat_general::should_exist", array("#course-listing", "css_element"));
break;
case "Course categories":
$this->execute("behat_general::should_exist", array("#category-listing", "css_element"));
$this->execute("behat_general::should_exist", array("#course-listing", "css_element"));
break;
case "Courses categories and courses":
default:
$this->execute("behat_general::should_exist", array("#category-listing", "css_element"));
$this->execute("behat_general::should_exist", array("#course-listing", "css_element"));
break;
}
$this->execute("behat_general::should_exist", array("#course-detail", "css_element"));
}
/**
* Locates a course in the course category management interface and then triggers an action for it.
*
* @Given /^I click on "(?P<action_string>(?:[^"]|\\")*)" action for "(?P<name_string>(?:[^"]|\\")*)" in management course listing$/
*
* @param string $action The action to take. One of
* @param string $name The name of the course as it is displayed in the management interface.
*/
public function i_click_on_action_for_item_in_management_course_listing($action, $name) {
$node = $this->get_management_course_listing_node_by_name($name);
$this->user_clicks_on_management_listing_action('course', $node, $action);
}
/**
* Locates a category in the course category management interface and then triggers an action for it.
*
* @Given /^I click on "(?P<action_string>(?:[^"]|\\")*)" action for "(?P<name_string>(?:[^"]|\\")*)" in management category listing$/
*
* @param string $action The action to take. One of
* @param string $name The name of the category as it is displayed in the management interface.
*/
public function i_click_on_action_for_item_in_management_category_listing($action, $name) {
$node = $this->get_management_category_listing_node_by_name($name);
$this->user_clicks_on_management_listing_action('category', $node, $action);
}
/**
* Clicks to expand or collapse a category displayed on the frontpage
*
* @Given /^I toggle "(?P<categoryname_string>(?:[^"]|\\")*)" category children visibility in frontpage$/
* @throws ExpectationException
* @param string $categoryname
*/
public function i_toggle_category_children_visibility_in_frontpage($categoryname) {
$headingtags = array();
for ($i = 1; $i <= 6; $i++) {
$headingtags[] = 'self::h' . $i;
}
$exception = new ExpectationException('"' . $categoryname . '" category can not be found', $this->getSession());
$categoryliteral = behat_context_helper::escape($categoryname);
$xpath = "//div[@class='info']/descendant::*[" . implode(' or ', $headingtags) .
"][contains(@class,'categoryname')][./descendant::a[.=$categoryliteral]]";
$node = $this->find('xpath', $xpath, $exception);
$node->click();
// Smooth expansion.
$this->getSession()->wait(1000);
}
/**
* Finds the node to use for a management listitem action and clicks it.
*
* @param string $listingtype Either course or category.
* @param \Behat\Mink\Element\NodeElement $listingnode
* @param string $action The action being taken
* @throws Behat\Mink\Exception\ExpectationException
*/
protected function user_clicks_on_management_listing_action($listingtype, $listingnode, $action) {
$actionsnode = $listingnode->find('xpath', "//*" .
"[contains(concat(' ', normalize-space(@class), ' '), '{$listingtype}-item-actions')]");
if (!$actionsnode) {
throw new ExpectationException("Could not find the actions for $listingtype", $this->getSession());
}
$actionnode = $actionsnode->find('css', '.action-'.$action);
if (!$actionnode) {
throw new ExpectationException("Expected action was not available or not found ($action)", $this->getSession());
}
if ($this->running_javascript() && !$actionnode->isVisible()) {
$actionsnode->find('css', 'a[data-toggle=dropdown]')->click();
$actionnode = $actionsnode->find('css', '.action-'.$action);
}
$actionnode->click();
}
/**
* Clicks on a category in the management interface.
*
* @Given /^I click on "(?P<categoryname_string>(?:[^"]|\\")*)" category in the management category listing$/
* @param string $name The name of the category to click.
*/
public function i_click_on_category_in_the_management_category_listing($name) {
$node = $this->get_management_category_listing_node_by_name($name);
$node->find('css', 'a.categoryname')->click();
}
/**
* Locates a category in the course category management interface and then opens action menu for it.
*
* @Given /^I open the action menu for "(?P<name_string>(?:[^"]|\\")*)" in management category listing$/
*
* @param string $name The name of the category as it is displayed in the management interface.
*/
public function i_open_the_action_menu_for_item_in_management_category_listing($name) {
$node = $this->get_management_category_listing_node_by_name($name);
$node->find('xpath', "//*[contains(@class, 'category-item-actions')]//a[@data-toggle='dropdown']")->click();
}
/**
* Checks that the specified category actions menu contains an item.
*
* @Then /^"(?P<name_string>(?:[^"]|\\")*)" category actions menu should have "(?P<menu_item_string>(?:[^"]|\\")*)" item$/
*
* @param string $name
* @param string $menuitem
* @throws Behat\Mink\Exception\ExpectationException
*/
public function category_actions_menu_should_have_item($name, $menuitem) {
$node = $this->get_management_category_listing_node_by_name($name);
$notfoundexception = new ExpectationException('"' . $name . '" doesn\'t have a "' .
$menuitem . '" item', $this->getSession());
$this->find('named_partial', ['link', $menuitem], $notfoundexception, $node);
}
/**
* Checks that the specified category actions menu does not contain an item.
*
* @Then /^"(?P<name_string>(?:[^"]|\\")*)" category actions menu should not have "(?P<menu_item_string>(?:[^"]|\\")*)" item$/
*
* @param string $name
* @param string $menuitem
* @throws Behat\Mink\Exception\ExpectationException
*/
public function category_actions_menu_should_not_have_item($name, $menuitem) {
$node = $this->get_management_category_listing_node_by_name($name);
try {
$this->find('named_partial', ['link', $menuitem], false, $node);
throw new ExpectationException('"' . $name . '" has a "' . $menuitem .
'" item when it should not', $this->getSession());
} catch (ElementNotFoundException $e) {
// This is good, the menu item should not be there.
}
}
/**
* Go to the course participants
*
* @Given /^I navigate to course participants$/
*/
public function i_navigate_to_course_participants() {
$this->execute('behat_navigation::i_select_from_flat_navigation_drawer', get_string('participants'));
}
/**
* Check that one teacher appears before another in the course contacts.
*
* @Given /^I should see teacher "(?P<pteacher_string>(?:[^"]|\\")*)" before "(?P<fteacher_string>(?:[^"]|\\")*)" in the course contact listing$/
*
* @param string $pteacher The first teacher to find
* @param string $fteacher The second teacher to find (should be after the first teacher)
*
* @throws ExpectationException
*/
public function i_should_see_teacher_before($pteacher, $fteacher) {
$xpath = "//ul[contains(@class,'teachers')]//li//a[text()='{$pteacher}']/ancestor::li//following::a[text()='{$fteacher}']";
$msg = "Teacher {$pteacher} does not appear before Teacher {$fteacher}";
if (!$this->getSession()->getDriver()->find($xpath)) {
throw new ExpectationException($msg, $this->getSession());
}
}
/**
* Check that one teacher oes not appears after another in the course contacts.
*
* @Given /^I should not see teacher "(?P<fteacher_string>(?:[^"]|\\")*)" after "(?P<pteacher_string>(?:[^"]|\\")*)" in the course contact listing$/
*
* @param string $fteacher The teacher that should not be found (after the other teacher)
* @param string $pteacher The teacher after who the other should not be found (this teacher must be found!)
*
* @throws ExpectationException
*/
public function i_should_not_see_teacher_after($fteacher, $pteacher) {
$xpathliteral = behat_context_helper::escape($pteacher);
$xpath = "/descendant-or-self::*[contains(., $xpathliteral)]" .
"[count(descendant::*[contains(., $xpathliteral)]) = 0]";
try {
$nodes = $this->find_all('xpath', $xpath);
} catch (ElementNotFoundException $e) {
throw new ExpectationException('"' . $pteacher . '" text was not found in the page', $this->getSession());
}
$xpath = "//ul[contains(@class,'teachers')]//li//a[text()='{$pteacher}']/ancestor::li//following::a[text()='{$fteacher}']";
$msg = "Teacher {$fteacher} appears after Teacher {$pteacher}";
if ($this->getSession()->getDriver()->find($xpath)) {
throw new ExpectationException($msg, $this->getSession());
}
}
/**
* Open the activity chooser in a course.
*
* @Given /^I open the activity chooser$/
*/
public function i_open_the_activity_chooser() {
$this->execute('behat_general::i_click_on',
array('//button[@data-action="open-chooser"]', 'xpath_element'));
$node = $this->get_selected_node('xpath_element', '//div[@data-region="modules"]');
$this->ensure_node_is_visible($node);
}
}
| gpl-3.0 |
Excommunicated/Hangfire | src/Hangfire.Core/Obsolete/IBootstrapperConfiguration.cs | 4189 | ๏ปฟ// This file is part of Hangfire.
// Copyright ยฉ 2013-2014 Sergey Odinokov.
//
// Hangfire is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3
// of the License, or any later version.
//
// Hangfire is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with Hangfire. If not, see <http://www.gnu.org/licenses/>.
using System;
using Hangfire.Dashboard;
namespace Hangfire
{
/// <exclude />
/// <summary>
/// Represents a configuration class for Hangfire components that
/// is used by the <see cref="OwinBootstrapper"/> class.
/// </summary>
[Obsolete("Please use `GlobalConfiguration` class instead. Will be removed in version 2.0.0.")]
public interface IBootstrapperConfiguration
{
/// <summary>
/// Tells bootstrapper to pass the given collection of filters
/// to the dashboard middleware to authorize dashboard requests.
/// Previous calls to this method are ignored. Empty array
/// enables access for all users.
/// </summary>
/// <param name="filters">Authorization filters</param>
[Obsolete("Please use `IAppBuilder.UseHangfireDashboard(\"/hangfire\", new DashboardOptions { AuthorizationFilters = filters })` OWIN extension method instead. Will be removed in version 2.0.0.")]
void UseAuthorizationFilters(params IAuthorizationFilter[] filters);
/// <summary>
/// Tells bootstrapper to register the given job filter globally.
/// </summary>
/// <param name="filter">Job filter instance</param>
[Obsolete("Please use `GlobalConfiguration.UseFilter` instead. Will be removed in version 2.0.0.")]
void UseFilter(object filter);
/// <summary>
/// Tells bootstrapper to map the dashboard middleware to the
/// given path in the OWIN pipeline.
/// </summary>
/// <param name="path">Dashboard path, '/hangfire' by default</param>
[Obsolete("Please use `IAppBuilder.UseHangfireDashboard(string pathMatch)` OWIN extension method instead. Will be removed in version 2.0.0.")]
void UseDashboardPath(string path);
/// <summary>
/// Tells bootstrapper to use the given path on Back To Site link in the dashboard.
/// </summary>
/// <param name="path">Back To Site path, '/' by default</param>
[Obsolete("Please use `IAppBuilder.UseHangfireDashboard(\"/hangfire\", new DashboardOptions { AppPath = path })` OWIN extension method instead. Will be removed in version 2.0.0.")]
void UseAppPath(string path);
/// <summary>
/// Tells bootstrapper to register the given instance of the
/// <see cref="JobStorage"/> class globally.
/// </summary>
/// <param name="storage">Job storage</param>
[Obsolete("Please use `GlobalConfiguration.UseStorage` instead. Will be removed in version 2.0.0.")]
void UseStorage(JobStorage storage);
/// <summary>
/// Tells bootstrapper to register the given instance of the
/// <see cref="JobActivator"/> class globally.
/// </summary>
/// <param name="activator">Job storage</param>
[Obsolete("Please use `GlobalConfiguration.UseActivator` instead. Will be removed in version 2.0.0.")]
void UseActivator(JobActivator activator);
/// <summary>
/// Tells bootstrapper to start the given job server on application
/// start, and stop it automatically on application shutdown request.
/// </summary>
/// <param name="server">Job server</param>
[Obsolete("Please use `IAppBuilder.UseHangfireServer` OWIN extension method instead. Will be removed in version 2.0.0.")]
void UseServer(Func<BackgroundJobServer> server);
}
} | gpl-3.0 |
reinhrst/panda | usr/lib/python2.7/dist-packages/chardet/escprober.py | 47 | ../../../../share/pyshared/chardet/escprober.py | gpl-3.0 |
jfrazelle/boulder | vendor/github.com/zmap/zlint/lints/lint_path_len_constraint_improperly_included.go | 2312 | package lints
/*
* ZLint Copyright 2018 Regents of the University of Michigan
*
* 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.
*/
/******************************************************************
RFC 5280: 4.2.1.9
CAs MUST NOT include the pathLenConstraint field unless the cA
boolean is asserted and the key usage extension asserts the
keyCertSign bit.
******************************************************************/
import (
"encoding/asn1"
"github.com/zmap/zcrypto/x509"
"github.com/zmap/zlint/util"
)
type pathLenIncluded struct{}
func (l *pathLenIncluded) Initialize() error {
return nil
}
func (l *pathLenIncluded) CheckApplies(cert *x509.Certificate) bool {
return util.IsExtInCert(cert, util.BasicConstOID)
}
func (l *pathLenIncluded) Execute(cert *x509.Certificate) *LintResult {
bc := util.GetExtFromCert(cert, util.BasicConstOID)
var seq asn1.RawValue
var isCa bool
_, err := asn1.Unmarshal(bc.Value, &seq)
if err != nil {
return &LintResult{Status: Fatal}
}
if len(seq.Bytes) == 0 {
return &LintResult{Status: Pass}
}
rest, err := asn1.UnmarshalWithParams(seq.Bytes, &isCa, "optional")
if err != nil {
return &LintResult{Status: Fatal}
}
keyUsageValue := util.IsExtInCert(cert, util.KeyUsageOID)
if len(rest) > 0 && (!cert.IsCA || !keyUsageValue || (keyUsageValue && cert.KeyUsage&x509.KeyUsageCertSign == 0)) {
return &LintResult{Status: Error}
}
return &LintResult{Status: Pass}
}
func init() {
RegisterLint(&Lint{
Name: "e_path_len_constraint_improperly_included",
Description: "CAs MUST NOT include the pathLenConstraint field unless the CA boolean is asserted and the keyCertSign bit is set",
Citation: "RFC 5280: 4.2.1.9",
Source: RFC5280,
EffectiveDate: util.RFC3280Date,
Lint: &pathLenIncluded{},
})
}
| mpl-2.0 |
tommynsong/terraform | working_dir.go | 377 | package main
import "github.com/hashicorp/terraform/internal/command/workdir"
func WorkingDir(originalDir string, overrideDataDir string) *workdir.Dir {
ret := workdir.NewDir(".") // caller should already have used os.Chdir in "-chdir=..." mode
ret.OverrideOriginalWorkingDir(originalDir)
if overrideDataDir != "" {
ret.OverrideDataDir(overrideDataDir)
}
return ret
}
| mpl-2.0 |
hhdevelopment/ocelot | ocelot-web/src/test/java/org/ocelotds/web/CdiBootstrapTest.java | 3131 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.ocelotds.web;
import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.Set;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.junit.Test;
import static org.mockito.Mockito.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import org.ocelotds.objects.Result;
import org.slf4j.Logger;
/**
*
* @author hhfrancois
*/
@RunWith(MockitoJUnitRunner.class)
public class CdiBootstrapTest {
private final static String BEANMANAGER = "java:comp/env/BeanManager";
@Mock
private Logger logger;
@InjectMocks
@Spy
private CdiBootstrapImpl cdiBootstrap;
/**
* Test of getBeanManager method, of class CdiBootstrap.
* @throws javax.naming.NamingException
*/
@Test
public void testGetBeanManager() throws NamingException {
System.out.println("getBeanManager");
// First time NamingException so null
when(cdiBootstrap.getInitialContext()).thenThrow(NamingException.class);
BeanManager result = cdiBootstrap.getBeanManager();
assertThat(result).isNull();
cdiBootstrap = spy(CdiBootstrapImpl.class);
// no exception so result = bm
BeanManager bm = mock(BeanManager.class);
InitialContext ic = mock(InitialContext.class);
when(ic.lookup(eq(BEANMANAGER))).thenReturn(bm);
when(cdiBootstrap.getInitialContext()).thenReturn(ic);
result = cdiBootstrap.getBeanManager();
assertThat(result).isEqualTo(bm);
// exception but not reached, so result = bm
when(cdiBootstrap.getInitialContext()).thenThrow(NamingException.class);
result = cdiBootstrap.getBeanManager();
assertThat(result).isEqualTo(bm);
}
/**
* Test of getBean method, of class CdiBootstrap.
* @throws javax.naming.NamingException
*/
@Test
public void testGetBean() throws NamingException {
System.out.println("getBean");
Bean b = mock(Bean.class);
when(b.getBeanClass()).thenReturn(Result.class);
Set<Bean<?>> beans = new HashSet<>();
beans.add(b);
CreationalContext context = mock(CreationalContext.class);
BeanManager bm = mock(BeanManager.class);
when(bm.getBeans(eq(Result.class), any(Annotation.class))).thenReturn(beans);
when(bm.createCreationalContext(eq(b))).thenReturn(context);
when(bm.getReference(eq(b), eq(Result.class), eq(context))).thenReturn(new Result());
when(cdiBootstrap.getBeanManager()).thenReturn(bm);
Object result = cdiBootstrap.getBean(Result.class);
assertThat(result).isInstanceOf(Result.class);
}
public static class CdiBootstrapImpl extends CdiBootstrap {
}
}
| mpl-2.0 |
CUModSquad/Camelot-Unchained | game/hud/src/components/fullscreen/PaperDoll/PopupMiniInventory.tsx | 15960 | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
import React, { useContext } from 'react';
import * as _ from 'lodash';
import { css } from '@csegames/linaria';
import { styled } from '@csegames/linaria/react';
import { utils, PageController, PageInfo } from '@csegames/camelot-unchained';
import PopupMiniInventorySlot from './PopupMiniInventorySlot';
import TabSubHeader from '../../shared/Tabs/TabSubHeader';
import FilterInput from '../Inventory/components/FilterInput';
import { displaySlotNames, GearSlots, MID_SCALE, HD_SCALE } from 'fullscreen/lib/constants';
import { getItemDefinitionName } from 'fullscreen/lib/utils';
import { InventoryItem } from 'gql/interfaces';
import { getScaledValue } from 'lib/scale';
// #region MiniInventoryBox constants
const MINI_INVENTORY_BOX_WIDTH = 620;
const MINI_INVENTORY_BOX_HEIGHT = 430;
// #endregion
const MiniInventoryBox = styled.div`
position: fixed;
background: linear-gradient(to bottom, rgba(55, 33, 19, 1), rgba(24, 17, 11, 0.9));
border-image: linear-gradient(to bottom, #623F26, transparent);
border-style: solid;
border-top-width: 1px;
border-left-width: 1px;
border-right-width: 1px;
border-bottom-width: 0px;
width: ${MINI_INVENTORY_BOX_WIDTH}px;
height: ${MINI_INVENTORY_BOX_HEIGHT}px;
overflow: hidden;
z-index: 10;
@media (max-width: 2560px) {
width: ${MINI_INVENTORY_BOX_WIDTH * MID_SCALE}px;
height: ${MINI_INVENTORY_BOX_HEIGHT * MID_SCALE}px;
}
@media (max-width: 1920px) {
width: ${MINI_INVENTORY_BOX_WIDTH * HD_SCALE}px;
height: ${MINI_INVENTORY_BOX_HEIGHT * HD_SCALE}px;
}
`;
// #region SubHeaderClass constants
const SUB_HEADER_CLASS_HEIGHT = 70;
// #endregion
const SubHeaderClass = css`
height: ${SUB_HEADER_CLASS_HEIGHT}px;
@media (max-width: 2560px) {
height: ${SUB_HEADER_CLASS_HEIGHT * MID_SCALE}px;
}
@media (max-width: 1920px) {
height: ${SUB_HEADER_CLASS_HEIGHT * HD_SCALE}px;
}
`;
// #region SubHeaderContentClass constants
const SUB_HEADER_CONTENT_CLASS_LETTER_SPACING = 2;
const SUB_HEADER_CONTENT_CLASS_PADDING_RIGHT = 10;
const SUB_HEADER_CONTENT_CLASS_PADDING_LEFT = 20;
const SUB_HEADER_CONTENT_CLASS_FONT_SIZE = 28;
// #endregion
const SubHeaderContentClass = css`
padding-right: ${SUB_HEADER_CONTENT_CLASS_PADDING_RIGHT}px;
padding-left: ${SUB_HEADER_CONTENT_CLASS_PADDING_LEFT}px;
letter-spacing: ${SUB_HEADER_CONTENT_CLASS_LETTER_SPACING}px;
font-size: ${SUB_HEADER_CONTENT_CLASS_FONT_SIZE}px;
text-transform: none;
display: flex;
align-items: center;
justify-content: space-between;
@media (max-width: 2560px) {
padding-right: ${SUB_HEADER_CONTENT_CLASS_PADDING_RIGHT * MID_SCALE}px;
padding-left: ${SUB_HEADER_CONTENT_CLASS_PADDING_LEFT * MID_SCALE}px;
letter-spacing: ${SUB_HEADER_CONTENT_CLASS_LETTER_SPACING * MID_SCALE}px;
font-size: ${SUB_HEADER_CONTENT_CLASS_FONT_SIZE * MID_SCALE}px;
}
@media (max-width: 1920px) {
padding-right: ${SUB_HEADER_CONTENT_CLASS_PADDING_RIGHT * HD_SCALE}px;
padding-left: ${SUB_HEADER_CONTENT_CLASS_PADDING_LEFT * HD_SCALE}px;
letter-spacing: ${SUB_HEADER_CONTENT_CLASS_LETTER_SPACING * HD_SCALE}px;
font-size: ${SUB_HEADER_CONTENT_CLASS_FONT_SIZE * HD_SCALE}px;
}
`;
// #region ControllerContainerStyle constants
const CONTROLLER_CONTAINER_STYLE_HEIGHT = 30;
// #endregion
const ControllerContainerStyle = css`
height: ${CONTROLLER_CONTAINER_STYLE_HEIGHT}px;
@media (max-width: 2560px) {
height: ${CONTROLLER_CONTAINER_STYLE_HEIGHT * MID_SCALE}px;
}
@media (max-width: 1920px) {
height: ${CONTROLLER_CONTAINER_STYLE_HEIGHT * HD_SCALE}px;
}
`;
// #region ControllerContainer constants
const CONTROLLER_CONTAINER_PADDING_VERTICAL = 4;
const CONTROLLER_CONTAIENR_PADDING_HORIZONTAL = 10;
const CONTROLLER_CONTAINER_HEIGHT = 30;
// #endregion
const ControllerContainer = styled.div`
display: flex;
align-items: center;
justify-content: space-between;
padding: ${CONTROLLER_CONTAINER_PADDING_VERTICAL}px ${CONTROLLER_CONTAIENR_PADDING_HORIZONTAL}px;
height: ${CONTROLLER_CONTAINER_HEIGHT}px;
background-color: rgba(20, 14, 7, 0.7);
@media (max-width: 2560px) {
height: ${CONTROLLER_CONTAINER_HEIGHT * MID_SCALE}px;
padding: ${CONTROLLER_CONTAINER_PADDING_VERTICAL * MID_SCALE}px ${CONTROLLER_CONTAIENR_PADDING_HORIZONTAL * MID_SCALE}px;
}
@media (max-width: 1920px) {
height: ${CONTROLLER_CONTAINER_HEIGHT * HD_SCALE}px;
padding: ${CONTROLLER_CONTAINER_PADDING_VERTICAL * HD_SCALE}px ${CONTROLLER_CONTAIENR_PADDING_HORIZONTAL * HD_SCALE}px;
}
`;
// #region ItemsContainer constants
const ITEMS_CONTAINER_PADDING = 10;
// #endregion
const ItemsContainer = styled.div`
padding: ${ITEMS_CONTAINER_PADDING}px;
height: ${MINI_INVENTORY_BOX_HEIGHT - SUB_HEADER_CLASS_HEIGHT}px;
@media (max-width: 2560px) {
padding: ${ITEMS_CONTAINER_PADDING * MID_SCALE}px;
height: ${(MINI_INVENTORY_BOX_HEIGHT - SUB_HEADER_CLASS_HEIGHT) * MID_SCALE}px;
}
@media (max-width: 1920px) {
padding: ${ITEMS_CONTAINER_PADDING * HD_SCALE}px;
height: ${(MINI_INVENTORY_BOX_HEIGHT - SUB_HEADER_CLASS_HEIGHT) * HD_SCALE}px;
}
`;
// #region ItemSpacing constants
const ITEM_SPACING_MARGIN_VERTICAL = 1;
const ITEM_SPACING_MARGIN_HORIZONTAL = 5;
// #endregion
const ItemSpacing = styled.div`
display: inline-block;
margin: ${ITEM_SPACING_MARGIN_VERTICAL}px ${ITEM_SPACING_MARGIN_HORIZONTAL}px;
@media (max-width: 2560px) {
margin: ${ITEM_SPACING_MARGIN_VERTICAL * MID_SCALE}px ${ITEM_SPACING_MARGIN_HORIZONTAL * MID_SCALE}px;
}
@media (max-width: 1920px) {
margin: ${ITEM_SPACING_MARGIN_VERTICAL * HD_SCALE}px ${ITEM_SPACING_MARGIN_HORIZONTAL * HD_SCALE}px;
}
`;
// #region SlotNameText constants
const SLOT_NAME_TEXT_FONT_SIZE = 28;
// #endregion
const SlotNameText = styled.p`
font-size: ${SLOT_NAME_TEXT_FONT_SIZE}px;
color: #D8BFA8;
margin: 0 !important;
padding: 0;
flex: 1;
white-space: nowrap;
@media (max-width: 2560px) {
font-size: ${SLOT_NAME_TEXT_FONT_SIZE * MID_SCALE}px;
}
@media (max-width: 1920px) {
font-size: ${SLOT_NAME_TEXT_FONT_SIZE * HD_SCALE}px;
}
`;
// #region PageNumberText constants
const PAGE_NUMBER_TEXT_MARGIN_BOTTOM = 10;
const PAGE_NUMBER_TEXT_FONT_SIZE = 24;
const PAGE_NUMBER_TEXT_LETTER_SPACING = 4;
// #endregion
const PageNumberText = styled.p`
display: flex;
align-items: center;
justify-content: space-between;
color: #D8BFA8;
margin: 0 ${PAGE_NUMBER_TEXT_MARGIN_BOTTOM}px 0 0 !important;
font-size: ${PAGE_NUMBER_TEXT_FONT_SIZE}px;
letter-spacing: ${PAGE_NUMBER_TEXT_LETTER_SPACING}px;
@media (max-width: 2560px) {
margin: 0 ${PAGE_NUMBER_TEXT_MARGIN_BOTTOM * MID_SCALE}px 0 0 !important;
font-size: ${PAGE_NUMBER_TEXT_FONT_SIZE * MID_SCALE}px;
letter-spacing: ${PAGE_NUMBER_TEXT_LETTER_SPACING * MID_SCALE}px;
}
@media (max-width: 1920px) {
margin: 0 ${PAGE_NUMBER_TEXT_MARGIN_BOTTOM * HD_SCALE}px 0 0 !important;
font-size: ${PAGE_NUMBER_TEXT_FONT_SIZE * HD_SCALE}px;
letter-spacing: ${PAGE_NUMBER_TEXT_LETTER_SPACING * HD_SCALE}px;
}
`;
// #region ControllerButton constants
const CONTROLLER_BUTTON_FONT_SIZE = 24;
const CONTROLLER_BUTTON_LETTER_SPACING = 2;
// #endregion
const ControllerButton = styled.div`
display: inline-block;
font-size: ${CONTROLLER_BUTTON_FONT_SIZE}px;
letter-spacing: ${CONTROLLER_BUTTON_LETTER_SPACING}px;
color: #D8BFA8;
cursor: pointer;
&:active {
text-shadow: 2px 2px rgba(0, 0, 0, 0.9);
}
@media (max-width: 2560px) {
font-size: ${CONTROLLER_BUTTON_FONT_SIZE * MID_SCALE}px;
letter-spacing: ${CONTROLLER_BUTTON_LETTER_SPACING * MID_SCALE}px;
}
@media (max-width: 1920px) {
font-size: ${CONTROLLER_BUTTON_FONT_SIZE * HD_SCALE}px;
letter-spacing: ${CONTROLLER_BUTTON_LETTER_SPACING * HD_SCALE}px;
}
`;
const DisabledControllerButton = css`
opacity: 0.5;
`;
// #region InputClass constants
const INPUT_CLASS_MARGIN_LEFT = 20;
const INPUT_CLASS_PADDING = 10;
const INPUT_CLASS_HEIGHT = 50;
// #endregion
const InputClass = css`
margin-left: ${INPUT_CLASS_MARGIN_LEFT}px;
padding: ${INPUT_CLASS_PADDING}px;
height: ${INPUT_CLASS_HEIGHT}px;
@media (max-width: 2560px) {
margin-left: ${INPUT_CLASS_MARGIN_LEFT * MID_SCALE}px;
padding: ${INPUT_CLASS_PADDING * MID_SCALE}px;
height: ${INPUT_CLASS_HEIGHT * MID_SCALE}px;
}
@media (max-width: 1920px) {
margin-left: ${INPUT_CLASS_MARGIN_LEFT * HD_SCALE}px;
padding: ${INPUT_CLASS_PADDING * HD_SCALE}px;
height: ${INPUT_CLASS_HEIGHT * HD_SCALE}px;
}
`;
export enum Alignment {
Armor = 1 << 0,
Weapon = 1 << 1,
Top = 1 << 2,
Bottom = 1 << 3,
Left = 1 << 4,
Right = 1 << 5,
TopRight = Alignment.Top | Alignment.Right,
TopLeft = Alignment.Top | Alignment.Left,
BottomRight = Alignment.Bottom | Alignment.Right,
BottomLeft = Alignment.Bottom | Alignment.Left,
WTopRight = Alignment.TopRight | Alignment.Weapon,
WTopLeft = Alignment.TopLeft | Alignment.Weapon,
ATopRight = Alignment.TopRight | Alignment.Armor,
ATopLeft = Alignment.TopLeft | Alignment.Armor,
ABottomRight = Alignment.BottomRight | Alignment.Armor,
ABottomLeft = Alignment.BottomLeft | Alignment.Armor,
}
export interface PopupMiniInventoryProps {
align: Alignment;
slotName: GearSlots;
inventoryItems: InventoryItem.Fragment[];
offsets: ClientRect;
onMouseOver: () => void;
onMouseLeave: () => void;
}
type Props = { uiContext: UIContext } & PopupMiniInventoryProps;
export interface PopupMiniInventoryState {
miniInventoryItems: InventoryItem.Fragment[];
searchValue: string;
top: number;
left: number;
}
export class PopupMiniInventory extends React.Component<Props, PopupMiniInventoryState> {
constructor(props: Props) {
super(props);
this.state = {
miniInventoryItems: [],
searchValue: '',
top: 0,
left: 0,
};
}
public render() {
const miniInventoryItems = _.filter(this.state.miniInventoryItems, (item) => {
return utils.doesSearchInclude(this.state.searchValue, getItemDefinitionName(item));
});
const amountOfPages = Math.ceil(miniInventoryItems.length / 8) + (miniInventoryItems.length % 8 > 0 ? 1 : 0) || 1;
const arrayOfPages: InventoryItem.Fragment[][] = [];
let nextIndex = 0;
if (amountOfPages > 1) {
for (let i = 1; i < amountOfPages; i++) {
const items = miniInventoryItems.slice(nextIndex, nextIndex + 8);
if (items.length === 8) {
arrayOfPages.push(items);
nextIndex += 8;
} else {
arrayOfPages.push([...items, ..._.fill(Array(8 - items.length), '' as any)]);
}
}
} else {
arrayOfPages.push([..._.fill(Array(8), '' as any)]);
}
const pages: PageInfo<{active: boolean}>[] = arrayOfPages.map((items, index) => {
return {
render: () => (
<ItemsContainer key={index}>
{items.map((item) => {
const gearSlots = item && _.find(item.staticDefinition.gearSlotSets, (gearSlotSet): any =>
_.find(gearSlotSet.gearSlots, gearSlot => gearSlot.id === this.props.slotName)).gearSlots;
return (
<ItemSpacing>
<PopupMiniInventorySlot item={item} gearSlots={gearSlots as any} />
</ItemSpacing>
);
})}
</ItemsContainer>
),
};
});
return (
<MiniInventoryBox
style={{ top: this.state.top, left: this.state.left }}
onMouseOver={this.props.onMouseOver}
onMouseLeave={this.props.onMouseLeave}>
<TabSubHeader className={SubHeaderClass} contentClassName={SubHeaderContentClass}>
<SlotNameText>{displaySlotNames[this.props.slotName]}</SlotNameText>
<FilterInput
className={InputClass}
onFilterChanged={this.onSearchChange}
filterText={this.state.searchValue}
/>
</TabSubHeader>
<PageController
pages={pages}
styles={{
controllerContainer: ControllerContainerStyle,
}}
renderPageController={(state, props, onNextPageClick, onPrevPageClick) => {
const moreNext = state.activePageIndex < pages.length - 1;
const morePrev = state.activePageIndex > 0;
return (
<ControllerContainer>
<ControllerButton className={!morePrev ? DisabledControllerButton : ''} onClick={onPrevPageClick}>
{'< Prev'}
</ControllerButton>
<PageNumberText>{state.activePageIndex + 1} / {pages.length}</PageNumberText>
<ControllerButton className={!moreNext ? DisabledControllerButton : ''} onClick={onNextPageClick}>
{'Next >'}
</ControllerButton>
</ControllerContainer>
);
}}
/>
</MiniInventoryBox>
);
}
public componentDidMount() {
this.setWindowPosition(this.props);
this.initializeMiniInventoryItems(this.props);
}
public componentWillReceiveProps(nextProps: Props) {
this.setWindowPosition(nextProps);
this.initializeMiniInventoryItems(nextProps);
}
private initializeMiniInventoryItems = (props: Props) => {
const { slotName, inventoryItems } = props;
const miniInventoryItems: InventoryItem.Fragment[] = [];
if (inventoryItems) {
inventoryItems.forEach((inventoryItem) => {
const itemInfo = inventoryItem && inventoryItem.staticDefinition;
if (itemInfo && itemInfo.gearSlotSets) {
itemInfo.gearSlotSets.forEach((gearSlotSet) => {
gearSlotSet.gearSlots.forEach((gearSlot) => {
if (gearSlot.id === slotName) {
miniInventoryItems.push(inventoryItem);
}
});
});
}
});
this.setState({ miniInventoryItems });
}
}
private setWindowPosition = (props: Props) => {
const { align, offsets } = props;
const { top, left, height, width } = offsets;
const containerHeight = getScaledValue(props.uiContext, MINI_INVENTORY_BOX_HEIGHT);
const containerWidth = getScaledValue(props.uiContext, MINI_INVENTORY_BOX_WIDTH);
const containerMargin = getScaledValue(props.uiContext, 10);
this.setState((state, props) => {
switch (align) {
case Alignment.WTopRight: {
return {
top: top - (containerHeight + containerMargin),
left,
};
}
case Alignment.WTopLeft: {
return {
top: top - (containerHeight + containerMargin),
left: left - (containerWidth) + width,
};
}
case Alignment.ATopRight: {
return {
top,
left: left + width + containerMargin,
};
}
case Alignment.ATopLeft: {
return {
top,
left: left - (containerWidth + containerMargin),
};
}
case Alignment.ABottomRight: {
return {
top: top - (containerHeight) + height,
left: left + width + containerMargin,
};
}
case Alignment.ABottomLeft: {
return {
top: top - (containerHeight) + height,
left: left - (containerWidth + containerMargin),
};
}
}
});
}
private onSearchChange = (searchValue: string) => {
this.setState({ searchValue });
}
}
// tslint:disable-next-line:function-name
function PopupMiniInventoryWithContext(props: PopupMiniInventoryProps) {
const uiContext = useContext(UIContext);
return (
<PopupMiniInventory uiContext={uiContext} {...props} />
);
}
export default PopupMiniInventoryWithContext;
| mpl-2.0 |
servinglynk/servinglynk-hmis | hmis-service-v2014/src/main/java/com/servinglynk/hmis/warehouse/service/impl/IncomeAndSourceServiceImpl.java | 4770 | package com.servinglynk.hmis.warehouse.service.impl;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import org.springframework.transaction.annotation.Transactional;
import com.servinglynk.hmis.warehouse.SortedPagination;
import com.servinglynk.hmis.warehouse.core.model.IncomeAndSource;
import com.servinglynk.hmis.warehouse.core.model.IncomeAndSources;
import com.servinglynk.hmis.warehouse.service.IncomeAndSourceService;
import com.servinglynk.hmis.warehouse.service.converter.IncomeAndSourceConverter;
import com.servinglynk.hmis.warehouse.service.exception.EnrollmentNotFound;
import com.servinglynk.hmis.warehouse.service.exception.IncomeAndSourceNotFoundException;
public class IncomeAndSourceServiceImpl extends ServiceBase implements IncomeAndSourceService {
@Transactional
public IncomeAndSource createIncomeAndSource(IncomeAndSource incomeAndSource,UUID enrollmentId,String caller){
com.servinglynk.hmis.warehouse.model.v2014.Incomeandsources pIncomeAndSource = IncomeAndSourceConverter.modelToEntity(incomeAndSource, null);
com.servinglynk.hmis.warehouse.model.v2014.Enrollment pEnrollment = daoFactory.getEnrollmentDao().getEnrollmentById(enrollmentId);
if(pEnrollment == null) throw new EnrollmentNotFound();
pIncomeAndSource.setEnrollmentid(pEnrollment);
pIncomeAndSource.setDateCreated(LocalDateTime.now());
// pIncomeAndSource.setUser(daoFactory.getHmisUserDao().findByUsername(caller));
daoFactory.getProjectDao().populateUserProjectGroupCode(pIncomeAndSource, caller);
daoFactory.getIncomeandsourcesDao().createIncomeAndSource(pIncomeAndSource);
incomeAndSource.setIncomeAndSourceId(pIncomeAndSource.getId());
return incomeAndSource;
}
@Transactional
public IncomeAndSource updateIncomeAndSource(IncomeAndSource incomeAndSource,UUID enrollmentId,String caller){
com.servinglynk.hmis.warehouse.model.v2014.Enrollment pEnrollment = daoFactory.getEnrollmentDao().getEnrollmentById(enrollmentId);
if(pEnrollment == null) throw new EnrollmentNotFound();
com.servinglynk.hmis.warehouse.model.v2014.Incomeandsources pIncomeAndSource = daoFactory.getIncomeandsourcesDao().getIncomeAndSourceById(incomeAndSource.getIncomeAndSourceId());
if(pIncomeAndSource==null) throw new IncomeAndSourceNotFoundException();
IncomeAndSourceConverter.modelToEntity(incomeAndSource, pIncomeAndSource);
pIncomeAndSource.setEnrollmentid(pEnrollment);
pIncomeAndSource.setDateUpdated(LocalDateTime.now());
// pIncomeAndSource.setUser(daoFactory.getHmisUserDao().findByUsername(caller));
daoFactory.getIncomeandsourcesDao().updateIncomeAndSource(pIncomeAndSource);
incomeAndSource.setIncomeAndSourceId(pIncomeAndSource.getId());
return incomeAndSource;
}
@Transactional
public IncomeAndSource deleteIncomeAndSource(UUID incomeAndSourceId,String caller){
com.servinglynk.hmis.warehouse.model.v2014.Incomeandsources pIncomeAndSource = daoFactory.getIncomeandsourcesDao().getIncomeAndSourceById(incomeAndSourceId);
if(pIncomeAndSource==null) throw new IncomeAndSourceNotFoundException();
daoFactory.getIncomeandsourcesDao().deleteIncomeAndSource(pIncomeAndSource);
return new IncomeAndSource();
}
@Transactional
public IncomeAndSource getIncomeAndSourceById(UUID incomeAndSourceId){
com.servinglynk.hmis.warehouse.model.v2014.Incomeandsources pIncomeAndSource = daoFactory.getIncomeandsourcesDao().getIncomeAndSourceById(incomeAndSourceId);
if(pIncomeAndSource==null) throw new IncomeAndSourceNotFoundException();
return IncomeAndSourceConverter.entityToModel( pIncomeAndSource );
}
@Transactional
public IncomeAndSources getAllEnrollmentIncomeAndSources(UUID enrollmentId,Integer startIndex, Integer maxItems){
IncomeAndSources incomeAndSources = new IncomeAndSources();
List<com.servinglynk.hmis.warehouse.model.v2014.Incomeandsources> entities = daoFactory.getIncomeandsourcesDao().getAllEnrollmentIncomeAndSources(enrollmentId,startIndex,maxItems);
for(com.servinglynk.hmis.warehouse.model.v2014.Incomeandsources entity : entities){
incomeAndSources.addIncomeAndSource(IncomeAndSourceConverter.entityToModel(entity));
}
long count = daoFactory.getIncomeandsourcesDao().getEnrollmentIncomeAndSourcesCount(enrollmentId);
SortedPagination pagination = new SortedPagination();
pagination.setFrom(startIndex);
pagination.setReturned(incomeAndSources.getIncomeAndSources().size());
pagination.setTotal((int)count);
incomeAndSources.setPagination(pagination);
return incomeAndSources;
}
}
| mpl-2.0 |
tafia/servo | components/layout/layout_task.rs | 70634 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The layout task. Performs layout on the DOM, builds display lists and sends them to be
//! painted.
#![allow(unsafe_code)]
use animation;
use construct::ConstructionResult;
use context::{SharedLayoutContext, heap_size_of_local_context};
use cssparser::ToCss;
use data::LayoutDataWrapper;
use display_list_builder::ToGfxColor;
use flow::{self, Flow, ImmutableFlowUtils, MutableFlowUtils, MutableOwnedFlowUtils};
use flow_ref::FlowRef;
use fragment::{Fragment, FragmentBorderBoxIterator, SpecificFragmentInfo};
use incremental::{LayoutDamageComputation, REFLOW, REFLOW_ENTIRE_DOCUMENT, REPAINT};
use layout_debug;
use opaque_node::OpaqueNodeMethods;
use parallel::{self, WorkQueueData};
use query::{LayoutRPCImpl, process_content_box_request, process_content_boxes_request, MarginPadding, Side};
use query::{MarginRetrievingFragmentBorderBoxIterator, PositionProperty, PositionRetrievingFragmentBorderBoxIterator};
use sequential;
use wrapper::LayoutNode;
use azure::azure::AzColor;
use canvas_traits::CanvasMsg;
use encoding::EncodingRef;
use encoding::all::UTF_8;
use fnv::FnvHasher;
use euclid::Matrix4;
use euclid::point::Point2D;
use euclid::rect::Rect;
use euclid::scale_factor::ScaleFactor;
use euclid::size::Size2D;
use gfx_traits::color;
use gfx::display_list::{ClippingRegion, DisplayList, OpaqueNode};
use gfx::display_list::StackingContext;
use gfx::font_cache_task::FontCacheTask;
use gfx::paint_task::{LayoutToPaintMsg, PaintLayer};
use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
use ipc_channel::router::ROUTER;
use layout_traits::LayoutTaskFactory;
use log;
use msg::compositor_msg::{Epoch, ScrollPolicy, LayerId};
use msg::constellation_msg::Msg as ConstellationMsg;
use msg::constellation_msg::{ConstellationChan, Failure, PipelineExitType, PipelineId};
use profile_traits::mem::{self, Report, ReportKind, ReportsChan};
use profile_traits::time::{self, ProfilerMetadata, profile};
use profile_traits::time::{TimerMetadataFrameType, TimerMetadataReflowType};
use net_traits::{load_bytes_iter, PendingAsyncLoad};
use net_traits::image_cache_task::{ImageCacheTask, ImageCacheResult, ImageCacheChan};
use script::dom::bindings::js::LayoutJS;
use script::dom::node::{LayoutData, Node};
use script::layout_interface::Animation;
use script::layout_interface::{LayoutChan, LayoutRPC, OffsetParentResponse};
use script::layout_interface::{NewLayoutTaskInfo, Msg, Reflow, ReflowGoal, ReflowQueryType};
use script::layout_interface::{ScriptLayoutChan, ScriptReflow, TrustedNodeAddress};
use script_traits::{ConstellationControlMsg, LayoutControlMsg, OpaqueScriptLayoutChannel};
use script_traits::StylesheetLoadResponder;
use selectors::parser::PseudoElement;
use serde_json;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::collections::HashMap;
use std::collections::hash_state::DefaultState;
use std::mem::transmute;
use std::ops::{Deref, DerefMut};
use std::sync::mpsc::{channel, Sender, Receiver, Select};
use std::sync::{Arc, Mutex, MutexGuard};
use string_cache::Atom;
use style::computed_values::{self, filter, mix_blend_mode};
use style::media_queries::{MediaType, MediaQueryList, Device};
use style::properties::style_structs;
use style::properties::longhands::{display, position};
use style::selector_matching::Stylist;
use style::stylesheets::{Origin, Stylesheet, CSSRuleIteratorExt};
use url::Url;
use util::geometry::{Au, MAX_RECT, ZERO_POINT};
use util::ipc::OptionalIpcSender;
use util::logical_geometry::LogicalPoint;
use util::mem::HeapSizeOf;
use util::opts;
use util::task::spawn_named_with_send_on_failure;
use util::task_state;
use util::workqueue::WorkQueue;
use wrapper::ThreadSafeLayoutNode;
/// The number of screens of data we're allowed to generate display lists for in each direction.
pub const DISPLAY_PORT_SIZE_FACTOR: i32 = 8;
/// The number of screens we have to traverse before we decide to generate new display lists.
const DISPLAY_PORT_THRESHOLD_SIZE_FACTOR: i32 = 4;
/// Mutable data belonging to the LayoutTask.
///
/// This needs to be protected by a mutex so we can do fast RPCs.
pub struct LayoutTaskData {
/// The root of the flow tree.
pub root_flow: Option<FlowRef>,
/// The image cache.
pub image_cache_task: ImageCacheTask,
/// The channel on which messages can be sent to the constellation.
pub constellation_chan: ConstellationChan,
/// The size of the viewport.
pub screen_size: Size2D<Au>,
/// The root stacking context.
pub stacking_context: Option<Arc<StackingContext>>,
/// Performs CSS selector matching and style resolution.
pub stylist: Box<Stylist>,
/// The workers that we use for parallel operation.
pub parallel_traversal: Option<WorkQueue<SharedLayoutContext, WorkQueueData>>,
/// Starts at zero, and increased by one every time a layout completes.
/// This can be used to easily check for invalid stale data.
pub generation: u32,
/// A queued response for the union of the content boxes of a node.
pub content_box_response: Rect<Au>,
/// A queued response for the content boxes of a node.
pub content_boxes_response: Vec<Rect<Au>>,
/// A queued response for the client {top, left, width, height} of a node in pixels.
pub client_rect_response: Rect<i32>,
/// A queued response for the resolved style property of an element.
pub resolved_style_response: Option<String>,
/// A queued response for the offset parent/rect of a node.
pub offset_parent_response: OffsetParentResponse,
/// The list of currently-running animations.
pub running_animations: Arc<HashMap<OpaqueNode, Vec<Animation>>>,
/// Receives newly-discovered animations.
pub new_animations_receiver: Receiver<Animation>,
/// A channel on which new animations that have been triggered by style recalculation can be
/// sent.
pub new_animations_sender: Sender<Animation>,
/// A counter for epoch messages
epoch: Epoch,
/// The position and size of the visible rect for each layer. We do not build display lists
/// for any areas more than `DISPLAY_PORT_SIZE_FACTOR` screens away from this area.
pub visible_rects: Arc<HashMap<LayerId, Rect<Au>, DefaultState<FnvHasher>>>,
}
/// Information needed by the layout task.
pub struct LayoutTask {
/// The ID of the pipeline that we belong to.
pub id: PipelineId,
/// The URL of the pipeline that we belong to.
pub url: Url,
/// Is the current reflow of an iframe, as opposed to a root window?
pub is_iframe: bool,
/// The port on which we receive messages from the script task.
pub port: Receiver<Msg>,
/// The port on which we receive messages from the constellation.
pub pipeline_port: Receiver<LayoutControlMsg>,
/// The port on which we receive messages from the image cache
image_cache_receiver: Receiver<ImageCacheResult>,
/// The channel on which the image cache can send messages to ourself.
image_cache_sender: ImageCacheChan,
/// The channel on which we or others can send messages to ourselves.
pub chan: LayoutChan,
/// The channel on which messages can be sent to the constellation.
pub constellation_chan: ConstellationChan,
/// The channel on which messages can be sent to the script task.
pub script_chan: Sender<ConstellationControlMsg>,
/// The channel on which messages can be sent to the painting task.
pub paint_chan: OptionalIpcSender<LayoutToPaintMsg>,
/// The channel on which messages can be sent to the time profiler.
pub time_profiler_chan: time::ProfilerChan,
/// The channel on which messages can be sent to the memory profiler.
pub mem_profiler_chan: mem::ProfilerChan,
/// The channel on which messages can be sent to the image cache.
pub image_cache_task: ImageCacheTask,
/// Public interface to the font cache task.
pub font_cache_task: FontCacheTask,
/// Is this the first reflow in this LayoutTask?
pub first_reflow: Cell<bool>,
/// To receive a canvas renderer associated to a layer, this message is propagated
/// to the paint chan
pub canvas_layers_receiver: Receiver<(LayerId, IpcSender<CanvasMsg>)>,
pub canvas_layers_sender: Sender<(LayerId, IpcSender<CanvasMsg>)>,
/// A mutex to allow for fast, read-only RPC of layout's internal data
/// structures, while still letting the LayoutTask modify them.
///
/// All the other elements of this struct are read-only.
pub rw_data: Arc<Mutex<LayoutTaskData>>,
}
impl LayoutTaskFactory for LayoutTask {
/// Spawns a new layout task.
fn create(_phantom: Option<&mut LayoutTask>,
id: PipelineId,
url: Url,
is_iframe: bool,
chan: OpaqueScriptLayoutChannel,
pipeline_port: IpcReceiver<LayoutControlMsg>,
constellation_chan: ConstellationChan,
failure_msg: Failure,
script_chan: Sender<ConstellationControlMsg>,
paint_chan: OptionalIpcSender<LayoutToPaintMsg>,
image_cache_task: ImageCacheTask,
font_cache_task: FontCacheTask,
time_profiler_chan: time::ProfilerChan,
mem_profiler_chan: mem::ProfilerChan,
shutdown_chan: Sender<()>) {
let ConstellationChan(con_chan) = constellation_chan.clone();
spawn_named_with_send_on_failure(format!("LayoutTask {:?}", id), task_state::LAYOUT, move || {
{ // Ensures layout task is destroyed before we send shutdown message
let sender = chan.sender();
let layout_chan = LayoutChan(sender);
let layout = LayoutTask::new(id,
url,
is_iframe,
chan.receiver(),
layout_chan.clone(),
pipeline_port,
constellation_chan,
script_chan,
paint_chan,
image_cache_task,
font_cache_task,
time_profiler_chan,
mem_profiler_chan.clone());
let reporter_name = format!("layout-reporter-{}", id.0);
mem_profiler_chan.run_with_memory_reporting(|| {
layout.start();
}, reporter_name, layout_chan.0, Msg::CollectReports);
}
shutdown_chan.send(()).unwrap();
}, ConstellationMsg::Failure(failure_msg), con_chan);
}
}
/// The `LayoutTask` `rw_data` lock must remain locked until the first reflow,
/// as RPC calls don't make sense until then. Use this in combination with
/// `LayoutTask::lock_rw_data` and `LayoutTask::return_rw_data`.
pub enum RWGuard<'a> {
/// If the lock was previously held, from when the task started.
Held(MutexGuard<'a, LayoutTaskData>),
/// If the lock was just used, and has been returned since there has been
/// a reflow already.
Used(MutexGuard<'a, LayoutTaskData>),
}
impl<'a> Deref for RWGuard<'a> {
type Target = LayoutTaskData;
fn deref(&self) -> &LayoutTaskData {
match *self {
RWGuard::Held(ref x) => &**x,
RWGuard::Used(ref x) => &**x,
}
}
}
impl<'a> DerefMut for RWGuard<'a> {
fn deref_mut(&mut self) -> &mut LayoutTaskData {
match *self {
RWGuard::Held(ref mut x) => &mut **x,
RWGuard::Used(ref mut x) => &mut **x,
}
}
}
fn add_font_face_rules(stylesheet: &Stylesheet, device: &Device, font_cache_task: &FontCacheTask) {
for font_face in stylesheet.effective_rules(&device).font_face() {
for source in &font_face.sources {
font_cache_task.add_web_font(font_face.family.clone(), source.clone());
}
}
}
impl LayoutTask {
/// Creates a new `LayoutTask` structure.
fn new(id: PipelineId,
url: Url,
is_iframe: bool,
port: Receiver<Msg>,
chan: LayoutChan,
pipeline_port: IpcReceiver<LayoutControlMsg>,
constellation_chan: ConstellationChan,
script_chan: Sender<ConstellationControlMsg>,
paint_chan: OptionalIpcSender<LayoutToPaintMsg>,
image_cache_task: ImageCacheTask,
font_cache_task: FontCacheTask,
time_profiler_chan: time::ProfilerChan,
mem_profiler_chan: mem::ProfilerChan)
-> LayoutTask {
let screen_size = Size2D::new(Au(0), Au(0));
let device = Device::new(
MediaType::Screen,
opts::get().initial_window_size.as_f32() * ScaleFactor::new(1.0));
let parallel_traversal = if opts::get().layout_threads != 1 {
Some(WorkQueue::new("LayoutWorker", task_state::LAYOUT,
opts::get().layout_threads))
} else {
None
};
// Create the channel on which new animations can be sent.
let (new_animations_sender, new_animations_receiver) = channel();
let (canvas_layers_sender, canvas_layers_receiver) = channel();
// Proxy IPC messages from the pipeline to the layout thread.
let pipeline_receiver = ROUTER.route_ipc_receiver_to_new_mpsc_receiver(pipeline_port);
// Ask the router to proxy IPC messages from the image cache task to the layout thread.
let (ipc_image_cache_sender, ipc_image_cache_receiver) = ipc::channel().unwrap();
let image_cache_receiver =
ROUTER.route_ipc_receiver_to_new_mpsc_receiver(ipc_image_cache_receiver);
let stylist = box Stylist::new(device);
for user_or_user_agent_stylesheet in stylist.stylesheets() {
add_font_face_rules(user_or_user_agent_stylesheet, &stylist.device, &font_cache_task);
}
LayoutTask {
id: id,
url: url,
is_iframe: is_iframe,
port: port,
pipeline_port: pipeline_receiver,
chan: chan,
script_chan: script_chan,
constellation_chan: constellation_chan.clone(),
paint_chan: paint_chan,
time_profiler_chan: time_profiler_chan,
mem_profiler_chan: mem_profiler_chan,
image_cache_task: image_cache_task.clone(),
font_cache_task: font_cache_task,
first_reflow: Cell::new(true),
image_cache_receiver: image_cache_receiver,
image_cache_sender: ImageCacheChan(ipc_image_cache_sender),
canvas_layers_receiver: canvas_layers_receiver,
canvas_layers_sender: canvas_layers_sender,
rw_data: Arc::new(Mutex::new(
LayoutTaskData {
root_flow: None,
image_cache_task: image_cache_task,
constellation_chan: constellation_chan,
screen_size: screen_size,
stacking_context: None,
stylist: stylist,
parallel_traversal: parallel_traversal,
generation: 0,
content_box_response: Rect::zero(),
content_boxes_response: Vec::new(),
client_rect_response: Rect::zero(),
resolved_style_response: None,
running_animations: Arc::new(HashMap::new()),
offset_parent_response: OffsetParentResponse::empty(),
visible_rects: Arc::new(HashMap::with_hash_state(Default::default())),
new_animations_receiver: new_animations_receiver,
new_animations_sender: new_animations_sender,
epoch: Epoch(0),
})),
}
}
/// Starts listening on the port.
fn start(self) {
let mut possibly_locked_rw_data = Some((*self.rw_data).lock().unwrap());
while self.handle_request(&mut possibly_locked_rw_data) {
// Loop indefinitely.
}
}
// Create a layout context for use in building display lists, hit testing, &c.
fn build_shared_layout_context(&self,
rw_data: &LayoutTaskData,
screen_size_changed: bool,
reflow_root: Option<&LayoutNode>,
url: &Url,
goal: ReflowGoal)
-> SharedLayoutContext {
SharedLayoutContext {
image_cache_task: rw_data.image_cache_task.clone(),
image_cache_sender: self.image_cache_sender.clone(),
screen_size: rw_data.screen_size.clone(),
screen_size_changed: screen_size_changed,
constellation_chan: rw_data.constellation_chan.clone(),
layout_chan: self.chan.clone(),
font_cache_task: self.font_cache_task.clone(),
canvas_layers_sender: self.canvas_layers_sender.clone(),
stylist: &*rw_data.stylist,
url: (*url).clone(),
reflow_root: reflow_root.map(|node| node.opaque()),
visible_rects: rw_data.visible_rects.clone(),
generation: rw_data.generation,
new_animations_sender: rw_data.new_animations_sender.clone(),
goal: goal,
running_animations: rw_data.running_animations.clone(),
}
}
/// Receives and dispatches messages from the script and constellation tasks
fn handle_request<'a>(&'a self,
possibly_locked_rw_data: &mut Option<MutexGuard<'a, LayoutTaskData>>)
-> bool {
enum PortToRead {
Pipeline,
Script,
ImageCache,
}
let port_to_read = {
let sel = Select::new();
let mut port1 = sel.handle(&self.port);
let mut port2 = sel.handle(&self.pipeline_port);
let mut port3 = sel.handle(&self.image_cache_receiver);
unsafe {
port1.add();
port2.add();
port3.add();
}
let ret = sel.wait();
if ret == port1.id() {
PortToRead::Script
} else if ret == port2.id() {
PortToRead::Pipeline
} else if ret == port3.id() {
PortToRead::ImageCache
} else {
panic!("invalid select result");
}
};
match port_to_read {
PortToRead::Pipeline => {
match self.pipeline_port.recv().unwrap() {
LayoutControlMsg::SetVisibleRects(new_visible_rects) => {
self.handle_request_helper(Msg::SetVisibleRects(new_visible_rects),
possibly_locked_rw_data)
}
LayoutControlMsg::TickAnimations => {
self.handle_request_helper(Msg::TickAnimations, possibly_locked_rw_data)
}
LayoutControlMsg::GetCurrentEpoch(sender) => {
self.handle_request_helper(Msg::GetCurrentEpoch(sender),
possibly_locked_rw_data)
}
LayoutControlMsg::ExitNow(exit_type) => {
self.handle_request_helper(Msg::ExitNow(exit_type),
possibly_locked_rw_data)
}
}
}
PortToRead::Script => {
let msg = self.port.recv().unwrap();
self.handle_request_helper(msg, possibly_locked_rw_data)
}
PortToRead::ImageCache => {
let _ = self.image_cache_receiver.recv().unwrap();
self.repaint(possibly_locked_rw_data)
}
}
}
/// If no reflow has happened yet, this will just return the lock in
/// `possibly_locked_rw_data`. Otherwise, it will acquire the `rw_data` lock.
///
/// If you do not wish RPCs to remain blocked, just drop the `RWGuard`
/// returned from this function. If you _do_ wish for them to remain blocked,
/// use `return_rw_data`.
fn lock_rw_data<'a>(&'a self,
possibly_locked_rw_data: &mut Option<MutexGuard<'a, LayoutTaskData>>)
-> RWGuard<'a> {
match possibly_locked_rw_data.take() {
None => RWGuard::Used((*self.rw_data).lock().unwrap()),
Some(x) => RWGuard::Held(x),
}
}
/// If no reflow has ever been triggered, this will keep the lock, locked
/// (and saved in `possibly_locked_rw_data`). If it has been, the lock will
/// be unlocked.
fn return_rw_data<'a>(possibly_locked_rw_data: &mut Option<MutexGuard<'a, LayoutTaskData>>,
rw_data: RWGuard<'a>) {
match rw_data {
RWGuard::Used(x) => drop(x),
RWGuard::Held(x) => *possibly_locked_rw_data = Some(x),
}
}
/// Repaint the scene, without performing style matching. This is typically
/// used when an image arrives asynchronously and triggers a relayout and
/// repaint.
/// TODO: In the future we could detect if the image size hasn't changed
/// since last time and avoid performing a complete layout pass.
fn repaint<'a>(&'a self,
possibly_locked_rw_data: &mut Option<MutexGuard<'a, LayoutTaskData>>) -> bool {
let mut rw_data = self.lock_rw_data(possibly_locked_rw_data);
let reflow_info = Reflow {
goal: ReflowGoal::ForDisplay,
page_clip_rect: MAX_RECT,
};
let mut layout_context = self.build_shared_layout_context(&*rw_data,
false,
None,
&self.url,
reflow_info.goal);
self.perform_post_style_recalc_layout_passes(&reflow_info,
&mut *rw_data,
&mut layout_context);
true
}
/// Receives and dispatches messages from other tasks.
fn handle_request_helper<'a>(&'a self,
request: Msg,
possibly_locked_rw_data: &mut Option<MutexGuard<'a,
LayoutTaskData>>)
-> bool {
match request {
Msg::AddStylesheet(sheet, mq) => {
self.handle_add_stylesheet(sheet, mq, possibly_locked_rw_data)
}
Msg::LoadStylesheet(url, mq, pending, link_element) => {
self.handle_load_stylesheet(url, mq, pending, link_element, possibly_locked_rw_data)
}
Msg::SetQuirksMode => self.handle_set_quirks_mode(possibly_locked_rw_data),
Msg::GetRPC(response_chan) => {
response_chan.send(box LayoutRPCImpl(self.rw_data.clone()) as
Box<LayoutRPC + Send>).unwrap();
},
Msg::Reflow(data) => {
profile(time::ProfilerCategory::LayoutPerform,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| self.handle_reflow(&*data, possibly_locked_rw_data));
},
Msg::TickAnimations => self.tick_all_animations(possibly_locked_rw_data),
Msg::SetVisibleRects(new_visible_rects) => {
self.set_visible_rects(new_visible_rects, possibly_locked_rw_data);
}
Msg::ReapLayoutData(dead_layout_data) => {
unsafe {
self.handle_reap_layout_data(dead_layout_data)
}
},
Msg::CollectReports(reports_chan) => {
self.collect_reports(reports_chan, possibly_locked_rw_data);
},
Msg::GetCurrentEpoch(sender) => {
let rw_data = self.lock_rw_data(possibly_locked_rw_data);
sender.send(rw_data.epoch).unwrap();
},
Msg::CreateLayoutTask(info) => {
self.create_layout_task(info)
}
Msg::PrepareToExit(response_chan) => {
self.prepare_to_exit(response_chan, possibly_locked_rw_data);
return false
},
Msg::ExitNow(exit_type) => {
debug!("layout: ExitNow received");
self.exit_now(possibly_locked_rw_data, exit_type);
return false
}
}
true
}
fn collect_reports<'a>(&'a self,
reports_chan: ReportsChan,
possibly_locked_rw_data: &mut Option<MutexGuard<'a, LayoutTaskData>>) {
let mut reports = vec![];
// FIXME(njn): Just measuring the display tree for now.
let rw_data = self.lock_rw_data(possibly_locked_rw_data);
let stacking_context = rw_data.stacking_context.as_ref();
reports.push(Report {
path: path![format!("url({})", self.url), "layout-task", "display-list"],
kind: ReportKind::ExplicitJemallocHeapSize,
size: stacking_context.map_or(0, |sc| sc.heap_size_of_children()),
});
// The LayoutTask has a context in TLS...
reports.push(Report {
path: path![format!("url({})", self.url), "layout-task", "local-context"],
kind: ReportKind::ExplicitJemallocHeapSize,
size: heap_size_of_local_context(),
});
// ... as do each of the LayoutWorkers, if present.
if let Some(ref traversal) = rw_data.parallel_traversal {
let sizes = traversal.heap_size_of_tls(heap_size_of_local_context);
for (i, size) in sizes.iter().enumerate() {
reports.push(Report {
path: path![format!("url({})", self.url),
format!("layout-worker-{}-local-context", i)],
kind: ReportKind::ExplicitJemallocHeapSize,
size: *size,
});
}
}
reports_chan.send(reports);
}
fn create_layout_task(&self, info: NewLayoutTaskInfo) {
LayoutTaskFactory::create(None::<&mut LayoutTask>,
info.id,
info.url.clone(),
info.is_parent,
info.layout_pair,
info.pipeline_port,
info.constellation_chan,
info.failure,
info.script_chan.clone(),
*info.paint_chan
.downcast::<OptionalIpcSender<LayoutToPaintMsg>>()
.unwrap(),
self.image_cache_task.clone(),
self.font_cache_task.clone(),
self.time_profiler_chan.clone(),
self.mem_profiler_chan.clone(),
info.layout_shutdown_chan);
}
/// Enters a quiescent state in which no new messages except for
/// `layout_interface::Msg::ReapLayoutData` will be processed until an `ExitNow` is
/// received. A pong is immediately sent on the given response channel.
fn prepare_to_exit<'a>(&'a self,
response_chan: Sender<()>,
possibly_locked_rw_data: &mut Option<MutexGuard<'a, LayoutTaskData>>) {
response_chan.send(()).unwrap();
loop {
match self.port.recv().unwrap() {
Msg::ReapLayoutData(dead_layout_data) => {
unsafe {
self.handle_reap_layout_data(dead_layout_data)
}
}
Msg::ExitNow(exit_type) => {
debug!("layout task is exiting...");
self.exit_now(possibly_locked_rw_data, exit_type);
break
}
Msg::CollectReports(_) => {
// Just ignore these messages at this point.
}
_ => {
panic!("layout: unexpected message received after `PrepareToExitMsg`")
}
}
}
}
/// Shuts down the layout task now. If there are any DOM nodes left, layout will now (safely)
/// crash.
fn exit_now<'a>(&'a self,
possibly_locked_rw_data: &mut Option<MutexGuard<'a, LayoutTaskData>>,
exit_type: PipelineExitType) {
let (response_chan, response_port) = ipc::channel().unwrap();
{
let mut rw_data = self.lock_rw_data(possibly_locked_rw_data);
if let Some(ref mut traversal) = (&mut *rw_data).parallel_traversal {
traversal.shutdown()
}
LayoutTask::return_rw_data(possibly_locked_rw_data, rw_data);
}
self.paint_chan.send(LayoutToPaintMsg::Exit(Some(response_chan), exit_type)).unwrap();
response_port.recv().unwrap()
}
fn handle_load_stylesheet<'a>(&'a self,
url: Url,
mq: MediaQueryList,
pending: PendingAsyncLoad,
responder: Box<StylesheetLoadResponder + Send>,
possibly_locked_rw_data:
&mut Option<MutexGuard<'a, LayoutTaskData>>) {
// TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding
let environment_encoding = UTF_8 as EncodingRef;
// TODO we don't really even need to load this if mq does not match
let (metadata, iter) = load_bytes_iter(pending);
let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s);
let final_url = metadata.final_url;
let sheet = Stylesheet::from_bytes_iter(iter,
final_url,
protocol_encoding_label,
Some(environment_encoding),
Origin::Author);
//TODO: mark critical subresources as blocking load as well (#5974)
self.script_chan.send(ConstellationControlMsg::StylesheetLoadComplete(self.id, url, responder)).unwrap();
self.handle_add_stylesheet(sheet, mq, possibly_locked_rw_data);
}
fn handle_add_stylesheet<'a>(&'a self,
sheet: Stylesheet,
mq: MediaQueryList,
possibly_locked_rw_data:
&mut Option<MutexGuard<'a, LayoutTaskData>>) {
// Find all font-face rules and notify the font cache of them.
// GWTODO: Need to handle unloading web fonts (when we handle unloading stylesheets!)
let mut rw_data = self.lock_rw_data(possibly_locked_rw_data);
if mq.evaluate(&rw_data.stylist.device) {
add_font_face_rules(&sheet, &rw_data.stylist.device, &self.font_cache_task);
rw_data.stylist.add_stylesheet(sheet);
}
LayoutTask::return_rw_data(possibly_locked_rw_data, rw_data);
}
/// Sets quirks mode for the document, causing the quirks mode stylesheet to be loaded.
fn handle_set_quirks_mode<'a>(&'a self,
possibly_locked_rw_data:
&mut Option<MutexGuard<'a, LayoutTaskData>>) {
let mut rw_data = self.lock_rw_data(possibly_locked_rw_data);
rw_data.stylist.add_quirks_mode_stylesheet();
LayoutTask::return_rw_data(possibly_locked_rw_data, rw_data);
}
fn try_get_layout_root(&self, node: LayoutNode) -> Option<FlowRef> {
let mut layout_data_ref = node.mutate_layout_data();
let layout_data =
match layout_data_ref.as_mut() {
None => return None,
Some(layout_data) => layout_data,
};
let result = layout_data.data.flow_construction_result.swap_out();
let mut flow = match result {
ConstructionResult::Flow(mut flow, abs_descendants) => {
// Note: Assuming that the root has display 'static' (as per
// CSS Section 9.3.1). Otherwise, if it were absolutely
// positioned, it would return a reference to itself in
// `abs_descendants` and would lead to a circular reference.
// Set Root as CB for any remaining absolute descendants.
flow.set_absolute_descendants(abs_descendants);
flow
}
_ => return None,
};
flow.mark_as_root();
Some(flow)
}
fn get_layout_root(&self, node: LayoutNode) -> FlowRef {
self.try_get_layout_root(node).expect("no layout root")
}
/// Performs layout constraint solving.
///
/// This corresponds to `Reflow()` in Gecko and `layout()` in WebKit/Blink and should be
/// benchmarked against those two. It is marked `#[inline(never)]` to aid profiling.
#[inline(never)]
fn solve_constraints<'a>(&self,
layout_root: &mut FlowRef,
shared_layout_context: &SharedLayoutContext) {
let _scope = layout_debug_scope!("solve_constraints");
sequential::traverse_flow_tree_preorder(layout_root, shared_layout_context);
}
/// Performs layout constraint solving in parallel.
///
/// This corresponds to `Reflow()` in Gecko and `layout()` in WebKit/Blink and should be
/// benchmarked against those two. It is marked `#[inline(never)]` to aid profiling.
#[inline(never)]
fn solve_constraints_parallel(&self,
traversal: &mut WorkQueue<SharedLayoutContext, WorkQueueData>,
layout_root: &mut FlowRef,
shared_layout_context: &SharedLayoutContext) {
let _scope = layout_debug_scope!("solve_constraints_parallel");
// NOTE: this currently computes borders, so any pruning should separate that
// operation out.
parallel::traverse_flow_tree_preorder(layout_root,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
shared_layout_context,
traversal);
}
/// Verifies that every node was either marked as a leaf or as a nonleaf in the flow tree.
/// This is only on in debug builds.
#[inline(never)]
#[cfg(debug)]
fn verify_flow_tree(&self, layout_root: &mut FlowRef) {
let mut traversal = traversal::FlowTreeVerification;
layout_root.traverse_preorder(&mut traversal);
}
#[cfg(not(debug))]
fn verify_flow_tree(&self, _: &mut FlowRef) {
}
fn process_node_geometry_request<'a>(&'a self,
requested_node: TrustedNodeAddress,
layout_root: &mut FlowRef,
rw_data: &mut RWGuard<'a>) {
let requested_node: OpaqueNode = OpaqueNodeMethods::from_script_node(requested_node);
let mut iterator = FragmentLocatingFragmentIterator::new(requested_node);
sequential::iterate_through_flow_tree_fragment_border_boxes(layout_root, &mut iterator);
rw_data.client_rect_response = iterator.client_rect;
}
// Compute the resolved value of property for a given (pseudo)element.
// Stores the result in rw_data.resolved_style_response.
// https://drafts.csswg.org/cssom/#resolved-value
fn process_resolved_style_request<'a>(&'a self,
requested_node: TrustedNodeAddress,
pseudo: &Option<PseudoElement>,
property: &Atom,
layout_root: &mut FlowRef,
rw_data: &mut RWGuard<'a>) {
// FIXME: Isolate this transmutation into a "bridge" module.
// FIXME(rust#16366): The following line had to be moved because of a
// rustc bug. It should be in the next unsafe block.
let node: LayoutJS<Node> = unsafe {
LayoutJS::from_trusted_node_address(requested_node)
};
let node: &LayoutNode = unsafe {
transmute(&node)
};
let layout_node = ThreadSafeLayoutNode::new(node);
let layout_node = match pseudo {
&Some(PseudoElement::Before) => layout_node.get_before_pseudo(),
&Some(PseudoElement::After) => layout_node.get_after_pseudo(),
_ => Some(layout_node)
};
let layout_node = match layout_node {
None => {
// The pseudo doesn't exist, return nothing. Chrome seems to query
// the element itself in this case, Firefox uses the resolved value.
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=29006
rw_data.resolved_style_response = None;
return;
}
Some(layout_node) => layout_node
};
let style = &*layout_node.style();
let positioned = match style.get_box().position {
position::computed_value::T::relative |
/*position::computed_value::T::sticky |*/
position::computed_value::T::fixed |
position::computed_value::T::absolute => true,
_ => false
};
//TODO: determine whether requested property applies to the element.
// eg. width does not apply to non-replaced inline elements.
// Existing browsers disagree about when left/top/right/bottom apply
// (Chrome seems to think they never apply and always returns resolved values).
// There are probably other quirks.
let applies = true;
// TODO: we will return neither the computed nor used value for margin and padding.
// Firefox returns blank strings for the computed value of shorthands,
// so this should be web-compatible.
match property.clone() {
atom!("margin-bottom") | atom!("margin-top") |
atom!("margin-left") | atom!("margin-right") |
atom!("padding-bottom") | atom!("padding-top") |
atom!("padding-left") | atom!("padding-right")
if applies && style.get_box().display != display::computed_value::T::none => {
let (margin_padding, side) = match *property {
atom!("margin-bottom") => (MarginPadding::Margin, Side::Bottom),
atom!("margin-top") => (MarginPadding::Margin, Side::Top),
atom!("margin-left") => (MarginPadding::Margin, Side::Left),
atom!("margin-right") => (MarginPadding::Margin, Side::Right),
atom!("padding-bottom") => (MarginPadding::Padding, Side::Bottom),
atom!("padding-top") => (MarginPadding::Padding, Side::Top),
atom!("padding-left") => (MarginPadding::Padding, Side::Left),
atom!("padding-right") => (MarginPadding::Padding, Side::Right),
_ => unreachable!()
};
let requested_node: OpaqueNode = OpaqueNodeMethods::from_script_node(requested_node);
let mut iterator =
MarginRetrievingFragmentBorderBoxIterator::new(requested_node,
side,
margin_padding,
style.writing_mode);
sequential::iterate_through_flow_tree_fragment_border_boxes(layout_root, &mut iterator);
rw_data.resolved_style_response = iterator.result.map(|r| r.to_css_string());
},
atom!("bottom") | atom!("top") | atom!("right") |
atom!("left") | atom!("width") | atom!("height")
if applies && positioned && style.get_box().display != display::computed_value::T::none => {
let layout_data = layout_node.borrow_layout_data();
let position = layout_data.as_ref().map(|layout_data| {
match layout_data.data.flow_construction_result {
ConstructionResult::Flow(ref flow_ref, _) =>
flow::base(flow_ref.deref()).stacking_relative_position,
// TODO search parents until we find node with a flow ref.
_ => ZERO_POINT
}
}).unwrap_or(ZERO_POINT);
let property = match *property {
atom!("bottom") => PositionProperty::Bottom,
atom!("top") => PositionProperty::Top,
atom!("left") => PositionProperty::Left,
atom!("right") => PositionProperty::Right,
atom!("width") => PositionProperty::Width,
atom!("height") => PositionProperty::Height,
_ => unreachable!()
};
let requested_node: OpaqueNode = OpaqueNodeMethods::from_script_node(requested_node);
let mut iterator =
PositionRetrievingFragmentBorderBoxIterator::new(requested_node,
property,
position);
sequential::iterate_through_flow_tree_fragment_border_boxes(layout_root, &mut iterator);
rw_data.resolved_style_response = iterator.result.map(|r| r.to_css_string());
},
// FIXME: implement used value computation for line-height
property => {
rw_data.resolved_style_response = style.computed_value_to_string(property.as_slice());
}
};
}
fn process_offset_parent_query<'a>(&'a self,
requested_node: TrustedNodeAddress,
layout_root: &mut FlowRef,
rw_data: &mut RWGuard<'a>) {
let requested_node: OpaqueNode = OpaqueNodeMethods::from_script_node(requested_node);
let mut iterator = ParentOffsetBorderBoxIterator::new(requested_node);
sequential::iterate_through_flow_tree_fragment_border_boxes(layout_root, &mut iterator);
let parent_info_index = iterator.parent_nodes.iter().rposition(|info| info.is_some());
match parent_info_index {
Some(parent_info_index) => {
let parent = iterator.parent_nodes[parent_info_index].as_ref().unwrap();
let origin = iterator.node_border_box.origin - parent.border_box.origin;
let size = iterator.node_border_box.size;
rw_data.offset_parent_response = OffsetParentResponse {
node_address: Some(parent.node_address.to_untrusted_node_address()),
rect: Rect::new(origin, size),
};
}
None => {
rw_data.offset_parent_response = OffsetParentResponse::empty();
}
}
}
fn compute_abs_pos_and_build_display_list<'a>(&'a self,
data: &Reflow,
layout_root: &mut FlowRef,
shared_layout_context: &mut SharedLayoutContext,
rw_data: &mut LayoutTaskData) {
let writing_mode = flow::base(&**layout_root).writing_mode;
profile(time::ProfilerCategory::LayoutDispListBuild,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| {
flow::mut_base(&mut **layout_root).stacking_relative_position =
LogicalPoint::zero(writing_mode).to_physical(writing_mode,
rw_data.screen_size);
flow::mut_base(&mut **layout_root).clip =
ClippingRegion::from_rect(&data.page_clip_rect);
match (&mut rw_data.parallel_traversal, opts::get().parallel_display_list_building) {
(&mut Some(ref mut traversal), true) => {
parallel::build_display_list_for_subtree(layout_root,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
shared_layout_context,
traversal);
}
_ => {
sequential::build_display_list_for_subtree(layout_root,
shared_layout_context);
}
}
if data.goal == ReflowGoal::ForDisplay {
debug!("Done building display list.");
let root_background_color = get_root_flow_background_color(&mut **layout_root);
let root_size = {
let root_flow = flow::base(&**layout_root);
root_flow.position.size.to_physical(root_flow.writing_mode)
};
let mut display_list = box DisplayList::new();
flow::mut_base(&mut **layout_root).display_list_building_result
.add_to(&mut *display_list);
let paint_layer = PaintLayer::new(layout_root.layer_id(0),
root_background_color,
ScrollPolicy::Scrollable);
let origin = Rect::new(Point2D::new(Au(0), Au(0)), root_size);
let stacking_context = Arc::new(StackingContext::new(display_list,
&origin,
&origin,
0,
filter::T::new(Vec::new()),
mix_blend_mode::T::normal,
Some(paint_layer),
Matrix4::identity(),
Matrix4::identity(),
true,
false));
if opts::get().dump_display_list {
println!("#### start printing display list.");
stacking_context.print("#".to_owned());
}
if opts::get().dump_display_list_json {
println!("{}", serde_json::to_string_pretty(&stacking_context).unwrap());
}
rw_data.stacking_context = Some(stacking_context.clone());
debug!("Layout done!");
rw_data.epoch.next();
self.paint_chan
.send(LayoutToPaintMsg::PaintInit(rw_data.epoch, stacking_context))
.unwrap();
}
});
}
/// The high-level routine that performs layout tasks.
fn handle_reflow<'a>(&'a self,
data: &ScriptReflow,
possibly_locked_rw_data: &mut Option<MutexGuard<'a, LayoutTaskData>>) {
// FIXME: Isolate this transmutation into a "bridge" module.
// FIXME(rust#16366): The following line had to be moved because of a
// rustc bug. It should be in the next unsafe block.
let mut node: LayoutJS<Node> = unsafe {
LayoutJS::from_trusted_node_address(data.document_root)
};
let node: &mut LayoutNode = unsafe {
transmute(&mut node)
};
debug!("layout: received layout request for: {}", self.url.serialize());
if log_enabled!(log::LogLevel::Debug) {
node.dump();
}
let mut rw_data = self.lock_rw_data(possibly_locked_rw_data);
let initial_viewport = data.window_size.initial_viewport;
let old_screen_size = rw_data.screen_size;
let current_screen_size = Size2D::new(Au::from_f32_px(initial_viewport.width.get()),
Au::from_f32_px(initial_viewport.height.get()));
rw_data.screen_size = current_screen_size;
// Handle conditions where the entire flow tree is invalid.
let screen_size_changed = current_screen_size != old_screen_size;
if screen_size_changed {
// Calculate the actual viewport as per DEVICE-ADAPT ยง 6
let device = Device::new(MediaType::Screen, initial_viewport);
rw_data.stylist.set_device(device);
if let Some(constraints) = rw_data.stylist.constrain_viewport() {
debug!("Viewport constraints: {:?}", constraints);
// other rules are evaluated against the actual viewport
rw_data.screen_size = Size2D::new(Au::from_f32_px(constraints.size.width.get()),
Au::from_f32_px(constraints.size.height.get()));
let device = Device::new(MediaType::Screen, constraints.size);
rw_data.stylist.set_device(device);
// let the constellation know about the viewport constraints
let ConstellationChan(ref constellation_chan) = rw_data.constellation_chan;
constellation_chan.send(ConstellationMsg::ViewportConstrained(
self.id, constraints)).unwrap();
}
}
// If the entire flow tree is invalid, then it will be reflowed anyhow.
let needs_dirtying = rw_data.stylist.update();
let needs_reflow = screen_size_changed && !needs_dirtying;
unsafe {
if needs_dirtying {
LayoutTask::dirty_all_nodes(node);
}
}
if needs_reflow {
if let Some(mut flow) = self.try_get_layout_root(*node) {
LayoutTask::reflow_all_nodes(&mut *flow);
}
}
// Create a layout context for use throughout the following passes.
let mut shared_layout_context = self.build_shared_layout_context(&*rw_data,
screen_size_changed,
Some(&node),
&self.url,
data.reflow_info.goal);
if node.is_dirty() || node.has_dirty_descendants() || rw_data.stylist.is_dirty() {
// Recalculate CSS styles and rebuild flows and fragments.
profile(time::ProfilerCategory::LayoutStyleRecalc,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| {
// Perform CSS selector matching and flow construction.
let rw_data = &mut *rw_data;
match rw_data.parallel_traversal {
None => {
sequential::traverse_dom_preorder(*node, &shared_layout_context);
}
Some(ref mut traversal) => {
parallel::traverse_dom_preorder(*node, &shared_layout_context, traversal);
}
}
});
// Retrieve the (possibly rebuilt) root flow.
rw_data.root_flow = Some(self.get_layout_root((*node).clone()));
// Kick off animations if any were triggered.
animation::process_new_animations(&mut *rw_data, self.id);
}
// Send new canvas renderers to the paint task
while let Ok((layer_id, renderer)) = self.canvas_layers_receiver.try_recv() {
// Just send if there's an actual renderer
self.paint_chan.send(LayoutToPaintMsg::CanvasLayer(layer_id, renderer)).unwrap();
}
// Perform post-style recalculation layout passes.
self.perform_post_style_recalc_layout_passes(&data.reflow_info,
&mut rw_data,
&mut shared_layout_context);
let mut root_flow = (*rw_data.root_flow.as_ref().unwrap()).clone();
match data.query_type {
ReflowQueryType::ContentBoxQuery(node) =>
process_content_box_request(node, &mut root_flow, &mut rw_data),
ReflowQueryType::ContentBoxesQuery(node) =>
process_content_boxes_request(node, &mut root_flow, &mut rw_data),
ReflowQueryType::NodeGeometryQuery(node) =>
self.process_node_geometry_request(node, &mut root_flow, &mut rw_data),
ReflowQueryType::ResolvedStyleQuery(node, ref pseudo, ref property) =>
self.process_resolved_style_request(node, pseudo, property, &mut root_flow, &mut rw_data),
ReflowQueryType::OffsetParentQuery(node) =>
self.process_offset_parent_query(node, &mut root_flow, &mut rw_data),
ReflowQueryType::NoQuery => {}
}
// Tell script that we're done.
//
// FIXME(pcwalton): This should probably be *one* channel, but we can't fix this without
// either select or a filtered recv() that only looks for messages of a given type.
data.script_join_chan.send(()).unwrap();
data.script_chan.send(ConstellationControlMsg::ReflowComplete(self.id, data.id)).unwrap();
}
fn set_visible_rects<'a>(&'a self,
new_visible_rects: Vec<(LayerId, Rect<Au>)>,
possibly_locked_rw_data: &mut Option<MutexGuard<'a, LayoutTaskData>>)
-> bool {
let mut rw_data = self.lock_rw_data(possibly_locked_rw_data);
// First, determine if we need to regenerate the display lists. This will happen if the
// layers have moved more than `DISPLAY_PORT_THRESHOLD_SIZE_FACTOR` away from their last
// positions.
let mut must_regenerate_display_lists = false;
let mut old_visible_rects = HashMap::with_hash_state(Default::default());
let inflation_amount =
Size2D::new(rw_data.screen_size.width * DISPLAY_PORT_THRESHOLD_SIZE_FACTOR,
rw_data.screen_size.height * DISPLAY_PORT_THRESHOLD_SIZE_FACTOR);
for &(ref layer_id, ref new_visible_rect) in &new_visible_rects {
match rw_data.visible_rects.get(layer_id) {
None => {
old_visible_rects.insert(*layer_id, *new_visible_rect);
}
Some(old_visible_rect) => {
old_visible_rects.insert(*layer_id, *old_visible_rect);
if !old_visible_rect.inflate(inflation_amount.width, inflation_amount.height)
.intersects(new_visible_rect) {
must_regenerate_display_lists = true;
}
}
}
}
if !must_regenerate_display_lists {
// Update `visible_rects` in case there are new layers that were discovered.
rw_data.visible_rects = Arc::new(old_visible_rects);
return true
}
debug!("regenerating display lists!");
for &(ref layer_id, ref new_visible_rect) in &new_visible_rects {
old_visible_rects.insert(*layer_id, *new_visible_rect);
}
rw_data.visible_rects = Arc::new(old_visible_rects);
// Regenerate the display lists.
let reflow_info = Reflow {
goal: ReflowGoal::ForDisplay,
page_clip_rect: MAX_RECT,
};
let mut layout_context = self.build_shared_layout_context(&*rw_data,
false,
None,
&self.url,
reflow_info.goal);
self.perform_post_main_layout_passes(&reflow_info, &mut *rw_data, &mut layout_context);
true
}
fn tick_all_animations<'a>(&'a self,
possibly_locked_rw_data: &mut Option<MutexGuard<'a,
LayoutTaskData>>) {
let mut rw_data = self.lock_rw_data(possibly_locked_rw_data);
animation::tick_all_animations(self, &mut rw_data)
}
pub fn tick_animations<'a>(&'a self, rw_data: &mut LayoutTaskData) {
let reflow_info = Reflow {
goal: ReflowGoal::ForDisplay,
page_clip_rect: MAX_RECT,
};
let mut layout_context = self.build_shared_layout_context(&*rw_data,
false,
None,
&self.url,
reflow_info.goal);
{
// Perform an abbreviated style recalc that operates without access to the DOM.
let mut root_flow = (*rw_data.root_flow.as_ref().unwrap()).clone();
let animations = &*rw_data.running_animations;
profile(time::ProfilerCategory::LayoutStyleRecalc,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| animation::recalc_style_for_animations(root_flow.deref_mut(), animations));
}
self.perform_post_style_recalc_layout_passes(&reflow_info,
&mut *rw_data,
&mut layout_context);
}
fn perform_post_style_recalc_layout_passes<'a>(&'a self,
data: &Reflow,
rw_data: &mut LayoutTaskData,
layout_context: &mut SharedLayoutContext) {
let mut root_flow = (*rw_data.root_flow.as_ref().unwrap()).clone();
profile(time::ProfilerCategory::LayoutRestyleDamagePropagation,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| {
if opts::get().nonincremental_layout || root_flow.deref_mut()
.compute_layout_damage()
.contains(REFLOW_ENTIRE_DOCUMENT) {
root_flow.deref_mut().reflow_entire_document()
}
});
// Verification of the flow tree, which ensures that all nodes were either marked as leaves
// or as non-leaves. This becomes a no-op in release builds. (It is inconsequential to
// memory safety but is a useful debugging tool.)
self.verify_flow_tree(&mut root_flow);
if opts::get().trace_layout {
layout_debug::begin_trace(root_flow.clone());
}
// Resolve generated content.
profile(time::ProfilerCategory::LayoutGeneratedContent,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| sequential::resolve_generated_content(&mut root_flow, &layout_context));
// Perform the primary layout passes over the flow tree to compute the locations of all
// the boxes.
profile(time::ProfilerCategory::LayoutMain,
self.profiler_metadata(),
self.time_profiler_chan.clone(),
|| {
match rw_data.parallel_traversal {
None => {
// Sequential mode.
self.solve_constraints(&mut root_flow, &layout_context)
}
Some(ref mut parallel) => {
// Parallel mode.
self.solve_constraints_parallel(parallel,
&mut root_flow,
&mut *layout_context);
}
}
});
self.perform_post_main_layout_passes(data, rw_data, layout_context);
}
fn perform_post_main_layout_passes<'a>(&'a self,
data: &Reflow,
rw_data: &mut LayoutTaskData,
layout_context: &mut SharedLayoutContext) {
// Build the display list if necessary, and send it to the painter.
let mut root_flow = (*rw_data.root_flow.as_ref().unwrap()).clone();
self.compute_abs_pos_and_build_display_list(data,
&mut root_flow,
&mut *layout_context,
rw_data);
self.first_reflow.set(false);
if opts::get().trace_layout {
layout_debug::end_trace();
}
if opts::get().dump_flow_tree {
root_flow.dump();
}
rw_data.generation += 1;
}
unsafe fn dirty_all_nodes(node: &mut LayoutNode) {
for node in node.traverse_preorder() {
// TODO(cgaebel): mark nodes which are sensitive to media queries as
// "changed":
// > node.set_changed(true);
node.set_dirty(true);
node.set_dirty_siblings(true);
node.set_dirty_descendants(true);
}
}
fn reflow_all_nodes(flow: &mut Flow) {
debug!("reflowing all nodes!");
flow::mut_base(flow).restyle_damage.insert(REFLOW | REPAINT);
for child in flow::child_iter(flow) {
LayoutTask::reflow_all_nodes(child);
}
}
/// Handles a message to destroy layout data. Layout data must be destroyed on *this* task
/// because the struct type is transmuted to a different type on the script side.
unsafe fn handle_reap_layout_data(&self, layout_data: LayoutData) {
let layout_data_wrapper: LayoutDataWrapper = transmute(layout_data);
layout_data_wrapper.remove_compositor_layers(self.constellation_chan.clone());
}
/// Returns profiling information which is passed to the time profiler.
fn profiler_metadata(&self) -> ProfilerMetadata {
Some((&self.url,
if self.is_iframe {
TimerMetadataFrameType::IFrame
} else {
TimerMetadataFrameType::RootWindow
},
if self.first_reflow.get() {
TimerMetadataReflowType::FirstReflow
} else {
TimerMetadataReflowType::Incremental
}))
}
}
struct FragmentLocatingFragmentIterator {
node_address: OpaqueNode,
client_rect: Rect<i32>,
}
impl FragmentLocatingFragmentIterator {
fn new(node_address: OpaqueNode) -> FragmentLocatingFragmentIterator {
FragmentLocatingFragmentIterator {
node_address: node_address,
client_rect: Rect::zero()
}
}
}
struct ParentBorderBoxInfo {
node_address: OpaqueNode,
border_box: Rect<Au>,
}
struct ParentOffsetBorderBoxIterator {
node_address: OpaqueNode,
last_level: i32,
has_found_node: bool,
node_border_box: Rect<Au>,
parent_nodes: Vec<Option<ParentBorderBoxInfo>>,
}
impl ParentOffsetBorderBoxIterator {
fn new(node_address: OpaqueNode) -> ParentOffsetBorderBoxIterator {
ParentOffsetBorderBoxIterator {
node_address: node_address,
last_level: -1,
has_found_node: false,
node_border_box: Rect::zero(),
parent_nodes: Vec::new(),
}
}
}
impl FragmentBorderBoxIterator for FragmentLocatingFragmentIterator {
fn process(&mut self, fragment: &Fragment, _: i32, border_box: &Rect<Au>) {
let style_structs::Border {
border_top_width: top_width,
border_right_width: right_width,
border_bottom_width: bottom_width,
border_left_width: left_width,
..
} = *fragment.style.get_border();
self.client_rect.origin.y = top_width.to_px();
self.client_rect.origin.x = left_width.to_px();
self.client_rect.size.width = (border_box.size.width - left_width - right_width).to_px();
self.client_rect.size.height = (border_box.size.height - top_width - bottom_width).to_px();
}
fn should_process(&mut self, fragment: &Fragment) -> bool {
fragment.node == self.node_address
}
}
// https://drafts.csswg.org/cssom-view/#extensions-to-the-htmlelement-interface
impl FragmentBorderBoxIterator for ParentOffsetBorderBoxIterator {
fn process(&mut self, fragment: &Fragment, level: i32, border_box: &Rect<Au>) {
if fragment.node == self.node_address {
// Found the fragment in the flow tree that matches the
// DOM node being looked for.
self.has_found_node = true;
self.node_border_box = *border_box;
// offsetParent returns null if the node is fixed.
if fragment.style.get_box().position == computed_values::position::T::fixed {
self.parent_nodes.clear();
}
} else if level > self.last_level {
// TODO(gw): Is there a less fragile way of checking whether this
// fragment is the body element, rather than just checking that
// the parent nodes stack contains the root node only?
let is_body_element = self.parent_nodes.len() == 1;
let is_valid_parent = match (is_body_element,
fragment.style.get_box().position,
&fragment.specific) {
// Spec says it's valid if any of these are true:
// 1) Is the body element
// 2) Is static position *and* is a table or table cell
// 3) Is not static position
(true, _, _) |
(false, computed_values::position::T::static_, &SpecificFragmentInfo::Table) |
(false, computed_values::position::T::static_, &SpecificFragmentInfo::TableCell) |
(false, computed_values::position::T::absolute, _) |
(false, computed_values::position::T::relative, _) |
(false, computed_values::position::T::fixed, _) => true,
// Otherwise, it's not a valid parent
(false, computed_values::position::T::static_, _) => false,
};
let parent_info = if is_valid_parent {
Some(ParentBorderBoxInfo {
border_box: *border_box,
node_address: fragment.node,
})
} else {
None
};
self.parent_nodes.push(parent_info);
} else if level < self.last_level {
self.parent_nodes.pop();
}
}
fn should_process(&mut self, _: &Fragment) -> bool {
!self.has_found_node
}
}
// The default computed value for background-color is transparent (see
// http://dev.w3.org/csswg/css-backgrounds/#background-color). However, we
// need to propagate the background color from the root HTML/Body
// element (http://dev.w3.org/csswg/css-backgrounds/#special-backgrounds) if
// it is non-transparent. The phrase in the spec "If the canvas background
// is not opaque, what shows through is UA-dependent." is handled by rust-layers
// clearing the frame buffer to white. This ensures that setting a background
// color on an iframe element, while the iframe content itself has a default
// transparent background color is handled correctly.
fn get_root_flow_background_color(flow: &mut Flow) -> AzColor {
if !flow.is_block_like() {
return color::transparent()
}
let block_flow = flow.as_block();
let kid = match block_flow.base.children.iter_mut().next() {
None => return color::transparent(),
Some(kid) => kid,
};
if !kid.is_block_like() {
return color::transparent()
}
let kid_block_flow = kid.as_block();
kid_block_flow.fragment
.style
.resolve_color(kid_block_flow.fragment.style.get_background().background_color)
.to_gfx_color()
}
| mpl-2.0 |
Enterprise-Content-Management/infoarchive-sip-sdk | core/src/main/java/com/opentext/ia/sdk/dto/Contents.java | 184 | /*
* Copyright (c) 2016-2017 by OpenText Corporation. All Rights Reserved.
*/
package com.opentext.ia.sdk.dto;
public class Contents extends ItemContainer<NamedLinkContainer> {
}
| mpl-2.0 |
Distrotech/libpwd | src/lib/WP6GraphicsBoxStylePacket.cpp | 9380 | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* libwpd
* Version: MPL 2.0 / LGPLv2.1+
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Major Contributor(s):
* Copyright (C) 2007 Fridrich Strba (fridrich.strba@bluewin.ch)
* Copyright (C) 2007 Novell Inc. (http://www.novell.com)
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms
* of the GNU Lesser General Public License Version 2.1 or later
* (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are
* applicable instead of those above.
*
* For further information visit http://libwpd.sourceforge.net
*/
/* "This product is not manufactured, approved, or supported by
* Corel Corporation or Corel Corporation Limited."
*/
#include <string.h>
#include "WP6GraphicsBoxStylePacket.h"
#include "WP6Parser.h"
WP6GraphicsBoxStylePacket::WP6GraphicsBoxStylePacket(WPXInputStream *input, WPXEncryption *encryption, int /* id */, uint32_t dataOffset, uint32_t dataSize):
WP6PrefixDataPacket(input, encryption),
m_isLibraryStyle(false),
m_boxStyleName(),
m_generalPositioningFlags(0x00),
m_horizontalPositioningFlags(0x00),
m_horizontalOffset(0),
m_leftColumn(0x00),
m_rightColumn(0x00),
m_verticalPositioningFlags(0x00),
m_verticalOffset(0),
m_widthFlags(0x00),
m_width(0),
m_heightFlags(0x00),
m_height(0),
m_contentType(0x00),
m_contentHAlign(0),
m_contentVAlign(0),
m_contentPreserveAspectRatio(true),
m_nativeWidth(0),
m_nativeHeight(0)
{
_read(input, encryption, dataOffset, dataSize);
}
WP6GraphicsBoxStylePacket::~WP6GraphicsBoxStylePacket()
{
}
void WP6GraphicsBoxStylePacket::_readContents(WPXInputStream *input, WPXEncryption *encryption)
{
WPD_DEBUG_MSG(("WP6GraphicsBoxStylePacket position: 0x%.8x\n", (unsigned)input->tell()));
uint16_t tmpNumChildIDs = readU16(input, encryption);
input->seek(tmpNumChildIDs * 2, WPX_SEEK_CUR);
uint16_t tmpSizeOfBoxData = readU16(input, encryption);
long tmpStartOfBoxData = input->tell();
// Reading the box name/library data
uint16_t tmpSizeOfBoxNameLibraryData = readU16(input, encryption);
long tmpBoxNameLibraryDataPosition = input->tell();
input->seek(1, WPX_SEEK_CUR);
m_isLibraryStyle = ((readU8(input, encryption) & 0x01) != 0x00);
int16_t tmpBoxNameLength = (int16_t)readU16(input, encryption);
if (tmpBoxNameLength > 0)
{
for (int16_t i = 0; i < (tmpBoxNameLength/2); i++)
{
uint16_t charWord = readU16(input, encryption);
uint8_t characterSet = (uint8_t)((charWord >> 8) & 0x00FF);
uint8_t character = (uint8_t)(charWord & 0xFF);
if (character == 0x00 && characterSet == 0x00)
break;
const uint32_t *chars;
int len = extendedCharacterWP6ToUCS4(character, characterSet, &chars);
for (int j = 0; j < len; j++)
appendUCS4(m_boxStyleName, (uint32_t)chars[j]);
}
}
else
{
switch (tmpBoxNameLength)
{
case 0:
m_boxStyleName = "Figure Box";
break;
case -1:
m_boxStyleName = "Table Box";
break;
case -2:
m_boxStyleName = "Text Box";
break;
case -3:
m_boxStyleName = "User Box";
break;
case -4:
m_boxStyleName = "Equation Box";
break;
case -5:
m_boxStyleName = "Button Box";
break;
default:
break;
}
}
WPD_DEBUG_MSG(("WP6GraphicsBoxStylePacket -- Box Style name: %s\n", m_boxStyleName.cstr()));
input->seek(tmpSizeOfBoxNameLibraryData + tmpBoxNameLibraryDataPosition, WPX_SEEK_SET);
// Skipping box counter data
uint16_t tmpSizeOfBoxCounterData = readU16(input, encryption);
WPD_DEBUG_MSG(("WP6GraphicsBoxStylePacket -- Box counter data\n"));
input->seek(tmpSizeOfBoxCounterData, WPX_SEEK_CUR);
// Reading Box positioning data
uint16_t tmpSizeOfBoxPositioningData = readU16(input, encryption);
long tmpBoxPositioningDataPosition = input->tell();
input->seek(1, WPX_SEEK_CUR);
m_generalPositioningFlags = readU8(input, encryption);
WPD_DEBUG_MSG(("WP6GraphicsBoxStylePacket -- Box Positioning data (general positioning flags: 0x%.2x)\n", m_generalPositioningFlags));
WPD_DEBUG_MSG(("WP6GraphicsBoxStylePacket -- Box Positioning data (anchor value: %i) (page offset bit: %i) (overlap flag: %i) (auto flag: %i)\n",
m_generalPositioningFlags & 0x07, (m_generalPositioningFlags & 0x08) >> 3, (m_generalPositioningFlags & 0x10) >> 4, (m_generalPositioningFlags & 0x20) >> 5));
m_horizontalPositioningFlags = readU8(input, encryption);
WPD_DEBUG_MSG(("WP6GraphicsBoxStylePacket -- Box Horizontal position (horizontal alignment type: %i) (horizontal alignment: %i)\n",
m_horizontalPositioningFlags & 0x03, (m_horizontalPositioningFlags & 0x1C) >> 2));
m_horizontalOffset = (int16_t)readU16(input, encryption);
WPD_DEBUG_MSG(("WP6GraphicsBoxStylePacket -- Box Horizontal Offset (%i)\n", m_horizontalOffset));
m_leftColumn = readU8(input, encryption);
m_rightColumn = readU8(input, encryption);
WPD_DEBUG_MSG(("WP6GraphicsBoxStylePacket -- Box Horizontal position (between columns %i and %i)\n", m_leftColumn, m_rightColumn));
m_verticalPositioningFlags = readU8(input, encryption);
WPD_DEBUG_MSG(("WP6GraphicsBoxStylePacket -- Box Vertical position (vertical alignment type: %i) (vertical alignment: %i) (vertical effect: %i)\n",
m_verticalPositioningFlags & 0x03, (m_verticalPositioningFlags & 0x1C) >> 2, (m_verticalPositioningFlags & 0x20) >> 5));
m_verticalOffset = (int16_t)readU16(input, encryption);
WPD_DEBUG_MSG(("WP6GraphicsBoxStylePacket -- Box Vertical Offset (%i)\n", m_verticalOffset));
m_widthFlags = readU8(input, encryption) & 0x01;
WPD_DEBUG_MSG(("WP6GraphicsBoxStylePacket -- Box Width Flags: 0x%.2x\n", m_widthFlags));
m_width = readU16(input, encryption);
WPD_DEBUG_MSG(("WP6GraphicsBoxStylePacket -- Box Width: %i\n", m_width));
m_heightFlags = readU8(input, encryption) & 0x01;
WPD_DEBUG_MSG(("WP6GraphicsBoxStylePacket -- Box Height Flags: 0x%.2x\n", m_heightFlags));
m_height = readU16(input, encryption);
WPD_DEBUG_MSG(("WP6GraphicsBoxStylePacket -- Box Height: %i\n", m_height));
input->seek(tmpSizeOfBoxPositioningData + tmpBoxPositioningDataPosition, WPX_SEEK_SET);
// Reading box content data
uint16_t tmpSizeOfBoxContentData = readU16(input, encryption);
long tmpBoxContentDataPosition = input->tell();
input->seek(1, WPX_SEEK_CUR);
m_contentType = readU8(input, encryption);
uint8_t tmpContentAlignFlags = readU8(input, encryption);
m_contentHAlign = tmpContentAlignFlags & 0x03;
m_contentVAlign = (uint8_t)((tmpContentAlignFlags & 0xC0) >> 2);
m_contentPreserveAspectRatio = ((tmpContentAlignFlags & 0x10) == 0x00);
WPD_DEBUG_MSG(("WP6GraphicsBoxStylePacket -- Box Content Type (%i)\n", m_contentType));
WPD_DEBUG_MSG(("WP6GraphicsBoxStylePacket -- Box Content Alignment (horizontal: 0x%.2x) (vertical: 0x%.2x) (preserve aspect ratio: %s)\n",
m_contentHAlign, m_contentVAlign, m_contentPreserveAspectRatio ? "true" : "false"));
switch (m_contentType)
{
case 0x03:
{
uint16_t tmpGraphicsRenderingInfoSize = readU16(input, encryption);
long tmpGraphicsRenderingInfoBegin = input->tell();
if (0x01 == (readU8(input, encryption) & 0xFF))
{
m_nativeWidth = readU16(input, encryption);
m_nativeHeight = readU16(input, encryption);
}
else
input->seek(4, WPX_SEEK_CUR);
input->seek(tmpGraphicsRenderingInfoSize + tmpGraphicsRenderingInfoBegin, WPX_SEEK_CUR);
}
break;
default:
break;
}
input->seek(tmpSizeOfBoxContentData + tmpBoxContentDataPosition, WPX_SEEK_SET);
// Reading box caption data
uint16_t tmpSizeOfBoxCaptionData = readU16(input, encryption);
long tmpBoxCaptionDataPosition = input->tell();
input->seek(tmpSizeOfBoxCaptionData + tmpBoxCaptionDataPosition, WPX_SEEK_SET);
// Reading box border data
uint16_t tmpSizeOfBoxBorderData = readU16(input, encryption);
long tmpBoxBorderDataPosition = input->tell();
input->seek(tmpSizeOfBoxBorderData + tmpBoxBorderDataPosition, WPX_SEEK_SET);
// Reading box fill data
uint16_t tmpSizeOfBoxFillData = readU16(input, encryption);
long tmpBoxFillDataPosition = input->tell();
input->seek(tmpSizeOfBoxFillData + tmpBoxFillDataPosition, WPX_SEEK_SET);
// Reading box wrapping data
uint16_t tmpSizeOfBoxWrappingData = readU16(input, encryption);
long tmpBoxWrappingDataPosition = input->tell();
input->seek(tmpSizeOfBoxWrappingData + tmpBoxWrappingDataPosition, WPX_SEEK_SET);
// Reading box hypertext data
uint16_t tmpSizeOfBoxHypertextData = readU16(input, encryption);
long tmpBoxHypertextDataPosition = input->tell();
input->seek(tmpSizeOfBoxHypertextData + tmpBoxHypertextDataPosition, WPX_SEEK_SET);
// Dumping hexadecimally the rest of the packet
long tmpCurrentPosition = input->tell();
if ((long)tmpStartOfBoxData + (long)tmpSizeOfBoxData - tmpCurrentPosition < 0)
throw FileException();
#ifdef DEBUG
for (unsigned i = 0; i < tmpStartOfBoxData + tmpSizeOfBoxData - tmpCurrentPosition; i++)
{
if (i % 8 == 0)
WPD_DEBUG_MSG(("\n "));
WPD_DEBUG_MSG(("%.2x ", readU8(input, encryption)));
}
#else
if (input->seek(tmpStartOfBoxData + tmpSizeOfBoxData, WPX_SEEK_SET))
throw FileException();
#endif
}
/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */
| mpl-2.0 |
ricardclau/packer | vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-06-01/subscriptions/subscriptions.go | 10363 | package subscriptions
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// Client is the all resource groups and resources exist within subscriptions. These operation enable you get
// information about your subscriptions and tenants. A tenant is a dedicated instance of Azure Active Directory (Azure
// AD) for your organization.
type Client struct {
BaseClient
}
// NewClient creates an instance of the Client client.
func NewClient() Client {
return NewClientWithBaseURI(DefaultBaseURI)
}
// NewClientWithBaseURI creates an instance of the Client client using a custom endpoint. Use this when interacting
// with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewClientWithBaseURI(baseURI string) Client {
return Client{NewWithBaseURI(baseURI)}
}
// Get gets details about a specified subscription.
// Parameters:
// subscriptionID - the ID of the target subscription.
func (client Client) Get(ctx context.Context, subscriptionID string) (result Subscription, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/Client.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.GetPreparer(ctx, subscriptionID)
if err != nil {
err = autorest.NewErrorWithError(err, "subscriptions.Client", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "subscriptions.Client", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "subscriptions.Client", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client Client) GetPreparer(ctx context.Context, subscriptionID string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", subscriptionID),
}
const APIVersion = "2016-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client Client) GetSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client Client) GetResponder(resp *http.Response) (result Subscription, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List gets all subscriptions for a tenant.
func (client Client) List(ctx context.Context) (result ListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/Client.List")
defer func() {
sc := -1
if result.lr.Response.Response != nil {
sc = result.lr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "subscriptions.Client", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.lr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "subscriptions.Client", "List", resp, "Failure sending request")
return
}
result.lr, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "subscriptions.Client", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client Client) ListPreparer(ctx context.Context) (*http.Request, error) {
const APIVersion = "2016-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/subscriptions"),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client Client) ListSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client Client) ListResponder(resp *http.Response) (result ListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listNextResults retrieves the next set of results, if any.
func (client Client) listNextResults(ctx context.Context, lastResults ListResult) (result ListResult, err error) {
req, err := lastResults.listResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "subscriptions.Client", "listNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "subscriptions.Client", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "subscriptions.Client", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client Client) ListComplete(ctx context.Context) (result ListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/Client.List")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.List(ctx)
return
}
// ListLocations this operation provides all the locations that are available for resource providers; however, each
// resource provider may support a subset of this list.
// Parameters:
// subscriptionID - the ID of the target subscription.
func (client Client) ListLocations(ctx context.Context, subscriptionID string) (result LocationListResult, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/Client.ListLocations")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.ListLocationsPreparer(ctx, subscriptionID)
if err != nil {
err = autorest.NewErrorWithError(err, "subscriptions.Client", "ListLocations", nil, "Failure preparing request")
return
}
resp, err := client.ListLocationsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "subscriptions.Client", "ListLocations", resp, "Failure sending request")
return
}
result, err = client.ListLocationsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "subscriptions.Client", "ListLocations", resp, "Failure responding to request")
}
return
}
// ListLocationsPreparer prepares the ListLocations request.
func (client Client) ListLocationsPreparer(ctx context.Context, subscriptionID string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", subscriptionID),
}
const APIVersion = "2016-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/locations", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListLocationsSender sends the ListLocations request. The method will close the
// http.Response Body if it receives an error.
func (client Client) ListLocationsSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListLocationsResponder handles the response to the ListLocations request. The method always
// closes the http.Response Body.
func (client Client) ListLocationsResponder(resp *http.Response) (result LocationListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| mpl-2.0 |
digidotcom/xbeewificloudkit | karma/karma-unit.tpl.js | 2096 | module.exports = function ( karma ) {
karma.configure({
/**
* From where to look for files, starting with the location of this file.
*/
basePath: '../../',
/**
* This is the list of file patterns to load into the browser during testing.
*/
files: [
<% scripts.forEach( function ( file ) { %>'<%= file %>',
<% }); %>
'src/**/*.js',
'src/**/*.coffee',
],
frameworks: [ 'jasmine' ],
plugins: [ 'karma-jasmine', 'karma-firefox-launcher', 'karma-chrome-launcher', 'karma-phantomjs-launcher', 'karma-coffee-preprocessor' , 'karma-junit-reporter', 'karma-coverage'],
preprocessors: {
'**/*.coffee': 'coffee',
'src/**/!(*.spec).js': 'coverage'
},
/**
* How to report, by default.
*/
//reporters: 'dots',
reporters: ['progress', 'junit', 'coverage'],
junitReporter: {
outputFile: 'test-reports/frontend.xml',
suite: ''
},
coverageReporter: {
type : 'html',
dir : 'test-reports/'
},
/**
* On which port should the browser connect, on which port is the test runner
* operating, and what is the URL path for the browser to use.
*/
port: 9018,
runnerPort: 9100,
urlRoot: '/',
/**
* Disable file watching by default.
*/
autoWatch: false,
/**
* The list of browsers to launch to test on. This includes only "Firefox" by
* default, but other browser names include:
* Chrome, ChromeCanary, Firefox, Opera, Safari, PhantomJS
*
* Note that you can also use the executable name of the browser, like "chromium"
* or "firefox", but that these vary based on your operating system.
*
* You may also leave this blank and manually navigate your browser to
* http://localhost:9018/ when you're running tests. The window/tab can be left
* open and the tests will automatically occur there during the build. This has
* the aesthetic advantage of not launching a browser every time you save.
*/
browsers: [
'PhantomJS'
]
});
};
| mpl-2.0 |
openMF/mifosx-e2e-testing | browsermob-proxy/src/main/java/org/browsermob/proxy/jetty/log/LogSink.java | 1991 | // ========================================================================
// Copyright (c) 1997 MortBay Consulting, Sydney
// $Id: LogSink.java,v 1.1 2004/06/04 21:37:20 gregwilkins Exp $
// ========================================================================
package org.browsermob.proxy.jetty.log;
import org.browsermob.proxy.jetty.util.LifeCycle;
import java.io.Serializable;
// TODO: Auto-generated Javadoc
/* ------------------------------------------------------------ */
/**
* A Log sink. This class represents both a concrete or abstract sink of Log
* data. The default implementation logs to a PrintWriter, but derived
* implementations may log to files, syslog, or other logging APIs.
*
*
* @version $Id: LogSink.java,v 1.1 2004/06/04 21:37:20 gregwilkins Exp $
* @author Greg Wilkins (gregw)
*/
public interface LogSink extends LifeCycle, Serializable {
/* ------------------------------------------------------------ */
/**
* Sets the log impl.
*
* @param impl
* the new log impl
*/
public void setLogImpl(LogImpl impl);
/* ------------------------------------------------------------ */
/**
* Log a message. This method formats the log information as a string and
* calls log(String). It should only be specialized by a derived
* implementation if the format of the logged messages is to be changed.
*
* @param tag
* Tag for type of log
* @param msg
* The message
* @param frame
* The frame that generated the message.
* @param time
* The time stamp of the message.
*/
public void log(String tag, Object msg, Frame frame, long time);
/* ------------------------------------------------------------ */
/**
* Log a message. The formatted log string is written to the log sink. The
* default implementation writes the message to a PrintWriter.
*
* @param formattedLog
* the formatted log
*/
public void log(String formattedLog);
};
| mpl-2.0 |
pvandervelde/packer | builder/hyperv/iso/builder.go | 17473 | package iso
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"strings"
hypervcommon "github.com/hashicorp/packer/builder/hyperv/common"
"github.com/hashicorp/packer/common"
powershell "github.com/hashicorp/packer/common/powershell"
"github.com/hashicorp/packer/common/powershell/hyperv"
"github.com/hashicorp/packer/helper/communicator"
"github.com/hashicorp/packer/helper/config"
"github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/template/interpolate"
"github.com/mitchellh/multistep"
)
const (
DefaultDiskSize = 40 * 1024 // ~40GB
MinDiskSize = 256 // 256MB
MaxDiskSize = 64 * 1024 * 1024 // 64TB
DefaultRamSize = 1 * 1024 // 1GB
MinRamSize = 32 // 32MB
MaxRamSize = 32 * 1024 // 32GB
MinNestedVirtualizationRamSize = 4 * 1024 // 4GB
LowRam = 256 // 256MB
DefaultUsername = ""
DefaultPassword = ""
)
// Builder implements packer.Builder and builds the actual Hyperv
// images.
type Builder struct {
config Config
runner multistep.Runner
}
type Config struct {
common.PackerConfig `mapstructure:",squash"`
common.HTTPConfig `mapstructure:",squash"`
common.ISOConfig `mapstructure:",squash"`
common.FloppyConfig `mapstructure:",squash"`
hypervcommon.OutputConfig `mapstructure:",squash"`
hypervcommon.SSHConfig `mapstructure:",squash"`
hypervcommon.RunConfig `mapstructure:",squash"`
hypervcommon.ShutdownConfig `mapstructure:",squash"`
// The size, in megabytes, of the hard disk to create for the VM.
// By default, this is 130048 (about 127 GB).
DiskSize uint `mapstructure:"disk_size"`
// The size, in megabytes, of the computer memory in the VM.
// By default, this is 1024 (about 1 GB).
RamSize uint `mapstructure:"ram_size"`
//
SecondaryDvdImages []string `mapstructure:"secondary_iso_images"`
// Should integration services iso be mounted
GuestAdditionsMode string `mapstructure:"guest_additions_mode"`
// The path to the integration services iso
GuestAdditionsPath string `mapstructure:"guest_additions_path"`
// This is the name of the new virtual machine.
// By default this is "packer-BUILDNAME", where "BUILDNAME" is the name of the build.
VMName string `mapstructure:"vm_name"`
BootCommand []string `mapstructure:"boot_command"`
SwitchName string `mapstructure:"switch_name"`
SwitchVlanId string `mapstructure:"switch_vlan_id"`
VlanId string `mapstructure:"vlan_id"`
Cpu uint `mapstructure:"cpu"`
Generation uint `mapstructure:"generation"`
EnableMacSpoofing bool `mapstructure:"enable_mac_spoofing"`
EnableDynamicMemory bool `mapstructure:"enable_dynamic_memory"`
EnableSecureBoot bool `mapstructure:"enable_secure_boot"`
EnableVirtualizationExtensions bool `mapstructure:"enable_virtualization_extensions"`
TempPath string `mapstructure:"temp_path"`
// A separate path can be used for storing the VM's disk image. The purpose is to enable
// reading and writing to take place on different physical disks (read from VHD temp path
// write to regular temp path while exporting the VM) to eliminate a single-disk bottleneck.
VhdTempPath string `mapstructure:"vhd_temp_path"`
Communicator string `mapstructure:"communicator"`
SkipCompaction bool `mapstructure:"skip_compaction"`
ctx interpolate.Context
}
// Prepare processes the build configuration parameters.
func (b *Builder) Prepare(raws ...interface{}) ([]string, error) {
err := config.Decode(&b.config, &config.DecodeOpts{
Interpolate: true,
InterpolateContext: &b.config.ctx,
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{
"boot_command",
},
},
}, raws...)
if err != nil {
return nil, err
}
// Accumulate any errors and warnings
var errs *packer.MultiError
warnings := make([]string, 0)
isoWarnings, isoErrs := b.config.ISOConfig.Prepare(&b.config.ctx)
warnings = append(warnings, isoWarnings...)
errs = packer.MultiErrorAppend(errs, isoErrs...)
errs = packer.MultiErrorAppend(errs, b.config.FloppyConfig.Prepare(&b.config.ctx)...)
errs = packer.MultiErrorAppend(errs, b.config.HTTPConfig.Prepare(&b.config.ctx)...)
errs = packer.MultiErrorAppend(errs, b.config.RunConfig.Prepare(&b.config.ctx)...)
errs = packer.MultiErrorAppend(errs, b.config.OutputConfig.Prepare(&b.config.ctx, &b.config.PackerConfig)...)
errs = packer.MultiErrorAppend(errs, b.config.SSHConfig.Prepare(&b.config.ctx)...)
errs = packer.MultiErrorAppend(errs, b.config.ShutdownConfig.Prepare(&b.config.ctx)...)
if len(b.config.ISOConfig.ISOUrls) < 1 || (strings.ToLower(filepath.Ext(b.config.ISOConfig.ISOUrls[0])) != ".vhd" && strings.ToLower(filepath.Ext(b.config.ISOConfig.ISOUrls[0])) != ".vhdx") {
//We only create a new hard drive if an existing one to copy from does not exist
err = b.checkDiskSize()
if err != nil {
errs = packer.MultiErrorAppend(errs, err)
}
}
err = b.checkRamSize()
if err != nil {
errs = packer.MultiErrorAppend(errs, err)
}
if b.config.VMName == "" {
b.config.VMName = fmt.Sprintf("packer-%s", b.config.PackerBuildName)
}
log.Println(fmt.Sprintf("%s: %v", "VMName", b.config.VMName))
if b.config.SwitchName == "" {
b.config.SwitchName = b.detectSwitchName()
}
if b.config.Cpu < 1 {
b.config.Cpu = 1
}
if b.config.Generation < 1 || b.config.Generation > 2 {
b.config.Generation = 1
}
if b.config.Generation == 2 {
if len(b.config.FloppyFiles) > 0 || len(b.config.FloppyDirectories) > 0 {
err = errors.New("Generation 2 vms don't support floppy drives. Use ISO image instead.")
errs = packer.MultiErrorAppend(errs, err)
}
}
log.Println(fmt.Sprintf("Using switch %s", b.config.SwitchName))
log.Println(fmt.Sprintf("%s: %v", "SwitchName", b.config.SwitchName))
// Errors
if b.config.GuestAdditionsMode == "" {
if b.config.GuestAdditionsPath != "" {
b.config.GuestAdditionsMode = "attach"
} else {
b.config.GuestAdditionsPath = os.Getenv("WINDIR") + "\\system32\\vmguest.iso"
if _, err := os.Stat(b.config.GuestAdditionsPath); os.IsNotExist(err) {
if err != nil {
b.config.GuestAdditionsPath = ""
b.config.GuestAdditionsMode = "none"
} else {
b.config.GuestAdditionsMode = "attach"
}
}
}
}
if b.config.GuestAdditionsPath == "" && b.config.GuestAdditionsMode == "attach" {
b.config.GuestAdditionsPath = os.Getenv("WINDIR") + "\\system32\\vmguest.iso"
if _, err := os.Stat(b.config.GuestAdditionsPath); os.IsNotExist(err) {
if err != nil {
b.config.GuestAdditionsPath = ""
}
}
}
for _, isoPath := range b.config.SecondaryDvdImages {
if _, err := os.Stat(isoPath); os.IsNotExist(err) {
if err != nil {
errs = packer.MultiErrorAppend(
errs, fmt.Errorf("Secondary Dvd image does not exist: %s", err))
}
}
}
numberOfIsos := len(b.config.SecondaryDvdImages)
if b.config.GuestAdditionsMode == "attach" {
if _, err := os.Stat(b.config.GuestAdditionsPath); os.IsNotExist(err) {
if err != nil {
errs = packer.MultiErrorAppend(
errs, fmt.Errorf("Guest additions iso does not exist: %s", err))
}
}
numberOfIsos = numberOfIsos + 1
}
if b.config.Generation < 2 && numberOfIsos > 2 {
if b.config.GuestAdditionsMode == "attach" {
errs = packer.MultiErrorAppend(errs, fmt.Errorf("There are only 2 ide controllers available, so we can't support guest additions and these secondary dvds: %s", strings.Join(b.config.SecondaryDvdImages, ", ")))
} else {
errs = packer.MultiErrorAppend(errs, fmt.Errorf("There are only 2 ide controllers available, so we can't support these secondary dvds: %s", strings.Join(b.config.SecondaryDvdImages, ", ")))
}
} else if b.config.Generation > 1 && len(b.config.SecondaryDvdImages) > 16 {
if b.config.GuestAdditionsMode == "attach" {
errs = packer.MultiErrorAppend(errs, fmt.Errorf("There are not enough drive letters available for scsi (limited to 16), so we can't support guest additions and these secondary dvds: %s", strings.Join(b.config.SecondaryDvdImages, ", ")))
} else {
errs = packer.MultiErrorAppend(errs, fmt.Errorf("There are not enough drive letters available for scsi (limited to 16), so we can't support these secondary dvds: %s", strings.Join(b.config.SecondaryDvdImages, ", ")))
}
}
if b.config.EnableVirtualizationExtensions {
hasVirtualMachineVirtualizationExtensions, err := powershell.HasVirtualMachineVirtualizationExtensions()
if err != nil {
errs = packer.MultiErrorAppend(errs, fmt.Errorf("Failed detecting virtual machine virtualization extensions support: %s", err))
} else {
if !hasVirtualMachineVirtualizationExtensions {
errs = packer.MultiErrorAppend(errs, fmt.Errorf("This version of Hyper-V does not support virtual machine virtualization extension. Please use Windows 10 or Windows Server 2016 or newer."))
}
}
}
// Warnings
if b.config.ShutdownCommand == "" {
warnings = append(warnings,
"A shutdown_command was not specified. Without a shutdown command, Packer\n"+
"will forcibly halt the virtual machine, which may result in data loss.")
}
warning := b.checkHostAvailableMemory()
if warning != "" {
warnings = appendWarnings(warnings, warning)
}
if b.config.EnableVirtualizationExtensions {
if b.config.EnableDynamicMemory {
warning = fmt.Sprintf("For nested virtualization, when virtualization extension is enabled, dynamic memory should not be allowed.")
warnings = appendWarnings(warnings, warning)
}
if !b.config.EnableMacSpoofing {
warning = fmt.Sprintf("For nested virtualization, when virtualization extension is enabled, mac spoofing should be allowed.")
warnings = appendWarnings(warnings, warning)
}
if b.config.RamSize < MinNestedVirtualizationRamSize {
warning = fmt.Sprintf("For nested virtualization, when virtualization extension is enabled, there should be 4GB or more memory set for the vm, otherwise Hyper-V may fail to start any nested VMs.")
warnings = appendWarnings(warnings, warning)
}
}
if b.config.SwitchVlanId != "" {
if b.config.SwitchVlanId != b.config.VlanId {
warning = fmt.Sprintf("Switch network adaptor vlan should match virtual machine network adaptor vlan. The switch will not be able to see traffic from the VM.")
warnings = appendWarnings(warnings, warning)
}
}
if errs != nil && len(errs.Errors) > 0 {
return warnings, errs
}
return warnings, nil
}
// Run executes a Packer build and returns a packer.Artifact representing
// a Hyperv appliance.
func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
// Create the driver that we'll use to communicate with Hyperv
driver, err := hypervcommon.NewHypervPS4Driver()
if err != nil {
return nil, fmt.Errorf("Failed creating Hyper-V driver: %s", err)
}
// Set up the state.
state := new(multistep.BasicStateBag)
state.Put("cache", cache)
state.Put("config", &b.config)
state.Put("debug", b.config.PackerDebug)
state.Put("driver", driver)
state.Put("hook", hook)
state.Put("ui", ui)
steps := []multistep.Step{
&hypervcommon.StepCreateTempDir{
TempPath: b.config.TempPath,
VhdTempPath: b.config.VhdTempPath,
},
&hypervcommon.StepOutputDir{
Force: b.config.PackerForce,
Path: b.config.OutputDir,
},
&common.StepDownload{
Checksum: b.config.ISOChecksum,
ChecksumType: b.config.ISOChecksumType,
Description: "ISO",
ResultKey: "iso_path",
Url: b.config.ISOUrls,
Extension: b.config.TargetExtension,
TargetPath: b.config.TargetPath,
},
&common.StepCreateFloppy{
Files: b.config.FloppyConfig.FloppyFiles,
Directories: b.config.FloppyConfig.FloppyDirectories,
},
&common.StepHTTPServer{
HTTPDir: b.config.HTTPDir,
HTTPPortMin: b.config.HTTPPortMin,
HTTPPortMax: b.config.HTTPPortMax,
},
&hypervcommon.StepCreateSwitch{
SwitchName: b.config.SwitchName,
},
&hypervcommon.StepCreateVM{
VMName: b.config.VMName,
SwitchName: b.config.SwitchName,
RamSize: b.config.RamSize,
DiskSize: b.config.DiskSize,
Generation: b.config.Generation,
Cpu: b.config.Cpu,
EnableMacSpoofing: b.config.EnableMacSpoofing,
EnableDynamicMemory: b.config.EnableDynamicMemory,
EnableSecureBoot: b.config.EnableSecureBoot,
EnableVirtualizationExtensions: b.config.EnableVirtualizationExtensions,
},
&hypervcommon.StepEnableIntegrationService{},
&hypervcommon.StepMountDvdDrive{
Generation: b.config.Generation,
},
&hypervcommon.StepMountFloppydrive{
Generation: b.config.Generation,
},
&hypervcommon.StepMountGuestAdditions{
GuestAdditionsMode: b.config.GuestAdditionsMode,
GuestAdditionsPath: b.config.GuestAdditionsPath,
Generation: b.config.Generation,
},
&hypervcommon.StepMountSecondaryDvdImages{
IsoPaths: b.config.SecondaryDvdImages,
Generation: b.config.Generation,
},
&hypervcommon.StepConfigureVlan{
VlanId: b.config.VlanId,
SwitchVlanId: b.config.SwitchVlanId,
},
&hypervcommon.StepRun{
BootWait: b.config.BootWait,
},
&hypervcommon.StepTypeBootCommand{
BootCommand: b.config.BootCommand,
SwitchName: b.config.SwitchName,
Ctx: b.config.ctx,
},
// configure the communicator ssh, winrm
&communicator.StepConnect{
Config: &b.config.SSHConfig.Comm,
Host: hypervcommon.CommHost,
SSHConfig: hypervcommon.SSHConfigFunc(&b.config.SSHConfig),
},
// provision requires communicator to be setup
&common.StepProvision{},
&hypervcommon.StepShutdown{
Command: b.config.ShutdownCommand,
Timeout: b.config.ShutdownTimeout,
},
// wait for the vm to be powered off
&hypervcommon.StepWaitForPowerOff{},
// remove the secondary dvd images
// after we power down
&hypervcommon.StepUnmountSecondaryDvdImages{},
&hypervcommon.StepUnmountGuestAdditions{},
&hypervcommon.StepUnmountDvdDrive{},
&hypervcommon.StepUnmountFloppyDrive{
Generation: b.config.Generation,
},
&hypervcommon.StepExportVm{
OutputDir: b.config.OutputDir,
SkipCompaction: b.config.SkipCompaction,
},
// the clean up actions for each step will be executed reverse order
}
// Run the steps.
b.runner = common.NewRunner(steps, b.config.PackerConfig, ui)
b.runner.Run(state)
// Report any errors.
if rawErr, ok := state.GetOk("error"); ok {
return nil, rawErr.(error)
}
// If we were interrupted or cancelled, then just exit.
if _, ok := state.GetOk(multistep.StateCancelled); ok {
return nil, errors.New("Build was cancelled.")
}
if _, ok := state.GetOk(multistep.StateHalted); ok {
return nil, errors.New("Build was halted.")
}
return hypervcommon.NewArtifact(b.config.OutputDir)
}
// Cancel.
func (b *Builder) Cancel() {
if b.runner != nil {
log.Println("Cancelling the step runner...")
b.runner.Cancel()
}
}
func appendWarnings(slice []string, data ...string) []string {
m := len(slice)
n := m + len(data)
if n > cap(slice) { // if necessary, reallocate
// allocate double what's needed, for future growth.
newSlice := make([]string, (n+1)*2)
copy(newSlice, slice)
slice = newSlice
}
slice = slice[0:n]
copy(slice[m:n], data)
return slice
}
func (b *Builder) checkDiskSize() error {
if b.config.DiskSize == 0 {
b.config.DiskSize = DefaultDiskSize
}
log.Println(fmt.Sprintf("%s: %v", "DiskSize", b.config.DiskSize))
if b.config.DiskSize < MinDiskSize {
return fmt.Errorf("disk_size: Virtual machine requires disk space >= %v GB, but defined: %v", MinDiskSize, b.config.DiskSize/1024)
} else if b.config.DiskSize > MaxDiskSize {
return fmt.Errorf("disk_size: Virtual machine requires disk space <= %v GB, but defined: %v", MaxDiskSize, b.config.DiskSize/1024)
}
return nil
}
func (b *Builder) checkRamSize() error {
if b.config.RamSize == 0 {
b.config.RamSize = DefaultRamSize
}
log.Println(fmt.Sprintf("%s: %v", "RamSize", b.config.RamSize))
if b.config.RamSize < MinRamSize {
return fmt.Errorf("ram_size: Virtual machine requires memory size >= %v MB, but defined: %v", MinRamSize, b.config.RamSize)
} else if b.config.RamSize > MaxRamSize {
return fmt.Errorf("ram_size: Virtual machine requires memory size <= %v MB, but defined: %v", MaxRamSize, b.config.RamSize)
}
return nil
}
func (b *Builder) checkHostAvailableMemory() string {
powershellAvailable, _, _ := powershell.IsPowershellAvailable()
if powershellAvailable {
freeMB := powershell.GetHostAvailableMemory()
if (freeMB - float64(b.config.RamSize)) < LowRam {
return fmt.Sprintf("Hyper-V might fail to create a VM if there is not enough free memory in the system.")
}
}
return ""
}
func (b *Builder) detectSwitchName() string {
powershellAvailable, _, _ := powershell.IsPowershellAvailable()
if powershellAvailable {
// no switch name, try to get one attached to a online network adapter
onlineSwitchName, err := hyperv.GetExternalOnlineVirtualSwitch()
if onlineSwitchName != "" && err == nil {
return onlineSwitchName
}
}
return fmt.Sprintf("packer-%s", b.config.PackerBuildName)
}
| mpl-2.0 |
geoffschoeman/notes | src/notemodel.cpp | 4338 | #include "notemodel.h"
#include <QDebug>
NoteModel::NoteModel(QObject *parent)
: QAbstractListModel(parent)
{
}
NoteModel::~NoteModel()
{
}
QModelIndex NoteModel::addNote(NoteData* note)
{
const int rowCnt = rowCount();
beginInsertRows(QModelIndex(), rowCnt, rowCnt);
m_noteList << note;
endInsertRows();
return createIndex(rowCnt, 0);
}
QModelIndex NoteModel::insertNote(NoteData *note, int row)
{
if(row >= rowCount()){
return addNote(note);
}else{
beginInsertRows(QModelIndex(), row, row);
m_noteList.insert(row, note);
endInsertRows();
}
return createIndex(row,0);
}
NoteData* NoteModel::getNote(const QModelIndex& index)
{
if(index.isValid()){
return m_noteList.at(index.row());
}else{
return Q_NULLPTR;
}
}
void NoteModel::addListNote(QList<NoteData *> noteList)
{
int start = rowCount();
int end = start + noteList.count()-1;
beginInsertRows(QModelIndex(), start, end);
m_noteList << noteList;
endInsertRows();
}
NoteData* NoteModel::removeNote(const QModelIndex ¬eIndex)
{
int row = noteIndex.row();
beginRemoveRows(QModelIndex(), row, row);
NoteData* note = m_noteList.takeAt(row);
endRemoveRows();
return note;
}
bool NoteModel::moveRow(const QModelIndex &sourceParent, int sourceRow, const QModelIndex &destinationParent, int destinationChild)
{
if(sourceRow<0
|| sourceRow >= m_noteList.count()
|| destinationChild <0
|| destinationChild >= m_noteList.count()){
return false;
}
beginMoveRows(sourceParent,sourceRow,sourceRow,destinationParent,destinationChild);
m_noteList.move(sourceRow,destinationChild);
endMoveRows();
return true;
}
void NoteModel::clearNotes()
{
beginResetModel();
m_noteList.clear();
endResetModel();
}
QVariant NoteModel::data(const QModelIndex &index, int role) const
{
if (index.row() < 0 || index.row() >= m_noteList.count())
return QVariant();
NoteData* note = m_noteList[index.row()];
if(role == NoteID){
return note->id();
}else if(role == NoteFullTitle){
return note->fullTitle();
}else if(role == NoteCreationDateTime){
return note->creationDateTime();
}else if(role == NoteLastModificationDateTime){
return note->lastModificationdateTime();
}else if(role == NoteDeletionDateTime){
return note->deletionDateTime();
}else if(role == NoteContent){
return note->content();
}else if(role == NoteScrollbarPos){
return note->scrollBarPosition();
}
return QVariant();
}
bool NoteModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid())
return false;
NoteData* note = m_noteList[index.row()];
if(role == NoteID){
note->setId(value.toString());
}else if(role == NoteFullTitle){
note->setFullTitle(value.toString());
}else if(role == NoteCreationDateTime){
note->setCreationDateTime(value.toDateTime());
}else if(role == NoteLastModificationDateTime){
note->setLastModificationDateTime(value.toDateTime());
}else if(role == NoteDeletionDateTime){
note->setDeletionDateTime(value.toDateTime());
}else if(role == NoteContent){
note->setContent(value.toString());
}else if(role == NoteScrollbarPos){
note->setScrollBarPosition(value.toInt());
}else{
return false;
}
emit dataChanged(this->index(index.row()),
this->index(index.row()),
QVector<int>(1,role));
return true;
}
Qt::ItemFlags NoteModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::ItemIsEnabled;
return QAbstractListModel::flags(index) | Qt::ItemIsEditable | Qt::ItemIsEditable ;
}
int NoteModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return m_noteList.count();
}
void NoteModel::sort(int column, Qt::SortOrder order)
{
Q_UNUSED(column)
Q_UNUSED(order)
std::stable_sort(m_noteList.begin(), m_noteList.end(), [](NoteData* lhs, NoteData* rhs){
return lhs->lastModificationdateTime() > rhs->lastModificationdateTime();
});
emit dataChanged(index(0), index(rowCount()-1));
}
| mpl-2.0 |
GENIVI/CANdevStudio | src/components/canload/tests/canloadmodel_test.cpp | 2766 | #include <QtWidgets/QApplication>
#include <canloadmodel.h>
#include <datamodeltypes/canrawdata.h>
#define CATCH_CONFIG_RUNNER
#include "log.h"
#include <QSignalSpy>
#include <catch.hpp>
#include <fakeit.hpp>
std::shared_ptr<spdlog::logger> kDefaultLogger;
// needed for QSignalSpy cause according to qtbug 49623 comments
// automatic detection of types is "flawed" in moc
Q_DECLARE_METATYPE(QCanBusFrame);
TEST_CASE("Test basic functionality", "[canloadModel]")
{
using namespace fakeit;
CanLoadModel cm;
REQUIRE(cm.caption() == "CanLoad");
REQUIRE(cm.name() == "CanLoad");
REQUIRE(cm.resizable() == false);
REQUIRE(cm.hasSeparateThread() == false);
REQUIRE(dynamic_cast<CanLoadModel*>(cm.clone().get()) != nullptr);
REQUIRE(dynamic_cast<QLabel*>(cm.embeddedWidget()) != nullptr);
}
TEST_CASE("painterDelegate", "[canloadModel]")
{
CanLoadModel cm;
REQUIRE(cm.painterDelegate() != nullptr);
}
TEST_CASE("nPorts", "[canloadModel]")
{
CanLoadModel cm;
REQUIRE(cm.nPorts(QtNodes::PortType::Out) == 0);
REQUIRE(cm.nPorts(QtNodes::PortType::In) == 1);
}
TEST_CASE("dataType", "[canloadModel]")
{
CanLoadModel cm;
NodeDataType ndt;
ndt = cm.dataType(QtNodes::PortType::In, 0);
REQUIRE(ndt.id == "rawframe");
REQUIRE(ndt.name == "RAW");
ndt = cm.dataType(QtNodes::PortType::In, 1);
REQUIRE(ndt.id == "");
REQUIRE(ndt.name == "");
ndt = cm.dataType(QtNodes::PortType::Out, 0);
REQUIRE(ndt.id == "");
REQUIRE(ndt.name == "");
}
TEST_CASE("outData", "[canloadModel]")
{
CanLoadModel cm;
auto nd = cm.outData(0);
REQUIRE(!nd);
}
TEST_CASE("setInData", "[canloadModel]")
{
CanLoadModel cm;
QCanBusFrame frame;
auto data = std::make_shared<CanRawData>(frame);
QSignalSpy spy(&cm, &CanLoadModel::frameIn);
REQUIRE(spy.count() == 0);
cm.setInData(data, 1);
cm.setInData({}, 1);
REQUIRE(spy.count() == 1);
}
TEST_CASE("currentLoad", "[canloadModel]")
{
CanLoadModel cm;
std::array<uint8_t, 10> array = {0, 0, 0, 200, 199, 100, 100, 8, 9, 0};
QSignalSpy spy(&cm, &CanLoadModel::requestRedraw);
REQUIRE(spy.count() == 0);
for(auto a : array) {
cm.currentLoad(a);
}
REQUIRE(spy.count() == 6);
}
int main(int argc, char* argv[])
{
bool haveDebug = std::getenv("CDS_DEBUG") != nullptr;
kDefaultLogger = spdlog::stdout_color_mt("cds");
if (haveDebug) {
kDefaultLogger->set_level(spdlog::level::debug);
}
cds_debug("Starting unit tests");
qRegisterMetaType<QCanBusFrame>(); // required by QSignalSpy
QApplication a(argc, argv); // QApplication must exist when constructing QWidgets TODO check QTest
return Catch::Session().run(argc, argv);
}
| mpl-2.0 |
libigl/libigl-examples | intersections/example.cpp | 16707 | #include <igl/Camera.h>
#include <igl/opengl/OpenGL_convenience.h>
#include <igl/barycenter.h>
#include <igl/cat.h>
#include <igl/opengl2/draw_floor.h>
#include <igl/opengl2/draw_mesh.h>
#include <igl/get_seconds.h>
#include <igl/jet.h>
#include <igl/list_to_matrix.h>
#include <igl/material_colors.h>
#include <igl/matlab_format.h>
#include <igl/normalize_row_lengths.h>
#include <igl/pathinfo.h>
#include <igl/per_face_normals.h>
#include <igl/polygon_mesh_to_triangle_mesh.h>
#include <igl/quat_to_mat.h>
#include <igl/readDMAT.h>
#include <igl/readMESH.h>
#include <igl/readOBJ.h>
#include <igl/readOFF.h>
#include <igl/readWRL.h>
#include <igl/opengl/report_gl_error.h>
#include <igl/snap_to_canonical_view_quat.h>
#include <igl/snap_to_fixed_up.h>
#include <igl/trackball.h>
#include <igl/two_axis_valuator_fixed_up.h>
#include <igl/writeOBJ.h>
#include <igl/anttweakbar/ReAntTweakBar.h>
#include <igl/cgal/remesh_self_intersections.h>
#include <igl/cgal/intersect_other.h>
#ifdef __APPLE__
# include <GLUT/glut.h>
#else
# include <GL/glut.h>
#endif
#include <Eigen/Core>
#include <vector>
#include <iostream>
#include <algorithm>
struct State
{
igl::Camera camera;
} s;
enum RotationType
{
ROTATION_TYPE_IGL_TRACKBALL = 0,
ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP = 1,
NUM_ROTATION_TYPES = 2,
} rotation_type;
bool is_rotating = false;
int down_x,down_y;
igl::Camera down_camera;
bool is_animating = false;
double animation_start_time = 0;
double ANIMATION_DURATION = 0.5;
Eigen::Quaterniond animation_from_quat;
Eigen::Quaterniond animation_to_quat;
// Use vector for range-based `for`
std::vector<State> undo_stack;
std::vector<State> redo_stack;
void push_undo()
{
undo_stack.push_back(s);
// Clear
redo_stack = std::vector<State>();
}
void undo()
{
using namespace std;
if(!undo_stack.empty())
{
redo_stack.push_back(s);
s = undo_stack.front();
undo_stack.pop_back();
}
}
void redo()
{
using namespace std;
if(!redo_stack.empty())
{
undo_stack.push_back(s);
s = redo_stack.front();
redo_stack.pop_back();
}
}
void TW_CALL set_rotation_type(const void * value, void * clientData)
{
using namespace Eigen;
using namespace std;
using namespace igl;
const RotationType old_rotation_type = rotation_type;
rotation_type = *(const RotationType *)(value);
if(rotation_type == ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP &&
old_rotation_type != ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP)
{
push_undo();
animation_from_quat = s.camera.m_rotation_conj;
snap_to_fixed_up(animation_from_quat,animation_to_quat);
// start animation
animation_start_time = get_seconds();
is_animating = true;
}
}
void TW_CALL get_rotation_type(void * value, void *clientData)
{
RotationType * rt = (RotationType *)(value);
*rt = rotation_type;
}
// Width and height of window
int width,height;
// Position of light
float light_pos[4] = {0.1,0.1,-0.9,0};
// V,U Vertex positions
// C,D Colors
// N,W Normals
// mid combined "centroid"
Eigen::MatrixXd V,N,C,Z,mid,U,W,D,VU;
// F,G faces
Eigen::MatrixXi F,G;
bool has_other = false;
bool show_A = true;
bool show_B = true;
int selected_col = 0;
// Bounding box diagonal length
double bbd;
// Running ambient occlusion
Eigen::VectorXd S;
int tot_num_samples = 0;
#define REBAR_NAME "temp.rbr"
igl::anttweakbar::ReTwBar rebar; // Pointer to the tweak bar
void reshape(int width,int height)
{
using namespace std;
// Save width and height
::width = width;
::height = height;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0,0,width,height);
// Send the new window size to AntTweakBar
TwWindowSize(width, height);
// Set aspect for all cameras
s.camera.m_aspect = (double)width/(double)height;
for(auto & s : undo_stack)
{
s.camera.m_aspect = (double)width/(double)height;
}
for(auto & s : redo_stack)
{
s.camera.m_aspect = (double)width/(double)height;
}
}
void push_scene()
{
using namespace igl;
using namespace std;
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
auto & camera = s.camera;
gluPerspective(camera.m_angle,camera.m_aspect,camera.m_near,camera.m_far);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
gluLookAt(
camera.eye()(0), camera.eye()(1), camera.eye()(2),
camera.at()(0), camera.at()(1), camera.at()(2),
camera.up()(0), camera.up()(1), camera.up()(2));
}
void pop_scene()
{
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
}
void pop_object()
{
glPopMatrix();
}
// Scale and shift for object
void push_object()
{
glPushMatrix();
glScaled(2./bbd,2./bbd,2./bbd);
glTranslated(-mid(0,0),-mid(0,1),-mid(0,2));
}
// Set up double-sided lights
void lights()
{
using namespace std;
glEnable(GL_LIGHTING);
glLightModelf(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
float amb[4];
amb[0] = amb[1] = amb[2] = 0;
amb[3] = 1.0;
float diff[4] = {0.0,0.0,0.0,0.0};
diff[0] = diff[1] = diff[2] = (1.0 - 0/0.4);;
diff[3] = 1.0;
float zeros[4] = {0.0,0.0,0.0,0.0};
float pos[4];
copy(light_pos,light_pos+4,pos);
glLightfv(GL_LIGHT0,GL_AMBIENT,amb);
glLightfv(GL_LIGHT0,GL_DIFFUSE,diff);
glLightfv(GL_LIGHT0,GL_SPECULAR,zeros);
glLightfv(GL_LIGHT0,GL_POSITION,pos);
pos[0] *= -1;
pos[1] *= -1;
pos[2] *= -1;
glLightfv(GL_LIGHT1,GL_AMBIENT,amb);
glLightfv(GL_LIGHT1,GL_DIFFUSE,diff);
glLightfv(GL_LIGHT1,GL_SPECULAR,zeros);
glLightfv(GL_LIGHT1,GL_POSITION,pos);
}
const float back[4] = {30.0/255.0,30.0/255.0,50.0/255.0,0};
void display()
{
using namespace Eigen;
using namespace igl;
using namespace std;
glClearColor(back[0],back[1],back[2],0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if(is_animating)
{
double t = (get_seconds() - animation_start_time)/ANIMATION_DURATION;
if(t > 1)
{
t = 1;
is_animating = false;
}
const Quaterniond q = animation_from_quat.slerp(t,animation_to_quat).normalized();
s.camera.orbit(q.conjugate());
}
glDisable(GL_LIGHTING);
lights();
push_scene();
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE);
push_object();
// Draw the model
// Set material properties
glEnable(GL_COLOR_MATERIAL);
const auto draw = [](
const MatrixXd & V,
const MatrixXi & F,
const MatrixXd & N,
const MatrixXd & C)
{
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_POLYGON_OFFSET_FILL); // Avoid Stitching!
glPolygonOffset(1.0,1);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
igl::opengl2::draw_mesh(V,F,N,C);
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glDisable(GL_COLOR_MATERIAL);
const float black[4] = {0,0,0,1};
glColor4fv(black);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, black);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, black);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, black);
glLightfv(GL_LIGHT0, GL_AMBIENT, black);
glLightfv(GL_LIGHT0, GL_DIFFUSE, black);
glLineWidth(1.0);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
igl::opengl2::draw_mesh(V,F,N,C);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_COLOR_MATERIAL);
};
if(show_A)
{
draw(V,F,N,C);
}
if(show_B)
{
draw(U,G,W,D);
}
pop_object();
// Draw a nice floor
glPushMatrix();
const double floor_offset =
-2./bbd*(VU.col(1).maxCoeff()-mid(1));
glTranslated(0,floor_offset,0);
const float GREY[4] = {0.5,0.5,0.6,1.0};
const float DARK_GREY[4] = {0.2,0.2,0.3,1.0};
igl::opengl2::draw_floor(GREY,DARK_GREY);
glPopMatrix();
pop_scene();
igl::opengl::report_gl_error();
TwDraw();
glutSwapBuffers();
if(is_animating)
{
glutPostRedisplay();
}
}
void mouse_wheel(int wheel, int direction, int mouse_x, int mouse_y)
{
using namespace std;
using namespace igl;
using namespace Eigen;
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT,viewport);
if(wheel == 0 && TwMouseMotion(mouse_x, viewport[3] - mouse_y))
{
static double mouse_scroll_y = 0;
const double delta_y = 0.125*direction;
mouse_scroll_y += delta_y;
TwMouseWheel(mouse_scroll_y);
return;
}
push_undo();
auto & camera = s.camera;
if(wheel==0)
{
// factor of zoom change
double s = (1.-0.01*direction);
//// FOV zoom: just widen angle. This is hardly ever appropriate.
//camera.m_angle *= s;
//camera.m_angle = min(max(camera.m_angle,1),89);
camera.push_away(s);
}else
{
// Dolly zoom:
camera.dolly_zoom((double)direction*1.0);
}
}
void mouse(int glutButton, int glutState, int mouse_x, int mouse_y)
{
using namespace std;
using namespace Eigen;
using namespace igl;
bool tw_using = TwEventMouseButtonGLUT(glutButton,glutState,mouse_x,mouse_y);
switch(glutButton)
{
case GLUT_RIGHT_BUTTON:
case GLUT_LEFT_BUTTON:
{
switch(glutState)
{
case 1:
// up
glutSetCursor(GLUT_CURSOR_LEFT_ARROW);
is_rotating = false;
break;
case 0:
// down
if(!tw_using)
{
glutSetCursor(GLUT_CURSOR_CYCLE);
// collect information for trackball
is_rotating = true;
down_camera = s.camera;
down_x = mouse_x;
down_y = mouse_y;
}
break;
}
break;
}
// Scroll down
case 3:
{
mouse_wheel(0,-1,mouse_x,mouse_y);
break;
}
// Scroll up
case 4:
{
mouse_wheel(0,1,mouse_x,mouse_y);
break;
}
// Scroll left
case 5:
{
mouse_wheel(1,-1,mouse_x,mouse_y);
break;
}
// Scroll right
case 6:
{
mouse_wheel(1,1,mouse_x,mouse_y);
break;
}
}
glutPostRedisplay();
}
void mouse_drag(int mouse_x, int mouse_y)
{
using namespace igl;
using namespace Eigen;
if(is_rotating)
{
glutSetCursor(GLUT_CURSOR_CYCLE);
Quaterniond q;
auto & camera = s.camera;
switch(rotation_type)
{
case ROTATION_TYPE_IGL_TRACKBALL:
{
// Rotate according to trackball
igl::trackball<double>(
width,
height,
2.0,
down_camera.m_rotation_conj.coeffs().data(),
down_x,
down_y,
mouse_x,
mouse_y,
q.coeffs().data());
break;
}
case ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP:
{
// Rotate according to two axis valuator with fixed up vector
two_axis_valuator_fixed_up(
width, height,
2.0,
down_camera.m_rotation_conj,
down_x, down_y, mouse_x, mouse_y,
q);
break;
}
default:
break;
}
camera.orbit(q.conjugate());
}else
{
TwEventMouseMotionGLUT(mouse_x, mouse_y);
}
glutPostRedisplay();
}
void color_selfintersections(
const Eigen::MatrixXd & V,
const Eigen::MatrixXi & F,
Eigen::MatrixXd & C)
{
using namespace igl;
using namespace igl::cgal;
using namespace Eigen;
using namespace std;
MatrixXd SV;
MatrixXi SF,IF;
VectorXi J,IM;
RemeshSelfIntersectionsParam params;
params.detect_only = false;
remesh_self_intersections(V,F,params,SV,SF,IF,J,IM);
writeOBJ("FUCK.obj",SV,SF);
C.resize(F.rows(),3);
C.col(0).setConstant(0.4);
C.col(1).setConstant(0.8);
C.col(2).setConstant(0.3);
for(int f = 0;f<IF.rows();f++)
{
C.row(IF(f,0)) = RowVector3d(1,0.4,0.4);
C.row(IF(f,1)) = RowVector3d(1,0.4,0.4);
}
}
void color_intersections(
const Eigen::MatrixXd & V,
const Eigen::MatrixXi & F,
const Eigen::MatrixXd & U,
const Eigen::MatrixXi & G,
Eigen::MatrixXd & C,
Eigen::MatrixXd & D)
{
using namespace igl;
using namespace igl::cgal;
using namespace Eigen;
MatrixXi IF;
const bool first_only = false;
intersect_other(V,F,U,G,first_only,IF);
C.resize(F.rows(),3);
C.col(0).setConstant(0.4);
C.col(1).setConstant(0.8);
C.col(2).setConstant(0.3);
D.resize(G.rows(),3);
D.col(0).setConstant(0.4);
D.col(1).setConstant(0.3);
D.col(2).setConstant(0.8);
for(int f = 0;f<IF.rows();f++)
{
C.row(IF(f,0)) = RowVector3d(1,0.4,0.4);
D.row(IF(f,1)) = RowVector3d(0.8,0.7,0.3);
}
}
void key(unsigned char key, int mouse_x, int mouse_y)
{
using namespace std;
switch(key)
{
// ESC
case char(27):
rebar.save(REBAR_NAME);
// ^C
case char(3):
exit(0);
default:
if(!TwEventKeyboardGLUT(key,mouse_x,mouse_y))
{
cout<<"Unknown key command: "<<key<<" "<<int(key)<<endl;
}
}
glutPostRedisplay();
}
int main(int argc, char * argv[])
{
using namespace Eigen;
using namespace igl;
using namespace std;
// init mesh
string filename = "../shared/truck.obj";
string filename_other = "";
switch(argc)
{
case 3:
// Read and prepare mesh
filename_other = argv[2];
has_other=true;
// fall through
case 2:
// Read and prepare mesh
filename = argv[1];
break;
default:
cerr<<"Usage:"<<endl<<" ./example input.obj [other.obj]"<<endl;
cout<<endl<<"Opening default mesh..."<<endl;
}
const auto read = []
(const string & filename, MatrixXd & V, MatrixXi & F, MatrixXd & N) -> bool
{
// dirname, basename, extension and filename
string d,b,ext,f;
pathinfo(filename,d,b,ext,f);
// Convert extension to lower case
transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
vector<vector<double > > vV,vN,vTC;
vector<vector<int > > vF,vFTC,vFN;
if(ext == "obj")
{
// Convert extension to lower case
if(!igl::readOBJ(filename,vV,vTC,vN,vF,vFTC,vFN))
{
return false;
}
}else if(ext == "off")
{
// Convert extension to lower case
if(!igl::readOFF(filename,vV,vF,vN))
{
return false;
}
}else if(ext == "wrl")
{
// Convert extension to lower case
if(!igl::readWRL(filename,vV,vF))
{
return false;
}
//}else
//{
// // Convert extension to lower case
// MatrixXi T;
// if(!igl::readMESH(filename,V,T,F))
// {
// return false;
// }
// //if(F.size() > T.size() || F.size() == 0)
// {
// boundary_facets(T,F);
// }
}
if(vV.size() > 0)
{
if(!list_to_matrix(vV,V))
{
return false;
}
polygon_mesh_to_triangle_mesh(vF,F);
}
// Compute normals, centroid, colors, bounding box diagonal
per_face_normals(V,F,N);
return true;
};
if(!read(filename,V,F,N))
{
return 1;
}
if(has_other)
{
if(!read(argv[2],U,G,W))
{
return 1;
}
cat(1,V,U,VU);
color_intersections(V,F,U,G,C,D);
}else
{
VU = V;
color_selfintersections(V,F,C);
}
mid = 0.5*(VU.colwise().maxCoeff() + VU.colwise().minCoeff());
bbd = (VU.colwise().maxCoeff() - VU.colwise().minCoeff()).maxCoeff();
// Init glut
glutInit(&argc,argv);
if( !TwInit(TW_OPENGL, NULL) )
{
// A fatal error occured
fprintf(stderr, "AntTweakBar initialization failed: %s\n", TwGetLastError());
return 1;
}
// Create a tweak bar
rebar.TwNewBar("TweakBar");
rebar.TwAddVarRW("camera_rotation", TW_TYPE_QUAT4D,
s.camera.m_rotation_conj.coeffs().data(), "open readonly=true");
s.camera.push_away(3);
s.camera.dolly_zoom(25-s.camera.m_angle);
TwType RotationTypeTW = igl::anttweakbar::ReTwDefineEnumFromString("RotationType",
"igl_trackball,two-a...-fixed-up");
rebar.TwAddVarCB( "rotation_type", RotationTypeTW,
set_rotation_type,get_rotation_type,NULL,"keyIncr=] keyDecr=[");
if(has_other)
{
rebar.TwAddVarRW("show_A",TW_TYPE_BOOLCPP,&show_A, "key=a",false);
rebar.TwAddVarRW("show_B",TW_TYPE_BOOLCPP,&show_B, "key=b",false);
}
rebar.load(REBAR_NAME);
glutInitDisplayString("rgba depth double samples>=8 ");
glutInitWindowSize(glutGet(GLUT_SCREEN_WIDTH)/2.0,glutGet(GLUT_SCREEN_HEIGHT));
glutCreateWindow("mesh-intersections");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(key);
glutMouseFunc(mouse);
glutMotionFunc(mouse_drag);
glutPassiveMotionFunc(
[](int x, int y)
{
TwEventMouseMotionGLUT(x,y);
glutPostRedisplay();
});
static std::function<void(int)> timer_bounce;
auto timer = [] (int ms) {
timer_bounce(ms);
};
timer_bounce = [&] (int ms) {
glutTimerFunc(ms, timer, ms);
glutPostRedisplay();
};
glutTimerFunc(500, timer, 500);
glutMainLoop();
return 0;
}
| mpl-2.0 |
nnethercote/servo | tests/wpt/web-platform-tests/bluetooth/characteristic/getDescriptor/gen-descriptor-get-same-object.https.window.js | 1636 | // META: script=/resources/testharness.js
// META: script=/resources/testharnessreport.js
// META: script=/resources/testdriver.js
// META: script=/resources/testdriver-vendor.js
// META: script=/bluetooth/resources/bluetooth-helpers.js
// Generated by //third_party/WebKit/LayoutTests/bluetooth/generate.py
'use strict';
const test_desc = 'Calls to getDescriptor should return the same object.';
let characteristic;
bluetooth_test(
() => getMeasurementIntervalCharacteristic()
.then(_ => ({characteristic} = _))
.then(() => Promise.all([
characteristic.getDescriptor(user_description.alias),
characteristic.getDescriptor(user_description.name),
characteristic.getDescriptor(user_description.uuid)
]))
.then(descriptors_arrays => {
assert_true(descriptors_arrays.length > 0)
// Convert to arrays if necessary.
for (let i = 0; i < descriptors_arrays.length; i++) {
descriptors_arrays[i] = [].concat(descriptors_arrays[i]);
}
for (let i = 1; i < descriptors_arrays.length; i++) {
assert_equals(
descriptors_arrays[0].length,
descriptors_arrays[i].length);
}
let base_set = new Set(descriptors_arrays[0]);
for (let descriptors of descriptors_arrays) {
descriptors.forEach(
descriptor => assert_true(base_set.has(descriptor)));
}
}),
test_desc);
| mpl-2.0 |
ericawright/bedrock | tests/pages/regions/download_button.py | 965 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from selenium.webdriver.common.by import By
from pages.base import BaseRegion
class DownloadButton(BaseRegion):
_download_link_locator = (By.CSS_SELECTOR, '.download-link')
@property
def _platform_link(self):
els = [el for el in self.find_elements(*self._download_link_locator)
if el.is_displayed()]
assert len(els) == 1, 'Expected one platform link to be displayed'
return els[0]
@property
def is_displayed(self):
return self.root.is_displayed() and self._platform_link.is_displayed() or False
@property
def is_transitional_link(self):
return '/firefox/download/thanks/' in self._platform_link.get_attribute('href')
def click(self):
self._platform_link.click()
| mpl-2.0 |
Enterprise-Content-Management/infoarchive-sip-sdk | core/src/main/java/com/opentext/ia/sdk/dto/StorageEndPoints.java | 189 | /*
* Copyright (c) 2016-2017 by OpenText Corporation. All Rights Reserved.
*/
package com.opentext.ia.sdk.dto;
public class StorageEndPoints extends ItemContainer<StorageEndPoint> {
}
| mpl-2.0 |
Fidaman/Camelot-Unchained | widgets/cu-character-creation/lib/services/session/genders.d.ts | 423 | /**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { gender } from 'camelot-unchained';
export declare function selectGender(selected: gender): {
type: string;
selected: gender;
};
export default function reducer(state?: gender, action?: any): any;
| mpl-2.0 |
choreos/enactment_engine | cookbooks/jar/recipes/default.rb | 1188 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
include_recipe "apt" # java recipe is failing without recipe apt
include_recipe "java"
remote_file "#{node['CHOReOSData']['serviceData']['$NAME']['InstallationDir']}/service-$NAME.jar" do
source "#{node['CHOReOSData']['serviceData']['$NAME']['PackageURL']}"
action :create_if_missing
#notifies :start, "service[service_$NAME_jar]"
end
service "service_$NAME_jar" do
# Dirty trick to save the java pid to a file
start_command "start-stop-daemon -b --start --quiet --oknodo --pidfile /var/run/service-$NAME.pid --exec /bin/bash -- -c \"echo \\$\\$ > /var/run/service-$NAME.pid ; exec java -jar #{node['CHOReOSData']['serviceData']['$NAME']['InstallationDir']}/service-$NAME.jar\""
stop_command "start-stop-daemon --stop --signal 15 --quiet --oknodo --pidfile /var/run/service-$NAME.pid"
action :start
status_command "if ps -p `cat /var/run/service-$NAME.pid` > /dev/null ; then exit 0; else exit 1; fi"
supports :start => true, :stop => true, :status => true
end
| mpl-2.0 |
Yukarumya/Yukarum-Redfoxes | addon-sdk/source/test/test-require.js | 2278 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
'use strict';
const traceback = require('sdk/console/traceback');
const REQUIRE_LINE_NO = 29;
exports.test_no_args = function(assert) {
let passed = tryRequireModule(assert);
assert.ok(passed, 'require() with no args should raise helpful error');
};
exports.test_invalid_sdk_module = function (assert) {
let passed = tryRequireModule(assert, 'sdk/does-not-exist');
assert.ok(passed, 'require() with an invalid sdk module should raise');
};
exports.test_invalid_relative_module = function (assert) {
let passed = tryRequireModule(assert, './does-not-exist');
assert.ok(passed, 'require() with an invalid relative module should raise');
};
function tryRequireModule(assert, module) {
let passed = false;
try {
// This line number is important, referenced in REQUIRE_LINE_NO
let doesNotExist = require(module);
}
catch(e) {
checkError(assert, module, e);
passed = true;
}
return passed;
}
function checkError (assert, name, e) {
let msg = e.toString();
if (name) {
assert.ok(/is not found at/.test(msg),
'Error message indicates module not found');
assert.ok(msg.indexOf(name.replace(/\./g,'')) > -1,
'Error message has the invalid module name in the message');
}
else {
assert.equal(msg.indexOf('Error: You must provide a module name when calling require() from '), 0);
assert.ok(msg.indexOf("test-require") !== -1, msg);
}
// we'd also like to assert that the right filename
// and linenumber is in the stacktrace
let tb = traceback.fromException(e);
// The last frame may be inside a loader
let lastFrame = tb[tb.length - 1];
if (lastFrame.fileName.indexOf("toolkit/loader.js") !== -1 ||
lastFrame.fileName.indexOf("sdk/loader/cuddlefish.js") !== -1)
lastFrame = tb[tb.length - 2];
assert.ok(lastFrame.fileName.indexOf("test-require.js") !== -1,
'Filename found in stacktrace');
assert.equal(lastFrame.lineNumber, REQUIRE_LINE_NO,
'stacktrace has correct line number');
}
require('sdk/test').run(exports);
| mpl-2.0 |
Yukarumya/Yukarum-Redfoxes | js/src/tests/test262/ch12/12.9/12.9-1.js | 869 | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch12/12.9/12.9-1.js
* @description The return Statement - a return statement without an expression may have a LineTerminator before the semi-colon
*/
function testcase() {
var sum = 0;
(function innerTest() {
for (var i = 1; i <= 10; i++) {
if (i === 6) {
return
;
}
sum += i;
}
})();
return sum === 15;
}
runTestCase(testcase);
| mpl-2.0 |
imujjwal96/Brime | app/src/androidTest/java/com/procleus/brime/ApplicationTest.java | 349 | package com.procleus.brime;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | agpl-3.0 |
FreecraftCore/FreecraftCore.Serializer | src/FreecraftCore.Serializer.Compiler/IsExternalInit.cs | 220 | ๏ปฟ//See: https://stackoverflow.com/questions/64749385/predefined-type-system-runtime-compilerservices-isexternalinit-is-not-defined
namespace System.Runtime.CompilerServices
{
internal static class IsExternalInit { }
} | agpl-3.0 |
roselleebarle04/AIDR | aidr-persister/src/main/java/qa/qcri/aidr/persister/api/Persister4CollectionAPI.java | 3052 | /**
* REST Web Service
*
* @author Imran
*/
package qa.qcri.aidr.persister.api;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import qa.qcri.aidr.persister.collction.RedisCollectionPersister;
import qa.qcri.aidr.utils.GenericCache;
import qa.qcri.aidr.utils.PersisterConfigurationProperty;
import qa.qcri.aidr.utils.PersisterConfigurator;
@Path("collectionPersister")
public class Persister4CollectionAPI {
private static Logger logger = Logger.getLogger(Persister4CollectionAPI.class.getName());
@GET
@Path("/start")
@Produces(MediaType.APPLICATION_JSON)
public Response startPersister(@QueryParam("channel_provider") String provider, @QueryParam("collection_code") String code) {
String response = "";
try {
String channel = StringUtils.defaultIfBlank(provider, "") + "." + StringUtils.defaultIfBlank(code, "");
if (StringUtils.isNotEmpty(code)) {
if (GenericCache.getInstance().getCollectionPersisterObject(code) != null) {
response = "A persister is already running for this channel [" + channel + "]";
return Response.ok(response).build();
}
RedisCollectionPersister p = new RedisCollectionPersister(PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.DEFAULT_PERSISTER_FILE_PATH), channel, code);
p.startMe();
GenericCache.getInstance().setCollectionPersisterMap(code, p);
response = "Started persisting to " + PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.DEFAULT_PERSISTER_FILE_PATH);
return Response.ok(response).build();
}
} catch (Exception ex) {
logger.error(code + ": Failed to start persister");
response = "Failed to start persister " + ex.getMessage();
}
return Response.ok(response).build();
}
@GET
@Path("/stop")
@Produces(MediaType.APPLICATION_JSON)
public Response stopPersister(@QueryParam("collection_code") String code) {
String response;
try {
logger.debug(code + "Aborting persister...");
RedisCollectionPersister persister = GenericCache.getInstance().delCollectionPersisterMap(code);
if(persister != null)
persister.suspendMe();
logger.info("Aborting done for " + code);
response = "Persistance of [" + code + "] has been stopped.";
return Response.ok(response).build();
} catch (InterruptedException ex) {
logger.error(code + ": Failed to stop persister");
}
response = "Unable to locate a running persister with the given collection code:[" + code + "]";
return Response.ok(response).build();
}
}
| agpl-3.0 |
krille90/unitystation | UnityProject/Assets/Scripts/Electricity/PoweredDevices/APCPoweredDevice.cs | 3519 | ๏ปฟusing System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
using Mirror;
using Debug = UnityEngine.Debug;
public class APCPoweredDevice : NetworkBehaviour, IServerDespawn
{
public float MinimumWorkingVoltage = 190;
public float MaximumWorkingVoltage = 300;
public DeviceType deviceType = DeviceType.None;
[SerializeField]
private bool isSelfPowered = false;
public bool IsSelfPowered => isSelfPowered;
[SerializeField]
private float wattusage = 0.01f;
public float Wattusage
{
get { return wattusage; }
set
{
wattusage = value;
Resistance = 240 / (value / 240);
}
}
public float Resistance = 99999999;
public APC RelatedAPC;
public IAPCPowered Powered;
public bool AdvancedControlToScript;
public bool StateUpdateOnClient = true;
[SyncVar(hook = nameof(UpdateSynchronisedState))]
public PowerStates State;
private void Awake()
{
EnsureInit();
}
void Start()
{
Logger.LogTraceFormat("{0}({1}) starting, state {2}", Category.Electrical, name, transform.position.To2Int(), State);
if (Wattusage > 0)
{
Resistance = 240 / (Wattusage / 240);
}
}
private void EnsureInit()
{
if (Powered != null) return;
Powered = GetComponent<IAPCPowered>();
}
public void SetAPC(APC _APC)
{
if (_APC == null) return;
RemoveFromAPC();
RelatedAPC = _APC;
RelatedAPC.ConnectedDevices.Add(this);
}
public void RemoveFromAPC()
{
if (RelatedAPC == null) return;
if (RelatedAPC.ConnectedDevices.Contains(this))
{
RelatedAPC.ConnectedDevices.Remove(this);
PowerNetworkUpdate(0.1f);
}
}
public override void OnStartClient()
{
EnsureInit();
UpdateSynchronisedState(State, State);
}
public override void OnStartServer()
{
EnsureInit();
UpdateSynchronisedState(State, State);
}
public void PowerNetworkUpdate(float Voltage) //Could be optimised to not update when voltage is same as previous voltage
{
if (Powered == null) return;
if (AdvancedControlToScript)
{
Powered.PowerNetworkUpdate(Voltage);
}
else
{
var NewState = PowerStates.Off;
if (Voltage <= 1)
{
NewState = PowerStates.Off;
}
else if (Voltage > MaximumWorkingVoltage)
{
NewState = PowerStates.OverVoltage;
}
else if (Voltage < MinimumWorkingVoltage)
{
NewState = PowerStates.LowVoltage;
}
else {
NewState = PowerStates.On;
}
if (NewState == State) return;
State = NewState;
Powered.StateUpdate(State);
}
}
private void UpdateSynchronisedState(PowerStates _OldState, PowerStates _State)
{
EnsureInit();
if (_State != State)
{
Logger.LogTraceFormat("{0}({1}) state changing {2} to {3}", Category.Electrical, name, transform.position.To2Int(), State, _State);
}
State = _State;
if (Powered != null && StateUpdateOnClient)
{
Powered.StateUpdate(State);
}
}
void OnDrawGizmosSelected()
{
if (RelatedAPC == null)
{
if (isSelfPowered) return;
Gizmos.color = new Color(1f, 0f, 0, 1);
Gizmos.DrawCube(gameObject.transform.position,new Vector3(0.3f,0.3f));
return;
}
//Highlighting APC
Gizmos.color = new Color(0.5f, 0.5f, 1, 1);
Gizmos.DrawLine(RelatedAPC.transform.position, gameObject.transform.position);
Gizmos.DrawSphere(RelatedAPC.transform.position, 0.15f);
}
public void OnDespawnServer(DespawnInfo info)
{
RemoveFromAPC();
}
}
public enum DeviceType
{
None,
Lights,
Environment,
Equipment
}
public enum PowerStates
{
Off,
LowVoltage,
On,
OverVoltage,
} | agpl-3.0 |
City-of-Bloomington/green-rental | rentrocket/settings.py | 10440 | # Django settings for rentrocket project.
import os
# Set up relative references with "os"
BASE_DIR = os.path.abspath(os.path.dirname(__file__)) + os.sep
# Make sure the project is on the PYTHONPATH
import sys
if BASE_DIR not in sys.path:
sys.path.append(BASE_DIR)
ADMINS = (
#('Admin', 'admin@rentrocket.org'),
)
MANAGERS = ADMINS
#STATIC_ROOT = 'static'
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
#FORCE_PROD_DB = True
#SETTINGS_MODE='prod' ./manage.py syncdb
#https://developers.google.com/appengine/docs/python/cloud-sql/django
if (os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine')):
#or
#FORCE_PROD_DB):
# Running on production App Engine, so use a Google Cloud SQL database.
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '/cloudsql/rent-rocket:rent-rocket-db',
'NAME': 'rentrocket',
'USER': 'root',
}
}
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = BASE_DIR + '..' + os.sep + 'static'
# https://docs.djangoproject.com/en/dev/topics/email/
#https://bitbucket.org/andialbrecht/appengine_emailbackends/overview
EMAIL_BACKEND = 'appengine_emailbackend.EmailBackend'
#this needs to be the same as the one in the database:
SITE_ID = 2
elif os.getenv('SETTINGS_MODE') == 'prod':
# Running in development, but want to access the Google Cloud SQL instance
# in production.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '173.194.111.70',
'NAME': 'rentrocket',
'USER': 'root',
#add password in manually:
#or just change it!
'PASSWORD': '',
}
}
else:
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
#sqlite3 only works when running with manage.py
#will not work when running under app engine:
#'ENGINE': 'django.db.backends.sqlite3',
#'NAME': '../rentrocket_db.sq3',
# Running in development, so use a local MySQL database.
'ENGINE': 'django.db.backends.mysql',
'NAME': 'rentrocket',
'USER': 'rentrocket',
'PASSWORD': 'changeme',
#'HOST': 'localhost',
}
}
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = BASE_DIR + '..' + os.sep + 'static' + os.sep + 'auto'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
#BASE_DIR + 'static',
BASE_DIR + '..' + os.sep + 'static',
)
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
#this needs to be the same as the one in the database:
SITE_ID = 2
#after a database reset, this is the only one available
#SITE_ID = 1
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = [".rentrocket.org", ]
# 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 = 'America/New_York'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '6g)id=q6w^b4t1ya0sgk5!y8oo_bsd%s+k^symeds!t(6*-(2u'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'rentrocket.urls'
# Python dotted path to the WSGI application used by Django's runserver.
# not needed when using app engine for hosting:
# WSGI_APPLICATION = 'rentrocket.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates"
# or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
'rentrocket/templates',
#'registration_email/templates',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request",
"allauth.account.context_processors.account",
"allauth.socialaccount.context_processors.socialaccount",
)
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
"django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend",
)
LOGIN_REDIRECT_URL = '/'
SOCIALACCOUNT_QUERY_EMAIL = True
DEFAULT_FROM_EMAIL = "rentrocket@gmail.com"
# EMAIL_BACKEND configuration moved above
#http://stackoverflow.com/questions/18780729/django-allauth-verifying-email-only-on-non-social-signup
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'south',
'building',
'listing',
'city',
'content',
'inspection',
'manager',
'person',
'utility',
'source',
'allauth',
'allauth.account',
'allauth.socialaccount',
# ... include the providers you want to enable:
#'allauth.socialaccount.providers.angellist',
#'allauth.socialaccount.providers.bitly',
#'allauth.socialaccount.providers.dropbox',
# 'allauth.socialaccount.providers.facebook',
#'allauth.socialaccount.providers.github',
# 'allauth.socialaccount.providers.google',
#'allauth.socialaccount.providers.instagram',
# 'allauth.socialaccount.providers.linkedin',
#'allauth.socialaccount.providers.openid',
#'allauth.socialaccount.providers.persona',
#'allauth.socialaccount.providers.soundcloud',
#'allauth.socialaccount.providers.stackexchange',
#'allauth.socialaccount.providers.twitch',
# 'allauth.socialaccount.providers.twitter',
#'allauth.socialaccount.providers.vimeo',
#'allauth.socialaccount.providers.vk',
#'allauth.socialaccount.providers.weibo',
)
#for making file uploads work with Django on Google app engine.
#need the following settings, assembled from:
#https://docs.djangoproject.com/en/dev/topics/http/file-uploads/
#http://stackoverflow.com/questions/16034059/getting-google-app-engine-blob-info-in-django-view
FILE_UPLOAD_HANDLERS = ("content.custom_upload.BlobstoreFileUploadHandler", )
#these are the original (default) settings:
#("django.core.files.uploadhandler.MemoryFileUploadHandler",
# "django.core.files.uploadhandler.TemporaryFileUploadHandler",)
# 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,
},
}
}
| agpl-3.0 |
aborg0/RapidMiner-Unuk | src/com/rapidminer/gui/look/borders/ButtonBorder.java | 4542 | /*
* RapidMiner
*
* Copyright (C) 2001-2013 by Rapid-I and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapid-i.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.gui.look.borders;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.border.AbstractBorder;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.UIResource;
/**
* The UIResource for button borders.
*
* @author Ingo Mierswa
*/
public class ButtonBorder extends AbstractBorder implements UIResource {
private static final long serialVersionUID = 191853543634535781L;
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
g.translate(x, y);
JComponent jc = (JComponent) c;
boolean isRollover = false;
boolean isFocused = false;
if (jc instanceof JButton) {
isRollover = ((JButton) jc).getModel().isRollover();
isFocused = ((JButton) jc).hasFocus();
} else if (jc instanceof JComboBox) {
isFocused = ((JComboBox) jc).hasFocus();
}
Color c1 = new ColorUIResource(0);
Color c2 = new ColorUIResource(0);
Color c3 = new ColorUIResource(0);
Color c4 = new ColorUIResource(0);
Color c5 = new ColorUIResource(0);
Color c6 = new ColorUIResource(0);
if (isFocused) {
c1 = new ColorUIResource(105, 150, 225);
c2 = new ColorUIResource(92, 120, 166);
c3 = new ColorUIResource(130, 165, 220);
c4 = new ColorUIResource(210, 220, 240);
c5 = new ColorUIResource(163, 190, 230);
c6 = new ColorUIResource(120, 150, 205);
} else if (isRollover) {
c1 = new ColorUIResource(105, 190, 105);
c2 = new ColorUIResource(85, 140, 85);
c3 = new ColorUIResource(105, 165, 105);
c4 = new ColorUIResource(160, 210, 160);
c5 = new ColorUIResource(145, 200, 145);
c6 = new ColorUIResource(140, 190, 140);
} else {
c1 = new ColorUIResource(140, 140, 140);
c2 = new ColorUIResource(130, 130, 130);
c3 = new ColorUIResource(170, 170, 170);
c4 = new ColorUIResource(210, 210, 210);
c5 = new ColorUIResource(165, 165, 165);
c6 = new ColorUIResource(155, 155, 155);
}
g.setColor(c1);
g.drawLine(5, 0, w - 7, 0);
g.drawLine(0, 6, 0, h - 7);
g.drawLine(w - 1, 6, w - 1, h - 7);
g.setColor(c2);
g.drawLine(6, h - 1, w - 7, h - 1);
g.setColor(c5);
g.drawLine(0, 5, 1, 5);
g.drawLine(5, 1, 5, 0);
g.setColor(c1);
g.drawLine(1, 4, 1, 3);
g.drawLine(4, 1, 3, 1);
g.drawLine(3, 1, 1, 3);
g.setColor(c4);
g.drawLine(4, 0, 5, 1);
g.drawLine(0, 4, 1, 5);
g.drawLine(2, 3, 3, 2);
g.setColor(c5);
g.drawLine(w - 1, 5, w - 2, 5);
g.drawLine(w - 6, 0, w - 6, 1);
g.setColor(c1);
g.drawLine(w - 2, 4, w - 2, 3);
g.drawLine(w - 5, 1, w - 4, 1);
g.drawLine(w - 4, 1, w - 2, 3);
g.setColor(c4);
g.drawLine(w - 5, 0, w - 6, 1);
g.drawLine(w - 1, 4, w - 2, 5);
g.drawLine(w - 4, 2, w - 3, 3);
g.setColor(c3);
g.drawLine(2, h - 4, 3, h - 3);
g.drawLine(5, h - 2, 5, h - 1);
g.setColor(c5);
g.drawLine(0, h - 6, 1, h - 6);
g.setColor(c6);
g.drawLine(1, h - 5, 1, h - 4);
g.drawLine(4, h - 2, 3, h - 2);
g.drawLine(3, h - 2, 1, h - 4);
g.setColor(c3);
g.drawLine(w - 3, h - 4, w - 4, h - 3);
g.drawLine(w - 6, h - 2, w - 6, h - 1);
g.setColor(c5);
g.drawLine(w - 1, h - 6, w - 2, h - 6);
g.setColor(c6);
g.drawLine(w - 2, h - 5, w - 2, h - 4);
g.drawLine(w - 5, h - 2, w - 4, h - 2);
g.drawLine(w - 4, h - 2, w - 2, h - 4);
g.translate(-x, -y);
}
@Override
public Insets getBorderInsets(Component c) {
return new Insets(2, 2, 2, 2);
}
@Override
public Insets getBorderInsets(Component c, Insets insets) {
insets.top = insets.left = insets.right = 2;
insets.bottom = 5;
return insets;
}
}
| agpl-3.0 |
antoine-de/navitia | source/calendar/calendar_api.cpp | 3629 | /* Copyright ยฉ 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "calendar_api.h"
#include "type/pb_converter.h"
#include "calendar.h"
#include "ptreferential/ptreferential.h"
namespace navitia { namespace calendar {
void calendars(navitia::PbCreator& pb_creator,
const navitia::type::Data &d,
const std::string &start_date,
const std::string &end_date,
const size_t depth,
size_t count,
size_t start_page,
const std::string &filter,
const std::vector<std::string>& forbidden_uris) {
navitia::type::Indexes calendar_list;
boost::gregorian::date start_period(boost::gregorian::not_a_date_time);
boost::gregorian::date end_period(boost::gregorian::not_a_date_time);
if((!start_date.empty()) && (!end_date.empty())) {
try{
start_period = boost::gregorian::from_undelimited_string(start_date);
}catch(const std::exception& e) {
pb_creator.fill_pb_error(pbnavitia::Error::unable_to_parse,
"Unable to parse start_date, "+ std::string(e.what()));
return;
}
try{
end_period = boost::gregorian::from_undelimited_string(end_date);
}catch(const std::exception& e) {
pb_creator.fill_pb_error(pbnavitia::Error::unable_to_parse,
"Unable to parse end_date, "+ std::string(e.what()));
return;
}
}
auto action_period = boost::gregorian::date_period(start_period, end_period);
try{
Calendar calendar;
calendar_list = calendar.get_calendars(filter, forbidden_uris, d, action_period, pb_creator.now);
} catch(const ptref::parsing_error &parse_error) {
pb_creator.fill_pb_error(pbnavitia::Error::unable_to_parse, parse_error.more);
return;
} catch(const ptref::ptref_error &ptref_error){
pb_creator.fill_pb_error(pbnavitia::Error::bad_filter, ptref_error.more);
return;
}
size_t total_result = calendar_list.size();
calendar_list = paginate(calendar_list, count, start_page);
pb_creator.pb_fill(pb_creator.data->get_data<nt::Calendar>(calendar_list), depth);
pb_creator.make_paginate(total_result, start_page, count, pb_creator.calendars_size());
if (pb_creator.calendars_size() == 0) {
pb_creator.fill_pb_error(pbnavitia::Error::no_solution, pbnavitia::NO_SOLUTION,
"no solution found for calendars API");
}
}
}
}
| agpl-3.0 |
FullMetal210/milton2 | external/cardme/src/main/java/info/ineighborhood/cardme/vcard/features/KeyFeature.java | 5262 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package info.ineighborhood.cardme.vcard.features;
import info.ineighborhood.cardme.vcard.EncodingType;
import info.ineighborhood.cardme.vcard.types.media.KeyTextType;
/**
* Copyright (c) 2004, Neighborhood Technologies
* 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 Neighborhood Technologies nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
*
* @author George El-Haddad
* <br/>
* Feb 4, 2010
*
* <p><b>RFC 2426</b><br/>
* <b>3.7.2 KEY Type Definition</b>
* <ul>
* <li><b>Type name:</b> KEY</li>
* <li><b>Type purpose:</b> To specify a public key or authentication certificate associated with the object that the vCard represents.</li>
* <li><b>Type encoding:</b> The encoding MUST be reset to "b" using the ENCODING parameter in order to specify inline, encoded binary data. If the value is a text value, then the default encoding of 8bit is used and no explicit ENCODING parameter is needed.</li>
* <li><b>Type value:</b> A single value. The default is binary. It can also be reset to text value. The text value can be used to specify a text key.</li>
* <li><b>Type special note:</b> The type can also include the type parameter TYPE to specify the public key or authentication certificate format. The parameter type should specify an IANA registered public key or authentication certificate format. The parameter type can also specify a non-standard format.</li>
* </ul>
* </p>
*/
public interface KeyFeature extends TypeTools, TypeData {
/**
* <p>Returns the key as an array of bytes.</p>
*
* @return byte[]
*/
public byte[] getKey();
/**
* <p>Returns the encoding type of the key.</p>
*
* @return {@link EncodingType}
*/
public EncodingType getEncodingType();
/**
* <p>Returns the format type of the key.</p>
*
* @return {@link KeyTextType}
*/
public KeyTextType getKeyTextType();
/**
* <p>Sets the key.</p>
*
* @param keyBytes
*/
public void setKey(byte[] keyBytes);
/**
* <p>Sets the encoding type of the key.</p>
*
* @param encodingType
*/
public void setEncodingType(EncodingType encodingType);
/**
* <p>Sets the format type of the key.</p>
*
* @param keyTextType
*/
public void setKeyTextType(KeyTextType keyTextType);
/**
* <p>Returns true if this key has a format type.</p>
*
* @return boolean
*/
public boolean hasKeyTextType();
/**
* <p>Returns true if this key is stored in-line.</p>
*
* @return boolean
*/
public boolean isInline();
/**
* <p>Returns true if the key is stored in a compressed format.</p>
*
* @return boolean
*/
public boolean isSetCompression();
/**
* <p>Clears the key.</p>
*/
public void clearKey();
/**
* <p>Returns true if the key exists.</p>
*
* @return boolean
*/
public boolean hasKey();
/**
* <p>Returns a full copy of this object.</p>
*
* @return {@link KeyFeature}
*/
public KeyFeature clone();
} | agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/Nursing/src/ims/nursing/forms/skinbodychart/GenForm.java | 42250 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.nursing.forms.skinbodychart;
import ims.framework.*;
import ims.framework.controls.*;
import ims.framework.enumerations.*;
import ims.framework.utils.RuntimeAnchoring;
public class GenForm extends FormBridge
{
private static final long serialVersionUID = 1L;
public boolean canProvideData(IReportSeed[] reportSeeds)
{
return new ReportDataProvider(reportSeeds, this.getFormReportFields()).canProvideData();
}
public boolean hasData(IReportSeed[] reportSeeds)
{
return new ReportDataProvider(reportSeeds, this.getFormReportFields()).hasData();
}
public IReportField[] getData(IReportSeed[] reportSeeds)
{
return getData(reportSeeds, false);
}
public IReportField[] getData(IReportSeed[] reportSeeds, boolean excludeNulls)
{
return new ReportDataProvider(reportSeeds, this.getFormReportFields(), excludeNulls).getData();
}
private void validateContext(ims.framework.Context context)
{
if(context == null)
return;
if(!context.isValidContextType(ims.core.vo.CareContextShortVo.class))
throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.core.vo.CareContextShortVo' of the global context variable 'Core.CurrentCareContext' is not supported.");
if(!context.isValidContextType(ims.core.vo.ClinicalContactShortVo.class))
throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.core.vo.ClinicalContactShortVo' of the global context variable 'Core.CurrentClinicalContact' is not supported.");
if(!context.isValidContextType(ims.core.vo.PatientShort.class))
throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.core.vo.PatientShort' of the global context variable 'Core.PatientShort' is not supported.");
}
private void validateMandatoryContext(Context context)
{
if(new ims.framework.ContextVariable("Core.CurrentCareContext", "_cvp_Core.CurrentCareContext").getValueIsNull(context))
throw new ims.framework.exceptions.FormMandatoryContextMissingException("The required context data 'Core.CurrentCareContext' is not available.");
}
public boolean supportsRecordedInError()
{
return false;
}
public ims.vo.ValueObject getRecordedInErrorVo()
{
return null;
}
protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context) throws Exception
{
setContext(loader, form, appForm, factory, context, Boolean.FALSE, new Integer(0), null, null, new Integer(0));
}
protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context, Boolean skipContextValidation) throws Exception
{
setContext(loader, form, appForm, factory, context, skipContextValidation, new Integer(0), null, null, new Integer(0));
}
protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, ims.framework.Context context, Boolean skipContextValidation, Integer startControlID, ims.framework.utils.SizeInfo runtimeSize, ims.framework.Control control, Integer startTabIndex) throws Exception
{
if(loader == null); // this is to avoid eclipse warning only.
if(factory == null); // this is to avoid eclipse warning only.
if(runtimeSize == null); // this is to avoid eclipse warning only.
if(appForm == null)
throw new RuntimeException("Invalid application form");
if(startControlID == null)
throw new RuntimeException("Invalid startControlID");
if(control == null); // this is to avoid eclipse warning only.
if(startTabIndex == null)
throw new RuntimeException("Invalid startTabIndex");
this.context = context;
this.componentIdentifier = startControlID.toString();
this.formInfo = form.getFormInfo();
this.globalContext = new GlobalContext(context);
if(skipContextValidation == null || !skipContextValidation.booleanValue())
{
validateContext(context);
validateMandatoryContext(context);
}
super.setContext(form);
ims.framework.utils.SizeInfo designSize = new ims.framework.utils.SizeInfo(848, 632);
if(runtimeSize == null)
runtimeSize = designSize;
form.setWidth(runtimeSize.getWidth());
form.setHeight(runtimeSize.getHeight());
super.setFormReferences(FormReferencesFlyweightFactory.getInstance().create(Forms.class));
super.setImageReferences(ImageReferencesFlyweightFactory.getInstance().create(Images.class));
super.setGlobalContext(ContextBridgeFlyweightFactory.getInstance().create(GlobalContextBridge.class, context, false));
super.setLocalContext(new LocalContext(context, form.getFormInfo(), componentIdentifier));
// Panel Controls
RuntimeAnchoring anchoringHelper1 = new RuntimeAnchoring(designSize, runtimeSize, 8, 8, 832, 32, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT);
super.addControl(factory.getControl(Panel.class, new Object[] { control, new Integer(startControlID.intValue() + 1000), new Integer(anchoringHelper1.getX()), new Integer(anchoringHelper1.getY()), new Integer(anchoringHelper1.getWidth()), new Integer(anchoringHelper1.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFTRIGHT,"", new Integer(1), ""}));
// Label Controls
RuntimeAnchoring anchoringHelper2 = new RuntimeAnchoring(designSize, runtimeSize, 728, 40, 71, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1001), new Integer(anchoringHelper2.getX()), new Integer(anchoringHelper2.getY()), new Integer(anchoringHelper2.getWidth()), new Integer(anchoringHelper2.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT, "Skin Intact:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper3 = new RuntimeAnchoring(designSize, runtimeSize, 16, 64, 92, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1002), new Integer(anchoringHelper3.getX()), new Integer(anchoringHelper3.getY()), new Integer(anchoringHelper3.getWidth()), new Integer(anchoringHelper3.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Authoring HCP:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper4 = new RuntimeAnchoring(designSize, runtimeSize, 16, 40, 130, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1003), new Integer(anchoringHelper4.getX()), new Integer(anchoringHelper4.getY()), new Integer(anchoringHelper4.getWidth()), new Integer(anchoringHelper4.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "Authoring Date/Time:", new Integer(1), null, new Integer(0)}));
// Button Controls
RuntimeAnchoring anchoringHelper5 = new RuntimeAnchoring(designSize, runtimeSize, 754, 592, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1004), new Integer(anchoringHelper5.getX()), new Integer(anchoringHelper5.getY()), new Integer(anchoringHelper5.getWidth()), new Integer(anchoringHelper5.getHeight()), new Integer(startTabIndex.intValue() + 9), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Close", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
RuntimeAnchoring anchoringHelper6 = new RuntimeAnchoring(designSize, runtimeSize, 754, 592, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1005), new Integer(anchoringHelper6.getX()), new Integer(anchoringHelper6.getY()), new Integer(anchoringHelper6.getWidth()), new Integer(anchoringHelper6.getHeight()), new Integer(startTabIndex.intValue() + 8), ControlState.HIDDEN, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Cancel", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
RuntimeAnchoring anchoringHelper7 = new RuntimeAnchoring(designSize, runtimeSize, 674, 592, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1006), new Integer(anchoringHelper7.getX()), new Integer(anchoringHelper7.getY()), new Integer(anchoringHelper7.getWidth()), new Integer(anchoringHelper7.getHeight()), new Integer(startTabIndex.intValue() + 7), ControlState.HIDDEN, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Save", Boolean.TRUE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
RuntimeAnchoring anchoringHelper8 = new RuntimeAnchoring(designSize, runtimeSize, 16, 592, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1007), new Integer(anchoringHelper8.getX()), new Integer(anchoringHelper8.getY()), new Integer(anchoringHelper8.getWidth()), new Integer(anchoringHelper8.getHeight()), new Integer(startTabIndex.intValue() + 6), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "New", Boolean.TRUE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
// TextBox Controls
RuntimeAnchoring anchoringHelper9 = new RuntimeAnchoring(designSize, runtimeSize, 152, 64, 144, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1008), new Integer(anchoringHelper9.getX()), new Integer(anchoringHelper9.getY()), new Integer(anchoringHelper9.getWidth()), new Integer(anchoringHelper9.getHeight()), new Integer(startTabIndex.intValue() + 3), ControlState.DISABLED, ControlState.DISABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.FALSE, new Integer(0), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""}));
// Date Controls
RuntimeAnchoring anchoringHelper10 = new RuntimeAnchoring(designSize, runtimeSize, 152, 40, 104, 20, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(DateControl.class, new Object[] { control, new Integer(startControlID.intValue() + 1009), new Integer(anchoringHelper10.getX()), new Integer(anchoringHelper10.getY()), new Integer(anchoringHelper10.getWidth()), new Integer(anchoringHelper10.getHeight()), new Integer(startTabIndex.intValue() + 1), ControlState.DISABLED, ControlState.DISABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.TRUE, null, Boolean.FALSE, null, Boolean.FALSE, null}));
// CheckBox Controls
RuntimeAnchoring anchoringHelper11 = new RuntimeAnchoring(designSize, runtimeSize, 800, 40, 24, 16, ims.framework.enumerations.ControlAnchoring.TOPRIGHT);
super.addControl(factory.getControl(CheckBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1010), new Integer(anchoringHelper11.getX()), new Integer(anchoringHelper11.getY()), new Integer(anchoringHelper11.getWidth()), new Integer(anchoringHelper11.getHeight()), new Integer(startTabIndex.intValue() + 4), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.TOPRIGHT ,"", Boolean.TRUE, null}));
// Time Controls
RuntimeAnchoring anchoringHelper12 = new RuntimeAnchoring(designSize, runtimeSize, 256, 40, 40, 21, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(TimeControl.class, new Object[] { control, new Integer(startControlID.intValue() + 1011), new Integer(anchoringHelper12.getX()), new Integer(anchoringHelper12.getY()), new Integer(anchoringHelper12.getWidth()), new Integer(anchoringHelper12.getHeight()), new Integer(startTabIndex.intValue() + 2), ControlState.DISABLED, ControlState.DISABLED, ims.framework.enumerations.ControlAnchoring.TOPLEFT,Boolean.TRUE, Boolean.FALSE, null, Boolean.FALSE, ""}));
// Drawing Controls
RuntimeAnchoring anchoringHelper13 = new RuntimeAnchoring(designSize, runtimeSize, 16, 96, 813, 480, ims.framework.enumerations.ControlAnchoring.ALL);
super.addControl(factory.getControl(DrawingControl.class, new Object[] { control, new Integer(startControlID.intValue() + 1012), new Integer(anchoringHelper13.getX()), new Integer(anchoringHelper13.getY()), new Integer(anchoringHelper13.getWidth()), new Integer(anchoringHelper13.getHeight()), new Integer(startTabIndex.intValue() + 5), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL, new Boolean(true)}));
}
public Forms getForms()
{
return (Forms)super.getFormReferences();
}
public Images getImages()
{
return (Images)super.getImageReferences();
}
public Button btnClose()
{
return (Button)super.getControl(4);
}
public Button btnCancel()
{
return (Button)super.getControl(5);
}
public Button bSave()
{
return (Button)super.getControl(6);
}
public Button bNew()
{
return (Button)super.getControl(7);
}
public TextBox textBoxHCP()
{
return (TextBox)super.getControl(8);
}
public DateControl dateAssess()
{
return (DateControl)super.getControl(9);
}
public CheckBox chkSkinIntact()
{
return (CheckBox)super.getControl(10);
}
public TimeControl timeAssess()
{
return (TimeControl)super.getControl(11);
}
public DrawingControl drawingBodyChart()
{
return (DrawingControl)super.getControl(12);
}
public static class Forms implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
protected final class LocalFormName extends FormName
{
private static final long serialVersionUID = 1L;
private LocalFormName(int name)
{
super(name);
}
}
private Forms()
{
Nursing = new NursingForms();
COE = new COEForms();
SpinalInjuries = new SpinalInjuriesForms();
Core = new CoreForms();
}
public final class NursingForms implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
private NursingForms()
{
SkinReviewDialog = new LocalFormName(101143);
SkinReview = new LocalFormName(101142);
SkinBodyChartDialog = new LocalFormName(101189);
}
public final FormName SkinReviewDialog;
public final FormName SkinReview;
public final FormName SkinBodyChartDialog;
}
public final class COEForms implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
private COEForms()
{
AssessSkin = new LocalFormName(101112);
}
public final FormName AssessSkin;
}
public final class SpinalInjuriesForms implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
private SpinalInjuriesForms()
{
NurAssessmentSkin = new LocalFormName(105114);
}
public final FormName NurAssessmentSkin;
}
public final class CoreForms implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
private CoreForms()
{
YesNoDialog = new LocalFormName(102107);
}
public final FormName YesNoDialog;
}
public NursingForms Nursing;
public COEForms COE;
public SpinalInjuriesForms SpinalInjuries;
public CoreForms Core;
}
public static class Images implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
private final class ImageHelper extends ims.framework.utils.ImagePath
{
private static final long serialVersionUID = 1L;
private ImageHelper(int id, String path, Integer width, Integer height)
{
super(id, path, width, height);
}
}
private Images()
{
COE = new COEImages();
}
public final class COEImages implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
private COEImages()
{
Blue = new ImageHelper(101100, "Images/COE/blue12x12.gif", new Integer(12), new Integer(12));
BlueViolet = new ImageHelper(101101, "Images/COE/violet12x12.gif", new Integer(12), new Integer(12));
BodyChart = new ImageHelper(101110, "Images/COE/Body_new_colour.gif", new Integer(325), new Integer(325));
DarkCyan = new ImageHelper(101102, "Images/COE/darkcyan12x12.gif", new Integer(12), new Integer(12));
Hotpink = new ImageHelper(101103, "Images/COE/Hotpink.gif", new Integer(12), new Integer(12));
LightSeaGreen = new ImageHelper(101104, "Images/COE/LightSeaGreen.gif", new Integer(12), new Integer(12));
LightSkyBlue = new ImageHelper(101105, "Images/COE/lightblue12x12.gif", new Integer(12), new Integer(12));
Orange = new ImageHelper(101106, "Images/COE/orange12x12.gif", new Integer(12), new Integer(12));
Red = new ImageHelper(101107, "Images/COE/Red.gif", new Integer(12), new Integer(12));
Yellow = new ImageHelper(101109, "Images/COE/Yellow.gif", new Integer(12), new Integer(12));
Turquoise = new ImageHelper(101108, "Images/COE/Turquoise.gif", new Integer(12), new Integer(12));
}
public final ims.framework.utils.Image Blue;
public final ims.framework.utils.Image BlueViolet;
public final ims.framework.utils.Image BodyChart;
public final ims.framework.utils.Image DarkCyan;
public final ims.framework.utils.Image Hotpink;
public final ims.framework.utils.Image LightSeaGreen;
public final ims.framework.utils.Image LightSkyBlue;
public final ims.framework.utils.Image Orange;
public final ims.framework.utils.Image Red;
public final ims.framework.utils.Image Yellow;
public final ims.framework.utils.Image Turquoise;
}
public final COEImages COE;
}
public GlobalContext getGlobalContext()
{
return this.globalContext;
}
public static class GlobalContextBridge extends ContextBridge
{
private static final long serialVersionUID = 1L;
}
public LocalContext getLocalContext()
{
return (LocalContext)super.getLocalCtx();
}
public class LocalContext extends ContextBridge
{
private static final long serialVersionUID = 1L;
public LocalContext(Context context, ims.framework.FormInfo formInfo, String componentIdentifier)
{
super.setContext(context);
String prefix = formInfo.getLocalVariablesPrefix();
cxl_SkinAssCollection = new ims.framework.ContextVariable("SkinAssCollection", prefix + "_lv_Nursing.SkinBodyChart.__internal_x_context__SkinAssCollection_" + componentIdentifier + "");
cxl_PreviousSkinAssessment = new ims.framework.ContextVariable("PreviousSkinAssessment", prefix + "_lv_Nursing.SkinBodyChart.__internal_x_context__PreviousSkinAssessment_" + componentIdentifier + "");
cxl_ImageLoaded = new ims.framework.ContextVariable("ImageLoaded", prefix + "_lv_Nursing.SkinBodyChart.__internal_x_context__ImageLoaded_" + componentIdentifier + "");
cxl_CurrentVersionNo = new ims.framework.ContextVariable("CurrentVersionNo", prefix + "_lv_Nursing.SkinBodyChart.__internal_x_context__CurrentVersionNo_" + componentIdentifier + "");
}
public boolean getSkinAssCollectionIsNotNull()
{
return !cxl_SkinAssCollection.getValueIsNull(context);
}
public ims.nursing.vo.SkinAssessmentCollection getSkinAssCollection()
{
return (ims.nursing.vo.SkinAssessmentCollection)cxl_SkinAssCollection.getValue(context);
}
public void setSkinAssCollection(ims.nursing.vo.SkinAssessmentCollection value)
{
cxl_SkinAssCollection.setValue(context, value);
}
private ims.framework.ContextVariable cxl_SkinAssCollection = null;
public boolean getPreviousSkinAssessmentIsNotNull()
{
return !cxl_PreviousSkinAssessment.getValueIsNull(context);
}
public ims.nursing.vo.SkinAssessment getPreviousSkinAssessment()
{
return (ims.nursing.vo.SkinAssessment)cxl_PreviousSkinAssessment.getValue(context);
}
public void setPreviousSkinAssessment(ims.nursing.vo.SkinAssessment value)
{
cxl_PreviousSkinAssessment.setValue(context, value);
}
private ims.framework.ContextVariable cxl_PreviousSkinAssessment = null;
public boolean getImageLoadedIsNotNull()
{
return !cxl_ImageLoaded.getValueIsNull(context);
}
public Boolean getImageLoaded()
{
return (Boolean)cxl_ImageLoaded.getValue(context);
}
public void setImageLoaded(Boolean value)
{
cxl_ImageLoaded.setValue(context, value);
}
private ims.framework.ContextVariable cxl_ImageLoaded = null;
public boolean getCurrentVersionNoIsNotNull()
{
return !cxl_CurrentVersionNo.getValueIsNull(context);
}
public Integer getCurrentVersionNo()
{
return (Integer)cxl_CurrentVersionNo.getValue(context);
}
public void setCurrentVersionNo(Integer value)
{
cxl_CurrentVersionNo.setValue(context, value);
}
private ims.framework.ContextVariable cxl_CurrentVersionNo = null;
}
private IReportField[] getFormReportFields()
{
if(this.context == null)
return null;
if(this.reportFields == null)
this.reportFields = new ReportFields(this.context, this.formInfo, this.componentIdentifier).getReportFields();
return this.reportFields;
}
private class ReportFields
{
public ReportFields(Context context, ims.framework.FormInfo formInfo, String componentIdentifier)
{
this.context = context;
this.formInfo = formInfo;
this.componentIdentifier = componentIdentifier;
}
public IReportField[] getReportFields()
{
String prefix = formInfo.getLocalVariablesPrefix();
IReportField[] fields = new IReportField[123];
fields[0] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ID", "ID_Patient");
fields[1] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SEX", "Sex");
fields[2] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOB", "Dob");
fields[3] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOD", "Dod");
fields[4] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-RELIGION", "Religion");
fields[5] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISACTIVE", "IsActive");
fields[6] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ETHNICORIGIN", "EthnicOrigin");
fields[7] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-MARITALSTATUS", "MaritalStatus");
fields[8] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SCN", "SCN");
fields[9] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SOURCEOFINFORMATION", "SourceOfInformation");
fields[10] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-TIMEOFDEATH", "TimeOfDeath");
fields[11] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISQUICKREGISTRATIONPATIENT", "IsQuickRegistrationPatient");
fields[12] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-CURRENTRESPONSIBLECONSULTANT", "CurrentResponsibleConsultant");
fields[13] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-ID", "ID_Patient");
fields[14] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-SEX", "Sex");
fields[15] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-DOB", "Dob");
fields[16] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ID", "ID_ClinicalContact");
fields[17] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-SPECIALTY", "Specialty");
fields[18] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CONTACTTYPE", "ContactType");
fields[19] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-STARTDATETIME", "StartDateTime");
fields[20] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ENDDATETIME", "EndDateTime");
fields[21] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CARECONTEXT", "CareContext");
fields[22] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ISCLINICALNOTECREATED", "IsClinicalNoteCreated");
fields[23] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ID", "ID_Hcp");
fields[24] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-HCPTYPE", "HcpType");
fields[25] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISACTIVE", "IsActive");
fields[26] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISHCPARESPONSIBLEHCP", "IsHCPaResponsibleHCP");
fields[27] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISARESPONSIBLEEDCLINICIAN", "IsAResponsibleEDClinician");
fields[28] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ID", "ID_CareContext");
fields[29] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-CONTEXT", "Context");
fields[30] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ORDERINGHOSPITAL", "OrderingHospital");
fields[31] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ESTIMATEDDISCHARGEDATE", "EstimatedDischargeDate");
fields[32] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-STARTDATETIME", "StartDateTime");
fields[33] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ENDDATETIME", "EndDateTime");
fields[34] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-LOCATIONTYPE", "LocationType");
fields[35] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-RESPONSIBLEHCP", "ResponsibleHCP");
fields[36] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ID", "ID_EpisodeOfCare");
fields[37] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-CARESPELL", "CareSpell");
fields[38] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-SPECIALTY", "Specialty");
fields[39] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-RELATIONSHIP", "Relationship");
fields[40] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-STARTDATE", "StartDate");
fields[41] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ENDDATE", "EndDate");
fields[42] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ID", "ID_ClinicalNotes");
fields[43] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALNOTE", "ClinicalNote");
fields[44] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTETYPE", "NoteType");
fields[45] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-DISCIPLINE", "Discipline");
fields[46] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALCONTACT", "ClinicalContact");
fields[47] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISDERIVEDNOTE", "IsDerivedNote");
fields[48] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEW", "ForReview");
fields[49] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline");
fields[50] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-REVIEWINGDATETIME", "ReviewingDateTime");
fields[51] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISCORRECTED", "IsCorrected");
fields[52] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISTRANSCRIBED", "IsTranscribed");
fields[53] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-SOURCEOFNOTE", "SourceOfNote");
fields[54] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-RECORDINGDATETIME", "RecordingDateTime");
fields[55] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-INHOSPITALREPORT", "InHospitalReport");
fields[56] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CARECONTEXT", "CareContext");
fields[57] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification");
fields[58] = new ims.framework.ReportField(this.context, "_cvp_STHK.AvailableBedsListFilter", "BO-1014100009-ID", "ID_BedSpaceState");
fields[59] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ID", "ID_PendingEmergencyAdmission");
fields[60] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ADMISSIONSTATUS", "AdmissionStatus");
fields[61] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ID", "ID_InpatientEpisode");
fields[62] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ESTDISCHARGEDATE", "EstDischargeDate");
fields[63] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-ID", "ID_ClinicalNotes");
fields[64] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEW", "ForReview");
fields[65] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline");
fields[66] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification");
fields[67] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-CARECONTEXT", "CareContext");
fields[68] = new ims.framework.ReportField(this.context, "_cvp_Core.PasEvent", "BO-1014100003-ID", "ID_PASEvent");
fields[69] = new ims.framework.ReportField(this.context, "_cvp_Correspondence.CorrespondenceDetails", "BO-1052100001-ID", "ID_CorrespondenceDetails");
fields[70] = new ims.framework.ReportField(this.context, "_cvp_CareUk.CatsReferral", "BO-1004100035-ID", "ID_CatsReferral");
fields[71] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.ReadOnlyAssessment", "BO-1003100002-ID", "ID_Assessment");
fields[72] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.ReadOnlyAssessment", "BO-1003100002-DATETIMEINITIATED", "DateTimeInitiated");
fields[73] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.ReadOnlyAssessment", "BO-1003100002-CLINICALCONTACT", "ClinicalContact");
fields[74] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.ReadOnlyAssessment", "BO-1003100002-CARECONTEXT", "CareContext");
fields[75] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.ReadOnlyAssessment", "BO-1016100003-ISSKININTACT", "IsSkinIntact");
fields[76] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.SelectedSkinAssessment", "BO-1003100002-ID", "ID_Assessment");
fields[77] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.SelectedSkinAssessment", "BO-1003100002-DATETIMEINITIATED", "DateTimeInitiated");
fields[78] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.SelectedSkinAssessment", "BO-1003100002-CLINICALCONTACT", "ClinicalContact");
fields[79] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.SelectedSkinAssessment", "BO-1003100002-CARECONTEXT", "CareContext");
fields[80] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.SelectedSkinAssessment", "BO-1016100003-ISSKININTACT", "IsSkinIntact");
fields[81] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.SkinAssessmentVO", "BO-1003100002-ID", "ID_Assessment");
fields[82] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.SkinAssessmentVO", "BO-1003100002-DATETIMEINITIATED", "DateTimeInitiated");
fields[83] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.SkinAssessmentVO", "BO-1003100002-CLINICALCONTACT", "ClinicalContact");
fields[84] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.SkinAssessmentVO", "BO-1003100002-CARECONTEXT", "CareContext");
fields[85] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.SkinAssessmentVO", "BO-1016100003-ISSKININTACT", "IsSkinIntact");
fields[86] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-ID", "ID_SkinAssessmentFindings");
fields[87] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-WOUNDTYPE", "WoundType");
fields[88] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-SITEIMAGE", "SiteImage");
fields[89] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-SITENAME", "SiteName");
fields[90] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-SITEDETAILS", "SiteDetails");
fields[91] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-HOWLONGISITPRESENT", "HowLongIsItPresent");
fields[92] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-PRESSURESOREGRADE", "PressureSoreGrade");
fields[93] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-LENGTH", "Length");
fields[94] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-WIDTH", "Width");
fields[95] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-DEPTH", "Depth");
fields[96] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-WOUNDBED", "WoundBed");
fields[97] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-SURROUNDINGSKIN", "SurroundingSkin");
fields[98] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-EXUDATEAMOUNT", "ExudateAmount");
fields[99] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-EXUDATETYPE", "ExudateType");
fields[100] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-ODOUR", "Odour");
fields[101] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-PAIN", "Pain");
fields[102] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-INFECTIONSUSPECTED", "InfectionSuspected");
fields[103] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-SWABTAKEN", "SwabTaken");
fields[104] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-WOUNDTRACED", "WoundTraced");
fields[105] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-CLEANSEDWITH", "CleansedWith");
fields[106] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-PRIMARYDRESSING", "PrimaryDressing");
fields[107] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-SECONDARYDRESSING", "SecondaryDressing");
fields[108] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-FREQUENCYOFCHANGE", "FrequencyOfChange");
fields[109] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-COMMENT", "Comment");
fields[110] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-ISDISCONTINUEDASSESS", "IsDiscontinuedAssess");
fields[111] = new ims.framework.ReportField(this.context, "_cv_COE.SkinBodyChart.FindingsVO", "BO-1016100005-ISCONTINUEDASSESSMENT", "IsContinuedAssessment");
fields[112] = new ims.framework.ReportField(this.context, "_cv_Nursing.AssessmentComponent", "BO-1015100001-ID", "ID_AssessmentComponent");
fields[113] = new ims.framework.ReportField(this.context, "_cv_Nursing.AssessmentComponent", "BO-1015100001-ISCOMPLETE", "IsComplete");
fields[114] = new ims.framework.ReportField(this.context, "_cv_Nursing.AssessmentComponent", "BO-1015100001-COPY", "Copy");
fields[115] = new ims.framework.ReportField(this.context, "_cv_Nursing.AssessmentComponent", "BO-1015100001-COMPONENTTYPE", "ComponentType");
fields[116] = new ims.framework.ReportField(this.context, "_cv_Nursing.AssessmentHeaderInfo", "BO-1003100002-ID", "ID_Assessment");
fields[117] = new ims.framework.ReportField(this.context, "_cv_Nursing.AssessmentHeaderInfo", "BO-1003100002-DATETIMEINITIATED", "DateTimeInitiated");
fields[118] = new ims.framework.ReportField(this.context, "_cv_Nursing.AssessmentHeaderInfo", "BO-1003100002-CLINICALCONTACT", "ClinicalContact");
fields[119] = new ims.framework.ReportField(this.context, "_cv_Nursing.AssessmentHeaderInfo", "BO-1003100002-CARECONTEXT", "CareContext");
fields[120] = new ims.framework.ReportField(this.context, "_cv_Nursing.AssessmentHeaderInfo", "BO-1015100000-ASSESSMENTTYPE", "AssessmentType");
fields[121] = new ims.framework.ReportField(this.context, "_cv_Nursing.AssessmentHeaderInfo", "BO-1015100000-ASSESSMENTSTATUS", "AssessmentStatus");
fields[122] = new ims.framework.ReportField(this.context, "_cv_Nursing.AssessmentHeaderInfo", "BO-1015100000-DATETIMECOMPLETE", "DateTimeComplete");
return fields;
}
protected Context context = null;
protected ims.framework.FormInfo formInfo;
protected String componentIdentifier;
}
public String getUniqueIdentifier()
{
return null;
}
private Context context = null;
private ims.framework.FormInfo formInfo = null;
private String componentIdentifier;
private GlobalContext globalContext = null;
private IReportField[] reportFields = null;
}
| agpl-3.0 |
dmeltzer/snipe-it | app/Models/Loggable.php | 5826 | <?php
namespace App\Models;
use App\Notifications\AuditNotification;
use Illuminate\Support\Facades\Auth;
trait Loggable
{
/**
* @author Daniel Meltzer <dmeltzer.devel@gmail.com>
* @since [v3.4]
* @return \App\Models\Actionlog
*/
public function log()
{
return $this->morphMany(Actionlog::class, 'item');
}
/**
* @author Daniel Meltzer <dmeltzer.devel@gmail.com>
* @since [v3.4]
* @return \App\Models\Actionlog
*/
public function logCheckout($note, $target, $action_date = null)
{
$log = new Actionlog;
$log = $this->determineLogItemType($log);
if(Auth::user())
$log->user_id = Auth::user()->id;
if (!isset($target)) {
throw new \Exception('All checkout logs require a target.');
return;
}
if (!isset($target->id)) {
throw new \Exception('That target seems invalid (no target ID available).');
return;
}
$log->target_type = get_class($target);
$log->target_id = $target->id;
// Figure out what the target is
if ($log->target_type == Location::class) {
$log->location_id = $target->id;
} elseif ($log->target_type == Asset::class) {
$log->location_id = $target->location_id;
} else {
$log->location_id = $target->location_id;
}
$log->note = $note;
$log->action_date = $action_date;
if (!$log->action_date) {
$log->action_date = date('Y-m-d H:i:s');
}
$log->logaction('checkout');
return $log;
}
/**
* Helper method to determine the log item type
*/
private function determineLogItemType($log)
{
// We need to special case licenses because of license_seat vs license. So much for clean polymorphism :
if (static::class == LicenseSeat::class) {
$log->item_type = License::class;
$log->item_id = $this->license_id;
} else {
$log->item_type = static::class;
$log->item_id = $this->id;
}
return $log;
}
/**
* @author Daniel Meltzer <dmeltzer.devel@gmail.com>
* @since [v3.4]
* @return \App\Models\Actionlog
*/
public function logCheckin($target, $note, $action_date = null)
{
$log = new Actionlog;
$log->target_type = get_class($target);
$log->target_id = $target->id;
if (static::class == LicenseSeat::class) {
$log->item_type = License::class;
$log->item_id = $this->license_id;
} else {
$log->item_type = static::class;
$log->item_id = $this->id;
if (static::class == Asset::class) {
if ($asset = Asset::find($log->item_id)) {
$asset->increment('checkin_counter', 1);
}
}
}
$log->location_id = null;
$log->note = $note;
$log->action_date = $action_date;
if (!$log->action_date) {
$log->action_date = date('Y-m-d H:i:s');
}
$log->user_id = Auth::user()->id;
$log->logaction('checkin from');
return $log;
}
/**
* @author A. Gianotto <snipe@snipe.net>
* @since [v4.0]
* @return \App\Models\Actionlog
*/
public function logAudit($note, $location_id, $filename = null)
{
$log = new Actionlog;
$location = Location::find($location_id);
if (static::class == LicenseSeat::class) {
$log->item_type = License::class;
$log->item_id = $this->license_id;
} else {
$log->item_type = static::class;
$log->item_id = $this->id;
}
$log->location_id = ($location_id) ? $location_id : null;
$log->note = $note;
$log->user_id = Auth::user()->id;
$log->filename = $filename;
$log->logaction('audit');
$params = [
'item' => $log->item,
'filename' => $log->filename,
'admin' => $log->user,
'location' => ($location) ? $location->name : '',
'note' => $note
];
Setting::getSettings()->notify(new AuditNotification($params));
return $log;
}
/**
* @author Daniel Meltzer <dmeltzer.devel@gmail.com>
* @since [v3.5]
* @return \App\Models\Actionlog
*/
public function logCreate($note = null)
{
$user_id = -1;
if (Auth::user()) {
$user_id = Auth::user()->id;
}
$log = new Actionlog;
if (static::class == LicenseSeat::class) {
$log->item_type = License::class;
$log->item_id = $this->license_id;
} else {
$log->item_type = static::class;
$log->item_id = $this->id;
}
$log->location_id = null;
$log->note = $note;
$log->user_id = $user_id;
$log->logaction('create');
$log->save();
return $log;
}
/**
* @author Daniel Meltzer <dmeltzer.devel@gmail.com>
* @since [v3.4]
* @return \App\Models\Actionlog
*/
public function logUpload($filename, $note)
{
$log = new Actionlog;
if (static::class == LicenseSeat::class) {
$log->item_type = License::class;
$log->item_id = $this->license_id;
} else {
$log->item_type = static::class;
$log->item_id = $this->id;
}
$log->user_id = Auth::user()->id;
$log->note = $note;
$log->target_id = null;
$log->created_at = date("Y-m-d H:i:s");
$log->filename = $filename;
$log->logaction('uploaded');
return $log;
}
}
| agpl-3.0 |
RestComm/jasn | asn-impl/src/main/java/org/mobicents/protocols/asn/AsnException.java | 1365 | /*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.protocols.asn;
/**
*
* @author amit bhayani
*
*/
public class AsnException extends Exception {
public AsnException() {
}
public AsnException(String message) {
super(message);
}
public AsnException(Throwable cause) {
super(cause);
}
public AsnException(String message, Throwable cause) {
super(message, cause);
}
}
| agpl-3.0 |
venturehive/canvas-lms | app/jsx/calendar/scheduler/reducer.js | 1247 | /*
* Copyright (C) 2016 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas 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 Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { handleActions } from 'redux-actions'
import SchedulerActions from './actions'
import initialState from './store/initialState'
const reducer = handleActions({
[SchedulerActions.keys.SET_FIND_APPOINTMENT_MODE]: (state = initialState, action) => {
return {
...state,
inFindAppointmentMode: action.payload
}
},
[SchedulerActions.keys.SET_COURSE]: (state = initialState, action) => {
return {
...state,
selectedCourse: action.payload
}
}
});
export default reducer
| agpl-3.0 |
Irstea/collec | display/node_modules/alpaca/src/js/views/jquerymobile.js | 4403 | /**
* jQuery Mobile Theme ("mobile")
*
* Defines the Alpaca theme for jQuery Mobile.
*
* The views are:
*
* jquerymobile-view
* jquerymobile-edit
* jquerymobile-create
*
* This theme can also be selected by specifying the following view:
*
* {
* "ui": "jquerymobile",
* "type": "view" | ""edit" | "create"
* }
*
*/(function($) {
var Alpaca = $.alpaca;
// custom styles
var styles = {};
styles["button"] = "";
styles["smallButton"] = "";
styles["addIcon"] = "ui-icon-plus ui-btn-icon-left alpaca-jqm-icon";
styles["removeIcon"] = "ui-icon-minus ui-btn-icon-left alpaca-jqm-icon";
styles["upIcon"] = "ui-icon-carat-u ui-btn-icon-left alpaca-jqm-icon";
styles["downIcon"] = "ui-icon-carat-d ui-btn-icon-left alpaca-jqm-icon";
styles["expandedIcon"] = "ui-icon-carat-r ui-btn-icon-left alpaca-jqm-icon";
styles["collapsedIcon"] = "ui-icon-carat-d ui-btn-icon-left alpaca-jqm-icon";
// custom callbacks
var callbacks = {};
callbacks["container"] = function()
{
var containerElem = this.getContainerEl();
var el = containerElem.find("[data-role='fieldcontain']");
if (el.fieldcontain)
{
el.fieldcontain();
el.find("[type='radio'], [type='checkbox']").checkboxradio();
el.find("button, [data-role='button'], [type='button'], [type='submit'], [type='reset'], [type='image']").not(".ui-nojs").button();
el.find("input, textarea").not("[type='radio'], [type='checkbox'], button, [type='button'], [type='submit'], [type='reset'], [type='image']").textinput();
el.find("input, select").filter("[data-role='slider'], [data-type='range']").slider();
el.find("select:not([data-role='slider'])").selectmenu();
containerElem.find('[data-role="button"]').buttonMarkup();
containerElem.find('[data-role="controlgroup"]').controlgroup();
}
};
Alpaca.registerView({
"id": "jquerymobile-display",
"parent": "web-display",
"type": "display",
"ui":"jquerymobile",
"title": "Display view using jQuery Mobile",
"callbacks": callbacks,
"styles": styles,
//"legendStyle": "link",
//"toolbarStyle": "link",
//"buttonType": "link",
"messages": {
required: "Required Field",
invalid: "Invalid Field"
},
"render": function(field, renderedCallback) {
var self = this;
field.render(field.view, function(field) {
refreshPageForField(field.getFieldEl());
if (renderedCallback) {
renderedCallback.call(self, field);
}
});
},
"templates": {}
});
Alpaca.registerView({
"id": "jquerymobile-display-horizontal",
"parent": "jquerymobile-display",
"horizontal": true
});
Alpaca.registerView({
"id": "jquerymobile-edit",
"parent": "web-edit",
"type": "edit",
"ui": "jquerymobile",
"title": "Edit View for jQuery Mobile",
"callbacks": callbacks,
"styles": styles,
"templates": {},
"messages": {
required: "Required Field",
invalid: "Invalid Field"
},
"render": function(field, renderedCallback) {
var self = this;
field.render(function(field) {
refreshPageForField(field.getFieldEl());
if (renderedCallback) {
renderedCallback.call(self, field);
}
});
}
});
Alpaca.registerView({
"id": "jquerymobile-edit-horizontal",
"parent": "jquerymobile-edit",
"horizontal": true
});
var refreshPageForField = function(fieldEl)
{
// find the data-role="page" and refresh it
var el = fieldEl;
if (el)
{
while (el.attr("data-role") !== "page")
{
el = el.parent();
}
$(el).trigger('create');
}
};
Alpaca.registerView({
"id": "jquerymobile-create",
"parent": "jquerymobile-edit",
"type": "create",
"title": "Create view for jQuery Mobile",
"displayReadonly": false
});
})(jQuery); | agpl-3.0 |
sysraj86/carnivalcrm | custom/Extension/modules/relationships/language/Quotes.php | 516 | <?php
//THIS FILE IS AUTO GENERATED, DO NOT MODIFY
$mod_strings['LBL_ACCOUNTS_QUOTES_FROM_ACCOUNTS_TITLE'] = 'GITs';
$mod_strings['LBL_CONTACTS_QUOTES_FROM_CONTACTS_TITLE'] = 'Contacts';
$mod_strings['LBL_QUOTES_TOURS_FROM_TOURS_TITLE'] = 'Tours';
$mod_strings['LBL_QUOTES_ODERS_FROM_ODERS_TITLE'] = 'Oders';
$mod_strings['LBL_FITS_QUOTES_FROM_FITS_TITLE'] = 'FITs';
$mod_strings['LBL_ORDERS_QUOTES_FROM_ORDERS_TITLE'] = 'Orders';
$mod_strings['LBL_OPPORTUNITIES_QUOTES_FROM_OPPORTUNITIES_TITLE'] = 'Opportunities';
| agpl-3.0 |
rogpeppe/juju | cmd/juju/removeunit.go | 1207 | // Copyright 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package main
import (
"fmt"
"github.com/juju/cmd"
"github.com/juju/names"
"github.com/juju/juju/cmd/envcmd"
"github.com/juju/juju/juju"
)
// RemoveUnitCommand is responsible for destroying service units.
type RemoveUnitCommand struct {
envcmd.EnvCommandBase
UnitNames []string
}
func (c *RemoveUnitCommand) Info() *cmd.Info {
return &cmd.Info{
Name: "remove-unit",
Args: "<unit> [...]",
Purpose: "remove service units from the environment",
Aliases: []string{"destroy-unit"},
}
}
func (c *RemoveUnitCommand) Init(args []string) error {
c.UnitNames = args
if len(c.UnitNames) == 0 {
return fmt.Errorf("no units specified")
}
for _, name := range c.UnitNames {
if !names.IsUnit(name) {
return fmt.Errorf("invalid unit name %q", name)
}
}
return nil
}
// Run connects to the environment specified on the command line and destroys
// units therein.
func (c *RemoveUnitCommand) Run(_ *cmd.Context) error {
client, err := juju.NewAPIClientFromName(c.EnvName)
if err != nil {
return err
}
defer client.Close()
return client.DestroyServiceUnits(c.UnitNames...)
}
| agpl-3.0 |
gangadhar-kadam/sapphire_app | patches/january_2013/give_report_permission_on_read.py | 239 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
# License: GNU General Public License v3. See license.txt
import webnotes
def execute():
webnotes.conn.sql("""update tabDocPerm set `report`=`read`
where ifnull(permlevel,0)=0""")
| agpl-3.0 |
horus68/SuiteCRM-Horus68 | Zend/Gdata/Photos/UserQuery.php | 9946 | <?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_Gdata
* @subpackage Photos
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* @see Zend_Gdata_Gapps_Query
*/
require_once('Zend/Gdata/Gapps/Query.php');
/**
* Assists in constructing queries for user entries.
* Instances of this class can be provided in many places where a URL is
* required.
*
* For information on submitting queries to a server, see the
* service class, Zend_Gdata_Photos.
*
* @category Zend
* @package Zend_Gdata
* @subpackage Photos
* @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 Zend_Gdata_Photos_UserQuery extends Zend_Gdata_Query
{
/**
* Indicates the format of data returned in Atom feeds. Can be either
* 'api' or 'base'. Default value is 'api'.
*
* @var string
*/
protected $_projection = 'api';
/**
* Indicates whether to request a feed or entry in queries. Default
* value is 'feed';
*
* @var string
*/
protected $_type = 'feed';
/**
* A string which, if not null, indicates which user should
* be retrieved by this query. If null, the default user will be used
* instead.
*
* @var string
*/
protected $_user = Zend_Gdata_Photos::DEFAULT_USER;
/**
* Create a new Query object with default values.
*/
public function __construct()
{
parent::__construct();
}
/**
* Set's the format of data returned in Atom feeds. Can be either
* 'api' or 'base'. Normally, 'api' will be desired. Default is 'api'.
*
* @param string $value
* @return Zend_Gdata_Photos_UserQuery Provides a fluent interface
*/
public function setProjection($value)
{
$this->_projection = $value;
return $this;
}
/**
* Gets the format of data in returned in Atom feeds.
*
* @see setProjection
* @return string projection
*/
public function getProjection()
{
return $this->_projection;
}
/**
* Set's the type of data returned in queries. Can be either
* 'feed' or 'entry'. Normally, 'feed' will be desired. Default is 'feed'.
*
* @param string $value
* @return Zend_Gdata_Photos_UserQuery Provides a fluent interface
*/
public function setType($value)
{
$this->_type = $value;
return $this;
}
/**
* Gets the type of data in returned in queries.
*
* @see setType
* @return string type
*/
public function getType()
{
return $this->_type;
}
/**
* Set the user to query for. When set, this user's feed will be
* returned. If not set or null, the default user's feed will be returned
* instead.
*
* @param string $value The user to retrieve, or null for the default
* user.
*/
public function setUser($value)
{
if ($value !== null) {
$this->_user = $value;
} else {
$this->_user = Zend_Gdata_Photos::DEFAULT_USER;
}
}
/**
* Get the user which is to be returned.
*
* @see setUser
* @return string The visibility to retrieve.
*/
public function getUser()
{
return $this->_user;
}
/**
* Set the visibility filter for entries returned. Only entries which
* match this value will be returned. If null or unset, the default
* value will be used instead.
*
* Valid values are 'all' (default), 'public', and 'private'.
*
* @param string $value The visibility to filter by, or null to use the
* default value.
*/
public function setAccess($value)
{
if ($value !== null) {
$this->_params['access'] = $value;
} else {
unset($this->_params['access']);
}
}
/**
* Get the visibility filter for entries returned.
*
* @see setAccess
* @return string The visibility to filter by, or null for the default
* user.
*/
public function getAccess()
{
return $this->_params['access'];
}
/**
* Set the tag for entries that are returned. Only entries which
* match this value will be returned. If null or unset, this filter will
* not be applied.
*
* See http://code.google.com/apis/picasaweb/reference.html#Parameters
* for a list of valid values.
*
* @param string $value The tag to filter by, or null if no
* filter is to be applied.
*/
public function setTag($value)
{
if ($value !== null) {
$this->_params['tag'] = $value;
} else {
unset($this->_params['tag']);
}
}
/**
* Get the tag filter for entries returned.
*
* @see setTag
* @return string The tag to filter by, or null if no filter
* is to be applied.
*/
public function getTag()
{
return $this->_params['tag'];
}
/**
* Set the kind of entries that are returned. Only entries which
* match this value will be returned. If null or unset, this filter will
* not be applied.
*
* See http://code.google.com/apis/picasaweb/reference.html#Parameters
* for a list of valid values.
*
* @param string $value The kind to filter by, or null if no
* filter is to be applied.
*/
public function setKind($value)
{
if ($value !== null) {
$this->_params['kind'] = $value;
} else {
unset($this->_params['kind']);
}
}
/**
* Get the kind of entries to be returned.
*
* @see setKind
* @return string The kind to filter by, or null if no filter
* is to be applied.
*/
public function getKind()
{
return $this->_params['kind'];
}
/**
* Set the maximum image size for entries returned. Only entries which
* match this value will be returned. If null or unset, this filter will
* not be applied.
*
* See http://code.google.com/apis/picasaweb/reference.html#Parameters
* for a list of valid values.
*
* @param string $value The image size to filter by, or null if no
* filter is to be applied.
*/
public function setImgMax($value)
{
if ($value !== null) {
$this->_params['imgmax'] = $value;
} else {
unset($this->_params['imgmax']);
}
}
/**
* Get the maximum image size filter for entries returned.
*
* @see setImgMax
* @return string The image size size to filter by, or null if no filter
* is to be applied.
*/
public function getImgMax()
{
return $this->_params['imgmax'];
}
/**
* Set the thumbnail size filter for entries returned. Only entries which
* match this value will be returned. If null or unset, this filter will
* not be applied.
*
* See http://code.google.com/apis/picasaweb/reference.html#Parameters
* for a list of valid values.
*
* @param string $value The thumbnail size to filter by, or null if no
* filter is to be applied.
*/
public function setThumbsize($value)
{
if ($value !== null) {
$this->_params['thumbsize'] = $value;
} else {
unset($this->_params['thumbsize']);
}
}
/**
* Get the thumbnail size filter for entries returned.
*
* @see setThumbsize
* @return string The thumbnail size to filter by, or null if no filter
* is to be applied.
*/
public function getThumbsize()
{
return $this->_params['thumbsize'];
}
/**
* Returns the URL generated for this query, based on it's current
* parameters.
*
* @return string A URL generated based on the state of this query.
* @throws Zend_Gdata_App_InvalidArgumentException
*/
public function getQueryUrl($incomingUri = null)
{
$uri = Zend_Gdata_Photos::PICASA_BASE_URI;
if ($this->getType() !== null) {
$uri .= '/' . $this->getType();
} else {
require_once 'Zend/Gdata/App/InvalidArgumentException.php';
throw new Zend_Gdata_App_InvalidArgumentException(
'Type must be feed or entry, not null'
);
}
if ($this->getProjection() !== null) {
$uri .= '/' . $this->getProjection();
} else {
require_once 'Zend/Gdata/App/InvalidArgumentException.php';
throw new Zend_Gdata_App_InvalidArgumentException(
'Projection must not be null'
);
}
if ($this->getUser() !== null) {
$uri .= '/user/' . $this->getUser();
} else {
// Should never occur due to setter behavior
require_once 'Zend/Gdata/App/InvalidArgumentException.php';
throw new Zend_Gdata_App_InvalidArgumentException(
'User must not be null'
);
}
$uri .= $incomingUri;
$uri .= $this->getQueryString();
return $uri;
}
}
| agpl-3.0 |
RBSWebFactory/modules.website | lib/phptal/FormElements.php | 4733 | <?php
class FormElement extends ChangeTalAttribute
{
/**
* @see ChangeTalAttribute::getEvaluatedParameters()
*
* @return String[]
*/
protected function getEvaluatedParameters()
{
return array('value', 'evaluatedname', 'evaluatedlabel');
}
/**
* @see ChangeTalAttribute::getRenderClassName()
*
* @return String
*/
protected function getRenderClassName()
{
return 'website_FormHelper';
}
}
/**
* Use in HTML: <anytag change:submit="name toto"/>
*/
class PHPTAL_Php_Attribute_CHANGE_submit extends FormElement
{
}
/**
* Use in HTML: <anytag change:textinput="name toto; label &modules.tutu.tata.titiLabel"/>
*/
class PHPTAL_Php_Attribute_CHANGE_textinput extends FormElement
{
}
class PHPTAL_Php_Attribute_CHANGE_radioinput extends FormElement
{
}
class PHPTAL_Php_Attribute_CHANGE_checkboxinput extends FormElement
{
}
class PHPTAL_Php_Attribute_CHANGE_passwordinput extends FormElement
{
}
class PHPTAL_Php_Attribute_CHANGE_booleaninput extends FormElement
{
}
class PHPTAL_Php_Attribute_CHANGE_fileinput extends FormElement
{
}
class PHPTAL_Php_Attribute_CHANGE_uploadfield extends FormElement
{
}
class PHPTAL_Php_Attribute_CHANGE_listmultifield extends FormElement
{
}
/**
* Use in HTML: <anytag change:dateinput="name toto; label &modules.tutu.tata.titiLabel; format dd/yy/uu"/>
*/
class PHPTAL_Php_Attribute_CHANGE_dateinput extends FormElement
{
/**
* @see FormElement::getEvaluatedParameters()
*
* @return array
*/
protected function getEvaluatedParameters()
{
$evaluatedParameters = parent::getEvaluatedParameters();
$evaluatedParameters[] = 'startdate';
$evaluatedParameters[] = 'enddate';
return $evaluatedParameters;
}
}
/**
* Use in HTML: <anytag change:dateinput="name toto; label &modules.tutu.tata.titiLabel; format dd/yy/uu"/>
*/
class PHPTAL_Php_Attribute_CHANGE_datecombo extends PHPTAL_Php_Attribute_CHANGE_dateinput
{
/**
* @return String
*/
protected function getRenderMethodName()
{
return 'renderDateCombo';
}
}
/**
* Use in HTML: <anytag change:errors="[key myKey]"/>
*/
class PHPTAL_Php_Attribute_CHANGE_errors extends FormElement
{
}
/**
* Use in HTML: <anytag change:messages="[key myKey]"/>
*/
class PHPTAL_Php_Attribute_CHANGE_messages extends FormElement
{
}
/**
* Use in HTML: <anytag change:hiddeninput="name toto;"/>
*/
class PHPTAL_Php_Attribute_CHANGE_hiddeninput extends FormElement
{
}
class PHPTAL_Php_Attribute_CHANGE_richtextinput extends FormElement
{
}
class PHPTAL_Php_Attribute_CHANGE_bbcodeinput extends FormElement
{
}
class PHPTAL_Php_Attribute_CHANGE_durationinput extends FormElement
{
}
class PHPTAL_Php_Attribute_CHANGE_selectinput extends FormElement
{
/**
* @see FormElement::getEvaluatedParameters()
*
* @return array
*/
protected function getEvaluatedParameters()
{
$evaluatedParameters = parent::getEvaluatedParameters();
$evaluatedParameters[] = 'list';
return $evaluatedParameters;
}
}
/**
* Use in HTML: <anytag change:field="name toto;"/>
*/
class PHPTAL_Php_Attribute_CHANGE_field extends FormElement
{
/**
* @see FormElement::getEvaluatedParameters()
*
* @return array
*/
protected function getEvaluatedParameters()
{
$evaluatedParameters = parent::getEvaluatedParameters();
$evaluatedParameters[] = 'startdate';
$evaluatedParameters[] = 'enddate';
return $evaluatedParameters;
}
}
/**
* Use in HTML: <anytag change:textarea="name toto;"/>
*/
class PHPTAL_Php_Attribute_CHANGE_textarea extends FormElement
{
}
class PHPTAL_Php_Attribute_CHANGE_fieldlabel extends FormElement
{
}
class PHPTAL_Php_Attribute_CHANGE_label extends FormElement
{
public function start()
{
// We rewrite element
$this->tag->headFootDisabled = true;
parent::start();
}
public function end()
{
$this->tag->generator->doEchoRaw('website_FormHelper::endLabel()');
}
}
/**
* Use in HTML: <anytag change:form="method get">[...]</anytag>
*/
class PHPTAL_Php_Attribute_CHANGE_form extends FormElement
{
/**
* @see ChangeTalAttribute::getDefaultValues()
*
* @return String[]
*/
protected function getDefaultValues()
{
return array('showErrors' => false);
}
public function start()
{
$this->tag->headFootDisabled = true;
parent::start();
}
/**
* @see ChangeTalAttribute::getRenderMethodName()
*
* @return String
*/
protected function getRenderMethodName()
{
return 'initialize';
}
public function end()
{
$this->tag->generator->doEcho('website_FormHelper::finalize()');
}
}
| agpl-3.0 |
harihpr/tweetclickers | test/test_admin.py | 31857 | # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyBossa 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PyBossa. If not, see <http://www.gnu.org/licenses/>.
import json
from helper import web
from default import db, with_context
from mock import patch
from collections import namedtuple
from bs4 import BeautifulSoup
from pybossa.model.user import User
from pybossa.model.app import App
from pybossa.model.task import Task
from pybossa.model.category import Category
FakeRequest = namedtuple('FakeRequest', ['text', 'status_code', 'headers'])
class TestAdmin(web.Helper):
pkg_json_not_found = {
"help": "Return ...",
"success": False,
"error": {
"message": "Not found",
"__type": "Not Found Error"}}
# Tests
@with_context
def test_00_first_user_is_admin(self):
"""Test ADMIN First Created user is admin works"""
self.register()
user = db.session.query(User).get(1)
assert user.admin == 1, "User ID:1 should be admin, but it is not"
@with_context
def test_01_admin_index(self):
"""Test ADMIN index page works"""
self.register()
res = self.app.get("/admin", follow_redirects=True)
dom = BeautifulSoup(res.data)
err_msg = "There should be an index page for admin users and projects"
assert "Settings" in res.data, err_msg
divs = ['featured-apps', 'users', 'categories', 'users-list']
for div in divs:
err_msg = "There should be a button for managing %s" % div
assert dom.find(id=div) is not None, err_msg
@with_context
def test_01_admin_index_anonymous(self):
"""Test ADMIN index page works as anonymous user"""
res = self.app.get("/admin", follow_redirects=True)
err_msg = ("The user should not be able to access this page"
" but the returned status is %s" % res.data)
assert "Please sign in to access this page" in res.data, err_msg
@with_context
def test_01_admin_index_authenticated(self):
"""Test ADMIN index page works as signed in user"""
self.register()
self.signout()
self.register(name="tester2", email="tester2@tester.com",
password="tester")
res = self.app.get("/admin", follow_redirects=True)
err_msg = ("The user should not be able to access this page"
" but the returned status is %s" % res.status)
assert "403 FORBIDDEN" in res.status, err_msg
@with_context
def test_02_second_user_is_not_admin(self):
"""Test ADMIN Second Created user is NOT admin works"""
self.register()
self.signout()
self.register(name="tester2", email="tester2@tester.com",
password="tester")
self.signout()
user = db.session.query(User).get(2)
assert user.admin == 0, "User ID: 2 should not be admin, but it is"
@with_context
def test_03_admin_featured_apps_as_admin(self):
"""Test ADMIN featured projects works as an admin user"""
self.register()
self.signin()
res = self.app.get('/admin/featured', follow_redirects=True)
assert "Manage featured projects" in res.data, res.data
@with_context
def test_04_admin_featured_apps_as_anonymous(self):
"""Test ADMIN featured projects works as an anonymous user"""
res = self.app.get('/admin/featured', follow_redirects=True)
assert "Please sign in to access this page" in res.data, res.data
@with_context
def test_05_admin_featured_apps_as_user(self):
"""Test ADMIN featured projects works as a signed in user"""
self.register()
self.signout()
self.register(name="tester2", email="tester2@tester.com",
password="tester")
res = self.app.get('/admin/featured', follow_redirects=True)
assert res.status == "403 FORBIDDEN", res.status
@with_context
@patch('pybossa.core.uploader.upload_file', return_value=True)
def test_06_admin_featured_apps_add_remove_app(self, mock):
"""Test ADMIN featured projects add-remove works as an admin user"""
self.register()
self.new_application()
self.update_application()
# The project is in the system but not in the front page
res = self.app.get('/', follow_redirects=True)
assert "Sample Project" not in res.data,\
"The project should not be listed in the front page"\
" as it is not featured"
# Only projects that have been published can be featured
self.new_task(1)
app = db.session.query(App).get(1)
app.info = dict(task_presenter="something")
db.session.add(app)
db.session.commit()
res = self.app.get('/admin/featured', follow_redirects=True)
assert "Featured" in res.data, res.data
assert "Sample Project" in res.data, res.data
# Add it to the Featured list
res = self.app.post('/admin/featured/1')
f = json.loads(res.data)
assert f['id'] == 1, f
assert f['featured'] == True, f
# Check can be removed from featured
res = self.app.get('/admin/featured', follow_redirects=True)
assert "Remove from Featured!" in res.data,\
"The project should have a button to remove from featured"
# A retry should fail
res = self.app.post('/admin/featured/1')
err = json.loads(res.data)
err_msg = "App.id 1 already featured"
assert err['error'] == err_msg, err_msg
assert err['status_code'] == 415, "Status code should be 415"
# Remove it again from the Featured list
res = self.app.delete('/admin/featured/1')
f = json.loads(res.data)
assert f['id'] == 1, f
assert f['featured'] == False, f
# Check that can be added to featured
res = self.app.get('/admin/featured', follow_redirects=True)
assert "Add to Featured!" in res.data,\
"The project should have a button to add to featured"
# If we try to delete again, it should return an error
res = self.app.delete('/admin/featured/1')
err = json.loads(res.data)
assert err['status_code'] == 415, "Project should not be found"
err_msg = 'App.id 1 is not featured'
assert err['error'] == err_msg, err_msg
# Try with an id that does not exist
res = self.app.delete('/admin/featured/999')
err = json.loads(res.data)
assert err['status_code'] == 404, "Project should not be found"
err_msg = 'App.id 999 not found'
assert err['error'] == err_msg, err_msg
@with_context
@patch('pybossa.core.uploader.upload_file', return_value=True)
def test_07_admin_featured_apps_add_remove_app_non_admin(self, mock):
"""Test ADMIN featured projects add-remove works as an non-admin user"""
self.register()
self.signout()
self.register(name="John2", email="john2@john.com",
password="passwd")
self.new_application()
# The project is in the system but not in the front page
res = self.app.get('/', follow_redirects=True)
err_msg = ("The project should not be listed in the front page"
"as it is not featured")
assert "Create a Project" in res.data, err_msg
res = self.app.get('/admin/featured', follow_redirects=True)
err_msg = ("The user should not be able to access this page"
" but the returned status is %s" % res.status)
assert "403 FORBIDDEN" in res.status, err_msg
# Try to add the project to the featured list
res = self.app.post('/admin/featured/1')
err_msg = ("The user should not be able to POST to this page"
" but the returned status is %s" % res.status)
assert "403 FORBIDDEN" in res.status, err_msg
# Try to remove it again from the Featured list
res = self.app.delete('/admin/featured/1')
err_msg = ("The user should not be able to DELETE to this page"
" but the returned status is %s" % res.status)
assert "403 FORBIDDEN" in res.status, err_msg
@with_context
@patch('pybossa.core.uploader.upload_file', return_value=True)
def test_08_admin_featured_apps_add_remove_app_anonymous(self, mock):
"""Test ADMIN featured projects add-remove works as an anonymous user"""
self.register()
self.new_application()
self.signout()
# The project is in the system but not in the front page
res = self.app.get('/', follow_redirects=True)
assert "Create a Project" in res.data,\
"The project should not be listed in the front page"\
" as it is not featured"
res = self.app.get('/admin/featured', follow_redirects=True)
err_msg = ("The user should not be able to access this page"
" but the returned status is %s" % res.data)
assert "Please sign in to access this page" in res.data, err_msg
# Try to add the project to the featured list
res = self.app.post('/admin/featured/1', follow_redirects=True)
err_msg = ("The user should not be able to POST to this page"
" but the returned status is %s" % res.data)
assert "Please sign in to access this page" in res.data, err_msg
# Try to remove it again from the Featured list
res = self.app.delete('/admin/featured/1', follow_redirects=True)
err_msg = ("The user should not be able to DELETE to this page"
" but the returned status is %s" % res.data)
assert "Please sign in to access this page" in res.data, err_msg
@with_context
def test_09_admin_users_as_admin(self):
"""Test ADMIN users works as an admin user"""
self.register()
res = self.app.get('/admin/users', follow_redirects=True)
assert "Manage Admin Users" in res.data, res.data
@with_context
def test_10_admin_user_not_listed(self):
"""Test ADMIN users does not list himself works"""
self.register()
res = self.app.get('/admin/users', follow_redirects=True)
assert "Manage Admin Users" in res.data, res.data
assert "Current Users with Admin privileges" not in res.data, res.data
assert "John" not in res.data, res.data
@with_context
def test_11_admin_user_not_listed_in_search(self):
"""Test ADMIN users does not list himself in the search works"""
self.register()
data = {'user': 'john'}
res = self.app.post('/admin/users', data=data, follow_redirects=True)
assert "Manage Admin Users" in res.data, res.data
assert "Current Users with Admin privileges" not in res.data, res.data
assert "John" not in res.data, res.data
@with_context
def test_12_admin_user_search(self):
"""Test ADMIN users search works"""
# Create two users
self.register()
self.signout()
self.register(fullname="Juan Jose", name="juan",
email="juan@juan.com", password="juan")
self.signout()
# Signin with admin user
self.signin()
data = {'user': 'juan'}
res = self.app.post('/admin/users', data=data, follow_redirects=True)
assert "Juan Jose" in res.data, "username should be searchable"
# Check with uppercase
data = {'user': 'JUAN'}
res = self.app.post('/admin/users', data=data, follow_redirects=True)
err_msg = "username search should be case insensitive"
assert "Juan Jose" in res.data, err_msg
# Search fullname
data = {'user': 'Jose'}
res = self.app.post('/admin/users', data=data, follow_redirects=True)
assert "Juan Jose" in res.data, "fullname should be searchable"
# Check with uppercase
data = {'user': 'JOsE'}
res = self.app.post('/admin/users', data=data, follow_redirects=True)
err_msg = "fullname search should be case insensitive"
assert "Juan Jose" in res.data, err_msg
# Warning should be issued for non-found users
data = {'user': 'nothingExists'}
res = self.app.post('/admin/users', data=data, follow_redirects=True)
warning = ("We didn't find a user matching your query: <strong>%s</strong>" %
data['user'])
err_msg = "A flash message should be returned for non-found users"
assert warning in res.data, err_msg
@with_context
def test_13_admin_user_add_del(self):
"""Test ADMIN add/del user to admin group works"""
self.register()
self.signout()
self.register(fullname="Juan Jose", name="juan",
email="juan@juan.com", password="juan")
self.signout()
# Signin with admin user
self.signin()
# Add user.id=1000 (it does not exist)
res = self.app.get("/admin/users/add/1000", follow_redirects=True)
err = json.loads(res.data)
assert res.status_code == 404, res.status_code
assert err['error'] == "User not found", err
assert err['status_code'] == 404, err
# Add user.id=2 to admin group
res = self.app.get("/admin/users/add/2", follow_redirects=True)
assert "Current Users with Admin privileges" in res.data
err_msg = "User.id=2 should be listed as an admin"
assert "Juan Jose" in res.data, err_msg
# Remove user.id=2 from admin group
res = self.app.get("/admin/users/del/2", follow_redirects=True)
assert "Current Users with Admin privileges" not in res.data
err_msg = "User.id=2 should be listed as an admin"
assert "Juan Jose" not in res.data, err_msg
# Delete a non existant user should return an error
res = self.app.get("/admin/users/del/5000", follow_redirects=True)
err = json.loads(res.data)
assert res.status_code == 404, res.status_code
assert err['error'] == "User.id not found", err
assert err['status_code'] == 404, err
@with_context
def test_14_admin_user_add_del_anonymous(self):
"""Test ADMIN add/del user to admin group works as anonymous"""
self.register()
self.signout()
self.register(fullname="Juan Jose", name="juan",
email="juan@juan.com", password="juan")
self.signout()
# Add user.id=2 to admin group
res = self.app.get("/admin/users/add/2", follow_redirects=True)
err_msg = "User should be redirected to signin"
assert "Please sign in to access this page" in res.data, err_msg
# Remove user.id=2 from admin group
res = self.app.get("/admin/users/del/2", follow_redirects=True)
err_msg = "User should be redirected to signin"
assert "Please sign in to access this page" in res.data, err_msg
@with_context
def test_15_admin_user_add_del_authenticated(self):
"""Test ADMIN add/del user to admin group works as authenticated"""
self.register()
self.signout()
self.register(fullname="Juan Jose", name="juan",
email="juan@juan.com", password="juan")
self.signout()
self.register(fullname="Juan Jose2", name="juan2",
email="juan2@juan.com", password="juan2")
self.signout()
self.signin(email="juan2@juan.com", password="juan2")
# Add user.id=2 to admin group
res = self.app.get("/admin/users/add/2", follow_redirects=True)
assert res.status == "403 FORBIDDEN",\
"This action should be forbidden, not enought privileges"
# Remove user.id=2 from admin group
res = self.app.get("/admin/users/del/2", follow_redirects=True)
assert res.status == "403 FORBIDDEN",\
"This action should be forbidden, not enought privileges"
@with_context
def test_16_admin_user_export(self):
"""Test ADMIN user list export works as admin"""
self.register()
self.signout()
self.register(fullname="Juan Jose", name="juan",
email="juan@juan.com", password="juan")
self.signout()
self.register(fullname="Juan Jose2", name="juan2",
email="juan2@juan.com", password="juan2")
self.signin()
# The user is redirected to '/admin/' if no format is specified
res = self.app.get('/admin/users/export', follow_redirects=True)
assert 'Featured Projects' in res.data, res.data
assert 'Administrators' in res.data, res.data
res = self.app.get('/admin/users/export?firmit=', follow_redirects=True)
assert 'Featured Projects' in res.data, res.data
assert 'Administrators' in res.data, res.data
# A 415 error is raised if the format is not supported (is not either json or csv)
res = self.app.get('/admin/users/export?format=bad',
follow_redirects=True)
assert res.status_code == 415, res.status_code
# JSON is a valid format for exports
res = self.app.get('/admin/users/export?format=json',
follow_redirects=True)
assert res.status_code == 200, res.status_code
assert res.mimetype == 'application/json', res.mimetype
#CSV is a valid format for exports
res = self.app.get('/admin/users/export?format=csv',
follow_redirects=True)
assert res.status_code == 200, res.status_code
assert res.mimetype == 'text/csv', res.mimetype
@with_context
def test_17_admin_user_export_anonymous(self):
"""Test ADMIN user list export works as anonymous user"""
self.register()
self.signout()
# Whichever the args of the request are, the user is redirected to login
res = self.app.get('/admin/users/export', follow_redirects=True)
dom = BeautifulSoup(res.data)
err_msg = "Anonymous users should be redirected to sign in"
assert dom.find(id='signin') is not None, err_msg
res = self.app.get('/admin/users/export?firmit=', follow_redirects=True)
dom = BeautifulSoup(res.data)
err_msg = "Anonymous users should be redirected to sign in"
assert dom.find(id='signin') is not None, err_msg
res = self.app.get('/admin/users/export?format=bad',
follow_redirects=True)
dom = BeautifulSoup(res.data)
err_msg = "Anonymous users should be redirected to sign in"
assert dom.find(id='signin') is not None, err_msg
res = self.app.get('/admin/users/export?format=json',
follow_redirects=True)
dom = BeautifulSoup(res.data)
err_msg = "Anonymous users should be redirected to sign in"
assert dom.find(id='signin') is not None, err_msg
@with_context
def test_18_admin_user_export_authenticated(self):
"""Test ADMIN user list export works as authenticated non-admin user"""
self.register()
self.signout()
self.register(fullname="Juan Jose", name="juan",
email="juan@juan.com", password="juan")
# No matter what params in the request, Forbidden is raised
res = self.app.get('/admin/users/export', follow_redirects=True)
assert res.status_code == 403, res.status_code
res = self.app.get('/admin/users/export?firmit=', follow_redirects=True)
assert res.status_code == 403, res.status_code
res = self.app.get('/admin/users/export?format=bad',
follow_redirects=True)
assert res.status_code == 403, res.status_code
res = self.app.get('/admin/users/export?format=json',
follow_redirects=True)
assert res.status_code == 403, res.status_code
@with_context
@patch('pybossa.ckan.requests.get')
@patch('pybossa.core.uploader.upload_file', return_value=True)
def test_19_admin_update_app(self, Mock, Mock2):
"""Test ADMIN can update a project that belongs to another user"""
html_request = FakeRequest(json.dumps(self.pkg_json_not_found), 200,
{'content-type': 'application/json'})
Mock.return_value = html_request
self.register()
self.signout()
self.register(fullname="Juan Jose", name="juan",
email="juan@juan.com", password="juan")
self.new_application()
self.signout()
# Sign in with the root user
self.signin()
res = self.app.get('/app/sampleapp/settings')
err_msg = "Admin users should be able to get the settings page for any project"
assert res.status == "200 OK", err_msg
res = self.update_application(method="GET")
assert "Update the project" in res.data,\
"The project should be updated by admin users"
res = self.update_application(new_name="Root",
new_short_name="rootsampleapp")
res = self.app.get('/app/rootsampleapp', follow_redirects=True)
assert "Root" in res.data, "The app should be updated by admin users"
app = db.session.query(App)\
.filter_by(short_name="rootsampleapp").first()
juan = db.session.query(User).filter_by(name="juan").first()
assert app.owner_id == juan.id, "Owner_id should be: %s" % juan.id
assert app.owner_id != 1, "The owner should be not updated"
res = self.update_application(short_name="rootsampleapp",
new_short_name="sampleapp",
new_long_description="New Long Desc")
res = self.app.get('/app/sampleapp', follow_redirects=True)
err_msg = "The long description should have been updated"
assert "New Long Desc" in res.data, err_msg
@with_context
@patch('pybossa.core.uploader.upload_file', return_value=True)
def test_20_admin_delete_app(self, mock):
"""Test ADMIN can delete a project that belongs to another user"""
self.register()
self.signout()
self.register(fullname="Juan Jose", name="juan",
email="juan@juan.com", password="juan")
self.new_application()
self.signout()
# Sign in with the root user
self.signin()
res = self.delete_application(method="GET")
assert "Yes, delete it" in res.data,\
"The project should be deleted by admin users"
res = self.delete_application()
err_msg = "The project should be deleted by admin users"
assert "Project deleted!" in res.data, err_msg
@with_context
def test_21_admin_delete_tasks(self):
"""Test ADMIN can delete a project's tasks that belongs to another user"""
# Admin
self.create()
tasks = db.session.query(Task).filter_by(app_id=1).all()
assert len(tasks) > 0, "len(app.tasks) > 0"
res = self.signin(email=u'root@root.com', password=u'tester' + 'root')
res = self.app.get('/app/test-app/tasks/delete', follow_redirects=True)
err_msg = "Admin user should get 200 in GET"
assert res.status_code == 200, err_msg
res = self.app.post('/app/test-app/tasks/delete', follow_redirects=True)
err_msg = "Admin should get 200 in POST"
assert res.status_code == 200, err_msg
tasks = db.session.query(Task).filter_by(app_id=1).all()
assert len(tasks) == 0, "len(app.tasks) != 0"
@with_context
def test_22_admin_list_categories(self):
"""Test ADMIN list categories works"""
self.create()
# Anonymous user
url = '/admin/categories'
res = self.app.get(url, follow_redirects=True)
dom = BeautifulSoup(res.data)
err_msg = "Anonymous users should be redirected to sign in"
assert dom.find(id='signin') is not None, err_msg
# Authenticated user but not admin
self.signin(email=self.email_addr2, password=self.password)
res = self.app.get(url, follow_redirects=True)
err_msg = "Non-Admin users should get 403"
assert res.status_code == 403, err_msg
self.signout()
# Admin user
self.signin(email=self.root_addr, password=self.root_password)
res = self.app.get(url, follow_redirects=True)
dom = BeautifulSoup(res.data)
err_msg = "Admin users should be get a list of Categories"
assert dom.find(id='categories') is not None, err_msg
@with_context
def test_23_admin_add_category(self):
"""Test ADMIN add category works"""
self.create()
category = {'name': 'cat', 'short_name': 'cat',
'description': 'description'}
# Anonymous user
url = '/admin/categories'
res = self.app.post(url, data=category, follow_redirects=True)
dom = BeautifulSoup(res.data)
err_msg = "Anonymous users should be redirected to sign in"
assert dom.find(id='signin') is not None, err_msg
# Authenticated user but not admin
self.signin(email=self.email_addr2, password=self.password)
res = self.app.post(url, data=category, follow_redirects=True)
err_msg = "Non-Admin users should get 403"
assert res.status_code == 403, err_msg
self.signout()
# Admin
self.signin(email=self.root_addr, password=self.root_password)
res = self.app.post(url, data=category, follow_redirects=True)
err_msg = "Category should be added"
assert "Category added" in res.data, err_msg
assert category['name'] in res.data, err_msg
category = {'name': 'cat', 'short_name': 'cat',
'description': 'description'}
self.signin(email=self.root_addr, password=self.root_password)
res = self.app.post(url, data=category, follow_redirects=True)
err_msg = "Category form validation should work"
assert "Please correct the errors" in res.data, err_msg
@with_context
def test_24_admin_update_category(self):
"""Test ADMIN update category works"""
self.create()
obj = db.session.query(Category).get(1)
_name = obj.name
category = obj.dictize()
# Anonymous user GET
url = '/admin/categories/update/%s' % obj.id
res = self.app.get(url, follow_redirects=True)
dom = BeautifulSoup(res.data)
err_msg = "Anonymous users should be redirected to sign in"
assert dom.find(id='signin') is not None, err_msg
# Anonymous user POST
res = self.app.post(url, data=category, follow_redirects=True)
dom = BeautifulSoup(res.data)
err_msg = "Anonymous users should be redirected to sign in"
assert dom.find(id='signin') is not None, err_msg
# Authenticated user but not admin GET
self.signin(email=self.email_addr2, password=self.password)
res = self.app.post(url, follow_redirects=True)
err_msg = "Non-Admin users should get 403"
assert res.status_code == 403, err_msg
# Authenticated user but not admin POST
res = self.app.post(url, data=category, follow_redirects=True)
err_msg = "Non-Admin users should get 403"
assert res.status_code == 403, err_msg
self.signout()
# Admin GET
self.signin(email=self.root_addr, password=self.root_password)
res = self.app.get(url, follow_redirects=True)
err_msg = "Category should be listed for admin user"
assert _name in res.data, err_msg
# Check 404
url_404 = '/admin/categories/update/5000'
res = self.app.get(url_404, follow_redirects=True)
assert res.status_code == 404, res.status_code
# Admin POST
res = self.app.post(url, data=category, follow_redirects=True)
err_msg = "Category should be updated"
assert "Category updated" in res.data, err_msg
assert category['name'] in res.data, err_msg
updated_category = db.session.query(Category).get(obj.id)
assert updated_category.name == obj.name, err_msg
# With not valid form
category['name'] = None
res = self.app.post(url, data=category, follow_redirects=True)
assert "Please correct the errors" in res.data, err_msg
@with_context
def test_25_admin_delete_category(self):
"""Test ADMIN delete category works"""
self.create()
obj = db.session.query(Category).get(2)
category = obj.dictize()
# Anonymous user GET
url = '/admin/categories/del/%s' % obj.id
res = self.app.get(url, follow_redirects=True)
dom = BeautifulSoup(res.data)
err_msg = "Anonymous users should be redirected to sign in"
assert dom.find(id='signin') is not None, err_msg
# Anonymous user POST
res = self.app.post(url, data=category, follow_redirects=True)
dom = BeautifulSoup(res.data)
err_msg = "Anonymous users should be redirected to sign in"
assert dom.find(id='signin') is not None, err_msg
# Authenticated user but not admin GET
self.signin(email=self.email_addr2, password=self.password)
res = self.app.post(url, follow_redirects=True)
err_msg = "Non-Admin users should get 403"
assert res.status_code == 403, err_msg
# Authenticated user but not admin POST
res = self.app.post(url, data=category, follow_redirects=True)
err_msg = "Non-Admin users should get 403"
assert res.status_code == 403, err_msg
self.signout()
# Admin GET
self.signin(email=self.root_addr, password=self.root_password)
res = self.app.get(url, follow_redirects=True)
err_msg = "Category should be listed for admin user"
assert category['name'] in res.data, err_msg
# Admin POST
res = self.app.post(url, data=category, follow_redirects=True)
err_msg = "Category should be deleted"
assert "Category deleted" in res.data, err_msg
assert category['name'] not in res.data, err_msg
output = db.session.query(Category).get(obj.id)
assert output is None, err_msg
# Non existant category
category['id'] = 5000
url = '/admin/categories/del/5000'
res = self.app.post(url, data=category, follow_redirects=True)
assert res.status_code == 404, res.status_code
# Now try to delete the only available Category
obj = db.session.query(Category).first()
url = '/admin/categories/del/%s' % obj.id
category = obj.dictize()
res = self.app.post(url, data=category, follow_redirects=True)
print res.data
err_msg = "Category should not be deleted"
assert "Category deleted" not in res.data, err_msg
assert category['name'] in res.data, err_msg
output = db.session.query(Category).get(obj.id)
assert output.id == category['id'], err_msg
| agpl-3.0 |
emgirardin/compassion-modules | child_compassion/models/child_note.py | 1595 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Maxime Beck <mbcompte@gmail.com>
#
# The licence is in the file __openerp__.py
#
##############################################################################
from openerp import models, fields, api
from openerp.addons.message_center_compassion.mappings import base_mapping as \
mapping
class ChildNote(models.Model):
""" A child Note """
_name = 'compassion.child.note'
_description = 'Child Note'
# _order = 'date desc'
child_id = fields.Many2one(
'compassion.child', 'Child', required=True, ondelete='cascade'
)
body = fields.Char()
record_type = fields.Char()
type = fields.Char()
visibility = fields.Char()
source_code = fields.Char()
@api.model
def create(self, vals):
note = super(ChildNote, self).create(vals)
note.child_id.message_post(
note.body, "New beneficiary notes"
)
return note
@api.model
def process_commkit(self, commkit_data):
child_note_mapping = mapping.new_onramp_mapping(
self._name,
self.env,
'beneficiary_note')
vals = child_note_mapping.get_vals_from_connect(commkit_data)
child_note = self.create(vals)
return [child_note.id]
| agpl-3.0 |
ArminMa/metabaseElectronExecutable | frontend/src/metabase/questions/undo.js | 2302 |
import { createAction, createThunkAction } from "metabase/lib/redux";
import MetabaseAnalytics from "metabase/lib/analytics";
import _ from "underscore";
const ADD_UNDO = 'metabase/questions/ADD_UNDO';
const DISMISS_UNDO = 'metabase/questions/DISMISS_UNDO';
const PERFORM_UNDO = 'metabase/questions/PERFORM_UNDO';
let nextUndoId = 0;
export const addUndo = createThunkAction(ADD_UNDO, (undo) => {
return (dispatch, getState) => {
let id = nextUndoId++;
setTimeout(() => dispatch(dismissUndo(id, false)), 5000);
return { ...undo, id, _domId: id };
};
});
export const dismissUndo = createAction(DISMISS_UNDO, (undoId, track = true) => {
if (track) {
MetabaseAnalytics.trackEvent("Undo", "Dismiss Undo");
}
return undoId;
});
export const performUndo = createThunkAction(PERFORM_UNDO, (undoId) => {
return (dispatch, getState) => {
MetabaseAnalytics.trackEvent("Undo", "Perform Undo");
let undo = _.findWhere(getState().undo, { id: undoId });
if (undo) {
undo.actions.map(action =>
dispatch(action)
);
dispatch(dismissUndo(undoId, false));
}
};
});
export default function(state = [], { type, payload, error }) {
switch (type) {
case ADD_UNDO:
if (error) {
console.warn("ADD_UNDO", payload);
return state;
}
let previous = state[state.length - 1];
// if last undo was same type then merge them
if (previous && payload.type != null && payload.type === previous.type) {
return state.slice(0, -1).concat({
...payload,
count: previous.count + payload.count,
actions: [...previous.actions, ...payload.actions],
_domId: previous._domId // use original _domId so we don't get funky animations swapping for the new one
});
} else {
return state.concat(payload);
}
case DISMISS_UNDO:
if (error) {
console.warn("DISMISS_UNDO", payload);
return state;
}
return state.filter(undo => undo.id !== payload);
}
return state;
}
| agpl-3.0 |
xs2maverick/adhocracy3.mercator | src/adhocracy_frontend/adhocracy_frontend/tests/acceptance/RateSpec.js | 2089 | "use strict";
var shared = require("./shared.js");
var EmbeddedCommentsPage = require("./EmbeddedCommentsPage.js");
describe("ratings", function() {
var page;
beforeEach(function() {
shared.loginParticipant();
page = new EmbeddedCommentsPage("c1").get();
});
it("can upvote", function() {
var comment = page.createComment("c1");
var rate = page.getRateWidget(comment);
rate.element(by.css(".rate-pro")).click();
expect(rate.element(by.css(".rate-difference")).getText()).toEqual("+1");
});
it("can downvote", function() {
var comment = page.createComment("c2");
var rate = page.getRateWidget(comment);
rate.element(by.css(".rate-contra")).click();
expect(rate.element(by.css(".rate-difference")).getText()).toEqual("-1");
});
it("can vote neutrally", function() {
var comment = page.createComment("c3");
var rate = page.getRateWidget(comment);
rate.element(by.css(".rate-pro")).click();
expect(rate.element(by.css(".rate-difference")).getText()).toEqual("+1");
rate.element(by.css(".is-rate-button-active")).click();
expect(rate.element(by.css(".rate-difference")).getText()).toEqual("0");
});
it("is not affected by the edition of the comment", function() {
shared.loginParticipant();
var page = new EmbeddedCommentsPage("c2");
page.getUrl().then(function() {
// at this point annotator may not be logged
// if we don't add the first shared.loginParticipant();
// even if the same call is performed by the beforeEach
// function?!
var comment = page.createComment("c4");
var rate = page.getRateWidget(comment);
rate.element(by.css(".rate-pro")).click();
var changedComment = page.editComment(comment, ["c4 - edited"]);
var rate2 = page.getRateWidget(changedComment);
expect(rate2.element(by.css(".rate-difference")).getText()).toEqual("+1");
});
});
});
| agpl-3.0 |
TeamHypersomnia/Hypersomnia | src/3rdparty/Box2D/Dynamics/b2Island.cpp | 16656 | /*
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Collision/b2Distance.h>
#include <Box2D/Dynamics/b2Island.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2Fixture.h>
#include <Box2D/Dynamics/b2World.h>
#include <Box2D/Dynamics/Contacts/b2Contact.h>
#include <Box2D/Dynamics/Contacts/b2ContactSolver.h>
#include <Box2D/Dynamics/Joints/b2Joint.h>
#include <Box2D/Common/b2StackAllocator.h>
#include <Box2D/Common/b2Timer.h>
#include "augs/math/vec2.h"
/*
Position Correction Notes
=========================
I tried the several algorithms for position correction of the 2D revolute joint.
I looked at these systems:
- simple pendulum (1m diameter sphere on massless 5m stick) with initial angular velocity of 100 rad/s.
- suspension bridge with 30 1m long planks of length 1m.
- multi-link chain with 30 1m long links.
Here are the algorithms:
Baumgarte - A fraction of the position error is added to the velocity error. There is no
separate position solver.
Pseudo Velocities - After the velocity solver and position integration,
the position error, Jacobian, and effective mass are recomputed. Then
the velocity constraints are solved with pseudo velocities and a fraction
of the position error is added to the pseudo velocity error. The pseudo
velocities are initialized to zero and there is no warm-starting. After
the position solver, the pseudo velocities are added to the positions.
This is also called the First Order World method or the Position LCP method.
Modified Nonlinear Gauss-Seidel (NGS) - Like Pseudo Velocities except the
position error is re-computed for each constraint and the positions are updated
after the constraint is solved. The radius vectors (aka Jacobians) are
re-computed too (otherwise the algorithm has horrible instability). The pseudo
velocity states are not needed because they are effectively zero at the beginning
of each iteration. Since we have the current position error, we allow the
iterations to terminate early if the error becomes smaller than b2_linearSlop.
Full NGS or just NGS - Like Modified NGS except the effective mass are re-computed
each time a constraint is solved.
Here are the results:
Baumgarte - this is the cheapest algorithm but it has some stability problems,
especially with the bridge. The chain links separate easily close to the root
and they jitter as they struggle to pull together. This is one of the most common
methods in the field. The big drawback is that the position correction artificially
affects the momentum, thus leading to instabilities and false bounce. I used a
bias factor of 0.2. A larger bias factor makes the bridge less stable, a smaller
factor makes joints and contacts more spongy.
Pseudo Velocities - the is more stable than the Baumgarte method. The bridge is
stable. However, joints still separate with large angular velocities. Drag the
simple pendulum in a circle quickly and the joint will separate. The chain separates
easily and does not recover. I used a bias factor of 0.2. A larger value lead to
the bridge collapsing when a heavy cube drops on it.
Modified NGS - this algorithm is better in some ways than Baumgarte and Pseudo
Velocities, but in other ways it is worse. The bridge and chain are much more
stable, but the simple pendulum goes unstable at high angular velocities.
Full NGS - stable in all tests. The joints display good stiffness. The bridge
still sags, but this is better than infinite forces.
Recommendations
Pseudo Velocities are not really worthwhile because the bridge and chain cannot
recover from joint separation. In other cases the benefit over Baumgarte is small.
Modified NGS is not a robust method for the revolute joint due to the violent
instability seen in the simple pendulum. Perhaps it is viable with other constraint
types, especially scalar constraints where the effective mass is a scalar.
This leaves Baumgarte and Full NGS. Baumgarte has small, but manageable instabilities
and is very fast. I don't think we can escape Baumgarte, especially in highly
demanding cases where high constraint fidelity is not needed.
Full NGS is robust and easy on the eyes. I recommend this as an option for
higher fidelity simulation and certainly for suspension bridges and long chains.
Full NGS might be a good choice for ragdolls, especially motorized ragdolls where
joint separation can be problematic. The number of NGS iterations can be reduced
for better performance without harming robustness much.
Each joint in a can be handled differently in the position solver. So I recommend
a system where the user can select the algorithm on a per joint basis. I would
probably default to the slower Full NGS and let the user select the faster
Baumgarte method in performance critical scenarios.
*/
/*
Cache Performance
The Box2D solvers are dominated by cache misses. Data structures are designed
to increase the number of cache hits. Much of misses are due to random access
to body data. The constraint structures are iterated over linearly, which leads
to few cache misses.
The bodies are not accessed during iteration. Instead read only data, such as
the mass values are stored with the constraints. The mutable data are the constraint
impulses and the bodies velocities/positions. The impulses are held inside the
constraint structures. The body velocities/positions are held in compact, temporary
arrays to increase the number of cache hits. Linear and angular velocity are
stored in a single array since multiple arrays lead to multiple misses.
*/
/*
2D Rotation
R = [cos(theta) -sin(theta)]
[sin(theta) cos(theta) ]
thetaDot = omega
Let q1 = cos(theta), q2 = sin(theta).
R = [q1 -q2]
[q2 q1]
q1Dot = -thetaDot * q2
q2Dot = thetaDot * q1
q1_new = q1_old - dt * w * q2
q2_new = q2_old + dt * w * q1
then normalize.
This might be faster than computing sin+cos.
However, we can compute sin+cos of the same angle fast.
*/
b2Island::b2Island(
int32 bodyCapacity,
int32 contactCapacity,
int32 jointCapacity,
b2StackAllocator* allocator,
b2ContactListener* listener)
{
m_bodyCapacity = bodyCapacity;
m_contactCapacity = contactCapacity;
m_jointCapacity = jointCapacity;
m_bodyCount = 0;
m_contactCount = 0;
m_jointCount = 0;
m_allocator = allocator;
m_listener = listener;
m_bodies = (b2Body**)m_allocator->Allocate(bodyCapacity * sizeof(b2Body*));
m_contacts = (b2Contact**)m_allocator->Allocate(contactCapacity * sizeof(b2Contact*));
m_joints = (b2Joint**)m_allocator->Allocate(jointCapacity * sizeof(b2Joint*));
m_velocities = (b2Velocity*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Velocity));
m_positions = (b2Position*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Position));
}
b2Island::~b2Island()
{
// Warning: the order should reverse the constructor order.
m_allocator->Free(m_positions);
m_allocator->Free(m_velocities);
m_allocator->Free(m_joints);
m_allocator->Free(m_contacts);
m_allocator->Free(m_bodies);
}
void b2Island::Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& /* gravity */, bool allowSleep)
{
b2Timer timer;
float32 h = step.dt;
// Integrate velocities and apply damping. Initialize the body state.
for (int32 i = 0; i < m_bodyCount; ++i)
{
b2Body* b = m_bodies[i];
b2Vec2 c = b->m_sweep.c;
float32 a = b->m_sweep.a;
b2Vec2 v = b->m_linearVelocity;
float32 w = b->m_angularVelocity;
// Store positions for continuous collision.
b->m_sweep.c0 = b->m_sweep.c;
b->m_sweep.a0 = b->m_sweep.a;
if (b->m_type == b2_dynamicBody)
{
// Apply damping.
// ODE: dv/dt + c * v = 0
// Solution: v(t) = v0 * exp(-c * t)
// Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt)
// v2 = exp(-c * dt) * v1
// Pade approximation:
// v2 = v1 * 1 / (1 + c * dt)
v *= 1.0f / (1.0f + h * (b->m_linearDamping));
if (b->enable_angled_damping) {
v.x *= 1.0f / (1.0f + h * b->m_linearDampingVec.x);
v.y *= 1.0f / (1.0f + h * b->m_linearDampingVec.y);
}
w *= 1.0f / (1.0f + h * (b->m_angularDamping));
}
m_positions[i].c = c;
m_positions[i].a = a;
m_velocities[i].v = v;
m_velocities[i].w = w;
}
timer.Reset();
// Solver data
b2SolverData solverData;
solverData.step = step;
solverData.positions = m_positions;
solverData.velocities = m_velocities;
// Initialize velocity constraints.
b2ContactSolverDef contactSolverDef;
contactSolverDef.step = step;
contactSolverDef.contacts = m_contacts;
contactSolverDef.count = m_contactCount;
contactSolverDef.positions = m_positions;
contactSolverDef.velocities = m_velocities;
contactSolverDef.allocator = m_allocator;
b2ContactSolver contactSolver(&contactSolverDef);
contactSolver.InitializeVelocityConstraints();
if (step.warmStarting)
{
contactSolver.WarmStart();
}
for (int32 i = 0; i < m_jointCount; ++i)
{
m_joints[i]->InitVelocityConstraints(solverData);
}
profile->solveInit = timer.GetMilliseconds();
// Solve velocity constraints
timer.Reset();
for (int32 i = 0; i < step.velocityIterations; ++i)
{
for (int32 j = 0; j < m_jointCount; ++j)
{
m_joints[j]->SolveVelocityConstraints(solverData);
}
contactSolver.SolveVelocityConstraints();
}
// Store impulses for warm starting
contactSolver.StoreImpulses();
profile->solveVelocity = timer.GetMilliseconds();
// Integrate positions
for (int32 i = 0; i < m_bodyCount; ++i)
{
b2Vec2 c = m_positions[i].c;
float32 a = m_positions[i].a;
b2Vec2 v = m_velocities[i].v;
float32 w = m_velocities[i].w;
// Check for large velocities
b2Vec2 translation = h * v;
if (b2Dot(translation, translation) > b2_maxTranslationSquared)
{
float32 ratio = b2_maxTranslation / translation.Length();
v *= ratio;
}
float32 rotation = h * w;
if (rotation * rotation > b2_maxRotationSquared)
{
float32 ratio = b2_maxRotation / b2Abs(rotation);
w *= ratio;
}
// Integrate
c += h * v;
a += h * w;
m_positions[i].c = c;
m_positions[i].a = a;
m_velocities[i].v = v;
m_velocities[i].w = w;
}
// Solve position constraints
timer.Reset();
bool positionSolved = false;
for (int32 i = 0; i < step.positionIterations; ++i)
{
bool contactsOkay = contactSolver.SolvePositionConstraints();
bool jointsOkay = true;
for (int32 i = 0; i < m_jointCount; ++i)
{
bool jointOkay = m_joints[i]->SolvePositionConstraints(solverData);
jointsOkay = jointsOkay && jointOkay;
}
if (contactsOkay && jointsOkay)
{
// Exit early if the position errors are small.
positionSolved = true;
break;
}
}
// Copy state buffers back to the bodies
for (int32 i = 0; i < m_bodyCount; ++i)
{
b2Body* body = m_bodies[i];
body->m_sweep.c = m_positions[i].c;
body->m_sweep.a = m_positions[i].a;
body->m_linearVelocity = m_velocities[i].v;
body->m_angularVelocity = m_velocities[i].w;
body->SynchronizeTransform();
}
profile->solvePosition = timer.GetMilliseconds();
Report(contactSolver.m_velocityConstraints);
if (allowSleep)
{
float32 minSleepTime = b2_maxFloat;
const float32 linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance;
const float32 angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance;
for (int32 i = 0; i < m_bodyCount; ++i)
{
b2Body* b = m_bodies[i];
if (b->GetType() == b2_staticBody)
{
continue;
}
if ((b->m_flags & b2Body::e_autoSleepFlag) == 0 ||
b->m_angularVelocity * b->m_angularVelocity > angTolSqr ||
b2Dot(b->m_linearVelocity, b->m_linearVelocity) > linTolSqr)
{
b->m_sleepTime = 0.0f;
minSleepTime = 0.0f;
}
else
{
b->m_sleepTime += h;
minSleepTime = b2Min(minSleepTime, b->m_sleepTime);
}
}
if (minSleepTime >= b2_timeToSleep && positionSolved)
{
for (int32 i = 0; i < m_bodyCount; ++i)
{
b2Body* b = m_bodies[i];
b->SetAwake(false);
}
}
}
}
void b2Island::SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB)
{
b2Assert(toiIndexA < m_bodyCount);
b2Assert(toiIndexB < m_bodyCount);
// Initialize the body state.
for (int32 i = 0; i < m_bodyCount; ++i)
{
b2Body* b = m_bodies[i];
m_positions[i].c = b->m_sweep.c;
m_positions[i].a = b->m_sweep.a;
m_velocities[i].v = b->m_linearVelocity;
m_velocities[i].w = b->m_angularVelocity;
}
b2ContactSolverDef contactSolverDef;
contactSolverDef.contacts = m_contacts;
contactSolverDef.count = m_contactCount;
contactSolverDef.allocator = m_allocator;
contactSolverDef.step = subStep;
contactSolverDef.positions = m_positions;
contactSolverDef.velocities = m_velocities;
b2ContactSolver contactSolver(&contactSolverDef);
// Solve position constraints.
for (int32 i = 0; i < subStep.positionIterations; ++i)
{
bool contactsOkay = contactSolver.SolveTOIPositionConstraints(toiIndexA, toiIndexB);
if (contactsOkay)
{
break;
}
}
#if 0
// Is the new position really safe?
for (int32 i = 0; i < m_contactCount; ++i)
{
b2Contact* c = m_contacts[i];
b2Fixture* fA = c->GetFixtureA();
b2Fixture* fB = c->GetFixtureB();
b2Body* bA = fA->GetBody();
b2Body* bB = fB->GetBody();
int32 indexA = c->GetChildIndexA();
int32 indexB = c->GetChildIndexB();
b2DistanceInput input;
input.proxyA.Set(fA->GetShape(), indexA);
input.proxyB.Set(fB->GetShape(), indexB);
input.transformA = bA->GetTransform();
input.transformB = bB->GetTransform();
input.useRadii = false;
b2DistanceOutput output;
b2SimplexCache cache;
cache.count = 0;
b2Distance(&output, &cache, &input);
if (output.distance == 0 || cache.count == 3)
{
cache.count += 0;
}
}
#endif
// Leap of faith to new safe state.
m_bodies[toiIndexA]->m_sweep.c0 = m_positions[toiIndexA].c;
m_bodies[toiIndexA]->m_sweep.a0 = m_positions[toiIndexA].a;
m_bodies[toiIndexB]->m_sweep.c0 = m_positions[toiIndexB].c;
m_bodies[toiIndexB]->m_sweep.a0 = m_positions[toiIndexB].a;
// No warm starting is needed for TOI events because warm
// starting impulses were applied in the discrete solver.
contactSolver.InitializeVelocityConstraints();
// Solve velocity constraints.
for (int32 i = 0; i < subStep.velocityIterations; ++i)
{
contactSolver.SolveVelocityConstraints();
}
// Don't store the TOI contact forces for warm starting
// because they can be quite large.
float32 h = subStep.dt;
// Integrate positions
for (int32 i = 0; i < m_bodyCount; ++i)
{
b2Vec2 c = m_positions[i].c;
float32 a = m_positions[i].a;
b2Vec2 v = m_velocities[i].v;
float32 w = m_velocities[i].w;
// Check for large velocities
b2Vec2 translation = h * v;
if (b2Dot(translation, translation) > b2_maxTranslationSquared)
{
float32 ratio = b2_maxTranslation / translation.Length();
v *= ratio;
}
float32 rotation = h * w;
if (rotation * rotation > b2_maxRotationSquared)
{
float32 ratio = b2_maxRotation / b2Abs(rotation);
w *= ratio;
}
// Integrate
c += h * v;
a += h * w;
m_positions[i].c = c;
m_positions[i].a = a;
m_velocities[i].v = v;
m_velocities[i].w = w;
// Sync bodies
b2Body* body = m_bodies[i];
body->m_sweep.c = c;
body->m_sweep.a = a;
body->m_linearVelocity = v;
body->m_angularVelocity = w;
body->SynchronizeTransform();
}
Report(contactSolver.m_velocityConstraints);
}
void b2Island::Report(const b2ContactVelocityConstraint* constraints)
{
if (m_listener == NULL)
{
return;
}
for (int32 i = 0; i < m_contactCount; ++i)
{
b2Contact* c = m_contacts[i];
const b2ContactVelocityConstraint* vc = constraints + i;
b2ContactImpulse impulse;
impulse.count = vc->pointCount;
for (int32 j = 0; j < vc->pointCount; ++j)
{
impulse.normalImpulses[j] = vc->points[j].normalImpulse;
impulse.tangentImpulses[j] = vc->points[j].tangentImpulse;
}
m_listener->PostSolve(c, &impulse);
}
}
| agpl-3.0 |
bisq-network/exchange | desktop/src/test/java/bisq/desktop/ComponentsDemoLauncher.java | 204 | package bisq.desktop;
import javafx.application.Application;
public class ComponentsDemoLauncher {
public static void main(String[] args) {
Application.launch(ComponentsDemo.class);
}
}
| agpl-3.0 |
dwango/mastodon | app/javascript/mastodon/features/status/index.js | 15020 | import Immutable from 'immutable';
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { fetchStatus } from '../../actions/statuses';
import MissingIndicator from '../../components/missing_indicator';
import DetailedStatus from './components/detailed_status';
import ActionBar from './components/action_bar';
import Column from '../ui/components/column';
import {
favourite,
unfavourite,
reblog,
unreblog,
pin,
unpin,
} from '../../actions/interactions';
import {
replyCompose,
mentionCompose,
directCompose,
} from '../../actions/compose';
import { blockAccount } from '../../actions/accounts';
import {
muteStatus,
unmuteStatus,
deleteStatus,
hideStatus,
revealStatus,
} from '../../actions/statuses';
import { initMuteModal } from '../../actions/mutes';
import { initReport } from '../../actions/reports';
import { makeGetStatus } from '../../selectors';
import { ScrollContainer } from 'react-router-scroll-4';
import ColumnBackButton from '../../components/column_back_button';
import ColumnHeader from '../../components/column_header';
import StatusContainer from '../../containers/status_container';
import { openModal } from '../../actions/modal';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { HotKeys } from 'react-hotkeys';
import { boostModal, deleteModal } from '../../initial_state';
import { attachFullscreenListener, detachFullscreenListener, isFullscreen } from '../ui/util/fullscreen';
import { textForScreenReader } from '../../components/status';
import { openNiconicoVideoLink } from '../../actions/nicovideo_player';
const messages = defineMessages({
deleteConfirm: { id: 'confirmations.delete.confirm', defaultMessage: 'Delete' },
deleteMessage: { id: 'confirmations.delete.message', defaultMessage: 'Are you sure you want to delete this status?' },
redraftConfirm: { id: 'confirmations.redraft.confirm', defaultMessage: 'Delete & redraft' },
redraftMessage: { id: 'confirmations.redraft.message', defaultMessage: 'Are you sure you want to delete this status and re-draft it? Favourites and boosts will be lost, and replies to the original post will be orphaned.' },
blockConfirm: { id: 'confirmations.block.confirm', defaultMessage: 'Block' },
revealAll: { id: 'status.show_more_all', defaultMessage: 'Show more for all' },
hideAll: { id: 'status.show_less_all', defaultMessage: 'Show less for all' },
detailedStatus: { id: 'status.detailed_status', defaultMessage: 'Detailed conversation view' },
replyConfirm: { id: 'confirmations.reply.confirm', defaultMessage: 'Reply' },
replyMessage: { id: 'confirmations.reply.message', defaultMessage: 'Replying now will overwrite the message you are currently composing. Are you sure you want to proceed?' },
});
const makeMapStateToProps = () => {
const getStatus = makeGetStatus();
const mapStateToProps = (state, props) => {
const status = getStatus(state, { id: props.params.statusId });
let ancestorsIds = Immutable.List();
let descendantsIds = Immutable.List();
if (status) {
ancestorsIds = ancestorsIds.withMutations(mutable => {
let id = status.get('in_reply_to_id');
while (id) {
mutable.unshift(id);
id = state.getIn(['contexts', 'inReplyTos', id]);
}
});
descendantsIds = descendantsIds.withMutations(mutable => {
const ids = [status.get('id')];
while (ids.length > 0) {
let id = ids.shift();
const replies = state.getIn(['contexts', 'replies', id]);
if (status.get('id') !== id) {
mutable.push(id);
}
if (replies) {
replies.reverse().forEach(reply => {
ids.unshift(reply);
});
}
}
});
}
return {
status,
ancestorsIds,
descendantsIds,
highlightKeywords: state.get('highlight_keywords'),
askReplyConfirmation: state.getIn(['compose', 'text']).trim().length !== 0,
};
};
return mapStateToProps;
};
export default @injectIntl
@connect(makeMapStateToProps)
class Status extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
status: ImmutablePropTypes.map,
ancestorsIds: ImmutablePropTypes.list,
descendantsIds: ImmutablePropTypes.list,
intl: PropTypes.object.isRequired,
askReplyConfirmation: PropTypes.bool,
};
state = {
fullscreen: false,
};
componentWillMount () {
this.props.dispatch(fetchStatus(this.props.params.statusId));
}
componentDidMount () {
attachFullscreenListener(this.onFullScreenChange);
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) {
this._scrolledIntoView = false;
this.props.dispatch(fetchStatus(nextProps.params.statusId));
}
}
handleFavouriteClick = (status) => {
if (status.get('favourited')) {
this.props.dispatch(unfavourite(status));
} else {
this.props.dispatch(favourite(status));
}
}
handlePin = (status) => {
if (status.get('pinned')) {
this.props.dispatch(unpin(status));
} else {
this.props.dispatch(pin(status));
}
}
handleReplyClick = (status) => {
let { askReplyConfirmation, dispatch, intl } = this.props;
if (askReplyConfirmation) {
dispatch(openModal('CONFIRM', {
message: intl.formatMessage(messages.replyMessage),
confirm: intl.formatMessage(messages.replyConfirm),
onConfirm: () => dispatch(replyCompose(status, this.context.router.history)),
}));
} else {
dispatch(replyCompose(status, this.context.router.history));
}
}
handleModalReblog = (status) => {
this.props.dispatch(reblog(status));
}
handleReblogClick = (status, e) => {
if (status.get('reblogged')) {
this.props.dispatch(unreblog(status));
} else {
if ((e && e.shiftKey) || !boostModal) {
this.handleModalReblog(status);
} else {
this.props.dispatch(openModal('BOOST', { status, onReblog: this.handleModalReblog }));
}
}
}
handleDeleteClick = (status, history, withRedraft = false) => {
const { dispatch, intl } = this.props;
if (!deleteModal) {
dispatch(deleteStatus(status.get('id'), history, withRedraft));
} else {
dispatch(openModal('CONFIRM', {
message: intl.formatMessage(withRedraft ? messages.redraftMessage : messages.deleteMessage),
confirm: intl.formatMessage(withRedraft ? messages.redraftConfirm : messages.deleteConfirm),
onConfirm: () => dispatch(deleteStatus(status.get('id'), history, withRedraft)),
}));
}
}
handleDirectClick = (account, router) => {
this.props.dispatch(directCompose(account, router));
}
handleMentionClick = (account, router) => {
this.props.dispatch(mentionCompose(account, router));
}
handleOpenMedia = (media, index) => {
this.props.dispatch(openModal('MEDIA', { media, index }));
}
handleOpenVideo = (media, time) => {
this.props.dispatch(openModal('VIDEO', { media, time }));
}
handleMuteClick = (account) => {
this.props.dispatch(initMuteModal(account));
}
handleConversationMuteClick = (status) => {
if (status.get('muted')) {
this.props.dispatch(unmuteStatus(status.get('id')));
} else {
this.props.dispatch(muteStatus(status.get('id')));
}
}
handleToggleHidden = (status) => {
if (status.get('hidden')) {
this.props.dispatch(revealStatus(status.get('id')));
} else {
this.props.dispatch(hideStatus(status.get('id')));
}
}
handleToggleAll = () => {
const { status, ancestorsIds, descendantsIds } = this.props;
const statusIds = [status.get('id')].concat(ancestorsIds.toJS(), descendantsIds.toJS());
if (status.get('hidden')) {
this.props.dispatch(revealStatus(statusIds));
} else {
this.props.dispatch(hideStatus(statusIds));
}
}
handleBlockClick = (account) => {
const { dispatch, intl } = this.props;
dispatch(openModal('CONFIRM', {
message: <FormattedMessage id='confirmations.block.message' defaultMessage='Are you sure you want to block {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />,
confirm: intl.formatMessage(messages.blockConfirm),
onConfirm: () => dispatch(blockAccount(account.get('id'))),
}));
}
handleReport = (status) => {
this.props.dispatch(initReport(status.get('account'), status));
}
handleEmbed = (status) => {
this.props.dispatch(openModal('EMBED', { url: status.get('url') }));
}
handleHotkeyMoveUp = () => {
this.handleMoveUp(this.props.status.get('id'));
}
handleHotkeyMoveDown = () => {
this.handleMoveDown(this.props.status.get('id'));
}
handleHotkeyReply = e => {
e.preventDefault();
this.handleReplyClick(this.props.status);
}
handleHotkeyFavourite = () => {
this.handleFavouriteClick(this.props.status);
}
handleHotkeyBoost = () => {
this.handleReblogClick(this.props.status);
}
handleHotkeyMention = e => {
e.preventDefault();
this.handleMentionClick(this.props.status.get('account'));
}
handleHotkeyOpenProfile = () => {
this.context.router.history.push(`/accounts/${this.props.status.getIn(['account', 'id'])}`);
}
handleHotkeyToggleHidden = () => {
this.handleToggleHidden(this.props.status);
}
handleMoveUp = id => {
const { status, ancestorsIds, descendantsIds } = this.props;
if (id === status.get('id')) {
this._selectChild(ancestorsIds.size - 1);
} else {
let index = ancestorsIds.indexOf(id);
if (index === -1) {
index = descendantsIds.indexOf(id);
this._selectChild(ancestorsIds.size + index);
} else {
this._selectChild(index - 1);
}
}
}
handleMoveDown = id => {
const { status, ancestorsIds, descendantsIds } = this.props;
if (id === status.get('id')) {
this._selectChild(ancestorsIds.size + 1);
} else {
let index = ancestorsIds.indexOf(id);
if (index === -1) {
index = descendantsIds.indexOf(id);
this._selectChild(ancestorsIds.size + index + 2);
} else {
this._selectChild(index + 1);
}
}
}
_selectChild (index) {
const element = this.node.querySelectorAll('.focusable')[index];
if (element) {
element.focus();
}
}
renderChildren (list) {
return list.map(id => (
<StatusContainer
key={id}
id={id}
onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown}
contextType='thread'
/>
));
}
setRef = c => {
this.node = c;
}
componentDidUpdate () {
if (this._scrolledIntoView) {
return;
}
const { status, ancestorsIds } = this.props;
if (status && ancestorsIds && ancestorsIds.size > 0) {
const element = this.node.querySelectorAll('.focusable')[ancestorsIds.size - 1];
window.requestAnimationFrame(() => {
element.scrollIntoView(true);
});
this._scrolledIntoView = true;
}
}
componentWillUnmount () {
detachFullscreenListener(this.onFullScreenChange);
}
onFullScreenChange = () => {
this.setState({ fullscreen: isFullscreen() });
}
onNiconicoVideoLinkClick = videoId => {
this.props.dispatch(openNiconicoVideoLink(videoId));
}
render () {
let ancestors, descendants;
const { shouldUpdateScroll, status, ancestorsIds, descendantsIds, intl } = this.props;
const { fullscreen } = this.state;
const { highlightKeywords } = this.props;
if (status === null) {
return (
<Column>
<ColumnBackButton />
<MissingIndicator />
</Column>
);
}
if (ancestorsIds && ancestorsIds.size > 0) {
ancestors = <div>{this.renderChildren(ancestorsIds)}</div>;
}
if (descendantsIds && descendantsIds.size > 0) {
descendants = <div>{this.renderChildren(descendantsIds)}</div>;
}
const handlers = {
moveUp: this.handleHotkeyMoveUp,
moveDown: this.handleHotkeyMoveDown,
reply: this.handleHotkeyReply,
favourite: this.handleHotkeyFavourite,
boost: this.handleHotkeyBoost,
mention: this.handleHotkeyMention,
openProfile: this.handleHotkeyOpenProfile,
toggleHidden: this.handleHotkeyToggleHidden,
};
return (
<Column label={intl.formatMessage(messages.detailedStatus)}>
<ColumnHeader
showBackButton
extraButton={(
<button className='column-header__button' title={intl.formatMessage(status.get('hidden') ? messages.revealAll : messages.hideAll)} aria-label={intl.formatMessage(status.get('hidden') ? messages.revealAll : messages.hideAll)} onClick={this.handleToggleAll} aria-pressed={status.get('hidden') ? 'false' : 'true'}><i className={`fa fa-${status.get('hidden') ? 'eye-slash' : 'eye'}`} /></button>
)}
/>
<ScrollContainer scrollKey='thread' shouldUpdateScroll={shouldUpdateScroll}>
<div className={classNames('scrollable', { fullscreen })} ref={this.setRef}>
{ancestors}
<HotKeys handlers={handlers}>
<div className={classNames('focusable', 'detailed-status__wrapper')} tabIndex='0' aria-label={textForScreenReader(intl, status, false, !status.get('hidden'))}>
<DetailedStatus
status={status}
onOpenVideo={this.handleOpenVideo}
onOpenMedia={this.handleOpenMedia}
onToggleHidden={this.handleToggleHidden}
highlightKeywords={highlightKeywords}
onNiconicoVideoLinkClick={this.onNiconicoVideoLinkClick}
/>
<ActionBar
status={status}
onReply={this.handleReplyClick}
onFavourite={this.handleFavouriteClick}
onReblog={this.handleReblogClick}
onDelete={this.handleDeleteClick}
onDirect={this.handleDirectClick}
onMention={this.handleMentionClick}
onMute={this.handleMuteClick}
onMuteConversation={this.handleConversationMuteClick}
onBlock={this.handleBlockClick}
onReport={this.handleReport}
onPin={this.handlePin}
onEmbed={this.handleEmbed}
/>
</div>
</HotKeys>
{descendants}
</div>
</ScrollContainer>
</Column>
);
}
}
| agpl-3.0 |
brain-tec/server-tools | base_search_fuzzy/models/trgm_index.py | 5775 | # Copyright 2016 Eficent Business and IT Consulting Services S.L.
# Copyright 2016 Serpent Consulting Services Pvt. Ltd.
# Copyright 2017 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from odoo import _, api, exceptions, fields, models
from psycopg2.extensions import AsIs
_logger = logging.getLogger(__name__)
class TrgmIndex(models.Model):
"""Model for Trigram Index."""
_name = 'trgm.index'
_rec_name = 'field_id'
field_id = fields.Many2one(
comodel_name='ir.model.fields',
string='Field',
required=True,
help='You can either select a field of type "text" or "char".'
)
index_name = fields.Char(
string='Index Name',
readonly=True,
help='The index name is automatically generated like '
'fieldname_indextype_idx. If the index already exists and the '
'index is located in the same table then this index is reused. '
'If the index is located in another table then a number is added '
'at the end of the index name.'
)
index_type = fields.Selection(
selection=[('gin', 'GIN'), ('gist', 'GiST')],
string='Index Type',
default='gin',
required=True,
help='Cite from PostgreSQL documentation: "As a rule of thumb, a '
'GIN index is faster to search than a GiST index, but slower to '
'build or update; so GIN is better suited for static data and '
'GiST for often-updated data."'
)
@api.model_cr
def _trgm_extension_exists(self):
self.env.cr.execute("""
SELECT name, installed_version
FROM pg_available_extensions
WHERE name = 'pg_trgm'
LIMIT 1;
""")
extension = self.env.cr.fetchone()
if extension is None:
return 'missing'
if extension[1] is None:
return 'uninstalled'
return 'installed'
@api.model_cr
def _is_postgres_superuser(self):
self.env.cr.execute("SHOW is_superuser;")
superuser = self.env.cr.fetchone()
return superuser is not None and superuser[0] == 'on' or False
@api.model_cr
def _install_trgm_extension(self):
extension = self._trgm_extension_exists()
if extension == 'missing':
_logger.warning('To use pg_trgm you have to install the '
'postgres-contrib module.')
elif extension == 'uninstalled':
if self._is_postgres_superuser():
self.env.cr.execute("CREATE EXTENSION IF NOT EXISTS pg_trgm;")
return True
else:
_logger.warning('To use pg_trgm you have to create the '
'extension pg_trgm in your database or you '
'have to be the superuser.')
else:
return True
return False
@api.model_cr_context
def _auto_init(self):
res = super(TrgmIndex, self)._auto_init()
if self._install_trgm_extension():
_logger.info('The pg_trgm is loaded in the database and the '
'fuzzy search can be used.')
return res
@api.model_cr
def get_not_used_index(self, index_name, table_name, inc=1):
if inc > 1:
new_index_name = index_name + str(inc)
else:
new_index_name = index_name
self.env.cr.execute("""
SELECT tablename, indexname
FROM pg_indexes
WHERE indexname = %(index)s;
""", {'index': new_index_name})
indexes = self.env.cr.fetchone()
if indexes is not None and indexes[0] == table_name:
return True, index_name
elif indexes is not None:
return self.get_not_used_index(index_name, table_name,
inc + 1)
return False, new_index_name
@api.multi
def create_index(self):
self.ensure_one()
if not self._install_trgm_extension():
raise exceptions.UserError(_(
'The pg_trgm extension does not exists or cannot be '
'installed.'))
table_name = self.env[self.field_id.model_id.model]._table
column_name = self.field_id.name
index_type = self.index_type
index_name = '%s_%s_idx' % (column_name, index_type)
index_exists, index_name = self.get_not_used_index(
index_name, table_name)
if not index_exists:
self.env.cr.execute("""
CREATE INDEX %(index)s
ON %(table)s
USING %(indextype)s (%(column)s %(indextype)s_trgm_ops);
""", {
'table': AsIs(table_name),
'index': AsIs(index_name),
'column': AsIs(column_name),
'indextype': AsIs(index_type)
})
return index_name
@api.model
def index_exists(self, model_name, field_name):
field = self.env['ir.model.fields'].search([
('model', '=', model_name), ('name', '=', field_name)], limit=1)
if not field:
return False
trgm_index = self.search([('field_id', '=', field.id)], limit=1)
return bool(trgm_index)
@api.model
def create(self, vals):
rec = super(TrgmIndex, self).create(vals)
rec.index_name = rec.create_index()
return rec
@api.multi
def unlink(self):
for rec in self:
self.env.cr.execute("""
DROP INDEX IF EXISTS %(index)s;
""", {
'index': AsIs(rec.index_name),
})
return super(TrgmIndex, self).unlink()
| agpl-3.0 |
frankrousseau/weboob | modules/lutim/pages.py | 1113 | # -*- coding: utf-8 -*-
# Copyright(C) 2014 Vincent A
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
from weboob.deprecated.browser import Page
import re
class PageAll(Page):
def post(self, name, content, max_days):
pass
def get_info(self):
for link in self.browser.links():
linkurl = link.absolute_url
m = re.match(re.escape(self.url) + r'([a-zA-Z0-9]+)\?dl$', linkurl)
if m:
return {'id': m.group(1)}
| agpl-3.0 |
snap-cloud/snap-cloud | config/initializers/paperclip.rb | 233 | # Paperclip initializer
# change the default paths to work with S3.
Paperclip::Attachment.default_options[:url] = ':s3_domain_url'
Paperclip::Attachment.default_options[:path] = '/:class/:attachment/:id_partition/:style/:filename'
| agpl-3.0 |
BuildingSMART/IfcDoc | IfcKit/schemas/IfcDateTimeResource/IfcDayInMonthNumber.cs | 698 | // This file may be edited manually or auto-generated using IfcKit at www.buildingsmart-tech.org.
// IFC content is copyright (C) 1996-2018 BuildingSMART International Ltd.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace BuildingSmart.IFC.IfcDateTimeResource
{
public partial struct IfcDayInMonthNumber
{
[XmlText]
public Int64 Value { get; private set; }
public IfcDayInMonthNumber(Int64 value) : this()
{
this.Value = value;
}
}
}
| agpl-3.0 |
ritumalhotra8/IRIS | interaction-core/src/test/java/com/temenos/interaction/core/rim/TestResponseHTTPHypermediaRIM.java | 114118 | package com.temenos.interaction.core.rim;
/*
* #%L
* interaction-core
* %%
* Copyright (C) 2012 - 2013 Temenos Holdings N.V.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.whenNew;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.Response.StatusType;
import javax.ws.rs.core.UriInfo;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.temenos.interaction.core.MultivaluedMapHelper;
import com.temenos.interaction.core.MultivaluedMapImpl;
import com.temenos.interaction.core.command.CommandController;
import com.temenos.interaction.core.command.CommandHelper;
import com.temenos.interaction.core.command.GETExceptionCommand;
import com.temenos.interaction.core.command.HttpStatusTypes;
import com.temenos.interaction.core.command.InteractionCommand;
import com.temenos.interaction.core.command.InteractionCommand.Result;
import com.temenos.interaction.core.command.InteractionContext;
import com.temenos.interaction.core.command.InteractionException;
import com.temenos.interaction.core.command.MapBasedCommandController;
import com.temenos.interaction.core.command.NoopGETCommand;
import com.temenos.interaction.core.entity.Entity;
import com.temenos.interaction.core.entity.EntityMetadata;
import com.temenos.interaction.core.entity.EntityProperties;
import com.temenos.interaction.core.entity.GenericError;
import com.temenos.interaction.core.entity.Metadata;
import com.temenos.interaction.core.hypermedia.Action;
import com.temenos.interaction.core.hypermedia.BeanTransformer;
import com.temenos.interaction.core.hypermedia.CollectionResourceState;
import com.temenos.interaction.core.hypermedia.DynamicResourceState;
import com.temenos.interaction.core.hypermedia.Link;
import com.temenos.interaction.core.hypermedia.ResourceLocator;
import com.temenos.interaction.core.hypermedia.ResourceLocatorProvider;
import com.temenos.interaction.core.hypermedia.ResourceState;
import com.temenos.interaction.core.hypermedia.ResourceStateMachine;
import com.temenos.interaction.core.hypermedia.Transition;
import com.temenos.interaction.core.hypermedia.expression.Expression;
import com.temenos.interaction.core.hypermedia.expression.ResourceGETExpression;
import com.temenos.interaction.core.hypermedia.expression.SimpleLogicalExpressionEvaluator;
import com.temenos.interaction.core.resource.EntityResource;
import com.temenos.interaction.core.resource.RESTResource;
import com.temenos.interaction.core.resource.ResourceTypeHelper;
import com.temenos.interaction.core.web.RequestContext;
@RunWith(PowerMockRunner.class)
@PrepareForTest({HTTPHypermediaRIM.class})
public class TestResponseHTTPHypermediaRIM {
class MockEntity {
String id;
MockEntity(String id) {
this.id = id;
}
public String getId() {
return id;
}
};
@Before
public void setup() {
// initialise the thread local request context with requestUri and baseUri
RequestContext ctx = new RequestContext("/baseuri", "/requesturi", null);
RequestContext.setRequestContext(ctx);
}
private List<Action> mockActions() {
return mockActions(new Action("GET", Action.TYPE.VIEW),
new Action("DO", Action.TYPE.ENTRY));
}
private List<Action> mockActions(Action...actions) {
List<Action> actionsList = new ArrayList<Action>();
for (Action a : actions) {
actionsList.add(a);
}
return actionsList;
}
private List<Action> mockIncrementAction() {
List<Action> actions = new ArrayList<Action>();
actions.add(new Action("INCREMENT", Action.TYPE.ENTRY, null, "POST"));
return actions;
}
private List<Action> mockSingleAction(String actionName, Action.TYPE type, String method){
List<Action> actions = new ArrayList<Action>();
actions.add(new Action(actionName, type, null, method));
return actions;
}
private List<Action> mockExceptionActions() {
List<Action> actions = new ArrayList<Action>();
actions.add(new Action("GETException", Action.TYPE.VIEW));
return actions;
}
private List<Action> mockErrorActions() {
List<Action> actions = new ArrayList<Action>();
actions.add(new Action("noop", Action.TYPE.VIEW));
return actions;
}
private Metadata createMockMetadata() {
Metadata metadata = mock(Metadata.class);
when(metadata.getEntityMetadata(any(String.class))).thenReturn(mock(EntityMetadata.class));
return metadata;
}
/*
* This test checks that we receive a 404 'Not Found' if a GET command is not registered.
* Every resource must have a GET command, so no command means no resource (404)
*/
@Test
public void testGETCommandNotRegistered() {
// our empty command controller
CommandController mockCommandController = mock(CommandController.class);
when(mockCommandController.fetchCommand("GET")).thenReturn(mock(InteractionCommand.class));
ResourceState initialState = new ResourceState("entity", "state", new ArrayList<Action>(), "/path");
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockCommandController, new ResourceStateMachine(initialState), createMockMetadata());
Response response = rim.get(mock(HttpHeaders.class), "id", mockEmptyUriInfo());
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
}
/*
* This test checks that we receive a 405 'Method Not Allowed' if a command is
* not registered for the given method PUT/POST/DELETE.
*/
@Test
public void testPUTCommandNotRegisteredNotAllowedHeader() {
// our empty command controller
CommandController mockCommandController = mock(CommandController.class);
when(mockCommandController.fetchCommand("GET")).thenReturn(mock(InteractionCommand.class));
ResourceState initialState = new ResourceState("entity", "state", new ArrayList<Action>(), "/path");
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockCommandController, new ResourceStateMachine(initialState), createMockMetadata());
Response response = rim.put(mock(HttpHeaders.class), "id", mockEmptyUriInfo(), mock(EntityResource.class));
assertEquals(HttpStatusTypes.METHOD_NOT_ALLOWED.getStatusCode(), response.getStatus());
// as per the http spec, 405 MUST include an Allow header
List<Object> allowHeader = response.getMetadata().get("Allow");
assertNotNull(allowHeader);
assertEquals(1, allowHeader.size());
HashSet<String> methodsAllowedDetected = new HashSet<String>(Arrays.asList(allowHeader.get(0).toString().split("\\s*,\\s*")));
HashSet<String> methodsAllowed = new HashSet<String>(Arrays.asList("GET, OPTIONS, HEAD".split("\\s*,\\s*")));
assertEquals(methodsAllowed, methodsAllowedDetected);
}
/*
* This test checks that we receive a 405 'Method Not Allowed' if a command is
* not registered for the given method PUT/POST/DELETE.
*/
@Test
public void testPOSTCommandNotRegisteredNotAllowedHeader() {
// our empty command controller
CommandController mockCommandController = mock(CommandController.class);
when(mockCommandController.fetchCommand("GET")).thenReturn(mock(InteractionCommand.class));
ResourceState initialState = new ResourceState("entity", "state", new ArrayList<Action>(), "/path");
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockCommandController, new ResourceStateMachine(initialState), createMockMetadata());
Response response = rim.post(mock(HttpHeaders.class), "id", mockEmptyUriInfo(), mock(EntityResource.class));
assertEquals(HttpStatusTypes.METHOD_NOT_ALLOWED.getStatusCode(), response.getStatus());
// as per the http spec, 405 MUST include an Allow header
List<Object> allowHeader = response.getMetadata().get("Allow");
assertNotNull(allowHeader);
assertEquals(1, allowHeader.size());
HashSet<String> methodsAllowedDetected = new HashSet<String>(Arrays.asList(allowHeader.get(0).toString().split("\\s*,\\s*")));
HashSet<String> methodsAllowed = new HashSet<String>(Arrays.asList("GET, OPTIONS, HEAD".split("\\s*,\\s*")));
assertEquals(methodsAllowed, methodsAllowedDetected);
}
/*
* This test checks that we receive a 405 'Method Not Allowed' if a command is
* not registered for the given method PUT/POST/DELETE.
*/
@Test
public void testDELETECommandNotRegisteredNotAllowedHeader() {
// our empty command controller
CommandController mockCommandController = mock(CommandController.class);
when(mockCommandController.fetchCommand("GET")).thenReturn(mock(InteractionCommand.class));
ResourceState initialState = new ResourceState("entity", "state", new ArrayList<Action>(), "/path");
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockCommandController, new ResourceStateMachine(initialState), createMockMetadata());
Response response = rim.delete(mock(HttpHeaders.class), "id", mockEmptyUriInfo());
assertEquals(HttpStatusTypes.METHOD_NOT_ALLOWED.getStatusCode(), response.getStatus());
// as per the http spec, 405 MUST include an Allow header
List<Object> allowHeader = response.getMetadata().get("Allow");
assertNotNull(allowHeader);
assertEquals(1, allowHeader.size());
HashSet<String> methodsAllowedDetected = new HashSet<String>(Arrays.asList(allowHeader.get(0).toString().split("\\s*,\\s*")));
HashSet<String> methodsAllowed = new HashSet<String>(Arrays.asList("GET, OPTIONS, HEAD".split("\\s*,\\s*")));
assertEquals(methodsAllowed, methodsAllowedDetected);
}
/*
* This test is for a PUT request that returns HttpStatus 204 "No Content"
* A PUT command that does not return a new resource will inform the client
* that there is no new information to display, continue with the current
* view of this resource.
*/
@Test
public void testPUTBuildResponseWith204NoContent() throws Exception {
ResourceState initialState = new ResourceState("entity", "initialstate", mockActions(), "/path");
ResourceState updateState = new ResourceState("entity", "updatestate", mockActions(), "/path");
initialState.addTransition(new Transition.Builder().method(HttpMethod.PUT).target(updateState).build());
/*
* construct an InteractionCommand that simply mocks the result of
* storing a resource, with no updated resource for the user agent
* to re-display
*/
InteractionCommand mockCommand = new InteractionCommand() {
@Override
public Result execute(InteractionContext ctx) {
// this is how a command indicates No Content
ctx.setResource(null);
return Result.SUCCESS;
}
};
// create mock command controller
CommandController mockCommandController = mock(CommandController.class);
when(mockCommandController.fetchCommand("GET")).thenReturn(mock(InteractionCommand.class));
when(mockCommandController.isValidCommand("DO")).thenReturn(true);
when(mockCommandController.fetchCommand("DO")).thenReturn(mockCommand);
// RIM with command controller that issues our mock InteractionCommand
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockCommandController, new ResourceStateMachine(initialState), createMockMetadata());
Response response = rim.put(mock(HttpHeaders.class), "id", mockEmptyUriInfo(), mock(EntityResource.class));
// null resource for no content
RESTResource resource = (RESTResource) response.getEntity();
assertNull(resource);
// 204 http status for no content
assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
}
/*
* This test is for a PUT request that does not returns a resource; it returns
* HttpStatus 200 "OK" rather than 204 because the response has some links.
*/
@Test
public void testPUTBuildResponseNot204NoContentTransitions() throws Exception {
ResourceState initialState = new ResourceState("entity", "initialstate", mockActions(), "/path");
ResourceState updateState = new ResourceState("entity", "updatestate", mockActions(), "/path");
ResourceState otherState = new ResourceState("entity", "otherstate", mockActions(), "/path");
initialState.addTransition(new Transition.Builder().method(HttpMethod.PUT).target(updateState).build());
updateState.addTransition(new Transition.Builder().method(HttpMethod.GET).target(otherState).build());
/*
* construct an InteractionCommand that simply mocks the result of
* storing a resource, with no updated resource for the user agent
* to re-display
*/
InteractionCommand mockCommand = new InteractionCommand() {
@Override
public Result execute(InteractionContext ctx) {
// this is how a command indicates No Content
ctx.setResource(null);
return Result.SUCCESS;
}
};
// create mock command controller
CommandController mockCommandController = mock(CommandController.class);
when(mockCommandController.fetchCommand("GET")).thenReturn(mock(InteractionCommand.class));
when(mockCommandController.isValidCommand("DO")).thenReturn(true);
when(mockCommandController.fetchCommand("DO")).thenReturn(mockCommand);
// RIM with command controller that issues our mock InteractionCommand
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockCommandController, new ResourceStateMachine(initialState), createMockMetadata());
Response response = rim.put(mock(HttpHeaders.class), "id", mockEmptyUriInfo(), mock(EntityResource.class));
// null resource for no content
RESTResource resource = (RESTResource) response.getEntity();
assertNull(resource);
// 200 http status for no content
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
}
/*
* This test is for a DELETE request that returns HttpStatus 204 "No Content"
* A successful DELETE command does not return a new resource; where a target state
* is not found we'll inform the user agent that everything went OK, but there is
* nothing more to display i.e. No Content.
*/
@SuppressWarnings({ "unchecked" })
@Test
public void testDELETEBuildResponseWith204NoContentNoTransition() throws Exception {
/*
* construct an InteractionContext that simply mocks the result of
* deleting a resource, with no updated resource for the user agent
* to re-display
*/
ResourceState initialState = new ResourceState("entity", "initialstate", mockActions(), "/path");
ResourceState updateState = new ResourceState("entity", "updatestate", mockActions(), "/path");
initialState.addTransition(new Transition.Builder().method(HttpMethod.DELETE).target(updateState).build());
/*
* construct an InteractionCommand that simply mocks the result of
* storing a resource, with no updated resource for the user agent
* to re-display
*/
InteractionCommand mockCommand = new InteractionCommand() {
@Override
public Result execute(InteractionContext ctx) {
// this is how a command indicates No Content
ctx.setResource(null);
return Result.SUCCESS;
}
};
// create mock command controller
CommandController mockCommandController = mock(CommandController.class);
when(mockCommandController.fetchCommand("GET")).thenReturn(mock(InteractionCommand.class));
when(mockCommandController.isValidCommand("DO")).thenReturn(true);
when(mockCommandController.fetchCommand("DO")).thenReturn(mockCommand);
// RIM with command controller that issues our mock InteractionCommand
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockCommandController, new ResourceStateMachine(initialState), createMockMetadata());
Response response = rim.delete(mock(HttpHeaders.class), "id", mockEmptyUriInfo());
// null resource for no content
RESTResource resource = (RESTResource) response.getEntity();
assertNull(resource);
// 204 http status for no content
assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
}
/*
* This test is for a DELETE request that returns HttpStatus 204 "No Content"
* A successful DELETE command does not return a new resource; where a target state
* is a psuedo final state (effectively no target) we'll inform the user agent
* that everything went OK, but there is nothing more to display i.e. No Content.
*/
@SuppressWarnings({ "unchecked" })
@Test
public void testDELETEBuildResponseWith200WithContent() throws Exception {
/*
* construct an InteractionContext that simply mocks the result of
* deleting a resource, with no updated resource for the user agent
* to re-display
*/
ResourceState initialState = new ResourceState("entity", "state", mockActions(), "/path");
initialState.addTransition(new Transition.Builder().method(HttpMethod.DELETE).target(initialState).build());
InteractionContext testContext = new InteractionContext(mock(UriInfo.class), mock(HttpHeaders.class), mock(MultivaluedMap.class), mock(MultivaluedMap.class), initialState, mock(Metadata.class));
testContext.setResource(null);
// mock 'new InteractionContext()' in call to delete
whenNew(InteractionContext.class).withParameterTypes(UriInfo.class, HttpHeaders.class, MultivaluedMap.class, MultivaluedMap.class, ResourceState.class, Metadata.class)
.withArguments(any(UriInfo.class), any(HttpHeaders.class), any(MultivaluedMap.class), any(MultivaluedMap.class), any(ResourceState.class), any(Metadata.class)).thenReturn(testContext);
// RIM with command controller that issues commands that always return SUCCESS
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockNoopCommandController(), new ResourceStateMachine(initialState), createMockMetadata());
Response response = rim.delete(mock(HttpHeaders.class), "id", mockEmptyUriInfo());
// null resource
RESTResource resource = (RESTResource) response.getEntity();
assertNull(resource);
// 200 http status for Success with transition's content
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
}
/*
* This test is for a DELETE request that returns HttpStatus 205 "Reset Content"
* A successful DELETE command does not return a new resource and should inform
* the user agent to refresh the current view.
*/
@Test
public void testBuildResponseWith205ContentReset() throws Exception {
/*
* construct an InteractionContext that simply mocks the result of
* deleting a resource, with no updated resource for the user agent
* to re-display
*/
ResourceState initialState = new ResourceState("entity", "state", mockActions(), "/path");
ResourceState deletedState = new ResourceState(initialState, "deleted", mockActions());
initialState.addTransition(new Transition.Builder().method("DELETE").target(deletedState).build());
deletedState.addTransition(new Transition.Builder().flags(Transition.REDIRECT).target(initialState).build());
// RIM with command controller that issues commands that always return SUCCESS
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockNoopCommandController(), new ResourceStateMachine(initialState), createMockMetadata());
Response response = rim.delete(mock(HttpHeaders.class), "id", mockEmptyUriInfo());
// null resource
RESTResource resource = (RESTResource) response.getEntity();
assertNull(resource);
// 205 http status for Reset Content
assertEquals(HttpStatusTypes.RESET_CONTENT.getStatusCode(), response.getStatus());
}
/*
* This test is for a DELETE request that returns HttpStatus 205 "Reset Content"
* A successful DELETE command does not return a new resource and should inform
* the user agent to refresh the current view if the target is the same as the source.
*/
@SuppressWarnings({ "unchecked" })
@Test
public void testBuildResponseWith205ContentResetDifferentResource() throws Exception {
/*
* construct an InteractionContext that simply mocks the result of
* deleting a resource, with no updated resource for the user agent
* to re-display
*/
CollectionResourceState initialState = new CollectionResourceState("entity", "state", mockActions(), "/entities");
ResourceState existsState = new ResourceState(initialState, "exists", mockActions(), "/123");
ResourceState deletedState = new ResourceState(existsState, "deleted", mockActions());
initialState.addTransition(new Transition.Builder().flags(Transition.FOR_EACH).method("GET").target(existsState).build());
initialState.addTransition(new Transition.Builder().method("DELETE").target(deletedState).build());
existsState.addTransition(new Transition.Builder().method("DELETE").target(deletedState).build());
// the auto transition
deletedState.addTransition(new Transition.Builder().flags(Transition.REDIRECT).target(initialState).build());
InteractionContext testContext = new InteractionContext(mock(UriInfo.class), mock(HttpHeaders.class), mock(MultivaluedMap.class), mock(MultivaluedMap.class), initialState, mock(Metadata.class));
testContext.setResource(null);
// mock 'new InteractionContext()' in call to delete
whenNew(InteractionContext.class).withParameterTypes(UriInfo.class, HttpHeaders.class, MultivaluedMap.class, MultivaluedMap.class, ResourceState.class, Metadata.class)
.withArguments(any(UriInfo.class), any(HttpHeaders.class), any(MultivaluedMap.class), any(MultivaluedMap.class), any(ResourceState.class), any(Metadata.class)).thenReturn(testContext);
// RIM with command controller that issues commands that always return SUCCESS
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockNoopCommandController(), new ResourceStateMachine(initialState), createMockMetadata());
Collection<ResourceInteractionModel> children = rim.getChildren();
// find the resource interaction model for the entity item
HTTPHypermediaRIM itemRIM = null;
for (ResourceInteractionModel r : children) {
if (r.getResourcePath().equals("/entities/123")) {
itemRIM = (HTTPHypermediaRIM) r;
}
}
// mock the Link header
HttpHeaders mockHeaders = mock(HttpHeaders.class);
List<String> links = new ArrayList<String>();
links.add("</path>; rel=\"entity.state>DELETE>entity.deleted\"");
when(mockHeaders.getRequestHeader("Link")).thenReturn(links);
Response response = itemRIM.delete(mockHeaders, "id", mockEmptyUriInfo());
// null resource
RESTResource resource = (RESTResource) response.getEntity();
assertNull(resource);
// 205 http status for Reset Content
assertEquals(HttpStatusTypes.RESET_CONTENT.getStatusCode(), response.getStatus());
}
/*
* This test is for a DELETE request that supplies a custom link relation
* via the Link header. See (see rfc5988)
* When a user agent follows a link it is able to supply the link relations
* given to it by the server for that link. This provides the server with
* some information about which link the client followed, and therefore
* what state/links to show them next.
*/
@Test
public void testBuildResponseWith303SeeOtherDELETESameEntity() throws Exception {
/*
* construct an InteractionContext that simply mocks the result of
* deleting a resource, with no updated resource for the user agent
* to re-display
*/
ResourceState initialState = new ResourceState("home", "initial", mockActions(), "/machines");
ResourceState existsState = new ResourceState("toaster", "exists", mockActions(), "/machines/toaster");
ResourceState cookingState = new ResourceState(existsState, "cooking", mockActions(), "/cooking");
ResourceState idleState = new ResourceState(cookingState, "idle", mockActions());
// view the toaster if it exists (could show time remaining if cooking)
initialState.addTransition(new Transition.Builder().method("GET").target(existsState).build());
// start cooking the toast
existsState.addTransition(new Transition.Builder().method("PUT").target(cookingState).build());
// stop the toast cooking
cookingState.addTransition(new Transition.Builder().method("DELETE").target(idleState).build());
idleState.addTransition(new Transition.Builder().flags(Transition.REDIRECT).target(existsState).build());
// RIM with command controller that issues commands that always return SUCCESS
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockNoopCommandController(), new ResourceStateMachine(initialState), createMockMetadata());
Collection<ResourceInteractionModel> children = rim.getChildren();
// find the resource interaction model for the 'cooking' state
HTTPHypermediaRIM cookingStateRIM = null;
for (ResourceInteractionModel r : children) {
if (r.getResourcePath().equals("/machines/toaster/cooking")) {
cookingStateRIM = (HTTPHypermediaRIM) r;
}
}
// mock the Link header
HttpHeaders mockHeaders = mock(HttpHeaders.class);
List<String> links = new ArrayList<String>();
links.add("</path>; rel=\"toaster.cooking>toaster.idle\"");
when(mockHeaders.getRequestHeader("Link")).thenReturn(links);
Response response = cookingStateRIM.delete(mockHeaders, "id", mockEmptyUriInfo());
// null resource
RESTResource resource = (RESTResource) response.getEntity();
assertNull(resource);
// 303 "See Other" instructs user agent to fetch another resource as specified by the 'Location' header
assertEquals(Status.SEE_OTHER.getStatusCode(), response.getStatus());
List<Object> locationHeader = response.getMetadata().get("Location");
assertNotNull(locationHeader);
assertEquals(1, locationHeader.size());
assertEquals("/baseuri/machines/toaster", locationHeader.get(0));
}
/*
* This test is for a GET request to a resource that defines an auto transition;
* we expect to receive 303 'See Other'.
*/
@Test
public void testBuildResponseWith303SeeOtherGET() throws Exception {
/*
* construct an InteractionContext that simply mocks the result of
* a GET to a resource, with an auto transition
*/
ResourceState initialState = new ResourceState("home", "initial", mockActions(), "/machines");
ResourceState existsState = new ResourceState("toaster", "exists", mockActions(), "/machines/toaster");
ResourceState existsElsewhereState = new ResourceState("toaster", "existsOther", mockActions(), "/machines/toaster2");
// view the toaster if it exists (could show time remaining if cooking)
initialState.addTransition(new Transition.Builder().method("GET").target(existsState).build());
existsState.addTransition(new Transition.Builder().flags(Transition.REDIRECT).target(existsElsewhereState).build());
// RIM with command controller that issues commands that always return SUCCESS
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockNoopCommandController(), new ResourceStateMachine(initialState), createMockMetadata());
Collection<ResourceInteractionModel> children = rim.getChildren();
// find the resource interaction model for the 'exists' state
HTTPHypermediaRIM existsStateRIM = null;
for (ResourceInteractionModel r : children) {
if (r.getResourcePath().equals("/machines/toaster")) {
existsStateRIM = (HTTPHypermediaRIM) r;
}
}
// mock the Link header
Response response = existsStateRIM.get(mock(HttpHeaders.class), "id", mockEmptyUriInfo());
// null resource
RESTResource resource = (RESTResource) response.getEntity();
assertNull(resource);
// 303 "See Other" instructs user agent to fetch another resource as specified by the 'Location' header
assertEquals(Status.SEE_OTHER.getStatusCode(), response.getStatus());
List<Object> locationHeader = response.getMetadata().get("Location");
assertNotNull(locationHeader);
assertEquals(1, locationHeader.size());
assertEquals("/baseuri/machines/toaster2", locationHeader.get(0));
}
/*
* Same as testBuildResponseWith303SeeOtherGET with parameters
*/
@SuppressWarnings("unchecked")
@Test
public void testBuildResponseWith303SeeOtherGETWithParameters() throws Exception {
/*
* construct an InteractionContext that simply mocks the result of
* a GET to a resource, with an auto transition
*/
ResourceState initialState = new ResourceState("home", "initial", mockActions(), "/machines");
ResourceState existsState = new ResourceState("toaster", "exists", mockActions(), "/machines/toaster");
ResourceState existsElsewhereState = new ResourceState("toaster", "existsOther", mockActions(), "/machines/toaster/{id}");
// view the toaster if it exists (could show time remaining if cooking)
initialState.addTransition(new Transition.Builder().method("GET").target(existsState).build());
existsState.addTransition(new Transition.Builder().flags(Transition.REDIRECT).target(existsElsewhereState).build());
// RIM with command controller that issues commands that always return SUCCESS
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockNoopCommandController(), new ResourceStateMachine(initialState), createMockMetadata());
Collection<ResourceInteractionModel> children = rim.getChildren();
// find the resource interaction model for the 'exists' state
HTTPHypermediaRIM existsStateRIM = null;
for (ResourceInteractionModel r : children) {
if (r.getResourcePath().equals("/machines/toaster")) {
existsStateRIM = (HTTPHypermediaRIM) r;
}
}
// mock the Link header
MultivaluedMap<String, String> mockPathParameters = new MultivaluedMapImpl<String>();
mockPathParameters.add("id", "2");
UriInfo uriInfo = mock(UriInfo.class);
when(uriInfo.getPathParameters(anyBoolean())).thenReturn(mockPathParameters);
when(uriInfo.getQueryParameters(false)).thenReturn(mock(MultivaluedMap.class));
Response response = existsStateRIM.get(mock(HttpHeaders.class), "id", uriInfo);
// null resource
RESTResource resource = (RESTResource) response.getEntity();
assertNull(resource);
// 303 "See Other" instructs user agent to fetch another resource as specified by the 'Location' header
assertEquals(Status.SEE_OTHER.getStatusCode(), response.getStatus());
List<Object> locationHeader = response.getMetadata().get("Location");
assertNotNull(locationHeader);
assertEquals(1, locationHeader.size());
assertEquals("/baseuri/machines/toaster/2", locationHeader.get(0));
}
/*
* Same as testBuildResponseWith303SeeOtherGET with query parameters
*/
@Test
public void testBuildResponseWith303SeeOtherGETWithQueryParameters() throws Exception {
/*
* construct an InteractionContext that simply mocks the result of
* a GET to a resource, with an auto transition
*/
ResourceState initialState = new ResourceState("home", "initial", mockActions(), "/machines");
ResourceState existsState = new ResourceState("toaster", "exists", mockActions(), "/machines/toaster");
ResourceState existsElsewhereState = new ResourceState("toaster", "existsOther", mockActions(), "/machines/toaster/{id}");
// view the toaster if it exists (could show time remaining if cooking)
initialState.addTransition(new Transition.Builder().method("GET").target(existsState).build());
Map<String,String> uriParameters = new HashMap<String,String>();
uriParameters.put("test", "{test}");
existsState.addTransition(new Transition.Builder()
.flags(Transition.REDIRECT)
.target(existsElsewhereState)
.uriParameters(uriParameters)
.build());
// RIM with command controller that issues commands that always return SUCCESS
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockNoopCommandController(), new ResourceStateMachine(initialState), createMockMetadata());
Collection<ResourceInteractionModel> children = rim.getChildren();
// find the resource interaction model for the 'exists' state
HTTPHypermediaRIM existsStateRIM = null;
for (ResourceInteractionModel r : children) {
if (r.getResourcePath().equals("/machines/toaster")) {
existsStateRIM = (HTTPHypermediaRIM) r;
}
}
// mock the Link header
MultivaluedMap<String, String> mockPathParameters = new MultivaluedMapImpl<String>();
mockPathParameters.add("id", "2");
UriInfo uriInfo = mock(UriInfo.class);
when(uriInfo.getPathParameters(anyBoolean())).thenReturn(mockPathParameters);
MultivaluedMap<String, String> mockQueryParameters = new MultivaluedMapImpl<String>();
mockQueryParameters.add("test", "123");
when(uriInfo.getQueryParameters(false)).thenReturn(mockQueryParameters);
Response response = existsStateRIM.get(mock(HttpHeaders.class), "id", uriInfo);
// null resource
RESTResource resource = (RESTResource) response.getEntity();
assertNull(resource);
// 303 "See Other" instructs user agent to fetch another resource as specified by the 'Location' header
assertEquals(Status.SEE_OTHER.getStatusCode(), response.getStatus());
List<Object> locationHeader = response.getMetadata().get("Location");
assertNotNull(locationHeader);
assertEquals(1, locationHeader.size());
assertEquals("/baseuri/machines/toaster/2?test=123", locationHeader.get(0));
}
/*
* Same as testBuildResponseWith303SeeOtherGET with query parameters that replace a token
*/
@Test
public void testBuildResponseWith303SeeOtherGETWithTokenReplaceQueryParameters() throws Exception {
/*
* construct an InteractionContext that simply mocks the result of
* a GET to a resource, with an auto transition
*/
ResourceState initialState = new ResourceState("home", "initial", mockActions(), "/machines");
ResourceState existsState = new ResourceState("toaster", "exists", mockActions(), "/machines/toaster");
ResourceState existsElsewhereState = new ResourceState("toaster", "existsOther", mockActions(), "/machines/toaster/{id}");
// view the toaster if it exists (could show time remaining if cooking)
initialState.addTransition(new Transition.Builder().method("GET").target(existsState).build());
existsState.addTransition(new Transition.Builder().flags(Transition.REDIRECT).target(existsElsewhereState).build());
// RIM with command controller that issues commands that always return SUCCESS
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockNoopCommandController(), new ResourceStateMachine(initialState), createMockMetadata());
Collection<ResourceInteractionModel> children = rim.getChildren();
// find the resource interaction model for the 'exists' state
HTTPHypermediaRIM existsStateRIM = null;
for (ResourceInteractionModel r : children) {
if (r.getResourcePath().equals("/machines/toaster")) {
existsStateRIM = (HTTPHypermediaRIM) r;
}
}
// mock the Link header
UriInfo uriInfo = mock(UriInfo.class);
when(uriInfo.getPathParameters(anyBoolean())).thenReturn(new MultivaluedMapImpl<String>());
MultivaluedMap<String, String> mockQueryParameters = new MultivaluedMapImpl<String>();
mockQueryParameters.add("id", "123");
when(uriInfo.getQueryParameters(false)).thenReturn(mockQueryParameters);
Response response = existsStateRIM.get(mock(HttpHeaders.class), "id", uriInfo);
// null resource
RESTResource resource = (RESTResource) response.getEntity();
assertNull(resource);
// 303 "See Other" instructs user agent to fetch another resource as specified by the 'Location' header
assertEquals(Status.SEE_OTHER.getStatusCode(), response.getStatus());
List<Object> locationHeader = response.getMetadata().get("Location");
assertNotNull(locationHeader);
assertEquals(1, locationHeader.size());
assertEquals("/baseuri/machines/toaster/123", locationHeader.get(0));
}
/*
* This test is for a POST request that creates a new resource.
*/
@Test
public void testBuildResponseWith201Created() throws Exception {
/*
* construct an InteractionContext that simply mocks the result of
* creating a resource
*/
ResourceState initialState = new ResourceState("home", "initial", mockActions(new Action("GET", Action.TYPE.VIEW)), "/machines");
ResourceState createPsuedoState = new ResourceState(initialState, "create", mockActions(new Action("POST", Action.TYPE.ENTRY)));
ResourceState individualMachine = new ResourceState(initialState, "machine", mockActions(new Action("GET", Action.TYPE.VIEW)), "/{id}");
// create new machine
initialState.addTransition(new Transition.Builder().method("POST").target(createPsuedoState).build());
// an auto transition to the new resource
Map<String, String> uriLinkageMap = new HashMap<String, String>();
uriLinkageMap.put("id", "{id}");
createPsuedoState.addTransition(new Transition.Builder().flags(Transition.AUTO).target(individualMachine).uriParameters(uriLinkageMap).build());
MapBasedCommandController cc = new MapBasedCommandController();
cc.getCommandMap().put("GET", createCommand("entity", new Entity("entity", null), Result.SUCCESS));
cc.getCommandMap().put("POST", createCommand("entity", null, Result.CREATED));
// RIM with command controller that issues commands that always return CREATED
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(cc, new ResourceStateMachine(initialState, new BeanTransformer()), createMockMetadata());
Response response = rim.post(mock(HttpHeaders.class), "id", mockEmptyUriInfo(), mockEntityResourceWithId("123"));
// null resource
@SuppressWarnings("rawtypes")
GenericEntity ge = (GenericEntity) response.getEntity();
assertNotNull(ge);
RESTResource resource = (RESTResource) ge.getEntity();
assertNotNull(resource);
/*
* 201 "Created" informs the user agent that 'the request has been fulfilled and resulted
* in a new resource being created'. It can be accessed by a GET to the resource specified
* by the 'Location' header
*/
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
List<Object> locationHeader = response.getMetadata().get("Location");
assertNotNull(locationHeader);
assertEquals(1, locationHeader.size());
assertEquals("/baseuri/machines/123", locationHeader.get(0));
}
/*
* This test is for a POST request that creates a new resource, and returns
* the links for the resource we auto transition to.
*/
@Test
public void testPOSTwithAutoTransition() throws Exception {
/*
* construct an InteractionContext that simply mocks the result of
* creating a resource
*/
ResourceState initialState = new ResourceState("home", "initial", mockActions(new Action("GET", Action.TYPE.VIEW)), "/machines");
ResourceState createPsuedoState = new ResourceState(initialState, "create", mockActions(new Action("POST", Action.TYPE.ENTRY)));
ResourceState approvePsuedoState = new ResourceState(initialState, "approve", mockActions(new Action("POST", Action.TYPE.ENTRY)));
ResourceState individualMachine = new ResourceState(initialState, "machine", mockActions(new Action("GET", Action.TYPE.VIEW)), "/{id}");
individualMachine.addTransition(new Transition.Builder().method("GET").target(initialState).build());
// create new machine
initialState.addTransition(new Transition.Builder().method("POST").target(createPsuedoState).build());
// The state should transition from create -> approve -> machine; this tests multi state auto transitions
Map<String, String> uriLinkageMap = new HashMap<String, String>();
uriLinkageMap.put("id", "{id}");
createPsuedoState.addTransition(new Transition.Builder().flags(Transition.AUTO).target(approvePsuedoState).uriParameters(uriLinkageMap).build());
approvePsuedoState.addTransition(new Transition.Builder().flags(Transition.AUTO).target(individualMachine).uriParameters(uriLinkageMap).build());
MapBasedCommandController cc = new MapBasedCommandController();
cc.getCommandMap().put("GET", createCommand("entity", new Entity("entity", null), Result.SUCCESS));
cc.getCommandMap().put("POST", createCommand("entity", null, Result.CREATED));
// RIM with command controller that issues commands that always return CREATED
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(cc, new ResourceStateMachine(initialState, new BeanTransformer()), createMockMetadata());
Response response = rim.post(mock(HttpHeaders.class), "id", mockEmptyUriInfo(), mockEntityResourceWithId("123"));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
// null resource
@SuppressWarnings("rawtypes")
GenericEntity ge = (GenericEntity) response.getEntity();
assertNotNull(ge);
RESTResource resource = (RESTResource) ge.getEntity();
assertNotNull(resource);
/*
* Assert the links in the response match the target resource
*/
EntityResource<?> createdResource = (EntityResource<?>) ((GenericEntity<?>)response.getEntity()).getEntity();
List<Link> links = new ArrayList<Link>(createdResource.getLinks());
assertEquals(2, links.size());
assertEquals("machine", links.get(0).getTitle());
assertEquals("/baseuri/machines/123", links.get(0).getHref());
assertEquals("initial", links.get(1).getTitle());
assertEquals("/baseuri/machines", links.get(1).getHref());
}
/*
* This test is for a POST request that creates a new resource, and has
* an auto transition to a resource that does not exist
*/
@Test
public void testPOSTwithAutoTransitionToNonExistentResource() throws Exception {
/*
* construct an InteractionContext that simply mocks the result of
* creating a resource
*/
ResourceState initialState = new ResourceState("home", "initial", mockActions(), "/machines");
ResourceState createPsuedoState = new ResourceState(initialState, "create", mockActions());
ResourceState individualMachine = new ResourceState(initialState, "machine", mockActions(), "/{id}");
individualMachine.addTransition(new Transition.Builder().method("GET").target(initialState).build());
// create new machine
initialState.addTransition(new Transition.Builder().method("POST").target(createPsuedoState).build());
// an auto transition to the new resource
Map<String, String> uriLinkageMap = new HashMap<String, String>();
uriLinkageMap.put("id", "{id}");
createPsuedoState.addTransition(new Transition.Builder().flags(Transition.AUTO).target(individualMachine).uriParameters(uriLinkageMap).build());
// RIM with command controller that issues commands that return SUCCESS for 'DO' action and FAILURE for 'GET' action (see mockActions())
Map<String,InteractionCommand> commands = new HashMap<String,InteractionCommand>();
commands.put("DO", mockCommand_SUCCESS());
commands.put("GET", mockCommand_FAILURE());
CommandController commandController = new MapBasedCommandController(commands);
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(commandController, new ResourceStateMachine(initialState, new BeanTransformer()), createMockMetadata());
Response response = rim.post(mock(HttpHeaders.class), "id", mockEmptyUriInfo(), mockEntityResourceWithId("123"));
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
// null resource
@SuppressWarnings("rawtypes")
GenericEntity ge = (GenericEntity) response.getEntity();
assertNotNull(ge);
RESTResource resource = (RESTResource) ge.getEntity();
assertNotNull(resource);
}
@Test
public void testPOSTWithTwoConditionalAutomaticTransitionsAndDynamicResourceStates() throws InteractionException {
//given {a graph of resource states comprising of an initial state,
//a middle state and a dynamic state that autotransitions to another resource state}
ResourceState entrance = new ResourceState("house", "entrance", mockSingleAction("DO", Action.TYPE.ENTRY, "POST"), "/entrance", new String[]{"http://temenostech.temenos.com/rels/input"});
ResourceState doorframe = new ResourceState("house", "doorframe", mockSingleAction("NEXT", Action.TYPE.VIEW, "GET"), "/doorframe", new String[]{"http://temenostech.temenos.com/rels/next"});
ResourceState door = new DynamicResourceState("house", "door", "locator", new String[]{"time"});
ResourceState hallway = new ResourceState("house", "hallway", mockIncrementAction(), "/hallway", (String[])null);
ResourceState kitchen = new ResourceState("house", "kitchen", mockSingleAction("DONE", Action.TYPE.ENTRY, "POST"), "/kitchen", new String[]{"http://temenostech.temenos.com/rels/new"});
ResourceState sink = new ResourceState("house", "sink", mockActions(new Action("GET", Action.TYPE.VIEW)), "/sink");
ResourceState lighting = new ResourceState("house", "lighting", mockSingleAction("SEE", Action.TYPE.ENTRY, "POST"), "/lighting");
entrance.addTransition(new Transition.Builder().flags(Transition.AUTO).target(doorframe).evaluation(new ResourceGETExpression(doorframe, ResourceGETExpression.Function.OK)).build());
doorframe.addTransition(new Transition.Builder().flags(Transition.AUTO).target(door).build());
hallway.addTransition(new Transition.Builder().flags(Transition.AUTO).target(doorframe).evaluation(new ResourceGETExpression(doorframe, ResourceGETExpression.Function.OK)).build());
kitchen.addTransition(new Transition.Builder().method("GET").flags(Transition.EMBEDDED).target(lighting).build());
kitchen.addTransition(new Transition.Builder().method("GET").target(sink).build());
//and {a locator that always returns the hallway resource state when invoked with
//string "day" and the kitchen resource state when invoked with string "night"}
ResourceLocatorProvider locatorProvider = mock(ResourceLocatorProvider.class);
ResourceLocator locator = mock(ResourceLocator.class);
when(locator.resolve(eq("day"))).thenReturn(hallway);
when(locator.resolve(eq("night"))).thenReturn(kitchen);
when(locatorProvider.get(eq("locator"))).thenReturn(locator);
Map<String, InteractionCommand> commands = new HashMap<String, InteractionCommand>();
InteractionCommand doSomething = mock(InteractionCommand.class),
getSomething = mock(InteractionCommand.class),
increment = mock(InteractionCommand.class),
next = mock(InteractionCommand.class),
see = mock(InteractionCommand.class),
done = mock(InteractionCommand.class);
//and {two InteractionCommands that execute successfully}
when(getSomething.execute(any(InteractionContext.class))).thenReturn(Result.SUCCESS);
when(done.execute(any(InteractionContext.class))).thenReturn(Result.SUCCESS);
//and {a InteractionCommand for embedding content that fails}
when(see.execute(any(InteractionContext.class))).thenReturn(Result.INVALID_REQUEST);
//and {an InteractionCommand that sets up an alias for resolving a dynamic resource state}
doAnswer(new Answer<Result>() {
@Override
public Result answer(InvocationOnMock invocationOnMock) throws Throwable {
((InteractionContext)invocationOnMock.getArguments()[0]).setAttribute("time", "day");
return Result.SUCCESS;
}
}).when(doSomething).execute(any(InteractionContext.class));
//and {an InteractionCommand that forwards any incoming query parameters}
doAnswer(new Answer<Result>() {
@Override
public Result answer(InvocationOnMock invocationOnMock) throws Throwable {
InteractionContext ctx = (InteractionContext)invocationOnMock.getArguments()[0];
if(ctx.getResource() == null){
ctx.setResource(new EntityResource<Object>());
}
MultivaluedMapHelper.merge(ctx.getQueryParameters(),
ctx.getOutQueryParameters(), MultivaluedMapHelper.Strategy.FAVOUR_DEST);
return Result.SUCCESS;
}
}).when(next).execute(any(InteractionContext.class));
//and {an InteractionCommand that sets up an alias for resolving another
//dynamic resource state and adds query parameters}
doAnswer(new Answer<Result>() {
@Override
public Result answer(InvocationOnMock invocationOnMock) throws Throwable {
InteractionContext ctx = (InteractionContext)invocationOnMock.getArguments()[0];
if(ctx.getOutQueryParameters().get("mode") != null){
ctx.setAttribute("time", "night");
ctx.getOutQueryParameters().add("mode", "run");
ctx.getOutQueryParameters().put("mode", new ArrayList<String>(
Arrays.asList(new String[]{"run"}))
);
}
return Result.SUCCESS;
}
}).when(increment).execute(any(InteractionContext.class));
commands.put("GET", getSomething);
commands.put("DO", doSomething);
commands.put("DONE", done);
commands.put("INCREMENT", increment);
commands.put("NEXT", next);
commands.put("SEE", see);
CommandController commandController = new MapBasedCommandController(commands);
//when {the post method is invoked}
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(commandController, new ResourceStateMachine(entrance, new BeanTransformer(), locatorProvider), createMockMetadata(), locatorProvider);
Response response = rim.post(mock(HttpHeaders.class), "id", mockUriInfoWithParams(), mockEntityResourceWithId("123"));
//then {the response must be HTTP 201 Created}
assertEquals(Status.OK.getStatusCode(), response.getStatus());
//and {the response entity must not be null and must be an instance of/subtype RESTResource}
assertNotNull(GenericEntity.class.isAssignableFrom(response.getEntity().getClass()));
GenericEntity<?> responseEntity = (GenericEntity<?>) response.getEntity();
assertTrue(RESTResource.class.isAssignableFrom(responseEntity.getEntity().getClass()));
//and {the response entity must contain a link with a query parameter added by a command appended to it}
List<Link> links = new ArrayList<Link>(((RESTResource)responseEntity.getEntity()).getLinks());
assertThat(links.size(), equalTo(3));
assertThat(links.get(1).getHref(), equalTo("/baseuri/lighting?mode=run"));
//and {the location header must be set to the final resource resolved
//in the sequence of autotransitions}
assertThat((String)response.getMetadata().get("Location").get(0), allOf(containsString("/baseuri/kitchen"), containsString("mode=run")));
verify(doSomething, times(1)).execute(any(InteractionContext.class));
verify(increment, times(1)).execute(any(InteractionContext.class));
verify(done, times(1)).execute(any(InteractionContext.class));
}
@Test
public void testPOSTTwoConditionalAutomaticTransitionsAndFailingMiddleResource() throws InteractionException{
//given {a graph of resource states comprising of an initial state,
//a middle state and a dynamic state that autotransitions to another resource state}
ResourceState entrance = new ResourceState("house", "entrance", mockSingleAction("DO", Action.TYPE.ENTRY, "POST"), "/entrance", new String[]{"http://temenostech.temenos.com/rels/input"});
ResourceState doorframe = new ResourceState("house", "doorframe", mockSingleAction("NEXT", Action.TYPE.VIEW, "GET"), "/doorframe", new String[]{"http://temenostech.temenos.com/rels/next"});
ResourceState door = new DynamicResourceState("house", "door", "locator", new String[]{"time"});
ResourceState hallway = new ResourceState("house", "hallway", mockIncrementAction(), "/hallway", (String[])null);
ResourceState kitchen = new ResourceState("house", "kitchen", mockSingleAction("DONE", Action.TYPE.ENTRY, "POST"), "/kitchen", new String[]{"http://temenostech.temenos.com/rels/new"});
ResourceState sink = new ResourceState("house", "sink", mockSingleAction("GET", Action.TYPE.VIEW, "GET"), "/sink");
ResourceState lighting = new ResourceState("house", "lighting", mockSingleAction("SEE", Action.TYPE.ENTRY, "POST"), "/lighting");
entrance.addTransition(new Transition.Builder().flags(Transition.AUTO).target(doorframe).evaluation(new ResourceGETExpression(doorframe, ResourceGETExpression.Function.OK)).build());
doorframe.addTransition(new Transition.Builder().flags(Transition.AUTO).target(door).build());
hallway.addTransition(new Transition.Builder().flags(Transition.AUTO).target(doorframe).evaluation(new ResourceGETExpression(doorframe, ResourceGETExpression.Function.OK)).build());
kitchen.addTransition(new Transition.Builder().method("GET").flags(Transition.EMBEDDED).target(lighting).build());
kitchen.addTransition(new Transition.Builder().method("GET").target(sink).build());
//and {a locator that always returns the hallway resource state when invoked with
//string "day" and the kitchen resource state when invoked with string "night"}
ResourceLocatorProvider locatorProvider = mock(ResourceLocatorProvider.class);
ResourceLocator locator = mock(ResourceLocator.class);
when(locator.resolve(eq("day"))).thenReturn(hallway);
when(locator.resolve(eq("night"))).thenReturn(kitchen);
when(locatorProvider.get(eq("locator"))).thenReturn(locator);
Map<String, InteractionCommand> commands = new HashMap<String, InteractionCommand>();
InteractionCommand doSomething = mock(InteractionCommand.class),
getSomething = mock(InteractionCommand.class),
increment = mock(InteractionCommand.class),
next = mock(InteractionCommand.class),
see = mock(InteractionCommand.class),
done = mock(InteractionCommand.class);
//and {two InteractionCommands that execute successfully}
when(getSomething.execute(any(InteractionContext.class))).thenReturn(Result.SUCCESS);
when(done.execute(any(InteractionContext.class))).thenReturn(Result.SUCCESS);
//and {an InteractionCommand for embedding content that fails}
when(see.execute(any(InteractionContext.class))).thenReturn(Result.INVALID_REQUEST);
//and {middle InteractionCommand fails}
when(increment.execute(any(InteractionContext.class))).thenThrow(new InteractionException(Status.BAD_REQUEST));
//and {an InteractionCommand that sets up an alias for resolving a dynamic resource state}
doAnswer(new Answer<Result>() {
@Override
public Result answer(InvocationOnMock invocationOnMock) throws Throwable {
((InteractionContext)invocationOnMock.getArguments()[0]).setAttribute("time", "day");
return Result.SUCCESS;
}
}).when(doSomething).execute(any(InteractionContext.class));
//and {an InteractionCommand that forwards any incoming query parameters}
doAnswer(new Answer<Result>() {
@Override
public Result answer(InvocationOnMock invocationOnMock) throws Throwable {
InteractionContext ctx = (InteractionContext)invocationOnMock.getArguments()[0];
if(ctx.getResource() == null){
ctx.setResource(new EntityResource<Object>());
}
MultivaluedMapHelper.merge(ctx.getQueryParameters(),
ctx.getOutQueryParameters(), MultivaluedMapHelper.Strategy.FAVOUR_DEST);
return Result.SUCCESS;
}
}).when(next).execute(any(InteractionContext.class));
commands.put("GET", getSomething);
commands.put("DO", doSomething);
commands.put("DONE", done);
commands.put("INCREMENT", increment);
commands.put("NEXT", next);
commands.put("SEE", see);
CommandController commandController = new MapBasedCommandController(commands);
//when {the post method is invoked}
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(commandController, new ResourceStateMachine(entrance, new BeanTransformer(), locatorProvider), createMockMetadata(), locatorProvider);
Response response = rim.post(mock(HttpHeaders.class), "id", mockUriInfoWithParams(), mockEntityResourceWithId("123"));
//then {the response must be HTTP 400 bad request}
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
//and {the response entity must not be null and must be an instance of/subtype RESTResource}
assertNotNull(GenericEntity.class.isAssignableFrom(response.getEntity().getClass()));
GenericEntity<?> responseEntity = (GenericEntity<?>) response.getEntity();
assertTrue(RESTResource.class.isAssignableFrom(responseEntity.getEntity().getClass()));
//and {the response entity must contain a link with a query parameter added by a command appended to it}
List<Link> links = new ArrayList<Link>(((RESTResource)responseEntity.getEntity()).getLinks());
assertThat(links.size(), equalTo(1));
//and {the location header must be set to the final resource resolved
//in the sequence of autotransitions}
assertThat((String)response.getMetadata().get("Location").get(0), allOf(containsString("/baseuri/hallway"), containsString("mode=walk")));
verify(doSomething, times(1)).execute(any(InteractionContext.class));
verify(increment, times(2)).execute(any(InteractionContext.class));
verify(done, times(0)).execute(any(InteractionContext.class));
}
@Test
public void testPOSTWithTwoConditionalAutomaticTransitionsFalseEvaluationAndDynamicResourceStates() throws InteractionException {
//given {a graph of resource states comprising of an initial state,
//a middle state and a dynamic state that autotransitions to another resource state}
ResourceState entrance = new ResourceState("house", "entrance", mockSingleAction("DO", Action.TYPE.ENTRY, "POST"), "/entrance", new String[]{"http://temenostech.temenos.com/rels/input"});
ResourceState doorframe = new ResourceState("house", "doorframe", mockSingleAction("NEXT", Action.TYPE.VIEW, "GET"), "/doorframe", new String[]{"http://temenostech.temenos.com/rels/next"});
ResourceState door = new DynamicResourceState("house", "door", "locator", new String[]{"time"});
ResourceState hallway = new ResourceState("house", "hallway", mockIncrementAction(), "/hallway", (String[])null);
ResourceState kitchen = new ResourceState("house", "kitchen", mockSingleAction("DONE", Action.TYPE.ENTRY, "POST"), "/kitchen", new String[]{"http://temenostech.temenos.com/rels/new"});
ResourceState sink = new ResourceState("house", "sink", mockSingleAction("GET", Action.TYPE.VIEW, "GET"), "/sink");
ResourceState lighting = new ResourceState("house", "lighting", mockSingleAction("SEE", Action.TYPE.ENTRY, "POST"), "/lighting");
entrance.addTransition(new Transition.Builder().flags(Transition.AUTO).target(doorframe).evaluation(new ResourceGETExpression(doorframe, ResourceGETExpression.Function.OK)).build());
doorframe.addTransition(new Transition.Builder().flags(Transition.AUTO).target(door).build());
hallway.addTransition(new Transition.Builder().flags(Transition.AUTO).target(kitchen).evaluation(new ResourceGETExpression(kitchen, ResourceGETExpression.Function.OK)).build());
kitchen.addTransition(new Transition.Builder().method("GET").flags(Transition.EMBEDDED).target(lighting).build());
kitchen.addTransition(new Transition.Builder().method("GET").target(sink).build());
//and {a locator that always returns the hallway resource state when invoked with
//string "day"}
ResourceLocatorProvider locatorProvider = mock(ResourceLocatorProvider.class);
ResourceLocator locator = mock(ResourceLocator.class);
when(locator.resolve(eq("day"))).thenReturn(hallway);
when(locatorProvider.get(eq("locator"))).thenReturn(locator);
Map<String, InteractionCommand> commands = new HashMap<String, InteractionCommand>();
InteractionCommand doSomething = mock(InteractionCommand.class),
getSomething = mock(InteractionCommand.class),
increment = mock(InteractionCommand.class),
next = mock(InteractionCommand.class),
see = mock(InteractionCommand.class),
notDoneYet = mock(InteractionCommand.class),
done = mock(InteractionCommand.class);
//and {three InteractionCommands that execute successfully}
when(getSomething.execute(any(InteractionContext.class))).thenReturn(Result.SUCCESS);
when(next.execute(any(InteractionContext.class))).thenReturn(Result.SUCCESS);
when(done.execute(any(InteractionContext.class))).thenReturn(Result.SUCCESS);
//and {an InteractionCommand for embedding content that fails}
when(see.execute(any(InteractionContext.class))).thenReturn(Result.INVALID_REQUEST);
//and {an InteractionCommand that sets up an alias for resolving a dynamic resource state}
doAnswer(new Answer<Result>() {
@Override
public Result answer(InvocationOnMock invocationOnMock) throws Throwable {
((InteractionContext)invocationOnMock.getArguments()[0]).setAttribute("time", "day");
return Result.SUCCESS;
}
}).when(doSomething).execute(any(InteractionContext.class));
//and {an InteractionCommand that always throws an InteractionException}
doThrow(new InteractionException(Status.INTERNAL_SERVER_ERROR))
.when(increment)
.execute(any(InteractionContext.class));
commands.put("GET", getSomething);
commands.put("DO", doSomething);
commands.put("NOT_DONE_YET", notDoneYet);
commands.put("DONE", done);
commands.put("INCREMENT", increment);
commands.put("NEXT", next);
commands.put("SEE", see);
CommandController commandController = new MapBasedCommandController(commands);
//when {the post method is invoked}
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(commandController, new ResourceStateMachine(entrance, new BeanTransformer(), locatorProvider), createMockMetadata(), locatorProvider);
Response response = rim.post(mock(HttpHeaders.class), "id", mockUriInfoWithParams(), mockEntityResourceWithId("123"));
//then {the response must be HTTP 201 Created}
assertEquals(Status.OK.getStatusCode(), response.getStatus());
//and {the response entity must not be null and must be an instance of/subtype RESTResource}
assertNotNull(GenericEntity.class.isAssignableFrom(response.getEntity().getClass()));
GenericEntity<?> responseEntity = (GenericEntity<?>) response.getEntity();
assertTrue(RESTResource.class.isAssignableFrom(responseEntity.getEntity().getClass()));
//and {the response entity must contain a link with a query parameter added by a command appended to it}
List<Link> links = new ArrayList<Link>(((RESTResource)responseEntity.getEntity()).getLinks());
assertThat(links.size(), equalTo(3));
assertThat(links.get(1).getHref(), equalTo("/baseuri/lighting"));
//and {the location header must be set to the final resource resolved
//in the sequence of autotransitions}
assertThat((String)response.getMetadata().get("Location").get(0), allOf(containsString("/baseuri/kitchen"), containsString("mode=walk")));
verify(doSomething, times(1)).execute(any(InteractionContext.class));
verify(increment, times(1)).execute(any(InteractionContext.class));
verify(done, times(2)).execute(any(InteractionContext.class));
}
@Test
public void testPOSTWithOneConditionalAutomaticTransitionAndDynamicResourceState() throws InteractionException {
//given {a graph of resource states comprising of an initial state
//and a dynamic state that autotransitions to another resource state}
ResourceState entrance = new ResourceState(
"house", "entrance", mockSingleAction("DO", Action.TYPE.ENTRY, "POST"),
"/entrance", new String[]{"http://temenostech.temenos.com/rels/input"}
);
ResourceState doorframe = new ResourceState(
"house", "doorframe", mockSingleAction("NEXT", Action.TYPE.VIEW, "GET"),
"/doorframe", new String[]{"http://temenostech.temenos.com/rels/next"}
);
ResourceState door = new DynamicResourceState("house", "door", "locator", new String[]{"time"});
ResourceState hallway = new ResourceState(
"house", "hallway", mockSingleAction("DONE", Action.TYPE.ENTRY, "POST"),
"/hallway", (String[])null
);
ResourceState curtains = new ResourceState("house", "curtains", mockSingleAction("GET", Action.TYPE.VIEW, "GET"), "/curtains");
ResourceState lighting = new ResourceState("house", "lighting", mockSingleAction("GET", Action.TYPE.VIEW, "GET"), "/lighting");
entrance.addTransition(
new Transition.Builder()
.flags(Transition.AUTO)
.target(doorframe)
.evaluation(new ResourceGETExpression(doorframe, ResourceGETExpression.Function.OK))
.build()
);
doorframe.addTransition(new Transition.Builder().flags(Transition.AUTO).target(door).build());
hallway.addTransition(new Transition.Builder().method("GET").target(curtains).build());
hallway.addTransition(new Transition.Builder().method("GET").target(lighting).build());
//and {a locator that always returns the hallway resource state when invoked with
//string "day"}
ResourceLocatorProvider locatorProvider = mock(ResourceLocatorProvider.class);
ResourceLocator locator = mock(ResourceLocator.class);
when(locator.resolve(eq("day"))).thenReturn(hallway);
when(locatorProvider.get(eq("locator"))).thenReturn(locator);
Map<String, InteractionCommand> commands = new HashMap<String, InteractionCommand>();
InteractionCommand doSomething = mock(InteractionCommand.class),
getSomething = mock(InteractionCommand.class),
next = mock(InteractionCommand.class),
see = mock(InteractionCommand.class),
done = mock(InteractionCommand.class);
//and {three InteractionCommands that execute successfully}
when(getSomething.execute(any(InteractionContext.class))).thenReturn(Result.SUCCESS);
when(done.execute(any(InteractionContext.class))).thenReturn(Result.SUCCESS);
when(next.execute(any(InteractionContext.class))).thenReturn(Result.SUCCESS);
//and {an InteractionCommand that sets up an alias for resolving a
//dynamic resource state and adds query parameters}
doAnswer(new Answer<Result>() {
@Override
public Result answer(InvocationOnMock invocationOnMock) throws Throwable {
InteractionContext ctx = ((InteractionContext)invocationOnMock.getArguments()[0]);
ctx.setAttribute("time", "day");
ctx.getOutQueryParameters().put("mode", new ArrayList<String>(
Arrays.asList(new String[]{"run"}))
);
return Result.SUCCESS;
}
}).when(doSomething).execute(any(InteractionContext.class));
commands.put("GET", getSomething);
commands.put("DO", doSomething);
commands.put("DONE", done);
commands.put("NEXT", next);
commands.put("SEE", see);
CommandController commandController = new MapBasedCommandController(commands);
//when {the post method is invoked}
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(commandController,
new ResourceStateMachine(
entrance, new BeanTransformer(), locatorProvider
),
createMockMetadata(), locatorProvider
);
Response response = rim.post(mock(HttpHeaders.class), "id", mockUriInfoWithParams(), mockEntityResourceWithId("123"));
//then {the response must be HTTP 201 Created}
assertEquals(Status.OK.getStatusCode(), response.getStatus());
//and {the response entity must not be null and must be an instance of/subtype RESTResource}
assertNotNull(GenericEntity.class.isAssignableFrom(response.getEntity().getClass()));
GenericEntity<?> responseEntity = (GenericEntity<?>) response.getEntity();
assertTrue(RESTResource.class.isAssignableFrom(responseEntity.getEntity().getClass()));
//and {the response entity must contain a link with a query parameter added by a command appended to it}
List<Link> links = new ArrayList<Link>(((RESTResource)responseEntity.getEntity()).getLinks());
assertThat(links.size(), equalTo(3));
assertThat(links.get(1).getHref(), equalTo("/baseuri/curtains?mode=run"));
//and {the location header must be set to the final resource resolved
//in the sequence of autotransitions}
assertThat((String)response.getMetadata().get("Location").get(0),
allOf(containsString("/baseuri/hallway"), containsString("mode=run")));
verify(doSomething, times(1)).execute(any(InteractionContext.class));
verify(done, times(1)).execute(any(InteractionContext.class));
}
/*
* This test is for a POST request that creates a new resource, and uses
* linkage parameters to get the resource we transition too
*/
@Test
public void testPOSTwithAutoTransitionLinkageParameters() throws Exception {
/*
* construct an InteractionContext that simply mocks the result of
* creating a resource
*/
ResourceState initialState = new ResourceState("home", "initial", mockActions(), "/machines");
ResourceState createPsuedoState = new ResourceState(initialState, "create", mockActions());
ResourceState individualMachine = new ResourceState(initialState, "machine", mockActions(), "/{test}");
// create new machine
initialState.addTransition(new Transition.Builder().method("POST").target(createPsuedoState).build());
// an auto transition with parameters to the new resource
Map<String, String> linkageMap = new HashMap<String, String>();
linkageMap.put("test", "{id}");
createPsuedoState.addTransition(new Transition.Builder().flags(Transition.AUTO).target(individualMachine).uriParameters(linkageMap).build());
// RIM with command controller that issues commands that always return SUCCESS
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockNoopCommandController(), new ResourceStateMachine(initialState, new BeanTransformer()), createMockMetadata());
Response response = rim.post(mock(HttpHeaders.class), "id", mockEmptyUriInfo(), mockEntityResourceWithId("123"));
// null resource
@SuppressWarnings("rawtypes")
GenericEntity ge = (GenericEntity) response.getEntity();
assertNotNull(ge);
RESTResource resource = (RESTResource) ge.getEntity();
assertNotNull(resource);
/*
* Assert the links in the response match the target resource
*/
EntityResource<?> createdResource = (EntityResource<?>) ((GenericEntity<?>)response.getEntity()).getEntity();
List<Link> links = new ArrayList<Link>(createdResource.getLinks());
assertEquals(1, links.size());
assertEquals("/baseuri/machines/123", links.get(0).getHref());
}
/*
* This test is for a GET request that uses a query linkage parameters to get the
* resource we transition too.
*/
@Test
public void testGETwithAutoTransitionQueryLinkageParameters() throws Exception {
List<Action> actions = new ArrayList<Action>();
actions.add(new Action("GET", Action.TYPE.VIEW));
ResourceState initialState = new ResourceState("home", "initial", actions, "/machines");
// decide whether to go to 'machine' or 'initial'
ResourceState conditionPsuedoState = new ResourceState("home", "condition", actions, "/machines/condition");
ResourceState individualMachine = new ResourceState("home", "machine", actions, "/machines/{test}");
// create new machine
initialState.addTransition(new Transition.Builder().method("GET").target(conditionPsuedoState).build());
// an auto transition with parameters to the new resource
Map<String, String> linkageMap = new HashMap<String, String>();
linkageMap.put("test", "{mytestparam}");
conditionPsuedoState.addTransition(new Transition.Builder().flags(Transition.AUTO).target(individualMachine).uriParameters(linkageMap).build());
// RIM with command controller that issues commands that always return SUCCESS
Map<String,InteractionCommand> commands = new HashMap<String,InteractionCommand>();
commands.put("DO", mockCommand_SUCCESS()); // not used
commands.put("GET", new InteractionCommand() {
@Override
public Result execute(InteractionContext ctx)
throws InteractionException {
ctx.setResource(new EntityResource<String>(""));
return Result.SUCCESS;
}
});
CommandController commandController = new MapBasedCommandController(commands);
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(commandController, new ResourceStateMachine(initialState, new BeanTransformer()), createMockMetadata());
Collection<ResourceInteractionModel> children = rim.getChildren();
// find the resource interaction model for the 'exists' state
HTTPHypermediaRIM conditionStateRIM = null;
for (ResourceInteractionModel r : children) {
if (r.getResourcePath().equals("/machines/condition")) {
conditionStateRIM = (HTTPHypermediaRIM) r;
}
}
UriInfo uriInfo = mock(UriInfo.class);
when(uriInfo.getPathParameters(anyBoolean())).thenReturn(new MultivaluedMapImpl<String>());
MultivaluedMap<String, String> queryParameters = new MultivaluedMapImpl<String>();
queryParameters.add("mytestparam", "123");
when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters);
Response response = conditionStateRIM.get(mock(HttpHeaders.class), "id", uriInfo);
@SuppressWarnings("rawtypes")
GenericEntity ge = (GenericEntity) response.getEntity();
assertNotNull(ge);
RESTResource resource = (RESTResource) ge.getEntity();
assertNotNull(resource);
/*
* Assert the links in the response match the target resource
*/
EntityResource<?> createdResource = (EntityResource<?>) ((GenericEntity<?>)response.getEntity()).getEntity();
List<Link> links = new ArrayList<Link>(createdResource.getLinks());
assertEquals(1, links.size());
assertEquals("/baseuri/machines/123", links.get(0).getHref());
}
private EntityResource<Object> mockEntityResourceWithId(final String id) {
return new EntityResource<Object>(new MockEntity(id));
}
@SuppressWarnings({ "unchecked" })
@Test
public void testBuildResponseWithLinks() throws Exception {
// construct an InteractionContext that simply mocks the result of loading a resource
ResourceState initialState = new ResourceState("entity", "state", mockActions(), "/path");
InteractionContext testContext = new InteractionContext(mock(UriInfo.class), mock(HttpHeaders.class), mock(MultivaluedMap.class), mock(MultivaluedMap.class), initialState, mock(Metadata.class));
testContext.setResource(new EntityResource<Object>(null));
// mock 'new InteractionContext()' in call to get
whenNew(InteractionContext.class).withParameterTypes(UriInfo.class, HttpHeaders.class, MultivaluedMap.class, MultivaluedMap.class, ResourceState.class, Metadata.class)
.withArguments(any(UriInfo.class), any(HttpHeaders.class), any(MultivaluedMap.class), any(MultivaluedMap.class), any(ResourceState.class), any(Metadata.class)).thenReturn(testContext);
List<Link> links = new ArrayList<Link>();
links.add(new Link("id", "self", "href", null, null));
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockNoopCommandController(), new ResourceStateMachine(initialState), createMockMetadata());
Response response = rim.get(mock(HttpHeaders.class), "id", mockEmptyUriInfo());
RESTResource resourceWithLinks = (RESTResource) ((GenericEntity<?>)response.getEntity()).getEntity();
assertNotNull(resourceWithLinks.getLinks());
assertFalse(resourceWithLinks.getLinks().isEmpty());
assertEquals(1, resourceWithLinks.getLinks().size());
Link link = (Link) resourceWithLinks.getLinks().toArray()[0];
assertEquals("self", link.getRel());
}
@SuppressWarnings({ "unchecked" })
@Test
public void testBuildResponseWithDynamicLinkParams() throws Exception {
// construct an InteractionContext that simply mocks the result of loading a resource
ResourceState initialState = new ResourceState("entity", "state", mockActions(), "/path");
ResourceState b = new ResourceState(initialState, "b", new ArrayList<Action>());
Transition t = new Transition.Builder().source(initialState).method("GET").target(b).build();
initialState.addTransition(t);
InteractionContext testContext = new InteractionContext(mock(UriInfo.class), mock(HttpHeaders.class), mock(MultivaluedMap.class), mock(MultivaluedMap.class), initialState, mock(Metadata.class));
MultivaluedMap<String, String> outQueryParameters = testContext.getOutQueryParameters();
outQueryParameters.add("penguin", "emperor");
testContext.setResource(new EntityResource<Object>(null));
// mock 'new InteractionContext()' in call to get
whenNew(InteractionContext.class).withParameterTypes(UriInfo.class, HttpHeaders.class, MultivaluedMap.class, MultivaluedMap.class, ResourceState.class, Metadata.class)
.withArguments(any(UriInfo.class), any(HttpHeaders.class), any(MultivaluedMap.class), any(MultivaluedMap.class), any(ResourceState.class), any(Metadata.class)).thenReturn(testContext);
List<Link> links = new ArrayList<Link>();
links.add(new Link("id", "self", "href", null, null));
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockNoopCommandController(), new ResourceStateMachine(initialState), createMockMetadata());
Response response = rim.get(mock(HttpHeaders.class), "id", mockEmptyUriInfo());
RESTResource resourceWithLinks = (RESTResource) ((GenericEntity<?>)response.getEntity()).getEntity();
assertNotNull(resourceWithLinks.getLinks());
assertFalse(resourceWithLinks.getLinks().isEmpty());
assertEquals(2, resourceWithLinks.getLinks().size());
Link link = (Link) resourceWithLinks.getLinks().toArray()[0];
assertEquals("self", link.getRel());
link = (Link)resourceWithLinks.getLinks().toArray()[1];
assertEquals("item", link.getRel());
assertEquals("/baseuri/path?penguin=emperor", link.getHref());
}
@SuppressWarnings({ "unchecked" })
@Test
public void testBuildResponseWithMultipleDynamicLinkParams() throws Exception {
// construct an InteractionContext that simply mocks the result of loading a resource
ResourceState initialState = new ResourceState("entity", "state", mockActions(), "/path");
ResourceState b = new ResourceState(initialState, "b", new ArrayList<Action>());
Transition t = new Transition.Builder().source(initialState).method("GET").target(b).build();
initialState.addTransition(t);
InteractionContext testContext = new InteractionContext(mock(UriInfo.class), mock(HttpHeaders.class), mock(MultivaluedMap.class), mock(MultivaluedMap.class), initialState, mock(Metadata.class));
MultivaluedMap<String, String> outQueryParameters = testContext.getOutQueryParameters();
outQueryParameters.add("penguin", "emperor");
outQueryParameters.add("crispbread", "coconut");
outQueryParameters.add("penguin", "black");
testContext.setResource(new EntityResource<Object>(null));
// mock 'new InteractionContext()' in call to get
whenNew(InteractionContext.class).withParameterTypes(UriInfo.class, HttpHeaders.class, MultivaluedMap.class, MultivaluedMap.class, ResourceState.class, Metadata.class)
.withArguments(any(UriInfo.class), any(HttpHeaders.class), any(MultivaluedMap.class), any(MultivaluedMap.class), any(ResourceState.class), any(Metadata.class)).thenReturn(testContext);
List<Link> links = new ArrayList<Link>();
links.add(new Link("id", "self", "href", null, null));
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockNoopCommandController(), new ResourceStateMachine(initialState), createMockMetadata());
Response response = rim.get(mock(HttpHeaders.class), "id", mockEmptyUriInfo());
RESTResource resourceWithLinks = (RESTResource) ((GenericEntity<?>)response.getEntity()).getEntity();
assertNotNull(resourceWithLinks.getLinks());
assertFalse(resourceWithLinks.getLinks().isEmpty());
assertEquals(2, resourceWithLinks.getLinks().size());
Link link = (Link) resourceWithLinks.getLinks().toArray()[0];
assertEquals("self", link.getRel());
link = (Link)resourceWithLinks.getLinks().toArray()[1];
assertEquals("item", link.getRel());
assertEquals("/baseuri/path?penguin=emperor&penguin=black&crispbread=coconut", link.getHref());
}
@SuppressWarnings({ "unchecked" })
@Test
public void testBuildResponseEntityName() throws Exception {
// construct an InteractionContext that simply mocks the result of loading a resource
ResourceState initialState = new ResourceState("entity", "state", mockActions(), "/path");
InteractionContext testContext = new InteractionContext(mock(UriInfo.class), null, mock(MultivaluedMap.class), mock(MultivaluedMap.class), initialState, mock(Metadata.class));
testContext.setResource(new EntityResource<Object>(null));
// mock 'new InteractionContext()' in call to get
whenNew(InteractionContext.class).withParameterTypes(UriInfo.class, HttpHeaders.class, MultivaluedMap.class, MultivaluedMap.class, ResourceState.class, Metadata.class)
.withArguments(any(UriInfo.class), any(HttpHeaders.class), any(MultivaluedMap.class), any(MultivaluedMap.class), any(ResourceState.class), any(Metadata.class)).thenReturn(testContext);
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockNoopCommandController(), new ResourceStateMachine(initialState), createMockMetadata());
Response response = rim.get(mock(HttpHeaders.class), "id", mockEmptyUriInfo());
RESTResource resource = (RESTResource) ((GenericEntity<?>)response.getEntity()).getEntity();
assertNotNull(resource.getEntityName());
assertEquals("entity", resource.getEntityName());
}
@SuppressWarnings({ "unchecked" })
private UriInfo mockEmptyUriInfo() {
UriInfo uriInfo = mock(UriInfo.class);
when(uriInfo.getPathParameters(anyBoolean())).thenReturn(mock(MultivaluedMap.class));
when(uriInfo.getQueryParameters(false)).thenReturn(mock(MultivaluedMap.class));
return uriInfo;
}
private UriInfo mockUriInfoWithParams() {
UriInfo uriInfo = mock(UriInfo.class);
MultivaluedMap<String, String> queryParam = new MultivaluedMapImpl<String>();
queryParam.add("mode", "walk");
when(uriInfo.getPathParameters(anyBoolean())).thenReturn(new MultivaluedMapImpl<String>());
when(uriInfo.getQueryParameters(false)).thenReturn(queryParam);
when(uriInfo.getQueryParameters()).thenReturn(queryParam);
return uriInfo;
}
private CommandController mockNoopCommandController() {
// make sure command execution does nothing
CommandController commandController = mock(CommandController.class);
InteractionCommand testCommand = mockCommand_SUCCESS();
when(commandController.isValidCommand(anyString())).thenReturn(true);
when(commandController.fetchCommand(anyString())).thenReturn(testCommand);
return commandController;
}
// create command returning the supplied entity
private InteractionCommand createCommand(final String entityName, final Entity entity, final InteractionCommand.Result result) {
InteractionCommand command = new InteractionCommand() {
public Result execute(InteractionContext ctx) {
if (entity != null) {
ctx.setResource(new EntityResource<Entity>(entityName, entity));
}
return result;
}
};
return command;
}
private InteractionCommand mockCommand_SUCCESS() {
InteractionCommand mockCommand = mock(InteractionCommand.class);
try {
when(mockCommand.execute(any(InteractionContext.class))).thenReturn(Result.SUCCESS);
} catch(InteractionException ie) {
Assert.fail(ie.getMessage());
}
return mockCommand;
}
private InteractionCommand mockCommand_FAILURE() {
InteractionCommand mockCommand = mock(InteractionCommand.class);
try {
when(mockCommand.execute(any(InteractionContext.class))).thenReturn(Result.FAILURE);
} catch(InteractionException ie) {
Assert.fail(ie.getMessage());
}
return mockCommand;
}
/*
* This test is for an OPTIONS request.
* A OPTIONS request uses a GET command, the response must include an Allow header
* and no body plus HttpStatus 204 "No Content".
*/
@Test
public void testOPTIONSBuildResponseWithNoContent() throws Exception {
ResourceState initialState = new ResourceState("entity", "state", mockActions(), "/path");
initialState.addTransition(new Transition.Builder().method(HttpMethod.GET).target(initialState).build());
/*
* Construct an InteractionCommand that simply mocks the result of
* a successful command.
*/
final InteractionCommand mockCommand = new InteractionCommand() {
@Override
public Result execute(InteractionContext ctx) {
ctx.setResource(new EntityResource<Object>(null));
return Result.SUCCESS;
}
};
// create mock command controller
MapBasedCommandController mockCommandController = new MapBasedCommandController();
mockCommandController.setCommandMap(new HashMap<String, InteractionCommand>(){
private static final long serialVersionUID = 1L;
{
put("GET", mockCommand);
put("DO", mockCommand);
}
});
// RIM with command controller that issues our mock InteractionCommand
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockCommandController, new ResourceStateMachine(initialState), createMockMetadata());
Response response = rim.options(mock(HttpHeaders.class), "id", mockEmptyUriInfo());
// 204 http status for no content
assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
// check Allow header
Object allow = response.getMetadata().getFirst("Allow");
assertNotNull(allow);
String[] allows = allow.toString().split(", ");
assertEquals(3, allows.length);
List<String> allowsList = Arrays.asList(allows);
assertTrue(allowsList.contains("GET"));
assertTrue(allowsList.contains("OPTIONS"));
assertTrue(allowsList.contains("HEAD"));
}
/*
* This test checks that a 503 error returns a correct response
*/
@SuppressWarnings("unchecked")
@Test
public void testBuildResponseWith503ServiceUnavailable() {
Response response = getMockResponse(
getInteractionExceptionMockCommand(Status.SERVICE_UNAVAILABLE, "Failed to connect to resource manager."),
new GETExceptionCommand()
);
assertEquals(Response.Status.SERVICE_UNAVAILABLE.getStatusCode(), response.getStatus());
GenericEntity<?> ge = (GenericEntity<?>) response.getEntity();
assertNotNull("Excepted a response body", ge);
if(ResourceTypeHelper.isType(ge.getRawType(), ge.getType(), EntityResource.class, GenericError.class)) {
EntityResource<GenericError> er = (EntityResource<GenericError>) ge.getEntity();
GenericError error = er.getEntity();
assertEquals("503", error.getCode());
assertEquals("Failed to connect to resource manager.", error.getMessage());
}
else {
fail("Response body is not a generic error entity resource type.");
}
}
/*
* This test checks returning a 503 error without a response body
*/
@Test
public void testBuildResponseWith503ServiceUnavailableWithoutResponseBody() {
Response response = getMockResponse(getInteractionExceptionMockCommand(Status.SERVICE_UNAVAILABLE, null));
assertEquals(Response.Status.SERVICE_UNAVAILABLE.getStatusCode(), response.getStatus());
assertNull(response.getEntity());
}
/*
* This test checks that a 504 error returns a correct response
*/
@SuppressWarnings("unchecked")
@Test
public void testBuildResponseWith504GatewayTimeout() {
Response response = getMockResponse(
getInteractionExceptionMockCommand(HttpStatusTypes.GATEWAY_TIMEOUT, "Request timeout."),
new GETExceptionCommand()
);
assertEquals(HttpStatusTypes.GATEWAY_TIMEOUT.getStatusCode(), response.getStatus());
GenericEntity<?> ge = (GenericEntity<?>) response.getEntity();
assertNotNull("Excepted a response body", ge);
if(ResourceTypeHelper.isType(ge.getRawType(), ge.getType(), EntityResource.class, GenericError.class)) {
EntityResource<GenericError> er = (EntityResource<GenericError>) ge.getEntity();
GenericError error = er.getEntity();
assertEquals("504", error.getCode());
assertEquals("Request timeout.", error.getMessage());
}
else {
fail("Response body is not a generic error entity resource type.");
}
}
/*
* This test checks that a 500 error returns a proper error message inside
* the body of the response.
*/
@SuppressWarnings("unchecked")
@Test
public void testBuildResponseWith500InternalServerError() {
ResourceState initialState = new ResourceState("home", "initial", mockActions(), "/machines");
ResourceState createPsuedoState = new ResourceState(initialState, "create", mockActions());
// create new machine
initialState.addTransition(new Transition.Builder().method("POST").target(createPsuedoState).build());
Map<String,InteractionCommand> commands = new HashMap<String,InteractionCommand>();
commands.put("DO", getGenericErrorMockCommand(Result.FAILURE, "Resource manager: 5 fatal error and 2 warnings."));
commands.put("GET", mockCommand_SUCCESS());
CommandController commandController = new MapBasedCommandController(commands);
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(commandController, new ResourceStateMachine(initialState, new BeanTransformer()), createMockMetadata());
Response response = rim.post(mock(HttpHeaders.class), "id", mockEmptyUriInfo(), mockEntityResourceWithId("123"));
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
GenericEntity<?> ge = (GenericEntity<?>) response.getEntity();
assertNotNull("Excepted a response body", ge);
if(ResourceTypeHelper.isType(ge.getRawType(), ge.getType(), EntityResource.class, GenericError.class)) {
EntityResource<GenericError> er = (EntityResource<GenericError>) ge.getEntity();
GenericError error = er.getEntity();
assertEquals("FAILURE", error.getCode());
assertEquals("Resource manager: 5 fatal error and 2 warnings.", error.getMessage());
}
else {
fail("Response body is not a generic error entity resource type.");
}
}
/*
* This test checks that a 400 error returns a proper error message inside
* the body of the response.
*/
@SuppressWarnings("unchecked")
@Test
public void testBuildResponseWith400BadRequest() {
Response response = getMockResponse(getGenericErrorMockCommand(Result.INVALID_REQUEST, "Resource manager: 4 validation errors."));
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
GenericEntity<?> ge = (GenericEntity<?>) response.getEntity();
assertNotNull("Excepted a response body", ge);
if(ResourceTypeHelper.isType(ge.getRawType(), ge.getType(), EntityResource.class, GenericError.class)) {
EntityResource<GenericError> er = (EntityResource<GenericError>) ge.getEntity();
GenericError error = er.getEntity();
assertEquals("INVALID_REQUEST", error.getCode());
assertEquals("Resource manager: 4 validation errors.", error.getMessage());
}
else {
fail("Response body is not a generic error entity resource type.");
}
}
/*
* This test checks that a 403 error returns a proper status code
*/
@SuppressWarnings("unchecked")
@Test
public void testBuildResponseWith403AuthorisationFailure() {
Response response = getMockResponse(
getInteractionExceptionMockCommand(Status.FORBIDDEN, "User is not allowed to access this resource."),
new GETExceptionCommand()
);
assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus());
GenericEntity<?> ge = (GenericEntity<?>) response.getEntity();
assertNotNull("Excepted a response body", ge);
if(ResourceTypeHelper.isType(ge.getRawType(), ge.getType(), EntityResource.class, GenericError.class)) {
EntityResource<GenericError> er = (EntityResource<GenericError>) ge.getEntity();
GenericError error = er.getEntity();
assertEquals("403", error.getCode());
assertEquals("User is not allowed to access this resource.", error.getMessage());
}
else {
fail("Response body is not a generic error entity resource type.");
}
}
/*
* This test checks that a 500 error is returned when a
* command throws an exception.
*/
@Test
public void testGETCommandThrowsException() {
try {
getMockResponse(getRuntimeExceptionMockCommand("Unknown fatal error."));
fail("Test failed to throw a runtime exception");
}
catch(RuntimeException re) {
assertEquals("Unknown fatal error.", re.getMessage());
}
}
/*
* Test to ensure command can cause 404 error if a specific entity is not available.
*/
@Test
public void testGETBuildResponseWith404NotFound() {
Response response = getMockResponse(mockCommand_FAILURE());
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
}
/*
* Test to ensure command can cause 404 error without a response body if a specific entity is not available.
*/
@Test
public void testGETBuildResponseWith404NotFoundWithoutResponseBody() {
Response response = getMockResponse(mockCommand_FAILURE());
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
assertNull(response.getEntity());
}
/*
* Test to ensure command can cause 404 error if a specific entity is not available.
*/
@SuppressWarnings("unchecked")
@Test
public void testGETBuildResponseWith404NotFoundInteractionException() {
Response response = getMockResponse(
getInteractionExceptionMockCommand(Status.NOT_FOUND, "Resource manager: entity Fred not found or currently unavailable."),
new GETExceptionCommand()
);
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
GenericEntity<?> ge = (GenericEntity<?>) response.getEntity();
assertNotNull("Excepted a response body", ge);
if(ResourceTypeHelper.isType(ge.getRawType(), ge.getType(), EntityResource.class, GenericError.class)) {
EntityResource<GenericError> er = (EntityResource<GenericError>) ge.getEntity();
GenericError error = er.getEntity();
assertEquals("404", error.getCode());
assertEquals("Resource manager: entity Fred not found or currently unavailable.", error.getMessage());
}
else {
fail("Response body is not a generic error entity resource type.");
}
}
/*
* Test to ensure command can cause 404 error if a specific entity is not available on DELETE.
*/
@Test
public void testDELETEBuildResponseWith404NotFound() {
List<Action> actions = new ArrayList<Action>();
actions.add(new Action("DO", Action.TYPE.ENTRY));
/*
* construct an InteractionContext that simply mocks the result of
* creating a resource
*/
ResourceState initialState = new ResourceState("home", "initial", mockActions(), "/machines");
ResourceState individualMachine = new ResourceState(initialState, "machine", actions, "/{id}");
// create new machine
initialState.addTransition(new Transition.Builder().method("DELETE").target(individualMachine).build());
// RIM with command controller that issues commands that return SUCCESS for 'DO' action and FAILURE for 'GET' action (see mockActions())
Map<String,InteractionCommand> commands = new HashMap<String,InteractionCommand>();
commands.put("DO", mockCommand_FAILURE());
commands.put("GET", mockCommand_SUCCESS());
CommandController commandController = new MapBasedCommandController(commands);
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(commandController, new ResourceStateMachine(initialState, new BeanTransformer()), createMockMetadata());
HTTPHypermediaRIM deleteInteraction = (HTTPHypermediaRIM) rim.getChildren().iterator().next();
Response response = deleteInteraction.delete(mock(HttpHeaders.class), "id", mockEmptyUriInfo());
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
}
/*
* This test checks that a 400 error returns a proper error message inside
* the body of the response.
*/
@SuppressWarnings("unchecked")
@Test
public void testBuildResponseWith400BadRequestFromErrorResource() {
Response response = getMockResponseWithErrorResource(getGenericErrorMockCommand(Result.INVALID_REQUEST, "Resource manager: 4 validation errors."));
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
GenericEntity<?> ge = (GenericEntity<?>) response.getEntity();
assertNotNull("Excepted a response body", ge);
if(ResourceTypeHelper.isType(ge.getRawType(), ge.getType(), EntityResource.class, GenericError.class)) {
EntityResource<GenericError> er = (EntityResource<GenericError>) ge.getEntity();
assertEquals("ErrorEntity", er.getEntityName());
GenericError error = er.getEntity();
assertEquals("INVALID_REQUEST", error.getCode());
assertEquals("Resource manager: 4 validation errors.", error.getMessage());
assertNotNull(er.getLinks());
assertFalse(er.getLinks().isEmpty());
assertEquals(1, er.getLinks().size());
Link link = (Link) er.getLinks().toArray()[0];
assertEquals("self", link.getRel());
}
else {
fail("Response body is not a generic error entity resource type.");
}
}
@Test
public void testGETWithETagHeader() throws InteractionException {
//Create mock command
InteractionCommand mockCommand = new InteractionCommand() {
@Override
public Result execute(InteractionContext ctx) throws InteractionException {
RESTResource resource = new EntityResource<Object>(null);
resource.setEntityTag("ABCDEFG");
ctx.setResource(resource);
return Result.SUCCESS;
}
};
//Process mock command and check the response
Response response = getMockResponse(mockCommand);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
List<Object> etagHeader = response.getMetadata().get(HttpHeaders.ETAG);
assertNotNull(etagHeader);
assertEquals(1, etagHeader.size());
assertEquals("ABCDEFG", etagHeader.get(0));
}
@Test
public void testGETWithoutETagHeader() throws InteractionException {
//Create mock command
InteractionCommand mockCommand = new InteractionCommand() {
@Override
public Result execute(InteractionContext ctx) throws InteractionException {
ctx.setResource(new EntityResource<Object>(null));
return Result.SUCCESS;
}
};
//Process mock command and check the response
Response response = getMockResponse(mockCommand);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
List<Object> etagHeader = response.getMetadata().get(HttpHeaders.ETAG);
assertNull(etagHeader);
}
@Test
public void testGETWithEmptyETagHeader() throws InteractionException {
//Create mock command
InteractionCommand mockCommand = new InteractionCommand() {
@Override
public Result execute(InteractionContext ctx) throws InteractionException {
RESTResource resource = new EntityResource<Object>(null);
resource.setEntityTag("");
ctx.setResource(resource);
return Result.SUCCESS;
}
};
//Process mock command and check the response
Response response = getMockResponse(mockCommand);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
List<Object> etagHeader = response.getMetadata().get(HttpHeaders.ETAG);
assertNull(etagHeader);
}
/*
* This test checks that a 412 error returns a proper error message inside
* the body of the response.
*/
@SuppressWarnings("unchecked")
@Test
public void testBuildResponseWith412PreconditionFailed() {
Response response = getMockResponse(getGenericErrorMockCommand(Result.CONFLICT, "Resource has been modified by somebody else."));
assertEquals(Response.Status.PRECONDITION_FAILED.getStatusCode(), response.getStatus());
GenericEntity<?> ge = (GenericEntity<?>) response.getEntity();
assertNotNull("Excepted a response body", ge);
if(ResourceTypeHelper.isType(ge.getRawType(), ge.getType(), EntityResource.class, GenericError.class)) {
EntityResource<GenericError> er = (EntityResource<GenericError>) ge.getEntity();
GenericError error = er.getEntity();
assertEquals("CONFLICT", error.getCode());
assertEquals("Resource has been modified by somebody else.", error.getMessage());
}
else {
fail("Response body is not a generic error entity resource type.");
}
}
/*
* Test to ensure we return a 304 Not modified if the etag of the response is the same
* as the etag on the request's If-None-Match header.
*/
@Test
public void testBuildResponseWith304NotModified() {
HttpHeaders httpHeaders = mock(HttpHeaders.class);
doAnswer(new Answer<List<String>>() {
@SuppressWarnings("serial")
@Override
public List<String> answer(InvocationOnMock invocation) throws Throwable {
String headerName = (String) invocation.getArguments()[0];
if(headerName.equals(HttpHeaders.IF_NONE_MATCH)) {
return new ArrayList<String>() {{
add("ABCDEFG");
}};
}
return null;
}
}).when(httpHeaders).getRequestHeader(any(String.class));
Response response = getMockResponse(getEntityMockCommand("TestEntity", new EntityProperties(), "ABCDEFG"), null, httpHeaders);
assertEquals(Response.Status.NOT_MODIFIED.getStatusCode(), response.getStatus());
GenericEntity<?> ge = (GenericEntity<?>) response.getEntity();
assertNull("Should not have a response body", ge);
}
/*
* Test to ensure we return a 200 Success if the etag of the response is not the same
* as the etag on the request's If-None-Match header.
*/
@SuppressWarnings("unchecked")
@Test
public void testBuildResponseGETModifiedResource() {
HttpHeaders httpHeaders = mock(HttpHeaders.class);
doAnswer(new Answer<List<String>>() {
@SuppressWarnings("serial")
@Override
public List<String> answer(InvocationOnMock invocation) throws Throwable {
String headerName = (String) invocation.getArguments()[0];
if(headerName.equals(HttpHeaders.IF_NONE_MATCH)) {
return new ArrayList<String>() {{
add("ABCDEFG");
}};
}
return null;
}
}).when(httpHeaders).getRequestHeader(any(String.class));
Response response = getMockResponse(getEntityMockCommand("TestEntity", new EntityProperties(), "IJKLMNO"), null, httpHeaders);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
GenericEntity<?> ge = (GenericEntity<?>) response.getEntity();
assertNotNull("Expected a response body", ge);
if(ResourceTypeHelper.isType(ge.getRawType(), ge.getType(), EntityResource.class, Entity.class)) {
EntityResource<Entity> er = (EntityResource<Entity>) ge.getEntity();
assertEquals("TestEntity", er.getEntity().getName());
assertEquals("IJKLMNO", er.getEntityTag()); //Response should have new etag
}
else {
fail("Response body is not an entity resource type.");
}
}
/*
* This test is for a POST request that creates a new resource, and returns
* the links for the resource we auto transition to.
*/
@Test
public void testPOSTwithConditionalAutoTransitions() throws Exception {
/*
* construct an InteractionContext that simply mocks the result of
* creating a resource
*/
ResourceState initialState = new ResourceState("home", "initial", mockActions(), "/machines");
ResourceState createPsuedoState = new ResourceState(initialState, "create", mockActions());
ResourceState individualMachine = new ResourceState(initialState, "machine", mockActions(), "/individualMachine1/{id}");
individualMachine.addTransition(new Transition.Builder().method("GET").target(initialState).build());
ResourceState individualMachine2 = new ResourceState(initialState, "machine2", mockActions(), "/individualMachine2/{id}");
individualMachine.addTransition(new Transition.Builder().method("GET").target(initialState).build());
// create new machine
initialState.addTransition(new Transition.Builder().method("POST").target(createPsuedoState).build());
// an auto transition to the new resource
Map<String, String> uriLinkageMap = new HashMap<String, String>();
uriLinkageMap.put("id", "{id}");
//Add the first auto-transition
List<Expression> conditionalExpressions1 = new ArrayList<Expression>();
conditionalExpressions1.add(new SimpleLogicalExpressionEvaluator(new ArrayList<Expression>()) {
@Override
public boolean evaluate(HTTPHypermediaRIM rimHandler, InteractionContext ctx, EntityResource<?> resource) {
return false;
}
});
createPsuedoState.addTransition(new Transition.Builder().flags(Transition.AUTO).target(individualMachine).uriParameters(uriLinkageMap).evaluation(new SimpleLogicalExpressionEvaluator(conditionalExpressions1)).build());
//Add a second auto-transition
List<Expression> conditionalExpressions2 = new ArrayList<Expression>();
conditionalExpressions2.add(new SimpleLogicalExpressionEvaluator(new ArrayList<Expression>()) {
@Override
public boolean evaluate(HTTPHypermediaRIM rimHandler, InteractionContext ctx, EntityResource<?> resource) {
return true;
}
});
createPsuedoState.addTransition(new Transition.Builder().flags(Transition.AUTO).target(individualMachine2).uriParameters(uriLinkageMap).evaluation(new SimpleLogicalExpressionEvaluator(conditionalExpressions2)).build());
// RIM with command controller that issues commands that always return SUCCESS
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockNoopCommandController(), new ResourceStateMachine(initialState, new BeanTransformer()), createMockMetadata());
Response response = rim.post(mock(HttpHeaders.class), "id", mockEmptyUriInfo(), mockEntityResourceWithId("123"));
// null resource
@SuppressWarnings("rawtypes")
GenericEntity ge = (GenericEntity) response.getEntity();
assertNotNull(ge);
RESTResource resource = (RESTResource) ge.getEntity();
assertNotNull(resource);
/*
* Assert the links in the response match the target resource
*/
EntityResource<?> createdResource = (EntityResource<?>) ((GenericEntity<?>)response.getEntity()).getEntity();
List<Link> links = new ArrayList<Link>(createdResource.getLinks());
assertEquals(1, links.size());
assertEquals("machine2", links.get(0).getTitle());
assertEquals("/baseuri/machines/individualMachine2/123", links.get(0).getHref());
}
protected Response getMockResponse(InteractionCommand mockCommand) {
return this.getMockResponse(mockCommand, null);
}
protected Response getMockResponse(InteractionCommand mockCommand, InteractionCommand mockExceptionCommand) {
return this.getMockResponse(mockCommand, mockExceptionCommand, mock(HttpHeaders.class));
}
protected Response getMockResponse(final InteractionCommand mockCommand, InteractionCommand mockExceptionCommand, HttpHeaders httpHeaders) {
MapBasedCommandController mockCommandController = mock(MapBasedCommandController.class);
mockCommandController.setCommandMap(new HashMap<String, InteractionCommand>(){
private static final long serialVersionUID = 1L;
{
put("GET", mockCommand);
}
});
when(mockCommandController.fetchCommand("GET")).thenReturn(mockCommand);
when(mockCommandController.fetchCommand("DO")).thenReturn(mockCommand);
if(mockExceptionCommand != null) {
mockCommandController.getCommandMap().put("GETException", mockExceptionCommand);
when(mockCommandController.fetchCommand("GETException")).thenReturn(mockExceptionCommand);
}
ResourceState initialState = new ResourceState("entity", "state", mockActions(), "/path");
initialState.setInitial(true);
ResourceState exceptionState = null;
if(mockExceptionCommand != null) {
exceptionState = new ResourceState("exception", "exceptionState", mockExceptionActions(), "/exception");
exceptionState.setException(true);
}
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockCommandController, new ResourceStateMachine(initialState, exceptionState), createMockMetadata());
return rim.get(httpHeaders, "id", mockEmptyUriInfo());
}
protected Response getMockResponseWithErrorResource(final InteractionCommand mockCommand) {
MapBasedCommandController mockCommandController = mock(MapBasedCommandController.class);
final InteractionCommand noopCommand = new NoopGETCommand();
mockCommandController.setCommandMap(new HashMap<String, InteractionCommand>(){
private static final long serialVersionUID = 1L;
{
put("GET", mockCommand);
put("noop", noopCommand);
}
});
when(mockCommandController.fetchCommand("GET")).thenReturn(mockCommand);
when(mockCommandController.fetchCommand("DO")).thenReturn(mockCommand);
when(mockCommandController.fetchCommand("noop")).thenReturn(noopCommand);
ResourceState errorState = new ResourceState("ErrorEntity", "errorState", mockErrorActions(), "/error");
ResourceState initialState = new ResourceState("entity", "state", mockActions(), "/path", null, null, errorState);
initialState.setInitial(true);
HTTPHypermediaRIM rim = new HTTPHypermediaRIM(mockCommandController, new ResourceStateMachine(initialState), createMockMetadata());
return rim.get(mock(HttpHeaders.class), "id", mockEmptyUriInfo());
}
protected InteractionCommand getGenericErrorMockCommand(final InteractionCommand.Result result, final String body) {
InteractionCommand mockCommand = new InteractionCommand() {
@Override
public Result execute(InteractionContext ctx) {
if(body != null) {
ctx.setResource(createGenericErrorResource(new GenericError(result.toString(), body)));
}
return result;
}
};
return mockCommand;
}
protected InteractionCommand getInteractionExceptionMockCommand(final StatusType status, final String message) {
InteractionCommand mockCommand = new InteractionCommand() {
@Override
public Result execute(InteractionContext ctx) throws InteractionException {
throw new InteractionException(status, message);
}
};
return mockCommand;
}
protected InteractionCommand getRuntimeExceptionMockCommand(final String errorMessage) {
InteractionCommand mockCommand = new InteractionCommand() {
@Override
public Result execute(InteractionContext ctx) {
throw new RuntimeException(errorMessage);
}
};
return mockCommand;
}
protected InteractionCommand getEntityMockCommand(final String entityName, final EntityProperties entityProperties, final String etag) {
InteractionCommand mockCommand = new InteractionCommand() {
@Override
public Result execute(InteractionContext ctx) {
RESTResource resource = CommandHelper.createEntityResource(new Entity(entityName, entityProperties));
resource.setEntityTag(etag);
ctx.setResource(resource);
return Result.SUCCESS;
}
};
return mockCommand;
}
public static EntityResource<GenericError> createGenericErrorResource(GenericError error){
return CommandHelper.createEntityResource(error, GenericError.class);
}
}
| agpl-3.0 |
HZKnight/hzguestbook | env/dbmanager.class.php | 3968 | <?php
/*
* Copyright (C) 2014 Luca
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/agpl-3.0.html>.
*/
/**
* Interfaccia di comunicazione con il db (Database type MySql-PDO)
*
* @author Luca Liscio & Marco Lettieri
* @version v 2.0-PDO 2014/06/25 16:03:20
* @copyright Copyright 2014 Luca Liscio
* @license http://www.gnu.org/licenses/agpl-3.0.html GNU/AGPL3
*
* @package HZGuestBook
* @subpackage Env
* @filesource
*/
class DbManager {
private $_conn;
private $tbprefix;
/**
* All'atto della costruziine di un nuovo ogetto esegue la connessione al DB
*
* @param array $config contiene i parametri (type, host, uname, passwd, db) necessari alla connesione
* @throws PDOException
*/
public function __construct($config) {
$connstr = $config['type'].":host=".$config['host'].";dbname=".$config['db'].";charset=utf8";
$this->_conn = new PDO($connstr, $config['uname'], $config['passwd']);
$this->_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->_conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->tbprefix = $config['tb_prefix'];
}
/**
* Chiude la connesione con il db
*/
public function close(){
$this->_conn = null;
}
/**
* Esegue un query sql e restituisce il risultato
*
* @param string $sql stringa contenente la query
* @return array $result contiene il resultset
*/
public function &doQuery($sql){
//Send a sql query that returns a result
$sql = str_replace("$", $this->tbprefix, $sql);
$stmt = $this->_conn->query($sql);
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $res;
}
/**
* Invia al db query di tipo comando e restituisce l'esito dell'esecuzione
*
* @param string $sql
* @return array restituisce l'esito della query
*/
public function &doUpdate($sql){
//Send a sql command that returns the number of rows affected
$sql = str_replace("$", $this->tbprefix, $sql);
echo $sql;
$af = $this->_conn->exec($sql);
$result["sql"] = $sql;
$result["nbrows"] = $af;
return $result;
}
/**
* Restituisce l'ultimo id inserito
* @return mixed
*/
public function sql_insert_id(){
return $this->_conn->lastInsertId();
}
/**
* Formater for \' items
*/
public function sql_format($data){
//When passing the data from a post form, the \' are already set, we will
//replace them with a system code, then replace the single ' by \' and re
//replace the old system code with \'
$formateddata = str_replace("\'", "@sc:bsqu@", $data);
$formateddata = str_replace("'", "\'", $formateddata);
$formateddata = str_replace("@sc:bsqu@", "\'", $formateddata);
return $formateddata;
}
} | agpl-3.0 |
firewalla/firewalla | platform/docker/DockerPlatform.js | 1411 | /* Copyright 2016 Firewalla LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
const Platform = require('../Platform.js');
const f = require('../../net2/Firewalla.js')
const utils = require('../../lib/utils.js');
class DockerPlatform extends Platform {
getName() {
return "docker";
}
getLicenseTypes() {
return ["x0"];
}
getBoardSerial() {
return new Date() / 1;
}
getB4Binary() {
return `${f.getFirewallaHome()}/bin/real.x86_64/bitbridge7`;
}
getB6Binary() {
return `${f.getFirewallaHome()}/bin/real.x86_64/bitbridge6`;
}
async applyCPUDefaultProfile() {
return; // do nothing for red
}
async applyCPUBoostProfile() {
return; // do nothing for red
}
getSubnetCapacity() {
return 24;
}
}
module.exports = DockerPlatform;
| agpl-3.0 |
kailIII/emaresa | trunk.pe/account_reconcile_modifier/wizard/account_reconcile.py | 8383 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: OpenDrive Ltda
# Copyright (c) 2013 Opendrive Ltda
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################
import time
from osv import osv, fields
class account_reconcile_inherit(osv.osv_memory):
_inherit = 'account.move.line.reconcile'
_columns = {
'comment':fields.text('Comment'),
}
def trans_rec_reconcile_full_comment(self, cr, uid, ids, context=None):
mod_obj = self.pool.get('ir.model.data')
period_obj = self.pool.get('account.period')
account_move_line_obj = self.pool.get('account.move.line')
if context is None:
context = {}
date = False
period_id = False
journal_id= False
account_id = False
date = time.strftime('%Y-%m-%d')
ctx = dict(context or {}, account_period_prefer_normal=True)
ids = period_obj.find(cr, uid, dt=date, context=ctx)
if ids:
period_id = ids[0]
context.update({'reconcile_id': account_move_line_obj.reconcile(cr, uid, context['active_ids'], 'manual', account_id,\
period_id, journal_id, context=context)})
model_data_ids = mod_obj.search(cr, uid,[('model','=','ir.ui.view'),\
('name','=','view_account_move_line_reconcile_comment_full')], context=context)
resource_id = mod_obj.read(cr, uid, model_data_ids, fields=['res_id'], context=context)[0]['res_id']
return {
'name': 'Ingrese Comentario',
'context': context,
'view_type': 'form',
'view_mode': 'form',
'res_model': 'account.move.line.reconcile',
'views': [(resource_id,'form')],
'type': 'ir.actions.act_window',
'target': 'new',
}
def trans_rec_reconcile_full(self, cr, uid, ids, context=None):
wizard = self.browse(cr, uid, ids)[0]
if 'reconcile_id' in context:
self.pool.get('account.move.reconcile').write(cr, uid, [ context['reconcile_id'] ],\
{'comment': wizard.comment}, context=context)
return {'type': 'ir.actions.act_window_close'}
def trans_rec_reconcile_partial_comment(self, cr, uid, ids, context=None):
mod_obj = self.pool.get('ir.model.data')
if context is None:
context = {}
model_data_ids = mod_obj.search(cr, uid,[('model','=','ir.ui.view'),\
('name','=','account_move_line_reconcile_writeoff_comment')], context=context)
resource_id = mod_obj.read(cr, uid, model_data_ids, fields=['res_id'], context=context)[0]['res_id']
return {
'name': 'Ingrese Comentario',
'context': context,
'view_type': 'form',
'view_mode': 'form',
'res_model': 'account.move.line.reconcile.writeoff.comment',
'views': [(resource_id,'form')],
'type': 'ir.actions.act_window',
'target': 'new',
}
account_reconcile_inherit()
class account_move_line_reconcile_writeoff_comment(osv.osv_memory):
"""
Funcion de paso para no instanciar la vista de account.move.line.reconcile.writeoff, de lo contrario llamaria\n
los campos requeridos y no permite guardar el comentario.
"""
_name = 'account.move.line.reconcile.writeoff.comment'
_columns = {
'comment_partial':fields.text('Comment', size=64),
}
def trans_rec_reconcile_partial(self, cr, uid, ids, context=None):
context.update({'comment_partial': self.browse(cr, uid, ids)[0].comment_partial})
return self.pool.get('account.move.line.reconcile.writeoff').trans_rec_reconcile_partial(cr, uid, ids, context)
account_move_line_reconcile_writeoff_comment()
class account_move_reconcile_comment(osv.osv):
_inherit = 'account.move.line'
def reconcile_partial_comment(self, cr, uid, ids, type='auto', context=None, writeoff_acc_id=False, writeoff_period_id=False,\
writeoff_journal_id=False):
move_rec_obj = self.pool.get('account.move.reconcile')
merges = []
unmerge = []
total = 0.0
merges_rec = []
company_list = []
if context is None:
context = {}
for line in self.browse(cr, uid, ids, context=context):
if company_list and not line.company_id.id in company_list:
raise osv.except_osv(_('Warning!'), _('To reconcile the entries company should be the same for all entries.'))
company_list.append(line.company_id.id)
for line in self.browse(cr, uid, ids, context=context):
if line.account_id.currency_id:
currency_id = line.account_id.currency_id
else:
currency_id = line.company_id.currency_id
if line.reconcile_id:
raise osv.except_osv(_('Warning'),\
_("Journal Item '%s' (id: %s), Move '%s' is already reconciled!") % (line.name,\
line.id, line.move_id.name))
if line.reconcile_partial_id:
for line2 in line.reconcile_partial_id.line_partial_ids:
if not line2.reconcile_id:
if line2.id not in merges:
merges.append(line2.id)
if line2.account_id.currency_id:
total += line2.amount_currency
else:
total += (line2.debit or 0.0) - (line2.credit or 0.0)
merges_rec.append(line.reconcile_partial_id.id)
else:
unmerge.append(line.id)
if line.account_id.currency_id:
total += line.amount_currency
else:
total += (line.debit or 0.0) - (line.credit or 0.0)
if self.pool.get('res.currency').is_zero(cr, uid, currency_id, total):
res = self.reconcile(cr, uid, merges+unmerge, context=context, writeoff_acc_id=writeoff_acc_id,\
writeoff_period_id=writeoff_period_id, writeoff_journal_id=writeoff_journal_id)
return res
r_id = move_rec_obj.create(cr, uid, {
'type': type,
'line_partial_ids': map(lambda x: (4,x,False), merges+unmerge)
}, context=context)
move_rec_obj.reconcile_partial_check(cr, uid, [r_id] + merges_rec, context=context)
return r_id
class account_move_line_reconcile_writeoff_comment(osv.osv_memory):
_inherit = 'account.move.line.reconcile.writeoff'
def trans_rec_reconcile_partial(self, cr, uid, ids, context=None):
account_move_line_obj = self.pool.get('account.move.line')
reconcile_id = account_move_line_obj.reconcile_partial_comment(cr, uid, context['active_ids'], 'manual', context=context)
if reconcile_id and 'comment_partial' in context:
self.pool.get('account.move.reconcile').write(cr, uid, [reconcile_id],\
{'comment': context['comment_partial']}, context=context)
return {'type': 'ir.actions.act_window_close'}
def trans_rec_reconcile(self, cr, uid, ids, context=None):
wizard = self.browse(cr, uid, ids)[0]
account_move_line_obj = self.pool.get('account.move.line')
period_obj = self.pool.get('account.period')
if context is None:
context = {}
data = self.read(cr, uid, ids,context=context)[0]
account_id = data['writeoff_acc_id'][0]
context['date_p'] = data['date_p']
journal_id = data['journal_id'][0]
context['comment'] = data['comment']
if data['analytic_id']:
context['analytic_id'] = data['analytic_id'][0]
if context['date_p']:
date = context['date_p']
context['account_period_prefer_normal'] = True
ids = period_obj.find(cr, uid, dt=date, context=context)
if ids:
period_id = ids[0]
reconcile_id = account_move_line_obj.reconcile(cr, uid, context['active_ids'], 'manual', account_id,
period_id, journal_id, context=context)
self.pool.get('account.move.reconcile').write(cr, uid, [reconcile_id],\
{'comment': data['comment']}, context=context)
return {'type': 'ir.actions.act_window_close'}
account_move_line_reconcile_writeoff_comment()
| agpl-3.0 |
rafaelcoutinho/sislegis-app | src/main/java/br/gov/mj/sislegis/app/model/Comentario.java | 2515 | package br.gov.mj.sislegis.app.model;
import java.util.Date;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "getAllComentarios4Usuario", query = "select c from Comentario c where c.autor.id=:userId")
})
@JsonIgnoreProperties({ "idProposicao" })
public class Comentario extends AbstractEntity {
private static final long serialVersionUID = 739840933885769688L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@Column(length = 8000)
private String descricao;
@ManyToOne(fetch = FetchType.EAGER)
private Usuario autor;
@Column
@Temporal(TemporalType.TIMESTAMP)
private Date dataCriacao;
@ManyToOne(fetch = FetchType.EAGER)
private Proposicao proposicao;
private Boolean oculto = false;
public Long getId() {
return this.id;
}
public void setId(final Long id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Usuario getAutor() {
return autor;
}
public void setAutor(Usuario autor) {
this.autor = autor;
}
public Date getDataCriacao() {
return dataCriacao;
}
public void setDataCriacao(Date dataCriacao) {
this.dataCriacao = dataCriacao;
}
public Proposicao getProposicao() {
if (!Objects.isNull(this.proposicao)) {
Proposicao p = new Proposicao();
p.setId(proposicao.getId());
this.proposicao = p;
}
return this.proposicao;
}
public void setProposicao(final Proposicao proposicao) {
this.proposicao = proposicao;
}
public Boolean isOculto() {
return oculto;
}
public void setOculto(Boolean oculto) {
this.oculto = oculto;
}
@Override
public String toString() {
String result = getClass().getSimpleName() + " ";
if (descricao != null && !descricao.trim().isEmpty())
result += "descricao: " + descricao;
if (autor != null)
result += ", autor: " + autor;
return result;
}
} | agpl-3.0 |
Muhannes/diaspora | app/controllers/likes_controller.rb | 1792 | # Copyright (c) 2010-2011, Diaspora Inc. This file is
# licensed under the Affero General Public License version 3 or later. See
# the COPYRIGHT file.
class LikesController < ApplicationController
include ApplicationHelper
before_action :authenticate_user!
respond_to :html,
:mobile,
:json
def create
begin
@like = if target
current_user.like!(target)
end
rescue ActiveRecord::RecordNotFound, ActiveRecord::RecordInvalid => e
# do nothing
end
if @like
respond_to do |format|
format.html { render :nothing => true, :status => 201 }
format.mobile { redirect_to post_path(@like.post_id) }
format.json { render :json => @like.as_api_response(:backbone), :status => 201 }
end
else
render :nothing => true, :status => 422
end
end
def destroy
@like = Like.find_by_id_and_author_id!(params[:id], current_user.person.id)
current_user.retract(@like)
respond_to do |format|
format.json { render :nothing => true, :status => 204 }
end
end
#I can go when the old stream goes.
def index
@likes = target.likes.includes(:author => :profile)
@people = @likes.map(&:author)
respond_to do |format|
format.all { render :layout => false }
format.json { render :json => @likes.as_api_response(:backbone) }
end
end
private
def target
@target ||= if params[:post_id]
current_user.find_visible_shareable_by_id(Post, params[:post_id]) || raise(ActiveRecord::RecordNotFound.new)
else
Comment.find(params[:comment_id]).tap do |comment|
raise(ActiveRecord::RecordNotFound.new) unless current_user.find_visible_shareable_by_id(Post, comment.commentable_id)
end
end
end
end
| agpl-3.0 |
erdincay/lpclientpc | src/com/lp/editor/ui/LpToolBarButton.java | 2743 | /*******************************************************************************
* HELIUM V, Open Source ERP software for sustained success
* at small and medium-sized enterprises.
* Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of theLicense, or
* (at your option) any later version.
*
* According to sec. 7 of the GNU Affero General Public License, version 3,
* the terms of the AGPL are supplemented with the following terms:
*
* "HELIUM V" and "HELIUM 5" are registered trademarks of
* HELIUM V IT-Solutions GmbH. The licensing of the program under the
* AGPL does not imply a trademark license. Therefore any rights, title and
* interest in our trademarks remain entirely with us. If you want to propagate
* modified versions of the Program under the name "HELIUM V" or "HELIUM 5",
* you may only do so if you have a written permission by HELIUM V IT-Solutions
* GmbH (to acquire a permission please contact HELIUM V IT-Solutions
* at trademark@heliumv.com).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact: developers@heliumv.com
******************************************************************************/
package com.lp.editor.ui;
import javax.swing.JButton;
/**
* <p>Title: Toolbar - Buttons fuer den Lp - Editor</p>
* <p>Description: Buttons zur Verwendung in der Toolbar</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: Logistik Pur Software GmbH</p>
* @author Sascha Zelzer
* @author Kajetan Fuchsberger
* @version 0.0
* @since 0.0
*/
public class LpToolBarButton
extends JButton {
/**
*
*/
private static final long serialVersionUID = 1L;
String sText;
boolean bTextVisible;
public LpToolBarButton() {
super();
setRolloverEnabled(true);
bTextVisible = false;
}
public void setText(String sText) {
this.sText = sText;
if (bTextVisible) {
super.setText(this.sText);
}
}
public void setTextVisible(boolean bTextVisible) {
this.bTextVisible = bTextVisible;
if (this.bTextVisible) {
super.setText(sText);
}
else {
super.setText(null);
}
}
public boolean getTextVisible() {
return bTextVisible;
}
}
| agpl-3.0 |
neo4j-attic/graphdb | graph-algo/src/test/java/common/SimpleGraphBuilder.java | 8151 | /**
* Copyright (c) 2002-2011 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package common;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
public class SimpleGraphBuilder
{
public static final String KEY_ID = "__simpleGraphBuilderId__";
GraphDatabaseService graphDb;
HashMap<String,Node> nodes;
HashMap<Node,String> nodeNames;
Set<Relationship> edges;
RelationshipType currentRelType = null;
public SimpleGraphBuilder( GraphDatabaseService graphDb,
RelationshipType relationshipType )
{
super();
this.graphDb = graphDb;
nodes = new HashMap<String,Node>();
nodeNames = new HashMap<Node,String>();
edges = new HashSet<Relationship>();
setCurrentRelType( relationshipType );
}
public void clear()
{
for ( Node node : nodes.values() )
{
for ( Relationship relationship : node.getRelationships() )
{
relationship.delete();
}
node.delete();
}
nodes.clear();
nodeNames.clear();
edges.clear();
}
public Set<Relationship> getAllEdges()
{
return edges;
}
public Set<Node> getAllNodes()
{
return nodeNames.keySet();
}
public void setCurrentRelType( RelationshipType currentRelType )
{
this.currentRelType = currentRelType;
}
public Node makeNode( String id )
{
return makeNode( id, Collections.<String, Object>emptyMap() );
}
public Node makeNode( String id, Object... keyValuePairs )
{
return makeNode( id, toMap( keyValuePairs ) );
}
private Map<String, Object> toMap( Object[] keyValuePairs )
{
Map<String, Object> map = new HashMap<String, Object>();
for ( int i = 0; i < keyValuePairs.length; i++ )
{
map.put( keyValuePairs[i++].toString(), keyValuePairs[i] );
}
return map;
}
public Node makeNode( String id, Map<String, Object> properties )
{
Node node = graphDb.createNode();
nodes.put( id, node );
nodeNames.put( node, id );
node.setProperty( KEY_ID, id );
for ( Map.Entry<String, Object> property : properties.entrySet() )
{
if ( property.getKey().equals( KEY_ID ) )
{
throw new RuntimeException( "Can't use '" + property.getKey() + "'" );
}
node.setProperty( property.getKey(), property.getValue() );
}
return node;
}
public Node getNode( String id )
{
return getNode( id, false );
}
public Node getNode( String id, boolean force )
{
Node node = nodes.get( id );
if ( node == null && force )
{
node = makeNode( id );
}
return node;
}
public String getNodeId( Node node )
{
return nodeNames.get( node );
}
public Relationship makeEdge( String node1, String node2 )
{
return makeEdge( node1, node2, Collections.<String, Object>emptyMap() );
}
public Relationship makeEdge( String node1, String node2, Map<String, Object> edgeProperties )
{
Node n1 = getNode( node1, true ), n2 = getNode( node2, true );
Relationship relationship = n1
.createRelationshipTo( n2, currentRelType );
for ( Map.Entry<String, Object> property : edgeProperties.entrySet() )
{
relationship.setProperty( property.getKey(), property.getValue() );
}
edges.add( relationship );
return relationship;
}
public Relationship makeEdge( String node1, String node2, Object... keyValuePairs )
{
return makeEdge( node1, node2, toMap( keyValuePairs ) );
}
/**
* This creates a chain by adding a number of edges. Example: The input
* string "a,b,c,d,e" makes the chain a->b->c->d->e
* @param commaSeparatedNodeNames
* A string with the node names separated by commas.
*/
public void makeEdgeChain( String commaSeparatedNodeNames )
{
String[] nodeNames = commaSeparatedNodeNames.split( "," );
for ( int i = 0; i < nodeNames.length - 1; ++i )
{
makeEdge( nodeNames[i], nodeNames[i + 1] );
}
}
/**
* Same as makeEdgeChain, but with some property set on all edges.
* @param commaSeparatedNodeNames
* A string with the node names separated by commas.
* @param propertyName
* @param propertyValue
*/
public void makeEdgeChain( String commaSeparatedNodeNames,
String propertyName, Object propertyValue )
{
String[] nodeNames = commaSeparatedNodeNames.split( "," );
for ( int i = 0; i < nodeNames.length - 1; ++i )
{
makeEdge( nodeNames[i], nodeNames[i + 1], propertyName,
propertyValue );
}
}
/**
* This creates a number of edges from a number of node names, pairwise.
* Example: Input "a,b,c,d" gives a->b and c->d
* @param commaSeparatedNodeNames
*/
public void makeEdges( String commaSeparatedNodeNames )
{
String[] nodeNames = commaSeparatedNodeNames.split( "," );
for ( int i = 0; i < nodeNames.length / 2; ++i )
{
makeEdge( nodeNames[i * 2], nodeNames[i * 2 + 1] );
}
}
public void importEdges( File file )
{
try
{
CsvFileReader reader = new CsvFileReader( file );
while ( reader.hasNext() )
{
String[] line = reader.next();
makeEdge( line[0], line[1] );
}
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
/**
* Same as makeEdges, but with some property set on all edges.
* @param commaSeparatedNodeNames
* @param propertyName
* @param propertyValue
*/
public void makeEdges( String commaSeparatedNodeNames, String propertyName,
Object propertyValue )
{
String[] nodeNames = commaSeparatedNodeNames.split( "," );
for ( int i = 0; i < nodeNames.length / 2; ++i )
{
makeEdge( nodeNames[i * 2], nodeNames[i * 2 + 1], propertyName,
propertyValue );
}
}
/**
* @param node1Id
* @param node2Id
* @return One relationship between two given nodes, if there exists one,
* otherwise null.
*/
public Relationship getRelationship( String node1Id, String node2Id )
{
Node node1 = getNode( node1Id );
Node node2 = getNode( node2Id );
if ( node1 == null || node2 == null )
{
return null;
}
Iterable<Relationship> relationships = node1.getRelationships();
for ( Relationship relationship : relationships )
{
if ( relationship.getOtherNode( node1 ).equals( node2 ) )
{
return relationship;
}
}
return null;
}
}
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/Clinical/src/ims/clinical/forms/surgicalauditprocedurestaffdialog/GlobalContext.java | 6088 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.clinical.forms.surgicalauditprocedurestaffdialog;
import java.io.Serializable;
public final class GlobalContext extends ims.framework.FormContext implements Serializable
{
private static final long serialVersionUID = 1L;
public GlobalContext(ims.framework.Context context)
{
super(context);
Clinical = new ClinicalContext(context);
}
public final class ClinicalContext implements Serializable
{
private static final long serialVersionUID = 1L;
private ClinicalContext(ims.framework.Context context)
{
this.context = context;
}
public boolean getSelectedHCPsIsNotNull()
{
return !cx_ClinicalSelectedHCPs.getValueIsNull(context);
}
public java.util.ArrayList<Object> getSelectedHCPs()
{
return (java.util.ArrayList<Object>)cx_ClinicalSelectedHCPs.getValue(context);
}
public void setSelectedHCPs(java.util.ArrayList<Object> value)
{
cx_ClinicalSelectedHCPs.setValue(context, value);
}
private ims.framework.ContextVariable cx_ClinicalSelectedHCPs = new ims.framework.ContextVariable("Clinical.SelectedHCPs", "_cv_Clinical.SelectedHCPs");
public boolean getRadiographerSurgAuditProcDetailsIsNotNull()
{
return !cx_ClinicalRadiographerSurgAuditProcDetails.getValueIsNull(context);
}
public ims.core.vo.HcpLiteVoCollection getRadiographerSurgAuditProcDetails()
{
return (ims.core.vo.HcpLiteVoCollection)cx_ClinicalRadiographerSurgAuditProcDetails.getValue(context);
}
public void setRadiographerSurgAuditProcDetails(ims.core.vo.HcpLiteVoCollection value)
{
cx_ClinicalRadiographerSurgAuditProcDetails.setValue(context, value);
}
private ims.framework.ContextVariable cx_ClinicalRadiographerSurgAuditProcDetails = new ims.framework.ContextVariable("Clinical.RadiographerSurgAuditProcDetails", "_cv_Clinical.RadiographerSurgAuditProcDetails");
public boolean getSelectedHcpIsNotNull()
{
return !cx_ClinicalSelectedHcp.getValueIsNull(context);
}
public ims.core.vo.lookups.HcpDisType getSelectedHcp()
{
return (ims.core.vo.lookups.HcpDisType)cx_ClinicalSelectedHcp.getValue(context);
}
public void setSelectedHcp(ims.core.vo.lookups.HcpDisType value)
{
cx_ClinicalSelectedHcp.setValue(context, value);
}
private ims.framework.ContextVariable cx_ClinicalSelectedHcp = new ims.framework.ContextVariable("Clinical.SelectedHcp", "_cv_Clinical.SelectedHcp");
public boolean getSelectedHcpGradeIsNotNull()
{
return !cx_ClinicalSelectedHcpGrade.getValueIsNull(context);
}
public ims.core.vo.lookups.MedicGrade getSelectedHcpGrade()
{
return (ims.core.vo.lookups.MedicGrade)cx_ClinicalSelectedHcpGrade.getValue(context);
}
public void setSelectedHcpGrade(ims.core.vo.lookups.MedicGrade value)
{
cx_ClinicalSelectedHcpGrade.setValue(context, value);
}
private ims.framework.ContextVariable cx_ClinicalSelectedHcpGrade = new ims.framework.ContextVariable("Clinical.SelectedHcpGrade", "_cv_Clinical.SelectedHcpGrade");
public boolean getMedicsSurgicalAuditIsNotNull()
{
return !cx_ClinicalMedicsSurgicalAudit.getValueIsNull(context);
}
public ims.core.vo.MedicLiteVoCollection getMedicsSurgicalAudit()
{
return (ims.core.vo.MedicLiteVoCollection)cx_ClinicalMedicsSurgicalAudit.getValue(context);
}
public void setMedicsSurgicalAudit(ims.core.vo.MedicLiteVoCollection value)
{
cx_ClinicalMedicsSurgicalAudit.setValue(context, value);
}
private ims.framework.ContextVariable cx_ClinicalMedicsSurgicalAudit = new ims.framework.ContextVariable("Clinical.MedicsSurgicalAudit", "_cv_Clinical.MedicsSurgicalAudit");
public boolean getNursessSurgicalAuditIsNotNull()
{
return !cx_ClinicalNursessSurgicalAudit.getValueIsNull(context);
}
public ims.core.vo.NurseVoCollection getNursessSurgicalAudit()
{
return (ims.core.vo.NurseVoCollection)cx_ClinicalNursessSurgicalAudit.getValue(context);
}
public void setNursessSurgicalAudit(ims.core.vo.NurseVoCollection value)
{
cx_ClinicalNursessSurgicalAudit.setValue(context, value);
}
private ims.framework.ContextVariable cx_ClinicalNursessSurgicalAudit = new ims.framework.ContextVariable("Clinical.NursessSurgicalAudit", "_cv_Clinical.NursessSurgicalAudit");
private ims.framework.Context context;
}
public ClinicalContext Clinical;
}
| agpl-3.0 |
kaltura/KalturaGeneratedAPIClientsJava | src/main/java/com/kaltura/client/enums/EntryApplication.java | 2415 | // ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2021 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.client.enums;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
public enum EntryApplication implements EnumAsString {
KMC("0"),
KMS("1"),
KAF("2"),
PITCH("3"),
KMS_GO("4"),
WEBCAST_APP("5"),
PERSONAL_CAPTURE("6"),
KALTURA_MEETING("7");
private String value;
EntryApplication(String value) {
this.value = value;
}
@Override
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
public static EntryApplication get(String value) {
if(value == null)
{
return null;
}
// goes over EntryApplication defined values and compare the inner value with the given one:
for(EntryApplication item: values()) {
if(item.getValue().equals(value)) {
return item;
}
}
// in case the requested value was not found in the enum values, we return the first item as default.
return EntryApplication.values().length > 0 ? EntryApplication.values()[0]: null;
}
}
| agpl-3.0 |
trobert2/juju-core | utils/fslock/fslock_test.go | 8305 | // Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package fslock_test
import (
"fmt"
"io/ioutil"
"os"
"path"
"runtime"
"sync/atomic"
"time"
gc "launchpad.net/gocheck"
"launchpad.net/tomb"
coretesting "launchpad.net/juju-core/testing"
"launchpad.net/juju-core/testing/testbase"
"launchpad.net/juju-core/utils/fslock"
)
type fslockSuite struct {
testbase.LoggingSuite
lockDelay time.Duration
}
var _ = gc.Suite(&fslockSuite{})
func (s *fslockSuite) SetUpSuite(c *gc.C) {
s.LoggingSuite.SetUpSuite(c)
s.PatchValue(&fslock.LockWaitDelay, 1*time.Millisecond)
}
// This test also happens to test that locks can get created when the parent
// lock directory doesn't exist.
func (s *fslockSuite) TestValidNamesLockDir(c *gc.C) {
for _, name := range []string{
"a",
"longer",
"longer-with.special-characters",
} {
dir := c.MkDir()
_, err := fslock.NewLock(dir, name)
c.Assert(err, gc.IsNil)
}
}
func (s *fslockSuite) TestInvalidNames(c *gc.C) {
for _, name := range []string{
".start",
"-start",
"NoCapitals",
"no+plus",
"no/slash",
"no\\backslash",
"no$dollar",
"no:colon",
} {
dir := c.MkDir()
_, err := fslock.NewLock(dir, name)
c.Assert(err, gc.ErrorMatches, "Invalid lock name .*")
}
}
func (s *fslockSuite) TestNewLockWithExistingDir(c *gc.C) {
dir := c.MkDir()
err := os.MkdirAll(dir, 0755)
c.Assert(err, gc.IsNil)
_, err = fslock.NewLock(dir, "special")
c.Assert(err, gc.IsNil)
}
func (s *fslockSuite) TestNewLockWithExistingFileInPlace(c *gc.C) {
dir := c.MkDir()
err := os.MkdirAll(dir, 0755)
c.Assert(err, gc.IsNil)
path := path.Join(dir, "locks")
err = ioutil.WriteFile(path, []byte("foo"), 0644)
c.Assert(err, gc.IsNil)
_, err = fslock.NewLock(path, "special")
c.Assert(err, gc.ErrorMatches, `.* not a directory`)
}
func (s *fslockSuite) TestIsLockHeldBasics(c *gc.C) {
dir := c.MkDir()
lock, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
c.Assert(lock.IsLockHeld(), gc.Equals, false)
err = lock.Lock("")
c.Assert(err, gc.IsNil)
c.Assert(lock.IsLockHeld(), gc.Equals, true)
err = lock.Unlock()
c.Assert(err, gc.IsNil)
c.Assert(lock.IsLockHeld(), gc.Equals, false)
}
func (s *fslockSuite) TestIsLockHeldTwoLocks(c *gc.C) {
dir := c.MkDir()
lock1, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
lock2, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
err = lock1.Lock("")
c.Assert(err, gc.IsNil)
c.Assert(lock2.IsLockHeld(), gc.Equals, false)
}
func (s *fslockSuite) TestLockBlocks(c *gc.C) {
dir := c.MkDir()
lock1, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
lock2, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
acquired := make(chan struct{})
err = lock1.Lock("")
c.Assert(err, gc.IsNil)
go func() {
lock2.Lock("")
acquired <- struct{}{}
close(acquired)
}()
// Waiting for something not to happen is inherently hard...
select {
case <-acquired:
c.Fatalf("Unexpected lock acquisition")
case <-time.After(coretesting.ShortWait):
// all good
}
err = lock1.Unlock()
c.Assert(err, gc.IsNil)
select {
case <-acquired:
// all good
case <-time.After(coretesting.LongWait):
c.Fatalf("Expected lock acquisition")
}
c.Assert(lock2.IsLockHeld(), gc.Equals, true)
}
func (s *fslockSuite) TestLockWithTimeoutUnlocked(c *gc.C) {
dir := c.MkDir()
lock, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
err = lock.LockWithTimeout(10*time.Millisecond, "")
c.Assert(err, gc.IsNil)
}
func (s *fslockSuite) TestLockWithTimeoutLocked(c *gc.C) {
dir := c.MkDir()
lock1, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
lock2, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
err = lock1.Lock("")
c.Assert(err, gc.IsNil)
err = lock2.LockWithTimeout(10*time.Millisecond, "")
c.Assert(err, gc.Equals, fslock.ErrTimeout)
}
func (s *fslockSuite) TestUnlock(c *gc.C) {
dir := c.MkDir()
lock, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
err = lock.Unlock()
c.Assert(err, gc.Equals, fslock.ErrLockNotHeld)
}
func (s *fslockSuite) TestIsLocked(c *gc.C) {
dir := c.MkDir()
lock1, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
lock2, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
err = lock1.Lock("")
c.Assert(err, gc.IsNil)
c.Assert(lock1.IsLocked(), gc.Equals, true)
c.Assert(lock2.IsLocked(), gc.Equals, true)
}
func (s *fslockSuite) TestBreakLock(c *gc.C) {
dir := c.MkDir()
lock1, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
lock2, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
err = lock1.Lock("")
c.Assert(err, gc.IsNil)
err = lock2.BreakLock()
c.Assert(err, gc.IsNil)
c.Assert(lock2.IsLocked(), gc.Equals, false)
// Normally locks are broken due to client crashes, not duration.
err = lock1.Unlock()
c.Assert(err, gc.Equals, fslock.ErrLockNotHeld)
// Breaking a non-existant isn't an error
err = lock2.BreakLock()
c.Assert(err, gc.IsNil)
}
func (s *fslockSuite) TestMessage(c *gc.C) {
dir := c.MkDir()
lock, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
c.Assert(lock.Message(), gc.Equals, "")
err = lock.Lock("my message")
c.Assert(err, gc.IsNil)
c.Assert(lock.Message(), gc.Equals, "my message")
// Unlocking removes the message.
err = lock.Unlock()
c.Assert(err, gc.IsNil)
c.Assert(lock.Message(), gc.Equals, "")
}
func (s *fslockSuite) TestMessageAcrossLocks(c *gc.C) {
dir := c.MkDir()
lock1, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
lock2, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
err = lock1.Lock("very busy")
c.Assert(err, gc.IsNil)
c.Assert(lock2.Message(), gc.Equals, "very busy")
}
func (s *fslockSuite) TestInitialMessageWhenLocking(c *gc.C) {
dir := c.MkDir()
lock, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
err = lock.Lock("initial message")
c.Assert(err, gc.IsNil)
c.Assert(lock.Message(), gc.Equals, "initial message")
err = lock.Unlock()
c.Assert(err, gc.IsNil)
err = lock.LockWithTimeout(10*time.Millisecond, "initial timeout message")
c.Assert(err, gc.IsNil)
c.Assert(lock.Message(), gc.Equals, "initial timeout message")
}
func (s *fslockSuite) TestStress(c *gc.C) {
const lockAttempts = 200
const concurrentLocks = 10
var counter = new(int64)
// Use atomics to update lockState to make sure the lock isn't held by
// someone else. A value of 1 means locked, 0 means unlocked.
var lockState = new(int32)
var done = make(chan struct{})
defer close(done)
dir := c.MkDir()
var stress = func(name string) {
defer func() { done <- struct{}{} }()
lock, err := fslock.NewLock(dir, "testing")
if err != nil {
c.Errorf("Failed to create a new lock")
return
}
for i := 0; i < lockAttempts; i++ {
err = lock.Lock(name)
c.Assert(err, gc.IsNil)
state := atomic.AddInt32(lockState, 1)
c.Assert(state, gc.Equals, int32(1))
// Tell the go routine scheduler to give a slice to someone else
// while we have this locked.
runtime.Gosched()
// need to decrement prior to unlock to avoid the race of someone
// else grabbing the lock before we decrement the state.
atomic.AddInt32(lockState, -1)
err = lock.Unlock()
c.Assert(err, gc.IsNil)
// increment the general counter
atomic.AddInt64(counter, 1)
}
}
for i := 0; i < concurrentLocks; i++ {
go stress(fmt.Sprintf("Lock %d", i))
}
for i := 0; i < concurrentLocks; i++ {
<-done
}
c.Assert(*counter, gc.Equals, int64(lockAttempts*concurrentLocks))
}
func (s *fslockSuite) TestTomb(c *gc.C) {
const timeToDie = 200 * time.Millisecond
die := tomb.Tomb{}
dir := c.MkDir()
lock, err := fslock.NewLock(dir, "testing")
c.Assert(err, gc.IsNil)
// Just use one lock, and try to lock it twice.
err = lock.Lock("very busy")
c.Assert(err, gc.IsNil)
checkTomb := func() error {
select {
case <-die.Dying():
return tomb.ErrDying
default:
// no-op to fall through to return.
}
return nil
}
go func() {
time.Sleep(timeToDie)
die.Killf("time to die")
}()
err = lock.LockWithFunc("won't happen", checkTomb)
c.Assert(err, gc.Equals, tomb.ErrDying)
c.Assert(lock.Message(), gc.Equals, "very busy")
}
| agpl-3.0 |
GluuFederation/gluu-Asimba | asimba-wa/src/test/java/org/asimba/wa/integrationtest/saml/CustomAuthnRequestIntegrationTest.java | 4755 | /*
* Asimba - Serious Open Source SSO
*
* Copyright (C) 2014 Asimba
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see www.gnu.org/licenses
*
* Asimba - Serious Open Source SSO - More information on www.asimba.org
*
*/
package org.asimba.wa.integrationtest.saml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.asimba.wa.integrationtest.RunConfiguration;
import org.asimba.wa.integrationtest.saml2.sp.SAML2SP;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.opensaml.common.xml.SAMLConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gargoylesoftware.htmlunit.TextPage;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
/**
* Tests the sending of different SAML2 AuthnRequest messages with specific properties,
* both valid as well as invalid.<br/>
* <br/>
* Binding properties: all SAML messages are sent through HTTP-Redirect binding, and
* the responses are received through HTTP-Post binding.<br/>
* <br/>
* Tests being performed in this class:
* <ul>
* <li>UnsignedRequest : tests whether unsigned requests are rejected correctly</li>
* </ul>
*
* @author mdobrinic
*
*/
public class CustomAuthnRequestIntegrationTest {
private static Logger _logger = LoggerFactory.getLogger(CustomAuthnRequestIntegrationTest.class);
private WebClient _webClient;
private String _samlWebSSOUrl;
private SAML2SP _samlClient;
@Before
public void setup() throws Exception
{
_webClient = new WebClient();
_samlWebSSOUrl = RunConfiguration.getInstance().getProperty("asimbawa.saml.websso.url");
_samlClient = new SAML2SP("urn:asimba:requestor:samlclient-test:customauthnreq", null); // no SSL context (yet...)
_samlClient.registerInRequestorPool("requestorpool.1");
}
@After
public void stop()
{
_samlClient.unregister();
_webClient.closeAllWindows();
}
@Test @Category(SAMLTests.class)
public void testUnsignedRequest() throws Exception
{
_logger.trace("testUnsignedRequest entered");
// Send unsigned request, when signing is not required
WebRequest authnRequest = _samlClient.getAuthnWebRequest(_samlWebSSOUrl, SAMLConstants.SAML2_REDIRECT_BINDING_URI);
_logger.info("Sending request to {}", authnRequest.getUrl().toString());
HtmlPage htmlPage = _webClient.getPage(authnRequest);
String content = htmlPage.asXml();
_logger.info("Received (1): {}", content);
// Assert that we got a HTTP 200/OK:
assertEquals(200, htmlPage.getWebResponse().getStatusCode());
// Assert that we get the selection-form here:
HtmlForm form = htmlPage.getFormByName("select");
assertNotNull(form);
// Just cancel the request:
HtmlSubmitInput button = form.getInputByName("cancel");
TextPage textPage = button.click();
// .. and assert that we received AuthnFailed as SubStatuscode as SAML SP: and OK as content:
String samlSubStatusCode = _samlClient.getReceivedResponse().getSubStatusCode();
assertEquals("urn:oasis:names:tc:SAML:2.0:status:AuthnFailed", samlSubStatusCode);
assertEquals("OK", textPage.getContent());
// Now override property so signing is required:
_samlClient.unregisterProperty("saml2.signing");
_samlClient.registerProperty("saml2.signing", "true");
// Send unsigned request, when signing *is* required
authnRequest = _samlClient.getAuthnWebRequest(_samlWebSSOUrl, SAMLConstants.SAML2_REDIRECT_BINDING_URI);
_logger.info("Sending request to {}", authnRequest.getUrl().toString());
// Prepare for error:
_webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
// and make call
htmlPage = _webClient.getPage(authnRequest);
content = htmlPage.asXml();
_logger.info("Received (B1): {}", content);
// Assert that we get a HTTP 403/Forbidden response
assertEquals(403, htmlPage.getWebResponse().getStatusCode());
}
}
| agpl-3.0 |
RBSWebFactory/framework | persistentdocument/import/ScriptBindingElement.class.php | 784 | <?php
class import_ScriptBindingElement extends import_ScriptBaseElement
{
public function process()
{
if (isset($this->attributes['fileName']))
{
$fileName = f_util_FileUtils::buildAbsolutePath(WEBEDIT_HOME, $this->attributes['fileName']);
if (file_exists($fileName))
{
$this->script->executeInternal($fileName);
}
else
{
echo "Binding '$fileName' not found.\n";
}
}
else if (isset($this->attributes['name']) && isset($this->attributes['className']))
{
$className = $this->attributes['className'];
if (f_util_ClassUtils::classExists($className))
{
$this->script->registerElementClass($this->attributes['name'], $className);
}
else
{
echo "Class '$className' not found.\n";
}
}
}
} | agpl-3.0 |
sharmila76/empower_fresh_setup | custom/Extension/modules/HRM_Holydays/Ext/Language/en_us.HRM.php | 31769 | <?php
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "HRM_Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
$mod_strings [ "LBL_HRM_EMPLOYEES_HRM_HOLYDAYS_FROM_HRM_EMPLOYEES_TITLE" ] = "Employees" ;
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/ValueObjects/src/ims/core/vo/domain/LocSiteFullVoAssembler.java | 23722 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5007.25751)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 16/04/2014, 12:32
*
*/
package ims.core.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Daniel Laffan
*/
public class LocSiteFullVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.core.vo.LocSiteFullVo copy(ims.core.vo.LocSiteFullVo valueObjectDest, ims.core.vo.LocSiteFullVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_Location(valueObjectSrc.getID_Location());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// parentOrganisation
valueObjectDest.setParentOrganisation(valueObjectSrc.getParentOrganisation());
// Services
valueObjectDest.setServices(valueObjectSrc.getServices());
// ActivityLimitGroup
valueObjectDest.setActivityLimitGroup(valueObjectSrc.getActivityLimitGroup());
// Locations
valueObjectDest.setLocations(valueObjectSrc.getLocations());
// parentLocation
valueObjectDest.setParentLocation(valueObjectSrc.getParentLocation());
// Printers
valueObjectDest.setPrinters(valueObjectSrc.getPrinters());
// DefaultPrinter
valueObjectDest.setDefaultPrinter(valueObjectSrc.getDefaultPrinter());
// DesignatedPrinterForNewResults
valueObjectDest.setDesignatedPrinterForNewResults(valueObjectSrc.getDesignatedPrinterForNewResults());
// DesignatedPrinterForOCSOrder
valueObjectDest.setDesignatedPrinterForOCSOrder(valueObjectSrc.getDesignatedPrinterForOCSOrder());
// CodeMappings
valueObjectDest.setCodeMappings(valueObjectSrc.getCodeMappings());
// Address
valueObjectDest.setAddress(valueObjectSrc.getAddress());
// SecureAccommodation
valueObjectDest.setSecureAccommodation(valueObjectSrc.getSecureAccommodation());
// TreatingHosp
valueObjectDest.setTreatingHosp(valueObjectSrc.getTreatingHosp());
// ReferringHospital
valueObjectDest.setReferringHospital(valueObjectSrc.getReferringHospital());
// Name
valueObjectDest.setName(valueObjectSrc.getName());
// isActive
valueObjectDest.setIsActive(valueObjectSrc.getIsActive());
// IsVirtual
valueObjectDest.setIsVirtual(valueObjectSrc.getIsVirtual());
// Type
valueObjectDest.setType(valueObjectSrc.getType());
// DisplayInEDTracking
valueObjectDest.setDisplayInEDTracking(valueObjectSrc.getDisplayInEDTracking());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #createLocSiteFullVoCollectionFromLocSite(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.core.resource.place.domain.objects.LocSite objects.
*/
public static ims.core.vo.LocSiteFullVoCollection createLocSiteFullVoCollectionFromLocSite(java.util.Set domainObjectSet)
{
return createLocSiteFullVoCollectionFromLocSite(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.core.resource.place.domain.objects.LocSite objects.
*/
public static ims.core.vo.LocSiteFullVoCollection createLocSiteFullVoCollectionFromLocSite(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.core.vo.LocSiteFullVoCollection voList = new ims.core.vo.LocSiteFullVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.core.resource.place.domain.objects.LocSite domainObject = (ims.core.resource.place.domain.objects.LocSite) iterator.next();
ims.core.vo.LocSiteFullVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.core.resource.place.domain.objects.LocSite objects.
*/
public static ims.core.vo.LocSiteFullVoCollection createLocSiteFullVoCollectionFromLocSite(java.util.List domainObjectList)
{
return createLocSiteFullVoCollectionFromLocSite(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.core.resource.place.domain.objects.LocSite objects.
*/
public static ims.core.vo.LocSiteFullVoCollection createLocSiteFullVoCollectionFromLocSite(DomainObjectMap map, java.util.List domainObjectList)
{
ims.core.vo.LocSiteFullVoCollection voList = new ims.core.vo.LocSiteFullVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.core.resource.place.domain.objects.LocSite domainObject = (ims.core.resource.place.domain.objects.LocSite) domainObjectList.get(i);
ims.core.vo.LocSiteFullVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.core.resource.place.domain.objects.LocSite set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractLocSiteSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.LocSiteFullVoCollection voCollection)
{
return extractLocSiteSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractLocSiteSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.LocSiteFullVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.core.vo.LocSiteFullVo vo = voCollection.get(i);
ims.core.resource.place.domain.objects.LocSite domainObject = LocSiteFullVoAssembler.extractLocSite(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.core.resource.place.domain.objects.LocSite list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractLocSiteList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.LocSiteFullVoCollection voCollection)
{
return extractLocSiteList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractLocSiteList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.LocSiteFullVoCollection voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.core.vo.LocSiteFullVo vo = voCollection.get(i);
ims.core.resource.place.domain.objects.LocSite domainObject = LocSiteFullVoAssembler.extractLocSite(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.core.resource.place.domain.objects.LocSite object.
* @param domainObject ims.core.resource.place.domain.objects.LocSite
*/
public static ims.core.vo.LocSiteFullVo create(ims.core.resource.place.domain.objects.LocSite domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.core.resource.place.domain.objects.LocSite object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.core.vo.LocSiteFullVo create(DomainObjectMap map, ims.core.resource.place.domain.objects.LocSite domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.core.vo.LocSiteFullVo valueObject = (ims.core.vo.LocSiteFullVo) map.getValueObject(domainObject, ims.core.vo.LocSiteFullVo.class);
if ( null == valueObject )
{
valueObject = new ims.core.vo.LocSiteFullVo(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.core.resource.place.domain.objects.LocSite
*/
public static ims.core.vo.LocSiteFullVo insert(ims.core.vo.LocSiteFullVo valueObject, ims.core.resource.place.domain.objects.LocSite domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.core.resource.place.domain.objects.LocSite
*/
public static ims.core.vo.LocSiteFullVo insert(DomainObjectMap map, ims.core.vo.LocSiteFullVo valueObject, ims.core.resource.place.domain.objects.LocSite domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_Location(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// parentOrganisation
valueObject.setParentOrganisation(ims.core.vo.domain.OrganisationVoAssembler.create(map, domainObject.getParentOrganisation()) );
// Services
valueObject.setServices(ims.core.vo.domain.LocationServiceVoAssembler.createLocationServiceVoCollectionFromLocationService(map, domainObject.getServices()) );
// ActivityLimitGroup
valueObject.setActivityLimitGroup(ims.core.vo.domain.ActivityGroupLimitsVoAssembler.createActivityGroupLimitsVoCollectionFromActivityLimitGroup(map, domainObject.getActivityLimitGroup()) );
// Locations
valueObject.setLocations(ims.core.vo.domain.LocMostVoAssembler.createLocMostVoCollectionFromLocation(map, domainObject.getLocations()) );
// parentLocation
valueObject.setParentLocation(ims.core.vo.domain.LocMostVoAssembler.create(map, domainObject.getParentLocation()) );
// Printers
valueObject.setPrinters(ims.admin.vo.domain.PrinterVoAssembler.createPrinterVoCollectionFromPrinter(map, domainObject.getPrinters()) );
// DefaultPrinter
valueObject.setDefaultPrinter(ims.admin.vo.domain.PrinterVoAssembler.create(map, domainObject.getDefaultPrinter()) );
// DesignatedPrinterForNewResults
valueObject.setDesignatedPrinterForNewResults(ims.admin.vo.domain.PrinterVoAssembler.create(map, domainObject.getDesignatedPrinterForNewResults()) );
// DesignatedPrinterForOCSOrder
valueObject.setDesignatedPrinterForOCSOrder(ims.admin.vo.domain.PrinterVoAssembler.create(map, domainObject.getDesignatedPrinterForOCSOrder()) );
// CodeMappings
valueObject.setCodeMappings(ims.core.vo.domain.TaxonomyMapAssembler.createTaxonomyMapCollectionFromTaxonomyMap(map, domainObject.getCodeMappings()) );
// Address
valueObject.setAddress(ims.core.vo.domain.PersonAddressAssembler.create(map, domainObject.getAddress()) );
// SecureAccommodation
valueObject.setSecureAccommodation( domainObject.isSecureAccommodation() );
// TreatingHosp
valueObject.setTreatingHosp( domainObject.isTreatingHosp() );
// ReferringHospital
valueObject.setReferringHospital( domainObject.isReferringHospital() );
// Name
valueObject.setName(domainObject.getName());
// isActive
valueObject.setIsActive( domainObject.isIsActive() );
// IsVirtual
valueObject.setIsVirtual( domainObject.isIsVirtual() );
// Type
ims.domain.lookups.LookupInstance instance18 = domainObject.getType();
if ( null != instance18 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance18.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance18.getImage().getImageId(), instance18.getImage().getImagePath());
}
color = instance18.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.LocationType voLookup18 = new ims.core.vo.lookups.LocationType(instance18.getId(),instance18.getText(), instance18.isActive(), null, img, color);
ims.core.vo.lookups.LocationType parentVoLookup18 = voLookup18;
ims.domain.lookups.LookupInstance parent18 = instance18.getParent();
while (parent18 != null)
{
if (parent18.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent18.getImage().getImageId(), parent18.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent18.getColor();
if (color != null)
color.getValue();
parentVoLookup18.setParent(new ims.core.vo.lookups.LocationType(parent18.getId(),parent18.getText(), parent18.isActive(), null, img, color));
parentVoLookup18 = parentVoLookup18.getParent();
parent18 = parent18.getParent();
}
valueObject.setType(voLookup18);
}
// DisplayInEDTracking
valueObject.setDisplayInEDTracking( domainObject.isDisplayInEDTracking() );
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.core.resource.place.domain.objects.LocSite extractLocSite(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.LocSiteFullVo valueObject)
{
return extractLocSite(domainFactory, valueObject, new HashMap());
}
public static ims.core.resource.place.domain.objects.LocSite extractLocSite(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.LocSiteFullVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_Location();
ims.core.resource.place.domain.objects.LocSite domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.core.resource.place.domain.objects.LocSite)domMap.get(valueObject);
}
// ims.core.vo.LocSiteFullVo ID_LocSite field is unknown
domainObject = new ims.core.resource.place.domain.objects.LocSite();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_Location());
if (domMap.get(key) != null)
{
return (ims.core.resource.place.domain.objects.LocSite)domMap.get(key);
}
domainObject = (ims.core.resource.place.domain.objects.LocSite) domainFactory.getDomainObject(ims.core.resource.place.domain.objects.LocSite.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_Location());
domainObject.setParentOrganisation(ims.core.vo.domain.OrganisationVoAssembler.extractOrganisation(domainFactory, valueObject.getParentOrganisation(), domMap));
domainObject.setServices(ims.core.vo.domain.LocationServiceVoAssembler.extractLocationServiceSet(domainFactory, valueObject.getServices(), domainObject.getServices(), domMap));
domainObject.setActivityLimitGroup(ims.core.vo.domain.ActivityGroupLimitsVoAssembler.extractActivityLimitGroupSet(domainFactory, valueObject.getActivityLimitGroup(), domainObject.getActivityLimitGroup(), domMap));
domainObject.setLocations(ims.core.vo.domain.LocMostVoAssembler.extractLocationSet(domainFactory, valueObject.getLocations(), domainObject.getLocations(), domMap));
domainObject.setParentLocation(ims.core.vo.domain.LocMostVoAssembler.extractLocation(domainFactory, valueObject.getParentLocation(), domMap));
domainObject.setPrinters(ims.admin.vo.domain.PrinterVoAssembler.extractPrinterList(domainFactory, valueObject.getPrinters(), domainObject.getPrinters(), domMap));
domainObject.setDefaultPrinter(ims.admin.vo.domain.PrinterVoAssembler.extractPrinter(domainFactory, valueObject.getDefaultPrinter(), domMap));
domainObject.setDesignatedPrinterForNewResults(ims.admin.vo.domain.PrinterVoAssembler.extractPrinter(domainFactory, valueObject.getDesignatedPrinterForNewResults(), domMap));
domainObject.setDesignatedPrinterForOCSOrder(ims.admin.vo.domain.PrinterVoAssembler.extractPrinter(domainFactory, valueObject.getDesignatedPrinterForOCSOrder(), domMap));
domainObject.setCodeMappings(ims.core.vo.domain.TaxonomyMapAssembler.extractTaxonomyMapList(domainFactory, valueObject.getCodeMappings(), domainObject.getCodeMappings(), domMap));
domainObject.setAddress(ims.core.vo.domain.PersonAddressAssembler.extractAddress(domainFactory, valueObject.getAddress(), domMap));
domainObject.setSecureAccommodation(valueObject.getSecureAccommodation());
domainObject.setTreatingHosp(valueObject.getTreatingHosp());
domainObject.setReferringHospital(valueObject.getReferringHospital());
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getName() != null && valueObject.getName().equals(""))
{
valueObject.setName(null);
}
domainObject.setName(valueObject.getName());
domainObject.setIsActive(valueObject.getIsActive());
domainObject.setIsVirtual(valueObject.getIsVirtual());
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value18 = null;
if ( null != valueObject.getType() )
{
value18 =
domainFactory.getLookupInstance(valueObject.getType().getID());
}
domainObject.setType(value18);
domainObject.setDisplayInEDTracking(valueObject.getDisplayInEDTracking());
return domainObject;
}
}
| agpl-3.0 |
zh/statusnet | plugins/Bookmark/importbookmarks.php | 2631 | <?php
/**
* StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2010 StatusNet, Inc.
*
* Import a bookmarks file as notices
*
* PHP version 5
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category Bookmark
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
* @copyright 2010 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
* @link http://status.net/
*/
define('INSTALLDIR', realpath(dirname(__FILE__) . '/../..'));
$shortoptions = 'i:n:f:';
$longoptions = array('id=', 'nickname=', 'file=');
$helptext = <<<END_OF_IMPORTBOOKMARKS_HELP
importbookmarks.php [options]
Restore a backed-up Delicious.com bookmark file
-i --id ID of user to import bookmarks for
-n --nickname nickname of the user to import for
-f --file file to read from (STDIN by default)
END_OF_IMPORTBOOKMARKS_HELP;
require_once INSTALLDIR.'/scripts/commandline.inc';
/**
* Get the bookmarks file as a string
*
* Uses the -f or --file parameter to open and read a
* a bookmarks file
*
* @return string Contents of the file
*/
function getBookmarksFile()
{
$filename = get_option_value('f', 'file');
if (empty($filename)) {
show_help();
exit(1);
}
if (!file_exists($filename)) {
throw new Exception("No such file '$filename'.");
}
if (!is_file($filename)) {
throw new Exception("Not a regular file: '$filename'.");
}
if (!is_readable($filename)) {
throw new Exception("File '$filename' not readable.");
}
// TRANS: %s is the filename that contains a backup for a user.
printfv(_("Getting backup from file '%s'.")."\n", $filename);
$html = file_get_contents($filename);
return $html;
}
try {
$user = getUser();
$html = getBookmarksFile();
$qm = QueueManager::get();
$qm->enqueue(array($user, $html), 'dlcsback');
} catch (Exception $e) {
print $e->getMessage()."\n";
exit(1);
}
| agpl-3.0 |
FaizaGara/lima | lima_common/src/common/MediaProcessors/MediaProcessUnitPipeline.cpp | 994 | /*
Copyright 2002-2013 CEA LIST
This file is part of LIMA.
LIMA is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
LIMA 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with LIMA. If not, see <http://www.gnu.org/licenses/>
*/
#include "MediaProcessUnitPipeline.h"
#include "common/AbstractFactoryPattern/SimpleFactory.h"
namespace Lima {
namespace ObjetProcessing {
SimpleFactory<MediaProcessUnit,MediaProcessUnitPipeline> pipelineFactory("ProcessUnitPipeline");
} // ObjetProcessing
} // Lima
| agpl-3.0 |
salesagility-davidthomson/SuiteCRM | soap/SoapError.php | 3815 | <?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
* SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
* Copyright (C) 2011 - 2014 Salesagility Ltd.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
********************************************************************************/
require_once('soap/SoapErrorDefinitions.php');
class SoapError{
var $name;
var $number;
var $description;
function __construct(){
$this->set_error('no_error');
}
/**
* @deprecated deprecated since version 7.6, PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code, use __construct instead
*/
function SoapError(){
$deprecatedMessage = 'PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code';
if(isset($GLOBALS['log'])) {
$GLOBALS['log']->deprecated($deprecatedMessage);
}
else {
trigger_error($deprecatedMessage, E_USER_DEPRECATED);
}
self::__construct();
}
function set_error($error_name){
global $error_defs;
if(!isset($error_defs[$error_name])){
$this->name = 'An Undefined Error - ' . $error_name . ' occurred';
$this->number = '-1';
$this->description = 'There is no error definition for ' . $error_name;
}else{
$this->name = $error_defs[$error_name]['name'];
$this->number = $error_defs[$error_name]['number'];
$this->description = $error_defs[$error_name]['description'];
}
}
function get_soap_array(){
return Array('number'=>$this->number,
'name'=>$this->name,
'description'=>$this->description);
}
function getName() {
return $this->name;
} // fn
function getFaultCode() {
return $this->number;
} // fn
function getDescription() {
return $this->description;
} // fn
}
| agpl-3.0 |
PopulateTools/gobierto-dev | config/webpack/config/splitChunks.js | 141 | module.exports = {
optimization: {
runtimeChunk: false,
splitChunks: {
chunks: chunk => chunk.name !== "embeds"
}
}
};
| agpl-3.0 |
afishbeck/HPCC-Platform | system/security/test/author/StdAfx.cpp | 1099 | /*##############################################################################
Copyright (C) 2011 HPCC Systems.
All rights reserved. This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
############################################################################## */
// stdafx.cpp : source file that includes just the standard includes
// author.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| agpl-3.0 |
mbauskar/internal-hr | erpnext/accounts/doctype/sales_invoice/sales_invoice.py | 28480 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import frappe.defaults
from frappe.utils import add_days, cint, cstr, date_diff, flt, getdate, nowdate, \
get_first_day, get_last_day
from frappe.model.naming import make_autoname
from frappe import _, msgprint, throw
from erpnext.accounts.party import get_party_account, get_due_date
from erpnext.controllers.stock_controller import update_gl_entries_after
from frappe.model.mapper import get_mapped_doc
month_map = {'Monthly': 1, 'Quarterly': 3, 'Half-yearly': 6, 'Yearly': 12}
from erpnext.controllers.selling_controller import SellingController
class SalesInvoice(SellingController):
tname = 'Sales Invoice Item'
fname = 'entries'
def __init__(self, arg1, arg2=None):
super(SalesInvoice, self).__init__(arg1, arg2)
self.status_updater = [{
'source_dt': 'Sales Invoice Item',
'target_field': 'billed_amt',
'target_ref_field': 'amount',
'target_dt': 'Sales Order Item',
'join_field': 'so_detail',
'target_parent_dt': 'Sales Order',
'target_parent_field': 'per_billed',
'source_field': 'amount',
'join_field': 'so_detail',
'percent_join_field': 'sales_order',
'status_field': 'billing_status',
'keyword': 'Billed'
}]
def validate(self):
super(SalesInvoice, self).validate()
self.validate_posting_time()
self.so_dn_required()
self.validate_proj_cust()
self.validate_with_previous_doc()
self.validate_uom_is_integer("stock_uom", "qty")
self.check_stop_sales_order("sales_order")
self.validate_customer_account()
self.validate_debit_acc()
self.validate_fixed_asset_account()
self.clear_unallocated_advances("Sales Invoice Advance", "advance_adjustment_details")
self.add_remarks()
if cint(self.is_pos):
self.validate_pos()
self.validate_write_off_account()
if cint(self.update_stock):
self.validate_item_code()
self.update_current_stock()
self.validate_delivery_note()
if not self.is_opening:
self.is_opening = 'No'
self.set_aging_date()
frappe.get_doc("Account", self.debit_to).validate_due_date(self.posting_date, self.due_date)
self.set_against_income_account()
self.validate_c_form()
self.validate_time_logs_are_submitted()
self.validate_recurring_invoice()
self.validate_multiple_billing("Delivery Note", "dn_detail", "amount",
"delivery_note_details")
def on_submit(self):
if cint(self.update_stock) == 1:
self.update_stock_ledger()
else:
# Check for Approving Authority
if not self.recurring_id:
frappe.get_doc('Authorization Control').validate_approving_authority(self.doctype,
self.company, self.grand_total, self)
self.check_prev_docstatus()
self.update_status_updater_args()
self.update_prevdoc_status()
self.update_billing_status_for_zero_amount_refdoc("Sales Order")
# this sequence because outstanding may get -ve
self.make_gl_entries()
self.check_credit_limit(self.debit_to)
if not cint(self.is_pos) == 1:
self.update_against_document_in_jv()
self.update_c_form()
self.update_time_log_batch(self.name)
self.convert_to_recurring()
def before_cancel(self):
self.update_time_log_batch(None)
def on_cancel(self):
if cint(self.update_stock) == 1:
self.update_stock_ledger()
self.check_stop_sales_order("sales_order")
from erpnext.accounts.utils import remove_against_link_from_jv
remove_against_link_from_jv(self.doctype, self.name, "against_invoice")
self.update_status_updater_args()
self.update_prevdoc_status()
self.update_billing_status_for_zero_amount_refdoc("Sales Order")
self.make_cancel_gl_entries()
def update_status_updater_args(self):
if cint(self.update_stock):
self.status_updater.append({
'source_dt':'Sales Invoice Item',
'target_dt':'Sales Order Item',
'target_parent_dt':'Sales Order',
'target_parent_field':'per_delivered',
'target_field':'delivered_qty',
'target_ref_field':'qty',
'source_field':'qty',
'join_field':'so_detail',
'percent_join_field':'sales_order',
'status_field':'delivery_status',
'keyword':'Delivered',
'second_source_dt': 'Delivery Note Item',
'second_source_field': 'qty',
'second_join_field': 'prevdoc_detail_docname'
})
def on_update_after_submit(self):
self.validate_recurring_invoice()
self.convert_to_recurring()
def get_portal_page(self):
return "invoice" if self.docstatus==1 else None
def set_missing_values(self, for_validate=False):
self.set_pos_fields(for_validate)
if not self.debit_to:
self.debit_to = get_party_account(self.company, self.customer, "Customer")
if not self.due_date:
self.due_date = get_due_date(self.posting_date, self.customer, "Customer",
self.debit_to, self.company)
super(SalesInvoice, self).set_missing_values(for_validate)
def update_time_log_batch(self, sales_invoice):
for d in self.get(self.fname):
if d.time_log_batch:
tlb = frappe.get_doc("Time Log Batch", d.time_log_batch)
tlb.sales_invoice = sales_invoice
tlb.ignore_validate_update_after_submit = True
tlb.save()
def validate_time_logs_are_submitted(self):
for d in self.get(self.fname):
if d.time_log_batch:
status = frappe.db.get_value("Time Log Batch", d.time_log_batch, "status")
if status!="Submitted":
frappe.throw(_("Time Log Batch {0} must be 'Submitted'").format(d.time_log_batch))
def set_pos_fields(self, for_validate=False):
"""Set retail related fields from pos settings"""
if cint(self.is_pos) != 1:
return
from erpnext.stock.get_item_details import get_pos_settings_item_details, get_pos_settings
pos = get_pos_settings(self.company)
if pos:
if not for_validate and not self.customer:
self.customer = pos.customer
# self.set_customer_defaults()
for fieldname in ('territory', 'naming_series', 'currency', 'taxes_and_charges', 'letter_head', 'tc_name',
'selling_price_list', 'company', 'select_print_heading', 'cash_bank_account'):
if (not for_validate) or (for_validate and not self.get(fieldname)):
self.set(fieldname, pos.get(fieldname))
if not for_validate:
self.update_stock = cint(pos.get("update_stock"))
# set pos values in items
for item in self.get("entries"):
if item.get('item_code'):
for fname, val in get_pos_settings_item_details(pos,
frappe._dict(item.as_dict()), pos).items():
if (not for_validate) or (for_validate and not item.get(fname)):
item.set(fname, val)
# fetch terms
if self.tc_name and not self.terms:
self.terms = frappe.db.get_value("Terms and Conditions", self.tc_name, "terms")
# fetch charges
if self.taxes_and_charges and not len(self.get("other_charges")):
self.set_taxes("other_charges", "taxes_and_charges")
def get_advances(self):
super(SalesInvoice, self).get_advances(self.debit_to,
"Sales Invoice Advance", "advance_adjustment_details", "credit")
def get_company_abbr(self):
return frappe.db.sql("select abbr from tabCompany where name=%s", self.company)[0][0]
def update_against_document_in_jv(self):
"""
Links invoice and advance voucher:
1. cancel advance voucher
2. split into multiple rows if partially adjusted, assign against voucher
3. submit advance voucher
"""
lst = []
for d in self.get('advance_adjustment_details'):
if flt(d.allocated_amount) > 0:
args = {
'voucher_no' : d.journal_voucher,
'voucher_detail_no' : d.jv_detail_no,
'against_voucher_type' : 'Sales Invoice',
'against_voucher' : self.name,
'account' : self.debit_to,
'is_advance' : 'Yes',
'dr_or_cr' : 'credit',
'unadjusted_amt' : flt(d.advance_amount),
'allocated_amt' : flt(d.allocated_amount)
}
lst.append(args)
if lst:
from erpnext.accounts.utils import reconcile_against_document
reconcile_against_document(lst)
def validate_customer_account(self):
"""Validates Debit To Account and Customer Matches"""
if self.customer and self.debit_to and not cint(self.is_pos):
acc_head = frappe.db.sql("select master_name from `tabAccount` where name = %s and docstatus != 2", self.debit_to)
if (acc_head and cstr(acc_head[0][0]) != cstr(self.customer)) or \
(not acc_head and (self.debit_to != cstr(self.customer) + " - " + self.get_company_abbr())):
msgprint("Debit To: %s do not match with Customer: %s for Company: %s.\n If both correctly entered, please select Master Type \
and Master Name in account master." %(self.debit_to, self.customer,self.company), raise_exception=1)
def validate_debit_acc(self):
if frappe.db.get_value("Account", self.debit_to, "report_type") != "Balance Sheet":
frappe.throw(_("Account must be a balance sheet account"))
def validate_fixed_asset_account(self):
"""Validate Fixed Asset and whether Income Account Entered Exists"""
for d in self.get('entries'):
item = frappe.db.sql("""select name,is_asset_item,is_sales_item from `tabItem`
where name = %s and (ifnull(end_of_life,'')='' or end_of_life > now())""", d.item_code)
acc = frappe.db.sql("""select account_type from `tabAccount`
where name = %s and docstatus != 2""", d.income_account)
if item and item[0][1] == 'Yes' and not acc[0][0] == 'Fixed Asset':
msgprint(_("Account {0} must be of type 'Fixed Asset' as Item {1} is an Asset Item").format(d.item_code), raise_exception=True)
def validate_with_previous_doc(self):
super(SalesInvoice, self).validate_with_previous_doc(self.tname, {
"Sales Order": {
"ref_dn_field": "sales_order",
"compare_fields": [["customer", "="], ["company", "="], ["project_name", "="],
["currency", "="]],
},
"Delivery Note": {
"ref_dn_field": "delivery_note",
"compare_fields": [["customer", "="], ["company", "="], ["project_name", "="],
["currency", "="]],
},
})
if cint(frappe.defaults.get_global_default('maintain_same_sales_rate')):
super(SalesInvoice, self).validate_with_previous_doc(self.tname, {
"Sales Order Item": {
"ref_dn_field": "so_detail",
"compare_fields": [["rate", "="]],
"is_child_table": True,
"allow_duplicate_prev_row_id": True
},
"Delivery Note Item": {
"ref_dn_field": "dn_detail",
"compare_fields": [["rate", "="]],
"is_child_table": True
}
})
def set_aging_date(self):
if self.is_opening != 'Yes':
self.aging_date = self.posting_date
elif not self.aging_date:
throw(_("Ageing Date is mandatory for opening entry"))
def set_against_income_account(self):
"""Set against account for debit to account"""
against_acc = []
for d in self.get('entries'):
if d.income_account not in against_acc:
against_acc.append(d.income_account)
self.against_income_account = ','.join(against_acc)
def add_remarks(self):
if not self.remarks: self.remarks = 'No Remarks'
def so_dn_required(self):
"""check in manage account if sales order / delivery note required or not."""
dic = {'Sales Order':'so_required','Delivery Note':'dn_required'}
for i in dic:
if frappe.db.get_value('Selling Settings', None, dic[i]) == 'Yes':
for d in self.get('entries'):
if frappe.db.get_value('Item', d.item_code, 'is_stock_item') == 'Yes' \
and not d.get(i.lower().replace(' ','_')):
msgprint(_("{0} is mandatory for Item {1}").format(i,d.item_code), raise_exception=1)
def validate_proj_cust(self):
"""check for does customer belong to same project as entered.."""
if self.project_name and self.customer:
res = frappe.db.sql("""select name from `tabProject`
where name = %s and (customer = %s or
ifnull(customer,'')='')""", (self.project_name, self.customer))
if not res:
throw(_("Customer {0} does not belong to project {1}").format(self.customer,self.project_name))
def validate_pos(self):
if not self.cash_bank_account and flt(self.paid_amount):
msgprint(_("Cash or Bank Account is mandatory for making payment entry"))
raise Exception
if flt(self.paid_amount) + flt(self.write_off_amount) \
- flt(self.grand_total) > 1/(10**(self.precision("grand_total") + 1)):
frappe.throw(_("""Paid amount + Write Off Amount can not be greater than Grand Total"""))
def validate_item_code(self):
for d in self.get('entries'):
if not d.item_code:
msgprint(_("Item Code required at Row No {0}").format(d.idx), raise_exception=True)
def validate_delivery_note(self):
for d in self.get("entries"):
if d.delivery_note:
msgprint(_("Stock cannot be updated against Delivery Note {0}").format(d.delivery_note), raise_exception=1)
def validate_write_off_account(self):
if flt(self.write_off_amount) and not self.write_off_account:
msgprint(_("Please enter Write Off Account"), raise_exception=1)
def validate_c_form(self):
""" Blank C-form no if C-form applicable marked as 'No'"""
if self.amended_from and self.c_form_applicable == 'No' and self.c_form_no:
frappe.db.sql("""delete from `tabC-Form Invoice Detail` where invoice_no = %s
and parent = %s""", (self.amended_from, self.c_form_no))
frappe.db.set(self, 'c_form_no', '')
def update_current_stock(self):
for d in self.get('entries'):
if d.item_code and d.warehouse:
bin = frappe.db.sql("select actual_qty from `tabBin` where item_code = %s and warehouse = %s", (d.item_code, d.warehouse), as_dict = 1)
d.actual_qty = bin and flt(bin[0]['actual_qty']) or 0
for d in self.get('packing_details'):
bin = frappe.db.sql("select actual_qty, projected_qty from `tabBin` where item_code = %s and warehouse = %s", (d.item_code, d.warehouse), as_dict = 1)
d.actual_qty = bin and flt(bin[0]['actual_qty']) or 0
d.projected_qty = bin and flt(bin[0]['projected_qty']) or 0
def get_warehouse(self):
w = frappe.db.sql("""select warehouse from `tabPOS Setting`
where ifnull(user,'') = %s and company = %s""",
(frappe.session['user'], self.company))
w = w and w[0][0] or ''
if not w:
ps = frappe.db.sql("""select name, warehouse from `tabPOS Setting`
where ifnull(user,'') = '' and company = %s""", self.company)
if not ps:
msgprint(_("POS Setting required to make POS Entry"), raise_exception=True)
elif not ps[0][1]:
msgprint(_("Warehouse required in POS Setting"))
else:
w = ps[0][1]
return w
def on_update(self):
if cint(self.update_stock) == 1:
# Set default warehouse from pos setting
if cint(self.is_pos) == 1:
w = self.get_warehouse()
if w:
for d in self.get('entries'):
if not d.warehouse:
d.warehouse = cstr(w)
from erpnext.stock.doctype.packed_item.packed_item import make_packing_list
make_packing_list(self, 'entries')
else:
self.set('packing_details', [])
if cint(self.is_pos) == 1:
if flt(self.paid_amount) == 0:
if self.cash_bank_account:
frappe.db.set(self, 'paid_amount',
(flt(self.grand_total) - flt(self.write_off_amount)))
else:
# show message that the amount is not paid
frappe.db.set(self,'paid_amount',0)
frappe.msgprint(_("Note: Payment Entry will not be created since 'Cash or Bank Account' was not specified"))
else:
frappe.db.set(self,'paid_amount',0)
def check_prev_docstatus(self):
for d in self.get('entries'):
if d.sales_order:
submitted = frappe.db.sql("""select name from `tabSales Order`
where docstatus = 1 and name = %s""", d.sales_order)
if not submitted:
msgprint(_("Sales Order {0} is not submitted").format(d.sales_order))
raise Exception
if d.delivery_note:
submitted = frappe.db.sql("""select name from `tabDelivery Note`
where docstatus = 1 and name = %s""", d.delivery_note)
if not submitted:
throw(_("Delivery Note {0} is not submitted").format(d.delivery_note))
def update_stock_ledger(self):
sl_entries = []
for d in self.get_item_list():
if frappe.db.get_value("Item", d.item_code, "is_stock_item") == "Yes" \
and d.warehouse:
sl_entries.append(self.get_sl_entries(d, {
"actual_qty": -1*flt(d.qty),
"stock_uom": frappe.db.get_value("Item", d.item_code, "stock_uom")
}))
self.make_sl_entries(sl_entries)
def make_gl_entries(self, repost_future_gle=True):
gl_entries = self.get_gl_entries()
if gl_entries:
from erpnext.accounts.general_ledger import make_gl_entries
update_outstanding = cint(self.is_pos) and self.write_off_account \
and 'No' or 'Yes'
make_gl_entries(gl_entries, cancel=(self.docstatus == 2),
update_outstanding=update_outstanding, merge_entries=False)
if update_outstanding == "No":
from erpnext.accounts.doctype.gl_entry.gl_entry import update_outstanding_amt
update_outstanding_amt(self.debit_to, self.doctype, self.name)
if repost_future_gle and cint(self.update_stock) \
and cint(frappe.defaults.get_global_default("auto_accounting_for_stock")):
items, warehouse_account = self.get_items_and_warehouse_accounts()
update_gl_entries_after(self.posting_date, self.posting_time,
warehouse_account, items)
def get_gl_entries(self, warehouse_account=None):
from erpnext.accounts.general_ledger import merge_similar_entries
gl_entries = []
self.make_customer_gl_entry(gl_entries)
self.make_tax_gl_entries(gl_entries)
self.make_item_gl_entries(gl_entries)
# merge gl entries before adding pos entries
gl_entries = merge_similar_entries(gl_entries)
self.make_pos_gl_entries(gl_entries)
return gl_entries
def make_customer_gl_entry(self, gl_entries):
if self.grand_total:
gl_entries.append(
self.get_gl_dict({
"account": self.debit_to,
"against": self.against_income_account,
"debit": self.grand_total,
"remarks": self.remarks,
"against_voucher": self.name,
"against_voucher_type": self.doctype,
})
)
def make_tax_gl_entries(self, gl_entries):
for tax in self.get("other_charges"):
if flt(tax.tax_amount_after_discount_amount):
gl_entries.append(
self.get_gl_dict({
"account": tax.account_head,
"against": self.debit_to,
"credit": flt(tax.tax_amount_after_discount_amount),
"remarks": self.remarks,
"cost_center": tax.cost_center
})
)
def make_item_gl_entries(self, gl_entries):
# income account gl entries
for item in self.get("entries"):
if flt(item.base_amount):
gl_entries.append(
self.get_gl_dict({
"account": item.income_account,
"against": self.debit_to,
"credit": item.base_amount,
"remarks": self.remarks,
"cost_center": item.cost_center
})
)
# expense account gl entries
if cint(frappe.defaults.get_global_default("auto_accounting_for_stock")) \
and cint(self.update_stock):
gl_entries += super(SalesInvoice, self).get_gl_entries()
def make_pos_gl_entries(self, gl_entries):
if cint(self.is_pos) and self.cash_bank_account and self.paid_amount:
# POS, make payment entries
gl_entries.append(
self.get_gl_dict({
"account": self.debit_to,
"against": self.cash_bank_account,
"credit": self.paid_amount,
"remarks": self.remarks,
"against_voucher": self.name,
"against_voucher_type": self.doctype,
})
)
gl_entries.append(
self.get_gl_dict({
"account": self.cash_bank_account,
"against": self.debit_to,
"debit": self.paid_amount,
"remarks": self.remarks,
})
)
# write off entries, applicable if only pos
if self.write_off_account and self.write_off_amount:
gl_entries.append(
self.get_gl_dict({
"account": self.debit_to,
"against": self.write_off_account,
"credit": self.write_off_amount,
"remarks": self.remarks,
"against_voucher": self.name,
"against_voucher_type": self.doctype,
})
)
gl_entries.append(
self.get_gl_dict({
"account": self.write_off_account,
"against": self.debit_to,
"debit": self.write_off_amount,
"remarks": self.remarks,
"cost_center": self.write_off_cost_center
})
)
def update_c_form(self):
"""Update amended id in C-form"""
if self.c_form_no and self.amended_from:
frappe.db.sql("""update `tabC-Form Invoice Detail` set invoice_no = %s,
invoice_date = %s, territory = %s, net_total = %s,
grand_total = %s where invoice_no = %s and parent = %s""",
(self.name, self.amended_from, self.c_form_no))
def validate_recurring_invoice(self):
if self.convert_into_recurring_invoice:
self.validate_notification_email_id()
if not self.recurring_type:
msgprint(_("Please select {0}").format(self.meta.get_label("recurring_type")),
raise_exception=1)
elif not (self.invoice_period_from_date and \
self.invoice_period_to_date):
throw(_("Invoice Period From and Invoice Period To dates mandatory for recurring invoice"))
def convert_to_recurring(self):
if self.convert_into_recurring_invoice:
if not self.recurring_id:
frappe.db.set(self, "recurring_id",
make_autoname("RECINV/.#####"))
self.set_next_date()
elif self.recurring_id:
frappe.db.sql("""update `tabSales Invoice`
set convert_into_recurring_invoice = 0
where recurring_id = %s""", (self.recurring_id,))
def validate_notification_email_id(self):
if self.notification_email_address:
email_list = filter(None, [cstr(email).strip() for email in
self.notification_email_address.replace("\n", "").split(",")])
from frappe.utils import validate_email_add
for email in email_list:
if not validate_email_add(email):
throw(_("{0} is an invalid email address in 'Notification Email Address'").format(email))
else:
throw(_("'Notification Email Addresses' not specified for recurring invoice"))
def set_next_date(self):
""" Set next date on which auto invoice will be created"""
if not self.repeat_on_day_of_month:
msgprint(_("Please enter 'Repeat on Day of Month' field value"), raise_exception=1)
next_date = get_next_date(self.posting_date,
month_map[self.recurring_type], cint(self.repeat_on_day_of_month))
frappe.db.set(self, 'next_date', next_date)
def get_next_date(dt, mcount, day=None):
dt = getdate(dt)
from dateutil.relativedelta import relativedelta
dt += relativedelta(months=mcount, day=day)
return dt
def manage_recurring_invoices(next_date=None, commit=True):
"""
Create recurring invoices on specific date by copying the original one
and notify the concerned people
"""
next_date = next_date or nowdate()
recurring_invoices = frappe.db.sql("""select name, recurring_id
from `tabSales Invoice` where ifnull(convert_into_recurring_invoice, 0)=1
and docstatus=1 and next_date=%s
and next_date <= ifnull(end_date, '2199-12-31')""", next_date)
exception_list = []
for ref_invoice, recurring_id in recurring_invoices:
if not frappe.db.sql("""select name from `tabSales Invoice`
where posting_date=%s and recurring_id=%s and docstatus=1""",
(next_date, recurring_id)):
try:
ref_wrapper = frappe.get_doc('Sales Invoice', ref_invoice)
new_invoice_wrapper = make_new_invoice(ref_wrapper, next_date)
send_notification(new_invoice_wrapper)
if commit:
frappe.db.commit()
except:
if commit:
frappe.db.rollback()
frappe.db.begin()
frappe.db.sql("update `tabSales Invoice` set \
convert_into_recurring_invoice = 0 where name = %s", ref_invoice)
notify_errors(ref_invoice, ref_wrapper.customer, ref_wrapper.owner)
frappe.db.commit()
exception_list.append(frappe.get_traceback())
finally:
if commit:
frappe.db.begin()
if exception_list:
exception_message = "\n\n".join([cstr(d) for d in exception_list])
raise Exception, exception_message
def make_new_invoice(ref_wrapper, posting_date):
from erpnext.accounts.utils import get_fiscal_year
new_invoice = frappe.copy_doc(ref_wrapper)
mcount = month_map[ref_wrapper.recurring_type]
invoice_period_from_date = get_next_date(ref_wrapper.invoice_period_from_date, mcount)
# get last day of the month to maintain period if the from date is first day of its own month
# and to date is the last day of its own month
if (cstr(get_first_day(ref_wrapper.invoice_period_from_date)) == \
cstr(ref_wrapper.invoice_period_from_date)) and \
(cstr(get_last_day(ref_wrapper.invoice_period_to_date)) == \
cstr(ref_wrapper.invoice_period_to_date)):
invoice_period_to_date = get_last_day(get_next_date(ref_wrapper.invoice_period_to_date,
mcount))
else:
invoice_period_to_date = get_next_date(ref_wrapper.invoice_period_to_date, mcount)
new_invoice.update({
"posting_date": posting_date,
"aging_date": posting_date,
"due_date": add_days(posting_date, cint(date_diff(ref_wrapper.due_date,
ref_wrapper.posting_date))),
"invoice_period_from_date": invoice_period_from_date,
"invoice_period_to_date": invoice_period_to_date,
"fiscal_year": get_fiscal_year(posting_date)[0],
"owner": ref_wrapper.owner,
})
new_invoice.submit()
return new_invoice
def send_notification(new_rv):
"""Notify concerned persons about recurring invoice generation"""
from frappe.core.doctype.print_format.print_format import get_html
frappe.sendmail(new_rv.notification_email_address,
subject="New Invoice : " + new_rv.name,
message = get_html(new_rv, new_rv, "SalesInvoice"))
def notify_errors(inv, customer, owner):
from frappe.utils.user import get_system_managers
recipients=get_system_managers()
frappe.sendmail(recipients + [frappe.db.get_value("User", owner, "email")],
subject="[Urgent] Error while creating recurring invoice for %s" % inv,
message = frappe.get_template("template/emails/recurring_invoice_failed.html").render({
"name": inv,
"customer": customer
}))
assign_task_to_owner(inv, "Recurring Invoice Failed", recipients)
def assign_task_to_owner(inv, msg, users):
for d in users:
from frappe.widgets.form import assign_to
args = {
'assign_to' : d,
'doctype' : 'Sales Invoice',
'name' : inv,
'description' : msg,
'priority' : 'Urgent'
}
assign_to.add(args)
@frappe.whitelist()
def get_bank_cash_account(mode_of_payment):
val = frappe.db.get_value("Mode of Payment", mode_of_payment, "default_account")
if not val:
frappe.msgprint(_("Please set default Cash or Bank account in Mode of Payment {0}").format(mode_of_payment))
return {
"cash_bank_account": val
}
@frappe.whitelist()
def get_income_account(doctype, txt, searchfield, start, page_len, filters):
from erpnext.controllers.queries import get_match_cond
# income account can be any Credit account,
# but can also be a Asset account with account_type='Income Account' in special circumstances.
# Hence the first condition is an "OR"
return frappe.db.sql("""select tabAccount.name from `tabAccount`
where (tabAccount.report_type = "Profit and Loss"
or tabAccount.account_type = "Income Account")
and tabAccount.group_or_ledger="Ledger"
and tabAccount.docstatus!=2
and ifnull(tabAccount.master_type, "")=""
and ifnull(tabAccount.master_name, "")=""
and tabAccount.company = '%(company)s'
and tabAccount.%(key)s LIKE '%(txt)s'
%(mcond)s""" % {'company': filters['company'], 'key': searchfield,
'txt': "%%%s%%" % txt, 'mcond':get_match_cond(doctype)})
@frappe.whitelist()
def make_delivery_note(source_name, target_doc=None):
def set_missing_values(source, target):
target.run_method("set_missing_values")
target.run_method("calculate_taxes_and_totals")
def update_item(source_doc, target_doc, source_parent):
target_doc.base_amount = (flt(source_doc.qty) - flt(source_doc.delivered_qty)) * \
flt(source_doc.base_rate)
target_doc.amount = (flt(source_doc.qty) - flt(source_doc.delivered_qty)) * \
flt(source_doc.rate)
target_doc.qty = flt(source_doc.qty) - flt(source_doc.delivered_qty)
doclist = get_mapped_doc("Sales Invoice", source_name, {
"Sales Invoice": {
"doctype": "Delivery Note",
"validation": {
"docstatus": ["=", 1]
}
},
"Sales Invoice Item": {
"doctype": "Delivery Note Item",
"field_map": {
"name": "prevdoc_detail_docname",
"parent": "against_sales_invoice",
"serial_no": "serial_no"
},
"postprocess": update_item
},
"Sales Taxes and Charges": {
"doctype": "Sales Taxes and Charges",
"add_if_empty": True
},
"Sales Team": {
"doctype": "Sales Team",
"field_map": {
"incentives": "incentives"
},
"add_if_empty": True
}
}, target_doc, set_missing_values)
return doclist
| agpl-3.0 |
veda-consulting/uk.co.vedaconsulting.mosaico | ang/crmMosaico/AdvancedDialogCtrl.js | 458 | (function(angular, $, _) {
// Controller for editing mail-content with Mosaico in a popup dialog
// Scope members:
// - [input] "model": Object
// - "mailing": Object, CiviMail mailing
// - "attachments": Object, CrmAttachment
angular.module('crmMosaico').controller('CrmMosaicoAdvancedDialogCtrl', function CrmMosaicoAdvancedDialogCtrl($scope, dialogService) {
var ts = $scope.ts = CRM.ts(null);
});
})(angular, CRM.$, CRM._);
| agpl-3.0 |
mohierf/fusioninventory-for-glpi | scripts/logging.php | 2483 | <?php
/**
* Logging facility
*/
ini_set("log_errors", true);
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
set_error_handler(null);
include_once(__DIR__ . "/../../../inc/toolbox.class.php");
class Logging {
public static $LOG_CRITICAL = ['level'=>50, 'name'=>'CRITICAL '];
public static $LOG_ERROR = ['level'=>40, 'name'=>'ERROR '];
public static $LOG_QUIET = ['level'=>35, 'name'=>'QUIET '];
public static $LOG_WARNING = ['level'=>30, 'name'=>'WARNING '];
public static $LOG_INFO = ['level'=>20, 'name'=>'INFO '];
public static $LOG_DEBUG = ['level'=>10, 'name'=>'DEBUG '];
public $loglevel;
public function __construct($loglevel = null) {
if (is_null($loglevel)) {
$this->loglevel = self::$LOG_INFO;
} else {
$this->loglevel = $loglevel;
}
}
public function formatlog($messages, $loglevel) {
$msg = [];
foreach ($messages as $message) {
if (is_array($message) || is_object($message)) {
//$msg[] = print_r($message, true);
$msg[] = PluginFusioninventoryToolbox::formatJson(json_encode($message));
} else if (is_null($message)) {
$msg[] = ' NULL';
} else if (is_bool($message)) {
$msg[] = ($message ? 'true' : 'false');
} else {
$msg[] = $message;
}
}
return $loglevel['name'] . ': '. implode("\n", $msg);
}
function printlog($msg = "", $loglevel = null) {
if (is_null($loglevel)) {
$loglevel = self::$LOG_INFO;
}
/*
print(
var_export($this->loglevel['level'],true) . " >= " .
var_export($loglevel['level'],true) . "\n"
);
*/
if ($this->loglevel['level'] <= $loglevel['level']) {
print( $this->formatlog($msg, $loglevel) . PHP_EOL );
}
}
function info() {
$msg = func_get_args();
$this->printlog($msg, self::$LOG_INFO);
}
function error() {
$msg = func_get_args();
$this->printlog($msg, self::$LOG_ERROR);
}
function debug() {
$msg = func_get_args();
$this->printlog($msg, self::$LOG_DEBUG);
}
function setLevelFromArgs($quiet = false, $debug = false) {
$this->loglevel = self::$LOG_INFO;
if ($quiet) {
$this->loglevel = self::$LOG_QUIET;
} else if ($debug) {
$this->loglevel = self::$LOG_DEBUG;
}
}
}
| agpl-3.0 |
ESOedX/edx-platform | common/lib/safe_lxml/safe_lxml/tests.py | 624 | """Test that we have defused XML."""
from __future__ import absolute_import
import defusedxml
from lxml import etree
import pytest
@pytest.mark.parametrize("attr", ["XML", "fromstring", "parse"])
def test_etree_is_defused(attr):
func = getattr(etree, attr)
assert "defused" in func.__code__.co_filename
def test_entities_arent_resolved():
# Make sure we have disabled entity resolution.
xml = '<?xml version="1.0"?><!DOCTYPE mydoc [<!ENTITY hi "Hello">]> <root>&hi;</root>'
parser = etree.XMLParser()
with pytest.raises(defusedxml.EntitiesForbidden):
_ = etree.XML(xml, parser=parser)
| agpl-3.0 |
yonghyun-cho/QueryParser | QueryParser/src/queryParser/parser/PasingTest.java | 4436 | ๏ปฟpackage queryParser.parser;
import java.util.ArrayList;
import java.util.List;
/*
*
SELECT EMP.ENAME, EMP.SAL, DEPT.DNAME, (SELECT EMP.SAL FROM EMP WHERE EMPNO = 7839) FROM EMP, (SELECT DEPT.DNAME, DEPT.DEPTNO, DEPT.LOC FROM DEPT WHERE DEPTNO.SIZE > 100) DEPT WHERE EMP.DEPTNO = DEPT.DEPTNO AND DEPT.LOC = 'CHICAGO'
===========================
SELECT SUM(EMP.SAL)FROM EMP,DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO AND(EMP.COMM>50 OR EMP.SAL>1000)AND(EMP.SAL>800)
===========================
SELECT EMP.ENAME, EMP.SAL, DEPT.DNAME FROM EMP, (SELECT DEPT.DNAME, DEPT.DEPTNO, DEPT.LOC FROM DEPT WHERE DEPTNO.SIZE > 100) DEPT WHERE EMP.DEPTNO = DEPT.DEPTNO OR (EMP.LOC = DEPT.LOC AND EMP.COLA = DEPT.COLA) OR (EMP.COLB = DEPT.COLB AND (EMP.COLC = 'TEST' OR EMP.COLC = 'DOING'))
*/
public class PasingTest {
public static void main(String[] args) throws Exception {
// convertFunctionName();
//
// VisualQueryInfo visualQueryInfo = new VisualQueryInfo();
//
// // ํ์ผ ์
๋ ฅ ๋ก์ง ๋ณ๊ฒฝ // 2015.02.12. ์กฐ์ฉํ
// QueryParser qp = new QueryParser();
// qp.readQueryTextFile("C:\\testQuery.txt");
// // C:\\Users\\RHYH\\Documents\\testQuery.txt
//
// qp.parsingQueryToVisualQueryInfo();
//
// // Main Query
// QueryInfo mainQueryInfo = qp.getMainQueryInfo();
// visualQueryInfo.setMainQueryInfo(mainQueryInfo);
//
// // Sub Query
// Map<String, QueryInfo> subQueryInfoList = qp.getSubQueryInfoList();
// visualQueryInfo.setSubQueryMap(subQueryInfoList);
//
// visualQueryInfo.printVisualQueryInfo();
///////////////////////////////////////////////////
// statementTest();
///////////////////////////////////////////////////
//
// String simpleQuery = qp.getInputQuery().replace("\r\n", " ").replace("\n", " ");
// simpleQuery = simpleQuery.toUpperCase();
//
// System.out.println(simpleQuery);
//
// System.out.println("===========================");
// SubQueryParser subQueryParser = new SubQueryParser();
// subQueryParser.replaceAllBracket(simpleQuery);
// System.out.println("===========================");
}
// SELECT, FROM, WHERE ๊ตฌ๋ถํ๋ ๋ด์ฉ
// TODO ์๋ฌด๋๋.. "" ๋ () ์ฒ๋ผ ๋์ฒดํ๋ค๊ฐ ๋ค์ ๋ฃ์ด์ผ ํ ๋ฏ ์ถ์....
// "" ์ด๊ฑด ์ ์์ฐ์ด๋ ๋ถ๋ถ.. ์ผ๋จ ""๋ --๊ฐ์ ์ฃผ์์ ๋์ค์ ์ฒ๋ฆฌํ๋๋ก.
public static void statementTest(){
//////// TOBE [[[ FALSE ]]] !!!!
List<String> testSelectList_FALSE = new ArrayList<String>();
testSelectList_FALSE.add("\"SELECT TAB1");
testSelectList_FALSE.add("TOSELECT TAB1");
testSelectList_FALSE.add("TOSELECT SELECTNOT");
testSelectList_FALSE.add("\"THIS IS SELECT TAB1");
testSelectList_FALSE.add("\"ํ
์คํธ์, SELECT TAB2,");
testSelectList_FALSE.add("\"SELECT TAB1");
//////// TOBE [[[ TRUE ]]] !!!!
List<String> testSelectList_TRUE = new ArrayList<String>();
testSelectList_TRUE.add("SELECT TAB1");
testSelectList_TRUE.add(" SELECT TAB2,");
testSelectList_TRUE.add("(SELECT TAB1,");
testSelectList_TRUE.add("( SELECT TAB2,");
testSelectList_TRUE.add("\"ํ
์คํธ์\", SELECT TAB2,");
testSelectList_TRUE.add("\"ํ
์คํธ์\",(SELECT TAB2,");
// ๋ฌธ์๊ฐ ์๊ณ . Object์ด๋ฆ ๊ฐ๋ฅ ๋ฌธ์, "๊ฐ ์ค์ง ์๊ฑฐ๋ ๋๋ ์๋ฌด ๋ฌธ์๊ฐ ์๊ณ "SELECT "์ธ ๊ฒฝ์ฐ
// String regex = "(.*[^a-zA-Z0-9_$#\"]|)SELECT .*";
// ๋ฌธ์๊ฐ ์๊ณ . (, ๊ณต๋ฐฑ ์ด๊ฑฐ๋ ๋๋ ์๋ฌด ๋ฌธ์๊ฐ ์๊ณ "SELECT "์ธ ๊ฒฝ์ฐ
String regex = "(.*(\\(|[\\s]+)|)SELECT .*";
for(String string: testSelectList_FALSE){
if(string.matches(regex)){
System.out.println("[[FALSE]]์ฌ์ผํ๋๋ฐ TRUE์!!");
System.out.println(string);
System.out.println("---------------");
}
}
for(String string: testSelectList_TRUE){
if(string.matches(regex) == false){
System.out.println("[[TRUE]]์ฌ์ผ ํ๋๋ฐ FALSE์!!");
System.out.println(string);
System.out.println("---------------");
}
}
}
public static void convertFunctionName(){
String result = "";
String functionListText = "STATS_T_TEST_ONE STATS_T_TEST_PAIRED STATS_T_TEST_INDEP STATS_T_TEST_INDEPU";
String[] functionArr = functionListText.split("\t");
for(String function: functionArr){
result = result + function.trim() + "(\"" + function.trim() + "\"), ";
}
System.out.println(result);
}
}
| agpl-3.0 |