code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
package system // import "github.com/docker/docker/pkg/system"
import (
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"syscall"
"time"
"unsafe"
winio "github.com/Microsoft/go-winio"
"golang.org/x/sys/windows"
)
const (
// SddlAdministratorsLocalSystem is local administrators plus NT AUTHORITY\System
SddlAdministratorsLocalSystem = "D:P(A;OICI;GA;;;BA)(A;OICI;GA;;;SY)"
)
// MkdirAllWithACL is a wrapper for MkdirAll that creates a directory
// with an appropriate SDDL defined ACL.
func MkdirAllWithACL(path string, perm os.FileMode, sddl string) error {
return mkdirall(path, true, sddl)
}
// MkdirAll implementation that is volume path aware for Windows. It can be used
// as a drop-in replacement for os.MkdirAll()
func MkdirAll(path string, _ os.FileMode) error {
return mkdirall(path, false, "")
}
// mkdirall is a custom version of os.MkdirAll modified for use on Windows
// so that it is both volume path aware, and can create a directory with
// a DACL.
func mkdirall(path string, applyACL bool, sddl string) error {
if re := regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`); re.MatchString(path) {
return nil
}
// The rest of this method is largely copied from os.MkdirAll and should be kept
// as-is to ensure compatibility.
// Fast path: if we can tell whether path is a directory or file, stop with success or error.
dir, err := os.Stat(path)
if err == nil {
if dir.IsDir() {
return nil
}
return &os.PathError{
Op: "mkdir",
Path: path,
Err: syscall.ENOTDIR,
}
}
// Slow path: make sure parent exists and then call Mkdir for path.
i := len(path)
for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator.
i--
}
j := i
for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element.
j--
}
if j > 1 {
// Create parent
err = mkdirall(path[0:j-1], false, sddl)
if err != nil {
return err
}
}
// Parent now exists; invoke os.Mkdir or mkdirWithACL and use its result.
if applyACL {
err = mkdirWithACL(path, sddl)
} else {
err = os.Mkdir(path, 0)
}
if err != nil {
// Handle arguments like "foo/." by
// double-checking that directory doesn't exist.
dir, err1 := os.Lstat(path)
if err1 == nil && dir.IsDir() {
return nil
}
return err
}
return nil
}
// mkdirWithACL creates a new directory. If there is an error, it will be of
// type *PathError. .
//
// This is a modified and combined version of os.Mkdir and windows.Mkdir
// in golang to cater for creating a directory am ACL permitting full
// access, with inheritance, to any subfolder/file for Built-in Administrators
// and Local System.
func mkdirWithACL(name string, sddl string) error {
sa := windows.SecurityAttributes{Length: 0}
sd, err := winio.SddlToSecurityDescriptor(sddl)
if err != nil {
return &os.PathError{Op: "mkdir", Path: name, Err: err}
}
sa.Length = uint32(unsafe.Sizeof(sa))
sa.InheritHandle = 1
sa.SecurityDescriptor = uintptr(unsafe.Pointer(&sd[0]))
namep, err := windows.UTF16PtrFromString(name)
if err != nil {
return &os.PathError{Op: "mkdir", Path: name, Err: err}
}
e := windows.CreateDirectory(namep, &sa)
if e != nil {
return &os.PathError{Op: "mkdir", Path: name, Err: e}
}
return nil
}
// IsAbs is a platform-specific wrapper for filepath.IsAbs. On Windows,
// golang filepath.IsAbs does not consider a path \windows\system32 as absolute
// as it doesn't start with a drive-letter/colon combination. However, in
// docker we need to verify things such as WORKDIR /windows/system32 in
// a Dockerfile (which gets translated to \windows\system32 when being processed
// by the daemon. This SHOULD be treated as absolute from a docker processing
// perspective.
func IsAbs(path string) bool {
if !filepath.IsAbs(path) {
if !strings.HasPrefix(path, string(os.PathSeparator)) {
return false
}
}
return true
}
// The origin of the functions below here are the golang OS and windows packages,
// slightly modified to only cope with files, not directories due to the
// specific use case.
//
// The alteration is to allow a file on Windows to be opened with
// FILE_FLAG_SEQUENTIAL_SCAN (particular for docker load), to avoid eating
// the standby list, particularly when accessing large files such as layer.tar.
// CreateSequential creates the named file with mode 0666 (before umask), truncating
// it if it already exists. If successful, methods on the returned
// File can be used for I/O; the associated file descriptor has mode
// O_RDWR.
// If there is an error, it will be of type *PathError.
func CreateSequential(name string) (*os.File, error) {
return OpenFileSequential(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0)
}
// OpenSequential opens the named file for reading. If successful, methods on
// the returned file can be used for reading; the associated file
// descriptor has mode O_RDONLY.
// If there is an error, it will be of type *PathError.
func OpenSequential(name string) (*os.File, error) {
return OpenFileSequential(name, os.O_RDONLY, 0)
}
// OpenFileSequential is the generalized open call; most users will use Open
// or Create instead.
// If there is an error, it will be of type *PathError.
func OpenFileSequential(name string, flag int, _ os.FileMode) (*os.File, error) {
if name == "" {
return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOENT}
}
r, errf := windowsOpenFileSequential(name, flag, 0)
if errf == nil {
return r, nil
}
return nil, &os.PathError{Op: "open", Path: name, Err: errf}
}
func windowsOpenFileSequential(name string, flag int, _ os.FileMode) (file *os.File, err error) {
r, e := windowsOpenSequential(name, flag|windows.O_CLOEXEC, 0)
if e != nil {
return nil, e
}
return os.NewFile(uintptr(r), name), nil
}
func makeInheritSa() *windows.SecurityAttributes {
var sa windows.SecurityAttributes
sa.Length = uint32(unsafe.Sizeof(sa))
sa.InheritHandle = 1
return &sa
}
func windowsOpenSequential(path string, mode int, _ uint32) (fd windows.Handle, err error) {
if len(path) == 0 {
return windows.InvalidHandle, windows.ERROR_FILE_NOT_FOUND
}
pathp, err := windows.UTF16PtrFromString(path)
if err != nil {
return windows.InvalidHandle, err
}
var access uint32
switch mode & (windows.O_RDONLY | windows.O_WRONLY | windows.O_RDWR) {
case windows.O_RDONLY:
access = windows.GENERIC_READ
case windows.O_WRONLY:
access = windows.GENERIC_WRITE
case windows.O_RDWR:
access = windows.GENERIC_READ | windows.GENERIC_WRITE
}
if mode&windows.O_CREAT != 0 {
access |= windows.GENERIC_WRITE
}
if mode&windows.O_APPEND != 0 {
access &^= windows.GENERIC_WRITE
access |= windows.FILE_APPEND_DATA
}
sharemode := uint32(windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE)
var sa *windows.SecurityAttributes
if mode&windows.O_CLOEXEC == 0 {
sa = makeInheritSa()
}
var createmode uint32
switch {
case mode&(windows.O_CREAT|windows.O_EXCL) == (windows.O_CREAT | windows.O_EXCL):
createmode = windows.CREATE_NEW
case mode&(windows.O_CREAT|windows.O_TRUNC) == (windows.O_CREAT | windows.O_TRUNC):
createmode = windows.CREATE_ALWAYS
case mode&windows.O_CREAT == windows.O_CREAT:
createmode = windows.OPEN_ALWAYS
case mode&windows.O_TRUNC == windows.O_TRUNC:
createmode = windows.TRUNCATE_EXISTING
default:
createmode = windows.OPEN_EXISTING
}
// Use FILE_FLAG_SEQUENTIAL_SCAN rather than FILE_ATTRIBUTE_NORMAL as implemented in golang.
//https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
const fileFlagSequentialScan = 0x08000000 // FILE_FLAG_SEQUENTIAL_SCAN
h, e := windows.CreateFile(pathp, access, sharemode, sa, createmode, fileFlagSequentialScan, 0)
return h, e
}
// Helpers for TempFileSequential
var rand uint32
var randmu sync.Mutex
func reseed() uint32 {
return uint32(time.Now().UnixNano() + int64(os.Getpid()))
}
func nextSuffix() string {
randmu.Lock()
r := rand
if r == 0 {
r = reseed()
}
r = r*1664525 + 1013904223 // constants from Numerical Recipes
rand = r
randmu.Unlock()
return strconv.Itoa(int(1e9 + r%1e9))[1:]
}
// TempFileSequential is a copy of ioutil.TempFile, modified to use sequential
// file access. Below is the original comment from golang:
// TempFile creates a new temporary file in the directory dir
// with a name beginning with prefix, opens the file for reading
// and writing, and returns the resulting *os.File.
// If dir is the empty string, TempFile uses the default directory
// for temporary files (see os.TempDir).
// Multiple programs calling TempFile simultaneously
// will not choose the same file. The caller can use f.Name()
// to find the pathname of the file. It is the caller's responsibility
// to remove the file when no longer needed.
func TempFileSequential(dir, prefix string) (f *os.File, err error) {
if dir == "" {
dir = os.TempDir()
}
nconflict := 0
for i := 0; i < 10000; i++ {
name := filepath.Join(dir, prefix+nextSuffix())
f, err = OpenFileSequential(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
if os.IsExist(err) {
if nconflict++; nconflict > 10 {
randmu.Lock()
rand = reseed()
randmu.Unlock()
}
continue
}
break
}
return
}
| mudler/docker-companion | vendor/github.com/docker/docker/pkg/system/filesys_windows.go | GO | gpl-3.0 | 9,173 |
modules.define(
'spec',
['button', 'i-bem__dom', 'chai', 'jquery', 'BEMHTML'],
function(provide, Button, BEMDOM, chai, $, BEMHTML) {
var expect = chai.expect;
describe('button_type_link', function() {
var button;
beforeEach(function() {
button = buildButton({
block : 'button',
mods : { type : 'link' },
url : '/'
});
});
afterEach(function() {
BEMDOM.destruct(button.domElem);
});
describe('url', function() {
it('should properly gets url', function() {
button.domElem.attr('href').should.be.equal('/');
button.getUrl().should.be.equal('/');
});
it('should properly sets url', function() {
button.setUrl('/bla');
button.domElem.attr('href').should.be.equal('/bla');
button.getUrl().should.be.equal('/bla');
});
});
describe('disabled', function() {
it('should remove "href" attribute if disabled before init', function() {
BEMDOM.destruct(button.domElem); // we need to destruct default button from beforeEach
button = buildButton({
block : 'button',
mods : { type : 'link', disabled : true },
url : '/'
});
button.getUrl().should.be.equal('/');
expect(button.domElem.attr('href')).to.be.undefined;
});
it('should update attributes properly', function() {
button.setMod('disabled');
button.domElem.attr('aria-disabled').should.be.equal('true');
expect(button.domElem.attr('href')).to.be.undefined;
button.delMod('disabled');
button.domElem.attr('href').should.be.equal('/');
expect(button.domElem.attr('aria-disabled')).to.be.undefined;
});
});
function buildButton(bemjson) {
return BEMDOM.init($(BEMHTML.apply(bemjson))
.appendTo('body'))
.bem('button');
}
});
provide();
});
| dojdev/bem-components | common.blocks/button/_type/button_type_link.spec.js | JavaScript | mpl-2.0 | 2,043 |
<!DOCTYPE html>
<meta charset="utf-8">
<title>Async local storage: should not work in non-secure contexts when included via an import statement</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script>
"use strict";
setup({ allow_uncaught_exception: true });
test(() => {
assert_false(self.isSecureContext, "This test must run in a non-secure context");
}, "Prerequisite check");
async_test(t => {
window.addEventListener("error", t.step_func_done(errorEvent => {
assert_equals(errorEvent.error.constructor, DOMException, "Must trigger a DOMException");
assert_equals(errorEvent.error.name, "SecurityError",
"The DOMException must be a \"SecurityError\"");
}, { once: true }));
});
</script>
<script type="module">
import "std:async-local-storage";
</script>
| danlrobertson/servo | tests/wpt/web-platform-tests/async-local-storage/non-secure-context-import-statement.tentative.html | HTML | mpl-2.0 | 849 |
/**
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations under
* the License.
*
* The Original Code is OpenELIS code.
*
* Copyright (C) The Minnesota Department of Health. All Rights Reserved.
*/
package us.mn.state.health.lims.codeelementtype.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import us.mn.state.health.lims.codeelementtype.dao.CodeElementTypeDAO;
import us.mn.state.health.lims.codeelementtype.daoimpl.CodeElementTypeDAOImpl;
import us.mn.state.health.lims.codeelementtype.valueholder.CodeElementType;
import us.mn.state.health.lims.common.action.BaseAction;
import us.mn.state.health.lims.common.action.BaseActionForm;
import us.mn.state.health.lims.common.exception.LIMSRuntimeException;
import us.mn.state.health.lims.common.log.LogEvent;
import us.mn.state.health.lims.common.util.StringUtil;
/**
* @author diane benz
*
* To change this generated comment edit the template variable "typecomment":
* Window>Preferences>Java>Templates. To enable and disable the creation of type
* comments go to Window>Preferences>Java>Code Generation.
*/
public class CodeElementTypeNextPreviousAction extends BaseAction {
private boolean isNew = false;
protected ActionForward performAction(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// The first job is to determine if we are coming to this action with an
// ID parameter in the request. If there is no parameter, we are
// creating a new Analyte.
// If there is a parameter present, we should bring up an existing
// Analyte to edit.
String forward = FWD_SUCCESS;
request.setAttribute(ALLOW_EDITS_KEY, "true");
request.setAttribute(PREVIOUS_DISABLED, "false");
request.setAttribute(NEXT_DISABLED, "false");
String id = request.getParameter(ID);
if (StringUtil.isNullorNill(id) || "0".equals(id)) {
isNew = true;
} else {
isNew = false;
}
BaseActionForm dynaForm = (BaseActionForm) form;
String start = (String) request.getParameter("startingRecNo");
String direction = (String) request.getParameter("direction");
// System.out.println("This is ID from request " + id);
CodeElementType codeElementType = new CodeElementType();
codeElementType.setId(id);
try {
CodeElementTypeDAO codeElementTypeDAO = new CodeElementTypeDAOImpl();
//retrieve analyte by id since the name may have changed
codeElementTypeDAO.getData(codeElementType);
if (FWD_NEXT.equals(direction)) {
//bugzilla 1427 pass in name not id
List codeElementTypes = codeElementTypeDAO.getNextCodeElementTypeRecord(codeElementType.getText());
if (codeElementTypes != null && codeElementTypes.size() > 0) {
codeElementType = (CodeElementType) codeElementTypes.get(0);
codeElementTypeDAO.getData(codeElementType);
if (codeElementTypes.size() < 2) {
// disable next button
request.setAttribute(NEXT_DISABLED, "true");
}
id = codeElementType.getId();
} else {
// just disable next button
request.setAttribute(NEXT_DISABLED, "true");
}
}
if (FWD_PREVIOUS.equals(direction)) {
//bugzilla 1427 pass in name not id
List codeElementTypes = codeElementTypeDAO.getPreviousCodeElementTypeRecord(codeElementType.getText());
if (codeElementTypes != null && codeElementTypes.size() > 0) {
codeElementType = (CodeElementType) codeElementTypes.get(0);
codeElementTypeDAO.getData(codeElementType);
if (codeElementTypes.size() < 2) {
// disable previous button
request.setAttribute(PREVIOUS_DISABLED, "true");
}
id = codeElementType.getId();
} else {
// just disable next button
request.setAttribute(PREVIOUS_DISABLED, "true");
}
}
} catch (LIMSRuntimeException lre) {
//bugzilla 2154
LogEvent.logError("CodeElementTypeNextPreviousAction","performAction()",lre.toString());
request.setAttribute(ALLOW_EDITS_KEY, "false");
// disable previous and next
request.setAttribute(PREVIOUS_DISABLED, "true");
request.setAttribute(NEXT_DISABLED, "true");
forward = FWD_FAIL;
}
if (forward.equals(FWD_FAIL))
return mapping.findForward(forward);
if (codeElementType.getId() != null && !codeElementType.getId().equals("0")) {
request.setAttribute(ID, codeElementType.getId());
}
return getForward(mapping.findForward(forward), id, start);
}
protected String getPageTitleKey() {
return null;
}
protected String getPageSubtitleKey() {
return null;
}
} | mark47/OESandbox | app/src/us/mn/state/health/lims/codeelementtype/action/CodeElementTypeNextPreviousAction.java | Java | mpl-2.0 | 5,173 |
import java.util.Scanner;
public class SegmentTree {
private static class Node {
public int left, right;
public long add, sum;
public Node(int left, int right, long sum) {
this.left = left;
this.right = right;
this.sum = sum;
}
}
private Node[] tree;
private int size;
public SegmentTree(int n,int[] arr) {
size = (n<<2);
tree = new Node[size];
build(0, 0, n-1, arr);
}
private void build(int pos, int p, int r, int[] arr) {
if (p == r) {
tree[pos] = new Node(p, r, arr[p]);
} else {
build(2*pos+1, p, (p+r)/2, arr);
build(2*pos+2, (p+r)/2+1, r, arr);
tree[pos] = new Node(p, r, tree[2*pos+1].sum + tree[2*pos+2].sum);
}
}
public void update(int p, int r, long delt) {
p = (tree[0].left < p)?
p : tree[0].left;
r = (tree[0].right > r)?
r : tree[0].right;
if (p <= r) {
updateHelp(0, p, r, delt);
}
}
private void updateHelp(int pos, int p, int r, long delt) {
if (tree[pos].left>=p && tree[pos].right<=r) {
tree[pos].add += delt;
tree[pos].sum +=
(tree[pos].right-tree[pos].left+1)*delt;
} else {
if (tree[pos].add!=0) {
pushDown(pos);
}
int mid = (tree[pos].left+tree[pos].right)/2;
if (p <= mid) {
updateHelp(2*pos+1, p, r, delt);
}
if (mid+1 <= r) {
updateHelp(2*pos+2, p, r, delt);
}
tree[pos].sum = tree[2*pos+1].sum + tree[2*pos+2].sum;
}
}
private void pushDown(int pos) {
int left = 2*pos+1, right = 2*pos+2;
tree[left].add += tree[pos].add;
tree[right].add += tree[pos].add;
tree[left].sum +=
(tree[left].right-tree[left].left+1)*tree[pos].add;
tree[right].sum +=
(tree[right].right-tree[right].left+1)*tree[pos].add;
tree[pos].add = 0;
}
public long query(int p,int r) {
if (tree[0].left<=p && tree[0].right>=r) {
return queryHelp(0,p,r);
} else {
return 0;
}
}
private long queryHelp(int pos,int p,int r) {
if (tree[pos].left>=p && tree[pos].right<=r) {
return tree[pos].sum;
} else {
if (tree[pos].add!=0) {
pushDown(pos);
}
long val = 0;
int mid = (tree[pos].left+tree[pos].right)/2;
if (p <= mid) {
val += queryHelp(2*pos+1, p, r);
}
if (mid+1 <= r) {
val += queryHelp(2*pos+2, p, r);
}
return val;
}
}
public static void main(String[] args) {
Main.main(args);
}
}
class Main {
/** POJ 3468: http://poj.org/problem?id=3468 */
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
int q = in.nextInt();
for (int i=0;i<n;i++) {
arr[i] = in.nextInt();
}
SegmentTree tr = new SegmentTree(n,arr);
for (int i=0;i<q;i++) {
String op = in.next();
if (op.equals("C")) {
int p = in.nextInt()-1;
int r = in.nextInt()-1;
tr.update(p,r,in.nextInt());
} else if (op.equals("Q")) {
int p = in.nextInt()-1;
int r = in.nextInt()-1;
System.out.println(tr.query(p,r));
}
}
in.close();
}
}
| DevinZ1993/Pieces-of-Code | java/Sets/src/SegmentTree.java | Java | mpl-2.0 | 3,871 |
// |jit-test| allow-oom; allow-unhandlable-oom
gcparam("maxBytes", gcparam("gcBytes") + 4*1024);
var max = 400;
function f(b) {
if (b) {
f(b - 1);
} else {
g = {
apply:function(x,y) { }
};
}
g.apply(null, arguments);
}
f(max - 1);
| Yukarumya/Yukarum-Redfoxes | js/src/jit-test/tests/baseline/bug847425.js | JavaScript | mpl-2.0 | 294 |
{% extends "demos/base.html" %}
{% block body_attributes %}id="demostudio"{% endblock %}
{% block bodyclass %}section-demos landing {% if is_demo_home %}section-demos-home{% endif %}{% endblock %}
{% block extrahead %}
<link rel="alternate" type="application/atom+xml" title="{{_('Recent demos')}}"
href="{{ url('demos_feed_recent', format='atom') }}" />
<link rel="alternate" type="application/atom+xml" title="{{_('Featured demos')}}"
href="{{ url('demos_feed_featured', format='atom') }}" />
{% endblock %}
{% block title %}{{ page_title(_('Demo Studio')) }}{% endblock %}
{% block content %}
<section id="content">
<div class="wrap">
<header id="demos-head">
<h1><a href="{{ url('demos') }}">{{_("Mozilla Demo Studio")}}</a></h1>
<ul class="demo-buttons">
<li class="submit"><a href="{{ url('demos_submit') }}" class="button positive"><b></b>{{_("Submit a Demo")}}</a></li>
<li class="learnmore menu"><a href="#learn-pop" class="button">{{ _('Learn More') }}</a>
<div id="learn-pop" aria-hidden="true">
{% trans %}
<p>Welcome to the Mozilla Demo Studio, where developers like you can develop, share, demonstrate, and learn all about Web technologies. See what's possible by exploring Demo Studio:</p>
<ul>
<li>View demos that showcase what HTML, CSS, and JavaScript can do.</li>
<li>Inspect the source code for those demos so you can see how they work.</li>
<li>Read documentation to learn about the open standards and technologies that power the Web.</li>
</ul>
{% endtrans %}
</div>
</li>
</ul>
</header>
{% if featured_submission_list | length >= 3 %}
<section id="featured-demos">
<header>
<h2>{{_("Featured Demos")}}</h2>
</header>
<ul class="nav-slide">
<li class="nav-prev"><a href="#demo-prev" class="prev" title="{{_("See the previous demo")}}">{{_("Previous")}}</a></li>
<li class="nav-next"><a href="#demo-next" class="next" title="{{_("See the next demo")}}">{{_("Next")}}</a></li>
</ul>
{% set submission = featured_submission_list[1] %}
<div id="demo-main">
{# <strong class="flag">{{_("Derby Winner")}}</strong> #}
<div class="preview">
<a href="{{ url('demos_detail', slug=submission.slug) }}">
<img src="{{ submission.screenshot_1.url }}" alt="" width="435" height="326">
</a>
<div class="demo-details">
<h2 class="demo-title">
<a href="{{ url('demos_detail', slug=submission.slug) }}">{{ submission.title }}</a>
</h2>
<p class="byline vcard">
{{ user_link(submission.creator, show_gravatar=True) }}
</p>
<p class="desc">
<span class="descText">{{ submission.summary }}</span>
<a href="{{ url('demos_detail', slug=submission.slug) }}" class="descLink">{{_("Details")}}</a>
</p>
<p class="launch">
<a href="{{ url('demos_launch', slug=submission.slug) }}" class="button">{{_("Launch")}}</a>
</p>
</div>
</div>
</div>
{% set submission = featured_submission_list[0] %}
<div id="demo-prev" class="side">
<div class="preview">
<h2 class="demo-title">
<a href="{{ url('demos_detail', slug=submission.slug) }}">
<img class="preview" src="{{ submission.screenshot_1.url }}" alt="" width="261" height="195">
<b>{{ submission.title }}</b>
</a>
</h2>
</div>
</div>
{% set submission = featured_submission_list[2] %}
<div id="demo-next" class="side">
<div class="preview">
<h2 class="demo-title">
<a href="{{ url('demos_detail', slug=submission.slug) }}">
<img class="preview" src="{{ submission.screenshot_1.url }}" alt="" width="261" height="195">
<b>{{ submission.title }}</b>
</a>
</h2>
</div>
</div>
</section>
{% endif %}
<section id="content-main" class="full" role="main">
<div id="search-browse">
<form class="demo-search" method="GET" action="{{ url('demos_search') }}">
<p>
<input type="search" id="search-demos" name="q" placeholder="{{_("Search demos")}}" />
<noscript><button type="submit">{{_("Search demos")}}</button></noscript>
</p>
</form>
{% trans %}<b>or</b>{% endtrans %}
<div id="demo-tags" class="menu">
<a href="#tags-list" class="button neutral">{{_("Browse by Technology")}}</a>
<ul id="tags-list">
{% for tag in tags_used_for_submissions() %}
{% if tag.name.startswith('tech:') %}
<li><a href="{{ url('demos_tag', tag=tag.name) }}">{{ tag_title(tag) }}</a></li>
{% endif %}
{% endfor %}
</ul>
</div>
<div class="demo-mobile-list">
<ul>
<li><a href="all?sort=upandcoming#gallery-list" class="button neutral">{{ ("Browse by up & coming") }}</a></li>
<li><a href="all?sort=launches#gallery-list" class="button neutral">{{ ("Browse by most viewed") }}</a></li>
<li><a href="all?sort=likes#gallery-list" class="button neutral">{{ ("Browse by most liked") }}</a></li>
<li><a href="all?sort=created#gallery-list" class="button neutral">{{ ("Browse by most recent") }}</a></li>
</ul>
</div>
</div>
<div class="demo-landing-gallery">
{{ submission_listing(request, submission_list, is_paginated, paginator, page_obj,
_('Subscribe to a feed of %(tag_title)s demos', tag_title=_('recent')),
url('demos_feed_recent', format='rss'), cols_per_row=4,
pagination_base_url=url('demos_all') ) }}
</div>
</section><!-- /#content-main -->
</div>
</section>
{% endblock %}
{% block js %}
{{ super() }}
<script type="text/javascript">
$(document).ready(function() {
var $featuredDemos = $("#featured-demos"),
$details = $("#demo-main .demo-details"),
$demoPrev = $('#demo-prev'),
$demoNext = $('#demo-next');
$featuredDemos.addClass("js");
$("#demo-main .demo-details, #featured-demos .side .demo-title b").hide().attr("aria-hidden", "true");
$("#demo-main .preview").hoverIntent({
interval: 150,
over: function(){
$details.fadeIn().removeAttr("aria-hidden");
},
out: function(){
$details.fadeOut("fast").attr("aria-hidden", "true");
}
});
$("#featured-demos .side .preview").hoverIntent({
interval: 250,
over: function(){
$(this).find("img").animate({ opacity: "1" }, 150);
$(this).find(".demo-title b").fadeIn(150).removeAttr("aria-hidden");
},
out: function(){
$(this).find("img").animate({ opacity: ".6" }, 250);
$(this).find(".demo-title b").fadeOut(250).attr("aria-hidden", "true");
}
});
/**
* Set up featured demos rotation - loads up the JSON feed for featured demos
* and does DOM juggling to page through the items.
*/
var featured_demos_feed_url =
'{{ url('demos_feed_featured', format='json') }}';
// Hide buttons until feed loaded.
$(".nav-slide .next, .nav-slide .prev").hide();
// Load the feed, wire everything up once the data's been received.
$.getJSON(featured_demos_feed_url, function (demos) {
// Refrain from wiring up nav, if no items fetched from feed.
if (!demos || demos.length == 0) {
return;
}
// Start the current index at 1, since 0 and 2 should already be in prev
// and next positions.
var currentIndex = 1;
// Store node queries that don't need to be made more than once
var $demoNextPreview = $('#demo-next .preview'),
$demoMainPreview = $('#demo-main .preview'),
$demoPrevPreview = $('#demo-prev .preview');
// Create next / prev button vars here
var $nextBtn = $('.nav-slide .next'),
$prevBtn = $('.nav-slide .prev');
var updatePrevFeaturedDemo = createDemoUpdates(-1, $demoPrev);
var updateNextFeaturedDemo = createDemoUpdates(1, $demoNext);
var demoFadeTime = 250;
var demoDelayFactor = .5;
if($('#demo-prev').css('display') == 'none') { // Small screen, "previous" and "next" aren't shown
demoDelayFactor = 0;
}
// Show the next button and wire up click handler.
$nextBtn.show().on('click', function() {
currentIndex = (currentIndex == demos.length - 1? 0 : currentIndex + 1);
$demoNextPreview.fadeOut(demoFadeTime, function() {
updateNextFeaturedDemo();
$(this).fadeIn(demoFadeTime);
});
$demoMainPreview.delay(parseInt(demoFadeTime * demoDelayFactor)).fadeOut(demoFadeTime, function() {
updateMainFeaturedDemo();
$(this).fadeIn(demoFadeTime);
});
$demoPrevPreview.delay(parseInt(demoFadeTime * demoDelayFactor * 2)).fadeOut(demoFadeTime, function() {
updatePrevFeaturedDemo();
$(this).fadeIn(demoFadeTime);
});
return false;
});
// Show the previous button and wire up click handler.
$prevBtn.show().on('click', function() {
currentIndex = (currentIndex == 0 ? demos.length - 1 : currentIndex - 1);
$demoPrevPreview.fadeOut(demoFadeTime, function() {
updatePrevFeaturedDemo();
$(this).fadeIn(demoFadeTime);
});
$demoMainPreview.delay(parseInt(demoFadeTime * demoDelayFactor)).fadeOut(demoFadeTime, function() {
updateMainFeaturedDemo();
$(this).fadeIn(demoFadeTime);
});
$demoNextPreview.delay(parseInt(demoFadeTime * demoDelayFactor * 2)).fadeOut(demoFadeTime, function() {
updateNextFeaturedDemo();
$(this).fadeIn(demoFadeTime);
});
return false;
});
// Update the main demo from the current index demo.
function updateMainFeaturedDemo() {
var demo = demos[currentIndex];
$('#demo-main')
.find('.preview img').attr('src', demo.screenshot).end()
.find('.preview a').attr('href', demo.link).end()
.find('.demo-title a')
.attr('href', demo.link)
.text(demo.title)
.end()
.find('.byline a')
.attr('href', demo.author_link)
.find('span').text(demo.author_name).end()
.find('img').attr('src', demo.author_avatar).end()
.end()
.find('.descText').text(demo.summary).end()
.find('.descLink')
.attr('href', demo.link)
.end()
.find('.launch a').attr('href', demo.link + '/launch')
.end();
}
// Create functions for next and previous movement
function createDemoUpdates(offset, $element) {
return function() {
var scrollIndex = currentIndex + offset;
if(!demos[scrollIndex]) {
if(offset < 0) { // Previous, so show the last one in the "prev" spot
scrollIndex = demos.length - 1;
}
else { // Next, show the first one in the "next" spot
scrollIndex = 0;
}
}
var demo = demos[scrollIndex];
$element
.find('.preview img').attr('src', demo ? demo.screenshot : '').end()
.find('.demo-title a').attr('href', demo ? demo.link : '#').end()
.find('.demo-title b').text(demo ? demo.title : '').end();
};
}
// Preload images for sake of smoothness
$.each(demos, function() {
$('<img>').attr({
'src': this.screenshot,
'aria-hidden': 'true',
'class': 'offscreen'
}).appendTo(document.body);
});
});
});
</script>
{% endblock %}
| jezdez/kuma | kuma/demos/templates/demos/home.html | HTML | mpl-2.0 | 12,292 |
"""
Tests for Blocks api.py
"""
from django.test.client import RequestFactory
from course_blocks.tests.helpers import EnableTransformerRegistryMixin
from student.tests.factories import UserFactory
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
from xmodule.modulestore.tests.factories import SampleCourseFactory
from ..api import get_blocks
class TestGetBlocks(EnableTransformerRegistryMixin, SharedModuleStoreTestCase):
"""
Tests for the get_blocks function
"""
@classmethod
def setUpClass(cls):
super(TestGetBlocks, cls).setUpClass()
cls.course = SampleCourseFactory.create()
# hide the html block
cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1'))
cls.html_block.visible_to_staff_only = True
cls.store.update_item(cls.html_block, ModuleStoreEnum.UserID.test)
def setUp(self):
super(TestGetBlocks, self).setUp()
self.user = UserFactory.create()
self.request = RequestFactory().get("/dummy")
self.request.user = self.user
def test_basic(self):
blocks = get_blocks(self.request, self.course.location, self.user)
self.assertEquals(blocks['root'], unicode(self.course.location))
# subtract for (1) the orphaned course About block and (2) the hidden Html block
self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.course.id)) - 2)
self.assertNotIn(unicode(self.html_block.location), blocks['blocks'])
def test_no_user(self):
blocks = get_blocks(self.request, self.course.location)
self.assertIn(unicode(self.html_block.location), blocks['blocks'])
def test_access_before_api_transformer_order(self):
"""
Tests the order of transformers: access checks are made before the api
transformer is applied.
"""
blocks = get_blocks(self.request, self.course.location, self.user, nav_depth=5, requested_fields=['nav_depth'])
vertical_block = self.store.get_item(self.course.id.make_usage_key('vertical', 'vertical_x1a'))
problem_block = self.store.get_item(self.course.id.make_usage_key('problem', 'problem_x1a_1'))
vertical_descendants = blocks['blocks'][unicode(vertical_block.location)]['descendants']
self.assertIn(unicode(problem_block.location), vertical_descendants)
self.assertNotIn(unicode(self.html_block.location), vertical_descendants)
| antoviaque/edx-platform | lms/djangoapps/course_api/blocks/tests/test_api.py | Python | agpl-3.0 | 2,533 |
"""This *was* the parser for the current HTML format on parl.gc.ca.
But now we have XML. See parl_document.py.
This module is organized like so:
__init__.py - utility functions, simple parse interface
common.py - infrastructure used in the parsers, i.e. regexes
current.py - parser for the Hansard format used from 2006 to the present
old.py - (fairly crufty) parser for the format used from 1994 to 2006
"""
from parliament.imports.hans_old.common import *
import logging
logger = logging.getLogger(__name__)
class HansardParser2009(HansardParser):
def __init__(self, hansard, html):
for regex in STARTUP_RE_2009:
html = re.sub(regex[0], regex[1], html)
super(HansardParser2009, self).__init__(hansard, html)
for x in self.soup.findAll('a', 'deleteMe'):
x.findParent('div').extract()
def process_related_link(self, tag, string, current_politician=None):
#print "PROCESSING RELATED for %s" % string
resid = re.search(r'ResourceID=(\d+)', tag['href'])
restype = re.search(r'ResourceType=(Document|Affiliation)', tag['href'])
if not resid and restype:
return string
resid, restype = int(resid.group(1)), restype.group(1)
if restype == 'Document':
try:
bill = Bill.objects.get_by_legisinfo_id(resid)
except Bill.DoesNotExist:
match = re.search(r'\b[CS]\-\d+[A-E]?\b', string)
if not match:
logger.error("Invalid bill link %s" % string)
return string
bill = Bill.objects.create_temporary_bill(legisinfo_id=resid,
number=match.group(0), session=self.hansard.session)
except Exception, e:
print "Related bill search failed for callback %s" % resid
print repr(e)
return string
return u'<bill id="%d" name="%s">%s</bill>' % (bill.id, escape(bill.name), string)
elif restype == 'Affiliation':
try:
pol = Politician.objects.getByParlID(resid)
except Politician.DoesNotExist:
print "Related politician search failed for callback %s" % resid
if getattr(settings, 'PARLIAMENT_LABEL_FAILED_CALLBACK', False):
# FIXME migrate away from internalxref?
InternalXref.objects.get_or_create(schema='pol_parlid', int_value=resid, target_id=-1)
return string
if pol == current_politician:
return string # When someone mentions her riding, don't link back to her
return u'<pol id="%d" name="%s">%s</pol>' % (pol.id, escape(pol.name), string)
def get_text(self, cursor):
text = u''
for string in cursor.findAll(text=parsetools.r_hasText):
if string.parent.name == 'a' and string.parent['class'] == 'WebOption':
text += self.process_related_link(string.parent, string, self.t['politician'])
else:
text += unicode(string)
return text
def parse(self):
super(HansardParser2009, self).parse()
# Initialize variables
t = ParseTracker()
self.t = t
member_refs = {}
# Get the date
c = self.soup.find(text='OFFICIAL REPORT (HANSARD)').findNext('h2')
self.date = datetime.datetime.strptime(c.string.strip(), "%A, %B %d, %Y").date()
self.hansard.date = self.date
self.hansard.save()
c = c.findNext(text=r_housemet)
match = re.search(r_housemet, c.string)
t['timestamp'] = self.houseTime(match.group(1), match.group(2))
t.setNext('timestamp', t['timestamp'])
# Move the pointer to the start
c = c.next
# And start the big loop
while c is not None:
# It's a string
if not hasattr(c, 'name'):
pass
# Heading
elif c.name == 'h2':
c = c.next
if not parsetools.isString(c): raise ParseException("Expecting string right after h2")
t.setNext('heading', parsetools.titleIfNecessary(parsetools.tameWhitespace(c.string.strip())))
# Topic
elif c.name == 'h3':
top = c.find(text=r_letter)
#if not parsetools.isString(c):
# check if it's an empty header
# if c.parent.find(text=r_letter):
# raise ParseException("Expecting string right after h3")
if top is not None:
c = top
t['topic_set'] = True
t.setNext('topic', parsetools.titleIfNecessary(parsetools.tameWhitespace(c.string.strip())))
elif c.name == 'h4':
if c.string == 'APPENDIX':
self.saveStatement(t)
print "Appendix reached -- we're done!"
break
# Timestamp
elif c.name == 'a' and c.has_key('name') and c['name'].startswith('T'):
match = re.search(r'^T(\d\d)(\d\d)$', c['name'])
if match:
t.setNext('timestamp', parsetools.time_to_datetime(
hour=int(match.group(1)),
minute=int(match.group(2)),
date=self.date))
else:
raise ParseException("Couldn't match time %s" % c.attrs['name'])
elif c.name == 'b' and c.string:
# Something to do with written answers
match = r_honorific.search(c.string)
if match:
# It's a politician asking or answering a question
# We don't get a proper link here, so this has to be a name match
polname = re.sub(r'\(.+\)', '', match.group(2)).strip()
self.saveStatement(t)
t['member_title'] = c.string.strip()
t['written_question'] = True
try:
pol = Politician.objects.get_by_name(polname, session=self.hansard.session)
t['politician'] = pol
t['member'] = ElectedMember.objects.get_by_pol(politician=pol, date=self.date)
except Politician.DoesNotExist:
print "WARNING: No name match for %s" % polname
except Politician.MultipleObjectsReturned:
print "WARNING: Multiple pols for %s" % polname
else:
if not c.string.startswith('Question'):
print "WARNING: Unexplained boldness: %s" % c.string
# div -- the biggie
elif c.name == 'div':
origdiv = c
if c.find('b'):
# We think it's a new speaker
# Save the current buffer
self.saveStatement(t)
c = c.find('b')
if c.find('a'):
# There's a link...
c = c.find('a')
match = re.search(r'ResourceType=Affiliation&ResourceID=(\d+)', c['href'])
if match and c.find(text=r_letter):
parlwebid = int(match.group(1))
# We have the parl ID. First, see if we already know this ID.
pol = Politician.objects.getByParlID(parlwebid, lookOnline=False)
if pol is None:
# We don't. Try to do a quick name match first (if flags say so)
if not GET_PARLID_ONLINE:
who = c.next.string
match = re.search(r_honorific, who)
if match:
polname = re.sub(r'\(.+\)', '', match.group(2)).strip()
try:
#print "Looking for %s..." % polname,
pol = Politician.objects.get_by_name(polname, session=self.hansard.session)
#print "found."
except Politician.DoesNotExist:
pass
except Politician.MultipleObjectsReturned:
pass
if pol is None:
# Still no match. Go online...
try:
pol = Politician.objects.getByParlID(parlwebid, session=self.hansard.session)
except Politician.DoesNotExist:
print "WARNING: Couldn't find politician for ID %d" % parlwebid
if pol is not None:
t['member'] = ElectedMember.objects.get_by_pol(politician=pol, date=self.date)
t['politician'] = pol
c = c.next
if not parsetools.isString(c): raise Exception("Expecting string in b for member name")
t['member_title'] = c.strip()
#print c
if t['member_title'].endswith(':'): # Remove colon in e.g. Some hon. members:
t['member_title'] = t['member_title'][:-1]
# Sometimes we don't get a link for short statements -- see if we can identify by backreference
if t['member']:
member_refs[t['member_title']] = t['member']
# Also save a backref w/o position/riding
member_refs[re.sub(r'\s*\(.+\)\s*', '', t['member_title'])] = t['member']
elif t['member_title'] in member_refs:
t['member'] = member_refs[t['member_title']]
t['politician'] = t['member'].politician
c.findParent('b').extract() # We've got the title, now get the rest of the paragraph
c = origdiv
t.addText(self.get_text(c))
else:
# There should be text in here
if c.find('div'):
if c.find('div', 'Footer'):
# We're done!
self.saveStatement(t)
print "Footer div reached -- done!"
break
raise Exception("I wasn't expecting another div in here")
txt = self.get_text(c).strip()
if r_proceedings.search(txt):
self.saveStatement(t)
self.saveProceedingsStatement(txt, t)
else:
t.addText(txt, blockquote=bool(c.find('small')))
else:
#print c.name
if c.name == 'b':
print "B: ",
print c
#if c.name == 'p':
# print "P: ",
# print c
c = c.next
return self.statements
| twhyte/openparliament | parliament/imports/hans_old/current.py | Python | agpl-3.0 | 11,722 |
require_relative 'test_helper'
class BoxesTest < ActiveSupport::TestCase
def setup
create_and_activate_user
login_api
end
kinds= %w[Profile Community Person Enterprise Environment]
kinds.each do |kind|
should "get_boxes_from_#{kind.downcase.pluralize}" do
context_obj = fast_create(kind.constantize)
box = fast_create(Box, :owner_id => context_obj.id, :owner_type => (kind == 'Environment') ? 'Environment' : 'Profile')
get "/api/v1/#{kind.downcase.pluralize}/#{context_obj.id}/boxes?#{params.to_query}"
json = JSON.parse(last_response.body)
assert_equal box.id, json.first["id"]
end
end
should 'get boxes from default environment' do
Environment.delete_all
environment = fast_create(Environment, :is_default => true)
box = fast_create(Box, :owner_id => environment.id, :owner_type => 'Environment')
get "/api/v1/environments/default/boxes?#{params.to_query}"
json = JSON.parse(last_response.body)
assert_equal box.id, json.first["id"]
end
should 'get boxes from context environment' do
env = fast_create(Environment, :is_default => true)
env2 = fast_create(Environment).domains << Domain.new(:name => 'test.host')
box = fast_create(Box, :owner_id => environment.id, :owner_type => 'Environment')
get "/api/v1/environments/context/boxes?#{params.to_query}"
json = JSON.parse(last_response.body)
assert_equal box.id, json.first["id"]
end
should 'not display block api_content by default' do
Environment.delete_all
environment = fast_create(Environment, :is_default => true)
box = fast_create(Box, :owner_id => environment.id, :owner_type => 'Environment')
block = fast_create(Block, box_id: box.id)
get "/api/v1/environments/default/boxes?#{params.to_query}"
json = JSON.parse(last_response.body)
assert !json.first["blocks"].first.key?('api_content')
end
should 'get blocks from boxes' do
Environment.delete_all
environment = fast_create(Environment, :is_default => true)
box = fast_create(Box, :owner_id => environment.id, :owner_type => 'Environment')
block = fast_create(Block, box_id: box.id)
get "/api/v1/environments/default/boxes?#{params.to_query}"
json = JSON.parse(last_response.body)
assert_equal [block.id], json.first["blocks"].map {|b| b['id']}
end
should 'not list a block for not logged users' do
logout_api
profile = fast_create(Profile)
box = fast_create(Box, :owner_id => profile.id, :owner_type => Profile.name)
block = fast_create(Block, box_id: box.id)
block.display = 'never'
block.save!
get "/api/v1/profiles/#{profile.id}/boxes?#{params.to_query}"
json = JSON.parse(last_response.body)
assert_equal [], json.first["blocks"].map {|b| b['id']}
end
should 'list a block with logged in display_user for a logged user' do
profile = fast_create(Profile)
box = fast_create(Box, :owner_id => profile.id, :owner_type => Profile.name)
block = fast_create(Block, box_id: box.id)
block.display_user = 'logged'
block.save!
get "/api/v1/profiles/#{profile.id}/boxes?#{params.to_query}"
json = JSON.parse(last_response.body)
assert_equal [block.id], json.first["blocks"].map {|b| b['id']}
end
should 'list a block with not logged in display_user for an admin user' do
profile = fast_create(Profile)
profile.add_admin(person)
box = fast_create(Box, :owner_id => profile.id, :owner_type => Profile.name)
block = fast_create(Block, box_id: box.id)
block.display_user = 'not_logged'
block.save!
get "/api/v1/profiles/#{profile.id}/boxes?#{params.to_query}"
json = JSON.parse(last_response.body)
assert_equal [block.id], json.first["blocks"].map {|b| b['id']}
end
should 'not list boxes for user without permission' do
profile = fast_create(Profile, public_profile: false)
box = fast_create(Box, :owner_id => profile.id, :owner_type => Profile.name)
block = fast_create(Block, box_id: box.id)
get "/api/v1/profiles/#{profile.id}/boxes?#{params.to_query}"
json = JSON.parse(last_response.body)
assert_equal 403, last_response.status
end
end
| coletivoEITA/noosfero-ecosol | test/api/boxes_test.rb | Ruby | agpl-3.0 | 4,177 |
/*
* This file is part of ToroDB.
*
* ToroDB 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.
*
* ToroDB 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 ToroDB. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (c) 2014, 8Kdata Technology
*
*/
package com.torodb.torod.core.language.querycriteria;
import com.torodb.torod.core.language.AttributeReference;
import com.torodb.torod.core.language.querycriteria.utils.QueryCriteriaVisitor;
import com.torodb.torod.core.subdocument.values.Value;
/**
*
*/
public class IsGreaterOrEqualQueryCriteria extends AttributeAndValueQueryCriteria {
private static final long serialVersionUID = 1L;
public IsGreaterOrEqualQueryCriteria(AttributeReference attributeReference, Value<?> val) {
super(attributeReference, val);
}
@Override
protected int getBaseHash() {
return 5;
}
@Override
public String toString() {
return getAttributeReference() + " >= " + getValue();
}
@Override
public <Result, Arg> Result accept(QueryCriteriaVisitor<Result, Arg> visitor, Arg arg) {
return visitor.visit(this, arg);
}
}
| ahachete/torodb | torod/torod-core/src/main/java/com/torodb/torod/core/language/querycriteria/IsGreaterOrEqualQueryCriteria.java | Java | agpl-3.0 | 1,681 |
import Analyzer from 'parser/core/Analyzer';
import RESOURCE_TYPES from 'game/RESOURCE_TYPES';
class Insanity extends Analyzer {
_insanityEvents = [];
on_toPlayer_energize(event) {
if (event.resourceChangeType === RESOURCE_TYPES.INSANITY.id) {
this._insanityEvents = [
...this._insanityEvents,
event,
];
}
}
get events() {
return this._insanityEvents;
}
}
export default Insanity;
| ronaldpereira/WoWAnalyzer | src/parser/priest/shadow/modules/core/Insanity.js | JavaScript | agpl-3.0 | 435 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is built by mktables from e.g. UnicodeData.txt.
# Any changes made here will be lost!
#
# This file supports:
# \p{L}
# \p{L} (and fuzzy permutations)
#
# Meaning: Major Category 'L'
#
return <<'END';
0041 005A
0061 007A
00AA
00B5
00BA
00C0 00D6
00D8 00F6
00F8 02C1
02C6 02D1
02E0 02E4
02EE
037A 037D
0386
0388 038A
038C
038E 03A1
03A3 03CE
03D0 03F5
03F7 0481
048A 0513
0531 0556
0559
0561 0587
05D0 05EA
05F0 05F2
0621 063A
0640 064A
066E 066F
0671 06D3
06D5
06E5 06E6
06EE 06EF
06FA 06FC
06FF
0710
0712 072F
074D 076D
0780 07A5
07B1
07CA 07EA
07F4 07F5
07FA
0904 0939
093D
0950
0958 0961
097B 097F
0985 098C
098F 0990
0993 09A8
09AA 09B0
09B2
09B6 09B9
09BD
09CE
09DC 09DD
09DF 09E1
09F0 09F1
0A05 0A0A
0A0F 0A10
0A13 0A28
0A2A 0A30
0A32 0A33
0A35 0A36
0A38 0A39
0A59 0A5C
0A5E
0A72 0A74
0A85 0A8D
0A8F 0A91
0A93 0AA8
0AAA 0AB0
0AB2 0AB3
0AB5 0AB9
0ABD
0AD0
0AE0 0AE1
0B05 0B0C
0B0F 0B10
0B13 0B28
0B2A 0B30
0B32 0B33
0B35 0B39
0B3D
0B5C 0B5D
0B5F 0B61
0B71
0B83
0B85 0B8A
0B8E 0B90
0B92 0B95
0B99 0B9A
0B9C
0B9E 0B9F
0BA3 0BA4
0BA8 0BAA
0BAE 0BB9
0C05 0C0C
0C0E 0C10
0C12 0C28
0C2A 0C33
0C35 0C39
0C60 0C61
0C85 0C8C
0C8E 0C90
0C92 0CA8
0CAA 0CB3
0CB5 0CB9
0CBD
0CDE
0CE0 0CE1
0D05 0D0C
0D0E 0D10
0D12 0D28
0D2A 0D39
0D60 0D61
0D85 0D96
0D9A 0DB1
0DB3 0DBB
0DBD
0DC0 0DC6
0E01 0E30
0E32 0E33
0E40 0E46
0E81 0E82
0E84
0E87 0E88
0E8A
0E8D
0E94 0E97
0E99 0E9F
0EA1 0EA3
0EA5
0EA7
0EAA 0EAB
0EAD 0EB0
0EB2 0EB3
0EBD
0EC0 0EC4
0EC6
0EDC 0EDD
0F00
0F40 0F47
0F49 0F6A
0F88 0F8B
1000 1021
1023 1027
1029 102A
1050 1055
10A0 10C5
10D0 10FA
10FC
1100 1159
115F 11A2
11A8 11F9
1200 1248
124A 124D
1250 1256
1258
125A 125D
1260 1288
128A 128D
1290 12B0
12B2 12B5
12B8 12BE
12C0
12C2 12C5
12C8 12D6
12D8 1310
1312 1315
1318 135A
1380 138F
13A0 13F4
1401 166C
166F 1676
1681 169A
16A0 16EA
1700 170C
170E 1711
1720 1731
1740 1751
1760 176C
176E 1770
1780 17B3
17D7
17DC
1820 1877
1880 18A8
1900 191C
1950 196D
1970 1974
1980 19A9
19C1 19C7
1A00 1A16
1B05 1B33
1B45 1B4B
1D00 1DBF
1E00 1E9B
1EA0 1EF9
1F00 1F15
1F18 1F1D
1F20 1F45
1F48 1F4D
1F50 1F57
1F59
1F5B
1F5D
1F5F 1F7D
1F80 1FB4
1FB6 1FBC
1FBE
1FC2 1FC4
1FC6 1FCC
1FD0 1FD3
1FD6 1FDB
1FE0 1FEC
1FF2 1FF4
1FF6 1FFC
2071
207F
2090 2094
2102
2107
210A 2113
2115
2119 211D
2124
2126
2128
212A 212D
212F 2139
213C 213F
2145 2149
214E
2183 2184
2C00 2C2E
2C30 2C5E
2C60 2C6C
2C74 2C77
2C80 2CE4
2D00 2D25
2D30 2D65
2D6F
2D80 2D96
2DA0 2DA6
2DA8 2DAE
2DB0 2DB6
2DB8 2DBE
2DC0 2DC6
2DC8 2DCE
2DD0 2DD6
2DD8 2DDE
3005 3006
3031 3035
303B 303C
3041 3096
309D 309F
30A1 30FA
30FC 30FF
3105 312C
3131 318E
31A0 31B7
31F0 31FF
3400 4DB5
4E00 9FBB
A000 A48C
A717 A71A
A800 A801
A803 A805
A807 A80A
A80C A822
A840 A873
AC00 D7A3
F900 FA2D
FA30 FA6A
FA70 FAD9
FB00 FB06
FB13 FB17
FB1D
FB1F FB28
FB2A FB36
FB38 FB3C
FB3E
FB40 FB41
FB43 FB44
FB46 FBB1
FBD3 FD3D
FD50 FD8F
FD92 FDC7
FDF0 FDFB
FE70 FE74
FE76 FEFC
FF21 FF3A
FF41 FF5A
FF66 FFBE
FFC2 FFC7
FFCA FFCF
FFD2 FFD7
FFDA FFDC
10000 1000B
1000D 10026
10028 1003A
1003C 1003D
1003F 1004D
10050 1005D
10080 100FA
10300 1031E
10330 10340
10342 10349
10380 1039D
103A0 103C3
103C8 103CF
10400 1049D
10800 10805
10808
1080A 10835
10837 10838
1083C
1083F
10900 10915
10A00
10A10 10A13
10A15 10A17
10A19 10A33
12000 1236E
1D400 1D454
1D456 1D49C
1D49E 1D49F
1D4A2
1D4A5 1D4A6
1D4A9 1D4AC
1D4AE 1D4B9
1D4BB
1D4BD 1D4C3
1D4C5 1D505
1D507 1D50A
1D50D 1D514
1D516 1D51C
1D51E 1D539
1D53B 1D53E
1D540 1D544
1D546
1D54A 1D550
1D552 1D6A5
1D6A8 1D6C0
1D6C2 1D6DA
1D6DC 1D6FA
1D6FC 1D714
1D716 1D734
1D736 1D74E
1D750 1D76E
1D770 1D788
1D78A 1D7A8
1D7AA 1D7C2
1D7C4 1D7CB
20000 2A6D6
2F800 2FA1D
END
| jondo/paperpile | plack/perl5/linux64/base/unicore/lib/gc_sc/L.pl | Perl | agpl-3.0 | 4,050 |
/*
* This file is part of CoAnSys project.
* Copyright (c) 2012-2015 ICM-UW
*
* CoAnSys 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.
* CoAnSys 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 CoAnSys. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.coansys.disambiguation.author.pig.merger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataByteArray;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.apache.pig.tools.pigstats.PigStatusReporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.edu.icm.coansys.commons.java.DiacriticsRemover;
import pl.edu.icm.coansys.commons.java.StackTraceExtractor;
import pl.edu.icm.coansys.models.DocumentProtos.Author;
import pl.edu.icm.coansys.models.DocumentProtos.BasicMetadata;
import pl.edu.icm.coansys.models.DocumentProtos.DocumentMetadata;
import pl.edu.icm.coansys.models.DocumentProtos.DocumentWrapper;
import pl.edu.icm.coansys.models.DocumentProtos.KeyValue;
/**
*
* @author pdendek
*/
public class MergeDocumentWithOrcid extends EvalFunc<Tuple> {
PigStatusReporter myPigStatusReporter;
private static final Logger logger = LoggerFactory
.getLogger(MergeDocumentWithOrcid.class);
@Override
public Schema outputSchema(Schema p_input) {
try {
return Schema.generateNestedSchema(DataType.TUPLE,
DataType.CHARARRAY, DataType.BYTEARRAY);
} catch (FrontendException e) {
logger.error("Error in creating output schema:", e);
throw new IllegalStateException(e);
}
}
@Override
public Tuple exec(Tuple input) throws IOException {
if (input == null || input.size() != 3) {
return null;
}
try {
myPigStatusReporter = PigStatusReporter.getInstance();
//load input tuple
////doi
String docId = (String) input.get(0);
////normal document
DataByteArray dbaD = (DataByteArray) input.get(1);
////orcid document
DataByteArray dbaO = (DataByteArray) input.get(2);
//load input documents
DocumentWrapper dwD = DocumentWrapper.parseFrom(dbaD.get());
List<Author> aDL = dwD.getDocumentMetadata().getBasicMetadata().getAuthorList();
DocumentWrapper dwO = DocumentWrapper.parseFrom(dbaO.get());
List<Author> aOL = dwO.getDocumentMetadata().getBasicMetadata().getAuthorList();
//calculate merged author list
List<Author> aRL = matchAuthors(docId,aDL,aOL);
//construct resulting document
BasicMetadata.Builder bmR = BasicMetadata.newBuilder(DocumentWrapper.newBuilder(dwD).getDocumentMetadata().getBasicMetadata());
bmR.clearAuthor();
bmR.addAllAuthor(aRL);
DocumentMetadata.Builder dmR = DocumentMetadata.newBuilder(DocumentWrapper.newBuilder(dwD).getDocumentMetadata());
dmR.setBasicMetadata(bmR);
DocumentWrapper.Builder dwR = DocumentWrapper.newBuilder(dwD);
dwR.setDocumentMetadata(dmR);
//construct resulting tuple
Tuple result = TupleFactory.getInstance().newTuple();
result.append(docId);
result.append(new DataByteArray(dwR.build().toByteArray()));
return result;
} catch (Exception e) {
logger.error("Error in processing input row:", e);
throw new IOException("Caught exception processing input row:\n"
+ StackTraceExtractor.getStackTrace(e));
}
}
protected List<Author> matchAuthors(String docId, List<Author> base,
List<Author> second) {
List<Author> result = new ArrayList<Author>(base.size());
List<Author> secondCopy = new ArrayList<Author>(second);
boolean changedBln = false;
int changedInt = 0;
logger.error("-------------------------------------------");
logger.error("number of base authors: "+base.size()+"\tnumber of orcid authors");
for (Author author : base) {
Author foundAuthor = null;
for (Author secondAuthor : secondCopy) {
if (
equalsIgnoreCaseIgnoreDiacritics(author.getName(), secondAuthor.getName())
||
//equalsIgnoreCaseIgnoreDiacritics(author.getForenames(), secondAuthor.getForenames()) &&
equalsIgnoreCaseIgnoreDiacritics(author.getSurname(), secondAuthor.getSurname())
){
foundAuthor = secondAuthor;
break;
}
}
if (foundAuthor != null) {
result.add(merge(author,foundAuthor));
changedBln = true;
changedInt++;
if(myPigStatusReporter != null){
Counter c = myPigStatusReporter.getCounter("ORCID Enhancement", "Author Enhanced");
if(c!=null){
c.increment(1);
}
}
} else {
result.add(Author.newBuilder(author).build());
}
}
if(changedBln){
logger.info("------------------------------------------");
logger.info("Changed docId:"+docId);
if(myPigStatusReporter != null){
Counter c = myPigStatusReporter.getCounter("ORCID Enhancement", "Document Enhanced");
if(c!=null){
c.increment(1);
}
}
}
logger.error("number of intersections: "+changedInt);
return result;
}
private Author merge(Author author, Author foundAuthor) {
Author.Builder builder = Author.newBuilder(author);
for(KeyValue kv : foundAuthor.getExtIdList()){
if("orcid-author-id".equals(kv.getKey())){
KeyValue.Builder kvb = KeyValue.newBuilder();
kvb.setKey(kv.getKey());
kvb.setValue(kv.getValue());
builder.addExtId(kvb.build());
logger.info("<k:"+kv.getKey()+"; v:"+kv.getValue()+">");
logger.info("<kc:"+kvb.getKey()+"; vc:"+kvb.getValue()+">");
}
}
Author ret = builder.build();
logger.info("<auth:"+ret.toString()+">");
return ret;
}
private boolean equalsIgnoreCaseIgnoreDiacritics(String firstName,
String secondName) {
if (firstName.isEmpty() || secondName.isEmpty()) {
return false;
}
return DiacriticsRemover.removeDiacritics(firstName).equalsIgnoreCase(
DiacriticsRemover.removeDiacritics(secondName));
}
}
| acz-icm/coansys | disambiguation-author/disambiguation-author-logic/src/main/java/pl/edu/icm/coansys/disambiguation/author/pig/merger/MergeDocumentWithOrcid.java | Java | agpl-3.0 | 6,921 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2007-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.web.command;
/**
* Command object for listing a specific statistics report. This object deserializes query params
* for a specific report, identified by integer ID.
*
* @author <a href="mailto:dj@opennms.org">DJ Gregor</a>
* @version $Id: $
* @since 1.8.1
*/
public class StatisticsReportCommand {
private Integer m_id;
/**
* <p>getId</p>
*
* @return a {@link java.lang.Integer} object.
*/
public Integer getId() {
return m_id;
}
/**
* <p>setId</p>
*
* @param id a {@link java.lang.Integer} object.
*/
public void setId(Integer id) {
m_id = id;
}
}
| roskens/opennms-pre-github | opennms-webapp/src/main/java/org/opennms/web/command/StatisticsReportCommand.java | Java | agpl-3.0 | 1,870 |
// Copyright 2020 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package azuretesting
import (
"encoding/json"
"reflect"
)
// JsonMarshalRaw does the same a json.Marshal, except that it does not
// use the MarshalJSON methods of the value being marshaled. If any types
// are specified in the allow set then those will use their MarshalJSON
// method.
//
// Many of the types in the Azure SDK have MarshalJSON which skip over
// fields that are marked as READ-ONLY, this is useful for the client,
// but a problem when pretending to be a server.
func JsonMarshalRaw(v interface{}, allow ...reflect.Type) ([]byte, error) {
allowed := make(map[reflect.Type]bool, len(allow))
for _, a := range allow {
allowed[a] = true
}
if v != nil {
v = rawValueMaker{allowed}.rawValue(reflect.ValueOf(v)).Interface()
}
return json.Marshal(v)
}
type rawValueMaker struct {
allowed map[reflect.Type]bool
}
func (m rawValueMaker) rawValue(v reflect.Value) reflect.Value {
t := v.Type()
if m.allowed[t] {
return v
}
switch t.Kind() {
case reflect.Ptr:
return m.rawPointerValue(v)
case reflect.Struct:
return m.rawStructValue(v)
case reflect.Map:
return m.rawMapValue(v)
case reflect.Slice:
return m.rawSliceValue(v)
default:
return v
}
}
func (m rawValueMaker) rawPointerValue(v reflect.Value) reflect.Value {
if v.IsNil() {
return v
}
rv := m.rawValue(v.Elem())
if rv.CanAddr() {
return rv.Addr()
}
pv := reflect.New(rv.Type())
pv.Elem().Set(rv)
return pv
}
func (m rawValueMaker) rawStructValue(v reflect.Value) reflect.Value {
t := v.Type()
fields := make([]reflect.StructField, 0, t.NumField())
values := make([]reflect.Value, 0, t.NumField())
for i := 0; i < t.NumField(); i++ {
sf := t.Field(i)
if sf.PkgPath != "" || sf.Tag.Get("json") == "-" {
// Skip fields that won't ever be marshaled.
continue
}
if tag, ok := sf.Tag.Lookup("json"); ok && tag == "" {
// Also skip fields with a present, but empty, json tag.
continue
}
rv := m.rawValue(v.Field(i))
sf.Type = rv.Type()
sf.Anonymous = false
fields = append(fields, sf)
values = append(values, rv)
}
newT := reflect.StructOf(fields)
newV := reflect.New(newT).Elem()
for i, v := range values {
newV.Field(i).Set(v)
}
return newV
}
var interfaceType = reflect.TypeOf((*interface{})(nil)).Elem()
func (m rawValueMaker) rawMapValue(v reflect.Value) reflect.Value {
newV := reflect.MakeMap(reflect.MapOf(v.Type().Key(), interfaceType))
for _, key := range v.MapKeys() {
value := v.MapIndex(key)
newV.SetMapIndex(key, m.rawValue(value))
}
return newV
}
func (m rawValueMaker) rawSliceValue(v reflect.Value) reflect.Value {
newV := reflect.MakeSlice(reflect.SliceOf(interfaceType), v.Len(), v.Len())
for i := 0; i < v.Len(); i++ {
newV.Index(i).Set(m.rawValue(v.Index(i)))
}
return newV
}
| freyes/juju | provider/azure/internal/azuretesting/json.go | GO | agpl-3.0 | 2,870 |
#pragma checksum "C:\Users\agomez.ETIC\Documents\Visual Studio 2013\Projects\Edatalia_signplyRT\Edatalia_signplyRT\ServiceContractPage.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "24BB41AB0CC87304CC4E51704C814814"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Edatalia_signplyRT
{
partial class ServiceContractPage : global::Windows.UI.Xaml.Controls.Page
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
private global::Windows.UI.Xaml.Controls.Page pageRoot;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
private global::Windows.UI.Xaml.Controls.StackPanel spContractData;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
private global::Windows.UI.Xaml.Controls.DatePicker dtPicker;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
private global::Windows.UI.Xaml.Controls.TextBox tbImporte;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
private global::Windows.UI.Xaml.Controls.Button backButton;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
private global::Windows.UI.Xaml.Controls.TextBlock pageTitle;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
private global::Windows.UI.Xaml.Controls.Image imgTittle;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
private global::Windows.UI.Xaml.Controls.AppBar bottomAppBar;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
private global::Windows.UI.Xaml.Controls.AppBarButton appbtnOpen;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
private global::Windows.UI.Xaml.Controls.AppBarButton appbtnCancel;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
private bool _contentLoaded;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent()
{
if (_contentLoaded)
return;
_contentLoaded = true;
global::Windows.UI.Xaml.Application.LoadComponent(this, new global::System.Uri("ms-appx:///ServiceContractPage.xaml"), global::Windows.UI.Xaml.Controls.Primitives.ComponentResourceLocation.Application);
pageRoot = (global::Windows.UI.Xaml.Controls.Page)this.FindName("pageRoot");
spContractData = (global::Windows.UI.Xaml.Controls.StackPanel)this.FindName("spContractData");
dtPicker = (global::Windows.UI.Xaml.Controls.DatePicker)this.FindName("dtPicker");
tbImporte = (global::Windows.UI.Xaml.Controls.TextBox)this.FindName("tbImporte");
backButton = (global::Windows.UI.Xaml.Controls.Button)this.FindName("backButton");
pageTitle = (global::Windows.UI.Xaml.Controls.TextBlock)this.FindName("pageTitle");
imgTittle = (global::Windows.UI.Xaml.Controls.Image)this.FindName("imgTittle");
bottomAppBar = (global::Windows.UI.Xaml.Controls.AppBar)this.FindName("bottomAppBar");
appbtnOpen = (global::Windows.UI.Xaml.Controls.AppBarButton)this.FindName("appbtnOpen");
appbtnCancel = (global::Windows.UI.Xaml.Controls.AppBarButton)this.FindName("appbtnCancel");
}
}
}
| edatalia/edatalia_eContrato | obj/x86/Release/ServiceContractPage.g.i.cs | C# | agpl-3.0 | 4,272 |
<?php
/*********************************************************************************
* TimeTrex is a Payroll and Time Management program developed by
* TimeTrex Software Inc. Copyright (C) 2003 - 2014 TimeTrex Software Inc.
*
* 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 TIMETREX, TIMETREX 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 TimeTrex headquarters at Unit 22 - 2475 Dobbin Rd. Suite
* #292 Westbank, BC V4T 2E9, Canada or at email address info@timetrex.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 TimeTrex" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by TimeTrex".
********************************************************************************/
/**
* @package API\Accrual
*/
class APIAccrualBalance extends APIFactory {
protected $main_class = 'AccrualBalanceFactory';
public function __construct() {
parent::__construct(); //Make sure parent constructor is always called.
return TRUE;
}
/**
* Get options for dropdown boxes.
* @param string $name Name of options to return, ie: 'columns', 'type', 'status'
* @param mixed $parent Parent name/ID of options to return if data is in hierarchical format. (ie: Province)
* @return array
*/
function getOptions( $name, $parent = NULL ) {
if ( $name == 'columns'
AND ( !$this->getPermissionObject()->Check('accrual', 'enabled')
OR !( $this->getPermissionObject()->Check('accrual', 'view') OR $this->getPermissionObject()->Check('accrual', 'view_child') ) ) ) {
$name = 'list_columns';
}
return parent::getOptions( $name, $parent );
}
/**
* Get accrual balance data for one or more accrual balancees.
* @param array $data filter data
* @return array
*/
function getAccrualBalance( $data = NULL, $disable_paging = FALSE ) {
if ( !$this->getPermissionObject()->Check('accrual', 'enabled')
OR !( $this->getPermissionObject()->Check('accrual', 'view') OR $this->getPermissionObject()->Check('accrual', 'view_own') OR $this->getPermissionObject()->Check('accrual', 'view_child') ) ) {
return $this->getPermissionObject()->PermissionDenied();
}
$data = $this->initializeFilterAndPager( $data, $disable_paging );
$data['filter_data']['permission_children_ids'] = $this->getPermissionObject()->getPermissionChildren( 'accrual', 'view' );
$blf = TTnew( 'AccrualBalanceListFactory' );
$blf->getAPISearchByCompanyIdAndArrayCriteria( $this->getCurrentCompanyObject()->getId(), $data['filter_data'], $data['filter_items_per_page'], $data['filter_page'], NULL, $data['filter_sort'] );
Debug::Text('Record Count: '. $blf->getRecordCount(), __FILE__, __LINE__, __METHOD__, 10);
if ( $blf->getRecordCount() > 0 ) {
$this->getProgressBarObject()->start( $this->getAMFMessageID(), $blf->getRecordCount() );
$this->setPagerObject( $blf );
foreach( $blf as $b_obj ) {
$retarr[] = $b_obj->getObjectAsArray( $data['filter_columns'], $data['filter_data']['permission_children_ids'] );
$this->getProgressBarObject()->set( $this->getAMFMessageID(), $blf->getCurrentRow() );
}
$this->getProgressBarObject()->stop( $this->getAMFMessageID() );
return $this->returnHandler( $retarr );
}
return $this->returnHandler( TRUE ); //No records returned.
}
}
?>
| BrunoChauvet/timetrex | classes/modules/api/accrual/APIAccrualBalance.class.php | PHP | agpl-3.0 | 4,549 |
Clazz.declarePackage ("org.jmol.shapespecial");
Clazz.load (["org.jmol.shape.AtomShape", "org.jmol.atomdata.RadiusData", "org.jmol.util.BitSet"], "org.jmol.shapespecial.Dots", ["java.util.Hashtable", "org.jmol.constant.EnumVdw", "org.jmol.geodesic.EnvelopeCalculation", "org.jmol.util.BitSetUtil", "$.Colix", "$.Escape", "$.Logger", "$.Matrix3f", "$.StringXBuilder"], function () {
c$ = Clazz.decorateAsClass (function () {
this.ec = null;
this.isSurface = false;
this.bsOn = null;
this.bsSelected = null;
this.bsIgnore = null;
this.thisAtom = 0;
this.thisRadius = 0;
this.thisArgb = 0;
this.rdLast = null;
Clazz.instantialize (this, arguments);
}, org.jmol.shapespecial, "Dots", org.jmol.shape.AtomShape);
Clazz.prepareFields (c$, function () {
this.bsOn = new org.jmol.util.BitSet ();
this.rdLast = new org.jmol.atomdata.RadiusData (null, 0, null, null);
});
Clazz.defineMethod (c$, "initShape",
function () {
Clazz.superCall (this, org.jmol.shapespecial.Dots, "initShape", []);
this.translucentAllowed = false;
this.ec = new org.jmol.geodesic.EnvelopeCalculation (this.viewer, this.atomCount, this.mads);
});
Clazz.defineMethod (c$, "getSize",
function (atomIndex) {
return (this.mads == null ? Clazz.doubleToInt (Math.floor (this.ec.getRadius (atomIndex) * 2000)) : this.mads[atomIndex] * 2);
}, "~N");
Clazz.defineMethod (c$, "setProperty",
function (propertyName, value, bs) {
if ("init" === propertyName) {
this.initialize ();
return;
}if ("translucency" === propertyName) {
if (!this.translucentAllowed) return;
}if ("ignore" === propertyName) {
this.bsIgnore = value;
return;
}if ("select" === propertyName) {
this.bsSelected = value;
return;
}if ("radius" === propertyName) {
this.thisRadius = (value).floatValue ();
if (this.thisRadius > 16) this.thisRadius = 16;
return;
}if ("colorRGB" === propertyName) {
this.thisArgb = (value).intValue ();
return;
}if ("atom" === propertyName) {
this.thisAtom = (value).intValue ();
if (this.thisAtom >= this.atoms.length) return;
this.atoms[this.thisAtom].setShapeVisibility (this.myVisibilityFlag, true);
this.ec.allocDotsConvexMaps (this.atomCount);
return;
}if ("dots" === propertyName) {
if (this.thisAtom >= this.atoms.length) return;
this.isActive = true;
this.ec.setFromBits (this.thisAtom, value);
this.atoms[this.thisAtom].setShapeVisibility (this.myVisibilityFlag, true);
if (this.mads == null) {
this.ec.setMads (null);
this.mads = Clazz.newShortArray (this.atomCount, 0);
for (var i = 0; i < this.atomCount; i++) if (this.atoms[i].isInFrame () && this.atoms[i].isShapeVisible (this.myVisibilityFlag)) try {
this.mads[i] = Clazz.floatToShort (this.ec.getAppropriateRadius (i) * 1000);
} catch (e) {
if (Clazz.exceptionOf (e, Exception)) {
} else {
throw e;
}
}
this.ec.setMads (this.mads);
}this.mads[this.thisAtom] = Clazz.floatToShort (this.thisRadius * 1000);
if (this.colixes == null) {
this.colixes = Clazz.newShortArray (this.atomCount, 0);
this.paletteIDs = Clazz.newByteArray (this.atomCount, 0);
}this.colixes[this.thisAtom] = org.jmol.util.Colix.getColix (this.thisArgb);
this.bsOn.set (this.thisAtom);
return;
}if ("refreshTrajectories" === propertyName) {
bs = (value)[1];
var m4 = (value)[2];
if (m4 == null) return;
var m = new org.jmol.util.Matrix3f ();
m4.getRotationScale (m);
this.ec.reCalculate (bs, m);
return;
}if (propertyName === "deleteModelAtoms") {
var firstAtomDeleted = ((value)[2])[1];
var nAtomsDeleted = ((value)[2])[2];
org.jmol.util.BitSetUtil.deleteBits (this.bsOn, bs);
this.ec.deleteAtoms (firstAtomDeleted, nAtomsDeleted);
}Clazz.superCall (this, org.jmol.shapespecial.Dots, "setProperty", [propertyName, value, bs]);
}, "~S,~O,org.jmol.util.BitSet");
Clazz.defineMethod (c$, "initialize",
function () {
this.bsSelected = null;
this.bsIgnore = null;
this.isActive = false;
if (this.ec == null) this.ec = new org.jmol.geodesic.EnvelopeCalculation (this.viewer, this.atomCount, this.mads);
});
Clazz.overrideMethod (c$, "setSizeRD",
function (rd, bsSelected) {
if (rd == null) rd = new org.jmol.atomdata.RadiusData (null, 0, org.jmol.atomdata.RadiusData.EnumType.ABSOLUTE, null);
if (this.bsSelected != null) bsSelected = this.bsSelected;
if (org.jmol.util.Logger.debugging) {
org.jmol.util.Logger.debug ("Dots.setSize " + rd.value);
}var isVisible = true;
var setRadius = 3.4028235E38;
this.isActive = true;
switch (rd.factorType) {
case org.jmol.atomdata.RadiusData.EnumType.OFFSET:
break;
case org.jmol.atomdata.RadiusData.EnumType.ABSOLUTE:
if (rd.value == 0) isVisible = false;
setRadius = rd.value;
default:
rd.valueExtended = this.viewer.getCurrentSolventProbeRadius ();
}
var maxRadius;
switch (rd.vdwType) {
case org.jmol.constant.EnumVdw.ADPMIN:
case org.jmol.constant.EnumVdw.ADPMAX:
case org.jmol.constant.EnumVdw.HYDRO:
case org.jmol.constant.EnumVdw.TEMP:
maxRadius = setRadius;
break;
case org.jmol.constant.EnumVdw.IONIC:
maxRadius = this.modelSet.getMaxVanderwaalsRadius () * 2;
break;
default:
maxRadius = this.modelSet.getMaxVanderwaalsRadius ();
}
var newSet = (this.rdLast.value != rd.value || this.rdLast.valueExtended != rd.valueExtended || this.rdLast.factorType !== rd.factorType || this.rdLast.vdwType !== rd.vdwType || this.ec.getDotsConvexMax () == 0);
if (isVisible) {
for (var i = bsSelected.nextSetBit (0); i >= 0; i = bsSelected.nextSetBit (i + 1)) if (!this.bsOn.get (i)) {
this.bsOn.set (i);
newSet = true;
}
} else {
var isAll = (bsSelected == null);
var i0 = (isAll ? this.atomCount - 1 : bsSelected.nextSetBit (0));
for (var i = i0; i >= 0; i = (isAll ? i - 1 : bsSelected.nextSetBit (i + 1))) this.bsOn.setBitTo (i, false);
}for (var i = this.atomCount; --i >= 0; ) {
this.atoms[i].setShapeVisibility (this.myVisibilityFlag, this.bsOn.get (i));
}
if (!isVisible) return;
if (newSet) {
this.mads = null;
this.ec.newSet ();
}var dotsConvexMaps = this.ec.getDotsConvexMaps ();
if (dotsConvexMaps != null) {
for (var i = this.atomCount; --i >= 0; ) if (this.bsOn.get (i)) {
dotsConvexMaps[i] = null;
}
}if (dotsConvexMaps == null) {
this.colixes = Clazz.newShortArray (this.atomCount, 0);
this.paletteIDs = Clazz.newByteArray (this.atomCount, 0);
}this.ec.calculate (rd, maxRadius, this.bsOn, this.bsIgnore, !this.viewer.getDotSurfaceFlag (), this.viewer.getDotsSelectedOnlyFlag (), this.isSurface, true);
this.rdLast = rd;
}, "org.jmol.atomdata.RadiusData,org.jmol.util.BitSet");
Clazz.overrideMethod (c$, "setModelClickability",
function () {
for (var i = this.atomCount; --i >= 0; ) {
var atom = this.atoms[i];
if ((atom.getShapeVisibilityFlags () & this.myVisibilityFlag) == 0 || this.modelSet.isAtomHidden (i)) continue;
atom.setClickable (this.myVisibilityFlag);
}
});
Clazz.overrideMethod (c$, "getShapeState",
function () {
var dotsConvexMaps = this.ec.getDotsConvexMaps ();
if (dotsConvexMaps == null || this.ec.getDotsConvexMax () == 0) return "";
var s = new org.jmol.util.StringXBuilder ();
var temp = new java.util.Hashtable ();
var atomCount = this.viewer.getAtomCount ();
var type = (this.isSurface ? "geoSurface " : "dots ");
for (var i = 0; i < atomCount; i++) {
if (!this.bsOn.get (i) || dotsConvexMaps[i] == null) continue;
if (this.bsColixSet != null && this.bsColixSet.get (i)) org.jmol.shape.Shape.setStateInfo (temp, i, this.getColorCommand (type, this.paletteIDs[i], this.colixes[i]));
var bs = dotsConvexMaps[i];
if (!bs.isEmpty ()) {
var r = this.ec.getAppropriateRadius (i);
org.jmol.shape.Shape.appendCmd (s, type + i + " radius " + r + " " + org.jmol.util.Escape.escape (bs));
}}
s.append (org.jmol.shape.Shape.getShapeCommands (temp, null));
return s.toString ();
});
Clazz.defineStatics (c$,
"SURFACE_DISTANCE_FOR_CALCULATION", 10,
"MAX_LEVEL", 3);
});
| ksripathi/edx-demo-course | static/jsmol/j2s/org/jmol/shapespecial/Dots.js | JavaScript | agpl-3.0 | 7,637 |
import re
import uuid
from xmodule.assetstore.assetmgr import AssetManager
XASSET_LOCATION_TAG = 'c4x'
XASSET_SRCREF_PREFIX = 'xasset:'
XASSET_THUMBNAIL_TAIL_NAME = '.jpg'
STREAM_DATA_CHUNK_SIZE = 1024
import os
import logging
import StringIO
from urlparse import urlparse, urlunparse, parse_qsl
from urllib import urlencode
from opaque_keys.edx.locator import AssetLocator
from opaque_keys.edx.keys import CourseKey, AssetKey
from opaque_keys import InvalidKeyError
from xmodule.modulestore.exceptions import ItemNotFoundError
from xmodule.exceptions import NotFoundError
from PIL import Image
class StaticContent(object):
def __init__(self, loc, name, content_type, data, last_modified_at=None, thumbnail_location=None, import_path=None,
length=None, locked=False):
self.location = loc
self.name = name # a display string which can be edited, and thus not part of the location which needs to be fixed
self.content_type = content_type
self._data = data
self.length = length
self.last_modified_at = last_modified_at
self.thumbnail_location = thumbnail_location
# optional information about where this file was imported from. This is needed to support import/export
# cycles
self.import_path = import_path
self.locked = locked
@property
def is_thumbnail(self):
return self.location.category == 'thumbnail'
@staticmethod
def generate_thumbnail_name(original_name, dimensions=None):
"""
- original_name: Name of the asset (typically its location.name)
- dimensions: `None` or a tuple of (width, height) in pixels
"""
name_root, ext = os.path.splitext(original_name)
if not ext == XASSET_THUMBNAIL_TAIL_NAME:
name_root = name_root + ext.replace(u'.', u'-')
if dimensions:
width, height = dimensions # pylint: disable=unpacking-non-sequence
name_root += "-{}x{}".format(width, height)
return u"{name_root}{extension}".format(
name_root=name_root,
extension=XASSET_THUMBNAIL_TAIL_NAME,
)
@staticmethod
def compute_location(course_key, path, revision=None, is_thumbnail=False):
"""
Constructs a location object for static content.
- course_key: the course that this asset belongs to
- path: is the name of the static asset
- revision: is the object's revision information
- is_thumbnail: is whether or not we want the thumbnail version of this
asset
"""
path = path.replace('/', '_')
return course_key.make_asset_key(
'asset' if not is_thumbnail else 'thumbnail',
AssetLocator.clean_keeping_underscores(path)
).for_branch(None)
def get_id(self):
return self.location
@property
def data(self):
return self._data
ASSET_URL_RE = re.compile(r"""
/?c4x/
(?P<org>[^/]+)/
(?P<course>[^/]+)/
(?P<category>[^/]+)/
(?P<name>[^/]+)
""", re.VERBOSE | re.IGNORECASE)
@staticmethod
def is_c4x_path(path_string):
"""
Returns a boolean if a path is believed to be a c4x link based on the leading element
"""
return StaticContent.ASSET_URL_RE.match(path_string) is not None
@staticmethod
def get_static_path_from_location(location):
"""
This utility static method will take a location identifier and create a 'durable' /static/.. URL representation of it.
This link is 'durable' as it can maintain integrity across cloning of courseware across course-ids, e.g. reruns of
courses.
In the LMS/CMS, we have runtime link-rewriting, so at render time, this /static/... format will get translated into
the actual /c4x/... path which the client needs to reference static content
"""
if location is not None:
return u"/static/{name}".format(name=location.name)
else:
return None
@staticmethod
def get_base_url_path_for_course_assets(course_key):
if course_key is None:
return None
assert isinstance(course_key, CourseKey)
placeholder_id = uuid.uuid4().hex
# create a dummy asset location with a fake but unique name. strip off the name, and return it
url_path = StaticContent.serialize_asset_key_with_slash(
course_key.make_asset_key('asset', placeholder_id).for_branch(None)
)
return url_path.replace(placeholder_id, '')
@staticmethod
def get_location_from_path(path):
"""
Generate an AssetKey for the given path (old c4x/org/course/asset/name syntax)
"""
try:
return AssetKey.from_string(path)
except InvalidKeyError:
# TODO - re-address this once LMS-11198 is tackled.
if path.startswith('/'):
# try stripping off the leading slash and try again
return AssetKey.from_string(path[1:])
@staticmethod
def get_asset_key_from_path(course_key, path):
"""
Parses a path, extracting an asset key or creating one.
Args:
course_key: key to the course which owns this asset
path: the path to said content
Returns:
AssetKey: the asset key that represents the path
"""
# Clean up the path, removing any static prefix and any leading slash.
if path.startswith('/static/'):
path = path[len('/static/'):]
path = path.lstrip('/')
try:
return AssetKey.from_string(path)
except InvalidKeyError:
# If we couldn't parse the path, just let compute_location figure it out.
# It's most likely a path like /image.png or something.
return StaticContent.compute_location(course_key, path)
@staticmethod
def get_canonicalized_asset_path(course_key, path, base_url):
"""
Returns a fully-qualified path to a piece of static content.
If a static asset CDN is configured, this path will include it.
Otherwise, the path will simply be relative.
Args:
course_key: key to the course which owns this asset
path: the path to said content
Returns:
string: fully-qualified path to asset
"""
# Break down the input path.
_, _, relative_path, params, query_string, fragment = urlparse(path)
# Convert our path to an asset key if it isn't one already.
asset_key = StaticContent.get_asset_key_from_path(course_key, relative_path)
# Check the status of the asset to see if this can be served via CDN aka publicly.
serve_from_cdn = False
try:
content = AssetManager.find(asset_key, as_stream=True)
is_locked = getattr(content, "locked", True)
serve_from_cdn = not is_locked
except (ItemNotFoundError, NotFoundError):
# If we can't find the item, just treat it as if it's locked.
serve_from_cdn = False
# Update any query parameter values that have asset paths in them. This is for assets that
# require their own after-the-fact values, like a Flash file that needs the path of a config
# file passed to it e.g. /static/visualization.swf?configFile=/static/visualization.xml
query_params = parse_qsl(query_string)
updated_query_params = []
for query_name, query_value in query_params:
if query_value.startswith("/static/"):
new_query_value = StaticContent.get_canonicalized_asset_path(course_key, query_value, base_url)
updated_query_params.append((query_name, new_query_value))
else:
updated_query_params.append((query_name, query_value))
serialized_asset_key = StaticContent.serialize_asset_key_with_slash(asset_key)
base_url = base_url if serve_from_cdn else ''
return urlunparse((None, base_url, serialized_asset_key, params, urlencode(updated_query_params), fragment))
def stream_data(self):
yield self._data
@staticmethod
def serialize_asset_key_with_slash(asset_key):
"""
Legacy code expects the serialized asset key to start w/ a slash; so, do that in one place
:param asset_key:
"""
url = unicode(asset_key)
if not url.startswith('/'):
url = '/' + url # TODO - re-address this once LMS-11198 is tackled.
return url
class StaticContentStream(StaticContent):
def __init__(self, loc, name, content_type, stream, last_modified_at=None, thumbnail_location=None, import_path=None,
length=None, locked=False):
super(StaticContentStream, self).__init__(loc, name, content_type, None, last_modified_at=last_modified_at,
thumbnail_location=thumbnail_location, import_path=import_path,
length=length, locked=locked)
self._stream = stream
def stream_data(self):
while True:
chunk = self._stream.read(STREAM_DATA_CHUNK_SIZE)
if len(chunk) == 0:
break
yield chunk
def stream_data_in_range(self, first_byte, last_byte):
"""
Stream the data between first_byte and last_byte (included)
"""
self._stream.seek(first_byte)
position = first_byte
while True:
if last_byte < position + STREAM_DATA_CHUNK_SIZE - 1:
chunk = self._stream.read(last_byte - position + 1)
yield chunk
break
chunk = self._stream.read(STREAM_DATA_CHUNK_SIZE)
position += STREAM_DATA_CHUNK_SIZE
yield chunk
def close(self):
self._stream.close()
def copy_to_in_mem(self):
self._stream.seek(0)
content = StaticContent(self.location, self.name, self.content_type, self._stream.read(),
last_modified_at=self.last_modified_at, thumbnail_location=self.thumbnail_location,
import_path=self.import_path, length=self.length, locked=self.locked)
return content
class ContentStore(object):
'''
Abstraction for all ContentStore providers (e.g. MongoDB)
'''
def save(self, content):
raise NotImplementedError
def find(self, filename):
raise NotImplementedError
def get_all_content_for_course(self, course_key, start=0, maxresults=-1, sort=None, filter_params=None):
'''
Returns a list of static assets for a course, followed by the total number of assets.
By default all assets are returned, but start and maxresults can be provided to limit the query.
The return format is a list of asset data dictionaries.
The asset data dictionaries have the following keys:
asset_key (:class:`opaque_keys.edx.AssetKey`): The key of the asset
displayname: The human-readable name of the asset
uploadDate (datetime.datetime): The date and time that the file was uploadDate
contentType: The mimetype string of the asset
md5: An md5 hash of the asset content
'''
raise NotImplementedError
def delete_all_course_assets(self, course_key):
"""
Delete all of the assets which use this course_key as an identifier
:param course_key:
"""
raise NotImplementedError
def copy_all_course_assets(self, source_course_key, dest_course_key):
"""
Copy all the course assets from source_course_key to dest_course_key
"""
raise NotImplementedError
def generate_thumbnail(self, content, tempfile_path=None, dimensions=None):
"""Create a thumbnail for a given image.
Returns a tuple of (StaticContent, AssetKey)
`content` is the StaticContent representing the image you want to make a
thumbnail out of.
`tempfile_path` is a string path to the location of a file to read from
in order to grab the image data, instead of relying on `content.data`
`dimensions` is an optional param that represents (width, height) in
pixels. It defaults to None.
"""
thumbnail_content = None
# use a naming convention to associate originals with the thumbnail
thumbnail_name = StaticContent.generate_thumbnail_name(
content.location.name, dimensions=dimensions
)
thumbnail_file_location = StaticContent.compute_location(
content.location.course_key, thumbnail_name, is_thumbnail=True
)
# if we're uploading an image, then let's generate a thumbnail so that we can
# serve it up when needed without having to rescale on the fly
if content.content_type is not None and content.content_type.split('/')[0] == 'image':
try:
# use PIL to do the thumbnail generation (http://www.pythonware.com/products/pil/)
# My understanding is that PIL will maintain aspect ratios while restricting
# the max-height/width to be whatever you pass in as 'size'
# @todo: move the thumbnail size to a configuration setting?!?
if tempfile_path is None:
im = Image.open(StringIO.StringIO(content.data))
else:
im = Image.open(tempfile_path)
# I've seen some exceptions from the PIL library when trying to save palletted
# PNG files to JPEG. Per the google-universe, they suggest converting to RGB first.
im = im.convert('RGB')
if not dimensions:
dimensions = (128, 128)
im.thumbnail(dimensions, Image.ANTIALIAS)
thumbnail_file = StringIO.StringIO()
im.save(thumbnail_file, 'JPEG')
thumbnail_file.seek(0)
# store this thumbnail as any other piece of content
thumbnail_content = StaticContent(thumbnail_file_location, thumbnail_name,
'image/jpeg', thumbnail_file)
self.save(thumbnail_content)
except Exception, e:
# log and continue as thumbnails are generally considered as optional
logging.exception(u"Failed to generate thumbnail for {0}. Exception: {1}".format(content.location, str(e)))
return thumbnail_content, thumbnail_file_location
def ensure_indexes(self):
"""
Ensure that all appropriate indexes are created that are needed by this modulestore, or raise
an exception if unable to.
"""
pass
| MakeHer/edx-platform | common/lib/xmodule/xmodule/contentstore/content.py | Python | agpl-3.0 | 14,964 |
<?php
/*
* 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Query\AST;
/**
* JoinVariableDeclaration ::= Join [IndexBy]
*
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link www.doctrine-project.org
* @since 2.5
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
*/
class JoinVariableDeclaration extends Node
{
/**
* @var Join
*/
public $join;
/**
* @var IndexBy|null
*/
public $indexBy;
/**
* Constructor.
*
* @param Join $join
* @param IndexBy|null $indexBy
*/
public function __construct($join, $indexBy)
{
$this->join = $join;
$this->indexBy = $indexBy;
}
/**
* {@inheritdoc}
*/
public function dispatch($walker)
{
return $walker->walkJoinVariableDeclaration($this);
}
}
| hannesk001/SPHERE-Framework | Library/MOC-V/Component/Database/Vendor/Doctrine2ORM/2.5.0/lib/Doctrine/ORM/Query/AST/JoinVariableDeclaration.php | PHP | agpl-3.0 | 1,810 |
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
import Point from './Point.js';
import U from './Utilities.js';
var seriesType = U.seriesType;
var seriesTypes = H.seriesTypes;
/**
* The ohlc series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.ohlc
*
* @augments Highcharts.Series
*/
seriesType('ohlc', 'column'
/**
* An OHLC chart is a style of financial chart used to describe price
* movements over time. It displays open, high, low and close values per
* data point.
*
* @sample stock/demo/ohlc/
* OHLC chart
*
* @extends plotOptions.column
* @excluding borderColor, borderRadius, borderWidth, crisp, stacking,
* stack
* @product highstock
* @optionparent plotOptions.ohlc
*/
, {
/**
* The approximate pixel width of each group. If for example a series
* with 30 points is displayed over a 600 pixel wide plot area, no
* grouping is performed. If however the series contains so many points
* that the spacing is less than the groupPixelWidth, Highcharts will
* try to group it into appropriate groups so that each is more or less
* two pixels wide. Defaults to `5`.
*
* @type {number}
* @default 5
* @product highstock
* @apioption plotOptions.ohlc.dataGrouping.groupPixelWidth
*/
/**
* The pixel width of the line/border. Defaults to `1`.
*
* @sample {highstock} stock/plotoptions/ohlc-linewidth/
* A greater line width
*
* @type {number}
* @default 1
* @product highstock
*
* @private
*/
lineWidth: 1,
tooltip: {
pointFormat: '<span style="color:{point.color}">\u25CF</span> ' +
'<b> {series.name}</b><br/>' +
'Open: {point.open}<br/>' +
'High: {point.high}<br/>' +
'Low: {point.low}<br/>' +
'Close: {point.close}<br/>'
},
threshold: null,
states: {
/**
* @extends plotOptions.column.states.hover
* @product highstock
*/
hover: {
/**
* The pixel width of the line representing the OHLC point.
*
* @type {number}
* @default 3
* @product highstock
*/
lineWidth: 3
}
},
/**
* Determines which one of `open`, `high`, `low`, `close` values should
* be represented as `point.y`, which is later used to set dataLabel
* position and [compare](#plotOptions.series.compare).
*
* @sample {highstock} stock/plotoptions/ohlc-pointvalkey/
* Possible values
*
* @type {string}
* @default close
* @validvalue ["open", "high", "low", "close"]
* @product highstock
* @apioption plotOptions.ohlc.pointValKey
*/
/**
* @default close
* @apioption plotOptions.ohlc.colorKey
*/
/**
* Line color for up points.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highstock
* @apioption plotOptions.ohlc.upColor
*/
stickyTracking: true
},
/**
* @lends Highcharts.seriesTypes.ohlc
*/
{
/* eslint-disable valid-jsdoc */
directTouch: false,
pointArrayMap: ['open', 'high', 'low', 'close'],
toYData: function (point) {
// return a plain array for speedy calculation
return [point.open, point.high, point.low, point.close];
},
pointValKey: 'close',
pointAttrToOptions: {
stroke: 'color',
'stroke-width': 'lineWidth'
},
/**
* @private
* @function Highcarts.seriesTypes.ohlc#init
* @return {void}
*/
init: function () {
seriesTypes.column.prototype.init.apply(this, arguments);
this.options.stacking = void 0; // #8817
},
/**
* Postprocess mapping between options and SVG attributes
*
* @private
* @function Highcharts.seriesTypes.ohlc#pointAttribs
* @param {Highcharts.OHLCPoint} point
* @param {string} state
* @return {Highcharts.SVGAttributes}
*/
pointAttribs: function (point, state) {
var attribs = seriesTypes.column.prototype.pointAttribs.call(this, point, state), options = this.options;
delete attribs.fill;
if (!point.options.color &&
options.upColor &&
point.open < point.close) {
attribs.stroke = options.upColor;
}
return attribs;
},
/**
* Translate data points from raw values x and y to plotX and plotY
*
* @private
* @function Highcharts.seriesTypes.ohlc#translate
* @return {void}
*/
translate: function () {
var series = this, yAxis = series.yAxis, hasModifyValue = !!series.modifyValue, translated = [
'plotOpen',
'plotHigh',
'plotLow',
'plotClose',
'yBottom'
]; // translate OHLC for
seriesTypes.column.prototype.translate.apply(series);
// Do the translation
series.points.forEach(function (point) {
[point.open, point.high, point.low, point.close, point.low]
.forEach(function (value, i) {
if (value !== null) {
if (hasModifyValue) {
value = series.modifyValue(value);
}
point[translated[i]] =
yAxis.toPixels(value, true);
}
});
// Align the tooltip to the high value to avoid covering the
// point
point.tooltipPos[1] =
point.plotHigh + yAxis.pos - series.chart.plotTop;
});
},
/**
* Draw the data points
*
* @private
* @function Highcharts.seriesTypes.ohlc#drawPoints
* @return {void}
*/
drawPoints: function () {
var series = this, points = series.points, chart = series.chart,
/**
* Extend vertical stem to open and close values.
*/
extendStem = function (path, halfStrokeWidth, openOrClose) {
var start = path[0];
var end = path[1];
// We don't need to worry about crisp - openOrClose value
// is already crisped and halfStrokeWidth should remove it.
if (typeof start[2] === 'number') {
start[2] = Math.max(openOrClose + halfStrokeWidth, start[2]);
}
if (typeof end[2] === 'number') {
end[2] = Math.min(openOrClose - halfStrokeWidth, end[2]);
}
};
points.forEach(function (point) {
var plotOpen, plotClose, crispCorr, halfWidth, path, graphic = point.graphic, crispX, isNew = !graphic, strokeWidth;
if (typeof point.plotY !== 'undefined') {
// Create and/or update the graphic
if (!graphic) {
point.graphic = graphic = chart.renderer.path()
.add(series.group);
}
if (!chart.styledMode) {
graphic.attr(series.pointAttribs(point, (point.selected && 'select'))); // #3897
}
// crisp vector coordinates
strokeWidth = graphic.strokeWidth();
crispCorr = (strokeWidth % 2) / 2;
// #2596:
crispX = Math.round(point.plotX) - crispCorr;
halfWidth = Math.round(point.shapeArgs.width / 2);
// the vertical stem
path = [
['M', crispX, Math.round(point.yBottom)],
['L', crispX, Math.round(point.plotHigh)]
];
// open
if (point.open !== null) {
plotOpen = Math.round(point.plotOpen) + crispCorr;
path.push(['M', crispX, plotOpen], ['L', crispX - halfWidth, plotOpen]);
extendStem(path, strokeWidth / 2, plotOpen);
}
// close
if (point.close !== null) {
plotClose = Math.round(point.plotClose) + crispCorr;
path.push(['M', crispX, plotClose], ['L', crispX + halfWidth, plotClose]);
extendStem(path, strokeWidth / 2, plotClose);
}
graphic[isNew ? 'attr' : 'animate']({ d: path })
.addClass(point.getClassName(), true);
}
});
},
animate: null // Disable animation
/* eslint-enable valid-jsdoc */
},
/**
* @lends Highcharts.seriesTypes.ohlc.prototype.pointClass.prototype
*/
{
/* eslint-disable valid-jsdoc */
/**
* Extend the parent method by adding up or down to the class name.
* @private
* @function Highcharts.seriesTypes.ohlc#getClassName
* @return {string}
*/
getClassName: function () {
return Point.prototype.getClassName.call(this) +
(this.open < this.close ?
' highcharts-point-up' :
' highcharts-point-down');
}
/* eslint-enable valid-jsdoc */
});
/**
* A `ohlc` series. If the [type](#series.ohlc.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.ohlc
* @excluding dataParser, dataURL
* @product highstock
* @apioption series.ohlc
*/
/**
* An array of data points for the series. For the `ohlc` series type,
* points can be given in the following ways:
*
* 1. An array of arrays with 5 or 4 values. In this case, the values correspond
* to `x,open,high,low,close`. If the first value is a string, it is applied
* as the name of the point, and the `x` value is inferred. The `x` value can
* also be omitted, in which case the inner arrays should be of length 4\.
* Then the `x` value is automatically calculated, either starting at 0 and
* incremented by 1, or from `pointStart` and `pointInterval` given in the
* series options.
* ```js
* data: [
* [0, 6, 5, 6, 7],
* [1, 9, 4, 8, 2],
* [2, 6, 3, 4, 10]
* ]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.ohlc.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* open: 3,
* high: 4,
* low: 5,
* close: 2,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* open: 4,
* high: 3,
* low: 6,
* close: 7,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @type {Array<Array<(number|string),number,number,number>|Array<(number|string),number,number,number,number>|*>}
* @extends series.arearange.data
* @excluding y, marker
* @product highstock
* @apioption series.ohlc.data
*/
/**
* The closing value of each data point.
*
* @type {number}
* @product highstock
* @apioption series.ohlc.data.close
*/
/**
* The opening value of each data point.
*
* @type {number}
* @product highstock
* @apioption series.ohlc.data.open
*/
''; // adds doclets above to transpilat
| burki/jewish-history-online | web/vendor/highcharts/es-modules/parts/OHLCSeries.js | JavaScript | agpl-3.0 | 11,563 |
# -*- coding: utf-8 -*-
# Copyright(C) 2010-2015 Julien Veyssier, Laurent Bachelier
#
# 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/>.
import random
import urllib
from urlparse import urlsplit
from weboob.deprecated.browser import Browser, BrowserHTTPNotFound
from .pages.index import IndexPage
from .pages.torrents import TorrentPage, TorrentsPage
__all__ = ['PiratebayBrowser']
class PiratebayBrowser(Browser):
ENCODING = 'utf-8'
DOMAINS = ['thepiratebay.vg',
'thepiratebay.la',
'thepiratebay.mn',
'thepiratebay.gd']
def __init__(self, url, *args, **kwargs):
url = url or 'https://%s/' % random.choice(self.DOMAINS)
url_parsed = urlsplit(url)
self.PROTOCOL = url_parsed.scheme
self.DOMAIN = url_parsed.netloc
self.PAGES = {
'%s://%s/' % (self.PROTOCOL, self.DOMAIN): IndexPage,
'%s://%s/search/.*/0/7/0' % (self.PROTOCOL, self.DOMAIN): TorrentsPage,
'%s://%s/torrent/.*' % (self.PROTOCOL, self.DOMAIN): TorrentPage
}
Browser.__init__(self, *args, **kwargs)
def iter_torrents(self, pattern):
self.location('%s://%s/search/%s/0/7/0' % (self.PROTOCOL,
self.DOMAIN,
urllib.quote_plus(pattern.encode('utf-8'))))
assert self.is_on_page(TorrentsPage)
return self.page.iter_torrents()
def get_torrent(self, _id):
try:
self.location('%s://%s/torrent/%s/' % (self.PROTOCOL,
self.DOMAIN,
_id))
except BrowserHTTPNotFound:
return
if self.is_on_page(TorrentPage):
return self.page.get_torrent(_id)
| sputnick-dev/weboob | modules/piratebay/browser.py | Python | agpl-3.0 | 2,463 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>rgaa22 Test.03021 NMI 07</title>
</head>
<body>
<div>
<h1>rgaa22 Test.03021 NMI 07</h1>
<div class="test-detail" lang="fr">
Présence d’information préalable sur le caractère obligatoire de certains champs de saisie et du type/format de saisie attendue si nécessaire
</div>
<div class="testcase">
<form action="mock_action">
<p>
<textarea cols="100" rows="4"></textarea>
<input name="submit" type="submit" value="Action" />
</p>
</form>
</div>
<div class="test-explanation">NMI : The page contains at least one form that needs to be manually checked</div>
</div>
</body>
</html> | dzc34/Asqatasun | rules/rules-rgaa2.2/src/test/resources/testcases/rgaa22/Rgaa22Rule03021/RGAA22.Test.3.2-3NMI-07.html | HTML | agpl-3.0 | 1,153 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2007-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.core.tasks;
import org.springframework.util.Assert;
/**
* <p>AsyncTask class.</p>
*
* @author ranger
* @version $Id: $
*/
public class AsyncTask<T> extends AbstractTask {
private final Async<T> m_async;
private final Callback<T> m_callback;
/**
* <p>Constructor for AsyncTask.</p>
*
* @param coordinator a {@link org.opennms.core.tasks.TaskCoordinator} object.
* @param parent a {@link org.opennms.core.tasks.ContainerTask} object.
* @param async a {@link org.opennms.core.tasks.Async} object.
* @param <T> a T object.
*/
public AsyncTask(TaskCoordinator coordinator, ContainerTask<?> parent, Async<T> async) {
this(coordinator, parent, async, null);
}
/**
* <p>Constructor for AsyncTask.</p>
*
* @param coordinator a {@link org.opennms.core.tasks.TaskCoordinator} object.
* @param parent a {@link org.opennms.core.tasks.ContainerTask} object.
* @param async a {@link org.opennms.core.tasks.Async} object.
* @param callback a {@link org.opennms.core.tasks.Callback} object.
*/
public AsyncTask(TaskCoordinator coordinator, ContainerTask<?> parent, Async<T> async, Callback<T> callback) {
super(coordinator, parent);
Assert.notNull(async, "async parameter must not be null");
m_async = async;
m_callback = callback;
}
/** {@inheritDoc} */
@Override
public String toString() {
return String.valueOf(m_async);
}
/** {@inheritDoc} */
@Override
protected void doSubmit() {
Callback<T> callback = callback();
try {
m_async.supplyAsyncThenAccept(callback);
} catch (Throwable t) {
callback.handleException(t);
}
}
/**
* <p>markTaskAsCompleted</p>
*/
private final void markTaskAsCompleted() {
getCoordinator().markTaskAsCompleted(this);
}
private Callback<T> callback() {
return new Callback<T>() {
@Override
public void accept(T t) {
try {
if (m_callback != null) {
m_callback.accept(t);
}
} finally {
markTaskAsCompleted();
}
}
@Override
public T apply(Throwable t) {
try {
if (m_callback != null) {
m_callback.handleException(t);
}
} finally {
markTaskAsCompleted();
}
return null;
}
};
}
}
| aihua/opennms | core/tasks/src/main/java/org/opennms/core/tasks/AsyncTask.java | Java | agpl-3.0 | 3,889 |
# frozen_string_literal: true
class Settings::PreferencesController < ApplicationController
layout 'admin'
before_action :authenticate_user!
def show; end
def update
user_settings.update(user_settings_params.to_h)
if current_user.update(user_params)
I18n.locale = current_user.locale
redirect_to settings_preferences_path, notice: I18n.t('generic.changes_saved_msg')
else
render :show
end
end
private
def user_settings
UserSettingsDecorator.new(current_user)
end
def user_params
params.require(:user).permit(
:locale,
filtered_languages: []
)
end
def user_settings_params
params.require(:user).permit(
:setting_default_privacy,
:setting_boost_modal,
:setting_auto_play_gif,
notification_emails: %i(follow follow_request reblog favourite mention digest),
interactions: %i(must_be_follower must_be_following)
)
end
end
| TootCat/mastodon | app/controllers/settings/preferences_controller.rb | Ruby | agpl-3.0 | 946 |
<?php
// created: 2015-12-11 14:01:20
$dictionary['Contact']['fields']['salutation']['len']=100;
$dictionary['Contact']['fields']['salutation']['inline_edit']=true;
$dictionary['Contact']['fields']['salutation']['comments']='Contact salutation (e.g., Mr, Ms)';
$dictionary['Contact']['fields']['salutation']['merge_filter']='disabled';
?> | auf/crm_auf_org | metadata/custom/modulebuilder/builds/all_auf/Extension/modules/Contacts/Ext/Vardefs/sugarfield_salutation.php | PHP | agpl-3.0 | 341 |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 1997, 2014 Oracle and/or its affiliates. All rights reserved.
*
* $Id$
*/
#include "db_config.h"
#include "db_int.h"
/*
* __os_rmdir --
* Remove a directory.
*/
int
__os_rmdir(env, name)
ENV *env;
const char *name;
{
DB_ENV *dbenv;
_TCHAR *tname;
int ret;
dbenv = env == NULL ? NULL : env->dbenv;
if (dbenv != NULL &&
FLD_ISSET(dbenv->verbose, DB_VERB_FILEOPS | DB_VERB_FILEOPS_ALL))
__db_msg(env, DB_STR_A("0240", "fileops: rmdir %s",
"%s"), name);
TO_TSTRING(env, name, tname, ret);
if (ret != 0)
return (ret);
RETRY_CHK(!RemoveDirectory(tname), ret);
FREE_STRING(env, tname);
if (ret != 0)
return (__os_posix_err(ret));
return (ret);
}
| zheguang/BerkeleyDB | src/os_windows/os_rmdir.c | C | agpl-3.0 | 763 |
"""This module implement decorators for wrapping data sources so as to
simplify their construction and attribution of properties.
"""
import functools
def data_source_generator(name=None, **properties):
"""Decorator for applying to a simple data source which directly
returns an iterable/generator with the metrics for each sample. The
function the decorator is applied to must take no arguments.
"""
def _decorator(func):
@functools.wraps(func)
def _properties(settings):
def _factory(environ):
return func
d = dict(properties)
d['name'] = name
d['factory'] = _factory
return d
return _properties
return _decorator
def data_source_factory(name=None, **properties):
"""Decorator for applying to a data source defined as a factory. The
decorator can be applied to a class or a function. The class
constructor or function must accept arguments of 'settings', being
configuration settings for the data source, and 'environ' being
information about the context in which the data source is being
used. The resulting object must be a callable which directly returns
an iterable/generator with the metrics for each sample.
"""
def _decorator(func):
@functools.wraps(func)
def _properties(settings):
def _factory(environ):
return func(settings, environ)
d = dict(properties)
d['name'] = name
d['factory'] = _factory
return d
return _properties
return _decorator
| GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/newrelic-2.46.0.37/newrelic/samplers/decorators.py | Python | agpl-3.0 | 1,626 |
<?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 - 2018 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".
*/
/**
* Predefined logic hooks
* after_ui_frame
* after_ui_footer
* after_save
* before_save
* before_retrieve
* after_retrieve
* process_record
* before_delete
* after_delete
* before_restore
* after_restore
* server_roundtrip
* before_logout
* after_logout
* before_login
* after_login
* login_failed
* after_session_start
* after_entry_point
*
* @api
*/
class LogicHook
{
public $bean = null;
public function __construct()
{
}
/**
* Static Function which returns and instance of LogicHook
*
* @return unknown
*/
public static function initialize()
{
if (empty($GLOBALS['logic_hook'])) {
$GLOBALS['logic_hook'] = new LogicHook();
}
return $GLOBALS['logic_hook'];
}
public function setBean($bean)
{
$this->bean = $bean;
return $this;
}
protected $hook_map = array();
protected $hookscan = array();
public function getHooksMap()
{
return $this->hook_map;
}
public function getHooksList()
{
return $this->hookscan;
}
public function scanHooksDir($extpath)
{
if (is_dir($extpath)) {
$dir = dir($extpath);
while ($entry = $dir->read()) {
if ($entry != '.' && $entry != '..' && strtolower(substr($entry, -4)) == ".php" && is_file($extpath.'/'.$entry)) {
unset($hook_array);
include($extpath.'/'.$entry);
if (!empty($hook_array)) {
foreach ($hook_array as $type => $hookg) {
foreach ($hookg as $index => $hook) {
$this->hookscan[$type][] = $hook;
$idx = count($this->hookscan[$type])-1;
$this->hook_map[$type][$idx] = array("file" => $extpath.'/'.$entry, "index" => $index);
}
}
}
}
}
}
}
protected static $hooks = array();
public static function refreshHooks()
{
self::$hooks = array();
}
public function loadHooks($module_dir)
{
$hook_array = array();
if (!empty($module_dir)) {
$custom = "custom/modules/$module_dir";
} else {
$custom = "custom/modules";
}
if (file_exists("$custom/logic_hooks.php")) {
if (isset($GLOBALS['log'])) {
$GLOBALS['log']->debug('Including module specific hook file for '.$custom);
}
include("$custom/logic_hooks.php");
}
if (empty($module_dir)) {
$custom = "custom/application";
}
if (file_exists("$custom/Ext/LogicHooks/logichooks.ext.php")) {
if (isset($GLOBALS['log'])) {
$GLOBALS['log']->debug('Including Ext hook file for '.$custom);
}
include("$custom/Ext/LogicHooks/logichooks.ext.php");
}
return $hook_array;
}
public function getHooks($module_dir, $refresh = false)
{
if ($refresh || !isset(self::$hooks[$module_dir])) {
self::$hooks[$module_dir] = $this->loadHooks($module_dir);
}
return self::$hooks[$module_dir];
}
/**
* Provide a means for developers to create upgrade safe business logic hooks.
* If the bean is null, then we assume this call was not made from a SugarBean Object and
* therefore we do not pass it to the method call.
*
* @param string $module_dir
* @param string $event
* @param array $arguments
* @param SugarBean $bean
*/
public function call_custom_logic($module_dir, $event, $arguments = null)
{
// declare the hook array variable, it will be defined in the included file.
$hook_array = null;
if (isset($GLOBALS['log'])) {
$GLOBALS['log']->debug("Hook called: $module_dir::$event");
}
if (!empty($module_dir)) {
// This will load an array of the hooks to process
$hooks = $this->getHooks($module_dir);
if (!empty($hooks)) {
$this->process_hooks($hooks, $event, $arguments);
}
}
$hooks = $this->getHooks('');
if (!empty($hooks)) {
$this->process_hooks($hooks, $event, $arguments);
}
}
/**
* This is called from call_custom_logic and actually performs the action as defined in the
* logic hook. If the bean is null, then we assume this call was not made from a SugarBean Object and
* therefore we do not pass it to the method call.
*
* @param array $hook_array
* @param string $event
* @param array $arguments
* @param SugarBean $bean
*/
public function process_hooks($hook_array, $event, $arguments)
{
// Now iterate through the array for the appropriate hook
if (!empty($hook_array[$event])) {
// Apply sorting to the hooks using the sort index.
// Hooks with matching sort indexes will be processed in no particular order.
$sorted_indexes = array();
foreach ($hook_array[$event] as $idx => $hook_details) {
$order_idx = $hook_details[0];
$sorted_indexes[$idx] = $order_idx;
}
asort($sorted_indexes);
$process_order = array_keys($sorted_indexes);
foreach ($process_order as $hook_index) {
$hook_details = $hook_array[$event][$hook_index];
if (!file_exists($hook_details[2])) {
if (isset($GLOBALS['log'])) {
$GLOBALS['log']->error('Unable to load custom logic file: '.$hook_details[2]);
}
continue;
}
include_once($hook_details[2]);
$hook_class = $hook_details[3];
$hook_function = $hook_details[4];
// Make a static call to the function of the specified class
//TODO Make a factory for these classes. Cache instances accross uses
if ($hook_class == $hook_function) {
if (isset($GLOBALS['log'])) {
$GLOBALS['log']->debug('Creating new instance of hook class '.$hook_class.' with parameters');
}
if (!is_null($this->bean)) {
$class = new $hook_class($this->bean, $event, $arguments);
} else {
$class = new $hook_class($event, $arguments);
}
} else {
if (isset($GLOBALS['log'])) {
$GLOBALS['log']->debug('Creating new instance of hook class '.$hook_class.' without parameters');
}
$class = new $hook_class();
if (!is_null($this->bean)) {
$class->$hook_function($this->bean, $event, $arguments);
} else {
$class->$hook_function($event, $arguments);
}
}
}
}
}
}
| JimMackin/SuiteCRM | include/utils/LogicHook.php | PHP | agpl-3.0 | 9,433 |
package tc.oc.api.ocn;
import java.util.Collection;
import javax.inject.Singleton;
import com.google.common.util.concurrent.ListenableFuture;
import tc.oc.api.docs.MapRating;
import tc.oc.api.docs.virtual.MapDoc;
import tc.oc.api.docs.virtual.UserDoc;
import tc.oc.api.exceptions.NotFound;
import tc.oc.api.http.HttpOption;
import tc.oc.api.maps.MapRatingsRequest;
import tc.oc.api.maps.MapRatingsResponse;
import tc.oc.api.maps.MapService;
import tc.oc.api.maps.UpdateMapsResponse;
import tc.oc.api.model.HttpModelService;
import tc.oc.commons.core.concurrent.FutureUtils;
import tc.oc.commons.core.stream.Collectors;
@Singleton
class OCNMapService extends HttpModelService<MapDoc, MapDoc> implements MapService {
public ListenableFuture<Object> rate(MapRating rating) {
return this.client().post(memberUri(rating.map_id, "rate"), rating, Object.class, HttpOption.INFINITE_RETRY);
}
public ListenableFuture<MapRatingsResponse> getRatings(MapRatingsRequest request) {
return this.client().post(memberUri(request.map_id, "get_ratings"), request, MapRatingsResponse.class, HttpOption.INFINITE_RETRY);
}
public UpdateMapsResponse updateMaps(Collection<? extends MapDoc> maps) {
final ListenableFuture<MapUpdateMultiResponse> future = updateMulti(maps, MapUpdateMultiResponse.class);
return new UpdateMapsResponse(
(ListenableFuture) future,
maps.stream()
.flatMap(MapDoc::authorAndContributorUuids)
.distinct()
.collect(Collectors.mappingTo(uuid -> FutureUtils.mapSync(
future,
response -> {
final UserDoc.Identity user = response.users_by_uuid.get(uuid);
if(user != null) return user;
throw new NotFound();
}
)))
);
}
}
| OvercastNetwork/ProjectAres | API/ocn/src/main/java/tc/oc/api/ocn/OCNMapService.java | Java | agpl-3.0 | 1,908 |
/*--------------------------------------------------------------------
Copyright (c) 2011 Local Projects. All rights reserved.
Licensed under the Affero GNU GPL v3, see LICENSE for more details.
--------------------------------------------------------------------*/
tc.gam.widgetVisibilityHandler = function(options) {
var self = {
currentHash: window.location.hash,
previousHash: null
};
self._setHash = function(hash) {
if (hash === self.currentHash) {
tc.jQ(window).trigger('hashchange');
} else {
//This will trigger the 'hashchange' event because the hash is different
window.location.hash = hash;
}
};
self._getHash = function() {
return window.location.hash.substring(1, window.location.hash.length);
};
self._goHome = function() {
self._setHash('show,home');
};
self._triggerWidgetVisibilityEvent = function(action, widget, id) {
tc.jQ(tc).trigger(action + '-project-widget', [widget, id]);
};
self._onHashChange = function(event) {
var action, widget;
self.previousHash = self.currentHash;
self.currentHash = self._getHash();
// For project-home hash, fire goHome.
if (!self.currentHash || self.currentHash === 'project-home') {
self._goHome();
} else {
action = self.currentHash.split(',')[0];
widget = self.currentHash.split(',')[1];
id = self.currentHash.split(',')[2];
}
tc.util.log('&&& hashchange: ' + action + ', ' + widget);
self._triggerWidgetVisibilityEvent(action, widget, id);
};
var bindEvents = function() {
tc.jQ(window).bind('hashchange', self._onHashChange);
};
var init = function() {
bindEvents();
if (self.currentHash) {
self._setHash(self.currentHash);
} else {
self._goHome();
}
};
init();
return self;
}; | localprojects/Change-By-Us | static/js/tc.gam.widget-visibility-handler.js | JavaScript | agpl-3.0 | 2,065 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Rgaa30 Test.10.4.2 Failed 03_3</title>
<style type="text/css">
@media tv {
h1{
font-size: 15mm;
}
}
</style>
</head>
<body>
<div>
<h1>Rgaa30 Test.10.4.2 Failed 03_3</h1>
<div class="test-detail" lang="fr"> Dans les
<a href="http://references.modernisation.gouv.fr/referentiel-technique-0#mFeuilleStyle">feuilles de styles</a> du
<a href="http://references.modernisation.gouv.fr/referentiel-technique-0#mSiteWeb">site Web</a>, pour les types de média
<code>screen</code>,
<code>tv</code>,
<code>handheld</code>,
<code>projection</code>, les tailles de caractères utilisent-elles uniquement des
<a href="http://references.modernisation.gouv.fr/referentiel-technique-0#mTailleCaractere">unités relatives</a> ?
</div>
<p class="test-explanation"> Failed: The pc unit is used on a font-size property of a css rule applied to the "tv" media. </p>
</div>
</body>
</html> | dzc34/Asqatasun | rules/rules-rgaa3.0/src/test/resources/testcases/rgaa30/Rgaa30Rule100402/Rgaa30.Test.10.04.02-2Failed-03_3.html | HTML | agpl-3.0 | 1,459 |
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# LICENSE
#
# Copyright (c) 2010-2017, GEM Foundation, G. Weatherill, M. Pagani,
# D. Monelli.
#
# The Hazard Modeller's Toolkit 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.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>
#
#DISCLAIMER
#
# The software Hazard Modeller's Toolkit (openquake.hmtk) provided herein
#is released as a prototype implementation on behalf of
# scientists and engineers working within the GEM Foundation (Global
#Earthquake Model).
#
# It is distributed for the purpose of open collaboration and in the
# hope that it will be useful to the scientific, engineering, disaster
# risk and software design communities.
#
# The software is NOT distributed as part of GEM's OpenQuake suite
# (http://www.globalquakemodel.org/openquake) and must be considered as a
# separate entity. The software provided herein is designed and implemented
# by scientific staff. It is not developed to the design standards, nor
# subject to same level of critical review by professional software
# developers, as GEM's OpenQuake software suite.
#
# Feedback and contribution to the software is welcome, and can be
# directed to the hazard scientific staff of the GEM Model Facility
# (hazard@globalquakemodel.org).
#
# The Hazard Modeller's Toolkit (openquake.hmtk) is therefore distributed 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.
#
# The GEM Foundation, and the authors of the software, assume no
# liability for use of the software.
| gem/oq-hazardlib | openquake/hmtk/strain/regionalisation/__init__.py | Python | agpl-3.0 | 1,925 |
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library 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 library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: style.hpp 39 2005-04-10 20:39:53Z pavlenko $
#ifndef STYLE_HPP
#define STYLE_HPP
// mapnik
#include <mapnik/color.hpp>
#include <mapnik/symbolizer.hpp>
// boost
#include <boost/shared_ptr.hpp>
// stl
#include <vector>
#include <algorithm>
#include <functional>
namespace mapnik { }
#endif //STYLE_HPP
| carlos-lopez-garces/mapnik-trunk | include/mapnik/style.hpp | C++ | lgpl-2.1 | 1,310 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!--
This library is part of OpenCms -
the Open Source Content Management System
Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
This library 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 library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
For further information about Alkacon Software GmbH, please see the
company website: http://www.alkacon.com
For further information about OpenCms, please see the
project website: http://www.opencms.org
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-->
</head>
<body bgcolor="white">
Contains server side classes for the XML content editor.<p>
<!-- Put @see and @since tags down here. -->
@since 8.5.0
</body>
</html>
| sbonoc/opencms-core | src/org/opencms/ade/contenteditor/package.html | HTML | lgpl-2.1 | 1,311 |
/*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* This library 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 library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.workplace.tools.content;
import org.opencms.file.CmsProperty;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsVfsException;
import org.opencms.i18n.CmsMessages;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.lock.CmsLock;
import org.opencms.main.CmsException;
import org.opencms.main.OpenCms;
import org.opencms.workplace.CmsDialog;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.workplace.CmsWorkplaceSettings;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
/**
* Provides methods for the delete property definition dialog.<p>
*
* @since 6.0.0
*/
public class CmsPropertyDelete extends CmsDialog {
/** Value for the action: delete cascade. */
public static final int ACTION_DELETE_CASCADE = 100;
/** Request parameter value for the action: delete cascade. */
public static final String DIALOG_DELETE_CASCADE = "deletecascade";
/** The dialog type. */
public static final String DIALOG_TYPE = "propertydelete";
/** Request parameter name for the property name. */
public static final String PARAM_PROPERTYNAME = "propertyname";
private String m_paramPropertyName;
/**
* Public constructor with JSP action element.<p>
*
* @param jsp an initialized JSP action element
*/
public CmsPropertyDelete(CmsJspActionElement jsp) {
super(jsp);
}
/**
* Public constructor with JSP variables.<p>
*
* @param context the JSP page context
* @param req the JSP request
* @param res the JSP response
*/
public CmsPropertyDelete(PageContext context, HttpServletRequest req, HttpServletResponse res) {
this(new CmsJspActionElement(context, req, res));
}
/**
* Deletes the property definition.<p>
*
* @throws JspException if problems including sub-elements occur
*/
public void actionDelete() throws JspException {
// save initialized instance of this class in request attribute for included sub-elements
getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this);
try {
getCms().deletePropertyDefinition(getParamPropertyName());
// close the dialog
actionCloseDialog();
} catch (Throwable e) {
// error while deleting property definition, show error dialog
includeErrorpage(this, e);
}
}
/**
* Deletes the property definition by cascading the properties on resources.<p>
*
* @throws JspException if problems including sub-elements occur
*/
public void actionDeleteCascade() throws JspException {
// save initialized instance of this class in request attribute for included sub-elements
getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this);
try {
// list of all resources containing this propertydefinition
List resourcesWithProperty = getCms().readResourcesWithProperty(getParamPropertyName());
// list of all resources locked by another user, containing this propertydefinition
List resourcesLockedByOtherUser = getResourcesLockedByOtherUser(resourcesWithProperty);
// do the following operations only if all of the resources are not locked by another user
if (resourcesLockedByOtherUser.isEmpty()) {
// save the site root
String storedSiteRoot = getCms().getRequestContext().getSiteRoot();
try {
// change to the root site
getCms().getRequestContext().setSiteRoot("/");
Iterator i = resourcesWithProperty.iterator();
while (i.hasNext()) {
CmsResource resource = (CmsResource)i.next();
// read the property object
CmsProperty property = getCms().readPropertyObject(
resource.getRootPath(),
getParamPropertyName(),
false);
// try to delete the property if it is not the NULL PROPERTY
// if the property is the NULL PROPERTY, it only had a shared
// value which was deleted at a sibling which was already processed
if (!property.isNullProperty()) {
CmsLock lock = getCms().getLock(resource);
if (lock.isUnlocked()) {
// lock the resource for the current (Admin) user
getCms().lockResource(resource.getRootPath());
}
property.setStructureValue(CmsProperty.DELETE_VALUE);
property.setResourceValue(CmsProperty.DELETE_VALUE);
// write the property with the null value to the resource and cascade it from the definition
getCms().writePropertyObject(resource.getRootPath(), property);
// unlock the resource
getCms().unlockResource(resource.getRootPath());
}
}
// delete the property definition at last
getCms().deletePropertyDefinition(getParamPropertyName());
} finally {
// restore the siteroot
getCms().getRequestContext().setSiteRoot(storedSiteRoot);
// close the dialog
actionCloseDialog();
}
} else {
StringBuffer reason = new StringBuffer();
reason.append(dialogWhiteBoxStart());
reason.append(buildResourceList(resourcesLockedByOtherUser, true));
reason.append(dialogWhiteBoxEnd());
throw new CmsVfsException(Messages.get().container(
Messages.ERR_DEL_PROP_RESOURCES_LOCKED_1,
reason.toString()));
}
} catch (Throwable e) {
// error while deleting property definition, show error dialog
includeErrorpage(this, e);
}
}
/**
* Builds a HTML list of Resources that use the specified property.<p>
*
* @throws CmsException if operation was not successful
*
* @return the HTML String for the Resource list
*/
public String buildResourceList() throws CmsException {
List resourcesWithProperty = getCms().readResourcesWithProperty(getParamPropertyName());
return buildResourceList(resourcesWithProperty, false);
}
/**
* Builds a HTML list of Resources.<p>
*
* Columns: Type, Name, Uri, Value of the property, locked by(optional).<p>
*
* @param resourceList a list of resources
* @param lockInfo a boolean to decide if the locked info should be shown or not
* @throws CmsException if operation was not successful
*
* @return the HTML String for the Resource list
*/
public String buildResourceList(List resourceList, boolean lockInfo) throws CmsException {
// reverse the resource list
Collections.reverse(resourceList);
CmsMessages messages = Messages.get().getBundle(getLocale());
StringBuffer result = new StringBuffer();
result.append("<table border=\"0\" width=\"100%\" cellpadding=\"1\" cellspacing=\"1\">\n");
result.append("<tr>\n");
// Type
result.append("\t<td style=\"width:5%;\" class=\"textbold\">");
result.append(messages.key(Messages.GUI_INPUT_TYPE_0));
result.append("</td>\n");
// Uri
result.append("\t<td style=\"width:40%;\" class=\"textbold\">");
result.append(messages.key(Messages.GUI_INPUT_ADRESS_0));
result.append("</td>\n");
// Name
result.append("\t<td style=\"width:25%;\" class=\"textbold\">");
result.append(messages.key(Messages.GUI_INPUT_TITLE_0));
result.append("</td>\n");
if (!lockInfo) {
// Property value
result.append("\t<td style=\"width:30%;\" class=\"textbold\">");
result.append(messages.key(Messages.GUI_INPUT_PROPERTYVALUE_0));
result.append("</td>\n");
}
if (lockInfo) {
// Property value
result.append("\t<td style=\"width:30%;\" class=\"textbold\">");
result.append(messages.key(Messages.GUI_EXPLORER_LOCKEDBY_0));
result.append("</td>\n");
result.append("</tr>\n");
}
result.append("</tr>\n");
result.append("<tr><td colspan=\"4\"><span style=\"height: 6px;\"> </span></td></tr>\n");
String storedSiteRoot = getCms().getRequestContext().getSiteRoot();
try {
getCms().getRequestContext().setSiteRoot("/");
Iterator i = resourceList.iterator();
while (i.hasNext()) {
CmsResource resource = (CmsResource)i.next();
String filetype = OpenCms.getResourceManager().getResourceType(resource.getTypeId()).getTypeName();
result.append("<tr>\n");
// file type
result.append("\t<td>");
result.append("<img src=\"");
result.append(getSkinUri());
result.append(CmsWorkplace.RES_PATH_FILETYPES);
result.append(filetype);
result.append(".gif\">");
result.append("</td>\n");
// file address
result.append("\t<td>");
result.append(resource.getRootPath());
result.append("</td>\n");
// title
result.append("\t<td>");
result.append(getJsp().property(CmsPropertyDefinition.PROPERTY_TITLE, resource.getRootPath(), ""));
result.append("</td>\n");
// current value of the property
if (!lockInfo) {
result.append("\t<td>");
result.append(getJsp().property(getParamPropertyName(), resource.getRootPath()));
result.append("</td>\n");
}
// locked by user
if (lockInfo) {
CmsLock lock = getCms().getLock(resource);
result.append("\t<td>");
result.append(getCms().readUser(lock.getUserId()).getName());
result.append("</td>\n");
}
result.append("</tr>\n");
}
result.append("</table>\n");
} finally {
getCms().getRequestContext().setSiteRoot(storedSiteRoot);
}
return result.toString();
}
/**
* Builds the html for the property definition select box.<p>
*
* @param attributes optional attributes for the <select> tag
* @return the html for the property definition select box
*/
public String buildSelectProperty(String attributes) {
return CmsPropertyChange.buildSelectProperty(getCms(), Messages.get().getBundle(getLocale()).key(
Messages.GUI_PLEASE_SELECT_0), attributes, "");
}
/**
* Returns the value of the propertyname parameter.<p>
*
* @return the value of the propertyname parameter
*/
public String getParamPropertyName() {
return m_paramPropertyName;
}
/**
* Sets the value of the propertyname parameter.<p>
*
* @param paramPropertyName the value of the propertyname parameter
*/
public void setParamPropertyName(String paramPropertyName) {
m_paramPropertyName = paramPropertyName;
}
/**
* @see org.opencms.workplace.CmsWorkplace#initWorkplaceRequestValues(org.opencms.workplace.CmsWorkplaceSettings, javax.servlet.http.HttpServletRequest)
*/
protected void initWorkplaceRequestValues(CmsWorkplaceSettings settings, HttpServletRequest request) {
// fill the parameter values in the get/set methods
fillParamValues(request);
// set the dialog type
setParamDialogtype(DIALOG_TYPE);
// set the action for the JSP switch
if (DIALOG_OK.equals(getParamAction())) {
setAction(ACTION_OK);
setParamTitle(Messages.get().getBundle(getLocale()).key(Messages.GUI_TITLE_PROPERTYDELETE_0)
+ ": "
+ getParamPropertyName());
} else if (DIALOG_CANCEL.equals(getParamAction())) {
setAction(ACTION_CANCEL);
} else if (DIALOG_DELETE_CASCADE.equals(getParamAction())) {
setAction(ACTION_DELETE_CASCADE);
} else {
setAction(ACTION_DEFAULT);
// build title for change property value dialog
setParamTitle(Messages.get().getBundle(getLocale()).key(Messages.GUI_TITLE_PROPERTYDELETE_0));
}
}
/**
* Returns a list of resources that are locked by another user as the current user.<p>
*
* @param resourceList the list of all (mixed) resources
*
* @return a list of resources that are locked by another user as the current user
* @throws CmsException if the getLock operation fails
*/
private List getResourcesLockedByOtherUser(List resourceList) throws CmsException {
List lockedResourcesByOtherUser = new ArrayList();
Iterator i = resourceList.iterator();
while (i.hasNext()) {
CmsResource resource = (CmsResource)i.next();
// get the lock state for the resource
CmsLock lock = getCms().getLock(resource);
// add this resource to the list if this is locked by another user
if (!lock.isUnlocked() && !lock.isOwnedBy(getCms().getRequestContext().getCurrentUser())) {
lockedResourcesByOtherUser.add(resource);
}
}
return lockedResourcesByOtherUser;
}
}
| serrapos/opencms-core | src-modules/org/opencms/workplace/tools/content/CmsPropertyDelete.java | Java | lgpl-2.1 | 15,467 |
class Extension(object):
"""
Base class for creating extensions.
Args:
kwargs[dict]: All key, value pairings are stored as "configuration" options, see getConfigs.
"""
def __init__(self, **kwargs):
#: Configure options
self._configs = kwargs
self._configs.setdefault('headings', ['section', 'subsection', 'subsubsection', 'textbf', 'underline', 'emph'])
def getConfigs(self):
"""
Return the dictionary of configure options.
"""
return self._configs
def extend(self, translator):
"""
Elements should be added to the storage of the Translator instance within this function.
Args:
translator[Translator]: The object to be used for converting the html.
"""
pass
| vityurkiv/Ox | python/MooseDocs/html2latex/Extension.py | Python | lgpl-2.1 | 735 |
#!/usr/bin/python
import math
import Sofa
def tostr(L):
return str(L).replace('[', '').replace("]", '').replace(",", ' ')
def transform(T,p):
return [T[0][0]*p[0]+T[0][1]*p[1]+T[0][2]*p[2]+T[1][0],T[0][3]*p[0]+T[0][4]*p[1]+T[0][5]*p[2]+T[1][1],T[0][6]*p[0]+T[0][7]*p[1]+T[0][8]*p[2]+T[1][2]]
def transformF(T,F):
return [T[0][0]*F[0]+T[0][1]*F[3]+T[0][2]*F[6],T[0][0]*F[1]+T[0][1]*F[4]+T[0][2]*F[7],T[0][0]*F[2]+T[0][1]*F[5]+T[0][2]*F[8],T[0][3]*F[0]+T[0][4]*F[3]+T[0][5]*F[6],T[0][3]*F[1]+T[0][4]*F[4]+T[0][5]*F[7],T[0][3]*F[2]+T[0][4]*F[5]+T[0][5]*F[8],T[0][6]*F[0]+T[0][7]*F[3]+T[0][8]*F[6],T[0][6]*F[1]+T[0][7]*F[4]+T[0][8]*F[7],T[0][6]*F[2]+T[0][7]*F[5]+T[0][8]*F[8]]
def compare(p1,p2):
res = 0
for i,P1 in enumerate(p1):
for j,item in enumerate(P1):
res = res+ (item-p2[i][j])*(item-p2[i][j])
return res
ERRORTOL = 1e-5
T = [[2,0,0,0,2,0,0,0,2],[0,0,0]]
#T = [[0.8,1.2,0.3,0,1.9,0.45,0.5,2.8,0.2],[5,2,8]]
samples= [[0.5,0.5,0.5], [0.23,0.5,0.8], [0,0.12,0], [0.8,0,0.58]]
# scene creation method
def createScene(rootNode):
rootNode.createObject('RequiredPlugin', pluginName="Flexible")
rootNode.createObject('VisualStyle', displayFlags="showBehaviorModels")
restpos = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]]
pos = [transform(T,item) for item in restpos]
###########################################################
simNode = rootNode.createChild('Hexa_barycentric')
simNode.createObject('MeshTopology', name="mesh", position=tostr(restpos), hexahedra="0 1 3 2 4 5 7 6")
simNode.createObject('MechanicalObject', template="Vec3d", name="parent", rest_position="@mesh.position",position=tostr(pos) )
simNode.createObject('BarycentricShapeFunction', position="@parent.rest_position", nbRef="8")
childNode = simNode.createChild('childP')
childNode.createObject('MechanicalObject', template="Vec3d", name="child", position=tostr(samples) , showObject="1")
childNode.createObject('LinearMapping', template="Vec3d,Vec3d")
childNode = simNode.createChild('childF')
childNode.createObject('GaussPointContainer', position=tostr(samples))
childNode.createObject('MechanicalObject', template="F331", name="child")
childNode.createObject('LinearMapping', template="Vec3d,F331", showDeformationGradientScale="1")
childNode = simNode.createChild('Visu')
childNode.createObject('VisualModel', color="8e-1 8e-1 1 1e-1")
childNode.createObject('IdentityMapping')
childNode = simNode.createChild('Visu2')
childNode.createObject('VisualStyle', displayFlags="showWireframe")
childNode.createObject('VisualModel', color="8e-1 8e-1 1 1")
childNode.createObject('IdentityMapping')
simNode.createObject('PythonScriptController',filename="FEM.py", classname="Controller")
###########################################################
simNode = rootNode.createChild('Tetra_barycentric')
simNode.createObject('MeshTopology', name="mesh", position=tostr(restpos), tetrahedra="0 5 1 7 0 1 2 7 1 2 7 3 7 2 0 6 7 6 0 5 6 5 4 0")
simNode.createObject('MechanicalObject', template="Vec3d", name="parent", rest_position="@mesh.position",position=tostr(pos) )
simNode.createObject('BarycentricShapeFunction', position="@parent.rest_position", nbRef="4")
childNode = simNode.createChild('childP')
childNode.createObject('MechanicalObject', template="Vec3d", name="child", position=tostr(samples) , showObject="1")
childNode.createObject('LinearMapping', template="Vec3d,Vec3d")
childNode = simNode.createChild('childF')
childNode.createObject('GaussPointContainer', position=tostr(samples))
childNode.createObject('MechanicalObject', template="F331", name="child")
childNode.createObject('LinearMapping', template="Vec3d,F331")
simNode.createObject('PythonScriptController',filename="FEM.py", classname="Controller")
###########################################################
simNode = rootNode.createChild('Hexa_shepard')
simNode.createObject('MeshTopology', name="mesh", position=tostr(restpos), hexahedra="0 1 3 2 4 5 7 6")
simNode.createObject('MechanicalObject', template="Vec3d", name="parent", rest_position="@mesh.position",position=tostr(pos) )
simNode.createObject('ShepardShapeFunction', position="@parent.rest_position", power="2")
childNode = simNode.createChild('childP')
childNode.createObject('MechanicalObject', template="Vec3d", name="child", position=tostr(samples) , showObject="1")
childNode.createObject('LinearMapping', template="Vec3d,Vec3d")
childNode = simNode.createChild('childF')
childNode.createObject('GaussPointContainer', position=tostr(samples))
childNode.createObject('MechanicalObject', template="F331", name="child")
childNode.createObject('LinearMapping', template="Vec3d,F331")
simNode.createObject('PythonScriptController',filename="FEM.py", classname="Controller")
###########################################################
rootNode.animate=1
return rootNode
class Controller(Sofa.PythonScriptController):
def createGraph(self,node):
self.node=node
self.done=0
return 0
def onEndAnimationStep(self,dt):
if self.done==0:
print "TEST "+self.node.name+":"
# test points
restpos = self.node.getObject('childP/child').findData('rest_position').value
refpos = [transform(T,item) for item in restpos]
pos = self.node.getObject('childP/child').findData('position').value
error = compare(refpos,pos)
if error>ERRORTOL :
print "\t"+"\033[91m"+"[FAILED]"+"\033[0m"+" error on P= "+str(error)
else :
print "\t"+"\033[92m"+"[OK]"+"\033[0m"+" error on P= "+str(error)
# test defo gradients
restpos = [1,0,0,0,1,0,0,0,1]
pos = self.node.getObject('childF/child').findData('position').value
refpos = [transformF(T,restpos) for item in pos]
error = compare(refpos,pos)
if error>ERRORTOL :
print "\t"+"\033[91m"+"[FAILED]"+"\033[0m"+" error on F= "+str(error)
else :
print "\t"+"\033[92m"+"[OK]"+"\033[0m"+" error on F= "+str(error)
self.done=1
return 0
| FabienPean/sofa | applications/plugins/Flexible/examples/patch_test/FEM.py | Python | lgpl-2.1 | 6,005 |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#ifndef POSITIONERNODEINSTANCE_H
#define POSITIONERNODEINSTANCE_H
#include "qmlgraphicsitemnodeinstance.h"
QT_BEGIN_NAMESPACE
class QDeclarativeBasePositioner;
QT_END_NAMESPACE
namespace QmlDesigner {
namespace Internal {
class PositionerNodeInstance : public QmlGraphicsItemNodeInstance
{
public:
typedef QSharedPointer<PositionerNodeInstance> Pointer;
typedef QWeakPointer<PositionerNodeInstance> WeakPointer;
static Pointer create(QObject *objectToBeWrapped);
void setPropertyVariant(const PropertyName &name, const QVariant &value);
void setPropertyBinding(const PropertyName &name, const QString &expression);
bool isPositioner() const;
bool isResizable() const;
void refreshPositioner();
protected:
PositionerNodeInstance(QDeclarativeBasePositioner *item);
QDeclarativeBasePositioner *positioner() const;
};
} // namespace Internal
} // namespace QmlDesigner
#endif // POSITIONERNODEINSTANCE_H
| farseerri/git_code | share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/positionernodeinstance.h | C | lgpl-2.1 | 2,469 |
/* liblxcapi
*
* Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
* Copyright © 2012 Canonical Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of 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.
*/
#include "config.h"
#include <lxc/lxccontainer.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <errno.h>
#define MYNAME "lxctest1"
int main(int argc, char *argv[])
{
struct lxc_container *c;
int ret = 1;
if ((c = lxc_container_new(MYNAME, NULL)) == NULL) {
fprintf(stderr, "%d: error opening lxc_container %s\n", __LINE__, MYNAME);
ret = 1;
goto out;
}
if (c->is_defined(c)) {
fprintf(stderr, "%d: %s thought it was defined\n", __LINE__, MYNAME);
goto out;
}
if (!c->set_config_item(c, "lxc.net.0.type", "veth")) {
fprintf(stderr, "%d: failed to set network type\n", __LINE__);
goto out;
}
c->set_config_item(c, "lxc.net.0.link", "lxcbr0");
c->set_config_item(c, "lxc.net.0.flags", "up");
if (!c->createl(c, "busybox", NULL, NULL, 0, NULL)) {
fprintf(stderr, "%d: failed to create a container\n", __LINE__);
goto out;
}
if (!c->is_defined(c)) {
fprintf(stderr, "%d: %s thought it was not defined\n", __LINE__, MYNAME);
goto out;
}
c->clear_config(c);
c->load_config(c, NULL);
c->want_daemonize(c, true);
if (!c->startl(c, 0, NULL)) {
fprintf(stderr, "%d: failed to start %s\n", __LINE__, MYNAME);
goto out;
}
/* Wait for init to be ready for SIGPWR */
sleep(20);
if (!c->shutdown(c, 120)) {
fprintf(stderr, "%d: failed to shut down %s\n", __LINE__, MYNAME);
if (!c->stop(c))
fprintf(stderr, "%d: failed to kill %s\n", __LINE__, MYNAME);
goto out;
}
if (!c->destroy(c)) {
fprintf(stderr, "%d: error deleting %s\n", __LINE__, MYNAME);
goto out;
}
if (c->is_defined(c)) {
fprintf(stderr, "%d: %s thought it was defined\n", __LINE__, MYNAME);
goto out;
}
fprintf(stderr, "all lxc_container tests passed for %s\n", c->name);
ret = 0;
out:
if (c && c->is_defined(c))
c->destroy(c);
lxc_container_put(c);
exit(ret);
}
| Blub/lxc | src/tests/shutdowntest.c | C | lgpl-2.1 | 2,671 |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Serf(SConsPackage):
"""Apache Serf - a high performance C-based HTTP client library
built upon the Apache Portable Runtime (APR) library"""
homepage = 'https://serf.apache.org/'
url = 'https://archive.apache.org/dist/serf/serf-1.3.9.tar.bz2'
maintainers = ['cosmicexplorer']
version('1.3.9', sha256='549c2d21c577a8a9c0450facb5cca809f26591f048e466552240947bdf7a87cc')
version('1.3.8', sha256='e0500be065dbbce490449837bb2ab624e46d64fc0b090474d9acaa87c82b2590')
variant('debug', default=False,
description='Enable debugging info and strict compile warnings')
depends_on('apr')
depends_on('apr-util')
depends_on('openssl')
depends_on('python+pythoncmd', type='build')
depends_on('scons@2.3.0:', type='build')
depends_on('uuid')
depends_on('zlib')
patch('py3syntax.patch')
patch('py3-hashbang.patch')
def build_args(self, spec, prefix):
args = {
'PREFIX': prefix,
'APR': spec['apr'].prefix,
'APU': spec['apr-util'].prefix,
'OPENSSL': spec['openssl'].prefix,
'ZLIB': spec['zlib'].prefix,
'DEBUG': 'yes' if '+debug' in spec else 'no',
}
# SCons doesn't pass Spack environment variables to the
# execution environment. Therefore, we can't use Spack's compiler
# wrappers. Use the actual compilers. SCons seems to RPATH things
# on its own anyway.
args['CC'] = self.compiler.cc
# Old versions of serf ignore the ZLIB variable on non-Windows platforms.
# Also, there is no UUID variable to specify its installation location.
# Pass explicit link flags for both.
library_dirs = []
include_dirs = []
for dep in spec.dependencies(deptype='link'):
query = self.spec[dep.name]
library_dirs.extend(query.libs.directories)
include_dirs.extend(query.headers.directories)
rpath = self.compiler.cc_rpath_arg
args['LINKFLAGS'] = '-L' + ' -L'.join(library_dirs)
args['LINKFLAGS'] += ' ' + rpath + (' ' + rpath).join(library_dirs)
args['CPPFLAGS'] = '-I' + ' -I'.join(include_dirs)
return [key + '=' + value for key, value in args.items()]
def build_test(self):
# FIXME: Several test failures:
#
# There were 14 failures:
# 1) test_ssl_trust_rootca
# 2) test_ssl_certificate_chain_with_anchor
# 3) test_ssl_certificate_chain_all_from_server
# 4) test_ssl_no_servercert_callback_allok
# 5) test_ssl_large_response
# 6) test_ssl_large_request
# 7) test_ssl_client_certificate
# 8) test_ssl_future_server_cert
# 9) test_setup_ssltunnel
# 10) test_ssltunnel_basic_auth
# 11) test_ssltunnel_basic_auth_server_has_keepalive_off
# 12) test_ssltunnel_basic_auth_proxy_has_keepalive_off
# 13) test_ssltunnel_basic_auth_proxy_close_conn_on_200resp
# 14) test_ssltunnel_digest_auth
#
# These seem to be related to:
# https://groups.google.com/forum/#!topic/serf-dev/YEFTTdF1Qwc
scons('check')
| LLNL/spack | var/spack/repos/builtin/packages/serf/package.py | Python | lgpl-2.1 | 3,412 |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
/*
* Expected: 'i_first' 'c_first'
* Not expected: 'i_second' 'c_second' 'f_second'
*/
typedef struct {
int i_first;
char c_first;
} S1;
typedef struct {
int i_second;
char c_second;
float f_second;
} S2;
void foo()
{
S1 s;
s.<<<<;
}
| maui-packages/qt-creator | src/plugins/clangcodemodel/test/cxx_regression_2.cpp | C++ | lgpl-2.1 | 1,722 |
\hypertarget{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor}{}\section{Cqrs.\+Akka.\+Tests.\+Unit.\+Events.\+Handlers.\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor Class Reference}
\label{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor}\index{Cqrs.\+Akka.\+Tests.\+Unit.\+Events.\+Handlers.\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor@{Cqrs.\+Akka.\+Tests.\+Unit.\+Events.\+Handlers.\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor}}
An Akka.\+Net based I\+Event\+Handler that handles the \hyperlink{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1HelloWorldRepliedTo}{Hello\+World\+Replied\+To}.
Inheritance diagram for Cqrs.\+Akka.\+Tests.\+Unit.\+Events.\+Handlers.\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor\+:\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[height=2.000000cm]{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor}
\end{center}
\end{figure}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
void \hyperlink{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor_a9d843860260cd66f8354b9df234a1663_a9d843860260cd66f8354b9df234a1663}{Handle} (\hyperlink{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1HelloWorldRepliedTo}{Hello\+World\+Replied\+To} message)
\begin{DoxyCompactList}\small\item\em Responds to the provided {\itshape message} . \end{DoxyCompactList}\item
\hyperlink{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor_a174cd0183fbe16aaa74f18320e871a5f_a174cd0183fbe16aaa74f18320e871a5f}{Hello\+World\+Replied\+To\+Event\+Handler\+Actor} (I\+Logger logger, I\+Correlation\+Id\+Helper correlation\+Id\+Helper, \hyperlink{interfaceCqrs_1_1Authentication_1_1IAuthenticationTokenHelper}{I\+Authentication\+Token\+Helper}$<$ Guid $>$ authentication\+Token\+Helper)
\begin{DoxyCompactList}\small\item\em Instantiates a new instance of \hyperlink{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor}{Hello\+World\+Replied\+To\+Event\+Handler\+Actor}. \end{DoxyCompactList}\end{DoxyCompactItemize}
\subsection*{Additional Inherited Members}
\subsection{Detailed Description}
An Akka.\+Net based I\+Event\+Handler that handles the \hyperlink{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1HelloWorldRepliedTo}{Hello\+World\+Replied\+To}.
\subsection{Constructor \& Destructor Documentation}
\mbox{\Hypertarget{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor_a174cd0183fbe16aaa74f18320e871a5f_a174cd0183fbe16aaa74f18320e871a5f}\label{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor_a174cd0183fbe16aaa74f18320e871a5f_a174cd0183fbe16aaa74f18320e871a5f}}
\index{Cqrs\+::\+Akka\+::\+Tests\+::\+Unit\+::\+Events\+::\+Handlers\+::\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor@{Cqrs\+::\+Akka\+::\+Tests\+::\+Unit\+::\+Events\+::\+Handlers\+::\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor}!Hello\+World\+Replied\+To\+Event\+Handler\+Actor@{Hello\+World\+Replied\+To\+Event\+Handler\+Actor}}
\index{Hello\+World\+Replied\+To\+Event\+Handler\+Actor@{Hello\+World\+Replied\+To\+Event\+Handler\+Actor}!Cqrs\+::\+Akka\+::\+Tests\+::\+Unit\+::\+Events\+::\+Handlers\+::\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor@{Cqrs\+::\+Akka\+::\+Tests\+::\+Unit\+::\+Events\+::\+Handlers\+::\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor}}
\subsubsection{\texorpdfstring{Hello\+World\+Replied\+To\+Event\+Handler\+Actor()}{HelloWorldRepliedToEventHandlerActor()}}
{\footnotesize\ttfamily Cqrs.\+Akka.\+Tests.\+Unit.\+Events.\+Handlers.\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor.\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor (\begin{DoxyParamCaption}\item[{I\+Logger}]{logger, }\item[{I\+Correlation\+Id\+Helper}]{correlation\+Id\+Helper, }\item[{\hyperlink{interfaceCqrs_1_1Authentication_1_1IAuthenticationTokenHelper}{I\+Authentication\+Token\+Helper}$<$ Guid $>$}]{authentication\+Token\+Helper }\end{DoxyParamCaption})}
Instantiates a new instance of \hyperlink{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor}{Hello\+World\+Replied\+To\+Event\+Handler\+Actor}.
\subsection{Member Function Documentation}
\mbox{\Hypertarget{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor_a9d843860260cd66f8354b9df234a1663_a9d843860260cd66f8354b9df234a1663}\label{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor_a9d843860260cd66f8354b9df234a1663_a9d843860260cd66f8354b9df234a1663}}
\index{Cqrs\+::\+Akka\+::\+Tests\+::\+Unit\+::\+Events\+::\+Handlers\+::\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor@{Cqrs\+::\+Akka\+::\+Tests\+::\+Unit\+::\+Events\+::\+Handlers\+::\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor}!Handle@{Handle}}
\index{Handle@{Handle}!Cqrs\+::\+Akka\+::\+Tests\+::\+Unit\+::\+Events\+::\+Handlers\+::\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor@{Cqrs\+::\+Akka\+::\+Tests\+::\+Unit\+::\+Events\+::\+Handlers\+::\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor}}
\subsubsection{\texorpdfstring{Handle()}{Handle()}}
{\footnotesize\ttfamily void Cqrs.\+Akka.\+Tests.\+Unit.\+Events.\+Handlers.\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor.\+Handle (\begin{DoxyParamCaption}\item[{\hyperlink{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1HelloWorldRepliedTo}{Hello\+World\+Replied\+To}}]{message }\end{DoxyParamCaption})}
Responds to the provided {\itshape message} .
\begin{DoxyParams}{Parameters}
{\em message} & The \hyperlink{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1HelloWorldRepliedTo}{Hello\+World\+Replied\+To} to respond to or \char`\"{}handle\char`\"{}\\
\hline
\end{DoxyParams}
| cdmdotnet/CQRS | wiki/docs/2.4/latex/classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor.tex | TeX | lgpl-2.1 | 5,959 |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmlconsoleview.h"
#include "qmlconsoleitemdelegate.h"
#include "qmlconsoleitemmodel.h"
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/manhattanstyle.h>
#include <utils/hostosinfo.h>
#include <QMouseEvent>
#include <QPainter>
#include <QApplication>
#include <QClipboard>
#include <QAbstractProxyModel>
#include <QFileInfo>
#include <QScrollBar>
#include <QStyleFactory>
#include <QString>
#include <QUrl>
using namespace QmlJS;
namespace QmlJSTools {
namespace Internal {
class QmlConsoleViewStyle : public ManhattanStyle
{
public:
QmlConsoleViewStyle(const QString &baseStyleName) : ManhattanStyle(baseStyleName) {}
void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter,
const QWidget *widget = 0) const
{
if (element != QStyle::PE_PanelItemViewRow)
ManhattanStyle::drawPrimitive(element, option, painter, widget);
}
int styleHint(StyleHint hint, const QStyleOption *option = 0, const QWidget *widget = 0,
QStyleHintReturn *returnData = 0) const {
if (hint == SH_ItemView_ShowDecorationSelected)
return 0;
else
return ManhattanStyle::styleHint(hint, option, widget, returnData);
}
};
///////////////////////////////////////////////////////////////////////
//
// QmlConsoleView
//
///////////////////////////////////////////////////////////////////////
QmlConsoleView::QmlConsoleView(QWidget *parent) :
Utils::TreeView(parent)
{
setFrameStyle(QFrame::NoFrame);
setHeaderHidden(true);
setRootIsDecorated(false);
setUniformRowHeights(true);
setEditTriggers(QAbstractItemView::AllEditTriggers);
setStyleSheet(QLatin1String("QTreeView::branch:has-siblings:!adjoins-item {"
"border-image: none;"
"image: none; }"
"QTreeView::branch:has-siblings:adjoins-item {"
"border-image: none;"
"image: none; }"
"QTreeView::branch:!has-children:!has-siblings:adjoins-item {"
"border-image: none;"
"image: none; }"
"QTreeView::branch:has-children:!has-siblings:closed,"
"QTreeView::branch:closed:has-children:has-siblings {"
"border-image: none;"
"image: none; }"
"QTreeView::branch:open:has-children:!has-siblings,"
"QTreeView::branch:open:has-children:has-siblings {"
"border-image: none;"
"image: none; }"));
QString baseName = QApplication::style()->objectName();
if (Utils::HostOsInfo::isAnyUnixHost() && !Utils::HostOsInfo::isMacHost()
&& baseName == QLatin1String("windows")) {
// Sometimes we get the standard windows 95 style as a fallback
if (QStyleFactory::keys().contains(QLatin1String("Fusion"))) {
baseName = QLatin1String("fusion"); // Qt5
} else { // Qt4
// e.g. if we are running on a KDE4 desktop
QByteArray desktopEnvironment = qgetenv("DESKTOP_SESSION");
if (desktopEnvironment == "kde")
baseName = QLatin1String("plastique");
else
baseName = QLatin1String("cleanlooks");
}
}
QmlConsoleViewStyle *style = new QmlConsoleViewStyle(baseName);
setStyle(style);
style->setParent(this);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
horizontalScrollBar()->setSingleStep(20);
verticalScrollBar()->setSingleStep(20);
connect(this, SIGNAL(activated(QModelIndex)), SLOT(onRowActivated(QModelIndex)));
}
void QmlConsoleView::onScrollToBottom()
{
// Keep scrolling to bottom if scroll bar is not at maximum()
if (verticalScrollBar()->value() != verticalScrollBar()->maximum())
scrollToBottom();
}
void QmlConsoleView::mousePressEvent(QMouseEvent *event)
{
QPoint pos = event->pos();
QModelIndex index = indexAt(pos);
if (index.isValid()) {
ConsoleItem::ItemType type = (ConsoleItem::ItemType)index.data(
QmlConsoleItemModel::TypeRole).toInt();
bool handled = false;
if (type == ConsoleItem::UndefinedType) {
bool showTypeIcon = index.parent() == QModelIndex();
ConsoleItemPositions positions(visualRect(index), viewOptions().font, showTypeIcon,
true);
if (positions.expandCollapseIcon().contains(pos)) {
if (isExpanded(index))
setExpanded(index, false);
else
setExpanded(index, true);
handled = true;
}
}
if (!handled)
Utils::TreeView::mousePressEvent(event);
} else {
selectionModel()->setCurrentIndex(model()->index(model()->rowCount() - 1, 0),
QItemSelectionModel::ClearAndSelect);
}
}
void QmlConsoleView::resizeEvent(QResizeEvent *e)
{
static_cast<QmlConsoleItemDelegate *>(itemDelegate())->emitSizeHintChanged(
selectionModel()->currentIndex());
Utils::TreeView::resizeEvent(e);
}
void QmlConsoleView::drawBranches(QPainter *painter, const QRect &rect,
const QModelIndex &index) const
{
static_cast<QmlConsoleItemDelegate *>(itemDelegate())->drawBackground(painter, rect, index,
false);
Utils::TreeView::drawBranches(painter, rect, index);
}
void QmlConsoleView::contextMenuEvent(QContextMenuEvent *event)
{
QModelIndex itemIndex = indexAt(event->pos());
QMenu menu;
QAction *copy = new QAction(tr("&Copy"), this);
copy->setEnabled(itemIndex.isValid());
menu.addAction(copy);
QAction *show = new QAction(tr("&Show in Editor"), this);
show->setEnabled(canShowItemInTextEditor(itemIndex));
menu.addAction(show);
menu.addSeparator();
QAction *clear = new QAction(tr("C&lear"), this);
menu.addAction(clear);
QAction *a = menu.exec(event->globalPos());
if (a == 0)
return;
if (a == copy) {
copyToClipboard(itemIndex);
} else if (a == show) {
onRowActivated(itemIndex);
} else if (a == clear) {
QAbstractProxyModel *proxyModel = qobject_cast<QAbstractProxyModel *>(model());
QmlConsoleItemModel *handler = qobject_cast<QmlConsoleItemModel *>(
proxyModel->sourceModel());
handler->clear();
}
}
void QmlConsoleView::onRowActivated(const QModelIndex &index)
{
if (!index.isValid())
return;
// See if we have file and line Info
QString filePath = model()->data(index, QmlConsoleItemModel::FileRole).toString();
const QUrl fileUrl = QUrl(filePath);
if (fileUrl.isLocalFile())
filePath = fileUrl.toLocalFile();
if (!filePath.isEmpty()) {
QFileInfo fi(filePath);
if (fi.exists() && fi.isFile() && fi.isReadable()) {
int line = model()->data(index, QmlConsoleItemModel::LineRole).toInt();
Core::EditorManager::openEditorAt(fi.canonicalFilePath(), line);
}
}
}
void QmlConsoleView::copyToClipboard(const QModelIndex &index)
{
if (!index.isValid())
return;
QString contents = model()->data(index, QmlConsoleItemModel::ExpressionRole).toString();
// See if we have file and line Info
QString filePath = model()->data(index, QmlConsoleItemModel::FileRole).toString();
const QUrl fileUrl = QUrl(filePath);
if (fileUrl.isLocalFile())
filePath = fileUrl.toLocalFile();
if (!filePath.isEmpty()) {
contents = QString::fromLatin1("%1 %2: %3").arg(contents).arg(filePath).arg(
model()->data(index, QmlConsoleItemModel::LineRole).toString());
}
QClipboard *cb = QApplication::clipboard();
cb->setText(contents);
}
bool QmlConsoleView::canShowItemInTextEditor(const QModelIndex &index)
{
if (!index.isValid())
return false;
// See if we have file and line Info
QString filePath = model()->data(index, QmlConsoleItemModel::FileRole).toString();
const QUrl fileUrl = QUrl(filePath);
if (fileUrl.isLocalFile())
filePath = fileUrl.toLocalFile();
if (!filePath.isEmpty()) {
QFileInfo fi(filePath);
if (fi.exists() && fi.isFile() && fi.isReadable())
return true;
}
return false;
}
} // Internal
} // QmlJSTools
| AltarBeastiful/qt-creator | src/plugins/qmljstools/qmlconsoleview.cpp | C++ | lgpl-2.1 | 10,425 |
/********************************************************************************/
/* Projeto: Biblioteca ZeusDFe */
/* Biblioteca C# para auxiliar no desenvolvimento das demais bibliotecas DFe */
/* */
/* */
/* Direitos Autorais Reservados (c) 2014 Adenilton Batista da Silva */
/* Zeusdev Tecnologia LTDA ME */
/* */
/* Você pode obter a última versão desse arquivo no GitHub */
/* localizado em https://github.com/adeniltonbs/Zeus.Net.NFe.NFCe */
/* */
/* */
/* Esta biblioteca é software livre; você pode redistribuí-la e/ou modificá-la */
/* sob os termos da Licença Pública Geral Menor do GNU conforme publicada pela */
/* Free Software Foundation; tanto a versão 2.1 da Licença, ou (a seu critério) */
/* qualquer versão posterior. */
/* */
/* Esta biblioteca é distribuída na expectativa de que seja útil, porém, SEM */
/* NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU */
/* ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral Menor*/
/* do GNU para mais detalhes. (Arquivo LICENÇA.TXT ou LICENSE.TXT) */
/* */
/* Você deve ter recebido uma cópia da Licença Pública Geral Menor do GNU junto*/
/* com esta biblioteca; se não, escreva para a Free Software Foundation, Inc., */
/* no endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. */
/* Você também pode obter uma copia da licença em: */
/* http://www.opensource.org/licenses/lgpl-license.php */
/* */
/* Zeusdev Tecnologia LTDA ME - adenilton@zeusautomacao.com.br */
/* http://www.zeusautomacao.com.br/ */
/* Rua Comendador Francisco josé da Cunha, 111 - Itabaiana - SE - 49500-000 */
/********************************************************************************/
using System.Xml.Serialization;
namespace DFe.Classes.Assinatura
{
public class Transform
{
/// <summary>
/// XS13 - Atributos válidos Algorithm do Transform:
/// <para>http://www.w3.org/TR/2001/REC-xml-c14n-20010315</para>
/// <para>http://www.w3.org/2000/09/xmldsig#enveloped-signature</para>
/// </summary>
[XmlAttribute]
public string Algorithm { get; set; }
}
} | adrbarros/Zeus.Net.NFe.NFCe | Shared.DFe.Classes/Assinatura/Transform.cs | C# | lgpl-2.1 | 3,142 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LCOV - doc-coverage.info - Ninject/Azure/Cqrs.Ninject.Azure.BlobStorage/Configuration/BlobStorageDataStoreModule.cs</title>
<link rel="stylesheet" type="text/css" href="../../../../gcov.css">
</head>
<body>
<table width="100%" border=0 cellspacing=0 cellpadding=0>
<tr><td class="title">LCOV - code coverage report</td></tr>
<tr><td class="ruler"><img src="../../../../glass.png" width=3 height=3 alt=""></td></tr>
<tr>
<td width="100%">
<table cellpadding=1 border=0 width="100%">
<tr>
<td width="10%" class="headerItem">Current view:</td>
<td width="35%" class="headerValue"><a href="../../../../index.html">top level</a> - <a href="index.html">Ninject/Azure/Cqrs.Ninject.Azure.BlobStorage/Configuration</a> - BlobStorageDataStoreModule.cs</td>
<td width="5%"></td>
<td width="15%"></td>
<td width="10%" class="headerCovTableHead">Hit</td>
<td width="10%" class="headerCovTableHead">Total</td>
<td width="15%" class="headerCovTableHead">Coverage</td>
</tr>
<tr>
<td class="headerItem">Test:</td>
<td class="headerValue">doc-coverage.info</td>
<td></td>
<td class="headerItem">Lines:</td>
<td class="headerCovTableEntry">4</td>
<td class="headerCovTableEntry">5</td>
<td class="headerCovTableEntryMed">80.0 %</td>
</tr>
<tr>
<td class="headerItem">Date:</td>
<td class="headerValue">2017-07-26</td>
<td></td>
</tr>
<tr><td><img src="../../../../glass.png" width=3 height=3 alt=""></td></tr>
</table>
</td>
</tr>
<tr><td class="ruler"><img src="../../../../glass.png" width=3 height=3 alt=""></td></tr>
</table>
<table cellpadding=0 cellspacing=0 border=0>
<tr>
<td><br></td>
</tr>
<tr>
<td>
<pre class="sourceHeading"> Line data Source code</pre>
<pre class="source">
<span class="lineNum"> 1 </span> : #region Copyright
<span class="lineNum"> 2 </span> : // // -----------------------------------------------------------------------
<span class="lineNum"> 3 </span> : // // <copyright company="cdmdotnet Limited">
<span class="lineNum"> 4 </span> : // // Copyright cdmdotnet Limited. All rights reserved.
<span class="lineNum"> 5 </span> : // // </copyright>
<span class="lineNum"> 6 </span> : // // -----------------------------------------------------------------------
<span class="lineNum"> 7 </span> : #endregion
<span class="lineNum"> 8 </span> :
<span class="lineNum"> 9 </span> : using Cqrs.Azure.BlobStorage.DataStores;
<span class="lineNum"> 10 </span> : using Ninject.Modules;
<span class="lineNum"> 11 </span> :
<span class="lineNum"> 12 </span> : namespace Cqrs.Ninject.Azure.BlobStorage.Configuration
<span class="lineNum"> 13 </span> : {
<span class="lineNum"> 14 </span> : public class BlobStorageDataStoreModule : NinjectModule
<span class="lineNum"> 15 </span><span class="lineNoCov"> 0 : {</span>
<span class="lineNum"> 16 </span> : #region Overrides of NinjectModule
<span class="lineNum"> 17 </span> :
<span class="lineNum"> 18 </span> : /// <summary>
<span class="lineNum"> 19 </span> : /// Loads the module into the kernel.
<span class="lineNum"> 20 </span> : /// </summary>
<span class="lineNum"> 21 </span><span class="lineCov"> 1 : public override void Load()</span>
<span class="lineNum"> 22 </span> : {
<span class="lineNum"> 23 </span> : RegisterFactories();
<span class="lineNum"> 24 </span> : RegisterServices();
<span class="lineNum"> 25 </span> : RegisterCqrsRequirements();
<span class="lineNum"> 26 </span> : }
<span class="lineNum"> 27 </span> :
<span class="lineNum"> 28 </span> : #endregion
<span class="lineNum"> 29 </span> :
<span class="lineNum"> 30 </span> : /// <summary>
<span class="lineNum"> 31 </span> : /// Register the all services
<span class="lineNum"> 32 </span> : /// </summary>
<span class="lineNum"> 33 </span><span class="lineCov"> 1 : public virtual void RegisterServices()</span>
<span class="lineNum"> 34 </span> : {
<span class="lineNum"> 35 </span> : }
<span class="lineNum"> 36 </span> :
<span class="lineNum"> 37 </span> : /// <summary>
<span class="lineNum"> 38 </span> : /// Register the all factories
<span class="lineNum"> 39 </span> : /// </summary>
<span class="lineNum"> 40 </span><span class="lineCov"> 1 : public virtual void RegisterFactories()</span>
<span class="lineNum"> 41 </span> : {
<span class="lineNum"> 42 </span> : Bind<IBlobStorageDataStoreConnectionStringFactory>()
<span class="lineNum"> 43 </span> : .To<BlobStorageDataStoreConnectionStringFactory>()
<span class="lineNum"> 44 </span> : .InSingletonScope();
<span class="lineNum"> 45 </span> : }
<span class="lineNum"> 46 </span> :
<span class="lineNum"> 47 </span> : /// <summary>
<span class="lineNum"> 48 </span> : /// Register the all Cqrs command handlers
<span class="lineNum"> 49 </span> : /// </summary>
<span class="lineNum"> 50 </span><span class="lineCov"> 1 : public virtual void RegisterCqrsRequirements()</span>
<span class="lineNum"> 51 </span> : {
<span class="lineNum"> 52 </span> : }
<span class="lineNum"> 53 </span> : }
<span class="lineNum"> 54 </span> : }
</pre>
</td>
</tr>
</table>
<br>
<table width="100%" border=0 cellspacing=0 cellpadding=0>
<tr><td class="ruler"><img src="../../../../glass.png" width=3 height=3 alt=""></td></tr>
<tr><td class="versionInfo">Generated by: <a href="http://ltp.sourceforge.net/coverage/lcov.php" target="_parent">LCOV version 1.10</a></td></tr>
</table>
<br>
</body>
</html>
| cdmdotnet/CQRS | wiki/docs/2.1/coverage-report/Ninject/Azure/Cqrs.Ninject.Azure.BlobStorage/Configuration/BlobStorageDataStoreModule.cs.gcov.html | HTML | lgpl-2.1 | 7,402 |
// ---------------------------------------------------------------------
//
// Copyright (C) 2009 - 2014 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// make sure only one processor finds a locally-owned cell around a point
#include "../tests.h"
#include "coarse_grid_common.h"
#include <deal.II/base/logstream.h>
#include <deal.II/base/tensor.h>
#include <deal.II/grid/tria.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_out.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/base/utilities.h>
#include <fstream>
template<int dim>
void test()
{
unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD);
if (true)
{
if (Utilities::MPI::this_mpi_process (MPI_COMM_WORLD) == 0)
deallog << "hyper_cube" << std::endl;
parallel::distributed::Triangulation<dim> tr(MPI_COMM_WORLD);
GridGenerator::hyper_cube(tr);
tr.refine_global(2);
// choose a point that is guaranteed to lie in the domain but not
// at the interface between cells
Point<dim> p;
for (unsigned int d=0; d<dim; ++d)
p[d] = 1./3;
typename parallel::distributed::Triangulation<dim>::active_cell_iterator
cell = GridTools::find_active_cell_around_point (tr, p);
const unsigned int
n_locally_owned
= Utilities::MPI::sum (cell->is_locally_owned() ? 1 : 0,
MPI_COMM_WORLD);
const unsigned int
n_locally_owned_or_ghost
= Utilities::MPI::sum (!cell->is_artificial() ? 1 : 0,
MPI_COMM_WORLD);
if (myid == 0)
deallog << "Locally owned: "
<< n_locally_owned
<< std::endl
<< "Locally owned or ghost: "
<< n_locally_owned_or_ghost
<< std::endl;
}
}
int main(int argc, char *argv[])
{
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD);
deallog.push(Utilities::int_to_string(myid));
if (myid == 0)
{
std::ofstream logfile("output");
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
deallog.push("2d");
test<2>();
deallog.pop();
deallog.push("3d");
test<3>();
deallog.pop();
}
else
{
test<2>();
test<3>();
}
}
| natashasharma/dealii | tests/mpi/find_active_cell_around_point_01.cc | C++ | lgpl-2.1 | 2,929 |
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtXmlPatterns module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qnamepool_p.h"
#include "qdelegatingnamespaceresolver_p.h"
QT_BEGIN_NAMESPACE
using namespace QPatternist;
DelegatingNamespaceResolver::DelegatingNamespaceResolver(const NamespaceResolver::Ptr &resolver) : m_nsResolver(resolver)
{
Q_ASSERT(m_nsResolver);
}
DelegatingNamespaceResolver::DelegatingNamespaceResolver(const NamespaceResolver::Ptr &ns,
const Bindings &overrides) : m_nsResolver(ns)
, m_bindings(overrides)
{
Q_ASSERT(m_nsResolver);
}
QXmlName::NamespaceCode DelegatingNamespaceResolver::lookupNamespaceURI(const QXmlName::PrefixCode prefix) const
{
const QXmlName::NamespaceCode val(m_bindings.value(prefix, NoBinding));
if(val == NoBinding)
return m_nsResolver->lookupNamespaceURI(prefix);
else
return val;
}
NamespaceResolver::Bindings DelegatingNamespaceResolver::bindings() const
{
Bindings bs(m_nsResolver->bindings());
const Bindings::const_iterator end(m_bindings.constEnd());
Bindings::const_iterator it(m_bindings.constBegin());
for(; it != end; ++it)
bs.insert(it.key(), it.value());
return bs;
}
void DelegatingNamespaceResolver::addBinding(const QXmlName nb)
{
if(nb.namespaceURI() == StandardNamespaces::UndeclarePrefix)
m_bindings.remove(nb.prefix());
else
m_bindings.insert(nb.prefix(), nb.namespaceURI());
}
QT_END_NAMESPACE
| RLovelett/qt | src/xmlpatterns/utils/qdelegatingnamespaceresolver.cpp | C++ | lgpl-2.1 | 3,480 |
#ifndef H_RED_TIME
#define H_RED_TIME
#include <time.h>
static inline uint64_t red_now(void)
{
struct timespec time;
clock_gettime(CLOCK_MONOTONIC, &time);
return ((uint64_t) time.tv_sec) * 1000000000 + time.tv_nsec;
}
#endif
| alon/spice-server | server/red_time.h | C | lgpl-2.1 | 243 |
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../fast/js/resources/js-test-style.css"/>
<script src="resources/audio-testing.js"></script>
<script src="../fast/js/resources/js-test-pre.js"></script>
<script src="resources/biquad-testing.js"></script>
</head>
<body>
<div id="description"></div>
<div id="console"></div>
<script>
description("Tests Biquad peaking filter.");
function runTest() {
if (window.testRunner) {
testRunner.dumpAsText();
testRunner.waitUntilDone();
}
window.jsTestIsAsync = true;
// Create offline audio context.
var context = new webkitOfflineAudioContext(2, sampleRate * renderLengthSeconds, sampleRate);
// Dummy filter to get filter type constant
var f = context.createBiquadFilter();
// The filters we want to test.
var filterParameters = [{cutoff : 0, q : 10, gain : 10 },
{cutoff : 1, q : 10, gain : 10 },
{cutoff : .5, q : 0, gain : 10 },
{cutoff : 0.25, q : 10, gain : 10 },
];
createTestAndRun(context, f.PEAKING, filterParameters);
}
runTest();
successfullyParsed = true;
</script>
<script src="../fast/js/resources/js-test-post.js"></script>
</body>
</html>
| youfoh/webkit-efl | LayoutTests/webaudio/biquad-peaking.html | HTML | lgpl-2.1 | 1,308 |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Qnnpack(CMakePackage):
"""QNNPACK (Quantized Neural Networks PACKage) is a mobile-optimized
library for low-precision high-performance neural network inference.
QNNPACK provides implementation of common neural network operators on
quantized 8-bit tensors."""
homepage = "https://github.com/pytorch/QNNPACK"
git = "https://github.com/pytorch/QNNPACK.git"
version('master', branch='master')
version('2019-08-28', commit='7d2a4e9931a82adc3814275b6219a03e24e36b4c') # py-torch@1.3:1.9
version('2018-12-27', commit='6c62fddc6d15602be27e9e4cbb9e985151d2fa82') # py-torch@1.2
version('2018-12-04', commit='ef05e87cef6b8e719989ce875b5e1c9fdb304c05') # py-torch@1.0:1.1
depends_on('cmake@3.5:', type='build')
depends_on('ninja', type='build')
depends_on('python', type='build')
resource(
name='cpuinfo',
git='https://github.com/Maratyszcza/cpuinfo.git',
destination='deps',
placement='cpuinfo'
)
resource(
name='fp16',
git='https://github.com/Maratyszcza/FP16.git',
destination='deps',
placement='fp16'
)
resource(
name='fxdiv',
git='https://github.com/Maratyszcza/FXdiv.git',
destination='deps',
placement='fxdiv'
)
resource(
name='googlebenchmark',
url='https://github.com/google/benchmark/archive/v1.4.1.zip',
sha256='61ae07eb5d4a0b02753419eb17a82b7d322786bb36ab62bd3df331a4d47c00a7',
destination='deps',
placement='googlebenchmark',
)
resource(
name='googletest',
url='https://github.com/google/googletest/archive/release-1.8.0.zip',
sha256='f3ed3b58511efd272eb074a3a6d6fb79d7c2e6a0e374323d1e6bcbcc1ef141bf',
destination='deps',
placement='googletest',
)
resource(
name='psimd',
git='https://github.com/Maratyszcza/psimd.git',
destination='deps',
placement='psimd'
)
resource(
name='pthreadpool',
git='https://github.com/Maratyszcza/pthreadpool.git',
destination='deps',
placement='pthreadpool'
)
generator = 'Ninja'
def cmake_args(self):
return [
self.define('CPUINFO_SOURCE_DIR',
join_path(self.stage.source_path, 'deps', 'cpuinfo')),
self.define('FP16_SOURCE_DIR',
join_path(self.stage.source_path, 'deps', 'fp16')),
self.define('FXDIV_SOURCE_DIR',
join_path(self.stage.source_path, 'deps', 'fxdiv')),
self.define('PSIMD_SOURCE_DIR',
join_path(self.stage.source_path, 'deps', 'psimd')),
self.define('PTHREADPOOL_SOURCE_DIR',
join_path(self.stage.source_path, 'deps', 'pthreadpool')),
self.define('GOOGLEBENCHMARK_SOURCE_DIR',
join_path(self.stage.source_path, 'deps', 'googlebenchmark')),
self.define('GOOGLETEST_SOURCE_DIR',
join_path(self.stage.source_path, 'deps', 'googletest')),
]
| LLNL/spack | var/spack/repos/builtin/packages/qnnpack/package.py | Python | lgpl-2.1 | 3,348 |
/* **********************************************************
* Copyright (c) 2012 Google, Inc. All rights reserved.
* Copyright (c) 2009 VMware, Inc. All rights reserved.
* **********************************************************/
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of VMware, Inc. nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
/*
* nudgeunix.c: nudges a target Linux process
*
* XXX: share code with DRcontrol.c?
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <assert.h>
#include "configure.h"
#include "globals_shared.h"
extern bool
create_nudge_signal_payload(siginfo_t *info OUT, uint action_mask,
client_id_t client_id, uint64 client_arg);
static const char *usage_str =
"usage: nudgeunix [-help] [-v] [-pid <pid>] [-type <type>] [-client <ID> <arg>]\n"
" -help Display this usage information\n"
" -v Display version information\n"
" -pid <pid> Nudge the process with id <pid>\n"
" -client <ID> <arg>\n"
" Nudge the client with ID <ID> in the process specified\n"
" with -pid <pid>, and pass <arg> as an argument to the\n"
" client's nudge callback. <ID> must be the 8-digit hex\n"
" ID of the target client. <arg> should be a hex\n"
" literal (0, 1, 3f etc.).\n"
" -type <type>\n"
" Send a nudge of type <type> to the process specified\n"
" with -pid <pid>. Type can be a numeric value or a\n"
" symbolic name. This argument can be repeated.\n"
" E.g., \"-type reset -type stats\".\n"
;
static int
usage(void)
{
fprintf(stderr, "%s", usage_str);
return 1;
}
int
main(int argc, const char *argv[])
{
process_id_t target_pid = 0;
uint action_mask = 0;
client_id_t client_id = 0;
uint64 client_arg = 0;
int i;
siginfo_t info;
int arg_offs = 1;
bool success;
/* parse command line */
if (argc <= 1)
return usage();
while (arg_offs < argc && argv[arg_offs][0] == '-') {
if (strcmp(argv[arg_offs], "-help") == 0) {
return usage();
} else if (strcmp(argv[arg_offs], "-v") == 0) {
printf("nudgeunix version %s -- build %d\n",
STRINGIFY(VERSION_NUMBER), BUILD_NUMBER);
exit(0);
} else if (strcmp(argv[arg_offs], "-pid") == 0) {
if (argc <= arg_offs+1)
return usage();
target_pid = strtoul(argv[arg_offs+1], NULL, 10);
arg_offs += 2;
} else if (strcmp(argv[arg_offs], "-client") == 0) {
if (argc <= arg_offs+2)
return usage();
action_mask |= NUDGE_GENERIC(client);
client_id = strtoul(argv[arg_offs+1], NULL, 16);
client_arg = strtoull(argv[arg_offs+2], NULL, 16);
arg_offs += 3;
} else if (strcmp(argv[arg_offs], "-type") == 0) {
int type_numeric;
if (argc <= arg_offs+1)
return usage();
type_numeric = strtoul(argv[arg_offs+1], NULL, 10);
action_mask |= type_numeric;
/* compare against symbolic names */
{
int found = 0;
#define NUDGE_DEF(name, comment) \
if (strcmp(#name, argv[arg_offs+1]) == 0) { \
found = 1; \
action_mask |= NUDGE_GENERIC(name); \
}
NUDGE_DEFINITIONS();
#undef NUDGE_DEF
if (!found && type_numeric == 0) {
fprintf(stderr, "ERROR: unknown -nudge %s\n", argv[arg_offs+1]);
return usage();
}
}
arg_offs += 2;
} else
return usage();
}
if (arg_offs < argc)
return usage();
/* construct the payload */
success = create_nudge_signal_payload(&info, action_mask, client_id, client_arg);
assert(success); /* failure means kernel's sigqueueinfo has changed */
/* send the nudge */
i = syscall(SYS_rt_sigqueueinfo, target_pid, NUDGESIG_SIGNUM, &info);
if (i < 0)
fprintf(stderr, "nudge FAILED with error %d\n", i);
return i;
}
| bl4ckic3/dynamorio | tools/nudgeunix.c | C | lgpl-2.1 | 5,878 |
#ifndef BOOST_CORE_LIGHTWEIGHT_TEST_TRAIT_HPP
#define BOOST_CORE_LIGHTWEIGHT_TEST_TRAIT_HPP
// MS compatible compilers support #pragma once
#if defined(_MSC_VER)
# pragma once
#endif
// boost/core/lightweight_test_trait.hpp
//
// BOOST_TEST_TRAIT_TRUE, BOOST_TEST_TRAIT_FALSE, BOOST_TEST_TRAIT_SAME
//
// Copyright 2014, 2021 Peter Dimov
//
// Copyright 2019 Glen Joseph Fernandes
// (glenjofe@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <boost/core/lightweight_test.hpp>
#include <boost/core/type_name.hpp>
#include <boost/core/is_same.hpp>
#include <boost/config.hpp>
namespace boost
{
namespace detail
{
template< class T > inline void test_trait_impl( char const * trait, void (*)( T ),
bool expected, char const * file, int line, char const * function )
{
if( T::value == expected )
{
test_results();
}
else
{
BOOST_LIGHTWEIGHT_TEST_OSTREAM
<< file << "(" << line << "): predicate '" << trait << "' ["
<< boost::core::type_name<T>() << "]"
<< " test failed in function '" << function
<< "' (should have been " << ( expected? "true": "false" ) << ")"
<< std::endl;
++test_results().errors();
}
}
template<class T> inline bool test_trait_same_impl_( T )
{
return T::value;
}
template<class T1, class T2> inline void test_trait_same_impl( char const * types,
boost::core::is_same<T1, T2> same, char const * file, int line, char const * function )
{
if( test_trait_same_impl_( same ) )
{
test_results();
}
else
{
BOOST_LIGHTWEIGHT_TEST_OSTREAM
<< file << "(" << line << "): test 'is_same<" << types << ">'"
<< " failed in function '" << function
<< "' ('" << boost::core::type_name<T1>()
<< "' != '" << boost::core::type_name<T2>() << "')"
<< std::endl;
++test_results().errors();
}
}
} // namespace detail
} // namespace boost
#define BOOST_TEST_TRAIT_TRUE(type) ( ::boost::detail::test_trait_impl(#type, (void(*)type)0, true, __FILE__, __LINE__, BOOST_CURRENT_FUNCTION) )
#define BOOST_TEST_TRAIT_FALSE(type) ( ::boost::detail::test_trait_impl(#type, (void(*)type)0, false, __FILE__, __LINE__, BOOST_CURRENT_FUNCTION) )
#if defined(__GNUC__)
// ignoring -Wvariadic-macros with #pragma doesn't work under GCC
# pragma GCC system_header
#endif
#define BOOST_TEST_TRAIT_SAME(...) ( ::boost::detail::test_trait_same_impl(#__VA_ARGS__, ::boost::core::is_same<__VA_ARGS__>(), __FILE__, __LINE__, BOOST_CURRENT_FUNCTION) )
#endif // #ifndef BOOST_CORE_LIGHTWEIGHT_TEST_TRAIT_HPP
| qianqians/abelkhan | cpp_component/3rdparty/boost/boost/core/lightweight_test_trait.hpp | C++ | lgpl-2.1 | 2,747 |
package org.auscope.portal.core.util;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.auscope.portal.core.test.PortalTestClass;
import org.junit.Assert;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
* Unit tests for DOMUtil
*
* @author Josh Vote
*
*/
public class TestDOMUtil extends PortalTestClass {
/**
* Simple test to ensure that the 2 DOM util methods are reversible
* @throws SAXException
* @throws IOException
* @throws ParserConfigurationException
* @throws TransformerException
*/
@Test
public void testReversibleTransformation() throws ParserConfigurationException, IOException, SAXException, TransformerException {
final String originalXmlString = ResourceUtil
.loadResourceAsString("org/auscope/portal/core/test/xml/TestXML_NoPrettyPrint.xml");
final Document doc = DOMUtil.buildDomFromString(originalXmlString);
final String newXmlString = DOMUtil.buildStringFromDom(doc, false);
Assert.assertEquals(originalXmlString, newXmlString);
}
/**
* Namespace for use with src/test/resources/TestXML_NoPrettyPrint.xml
*
* @author vot002
*
*/
public class SimpleXMLNamespace implements NamespaceContext {
private Map<String, String> map;
public SimpleXMLNamespace() {
map = new HashMap<>();
map.put("test", "http://test.namespace");
map.put("test2", "http://test2.namespace");
}
/**
* This method returns the uri for all prefixes needed.
*
* @param prefix
* @return uri
*/
@Override
public String getNamespaceURI(final String prefix) {
if (prefix == null)
throw new IllegalArgumentException("No prefix provided!");
if (map.containsKey(prefix))
return map.get(prefix);
else
return XMLConstants.NULL_NS_URI;
}
@Override
public String getPrefix(final String namespaceURI) {
// Not needed in this context.
return null;
}
@Override
public Iterator<String> getPrefixes(final String namespaceURI) {
// Not needed in this context.
return null;
}
}
/**
* Simple test to ensure that the DOM object is namespace aware
* @throws XPathExpressionException
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
@Test
public void testDOMObjectNamespace() throws XPathExpressionException, IOException, ParserConfigurationException, SAXException {
//Build our DOM
final String originalXmlString = ResourceUtil
.loadResourceAsString("org/auscope/portal/core/test/xml/TestXML_NoPrettyPrint.xml");
final Document doc = DOMUtil.buildDomFromString(originalXmlString);
//Build our queries (namespace aware)
final XPathFactory factory = XPathFactory.newDefaultInstance();
final XPath xPath = factory.newXPath();
xPath.setNamespaceContext(new SimpleXMLNamespace());
final XPathExpression getChild1Expr = xPath.compile("test:root/test2:child1");
final XPathExpression getChild2Expr = xPath.compile("test:root/test2:child2");
final XPathExpression failingExpr = xPath.compile("root/child1");
Node testNode = (Node) getChild1Expr.evaluate(doc, XPathConstants.NODE);
Assert.assertNotNull(testNode);
Assert.assertEquals("child1Value", testNode.getTextContent());
testNode = (Node) getChild2Expr.evaluate(doc, XPathConstants.NODE);
Assert.assertNotNull(testNode);
Assert.assertEquals("child2Value", testNode.getTextContent());
//This should fail (no namespace specified)
testNode = (Node) failingExpr.evaluate(doc, XPathConstants.NODE);
Assert.assertNull(testNode);
}
}
| jia020/portal-core | src/test/java/org/auscope/portal/core/util/TestDOMUtil.java | Java | lgpl-3.0 | 4,481 |
import unittest
from ctypes import *
from struct import calcsize
import _testcapi
class SubclassesTest(unittest.TestCase):
def test_subclass(self):
class X(Structure):
_fields_ = [("a", c_int)]
class Y(X):
_fields_ = [("b", c_int)]
class Z(X):
pass
self.assertEqual(sizeof(X), sizeof(c_int))
self.assertEqual(sizeof(Y), sizeof(c_int)*2)
self.assertEqual(sizeof(Z), sizeof(c_int))
self.assertEqual(X._fields_, [("a", c_int)])
self.assertEqual(Y._fields_, [("b", c_int)])
self.assertEqual(Z._fields_, [("a", c_int)])
def test_subclass_delayed(self):
class X(Structure):
pass
self.assertEqual(sizeof(X), 0)
X._fields_ = [("a", c_int)]
class Y(X):
pass
self.assertEqual(sizeof(Y), sizeof(X))
Y._fields_ = [("b", c_int)]
class Z(X):
pass
self.assertEqual(sizeof(X), sizeof(c_int))
self.assertEqual(sizeof(Y), sizeof(c_int)*2)
self.assertEqual(sizeof(Z), sizeof(c_int))
self.assertEqual(X._fields_, [("a", c_int)])
self.assertEqual(Y._fields_, [("b", c_int)])
self.assertEqual(Z._fields_, [("a", c_int)])
class StructureTestCase(unittest.TestCase):
formats = {"c": c_char,
"b": c_byte,
"B": c_ubyte,
"h": c_short,
"H": c_ushort,
"i": c_int,
"I": c_uint,
"l": c_long,
"L": c_ulong,
"q": c_longlong,
"Q": c_ulonglong,
"f": c_float,
"d": c_double,
}
def test_simple_structs(self):
for code, tp in self.formats.items():
class X(Structure):
_fields_ = [("x", c_char),
("y", tp)]
self.assertEqual((sizeof(X), code),
(calcsize("c%c0%c" % (code, code)), code))
def test_unions(self):
for code, tp in self.formats.items():
class X(Union):
_fields_ = [("x", c_char),
("y", tp)]
self.assertEqual((sizeof(X), code),
(calcsize("%c" % (code)), code))
def test_struct_alignment(self):
class X(Structure):
_fields_ = [("x", c_char * 3)]
self.assertEqual(alignment(X), calcsize("s"))
self.assertEqual(sizeof(X), calcsize("3s"))
class Y(Structure):
_fields_ = [("x", c_char * 3),
("y", c_int)]
self.assertEqual(alignment(Y), calcsize("i"))
self.assertEqual(sizeof(Y), calcsize("3si"))
class SI(Structure):
_fields_ = [("a", X),
("b", Y)]
self.assertEqual(alignment(SI), max(alignment(Y), alignment(X)))
self.assertEqual(sizeof(SI), calcsize("3s0i 3si 0i"))
class IS(Structure):
_fields_ = [("b", Y),
("a", X)]
self.assertEqual(alignment(SI), max(alignment(X), alignment(Y)))
self.assertEqual(sizeof(IS), calcsize("3si 3s 0i"))
class XX(Structure):
_fields_ = [("a", X),
("b", X)]
self.assertEqual(alignment(XX), alignment(X))
self.assertEqual(sizeof(XX), calcsize("3s 3s 0s"))
def test_emtpy(self):
# I had problems with these
#
# Although these are patological cases: Empty Structures!
class X(Structure):
_fields_ = []
class Y(Union):
_fields_ = []
# Is this really the correct alignment, or should it be 0?
self.assertTrue(alignment(X) == alignment(Y) == 1)
self.assertTrue(sizeof(X) == sizeof(Y) == 0)
class XX(Structure):
_fields_ = [("a", X),
("b", X)]
self.assertEqual(alignment(XX), 1)
self.assertEqual(sizeof(XX), 0)
def test_fields(self):
# test the offset and size attributes of Structure/Unoin fields.
class X(Structure):
_fields_ = [("x", c_int),
("y", c_char)]
self.assertEqual(X.x.offset, 0)
self.assertEqual(X.x.size, sizeof(c_int))
self.assertEqual(X.y.offset, sizeof(c_int))
self.assertEqual(X.y.size, sizeof(c_char))
# readonly
self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92)
self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92)
class X(Union):
_fields_ = [("x", c_int),
("y", c_char)]
self.assertEqual(X.x.offset, 0)
self.assertEqual(X.x.size, sizeof(c_int))
self.assertEqual(X.y.offset, 0)
self.assertEqual(X.y.size, sizeof(c_char))
# readonly
self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92)
self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92)
# XXX Should we check nested data types also?
# offset is always relative to the class...
def test_packed(self):
class X(Structure):
_fields_ = [("a", c_byte),
("b", c_longlong)]
_pack_ = 1
self.assertEqual(sizeof(X), 9)
self.assertEqual(X.b.offset, 1)
class X(Structure):
_fields_ = [("a", c_byte),
("b", c_longlong)]
_pack_ = 2
self.assertEqual(sizeof(X), 10)
self.assertEqual(X.b.offset, 2)
class X(Structure):
_fields_ = [("a", c_byte),
("b", c_longlong)]
_pack_ = 4
self.assertEqual(sizeof(X), 12)
self.assertEqual(X.b.offset, 4)
import struct
longlong_size = struct.calcsize("q")
longlong_align = struct.calcsize("bq") - longlong_size
class X(Structure):
_fields_ = [("a", c_byte),
("b", c_longlong)]
_pack_ = 8
self.assertEqual(sizeof(X), longlong_align + longlong_size)
self.assertEqual(X.b.offset, min(8, longlong_align))
d = {"_fields_": [("a", "b"),
("b", "q")],
"_pack_": -1}
self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
# Issue 15989
d = {"_fields_": [("a", c_byte)],
"_pack_": _testcapi.INT_MAX + 1}
self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
d = {"_fields_": [("a", c_byte)],
"_pack_": _testcapi.UINT_MAX + 2}
self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
def test_initializers(self):
class Person(Structure):
_fields_ = [("name", c_char*6),
("age", c_int)]
self.assertRaises(TypeError, Person, 42)
self.assertRaises(ValueError, Person, b"asldkjaslkdjaslkdj")
self.assertRaises(TypeError, Person, "Name", "HI")
# short enough
self.assertEqual(Person(b"12345", 5).name, b"12345")
# exact fit
self.assertEqual(Person(b"123456", 5).name, b"123456")
# too long
self.assertRaises(ValueError, Person, b"1234567", 5)
def test_conflicting_initializers(self):
class POINT(Structure):
_fields_ = [("x", c_int), ("y", c_int)]
# conflicting positional and keyword args
self.assertRaises(TypeError, POINT, 2, 3, x=4)
self.assertRaises(TypeError, POINT, 2, 3, y=4)
# too many initializers
self.assertRaises(TypeError, POINT, 2, 3, 4)
def test_keyword_initializers(self):
class POINT(Structure):
_fields_ = [("x", c_int), ("y", c_int)]
pt = POINT(1, 2)
self.assertEqual((pt.x, pt.y), (1, 2))
pt = POINT(y=2, x=1)
self.assertEqual((pt.x, pt.y), (1, 2))
def test_invalid_field_types(self):
class POINT(Structure):
pass
self.assertRaises(TypeError, setattr, POINT, "_fields_", [("x", 1), ("y", 2)])
def test_invalid_name(self):
# field name must be string
def declare_with_name(name):
class S(Structure):
_fields_ = [(name, c_int)]
self.assertRaises(TypeError, declare_with_name, b"x")
def test_intarray_fields(self):
class SomeInts(Structure):
_fields_ = [("a", c_int * 4)]
# can use tuple to initialize array (but not list!)
self.assertEqual(SomeInts((1, 2)).a[:], [1, 2, 0, 0])
self.assertEqual(SomeInts((1, 2)).a[::], [1, 2, 0, 0])
self.assertEqual(SomeInts((1, 2)).a[::-1], [0, 0, 2, 1])
self.assertEqual(SomeInts((1, 2)).a[::2], [1, 0])
self.assertEqual(SomeInts((1, 2)).a[1:5:6], [2])
self.assertEqual(SomeInts((1, 2)).a[6:4:-1], [])
self.assertEqual(SomeInts((1, 2, 3, 4)).a[:], [1, 2, 3, 4])
self.assertEqual(SomeInts((1, 2, 3, 4)).a[::], [1, 2, 3, 4])
# too long
# XXX Should raise ValueError?, not RuntimeError
self.assertRaises(RuntimeError, SomeInts, (1, 2, 3, 4, 5))
def test_nested_initializers(self):
# test initializing nested structures
class Phone(Structure):
_fields_ = [("areacode", c_char*6),
("number", c_char*12)]
class Person(Structure):
_fields_ = [("name", c_char * 12),
("phone", Phone),
("age", c_int)]
p = Person(b"Someone", (b"1234", b"5678"), 5)
self.assertEqual(p.name, b"Someone")
self.assertEqual(p.phone.areacode, b"1234")
self.assertEqual(p.phone.number, b"5678")
self.assertEqual(p.age, 5)
def test_structures_with_wchar(self):
try:
c_wchar
except NameError:
return # no unicode
class PersonW(Structure):
_fields_ = [("name", c_wchar * 12),
("age", c_int)]
p = PersonW("Someone \xe9")
self.assertEqual(p.name, "Someone \xe9")
self.assertEqual(PersonW("1234567890").name, "1234567890")
self.assertEqual(PersonW("12345678901").name, "12345678901")
# exact fit
self.assertEqual(PersonW("123456789012").name, "123456789012")
#too long
self.assertRaises(ValueError, PersonW, "1234567890123")
def test_init_errors(self):
class Phone(Structure):
_fields_ = [("areacode", c_char*6),
("number", c_char*12)]
class Person(Structure):
_fields_ = [("name", c_char * 12),
("phone", Phone),
("age", c_int)]
cls, msg = self.get_except(Person, b"Someone", (1, 2))
self.assertEqual(cls, RuntimeError)
self.assertEqual(msg,
"(Phone) <class 'TypeError'>: "
"expected string, int found")
cls, msg = self.get_except(Person, b"Someone", (b"a", b"b", b"c"))
self.assertEqual(cls, RuntimeError)
if issubclass(Exception, object):
self.assertEqual(msg,
"(Phone) <class 'TypeError'>: too many initializers")
else:
self.assertEqual(msg, "(Phone) TypeError: too many initializers")
def test_huge_field_name(self):
# issue12881: segfault with large structure field names
def create_class(length):
class S(Structure):
_fields_ = [('x' * length, c_int)]
for length in [10 ** i for i in range(0, 8)]:
try:
create_class(length)
except MemoryError:
# MemoryErrors are OK, we just don't want to segfault
pass
def get_except(self, func, *args):
try:
func(*args)
except Exception as detail:
return detail.__class__, str(detail)
## def test_subclass_creation(self):
## meta = type(Structure)
## # same as 'class X(Structure): pass'
## # fails, since we need either a _fields_ or a _abstract_ attribute
## cls, msg = self.get_except(meta, "X", (Structure,), {})
## self.assertEqual((cls, msg),
## (AttributeError, "class must define a '_fields_' attribute"))
def test_abstract_class(self):
class X(Structure):
_abstract_ = "something"
# try 'X()'
cls, msg = self.get_except(eval, "X()", locals())
self.assertEqual((cls, msg), (TypeError, "abstract class"))
def test_methods(self):
## class X(Structure):
## _fields_ = []
self.assertTrue("in_dll" in dir(type(Structure)))
self.assertTrue("from_address" in dir(type(Structure)))
self.assertTrue("in_dll" in dir(type(Structure)))
def test_positional_args(self):
# see also http://bugs.python.org/issue5042
class W(Structure):
_fields_ = [("a", c_int), ("b", c_int)]
class X(W):
_fields_ = [("c", c_int)]
class Y(X):
pass
class Z(Y):
_fields_ = [("d", c_int), ("e", c_int), ("f", c_int)]
z = Z(1, 2, 3, 4, 5, 6)
self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f),
(1, 2, 3, 4, 5, 6))
z = Z(1)
self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f),
(1, 0, 0, 0, 0, 0))
self.assertRaises(TypeError, lambda: Z(1, 2, 3, 4, 5, 6, 7))
class PointerMemberTestCase(unittest.TestCase):
def test(self):
# a Structure with a POINTER field
class S(Structure):
_fields_ = [("array", POINTER(c_int))]
s = S()
# We can assign arrays of the correct type
s.array = (c_int * 3)(1, 2, 3)
items = [s.array[i] for i in range(3)]
self.assertEqual(items, [1, 2, 3])
# The following are bugs, but are included here because the unittests
# also describe the current behaviour.
#
# This fails with SystemError: bad arg to internal function
# or with IndexError (with a patch I have)
s.array[0] = 42
items = [s.array[i] for i in range(3)]
self.assertEqual(items, [42, 2, 3])
s.array[0] = 1
## s.array[1] = 42
items = [s.array[i] for i in range(3)]
self.assertEqual(items, [1, 2, 3])
def test_none_to_pointer_fields(self):
class S(Structure):
_fields_ = [("x", c_int),
("p", POINTER(c_int))]
s = S()
s.x = 12345678
s.p = None
self.assertEqual(s.x, 12345678)
class TestRecursiveStructure(unittest.TestCase):
def test_contains_itself(self):
class Recursive(Structure):
pass
try:
Recursive._fields_ = [("next", Recursive)]
except AttributeError as details:
self.assertTrue("Structure or union cannot contain itself" in
str(details))
else:
self.fail("Structure or union cannot contain itself")
def test_vice_versa(self):
class First(Structure):
pass
class Second(Structure):
pass
First._fields_ = [("second", Second)]
try:
Second._fields_ = [("first", First)]
except AttributeError as details:
self.assertTrue("_fields_ is final" in
str(details))
else:
self.fail("AttributeError not raised")
if __name__ == '__main__':
unittest.main()
| LaoZhongGu/kbengine | kbe/src/lib/python/Lib/ctypes/test/test_structures.py | Python | lgpl-3.0 | 15,782 |
// Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package debugstatus_test
import (
"encoding/json"
"net/http"
jc "github.com/juju/testing/checkers"
"github.com/juju/testing/httptesting"
"github.com/juju/utils/debugstatus"
"github.com/julienschmidt/httprouter"
gc "gopkg.in/check.v1"
"gopkg.in/errgo.v1"
"github.com/juju/httprequest"
)
var errorMapper httprequest.ErrorMapper = func(err error) (httpStatus int, errorBody interface{}) {
return http.StatusInternalServerError, httprequest.RemoteError{
Message: err.Error(),
}
}
type handlerSuite struct {
}
var _ = gc.Suite(&handlerSuite{})
var errUnauthorized = errgo.New("you shall not pass!")
func newHTTPHandler(h *debugstatus.Handler) http.Handler {
errMapper := httprequest.ErrorMapper(func(err error) (httpStatus int, errorBody interface{}) {
code, status := "", http.StatusInternalServerError
switch errgo.Cause(err) {
case errUnauthorized:
code, status = "unauthorized", http.StatusUnauthorized
case debugstatus.ErrNoPprofConfigured:
code, status = "forbidden", http.StatusForbidden
case debugstatus.ErrNoTraceConfigured:
code, status = "forbidden", http.StatusForbidden
}
return status, httprequest.RemoteError{
Code: code,
Message: err.Error(),
}
})
handlers := errMapper.Handlers(func(httprequest.Params) (*debugstatus.Handler, error) {
return h, nil
})
r := httprouter.New()
for _, h := range handlers {
r.Handle(h.Method, h.Path, h.Handle)
}
return r
}
func (s *handlerSuite) TestServeDebugStatus(c *gc.C) {
httpHandler := newHTTPHandler(&debugstatus.Handler{
Check: func() map[string]debugstatus.CheckResult {
return debugstatus.Check(debugstatus.ServerStartTime)
},
})
httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
Handler: httpHandler,
URL: "/debug/status",
ExpectBody: httptesting.BodyAsserter(func(c *gc.C, body json.RawMessage) {
var result map[string]debugstatus.CheckResult
err := json.Unmarshal(body, &result)
c.Assert(err, gc.IsNil)
for k, v := range result {
v.Duration = 0
result[k] = v
}
c.Assert(result, jc.DeepEquals, map[string]debugstatus.CheckResult{
"server_started": {
Name: "Server started",
Value: debugstatus.StartTime.String(),
Passed: true,
},
})
}),
})
}
func (s *handlerSuite) TestServeDebugStatusWithNilCheck(c *gc.C) {
httpHandler := newHTTPHandler(&debugstatus.Handler{})
httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
Handler: httpHandler,
URL: "/debug/status",
ExpectBody: map[string]debugstatus.CheckResult{},
})
}
func (s *handlerSuite) TestServeDebugInfo(c *gc.C) {
version := debugstatus.Version{
GitCommit: "some-git-status",
Version: "a-version",
}
httpHandler := newHTTPHandler(&debugstatus.Handler{
Version: version,
})
httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
Handler: httpHandler,
URL: "/debug/info",
ExpectStatus: http.StatusOK,
ExpectBody: version,
})
}
var debugPprofPaths = []string{
"/debug/pprof/",
"/debug/pprof/cmdline",
"/debug/pprof/profile?seconds=1",
"/debug/pprof/symbol",
"/debug/pprof/goroutine",
}
func (s *handlerSuite) TestServeDebugPprof(c *gc.C) {
httpHandler := newHTTPHandler(&debugstatus.Handler{
CheckPprofAllowed: func(req *http.Request) error {
if req.Header.Get("Authorization") == "" {
return errUnauthorized
}
return nil
},
})
authHeader := make(http.Header)
authHeader.Set("Authorization", "let me in")
for i, path := range debugPprofPaths {
c.Logf("%d. %s", i, path)
httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
Handler: httpHandler,
URL: path,
ExpectStatus: http.StatusUnauthorized,
ExpectBody: httprequest.RemoteError{
Code: "unauthorized",
Message: "you shall not pass!",
},
})
rr := httptesting.DoRequest(c, httptesting.DoRequestParams{
Handler: httpHandler,
URL: path,
Header: authHeader,
})
c.Assert(rr.Code, gc.Equals, http.StatusOK)
}
}
func (s *handlerSuite) TestDebugPprofForbiddenWhenNotConfigured(c *gc.C) {
httpHandler := newHTTPHandler(&debugstatus.Handler{})
httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
Handler: httpHandler,
URL: "/debug/pprof/",
ExpectStatus: http.StatusForbidden,
ExpectBody: httprequest.RemoteError{
Code: "forbidden",
Message: "no pprof access configured",
},
})
}
var debugTracePaths = []string{
"/debug/events",
"/debug/requests",
}
func (s *handlerSuite) TestServeTraceEvents(c *gc.C) {
httpHandler := newHTTPHandler(&debugstatus.Handler{
CheckTraceAllowed: func(req *http.Request) (bool, error) {
if req.Header.Get("Authorization") == "" {
return false, errUnauthorized
}
return false, nil
},
})
authHeader := make(http.Header)
authHeader.Set("Authorization", "let me in")
for i, path := range debugTracePaths {
c.Logf("%d. %s", i, path)
httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
Handler: httpHandler,
URL: path,
ExpectStatus: http.StatusUnauthorized,
ExpectBody: httprequest.RemoteError{
Code: "unauthorized",
Message: "you shall not pass!",
},
})
rr := httptesting.DoRequest(c, httptesting.DoRequestParams{
Handler: httpHandler,
URL: path,
Header: authHeader,
})
c.Assert(rr.Code, gc.Equals, http.StatusOK)
}
}
func (s *handlerSuite) TestDebugEventsForbiddenWhenNotConfigured(c *gc.C) {
httpHandler := newHTTPHandler(&debugstatus.Handler{})
httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
Handler: httpHandler,
URL: "/debug/events",
ExpectStatus: http.StatusForbidden,
ExpectBody: httprequest.RemoteError{
Code: "forbidden",
Message: "no trace access configured",
},
})
}
| bz2/utils | debugstatus/handler_test.go | GO | lgpl-3.0 | 5,855 |
package org.auscope.portal.core.services.responses.vocab;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathException;
import org.auscope.portal.core.services.namespaces.VocabNamespaceContext;
import org.auscope.portal.core.test.PortalTestClass;
import org.auscope.portal.core.util.DOMUtil;
import org.auscope.portal.core.util.ResourceUtil;
import org.junit.Assert;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
* Unit tests for ConceptFactory
*
* @author Josh Vote
*
*/
public class TestConceptFactory extends PortalTestClass {
private void assertSameConcept(Concept[] expected, Concept[] actual, List<String> traversedUrns) {
String errMsg = String.format("%1$s != %2$s", Arrays.toString(expected), Arrays.toString(actual));
Assert.assertArrayEquals(errMsg, expected, actual);
for (int i = 0; i < expected.length; i++) {
assertSameConcept(expected[i], actual[i], traversedUrns);
}
}
private void assertSameConcept(Concept expected, Concept actual, List<String> traversedUrns) {
String errMsg = String.format("%1$s != %2$s", expected, actual);
Assert.assertEquals(errMsg, expected, actual);
Assert.assertEquals(errMsg, expected.getLabel(), actual.getLabel());
Assert.assertEquals(errMsg, expected.getPreferredLabel(), actual.getPreferredLabel());
Assert.assertEquals(errMsg, expected.isHref(), actual.isHref());
Assert.assertEquals(errMsg, expected.getDefinition(), actual.getDefinition());
//To deal with cycles in the hierarchy
if (traversedUrns.contains(expected.getUrn())) {
return;
} else {
traversedUrns.add(expected.getUrn());
}
assertSameConcept(expected.getBroader(), actual.getBroader(), traversedUrns);
assertSameConcept(expected.getNarrower(), actual.getNarrower(), traversedUrns);
assertSameConcept(expected.getRelated(), actual.getRelated(), traversedUrns);
}
/**
* Runs the factory through a standard SISSVoc response XML
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
* @throws XPathException
*/
@Test
public void testSISSVocRDF() throws IOException, ParserConfigurationException, SAXException, XPathException {
//Build our expectation
Concept concept1 = new Concept("urn:concept:1");
Concept concept2 = new Concept("urn:concept:2");
Concept concept3 = new Concept("urn:concept:3");
Concept concept4 = new Concept("urn:concept:4");
NamedIndividual ni1 = new NamedIndividual("urn:ni:1");
NamedIndividual ni2 = new NamedIndividual("urn:ni:2");
NamedIndividual ni3 = new NamedIndividual("urn:ni:3");
concept1.setNarrower(new Concept[] {concept2, concept3, ni2});
concept1.setLabel("LabelConcept1");
concept1.setPreferredLabel("PrefLabelConcept1");
concept2.setBroader(new Concept[] {concept1});
concept2.setRelated(new Concept[] {concept3});
concept2.setLabel("LabelConcept2");
concept2.setPreferredLabel("PrefLabelConcept2");
concept2.setDefinition("DefinitionConcept2");
concept3.setBroader(new Concept[] {concept1});
concept3.setRelated(new Concept[] {concept2});
concept3.setNarrower(new Concept[] {ni1});
concept3.setLabel("LabelConcept3");
concept3.setPreferredLabel("PrefLabelConcept3");
concept4.setNarrower(new Concept[] {ni3});
concept4.setLabel("LabelConcept4");
concept4.setPreferredLabel("PrefLabelConcept4");
concept4.setDefinition("DefinitionConcept4");
ni1.setBroader(new Concept[] {concept3});
ni1.setLabel("LabelNamedIndividual1");
ni1.setPreferredLabel("PrefLabelNamedIndividual1");
ni2.setBroader(new Concept[] {concept1});
ni2.setLabel("LabelNamedIndividual2");
ni2.setPreferredLabel("PrefLabelNamedIndividual2");
ni3.setBroader(new Concept[] {concept4});
ni3.setLabel("LabelNamedIndividual3");
ni3.setPreferredLabel("PrefLabelNamedIndividual3");
Concept[] expectation = new Concept[] {concept1, concept4};
//Build our actual list
String responseXml = ResourceUtil
.loadResourceAsString("org/auscope/portal/core/test/responses/sissvoc/SISSVocResponse.xml");
Document responseDoc = DOMUtil.buildDomFromString(responseXml);
Node rdfNode = (Node) DOMUtil.compileXPathExpr("rdf:RDF", new VocabNamespaceContext()).evaluate(responseDoc,
XPathConstants.NODE);
ConceptFactory cf = new ConceptFactory();
Concept[] actualConcepts = cf.parseFromRDF(rdfNode);
Assert.assertNotNull(actualConcepts);
assertSameConcept(expectation, actualConcepts, new ArrayList<String>());
}
/**
* This is a legacy test for the older vocabularyServiceResponse.xml
*
* It tests our concepts still return EVEN if we don't define top level concepts
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
* @throws XPathException
*/
@Test
public void testGetConcepts() throws IOException, ParserConfigurationException, SAXException, XPathException {
String responseXml = ResourceUtil
.loadResourceAsString("org/auscope/portal/core/test/responses/sissvoc/vocabularyServiceResponse.xml");
Document responseDoc = DOMUtil.buildDomFromString(responseXml);
Node rdfNode = (Node) DOMUtil.compileXPathExpr("rdf:RDF", new VocabNamespaceContext()).evaluate(responseDoc,
XPathConstants.NODE);
ConceptFactory cf = new ConceptFactory();
Concept[] actualConcepts = cf.parseFromRDF(rdfNode);
Assert.assertEquals("There are 27 concepts", 27, actualConcepts.length);
//Must contain: Siltstone - concrete aggregate
boolean found = false;
for (Concept concept : actualConcepts) {
if (concept.getPreferredLabel().equals("Siltstone - concrete aggregate")) {
found = true;
break;
}
}
Assert.assertTrue("Must contain: Siltstone - concrete aggregate", found);
//Must contain: Gneiss - crusher dust
found = false;
for (Concept concept : actualConcepts) {
if (concept.getPreferredLabel().equals("Gneiss - crusher dust")) {
found = true;
break;
}
}
Assert.assertTrue("Must contain: Gneiss - crusher dust", found);
}
}
| jia020/portal-core | src/test/java/org/auscope/portal/core/services/responses/vocab/TestConceptFactory.java | Java | lgpl-3.0 | 6,879 |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Schema
{
internal class JsonSchemaWriter
{
private readonly JsonWriter _writer;
private readonly JsonSchemaResolver _resolver;
public JsonSchemaWriter(JsonWriter writer, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(writer, "writer");
_writer = writer;
_resolver = resolver;
}
private void ReferenceOrWriteSchema(JsonSchema schema)
{
if (schema.Id != null && _resolver.GetSchema(schema.Id) != null)
{
_writer.WriteStartObject();
_writer.WritePropertyName(JsonSchemaConstants.ReferencePropertyName);
_writer.WriteValue(schema.Id);
_writer.WriteEndObject();
}
else
{
WriteSchema(schema);
}
}
public void WriteSchema(JsonSchema schema)
{
ValidationUtils.ArgumentNotNull(schema, "schema");
if (!_resolver.LoadedSchemas.Contains(schema))
_resolver.LoadedSchemas.Add(schema);
_writer.WriteStartObject();
WritePropertyIfNotNull(_writer, JsonSchemaConstants.IdPropertyName, schema.Id);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.TitlePropertyName, schema.Title);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.DescriptionPropertyName, schema.Description);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.OptionalPropertyName, schema.Optional);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.ReadOnlyPropertyName, schema.ReadOnly);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.HiddenPropertyName, schema.Hidden);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.TransientPropertyName, schema.Transient);
if (schema.Type != null)
WriteType(JsonSchemaConstants.TypePropertyName, _writer, schema.Type.Value);
if (!schema.AllowAdditionalProperties)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
_writer.WriteValue(schema.AllowAdditionalProperties);
}
else
{
if (schema.AdditionalProperties != null)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
ReferenceOrWriteSchema(schema.AdditionalProperties);
}
}
if (schema.Properties != null)
{
_writer.WritePropertyName(JsonSchemaConstants.PropertiesPropertyName);
_writer.WriteStartObject();
foreach (KeyValuePair<string, JsonSchema> property in schema.Properties)
{
_writer.WritePropertyName(property.Key);
ReferenceOrWriteSchema(property.Value);
}
_writer.WriteEndObject();
}
WriteItems(schema);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumPropertyName, schema.Minimum);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumPropertyName, schema.Maximum);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumLengthPropertyName, schema.MinimumLength);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumLengthPropertyName, schema.MaximumLength);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumItemsPropertyName, schema.MinimumItems);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumItemsPropertyName, schema.MaximumItems);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumDecimalsPropertyName, schema.MaximumDecimals);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.FormatPropertyName, schema.Format);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.PatternPropertyName, schema.Pattern);
if (schema.Enum != null)
{
_writer.WritePropertyName(JsonSchemaConstants.EnumPropertyName);
_writer.WriteStartArray();
foreach (JToken token in schema.Enum)
{
token.WriteTo(_writer);
}
_writer.WriteEndArray();
}
if (schema.Default != null)
{
_writer.WritePropertyName(JsonSchemaConstants.DefaultPropertyName);
schema.Default.WriteTo(_writer);
}
if (schema.Options != null)
{
_writer.WritePropertyName(JsonSchemaConstants.OptionsPropertyName);
_writer.WriteStartArray();
foreach (KeyValuePair<JToken, string> option in schema.Options)
{
_writer.WriteStartObject();
_writer.WritePropertyName(JsonSchemaConstants.OptionValuePropertyName);
option.Key.WriteTo(_writer);
if (option.Value != null)
{
_writer.WritePropertyName(JsonSchemaConstants.OptionValuePropertyName);
_writer.WriteValue(option.Value);
}
_writer.WriteEndObject();
}
_writer.WriteEndArray();
}
if (schema.Disallow != null)
WriteType(JsonSchemaConstants.DisallowPropertyName, _writer, schema.Disallow.Value);
if (schema.Extends != null)
{
_writer.WritePropertyName(JsonSchemaConstants.ExtendsPropertyName);
ReferenceOrWriteSchema(schema.Extends);
}
_writer.WriteEndObject();
}
private void WriteItems(JsonSchema schema)
{
if (CollectionUtils.IsNullOrEmpty(schema.Items))
return;
_writer.WritePropertyName(JsonSchemaConstants.ItemsPropertyName);
if (schema.Items.Count == 1)
{
ReferenceOrWriteSchema(schema.Items[0]);
return;
}
_writer.WriteStartArray();
foreach (JsonSchema itemSchema in schema.Items)
{
ReferenceOrWriteSchema(itemSchema);
}
_writer.WriteEndArray();
}
private void WriteType(string propertyName, JsonWriter writer, JsonSchemaType type)
{
IList<JsonSchemaType> types;
if (System.Enum.IsDefined(typeof(JsonSchemaType), type))
types = new List<JsonSchemaType> { type };
else
types = EnumUtils.GetFlagsValues(type).Where(v => v != JsonSchemaType.None).ToList();
if (types.Count == 0)
return;
writer.WritePropertyName(propertyName);
if (types.Count == 1)
{
writer.WriteValue(JsonSchemaBuilder.MapType(types[0]));
return;
}
writer.WriteStartArray();
foreach (JsonSchemaType jsonSchemaType in types)
{
writer.WriteValue(JsonSchemaBuilder.MapType(jsonSchemaType));
}
writer.WriteEndArray();
}
private void WritePropertyIfNotNull(JsonWriter writer, string propertyName, object value)
{
if (value != null)
{
writer.WritePropertyName(propertyName);
writer.WriteValue(value);
}
}
}
}
| consumentor/Server | trunk/tools/Json.Net/Source/Src/Newtonsoft.Json/Schema/JsonSchemaWriter.cs | C# | lgpl-3.0 | 8,106 |
/**
* This file is part of FNLP (formerly FudanNLP).
*
* FNLP is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FNLP 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 General Public License
* along with FudanNLP. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2009-2014 www.fnlp.org. All rights reserved.
*/
package org.fnlp.util.exception;
import java.io.FileNotFoundException;
import java.io.IOException;
public class LoadModelException extends Exception {
private static final long serialVersionUID = -3933859344026018386L;
public LoadModelException(Exception e, String file) {
super(e);
if( e instanceof FileNotFoundException) {
System.out.println("模型文件不存在: "+ file);
} else if (e instanceof ClassNotFoundException) {
System.out.println("模型文件版本错误。");
} else if (e instanceof IOException) {
System.out.println("模型文件读入错误: "+file);
}
e.printStackTrace();
}
public LoadModelException(String msg) {
super(msg);
printStackTrace();
}
} | xpqiu/fnlp | fnlp-core/src/main/java/org/fnlp/util/exception/LoadModelException.java | Java | lgpl-3.0 | 1,512 |
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// 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.
//
// System.Runtime.InteropServices/DESCKIND.cs
//
// Paolo Molaro (lupus@ximian.com)
//
// (C) 2002 Ximian, Inc.
using System;
namespace System.Runtime.InteropServices
{
[Obsolete]
[Serializable]
public enum DESCKIND {
DESCKIND_NONE = 0,
DESCKIND_FUNCDESC = 1,
DESCKIND_VARDESC = 2,
DESCKIND_TYPECOMP = 3,
DESCKIND_IMPLICITAPPOBJ = 4,
DESCKIND_MAX = 5
}
}
| edwinspire/VSharp | v#/corlib/System.Runtime.InteropServices/DESCKIND.cs | C# | lgpl-3.0 | 1,520 |
namespace StockSharp.Algo.Export
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using Ecng.Common;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
/// <summary>
/// Ýêñïîðò â xml.
/// </summary>
public class XmlExporter : BaseExporter
{
private const string _timeFormat = "yyyy-MM-dd HH:mm:ss.fff zzz";
/// <summary>
/// Ñîçäàòü <see cref="XmlExporter"/>.
/// </summary>
/// <param name="security">Èíñòðóìåíò.</param>
/// <param name="arg">Ïàðàìåòð äàííûõ.</param>
/// <param name="isCancelled">Îáðàáîò÷èê, âîçâðàùàþùèé ïðèçíàê ïðåðûâàíèÿ ýêñïîðòà.</param>
/// <param name="fileName">Ïóòü ê ôàéëó.</param>
public XmlExporter(Security security, object arg, Func<int, bool> isCancelled, string fileName)
: base(security, arg, isCancelled, fileName)
{
}
/// <summary>
/// Ýêñïîðòèðîâàòü <see cref="ExecutionMessage"/>.
/// </summary>
/// <param name="messages">Ñîîáùåíèÿ.</param>
protected override void Export(IEnumerable<ExecutionMessage> messages)
{
switch ((ExecutionTypes)Arg)
{
case ExecutionTypes.Tick:
{
Do(messages, "trades", (writer, trade) =>
{
writer.WriteStartElement("trade");
writer.WriteAttribute("id", trade.TradeId == null ? trade.TradeStringId : trade.TradeId.To<string>());
writer.WriteAttribute("serverTime", trade.ServerTime.ToString(_timeFormat));
writer.WriteAttribute("localTime", trade.LocalTime.ToString(_timeFormat));
writer.WriteAttribute("price", trade.TradePrice);
writer.WriteAttribute("volume", trade.Volume);
if (trade.OriginSide != null)
writer.WriteAttribute("originSide", trade.OriginSide.Value);
if (trade.OpenInterest != null)
writer.WriteAttribute("openInterest", trade.OpenInterest.Value);
if (trade.IsUpTick != null)
writer.WriteAttribute("isUpTick", trade.IsUpTick.Value);
writer.WriteEndElement();
});
break;
}
case ExecutionTypes.OrderLog:
{
Do(messages, "orderLog", (writer, item) =>
{
writer.WriteStartElement("item");
writer.WriteAttribute("id", item.OrderId == null ? item.OrderStringId : item.OrderId.To<string>());
writer.WriteAttribute("serverTime", item.ServerTime.ToString(_timeFormat));
writer.WriteAttribute("localTime", item.LocalTime.ToString(_timeFormat));
writer.WriteAttribute("price", item.Price);
writer.WriteAttribute("volume", item.Volume);
writer.WriteAttribute("side", item.Side);
writer.WriteAttribute("state", item.OrderState);
writer.WriteAttribute("timeInForce", item.TimeInForce);
writer.WriteAttribute("isSystem", item.IsSystem);
if (item.TradePrice != null)
{
writer.WriteAttribute("tradeId", item.TradeId == null ? item.TradeStringId : item.TradeId.To<string>());
writer.WriteAttribute("tradePrice", item.TradePrice);
if (item.OpenInterest != null)
writer.WriteAttribute("openInterest", item.OpenInterest.Value);
}
writer.WriteEndElement();
});
break;
}
case ExecutionTypes.Order:
case ExecutionTypes.Trade:
{
Do(messages, "executions", (writer, item) =>
{
writer.WriteStartElement("item");
writer.WriteAttribute("serverTime", item.ServerTime.ToString(_timeFormat));
writer.WriteAttribute("localTime", item.LocalTime.ToString(_timeFormat));
writer.WriteAttribute("portfolio", item.PortfolioName);
writer.WriteAttribute("transactionId", item.TransactionId);
writer.WriteAttribute("id", item.OrderId == null ? item.OrderStringId : item.OrderId.To<string>());
writer.WriteAttribute("price", item.Price);
writer.WriteAttribute("volume", item.Volume);
writer.WriteAttribute("balance", item.Balance);
writer.WriteAttribute("side", item.Side);
writer.WriteAttribute("type", item.OrderType);
writer.WriteAttribute("state", item.OrderState);
writer.WriteAttribute("tradeId", item.TradeId == null ? item.TradeStringId : item.TradeId.To<string>());
writer.WriteAttribute("tradePrice", item.TradePrice);
writer.WriteEndElement();
});
break;
}
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Ýêñïîðòèðîâàòü <see cref="QuoteChangeMessage"/>.
/// </summary>
/// <param name="messages">Ñîîáùåíèÿ.</param>
protected override void Export(IEnumerable<QuoteChangeMessage> messages)
{
Do(messages, "depths", (writer, depth) =>
{
writer.WriteStartElement("depth");
writer.WriteAttribute("serverTime", depth.ServerTime.ToString(_timeFormat));
writer.WriteAttribute("localTime", depth.LocalTime.ToString(_timeFormat));
foreach (var quote in depth.Bids.Concat(depth.Asks).OrderByDescending(q => q.Price))
{
writer.WriteStartElement("quote");
writer.WriteAttribute("price", quote.Price);
writer.WriteAttribute("volume", quote.Volume);
writer.WriteAttribute("side", quote.Side);
writer.WriteEndElement();
}
writer.WriteEndElement();
});
}
/// <summary>
/// Ýêñïîðòèðîâàòü <see cref="Level1ChangeMessage"/>.
/// </summary>
/// <param name="messages">Ñîîáùåíèÿ.</param>
protected override void Export(IEnumerable<Level1ChangeMessage> messages)
{
Do(messages, "messages", (writer, message) =>
{
writer.WriteStartElement("message");
writer.WriteAttribute("serverTime", message.ServerTime.ToString(_timeFormat));
writer.WriteAttribute("localTime", message.LocalTime.ToString(_timeFormat));
foreach (var pair in message.Changes)
writer.WriteAttribute(pair.Key.ToString(), pair.Value is DateTime ? ((DateTime)pair.Value).ToString(_timeFormat) : pair.Value);
writer.WriteEndElement();
});
}
/// <summary>
/// Ýêñïîðòèðîâàòü <see cref="CandleMessage"/>.
/// </summary>
/// <param name="messages">Ñîîáùåíèÿ.</param>
protected override void Export(IEnumerable<CandleMessage> messages)
{
Do(messages, "candles", (writer, candle) =>
{
writer.WriteStartElement("candle");
writer.WriteAttribute("openTime", candle.OpenTime.ToString(_timeFormat));
writer.WriteAttribute("closeTime", candle.CloseTime.ToString(_timeFormat));
writer.WriteAttribute("O", candle.OpenPrice);
writer.WriteAttribute("H", candle.HighPrice);
writer.WriteAttribute("L", candle.LowPrice);
writer.WriteAttribute("C", candle.ClosePrice);
writer.WriteAttribute("V", candle.TotalVolume);
if (candle.OpenInterest != null)
writer.WriteAttribute("openInterest", candle.OpenInterest.Value);
writer.WriteEndElement();
});
}
/// <summary>
/// Ýêñïîðòèðîâàòü <see cref="NewsMessage"/>.
/// </summary>
/// <param name="messages">Ñîîáùåíèÿ.</param>
protected override void Export(IEnumerable<NewsMessage> messages)
{
Do(messages, "news", (writer, n) =>
{
writer.WriteStartElement("item");
if (!n.Id.IsEmpty())
writer.WriteAttribute("id", n.Id);
writer.WriteAttribute("serverTime", n.ServerTime.ToString(_timeFormat));
writer.WriteAttribute("localTime", n.LocalTime.ToString(_timeFormat));
if (n.SecurityId != null)
writer.WriteAttribute("securityCode", n.SecurityId.Value.SecurityCode);
if (!n.BoardCode.IsEmpty())
writer.WriteAttribute("boardCode", n.BoardCode);
writer.WriteAttribute("headline", n.Headline);
if (!n.Source.IsEmpty())
writer.WriteAttribute("source", n.Source);
if (n.Url != null)
writer.WriteAttribute("board", n.Url);
if (!n.Story.IsEmpty())
writer.WriteCData(n.Story);
writer.WriteEndElement();
});
}
/// <summary>
/// Ýêñïîðòèðîâàòü <see cref="SecurityMessage"/>.
/// </summary>
/// <param name="messages">Ñîîáùåíèÿ.</param>
protected override void Export(IEnumerable<SecurityMessage> messages)
{
Do(messages, "securities", (writer, security) =>
{
writer.WriteStartElement("security");
writer.WriteAttribute("code", security.SecurityId.SecurityCode);
writer.WriteAttribute("board", security.SecurityId.BoardCode);
if (!security.Name.IsEmpty())
writer.WriteAttribute("name", security.Name);
if (!security.ShortName.IsEmpty())
writer.WriteAttribute("shortName", security.ShortName);
if (security.PriceStep != null)
writer.WriteAttribute("priceStep", security.PriceStep.Value);
if (security.VolumeStep != null)
writer.WriteAttribute("volumeStep", security.VolumeStep.Value);
if (security.Multiplier != null)
writer.WriteAttribute("multiplier", security.Multiplier.Value);
if (security.Decimals != null)
writer.WriteAttribute("decimals", security.Decimals.Value);
if (security.Currency != null)
writer.WriteAttribute("currency", security.Currency.Value);
if (security.SecurityType != null)
writer.WriteAttribute("type", security.SecurityType.Value);
if (security.OptionType != null)
writer.WriteAttribute("optionType", security.OptionType.Value);
if (security.Strike != null)
writer.WriteAttribute("strike", security.Strike.Value);
if (!security.BinaryOptionType.IsEmpty())
writer.WriteAttribute("binaryOptionType", security.BinaryOptionType);
if (!security.UnderlyingSecurityCode.IsEmpty())
writer.WriteAttribute("underlyingSecurityCode", security.UnderlyingSecurityCode);
if (security.ExpiryDate != null)
writer.WriteAttribute("expiryDate", security.ExpiryDate.Value.ToString("yyyy-MM-dd"));
if (security.SettlementDate != null)
writer.WriteAttribute("settlementDate", security.SettlementDate.Value.ToString("yyyy-MM-dd"));
if (!security.SecurityId.Bloomberg.IsEmpty())
writer.WriteAttribute("bloomberg", security.SecurityId.Bloomberg);
if (!security.SecurityId.Cusip.IsEmpty())
writer.WriteAttribute("cusip", security.SecurityId.Cusip);
if (!security.SecurityId.IQFeed.IsEmpty())
writer.WriteAttribute("iqfeed", security.SecurityId.IQFeed);
if (security.SecurityId.InteractiveBrokers != null)
writer.WriteAttribute("ib", security.SecurityId.InteractiveBrokers);
if (!security.SecurityId.Isin.IsEmpty())
writer.WriteAttribute("isin", security.SecurityId.Isin);
if (!security.SecurityId.Plaza.IsEmpty())
writer.WriteAttribute("plaza", security.SecurityId.Plaza);
if (!security.SecurityId.Ric.IsEmpty())
writer.WriteAttribute("ric", security.SecurityId.Ric);
if (!security.SecurityId.Sedol.IsEmpty())
writer.WriteAttribute("sedol", security.SecurityId.Sedol);
writer.WriteEndElement();
});
}
private void Do<TValue>(IEnumerable<TValue> values, string rootElem, Action<XmlWriter, TValue> action)
{
using (var writer = XmlWriter.Create(Path, new XmlWriterSettings { Indent = true }))
{
writer.WriteStartElement(rootElem);
foreach (var value in values)
{
if (!CanProcess())
break;
action(writer, value);
}
writer.WriteEndElement();
}
}
}
} | donaldlee2008/StockSharp | Algo/Export/XmlExporter.cs | C# | lgpl-3.0 | 11,023 |
/****
* Sming Framework Project - Open Source framework for high efficiency native ESP8266 development.
* Created 2015 by Skurydin Alexey
* http://github.com/anakod/Sming
* All files of the Sming Core are provided under the LGPL v3 license.
****/
/** @defgroup httpconsts HTTP constants to be used with HTTP client or HTTP server
* @brief Provides HTTP constants
* @ingroup httpserver
* @ingroup httpclient
* @{
*/
#ifndef _SMING_CORE_NETWORK_WEBCONSTANTS_H_
#define _SMING_CORE_NETWORK_WEBCONSTANTS_H_
#define MIME_TYPE_MAP(XX) \
/* Type, extension start, Mime type */ \
\
/* Texts */ \
XX(HTML, "htm", "text/html") \
XX(TEXT, "txt", "text/plain") \
XX(JS, "js", "text/javascript") \
XX(CSS, "css", "text/css") \
XX(XML, "xml", "text/xml") \
XX(JSON, "json", "application/json") \
\
/* Images */ \
XX(JPEG, "jpg", "image/jpeg") \
XX(GIF, "git", "image/gif") \
XX(PNG, "png", "image/png") \
XX(SVG, "svg", "image/svg+xml") \
XX(ICO, "ico", "image/x-icon") \
\
/* Archives */ \
XX(GZIP, "gzip", "application/x-gzip") \
XX(ZIP, "zip", "application/zip") \
\
/* Binary and Form */ \
XX(BINARY, "", "application/octet-stream") \
XX(FORM_URL_ENCODED, "", "application/x-www-form-urlencoded") \
XX(FORM_MULTIPART, "", "multipart/form-data") \
enum MimeType
{
#define XX(name, extensionStart, mime) MIME_##name,
MIME_TYPE_MAP(XX)
#undef XX
};
namespace ContentType
{
static const char* fromFileExtension(const String extension)
{
String ext = extension;
ext.toLowerCase();
#define XX(name, extensionStart, mime) if(ext.startsWith(extensionStart)) { return mime; }
MIME_TYPE_MAP(XX)
#undef XX
// Unknown
return "<unknown>";
}
static const char *toString(enum MimeType m)
{
#define XX(name, extensionStart, mime) if(MIME_##name == m) { return mime; }
MIME_TYPE_MAP(XX)
#undef XX
// Unknown
return "<unknown>";
}
static const char* fromFullFileName(const String fileName)
{
int p = fileName.lastIndexOf('.');
if (p != -1)
{
String ext = fileName.substring(p + 1);
const char *mime = ContentType::fromFileExtension(ext);
return mime;
}
return NULL;
}
};
/** @} */
#endif /* _SMING_CORE_NETWORK_WEBCONSTANTS_H_ */
| blinkingnoise/Sming | Sming/SmingCore/Network/WebConstants.h | C | lgpl-3.0 | 2,619 |
/* linalg/tridiag.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2002, 2004, 2007 Gerard Jungman, Brian Gough, David Necas
*
* 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.
*/
/* Author: G. Jungman */
#include "gsl__config.h"
#include <stdlib.h>
#include <math.h>
#include "gsl_errno.h"
#include "gsl_linalg__tridiag.h"
#include "gsl_linalg.h"
/* for description of method see [Engeln-Mullges + Uhlig, p. 92]
*
* diag[0] offdiag[0] 0 .....
* offdiag[0] diag[1] offdiag[1] .....
* 0 offdiag[1] diag[2]
* 0 0 offdiag[2] .....
*/
static
int
solve_tridiag(
const double diag[], size_t d_stride,
const double offdiag[], size_t o_stride,
const double b[], size_t b_stride,
double x[], size_t x_stride,
size_t N)
{
int status = GSL_SUCCESS;
double *gamma = (double *) malloc (N * sizeof (double));
double *alpha = (double *) malloc (N * sizeof (double));
double *c = (double *) malloc (N * sizeof (double));
double *z = (double *) malloc (N * sizeof (double));
if (gamma == 0 || alpha == 0 || c == 0 || z == 0)
{
GSL_ERROR("failed to allocate working space", GSL_ENOMEM);
}
else
{
size_t i, j;
/* Cholesky decomposition
A = L.D.L^t
lower_diag(L) = gamma
diag(D) = alpha
*/
alpha[0] = diag[0];
gamma[0] = offdiag[0] / alpha[0];
if (alpha[0] == 0) {
status = GSL_EZERODIV;
}
for (i = 1; i < N - 1; i++)
{
alpha[i] = diag[d_stride * i] - offdiag[o_stride*(i - 1)] * gamma[i - 1];
gamma[i] = offdiag[o_stride * i] / alpha[i];
if (alpha[i] == 0) {
status = GSL_EZERODIV;
}
}
if (N > 1)
{
alpha[N - 1] = diag[d_stride * (N - 1)] - offdiag[o_stride*(N - 2)] * gamma[N - 2];
}
/* update RHS */
z[0] = b[0];
for (i = 1; i < N; i++)
{
z[i] = b[b_stride * i] - gamma[i - 1] * z[i - 1];
}
for (i = 0; i < N; i++)
{
c[i] = z[i] / alpha[i];
}
/* backsubstitution */
x[x_stride * (N - 1)] = c[N - 1];
if (N >= 2)
{
for (i = N - 2, j = 0; j <= N - 2; j++, i--)
{
x[x_stride * i] = c[i] - gamma[i] * x[x_stride * (i + 1)];
}
}
}
if (z != 0)
free (z);
if (c != 0)
free (c);
if (alpha != 0)
free (alpha);
if (gamma != 0)
free (gamma);
if (status == GSL_EZERODIV) {
GSL_ERROR ("matrix must be positive definite", status);
}
return status;
}
/* plain gauss elimination, only not bothering with the zeroes
*
* diag[0] abovediag[0] 0 .....
* belowdiag[0] diag[1] abovediag[1] .....
* 0 belowdiag[1] diag[2]
* 0 0 belowdiag[2] .....
*/
static
int
solve_tridiag_nonsym(
const double diag[], size_t d_stride,
const double abovediag[], size_t a_stride,
const double belowdiag[], size_t b_stride,
const double rhs[], size_t r_stride,
double x[], size_t x_stride,
size_t N)
{
int status = GSL_SUCCESS;
double *alpha = (double *) malloc (N * sizeof (double));
double *z = (double *) malloc (N * sizeof (double));
if (alpha == 0 || z == 0)
{
GSL_ERROR("failed to allocate working space", GSL_ENOMEM);
}
else
{
size_t i, j;
/* Bidiagonalization (eliminating belowdiag)
& rhs update
diag' = alpha
rhs' = z
*/
alpha[0] = diag[0];
z[0] = rhs[0];
if (alpha[0] == 0) {
status = GSL_EZERODIV;
}
for (i = 1; i < N; i++)
{
const double t = belowdiag[b_stride*(i - 1)]/alpha[i-1];
alpha[i] = diag[d_stride*i] - t*abovediag[a_stride*(i - 1)];
z[i] = rhs[r_stride*i] - t*z[i-1];
if (alpha[i] == 0) {
status = GSL_EZERODIV;
}
}
/* backsubstitution */
x[x_stride * (N - 1)] = z[N - 1]/alpha[N - 1];
if (N >= 2)
{
for (i = N - 2, j = 0; j <= N - 2; j++, i--)
{
x[x_stride * i] = (z[i] - abovediag[a_stride*i] * x[x_stride * (i + 1)])/alpha[i];
}
}
}
if (z != 0)
free (z);
if (alpha != 0)
free (alpha);
if (status == GSL_EZERODIV) {
GSL_ERROR ("matrix must be positive definite", status);
}
return status;
}
/* for description of method see [Engeln-Mullges + Uhlig, p. 96]
*
* diag[0] offdiag[0] 0 ..... offdiag[N-1]
* offdiag[0] diag[1] offdiag[1] .....
* 0 offdiag[1] diag[2]
* 0 0 offdiag[2] .....
* ... ...
* offdiag[N-1] ...
*
*/
static
int
solve_cyc_tridiag(
const double diag[], size_t d_stride,
const double offdiag[], size_t o_stride,
const double b[], size_t b_stride,
double x[], size_t x_stride,
size_t N)
{
int status = GSL_SUCCESS;
double * delta = (double *) malloc (N * sizeof (double));
double * gamma = (double *) malloc (N * sizeof (double));
double * alpha = (double *) malloc (N * sizeof (double));
double * c = (double *) malloc (N * sizeof (double));
double * z = (double *) malloc (N * sizeof (double));
if (delta == 0 || gamma == 0 || alpha == 0 || c == 0 || z == 0)
{
GSL_ERROR("failed to allocate working space", GSL_ENOMEM);
}
else
{
size_t i, j;
double sum = 0.0;
/* factor */
if (N == 1)
{
x[0] = b[0] / diag[0];
return GSL_SUCCESS;
}
alpha[0] = diag[0];
gamma[0] = offdiag[0] / alpha[0];
delta[0] = offdiag[o_stride * (N-1)] / alpha[0];
if (alpha[0] == 0) {
status = GSL_EZERODIV;
}
for (i = 1; i < N - 2; i++)
{
alpha[i] = diag[d_stride * i] - offdiag[o_stride * (i-1)] * gamma[i - 1];
gamma[i] = offdiag[o_stride * i] / alpha[i];
delta[i] = -delta[i - 1] * offdiag[o_stride * (i-1)] / alpha[i];
if (alpha[i] == 0) {
status = GSL_EZERODIV;
}
}
for (i = 0; i < N - 2; i++)
{
sum += alpha[i] * delta[i] * delta[i];
}
alpha[N - 2] = diag[d_stride * (N - 2)] - offdiag[o_stride * (N - 3)] * gamma[N - 3];
gamma[N - 2] = (offdiag[o_stride * (N - 2)] - offdiag[o_stride * (N - 3)] * delta[N - 3]) / alpha[N - 2];
alpha[N - 1] = diag[d_stride * (N - 1)] - sum - alpha[(N - 2)] * gamma[N - 2] * gamma[N - 2];
/* update */
z[0] = b[0];
for (i = 1; i < N - 1; i++)
{
z[i] = b[b_stride * i] - z[i - 1] * gamma[i - 1];
}
sum = 0.0;
for (i = 0; i < N - 2; i++)
{
sum += delta[i] * z[i];
}
z[N - 1] = b[b_stride * (N - 1)] - sum - gamma[N - 2] * z[N - 2];
for (i = 0; i < N; i++)
{
c[i] = z[i] / alpha[i];
}
/* backsubstitution */
x[x_stride * (N - 1)] = c[N - 1];
x[x_stride * (N - 2)] = c[N - 2] - gamma[N - 2] * x[x_stride * (N - 1)];
if (N >= 3)
{
for (i = N - 3, j = 0; j <= N - 3; j++, i--)
{
x[x_stride * i] = c[i] - gamma[i] * x[x_stride * (i + 1)] - delta[i] * x[x_stride * (N - 1)];
}
}
}
if (z != 0)
free (z);
if (c != 0)
free (c);
if (alpha != 0)
free (alpha);
if (gamma != 0)
free (gamma);
if (delta != 0)
free (delta);
if (status == GSL_EZERODIV) {
GSL_ERROR ("matrix must be positive definite", status);
}
return status;
}
/* solve following system w/o the corner elements and then use
* Sherman-Morrison formula to compensate for them
*
* diag[0] abovediag[0] 0 ..... belowdiag[N-1]
* belowdiag[0] diag[1] abovediag[1] .....
* 0 belowdiag[1] diag[2]
* 0 0 belowdiag[2] .....
* ... ...
* abovediag[N-1] ...
*/
static
int solve_cyc_tridiag_nonsym(
const double diag[], size_t d_stride,
const double abovediag[], size_t a_stride,
const double belowdiag[], size_t b_stride,
const double rhs[], size_t r_stride,
double x[], size_t x_stride,
size_t N)
{
int status = GSL_SUCCESS;
double *alpha = (double *) malloc (N * sizeof (double));
double *zb = (double *) malloc (N * sizeof (double));
double *zu = (double *) malloc (N * sizeof (double));
double *w = (double *) malloc (N * sizeof (double));
if (alpha == 0 || zb == 0 || zu == 0 || w == 0)
{
GSL_ERROR("failed to allocate working space", GSL_ENOMEM);
}
else
{
double beta;
/* Bidiagonalization (eliminating belowdiag)
& rhs update
diag' = alpha
rhs' = zb
rhs' for Aq=u is zu
*/
zb[0] = rhs[0];
if (diag[0] != 0) beta = -diag[0]; else beta = 1;
{
const double q = 1 - abovediag[0]*belowdiag[0]/(diag[0]*diag[d_stride]);
if (fabs(q/beta) > 0.5 && fabs(q/beta) < 2) {
beta *= (fabs(q/beta) < 1) ? 0.5 : 2;
}
}
zu[0] = beta;
alpha[0] = diag[0] - beta;
if (alpha[0] == 0) {
status = GSL_EZERODIV;
}
{
size_t i;
for (i = 1; i+1 < N; i++)
{
const double t = belowdiag[b_stride*(i - 1)]/alpha[i-1];
alpha[i] = diag[d_stride*i] - t*abovediag[a_stride*(i - 1)];
zb[i] = rhs[r_stride*i] - t*zb[i-1];
zu[i] = -t*zu[i-1];
/* FIXME!!! */
if (alpha[i] == 0) {
status = GSL_EZERODIV;
}
}
}
{
const size_t i = N-1;
const double t = belowdiag[b_stride*(i - 1)]/alpha[i-1];
alpha[i] = diag[d_stride*i]
- abovediag[a_stride*i]*belowdiag[b_stride*i]/beta
- t*abovediag[a_stride*(i - 1)];
zb[i] = rhs[r_stride*i] - t*zb[i-1];
zu[i] = abovediag[a_stride*i] - t*zu[i-1];
/* FIXME!!! */
if (alpha[i] == 0) {
status = GSL_EZERODIV;
}
}
/* backsubstitution */
{
size_t i, j;
w[N-1] = zu[N-1]/alpha[N-1];
x[N-1] = zb[N-1]/alpha[N-1];
for (i = N - 2, j = 0; j <= N - 2; j++, i--)
{
w[i] = (zu[i] - abovediag[a_stride*i] * w[i+1])/alpha[i];
x[i*x_stride] = (zb[i] - abovediag[a_stride*i] * x[x_stride*(i + 1)])/alpha[i];
}
}
/* Sherman-Morrison */
{
const double vw = w[0] + belowdiag[b_stride*(N - 1)]/beta * w[N-1];
const double vx = x[0] + belowdiag[b_stride*(N - 1)]/beta * x[x_stride*(N - 1)];
/* FIXME!!! */
if (vw + 1 == 0) {
status = GSL_EZERODIV;
}
{
size_t i;
for (i = 0; i < N; i++)
x[i] -= vx/(1 + vw)*w[i];
}
}
}
if (zb != 0)
free (zb);
if (zu != 0)
free (zu);
if (w != 0)
free (w);
if (alpha != 0)
free (alpha);
if (status == GSL_EZERODIV) {
GSL_ERROR ("matrix must be positive definite", status);
}
return status;
}
int
gsl_linalg_solve_symm_tridiag(
const gsl_vector * diag,
const gsl_vector * offdiag,
const gsl_vector * rhs,
gsl_vector * solution)
{
if(diag->size != rhs->size)
{
GSL_ERROR ("size of diag must match rhs", GSL_EBADLEN);
}
else if (offdiag->size != rhs->size-1)
{
GSL_ERROR ("size of offdiag must match rhs-1", GSL_EBADLEN);
}
else if (solution->size != rhs->size)
{
GSL_ERROR ("size of solution must match rhs", GSL_EBADLEN);
}
else
{
return solve_tridiag(diag->data, diag->stride,
offdiag->data, offdiag->stride,
rhs->data, rhs->stride,
solution->data, solution->stride,
diag->size);
}
}
int
gsl_linalg_solve_tridiag(
const gsl_vector * diag,
const gsl_vector * abovediag,
const gsl_vector * belowdiag,
const gsl_vector * rhs,
gsl_vector * solution)
{
if(diag->size != rhs->size)
{
GSL_ERROR ("size of diag must match rhs", GSL_EBADLEN);
}
else if (abovediag->size != rhs->size-1)
{
GSL_ERROR ("size of abovediag must match rhs-1", GSL_EBADLEN);
}
else if (belowdiag->size != rhs->size-1)
{
GSL_ERROR ("size of belowdiag must match rhs-1", GSL_EBADLEN);
}
else if (solution->size != rhs->size)
{
GSL_ERROR ("size of solution must match rhs", GSL_EBADLEN);
}
else
{
return solve_tridiag_nonsym(diag->data, diag->stride,
abovediag->data, abovediag->stride,
belowdiag->data, belowdiag->stride,
rhs->data, rhs->stride,
solution->data, solution->stride,
diag->size);
}
}
int
gsl_linalg_solve_symm_cyc_tridiag(
const gsl_vector * diag,
const gsl_vector * offdiag,
const gsl_vector * rhs,
gsl_vector * solution)
{
if(diag->size != rhs->size)
{
GSL_ERROR ("size of diag must match rhs", GSL_EBADLEN);
}
else if (offdiag->size != rhs->size)
{
GSL_ERROR ("size of offdiag must match rhs", GSL_EBADLEN);
}
else if (solution->size != rhs->size)
{
GSL_ERROR ("size of solution must match rhs", GSL_EBADLEN);
}
else if (diag->size < 3)
{
GSL_ERROR ("size of cyclic system must be 3 or more", GSL_EBADLEN);
}
else
{
return solve_cyc_tridiag(diag->data, diag->stride,
offdiag->data, offdiag->stride,
rhs->data, rhs->stride,
solution->data, solution->stride,
diag->size);
}
}
int
gsl_linalg_solve_cyc_tridiag(
const gsl_vector * diag,
const gsl_vector * abovediag,
const gsl_vector * belowdiag,
const gsl_vector * rhs,
gsl_vector * solution)
{
if(diag->size != rhs->size)
{
GSL_ERROR ("size of diag must match rhs", GSL_EBADLEN);
}
else if (abovediag->size != rhs->size)
{
GSL_ERROR ("size of abovediag must match rhs", GSL_EBADLEN);
}
else if (belowdiag->size != rhs->size)
{
GSL_ERROR ("size of belowdiag must match rhs", GSL_EBADLEN);
}
else if (solution->size != rhs->size)
{
GSL_ERROR ("size of solution must match rhs", GSL_EBADLEN);
}
else if (diag->size < 3)
{
GSL_ERROR ("size of cyclic system must be 3 or more", GSL_EBADLEN);
}
else
{
return solve_cyc_tridiag_nonsym(diag->data, diag->stride,
abovediag->data, abovediag->stride,
belowdiag->data, belowdiag->stride,
rhs->data, rhs->stride,
solution->data, solution->stride,
diag->size);
}
}
| PeterWolf-tw/NeoPraat | sources_5401/external/gsl/gsl_linalg__tridiag.c | C | lgpl-3.0 | 15,815 |
{
"translatorID": "cd587058-6125-4b33-a876-8c6aae48b5e8",
"label": "WHO",
"creator": "Mario Trojan, Philipp Zumstein",
"target": "^http://apps\\.who\\.int/iris/",
"minVersion": "3.0",
"maxVersion": "",
"priority": 100,
"inRepository": true,
"translatorType": 4,
"browserSupport": "gcsibv",
"lastUpdated": "2018-09-02 14:34:27"
}
/*
***** BEGIN LICENSE BLOCK *****
Copyright © 2018 Mario Trojan
This file is part of Zotero.
Zotero 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.
Zotero 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 Zotero. If not, see <http://www.gnu.org/licenses/>.
***** END LICENSE BLOCK *****
*/
// attr()/text() v2
function attr(docOrElem,selector,attr,index){var elem=index?docOrElem.querySelectorAll(selector).item(index):docOrElem.querySelector(selector);return elem?elem.getAttribute(attr):null;}
function text(docOrElem,selector,index){var elem=index?docOrElem.querySelectorAll(selector).item(index):docOrElem.querySelector(selector);return elem?elem.textContent:null;}
function detectWeb(doc, url) {
if (url.includes("/handle/") && text(doc, 'div.item-summary-view-metadata')) {
var type = attr(doc, 'meta[name="DC.type"]', 'content');
//Z.debug(type);
if (type && type.includes("articles")) {
return "journalArticle";
}
if (type && (type.includes("Book") || type.includes("Publications"))) {
return "book";
}
return "report";
} else if (getSearchResults(doc, true)) {
return "multiple";
}
}
function getSearchResults(doc, checkOnly) {
var items = {};
var found = false;
var rows = doc.querySelectorAll('h4.artifact-title>a');
for (let i=0; i<rows.length; i++) {
let href = rows[i].href;
var title = rows[i].textContent;
if (!href || !title) continue;
if (checkOnly) return true;
found = true;
items[href] = title;
}
return found ? items : false;
}
function doWeb(doc, url) {
if (detectWeb(doc, url) == "multiple") {
Zotero.selectItems(getSearchResults(doc, false), function (items) {
if (!items) {
return true;
}
var articles = [];
for (var i in items) {
articles.push(i);
}
ZU.processDocuments(articles, scrape);
});
} else {
scrape(doc, url);
}
}
function scrape(doc, url) {
// copy meta tags in body to head
var head = doc.getElementsByTagName('head');
var metasInBody = ZU.xpath(doc, '//body/meta');
for (let meta of metasInBody) {
head[0].append(meta);
}
var type = detectWeb(doc, url);
var translator = Zotero.loadTranslator('web');
// Embedded Metadata
translator.setTranslator('951c027d-74ac-47d4-a107-9c3069ab7b48');
translator.setHandler('itemDone', function (obj, item) {
if (item.publisher && !item.place && item.publisher.includes(' : ')) {
let placePublisher = item.publisher.split(' : ');
item.place = placePublisher[0];
item.publisher = placePublisher[1];
}
var firstAuthor = attr(doc, 'meta[name="DC.creator"]', 'content');
if (firstAuthor && !firstAuthor.includes(',')) {
item.creators[0] = {
"lastName": firstAuthor,
"creatorType": "author",
"fieldMode": true
};
}
var descriptions = doc.querySelectorAll('meta[name="DC.description"]');
// DC.description doesn't actually contain other useful content,
// except possibly the number of pages
for (let description of descriptions) {
var numPages = description.content.match(/(([lxiv]+,\s*)?\d+)\s*p/);
if (numPages) {
if (ZU.fieldIsValidForType("numPages", item.itemType)) {
item.numPages = numPages[1];
}
else if (!item.extra) {
item.extra = "number-of-pages: " + numPages[1];
}
else {
item.extra += "\nnumber-of-pages: " + numPages[1];
}
delete item.abstractNote;
}
}
item.complete();
});
translator.getTranslatorObject(function(trans) {
trans.itemType = type;
trans.doWeb(doc, url);
});
}
/** BEGIN TEST CASES **/
var testCases = [
{
"type": "web",
"url": "http://apps.who.int/iris/handle/10665/70863?locale=ar",
"items": [
{
"itemType": "report",
"title": "Consensus document on the epidemiology of severe acute respiratory syndrome (SARS)",
"creators": [
{
"lastName": "World Health Organization",
"creatorType": "author",
"fieldMode": true
}
],
"date": "2003",
"extra": "number-of-pages: 46",
"institution": "World Health Organization",
"language": "en",
"libraryCatalog": "apps.who.int",
"place": "Geneva",
"reportNumber": "WHO/CDS/CSR/GAR/2003.11",
"url": "http://apps.who.int/iris/handle/10665/70863",
"attachments": [
{
"title": "Full Text PDF",
"mimeType": "application/pdf"
},
{
"title": "Snapshot"
}
],
"tags": [
{
"tag": "Communicable Diseases and their Control"
},
{
"tag": "Disease outbreaks"
},
{
"tag": "Epidemiologic surveillance"
},
{
"tag": "Severe acute respiratory syndrome"
}
],
"notes": [],
"seeAlso": []
}
]
},
{
"type": "web",
"url": "http://apps.who.int/iris/handle/10665/272081",
"items": [
{
"itemType": "journalArticle",
"title": "Providing oxygen to children in hospitals: a realist review",
"creators": [
{
"firstName": "Hamish",
"lastName": "Graham",
"creatorType": "author"
},
{
"firstName": "Shidan",
"lastName": "Tosif",
"creatorType": "author"
},
{
"firstName": "Amy",
"lastName": "Gray",
"creatorType": "author"
},
{
"firstName": "Shamim",
"lastName": "Qazi",
"creatorType": "author"
},
{
"firstName": "Harry",
"lastName": "Campbell",
"creatorType": "author"
},
{
"firstName": "David",
"lastName": "Peel",
"creatorType": "author"
},
{
"firstName": "Barbara",
"lastName": "McPake",
"creatorType": "author"
},
{
"firstName": "Trevor",
"lastName": "Duke",
"creatorType": "author"
}
],
"date": "2017-4-01",
"DOI": "10.2471/BLT.16.186676",
"ISSN": "0042-9686",
"abstractNote": "288",
"extra": "PMID: 28479624",
"issue": "4",
"language": "en",
"libraryCatalog": "apps.who.int",
"pages": "288-302",
"publicationTitle": "Bulletin of the World Health Organization",
"rights": "http://creativecommons.org/licenses/by/3.0/igo/legalcode",
"shortTitle": "Providing oxygen to children in hospitals",
"url": "http://apps.who.int/iris/handle/10665/272081",
"volume": "95",
"attachments": [
{
"title": "Full Text PDF",
"mimeType": "application/pdf"
},
{
"title": "Snapshot"
},
{
"title": "PubMed entry",
"mimeType": "text/html",
"snapshot": false
}
],
"tags": [
{
"tag": "Systematic Reviews"
}
],
"notes": [],
"seeAlso": []
}
]
},
{
"type": "web",
"url": "http://apps.who.int/iris/handle/10665/273678",
"items": [
{
"itemType": "book",
"title": "Сборник руководящих принципов и стандартов ВОЗ: обеспечение оптимального оказания медицинских услуг пациентам с туберкулезом",
"creators": [
{
"lastName": "Всемирная организация здравоохранения",
"creatorType": "author",
"fieldMode": true
}
],
"date": "2018",
"ISBN": "9789244514108",
"language": "ru",
"libraryCatalog": "apps.who.int",
"numPages": "47",
"publisher": "Всемирная организация здравоохранения",
"rights": "CC BY-NC-SA 3.0 IGO",
"shortTitle": "Сборник руководящих принципов и стандартов ВОЗ",
"url": "http://apps.who.int/iris/handle/10665/273678",
"attachments": [
{
"title": "Full Text PDF",
"mimeType": "application/pdf"
},
{
"title": "Snapshot"
}
],
"tags": [
{
"tag": "Delivery of Health Care"
},
{
"tag": "Disease Management"
},
{
"tag": "Guideline"
},
{
"tag": "Infection Control"
},
{
"tag": "Multidrug-Resistant"
},
{
"tag": "Patient Care"
},
{
"tag": "Reference Standards"
},
{
"tag": "Tuberculosis"
}
],
"notes": [],
"seeAlso": []
}
]
},
{
"type": "web",
"url": "http://apps.who.int/iris/handle/10665/165097",
"items": "multiple"
},
{
"type": "web",
"url": "http://apps.who.int/iris/discover?query=acupuncture",
"items": "multiple"
}
];
/** END TEST CASES **/
| ZotPlus/zotero-better-bibtex | test/fixtures/profile/zotero/zotero/translators/WHO.js | JavaScript | unlicense | 9,219 |
'use strict';
angular.module('mgcrea.ngStrap.typeahead', ['mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.parseOptions'])
.provider('$typeahead', function() {
var defaults = this.defaults = {
animation: 'am-fade',
prefixClass: 'typeahead',
prefixEvent: '$typeahead',
placement: 'bottom-left',
template: 'typeahead/typeahead.tpl.html',
trigger: 'focus',
container: false,
keyboard: true,
html: false,
delay: 0,
minLength: 1,
filter: 'filter',
limit: 6
};
this.$get = function($window, $rootScope, $tooltip) {
var bodyEl = angular.element($window.document.body);
function TypeaheadFactory(element, controller, config) {
var $typeahead = {};
// Common vars
var options = angular.extend({}, defaults, config);
$typeahead = $tooltip(element, options);
var parentScope = config.scope;
var scope = $typeahead.$scope;
scope.$resetMatches = function(){
scope.$matches = [];
scope.$activeIndex = 0;
};
scope.$resetMatches();
scope.$activate = function(index) {
scope.$$postDigest(function() {
$typeahead.activate(index);
});
};
scope.$select = function(index, evt) {
scope.$$postDigest(function() {
$typeahead.select(index);
});
};
scope.$isVisible = function() {
return $typeahead.$isVisible();
};
// Public methods
$typeahead.update = function(matches) {
scope.$matches = matches;
if(scope.$activeIndex >= matches.length) {
scope.$activeIndex = 0;
}
};
$typeahead.activate = function(index) {
scope.$activeIndex = index;
};
$typeahead.select = function(index) {
var value = scope.$matches[index].value;
controller.$setViewValue(value);
controller.$render();
scope.$resetMatches();
if(parentScope) parentScope.$digest();
// Emit event
scope.$emit(options.prefixEvent + '.select', value, index);
};
// Protected methods
$typeahead.$isVisible = function() {
if(!options.minLength || !controller) {
return !!scope.$matches.length;
}
// minLength support
return scope.$matches.length && angular.isString(controller.$viewValue) && controller.$viewValue.length >= options.minLength;
};
$typeahead.$getIndex = function(value) {
var l = scope.$matches.length, i = l;
if(!l) return;
for(i = l; i--;) {
if(scope.$matches[i].value === value) break;
}
if(i < 0) return;
return i;
};
$typeahead.$onMouseDown = function(evt) {
// Prevent blur on mousedown
evt.preventDefault();
evt.stopPropagation();
};
$typeahead.$onKeyDown = function(evt) {
if(!/(38|40|13)/.test(evt.keyCode)) return;
// Let ngSubmit pass if the typeahead tip is hidden
if($typeahead.$isVisible()) {
evt.preventDefault();
evt.stopPropagation();
}
// Select with enter
if(evt.keyCode === 13 && scope.$matches.length) {
$typeahead.select(scope.$activeIndex);
}
// Navigate with keyboard
else if(evt.keyCode === 38 && scope.$activeIndex > 0) scope.$activeIndex--;
else if(evt.keyCode === 40 && scope.$activeIndex < scope.$matches.length - 1) scope.$activeIndex++;
else if(angular.isUndefined(scope.$activeIndex)) scope.$activeIndex = 0;
scope.$digest();
};
// Overrides
var show = $typeahead.show;
$typeahead.show = function() {
show();
setTimeout(function() {
$typeahead.$element.on('mousedown', $typeahead.$onMouseDown);
if(options.keyboard) {
element.on('keydown', $typeahead.$onKeyDown);
}
});
};
var hide = $typeahead.hide;
$typeahead.hide = function() {
$typeahead.$element.off('mousedown', $typeahead.$onMouseDown);
if(options.keyboard) {
element.off('keydown', $typeahead.$onKeyDown);
}
hide();
};
return $typeahead;
}
TypeaheadFactory.defaults = defaults;
return TypeaheadFactory;
};
})
.directive('bsTypeahead', function($window, $parse, $q, $typeahead, $parseOptions) {
var defaults = $typeahead.defaults;
return {
restrict: 'EAC',
require: 'ngModel',
link: function postLink(scope, element, attr, controller) {
// Directive options
var options = {scope: scope};
angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'filter', 'limit', 'minLength', 'watchOptions', 'selectMode'], function(key) {
if(angular.isDefined(attr[key])) options[key] = attr[key];
});
// Build proper ngOptions
var filter = options.filter || defaults.filter;
var limit = options.limit || defaults.limit;
var ngOptions = attr.ngOptions;
if(filter) ngOptions += ' | ' + filter + ':$viewValue';
if(limit) ngOptions += ' | limitTo:' + limit;
var parsedOptions = $parseOptions(ngOptions);
// Initialize typeahead
var typeahead = $typeahead(element, controller, options);
// Watch options on demand
if(options.watchOptions) {
// Watch ngOptions values before filtering for changes, drop function calls
var watchedOptions = parsedOptions.$match[7].replace(/\|.+/, '').replace(/\(.*\)/g, '').trim();
scope.$watch(watchedOptions, function (newValue, oldValue) {
// console.warn('scope.$watch(%s)', watchedOptions, newValue, oldValue);
parsedOptions.valuesFn(scope, controller).then(function (values) {
typeahead.update(values);
controller.$render();
});
}, true);
}
// Watch model for changes
scope.$watch(attr.ngModel, function(newValue, oldValue) {
// console.warn('$watch', element.attr('ng-model'), newValue);
scope.$modelValue = newValue; // Publish modelValue on scope for custom templates
parsedOptions.valuesFn(scope, controller)
.then(function(values) {
// Prevent input with no future prospect if selectMode is truthy
// @TODO test selectMode
if(options.selectMode && !values.length && newValue.length > 0) {
controller.$setViewValue(controller.$viewValue.substring(0, controller.$viewValue.length - 1));
return;
}
if(values.length > limit) values = values.slice(0, limit);
var isVisible = typeahead.$isVisible();
isVisible && typeahead.update(values);
// Do not re-queue an update if a correct value has been selected
if(values.length === 1 && values[0].value === newValue) return;
!isVisible && typeahead.update(values);
// Queue a new rendering that will leverage collection loading
controller.$render();
});
});
// Model rendering in view
controller.$render = function () {
// console.warn('$render', element.attr('ng-model'), 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue, 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue);
if(controller.$isEmpty(controller.$viewValue)) return element.val('');
var index = typeahead.$getIndex(controller.$modelValue);
var selected = angular.isDefined(index) ? typeahead.$scope.$matches[index].label : controller.$viewValue;
selected = angular.isObject(selected) ? selected.label : selected;
element.val(selected.replace(/<(?:.|\n)*?>/gm, '').trim());
};
// Garbage collection
scope.$on('$destroy', function() {
if (typeahead) typeahead.destroy();
options = null;
typeahead = null;
});
}
};
});
| anirvann/testApp | vendor/angular-strap/src/typeahead/typeahead.js | JavaScript | unlicense | 8,390 |
namespace TinderApp.Library.Controls
{
public interface IApp
{
CustomPhoneApplicationFrame RootFrameInstance { get; }
void Logout();
}
} | brianhama/tinder | TinderApp.Library/Controls/IApp.cs | C# | unlicense | 168 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.common;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.api.core.client.ActiveMQClient;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.client.ClientRequestor;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.api.core.management.ManagementHelper;
import org.apache.activemq.artemis.api.core.management.ResourceNames;
import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory;
import org.apache.activemq.artemis.tests.util.SpawnedVMSupport;
import org.junit.Assert;
import org.objectweb.jtests.jms.admin.Admin;
/**
* AbstractAdmin.
*/
public class AbstractAdmin implements Admin {
protected ClientSession clientSession;
protected ClientRequestor requestor;
protected boolean serverLifeCycleActive;
protected Process serverProcess;
protected ServerLocator serverLocator;
protected ClientSessionFactory sf;
// this is a constant to control if we should use a separate VM for the server.
public static final boolean spawnServer = false;
/**
* Determines whether to act or 'no-op' on serverStart() and
* serverStop(). This is used when testing combinations of client and
* servers with different versions.
*/
private static final String SERVER_LIVE_CYCLE_PROPERTY = "org.apache.activemq.artemis.jms.ActiveMQAMQPAdmin.serverLifeCycle";
public AbstractAdmin() {
serverLifeCycleActive = Boolean.valueOf(System.getProperty(SERVER_LIVE_CYCLE_PROPERTY, "true"));
}
@Override
public String getName() {
return getClass().getName();
}
@Override
public void start() throws Exception {
serverLocator = ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(NettyConnectorFactory.class.getName()));
sf = serverLocator.createSessionFactory();
clientSession = sf.createSession(ActiveMQDefaultConfiguration.getDefaultClusterUser(), ActiveMQDefaultConfiguration.getDefaultClusterPassword(), false, true, true, false, 1);
requestor = new ClientRequestor(clientSession, ActiveMQDefaultConfiguration.getDefaultManagementAddress());
clientSession.start();
}
@Override
public void stop() throws Exception {
requestor.close();
if (sf != null) {
sf.close();
}
if (serverLocator != null) {
serverLocator.close();
}
sf = null;
serverLocator = null;
}
@Override
public Context createContext() throws NamingException {
return new InitialContext();
}
@Override
public void createConnectionFactory(final String name) {
throw new RuntimeException("FIXME NYI createConnectionFactory");
}
@Override
public void deleteConnectionFactory(final String name) {
throw new RuntimeException("FIXME NYI deleteConnectionFactory");
}
@Override
public void createQueue(final String name) {
Boolean result;
try {
result = (Boolean) invokeSyncOperation(ResourceNames.JMS_SERVER, "createQueue", name, name);
Assert.assertEquals(true, result.booleanValue());
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
@Override
public void deleteQueue(final String name) {
Boolean result;
try {
result = (Boolean) invokeSyncOperation(ResourceNames.JMS_SERVER, "destroyQueue", name);
Assert.assertEquals(true, result.booleanValue());
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
@Override
public void createQueueConnectionFactory(final String name) {
createConnectionFactory(name);
}
@Override
public void deleteQueueConnectionFactory(final String name) {
deleteConnectionFactory(name);
}
@Override
public void createTopic(final String name) {
Boolean result;
try {
result = (Boolean) invokeSyncOperation(ResourceNames.JMS_SERVER, "createTopic", name, name);
Assert.assertEquals(true, result.booleanValue());
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
@Override
public void deleteTopic(final String name) {
Boolean result;
try {
result = (Boolean) invokeSyncOperation(ResourceNames.JMS_SERVER, "destroyTopic", name);
Assert.assertEquals(true, result.booleanValue());
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
@Override
public void createTopicConnectionFactory(final String name) {
createConnectionFactory(name);
}
@Override
public void deleteTopicConnectionFactory(final String name) {
deleteConnectionFactory(name);
}
@Override
public void startServer() throws Exception {
if (!serverLifeCycleActive) {
return;
}
if (spawnServer) {
String[] vmArgs = new String[]{};
serverProcess = SpawnedVMSupport.spawnVM(SpawnedJMSServer.class.getName(), vmArgs, false);
InputStreamReader isr = new InputStreamReader(serverProcess.getInputStream());
final BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("SERVER: " + line);
if ("OK".equals(line.trim())) {
new Thread() {
@Override
public void run() {
try {
String line1 = null;
while ((line1 = br.readLine()) != null) {
System.out.println("SERVER: " + line1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
return;
} else if ("KO".equals(line.trim())) {
// something went wrong with the server, destroy it:
serverProcess.destroy();
throw new IllegalStateException("Unable to start the spawned server :" + line);
}
}
} else {
SpawnedJMSServer.startServer();
}
}
@Override
public void stopServer() throws Exception {
if (!serverLifeCycleActive) {
return;
}
if (spawnServer) {
OutputStreamWriter osw = new OutputStreamWriter(serverProcess.getOutputStream());
osw.write("STOP\n");
osw.flush();
int exitValue = serverProcess.waitFor();
if (exitValue != 0) {
serverProcess.destroy();
}
} else {
SpawnedJMSServer.stopServer();
}
}
protected Object invokeSyncOperation(final String resourceName,
final String operationName,
final Object... parameters) throws Exception {
ClientMessage message = clientSession.createMessage(false);
ManagementHelper.putOperationInvocation(message, resourceName, operationName, parameters);
ClientMessage reply;
try {
reply = requestor.request(message, 3000);
} catch (Exception e) {
throw new IllegalStateException("Exception while invoking " + operationName + " on " + resourceName, e);
}
if (reply == null) {
throw new IllegalStateException("no reply received when invoking " + operationName + " on " + resourceName);
}
if (!ManagementHelper.hasOperationSucceeded(reply)) {
throw new IllegalStateException("operation failed when invoking " + operationName +
" on " +
resourceName +
": " +
ManagementHelper.getResult(reply));
}
return ManagementHelper.getResult(reply);
}
}
| okalmanRH/jboss-activemq-artemis | tests/joram-tests/src/test/java/org/apache/activemq/artemis/common/AbstractAdmin.java | Java | apache-2.0 | 9,253 |
/*
Copyright 2019 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package retry
import (
"errors"
"testing"
)
// Returns a function that will return n errors, then return successfully forever.
func errorGenerator(n int, retryable bool) func() error {
errorCount := 0
return func() (err error) {
if errorCount < n {
errorCount++
e := errors.New("Error")
if retryable {
return &RetriableError{Err: e}
}
return e
}
return nil
}
}
func TestErrorGenerator(t *testing.T) {
errors := 3
f := errorGenerator(errors, false)
for i := 0; i < errors-1; i++ {
if err := f(); err == nil {
t.Fatalf("Error should have been thrown at iteration %v", i)
}
}
if err := f(); err == nil {
t.Fatalf("Error should not have been thrown this call!")
}
}
| dalehamel/minikube | pkg/util/retry/retry_test.go | GO | apache-2.0 | 1,303 |
EXTRA_OBJS=typex.o addx.o
include ../common
| thender/ppp | tests/t0323x/Makefile | Makefile | apache-2.0 | 44 |
#!/bin/bash
set -x
set -e
resources/Datasources/hbase/createHbaseTables.sh
wait
hbase org.apache.hadoop.hbase.mapreduce.ImportTsv -Dmapred.map.tasks.speculative.execution=false -Dmapred.reduce.tasks.speculative.execution=false -Dimporttsv.columns=HBASE_ROW_KEY,onecf:name,twocf:age,twocf:registration,threecf:contributions,threecf:voterzone,fourcf:create_date voter /drill/testdata/hbase/votertab
hbase org.apache.hadoop.hbase.mapreduce.ImportTsv -Dmapred.map.tasks.speculative.execution=false -Dmapred.reduce.tasks.speculative.execution=false -Dimporttsv.columns=HBASE_ROW_KEY,onecf:name,twocf:age,threecf:gpa,fourcf:studentnum,fivecf:create_date student /drill/testdata/hbase/studenttab
set +x
| Agirish/drill-test-framework-archive | framework/resources/Datasources/hbase/hbase.sh | Shell | apache-2.0 | 702 |
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
use clippy_utils::get_parent_node;
use clippy_utils::source::snippet_with_context;
use clippy_utils::sugg;
use clippy_utils::ty::is_copy;
use rustc_errors::Applicability;
use rustc_hir::{BindingAnnotation, Expr, ExprKind, MatchSource, Node, PatKind};
use rustc_lint::LateContext;
use rustc_middle::ty::{self, adjustment::Adjust};
use rustc_span::symbol::{sym, Symbol};
use super::CLONE_DOUBLE_REF;
use super::CLONE_ON_COPY;
/// Checks for the `CLONE_ON_COPY` lint.
#[allow(clippy::too_many_lines)]
pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, method_name: Symbol, args: &[Expr<'_>]) {
let arg = match args {
[arg] if method_name == sym::clone => arg,
_ => return,
};
if cx
.typeck_results()
.type_dependent_def_id(expr.hir_id)
.and_then(|id| cx.tcx.trait_of_item(id))
.zip(cx.tcx.lang_items().clone_trait())
.map_or(true, |(x, y)| x != y)
{
return;
}
let arg_adjustments = cx.typeck_results().expr_adjustments(arg);
let arg_ty = arg_adjustments
.last()
.map_or_else(|| cx.typeck_results().expr_ty(arg), |a| a.target);
let ty = cx.typeck_results().expr_ty(expr);
if let ty::Ref(_, inner, _) = arg_ty.kind() {
if let ty::Ref(_, innermost, _) = inner.kind() {
span_lint_and_then(
cx,
CLONE_DOUBLE_REF,
expr.span,
&format!(
"using `clone` on a double-reference; \
this will copy the reference of type `{}` instead of cloning the inner type",
ty
),
|diag| {
if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
let mut ty = innermost;
let mut n = 0;
while let ty::Ref(_, inner, _) = ty.kind() {
ty = inner;
n += 1;
}
let refs = "&".repeat(n + 1);
let derefs = "*".repeat(n);
let explicit = format!("<{}{}>::clone({})", refs, ty, snip);
diag.span_suggestion(
expr.span,
"try dereferencing it",
format!("{}({}{}).clone()", refs, derefs, snip.deref()),
Applicability::MaybeIncorrect,
);
diag.span_suggestion(
expr.span,
"or try being explicit if you are sure, that you want to clone a reference",
explicit,
Applicability::MaybeIncorrect,
);
}
},
);
return; // don't report clone_on_copy
}
}
if is_copy(cx, ty) {
let parent_is_suffix_expr = match get_parent_node(cx.tcx, expr.hir_id) {
Some(Node::Expr(parent)) => match parent.kind {
// &*x is a nop, &x.clone() is not
ExprKind::AddrOf(..) => return,
// (*x).func() is useless, x.clone().func() can work in case func borrows self
ExprKind::MethodCall(_, _, [self_arg, ..], _)
if expr.hir_id == self_arg.hir_id && ty != cx.typeck_results().expr_ty_adjusted(expr) =>
{
return;
},
ExprKind::MethodCall(_, _, [self_arg, ..], _) if expr.hir_id == self_arg.hir_id => true,
ExprKind::Match(_, _, MatchSource::TryDesugar | MatchSource::AwaitDesugar)
| ExprKind::Field(..)
| ExprKind::Index(..) => true,
_ => false,
},
// local binding capturing a reference
Some(Node::Local(l))
if matches!(
l.pat.kind,
PatKind::Binding(BindingAnnotation::Ref | BindingAnnotation::RefMut, ..)
) =>
{
return;
},
_ => false,
};
let mut app = Applicability::MachineApplicable;
let snip = snippet_with_context(cx, arg.span, expr.span.ctxt(), "_", &mut app).0;
let deref_count = arg_adjustments
.iter()
.take_while(|adj| matches!(adj.kind, Adjust::Deref(_)))
.count();
let (help, sugg) = if deref_count == 0 {
("try removing the `clone` call", snip.into())
} else if parent_is_suffix_expr {
("try dereferencing it", format!("({}{})", "*".repeat(deref_count), snip))
} else {
("try dereferencing it", format!("{}{}", "*".repeat(deref_count), snip))
};
span_lint_and_sugg(
cx,
CLONE_ON_COPY,
expr.span,
&format!("using `clone` on type `{}` which implements the `Copy` trait", ty),
help,
sugg,
app,
);
}
}
| graydon/rust | src/tools/clippy/clippy_lints/src/methods/clone_on_copy.rs | Rust | apache-2.0 | 5,174 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.qpid.jms.integration;
import static org.apache.qpid.jms.provider.amqp.AmqpSupport.ANONYMOUS_RELAY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.UUID;
import javax.jms.JMSContext;
import javax.jms.JMSProducer;
import org.apache.qpid.jms.test.QpidJmsTestCase;
import org.apache.qpid.jms.test.testpeer.TestAmqpPeer;
import org.apache.qpid.proton.amqp.Binary;
import org.apache.qpid.proton.amqp.Symbol;
import org.junit.Test;
public class JMSContextIntegrationTest extends QpidJmsTestCase {
private final IntegrationTestFixture testFixture = new IntegrationTestFixture();
private Symbol[] SERVER_ANONYMOUS_RELAY = new Symbol[]{ANONYMOUS_RELAY};
@Test(timeout = 20000)
public void testCreateAndCloseContext() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
JMSContext context = testFixture.createJMSContext(testPeer);
testPeer.expectClose();
context.close();
testPeer.waitForAllHandlersToComplete(1000);
}
}
@Test(timeout = 20000)
public void testCreateContextWithClientId() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
JMSContext context = testFixture.createJMSContext(testPeer, false, null, null, null, true);
testPeer.expectClose();
context.close();
testPeer.waitForAllHandlersToComplete(1000);
}
}
@Test(timeout = 20000)
public void testCreateContextAndSetClientID() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
JMSContext context = testFixture.createJMSContext(testPeer, false, null, null, null, false);
context.setClientID(UUID.randomUUID().toString());
testPeer.expectClose();
context.close();
testPeer.waitForAllHandlersToComplete(1000);
}
}
@Test(timeout = 20000)
public void testCreateAutoAckSessionByDefault() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
JMSContext context = testFixture.createJMSContext(testPeer);
assertEquals(JMSContext.AUTO_ACKNOWLEDGE, context.getSessionMode());
testPeer.expectBegin();
context.createTopic("TopicName");
testPeer.expectEnd();
testPeer.expectClose();
context.close();
testPeer.waitForAllHandlersToComplete(1000);
}
}
@Test(timeout = 20000)
public void testCreateContextWithTransactedSessionMode() throws Exception {
Binary txnId = new Binary(new byte[]{ (byte) 5, (byte) 6, (byte) 7, (byte) 8});
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
JMSContext context = testFixture.createJMSContext(testPeer, JMSContext.SESSION_TRANSACTED);
assertEquals(JMSContext.SESSION_TRANSACTED, context.getSessionMode());
// Session should be created and a coordinator should be attached since this
// should be a TX session, then a new TX is declared, once closed the TX should
// be discharged as a roll back.
testPeer.expectBegin();
testPeer.expectCoordinatorAttach();
testPeer.expectDeclare(txnId);
testPeer.expectDischarge(txnId, true);
testPeer.expectEnd();
testPeer.expectClose();
context.createTopic("TopicName");
context.close();
testPeer.waitForAllHandlersToComplete(1000);
}
}
@Test(timeout = 20000)
public void testCreateContextFromContextWithSessionsActive() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
JMSContext context = testFixture.createJMSContext(testPeer);
assertEquals(JMSContext.AUTO_ACKNOWLEDGE, context.getSessionMode());
testPeer.expectBegin();
context.createTopic("TopicName");
// Create a second should not create a new session yet, once a new connection is
// create on demand then close of the second context should only close the session
JMSContext other = context.createContext(JMSContext.CLIENT_ACKNOWLEDGE);
assertEquals(JMSContext.CLIENT_ACKNOWLEDGE, other.getSessionMode());
testPeer.expectBegin();
testPeer.expectEnd();
other.createTopic("TopicName");
other.close();
testPeer.waitForAllHandlersToComplete(1000);
// Now the connection should close down.
testPeer.expectEnd();
testPeer.expectClose();
context.close();
testPeer.waitForAllHandlersToComplete(1000);
}
}
@Test(timeout = 20000)
public void testOnlyOneProducerCreatedInSingleContext() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
JMSContext context = testFixture.createJMSContext(testPeer, SERVER_ANONYMOUS_RELAY);
assertEquals(JMSContext.AUTO_ACKNOWLEDGE, context.getSessionMode());
testPeer.expectBegin();
testPeer.expectSenderAttach();
// One producer created should send an attach.
JMSProducer producer1 = context.createProducer();
assertNotNull(producer1);
// An additional one should not result in an attach
JMSProducer producer2 = context.createProducer();
assertNotNull(producer2);
testPeer.expectEnd();
testPeer.expectClose();
context.close();
testPeer.waitForAllHandlersToComplete(1000);
}
}
@Test(timeout = 20000)
public void testEachContextGetsItsOwnProducer() throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
JMSContext context = testFixture.createJMSContext(testPeer, SERVER_ANONYMOUS_RELAY);
assertEquals(JMSContext.AUTO_ACKNOWLEDGE, context.getSessionMode());
testPeer.expectBegin();
testPeer.expectSenderAttach();
testPeer.expectBegin();
testPeer.expectSenderAttach();
// One producer created should send an attach.
JMSProducer producer1 = context.createProducer();
assertNotNull(producer1);
// An additional one should not result in an attach
JMSContext other = context.createContext(JMSContext.AUTO_ACKNOWLEDGE);
JMSProducer producer2 = other.createProducer();
assertNotNull(producer2);
testPeer.expectEnd();
testPeer.expectEnd();
testPeer.expectClose();
other.close();
context.close();
testPeer.waitForAllHandlersToComplete(1000);
}
}
}
| apache/qpid-jms | qpid-jms-client/src/test/java/org/apache/qpid/jms/integration/JMSContextIntegrationTest.java | Java | apache-2.0 | 7,660 |
# 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.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
| dmlc/tvm | tests/python/unittest/test_tir_transform_simplify.py | Python | apache-2.0 | 5,007 |
The MIT License (MIT)
Copyright (c) 2014-2016 Oleg Kiriljuk
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.
------------------------------------------------------------------------------
[GNU GENERAL PUBLIC LICENSE](http://www.gnu.org/licenses/gpl-2.0.html)
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS | shenzhongwei/wine | vendor/bower/free-jqgrid/LICENSE.md | Markdown | apache-2.0 | 16,427 |
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn foo<T>(o: myoption<T>) -> int {
let mut x: int = 5;
match o {
none::<T> => { }
some::<T>(_t) => { x += 1; }
}
return x;
}
enum myoption<T> { none, some(T), }
pub fn main() { info!("{}", 5); }
| mitsuhiko/rust | src/test/run-pass/use-uninit-match.rs | Rust | apache-2.0 | 698 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.elasticsearch;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.Component;
import org.apache.camel.component.extension.ComponentVerifierExtension;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Assert;
import org.junit.Test;
public class ElasticsearchRestComponentVerifierExtensionTest extends CamelTestSupport {
// *************************************************
// Tests (parameters)
// *************************************************
@Override
public boolean isUseRouteBuilder() {
return false;
}
@Test
public void testParameters() throws Exception {
Component component = context().getComponent("elasticsearch-rest");
ComponentVerifierExtension verifier = component.getExtension(ComponentVerifierExtension.class).orElseThrow(IllegalStateException::new);
Map<String, Object> parameters = new HashMap<>();
parameters.put("hostAddresses", "http://localhost:9000");
parameters.put("clusterName", "es-test");
ComponentVerifierExtension.Result result = verifier.verify(ComponentVerifierExtension.Scope.PARAMETERS, parameters);
Assert.assertEquals(ComponentVerifierExtension.Result.Status.OK, result.getStatus());
}
@Test
public void testConnectivity() throws Exception {
Component component = context().getComponent("elasticsearch-rest");
ComponentVerifierExtension verifier = component.getExtension(ComponentVerifierExtension.class).orElseThrow(IllegalStateException::new);
Map<String, Object> parameters = new HashMap<>();
parameters.put("hostAddresses", "http://localhost:9000");
ComponentVerifierExtension.Result result = verifier.verify(ComponentVerifierExtension.Scope.CONNECTIVITY, parameters);
Assert.assertEquals(ComponentVerifierExtension.Result.Status.ERROR, result.getStatus());
}
}
| objectiser/camel | components/camel-elasticsearch-rest/src/test/java/org/apache/camel/component/elasticsearch/ElasticsearchRestComponentVerifierExtensionTest.java | Java | apache-2.0 | 2,756 |
package org.apereo.cas.authentication;
import com.google.common.base.Splitter;
import org.apereo.cas.authentication.principal.Principal;
import org.apereo.cas.services.MultifactorAuthenticationProvider;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.services.RegisteredServiceMultifactorPolicy;
import org.apereo.cas.util.CollectionUtils;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
/**
* Default MFA Trigger selection strategy. This strategy looks for valid triggers in the following order: request
* parameter, RegisteredService policy, principal attribute.
*
* @author Daniel Frett
* @since 5.0.0
*/
public class DefaultMultifactorTriggerSelectionStrategy implements MultifactorTriggerSelectionStrategy {
private static final Splitter ATTR_NAMES = Splitter.on(',').trimResults().omitEmptyStrings();
private final String requestParameter;
private final String globalPrincipalAttributeNameTriggers;
public DefaultMultifactorTriggerSelectionStrategy(final String attributeNameTriggers, final String requestParameter) {
this.globalPrincipalAttributeNameTriggers = attributeNameTriggers;
this.requestParameter = requestParameter;
}
@Override
public Optional<String> resolve(final Collection<MultifactorAuthenticationProvider> providers,
final HttpServletRequest request, final RegisteredService service, final Principal principal) {
Optional<String> provider = Optional.empty();
// short-circuit if we don't have any available MFA providers
if (providers == null || providers.isEmpty()) {
return provider;
}
final Set<String> validProviderIds = providers.stream()
.map(MultifactorAuthenticationProvider::getId)
.collect(Collectors.toSet());
// check for an opt-in provider id parameter trigger, we only care about the first value
if (!provider.isPresent() && request != null) {
provider = Optional.ofNullable(request.getParameter(requestParameter))
.filter(validProviderIds::contains);
}
// check for a RegisteredService configured trigger
if (!provider.isPresent() && service != null) {
final RegisteredServiceMultifactorPolicy policy = service.getMultifactorPolicy();
if (shouldApplyRegisteredServiceMultifactorPolicy(policy, principal)) {
provider = policy.getMultifactorAuthenticationProviders().stream()
.filter(validProviderIds::contains)
.findFirst();
}
}
// check for principal attribute trigger
if (!provider.isPresent() && principal != null
&& StringUtils.hasText(globalPrincipalAttributeNameTriggers)) {
provider = StreamSupport.stream(ATTR_NAMES.split(globalPrincipalAttributeNameTriggers).spliterator(), false)
// principal.getAttribute(name).values
.map(principal.getAttributes()::get).filter(Objects::nonNull)
.map(CollectionUtils::toCollection).flatMap(Set::stream)
// validProviderIds.contains((String) value)
.filter(String.class::isInstance).map(String.class::cast).filter(validProviderIds::contains)
.findFirst();
}
// return the resolved trigger
return provider;
}
private static boolean shouldApplyRegisteredServiceMultifactorPolicy(final RegisteredServiceMultifactorPolicy policy, final Principal principal) {
final String attrName = policy.getPrincipalAttributeNameTrigger();
final String attrValue = policy.getPrincipalAttributeValueToMatch();
// Principal attribute name and/or value is not defined
if (!StringUtils.hasText(attrName) || !StringUtils.hasText(attrValue)) {
return true;
}
// no Principal, we should enforce policy
if (principal == null) {
return true;
}
// check to see if any of the specified attributes match the attrValue pattern
final Predicate<String> attrValuePredicate = Pattern.compile(attrValue).asPredicate();
return StreamSupport.stream(ATTR_NAMES.split(attrName).spliterator(), false)
.map(principal.getAttributes()::get)
.filter(Objects::nonNull)
.map(CollectionUtils::toCollection)
.flatMap(Set::stream)
.filter(String.class::isInstance)
.map(String.class::cast)
.anyMatch(attrValuePredicate);
}
}
| creamer/cas | core/cas-server-core-services/src/main/java/org/apereo/cas/authentication/DefaultMultifactorTriggerSelectionStrategy.java | Java | apache-2.0 | 4,960 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2017 F5 Networks Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {
'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.0'
}
DOCUMENTATION = '''
module: iworkflow_license_pool
short_description: Manage license pools in iWorkflow.
description:
- Manage license pools in iWorkflow.
version_added: 2.4
options:
name:
description:
- Name of the license pool to create.
required: True
state:
description:
- Whether the license pool should exist, or not. A state of C(present)
will attempt to activate the license pool if C(accept_eula) is set
to C(yes).
required: False
default: present
choices:
- present
- absent
base_key:
description:
- Key that the license server uses to verify the functionality that
you are entitled to license. This option is required if you are
creating a new license.
required: False
default: None
accept_eula:
description:
- Specifies that you accept the EULA that is part of iWorkflow. Note
that this is required to activate the license pool. If this is not
specified, or it is set to C(no), then the pool will remain in a state
of limbo until you choose to accept the EULA. This option is required
when updating a license. It is also suggested that you provide it when
creating a license, but if you do not, the license will remain
inactive and you will have to run this module again with this option
set to C(yes) to activate it.
required: False
default: 'no'
choices:
- yes
- no
notes:
- Requires the f5-sdk Python package on the host. This is as easy as pip
install f5-sdk.
extends_documentation_fragment: f5
requirements:
- f5-sdk >= 2.3.0
- iWorkflow >= 2.1.0
author:
- Tim Rupp (@caphrim007)
'''
EXAMPLES = '''
- name: Create license pool
iworkflow_license_pool:
accept_eula: "yes"
name: "my-lic-pool"
base_key: "XXXXX-XXXXX-XXXXX-XXXXX-XXXXXXX"
state: "present"
server: "iwf.mydomain.com"
password: "secret"
user: "admin"
validate_certs: "no"
delegate_to: localhost
'''
RETURN = '''
'''
import time
from ansible.module_utils.basic import BOOLEANS
from ansible.module_utils.f5_utils import (
AnsibleF5Client,
AnsibleF5Parameters,
F5ModuleError,
HAS_F5SDK,
iControlUnexpectedHTTPError
)
class Parameters(AnsibleF5Parameters):
api_map = {
'baseRegKey': 'base_key'
}
returnables = []
api_attributes = [
'baseRegKey', 'state'
]
updatables = []
def to_return(self):
result = {}
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
return result
def api_params(self):
result = {}
for api_attribute in self.api_attributes:
if self.api_map is not None and api_attribute in self.api_map:
result[api_attribute] = getattr(self, self.api_map[api_attribute])
else:
result[api_attribute] = getattr(self, api_attribute)
result = self._filter_params(result)
return result
@property
def name(self):
if self._values['name'] is None:
return None
name = str(self._values['name']).strip()
if name == '':
raise F5ModuleError(
"You must specify a name for this module"
)
return name
class ModuleManager(object):
def __init__(self, client):
self.client = client
self.have = None
self.want = Parameters(self.client.module.params)
self.changes = Parameters()
def _set_changed_options(self):
changed = {}
for key in Parameters.returnables:
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = Parameters(changed)
def _update_changed_options(self):
changed = {}
for key in Parameters.updatables:
if getattr(self.want, key) is not None:
attr1 = getattr(self.want, key)
attr2 = getattr(self.have, key)
if attr1 != attr2:
changed[key] = attr1
if changed:
self.changes = Parameters(changed)
return True
return False
def _pool_is_licensed(self):
if self.have.state == 'LICENSED':
return True
return False
def _pool_is_unlicensed_eula_unaccepted(self, current):
if current.state != 'LICENSED' and not self.want.accept_eula:
return True
return False
def exec_module(self):
changed = False
result = dict()
state = self.want.state
try:
if state == "present":
changed = self.present()
elif state == "absent":
changed = self.absent()
except iControlUnexpectedHTTPError as e:
raise F5ModuleError(str(e))
result.update(**self.changes.to_return())
result.update(dict(changed=changed))
return result
def exists(self):
collection = self.client.api.cm.shared.licensing.pools_s.get_collection(
requests_params=dict(
params="$filter=name+eq+'{0}'".format(self.want.name)
)
)
if len(collection) == 1:
return True
elif len(collection) == 0:
return False
else:
raise F5ModuleError(
"Multiple license pools with the provided name were found!"
)
def present(self):
if self.exists():
return self.update()
else:
return self.create()
def should_update(self):
if self._pool_is_licensed():
return False
if self._pool_is_unlicensed_eula_unaccepted():
return False
return True
def update(self):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.module.check_mode:
return True
self.update_on_device()
return True
def update_on_device(self):
collection = self.client.api.cm.shared.licensing.pools_s.get_collection(
requests_params=dict(
params="$filter=name+eq+'{0}'".format(self.want.name)
)
)
resource = collection.pop()
resource.modify(
state='RELICENSE',
method='AUTOMATIC'
)
return self._wait_for_license_pool_state_to_activate(resource)
def create(self):
self._set_changed_options()
if self.client.check_mode:
return True
if self.want.base_key is None:
raise F5ModuleError(
"You must specify a 'base_key' when creating a license pool"
)
self.create_on_device()
return True
def read_current_from_device(self):
collection = self.client.api.cm.shared.licensing.pools_s.get_collection(
requests_params=dict(
params="$filter=name+eq+'{0}'".format(self.want.name)
)
)
resource = collection.pop()
result = resource.attrs
return Parameters(result)
def create_on_device(self):
resource = self.client.api.cm.shared.licensing.pools_s.pool.create(
name=self.want.name,
baseRegKey=self.want.base_key,
method="AUTOMATIC"
)
return self._wait_for_license_pool_state_to_activate(resource)
def _wait_for_license_pool_state_to_activate(self, pool):
error_values = ['EXPIRED', 'FAILED']
# Wait no more than 5 minutes
for x in range(1, 30):
pool.refresh()
if pool.state == 'LICENSED':
return True
elif pool.state == 'WAITING_FOR_EULA_ACCEPTANCE':
pool.modify(
eulaText=pool.eulaText,
state='ACCEPTED_EULA'
)
elif pool.state in error_values:
raise F5ModuleError(pool.errorText)
time.sleep(10)
def absent(self):
if self.exists():
return self.remove()
return False
def remove(self):
if self.client.check_mode:
return True
self.remove_from_device()
if self.exists():
raise F5ModuleError("Failed to delete the license pool")
return True
def remove_from_device(self):
collection = self.client.api.cm.shared.licensing.pools_s.get_collection(
requests_params=dict(
params="$filter=name+eq+'{0}'".format(self.want.name)
)
)
resource = collection.pop()
if resource:
resource.delete()
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
self.argument_spec = dict(
accept_eula=dict(
type='bool',
default='no',
choices=BOOLEANS
),
base_key=dict(
required=False,
no_log=True
),
name=dict(
required=True
),
state=dict(
required=False,
default='present',
choices=['absent', 'present']
)
)
self.f5_product_name = 'iworkflow'
def main():
if not HAS_F5SDK:
raise F5ModuleError("The python f5-sdk module is required")
spec = ArgumentSpec()
client = AnsibleF5Client(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
f5_product_name=spec.f5_product_name
)
try:
mm = ModuleManager(client)
results = mm.exec_module()
client.module.exit_json(**results)
except F5ModuleError as e:
client.module.fail_json(msg=str(e))
if __name__ == '__main__':
main()
| mcgonagle/ansible_f5 | library_old/iworkflow_license_pool.py | Python | apache-2.0 | 10,879 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jmeter.gui;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.MenuElement;
import org.apache.jmeter.exceptions.IllegalUserActionException;
import org.apache.jmeter.gui.action.AbstractAction;
import org.apache.jmeter.gui.action.ActionNames;
import org.apache.jmeter.gui.action.ActionRouter;
import org.apache.jmeter.gui.plugin.MenuCreator;
import org.apache.jmeter.util.JMeterUtils;
public class HtmlReportAction extends AbstractAction implements MenuCreator {
private static Set<String> commands = new HashSet<>();
private HtmlReportUI htmlReportPanel;
static {
commands.add(ActionNames.HTML_REPORT);
}
public HtmlReportAction() {
super();
}
@Override
public void doAction(ActionEvent e) throws IllegalUserActionException {
htmlReportPanel = new HtmlReportUI();
htmlReportPanel.showInputDialog(getParentFrame(e));
}
@Override
public Set<String> getActionNames() {
return commands;
}
@Override
public JMenuItem[] getMenuItemsAtLocation(MENU_LOCATION location) {
if (location != MENU_LOCATION.TOOLS) {
return new JMenuItem[0];
}
// Use the action name as resource key because the action name is used by JMeterMenuBar too when changing languages.
JMenuItem menuItem = new JMenuItem(JMeterUtils.getResString(ActionNames.HTML_REPORT), KeyEvent.VK_UNDEFINED);
menuItem.setName(ActionNames.HTML_REPORT);
menuItem.setActionCommand(ActionNames.HTML_REPORT);
menuItem.setAccelerator(null);
menuItem.addActionListener(ActionRouter.getInstance());
return new JMenuItem[] { menuItem };
}
@Override
public JMenu[] getTopLevelMenus() {
return new JMenu[0];
}
@Override
public boolean localeChanged(MenuElement menu) {
return false;
}
@Override
public void localeChanged() {
// NOOP
}
public HtmlReportUI getHtmlReportPanel() {
return htmlReportPanel;
}
}
| apache/jmeter | src/core/src/main/java/org/apache/jmeter/gui/HtmlReportAction.java | Java | apache-2.0 | 2,972 |
{% extends 'base.html' %}
{% block main %}
{% include "project/databases/_create_database.html" %}
{% endblock %}
| openstack/trove-dashboard | trove_dashboard/content/databases/templates/databases/create_database.html | HTML | apache-2.0 | 118 |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.model.bpmn.impl.instance.camunda;
import static org.camunda.bpm.model.bpmn.impl.BpmnModelConstants.CAMUNDA_ELEMENT_CONNECTOR;
import static org.camunda.bpm.model.bpmn.impl.BpmnModelConstants.CAMUNDA_NS;
import org.camunda.bpm.model.bpmn.impl.instance.BpmnModelElementInstanceImpl;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaConnector;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaConnectorId;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaInputOutput;
import org.camunda.bpm.model.xml.ModelBuilder;
import org.camunda.bpm.model.xml.impl.instance.ModelTypeInstanceContext;
import org.camunda.bpm.model.xml.type.ModelElementTypeBuilder;
import org.camunda.bpm.model.xml.type.ModelElementTypeBuilder.ModelTypeInstanceProvider;
import org.camunda.bpm.model.xml.type.child.ChildElement;
import org.camunda.bpm.model.xml.type.child.SequenceBuilder;
/**
* The BPMN connector camunda extension element
*
* @author Sebastian Menski
*/
public class CamundaConnectorImpl extends BpmnModelElementInstanceImpl implements CamundaConnector {
protected static ChildElement<CamundaConnectorId> camundaConnectorIdChild;
protected static ChildElement<CamundaInputOutput> camundaInputOutputChild;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CamundaConnector.class, CAMUNDA_ELEMENT_CONNECTOR)
.namespaceUri(CAMUNDA_NS)
.instanceProvider(new ModelTypeInstanceProvider<CamundaConnector>() {
public CamundaConnector newInstance(ModelTypeInstanceContext instanceContext) {
return new CamundaConnectorImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
camundaConnectorIdChild = sequenceBuilder.element(CamundaConnectorId.class)
.required()
.build();
camundaInputOutputChild = sequenceBuilder.element(CamundaInputOutput.class)
.build();
typeBuilder.build();
}
public CamundaConnectorImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public CamundaConnectorId getCamundaConnectorId() {
return camundaConnectorIdChild.getChild(this);
}
public void setCamundaConnectorId(CamundaConnectorId camundaConnectorId) {
camundaConnectorIdChild.setChild(this, camundaConnectorId);
}
public CamundaInputOutput getCamundaInputOutput() {
return camundaInputOutputChild.getChild(this);
}
public void setCamundaInputOutput(CamundaInputOutput camundaInputOutput) {
camundaInputOutputChild.setChild(this, camundaInputOutput);
}
}
| camunda/camunda-bpmn-model | src/main/java/org/camunda/bpm/model/bpmn/impl/instance/camunda/CamundaConnectorImpl.java | Java | apache-2.0 | 3,445 |
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::old_io::{Command, IoError, OtherIoError};
use target::TargetOptions;
use self::Arch::*;
#[allow(non_camel_case_types)]
#[derive(Copy)]
pub enum Arch {
Armv7,
Armv7s,
Arm64,
I386,
X86_64
}
impl Arch {
pub fn to_string(&self) -> &'static str {
match self {
&Armv7 => "armv7",
&Armv7s => "armv7s",
&Arm64 => "arm64",
&I386 => "i386",
&X86_64 => "x86_64"
}
}
}
pub fn get_sdk_root(sdk_name: &str) -> String {
let res = Command::new("xcrun")
.arg("--show-sdk-path")
.arg("-sdk")
.arg(sdk_name)
.spawn()
.and_then(|c| c.wait_with_output())
.and_then(|output| {
if output.status.success() {
Ok(String::from_utf8(output.output).unwrap())
} else {
Err(IoError {
kind: OtherIoError,
desc: "process exit with error",
detail: String::from_utf8(output.error).ok()})
}
});
match res {
Ok(output) => output.trim().to_string(),
Err(e) => panic!("failed to get {} SDK path: {}", sdk_name, e)
}
}
fn pre_link_args(arch: Arch) -> Vec<String> {
let sdk_name = match arch {
Armv7 | Armv7s | Arm64 => "iphoneos",
I386 | X86_64 => "iphonesimulator"
};
let arch_name = arch.to_string();
vec!["-arch".to_string(), arch_name.to_string(),
"-Wl,-syslibroot".to_string(), get_sdk_root(sdk_name)]
}
fn target_cpu(arch: Arch) -> String {
match arch {
Armv7 => "cortex-a8", // iOS7 is supported on iPhone 4 and higher
Armv7s => "cortex-a9",
Arm64 => "cyclone",
I386 => "generic",
X86_64 => "x86-64",
}.to_string()
}
pub fn opts(arch: Arch) -> TargetOptions {
TargetOptions {
cpu: target_cpu(arch),
dynamic_linking: false,
executables: true,
// Although there is an experimental implementation of LLVM which
// supports SS on armv7 it wasn't approved by Apple, see:
// http://lists.cs.uiuc.edu/pipermail/llvm-commits/Week-of-Mon-20140505/216350.html
// It looks like it might be never accepted to upstream LLVM.
//
// SS might be also enabled on Arm64 as it has builtin support in LLVM
// but I haven't tested it through yet
morestack: false,
pre_link_args: pre_link_args(arch),
.. super::apple_base::opts()
}
}
| richo/rust | src/librustc_back/target/apple_ios_base.rs | Rust | apache-2.0 | 3,192 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.edu.learning.stepic;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupActivity;
import com.jetbrains.edu.learning.courseGeneration.StudyProjectGenerator;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class StudyCoursesUpdater implements StartupActivity {
public static StudyCoursesUpdater getInstance() {
final StartupActivity[] extensions = Extensions.getExtensions(StartupActivity.POST_STARTUP_ACTIVITY);
for (StartupActivity extension : extensions) {
if (extension instanceof StudyCoursesUpdater) {
return (StudyCoursesUpdater) extension;
}
}
throw new UnsupportedOperationException("could not find self");
}
@Override
public void runActivity(@NotNull final Project project) {
final Application application = ApplicationManager.getApplication();
if (application.isUnitTestMode()) {
return;
}
if (checkNeeded()) {
application.executeOnPooledThread(new Runnable() {
@Override
public void run() {
final List<CourseInfo> courses = EduStepicConnector.getCourses();
StudyProjectGenerator.flushCache(courses);
}
});
}
}
public static boolean checkNeeded() {
final List<CourseInfo> courses = StudyProjectGenerator.getCoursesFromCache();
return courses.isEmpty();
}
}
| Soya93/Extract-Refactoring | python/educational-core/student/src/com/jetbrains/edu/learning/stepic/StudyCoursesUpdater.java | Java | apache-2.0 | 2,161 |
{{{
"title": "Getting Started with GitLab - Blueprint",
"date": "05-14-2015",
"author": "<a href='https://twitter.com/KeithResar'>@KeithResar</a>",
"attachments": [],
"contentIsHTML": false
}}}
### Description
<img alt="GitLab Logo" src="/knowledge-base/images/bitnami_logos/gitlab-stack-110x117-6ab77fbd4c6d3b0453a520ece95300ca.png" style="border:0;float:right;max-width:250px">
After reading this article, the reader should feel comfortable deploying the GitLab stack (version 7.10.1-0) by Bitnami.
<a href="https://bitnami.com/" rel="no-follow">Bitnami</a> has integrated their <a href="https://bitnami.com/stack/gitlab" rel="no-follow">GitLab stack</a> with the CenturyLink Cloud platform with a single-click deploy solution. The purpose of this KB article is to help the reader take advantage of this integration to achieve rapid time-to-value for this GitLab solution.
The GitLab open source edition is a developer tool that allows users to collaborate on code, create new projects, manage repositories, and perform code reviews. When using GitLab, users can keep their code on their own servers, either in the cloud or on-premise. For additional peace of mind, the free community edition even features enterprise-grade features such as a mature user permissions scheme and support for high availability. This GitLab stack is bundled with GitLab CI, a continuous integration server. Just point your projects at the CI server and automate all your tests.
### Audience
CenturyLink Cloud Users
### Deploying GitLab on a New Server
GitLab is available as a Blueprint for deployment on a **new server**.
#### Steps
1. **Locate the Blueprint in the Blueprint Library**
Starting from the CenturyLink Control Panel, navigate to the Blueprints Library. Search for **GitLab on Linux** in the keyword search on the right side of the page.
2. **Click the Deploy Blueprint button.**
3. **Set Required parameters.**
Set the following parameters in addition to those associated with your server itself (password, network, group, etc.):
* **Apache server SSL port** - default 443
* **Redis port** - Redis Server port default 6379
* **Apache server port** - default 80
* **Service Password** - Provide service password 6 chars or more
* **User's name** - Users Name
5. **Review and Confirm the Blueprint**
6. **Deploy the Blueprint**
Once verified, click on the `deploy blueprint` button. You will see the deployment details stating the Blueprint is queued for execution.
This will kick off the Blueprint deploy process and load a page where you can track the deployment progress. Deployment will typically complete within five minutes.
7. **Deployment Complete**
Once the Blueprint has finished executing on your server you may access GitLab by navigating to your server via http.
8. **Enable public access** (optional)
Servers are built using private IPs only with access with client or IPSEC VPN. For inbound access from the Internet add a public IP to your master server.
<a href="../../Network/how-to-add-public-ip-to-virtual-machine.md">
<img style="border:0;width:50px;vertical-align:middle;" src="../../images/shared_assets/fw_icon.png">
Adding a public IP to your virtual machine
</a>
### Deploying GitLab on an existing server (alternate option)
GitLab is available as a Blueprint Package for deployment on an existing server based on your own sizing requirements or to support more advanced configurations such as customized Blueprint Workflows to repeatably deploy multiple stacks on the same machines
#### Steps
1. **Deploy or Identify an Existing Server**
Identify the server targeted for GitLab installation. Operating sustem must be linux.
See the [Creating a new enterprise cloud server](../../Servers/creating-a-new-enterprise-cloud-server.md) KB for more information on completing this step.
2. **Select to Execute the Package on a Server Group**
Packages can be executed on one more more servers in a group. Search for the public script package named **Install GitLab on Linux**.
See the [using group tasks to install scripts on groups](../../Servers/using-group-tasks-to-install-software-and-run-scripts-on-groups.md) KB for more information on how to complete the next few steps.
3. **Set Parameters**
Set the following parameters:
* **Apache server SSL port** - default 443
* **Redis port** - Redis Server port default 6379
* **Apache server port** - default 80
* **Service Password** - Provide service password 6 chars or more
* **User's name** - Users Name
4. **Deploy the Blueprint**
Once verified, click on the `execute package` button. You will see the deployment details stating the Blueprint is queued for execution.
This will kick off the Blueprint deploy process and load a page where you can track the deployment progress. Deployment will typically complete within five minutes.
5. **Deployment Complete**
Once the Blueprint has finished executing on your server you may access GitLab by navigating to your server via http.
6. **Enable public access** (optional)
Servers are built using private IPs only with access with client or IPSEC VPN. For inbound access from the Internet add a public IP to your master server.
<a href="../../Network/how-to-add-public-ip-to-virtual-machine.md">
<img style="border:0;width:50px;vertical-align:middle;" src="../../images/shared_assets/fw_icon.png">
Adding a public IP to your virtual machine
</a>
### Pricing
The costs listed above in the above steps are for the infrastructure only.
### About Bitnami
CenturyLink Cloud works with [Bitnami](http://www.bitnami.com) to provide open source software integrations to its customers. Bitnami is a library of popular server applications and development environments that can be installed with one click, either in your laptop, in a virtual machine or hosted in the cloud. Bitnami takes care of compiling and configuring the applications and all of their dependencies (third-party libraries, language runtimes, databases) so they work out-of-the-box. The resulting packaged software (a 'stack') is then made available as native installers, virtual machines and cloud images. These Bitnami application packages provide a consistent, secure and optimized end-user experience when deploying any app, on any platform.
### Frequently Asked Questions
**Who should I contact for support?**
* For issues related to cloud infrastructure, please open a ticket using the [CenturyLink Cloud Support Process](../../Support/how-do-i-report-a-support-issue.md).
* For issues related to deploying the Bitnami Blueprint on CenturyLink Cloud, Licensing or Accessing the deployed software, please visit the [Bitnami Support website](http://www.bitnami.com/support)
**How do I access GitLab for the first time?**
Nearly all Bitnami stacks can be accessed and configured by navigating to your server with a web browser.
| kjmd75/PublicKB | Ecosystem Partners/Marketplace Guides/getting-started-with-gitlab-blueprint.md | Markdown | apache-2.0 | 6,972 |
///<reference path="app.js" />
define(['Dexie', 'Dexie.Observable', './console'], function (Dexie, DexieObservable, console) {
// Declare Dexie instance and explicitely apply the addon:
var db = new Dexie("appdb2", { addons: [DexieObservable] });
// Define database schema
db.version(1).stores({
contacts: '++id,first,last'
});
// Populate ground data
db.on('populate', function () {
console.log("Populating data first time");
// Populate a contact
db.contacts.add({ first: 'Arnold', last: 'Fitzgerald' });
});
// Open database
db.open();
return db;
});
| YuriSolovyov/Dexie.js | samples/requirejs-with-addons/scripts/db.js | JavaScript | apache-2.0 | 643 |
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.test.api.runtime.util;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.ExecutionListener;
/**
* @author: Johannes Heinemann
*/
public class IncrementCounterListener implements ExecutionListener {
public static int counter = 0;
@Override
public void notify(DelegateExecution execution) throws Exception {
counter++;
}
}
| AlexMinsk/camunda-bpm-platform | engine/src/test/java/org/camunda/bpm/engine/test/api/runtime/util/IncrementCounterListener.java | Java | apache-2.0 | 977 |
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
enum Test {
DivZero = 1/0,
//~^ attempt to divide by zero
//~| ERROR evaluation of constant value failed
RemZero = 1%0,
//~^ attempt to calculate the remainder with a divisor of zero
//~| ERROR evaluation of constant value failed
}
fn main() {}
| GBGamer/rust | src/test/ui/eval-enum.rs | Rust | apache-2.0 | 737 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.deltaspike.test.api.config;
import org.apache.deltaspike.core.api.config.ConfigResolver;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
public class ConfigResolverTest
{
@Test
public void testOverruledValue()
{
String result = ConfigResolver.getPropertyValue("test");
Assert.assertEquals("test2", result);
}
@Test
public void testOrderOfAllValues()
{
List<String> result = ConfigResolver.getAllPropertyValues("test");
Assert.assertEquals(2, result.size());
Assert.assertEquals("test1", result.get(0));
Assert.assertEquals("test2", result.get(1));
}
}
| sbryzak/DeltaSpike | deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java | Java | apache-2.0 | 1,482 |
package foo;
public class ControllerB2 extends grails.TopB {
public void foo() {
super.foo();
System.out.println("ControllerB.foo() running again!");
}
}
| spring-projects/spring-loaded | testdata/src/main/java/foo/ControllerB2.java | Java | apache-2.0 | 162 |
#ifndef MANDIR
#define MANDIR "/usr/local/man"
#endif
| LiberatorUSA/GUCEF | dependencies/agar/tests/config/mandir.h | C | apache-2.0 | 54 |
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/rtp_rtcp/source/rtp_format_h264.h"
namespace webrtc {
void FuzzOneInput(const uint8_t* data, size_t size) {
RtpDepacketizerH264 depacketizer;
RtpDepacketizer::ParsedPayload parsed_payload;
depacketizer.Parse(&parsed_payload, data, size);
}
} // namespace webrtc
| wangcy6/storm_app | frame/c++/webrtc-master/test/fuzzers/h264_depacketizer_fuzzer.cc | C++ | apache-2.0 | 701 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>selenium.webdriver.remote.webelement — Selenium 2.0 documentation</title>
<link rel="stylesheet" href="../_static/default.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '2.0',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<link rel="top" title="Selenium 2.0 documentation" href="../index.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li><a href="../index.html">Selenium 2.0 documentation</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="module-selenium.webdriver.remote.webelement">
<span id="selenium-webdriver-remote-webelement"></span><h1>selenium.webdriver.remote.webelement<a class="headerlink" href="#module-selenium.webdriver.remote.webelement" title="Permalink to this headline">¶</a></h1>
<dl class="class">
<dt id="selenium.webdriver.remote.webelement.WebElement">
<em class="property">class </em><tt class="descclassname">selenium.webdriver.remote.webelement.</tt><tt class="descname">WebElement</tt><big>(</big><em>parent</em>, <em>id_</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents a DOM element.</p>
<p>Generally, all interesting operations that interact with a document will be
performed through this interface.</p>
<p>All method calls will do a freshness check to ensure that the element
reference is still valid. This essentially determines whether or not the
element is still attached to the DOM. If this test fails, then an
<tt class="docutils literal"><span class="pre">StaleElementReferenceException</span></tt> is thrown, and all future calls to this
instance will fail.</p>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.clear">
<tt class="descname">clear</tt><big>(</big><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.clear"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Clears the text if it’s a text entry element.</p>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.click">
<tt class="descname">click</tt><big>(</big><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.click"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.click" title="Permalink to this definition">¶</a></dt>
<dd><p>Clicks the element.</p>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_element">
<tt class="descname">find_element</tt><big>(</big><em>by='id'</em>, <em>value=None</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_element"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_element" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_element_by_class_name">
<tt class="descname">find_element_by_class_name</tt><big>(</big><em>name</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_element_by_class_name"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_element_by_class_name" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds element within this element’s children by class name.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple">
<li>name - class name to search for.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_element_by_css_selector">
<tt class="descname">find_element_by_css_selector</tt><big>(</big><em>css_selector</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_element_by_css_selector"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_element_by_css_selector" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds element within this element’s children by CSS selector.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple">
<li>css_selector - CSS selctor string, ex: ‘a.nav#home’</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_element_by_id">
<tt class="descname">find_element_by_id</tt><big>(</big><em>id_</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_element_by_id"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_element_by_id" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds element within this element’s children by ID.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple">
<li><a href="#id1"><span class="problematic" id="id2">id_</span></a> - ID of child element to locate.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_element_by_link_text">
<tt class="descname">find_element_by_link_text</tt><big>(</big><em>link_text</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_element_by_link_text"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_element_by_link_text" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds element within this element’s children by visible link text.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple">
<li>link_text - Link text string to search for.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_element_by_name">
<tt class="descname">find_element_by_name</tt><big>(</big><em>name</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_element_by_name"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_element_by_name" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds element within this element’s children by name.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple">
<li>name - name property of the element to find.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_element_by_partial_link_text">
<tt class="descname">find_element_by_partial_link_text</tt><big>(</big><em>link_text</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_element_by_partial_link_text"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_element_by_partial_link_text" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds element within this element’s children by partially visible link text.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple">
<li>link_text - Link text string to search for.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_element_by_tag_name">
<tt class="descname">find_element_by_tag_name</tt><big>(</big><em>name</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_element_by_tag_name"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_element_by_tag_name" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds element within this element’s children by tag name.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple">
<li>name - name of html tag (eg: h1, a, span)</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_element_by_xpath">
<tt class="descname">find_element_by_xpath</tt><big>(</big><em>xpath</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_element_by_xpath"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_element_by_xpath" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds element by xpath.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body">xpath - xpath of element to locate. “//input[@class=’myelement’]”</td>
</tr>
</tbody>
</table>
<p>Note: The base path will be relative to this element’s location.</p>
<p>This will select the first link under this element.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">myelement</span><span class="o">.</span><span class="n">find_elements_by_xpath</span><span class="p">(</span><span class="s">".//a"</span><span class="p">)</span>
</pre></div>
</div>
<p>However, this will select the first link on the page.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">myelement</span><span class="o">.</span><span class="n">find_elements_by_xpath</span><span class="p">(</span><span class="s">"//a"</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_elements">
<tt class="descname">find_elements</tt><big>(</big><em>by='id'</em>, <em>value=None</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_elements"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_elements" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_elements_by_class_name">
<tt class="descname">find_elements_by_class_name</tt><big>(</big><em>name</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_elements_by_class_name"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_elements_by_class_name" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds a list of elements within this element’s children by class name.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple">
<li>name - class name to search for.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_elements_by_css_selector">
<tt class="descname">find_elements_by_css_selector</tt><big>(</big><em>css_selector</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_elements_by_css_selector"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_elements_by_css_selector" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds a list of elements within this element’s children by CSS selector.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple">
<li>css_selector - CSS selctor string, ex: ‘a.nav#home’</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_elements_by_id">
<tt class="descname">find_elements_by_id</tt><big>(</big><em>id_</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_elements_by_id"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_elements_by_id" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds a list of elements within this element’s children by ID.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple">
<li><a href="#id3"><span class="problematic" id="id4">id_</span></a> - Id of child element to find.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_elements_by_link_text">
<tt class="descname">find_elements_by_link_text</tt><big>(</big><em>link_text</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_elements_by_link_text"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_elements_by_link_text" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds a list of elements within this element’s children by visible link text.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple">
<li>link_text - Link text string to search for.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_elements_by_name">
<tt class="descname">find_elements_by_name</tt><big>(</big><em>name</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_elements_by_name"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_elements_by_name" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds a list of elements within this element’s children by name.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple">
<li>name - name property to search for.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_elements_by_partial_link_text">
<tt class="descname">find_elements_by_partial_link_text</tt><big>(</big><em>link_text</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_elements_by_partial_link_text"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_elements_by_partial_link_text" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds a list of elements within this element’s children by link text.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple">
<li>link_text - Link text string to search for.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_elements_by_tag_name">
<tt class="descname">find_elements_by_tag_name</tt><big>(</big><em>name</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_elements_by_tag_name"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_elements_by_tag_name" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds a list of elements within this element’s children by tag name.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple">
<li>name - name of html tag (eg: h1, a, span)</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.find_elements_by_xpath">
<tt class="descname">find_elements_by_xpath</tt><big>(</big><em>xpath</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.find_elements_by_xpath"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.find_elements_by_xpath" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds elements within the element by xpath.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple">
<li>xpath - xpath locator string.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Note: The base path will be relative to this element’s location.</p>
<p>This will select all links under this element.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">myelement</span><span class="o">.</span><span class="n">find_elements_by_xpath</span><span class="p">(</span><span class="s">".//a"</span><span class="p">)</span>
</pre></div>
</div>
<p>However, this will select all links in the page itself.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">myelement</span><span class="o">.</span><span class="n">find_elements_by_xpath</span><span class="p">(</span><span class="s">"//a"</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.get_attribute">
<tt class="descname">get_attribute</tt><big>(</big><em>name</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.get_attribute"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.get_attribute" title="Permalink to this definition">¶</a></dt>
<dd><p>Gets the given attribute or property of the element.</p>
<p>This method will first try to return the value of a property with the
given name. If a property with that name doesn’t exist, it returns the
value of the attribute with the same name. If there’s no attribute with
that name, <tt class="docutils literal"><span class="pre">None</span></tt> is returned.</p>
<p>Values which are considered truthy, that is equals “true” or “false”,
are returned as booleans. All other non-<tt class="docutils literal"><span class="pre">None</span></tt> values are returned
as strings. For attributes or properties which do not exist, <tt class="docutils literal"><span class="pre">None</span></tt>
is returned.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple">
<li>name - Name of the attribute/property to retrieve.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Check if the "active" CSS class is applied to an element.</span>
<span class="n">is_active</span> <span class="o">=</span> <span class="s">"active"</span> <span class="ow">in</span> <span class="n">target_element</span><span class="o">.</span><span class="n">get_attribute</span><span class="p">(</span><span class="s">"class"</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>
<dl class="attribute">
<dt id="selenium.webdriver.remote.webelement.WebElement.id">
<tt class="descname">id</tt><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.id"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.id" title="Permalink to this definition">¶</a></dt>
<dd><p>Internal ID used by selenium.</p>
<p>This is mainly for internal use. Simple use cases such as checking if 2
webelements refer to the same element, can be done using <tt class="docutils literal"><span class="pre">==</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">if</span> <span class="n">element1</span> <span class="o">==</span> <span class="n">element2</span><span class="p">:</span>
<span class="k">print</span><span class="p">(</span><span class="s">"These 2 are equal"</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.is_displayed">
<tt class="descname">is_displayed</tt><big>(</big><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.is_displayed"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.is_displayed" title="Permalink to this definition">¶</a></dt>
<dd><p>Whether the element is visible to a user.</p>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.is_enabled">
<tt class="descname">is_enabled</tt><big>(</big><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.is_enabled"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.is_enabled" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns whether the element is enabled.</p>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.is_selected">
<tt class="descname">is_selected</tt><big>(</big><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.is_selected"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.is_selected" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns whether the element is selected.</p>
<p>Can be used to check if a checkbox or radio button is selected.</p>
</dd></dl>
<dl class="attribute">
<dt id="selenium.webdriver.remote.webelement.WebElement.location">
<tt class="descname">location</tt><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.location"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.location" title="Permalink to this definition">¶</a></dt>
<dd><p>The location of the element in the renderable canvas.</p>
</dd></dl>
<dl class="attribute">
<dt id="selenium.webdriver.remote.webelement.WebElement.location_once_scrolled_into_view">
<tt class="descname">location_once_scrolled_into_view</tt><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.location_once_scrolled_into_view"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.location_once_scrolled_into_view" title="Permalink to this definition">¶</a></dt>
<dd><p>THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover
where on the screen an element is so that we can click it. This method
should cause the element to be scrolled into view.</p>
<p>Returns the top lefthand corner location on the screen, or <tt class="docutils literal"><span class="pre">None</span></tt> if
the element is not visible.</p>
</dd></dl>
<dl class="attribute">
<dt id="selenium.webdriver.remote.webelement.WebElement.parent">
<tt class="descname">parent</tt><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.parent"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.parent" title="Permalink to this definition">¶</a></dt>
<dd><p>Internal reference to the WebDriver instance this element was found from.</p>
</dd></dl>
<dl class="attribute">
<dt id="selenium.webdriver.remote.webelement.WebElement.rect">
<tt class="descname">rect</tt><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.rect"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.rect" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary with the size and location of the element.</p>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.send_keys">
<tt class="descname">send_keys</tt><big>(</big><em>*value</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.send_keys"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.send_keys" title="Permalink to this definition">¶</a></dt>
<dd><p>Simulates typing into the element.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first simple">
<li>value - A string for typing, or setting form fields. For setting</li>
</ul>
<p class="last">file inputs, this could be a local file path.</p>
</td>
</tr>
</tbody>
</table>
<p>Use this to send simple key events or to fill out form fields:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">form_textfield</span> <span class="o">=</span> <span class="n">driver</span><span class="o">.</span><span class="n">find_element_by_name</span><span class="p">(</span><span class="s">'username'</span><span class="p">)</span>
<span class="n">form_textfield</span><span class="o">.</span><span class="n">send_keys</span><span class="p">(</span><span class="s">"admin"</span><span class="p">)</span>
</pre></div>
</div>
<p>This can also be used to set file inputs.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">file_input</span> <span class="o">=</span> <span class="n">driver</span><span class="o">.</span><span class="n">find_element_by_name</span><span class="p">(</span><span class="s">'profilePic'</span><span class="p">)</span>
<span class="n">file_input</span><span class="o">.</span><span class="n">send_keys</span><span class="p">(</span><span class="s">"path/to/profilepic.gif"</span><span class="p">)</span>
<span class="c"># Generally it's better to wrap the file path in one of the methods</span>
<span class="c"># in os.path to return the actual path to support cross OS testing.</span>
<span class="c"># file_input.send_keys(os.path.abspath("path/to/profilepic.gif"))</span>
</pre></div>
</div>
</dd></dl>
<dl class="attribute">
<dt id="selenium.webdriver.remote.webelement.WebElement.size">
<tt class="descname">size</tt><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.size"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.size" title="Permalink to this definition">¶</a></dt>
<dd><p>The size of the element.</p>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.submit">
<tt class="descname">submit</tt><big>(</big><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.submit"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.submit" title="Permalink to this definition">¶</a></dt>
<dd><p>Submits a form.</p>
</dd></dl>
<dl class="attribute">
<dt id="selenium.webdriver.remote.webelement.WebElement.tag_name">
<tt class="descname">tag_name</tt><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.tag_name"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.tag_name" title="Permalink to this definition">¶</a></dt>
<dd><p>This element’s <tt class="docutils literal"><span class="pre">tagName</span></tt> property.</p>
</dd></dl>
<dl class="attribute">
<dt id="selenium.webdriver.remote.webelement.WebElement.text">
<tt class="descname">text</tt><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.text"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.text" title="Permalink to this definition">¶</a></dt>
<dd><p>The text of the element.</p>
</dd></dl>
<dl class="method">
<dt id="selenium.webdriver.remote.webelement.WebElement.value_of_css_property">
<tt class="descname">value_of_css_property</tt><big>(</big><em>property_name</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html#WebElement.value_of_css_property"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#selenium.webdriver.remote.webelement.WebElement.value_of_css_property" title="Permalink to this definition">¶</a></dt>
<dd><p>The value of a CSS property.</p>
</dd></dl>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/webdriver_remote/selenium.webdriver.remote.webelement.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="../search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li><a href="../index.html">Selenium 2.0 documentation</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2011, plightbo, simon.m.stewart, hbchai, jrhuggins, et al..
</div>
</body>
</html> | sebady/selenium | docs/api/py/webdriver_remote/selenium.webdriver.remote.webelement.html | HTML | apache-2.0 | 35,257 |
<!DOCTYPE html>
<html>
<head>
<script>
function loadHandler() {
if (opener) {
// opener.console.log("oauth callback href:", location.href);
if (location.hash) {
opener.require("esri/kernel").id.setOAuthResponseHash(location.hash);
close();
}
} else {
close();
}
}
</script>
</head>
<body onload="loadHandler();">
</body>
</html> | nheminger/ago-assistant | src/oauth-callback.html | HTML | apache-2.0 | 516 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 io.undertow.conduits;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.TimeUnit;
import io.undertow.UndertowLogger;
import io.undertow.UndertowMessages;
import io.undertow.UndertowOptions;
import io.undertow.server.OpenListener;
import io.undertow.util.WorkerUtils;
import org.xnio.ChannelListener;
import org.xnio.ChannelListeners;
import org.xnio.IoUtils;
import org.xnio.Options;
import org.xnio.StreamConnection;
import org.xnio.XnioExecutor;
import org.xnio.channels.ReadTimeoutException;
import org.xnio.channels.StreamSinkChannel;
import org.xnio.conduits.AbstractStreamSourceConduit;
import org.xnio.conduits.ConduitStreamSourceChannel;
import org.xnio.conduits.ReadReadyHandler;
import org.xnio.conduits.StreamSourceConduit;
/**
* Wrapper for read timeout. This should always be the first wrapper applied to the underlying channel.
*
* @author Stuart Douglas
* @see org.xnio.Options#READ_TIMEOUT
*/
public final class ReadTimeoutStreamSourceConduit extends AbstractStreamSourceConduit<StreamSourceConduit> {
private XnioExecutor.Key handle;
private final StreamConnection connection;
private volatile long expireTime = -1;
private final OpenListener openListener;
private static final int FUZZ_FACTOR = 50; //we add 50ms to the timeout to make sure the underlying channel has actually timed out
private volatile boolean expired;
private final Runnable timeoutCommand = new Runnable() {
@Override
public void run() {
handle = null;
if (expireTime == -1) {
return;
}
long current = System.currentTimeMillis();
if (current < expireTime) {
//timeout has been bumped, re-schedule
handle = WorkerUtils.executeAfter(connection.getIoThread(),timeoutCommand, (expireTime - current) + FUZZ_FACTOR, TimeUnit.MILLISECONDS);
return;
}
UndertowLogger.REQUEST_LOGGER.tracef("Timing out channel %s due to inactivity", connection.getSourceChannel());
synchronized (ReadTimeoutStreamSourceConduit.this) {
expired = true;
}
boolean readResumed = connection.getSourceChannel().isReadResumed();
ChannelListener<? super ConduitStreamSourceChannel> readListener = connection.getSourceChannel().getReadListener();
if (readResumed) {
ChannelListeners.invokeChannelListener(connection.getSourceChannel(), readListener);
}
if (connection.getSinkChannel().isWriteResumed()) {
ChannelListeners.invokeChannelListener(connection.getSinkChannel(), connection.getSinkChannel().getWriteListener());
}
// close only after invoking listeners, to allow space for listener getting ReadTimeoutException
IoUtils.safeClose(connection);
}
};
public ReadTimeoutStreamSourceConduit(final StreamSourceConduit delegate, StreamConnection connection, OpenListener openListener) {
super(delegate);
this.connection = connection;
this.openListener = openListener;
final ReadReadyHandler handler = new ReadReadyHandler.ChannelListenerHandler<>(connection.getSourceChannel());
delegate.setReadReadyHandler(new ReadReadyHandler() {
@Override
public void readReady() {
handler.readReady();
}
@Override
public void forceTermination() {
cleanup();
handler.forceTermination();
}
@Override
public void terminated() {
cleanup();
handler.terminated();
}
});
}
private void handleReadTimeout(final long ret) throws IOException {
if (!connection.isOpen()) {
cleanup();
return;
}
if (ret == -1) {
cleanup();
return;
}
Integer timeout = getTimeout();
if (timeout == null || timeout <= 0) {
return;
}
final long currentTime = System.currentTimeMillis();
if (ret == 0) {
final long expireTimeVar = expireTime;
if (expireTimeVar != -1 && currentTime > expireTimeVar) {
IoUtils.safeClose(connection);
throw UndertowMessages.MESSAGES.readTimedOut(this.getTimeout());
}
}
expireTime = currentTime + timeout;
if (handle == null) {
handle = connection.getIoThread().executeAfter(timeoutCommand, timeout, TimeUnit.MILLISECONDS);
}
}
@Override
public long transferTo(final long position, final long count, final FileChannel target) throws IOException {
checkExpired();
long ret = super.transferTo(position, count, target);
handleReadTimeout(ret);
return ret;
}
@Override
public long transferTo(final long count, final ByteBuffer throughBuffer, final StreamSinkChannel target) throws IOException {
checkExpired();
long ret = super.transferTo(count, throughBuffer, target);
handleReadTimeout(ret);
return ret;
}
@Override
public long read(final ByteBuffer[] dsts, final int offset, final int length) throws IOException {
checkExpired();
long ret = super.read(dsts, offset, length);
handleReadTimeout(ret);
return ret;
}
@Override
public int read(final ByteBuffer dst) throws IOException {
checkExpired();
int ret = super.read(dst);
handleReadTimeout(ret);
return ret;
}
@Override
public void awaitReadable() throws IOException {
checkExpired();
Integer timeout = getTimeout();
if (timeout != null && timeout > 0) {
super.awaitReadable(timeout + FUZZ_FACTOR, TimeUnit.MILLISECONDS);
} else {
super.awaitReadable();
}
}
@Override
public void awaitReadable(long time, TimeUnit timeUnit) throws IOException {
checkExpired();
Integer timeout = getTimeout();
if (timeout != null && timeout > 0) {
long millis = timeUnit.toMillis(time);
super.awaitReadable(Math.min(millis, timeout + FUZZ_FACTOR), TimeUnit.MILLISECONDS);
} else {
super.awaitReadable(time, timeUnit);
}
}
private Integer getTimeout() {
Integer timeout = 0;
try {
timeout = connection.getSourceChannel().getOption(Options.READ_TIMEOUT);
} catch (IOException ignore) {
// should never happen
}
Integer idleTimeout = openListener.getUndertowOptions().get(UndertowOptions.IDLE_TIMEOUT);
if ((timeout == null || timeout <= 0) && idleTimeout != null) {
timeout = idleTimeout;
} else if (timeout != null && idleTimeout != null && idleTimeout > 0) {
timeout = Math.min(timeout, idleTimeout);
}
return timeout;
}
@Override
public void terminateReads() throws IOException {
checkExpired();
super.terminateReads();
cleanup();
}
private void cleanup() {
if (handle != null) {
handle.remove();
handle = null;
expireTime = -1;
}
}
@Override
public void suspendReads() {
super.suspendReads();
cleanup();
}
private void checkExpired() throws ReadTimeoutException {
synchronized (this) {
if (expired) {
throw UndertowMessages.MESSAGES.readTimedOut(System.currentTimeMillis());
}
}
}
public String toString() {
return super.toString() + " (next: " + next + ")";
}
}
| rhusar/undertow | core/src/main/java/io/undertow/conduits/ReadTimeoutStreamSourceConduit.java | Java | apache-2.0 | 8,603 |
// Copyright (c) 2019 The Jaeger Authors.
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cache
import (
"container/list"
"sync"
"time"
)
// LRU is a concurrent fixed size cache that evicts elements in LRU order as well as by TTL.
type LRU struct {
mux sync.Mutex
byAccess *list.List
byKey map[string]*list.Element
maxSize int
ttl time.Duration
TimeNow func() time.Time
onEvict EvictCallback
}
// NewLRU creates a new LRU cache with default options.
func NewLRU(maxSize int) *LRU {
return NewLRUWithOptions(maxSize, nil)
}
// NewLRUWithOptions creates a new LRU cache with the given options.
func NewLRUWithOptions(maxSize int, opts *Options) *LRU {
if opts == nil {
opts = &Options{}
}
if opts.TimeNow == nil {
opts.TimeNow = time.Now
}
return &LRU{
byAccess: list.New(),
byKey: make(map[string]*list.Element, opts.InitialCapacity),
ttl: opts.TTL,
maxSize: maxSize,
TimeNow: opts.TimeNow,
onEvict: opts.OnEvict,
}
}
// Get retrieves the value stored under the given key
func (c *LRU) Get(key string) interface{} {
c.mux.Lock()
defer c.mux.Unlock()
elt := c.byKey[key]
if elt == nil {
return nil
}
cacheEntry := elt.Value.(*cacheEntry)
if !cacheEntry.expiration.IsZero() && c.TimeNow().After(cacheEntry.expiration) {
// Entry has expired
if c.onEvict != nil {
c.onEvict(cacheEntry.key, cacheEntry.value)
}
c.byAccess.Remove(elt)
delete(c.byKey, cacheEntry.key)
return nil
}
c.byAccess.MoveToFront(elt)
return cacheEntry.value
}
// Put puts a new value associated with a given key, returning the existing value (if present)
func (c *LRU) Put(key string, value interface{}) interface{} {
c.mux.Lock()
defer c.mux.Unlock()
elt := c.byKey[key]
return c.putWithMutexHold(key, value, elt)
}
// CompareAndSwap puts a new value associated with a given key if existing value matches oldValue.
// It returns itemInCache as the element in cache after the function is executed and replaced as true if value is replaced, false otherwise.
func (c *LRU) CompareAndSwap(key string, oldValue, newValue interface{}) (itemInCache interface{}, replaced bool) {
c.mux.Lock()
defer c.mux.Unlock()
elt := c.byKey[key]
// If entry not found, old value should be nil
if elt == nil && oldValue != nil {
return nil, false
}
if elt != nil {
// Entry found, compare it with that you expect.
entry := elt.Value.(*cacheEntry)
if entry.value != oldValue {
return entry.value, false
}
}
c.putWithMutexHold(key, newValue, elt)
return newValue, true
}
// putWithMutexHold populates the cache and returns the inserted value.
// Caller is expected to hold the c.mut mutex before calling.
func (c *LRU) putWithMutexHold(key string, value interface{}, elt *list.Element) interface{} {
if elt != nil {
entry := elt.Value.(*cacheEntry)
existing := entry.value
entry.value = value
if c.ttl != 0 {
entry.expiration = c.TimeNow().Add(c.ttl)
}
c.byAccess.MoveToFront(elt)
return existing
}
entry := &cacheEntry{
key: key,
value: value,
}
if c.ttl != 0 {
entry.expiration = c.TimeNow().Add(c.ttl)
}
c.byKey[key] = c.byAccess.PushFront(entry)
for len(c.byKey) > c.maxSize {
oldest := c.byAccess.Remove(c.byAccess.Back()).(*cacheEntry)
if c.onEvict != nil {
c.onEvict(oldest.key, oldest.value)
}
delete(c.byKey, oldest.key)
}
return nil
}
// Delete deletes a key, value pair associated with a key
func (c *LRU) Delete(key string) {
c.mux.Lock()
defer c.mux.Unlock()
elt := c.byKey[key]
if elt != nil {
entry := c.byAccess.Remove(elt).(*cacheEntry)
if c.onEvict != nil {
c.onEvict(entry.key, entry.value)
}
delete(c.byKey, key)
}
}
// Size returns the number of entries currently in the lru, useful if cache is not full
func (c *LRU) Size() int {
c.mux.Lock()
defer c.mux.Unlock()
return len(c.byKey)
}
type cacheEntry struct {
key string
expiration time.Time
value interface{}
}
| uber/jaeger | pkg/cache/lru.go | GO | apache-2.0 | 4,507 |
/*
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.test.functional.gateway;
import java.util.HashMap;
import java.util.Map;
import org.jbpm.executor.ExecutorServiceFactory;
import org.jbpm.test.JbpmTestCase;
import org.jbpm.test.wih.ListWorkItemHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.kie.api.executor.ExecutorService;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.process.ProcessInstance;
import static org.junit.Assert.assertNull;
/**
* Parallel gateway execution test. 2x parallel fork, 1x join
*/
public class ParallelGatewayAsyncTest extends JbpmTestCase {
private static final String PARALLEL_GATEWAY_ASYNC = "org/jbpm/test/functional/gateway/ParallelGatewayAsync.bpmn";
private static final String PARALLEL_GATEWAY_ASYNC_ID = "org.jbpm.test.functional.gateway.ParallelGatewayAsync";
private ExecutorService executorService;
private KieSession kieSession;
private ListWorkItemHandler wih;
public ParallelGatewayAsyncTest() {
super(true, true);
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
executorService = ExecutorServiceFactory.newExecutorService(getEmf());
executorService.setInterval(1);
executorService.init();
addEnvironmentEntry("AsyncMode", "true");
addEnvironmentEntry("ExecutorService", executorService);
wih = new ListWorkItemHandler();
addWorkItemHandler("Human Task", wih);
kieSession = createKSession(PARALLEL_GATEWAY_ASYNC);
}
@After
public void tearDown() throws Exception {
executorService.clearAllErrors();
executorService.clearAllRequests();
executorService.destroy();
super.tearDown();
}
/**
* Simple parallel gateway test.
*/
@Test(timeout = 30000)
public void testParallelGatewayAsync() throws Exception {
Map<String, Object> inputs = new HashMap<>();
inputs.put("useHT", Boolean.TRUE);
inputs.put("mode", "1");
ProcessInstance pi = kieSession.startProcess(PARALLEL_GATEWAY_ASYNC_ID, inputs);
Thread.sleep(3000L);
wih.getWorkItems().forEach(e -> kieSession.getWorkItemManager().completeWorkItem(e.getId(), e.getParameters()));
Thread.sleep(1000L);
assertNull(kieSession.getProcessInstance(pi.getId()));
}
}
| droolsjbpm/jbpm | jbpm-test-coverage/src/test/java/org/jbpm/test/functional/gateway/ParallelGatewayAsyncTest.java | Java | apache-2.0 | 3,008 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template value_accumulator_impl</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../../accumulators/reference.html#header.boost.accumulators.framework.accumulators.value_accumulator_hpp" title="Header <boost/accumulators/framework/accumulators/value_accumulator.hpp>">
<link rel="prev" href="../feature_of_tag_idp65558112.html" title="Struct template feature_of<tag::reference< ValueType, Tag >>">
<link rel="next" href="../feature_of_tag_idp65573344.html" title="Struct template feature_of<tag::value< ValueType, Tag >>">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../feature_of_tag_idp65558112.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.framework.accumulators.value_accumulator_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../feature_of_tag_idp65573344.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.accumulators.impl.value_accumulator_impl"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template value_accumulator_impl</span></h2>
<p>boost::accumulators::impl::value_accumulator_impl</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../../accumulators/reference.html#header.boost.accumulators.framework.accumulators.value_accumulator_hpp" title="Header <boost/accumulators/framework/accumulators/value_accumulator.hpp>">boost/accumulators/framework/accumulators/value_accumulator.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> ValueType<span class="special">,</span> <span class="keyword">typename</span> Tag<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="value_accumulator_impl.html" title="Struct template value_accumulator_impl">value_accumulator_impl</a> <span class="special">:</span> <span class="keyword">public</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">accumulators</span><span class="special">::</span><span class="identifier">accumulator_base</span> <span class="special">{</span>
<span class="comment">// types</span>
<span class="keyword">typedef</span> <span class="identifier">ValueType</span> <a name="boost.accumulators.impl.value_accumulator_impl.result_type"></a><span class="identifier">result_type</span><span class="special">;</span>
<span class="comment">// <a class="link" href="value_accumulator_impl.html#boost.accumulators.impl.value_accumulator_implconstruct-copy-destruct">construct/copy/destruct</a></span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Args<span class="special">></span> <a class="link" href="value_accumulator_impl.html#idp65583632-bb"><span class="identifier">value_accumulator_impl</span></a><span class="special">(</span><span class="identifier">Args</span> <span class="keyword">const</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="comment">// <a class="link" href="value_accumulator_impl.html#idp65580976-bb">public member functions</a></span>
<span class="identifier">result_type</span> <a class="link" href="value_accumulator_impl.html#idp65581536-bb"><span class="identifier">result</span></a><span class="special">(</span><a class="link" href="../dont_care.html" title="Struct dont_care">dont_care</a><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp100236752"></a><h2>Description</h2>
<div class="refsect2">
<a name="idp100237168"></a><h3>
<a name="boost.accumulators.impl.value_accumulator_implconstruct-copy-destruct"></a><code class="computeroutput">value_accumulator_impl</code>
public
construct/copy/destruct</h3>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Args<span class="special">></span> <a name="idp65583632-bb"></a><span class="identifier">value_accumulator_impl</span><span class="special">(</span><span class="identifier">Args</span> <span class="keyword">const</span> <span class="special">&</span> args<span class="special">)</span><span class="special">;</span></pre></li></ol></div>
</div>
<div class="refsect2">
<a name="idp100247696"></a><h3>
<a name="idp65580976-bb"></a><code class="computeroutput">value_accumulator_impl</code> public member functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><pre class="literallayout"><span class="identifier">result_type</span> <a name="idp65581536-bb"></a><span class="identifier">result</span><span class="special">(</span><a class="link" href="../dont_care.html" title="Struct dont_care">dont_care</a><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li></ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2005, 2006 Eric Niebler<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../feature_of_tag_idp65558112.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.framework.accumulators.value_accumulator_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../feature_of_tag_idp65573344.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| biospi/seamass-windeps | src/boost_1_57_0/doc/html/boost/accumulators/impl/value_accumulator_impl.html | HTML | apache-2.0 | 7,734 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<a action="TestAction" controller="TestController" _arg="args">Text</a>
</body>
</html>
| yonglehou/Jumony | WebTest/ActionUrlTest/Test1.html | HTML | apache-2.0 | 265 |
require_relative '../../puppet_x/puppetlabs/property/tag.rb'
require_relative '../../puppet_x/puppetlabs/property/region.rb'
require_relative '../../puppet_x/puppetlabs/aws_ingress_rules_parser'
Puppet::Type.newtype(:ec2_securitygroup) do
@doc = 'type representing an EC2 security group'
ensurable
newparam(:name, namevar: true) do
desc 'the name of the security group'
validate do |value|
fail 'security groups must have a name' if value == ''
fail 'name should be a String' unless value.is_a?(String)
end
end
newproperty(:region, :parent => PuppetX::Property::AwsRegion) do
desc 'the region in which to launch the security group'
end
newproperty(:ingress, :array_matching => :all) do
desc 'rules for ingress traffic'
def insync?(is)
for_comparison = Marshal.load(Marshal.dump(should))
parser = PuppetX::Puppetlabs::AwsIngressRulesParser.new(for_comparison)
to_create = parser.rules_to_create(is)
to_delete = parser.rules_to_delete(is)
to_create.empty? && to_delete.empty?
end
validate do |value|
fail 'ingress should be a Hash' unless value.is_a?(Hash)
end
end
newproperty(:tags, :parent => PuppetX::Property::AwsTag) do
desc 'the tags for the security group'
end
newproperty(:description) do
desc 'a short description of the group'
validate do |value|
fail 'description cannot be blank' if value == ''
fail 'description should be a String' unless value.is_a?(String)
end
end
newproperty(:vpc) do
desc 'A VPC to which the group should be associated'
validate do |value|
fail 'vpc should be a String' unless value.is_a?(String)
end
end
newproperty(:id) do
desc 'The unique identifier for the security group'
end
autorequire(:ec2_vpc) do
self[:vpc]
end
end
| gregohardy/puppetlabs-aws | lib/puppet/type/ec2_securitygroup.rb | Ruby | apache-2.0 | 1,842 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.