repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
|---|---|---|---|---|
macchina-io/macchina.io
|
platform/Crypto/include/Poco/Crypto/CipherImpl.h
|
1275
|
//
// CipherImpl.h
//
// Library: Crypto
// Package: Cipher
// Module: CipherImpl
//
// Definition of the CipherImpl class.
//
// Copyright (c) 2008, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Crypto_CipherImpl_INCLUDED
#define Crypto_CipherImpl_INCLUDED
#include "Poco/Crypto/Crypto.h"
#include "Poco/Crypto/Cipher.h"
#include "Poco/Crypto/CipherKey.h"
#include "Poco/Crypto/OpenSSLInitializer.h"
#include <openssl/evp.h>
namespace Poco {
namespace Crypto {
class CipherImpl: public Cipher
/// An implementation of the Cipher class for OpenSSL's crypto library.
{
public:
CipherImpl(const CipherKey& key);
/// Creates a new CipherImpl object for the given CipherKey.
virtual ~CipherImpl();
/// Destroys the CipherImpl.
const std::string& name() const;
/// Returns the name of the cipher.
CryptoTransform::Ptr createEncryptor();
/// Creates an encryptor object.
CryptoTransform::Ptr createDecryptor();
/// Creates a decryptor object.
private:
CipherKey _key;
OpenSSLInitializer _openSSLInitializer;
};
//
// Inlines
//
inline const std::string& CipherImpl::name() const
{
return _key.name();
}
} } // namespace Poco::Crypto
#endif // Crypto_CipherImpl_INCLUDED
|
apache-2.0
|
IOS-ZX/Notes
|
Notes/Record/Controller/CreateRemindController.h
|
221
|
//
// CreateRemindController.h
// Notes
//
// Created by rimi on 2017/1/10.
// Copyright © 2017年 iOS-ZX. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface CreateRemindController : UIViewController
@end
|
apache-2.0
|
cloudnautique/cloud-cattle
|
code/iaas/agent-instance/src/main/java/io/cattle/platform/agent/instance/service/impl/HostIpAddressMapNicLookup.java
|
1363
|
package io.cattle.platform.agent.instance.service.impl;
import static io.cattle.platform.core.model.tables.HostTable.*;
import static io.cattle.platform.core.model.tables.InstanceHostMapTable.*;
import static io.cattle.platform.core.model.tables.NicTable.*;
import io.cattle.platform.agent.instance.service.InstanceNicLookup;
import io.cattle.platform.core.model.HostIpAddressMap;
import io.cattle.platform.core.model.Nic;
import io.cattle.platform.core.model.tables.records.NicRecord;
import io.cattle.platform.db.jooq.dao.impl.AbstractJooqDao;
import java.util.List;
public class HostIpAddressMapNicLookup extends AbstractJooqDao implements InstanceNicLookup {
@Override
public List<? extends Nic> getNics(Object obj) {
if ( ! ( obj instanceof HostIpAddressMap ) ) {
return null;
}
return create()
.select(NIC.fields())
.from(HOST)
.join(INSTANCE_HOST_MAP)
.on(INSTANCE_HOST_MAP.HOST_ID.eq(HOST.ID))
.join(NIC)
.on(NIC.INSTANCE_ID.eq(INSTANCE_HOST_MAP.INSTANCE_ID))
.where(HOST.ID.eq(((HostIpAddressMap)obj).getHostId())
.and(NIC.REMOVED.isNull())
.and(INSTANCE_HOST_MAP.REMOVED.isNull()))
.fetchInto(NicRecord.class);
}
}
|
apache-2.0
|
adoc-editor/editor-web
|
app/views/layout/subheader.html
|
1266
|
<md-toolbar flex hide-sm style="height:30px; background-color: #f7f7f8; font-size:.9em; min-height: 0" class="md-accent"
ng-controller="SubheaderCtrl as subheader" ng-show="subheader.isActive() && user.auth">
<md-subheader class="md-accent" style="padding:6px 6px;">
<md-icon md-svg-icon="image:ic_filter_{{subheader.breadcrumb.users.length}}_24px" style="color:#aed581;width:18px;height:18px;" ></md-icon>
<md-icon md-svg-icon="file:ic_folder_open_24px" alt="" style="width:16px;height:16px;" >
</md-icon>
<span style="text-decoration: underline;" ng-click="app.toggleProject()">{{subheader.breadcrumb.project}}</span>
<md-icon md-svg-icon="navigation:ic_chevron_right_24px" style="width:16px;height:16px;" ></md-icon>
{{subheader.breadcrumb.file}}
<md-button ng-show="subheader.breadcrumb.fileId != ''" title="Close this file" ng-click="subheader.closeFile()"
class="md-button-fab" aria-label="Close the file" style="padding:0">
<md-tooltip>
Close the file
</md-tooltip>
<md-icon md-svg-icon="navigation:ic_cancel_24px" style="width:16px;height:16px;" ></md-icon>
</md-button>
</md-subheader>
</md-toolbar>
|
apache-2.0
|
frhumanes/consulting
|
web/src/decorators.py
|
3520
|
# -*- encoding: utf-8 -*-
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from functools import wraps
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.core.exceptions import PermissionDenied
from datetime import datetime
def paginate(template_name=None, list_name='default', objects_per_page=10):
def inner_p(fn):
def wrapped(request, *args, **kwargs):
fn_res = fn(request, *args, **kwargs)
objects = fn_res[list_name]
paginator = Paginator(objects, objects_per_page)
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
# If page request (9999) is out of range,
# deliver last page of results.
try:
loo = paginator.page(page)
except (EmptyPage, InvalidPage):
loo = paginator.page(paginator.num_pages)
fn_res.update({list_name: loo})
if 'template_name' in fn_res:
return render_to_response(fn_res['template_name'], fn_res,
context_instance=RequestContext(request))
else:
return render_to_response(template_name, fn_res,
context_instance=RequestContext(request))
return wraps(fn)(wrapped)
return inner_p
def only_doctor(func):
def _fn(request, *args, **kwargs):
if request.user.get_profile().is_doctor():
return func(request, *args, **kwargs)
else:
return HttpResponseRedirect(reverse('cal.index'))
return _fn
def only_doctor_consulting(func):
def _fn(request, *args, **kwargs):
if request.user.get_profile().is_doctor():
if 'patient_user_id' in kwargs and not request.user.doctor.filter(user__id=kwargs['patient_user_id']):
raise PermissionDenied
if 'id_patient' in kwargs and not request.user.doctor.filter(user__id=kwargs['id_patient']):
raise PermissionDenied
if 'id_task' in kwargs and not request.user.doctor.filter(user__patient_tasks__id=kwargs['id_task']):
raise PermissionDenied
if 'id_appointment' in kwargs and not request.user.doctor.filter(user__appointment_patient__id=kwargs['id_appointment']):
raise PermissionDenied
return func(request, *args, **kwargs)
else:
return HttpResponseRedirect(reverse('consulting_index'))
return _fn
def only_patient_consulting(func):
def _fn(request, *args, **kwargs):
if request.user.get_profile().is_patient():
return func(request, *args, **kwargs)
else:
return HttpResponseRedirect(reverse('consulting_index'))
return _fn
def only_doctor_administrative(func):
def _fn(request, *args, **kwargs):
if request.user.get_profile().is_administrative() or\
request.user.get_profile().is_doctor():
return func(request, *args, **kwargs)
else:
return HttpResponseRedirect(reverse('consulting_index'))
return _fn
def update_password_date(func):
def _fn(request, *args, **kwargs):
prof = request.user.get_profile()
prof.updated_password_at = datetime.today()
prof.save()
return func(request, *args, **kwargs)
return _fn
|
apache-2.0
|
stweil/tesseract-ocr.github.io
|
3.x/a00068.js
|
340
|
var a00068 =
[
[ "base", "a00068.html#a5ea674ad553da52d47ffe1df62d6eb9d", null ],
[ "MemberSignature", "a00068.html#a31088531e14b7f77e1df653d1003237d", null ],
[ "_ConstTessMemberResultCallback_5_3", "a00068.html#a47e920466d4dcc3529e4c296c8ad619f", null ],
[ "Run", "a00068.html#a5fa1d64d09741b114bda949599035b9c", null ]
];
|
apache-2.0
|
wchiviti/hlfdocsweb
|
Higherlife Document Management System/src/main/java/tech/hobbs/hlfdocmgmntsystem/dao/messages/Impl/MessageDaoImpl.java
|
1181
|
package tech.hobbs.hlfdocmgmntsystem.dao.messages.Impl;
import java.util.List;
import javax.mail.Message;
import org.springframework.stereotype.Repository;
import tech.hobbs.hlfdocmgmntsystem.dao.messages.MessageDao;
import tech.hobbs.hlfdocmgmntsystem.model.student.Student;
@Repository
public class MessageDaoImpl implements MessageDao {
@Override
public List<Message> findAll() {
// TODO Auto-generated method stub
return null;
}
@Override
public void saveOrUpdate(Message model) {
// TODO Auto-generated method stub
}
@Override
public void delete(Message model) {
// TODO Auto-generated method stub
}
@Override
public List<Message> findByRecipientFileno(Student student) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Message> findBySenderFileno(Student student) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Message> findByReadStatus(Boolean status) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Message> findAllTrashed() {
// TODO Auto-generated method stub
return null;
}
}
|
apache-2.0
|
olehmberg/winter
|
winter-usecases/src/main/java/de/uni_mannheim/informatik/dws/winter/usecase/events/model/EventCSVFormatter.java
|
960
|
package de.uni_mannheim.informatik.dws.winter.usecase.events.model;
import java.util.ArrayList;
import java.util.List;
import de.uni_mannheim.informatik.dws.winter.model.DataSet;
import de.uni_mannheim.informatik.dws.winter.model.defaultmodel.Attribute;
import de.uni_mannheim.informatik.dws.winter.model.io.CSVDataSetFormatter;
/**
* {@link CSVDataSetFormatter} for {@link Event}s.
*
* @author Daniel Ringler
*
*/
public class EventCSVFormatter extends CSVDataSetFormatter<Event,Attribute> {
@Override
public String[] getHeader(List<Attribute> orderedHeader) {
List<String> names = new ArrayList<>();
for (Attribute att : orderedHeader) {
names.add(att.getIdentifier());
}
return names.toArray(new String[names.size()]);
}
@Override
public String[] format(Event record, DataSet<Event, Attribute> dataset, List<Attribute> orderedHeader) {//}, char s) {
return record.getAllAttributeValues(',');//s);
}
}
|
apache-2.0
|
0111001101111010/Voice-Enabled-Timer
|
src/com/voidstar/glass/voiceenabledtimer/SelectValueScrollAdapter.java
|
2132
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.voidstar.glass.voiceenabledtimer;
import com.google.android.glass.widget.CardScrollAdapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
/**
* Adapter for the {@link CardSrollView} inside {@link SelectValueActivity}.
*/
public class SelectValueScrollAdapter extends CardScrollAdapter {
private final Context mContext;
private final int mCount;
public SelectValueScrollAdapter(Context context, int count) {
mContext = context;
mCount = count;
}
@Override
public int getCount() {
return mCount;
}
@Override
public Object getItem(int position) {
return Integer.valueOf(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.card_select_value, parent);
}
final TextView view = (TextView) convertView.findViewById(R.id.value);
view.setText(String.format("%02d", position));
return convertView;
}
@Override
public int getPosition(Object id) {
if (id instanceof Integer) {
int idInt = (Integer) id;
if (idInt >= 0 && idInt < mCount) {
return idInt;
}
}
return AdapterView.INVALID_POSITION;
}
}
|
apache-2.0
|
pwittrock/reference-docs
|
vendor/k8s.io/metrics/IMPLEMENTATIONS.md
|
834
|
# Implementations
## Resource Metrics API
- [Heapster](https://github.com/kubernetes/heapster): a application which
gathers metrics, writes them to metrics storage "sinks", and exposes the
resource metrics API from in-memory storage.
- [Metrics Server](https://github.com/kubernetes/heapster):
a lighter-weight in-memory server specifically for the resource metrics
API.
## Custom Metrics API
***NB: None of the below implemenations are officially part of Kubernetes.
They are listed here for convinience.***
- [Prometheus
Adapter](https://github.com/directxman12/k8s-prometheus-adapter). An
implementation of the custom metrics API that attempts to support
arbitrary metrics following a set label and naming scheme.
- [Google Stackdriver (coming
soon)](https://github.com/GoogleCloudPlatform/k8s-stackdriver)
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Eurotiomycetes/Chaetothyriales/Coniosporium/Coniosporium subseriatum/README.md
|
207
|
# Coniosporium subseriatum Ellis & Everh. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Coniosporium subseriatum Ellis & Everh.
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Echinocactus/Echinocactus odierii/README.md
|
189
|
# Echinocactus odierii Lem. ex Salm-Dyck. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Gymnanthemum myrianthum/ Syn. Vernonia myriantha/README.md
|
183
|
# Vernonia myriantha Hook.f. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Acianthera/Acianthera jordanensis/ Syn. Pleurothallis neojordanensis/README.md
|
190
|
# Pleurothallis neojordanensis Luer SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
OpenNTF/XPagesToolkit
|
org.openntf.xpt.agents/src/org/openntf/xpt/agents/master/ExecutionUserProperties.java
|
1540
|
/*
* Copyright 2013, WebGate Consulting AG
*
* 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.openntf.xpt.agents.master;
import java.io.Serializable;
import java.util.List;
public class ExecutionUserProperties implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private boolean m_LoggedIn = false;
private String m_UserName = "";
private int m_AccessLevel;
private List<String> m_Roles;
public boolean isLoggedIn() {
return m_LoggedIn;
}
public void setLoggedIn(boolean loggedIn) {
m_LoggedIn = loggedIn;
}
public String getUserName() {
return m_UserName;
}
public void setUserName(String userName) {
m_UserName = userName;
}
public int getAccessLevel() {
return m_AccessLevel;
}
public void setAccessLevel(int accessLevel) {
m_AccessLevel = accessLevel;
}
public List<String> getRoles() {
return m_Roles;
}
public void setRoles(List<String> roles) {
m_Roles = roles;
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Pinophyta/Pinopsida/Pinales/Cupressaceae/Juniperus/Juniperus monticola/Juniperus monticola orizabensis/README.md
|
190
|
# Juniperus monticola f. orizabensis Martinez FORM
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Lycopodiophyta/Lycopodiopsida/Lycopodiales/Lycopodiaceae/Huperzia/Urostachys difformis/README.md
|
187
|
# Urostachys difformis Herter ex Nessel SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Aeschynomene/Aeschynomene gracilipes/README.md
|
187
|
# Aeschynomene gracilipes Taub. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Protozoa/Euglenozoa/Entosiphonomonas/Entosiphon limenites/README.md
|
198
|
# Entosiphon limenites R.E. Norris SPECIES
#### Status
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Rosa/Rosa hirtifolia/Rosa hirtifolia hirtifolia/README.md
|
173
|
# Rosa hirtifolia var. hirtifolia VARIETY
#### Status
ACCEPTED
#### According to
NUB Generator [autonym]
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Lecanoromycetes/Teloschistales/Teloschistaceae/Gasparrinia/Gasparrinia granulosa/Gasparrinia granulosa perminuta/README.md
|
242
|
# Gasparrinia granulosa var. perminuta Mereschk. VARIETY
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Lich. Ros. exr. 63 (1913)
#### Original name
Gasparrinia granulosa var. perminuta Mereschk.
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Thymus/Thymus roseus/README.md
|
176
|
# Thymus roseus Schipczinsky SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
Dia6lo/Mechanism
|
Mechanism/RenderObjects/Animations/Animators.ts
|
865
|
/// <reference path="GenericAnimator.ts"/>
class Vector2Animator<T extends RenderObject> extends GenericAnimator<T, Vector2> {
interpolate(amount: number, from: Vector2, to: Vector2, interpolation: Interpolation): Vector2 {
switch (interpolation) {
case Interpolation.Linear:
return new Vector2(Math.lerp(amount, from.x, to.x), Math.lerp(amount, from.y, to.y));
default:
throw "Not supported";
}
}
}
class NumberAnimator<T extends RenderObject> extends GenericAnimator<T, number> {
interpolate(amount: number, from: number, to: number, interpolation: Interpolation): number {
switch (interpolation) {
case Interpolation.Linear:
return Math.lerp(amount, from, to);
default:
throw "Not supported";
}
}
}
|
apache-2.0
|
aravindsagar/SmartLockScreen
|
libsuperuser/src/eu/chainfire/libsuperuser/Shell.java
|
66888
|
/*
* Copyright (C) 2012-2014 Jorrit "Chainfire" Jongma
*
* 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 eu.chainfire.libsuperuser;
import android.os.Handler;
import android.os.Looper;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import eu.chainfire.libsuperuser.StreamGobbler.OnLineListener;
/**
* Class providing functionality to execute commands in a (root) shell
*/
public class Shell {
/**
* <p>
* Runs commands using the supplied shell, and returns the output, or null
* in case of errors.
* </p>
* <p>
* This method is deprecated and only provided for backwards compatibility.
* Use {@link #run(String, String[], String[], boolean)} instead, and see
* that same method for usage notes.
* </p>
*
* @param shell The shell to use for executing the commands
* @param commands The commands to execute
* @param wantSTDERR Return STDERR in the output ?
* @return Output of the commands, or null in case of an error
*/
@Deprecated
public static List<String> run(String shell, String[] commands, boolean wantSTDERR) {
return run(shell, commands, null, wantSTDERR);
}
/**
* <p>
* Runs commands using the supplied shell, and returns the output, or null
* in case of errors.
* </p>
* <p>
* Note that due to compatibility with older Android versions, wantSTDERR is
* not implemented using redirectErrorStream, but rather appended to the
* output. STDOUT and STDERR are thus not guaranteed to be in the correct
* order in the output.
* </p>
* <p>
* Note as well that this code will intentionally crash when run in debug
* mode from the main thread of the application. You should always execute
* shell commands from a background thread.
* </p>
* <p>
* When in debug mode, the code will also excessively log the commands
* passed to and the output returned from the shell.
* </p>
* <p>
* Though this function uses background threads to gobble STDOUT and STDERR
* so a deadlock does not occur if the shell produces massive output, the
* output is still stored in a List<String>, and as such doing
* something like <em>'ls -lR /'</em> will probably have you run out of
* memory.
* </p>
*
* @param shell The shell to use for executing the commands
* @param commands The commands to execute
* @param environment List of all environment variables (in 'key=value'
* format) or null for defaults
* @param wantSTDERR Return STDERR in the output ?
* @return Output of the commands, or null in case of an error
*/
public static List<String> run(String shell, String[] commands, String[] environment,
boolean wantSTDERR) {
String shellUpper = shell.toUpperCase(Locale.ENGLISH);
if (Debug.getSanityChecksEnabledEffective() && Debug.onMainThread()) {
// check if we're running in the main thread, and if so, crash if
// we're in debug mode, to let the developer know attention is
// needed here.
Debug.log(ShellOnMainThreadException.EXCEPTION_COMMAND);
throw new ShellOnMainThreadException(ShellOnMainThreadException.EXCEPTION_COMMAND);
}
Debug.logCommand(String.format("[%s%%] START", shellUpper));
List<String> res = Collections.synchronizedList(new ArrayList<String>());
try {
// Combine passed environment with system environment
if (environment != null) {
Map<String, String> newEnvironment = new HashMap<String, String>();
newEnvironment.putAll(System.getenv());
int split;
for (String entry : environment) {
if ((split = entry.indexOf("=")) >= 0) {
newEnvironment.put(entry.substring(0, split), entry.substring(split + 1));
}
}
int i = 0;
environment = new String[newEnvironment.size()];
for (Map.Entry<String, String> entry : newEnvironment.entrySet()) {
environment[i] = entry.getKey() + "=" + entry.getValue();
i++;
}
}
// setup our process, retrieve STDIN stream, and STDOUT/STDERR
// gobblers
Process process = Runtime.getRuntime().exec(shell, environment);
DataOutputStream STDIN = new DataOutputStream(process.getOutputStream());
StreamGobbler STDOUT = new StreamGobbler(shellUpper + "-", process.getInputStream(),
res);
StreamGobbler STDERR = new StreamGobbler(shellUpper + "*", process.getErrorStream(),
wantSTDERR ? res : null);
// start gobbling and write our commands to the shell
STDOUT.start();
STDERR.start();
try {
for (String write : commands) {
Debug.logCommand(String.format("[%s+] %s", shellUpper, write));
STDIN.write((write + "\n").getBytes("UTF-8"));
STDIN.flush();
}
STDIN.write("exit\n".getBytes("UTF-8"));
STDIN.flush();
} catch (IOException e) {
if (e.getMessage().contains("EPIPE")) {
// method most horrid to catch broken pipe, in which case we
// do nothing. the command is not a shell, the shell closed
// STDIN, the script already contained the exit command, etc.
// these cases we want the output instead of returning null
} else {
// other issues we don't know how to handle, leads to
// returning null
throw e;
}
}
// wait for our process to finish, while we gobble away in the
// background
process.waitFor();
// make sure our threads are done gobbling, our streams are closed,
// and the process is destroyed - while the latter two shouldn't be
// needed in theory, and may even produce warnings, in "normal" Java
// they are required for guaranteed cleanup of resources, so lets be
// safe and do this on Android as well
try {
STDIN.close();
} catch (IOException e) {
}
STDOUT.join();
STDERR.join();
process.destroy();
// in case of su, 255 usually indicates access denied
if (SU.isSU(shell) && (process.exitValue() == 255)) {
res = null;
}
} catch (IOException e) {
// shell probably not found
res = null;
} catch (InterruptedException e) {
// this should really be re-thrown
res = null;
}
Debug.logCommand(String.format("[%s%%] END", shell.toUpperCase(Locale.ENGLISH)));
return res;
}
protected static String[] availableTestCommands = new String[] {
"echo -BOC-",
"id"
};
/**
* See if the shell is alive, and if so, check the UID
*
* @param ret Standard output from running availableTestCommands
* @param checkForRoot true if we are expecting this shell to be running as
* root
* @return true on success, false on error
*/
protected static boolean parseAvailableResult(List<String> ret, boolean checkForRoot) {
if (ret == null)
return false;
// this is only one of many ways this can be done
boolean echo_seen = false;
for (String line : ret) {
if (line.contains("uid=")) {
// id command is working, let's see if we are actually root
return !checkForRoot || line.contains("uid=0");
} else if (line.contains("-BOC-")) {
// if we end up here, at least the su command starts some kind
// of shell,
// let's hope it has root privileges - no way to know without
// additional
// native binaries
echo_seen = true;
}
}
return echo_seen;
}
/**
* This class provides utility functions to easily execute commands using SH
*/
public static class SH {
/**
* Runs command and return output
*
* @param command The command to run
* @return Output of the command, or null in case of an error
*/
public static List<String> run(String command) {
return Shell.run("sh", new String[] {
command
}, null, false);
}
/**
* Runs commands and return output
*
* @param commands The commands to run
* @return Output of the commands, or null in case of an error
*/
public static List<String> run(List<String> commands) {
return Shell.run("sh", commands.toArray(new String[commands.size()]), null, false);
}
/**
* Runs commands and return output
*
* @param commands The commands to run
* @return Output of the commands, or null in case of an error
*/
public static List<String> run(String[] commands) {
return Shell.run("sh", commands, null, false);
}
}
/**
* This class provides utility functions to easily execute commands using SU
* (root shell), as well as detecting whether or not root is available, and
* if so which version.
*/
public static class SU {
private static Boolean isSELinuxEnforcing = null;
private static String[] suVersion = new String[] {
null, null
};
/**
* Runs command as root (if available) and return output
*
* @param command The command to run
* @return Output of the command, or null if root isn't available or in
* case of an error
*/
public static List<String> run(String command) {
return Shell.run("su", new String[] {
command
}, null, false);
}
/**
* Runs commands as root (if available) and return output
*
* @param commands The commands to run
* @return Output of the commands, or null if root isn't available or in
* case of an error
*/
public static List<String> run(List<String> commands) {
return Shell.run("su", commands.toArray(new String[commands.size()]), null, false);
}
/**
* Runs commands as root (if available) and return output
*
* @param commands The commands to run
* @return Output of the commands, or null if root isn't available or in
* case of an error
*/
public static List<String> run(String[] commands) {
return Shell.run("su", commands, null, false);
}
/**
* Detects whether or not superuser access is available, by checking the
* output of the "id" command if available, checking if a shell runs at
* all otherwise
*
* @return True if superuser access available
*/
public static boolean available() {
// this is only one of many ways this can be done
List<String> ret = run(Shell.availableTestCommands);
return Shell.parseAvailableResult(ret, true);
}
/**
* <p>
* Detects the version of the su binary installed (if any), if supported
* by the binary. Most binaries support two different version numbers,
* the public version that is displayed to users, and an internal
* version number that is used for version number comparisons. Returns
* null if su not available or retrieving the version isn't supported.
* </p>
* <p>
* Note that su binary version and GUI (APK) version can be completely
* different.
* </p>
* <p>
* This function caches its result to improve performance on multiple
* calls
* </p>
*
* @param internal Request human-readable version or application
* internal version
* @return String containing the su version or null
*/
public static synchronized String version(boolean internal) {
int idx = internal ? 0 : 1;
if (suVersion[idx] == null) {
String version = null;
List<String> ret = Shell.run(
internal ? "su -V" : "su -v",
new String[] { "exit" },
null,
false
);
if (ret != null) {
for (String line : ret) {
if (!internal) {
if (line.contains(".")) {
version = line;
break;
}
} else {
try {
if (Integer.parseInt(line) > 0) {
version = line;
break;
}
} catch (NumberFormatException e) {
}
}
}
}
suVersion[idx] = version;
}
return suVersion[idx];
}
/**
* Attempts to deduce if the shell command refers to a su shell
*
* @param shell Shell command to run
* @return Shell command appears to be su
*/
public static boolean isSU(String shell) {
// Strip parameters
int pos = shell.indexOf(' ');
if (pos >= 0) {
shell = shell.substring(0, pos);
}
// Strip path
pos = shell.lastIndexOf('/');
if (pos >= 0) {
shell = shell.substring(pos + 1);
}
return shell.equals("su");
}
/**
* Constructs a shell command to start a su shell using the supplied uid
* and SELinux context. This is can be an expensive operation, consider
* caching the result.
*
* @param uid Uid to use (0 == root)
* @param context (SELinux) context name to use or null
* @return Shell command
*/
public static String shell(int uid, String context) {
// su[ --context <context>][ <uid>]
String shell = "su";
if ((context != null) && isSELinuxEnforcing()) {
String display = version(false);
String internal = version(true);
// We only know the format for SuperSU v1.90+ right now
if ((display != null) &&
(internal != null) &&
(display.endsWith("SUPERSU")) &&
(Integer.valueOf(internal) >= 190)) {
shell = String.format(Locale.ENGLISH, "%s --context %s", shell, context);
}
}
// Most su binaries support the "su <uid>" format, but in case
// they don't, lets skip it for the default 0 (root) case
if (uid > 0) {
shell = String.format(Locale.ENGLISH, "%s %d", shell, uid);
}
return shell;
}
/**
* Constructs a shell command to start a su shell connected to mount
* master daemon, to perform public mounts on Android 4.3+ (or 4.2+ in
* SELinux enforcing mode)
*
* @return Shell command
*/
public static String shellMountMaster() {
if (android.os.Build.VERSION.SDK_INT >= 17) {
return "su --mount-master";
}
return "su";
}
/**
* Detect if SELinux is set to enforcing, caches result
*
* @return true if SELinux set to enforcing, or false in the case of
* permissive or not present
*/
public static synchronized boolean isSELinuxEnforcing() {
if (isSELinuxEnforcing == null) {
Boolean enforcing = null;
// First known firmware with SELinux built-in was a 4.2 (17)
// leak
if (android.os.Build.VERSION.SDK_INT >= 17) {
// Detect enforcing through sysfs, not always present
if (enforcing == null) {
File f = new File("/sys/fs/selinux/enforce");
if (f.exists()) {
try {
InputStream is = new FileInputStream("/sys/fs/selinux/enforce");
try {
enforcing = (is.read() == '1');
} finally {
is.close();
}
} catch (Exception e) {
}
}
}
// 4.4+ builds are enforcing by default, take the gamble
if (enforcing == null) {
enforcing = (android.os.Build.VERSION.SDK_INT >= 19);
}
}
if (enforcing == null) {
enforcing = false;
}
isSELinuxEnforcing = enforcing;
}
return isSELinuxEnforcing;
}
/**
* <p>
* Clears results cached by isSELinuxEnforcing() and version(boolean
* internal) calls.
* </p>
* <p>
* Most apps should never need to call this, as neither enforcing status
* nor su version is likely to change on a running device - though it is
* not impossible.
* </p>
*/
public static synchronized void clearCachedResults() {
isSELinuxEnforcing = null;
suVersion[0] = null;
suVersion[1] = null;
}
}
private interface OnResult {
// for any onCommandResult callback
public static final int WATCHDOG_EXIT = -1;
public static final int SHELL_DIED = -2;
// for Interactive.open() callbacks only
public static final int SHELL_EXEC_FAILED = -3;
public static final int SHELL_WRONG_UID = -4;
public static final int SHELL_RUNNING = 0;
}
/**
* Command result callback, notifies the recipient of the completion of a
* command block, including the (last) exit code, and the full output
*/
public interface OnCommandResultListener extends OnResult {
/**
* <p>
* Command result callback
* </p>
* <p>
* Depending on how and on which thread the shell was created, this
* callback may be executed on one of the gobbler threads. In that case,
* it is important the callback returns as quickly as possible, as
* delays in this callback may pause the native process or even result
* in a deadlock
* </p>
* <p>
* See {@link Shell.Interactive} for threading details
* </p>
*
* @param commandCode Value previously supplied to addCommand
* @param exitCode Exit code of the last command in the block
* @param output All output generated by the command block
*/
public void onCommandResult(int commandCode, int exitCode, List<String> output);
}
/**
* Command per line callback for parsing the output line by line without
* buffering It also notifies the recipient of the completion of a command
* block, including the (last) exit code.
*/
public interface OnCommandLineListener extends OnResult, OnLineListener {
/**
* <p>
* Command result callback
* </p>
* <p>
* Depending on how and on which thread the shell was created, this
* callback may be executed on one of the gobbler threads. In that case,
* it is important the callback returns as quickly as possible, as
* delays in this callback may pause the native process or even result
* in a deadlock
* </p>
* <p>
* See {@link Shell.Interactive} for threading details
* </p>
*
* @param commandCode Value previously supplied to addCommand
* @param exitCode Exit code of the last command in the block
*/
public void onCommandResult(int commandCode, int exitCode);
}
/**
* Internal class to store command block properties
*/
private static class Command {
private static int commandCounter = 0;
private final String[] commands;
private final int code;
private final OnCommandResultListener onCommandResultListener;
private final OnCommandLineListener onCommandLineListener;
private final String marker;
public Command(String[] commands, int code,
OnCommandResultListener onCommandResultListener,
OnCommandLineListener onCommandLineListener) {
this.commands = commands;
this.code = code;
this.onCommandResultListener = onCommandResultListener;
this.onCommandLineListener = onCommandLineListener;
this.marker = UUID.randomUUID().toString() + String.format("-%08x", ++commandCounter);
}
}
/**
* Builder class for {@link Shell.Interactive}
*/
public static class Builder {
private Handler handler = null;
private boolean autoHandler = true;
private String shell = "sh";
private boolean wantSTDERR = false;
private List<Command> commands = new LinkedList<Command>();
private Map<String, String> environment = new HashMap<String, String>();
private OnLineListener onSTDOUTLineListener = null;
private OnLineListener onSTDERRLineListener = null;
private int watchdogTimeout = 0;
/**
* <p>
* Set a custom handler that will be used to post all callbacks to
* </p>
* <p>
* See {@link Shell.Interactive} for further details on threading and
* handlers
* </p>
*
* @param handler Handler to use
* @return This Builder object for method chaining
*/
public Builder setHandler(Handler handler) {
this.handler = handler;
return this;
}
/**
* <p>
* Automatically create a handler if possible ? Default to true
* </p>
* <p>
* See {@link Shell.Interactive} for further details on threading and
* handlers
* </p>
*
* @param autoHandler Auto-create handler ?
* @return This Builder object for method chaining
*/
public Builder setAutoHandler(boolean autoHandler) {
this.autoHandler = autoHandler;
return this;
}
/**
* Set shell binary to use. Usually "sh" or "su", do not use a full path
* unless you have a good reason to
*
* @param shell Shell to use
* @return This Builder object for method chaining
*/
public Builder setShell(String shell) {
this.shell = shell;
return this;
}
/**
* Convenience function to set "sh" as used shell
*
* @return This Builder object for method chaining
*/
public Builder useSH() {
return setShell("sh");
}
/**
* Convenience function to set "su" as used shell
*
* @return This Builder object for method chaining
*/
public Builder useSU() {
return setShell("su");
}
/**
* Set if error output should be appended to command block result output
*
* @param wantSTDERR Want error output ?
* @return This Builder object for method chaining
*/
public Builder setWantSTDERR(boolean wantSTDERR) {
this.wantSTDERR = wantSTDERR;
return this;
}
/**
* Add or update an environment variable
*
* @param key Key of the environment variable
* @param value Value of the environment variable
* @return This Builder object for method chaining
*/
public Builder addEnvironment(String key, String value) {
environment.put(key, value);
return this;
}
/**
* Add or update environment variables
*
* @param addEnvironment Map of environment variables
* @return This Builder object for method chaining
*/
public Builder addEnvironment(Map<String, String> addEnvironment) {
environment.putAll(addEnvironment);
return this;
}
/**
* Add a command to execute
*
* @param command Command to execute
* @return This Builder object for method chaining
*/
public Builder addCommand(String command) {
return addCommand(command, 0, null);
}
/**
* <p>
* Add a command to execute, with a callback to be called on completion
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param command Command to execute
* @param code User-defined value passed back to the callback
* @param onCommandResultListener Callback to be called on completion
* @return This Builder object for method chaining
*/
public Builder addCommand(String command, int code,
OnCommandResultListener onCommandResultListener) {
return addCommand(new String[] {
command
}, code, onCommandResultListener);
}
/**
* Add commands to execute
*
* @param commands Commands to execute
* @return This Builder object for method chaining
*/
public Builder addCommand(List<String> commands) {
return addCommand(commands, 0, null);
}
/**
* <p>
* Add commands to execute, with a callback to be called on completion
* (of all commands)
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param commands Commands to execute
* @param code User-defined value passed back to the callback
* @param onCommandResultListener Callback to be called on completion
* (of all commands)
* @return This Builder object for method chaining
*/
public Builder addCommand(List<String> commands, int code,
OnCommandResultListener onCommandResultListener) {
return addCommand(commands.toArray(new String[commands.size()]), code,
onCommandResultListener);
}
/**
* Add commands to execute
*
* @param commands Commands to execute
* @return This Builder object for method chaining
*/
public Builder addCommand(String[] commands) {
return addCommand(commands, 0, null);
}
/**
* <p>
* Add commands to execute, with a callback to be called on completion
* (of all commands)
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param commands Commands to execute
* @param code User-defined value passed back to the callback
* @param onCommandResultListener Callback to be called on completion
* (of all commands)
* @return This Builder object for method chaining
*/
public Builder addCommand(String[] commands, int code,
OnCommandResultListener onCommandResultListener) {
this.commands.add(new Command(commands, code, onCommandResultListener, null));
return this;
}
/**
* <p>
* Set a callback called for every line output to STDOUT by the shell
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param onLineListener Callback to be called for each line
* @return This Builder object for method chaining
*/
public Builder setOnSTDOUTLineListener(OnLineListener onLineListener) {
this.onSTDOUTLineListener = onLineListener;
return this;
}
/**
* <p>
* Set a callback called for every line output to STDERR by the shell
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param onLineListener Callback to be called for each line
* @return This Builder object for method chaining
*/
public Builder setOnSTDERRLineListener(OnLineListener onLineListener) {
this.onSTDERRLineListener = onLineListener;
return this;
}
/**
* <p>
* Enable command timeout callback
* </p>
* <p>
* This will invoke the onCommandResult() callback with exitCode
* WATCHDOG_EXIT if a command takes longer than watchdogTimeout seconds
* to complete.
* </p>
* <p>
* If a watchdog timeout occurs, it generally means that the Interactive
* session is out of sync with the shell process. The caller should
* close the current session and open a new one.
* </p>
*
* @param watchdogTimeout Timeout, in seconds; 0 to disable
* @return This Builder object for method chaining
*/
public Builder setWatchdogTimeout(int watchdogTimeout) {
this.watchdogTimeout = watchdogTimeout;
return this;
}
/**
* <p>
* Enable/disable reduced logcat output
* </p>
* <p>
* Note that this is a global setting
* </p>
*
* @param useMinimal true for reduced output, false for full output
* @return This Builder object for method chaining
*/
public Builder setMinimalLogging(boolean useMinimal) {
Debug.setLogTypeEnabled(Debug.LOG_COMMAND | Debug.LOG_OUTPUT, !useMinimal);
return this;
}
/**
* Construct a {@link Shell.Interactive} instance, and start the shell
*/
public Interactive open() {
return new Interactive(this, null);
}
/**
* Construct a {@link Shell.Interactive} instance, try to start the
* shell, and call onCommandResultListener to report success or failure
*
* @param onCommandResultListener Callback to return shell open status
*/
public Interactive open(OnCommandResultListener onCommandResultListener) {
return new Interactive(this, onCommandResultListener);
}
}
/**
* <p>
* An interactive shell - initially created with {@link Shell.Builder} -
* that executes blocks of commands you supply in the background, optionally
* calling callbacks as each block completes.
* </p>
* <p>
* STDERR output can be supplied as well, but due to compatibility with
* older Android versions, wantSTDERR is not implemented using
* redirectErrorStream, but rather appended to the output. STDOUT and STDERR
* are thus not guaranteed to be in the correct order in the output.
* </p>
* <p>
* Note as well that the close() and waitForIdle() methods will
* intentionally crash when run in debug mode from the main thread of the
* application. Any blocking call should be run from a background thread.
* </p>
* <p>
* When in debug mode, the code will also excessively log the commands
* passed to and the output returned from the shell.
* </p>
* <p>
* Though this function uses background threads to gobble STDOUT and STDERR
* so a deadlock does not occur if the shell produces massive output, the
* output is still stored in a List<String>, and as such doing
* something like <em>'ls -lR /'</em> will probably have you run out of
* memory when using a {@link Shell.OnCommandResultListener}. A work-around
* is to not supply this callback, but using (only)
* {@link Shell.Builder#setOnSTDOUTLineListener(OnLineListener)}. This way,
* an internal buffer will not be created and wasting your memory.
* </p>
* <h3>Callbacks, threads and handlers</h3>
* <p>
* On which thread the callbacks execute is dependent on your
* initialization. You can supply a custom Handler using
* {@link Shell.Builder#setHandler(Handler)} if needed. If you do not supply
* a custom Handler - unless you set
* {@link Shell.Builder#setAutoHandler(boolean)} to false - a Handler will
* be auto-created if the thread used for instantiation of the object has a
* Looper.
* </p>
* <p>
* If no Handler was supplied and it was also not auto-created, all
* callbacks will be called from either the STDOUT or STDERR gobbler
* threads. These are important threads that should be blocked as little as
* possible, as blocking them may in rare cases pause the native process or
* even create a deadlock.
* </p>
* <p>
* The main thread must certainly have a Looper, thus if you call
* {@link Shell.Builder#open()} from the main thread, a handler will (by
* default) be auto-created, and all the callbacks will be called on the
* main thread. While this is often convenient and easy to code with, you
* should be aware that if your callbacks are 'expensive' to execute, this
* may negatively impact UI performance.
* </p>
* <p>
* Background threads usually do <em>not</em> have a Looper, so calling
* {@link Shell.Builder#open()} from such a background thread will (by
* default) result in all the callbacks being executed in one of the gobbler
* threads. You will have to make sure the code you execute in these
* callbacks is thread-safe.
* </p>
*/
public static class Interactive {
private final Handler handler;
private final boolean autoHandler;
private final String shell;
private final boolean wantSTDERR;
private final List<Command> commands;
private final Map<String, String> environment;
private final OnLineListener onSTDOUTLineListener;
private final OnLineListener onSTDERRLineListener;
private int watchdogTimeout;
private Process process = null;
private DataOutputStream STDIN = null;
private StreamGobbler STDOUT = null;
private StreamGobbler STDERR = null;
private ScheduledThreadPoolExecutor watchdog = null;
private volatile boolean running = false;
private volatile boolean idle = true; // read/write only synchronized
private volatile boolean closed = true;
private volatile int callbacks = 0;
private volatile int watchdogCount;
private Object idleSync = new Object();
private Object callbackSync = new Object();
private volatile int lastExitCode = 0;
private volatile String lastMarkerSTDOUT = null;
private volatile String lastMarkerSTDERR = null;
private volatile Command command = null;
private volatile List<String> buffer = null;
/**
* The only way to create an instance: Shell.Builder::open()
*
* @param builder Builder class to take values from
*/
private Interactive(final Builder builder,
final OnCommandResultListener onCommandResultListener) {
autoHandler = builder.autoHandler;
shell = builder.shell;
wantSTDERR = builder.wantSTDERR;
commands = builder.commands;
environment = builder.environment;
onSTDOUTLineListener = builder.onSTDOUTLineListener;
onSTDERRLineListener = builder.onSTDERRLineListener;
watchdogTimeout = builder.watchdogTimeout;
// If a looper is available, we offload the callbacks from the
// gobbling threads
// to whichever thread created us. Would normally do this in open(),
// but then we could not declare handler as final
if ((Looper.myLooper() != null) && (builder.handler == null) && autoHandler) {
handler = new Handler();
} else {
handler = builder.handler;
}
boolean ret = open();
if (onCommandResultListener == null) {
return;
} else if (ret == false) {
onCommandResultListener.onCommandResult(0,
OnCommandResultListener.SHELL_EXEC_FAILED, null);
return;
}
// Allow up to 60 seconds for SuperSU/Superuser dialog, then enable
// the user-specified
// timeout for all subsequent operations
watchdogTimeout = 60;
addCommand(Shell.availableTestCommands, 0, new OnCommandResultListener() {
public void onCommandResult(int commandCode, int exitCode, List<String> output) {
if (exitCode == OnCommandResultListener.SHELL_RUNNING &&
Shell.parseAvailableResult(output, Shell.SU.isSU(shell)) != true) {
// shell is up, but it's brain-damaged
exitCode = OnCommandResultListener.SHELL_WRONG_UID;
}
watchdogTimeout = builder.watchdogTimeout;
onCommandResultListener.onCommandResult(0, exitCode, output);
}
});
}
@Override
protected void finalize() throws Throwable {
if (!closed && Debug.getSanityChecksEnabledEffective()) {
// waste of resources
Debug.log(ShellNotClosedException.EXCEPTION_NOT_CLOSED);
throw new ShellNotClosedException();
}
super.finalize();
}
/**
* Add a command to execute
*
* @param command Command to execute
*/
public void addCommand(String command) {
addCommand(command, 0, (OnCommandResultListener) null);
}
/**
* <p>
* Add a command to execute, with a callback to be called on completion
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param command Command to execute
* @param code User-defined value passed back to the callback
* @param onCommandResultListener Callback to be called on completion
*/
public void addCommand(String command, int code,
OnCommandResultListener onCommandResultListener) {
addCommand(new String[] {
command
}, code, onCommandResultListener);
}
/**
* <p>
* Add a command to execute, with a callback. This callback gobbles the
* output line by line without buffering it and also returns the result
* code on completion.
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param command Command to execute
* @param code User-defined value passed back to the callback
* @param onCommandLineListener Callback
*/
public void addCommand(String command, int code, OnCommandLineListener onCommandLineListener) {
addCommand(new String[] {
command
}, code, onCommandLineListener);
}
/**
* Add commands to execute
*
* @param commands Commands to execute
*/
public void addCommand(List<String> commands) {
addCommand(commands, 0, (OnCommandResultListener) null);
}
/**
* <p>
* Add commands to execute, with a callback to be called on completion
* (of all commands)
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param commands Commands to execute
* @param code User-defined value passed back to the callback
* @param onCommandResultListener Callback to be called on completion
* (of all commands)
*/
public void addCommand(List<String> commands, int code,
OnCommandResultListener onCommandResultListener) {
addCommand(commands.toArray(new String[commands.size()]), code, onCommandResultListener);
}
/**
* <p>
* Add commands to execute, with a callback. This callback gobbles the
* output line by line without buffering it and also returns the result
* code on completion.
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param commands Commands to execute
* @param code User-defined value passed back to the callback
* @param onCommandLineListener Callback
*/
public void addCommand(List<String> commands, int code,
OnCommandLineListener onCommandLineListener) {
addCommand(commands.toArray(new String[commands.size()]), code, onCommandLineListener);
}
/**
* Add commands to execute
*
* @param commands Commands to execute
*/
public void addCommand(String[] commands) {
addCommand(commands, 0, (OnCommandResultListener) null);
}
/**
* <p>
* Add commands to execute, with a callback to be called on completion
* (of all commands)
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param commands Commands to execute
* @param code User-defined value passed back to the callback
* @param onCommandResultListener Callback to be called on completion
* (of all commands)
*/
public synchronized void addCommand(String[] commands, int code,
OnCommandResultListener onCommandResultListener) {
this.commands.add(new Command(commands, code, onCommandResultListener, null));
runNextCommand();
}
/**
* <p>
* Add commands to execute, with a callback. This callback gobbles the
* output line by line without buffering it and also returns the result
* code on completion.
* </p>
* <p>
* The thread on which the callback executes is dependent on various
* factors, see {@link Shell.Interactive} for further details
* </p>
*
* @param commands Commands to execute
* @param code User-defined value passed back to the callback
* @param onCommandLineListener Callback
*/
public synchronized void addCommand(String[] commands, int code,
OnCommandLineListener onCommandLineListener) {
this.commands.add(new Command(commands, code, null, onCommandLineListener));
runNextCommand();
}
/**
* Run the next command if any and if ready, signals idle state if no
* commands left
*/
private void runNextCommand() {
runNextCommand(true);
}
/**
* Called from a ScheduledThreadPoolExecutor timer thread every second
* when there is an outstanding command
*/
private synchronized void handleWatchdog() {
final int exitCode;
if (watchdog == null)
return;
if (watchdogTimeout == 0)
return;
if (!isRunning()) {
exitCode = OnCommandResultListener.SHELL_DIED;
Debug.log(String.format("[%s%%] SHELL_DIED", shell.toUpperCase(Locale.ENGLISH)));
} else if (watchdogCount++ < watchdogTimeout) {
return;
} else {
exitCode = OnCommandResultListener.WATCHDOG_EXIT;
Debug.log(String.format("[%s%%] WATCHDOG_EXIT", shell.toUpperCase(Locale.ENGLISH)));
}
if (handler != null) {
postCallback(command, exitCode, buffer);
}
// prevent multiple callbacks for the same command
command = null;
buffer = null;
idle = true;
watchdog.shutdown();
watchdog = null;
kill();
}
/**
* Start the periodic timer when a command is submitted
*/
private void startWatchdog() {
if (watchdogTimeout == 0) {
return;
}
watchdogCount = 0;
watchdog = new ScheduledThreadPoolExecutor(1);
watchdog.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
handleWatchdog();
}
}, 1, 1, TimeUnit.SECONDS);
}
/**
* Disable the watchdog timer upon command completion
*/
private void stopWatchdog() {
if (watchdog != null) {
watchdog.shutdownNow();
watchdog = null;
}
}
/**
* Run the next command if any and if ready
*
* @param notifyIdle signals idle state if no commands left ?
*/
private void runNextCommand(boolean notifyIdle) {
// must always be called from a synchronized method
boolean running = isRunning();
if (!running)
idle = true;
if (running && idle && (commands.size() > 0)) {
Command command = commands.get(0);
commands.remove(0);
buffer = null;
lastExitCode = 0;
lastMarkerSTDOUT = null;
lastMarkerSTDERR = null;
if (command.commands.length > 0) {
try {
if (command.onCommandResultListener != null) {
// no reason to store the output if we don't have an
// OnCommandResultListener
// user should catch the output with an
// OnLineListener in this case
buffer = Collections.synchronizedList(new ArrayList<String>());
}
idle = false;
this.command = command;
startWatchdog();
for (String write : command.commands) {
Debug.logCommand(String.format("[%s+] %s",
shell.toUpperCase(Locale.ENGLISH), write));
STDIN.write((write + "\n").getBytes("UTF-8"));
}
STDIN.write(("echo " + command.marker + " $?\n").getBytes("UTF-8"));
STDIN.write(("echo " + command.marker + " >&2\n").getBytes("UTF-8"));
STDIN.flush();
} catch (IOException e) {
}
} else {
runNextCommand(false);
}
} else if (!running) {
// our shell died for unknown reasons - abort all submissions
while (commands.size() > 0) {
postCallback(commands.remove(0), OnCommandResultListener.SHELL_DIED, null);
}
}
if (idle && notifyIdle) {
synchronized (idleSync) {
idleSync.notifyAll();
}
}
}
/**
* Processes a STDOUT/STDERR line containing an end/exitCode marker
*/
private synchronized void processMarker() {
if (command.marker.equals(lastMarkerSTDOUT)
&& (command.marker.equals(lastMarkerSTDERR))) {
postCallback(command, lastExitCode, buffer);
stopWatchdog();
command = null;
buffer = null;
idle = true;
runNextCommand();
}
}
/**
* Process a normal STDOUT/STDERR line
*
* @param line Line to process
* @param listener Callback to call or null
*/
private synchronized void processLine(String line, OnLineListener listener) {
if (listener != null) {
if (handler != null) {
final String fLine = line;
final OnLineListener fListener = listener;
startCallback();
handler.post(new Runnable() {
@Override
public void run() {
try {
fListener.onLine(fLine);
} finally {
endCallback();
}
}
});
} else {
listener.onLine(line);
}
}
}
/**
* Add line to internal buffer
*
* @param line Line to add
*/
private synchronized void addBuffer(String line) {
if (buffer != null) {
buffer.add(line);
}
}
/**
* Increase callback counter
*/
private void startCallback() {
synchronized (callbackSync) {
callbacks++;
}
}
/**
* Schedule a callback to run on the appropriate thread
*/
private void postCallback(final Command fCommand, final int fExitCode,
final List<String> fOutput) {
if (fCommand.onCommandResultListener == null && fCommand.onCommandLineListener == null) {
return;
}
if (handler == null) {
if ((fCommand.onCommandResultListener != null) && (fOutput != null))
fCommand.onCommandResultListener.onCommandResult(fCommand.code, fExitCode,
fOutput);
if (fCommand.onCommandLineListener != null)
fCommand.onCommandLineListener.onCommandResult(fCommand.code, fExitCode);
return;
}
startCallback();
handler.post(new Runnable() {
@Override
public void run() {
try {
if ((fCommand.onCommandResultListener != null) && (fOutput != null))
fCommand.onCommandResultListener.onCommandResult(fCommand.code,
fExitCode, fOutput);
if (fCommand.onCommandLineListener != null)
fCommand.onCommandLineListener
.onCommandResult(fCommand.code, fExitCode);
} finally {
endCallback();
}
}
});
}
/**
* Decrease callback counter, signals callback complete state when
* dropped to 0
*/
private void endCallback() {
synchronized (callbackSync) {
callbacks--;
if (callbacks == 0) {
callbackSync.notifyAll();
}
}
}
/**
* Internal call that launches the shell, starts gobbling, and starts
* executing commands. See {@link Shell.Interactive}
*
* @return Opened successfully ?
*/
private synchronized boolean open() {
Debug.log(String.format("[%s%%] START", shell.toUpperCase(Locale.ENGLISH)));
try {
// setup our process, retrieve STDIN stream, and STDOUT/STDERR
// gobblers
if (environment.size() == 0) {
process = Runtime.getRuntime().exec(shell);
} else {
Map<String, String> newEnvironment = new HashMap<String, String>();
newEnvironment.putAll(System.getenv());
newEnvironment.putAll(environment);
int i = 0;
String[] env = new String[newEnvironment.size()];
for (Map.Entry<String, String> entry : newEnvironment.entrySet()) {
env[i] = entry.getKey() + "=" + entry.getValue();
i++;
}
process = Runtime.getRuntime().exec(shell, env);
}
STDIN = new DataOutputStream(process.getOutputStream());
STDOUT = new StreamGobbler(shell.toUpperCase(Locale.ENGLISH) + "-",
process.getInputStream(), new OnLineListener() {
@Override
public void onLine(String line) {
synchronized (Interactive.this) {
if (command == null) {
return;
}
if (line.startsWith(command.marker)) {
try {
lastExitCode = Integer.valueOf(
line.substring(command.marker.length() + 1), 10);
} catch (Exception e) {
}
lastMarkerSTDOUT = command.marker;
processMarker();
} else {
addBuffer(line);
processLine(line, onSTDOUTLineListener);
processLine(line, command.onCommandLineListener);
}
}
}
});
STDERR = new StreamGobbler(shell.toUpperCase(Locale.ENGLISH) + "*",
process.getErrorStream(), new OnLineListener() {
@Override
public void onLine(String line) {
synchronized (Interactive.this) {
if (command == null) {
return;
}
if (line.startsWith(command.marker)) {
lastMarkerSTDERR = command.marker;
processMarker();
} else {
if (wantSTDERR)
addBuffer(line);
processLine(line, onSTDERRLineListener);
}
}
}
});
// start gobbling and write our commands to the shell
STDOUT.start();
STDERR.start();
running = true;
closed = false;
runNextCommand();
return true;
} catch (IOException e) {
// shell probably not found
return false;
}
}
/**
* Close shell and clean up all resources. Call this when you are done
* with the shell. If the shell is not idle (all commands completed) you
* should not call this method from the main UI thread because it may
* block for a long time. This method will intentionally crash your app
* (if in debug mode) if you try to do this anyway.
*/
public void close() {
boolean _idle = isIdle(); // idle must be checked synchronized
synchronized (this) {
if (!running)
return;
running = false;
closed = true;
}
// This method should not be called from the main thread unless the
// shell is idle and can be cleaned up with (minimal) waiting. Only
// throw in debug mode.
if (!_idle && Debug.getSanityChecksEnabledEffective() && Debug.onMainThread()) {
Debug.log(ShellOnMainThreadException.EXCEPTION_NOT_IDLE);
throw new ShellOnMainThreadException(ShellOnMainThreadException.EXCEPTION_NOT_IDLE);
}
if (!_idle)
waitForIdle();
try {
try {
STDIN.write(("exit\n").getBytes("UTF-8"));
STDIN.flush();
} catch (IOException e) {
if (e.getMessage().contains("EPIPE")) {
// we're not running a shell, the shell closed STDIN,
// the script already contained the exit command, etc.
} else {
throw e;
}
}
// wait for our process to finish, while we gobble away in the
// background
process.waitFor();
// make sure our threads are done gobbling, our streams are
// closed, and the process is destroyed - while the latter two
// shouldn't be needed in theory, and may even produce warnings,
// in "normal" Java they are required for guaranteed cleanup of
// resources, so lets be safe and do this on Android as well
try {
STDIN.close();
} catch (IOException e) {
// STDIN going missing is no reason to abort
}
STDOUT.join();
STDERR.join();
stopWatchdog();
process.destroy();
} catch (IOException e) {
// various unforseen IO errors may still occur
} catch (InterruptedException e) {
// this should really be re-thrown
}
Debug.log(String.format("[%s%%] END", shell.toUpperCase(Locale.ENGLISH)));
}
/**
* Try to clean up as much as possible from a shell that's gotten itself
* wedged. Hopefully the StreamGobblers will croak on their own when the
* other side of the pipe is closed.
*/
public synchronized void kill() {
running = false;
closed = true;
try {
STDIN.close();
} catch (IOException e) {
}
try {
process.destroy();
} catch (Exception e) {
}
}
/**
* Is our shell still running ?
*
* @return Shell running ?
*/
public boolean isRunning() {
if (process == null) {
return false;
}
try {
// if this throws, we're still running
process.exitValue();
return false;
} catch (IllegalThreadStateException e) {
}
return true;
}
/**
* Have all commands completed executing ?
*
* @return Shell idle ?
*/
public synchronized boolean isIdle() {
if (!isRunning()) {
idle = true;
synchronized (idleSync) {
idleSync.notifyAll();
}
}
return idle;
}
/**
* <p>
* Wait for idle state. As this is a blocking call, you should not call
* it from the main UI thread. If you do so and debug mode is enabled,
* this method will intentionally crash your app.
* </p>
* <p>
* If not interrupted, this method will not return until all commands
* have finished executing. Note that this does not necessarily mean
* that all the callbacks have fired yet.
* </p>
* <p>
* If no Handler is used, all callbacks will have been executed when
* this method returns. If a Handler is used, and this method is called
* from a different thread than associated with the Handler's Looper,
* all callbacks will have been executed when this method returns as
* well. If however a Handler is used but this method is called from the
* same thread as associated with the Handler's Looper, there is no way
* to know.
* </p>
* <p>
* In practice this means that in most simple cases all callbacks will
* have completed when this method returns, but if you actually depend
* on this behavior, you should make certain this is indeed the case.
* </p>
* <p>
* See {@link Shell.Interactive} for further details on threading and
* handlers
* </p>
*
* @return True if wait complete, false if wait interrupted
*/
public boolean waitForIdle() {
if (Debug.getSanityChecksEnabledEffective() && Debug.onMainThread()) {
Debug.log(ShellOnMainThreadException.EXCEPTION_WAIT_IDLE);
throw new ShellOnMainThreadException(ShellOnMainThreadException.EXCEPTION_WAIT_IDLE);
}
if (isRunning()) {
synchronized (idleSync) {
while (!idle) {
try {
idleSync.wait();
} catch (InterruptedException e) {
return false;
}
}
}
if ((handler != null) &&
(handler.getLooper() != null) &&
(handler.getLooper() != Looper.myLooper())) {
// If the callbacks are posted to a different thread than
// this one, we can wait until all callbacks have called
// before returning. If we don't use a Handler at all, the
// callbacks are already called before we get here. If we do
// use a Handler but we use the same Looper, waiting here
// would actually block the callbacks from being called
synchronized (callbackSync) {
while (callbacks > 0) {
try {
callbackSync.wait();
} catch (InterruptedException e) {
return false;
}
}
}
}
}
return true;
}
/**
* Are we using a Handler to post callbacks ?
*
* @return Handler used ?
*/
public boolean hasHandler() {
return (handler != null);
}
}
}
|
apache-2.0
|
wanghuaisheng/WitsWay
|
Solutions/AppUtilities/Utilities/Thread/LockObject.cs
|
1682
|
#region License(Apache Version 2.0)
/******************************************
* Copyright ®2017-Now WangHuaiSheng.
* 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.
* Detail: https://github.com/WangHuaiSheng/WitsWay/LICENSE
* ***************************************/
#endregion
#region ChangeLog
/******************************************
* 2017-10-7 OutMan Create
*
* ***************************************/
#endregion
using System;
namespace WitsWay.Utilities.Thread
{
/// <summary>
/// 锁对象
/// </summary>
public class LockObject
{
private volatile bool _initing;
private readonly object _executeLock = new object();
/// <summary>
/// 锁定执行
/// </summary>
/// <param name="action">执行方法</param>
public void LockExecute(Action action)
{
if (!_initing)
{
lock (_executeLock)
{
if (_initing != true)
{
action();
}
_initing = true;
}
}
_initing = false;
}
}
}
|
apache-2.0
|
johannesbraun/clm_autocomplete
|
docs/solr-core/org/apache/solr/core/snapshots/package-frame.html
|
1881
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_102) on Wed Nov 02 19:53:02 IST 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>org.apache.solr.core.snapshots (Solr 6.3.0 API)</title>
<meta name="date" content="2016-11-02">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../../../org/apache/solr/core/snapshots/package-summary.html" target="classFrame">org.apache.solr.core.snapshots</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="CollectionSnapshotMetaData.html" title="class in org.apache.solr.core.snapshots" target="classFrame">CollectionSnapshotMetaData</a></li>
<li><a href="CollectionSnapshotMetaData.CoreSnapshotMetaData.html" title="class in org.apache.solr.core.snapshots" target="classFrame">CollectionSnapshotMetaData.CoreSnapshotMetaData</a></li>
<li><a href="SolrSnapshotManager.html" title="class in org.apache.solr.core.snapshots" target="classFrame">SolrSnapshotManager</a></li>
<li><a href="SolrSnapshotMetaDataManager.html" title="class in org.apache.solr.core.snapshots" target="classFrame">SolrSnapshotMetaDataManager</a></li>
<li><a href="SolrSnapshotMetaDataManager.SnapshotMetaData.html" title="class in org.apache.solr.core.snapshots" target="classFrame">SolrSnapshotMetaDataManager.SnapshotMetaData</a></li>
</ul>
<h2 title="Enums">Enums</h2>
<ul title="Enums">
<li><a href="CollectionSnapshotMetaData.SnapshotStatus.html" title="enum in org.apache.solr.core.snapshots" target="classFrame">CollectionSnapshotMetaData.SnapshotStatus</a></li>
</ul>
</div>
</body>
</html>
|
apache-2.0
|
Banbana/TianTianMovie
|
天天影视/天天影视/AppDelegate.h
|
408
|
//
// AppDelegate.h
// 天天影视
//
// Created by 卢恒 on 15/12/4.
// Copyright © 2015年 卢恒. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TuiJianViewController.h"
#import "FenLeiViewController.h"
#import "SouSuoViewController.h"
#import "SheZhiViewController.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
apache-2.0
|
michaelzzh/LF_PredictionIO
|
data/src/test/scala/org/apache/predictionio/data/api/SegmentIOAuthSpec.scala
|
6490
|
/*
* 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.predictionio.data.api
import akka.actor.{ActorSystem, Props}
import akka.testkit.TestProbe
import org.apache.predictionio.data.storage._
import org.joda.time.DateTime
import org.specs2.mutable.Specification
import spray.http.HttpHeaders.RawHeader
import spray.http.{ContentTypes, HttpEntity, HttpResponse}
import spray.httpx.RequestBuilding._
import sun.misc.BASE64Encoder
import scala.concurrent.{Future, ExecutionContext}
class SegmentIOAuthSpec extends Specification {
val system = ActorSystem("EventServiceSpecSystem")
sequential
isolated
val eventClient = new LEvents {
override def init(appId: Int, channelId: Option[Int]): Boolean = true
override def futureInsert(event: Event, appId: Int, channelId: Option[Int])
(implicit ec: ExecutionContext): Future[String] =
Future successful "event_id"
override def futureFind(
appId: Int, channelId: Option[Int], startTime: Option[DateTime],
untilTime: Option[DateTime], entityType: Option[String],
entityId: Option[String], eventNames: Option[Seq[String]],
targetEntityType: Option[Option[String]],
targetEntityId: Option[Option[String]], limit: Option[Int],
reversed: Option[Boolean])
(implicit ec: ExecutionContext): Future[Iterator[Event]] =
Future successful List.empty[Event].iterator
override def futureGet(eventId: String, appId: Int, channelId: Option[Int])
(implicit ec: ExecutionContext): Future[Option[Event]] =
Future successful None
override def futureGetEntityIds(appId: Int,channelId: Option[Int])(implicit ec: scala.concurrent.ExecutionContext): Future[Seq[String]] = {}
throw new NotImplementedError("get entityIds is not implemented for hbase")
}
def getEntityIds(appId: Int, channelId: Option[Int])(implicit ec: ExecutionContext): Seq[String] = {
throw new NotImplementedError("get entityIds is not implemented for hbase")
}
override def remove(appId: Int, channelId: Option[Int]): Boolean = true
override def futureDelete(eventId: String, appId: Int, channelId: Option[Int])
(implicit ec: ExecutionContext): Future[Boolean] =
Future successful true
override def close(): Unit = {}
}
val appId = 0
val accessKeysClient = new AccessKeys {
override def insert(k: AccessKey): Option[String] = null
override def getByAppid(appid: Int): Seq[AccessKey] = null
override def update(k: AccessKey): Unit = {}
override def delete(k: String): Unit = {}
override def getAll(): Seq[AccessKey] = null
override def get(k: String): Option[AccessKey] =
k match {
case "abc" ⇒ Some(AccessKey(k, appId, Seq.empty))
case _ ⇒ None
}
}
val channelsClient = Storage.getMetaDataChannels()
val eventServiceActor = system.actorOf(
Props(
new EventServiceActor(
eventClient,
accessKeysClient,
channelsClient,
EventServerConfig()
)
)
)
val base64Encoder = new BASE64Encoder
"Event Service" should {
"reject with CredentialsRejected with invalid credentials" in {
val accessKey = "abc123:"
val probe = TestProbe()(system)
probe.send(
eventServiceActor,
Post("/webhooks/segmentio.json")
.withHeaders(
List(
RawHeader("Authorization", s"Basic $accessKey")
)
)
)
probe.expectMsg(
HttpResponse(
401,
HttpEntity(
contentType = ContentTypes.`application/json`,
string = """{"message":"Invalid accessKey."}"""
)
)
)
success
}
"reject with CredentialsMissed without credentials" in {
val probe = TestProbe()(system)
probe.send(
eventServiceActor,
Post("/webhooks/segmentio.json")
)
probe.expectMsg(
HttpResponse(
401,
HttpEntity(
contentType = ContentTypes.`application/json`,
string = """{"message":"Missing accessKey."}"""
)
)
)
success
}
"process SegmentIO identity request properly" in {
val jsonReq =
"""
|{
| "anonymous_id": "507f191e810c19729de860ea",
| "channel": "browser",
| "context": {
| "ip": "8.8.8.8",
| "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5)"
| },
| "message_id": "022bb90c-bbac-11e4-8dfc-aa07a5b093db",
| "timestamp": "2015-02-23T22:28:55.387Z",
| "sent_at": "2015-02-23T22:28:55.111Z",
| "traits": {
| "name": "Peter Gibbons",
| "email": "peter@initech.com",
| "plan": "premium",
| "logins": 5
| },
| "type": "identify",
| "user_id": "97980cfea0067",
| "version": "2"
|}
""".stripMargin
val accessKey = "abc:"
val accessKeyEncoded = base64Encoder.encodeBuffer(accessKey.getBytes)
val probe = TestProbe()(system)
probe.send(
eventServiceActor,
Post(
"/webhooks/segmentio.json",
HttpEntity(ContentTypes.`application/json`, jsonReq.getBytes)
).withHeaders(
List(
RawHeader("Authorization", s"Basic $accessKeyEncoded")
)
)
)
probe.expectMsg(
HttpResponse(
201,
HttpEntity(
contentType = ContentTypes.`application/json`,
string = """{"eventId":"event_id"}"""
)
)
)
success
}
}
step(system.shutdown())
}
|
apache-2.0
|
tavultesoft/keymanweb
|
windows/src/ext/jedi/jvcl/jvcl/examples/JvChartDemo/BCB/StatClasses.h
|
1200
|
//---------------------------------------------------------------------------
#ifndef StatClassesH
#define StatClassesH
#include <vector>
using namespace std;
class TStatArray
{
protected:
//bool FFirst;
bool FGrows; // false=rolling average (circular buffer mode), true=average or sd of any number of samples (array grows without limit)
vector<bool> FValues;
int FLength; // Array absolute size (may still be no data even if this is >0)
int FIndex; // Where will the next sample be stored into the array?
int FCount; // How many valid samples are in the array right now?
void SetLen(int aLength);
public:
void AddValue(double aValue);
double Average();
double StandardDeviation();
__property bool Grows = {read=FGrows, write=FGrows}; // false=rolling average, true=average ALL samples (grows to fit)
__property int Length = {read=FLength, write=SetLen};
__property int Count = {read=FCount};
//__property bool First = {read=FFirst};
void Reset(); // Clear everything!
TStatArray();
TStatArray(int initialLength);
~TStatArray();
};
//---------------------------------------------------------------------------
#endif
|
apache-2.0
|
maheshika/carbon4-kernel
|
core/org.wso2.carbon.ndatasource.core/src/main/java/org/wso2/carbon/ndatasource/core/services/WSDataSourceMetaInfo.java
|
3828
|
/**
* Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.ndatasource.core.services;
import org.w3c.dom.Element;
import org.wso2.carbon.ndatasource.core.DataSourceMetaInfo;
import org.wso2.carbon.ndatasource.core.JNDIConfig;
import org.wso2.carbon.ndatasource.core.DataSourceMetaInfo.DataSourceDefinition;
import org.wso2.carbon.ndatasource.core.utils.DataSourceUtils;
/**
* This is a bean class to contain the DataSourceMetaInfo in a web services context.
*/
public class WSDataSourceMetaInfo {
private String name;
private String description;
private JNDIConfig jndiConfig;
private boolean system;
private WSDataSourceDefinition definition;
public WSDataSourceMetaInfo() {
}
public WSDataSourceMetaInfo(DataSourceMetaInfo metaInfo) {
this.name = metaInfo.getName();
this.description = metaInfo.getDescription();
this.jndiConfig = metaInfo.getJndiConfig();
this.system = metaInfo.isSystem();
this.definition = new WSDataSourceDefinition(metaInfo.getDefinition());
}
public DataSourceMetaInfo extractDataSourceMetaInfo() {
DataSourceMetaInfo dsmInfo = new DataSourceMetaInfo();
dsmInfo.setName(this.getName());
dsmInfo.setDescription(this.getDescription());
dsmInfo.setSystem(this.isSystem());
dsmInfo.setJndiConfig(this.getJndiConfig());
dsmInfo.setDefinition(this.getDefinition().extractDataSourceDefinition());
return dsmInfo;
}
public boolean isSystem() {
return system;
}
public void setSystem(boolean system) {
this.system = system;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public JNDIConfig getJndiConfig() {
return jndiConfig;
}
public void setJndiConfig(JNDIConfig jndiConfig) {
this.jndiConfig = jndiConfig;
}
public WSDataSourceDefinition getDefinition() {
return definition;
}
public void setDefinition(WSDataSourceDefinition definition) {
this.definition = definition;
}
/**
* This is a bean class to contain the DataSourceDefinition in a web services context.
*/
public static class WSDataSourceDefinition {
private String type;
private String dsXMLConfiguration;
public WSDataSourceDefinition() {
}
public WSDataSourceDefinition(DataSourceDefinition dsDef) {
this.type = dsDef.getType();
this.dsXMLConfiguration = DataSourceUtils.elementToString((Element)
dsDef.getDsXMLConfiguration());
}
public DataSourceDefinition extractDataSourceDefinition() {
DataSourceDefinition dsDef = new DataSourceDefinition();
dsDef.setType(this.getType());
dsDef.setDsXMLConfiguration(DataSourceUtils.stringToElement(
this.getDsXMLConfiguration()));
return dsDef;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDsXMLConfiguration() {
return dsXMLConfiguration;
}
public void setDsXMLConfiguration(String dsXMLConfiguration) {
this.dsXMLConfiguration = dsXMLConfiguration;
}
}
}
|
apache-2.0
|
thiagogarbazza/exemplos
|
example-xml-with-sax/src/test/java/com/github/thiagogarbazza/examples/xmlwithsax/ResourceGetter.java
|
621
|
package com.github.thiagogarbazza.examples.xmlwithsax;
import java.io.File;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
class ResourceGetter {
static File resourceFile(final String filePath) {
final URL url = Thread.currentThread().getContextClassLoader().getResource(filePath);
try {
return new File(url.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
static InputStream resourceInputStream(final String filePath) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
}
}
|
apache-2.0
|
naver/hubblemon
|
manage.py
|
252
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hubblemon.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
apache-2.0
|
muffato/ensembl
|
misc-scripts/xref_mapping/XrefMapper/Methods/ExonerateGappedBest1_55_perc_id.pm
|
1101
|
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2019] EMBL-European Bioinformatics Institute
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.
=cut
package XrefMapper::Methods::ExonerateGappedBest1_55_perc_id;
use XrefMapper::Methods::ExonerateBasic;
use vars '@ISA';
@ISA = qw{XrefMapper::Methods::ExonerateBasic};
sub options {
return ('--gappedextension FALSE', '--model', 'affine:local', '--subopt', 'no', '--bestn', '1');
}
sub query_identity_threshold {
return 55;
}
sub target_identity_threshold {
return 55;
}
1;
|
apache-2.0
|
PhaedrusTheGreek/transform_vis
|
public/options_template.html
|
1307
|
<div ng-controller="TransformVisEditorController as paramCtrl" style="width: 100%;">
<div class="form-group">
<label> Index Pattern </label>
<select name="indexPattern" class="form-control ng-pristine ng-untouched"
ng-model="editorState.params.indexpattern" required
ng-options="option.id as option.attributes.title for option in indexPatternOptions"></select>
</div>
<div class="form-group">
<label> Query DSL </label>
<div ui-ace="{ onLoad: aceLoaded, mode: 'json' }" ng-model="editorState.params.querydsl"
class="template-editor form-control ng-pristine ng-untouched ng-valid ng-scope ace_editor ace-tm"/>
</div>
<div ng-if="options.allow_unsafe" class="form-group">
<label> Javascript </label>
<div ui-ace="{ onLoad: aceLoaded, mode: 'javascript' }" ng-model="editorState.params.meta"
class="template-editor form-control ng-pristine ng-untouched ng-valid ng-scope ace_editor ace-tm"/>
</div>
<div class="form-group">
<label> Template </label>
<div ui-ace="{ onLoad: aceLoaded, mode: 'html' }" ng-model="editorState.params.formula"
class="template-editor form-control ng-pristine ng-untouched ng-valid ng-scope ace_editor ace-tm"/>
</div>
</div>
|
apache-2.0
|
sonu283304/onos
|
core/store/dist/src/main/java/org/onosproject/store/cluster/messaging/impl/ClusterCommunicationManager.java
|
13581
|
/*
* Copyright 2014-2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.store.cluster.messaging.impl;
import com.google.common.base.Throwables;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onlab.util.Tools;
import org.onosproject.cluster.ClusterService;
import org.onosproject.cluster.ControllerNode;
import org.onosproject.cluster.NodeId;
import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
import org.onosproject.store.cluster.messaging.ClusterMessage;
import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
import org.onosproject.store.cluster.messaging.Endpoint;
import org.onosproject.store.cluster.messaging.MessageSubject;
import org.onosproject.store.cluster.messaging.MessagingService;
import org.onosproject.utils.MeteringAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
@Component(immediate = true)
@Service
public class ClusterCommunicationManager
implements ClusterCommunicationService {
private final Logger log = LoggerFactory.getLogger(getClass());
private final MeteringAgent subjectMeteringAgent = new MeteringAgent(PRIMITIVE_NAME, SUBJECT_PREFIX, true);
private final MeteringAgent endpointMeteringAgent = new MeteringAgent(PRIMITIVE_NAME, ENDPOINT_PREFIX, true);
private static final String PRIMITIVE_NAME = "clusterCommunication";
private static final String SUBJECT_PREFIX = "subject";
private static final String ENDPOINT_PREFIX = "endpoint";
private static final String SERIALIZING = "serialization";
private static final String DESERIALIZING = "deserialization";
private static final String NODE_PREFIX = "node:";
private static final String ROUND_TRIP_SUFFIX = ".rtt";
private static final String ONE_WAY_SUFFIX = ".oneway";
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
private ClusterService clusterService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected MessagingService messagingService;
private NodeId localNodeId;
@Activate
public void activate() {
localNodeId = clusterService.getLocalNode().id();
log.info("Started");
}
@Deactivate
public void deactivate() {
log.info("Stopped");
}
@Override
public <M> void broadcast(M message,
MessageSubject subject,
Function<M, byte[]> encoder) {
multicast(message,
subject,
encoder,
clusterService.getNodes()
.stream()
.filter(node -> !Objects.equal(node, clusterService.getLocalNode()))
.map(ControllerNode::id)
.collect(Collectors.toSet()));
}
@Override
public <M> void broadcastIncludeSelf(M message,
MessageSubject subject,
Function<M, byte[]> encoder) {
multicast(message,
subject,
encoder,
clusterService.getNodes()
.stream()
.map(ControllerNode::id)
.collect(Collectors.toSet()));
}
@Override
public <M> CompletableFuture<Void> unicast(M message,
MessageSubject subject,
Function<M, byte[]> encoder,
NodeId toNodeId) {
try {
byte[] payload = new ClusterMessage(
localNodeId,
subject,
timeFunction(encoder, subjectMeteringAgent, SERIALIZING).apply(message)
).getBytes();
return doUnicast(subject, payload, toNodeId);
} catch (Exception e) {
return Tools.exceptionalFuture(e);
}
}
@Override
public <M> void multicast(M message,
MessageSubject subject,
Function<M, byte[]> encoder,
Set<NodeId> nodes) {
byte[] payload = new ClusterMessage(
localNodeId,
subject,
timeFunction(encoder, subjectMeteringAgent, SERIALIZING).apply(message))
.getBytes();
nodes.forEach(nodeId -> doUnicast(subject, payload, nodeId));
}
@Override
public <M, R> CompletableFuture<R> sendAndReceive(M message,
MessageSubject subject,
Function<M, byte[]> encoder,
Function<byte[], R> decoder,
NodeId toNodeId) {
try {
ClusterMessage envelope = new ClusterMessage(
clusterService.getLocalNode().id(),
subject,
timeFunction(encoder, subjectMeteringAgent, SERIALIZING).
apply(message));
return sendAndReceive(subject, envelope.getBytes(), toNodeId).
thenApply(bytes -> timeFunction(decoder, subjectMeteringAgent, DESERIALIZING).apply(bytes));
} catch (Exception e) {
return Tools.exceptionalFuture(e);
}
}
private CompletableFuture<Void> doUnicast(MessageSubject subject, byte[] payload, NodeId toNodeId) {
ControllerNode node = clusterService.getNode(toNodeId);
checkArgument(node != null, "Unknown nodeId: %s", toNodeId);
Endpoint nodeEp = new Endpoint(node.ip(), node.tcpPort());
MeteringAgent.Context context = subjectMeteringAgent.startTimer(subject.toString() + ONE_WAY_SUFFIX);
return messagingService.sendAsync(nodeEp, subject.value(), payload).whenComplete((r, e) -> context.stop(e));
}
private CompletableFuture<byte[]> sendAndReceive(MessageSubject subject, byte[] payload, NodeId toNodeId) {
ControllerNode node = clusterService.getNode(toNodeId);
checkArgument(node != null, "Unknown nodeId: %s", toNodeId);
Endpoint nodeEp = new Endpoint(node.ip(), node.tcpPort());
MeteringAgent.Context epContext = endpointMeteringAgent.
startTimer(NODE_PREFIX + toNodeId.toString() + ROUND_TRIP_SUFFIX);
MeteringAgent.Context subjectContext = subjectMeteringAgent.
startTimer(subject.toString() + ROUND_TRIP_SUFFIX);
return messagingService.sendAndReceive(nodeEp, subject.value(), payload).
whenComplete((bytes, throwable) -> {
subjectContext.stop(throwable);
epContext.stop(throwable);
});
}
@Override
public void addSubscriber(MessageSubject subject,
ClusterMessageHandler subscriber,
ExecutorService executor) {
messagingService.registerHandler(subject.value(),
new InternalClusterMessageHandler(subscriber),
executor);
}
@Override
public void removeSubscriber(MessageSubject subject) {
messagingService.unregisterHandler(subject.value());
}
@Override
public <M, R> void addSubscriber(MessageSubject subject,
Function<byte[], M> decoder,
Function<M, R> handler,
Function<R, byte[]> encoder,
Executor executor) {
messagingService.registerHandler(subject.value(),
new InternalMessageResponder<M, R>(decoder, encoder, m -> {
CompletableFuture<R> responseFuture = new CompletableFuture<>();
executor.execute(() -> {
try {
responseFuture.complete(handler.apply(m));
} catch (Exception e) {
responseFuture.completeExceptionally(e);
}
});
return responseFuture;
}));
}
@Override
public <M, R> void addSubscriber(MessageSubject subject,
Function<byte[], M> decoder,
Function<M, CompletableFuture<R>> handler,
Function<R, byte[]> encoder) {
messagingService.registerHandler(subject.value(),
new InternalMessageResponder<>(decoder, encoder, handler));
}
@Override
public <M> void addSubscriber(MessageSubject subject,
Function<byte[], M> decoder,
Consumer<M> handler,
Executor executor) {
messagingService.registerHandler(subject.value(),
new InternalMessageConsumer<>(decoder, handler),
executor);
}
/**
* Performs the timed function, returning the value it would while timing the operation.
*
* @param timedFunction the function to be timed
* @param meter the metering agent to be used to time the function
* @param opName the opname to be used when starting the meter
* @param <A> The param type of the function
* @param <B> The return type of the function
* @return the value returned by the timed function
*/
private <A, B> Function<A, B> timeFunction(Function<A, B> timedFunction,
MeteringAgent meter, String opName) {
checkNotNull(timedFunction);
checkNotNull(meter);
checkNotNull(opName);
return new Function<A, B>() {
@Override
public B apply(A a) {
final MeteringAgent.Context context = meter.startTimer(opName);
B result = null;
try {
result = timedFunction.apply(a);
context.stop(null);
return result;
} catch (Exception e) {
context.stop(e);
Throwables.propagate(e);
return null;
}
}
};
}
private class InternalClusterMessageHandler implements BiFunction<Endpoint, byte[], byte[]> {
private ClusterMessageHandler handler;
public InternalClusterMessageHandler(ClusterMessageHandler handler) {
this.handler = handler;
}
@Override
public byte[] apply(Endpoint sender, byte[] bytes) {
ClusterMessage message = ClusterMessage.fromBytes(bytes);
handler.handle(message);
return message.response();
}
}
private class InternalMessageResponder<M, R> implements BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> {
private final Function<byte[], M> decoder;
private final Function<R, byte[]> encoder;
private final Function<M, CompletableFuture<R>> handler;
public InternalMessageResponder(Function<byte[], M> decoder,
Function<R, byte[]> encoder,
Function<M, CompletableFuture<R>> handler) {
this.decoder = decoder;
this.encoder = encoder;
this.handler = handler;
}
@Override
public CompletableFuture<byte[]> apply(Endpoint sender, byte[] bytes) {
return handler.apply(timeFunction(decoder, subjectMeteringAgent, DESERIALIZING).
apply(ClusterMessage.fromBytes(bytes).payload())).
thenApply(m -> timeFunction(encoder, subjectMeteringAgent, SERIALIZING).apply(m));
}
}
private class InternalMessageConsumer<M> implements BiConsumer<Endpoint, byte[]> {
private final Function<byte[], M> decoder;
private final Consumer<M> consumer;
public InternalMessageConsumer(Function<byte[], M> decoder, Consumer<M> consumer) {
this.decoder = decoder;
this.consumer = consumer;
}
@Override
public void accept(Endpoint sender, byte[] bytes) {
consumer.accept(timeFunction(decoder, subjectMeteringAgent, DESERIALIZING).
apply(ClusterMessage.fromBytes(bytes).payload()));
}
}
}
|
apache-2.0
|
flitte/Gaffer
|
tinkerpop/src/main/java/gaffer/gafferpop/GafferPopEdge.java
|
4463
|
/*
* Copyright 2016 Crown Copyright
*
* 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 gaffer.gafferpop;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A <code>GafferPopEdge</code> is an {@link GafferPopElement} and {link Edge}.
* <p>
* inVertex() and outVertex() methods are not supported as it is possible for a
* edge to have multiple in vertices and multiple out vertices (due to the mapping
* to a TinkerPop vertex to Gaffer {@link gaffer.data.element.Entity}.
* Use vertices(Direction) instead.
* </p>
* <p>
* An ID is required to be an {@link EdgeId} which contains the source and
* destination of an edge.
* </p>
*/
public final class GafferPopEdge extends GafferPopElement implements Edge {
private Map<String, Property> properties;
public GafferPopEdge(final String label, final Object source, final Object dest, final GafferPopGraph graph) {
super(label, new EdgeId(source, dest), graph);
}
@Override
public <V> Property<V> property(final String key, final V value) {
if (isReadOnly()) {
throw new UnsupportedOperationException("Updates are not supported");
}
ElementHelper.validateProperty(key, value);
final Property<V> newProperty = new GafferPopProperty<>(this, key, value);
if (null == this.properties) {
this.properties = new HashMap<>();
}
this.properties.put(key, newProperty);
return newProperty;
}
@Override
public <V> Property<V> property(final String key) {
return null == this.properties ? Property.<V>empty() : this.properties.getOrDefault(key, Property.<V>empty());
}
@Override
public <V> Iterator<Property<V>> properties(final String... propertyKeys) {
if (null == this.properties) {
return Collections.emptyIterator();
}
if (propertyKeys.length == 1) {
final Property<V> property = this.properties.get(propertyKeys[0]);
return null == property ? Collections.emptyIterator() : IteratorUtils.of(property);
} else {
return (Iterator) this.properties.entrySet()
.stream()
.filter(entry -> ElementHelper.keyExists(entry.getKey(), propertyKeys))
.map(entry -> entry.getValue()).collect(Collectors.toList())
.iterator();
}
}
@Override
public Iterator<Vertex> vertices(final Direction direction) {
if (Direction.IN.equals(direction)) {
return graph().vertices(id().getDest());
}
if (Direction.OUT.equals(direction)) {
return graph().vertices(id().getSource());
}
return graph().vertices(id().getSource(), id().getDest());
}
@Override
public Set<String> keys() {
return null == this.properties ? Collections.emptySet() : this.properties.keySet();
}
@Override
public EdgeId id() {
return (EdgeId) super.id();
}
@Override
public String toString() {
return "e[" + id().getSource() + "-" + label + "->" + id().getDest() + "]";
}
@Override
public Vertex outVertex() {
throw new UnsupportedOperationException("Use 'vertices(Direction)' instead - it may return multiple vertices");
}
@Override
public Vertex inVertex() {
throw new UnsupportedOperationException("Use 'vertices(Direction)' instead - it may return multiple vertices");
}
}
|
apache-2.0
|
sdgdsffdsfff/presto
|
presto-spi/src/main/java/com/facebook/presto/spi/Range.java
|
6940
|
/*
* 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.facebook.presto.spi;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
/**
* A Range of values across the continuous space defined by the types of the Markers
*/
public final class Range
{
private final Marker low;
private final Marker high;
@JsonCreator
public Range(
@JsonProperty("low") Marker low,
@JsonProperty("high") Marker high)
{
Objects.requireNonNull(low, "value is null");
Objects.requireNonNull(high, "value is null");
if (!low.getType().equals(high.getType())) {
throw new IllegalArgumentException(String.format("Marker types do not match: %s vs %s", low.getType(), high.getType()));
}
if (low.isUpperUnbounded()) {
throw new IllegalArgumentException("low cannot be upper unbounded");
}
if (high.isLowerUnbounded()) {
throw new IllegalArgumentException("high cannot be lower unbounded");
}
if (low.compareTo(high) > 0) {
throw new IllegalArgumentException("low must be less than or equal to high");
}
this.low = low;
this.high = high;
}
public static Range all(Class<?> type)
{
return new Range(Marker.lowerUnbounded(type), Marker.upperUnbounded(type));
}
public static Range greaterThan(Comparable<?> low)
{
return new Range(Marker.above(low), Marker.upperUnbounded(low.getClass()));
}
public static Range greaterThanOrEqual(Comparable<?> low)
{
return new Range(Marker.exactly(low), Marker.upperUnbounded(low.getClass()));
}
public static Range lessThan(Comparable<?> high)
{
return new Range(Marker.lowerUnbounded(high.getClass()), Marker.below(high));
}
public static Range lessThanOrEqual(Comparable<?> high)
{
return new Range(Marker.lowerUnbounded(high.getClass()), Marker.exactly(high));
}
public static Range equal(Comparable<?> value)
{
return new Range(Marker.exactly(value), Marker.exactly(value));
}
public static Range range(Comparable<?> low, boolean lowInclusive, Comparable<?> high, boolean highInclusive)
{
Marker lowMarker = lowInclusive ? Marker.exactly(low) : Marker.above(low);
Marker highMarker = highInclusive ? Marker.exactly(high) : Marker.below(high);
return new Range(lowMarker, highMarker);
}
@JsonIgnore
public Class<?> getType()
{
return low.getType();
}
@JsonProperty
public Marker getLow()
{
return low;
}
@JsonProperty
public Marker getHigh()
{
return high;
}
@JsonIgnore
public boolean isSingleValue()
{
return !low.isLowerUnbounded() &&
!high.isUpperUnbounded() &&
low.getBound() == Marker.Bound.EXACTLY &&
high.getBound() == Marker.Bound.EXACTLY &&
low.getValue() == high.getValue();
}
@JsonIgnore
public Comparable<?> getSingleValue()
{
if (!isSingleValue()) {
throw new IllegalStateException("Range does not have just a single value");
}
return low.getValue();
}
@JsonIgnore
public boolean isAll()
{
return low.isLowerUnbounded() && high.isUpperUnbounded();
}
public boolean includes(Marker marker)
{
Objects.requireNonNull(marker, "marker is null");
checkTypeCompatibility(marker);
return low.compareTo(marker) <= 0 && high.compareTo(marker) >= 0;
}
public boolean contains(Range other)
{
checkTypeCompatibility(other);
return this.getLow().compareTo(other.getLow()) <= 0 &&
this.getHigh().compareTo(other.getHigh()) >= 0;
}
public Range span(Range other)
{
checkTypeCompatibility(other);
Marker lowMarker = Marker.min(low, other.getLow());
Marker highMarker = Marker.max(high, other.getHigh());
return new Range(lowMarker, highMarker);
}
public boolean overlaps(Range other)
{
checkTypeCompatibility(other);
return this.getLow().compareTo(other.getHigh()) <= 0 &&
other.getLow().compareTo(this.getHigh()) <= 0;
}
public Range intersect(Range other)
{
checkTypeCompatibility(other);
if (!this.overlaps(other)) {
throw new IllegalArgumentException("Cannot intersect non-overlapping ranges");
}
Marker lowMarker = Marker.max(low, other.getLow());
Marker highMarker = Marker.min(high, other.getHigh());
return new Range(lowMarker, highMarker);
}
private void checkTypeCompatibility(Range range)
{
if (!getType().equals(range.getType())) {
throw new IllegalArgumentException(String.format("Mismatched Range types: %s vs %s", getType(), range.getType()));
}
}
private void checkTypeCompatibility(Marker marker)
{
if (!getType().equals(marker.getType())) {
throw new IllegalArgumentException(String.format("Marker of %s does not match Range of %s", marker.getType(), getType()));
}
}
@Override
public int hashCode()
{
return Objects.hash(low, high);
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Range other = (Range) obj;
return Objects.equals(this.low, other.low) &&
Objects.equals(this.high, other.high);
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
if (isSingleValue()) {
sb.append('[').append(low.getValue()).append(']');
}
else {
sb.append((low.getBound() == Marker.Bound.EXACTLY) ? '[' : '(');
sb.append(low.isLowerUnbounded() ? "<min>" : low.getValue());
sb.append(", ");
sb.append(high.isUpperUnbounded() ? "<max>" : high.getValue());
sb.append((high.getBound() == Marker.Bound.EXACTLY) ? ']' : ')');
}
return sb.toString();
}
}
|
apache-2.0
|
shaoxuan-wang/flink
|
flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/calls/RandCallGen.scala
|
1994
|
/*
* 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.flink.table.codegen.calls
import org.apache.flink.table.codegen.{CodeGeneratorContext, GeneratedExpression}
import org.apache.flink.table.codegen.GenerateUtils.generateCallIfArgsNotNull
import org.apache.flink.table.types.logical.{DoubleType, IntType, LogicalType}
/**
* Generates a random function call.
* Supports: RAND([seed]) and RAND_INTEGER([seed, ] bound)
*/
class RandCallGen(isRandInteger: Boolean, hasSeed: Boolean) extends CallGenerator {
override def generate(
ctx: CodeGeneratorContext,
operands: Seq[GeneratedExpression],
returnType: LogicalType): GeneratedExpression = {
val randField = if (hasSeed) {
if (operands.head.literal) {
ctx.addReusableRandom(Some(operands.head))
} else {
s"(new java.util.Random(${operands.head.resultTerm}))"
}
} else {
ctx.addReusableRandom(None)
}
if (isRandInteger) {
generateCallIfArgsNotNull(ctx, new IntType(), operands) { terms =>
s"$randField.nextInt(${terms.last})"
}
} else {
generateCallIfArgsNotNull(ctx, new DoubleType(), operands) { _ =>
s"$randField.nextDouble()"
}
}
}
}
|
apache-2.0
|
SPECURE/ratel-nettest
|
RMBTAndroid/src/at/alladin/rmbt/android/util/CheckIpTask.java
|
7069
|
/*******************************************************************************
* Copyright 2013-2015 alladin-IT GmbH
*
* 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 at.alladin.rmbt.android.util;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
import at.alladin.rmbt.android.adapter.result.OnCompleteListener;
import at.alladin.rmbt.android.main.RMBTMainActivity;
import at.alladin.rmbt.android.util.net.NetworkInfoCollector;
public class CheckIpTask extends AsyncTask<Void, Void, JSONArray>
{
private final RMBTMainActivity activity;
private JSONArray newsList;
String lastIp;
InetAddress privateIpv6;
InetAddress privateIpv4;
String publicIpv4;
String publicIpv6;
boolean needsRetry = false;
ControlServerConnection serverConn;
private OnCompleteListener onCompleteListener;
/**
*
*/
private static final String DEBUG_TAG = "CheckIpTask";
public CheckIpTask(final RMBTMainActivity activity)
{
this.activity = activity;
}
/**
*
* @param listener
*/
public void setOnCompleteListener(OnCompleteListener listener) {
this.onCompleteListener = listener;
}
@Override
protected JSONArray doInBackground(final Void... params)
{
needsRetry = false;
serverConn = new ControlServerConnection(activity);
try {
Socket s = new Socket();
InetSocketAddress addr = new InetSocketAddress(ConfigHelper.getCachedControlServerNameIpv4(activity.getApplicationContext()),
ConfigHelper.getControlServerPort(activity.getApplicationContext()));
s.connect(addr, 5000);
privateIpv4 = s.getLocalAddress();
s.close();
}
catch (Exception e) {
e.printStackTrace();
}
try {
Socket s = new Socket();
InetSocketAddress addr = new InetSocketAddress(ConfigHelper.getCachedControlServerNameIpv6(activity.getApplicationContext()),
ConfigHelper.getControlServerPort(activity.getApplicationContext()));
s.connect(addr, 5000);
privateIpv6 = s.getLocalAddress();
s.close();
}
catch (SocketTimeoutException e) {
e.printStackTrace();
needsRetry = ConfigHelper.isRetryRequiredOnIpv6SocketTimeout(activity);
}
catch (Exception e) {
needsRetry = false;
e.printStackTrace();
}
newsList = new JSONArray();
if (privateIpv4 != null) {
JSONArray response = serverConn.requestIp(false);
if (response != null && response.length() >= 1) {
newsList.put(response.opt(0));
}
}
else {
Log.d(DEBUG_TAG, "no private ipv4 found");
}
if (privateIpv6 != null) {
JSONArray response = serverConn.requestIp(true);
if (response != null && response.length() >= 1) {
newsList.put(response.opt(0));
}
}
else {
Log.d(DEBUG_TAG, "no private ipv6 found");
}
return newsList;
}
@Override
protected void onCancelled()
{
if (serverConn != null)
{
serverConn.unload();
serverConn = null;
}
}
@Override
protected void onPostExecute(final JSONArray newsList)
{
try {
Log.d(DEBUG_TAG, "News: " + newsList);
int ipv = 4;
if (newsList != null && newsList.length() > 0 && !serverConn.hasError()) {
for (int i = 0; i < newsList.length(); i++) {
if (!isCancelled() && !Thread.interrupted()) {
try
{
final JSONObject newsItem = newsList.getJSONObject(i);
if (newsItem.has("v"))
{
ipv = newsItem.getInt("v");
if (ipv == 6) {
try {
publicIpv6 = newsItem.getString("ip");
} catch (Exception e) {
e.printStackTrace();
}
}
else {
try {
publicIpv4 = newsItem.getString("ip");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
catch (final JSONException e)
{
e.printStackTrace();
}
}
}
if (onCompleteListener != null && !needsRetry) {
onCompleteListener.onComplete(NetworkInfoCollector.FLAG_PRIVATE_IPV6, privateIpv6);
onCompleteListener.onComplete(NetworkInfoCollector.FLAG_PRIVATE_IPV4, privateIpv4);
onCompleteListener.onComplete(NetworkInfoCollector.FLAG_IPV4, publicIpv4);
onCompleteListener.onComplete(NetworkInfoCollector.FLAG_IPV6, publicIpv6);
onCompleteListener.onComplete(NetworkInfoCollector.FLAG_IP_TASK_COMPLETED, null);
}
else if (onCompleteListener != null) {
onCompleteListener.onComplete(OnCompleteListener.ERROR, NetworkInfoCollector.FLAG_IP_TASK_NEEDS_RETRY);
}
}
else {
ConfigHelper.setLastIp(activity.getApplicationContext(), null);
if (onCompleteListener != null) {
onCompleteListener.onComplete(OnCompleteListener.ERROR, null);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
// finally {
// if (onCompleteListener != null) {
// onCompleteListener.onComplete(NetworkInfoCollector.FLAG_IP_TASK_COMPLETED, null);
// }
// }
}
}
|
apache-2.0
|
thymol/thymol.js
|
src/main/webapp/WEB-INF/templates/thymol/debug/debug-data.js
|
41
|
thDebug = true;
thAllowNullText = false;
|
apache-2.0
|
nortal/araneaframework
|
src/org/araneaframework/uilib/form/constraint/OptionalConstraint.java
|
2059
|
/*
* Copyright 2006 Webmedia Group Ltd.
*
* 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.araneaframework.uilib.form.constraint;
import org.araneaframework.Environment;
import org.araneaframework.uilib.form.Constraint;
/**
* Optional <code>Constraint</code> only applies when constrained field has some real value. This class is a wrapper
* around the <code>Constraint</code>, and the wrapped <code>Constraint</code> will be applied only if the constrained
* field has been read from the request.
*
* @author Jevgeni Kabanov (ekabanov@araneaframework.org)
*/
public class OptionalConstraint extends BaseGenericFieldConstraint {
private Constraint constraint;
/**
* Creates a new <code>OptionalConstraint</code> wrapper for given <code>constraint</code>. The latter will be
* validated only if the field has a value.
*
* @param constraint The constraint to use for validation.
*/
public OptionalConstraint(Constraint constraint) {
this.constraint = constraint;
}
@Override
protected void validateConstraint() throws Exception {
if (getValue() != null) {
this.constraint.validate();
addErrors(this.constraint.getErrors());
this.constraint.clearErrors();
}
}
@Override
public void setCustomErrorMessage(String customErrorMessage) {
this.constraint.setCustomErrorMessage(customErrorMessage);
}
@Override
public void setEnvironment(Environment environment) {
super.setEnvironment(environment);
this.constraint.setEnvironment(environment);
}
}
|
apache-2.0
|
mkshimod/digits
|
app/lib/collections/Contacts.js
|
1938
|
contacts = "Contacts"; // avoid typos, this string occurs many times.
Contacts = new Mongo.Collection(contacts);
Meteor.methods({
/**
* Invoked by AutoForm to add a new Contacts record.
* @param doc The Contacts document.
*/
addContacts: function(doc) {
check(doc, Contacts.simpleSchema());
Contacts.insert(doc);
},
/**
*
* Invoked by AutoForm to update a Contacts record.
* @param doc The Contacts document.
* @param docID It's ID.
*/
editContacts: function(doc, docID) {
check(doc, Contacts.simpleSchema());
Contacts.update({_id: docID}, doc);
},
deleteContacts: function(docID) {
Contacts.remove(docID);
}
});
// Publish the entire Collection. Subscription performed in the router.
if (Meteor.isServer) {
Meteor.publish(contacts, function () {
return Contacts.find();
});
}
/**
* Create the schema for Contacts
* See: https://github.com/aldeed/meteor-autoform#common-questions
* See: https://github.com/aldeed/meteor-autoform#affieldinput
*/
Contacts.attachSchema(new SimpleSchema({
firstName: {
label: "First Name",
type: String,
optional: false,
max: 20,
autoform: {
group: contacts,
placeholder: "John"
}
},
lastName: {
label: "Last Name",
type: String,
optional: false,
max: 20,
autoform: {
group: contacts,
placeholder: "Doe"
}
},
address: {
label: "Address",
type: String,
optional: false,
max: 50,
autoform: {
group: contacts,
placeholder: "1234 Imaginary Ln."
}
},
phone: {
label: "Phone Number",
type: String,
optional: false,
max: 15,
autoform: {
group: contacts,
placeholder: "(555) 555-5555"
}
},
email: {
label: "Email Address",
type: String,
optional: false,
max: 20,
autoform: {
group: contacts,
placeholder: "johndoe@example.com"
}
}
}));
|
apache-2.0
|
dfalcone/soomla-wp-core
|
soomla-wp-core/soomla-wp-core-interface/events/AppToForegroundEvent.cs
|
877
|
/// Copyright (C) 2012-2015 Soomla 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.
using System;
namespace SoomlaWpCore.events
{
public class AppToForegroundEvent : SoomlaEvent
{
public AppToForegroundEvent() : this(null) { }
public AppToForegroundEvent(Object sender) : base(sender) { }
}
}
|
apache-2.0
|
arturkirakosian/java
|
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/GroupHelper.java
|
1203
|
package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import ru.stqa.pft.addressbook.model.GroupData;
/**
* Created by Artur on 17.04.16.
*/
public class GroupHelper extends HelperBase {
public GroupHelper(WebDriver wd) {
super(wd);
}
public void returnToGroupPage() {
click(By.linkText("group page"));
}
public void submitGroupCreation() {
click(By.name("submit"));
}
public void fillGroupForm(GroupData groupData) {
type(By.name("group_name"), groupData.getName());
type(By.name("group_header"), groupData.getHeader());
type(By.name("group_footer"), groupData.getFooter());
}
public void initGroupCreation() {
click(By.name("new"));
}
public void deletSelectedGroups() {
click(By.xpath("//div[@id='content']/form/input[5]"));
}
public void selectGroup() {
if (!wd.findElement(By.name("selected[]")).isSelected()) {
click(By.name("selected[]"));
}
}
public void initGroupModification() {
click(By.name("edit"));
}
public void submitGroupModification() {
click(By.name("update"));
}
}
|
apache-2.0
|
jrbn/trident
|
src/trident/kb/permsorter.cpp
|
39131
|
/*
* Copyright 2017 Jacopo Urbani
*
* 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.
**/
#include <trident/kb/permsorter.h>
#include <kognac/utils.h>
#include <kognac/compressor.h>
#include <boost/chrono.hpp>
#include <boost/log/trivial.hpp>
#include <boost/thread.hpp>
#include <tbb/parallel_sort.h>
#include <tbb/task_scheduler_init.h>
#include <thread>
#include <functional>
namespace timens = boost::chrono;
struct __PermSorter_sorter {
char *rawinput;
const int o1;
const int o2;
const int o3;
__PermSorter_sorter(char *rawinput, const int o1, const int o2,
const int o3) : rawinput(rawinput), o1(o1), o2(o2), o3(o3) {
}
bool operator()(long a, long b) const {
char *start_a = rawinput + a * 15;
char *start_b = rawinput + b * 15;
int ret = memcmp(start_a + o1, start_b + o1, 5);
if (ret < 0) {
return true;
} else if (ret == 0) {
ret = memcmp(start_a + o2, start_b + o2, 5);
if (ret < 0) {
return true;
} else if (ret == 0) {
ret = memcmp(start_a + o3, start_b + o3, 5);
return ret < 0;
}
}
return false;
}
};
void PermSorter::sortPermutation_old(char *rawinput,
std::vector<long> *idx,
int sorter) {
int o1 = 0, o2 = 0, o3 = 0;
switch (sorter) {
case IDX_SPO:
o1 = 0;
o2 = 5;
o3 = 10;
break;
case IDX_SOP:
o1 = 0;
o2 = 10;
o3 = 5;
break;
case IDX_OSP:
o1 = 10;
o2 = 0;
o3 = 5;
break;
case IDX_OPS:
o1 = 10;
o2 = 5;
o3 = 0;
break;
case IDX_POS:
o1 = 5;
o2 = 10;
o3 = 0;
break;
case IDX_PSO:
o1 = 5;
o2 = 0;
o3 = 10;
break;
default:
throw 10;
}
tbb::parallel_sort(idx->begin(), idx->end(), __PermSorter_sorter(rawinput, o1, o2, o3));
}
typedef std::array<unsigned char, 15> __PermSorter_triple;
bool __PermSorter_triple_sorter(const __PermSorter_triple &a,
const __PermSorter_triple &b) {
return a < b;
}
void PermSorter::sortPermutation(char *start, char *end) {
__PermSorter_triple *sstart = (__PermSorter_triple*) start;
__PermSorter_triple *send = (__PermSorter_triple*) end;
timens::system_clock::time_point starttime = timens::system_clock::now();
//std::sort(sstart, send, &__PermSorter_triple_sorter);
tbb::parallel_sort(sstart, send, &__PermSorter_triple_sorter);
timens::duration<double> duration = timens::system_clock::now() - starttime;
BOOST_LOG_TRIVIAL(debug) << "Time sorting: " << duration.count() << "s.";
}
void PermSorter::writeTermInBuffer(char *buffer, const long n) {
buffer[0] = (n >> 32) & 0xFF;
buffer[1] = (n >> 24) & 0xFF;
buffer[2] = (n >> 16) & 0xFF;
buffer[3] = (n >> 8) & 0xFF;
buffer[4] = n & 0xFF;
}
long PermSorter::readTermFromBuffer(char *buffer) {
long n = 0;
n += (long) (buffer[0] & 0xFF) << 32;
n += (long) (buffer[1] & 0xFF) << 24;
n += (buffer[2] & 0xFF) << 16;
n += (buffer[3] & 0xFF) << 8;
n += buffer[4] & 0xFF;
return n;
}
void PermSorter::dumpPermutation_seq_old(
char *rawinput,
long *start,
long *end,
MultiDiskLZ4Writer *writer,
int currentPart,
int sorter) {
if (sorter == IDX_SPO) {
while (start < end) {
Triple t;
char *bt = rawinput + 15 * *start;
t.s = PermSorter::readTermFromBuffer(bt);
t.p = PermSorter::readTermFromBuffer(bt + 5);
t.o = PermSorter::readTermFromBuffer(bt + 10);
t.writeTo(currentPart, writer);
start++;
}
} else {
long box1, box2;
while (start < end) {
Triple t;
char *bt = rawinput + 15 * *start;
t.s = PermSorter::readTermFromBuffer(bt);
t.p = PermSorter::readTermFromBuffer(bt + 5);
t.o = PermSorter::readTermFromBuffer(bt + 10);
switch (sorter) {
case IDX_SOP:
box1 = t.o;
t.o = t.p;
t.p = box1;
break;
case IDX_OSP:
box1 = t.s;
box2 = t.p;
t.s = t.o;
t.p = box1;
t.o = box2;
break;
case IDX_OPS:
box1 = t.s;
t.s = t.o;
t.o = box1;
break;
case IDX_POS:
box1 = t.s;
box2 = t.p;
t.s = box2;
t.p = t.o;
t.o = box1;
break;
case IDX_PSO:
box1 = t.p;
t.p = t.s;
t.s = box1;
break;
}
t.writeTo(currentPart, writer);
start++;
}
}
writer->setTerminated(currentPart);
}
void PermSorter::dumpPermutation_seq(
char *start,
char *end,
MultiDiskLZ4Writer *writer,
int currentPart) {
while (start < end) {
Triple t;
t.s = PermSorter::readTermFromBuffer(start);
t.p = PermSorter::readTermFromBuffer(start + 5);
t.o = PermSorter::readTermFromBuffer(start + 10);
t.writeTo(currentPart, writer);
start+=15;
}
writer->setTerminated(currentPart);
}
bool PermSorter::isMax(char *input, long idx) {
char *start = input + idx * 15;
for(int i = 0; i < 15; ++i) {
if (~(start[i]))
return false;
}
return true;
}
void PermSorter::dumpPermutation_old(char *input, long end,
int parallelProcesses,
int maxReadingThreads,
string out,
std::vector<long> &idx,
int sorter) {
//Set up the multidiskwriters...
MultiDiskLZ4Writer **writers = new MultiDiskLZ4Writer*[maxReadingThreads];
int partsPerWriter = parallelProcesses / maxReadingThreads;
int currentPart = 0;
for(int i = 0; i < maxReadingThreads; ++i) {
std::vector<string> files;
for(int j = 0; j < partsPerWriter; ++j) {
string o = out + string(".") + to_string(currentPart++);
files.push_back(o);
}
writers[i] = new MultiDiskLZ4Writer(files, 3, 4);
}
//Find out the total size of the written elements
long realSize = idx.size();
while (realSize > 0) {
if (PermSorter::isMax(input, idx[realSize - 1])) {
realSize--;
} else {
break;
}
}
BOOST_LOG_TRIVIAL(debug) << "MaxSize=" << idx.size() << " realSize=" << realSize;
long *rawidx = NULL;
if (idx.size() > 0)
rawidx = &(idx[0]);
boost::thread *threads = new boost::thread[parallelProcesses];
long chunkSize = max((long)1, (long)(realSize / parallelProcesses));
long currentEnd = 0;
for(int i = 0; i < parallelProcesses; ++i) {
long nextEnd;
if (i == parallelProcesses - 1) {
nextEnd = realSize;
} else {
nextEnd = currentEnd + chunkSize;
if (nextEnd > realSize)
nextEnd = realSize;
}
MultiDiskLZ4Writer *currentWriter = writers[i / partsPerWriter];
int currentPart = i % partsPerWriter;
if (nextEnd > currentEnd) {
threads[i] = boost::thread(PermSorter::dumpPermutation_seq_old,
input,
rawidx + currentEnd,
rawidx + nextEnd,
currentWriter,
currentPart,
sorter);
} else {
currentWriter->setTerminated(currentPart);
}
currentEnd = nextEnd;
}
for(int i = 0; i < parallelProcesses; ++i) {
threads[i].join();
}
for(int i = 0; i < maxReadingThreads; ++i) {
delete writers[i];
}
delete[] writers;
delete[] threads;
}
void PermSorter::dumpPermutation(char *input, long end,
int parallelProcesses,
int maxReadingThreads,
string out) {
//Set up the multidiskwriters...
MultiDiskLZ4Writer **writers = new MultiDiskLZ4Writer*[maxReadingThreads];
int partsPerWriter = parallelProcesses / maxReadingThreads;
int currentPart = 0;
for(int i = 0; i < maxReadingThreads; ++i) {
std::vector<string> files;
for(int j = 0; j < partsPerWriter; ++j) {
string o = out + string(".") + to_string(currentPart++);
files.push_back(o);
}
writers[i] = new MultiDiskLZ4Writer(files, 3, 4);
}
//Find out the total size of the written elements
long realSize = end;
while (realSize > 0) {
if (PermSorter::isMax(input, realSize - 1)) {
realSize--;
} else {
break;
}
}
boost::thread *threads = new boost::thread[parallelProcesses];
long chunkSize = max((long)1, (long)(realSize / parallelProcesses));
long currentEnd = 0;
for(int i = 0; i < parallelProcesses; ++i) {
long nextEnd;
if (i == parallelProcesses - 1) {
nextEnd = realSize;
} else {
nextEnd = currentEnd + chunkSize;
if (nextEnd > realSize)
nextEnd = realSize;
}
MultiDiskLZ4Writer *currentWriter = writers[i / partsPerWriter];
int currentPart = i % partsPerWriter;
if (nextEnd > currentEnd) {
threads[i] = boost::thread(PermSorter::dumpPermutation_seq,
input + currentEnd * 15,
input + nextEnd * 15,
currentWriter,
currentPart);
} else {
currentWriter->setTerminated(currentPart);
}
currentEnd = nextEnd;
}
for(int i = 0; i < parallelProcesses; ++i) {
threads[i].join();
}
for(int i = 0; i < maxReadingThreads; ++i) {
delete writers[i];
}
delete[] writers;
delete[] threads;
}
void PermSorter::sortChunks_seq_old(const int idReader,
MultiDiskLZ4Reader *reader,
char *start,
char *end,
long *count) {
long i = 0;
while (!reader->isEOF(idReader) && start < end) {
long first = reader->readLong(idReader);
long second = reader->readLong(idReader);
long third = reader->readLong(idReader);
PermSorter::writeTermInBuffer(start, first);
PermSorter::writeTermInBuffer(start + 5, second);
PermSorter::writeTermInBuffer(start + 10, third);
start += 15;
i++;
if (i % 1000000000 == 0) {
BOOST_LOG_TRIVIAL(debug) << "Processed " << i << " triples";
}
}
*count = i;
BOOST_LOG_TRIVIAL(debug) << "Loaded " << i << " triples";
memset(start, 0xFF, end - start);
}
void PermSorter::sortChunks_seq(const int idReader,
MultiDiskLZ4Reader *reader,
std::vector<std::unique_ptr<char[]>> *rawTriples,
long startIdx,
long endIdx,
long *count,
std::vector<std::pair<string, char>> additionalPermutations,
bool outputSPO) {
char *start = rawTriples->at(0).get() + startIdx;
char *end = rawTriples->at(0).get() + endIdx;
char *current = start;
long i = 0;
if (outputSPO) {
while (!reader->isEOF(idReader) && current < end) {
long first = reader->readLong(idReader);
long second = reader->readLong(idReader);
long third = reader->readLong(idReader);
PermSorter::writeTermInBuffer(current, first);
PermSorter::writeTermInBuffer(current + 5, second);
PermSorter::writeTermInBuffer(current + 10, third);
current += 15;
i++;
if (i % 1000000000 == 0) {
BOOST_LOG_TRIVIAL(debug) << "Processed " << i << " triples";
}
}
} else {
while (!reader->isEOF(idReader) && current < end) {
long first = reader->readLong(idReader);
long second = reader->readLong(idReader);
long third = reader->readLong(idReader);
PermSorter::writeTermInBuffer(current, first);
PermSorter::writeTermInBuffer(current + 5, third);
PermSorter::writeTermInBuffer(current + 10, second);
current += 15;
i++;
if (i % 1000000000 == 0) {
BOOST_LOG_TRIVIAL(debug) << "Processed " << i << " triples";
}
}
}
*count = i;
memset(current, 0xFF, end - current);
BOOST_LOG_TRIVIAL(debug) << "Loaded " << i << " triples. Now creating other permutations";
/************* SOP ************/
int idxSOP = 0;
for(auto p : additionalPermutations) {
if (p.second == IDX_SOP) {
break;
}
idxSOP++;
}
if (idxSOP < additionalPermutations.size()) { //Found SOP
//Copy all array, and swap the second and third element
char *startSOP = rawTriples->at(idxSOP + 1).get() + startIdx;
memcpy(startSOP, start, endIdx - startIdx);
for(long j = 0; j < i; ++j) {
//swap p and o
char tmp[5];
tmp[0] = startSOP[5]; //copy p in tmp
tmp[1] = startSOP[6];
tmp[2] = startSOP[7];
tmp[3] = startSOP[8];
tmp[4] = startSOP[9];
startSOP[5] = startSOP[10]; //copy o in p
startSOP[6] = startSOP[11];
startSOP[7] = startSOP[12];
startSOP[8] = startSOP[13];
startSOP[9] = startSOP[14];
startSOP[10] = tmp[0]; //copy p in o
startSOP[11] = tmp[1];
startSOP[12] = tmp[2];
startSOP[13] = tmp[3];
startSOP[14] = tmp[4];
startSOP += 15;
}
}
/************* PSO ************/
int idxPSO = 0;
for(auto p : additionalPermutations) {
if (p.second == IDX_PSO) {
break;
}
idxPSO++;
}
if (idxPSO < additionalPermutations.size()) { //Found PSO
char *startPSO = rawTriples->at(idxPSO + 1).get() + startIdx;
memcpy(startPSO, start, endIdx - startIdx);
for(long j = 0; j < i; ++j) {
//swap s and p
char tmp[5];
tmp[0] = startPSO[0]; //copy s in tmp
tmp[1] = startPSO[1];
tmp[2] = startPSO[2];
tmp[3] = startPSO[3];
tmp[4] = startPSO[4];
startPSO[0] = startPSO[5]; //copy p in s
startPSO[1] = startPSO[6];
startPSO[2] = startPSO[7];
startPSO[3] = startPSO[8];
startPSO[4] = startPSO[9];
startPSO[5] = tmp[0]; //copy s in p
startPSO[6] = tmp[1];
startPSO[7] = tmp[2];
startPSO[8] = tmp[3];
startPSO[9] = tmp[4];
startPSO += 15;
}
}
/************* POS ************/
int idxPOS = 0;
for(auto p : additionalPermutations) {
if (p.second == IDX_POS) {
break;
}
idxPOS++;
}
if (idxPOS < additionalPermutations.size()) { //Found POS
if (idxPSO >= additionalPermutations.size()) {
BOOST_LOG_TRIVIAL(error) << "I require also PSO";
throw 10;
}
char *startPSO = rawTriples->at(idxPSO + 1).get() + startIdx;
char *startPOS = rawTriples->at(idxPOS + 1).get() + startIdx;
memcpy(startPOS, startPSO, endIdx - startIdx);
for(long j = 0; j < i; ++j) {
//swap s and o
char tmp[5];
tmp[0] = startPOS[5]; //copy s in tmp
tmp[1] = startPOS[6];
tmp[2] = startPOS[7];
tmp[3] = startPOS[8];
tmp[4] = startPOS[9];
startPOS[5] = startPOS[10]; //copy o in s
startPOS[6] = startPOS[11];
startPOS[7] = startPOS[12];
startPOS[8] = startPOS[13];
startPOS[9] = startPOS[14];
startPOS[10] = tmp[0]; //copy s in o
startPOS[11] = tmp[1];
startPOS[12] = tmp[2];
startPOS[13] = tmp[3];
startPOS[14] = tmp[4];
startPOS += 15;
}
}
/************* OPS ************/
int idxOPS = 0;
for(auto p : additionalPermutations) {
if (p.second == IDX_OPS) {
break;
}
idxOPS++;
}
if (idxOPS < additionalPermutations.size()) { //Found OPS
char *startOPS = rawTriples->at(idxOPS + 1).get() + startIdx;
memcpy(startOPS, start, endIdx - startIdx);
for(long j = 0; j < i; ++j) {
//swap s and o
char tmp[5];
tmp[0] = startOPS[0]; //copy s in tmp
tmp[1] = startOPS[1];
tmp[2] = startOPS[2];
tmp[3] = startOPS[3];
tmp[4] = startOPS[4];
startOPS[0] = startOPS[10]; //copy o in s
startOPS[1] = startOPS[11];
startOPS[2] = startOPS[12];
startOPS[3] = startOPS[13];
startOPS[4] = startOPS[14];
startOPS[10] = tmp[0]; //copy s in o
startOPS[11] = tmp[1];
startOPS[12] = tmp[2];
startOPS[13] = tmp[3];
startOPS[14] = tmp[4];
startOPS += 15;
}
}
/************* OSP (labelled graph) ************/
if (outputSPO) {
int idxOSP = 0;
for(auto p : additionalPermutations) {
if (p.second == IDX_OSP) {
break;
}
idxOSP++;
}
if (idxOSP < additionalPermutations.size()) { //Found OSP
if (idxOPS >= additionalPermutations.size()) {
BOOST_LOG_TRIVIAL(error) << "I require also OPS";
throw 10;
}
char *startOPS = rawTriples->at(idxOPS + 1).get() + startIdx;
char *startOSP = rawTriples->at(idxOSP + 1).get() + startIdx;
memcpy(startOSP, startOPS, endIdx - startIdx);
for(long j = 0; j < i; ++j) {
//swap p and s
char tmp[5];
tmp[0] = startOSP[5]; //copy p in tmp
tmp[1] = startOSP[6];
tmp[2] = startOSP[7];
tmp[3] = startOSP[8];
tmp[4] = startOSP[9];
startOSP[5] = startOSP[10]; //copy s in p
startOSP[6] = startOSP[11];
startOSP[7] = startOSP[12];
startOSP[8] = startOSP[13];
startOSP[9] = startOSP[14];
startOSP[10] = tmp[0]; //copy s in o
startOSP[11] = tmp[1];
startOSP[12] = tmp[2];
startOSP[13] = tmp[3];
startOSP[14] = tmp[4];
startOSP += 15;
}
}
} else {
/************* OSP (unlabelled graph) ************/
int idxOSP = 0;
for(auto p : additionalPermutations) {
if (p.second == IDX_OSP) {
break;
}
idxOSP++;
}
if (idxOSP < additionalPermutations.size()) { //Found OSP
char *startOSP = rawTriples->at(idxOSP + 1).get() + startIdx;
memcpy(startOSP, start, endIdx - startIdx);
for(long j = 0; j < i; ++j) {
//swap o and s
char tmp[5];
tmp[0] = startOSP[5]; //copy o in tmp
tmp[1] = startOSP[6];
tmp[2] = startOSP[7];
tmp[3] = startOSP[8];
tmp[4] = startOSP[9];
startOSP[5] = startOSP[0]; //copy s in o
startOSP[6] = startOSP[1];
startOSP[7] = startOSP[2];
startOSP[8] = startOSP[3];
startOSP[9] = startOSP[4];
startOSP[0] = tmp[0]; //copy s in o
startOSP[1] = tmp[1];
startOSP[2] = tmp[2];
startOSP[3] = tmp[3];
startOSP[4] = tmp[4];
startOSP += 15;
}
}
}
}
void PermSorter::sortChunks_Old(string inputdir,
int maxReadingThreads,
int parallelProcesses,
long estimatedSize,
std::vector<std::pair<string, char>> &additionalPermutations) {
BOOST_LOG_TRIVIAL(debug) << "Start sortChunks";
//calculate the number of elements
long mem = Utils::getSystemMemory() * 0.8;
long nelements = mem / (15 + 8 * (additionalPermutations.size() + 1)); // 5 bytes per 3 triple elements + 8 * additionalPermutations.size()
long elementsMainMem = max((long)parallelProcesses,
min(nelements, (long)(estimatedSize * 1.2)));
//Make sure elementsMainMem is a multiple of parallelProcesses
elementsMainMem += parallelProcesses - (elementsMainMem % parallelProcesses);
/*** SORT THE ORIGINAL FILES IN BLOCKS OF N RECORDS ***/
vector<string> unsortedFiles = Utils::getFiles(inputdir);
MultiDiskLZ4Reader **readers = new MultiDiskLZ4Reader*[maxReadingThreads];
std::vector<std::vector<string>> inputsReaders(parallelProcesses);
int currentPart = 0;
for(int i = 0; i < unsortedFiles.size(); ++i) {
if (fs::exists(fs::path(unsortedFiles[i]))) {
inputsReaders[currentPart].push_back(unsortedFiles[i]);
currentPart = (currentPart + 1) % parallelProcesses;
}
}
auto itr = inputsReaders.begin();
int filesPerReader = parallelProcesses / maxReadingThreads;
for(int i = 0; i < maxReadingThreads; ++i) {
readers[i] = new MultiDiskLZ4Reader(filesPerReader,
3, 4);
readers[i]->start();
for(int j = 0; j < filesPerReader; ++j) {
if (itr->empty()) {
BOOST_LOG_TRIVIAL(debug) << "Part " << j << " is empty";
} else {
BOOST_LOG_TRIVIAL(debug) << "Part " << i << " " << j << " " << itr->at(0);
}
if (itr != inputsReaders.end()) {
readers[i]->addInput(j, *itr);
itr++;
} else {
std::vector<string> emptyset;
readers[i]->addInput(j, emptyset);
}
}
}
boost::thread *threads = new boost::thread[parallelProcesses];
BOOST_LOG_TRIVIAL(debug) << "Creating vectors of " << elementsMainMem << " elements. Each el is 15 bytes";
char *rawTriples = new char[elementsMainMem * 15];
std::vector<long> idx0(elementsMainMem);
for(long i = 0; i < elementsMainMem; ++i) {
idx0[i] = i;
}
std::vector<std::vector<long>> additionalIdxs(additionalPermutations.size());
for(int i = 0; i < additionalPermutations.size(); ++i) {
additionalIdxs[i] = idx0;
}
BOOST_LOG_TRIVIAL(debug) << "Creating vectors of " << elementsMainMem << ". done";
long maxInserts = max((long)1, (long)(elementsMainMem / parallelProcesses));
bool isFinished = false;
int iter = 0;
while (!isFinished) {
BOOST_LOG_TRIVIAL(debug) << "Load in parallel all the triples from disk to the main memory";
std::vector<long> counts(parallelProcesses);
for (int i = 0; i < parallelProcesses; ++i) {
MultiDiskLZ4Reader *reader = readers[i % maxReadingThreads];
int idReader = i / maxReadingThreads;
threads[i] = boost::thread(
boost::bind(&sortChunks_seq_old, idReader, reader,
rawTriples + (i * 15 * maxInserts),
rawTriples + ((i+1) * 15 * maxInserts),
&(counts[i])));
}
for (int i = 0; i < parallelProcesses; ++i) {
threads[i].join();
}
BOOST_LOG_TRIVIAL(debug) << "Fill the empty holes with new data";
int curPart = 0;
std::vector<std::pair<int, int>> openedStreams;
for(int i = 0; i < parallelProcesses; ++i) {
int idxReader = i % maxReadingThreads;
int idxPart = i / maxReadingThreads;
if (!readers[idxReader]->isEOF(idxPart)) {
openedStreams.push_back(make_pair(idxReader, idxPart));
}
}
while (curPart < parallelProcesses && !openedStreams.empty()) {
if (counts[curPart] < maxInserts) {
int idxCurPair = 0;
char *start = rawTriples + curPart * maxInserts * 15;
while (idxCurPair < openedStreams.size() &&
counts[curPart] < maxInserts) {
auto pair = openedStreams[idxCurPair];
long first = readers[pair.first]->readLong(pair.second);
long second = readers[pair.first]->readLong(pair.second);
long third = readers[pair.first]->readLong(pair.second);
PermSorter::writeTermInBuffer(start + counts[curPart]*15, first);
PermSorter::writeTermInBuffer(start + counts[curPart]*15+5, second);
PermSorter::writeTermInBuffer(start + counts[curPart]*15+10, third);
if (readers[pair.first]->isEOF(pair.second)) {
openedStreams.erase(openedStreams.begin() + idxCurPair);
if (idxCurPair == openedStreams.size()) {
idxCurPair = 0;
}
} else {
idxCurPair = (idxCurPair + 1) % openedStreams.size();
}
counts[curPart]++;
}
} else {
curPart++;
}
}
BOOST_LOG_TRIVIAL(debug) << "Finished filling holes";
BOOST_LOG_TRIVIAL(debug) << "Start sorting";
tbb::task_scheduler_init init(max(1, (int)(parallelProcesses / 6)));
std::thread *threads = new std::thread[additionalPermutations.size()];
for(int i = 0; i < additionalPermutations.size(); ++i) {
threads[i] = std::thread(
std::bind(&PermSorter::sortPermutation_old,
rawTriples,
&additionalIdxs[i],
additionalPermutations[i].second));
}
PermSorter::sortPermutation_old(rawTriples, &idx0, IDX_SPO);
for(int i = 0; i < additionalPermutations.size(); ++i) {
threads[i].join();
}
delete[] threads;
BOOST_LOG_TRIVIAL(debug) << "End sorting";
BOOST_LOG_TRIVIAL(debug) << "Start dumping";
long maxValue = maxInserts * 15 * parallelProcesses;
int addPermIdx = 0;
for(auto perm : additionalPermutations) {
string outputFile = perm.first + string("/sorted-") + to_string(iter++);
PermSorter::dumpPermutation_old(rawTriples,
maxValue,
parallelProcesses,
maxReadingThreads,
outputFile,
additionalIdxs[addPermIdx++],
perm.second);
}
string outputFile = inputdir + string("/sorted-") + to_string(iter++);
PermSorter::dumpPermutation_old(rawTriples,
maxValue,
parallelProcesses,
maxReadingThreads,
outputFile,
idx0,
IDX_SPO);
BOOST_LOG_TRIVIAL(debug) << "End dumping";
//Are all files read?
int i = 0;
for(; i < parallelProcesses; ++i) {
if (!readers[i % maxReadingThreads]->isEOF(i / maxReadingThreads)) {
break;
}
}
isFinished = i == parallelProcesses;
if (!isFinished) {
BOOST_LOG_TRIVIAL(debug) << "One round is not enough";
}
}
delete[] rawTriples;
for(int i = 0; i < maxReadingThreads; ++i) {
delete readers[i];
}
for(auto inputFile : unsortedFiles)
fs::remove(fs::path(inputFile));
delete[] readers;
delete[] threads;
}
struct _Offset {
char first;
char second;
char third;
};
void PermSorter::sortChunks(string inputdir,
int maxReadingThreads,
int parallelProcesses,
long estimatedSize,
bool outputSPO,
std::vector<std::pair<string, char>> &additionalPermutations) {
BOOST_LOG_TRIVIAL(debug) << "Start sortChunks";
//calculate the number of elements
long mem = Utils::getSystemMemory() * 0.8;
int nperms = additionalPermutations.size() + 1;
long nelements = mem / (15 * nperms);
long elementsMainMem = max((long)parallelProcesses,
min(nelements, (long)(estimatedSize * 1.2)));
//Make sure elementsMainMem is a multiple of parallelProcesses
elementsMainMem += parallelProcesses - (elementsMainMem % parallelProcesses);
/*** SORT THE ORIGINAL FILES IN BLOCKS OF N RECORDS ***/
vector<string> unsortedFiles = Utils::getFiles(inputdir);
MultiDiskLZ4Reader **readers = new MultiDiskLZ4Reader*[maxReadingThreads];
std::vector<std::vector<string>> inputsReaders(parallelProcesses);
int currentPart = 0;
for(int i = 0; i < unsortedFiles.size(); ++i) {
if (fs::exists(fs::path(unsortedFiles[i]))) {
inputsReaders[currentPart].push_back(unsortedFiles[i]);
currentPart = (currentPart + 1) % parallelProcesses;
}
}
auto itr = inputsReaders.begin();
int filesPerReader = parallelProcesses / maxReadingThreads;
for(int i = 0; i < maxReadingThreads; ++i) {
readers[i] = new MultiDiskLZ4Reader(filesPerReader,
3, 4);
readers[i]->start();
for(int j = 0; j < filesPerReader; ++j) {
if (itr->empty()) {
BOOST_LOG_TRIVIAL(debug) << "Part " << j << " is empty";
} else {
BOOST_LOG_TRIVIAL(debug) << "Part " << i << " " << j << " " << itr->at(0);
}
if (itr != inputsReaders.end()) {
readers[i]->addInput(j, *itr);
itr++;
} else {
std::vector<string> emptyset;
readers[i]->addInput(j, emptyset);
}
}
}
boost::thread *threads = new boost::thread[parallelProcesses];
BOOST_LOG_TRIVIAL(debug) << "Creating vectors of "
<< elementsMainMem << " elements. Each el is 15 bytes";
std::vector<std::unique_ptr<char[]>> rawTriples;
rawTriples.push_back(std::unique_ptr<char[]>(new char[elementsMainMem * 15]));
for(int i = 0; i < additionalPermutations.size(); ++i) {
rawTriples.push_back(std::unique_ptr<char[]>(new char[elementsMainMem * 15]));
}
BOOST_LOG_TRIVIAL(debug) << "Creating vectors of " << elementsMainMem << ". done";
long maxInserts = max((long)1, (long)(elementsMainMem / parallelProcesses));
bool isFinished = false;
int iter = 0;
while (!isFinished) {
BOOST_LOG_TRIVIAL(debug) << "Load in parallel all the triples from disk to the main memory";
std::vector<long> counts(parallelProcesses);
for (int i = 0; i < parallelProcesses; ++i) {
MultiDiskLZ4Reader *reader = readers[i % maxReadingThreads];
int idReader = i / maxReadingThreads;
threads[i] = boost::thread(
boost::bind(&sortChunks_seq, idReader, reader,
&rawTriples,
(i * 15 * maxInserts),
((i+1) * 15 * maxInserts),
&(counts[i]),
additionalPermutations,
outputSPO));
}
for (int i = 0; i < parallelProcesses; ++i) {
threads[i].join();
}
BOOST_LOG_TRIVIAL(debug) << "Fill the empty holes with new data";
int curPart = 0;
std::vector<std::pair<int, int>> openedStreams;
for(int i = 0; i < parallelProcesses; ++i) {
int idxReader = i % maxReadingThreads;
int idxPart = i / maxReadingThreads;
if (!readers[idxReader]->isEOF(idxPart)) {
openedStreams.push_back(make_pair(idxReader, idxPart));
}
}
std::vector<_Offset> offsets;
for(auto p : additionalPermutations) {
_Offset o;
switch (p.second) {
case IDX_SOP:
o.first = 0;
o.second = 10;
o.third = 5;
break;
case IDX_OPS:
o.first = 10;
o.second = 5;
o.third = 0;
break;
case IDX_OSP:
o.first = 5;
o.second = 10;
o.third = 0;
break;
case IDX_POS:
o.first = 10;
o.second = 0;
o.third = 5;
break;
case IDX_PSO:
o.first = 5;
o.second = 0;
o.third = 10;
break;
default:
throw 10;
}
offsets.push_back(o);
}
while (curPart < parallelProcesses && !openedStreams.empty()) {
if (counts[curPart] < maxInserts) {
int idxCurPair = 0;
const long startp = curPart * maxInserts * 15;
char *start = rawTriples[0].get() + startp;
while (idxCurPair < openedStreams.size() &&
counts[curPart] < maxInserts) {
auto pair = openedStreams[idxCurPair];
const long first = readers[pair.first]->readLong(pair.second);
const long second = readers[pair.first]->readLong(pair.second);
const long third = readers[pair.first]->readLong(pair.second);
const long starto = counts[curPart] * 15;
if (outputSPO) {
PermSorter::writeTermInBuffer(start + starto, first);
PermSorter::writeTermInBuffer(start + starto + 5, second);
PermSorter::writeTermInBuffer(start + starto + 10, third);
} else {
PermSorter::writeTermInBuffer(start + starto, first);
PermSorter::writeTermInBuffer(start + starto + 5, third);
PermSorter::writeTermInBuffer(start + starto + 10, second);
}
//Copy the triples also in the other permutations
for(int i = 0; i < additionalPermutations.size(); ++i) {
char *startperm = rawTriples[i + 1].get() + startp;
const _Offset o = offsets[i];
PermSorter::writeTermInBuffer(startperm + starto + o.first, first);
PermSorter::writeTermInBuffer(startperm + starto + o.second, second);
PermSorter::writeTermInBuffer(startperm + starto + o.third, third);
}
if (readers[pair.first]->isEOF(pair.second)) {
openedStreams.erase(openedStreams.begin() + idxCurPair);
if (idxCurPair == openedStreams.size()) {
idxCurPair = 0;
}
} else {
idxCurPair = (idxCurPair + 1) % openedStreams.size();
}
counts[curPart]++;
}
} else {
curPart++;
}
}
BOOST_LOG_TRIVIAL(debug) << "Finished filling holes";
BOOST_LOG_TRIVIAL(debug) << "Start sorting. Processes per permutation=" << max(1, (int)(parallelProcesses / nperms));
tbb::task_scheduler_init init(max(1, (int)(parallelProcesses / nperms)));
std::thread *threads = new std::thread[additionalPermutations.size()];
for(int i = 0; i < additionalPermutations.size(); ++i) {
threads[i] = std::thread(
std::bind(&PermSorter::sortPermutation,
rawTriples[i+1].get(), rawTriples[i+1].get() + 15 * maxInserts * parallelProcesses));
}
PermSorter::sortPermutation(rawTriples[0].get(), rawTriples[0].get() + 15 * maxInserts * parallelProcesses);
for(int i = 0; i < additionalPermutations.size(); ++i) {
threads[i].join();
}
delete[] threads;
BOOST_LOG_TRIVIAL(debug) << "End sorting";
BOOST_LOG_TRIVIAL(debug) << "Start dumping";
long maxValue = maxInserts * parallelProcesses;
int j = 1;
for(auto perm : additionalPermutations) {
string outputFile = perm.first + string("/sorted-") + to_string(iter++);
PermSorter::dumpPermutation(rawTriples[j++].get(),
maxValue,
parallelProcesses,
maxReadingThreads,
outputFile);
}
string outputFile = inputdir + string("/sorted-") + to_string(iter++);
PermSorter::dumpPermutation(rawTriples[0].get(),
maxValue,
parallelProcesses,
maxReadingThreads,
outputFile);
BOOST_LOG_TRIVIAL(debug) << "End dumping";
//Are all files read?
int i = 0;
for(; i < parallelProcesses; ++i) {
if (!readers[i % maxReadingThreads]->isEOF(i / maxReadingThreads)) {
break;
}
}
isFinished = i == parallelProcesses;
if (!isFinished) {
BOOST_LOG_TRIVIAL(debug) << "One round is not enough";
}
}
for(int i = 0; i < maxReadingThreads; ++i) {
delete readers[i];
}
for(auto inputFile : unsortedFiles)
fs::remove(fs::path(inputFile));
delete[] readers;
delete[] threads;
}
|
apache-2.0
|
joerg84/arangodb
|
lib/V8/V8LineEditor.cpp
|
11292
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "V8LineEditor.h"
#include "Logger/Logger.h"
#include "Basics/tri-strings.h"
#include "Utilities/Completer.h"
#include "Utilities/ShellBase.h"
#include "V8/v8-utils.h"
using namespace arangodb;
using namespace arangodb;
////////////////////////////////////////////////////////////////////////////////
/// @brief the active instance of the editor
////////////////////////////////////////////////////////////////////////////////
static std::atomic<V8LineEditor*> SINGLETON(nullptr);
////////////////////////////////////////////////////////////////////////////////
/// @brief signal handler for CTRL-C
////////////////////////////////////////////////////////////////////////////////
#ifdef _WIN32
static bool SignalHandler(DWORD eventType) {
switch (eventType) {
case CTRL_BREAK_EVENT:
case CTRL_C_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT: {
// get the instance of the console
auto instance = SINGLETON.load();
if (instance != nullptr) {
if (instance->isExecutingCommand()) {
v8::Isolate* isolate = instance->isolate();
if (!v8::V8::IsExecutionTerminating(isolate)) {
v8::V8::TerminateExecution(isolate);
}
}
instance->signal();
}
return true;
}
default: { return true; }
}
}
#else
static void SignalHandler(int signal) {
// get the instance of the console
auto instance = SINGLETON.load();
if (instance != nullptr) {
if (instance->isExecutingCommand()) {
v8::Isolate* isolate = instance->isolate();
if (!v8::V8::IsExecutionTerminating(isolate)) {
v8::V8::TerminateExecution(isolate);
}
}
instance->signal();
}
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief V8Completer
////////////////////////////////////////////////////////////////////////////////
namespace {
class V8Completer : public Completer {
public:
V8Completer() {}
~V8Completer() {}
public:
bool isComplete(std::string const& source, size_t lineno) override final {
int openParen = 0;
int openBrackets = 0;
int openBraces = 0;
int openStrings =
0; // only used for template strings, which can be multi-line
int openComments = 0;
enum line_parse_state_e {
NORMAL, // start
NORMAL_1, // from NORMAL: seen a single /
DOUBLE_QUOTE, // from NORMAL: seen a single "
DOUBLE_QUOTE_ESC, // from DOUBLE_QUOTE: seen a backslash
SINGLE_QUOTE, // from NORMAL: seen a single '
SINGLE_QUOTE_ESC, // from SINGLE_QUOTE: seen a backslash
BACKTICK, // from NORMAL: seen a single `
BACKTICK_ESC, // from BACKTICK: seen a backslash
MULTI_COMMENT, // from NORMAL_1: seen a *
MULTI_COMMENT_1, // from MULTI_COMMENT, seen a *
SINGLE_COMMENT // from NORMAL_1; seen a /
};
char const* ptr = source.c_str();
char const* end = ptr + source.length();
line_parse_state_e state = NORMAL;
while (ptr < end) {
if (state == DOUBLE_QUOTE) {
if (*ptr == '\\') {
state = DOUBLE_QUOTE_ESC;
} else if (*ptr == '"') {
state = NORMAL;
}
++ptr;
} else if (state == DOUBLE_QUOTE_ESC) {
state = DOUBLE_QUOTE;
ptr++;
} else if (state == SINGLE_QUOTE) {
if (*ptr == '\\') {
state = SINGLE_QUOTE_ESC;
} else if (*ptr == '\'') {
state = NORMAL;
}
++ptr;
} else if (state == SINGLE_QUOTE_ESC) {
state = SINGLE_QUOTE;
ptr++;
} else if (state == BACKTICK) {
if (*ptr == '\\') {
state = BACKTICK_ESC;
} else if (*ptr == '`') {
state = NORMAL;
--openStrings;
}
++ptr;
} else if (state == BACKTICK_ESC) {
state = BACKTICK;
ptr++;
} else if (state == MULTI_COMMENT) {
if (*ptr == '*') {
state = MULTI_COMMENT_1;
}
++ptr;
} else if (state == MULTI_COMMENT_1) {
if (*ptr == '/') {
state = NORMAL;
--openComments;
}
++ptr;
} else if (state == SINGLE_COMMENT) {
++ptr;
if (ptr == end || *ptr == '\n') {
state = NORMAL;
--openComments;
}
} else if (state == NORMAL_1) {
switch (*ptr) {
case '/':
state = SINGLE_COMMENT;
++openComments;
++ptr;
break;
case '*':
state = MULTI_COMMENT;
++openComments;
++ptr;
break;
default:
state = NORMAL; // try again, do not change ptr
break;
}
} else {
switch (*ptr) {
case '"':
state = DOUBLE_QUOTE;
break;
case '\'':
state = SINGLE_QUOTE;
break;
case '`':
state = BACKTICK;
++openStrings;
break;
case '/':
state = NORMAL_1;
break;
case '(':
++openParen;
break;
case ')':
--openParen;
break;
case '[':
++openBrackets;
break;
case ']':
--openBrackets;
break;
case '{':
++openBraces;
break;
case '}':
--openBraces;
break;
case '\\':
++ptr;
break;
}
++ptr;
}
}
return (openParen <= 0 && openBrackets <= 0 && openBraces <= 0 &&
openStrings <= 0 && openComments <= 0);
}
std::vector<std::string> alternatives(char const* text) override final {
std::vector<std::string> result;
// locate global object or sub-object
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Handle<v8::Object> current = context->Global();
std::string path;
char* prefix;
if (*text != '\0') {
TRI_vector_string_t splitted = TRI_SplitString(text, '.');
if (1 < splitted._length) {
for (size_t i = 0; i < splitted._length - 1; ++i) {
v8::Handle<v8::String> name = TRI_V8_STRING(splitted._buffer[i]);
if (!current->Has(name)) {
TRI_DestroyVectorString(&splitted);
return result;
}
v8::Handle<v8::Value> val = current->Get(name);
if (!val->IsObject()) {
TRI_DestroyVectorString(&splitted);
return result;
}
current = val->ToObject();
path = path + splitted._buffer[i] + ".";
}
prefix = TRI_DuplicateString(splitted._buffer[splitted._length - 1]);
} else {
prefix = TRI_DuplicateString(text);
}
TRI_DestroyVectorString(&splitted);
} else {
prefix = TRI_DuplicateString(text);
}
v8::HandleScope scope(isolate);
// compute all possible completions
v8::Handle<v8::Array> properties;
v8::Handle<v8::String> cpl = TRI_V8_ASCII_STRING("_COMPLETIONS");
if (current->HasOwnProperty(cpl)) {
v8::Handle<v8::Value> funcVal = current->Get(cpl);
if (funcVal->IsFunction()) {
v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(funcVal);
// assign a dummy entry to the args array even if we don't need it.
// this prevents "error C2466: cannot allocate an array of constant size 0" in MSVC
v8::Handle<v8::Value> args[] = { v8::Null(isolate) };
try {
v8::Handle<v8::Value> cpls = func->Call(current, 0, args);
if (cpls->IsArray()) {
properties = v8::Handle<v8::Array>::Cast(cpls);
}
} catch (...) {
// silently ignore errors here
}
}
} else {
properties = current->GetPropertyNames();
}
// locate
try {
if (!properties.IsEmpty()) {
uint32_t const n = properties->Length();
result.reserve(static_cast<size_t>(n));
for (uint32_t i = 0; i < n; ++i) {
v8::Handle<v8::Value> v = properties->Get(i);
TRI_Utf8ValueNFC str(TRI_UNKNOWN_MEM_ZONE, v);
char const* s = *str;
if (s != nullptr && *s) {
std::string suffix = (current->Get(v)->IsFunction()) ? "()" : "";
std::string name = path + s + suffix;
if (*prefix == '\0' || TRI_IsPrefixString(s, prefix)) {
result.emplace_back(name);
}
}
}
}
} catch (...) {
// ignore errors in case of OOM
}
TRI_FreeString(TRI_CORE_MEM_ZONE, prefix);
return result;
}
};
}
////////////////////////////////////////////////////////////////////////////////
/// @brief constructs a new editor
////////////////////////////////////////////////////////////////////////////////
V8LineEditor::V8LineEditor(v8::Isolate* isolate,
v8::Handle<v8::Context> context,
std::string const& history)
: LineEditor(),
_isolate(isolate),
_context(context),
_executingCommand(false) {
// register global instance
TRI_ASSERT(SINGLETON.load() == nullptr);
SINGLETON.store(this);
// create shell
_shell = ShellBase::buildShell(history, new V8Completer());
// handle control-c
#ifdef _WIN32
int res = SetConsoleCtrlHandler((PHANDLER_ROUTINE)SignalHandler, true);
if (res == 0) {
LOG_TOPIC(ERR, arangodb::Logger::FIXME) << "unable to install signal handler";
}
#else
struct sigaction sa;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = &SignalHandler;
int res = sigaction(SIGINT, &sa, 0);
if (res != 0) {
LOG_TOPIC(ERR, arangodb::Logger::FIXME) << "unable to install signal handler";
}
#endif
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destroys the editor
////////////////////////////////////////////////////////////////////////////////
V8LineEditor::~V8LineEditor() {
// unregister global instance
TRI_ASSERT(SINGLETON.load() != nullptr);
SINGLETON.store(nullptr);
}
|
apache-2.0
|
sendwithus/sendwithus_csharp
|
Sendwithus/SendwithusClient/API/Template.cs
|
18534
|
using Newtonsoft.Json;
using Sendwithus.Net;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
namespace Sendwithus
{
/// <summary>
/// sendwithus Template class
/// </summary>
public class Template
{
public const string DEFAULT_LOCALE = "en-US";
// all lowercase to match expected JSON format (case-sensitive on server side)
public string id { get; set; }
public string name { get; set; }
public string locale { get; set; }
public string created { get; set; }
public Collection<TemplateVersion> versions { get; set; }
public Collection<string> tags { get; set; }
/// <summary>
/// Create an empty Template
/// </summary>
public Template() {
locale = DEFAULT_LOCALE;
}
/// <summary>
/// Get all the templates associated with the account.
/// GET /templates
/// </summary>
/// <returns>A list of all the templates associated with the account</returns>
/// <exception cref="AggregateException">Thrown when the API response status code is not success or when the API call times out</exception>
/// <exception cref="InvalidOperationException">Thrown when making a Batch API Request that has already reached the maxmimum API calls per batch request</exception>
public static async Task<List<Template>> GetTemplatesAsync()
{
// Send the GET request
var resource = "templates";
var jsonResponse = await RequestManager.SendGetRequestAsync(resource);
// Convert the JSON result into an object
return JsonConvert.DeserializeObject<List<Template>>(jsonResponse);
}
/// <summary>
/// Get a template by ID.
/// GET /templates/(:template_id)
/// </summary>
/// <param name="templateId">The ID of the template</param>
/// <returns>The template with the given ID</returns>
/// <exception cref="AggregateException">Thrown when the API response status code is not success or when the API call times out</exception>
/// <exception cref="InvalidOperationException">Thrown when making a Batch API Request that has already reached the maxmimum API calls per batch request</exception>
public static async Task<Template> GetTemplateAsync(string templateId)
{
// Send the GET request
var resource = String.Format("templates/{0}", templateId);
var jsonResponse = await RequestManager.SendGetRequestAsync(resource);
// Convert the JSON result into an object
return JsonConvert.DeserializeObject<Template>(jsonResponse);
}
/// <summary>
/// Get a template by ID and locale.
/// GET /templates/(:template_id)/locales/(:locale)
/// </summary>
/// <param name="templateId">The ID of the template</param>
/// <param name="locale"></param>
/// <returns>The template with the given ID and locale</returns>
/// <exception cref="AggregateException">Thrown when the API response status code is not success or when the API call times out</exception>
/// <exception cref="InvalidOperationException">Thrown when making a Batch API Request that has already reached the maxmimum API calls per batch request</exception>
public static async Task<Template> GetTemplateAsync(string templateId, string locale)
{
// Send the GET request
var resource = String.Format("templates/{0}/locales/{1}", templateId, locale);
var jsonResponse = await RequestManager.SendGetRequestAsync(resource);
// Convert the JSON result into an object
return JsonConvert.DeserializeObject<Template>(jsonResponse);
}
/// <summary>
/// Get a list of template versions (with HTML/text).
/// GET /templates/(:template_id)/versions
/// </summary>
/// <param name="templateId">The ID of the template</param>
/// <returns>The template versions associated with the given ID</returns>
/// <exception cref="AggregateException">Thrown when the API response status code is not success or when the API call times out</exception>
/// <exception cref="InvalidOperationException">Thrown when making a Batch API Request that has already reached the maxmimum API calls per batch request</exception>
public static async Task<List<TemplateVersion>> GetTemplateVersionsAsync(string templateId)
{
// Send the GET request
var resource = String.Format("templates/{0}/versions", templateId);
var jsonResponse = await RequestManager.SendGetRequestAsync(resource);
// Convert the JSON result into an object
return JsonConvert.DeserializeObject<List<TemplateVersion>>(jsonResponse);
}
/// <summary>
/// Get a list of template versions (with HTML/text).
/// GET /templates/(:template_id)/locales/(:locale)/versions
/// </summary>
/// <param name="templateId">The ID of the template</param>
/// <param name="locale">The locale of the template</param>
/// <returns>The template versions associated with the given ID and locale</returns>
/// <exception cref="AggregateException">Thrown when the API response status code is not success or when the API call times out</exception>
/// <exception cref="InvalidOperationException">Thrown when making a Batch API Request that has already reached the maxmimum API calls per batch request</exception>
public static async Task<List<TemplateVersion>> GetTemplateVersionsAsync(string templateId, string locale)
{
// Send the GET request
var resource = String.Format("templates/{0}/locales/{1}/versions", templateId, locale);
var jsonResponse = await RequestManager.SendGetRequestAsync(resource);
// Convert the JSON result into an object
return JsonConvert.DeserializeObject<List<TemplateVersion>>(jsonResponse);
}
/// <summary>
/// Get a specific version (with HTML/text).
/// GET /templates/(:template_id)/versions/(:version_id)
/// </summary>
/// <param name="templateId">The ID of the template</param>
/// <param name="versionId">The ID of the version</param>
/// <returns>The template version associated with the given ID</returns>
/// <exception cref="AggregateException">Thrown when the API response status code is not success or when the API call times out</exception>
/// <exception cref="InvalidOperationException">Thrown when making a Batch API Request that has already reached the maxmimum API calls per batch request</exception>
public static async Task<TemplateVersion> GetTemplateVersionAsync(string templateId, string versionId)
{
// Send the GET request
var resource = String.Format("templates/{0}/versions/{1}", templateId, versionId);
var jsonResponse = await RequestManager.SendGetRequestAsync(resource);
// Convert the JSON result into an object
return JsonConvert.DeserializeObject<TemplateVersion>(jsonResponse);
}
/// <summary>
/// Get a specific version (with HTML/text).
/// GET /templates/(:template_id)/locales/(:locale)/versions/(:version_id)
/// </summary>
/// <param name="templateId">The ID of the template</param>
/// <param name="locale">The locale of the template</param>
/// <param name="versionId">The ID of the version</param>
/// <returns>The template version associated with the given ID</returns>
/// <exception cref="AggregateException">Thrown when the API response status code is not success or when the API call times out</exception>
/// <exception cref="InvalidOperationException">Thrown when making a Batch API Request that has already reached the maxmimum API calls per batch request</exception>
public static async Task<TemplateVersion> GetTemplateVersionAsync(string templateId, string locale, string versionId)
{
// Send the GET request
var resource = String.Format("templates/{0}/locales/{1}/versions/{2}", templateId, locale, versionId);
var jsonResponse = await RequestManager.SendGetRequestAsync(resource);
// Convert the JSON result into an object
return JsonConvert.DeserializeObject<TemplateVersion>(jsonResponse);
}
/// <summary>
/// Update a Template Version.
/// PUT /templates/(:template_id)/versions/(:version_id)
/// NOTE - At least one of html or text must be specified in the TemplateVersion
/// </summary>
/// <param name="templateId">The ID of the template</param>
/// <param name="versionId">The ID of the version</param>
/// <returns>The template version associated with the given ID</returns>
/// <exception cref="AggregateException">Thrown when the API response status code is not success or when the API call times out</exception>
/// <exception cref="InvalidOperationException">Thrown when making a Batch API Request that has already reached the maxmimum API calls per batch request</exception>
public static async Task<TemplateVersion> UpdateTemplateVersionAsync(string templateId, string versionId, TemplateVersion updatedTemplateVersion)
{
// Send the PUT request
var resource = String.Format("templates/{0}/versions/{1}", templateId, versionId);
var jsonResponse = await RequestManager.SendPutRequestAsync(resource, updatedTemplateVersion);
// Convert the JSON result into an object
return JsonConvert.DeserializeObject<TemplateVersion>(jsonResponse);
}
/// <summary>
/// Update a Template Version.
/// PUT /templates/(:template_id)/locales/(:locale)/versions/(:version_id)
/// </summary>
/// <param name="templateId">The ID of the template</param>
/// <param name="locale">The locale of the template</param>
/// <param name="versionId">The ID of the version</param>
/// <param name="updatedTemplateVersion">The updated template version</param>
/// <returns>The template version associated with the given ID</returns>
/// <exception cref="AggregateException">Thrown when the API response status code is not success or when the API call times out</exception>
/// <exception cref="InvalidOperationException">Thrown when making a Batch API Request that has already reached the maxmimum API calls per batch request</exception>
public static async Task<TemplateVersion> UpdateTemplateVersionAsync(string templateId, string locale, string versionId, TemplateVersion updatedTemplateVersion)
{
// Send the PUT request
var resource = String.Format("templates/{0}/locales/{1}/versions/{2}", templateId, locale, versionId);
var jsonResponse = await RequestManager.SendPutRequestAsync(resource, updatedTemplateVersion);
// Convert the JSON result into an object
return JsonConvert.DeserializeObject<TemplateVersion>(jsonResponse);
}
/// <summary>
/// Creates a new template.
/// POST /templates
/// </summary>
/// <param name="newTemplateVersion">The new version for the template</param>
/// <returns>The new template</returns>
/// <exception cref="AggregateException">Thrown when the API response status code is not success or when the API call times out</exception>
/// <exception cref="InvalidOperationException">Thrown when making a Batch API Request that has already reached the maxmimum API calls per batch request</exception>
public static async Task<Template> CreateTemplateAsync(TemplateVersion newTemplateVersion)
{
// Send the POST request
var resource = "templates";
var jsonResponse = await RequestManager.SendPostRequestAsync(resource, newTemplateVersion);
// Convert the JSON result into an object
return JsonConvert.DeserializeObject<Template>(jsonResponse);
}
/// <summary>
/// Add Locale to Existing Template.
/// POST /templates/(:template_id)/locales
/// </summary>
/// <param name="templateId">The ID of the template to add the locale to</param>
/// <param name="locale">The locale to add</param>
/// <param name="templateVersion">The template version</param>
/// <returns>The template with the updated locale</returns>
/// <exception cref="AggregateException">Thrown when the API response status code is not success or when the API call times out</exception>
/// <exception cref="InvalidOperationException">Thrown when making a Batch API Request that has already reached the maxmimum API calls per batch request</exception>
public static async Task<Template> AddLocaleToTemplate(string templateId, string locale, TemplateVersion templateVersion)
{
templateVersion.locale = locale;
// Send the POST request
var resource = String.Format("templates/{0}/locales", templateId);
var jsonResponse = await RequestManager.SendPostRequestAsync(resource, templateVersion);
// Convert the JSON result into an object
return JsonConvert.DeserializeObject<Template>(jsonResponse);
}
/// <summary>
/// Create a New Template Version.
/// POST /templates/(:template_id)/versions
/// </summary>
/// <param name="templateId">The ID of the template to add the version to</param>
/// <param name="templateVersion">The new template verison to add</param>
/// <returns>The newly created template version</returns>
/// <exception cref="AggregateException">Thrown when the API response status code is not success or when the API call times out</exception>
/// <exception cref="InvalidOperationException">Thrown when making a Batch API Request that has already reached the maxmimum API calls per batch request</exception>
public static async Task<TemplateVersion> CreateTemplateVersion(string templateId, TemplateVersion templateVersion)
{
// Send the POST request
var resource = String.Format("templates/{0}/versions", templateId);
var jsonResponse = await RequestManager.SendPostRequestAsync(resource, templateVersion);
// Convert the JSON result into an object
return JsonConvert.DeserializeObject<TemplateVersion>(jsonResponse);
}
/// <summary>
/// Create a New Template Version.
/// POST /templates/(:template_id)/locales/(:locale)/versions
/// </summary>
/// <param name="templateId">The ID of the template to add the version to</param>
/// <param name="locale">The locale of the template to add the version to</param>
/// /// <param name="templateVersion">The new verison to add to the template</param>
/// <returns>The newly created template version</returns>
/// <exception cref="AggregateException">Thrown when the API response status code is not success or when the API call times out</exception>
/// <exception cref="InvalidOperationException">Thrown when making a Batch API Request that has already reached the maxmimum API calls per batch request</exception>
public static async Task<TemplateVersion> CreateTemplateVersion(string templateId, string locale, TemplateVersion templateVersion)
{
// Send the POST request
var resource = String.Format("templates/{0}/locales/{1}/versions", templateId, locale);
var jsonResponse = await RequestManager.SendPostRequestAsync(resource, templateVersion);
// Convert the JSON result into an object
return JsonConvert.DeserializeObject<TemplateVersion>(jsonResponse);
}
/// <summary>
/// Delete a specific template.
/// DELETE /templates/(:template_id)
/// </summary>
/// <param name="templateId">The ID of the template to delete</param>
/// <returns>The status of the api call</returns>
/// <exception cref="AggregateException">Thrown when the API response status code is not success or when the API call times out</exception>
/// <exception cref="InvalidOperationException">Thrown when making a Batch API Request that has already reached the maxmimum API calls per batch request</exception>
public static async Task<GenericApiCallStatus> DeleteTemplate(string templateId)
{
// Send the POST request
var resource = String.Format("templates/{0}", templateId);
var jsonResponse = await RequestManager.SendDeleteRequestAsync(resource);
// Convert the JSON result into an object
return JsonConvert.DeserializeObject<GenericApiCallStatus>(jsonResponse);
}
/// <summary>
/// Delete a specific template with a given locale.
/// DELETE /templates/(:template_id)/locales/(:locale)
/// </summary>
/// <param name="templateId">The ID of the template to delete</param>
/// <param name="locale">The locale of the template to delete</param>
/// <returns>The status of the api call</returns>
/// <exception cref="AggregateException">Thrown when the API response status code is not success or when the API call times out</exception>
/// <exception cref="InvalidOperationException">Thrown when making a Batch API Request that has already reached the maxmimum API calls per batch request</exception>
public static async Task<GenericApiCallStatus> DeleteTemplate(string templateId, string locale)
{
// Send the POST request
var resource = String.Format("templates/{0}/locales/{1}", templateId, locale);
var jsonResponse = await RequestManager.SendDeleteRequestAsync(resource);
// Convert the JSON result into an object
return JsonConvert.DeserializeObject<GenericApiCallStatus>(jsonResponse);
}
}
}
|
apache-2.0
|
skjolber/3d-bin-container-packing
|
test/src/test/java/com/github/skjolber/packing/test/BouwkampCodeParserTest.java
|
917
|
package com.github.skjolber.packing.test;
import static com.google.common.truth.Truth.assertThat;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import com.github.skjolber.packing.test.bouwkamp.BouwkampCode;
import com.github.skjolber.packing.test.bouwkamp.BouwkampCodeParser;
public class BouwkampCodeParserTest {
@Test
public void testParser() throws IOException {
BouwkampCodeParser parser = new BouwkampCodeParser();
List<BouwkampCode> codes = parser.parse(getClass().getResourceAsStream("/simplePerfectSquaredRectangles/o12spsr.bkp"), StandardCharsets.UTF_8);
assertThat(codes.size()).isEqualTo(67);
for(BouwkampCode code : codes) {
assertThat(code.getLines().stream().flatMap( f -> f.getSquares().stream()).collect(Collectors.toList()).size()).isEqualTo(12);
}
}
}
|
apache-2.0
|
kubeflow/pipelines
|
samples/core/condition/condition_test.py
|
2438
|
# Copyright 2021 The Kubeflow Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import unittest
import kfp.deprecated as kfp
import kfp_server_api
from ml_metadata.proto import Execution
from .condition import condition
from .condition_v2 import condition as condition_v2
from kfp.samples.test.utils import KfpTask, debug_verify, run_pipeline_func, TestCase
def verify_heads(t: unittest.TestCase, run: kfp_server_api.ApiRun,
tasks: dict[str, KfpTask], **kwargs):
t.assertEqual(run.status, 'Succeeded')
t.assertCountEqual(['print-msg', 'condition-1', 'flip-coin'], tasks.keys())
t.assertCountEqual(['print-msg-2', 'print-msg-3', 'flip-coin-2'],
tasks['condition-1'].children.keys())
def verify_tails(t: unittest.TestCase, run: kfp_server_api.ApiRun,
tasks: dict[str, KfpTask], **kwargs):
t.assertEqual(run.status, 'Succeeded')
t.assertCountEqual(['print-msg', 'condition-1', 'flip-coin'], tasks.keys())
t.assertIsNone(tasks['condition-1'].children)
# MLMD canceled state means NotTriggered state for KFP.
t.assertEqual(Execution.State.CANCELED, tasks['condition-1'].state)
run_pipeline_func([
TestCase(
pipeline_func=condition_v2,
mode=kfp.dsl.PipelineExecutionMode.V2_ENGINE,
arguments={"force_flip_result": "heads"},
verify_func=verify_heads,
),
TestCase(
pipeline_func=condition_v2,
mode=kfp.dsl.PipelineExecutionMode.V2_ENGINE,
arguments={"force_flip_result": "tails"},
verify_func=verify_tails,
),
TestCase(
pipeline_func=condition,
mode=kfp.dsl.PipelineExecutionMode.V1_LEGACY,
arguments={"force_flip_result": "heads"},
),
TestCase(
pipeline_func=condition,
mode=kfp.dsl.PipelineExecutionMode.V1_LEGACY,
arguments={"force_flip_result": "tails"},
),
])
|
apache-2.0
|
elcoloo/app-geoladris-snmb
|
static/loc/es/html/siia.html
|
23439
|
<html xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta http-equiv=Content-Type content="text/html; charset=windows-1252">
<meta name=ProgId content=Word.Document>
<meta name=Generator content="Microsoft Word 12">
<meta name=Originator content="Microsoft Word 12">
<link rel=File-List href="siia_archivos/filelist.xml">
<!--[if gte mso 9]><xml>
<o:DocumentProperties>
<o:Author>Matias</o:Author>
<o:Template>Normal</o:Template>
<o:LastAuthor>Matias</o:LastAuthor>
<o:Revision>2</o:Revision>
<o:TotalTime>2</o:TotalTime>
<o:Created>2014-08-26T22:48:00Z</o:Created>
<o:LastSaved>2014-08-26T22:48:00Z</o:LastSaved>
<o:Pages>1</o:Pages>
<o:Words>98</o:Words>
<o:Characters>539</o:Characters>
<o:Lines>4</o:Lines>
<o:Paragraphs>1</o:Paragraphs>
<o:CharactersWithSpaces>636</o:CharactersWithSpaces>
<o:Version>12.00</o:Version>
</o:DocumentProperties>
</xml><![endif]-->
<link rel=themeData href="siia_archivos/themedata.thmx">
<link rel=colorSchemeMapping href="siia_archivos/colorschememapping.xml">
<!--[if gte mso 9]><xml>
<w:WordDocument>
<w:Zoom>110</w:Zoom>
<w:SpellingState>Clean</w:SpellingState>
<w:GrammarState>Clean</w:GrammarState>
<w:TrackMoves>false</w:TrackMoves>
<w:TrackFormatting/>
<w:HyphenationZone>21</w:HyphenationZone>
<w:PunctuationKerning/>
<w:ValidateAgainstSchemas/>
<w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>
<w:IgnoreMixedContent>false</w:IgnoreMixedContent>
<w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>
<w:DoNotPromoteQF/>
<w:LidThemeOther>ES-AR</w:LidThemeOther>
<w:LidThemeAsian>X-NONE</w:LidThemeAsian>
<w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript>
<w:Compatibility>
<w:BreakWrappedTables/>
<w:SnapToGridInCell/>
<w:WrapTextWithPunct/>
<w:UseAsianBreakRules/>
<w:DontGrowAutofit/>
<w:SplitPgBreakAndParaMark/>
<w:DontVertAlignCellWithSp/>
<w:DontBreakConstrainedForcedTables/>
<w:DontVertAlignInTxbx/>
<w:Word11KerningPairs/>
<w:CachedColBalance/>
</w:Compatibility>
<w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
<m:mathPr>
<m:mathFont m:val="Cambria Math"/>
<m:brkBin m:val="before"/>
<m:brkBinSub m:val="--"/>
<m:smallFrac m:val="off"/>
<m:dispDef/>
<m:lMargin m:val="0"/>
<m:rMargin m:val="0"/>
<m:defJc m:val="centerGroup"/>
<m:wrapIndent m:val="1440"/>
<m:intLim m:val="subSup"/>
<m:naryLim m:val="undOvr"/>
</m:mathPr></w:WordDocument>
</xml><![endif]--><!--[if gte mso 9]><xml>
<w:LatentStyles DefLockedState="false" DefUnhideWhenUsed="true"
DefSemiHidden="true" DefQFormat="false" DefPriority="99"
LatentStyleCount="267">
<w:LsdException Locked="false" Priority="0" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Normal"/>
<w:LsdException Locked="false" Priority="9" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="heading 1"/>
<w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 2"/>
<w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 3"/>
<w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 4"/>
<w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 5"/>
<w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 6"/>
<w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 7"/>
<w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 8"/>
<w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 9"/>
<w:LsdException Locked="false" Priority="39" Name="toc 1"/>
<w:LsdException Locked="false" Priority="39" Name="toc 2"/>
<w:LsdException Locked="false" Priority="39" Name="toc 3"/>
<w:LsdException Locked="false" Priority="39" Name="toc 4"/>
<w:LsdException Locked="false" Priority="39" Name="toc 5"/>
<w:LsdException Locked="false" Priority="39" Name="toc 6"/>
<w:LsdException Locked="false" Priority="39" Name="toc 7"/>
<w:LsdException Locked="false" Priority="39" Name="toc 8"/>
<w:LsdException Locked="false" Priority="39" Name="toc 9"/>
<w:LsdException Locked="false" Priority="35" QFormat="true" Name="caption"/>
<w:LsdException Locked="false" Priority="10" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Title"/>
<w:LsdException Locked="false" Priority="1" Name="Default Paragraph Font"/>
<w:LsdException Locked="false" Priority="11" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Subtitle"/>
<w:LsdException Locked="false" Priority="22" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Strong"/>
<w:LsdException Locked="false" Priority="20" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Emphasis"/>
<w:LsdException Locked="false" Priority="59" SemiHidden="false"
UnhideWhenUsed="false" Name="Table Grid"/>
<w:LsdException Locked="false" UnhideWhenUsed="false" Name="Placeholder Text"/>
<w:LsdException Locked="false" Priority="1" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="No Spacing"/>
<w:LsdException Locked="false" Priority="60" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Shading"/>
<w:LsdException Locked="false" Priority="61" SemiHidden="false"
UnhideWhenUsed="false" Name="Light List"/>
<w:LsdException Locked="false" Priority="62" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Grid"/>
<w:LsdException Locked="false" Priority="63" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 1"/>
<w:LsdException Locked="false" Priority="64" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 2"/>
<w:LsdException Locked="false" Priority="65" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 1"/>
<w:LsdException Locked="false" Priority="66" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 2"/>
<w:LsdException Locked="false" Priority="67" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 1"/>
<w:LsdException Locked="false" Priority="68" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 2"/>
<w:LsdException Locked="false" Priority="69" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 3"/>
<w:LsdException Locked="false" Priority="70" SemiHidden="false"
UnhideWhenUsed="false" Name="Dark List"/>
<w:LsdException Locked="false" Priority="71" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Shading"/>
<w:LsdException Locked="false" Priority="72" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful List"/>
<w:LsdException Locked="false" Priority="73" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Grid"/>
<w:LsdException Locked="false" Priority="60" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Shading Accent 1"/>
<w:LsdException Locked="false" Priority="61" SemiHidden="false"
UnhideWhenUsed="false" Name="Light List Accent 1"/>
<w:LsdException Locked="false" Priority="62" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Grid Accent 1"/>
<w:LsdException Locked="false" Priority="63" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 1 Accent 1"/>
<w:LsdException Locked="false" Priority="64" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 2 Accent 1"/>
<w:LsdException Locked="false" Priority="65" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 1 Accent 1"/>
<w:LsdException Locked="false" UnhideWhenUsed="false" Name="Revision"/>
<w:LsdException Locked="false" Priority="34" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="List Paragraph"/>
<w:LsdException Locked="false" Priority="29" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Quote"/>
<w:LsdException Locked="false" Priority="30" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Intense Quote"/>
<w:LsdException Locked="false" Priority="66" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 2 Accent 1"/>
<w:LsdException Locked="false" Priority="67" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 1 Accent 1"/>
<w:LsdException Locked="false" Priority="68" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 2 Accent 1"/>
<w:LsdException Locked="false" Priority="69" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 3 Accent 1"/>
<w:LsdException Locked="false" Priority="70" SemiHidden="false"
UnhideWhenUsed="false" Name="Dark List Accent 1"/>
<w:LsdException Locked="false" Priority="71" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Shading Accent 1"/>
<w:LsdException Locked="false" Priority="72" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful List Accent 1"/>
<w:LsdException Locked="false" Priority="73" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Grid Accent 1"/>
<w:LsdException Locked="false" Priority="60" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Shading Accent 2"/>
<w:LsdException Locked="false" Priority="61" SemiHidden="false"
UnhideWhenUsed="false" Name="Light List Accent 2"/>
<w:LsdException Locked="false" Priority="62" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Grid Accent 2"/>
<w:LsdException Locked="false" Priority="63" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 1 Accent 2"/>
<w:LsdException Locked="false" Priority="64" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 2 Accent 2"/>
<w:LsdException Locked="false" Priority="65" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 1 Accent 2"/>
<w:LsdException Locked="false" Priority="66" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 2 Accent 2"/>
<w:LsdException Locked="false" Priority="67" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 1 Accent 2"/>
<w:LsdException Locked="false" Priority="68" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 2 Accent 2"/>
<w:LsdException Locked="false" Priority="69" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 3 Accent 2"/>
<w:LsdException Locked="false" Priority="70" SemiHidden="false"
UnhideWhenUsed="false" Name="Dark List Accent 2"/>
<w:LsdException Locked="false" Priority="71" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Shading Accent 2"/>
<w:LsdException Locked="false" Priority="72" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful List Accent 2"/>
<w:LsdException Locked="false" Priority="73" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Grid Accent 2"/>
<w:LsdException Locked="false" Priority="60" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Shading Accent 3"/>
<w:LsdException Locked="false" Priority="61" SemiHidden="false"
UnhideWhenUsed="false" Name="Light List Accent 3"/>
<w:LsdException Locked="false" Priority="62" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Grid Accent 3"/>
<w:LsdException Locked="false" Priority="63" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 1 Accent 3"/>
<w:LsdException Locked="false" Priority="64" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 2 Accent 3"/>
<w:LsdException Locked="false" Priority="65" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 1 Accent 3"/>
<w:LsdException Locked="false" Priority="66" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 2 Accent 3"/>
<w:LsdException Locked="false" Priority="67" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 1 Accent 3"/>
<w:LsdException Locked="false" Priority="68" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 2 Accent 3"/>
<w:LsdException Locked="false" Priority="69" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 3 Accent 3"/>
<w:LsdException Locked="false" Priority="70" SemiHidden="false"
UnhideWhenUsed="false" Name="Dark List Accent 3"/>
<w:LsdException Locked="false" Priority="71" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Shading Accent 3"/>
<w:LsdException Locked="false" Priority="72" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful List Accent 3"/>
<w:LsdException Locked="false" Priority="73" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Grid Accent 3"/>
<w:LsdException Locked="false" Priority="60" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Shading Accent 4"/>
<w:LsdException Locked="false" Priority="61" SemiHidden="false"
UnhideWhenUsed="false" Name="Light List Accent 4"/>
<w:LsdException Locked="false" Priority="62" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Grid Accent 4"/>
<w:LsdException Locked="false" Priority="63" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 1 Accent 4"/>
<w:LsdException Locked="false" Priority="64" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 2 Accent 4"/>
<w:LsdException Locked="false" Priority="65" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 1 Accent 4"/>
<w:LsdException Locked="false" Priority="66" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 2 Accent 4"/>
<w:LsdException Locked="false" Priority="67" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 1 Accent 4"/>
<w:LsdException Locked="false" Priority="68" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 2 Accent 4"/>
<w:LsdException Locked="false" Priority="69" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 3 Accent 4"/>
<w:LsdException Locked="false" Priority="70" SemiHidden="false"
UnhideWhenUsed="false" Name="Dark List Accent 4"/>
<w:LsdException Locked="false" Priority="71" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Shading Accent 4"/>
<w:LsdException Locked="false" Priority="72" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful List Accent 4"/>
<w:LsdException Locked="false" Priority="73" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Grid Accent 4"/>
<w:LsdException Locked="false" Priority="60" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Shading Accent 5"/>
<w:LsdException Locked="false" Priority="61" SemiHidden="false"
UnhideWhenUsed="false" Name="Light List Accent 5"/>
<w:LsdException Locked="false" Priority="62" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Grid Accent 5"/>
<w:LsdException Locked="false" Priority="63" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 1 Accent 5"/>
<w:LsdException Locked="false" Priority="64" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 2 Accent 5"/>
<w:LsdException Locked="false" Priority="65" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 1 Accent 5"/>
<w:LsdException Locked="false" Priority="66" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 2 Accent 5"/>
<w:LsdException Locked="false" Priority="67" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 1 Accent 5"/>
<w:LsdException Locked="false" Priority="68" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 2 Accent 5"/>
<w:LsdException Locked="false" Priority="69" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 3 Accent 5"/>
<w:LsdException Locked="false" Priority="70" SemiHidden="false"
UnhideWhenUsed="false" Name="Dark List Accent 5"/>
<w:LsdException Locked="false" Priority="71" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Shading Accent 5"/>
<w:LsdException Locked="false" Priority="72" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful List Accent 5"/>
<w:LsdException Locked="false" Priority="73" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Grid Accent 5"/>
<w:LsdException Locked="false" Priority="60" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Shading Accent 6"/>
<w:LsdException Locked="false" Priority="61" SemiHidden="false"
UnhideWhenUsed="false" Name="Light List Accent 6"/>
<w:LsdException Locked="false" Priority="62" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Grid Accent 6"/>
<w:LsdException Locked="false" Priority="63" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 1 Accent 6"/>
<w:LsdException Locked="false" Priority="64" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 2 Accent 6"/>
<w:LsdException Locked="false" Priority="65" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 1 Accent 6"/>
<w:LsdException Locked="false" Priority="66" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 2 Accent 6"/>
<w:LsdException Locked="false" Priority="67" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 1 Accent 6"/>
<w:LsdException Locked="false" Priority="68" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 2 Accent 6"/>
<w:LsdException Locked="false" Priority="69" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 3 Accent 6"/>
<w:LsdException Locked="false" Priority="70" SemiHidden="false"
UnhideWhenUsed="false" Name="Dark List Accent 6"/>
<w:LsdException Locked="false" Priority="71" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Shading Accent 6"/>
<w:LsdException Locked="false" Priority="72" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful List Accent 6"/>
<w:LsdException Locked="false" Priority="73" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Grid Accent 6"/>
<w:LsdException Locked="false" Priority="19" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Subtle Emphasis"/>
<w:LsdException Locked="false" Priority="21" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Intense Emphasis"/>
<w:LsdException Locked="false" Priority="31" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Subtle Reference"/>
<w:LsdException Locked="false" Priority="32" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Intense Reference"/>
<w:LsdException Locked="false" Priority="33" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Book Title"/>
<w:LsdException Locked="false" Priority="37" Name="Bibliography"/>
<w:LsdException Locked="false" Priority="39" QFormat="true" Name="TOC Heading"/>
</w:LatentStyles>
</xml><![endif]-->
<style>
<!--
/* Font Definitions */
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;
mso-font-charset:1;
mso-generic-font-family:roman;
mso-font-format:other;
mso-font-pitch:variable;
mso-font-signature:0 0 0 0 0 0;}
@font-face
{font-family:Calibri;
panose-1:2 15 5 2 2 2 4 3 2 4;
mso-font-charset:0;
mso-generic-font-family:swiss;
mso-font-pitch:variable;
mso-font-signature:-536870145 1073786111 1 0 415 0;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{mso-style-unhide:no;
mso-style-qformat:yes;
mso-style-parent:"";
margin-top:0cm;
margin-right:0cm;
margin-bottom:10.0pt;
margin-left:0cm;
line-height:115%;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:Calibri;
mso-fareast-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;
mso-fareast-language:EN-US;}
a:link, span.MsoHyperlink
{mso-style-noshow:yes;
mso-style-priority:99;
color:blue;
text-decoration:underline;
text-underline:single;}
a:visited, span.MsoHyperlinkFollowed
{mso-style-noshow:yes;
mso-style-priority:99;
color:purple;
mso-themecolor:followedhyperlink;
text-decoration:underline;
text-underline:single;}
span.apple-converted-space
{mso-style-name:apple-converted-space;
mso-style-unhide:no;}
span.SpellE
{mso-style-name:"";
mso-spl-e:yes;}
.MsoChpDefault
{mso-style-type:export-only;
mso-default-props:yes;
font-size:10.0pt;
mso-ansi-font-size:10.0pt;
mso-bidi-font-size:10.0pt;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:Calibri;
mso-fareast-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;
mso-fareast-language:EN-US;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 3.0cm 70.85pt 3.0cm;
mso-header-margin:35.4pt;
mso-footer-margin:35.4pt;
mso-paper-source:0;}
div.WordSection1
{page:WordSection1;}
-->
</style>
<!--[if gte mso 10]>
<style>
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Tabla normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-fareast-language:EN-US;}
</style>
<![endif]--><!--[if gte mso 9]><xml>
<o:shapedefaults v:ext="edit" spidmax="3074"/>
</xml><![endif]--><!--[if gte mso 9]><xml>
<o:shapelayout v:ext="edit">
<o:idmap v:ext="edit" data="1"/>
</o:shapelayout></xml><![endif]-->
</head>
<body lang=ES-AR link=blue vlink=purple style='tab-interval:35.4pt'>
<div class=WordSection1>
<p class=MsoNormal style='text-align:justify;line-height:normal'><b
style='mso-bidi-font-weight:normal'><span style='mso-bidi-font-size:10.0pt;
color:#0070C0;background:white'>Sistema Integrado de Información Agropecuaria
(SIIA)<o:p></o:p></span></b></p>
<p class=MsoNormal style='text-align:justify;line-height:normal'><span
style='mso-bidi-font-size:10.0pt;background:white'>El Sistema Integrado de
Información Agropecuaria (SIIA) es un proyecto nacional del Programa de
Servicios Agrícolas Provinciales (PROSAP),<span style='mso-spacerun:yes'>
</span>financiado por el Banco Interamericano de Desarrollo (BID) y con
presupuesto de la Nación. El objetivo principal del SIIA es mejorar en
cantidad, calidad, relevancia, cobertura y accesibilidad la información
agropecuaria relevada y brindada por el <span class=SpellE>MAGyP</span>, a
partir de la consolidación de una infraestructura técnica, la disponibilidad de
sistemas informáticos homogéneos y homologados y la adopción de GIS. <o:p></o:p></span></p>
<p class=MsoNormal style='text-align:justify;line-height:normal'><span
style='mso-bidi-font-size:10.0pt;background:white'>http://www.siia.gov.ar/institucional<o:p></o:p></span></p>
</div>
</body>
</html>
|
apache-2.0
|
Kitware/HPCCloud
|
src/panels/SchedulerConfig/SGE.js
|
2229
|
import React from 'react';
import PropTypes from 'prop-types';
import style from 'HPCCloudStyle/ItemEditor.mcss';
export default class SchedulerConfigSGE extends React.Component {
constructor(props) {
super(props);
this.updateConfig = this.updateConfig.bind(this);
}
updateConfig(event) {
if (this.props.onChange) {
this.props.onChange(event);
}
}
render() {
return (
<div>
<section className={style.group}>
<label className={style.label}>Number of slots</label>
<input
className={style.input}
type="number"
min="1"
max={
this.props.runtime && this.props.max && this.props.max.sge
? this.props.max.sge.numberOfSlots
: null
}
value={this.props.config.sge.numberOfSlots}
data-key="sge.numberOfSlots"
onChange={this.updateConfig}
/>
</section>
<section className={style.group}>
<label className={style.label}>GPUs/Node</label>
<input
className={style.input}
type="number"
min="0"
max={
this.props.runtime && this.props.max && this.props.max.sge
? this.props.max.sge.numberOfGpusPerNode
: null
}
value={this.props.config.sge.numberOfGpusPerNode}
data-key="sge.numberOfGpusPerNode"
onChange={this.updateConfig}
/>
</section>
<section className={style.group}>
<label className={style.label}>Parallel Environment</label>
<input
className={style.input}
type="text"
value={this.props.config.sge.parallelEnvironment}
data-key="sge.parallelEnvironment"
onChange={this.updateConfig}
required
/>
</section>
</div>
);
}
}
SchedulerConfigSGE.propTypes = {
config: PropTypes.object,
max: PropTypes.object,
onChange: PropTypes.func,
runtime: PropTypes.bool,
};
SchedulerConfigSGE.defaultProps = {
config: undefined,
max: undefined,
onChange: undefined,
runtime: undefined,
};
|
apache-2.0
|
NativeScript/android-runtime
|
test-app/runtime/src/main/cpp/JEnv.h
|
15392
|
#ifndef JENV_H_
#define JENV_H_
#include "jni.h"
#include <map>
#include <string>
namespace tns {
class JEnv {
public:
JEnv();
JEnv(JNIEnv* jniEnv);
~JEnv();
operator JNIEnv* () const;
jclass GetObjectClass(jobject obj);
jsize GetArrayLength(jarray array);
jmethodID GetMethodID(jclass clazz, const std::string& name, const std::string& sig);
jmethodID GetStaticMethodID(jclass clazz, const std::string& name, const std::string& sig);
std::pair<jmethodID,jclass> GetInterfaceStaticMethodIDAndJClass(
const std::string &interfaceName, const std::string &methodName,
const std::string &sig);
jfieldID GetFieldID(jclass clazz, const std::string& name, const std::string& sig);
jfieldID GetStaticFieldID(jclass clazz, const std::string& name, const std::string& sig);
void CallStaticVoidMethodA(jclass clazz, jmethodID methodID, jvalue* args);
void CallNonvirtualVoidMethodA(jobject obj, jclass clazz, jmethodID methodID, jvalue* args);
void CallVoidMethodA(jobject obj, jmethodID methodID, jvalue* args);
jboolean CallStaticBooleanMethodA(jclass clazz, jmethodID methodID, jvalue* args);
jboolean CallNonvirtualBooleanMethodA(jobject obj, jclass clazz, jmethodID methodID, jvalue* args);
jboolean CallBooleanMethodA(jobject obj, jmethodID methodID, jvalue* args);
jbyte CallStaticByteMethodA(jclass clazz, jmethodID methodID, jvalue* args);
jbyte CallNonvirtualByteMethodA(jobject obj, jclass clazz, jmethodID methodID, jvalue* args);
jbyte CallByteMethodA(jobject obj, jmethodID methodID, jvalue* args);
jchar CallStaticCharMethodA(jclass clazz, jmethodID methodID, jvalue* args);
jchar CallNonvirtualCharMethodA(jobject obj, jclass clazz, jmethodID methodID, jvalue* args);
jchar CallCharMethodA(jobject obj, jmethodID methodID, jvalue* args);
jshort CallStaticShortMethodA(jclass clazz, jmethodID methodID, jvalue* args);
jshort CallNonvirtualShortMethodA(jobject obj, jclass clazz, jmethodID methodID, jvalue* args);
jshort CallShortMethodA(jobject obj, jmethodID methodID, jvalue* args);
jint CallStaticIntMethodA(jclass clazz, jmethodID methodID, jvalue* args);
jint CallNonvirtualIntMethodA(jobject obj, jclass clazz, jmethodID methodID, jvalue* args);
jint CallIntMethodA(jobject obj, jmethodID methodID, jvalue* args);
jlong CallStaticLongMethodA(jclass clazz, jmethodID methodID, jvalue* args);
jlong CallNonvirtualLongMethodA(jobject obj, jclass clazz, jmethodID methodID, jvalue* args);
jlong CallLongMethodA(jobject obj, jmethodID methodID, jvalue* args);
jfloat CallStaticFloatMethodA(jclass clazz, jmethodID methodID, jvalue* args);
jfloat CallNonvirtualFloatMethodA(jobject obj, jclass clazz, jmethodID methodID, jvalue* args);
jfloat CallFloatMethodA(jobject obj, jmethodID methodID, jvalue* args);
jdouble CallStaticDoubleMethodA(jclass clazz, jmethodID methodID, jvalue* args);
jdouble CallNonvirtualDoubleMethodA(jobject obj, jclass clazz, jmethodID methodID, jvalue* args);
jdouble CallDoubleMethodA(jobject obj, jmethodID methodID, jvalue* args);
jobject CallStaticObjectMethodA(jclass clazz, jmethodID methodID, jvalue* args);
jobject CallNonvirtualObjectMethodA(jobject obj, jclass clazz, jmethodID methodID, jvalue* args);
jobject CallObjectMethodA(jobject obj, jmethodID methodID, jvalue* args);
jobject GetStaticObjectField(jclass clazz, jfieldID fieldID);
jboolean GetStaticBooleanField(jclass clazz, jfieldID fieldID);
jbyte GetStaticByteField(jclass clazz, jfieldID fieldID);
jchar GetStaticCharField(jclass clazz, jfieldID fieldID);
jshort GetStaticShortField(jclass clazz, jfieldID fieldID);
jint GetStaticIntField(jclass clazz, jfieldID fieldID);
jlong GetStaticLongField(jclass clazz, jfieldID fieldID);
jfloat GetStaticFloatField(jclass clazz, jfieldID fieldID);
jdouble GetStaticDoubleField(jclass clazz, jfieldID fieldID);
void SetStaticObjectField(jclass clazz, jfieldID fieldID, jobject value);
void SetStaticBooleanField(jclass clazz, jfieldID fieldID, jboolean value);
void SetStaticByteField(jclass clazz, jfieldID fieldID, jbyte value);
void SetStaticCharField(jclass clazz, jfieldID fieldID, jchar value);
void SetStaticShortField(jclass clazz, jfieldID fieldID, jshort value);
void SetStaticIntField(jclass clazz, jfieldID fieldID, jint value);
void SetStaticLongField(jclass clazz, jfieldID fieldID, jlong value);
void SetStaticFloatField(jclass clazz, jfieldID fieldID, jfloat value);
void SetStaticDoubleField(jclass clazz, jfieldID fieldID, jdouble value);
jobject GetObjectField(jobject obj, jfieldID fieldID);
jboolean GetBooleanField(jobject obj, jfieldID fieldID);
jbyte GetByteField(jobject obj, jfieldID fieldID);
jchar GetCharField(jobject obj, jfieldID fieldID);
jshort GetShortField(jobject obj, jfieldID fieldID);
jint GetIntField(jobject obj, jfieldID fieldID);
jlong GetLongField(jobject obj, jfieldID fieldID);
jfloat GetFloatField(jobject obj, jfieldID fieldID);
jdouble GetDoubleField(jobject obj, jfieldID fieldID);
void SetObjectField(jobject obj, jfieldID fieldID, jobject value);
void SetBooleanField(jobject obj, jfieldID fieldID, jboolean value);
void SetByteField(jobject obj, jfieldID fieldID, jbyte value);
void SetCharField(jobject obj, jfieldID fieldID, jchar value);
void SetShortField(jobject obj, jfieldID fieldID, jshort value);
void SetIntField(jobject obj, jfieldID fieldID, jint value);
void SetLongField(jobject obj, jfieldID fieldID, jlong value);
void SetFloatField(jobject obj, jfieldID fieldID, jfloat value);
void SetDoubleField(jobject obj, jfieldID fieldID, jdouble value);
jstring NewString(const jchar* unicodeChars, jsize len);
jstring NewStringUTF(const char* bytes);
jobjectArray NewObjectArray(jsize length, jclass elementClass, jobject initialElement);
jobject GetObjectArrayElement(jobjectArray array, jsize index);
void SetObjectArrayElement(jobjectArray array, jsize index, jobject value);
const char* GetStringUTFChars(jstring str, jboolean* isCopy);
void ReleaseStringUTFChars(jstring str, const char* utf);
const jchar* GetStringChars(jstring str, jboolean* isCopy);
void ReleaseStringChars(jstring str, const jchar* chars);
const int GetStringLength(jstring str);
const int GetStringUTFLength(jstring str);
void GetStringUTFRegion(jstring str, jsize start, jsize len, char* buf);
jint Throw(jthrowable obj);
jint ThrowNew(jclass clazz, const std::string& message);
jboolean ExceptionCheck();
jthrowable ExceptionOccurred();
void ExceptionDescribe();
void ExceptionClear();
jboolean IsInstanceOf(jobject obj, jclass clazz);
jobjectRefType GetObjectRefType(jobject obj);
jobject NewGlobalRef(jobject obj);
jweak NewWeakGlobalRef(jobject obj);
void DeleteGlobalRef(jobject globalRef);
void DeleteWeakGlobalRef(jweak obj);
jobject NewLocalRef(jobject ref);
void DeleteLocalRef(jobject localRef);
jbyteArray NewByteArray(jsize length);
jbooleanArray NewBooleanArray(jsize length);
jcharArray NewCharArray(jsize length);
jshortArray NewShortArray(jsize length);
jintArray NewIntArray(jsize length);
jlongArray NewLongArray(jsize length);
jfloatArray NewFloatArray(jsize length);
jdoubleArray NewDoubleArray(jsize length);
jbyte* GetByteArrayElements(jbyteArray array, jboolean* isCopy);
void ReleaseByteArrayElements(jbyteArray array, jbyte* elems, jint mode);
void GetBooleanArrayRegion(jbooleanArray array, jsize start, jsize len, jboolean* buf);
void GetByteArrayRegion(jbyteArray array, jsize start, jsize len, jbyte* buf);
void GetCharArrayRegion(jcharArray array, jsize start, jsize len, jchar* buf);
void GetShortArrayRegion(jshortArray array, jsize start, jsize len, jshort* buf);
void GetIntArrayRegion(jintArray array, jsize start, jsize len, jint* buf);
void GetLongArrayRegion(jlongArray array, jsize start, jsize len, jlong* buf);
void GetFloatArrayRegion(jfloatArray array, jsize start, jsize len, jfloat* buf);
void GetDoubleArrayRegion(jdoubleArray array, jsize start, jsize len, jdouble* buf);
void SetByteArrayRegion(jbyteArray array, jsize start, jsize len, const jbyte* buf);
void SetBooleanArrayRegion(jbooleanArray array, jsize start, jsize len, const jboolean* buf);
void SetCharArrayRegion(jcharArray array, jsize start, jsize len, const jchar* buf);
void SetShortArrayRegion(jshortArray array, jsize start, jsize len, const jshort* buf);
void SetIntArrayRegion(jintArray array, jsize start, jsize len, const jint* buf);
void SetLongArrayRegion(jlongArray array, jsize start, jsize len, const jlong* buf);
void SetFloatArrayRegion(jfloatArray array, jsize start, jsize len, const jfloat* buf);
void SetDoubleArrayRegion(jdoubleArray array, jsize start, jsize len, const jdouble* buf);
jclass FindClass(const std::string& className);
/*
* The "CheckForClassInCache" will check if a class is loaded into the cache
* if it is: it returns a global reference of it
* if it is not: it will return "nullptr".
*/
jclass CheckForClassInCache(const std::string& className);
/*
* "InsertClassIntoCache" will take care of deleting the LocalReference of passed "jclass& tmp".
* A new GlobalReference object will be created from "tmp". The function returns the global object.
*/
jclass InsertClassIntoCache(const std::string& className, jclass& tmp);
jobject NewDirectByteBuffer(void* address, jlong capacity);
void* GetDirectBufferAddress(jobject buf);
jlong GetDirectBufferCapacity(jobject buf);
jboolean IsAssignableFrom(jclass clazz1, jclass clazz2);
template<typename ... Args>
void CallVoidMethod(jobject obj, jmethodID methodID, Args ... args) {
m_env->CallVoidMethod(obj, methodID, args...);
CheckForJavaException();
}
template<typename ... Args>
void CallStaticVoidMethod(jclass clazz, jmethodID methodID, Args ... args) {
m_env->CallStaticVoidMethod(clazz, methodID, args...);
CheckForJavaException();
}
template<typename ... Args>
void CallAppFail(jclass clazz, jmethodID methodID, Args ... args) {
m_env->CallStaticVoidMethod(clazz, methodID, args...);
}
template<typename ... Args>
jint CallStaticIntMethod(jclass clazz, jmethodID methodID, Args ... args) {
jint ji = m_env->CallStaticIntMethod(clazz, methodID, args...);
CheckForJavaException();
return ji;
}
template<typename ... Args>
jlong CallStaticLongMethod(jclass clazz, jmethodID methodID, Args ... args) {
jlong jd = m_env->CallStaticLongMethod(clazz, methodID, args...);
CheckForJavaException();
return jd;
}
template<typename ... Args>
jobject CallStaticObjectMethod(jclass clazz, jmethodID methodID, Args ... args) {
jobject jo = m_env->CallStaticObjectMethod(clazz, methodID, args...);
CheckForJavaException();
return jo;
}
template<typename ... Args>
jboolean CallStaticBooleanMethod(jclass clazz, jmethodID methodID, Args ... args) {
jboolean jbl = m_env->CallStaticBooleanMethod(clazz, methodID, args...);
CheckForJavaException();
return jbl;
}
template<typename ... Args>
jobject CallObjectMethod(jobject obj, jmethodID methodID, Args ... args) {
jobject jo = m_env->CallObjectMethod(obj, methodID, args...);
CheckForJavaException();
return jo;
}
template<typename ... Args>
jboolean CallBooleanMethod(jobject obj, jmethodID methodID, Args ... args) {
jboolean jbl = m_env->CallBooleanMethod(obj, methodID, args...);
CheckForJavaException();
return jbl;
}
template<typename ... Args>
jchar CallCharMethod(jobject obj, jmethodID methodID, Args ... args) {
jchar jc = m_env->CallCharMethod(obj, methodID, args...);
CheckForJavaException();
return jc;
}
template<typename ... Args>
jbyte CallByteMethod(jobject obj, jmethodID methodID, Args ... args) {
jbyte jbt = m_env->CallByteMethod(obj, methodID, args...);
CheckForJavaException();
return jbt;
}
template<typename ... Args>
jshort CallShortMethod(jobject obj, jmethodID methodID, Args ... args) {
jshort jsh = m_env->CallShortMethod(obj, methodID, args...);
CheckForJavaException();
return jsh;
}
template<typename ... Args>
jint CallIntMethod(jobject obj, jmethodID methodID, Args ... args) {
jint ji = m_env->CallIntMethod(obj, methodID, args...);
CheckForJavaException();
return ji;
}
template<typename ... Args>
jlong CallLongMethod(jobject obj, jmethodID methodID, Args ... args) {
jlong jl = m_env->CallLongMethod(obj, methodID, args...);
CheckForJavaException();
return jl;
}
template<typename ... Args>
jfloat CallFloatMethod(jobject obj, jmethodID methodID, Args ... args) {
jfloat jf = m_env->CallFloatMethod(obj, methodID, args...);
CheckForJavaException();
return jf;
}
template<typename ... Args>
jdouble CallDoubleMethod(jobject obj, jmethodID methodID, Args ... args) {
jdouble jd = m_env->CallDoubleMethod(obj, methodID, args...);
CheckForJavaException();
return jd;
}
template<typename ... Args>
jobject NewObject(jclass clazz, jmethodID methodID, Args ... args) {
jobject jo = m_env->NewObject(clazz, methodID, args...);
CheckForJavaException();
return jo;
}
jobject NewObjectA(jclass clazz, jmethodID methodID, jvalue* args) {
jobject jo = m_env->NewObjectA(clazz, methodID, args);
CheckForJavaException();
return jo;
}
static void Init(JavaVM* jvm);
private:
void CheckForJavaException();
JNIEnv* m_env;
static JavaVM* s_jvm;
static jclass RUNTIME_CLASS;
static jmethodID GET_CACHED_CLASS_METHOD_ID;
static std::map<std::string, jclass> s_classCache;
};
}
#endif /* JENV_H_ */
|
apache-2.0
|
leidenuniv-lacdr-abs/ms-vfetc
|
rebuild_and_run.sh
|
971
|
#!/usr/bin/env bash
docker build --no-cache -t vfetc .
docker run -it --rm -v $(pwd)/data/tmp:/out vfetc files=data/vendor/agilent/batches.zip outputfile=/out/agilent_from_zip.txt && cat data/tmp/agilent_from_zip.txt
docker run -it --rm -v $(pwd)/data/tmp:/out vfetc files=data/vendor/agilent/example_batch1.txt,data/vendor/agilent/example_batch2.txt outputfile=/out/agilent.txt && cat data/tmp/agilent.txt
docker run -it --rm -v $(pwd)/data/tmp:/out vfetc files=data/vendor/sciex/example_batch1.txt outputfile=/out/sciex.txt && cat data/tmp/sciex.txt
docker run -it --rm -v $(pwd)/data/tmp:/out vfetc files=data/vendor/shimadzu/example_batch1.txt,data/vendor/shimadzu/example_batch2.txt,data/vendor/shimadzu/example_batch3.txt outputfile=/out/shimadzu.txt && cat data/tmp/shimadzu.txt
docker run -it --rm -v $(pwd)/data/tmp:/out vfetc files=data/vendor/waters/example_batch1.txt,data/vendor/waters/example_batch2.txt outputfile=/out/waters.txt && cat data/tmp/waters.txt
|
apache-2.0
|
ziacik/TypeScript
|
tests/cases/unittests/services/preProcessFile.ts
|
20837
|
/// <reference path="..\..\..\..\src\harness\external\mocha.d.ts" />
/// <reference path="..\..\..\..\src\harness\harnessLanguageService.ts" />
declare namespace chai.assert {
function deepEqual(actual: any, expected: any): void;
}
describe('PreProcessFile:', function () {
function test(sourceText: string, readImportFile: boolean, detectJavaScriptImports: boolean, expectedPreProcess: ts.PreProcessedFileInfo): void {
var resultPreProcess = ts.preProcessFile(sourceText, readImportFile, detectJavaScriptImports);
assert.equal(resultPreProcess.isLibFile, expectedPreProcess.isLibFile, "Pre-processed file has different value for isLibFile. Expected: " + expectedPreProcess.isLibFile + ". Actual: " + resultPreProcess.isLibFile);
checkFileReferenceList("Imported files", expectedPreProcess.importedFiles, resultPreProcess.importedFiles);
checkFileReferenceList("Referenced files", expectedPreProcess.referencedFiles, resultPreProcess.referencedFiles);
checkFileReferenceList("Type reference directives", expectedPreProcess.typeReferenceDirectives, resultPreProcess.typeReferenceDirectives);
assert.deepEqual(resultPreProcess.ambientExternalModules, expectedPreProcess.ambientExternalModules);
}
function checkFileReferenceList(kind: string, expected: ts.FileReference[], actual: ts.FileReference[]) {
if (expected === actual) {
return;
}
if (!expected) {
assert.isTrue(false, `Expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
}
assert.equal(actual.length, expected.length, `[${kind}] Actual array's length does not match expected length. Expected files: ${JSON.stringify(expected)}, actual files: ${JSON.stringify(actual)}`);
for (var i = 0; i < expected.length; ++i) {
var actualReference = actual[i];
var expectedReference = expected[i];
assert.equal(actualReference.fileName, expectedReference.fileName, `[${kind}] actual file path does not match expected. Expected: "${expectedReference.fileName}". Actual: "${actualReference.fileName}".`);
assert.equal(actualReference.pos, expectedReference.pos, `[${kind}] actual file start position does not match expected. Expected: "${expectedReference.pos}". Actual: "${actualReference.pos}".`);
assert.equal(actualReference.end, expectedReference.end, `[${kind}] actual file end pos does not match expected. Expected: "${expectedReference.end}". Actual: "${actualReference.end}".`);
}
}
describe("Test preProcessFiles,", function () {
it("Correctly return referenced files from triple slash", function () {
test("///<reference path = \"refFile1.ts\" />" + "\n" + "///<reference path =\"refFile2.ts\"/>" + "\n" + "///<reference path=\"refFile3.ts\" />" + "\n" + "///<reference path= \"..\\refFile4d.ts\" />",
/* readImports */true,
/* detectJavaScriptImports */ false,
{
referencedFiles: [{ fileName: "refFile1.ts", pos: 0, end: 37 }, { fileName: "refFile2.ts", pos: 38, end: 73 },
{ fileName: "refFile3.ts", pos: 74, end: 109 }, { fileName: "..\\refFile4d.ts", pos: 110, end: 150 }],
importedFiles: <ts.FileReference[]>[],
typeReferenceDirectives: [],
ambientExternalModules: undefined,
isLibFile: false
});
}),
it("Do not return reference path because of invalid triple-slash syntax", function () {
test("///<reference path\"refFile1.ts\" />" + "\n" + "///<reference path =\"refFile2.ts\">" + "\n" + "///<referencepath=\"refFile3.ts\" />" + "\n" + "///<reference pat= \"refFile4d.ts\" />",
/* readImports */true,
/* detectJavaScriptImports */ false,
{
referencedFiles: <ts.FileReference[]>[],
importedFiles: <ts.FileReference[]>[],
typeReferenceDirectives: [],
ambientExternalModules: undefined,
isLibFile: false
});
}),
it("Correctly return imported files", function () {
test("import i1 = require(\"r1.ts\"); import i2 =require(\"r2.ts\"); import i3= require(\"r3.ts\"); import i4=require(\"r4.ts\"); import i5 = require (\"r5.ts\");",
/* readImports */true,
/* detectJavaScriptImports */ false,
{
referencedFiles: <ts.FileReference[]>[],
typeReferenceDirectives: [],
importedFiles: [{ fileName: "r1.ts", pos: 20, end: 25 }, { fileName: "r2.ts", pos: 49, end: 54 }, { fileName: "r3.ts", pos: 78, end: 83 },
{ fileName: "r4.ts", pos: 106, end: 111 }, { fileName: "r5.ts", pos: 138, end: 143 }],
ambientExternalModules: undefined,
isLibFile: false
});
}),
it("Do not return imported files if readImportFiles argument is false", function () {
test("import i1 = require(\"r1.ts\"); import i2 =require(\"r2.ts\"); import i3= require(\"r3.ts\"); import i4=require(\"r4.ts\"); import i5 = require (\"r5.ts\");",
/* readImports */ false,
/* detectJavaScriptImports */ false,
{
referencedFiles: <ts.FileReference[]>[],
typeReferenceDirectives: [],
importedFiles: <ts.FileReference[]>[],
ambientExternalModules: undefined,
isLibFile: false
});
}),
it("Do not return import path because of invalid import syntax", function () {
test("import i1 require(\"r1.ts\"); import = require(\"r2.ts\") import i3= require(\"r3.ts\"); import i5",
/* readImports */true,
/* detectJavaScriptImports */ false,
{
referencedFiles: <ts.FileReference[]>[],
typeReferenceDirectives: [],
importedFiles: [{ fileName: "r3.ts", pos: 73, end: 78 }],
ambientExternalModules: undefined,
isLibFile: false
});
}),
it("Correctly return referenced files and import files", function () {
test("///<reference path=\"refFile1.ts\" />" + "\n" + "///<reference path =\"refFile2.ts\"/>" + "\n" + "import i1 = require(\"r1.ts\"); import i2 =require(\"r2.ts\");",
/* readImports */true,
/* detectJavaScriptImports */ false,
{
referencedFiles: [{ fileName: "refFile1.ts", pos: 0, end: 35 }, { fileName: "refFile2.ts", pos: 36, end: 71 }],
typeReferenceDirectives: [],
importedFiles: [{ fileName: "r1.ts", pos: 92, end: 97 }, { fileName: "r2.ts", pos: 121, end: 126 }],
ambientExternalModules: undefined,
isLibFile: false
});
}),
it("Correctly return referenced files and import files even with some invalid syntax", function () {
test("///<reference path=\"refFile1.ts\" />" + "\n" + "///<reference path \"refFile2.ts\"/>" + "\n" + "import i1 = require(\"r1.ts\"); import = require(\"r2.ts\"); import i2 = require(\"r3.ts\");",
/* readImports */true,
/* detectJavaScriptImports */ false,
{
referencedFiles: [{ fileName: "refFile1.ts", pos: 0, end: 35 }],
typeReferenceDirectives: [],
importedFiles: [{ fileName: "r1.ts", pos: 91, end: 96 }, { fileName: "r3.ts", pos: 148, end: 153 }],
ambientExternalModules: undefined,
isLibFile: false
})
});
it("Correctly return ES6 imports", function () {
test("import * as ns from \"m1\";" + "\n" +
"import def, * as ns from \"m2\";" + "\n" +
"import def from \"m3\";" + "\n" +
"import {a} from \"m4\";" + "\n" +
"import {a as A} from \"m5\";" + "\n" +
"import {a as A, b, c as C} from \"m6\";" + "\n" +
"import def , {a, b, c as C} from \"m7\";" + "\n",
/* readImports */true,
/* detectJavaScriptImports */ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
importedFiles: [
{ fileName: "m1", pos: 20, end: 22 },
{ fileName: "m2", pos: 51, end: 53 },
{ fileName: "m3", pos: 73, end: 75 },
{ fileName: "m4", pos: 95, end: 97 },
{ fileName: "m5", pos: 122, end: 124 },
{ fileName: "m6", pos: 160, end: 162 },
{ fileName: "m7", pos: 199, end: 201 }
],
ambientExternalModules: undefined,
isLibFile: false
})
});
it("Correctly return ES6 exports", function () {
test("export * from \"m1\";" + "\n" +
"export {a} from \"m2\";" + "\n" +
"export {a as A} from \"m3\";" + "\n" +
"export {a as A, b, c as C} from \"m4\";" + "\n",
/* readImports */true,
/* detectJavaScriptImports */ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
importedFiles: [
{ fileName: "m1", pos: 14, end: 16 },
{ fileName: "m2", pos: 36, end: 38 },
{ fileName: "m3", pos: 63, end: 65 },
{ fileName: "m4", pos: 101, end: 103 },
],
ambientExternalModules: undefined,
isLibFile: false
})
});
it("Correctly return ambient external modules", () => {
test(`
declare module A {}
declare module "B" {}
function foo() {
}
`,
/* readImports */ true,
/* detectJavaScriptImports */ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
importedFiles: [],
ambientExternalModules: ["B"],
isLibFile: false
})
});
it("Correctly handles export import declarations", function () {
test("export import a = require(\"m1\");",
/* readImports */true,
/* detectJavaScriptImports */ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
importedFiles: [
{ fileName: "m1", pos: 26, end: 28 }
],
ambientExternalModules: undefined,
isLibFile: false
})
});
it("Correctly handles export require calls in JavaScript files", function () {
test(`
export import a = require("m1");
var x = require('m2');
foo(require('m3'));
var z = { f: require('m4') }
`,
/* readImports */true,
/* detectJavaScriptImports */ true,
{
referencedFiles: [],
typeReferenceDirectives: [],
importedFiles: [
{ fileName: "m1", pos: 39, end: 41 },
{ fileName: "m2", pos: 74, end: 76 },
{ fileName: "m3", pos: 105, end: 107 },
{ fileName: "m4", pos: 146, end: 148 },
],
ambientExternalModules: undefined,
isLibFile: false
})
});
it("Correctly handles dependency lists in define([deplist]) calls in JavaScript files", function () {
test(`
define(["mod1", "mod2"], (m1, m2) => {
});
`,
/* readImports */true,
/* detectJavaScriptImports */ true,
{
referencedFiles: [],
typeReferenceDirectives: [],
importedFiles: [
{ fileName: "mod1", pos: 21, end: 25 },
{ fileName: "mod2", pos: 29, end: 33 },
],
ambientExternalModules: undefined,
isLibFile: false
})
});
it("Correctly handles dependency lists in define(modName, [deplist]) calls in JavaScript files", function () {
test(`
define("mod", ["mod1", "mod2"], (m1, m2) => {
});
`,
/* readImports */true,
/* detectJavaScriptImports */ true,
{
referencedFiles: [],
typeReferenceDirectives: [],
importedFiles: [
{ fileName: "mod1", pos: 28, end: 32 },
{ fileName: "mod2", pos: 36, end: 40 },
],
ambientExternalModules: undefined,
isLibFile: false
})
});
it("correctly handles augmentations in external modules - 1", () => {
test(`
declare module "../Observable" {
interface I {}
}
export {}
`,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
importedFiles: [
{ "fileName": "../Observable", "pos": 28, "end": 41 }
],
ambientExternalModules: undefined,
isLibFile: false
})
});
it("correctly handles augmentations in external modules - 2", () => {
test(`
declare module "../Observable" {
interface I {}
}
import * as x from "m";
`,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
importedFiles: [
{ "fileName": "m", "pos": 135, "end": 136 },
{ "fileName": "../Observable", "pos": 28, "end": 41 }
],
ambientExternalModules: undefined,
isLibFile: false
})
});
it("correctly handles augmentations in external modules - 3", () => {
test(`
declare module "../Observable" {
interface I {}
}
import m = require("m");
`,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
importedFiles: [
{ "fileName": "m", "pos": 135, "end": 136 },
{ "fileName": "../Observable", "pos": 28, "end": 41 }
],
ambientExternalModules: undefined,
isLibFile: false
})
});
it("correctly handles augmentations in external modules - 4", () => {
test(`
declare module "../Observable" {
interface I {}
}
namespace N {}
export = N;
`,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
importedFiles: [
{ "fileName": "../Observable", "pos": 28, "end": 41 }
],
ambientExternalModules: undefined,
isLibFile: false
})
});
it("correctly handles augmentations in external modules - 5", () => {
test(`
declare module "../Observable" {
interface I {}
}
namespace N {}
export import IN = N;
`,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
importedFiles: [
{ "fileName": "../Observable", "pos": 28, "end": 41 }
],
ambientExternalModules: undefined,
isLibFile: false
})
});
it("correctly handles augmentations in external modules - 6", () => {
test(`
declare module "../Observable" {
interface I {}
}
export let x = 1;
`,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
importedFiles: [
{ "fileName": "../Observable", "pos": 28, "end": 41 }
],
ambientExternalModules: undefined,
isLibFile: false
})
});
it ("correctly handles augmentations in ambient external modules - 1", () => {
test(`
declare module "m1" {
export * from "m2";
declare module "augmentation" {
interface I {}
}
}
`,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
importedFiles: [
{ "fileName": "m2", "pos": 65, "end": 67 },
{ "fileName": "augmentation", "pos": 102, "end": 114 }
],
ambientExternalModules: ["m1"],
isLibFile: false
});
});
it ("correctly handles augmentations in ambient external modules - 2", () => {
test(`
namespace M { var x; }
import IM = M;
declare module "m1" {
export * from "m2";
declare module "augmentation" {
interface I {}
}
}
`,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
importedFiles: [
{ "fileName": "m2", "pos": 127, "end": 129 },
{ "fileName": "augmentation", "pos": 164, "end": 176 }
],
ambientExternalModules: ["m1"],
isLibFile: false
});
});
it ("correctly recognizes type reference directives", () => {
test(`
/// <reference path="a"/>
/// <reference types="a1"/>
/// <reference path="a2"/>
/// <reference types="a3"/>
`,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [
{ "pos": 13, "end": 38, "fileName": "a" },
{ "pos": 91, "end": 117, "fileName": "a2" }
],
typeReferenceDirectives: [
{ "pos": 51, "end": 78, "fileName": "a1" },
{ "pos": 130, "end": 157, "fileName": "a3" }
],
importedFiles: [],
ambientExternalModules: undefined,
isLibFile: false
});
})
});
});
|
apache-2.0
|
SunnyRx/JNUDarkSide
|
WebRoot/css/bootstrap.css
|
137752
|
/*!
* Bootstrap v3.3.0 (http://getbootstrap.com)
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
/*! normalize.css v3.0.2 | MIT License | git.io/normalize */
html {
font-family: sans-serif;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
body {
margin: 0;
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
menu,
nav,
section,
summary {
display: block;
}
audio,
canvas,
progress,
video {
display: inline-block;
vertical-align: baseline;
}
audio:not([controls]) {
display: none;
height: 0;
}
[hidden],
template {
display: none;
}
a {
background-color: transparent;
}
a:active,
a:hover {
outline: 0;
}
abbr[title] {
border-bottom: 1px dotted;
}
b,
strong {
font-weight: bold;
}
dfn {
font-style: italic;
}
h1 {
margin: .67em 0;
font-size: 2em;
}
mark {
color: #000;
background: #ff0;
}
small {
font-size: 80%;
}
sub,
sup {
position: relative;
font-size: 75%;
line-height: 0;
vertical-align: baseline;
}
sup {
top: -.5em;
}
sub {
bottom: -.25em;
}
img {
border: 0;
}
svg:not(:root) {
overflow: hidden;
}
figure {
margin: 1em 40px;
}
hr {
height: 0;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
pre {
overflow: auto;
}
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
button,
input,
optgroup,
select,
textarea {
margin: 0;
font: inherit;
color: inherit;
}
button {
overflow: visible;
}
button,
select {
text-transform: none;
}
button,
html input[type="button"],
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button;
cursor: pointer;
}
button[disabled],
html input[disabled] {
cursor: default;
}
button::-moz-focus-inner,
input::-moz-focus-inner {
padding: 0;
border: 0;
}
input {
line-height: normal;
}
input[type="checkbox"],
input[type="radio"] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 0;
}
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
input[type="search"] {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
-webkit-appearance: textfield;
}
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
fieldset {
padding: .35em .625em .75em;
margin: 0 2px;
border: 1px solid #c0c0c0;
}
legend {
padding: 0;
border: 0;
}
textarea {
overflow: auto;
}
optgroup {
font-weight: bold;
}
table {
border-spacing: 0;
border-collapse: collapse;
}
td,
th {
padding: 0;
}
/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */
@media print {
*,
*:before,
*:after {
color: #000 !important;
text-shadow: none !important;
background: transparent !important;
-webkit-box-shadow: none !important;
box-shadow: none !important;
}
a,
a:visited {
text-decoration: underline;
}
a[href]:after {
content: " (" attr(href) ")";
}
abbr[title]:after {
content: " (" attr(title) ")";
}
a[href^="#"]:after,
a[href^="javascript:"]:after {
content: "";
}
pre,
blockquote {
border: 1px solid #999;
page-break-inside: avoid;
}
thead {
display: table-header-group;
}
tr,
img {
page-break-inside: avoid;
}
img {
max-width: 100% !important;
}
p,
h2,
h3 {
orphans: 3;
widows: 3;
}
h2,
h3 {
page-break-after: avoid;
}
select {
background: #fff !important;
}
.navbar {
display: none;
}
.btn > .caret,
.dropup > .btn > .caret {
border-top-color: #000 !important;
}
.label {
border: 1px solid #000;
}
.table {
border-collapse: collapse !important;
}
.table td,
.table th {
background-color: #fff !important;
}
.table-bordered th,
.table-bordered td {
border: 1px solid #ddd !important;
}
}
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}
.glyphicon {
position: relative;
top: 1px;
display: inline-block;
font-family: 'Glyphicons Halflings';
font-style: normal;
font-weight: normal;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.glyphicon-asterisk:before {
content: "\2a";
}
.glyphicon-plus:before {
content: "\2b";
}
.glyphicon-euro:before,
.glyphicon-eur:before {
content: "\20ac";
}
.glyphicon-minus:before {
content: "\2212";
}
.glyphicon-cloud:before {
content: "\2601";
}
.glyphicon-envelope:before {
content: "\2709";
}
.glyphicon-pencil:before {
content: "\270f";
}
.glyphicon-glass:before {
content: "\e001";
}
.glyphicon-music:before {
content: "\e002";
}
.glyphicon-search:before {
content: "\e003";
}
.glyphicon-heart:before {
content: "\e005";
}
.glyphicon-star:before {
content: "\e006";
}
.glyphicon-star-empty:before {
content: "\e007";
}
.glyphicon-user:before {
content: "\e008";
}
.glyphicon-film:before {
content: "\e009";
}
.glyphicon-th-large:before {
content: "\e010";
}
.glyphicon-th:before {
content: "\e011";
}
.glyphicon-th-list:before {
content: "\e012";
}
.glyphicon-ok:before {
content: "\e013";
}
.glyphicon-remove:before {
content: "\e014";
}
.glyphicon-zoom-in:before {
content: "\e015";
}
.glyphicon-zoom-out:before {
content: "\e016";
}
.glyphicon-off:before {
content: "\e017";
}
.glyphicon-signal:before {
content: "\e018";
}
.glyphicon-cog:before {
content: "\e019";
}
.glyphicon-trash:before {
content: "\e020";
}
.glyphicon-home:before {
content: "\e021";
}
.glyphicon-file:before {
content: "\e022";
}
.glyphicon-time:before {
content: "\e023";
}
.glyphicon-road:before {
content: "\e024";
}
.glyphicon-download-alt:before {
content: "\e025";
}
.glyphicon-download:before {
content: "\e026";
}
.glyphicon-upload:before {
content: "\e027";
}
.glyphicon-inbox:before {
content: "\e028";
}
.glyphicon-play-circle:before {
content: "\e029";
}
.glyphicon-repeat:before {
content: "\e030";
}
.glyphicon-refresh:before {
content: "\e031";
}
.glyphicon-list-alt:before {
content: "\e032";
}
.glyphicon-lock:before {
content: "\e033";
}
.glyphicon-flag:before {
content: "\e034";
}
.glyphicon-headphones:before {
content: "\e035";
}
.glyphicon-volume-off:before {
content: "\e036";
}
.glyphicon-volume-down:before {
content: "\e037";
}
.glyphicon-volume-up:before {
content: "\e038";
}
.glyphicon-qrcode:before {
content: "\e039";
}
.glyphicon-barcode:before {
content: "\e040";
}
.glyphicon-tag:before {
content: "\e041";
}
.glyphicon-tags:before {
content: "\e042";
}
.glyphicon-book:before {
content: "\e043";
}
.glyphicon-bookmark:before {
content: "\e044";
}
.glyphicon-print:before {
content: "\e045";
}
.glyphicon-camera:before {
content: "\e046";
}
.glyphicon-font:before {
content: "\e047";
}
.glyphicon-bold:before {
content: "\e048";
}
.glyphicon-italic:before {
content: "\e049";
}
.glyphicon-text-height:before {
content: "\e050";
}
.glyphicon-text-width:before {
content: "\e051";
}
.glyphicon-align-left:before {
content: "\e052";
}
.glyphicon-align-center:before {
content: "\e053";
}
.glyphicon-align-right:before {
content: "\e054";
}
.glyphicon-align-justify:before {
content: "\e055";
}
.glyphicon-list:before {
content: "\e056";
}
.glyphicon-indent-left:before {
content: "\e057";
}
.glyphicon-indent-right:before {
content: "\e058";
}
.glyphicon-facetime-video:before {
content: "\e059";
}
.glyphicon-picture:before {
content: "\e060";
}
.glyphicon-map-marker:before {
content: "\e062";
}
.glyphicon-adjust:before {
content: "\e063";
}
.glyphicon-tint:before {
content: "\e064";
}
.glyphicon-edit:before {
content: "\e065";
}
.glyphicon-share:before {
content: "\e066";
}
.glyphicon-check:before {
content: "\e067";
}
.glyphicon-move:before {
content: "\e068";
}
.glyphicon-step-backward:before {
content: "\e069";
}
.glyphicon-fast-backward:before {
content: "\e070";
}
.glyphicon-backward:before {
content: "\e071";
}
.glyphicon-play:before {
content: "\e072";
}
.glyphicon-pause:before {
content: "\e073";
}
.glyphicon-stop:before {
content: "\e074";
}
.glyphicon-forward:before {
content: "\e075";
}
.glyphicon-fast-forward:before {
content: "\e076";
}
.glyphicon-step-forward:before {
content: "\e077";
}
.glyphicon-eject:before {
content: "\e078";
}
.glyphicon-chevron-left:before {
content: "\e079";
}
.glyphicon-chevron-right:before {
content: "\e080";
}
.glyphicon-plus-sign:before {
content: "\e081";
}
.glyphicon-minus-sign:before {
content: "\e082";
}
.glyphicon-remove-sign:before {
content: "\e083";
}
.glyphicon-ok-sign:before {
content: "\e084";
}
.glyphicon-question-sign:before {
content: "\e085";
}
.glyphicon-info-sign:before {
content: "\e086";
}
.glyphicon-screenshot:before {
content: "\e087";
}
.glyphicon-remove-circle:before {
content: "\e088";
}
.glyphicon-ok-circle:before {
content: "\e089";
}
.glyphicon-ban-circle:before {
content: "\e090";
}
.glyphicon-arrow-left:before {
content: "\e091";
}
.glyphicon-arrow-right:before {
content: "\e092";
}
.glyphicon-arrow-up:before {
content: "\e093";
}
.glyphicon-arrow-down:before {
content: "\e094";
}
.glyphicon-share-alt:before {
content: "\e095";
}
.glyphicon-resize-full:before {
content: "\e096";
}
.glyphicon-resize-small:before {
content: "\e097";
}
.glyphicon-exclamation-sign:before {
content: "\e101";
}
.glyphicon-gift:before {
content: "\e102";
}
.glyphicon-leaf:before {
content: "\e103";
}
.glyphicon-fire:before {
content: "\e104";
}
.glyphicon-eye-open:before {
content: "\e105";
}
.glyphicon-eye-close:before {
content: "\e106";
}
.glyphicon-warning-sign:before {
content: "\e107";
}
.glyphicon-plane:before {
content: "\e108";
}
.glyphicon-calendar:before {
content: "\e109";
}
.glyphicon-random:before {
content: "\e110";
}
.glyphicon-comment:before {
content: "\e111";
}
.glyphicon-magnet:before {
content: "\e112";
}
.glyphicon-chevron-up:before {
content: "\e113";
}
.glyphicon-chevron-down:before {
content: "\e114";
}
.glyphicon-retweet:before {
content: "\e115";
}
.glyphicon-shopping-cart:before {
content: "\e116";
}
.glyphicon-folder-close:before {
content: "\e117";
}
.glyphicon-folder-open:before {
content: "\e118";
}
.glyphicon-resize-vertical:before {
content: "\e119";
}
.glyphicon-resize-horizontal:before {
content: "\e120";
}
.glyphicon-hdd:before {
content: "\e121";
}
.glyphicon-bullhorn:before {
content: "\e122";
}
.glyphicon-bell:before {
content: "\e123";
}
.glyphicon-certificate:before {
content: "\e124";
}
.glyphicon-thumbs-up:before {
content: "\e125";
}
.glyphicon-thumbs-down:before {
content: "\e126";
}
.glyphicon-hand-right:before {
content: "\e127";
}
.glyphicon-hand-left:before {
content: "\e128";
}
.glyphicon-hand-up:before {
content: "\e129";
}
.glyphicon-hand-down:before {
content: "\e130";
}
.glyphicon-circle-arrow-right:before {
content: "\e131";
}
.glyphicon-circle-arrow-left:before {
content: "\e132";
}
.glyphicon-circle-arrow-up:before {
content: "\e133";
}
.glyphicon-circle-arrow-down:before {
content: "\e134";
}
.glyphicon-globe:before {
content: "\e135";
}
.glyphicon-wrench:before {
content: "\e136";
}
.glyphicon-tasks:before {
content: "\e137";
}
.glyphicon-filter:before {
content: "\e138";
}
.glyphicon-briefcase:before {
content: "\e139";
}
.glyphicon-fullscreen:before {
content: "\e140";
}
.glyphicon-dashboard:before {
content: "\e141";
}
.glyphicon-paperclip:before {
content: "\e142";
}
.glyphicon-heart-empty:before {
content: "\e143";
}
.glyphicon-link:before {
content: "\e144";
}
.glyphicon-phone:before {
content: "\e145";
}
.glyphicon-pushpin:before {
content: "\e146";
}
.glyphicon-usd:before {
content: "\e148";
}
.glyphicon-gbp:before {
content: "\e149";
}
.glyphicon-sort:before {
content: "\e150";
}
.glyphicon-sort-by-alphabet:before {
content: "\e151";
}
.glyphicon-sort-by-alphabet-alt:before {
content: "\e152";
}
.glyphicon-sort-by-order:before {
content: "\e153";
}
.glyphicon-sort-by-order-alt:before {
content: "\e154";
}
.glyphicon-sort-by-attributes:before {
content: "\e155";
}
.glyphicon-sort-by-attributes-alt:before {
content: "\e156";
}
.glyphicon-unchecked:before {
content: "\e157";
}
.glyphicon-expand:before {
content: "\e158";
}
.glyphicon-collapse-down:before {
content: "\e159";
}
.glyphicon-collapse-up:before {
content: "\e160";
}
.glyphicon-log-in:before {
content: "\e161";
}
.glyphicon-flash:before {
content: "\e162";
}
.glyphicon-log-out:before {
content: "\e163";
}
.glyphicon-new-window:before {
content: "\e164";
}
.glyphicon-record:before {
content: "\e165";
}
.glyphicon-save:before {
content: "\e166";
}
.glyphicon-open:before {
content: "\e167";
}
.glyphicon-saved:before {
content: "\e168";
}
.glyphicon-import:before {
content: "\e169";
}
.glyphicon-export:before {
content: "\e170";
}
.glyphicon-send:before {
content: "\e171";
}
.glyphicon-floppy-disk:before {
content: "\e172";
}
.glyphicon-floppy-saved:before {
content: "\e173";
}
.glyphicon-floppy-remove:before {
content: "\e174";
}
.glyphicon-floppy-save:before {
content: "\e175";
}
.glyphicon-floppy-open:before {
content: "\e176";
}
.glyphicon-credit-card:before {
content: "\e177";
}
.glyphicon-transfer:before {
content: "\e178";
}
.glyphicon-cutlery:before {
content: "\e179";
}
.glyphicon-header:before {
content: "\e180";
}
.glyphicon-compressed:before {
content: "\e181";
}
.glyphicon-earphone:before {
content: "\e182";
}
.glyphicon-phone-alt:before {
content: "\e183";
}
.glyphicon-tower:before {
content: "\e184";
}
.glyphicon-stats:before {
content: "\e185";
}
.glyphicon-sd-video:before {
content: "\e186";
}
.glyphicon-hd-video:before {
content: "\e187";
}
.glyphicon-subtitles:before {
content: "\e188";
}
.glyphicon-sound-stereo:before {
content: "\e189";
}
.glyphicon-sound-dolby:before {
content: "\e190";
}
.glyphicon-sound-5-1:before {
content: "\e191";
}
.glyphicon-sound-6-1:before {
content: "\e192";
}
.glyphicon-sound-7-1:before {
content: "\e193";
}
.glyphicon-copyright-mark:before {
content: "\e194";
}
.glyphicon-registration-mark:before {
content: "\e195";
}
.glyphicon-cloud-download:before {
content: "\e197";
}
.glyphicon-cloud-upload:before {
content: "\e198";
}
.glyphicon-tree-conifer:before {
content: "\e199";
}
.glyphicon-tree-deciduous:before {
content: "\e200";
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
*:before,
*:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html {
font-size: 10px;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.42857143;
color: #333;
background-color: #fff;
}
input,
button,
select,
textarea {
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
a {
color: #428bca;
text-decoration: none;
}
a:hover,
a:focus {
color: #2a6496;
text-decoration: underline;
}
a:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
figure {
margin: 0;
}
img {
vertical-align: middle;
}
.img-responsive,
.thumbnail > img,
.thumbnail a > img,
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
display: block;
max-width: 100%;
height: auto;
}
.img-rounded {
border-radius: 6px;
}
.img-thumbnail {
display: inline-block;
max-width: 100%;
height: auto;
padding: 4px;
line-height: 1.42857143;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
-webkit-transition: all .2s ease-in-out;
-o-transition: all .2s ease-in-out;
transition: all .2s ease-in-out;
}
.img-circle {
border-radius: 50%;
}
hr {
margin-top: 20px;
margin-bottom: 20px;
border: 0;
border-top: 1px solid #eee;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
.sr-only-focusable:active,
.sr-only-focusable:focus {
position: static;
width: auto;
height: auto;
margin: 0;
overflow: visible;
clip: auto;
}
h1,
h2,
h3,
h4,
h5,
h6,
.h1,
.h2,
.h3,
.h4,
.h5,
.h6 {
font-family: inherit;
font-weight: 500;
line-height: 1.1;
color: inherit;
}
h1 small,
h2 small,
h3 small,
h4 small,
h5 small,
h6 small,
.h1 small,
.h2 small,
.h3 small,
.h4 small,
.h5 small,
.h6 small,
h1 .small,
h2 .small,
h3 .small,
h4 .small,
h5 .small,
h6 .small,
.h1 .small,
.h2 .small,
.h3 .small,
.h4 .small,
.h5 .small,
.h6 .small {
font-weight: normal;
line-height: 1;
color: #777;
}
h1,
.h1,
h2,
.h2,
h3,
.h3 {
margin-top: 20px;
margin-bottom: 10px;
}
h1 small,
.h1 small,
h2 small,
.h2 small,
h3 small,
.h3 small,
h1 .small,
.h1 .small,
h2 .small,
.h2 .small,
h3 .small,
.h3 .small {
font-size: 65%;
}
h4,
.h4,
h5,
.h5,
h6,
.h6 {
margin-top: 10px;
margin-bottom: 10px;
}
h4 small,
.h4 small,
h5 small,
.h5 small,
h6 small,
.h6 small,
h4 .small,
.h4 .small,
h5 .small,
.h5 .small,
h6 .small,
.h6 .small {
font-size: 75%;
}
h1,
.h1 {
font-size: 36px;
}
h2,
.h2 {
font-size: 30px;
}
h3,
.h3 {
font-size: 24px;
}
h4,
.h4 {
font-size: 18px;
}
h5,
.h5 {
font-size: 14px;
}
h6,
.h6 {
font-size: 12px;
}
p {
margin: 0 0 10px;
}
.lead {
margin-bottom: 20px;
font-size: 16px;
font-weight: 300;
line-height: 1.4;
}
@media (min-width: 768px) {
.lead {
font-size: 21px;
}
}
small,
.small {
font-size: 85%;
}
mark,
.mark {
padding: .2em;
background-color: #fcf8e3;
}
.text-left {
text-align: left;
}
.text-right {
text-align: right;
}
.text-center {
text-align: center;
}
.text-justify {
text-align: justify;
}
.text-nowrap {
white-space: nowrap;
}
.text-lowercase {
text-transform: lowercase;
}
.text-uppercase {
text-transform: uppercase;
}
.text-capitalize {
text-transform: capitalize;
}
.text-muted {
color: #777;
}
.text-primary {
color: #428bca;
}
a.text-primary:hover {
color: #3071a9;
}
.text-success {
color: #3c763d;
}
a.text-success:hover {
color: #2b542c;
}
.text-info {
color: #31708f;
}
a.text-info:hover {
color: #245269;
}
.text-warning {
color: #8a6d3b;
}
a.text-warning:hover {
color: #66512c;
}
.text-danger {
color: #a94442;
}
a.text-danger:hover {
color: #843534;
}
.bg-primary {
color: #fff;
background-color: #428bca;
}
a.bg-primary:hover {
background-color: #3071a9;
}
.bg-success {
background-color: #dff0d8;
}
a.bg-success:hover {
background-color: #c1e2b3;
}
.bg-info {
background-color: #d9edf7;
}
a.bg-info:hover {
background-color: #afd9ee;
}
.bg-warning {
background-color: #fcf8e3;
}
a.bg-warning:hover {
background-color: #f7ecb5;
}
.bg-danger {
background-color: #f2dede;
}
a.bg-danger:hover {
background-color: #e4b9b9;
}
.page-header {
padding-bottom: 9px;
margin: 40px 0 20px;
border-bottom: 1px solid #eee;
}
ul,
ol {
margin-top: 0;
margin-bottom: 10px;
}
ul ul,
ol ul,
ul ol,
ol ol {
margin-bottom: 0;
}
.list-unstyled {
padding-left: 0;
list-style: none;
}
.list-inline {
padding-left: 0;
margin-left: -5px;
list-style: none;
}
.list-inline > li {
display: inline-block;
padding-right: 5px;
padding-left: 5px;
}
dl {
margin-top: 0;
margin-bottom: 20px;
}
dt,
dd {
line-height: 1.42857143;
}
dt {
font-weight: bold;
}
dd {
margin-left: 0;
}
@media (min-width: 768px) {
.dl-horizontal dt {
float: left;
width: 160px;
overflow: hidden;
clear: left;
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
}
.dl-horizontal dd {
margin-left: 180px;
}
}
abbr[title],
abbr[data-original-title] {
cursor: help;
border-bottom: 1px dotted #777;
}
.initialism {
font-size: 90%;
text-transform: uppercase;
}
blockquote {
padding: 10px 20px;
margin: 0 0 20px;
font-size: 17.5px;
border-left: 5px solid #eee;
}
blockquote p:last-child,
blockquote ul:last-child,
blockquote ol:last-child {
margin-bottom: 0;
}
blockquote footer,
blockquote small,
blockquote .small {
display: block;
font-size: 80%;
line-height: 1.42857143;
color: #777;
}
blockquote footer:before,
blockquote small:before,
blockquote .small:before {
content: '\2014 \00A0';
}
.blockquote-reverse,
blockquote.pull-right {
padding-right: 15px;
padding-left: 0;
text-align: right;
border-right: 5px solid #eee;
border-left: 0;
}
.blockquote-reverse footer:before,
blockquote.pull-right footer:before,
.blockquote-reverse small:before,
blockquote.pull-right small:before,
.blockquote-reverse .small:before,
blockquote.pull-right .small:before {
content: '';
}
.blockquote-reverse footer:after,
blockquote.pull-right footer:after,
.blockquote-reverse small:after,
blockquote.pull-right small:after,
.blockquote-reverse .small:after,
blockquote.pull-right .small:after {
content: '\00A0 \2014';
}
address {
margin-bottom: 20px;
font-style: normal;
line-height: 1.42857143;
}
code,
kbd,
pre,
samp {
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
}
code {
padding: 2px 4px;
font-size: 90%;
color: #c7254e;
background-color: #f9f2f4;
border-radius: 4px;
}
kbd {
padding: 2px 4px;
font-size: 90%;
color: #fff;
background-color: #333;
border-radius: 3px;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
}
kbd kbd {
padding: 0;
font-size: 100%;
font-weight: bold;
-webkit-box-shadow: none;
box-shadow: none;
}
pre {
display: block;
padding: 9.5px;
margin: 0 0 10px;
font-size: 13px;
line-height: 1.42857143;
color: #333;
word-break: break-all;
word-wrap: break-word;
background-color: #f5f5f5;
border: 1px solid #ccc;
border-radius: 4px;
}
pre code {
padding: 0;
font-size: inherit;
color: inherit;
white-space: pre-wrap;
background-color: transparent;
border-radius: 0;
}
.pre-scrollable {
max-height: 340px;
overflow-y: scroll;
}
.container {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
}
@media (min-width: 768px) {
.container {
width: 750px;
}
}
@media (min-width: 992px) {
.container {
width: 970px;
}
}
@media (min-width: 1200px) {
.container {
width: 1170px;
}
}
.container-fluid {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
}
.row {
margin-right: -15px;
margin-left: -15px;
}
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
position: relative;
min-height: 1px;
padding-right: 15px;
padding-left: 15px;
}
.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12 {
float: left;
}
.col-xs-12 {
width: 100%;
}
.col-xs-11 {
width: 91.66666667%;
}
.col-xs-10 {
width: 83.33333333%;
}
.col-xs-9 {
width: 75%;
}
.col-xs-8 {
width: 66.66666667%;
}
.col-xs-7 {
width: 58.33333333%;
}
.col-xs-6 {
width: 50%;
}
.col-xs-5 {
width: 41.66666667%;
}
.col-xs-4 {
width: 33.33333333%;
}
.col-xs-3 {
width: 25%;
}
.col-xs-2 {
width: 16.66666667%;
}
.col-xs-1 {
width: 8.33333333%;
}
.col-xs-pull-12 {
right: 100%;
}
.col-xs-pull-11 {
right: 91.66666667%;
}
.col-xs-pull-10 {
right: 83.33333333%;
}
.col-xs-pull-9 {
right: 75%;
}
.col-xs-pull-8 {
right: 66.66666667%;
}
.col-xs-pull-7 {
right: 58.33333333%;
}
.col-xs-pull-6 {
right: 50%;
}
.col-xs-pull-5 {
right: 41.66666667%;
}
.col-xs-pull-4 {
right: 33.33333333%;
}
.col-xs-pull-3 {
right: 25%;
}
.col-xs-pull-2 {
right: 16.66666667%;
}
.col-xs-pull-1 {
right: 8.33333333%;
}
.col-xs-pull-0 {
right: auto;
}
.col-xs-push-12 {
left: 100%;
}
.col-xs-push-11 {
left: 91.66666667%;
}
.col-xs-push-10 {
left: 83.33333333%;
}
.col-xs-push-9 {
left: 75%;
}
.col-xs-push-8 {
left: 66.66666667%;
}
.col-xs-push-7 {
left: 58.33333333%;
}
.col-xs-push-6 {
left: 50%;
}
.col-xs-push-5 {
left: 41.66666667%;
}
.col-xs-push-4 {
left: 33.33333333%;
}
.col-xs-push-3 {
left: 25%;
}
.col-xs-push-2 {
left: 16.66666667%;
}
.col-xs-push-1 {
left: 8.33333333%;
}
.col-xs-push-0 {
left: auto;
}
.col-xs-offset-12 {
margin-left: 100%;
}
.col-xs-offset-11 {
margin-left: 91.66666667%;
}
.col-xs-offset-10 {
margin-left: 83.33333333%;
}
.col-xs-offset-9 {
margin-left: 75%;
}
.col-xs-offset-8 {
margin-left: 66.66666667%;
}
.col-xs-offset-7 {
margin-left: 58.33333333%;
}
.col-xs-offset-6 {
margin-left: 50%;
}
.col-xs-offset-5 {
margin-left: 41.66666667%;
}
.col-xs-offset-4 {
margin-left: 33.33333333%;
}
.col-xs-offset-3 {
margin-left: 25%;
}
.col-xs-offset-2 {
margin-left: 16.66666667%;
}
.col-xs-offset-1 {
margin-left: 8.33333333%;
}
.col-xs-offset-0 {
margin-left: 0;
}
@media (min-width: 768px) {
.col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 {
float: left;
}
.col-sm-12 {
width: 100%;
}
.col-sm-11 {
width: 91.66666667%;
}
.col-sm-10 {
width: 83.33333333%;
}
.col-sm-9 {
width: 75%;
}
.col-sm-8 {
width: 66.66666667%;
}
.col-sm-7 {
width: 58.33333333%;
}
.col-sm-6 {
width: 50%;
}
.col-sm-5 {
width: 41.66666667%;
}
.col-sm-4 {
width: 33.33333333%;
}
.col-sm-3 {
width: 25%;
}
.col-sm-2 {
width: 16.66666667%;
}
.col-sm-1 {
width: 8.33333333%;
}
.col-sm-pull-12 {
right: 100%;
}
.col-sm-pull-11 {
right: 91.66666667%;
}
.col-sm-pull-10 {
right: 83.33333333%;
}
.col-sm-pull-9 {
right: 75%;
}
.col-sm-pull-8 {
right: 66.66666667%;
}
.col-sm-pull-7 {
right: 58.33333333%;
}
.col-sm-pull-6 {
right: 50%;
}
.col-sm-pull-5 {
right: 41.66666667%;
}
.col-sm-pull-4 {
right: 33.33333333%;
}
.col-sm-pull-3 {
right: 25%;
}
.col-sm-pull-2 {
right: 16.66666667%;
}
.col-sm-pull-1 {
right: 8.33333333%;
}
.col-sm-pull-0 {
right: auto;
}
.col-sm-push-12 {
left: 100%;
}
.col-sm-push-11 {
left: 91.66666667%;
}
.col-sm-push-10 {
left: 83.33333333%;
}
.col-sm-push-9 {
left: 75%;
}
.col-sm-push-8 {
left: 66.66666667%;
}
.col-sm-push-7 {
left: 58.33333333%;
}
.col-sm-push-6 {
left: 50%;
}
.col-sm-push-5 {
left: 41.66666667%;
}
.col-sm-push-4 {
left: 33.33333333%;
}
.col-sm-push-3 {
left: 25%;
}
.col-sm-push-2 {
left: 16.66666667%;
}
.col-sm-push-1 {
left: 8.33333333%;
}
.col-sm-push-0 {
left: auto;
}
.col-sm-offset-12 {
margin-left: 100%;
}
.col-sm-offset-11 {
margin-left: 91.66666667%;
}
.col-sm-offset-10 {
margin-left: 83.33333333%;
}
.col-sm-offset-9 {
margin-left: 75%;
}
.col-sm-offset-8 {
margin-left: 66.66666667%;
}
.col-sm-offset-7 {
margin-left: 58.33333333%;
}
.col-sm-offset-6 {
margin-left: 50%;
}
.col-sm-offset-5 {
margin-left: 41.66666667%;
}
.col-sm-offset-4 {
margin-left: 33.33333333%;
}
.col-sm-offset-3 {
margin-left: 25%;
}
.col-sm-offset-2 {
margin-left: 16.66666667%;
}
.col-sm-offset-1 {
margin-left: 8.33333333%;
}
.col-sm-offset-0 {
margin-left: 0;
}
}
@media (min-width: 992px) {
.col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {
float: left;
}
.col-md-12 {
width: 100%;
}
.col-md-11 {
width: 91.66666667%;
}
.col-md-10 {
width: 83.33333333%;
}
.col-md-9 {
width: 75%;
}
.col-md-8 {
width: 66.66666667%;
}
.col-md-7 {
width: 58.33333333%;
}
.col-md-6 {
width: 50%;
}
.col-md-5 {
width: 41.66666667%;
}
.col-md-4 {
width: 33.33333333%;
}
.col-md-3 {
width: 25%;
}
.col-md-2 {
width: 16.66666667%;
}
.col-md-1 {
width: 8.33333333%;
}
.col-md-pull-12 {
right: 100%;
}
.col-md-pull-11 {
right: 91.66666667%;
}
.col-md-pull-10 {
right: 83.33333333%;
}
.col-md-pull-9 {
right: 75%;
}
.col-md-pull-8 {
right: 66.66666667%;
}
.col-md-pull-7 {
right: 58.33333333%;
}
.col-md-pull-6 {
right: 50%;
}
.col-md-pull-5 {
right: 41.66666667%;
}
.col-md-pull-4 {
right: 33.33333333%;
}
.col-md-pull-3 {
right: 25%;
}
.col-md-pull-2 {
right: 16.66666667%;
}
.col-md-pull-1 {
right: 8.33333333%;
}
.col-md-pull-0 {
right: auto;
}
.col-md-push-12 {
left: 100%;
}
.col-md-push-11 {
left: 91.66666667%;
}
.col-md-push-10 {
left: 83.33333333%;
}
.col-md-push-9 {
left: 75%;
}
.col-md-push-8 {
left: 66.66666667%;
}
.col-md-push-7 {
left: 58.33333333%;
}
.col-md-push-6 {
left: 50%;
}
.col-md-push-5 {
left: 41.66666667%;
}
.col-md-push-4 {
left: 33.33333333%;
}
.col-md-push-3 {
left: 25%;
}
.col-md-push-2 {
left: 16.66666667%;
}
.col-md-push-1 {
left: 8.33333333%;
}
.col-md-push-0 {
left: auto;
}
.col-md-offset-12 {
margin-left: 100%;
}
.col-md-offset-11 {
margin-left: 91.66666667%;
}
.col-md-offset-10 {
margin-left: 83.33333333%;
}
.col-md-offset-9 {
margin-left: 75%;
}
.col-md-offset-8 {
margin-left: 66.66666667%;
}
.col-md-offset-7 {
margin-left: 58.33333333%;
}
.col-md-offset-6 {
margin-left: 50%;
}
.col-md-offset-5 {
margin-left: 41.66666667%;
}
.col-md-offset-4 {
margin-left: 33.33333333%;
}
.col-md-offset-3 {
margin-left: 25%;
}
.col-md-offset-2 {
margin-left: 16.66666667%;
}
.col-md-offset-1 {
margin-left: 8.33333333%;
}
.col-md-offset-0 {
margin-left: 0;
}
}
@media (min-width: 1200px) {
.col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 {
float: left;
}
.col-lg-12 {
width: 100%;
}
.col-lg-11 {
width: 91.66666667%;
}
.col-lg-10 {
width: 83.33333333%;
}
.col-lg-9 {
width: 75%;
}
.col-lg-8 {
width: 66.66666667%;
}
.col-lg-7 {
width: 58.33333333%;
}
.col-lg-6 {
width: 50%;
}
.col-lg-5 {
width: 41.66666667%;
}
.col-lg-4 {
width: 33.33333333%;
}
.col-lg-3 {
width: 25%;
}
.col-lg-2 {
width: 16.66666667%;
}
.col-lg-1 {
width: 8.33333333%;
}
.col-lg-pull-12 {
right: 100%;
}
.col-lg-pull-11 {
right: 91.66666667%;
}
.col-lg-pull-10 {
right: 83.33333333%;
}
.col-lg-pull-9 {
right: 75%;
}
.col-lg-pull-8 {
right: 66.66666667%;
}
.col-lg-pull-7 {
right: 58.33333333%;
}
.col-lg-pull-6 {
right: 50%;
}
.col-lg-pull-5 {
right: 41.66666667%;
}
.col-lg-pull-4 {
right: 33.33333333%;
}
.col-lg-pull-3 {
right: 25%;
}
.col-lg-pull-2 {
right: 16.66666667%;
}
.col-lg-pull-1 {
right: 8.33333333%;
}
.col-lg-pull-0 {
right: auto;
}
.col-lg-push-12 {
left: 100%;
}
.col-lg-push-11 {
left: 91.66666667%;
}
.col-lg-push-10 {
left: 83.33333333%;
}
.col-lg-push-9 {
left: 75%;
}
.col-lg-push-8 {
left: 66.66666667%;
}
.col-lg-push-7 {
left: 58.33333333%;
}
.col-lg-push-6 {
left: 50%;
}
.col-lg-push-5 {
left: 41.66666667%;
}
.col-lg-push-4 {
left: 33.33333333%;
}
.col-lg-push-3 {
left: 25%;
}
.col-lg-push-2 {
left: 16.66666667%;
}
.col-lg-push-1 {
left: 8.33333333%;
}
.col-lg-push-0 {
left: auto;
}
.col-lg-offset-12 {
margin-left: 100%;
}
.col-lg-offset-11 {
margin-left: 91.66666667%;
}
.col-lg-offset-10 {
margin-left: 83.33333333%;
}
.col-lg-offset-9 {
margin-left: 75%;
}
.col-lg-offset-8 {
margin-left: 66.66666667%;
}
.col-lg-offset-7 {
margin-left: 58.33333333%;
}
.col-lg-offset-6 {
margin-left: 50%;
}
.col-lg-offset-5 {
margin-left: 41.66666667%;
}
.col-lg-offset-4 {
margin-left: 33.33333333%;
}
.col-lg-offset-3 {
margin-left: 25%;
}
.col-lg-offset-2 {
margin-left: 16.66666667%;
}
.col-lg-offset-1 {
margin-left: 8.33333333%;
}
.col-lg-offset-0 {
margin-left: 0;
}
}
table {
background-color: transparent;
}
caption {
padding-top: 8px;
padding-bottom: 8px;
color: #777;
text-align: left;
}
th {
text-align: left;
}
.table {
width: 100%;
max-width: 100%;
margin-bottom: 20px;
}
.table > thead > tr > th,
.table > tbody > tr > th,
.table > tfoot > tr > th,
.table > thead > tr > td,
.table > tbody > tr > td,
.table > tfoot > tr > td {
padding: 8px;
line-height: 1.42857143;
vertical-align: top;
border-top: 1px solid #ddd;
}
.table > thead > tr > th {
vertical-align: bottom;
border-bottom: 2px solid #ddd;
}
.table > caption + thead > tr:first-child > th,
.table > colgroup + thead > tr:first-child > th,
.table > thead:first-child > tr:first-child > th,
.table > caption + thead > tr:first-child > td,
.table > colgroup + thead > tr:first-child > td,
.table > thead:first-child > tr:first-child > td {
border-top: 0;
}
.table > tbody + tbody {
border-top: 2px solid #ddd;
}
.table .table {
background-color: #fff;
}
.table-condensed > thead > tr > th,
.table-condensed > tbody > tr > th,
.table-condensed > tfoot > tr > th,
.table-condensed > thead > tr > td,
.table-condensed > tbody > tr > td,
.table-condensed > tfoot > tr > td {
padding: 5px;
}
.table-bordered {
border: 1px solid #ddd;
}
.table-bordered > thead > tr > th,
.table-bordered > tbody > tr > th,
.table-bordered > tfoot > tr > th,
.table-bordered > thead > tr > td,
.table-bordered > tbody > tr > td,
.table-bordered > tfoot > tr > td {
border: 1px solid #ddd;
}
.table-bordered > thead > tr > th,
.table-bordered > thead > tr > td {
border-bottom-width: 2px;
}
.table-striped > tbody > tr:nth-child(odd) {
background-color: #f9f9f9;
}
.table-hover > tbody > tr:hover {
background-color: #f5f5f5;
}
table col[class*="col-"] {
position: static;
display: table-column;
float: none;
}
table td[class*="col-"],
table th[class*="col-"] {
position: static;
display: table-cell;
float: none;
}
.table > thead > tr > td.active,
.table > tbody > tr > td.active,
.table > tfoot > tr > td.active,
.table > thead > tr > th.active,
.table > tbody > tr > th.active,
.table > tfoot > tr > th.active,
.table > thead > tr.active > td,
.table > tbody > tr.active > td,
.table > tfoot > tr.active > td,
.table > thead > tr.active > th,
.table > tbody > tr.active > th,
.table > tfoot > tr.active > th {
background-color: #f5f5f5;
}
.table-hover > tbody > tr > td.active:hover,
.table-hover > tbody > tr > th.active:hover,
.table-hover > tbody > tr.active:hover > td,
.table-hover > tbody > tr:hover > .active,
.table-hover > tbody > tr.active:hover > th {
background-color: #e8e8e8;
}
.table > thead > tr > td.success,
.table > tbody > tr > td.success,
.table > tfoot > tr > td.success,
.table > thead > tr > th.success,
.table > tbody > tr > th.success,
.table > tfoot > tr > th.success,
.table > thead > tr.success > td,
.table > tbody > tr.success > td,
.table > tfoot > tr.success > td,
.table > thead > tr.success > th,
.table > tbody > tr.success > th,
.table > tfoot > tr.success > th {
background-color: #dff0d8;
}
.table-hover > tbody > tr > td.success:hover,
.table-hover > tbody > tr > th.success:hover,
.table-hover > tbody > tr.success:hover > td,
.table-hover > tbody > tr:hover > .success,
.table-hover > tbody > tr.success:hover > th {
background-color: #d0e9c6;
}
.table > thead > tr > td.info,
.table > tbody > tr > td.info,
.table > tfoot > tr > td.info,
.table > thead > tr > th.info,
.table > tbody > tr > th.info,
.table > tfoot > tr > th.info,
.table > thead > tr.info > td,
.table > tbody > tr.info > td,
.table > tfoot > tr.info > td,
.table > thead > tr.info > th,
.table > tbody > tr.info > th,
.table > tfoot > tr.info > th {
background-color: #d9edf7;
}
.table-hover > tbody > tr > td.info:hover,
.table-hover > tbody > tr > th.info:hover,
.table-hover > tbody > tr.info:hover > td,
.table-hover > tbody > tr:hover > .info,
.table-hover > tbody > tr.info:hover > th {
background-color: #c4e3f3;
}
.table > thead > tr > td.warning,
.table > tbody > tr > td.warning,
.table > tfoot > tr > td.warning,
.table > thead > tr > th.warning,
.table > tbody > tr > th.warning,
.table > tfoot > tr > th.warning,
.table > thead > tr.warning > td,
.table > tbody > tr.warning > td,
.table > tfoot > tr.warning > td,
.table > thead > tr.warning > th,
.table > tbody > tr.warning > th,
.table > tfoot > tr.warning > th {
background-color: #fcf8e3;
}
.table-hover > tbody > tr > td.warning:hover,
.table-hover > tbody > tr > th.warning:hover,
.table-hover > tbody > tr.warning:hover > td,
.table-hover > tbody > tr:hover > .warning,
.table-hover > tbody > tr.warning:hover > th {
background-color: #faf2cc;
}
.table > thead > tr > td.danger,
.table > tbody > tr > td.danger,
.table > tfoot > tr > td.danger,
.table > thead > tr > th.danger,
.table > tbody > tr > th.danger,
.table > tfoot > tr > th.danger,
.table > thead > tr.danger > td,
.table > tbody > tr.danger > td,
.table > tfoot > tr.danger > td,
.table > thead > tr.danger > th,
.table > tbody > tr.danger > th,
.table > tfoot > tr.danger > th {
background-color: #f2dede;
}
.table-hover > tbody > tr > td.danger:hover,
.table-hover > tbody > tr > th.danger:hover,
.table-hover > tbody > tr.danger:hover > td,
.table-hover > tbody > tr:hover > .danger,
.table-hover > tbody > tr.danger:hover > th {
background-color: #ebcccc;
}
.table-responsive {
min-height: .01%;
overflow-x: auto;
}
@media screen and (max-width: 767px) {
.table-responsive {
width: 100%;
margin-bottom: 15px;
overflow-y: hidden;
-ms-overflow-style: -ms-autohiding-scrollbar;
border: 1px solid #ddd;
}
.table-responsive > .table {
margin-bottom: 0;
}
.table-responsive > .table > thead > tr > th,
.table-responsive > .table > tbody > tr > th,
.table-responsive > .table > tfoot > tr > th,
.table-responsive > .table > thead > tr > td,
.table-responsive > .table > tbody > tr > td,
.table-responsive > .table > tfoot > tr > td {
white-space: nowrap;
}
.table-responsive > .table-bordered {
border: 0;
}
.table-responsive > .table-bordered > thead > tr > th:first-child,
.table-responsive > .table-bordered > tbody > tr > th:first-child,
.table-responsive > .table-bordered > tfoot > tr > th:first-child,
.table-responsive > .table-bordered > thead > tr > td:first-child,
.table-responsive > .table-bordered > tbody > tr > td:first-child,
.table-responsive > .table-bordered > tfoot > tr > td:first-child {
border-left: 0;
}
.table-responsive > .table-bordered > thead > tr > th:last-child,
.table-responsive > .table-bordered > tbody > tr > th:last-child,
.table-responsive > .table-bordered > tfoot > tr > th:last-child,
.table-responsive > .table-bordered > thead > tr > td:last-child,
.table-responsive > .table-bordered > tbody > tr > td:last-child,
.table-responsive > .table-bordered > tfoot > tr > td:last-child {
border-right: 0;
}
.table-responsive > .table-bordered > tbody > tr:last-child > th,
.table-responsive > .table-bordered > tfoot > tr:last-child > th,
.table-responsive > .table-bordered > tbody > tr:last-child > td,
.table-responsive > .table-bordered > tfoot > tr:last-child > td {
border-bottom: 0;
}
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
display: block;
width: 100%;
padding: 0;
margin-bottom: 20px;
font-size: 21px;
line-height: inherit;
color: #333;
border: 0;
border-bottom: 1px solid #e5e5e5;
}
label {
display: inline-block;
max-width: 100%;
margin-bottom: 5px;
font-weight: bold;
}
input[type="search"] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
input[type="radio"],
input[type="checkbox"] {
margin: 4px 0 0;
margin-top: 1px \9;
line-height: normal;
}
input[type="file"] {
display: block;
}
input[type="range"] {
display: block;
width: 100%;
}
select[multiple],
select[size] {
height: auto;
}
input[type="file"]:focus,
input[type="radio"]:focus,
input[type="checkbox"]:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
output {
display: block;
padding-top: 7px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
}
.form-control {
display: block;
width: 100px;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
-webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}
.form-control:focus {
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
}
.form-control::-moz-placeholder {
color: #999;
opacity: 1;
}
.form-control:-ms-input-placeholder {
color: #999;
}
.form-control::-webkit-input-placeholder {
color: #999;
}
.form-control[disabled],
.form-control[readonly],
fieldset[disabled] .form-control {
cursor: not-allowed;
background-color: #eee;
opacity: 1;
}
textarea.form-control {
height: auto;
}
input[type="search"] {
-webkit-appearance: none;
}
input[type="date"],
input[type="time"],
input[type="datetime-local"],
input[type="month"] {
line-height: 34px;
line-height: 1.42857143 \0;
}
input[type="date"].input-sm,
input[type="time"].input-sm,
input[type="datetime-local"].input-sm,
input[type="month"].input-sm {
line-height: 30px;
line-height: 1.5 \0;
}
input[type="date"].input-lg,
input[type="time"].input-lg,
input[type="datetime-local"].input-lg,
input[type="month"].input-lg {
line-height: 46px;
line-height: 1.33 \0;
}
_:-ms-fullscreen,
:root input[type="date"],
_:-ms-fullscreen,
:root input[type="time"],
_:-ms-fullscreen,
:root input[type="datetime-local"],
_:-ms-fullscreen,
:root input[type="month"] {
line-height: 1.42857143;
}
_:-ms-fullscreen.input-sm,
:root input[type="date"].input-sm,
_:-ms-fullscreen.input-sm,
:root input[type="time"].input-sm,
_:-ms-fullscreen.input-sm,
:root input[type="datetime-local"].input-sm,
_:-ms-fullscreen.input-sm,
:root input[type="month"].input-sm {
line-height: 1.5;
}
_:-ms-fullscreen.input-lg,
:root input[type="date"].input-lg,
_:-ms-fullscreen.input-lg,
:root input[type="time"].input-lg,
_:-ms-fullscreen.input-lg,
:root input[type="datetime-local"].input-lg,
_:-ms-fullscreen.input-lg,
:root input[type="month"].input-lg {
line-height: 1.33;
}
.form-group {
margin-bottom: 15px;
}
.radio,
.checkbox {
position: relative;
display: block;
margin-top: 10px;
margin-bottom: 10px;
}
.radio label,
.checkbox label {
min-height: 20px;
padding-left: 20px;
margin-bottom: 0;
font-weight: normal;
cursor: pointer;
}
.radio input[type="radio"],
.radio-inline input[type="radio"],
.checkbox input[type="checkbox"],
.checkbox-inline input[type="checkbox"] {
position: absolute;
margin-top: 4px \9;
margin-left: -20px;
}
.radio + .radio,
.checkbox + .checkbox {
margin-top: -5px;
}
.radio-inline,
.checkbox-inline {
display: inline-block;
padding-left: 20px;
margin-bottom: 0;
font-weight: normal;
vertical-align: middle;
cursor: pointer;
}
.radio-inline + .radio-inline,
.checkbox-inline + .checkbox-inline {
margin-top: 0;
margin-left: 10px;
}
input[type="radio"][disabled],
input[type="checkbox"][disabled],
input[type="radio"].disabled,
input[type="checkbox"].disabled,
fieldset[disabled] input[type="radio"],
fieldset[disabled] input[type="checkbox"] {
cursor: not-allowed;
}
.radio-inline.disabled,
.checkbox-inline.disabled,
fieldset[disabled] .radio-inline,
fieldset[disabled] .checkbox-inline {
cursor: not-allowed;
}
.radio.disabled label,
.checkbox.disabled label,
fieldset[disabled] .radio label,
fieldset[disabled] .checkbox label {
cursor: not-allowed;
}
.form-control-static {
padding-top: 7px;
padding-bottom: 7px;
margin-bottom: 0;
}
.form-control-static.input-lg,
.form-control-static.input-sm {
padding-right: 0;
padding-left: 0;
}
.input-sm,
.form-group-sm .form-control {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
select.input-sm,
select.form-group-sm .form-control {
height: 30px;
line-height: 30px;
}
textarea.input-sm,
textarea.form-group-sm .form-control,
select[multiple].input-sm,
select[multiple].form-group-sm .form-control {
height: auto;
}
.input-lg,
.form-group-lg .form-control {
height: 46px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.33;
border-radius: 6px;
}
select.input-lg,
select.form-group-lg .form-control {
height: 46px;
line-height: 46px;
}
textarea.input-lg,
textarea.form-group-lg .form-control,
select[multiple].input-lg,
select[multiple].form-group-lg .form-control {
height: auto;
}
.has-feedback {
position: relative;
}
.has-feedback .form-control {
padding-right: 42.5px;
}
.form-control-feedback {
position: absolute;
top: 0;
right: 0;
z-index: 2;
display: block;
width: 34px;
height: 34px;
line-height: 34px;
text-align: center;
pointer-events: none;
}
.input-lg + .form-control-feedback {
width: 46px;
height: 46px;
line-height: 46px;
}
.input-sm + .form-control-feedback {
width: 30px;
height: 30px;
line-height: 30px;
}
.has-success .help-block,
.has-success .control-label,
.has-success .radio,
.has-success .checkbox,
.has-success .radio-inline,
.has-success .checkbox-inline,
.has-success.radio label,
.has-success.checkbox label,
.has-success.radio-inline label,
.has-success.checkbox-inline label {
color: #3c763d;
}
.has-success .form-control {
border-color: #3c763d;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
.has-success .form-control:focus {
border-color: #2b542c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
}
.has-success .input-group-addon {
color: #3c763d;
background-color: #dff0d8;
border-color: #3c763d;
}
.has-success .form-control-feedback {
color: #3c763d;
}
.has-warning .help-block,
.has-warning .control-label,
.has-warning .radio,
.has-warning .checkbox,
.has-warning .radio-inline,
.has-warning .checkbox-inline,
.has-warning.radio label,
.has-warning.checkbox label,
.has-warning.radio-inline label,
.has-warning.checkbox-inline label {
color: #8a6d3b;
}
.has-warning .form-control {
border-color: #8a6d3b;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
.has-warning .form-control:focus {
border-color: #66512c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
}
.has-warning .input-group-addon {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #8a6d3b;
}
.has-warning .form-control-feedback {
color: #8a6d3b;
}
.has-error .help-block,
.has-error .control-label,
.has-error .radio,
.has-error .checkbox,
.has-error .radio-inline,
.has-error .checkbox-inline,
.has-error.radio label,
.has-error.checkbox label,
.has-error.radio-inline label,
.has-error.checkbox-inline label {
color: #a94442;
}
.has-error .form-control {
border-color: #a94442;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
.has-error .form-control:focus {
border-color: #843534;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
}
.has-error .input-group-addon {
color: #a94442;
background-color: #f2dede;
border-color: #a94442;
}
.has-error .form-control-feedback {
color: #a94442;
}
.has-feedback label ~ .form-control-feedback {
top: 25px;
}
.has-feedback label.sr-only ~ .form-control-feedback {
top: 0;
}
.help-block {
display: block;
margin-top: 5px;
margin-bottom: 10px;
color: #737373;
}
@media (min-width: 768px) {
.form-inline .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.form-inline .form-control-static {
display: inline-block;
}
.form-inline .input-group {
display: inline-table;
vertical-align: middle;
}
.form-inline .input-group .input-group-addon,
.form-inline .input-group .input-group-btn,
.form-inline .input-group .form-control {
width: auto;
}
.form-inline .input-group > .form-control {
width: 100%;
}
.form-inline .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .radio,
.form-inline .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .radio label,
.form-inline .checkbox label {
padding-left: 0;
}
.form-inline .radio input[type="radio"],
.form-inline .checkbox input[type="checkbox"] {
position: relative;
margin-left: 0;
}
.form-inline .has-feedback .form-control-feedback {
top: 0;
}
}
.form-horizontal .radio,
.form-horizontal .checkbox,
.form-horizontal .radio-inline,
.form-horizontal .checkbox-inline {
padding-top: 7px;
margin-top: 0;
margin-bottom: 0;
}
.form-horizontal .radio,
.form-horizontal .checkbox {
min-height: 27px;
}
.form-horizontal .form-group {
margin-right: -15px;
margin-left: -15px;
}
@media (min-width: 768px) {
.form-horizontal .control-label {
padding-top: 7px;
margin-bottom: 0;
text-align: right;
}
}
.form-horizontal .has-feedback .form-control-feedback {
right: 15px;
}
@media (min-width: 768px) {
.form-horizontal .form-group-lg .control-label {
padding-top: 14.3px;
}
}
@media (min-width: 768px) {
.form-horizontal .form-group-sm .control-label {
padding-top: 6px;
}
}
.btn {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 14px;
font-weight: normal;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
-ms-touch-action: manipulation;
touch-action: manipulation;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
}
.btn:focus,
.btn:active:focus,
.btn.active:focus,
.btn.focus,
.btn:active.focus,
.btn.active.focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
.btn:hover,
.btn:focus,
.btn.focus {
color: #333;
text-decoration: none;
}
.btn:active,
.btn.active {
background-image: none;
outline: 0;
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
}
.btn.disabled,
.btn[disabled],
fieldset[disabled] .btn {
pointer-events: none;
cursor: not-allowed;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
box-shadow: none;
opacity: .65;
}
.btn-default {
color: #333;
background-color: #fff;
border-color: #ccc;
}
.btn-default:hover,
.btn-default:focus,
.btn-default.focus,
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
color: #333;
background-color: #e6e6e6;
border-color: #adadad;
}
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
background-image: none;
}
.btn-default.disabled,
.btn-default[disabled],
fieldset[disabled] .btn-default,
.btn-default.disabled:hover,
.btn-default[disabled]:hover,
fieldset[disabled] .btn-default:hover,
.btn-default.disabled:focus,
.btn-default[disabled]:focus,
fieldset[disabled] .btn-default:focus,
.btn-default.disabled.focus,
.btn-default[disabled].focus,
fieldset[disabled] .btn-default.focus,
.btn-default.disabled:active,
.btn-default[disabled]:active,
fieldset[disabled] .btn-default:active,
.btn-default.disabled.active,
.btn-default[disabled].active,
fieldset[disabled] .btn-default.active {
background-color: #fff;
border-color: #ccc;
}
.btn-default .badge {
color: #fff;
background-color: #333;
}
.btn-primary {
color: #fff;
background-color: #428bca;
border-color: #357ebd;
}
.btn-primary:hover,
.btn-primary:focus,
.btn-primary.focus,
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
color: #fff;
background-color: #3071a9;
border-color: #285e8e;
}
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
background-image: none;
}
.btn-primary.disabled,
.btn-primary[disabled],
fieldset[disabled] .btn-primary,
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled.focus,
.btn-primary[disabled].focus,
fieldset[disabled] .btn-primary.focus,
.btn-primary.disabled:active,
.btn-primary[disabled]:active,
fieldset[disabled] .btn-primary:active,
.btn-primary.disabled.active,
.btn-primary[disabled].active,
fieldset[disabled] .btn-primary.active {
background-color: #428bca;
border-color: #357ebd;
}
.btn-primary .badge {
color: #428bca;
background-color: #fff;
}
.btn-success {
color: #fff;
background-color: #5cb85c;
border-color: #4cae4c;
}
.btn-success:hover,
.btn-success:focus,
.btn-success.focus,
.btn-success:active,
.btn-success.active,
.open > .dropdown-toggle.btn-success {
color: #fff;
background-color: #449d44;
border-color: #398439;
}
.btn-success:active,
.btn-success.active,
.open > .dropdown-toggle.btn-success {
background-image: none;
}
.btn-success.disabled,
.btn-success[disabled],
fieldset[disabled] .btn-success,
.btn-success.disabled:hover,
.btn-success[disabled]:hover,
fieldset[disabled] .btn-success:hover,
.btn-success.disabled:focus,
.btn-success[disabled]:focus,
fieldset[disabled] .btn-success:focus,
.btn-success.disabled.focus,
.btn-success[disabled].focus,
fieldset[disabled] .btn-success.focus,
.btn-success.disabled:active,
.btn-success[disabled]:active,
fieldset[disabled] .btn-success:active,
.btn-success.disabled.active,
.btn-success[disabled].active,
fieldset[disabled] .btn-success.active {
background-color: #5cb85c;
border-color: #4cae4c;
}
.btn-success .badge {
color: #5cb85c;
background-color: #fff;
}
.btn-info {
color: #fff;
background-color: #5bc0de;
border-color: #46b8da;
}
.btn-info:hover,
.btn-info:focus,
.btn-info.focus,
.btn-info:active,
.btn-info.active,
.open > .dropdown-toggle.btn-info {
color: #fff;
background-color: #31b0d5;
border-color: #269abc;
}
.btn-info:active,
.btn-info.active,
.open > .dropdown-toggle.btn-info {
background-image: none;
}
.btn-info.disabled,
.btn-info[disabled],
fieldset[disabled] .btn-info,
.btn-info.disabled:hover,
.btn-info[disabled]:hover,
fieldset[disabled] .btn-info:hover,
.btn-info.disabled:focus,
.btn-info[disabled]:focus,
fieldset[disabled] .btn-info:focus,
.btn-info.disabled.focus,
.btn-info[disabled].focus,
fieldset[disabled] .btn-info.focus,
.btn-info.disabled:active,
.btn-info[disabled]:active,
fieldset[disabled] .btn-info:active,
.btn-info.disabled.active,
.btn-info[disabled].active,
fieldset[disabled] .btn-info.active {
background-color: #5bc0de;
border-color: #46b8da;
}
.btn-info .badge {
color: #5bc0de;
background-color: #fff;
}
.btn-warning {
color: #fff;
background-color: #f0ad4e;
border-color: #eea236;
}
.btn-warning:hover,
.btn-warning:focus,
.btn-warning.focus,
.btn-warning:active,
.btn-warning.active,
.open > .dropdown-toggle.btn-warning {
color: #fff;
background-color: #ec971f;
border-color: #d58512;
}
.btn-warning:active,
.btn-warning.active,
.open > .dropdown-toggle.btn-warning {
background-image: none;
}
.btn-warning.disabled,
.btn-warning[disabled],
fieldset[disabled] .btn-warning,
.btn-warning.disabled:hover,
.btn-warning[disabled]:hover,
fieldset[disabled] .btn-warning:hover,
.btn-warning.disabled:focus,
.btn-warning[disabled]:focus,
fieldset[disabled] .btn-warning:focus,
.btn-warning.disabled.focus,
.btn-warning[disabled].focus,
fieldset[disabled] .btn-warning.focus,
.btn-warning.disabled:active,
.btn-warning[disabled]:active,
fieldset[disabled] .btn-warning:active,
.btn-warning.disabled.active,
.btn-warning[disabled].active,
fieldset[disabled] .btn-warning.active {
background-color: #f0ad4e;
border-color: #eea236;
}
.btn-warning .badge {
color: #f0ad4e;
background-color: #fff;
}
.btn-danger {
color: #fff;
background-color: #d9534f;
border-color: #d43f3a;
}
.btn-danger:hover,
.btn-danger:focus,
.btn-danger.focus,
.btn-danger:active,
.btn-danger.active,
.open > .dropdown-toggle.btn-danger {
color: #fff;
background-color: #c9302c;
border-color: #ac2925;
}
.btn-danger:active,
.btn-danger.active,
.open > .dropdown-toggle.btn-danger {
background-image: none;
}
.btn-danger.disabled,
.btn-danger[disabled],
fieldset[disabled] .btn-danger,
.btn-danger.disabled:hover,
.btn-danger[disabled]:hover,
fieldset[disabled] .btn-danger:hover,
.btn-danger.disabled:focus,
.btn-danger[disabled]:focus,
fieldset[disabled] .btn-danger:focus,
.btn-danger.disabled.focus,
.btn-danger[disabled].focus,
fieldset[disabled] .btn-danger.focus,
.btn-danger.disabled:active,
.btn-danger[disabled]:active,
fieldset[disabled] .btn-danger:active,
.btn-danger.disabled.active,
.btn-danger[disabled].active,
fieldset[disabled] .btn-danger.active {
background-color: #d9534f;
border-color: #d43f3a;
}
.btn-danger .badge {
color: #d9534f;
background-color: #fff;
}
.btn-link {
font-weight: normal;
color: #428bca;
border-radius: 0;
}
.btn-link,
.btn-link:active,
.btn-link.active,
.btn-link[disabled],
fieldset[disabled] .btn-link {
background-color: transparent;
-webkit-box-shadow: none;
box-shadow: none;
}
.btn-link,
.btn-link:hover,
.btn-link:focus,
.btn-link:active {
border-color: transparent;
}
.btn-link:hover,
.btn-link:focus {
color: #2a6496;
text-decoration: underline;
background-color: transparent;
}
.btn-link[disabled]:hover,
fieldset[disabled] .btn-link:hover,
.btn-link[disabled]:focus,
fieldset[disabled] .btn-link:focus {
color: #777;
text-decoration: none;
}
.btn-lg,
.btn-group-lg > .btn {
padding: 10px 16px;
font-size: 18px;
line-height: 1.33;
border-radius: 6px;
}
.btn-sm,
.btn-group-sm > .btn {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
.btn-xs,
.btn-group-xs > .btn {
padding: 1px 5px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
.btn-block {
display: block;
width: 100%;
}
.btn-block + .btn-block {
margin-top: 5px;
}
input[type="submit"].btn-block,
input[type="reset"].btn-block,
input[type="button"].btn-block {
width: 100%;
}
.fade {
opacity: 0;
-webkit-transition: opacity .15s linear;
-o-transition: opacity .15s linear;
transition: opacity .15s linear;
}
.fade.in {
opacity: 1;
}
.collapse {
display: none;
visibility: hidden;
}
.collapse.in {
display: block;
visibility: visible;
}
tr.collapse.in {
display: table-row;
}
tbody.collapse.in {
display: table-row-group;
}
.collapsing {
position: relative;
height: 0;
overflow: hidden;
-webkit-transition-timing-function: ease;
-o-transition-timing-function: ease;
transition-timing-function: ease;
-webkit-transition-duration: .35s;
-o-transition-duration: .35s;
transition-duration: .35s;
-webkit-transition-property: height, visibility;
-o-transition-property: height, visibility;
transition-property: height, visibility;
}
.caret {
display: inline-block;
width: 0;
height: 0;
margin-left: 2px;
vertical-align: middle;
border-top: 4px solid;
border-right: 4px solid transparent;
border-left: 4px solid transparent;
}
.dropdown {
position: relative;
}
.dropdown-toggle:focus {
outline: 0;
}
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
display: none;
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0;
font-size: 14px;
text-align: left;
list-style: none;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .15);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
}
.dropdown-menu.pull-right {
right: 0;
left: auto;
}
.dropdown-menu .divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.dropdown-menu > li > a {
display: block;
padding: 3px 20px;
clear: both;
font-weight: normal;
line-height: 1.42857143;
color: #333;
white-space: nowrap;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
color: #262626;
text-decoration: none;
background-color: #f5f5f5;
}
.dropdown-menu > .active > a,
.dropdown-menu > .active > a:hover,
.dropdown-menu > .active > a:focus {
color: #fff;
text-decoration: none;
background-color: #428bca;
outline: 0;
}
.dropdown-menu > .disabled > a,
.dropdown-menu > .disabled > a:hover,
.dropdown-menu > .disabled > a:focus {
color: #777;
}
.dropdown-menu > .disabled > a:hover,
.dropdown-menu > .disabled > a:focus {
text-decoration: none;
cursor: not-allowed;
background-color: transparent;
background-image: none;
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
}
.open > .dropdown-menu {
display: block;
}
.open > a {
outline: 0;
}
.dropdown-menu-right {
right: 0;
left: auto;
}
.dropdown-menu-left {
right: auto;
left: 0;
}
.dropdown-header {
display: block;
padding: 3px 20px;
font-size: 12px;
line-height: 1.42857143;
color: #777;
white-space: nowrap;
}
.dropdown-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 990;
}
.pull-right > .dropdown-menu {
right: 0;
left: auto;
}
.dropup .caret,
.navbar-fixed-bottom .dropdown .caret {
content: "";
border-top: 0;
border-bottom: 4px solid;
}
.dropup .dropdown-menu,
.navbar-fixed-bottom .dropdown .dropdown-menu {
top: auto;
bottom: 100%;
margin-bottom: 1px;
}
@media (min-width: 768px) {
.navbar-right .dropdown-menu {
right: 0;
left: auto;
}
.navbar-right .dropdown-menu-left {
right: auto;
left: 0;
}
}
.btn-group,
.btn-group-vertical {
position: relative;
display: inline-block;
vertical-align: middle;
}
.btn-group > .btn,
.btn-group-vertical > .btn {
position: relative;
float: left;
}
.btn-group > .btn:hover,
.btn-group-vertical > .btn:hover,
.btn-group > .btn:focus,
.btn-group-vertical > .btn:focus,
.btn-group > .btn:active,
.btn-group-vertical > .btn:active,
.btn-group > .btn.active,
.btn-group-vertical > .btn.active {
z-index: 2;
}
.btn-group > .btn:focus,
.btn-group-vertical > .btn:focus {
outline: 0;
}
.btn-group .btn + .btn,
.btn-group .btn + .btn-group,
.btn-group .btn-group + .btn,
.btn-group .btn-group + .btn-group {
margin-left: -1px;
}
.btn-toolbar {
margin-left: -5px;
}
.btn-toolbar .btn-group,
.btn-toolbar .input-group {
float: left;
}
.btn-toolbar > .btn,
.btn-toolbar > .btn-group,
.btn-toolbar > .input-group {
margin-left: 5px;
}
.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {
border-radius: 0;
}
.btn-group > .btn:first-child {
margin-left: 0;
}
.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.btn-group > .btn:last-child:not(:first-child),
.btn-group > .dropdown-toggle:not(:first-child) {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group > .btn-group {
float: left;
}
.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {
border-radius: 0;
}
.btn-group > .btn-group:first-child > .btn:last-child,
.btn-group > .btn-group:first-child > .dropdown-toggle {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.btn-group > .btn-group:last-child > .btn:first-child {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group .dropdown-toggle:active,
.btn-group.open .dropdown-toggle {
outline: 0;
}
.btn-group > .btn + .dropdown-toggle {
padding-right: 8px;
padding-left: 8px;
}
.btn-group > .btn-lg + .dropdown-toggle {
padding-right: 12px;
padding-left: 12px;
}
.btn-group.open .dropdown-toggle {
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
}
.btn-group.open .dropdown-toggle.btn-link {
-webkit-box-shadow: none;
box-shadow: none;
}
.btn .caret {
margin-left: 0;
}
.btn-lg .caret {
border-width: 5px 5px 0;
border-bottom-width: 0;
}
.dropup .btn-lg .caret {
border-width: 0 5px 5px;
}
.btn-group-vertical > .btn,
.btn-group-vertical > .btn-group,
.btn-group-vertical > .btn-group > .btn {
display: block;
float: none;
width: 100%;
max-width: 100%;
}
.btn-group-vertical > .btn-group > .btn {
float: none;
}
.btn-group-vertical > .btn + .btn,
.btn-group-vertical > .btn + .btn-group,
.btn-group-vertical > .btn-group + .btn,
.btn-group-vertical > .btn-group + .btn-group {
margin-top: -1px;
margin-left: 0;
}
.btn-group-vertical > .btn:not(:first-child):not(:last-child) {
border-radius: 0;
}
.btn-group-vertical > .btn:first-child:not(:last-child) {
border-top-right-radius: 4px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group-vertical > .btn:last-child:not(:first-child) {
border-top-left-radius: 0;
border-top-right-radius: 0;
border-bottom-left-radius: 4px;
}
.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {
border-radius: 0;
}
.btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child,
.btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child {
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.btn-group-justified {
display: table;
width: 100%;
table-layout: fixed;
border-collapse: separate;
}
.btn-group-justified > .btn,
.btn-group-justified > .btn-group {
display: table-cell;
float: none;
width: 1%;
}
.btn-group-justified > .btn-group .btn {
width: 100%;
}
.btn-group-justified > .btn-group .dropdown-menu {
left: auto;
}
[data-toggle="buttons"] > .btn input[type="radio"],
[data-toggle="buttons"] > .btn-group > .btn input[type="radio"],
[data-toggle="buttons"] > .btn input[type="checkbox"],
[data-toggle="buttons"] > .btn-group > .btn input[type="checkbox"] {
position: absolute;
clip: rect(0, 0, 0, 0);
pointer-events: none;
}
.input-group {
position: relative;
display: table;
border-collapse: separate;
}
.input-group[class*="col-"] {
float: none;
padding-right: 0;
padding-left: 0;
}
.input-group .form-control {
position: relative;
z-index: 2;
float: left;
width: 100%;
margin-bottom: 0;
}
.input-group-lg > .form-control,
.input-group-lg > .input-group-addon,
.input-group-lg > .input-group-btn > .btn {
height: 46px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.33;
border-radius: 6px;
}
select.input-group-lg > .form-control,
select.input-group-lg > .input-group-addon,
select.input-group-lg > .input-group-btn > .btn {
height: 46px;
line-height: 46px;
}
textarea.input-group-lg > .form-control,
textarea.input-group-lg > .input-group-addon,
textarea.input-group-lg > .input-group-btn > .btn,
select[multiple].input-group-lg > .form-control,
select[multiple].input-group-lg > .input-group-addon,
select[multiple].input-group-lg > .input-group-btn > .btn {
height: auto;
}
.input-group-sm > .form-control,
.input-group-sm > .input-group-addon,
.input-group-sm > .input-group-btn > .btn {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
select.input-group-sm > .form-control,
select.input-group-sm > .input-group-addon,
select.input-group-sm > .input-group-btn > .btn {
height: 30px;
line-height: 30px;
}
textarea.input-group-sm > .form-control,
textarea.input-group-sm > .input-group-addon,
textarea.input-group-sm > .input-group-btn > .btn,
select[multiple].input-group-sm > .form-control,
select[multiple].input-group-sm > .input-group-addon,
select[multiple].input-group-sm > .input-group-btn > .btn {
height: auto;
}
.input-group-addon,
.input-group-btn,
.input-group .form-control {
display: table-cell;
}
.input-group-addon:not(:first-child):not(:last-child),
.input-group-btn:not(:first-child):not(:last-child),
.input-group .form-control:not(:first-child):not(:last-child) {
border-radius: 0;
}
.input-group-addon,
.input-group-btn {
width: 1%;
white-space: nowrap;
vertical-align: middle;
}
.input-group-addon {
padding: 6px 12px;
font-size: 14px;
font-weight: normal;
line-height: 1;
color: #555;
text-align: center;
background-color: #eee;
border: 1px solid #ccc;
border-radius: 4px;
}
.input-group-addon.input-sm {
padding: 5px 10px;
font-size: 12px;
border-radius: 3px;
}
.input-group-addon.input-lg {
padding: 10px 16px;
font-size: 18px;
border-radius: 6px;
}
.input-group-addon input[type="radio"],
.input-group-addon input[type="checkbox"] {
margin-top: 0;
}
.input-group .form-control:first-child,
.input-group-addon:first-child,
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group > .btn,
.input-group-btn:first-child > .dropdown-toggle,
.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle),
.input-group-btn:last-child > .btn-group:not(:last-child) > .btn {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.input-group-addon:first-child {
border-right: 0;
}
.input-group .form-control:last-child,
.input-group-addon:last-child,
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group > .btn,
.input-group-btn:last-child > .dropdown-toggle,
.input-group-btn:first-child > .btn:not(:first-child),
.input-group-btn:first-child > .btn-group:not(:first-child) > .btn {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.input-group-addon:last-child {
border-left: 0;
}
.input-group-btn {
position: relative;
font-size: 0;
white-space: nowrap;
}
.input-group-btn > .btn {
position: relative;
}
.input-group-btn > .btn + .btn {
margin-left: -1px;
}
.input-group-btn > .btn:hover,
.input-group-btn > .btn:focus,
.input-group-btn > .btn:active {
z-index: 2;
}
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group {
margin-right: -1px;
}
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group {
margin-left: -1px;
}
.nav {
padding-left: 0;
margin-bottom: 0;
list-style: none;
}
.nav > li {
position: relative;
display: block;
}
.nav > li > a {
position: relative;
display: block;
padding: 10px 15px;
}
.nav > li > a:hover,
.nav > li > a:focus {
text-decoration: none;
background-color: #eee;
}
.nav > li.disabled > a {
color: #777;
}
.nav > li.disabled > a:hover,
.nav > li.disabled > a:focus {
color: #777;
text-decoration: none;
cursor: not-allowed;
background-color: transparent;
}
.nav .open > a,
.nav .open > a:hover,
.nav .open > a:focus {
background-color: #eee;
border-color: #428bca;
}
.nav .nav-divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.nav > li > a > img {
max-width: none;
}
.nav-tabs {
border-bottom: 1px solid #ddd;
}
.nav-tabs > li {
float: left;
margin-bottom: -1px;
}
.nav-tabs > li > a {
margin-right: 2px;
line-height: 1.42857143;
border: 1px solid transparent;
border-radius: 4px 4px 0 0;
}
.nav-tabs > li > a:hover {
border-color: #eee #eee #ddd;
}
.nav-tabs > li.active > a,
.nav-tabs > li.active > a:hover,
.nav-tabs > li.active > a:focus {
color: #555;
cursor: default;
background-color: #fff;
border: 1px solid #ddd;
border-bottom-color: transparent;
}
.nav-tabs.nav-justified {
width: 100%;
border-bottom: 0;
}
.nav-tabs.nav-justified > li {
float: none;
}
.nav-tabs.nav-justified > li > a {
margin-bottom: 5px;
text-align: center;
}
.nav-tabs.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li {
display: table-cell;
width: 1%;
}
.nav-tabs.nav-justified > li > a {
margin-bottom: 0;
}
}
.nav-tabs.nav-justified > li > a {
margin-right: 0;
border-radius: 4px;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border: 1px solid #ddd;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li > a {
border-bottom: 1px solid #ddd;
border-radius: 4px 4px 0 0;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border-bottom-color: #fff;
}
}
.nav-pills > li {
float: left;
}
.nav-pills > li > a {
border-radius: 4px;
}
.nav-pills > li + li {
margin-left: 2px;
}
.nav-pills > li.active > a,
.nav-pills > li.active > a:hover,
.nav-pills > li.active > a:focus {
color: #fff;
background-color: #428bca;
}
.nav-stacked > li {
float: none;
}
.nav-stacked > li + li {
margin-top: 2px;
margin-left: 0;
}
.nav-justified {
width: 100%;
}
.nav-justified > li {
float: none;
}
.nav-justified > li > a {
margin-bottom: 5px;
text-align: center;
}
.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
@media (min-width: 768px) {
.nav-justified > li {
display: table-cell;
width: 1%;
}
.nav-justified > li > a {
margin-bottom: 0;
}
}
.nav-tabs-justified {
border-bottom: 0;
}
.nav-tabs-justified > li > a {
margin-right: 0;
border-radius: 4px;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border: 1px solid #ddd;
}
@media (min-width: 768px) {
.nav-tabs-justified > li > a {
border-bottom: 1px solid #ddd;
border-radius: 4px 4px 0 0;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border-bottom-color: #fff;
}
}
.tab-content > .tab-pane {
display: none;
visibility: hidden;
}
.tab-content > .active {
display: block;
visibility: visible;
}
.nav-tabs .dropdown-menu {
margin-top: -1px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.navbar {
position: relative;
min-height: 50px;
margin-bottom: 20px;
border: 1px solid transparent;
}
@media (min-width: 768px) {
.navbar {
border-radius: 4px;
}
}
@media (min-width: 768px) {
.navbar-header {
float: left;
}
}
.navbar-collapse {
padding-right: 15px;
padding-left: 15px;
overflow-x: visible;
-webkit-overflow-scrolling: touch;
border-top: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
}
.navbar-collapse.in {
overflow-y: auto;
}
@media (min-width: 768px) {
.navbar-collapse {
width: auto;
border-top: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-collapse.collapse {
display: block !important;
height: auto !important;
padding-bottom: 0;
overflow: visible !important;
visibility: visible !important;
}
.navbar-collapse.in {
overflow-y: visible;
}
.navbar-fixed-top .navbar-collapse,
.navbar-static-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
padding-right: 0;
padding-left: 0;
}
}
.navbar-fixed-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
max-height: 340px;
}
@media (max-device-width: 480px) and (orientation: landscape) {
.navbar-fixed-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
max-height: 200px;
}
}
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: -15px;
margin-left: -15px;
}
@media (min-width: 768px) {
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: 0;
margin-left: 0;
}
}
.navbar-static-top {
z-index: 1000;
border-width: 0 0 1px;
}
@media (min-width: 768px) {
.navbar-static-top {
border-radius: 0;
}
}
.navbar-fixed-top,
.navbar-fixed-bottom {
position: fixed;
right: 0;
left: 0;
z-index: 1030;
}
@media (min-width: 768px) {
.navbar-fixed-top,
.navbar-fixed-bottom {
border-radius: 0;
}
}
.navbar-fixed-top {
top: 0;
border-width: 0 0 1px;
}
.navbar-fixed-bottom {
bottom: 0;
margin-bottom: 0;
border-width: 1px 0 0;
}
.navbar-brand {
float: left;
height: 50px;
padding: 15px 15px;
font-size: 18px;
line-height: 20px;
}
.navbar-brand:hover,
.navbar-brand:focus {
text-decoration: none;
}
.navbar-brand > img {
display: block;
}
@media (min-width: 768px) {
.navbar > .container .navbar-brand,
.navbar > .container-fluid .navbar-brand {
margin-left: -15px;
}
}
.navbar-toggle {
position: relative;
float: right;
padding: 9px 10px;
margin-top: 8px;
margin-right: 15px;
margin-bottom: 8px;
background-color: transparent;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
}
.navbar-toggle:focus {
outline: 0;
}
.navbar-toggle .icon-bar {
display: block;
width: 22px;
height: 2px;
border-radius: 1px;
}
.navbar-toggle .icon-bar + .icon-bar {
margin-top: 4px;
}
@media (min-width: 768px) {
.navbar-toggle {
display: none;
}
}
.navbar-nav {
margin: 7.5px -15px;
}
.navbar-nav > li > a {
padding-top: 10px;
padding-bottom: 10px;
line-height: 20px;
}
@media (max-width: 767px) {
.navbar-nav .open .dropdown-menu {
position: static;
float: none;
width: auto;
margin-top: 0;
background-color: transparent;
border: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-nav .open .dropdown-menu > li > a,
.navbar-nav .open .dropdown-menu .dropdown-header {
padding: 5px 15px 5px 25px;
}
.navbar-nav .open .dropdown-menu > li > a {
line-height: 20px;
}
.navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-nav .open .dropdown-menu > li > a:focus {
background-image: none;
}
}
@media (min-width: 768px) {
.navbar-nav {
float: left;
margin: 0;
}
.navbar-nav > li {
float: left;
}
.navbar-nav > li > a {
padding-top: 15px;
padding-bottom: 15px;
}
}
.navbar-form {
padding: 10px 15px;
margin-top: 8px;
margin-right: -15px;
margin-bottom: 8px;
margin-left: -15px;
border-top: 1px solid transparent;
border-bottom: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
}
@media (min-width: 768px) {
.navbar-form .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.navbar-form .form-control-static {
display: inline-block;
}
.navbar-form .input-group {
display: inline-table;
vertical-align: middle;
}
.navbar-form .input-group .input-group-addon,
.navbar-form .input-group .input-group-btn,
.navbar-form .input-group .form-control {
width: auto;
}
.navbar-form .input-group > .form-control {
width: 100%;
}
.navbar-form .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio,
.navbar-form .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio label,
.navbar-form .checkbox label {
padding-left: 0;
}
.navbar-form .radio input[type="radio"],
.navbar-form .checkbox input[type="checkbox"] {
position: relative;
margin-left: 0;
}
.navbar-form .has-feedback .form-control-feedback {
top: 0;
}
}
@media (max-width: 767px) {
.navbar-form .form-group {
margin-bottom: 5px;
}
.navbar-form .form-group:last-child {
margin-bottom: 0;
}
}
@media (min-width: 768px) {
.navbar-form {
width: auto;
padding-top: 0;
padding-bottom: 0;
margin-right: 0;
margin-left: 0;
border: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
}
.navbar-nav > li > .dropdown-menu {
margin-top: 0;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.navbar-btn {
margin-top: 8px;
margin-bottom: 8px;
}
.navbar-btn.btn-sm {
margin-top: 10px;
margin-bottom: 10px;
}
.navbar-btn.btn-xs {
margin-top: 14px;
margin-bottom: 14px;
}
.navbar-text {
margin-top: 15px;
margin-bottom: 15px;
}
@media (min-width: 768px) {
.navbar-text {
float: left;
margin-right: 15px;
margin-left: 15px;
}
}
@media (min-width: 768px) {
.navbar-left {
float: left !important;
}
.navbar-right {
float: right !important;
margin-right: -15px;
}
.navbar-right ~ .navbar-right {
margin-right: 0;
}
}
.navbar-default {
background-color: #f8f8f8;
border-color: #e7e7e7;
}
.navbar-default .navbar-brand {
color: #777;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
color: #5e5e5e;
background-color: transparent;
}
.navbar-default .navbar-text {
color: #777;
}
.navbar-default .navbar-nav > li > a {
color: #777;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
color: #333;
background-color: transparent;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
color: #555;
background-color: #e7e7e7;
}
.navbar-default .navbar-nav > .disabled > a,
.navbar-default .navbar-nav > .disabled > a:hover,
.navbar-default .navbar-nav > .disabled > a:focus {
color: #ccc;
background-color: transparent;
}
.navbar-default .navbar-toggle {
border-color: #ddd;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
background-color: #ddd;
}
.navbar-default .navbar-toggle .icon-bar {
background-color: #888;
}
.navbar-default .navbar-collapse,
.navbar-default .navbar-form {
border-color: #e7e7e7;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
color: #555;
background-color: #e7e7e7;
}
@media (max-width: 767px) {
.navbar-default .navbar-nav .open .dropdown-menu > li > a {
color: #777;
}
.navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
color: #333;
background-color: transparent;
}
.navbar-default .navbar-nav .open .dropdown-menu > .active > a,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #555;
background-color: #e7e7e7;
}
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #ccc;
background-color: transparent;
}
}
.navbar-default .navbar-link {
color: #777;
}
.navbar-default .navbar-link:hover {
color: #333;
}
.navbar-default .btn-link {
color: #777;
}
.navbar-default .btn-link:hover,
.navbar-default .btn-link:focus {
color: #333;
}
.navbar-default .btn-link[disabled]:hover,
fieldset[disabled] .navbar-default .btn-link:hover,
.navbar-default .btn-link[disabled]:focus,
fieldset[disabled] .navbar-default .btn-link:focus {
color: #ccc;
}
.navbar-inverse {
background-color: #222;
border-color: #080808;
}
.navbar-inverse .navbar-brand {
color: #9d9d9d;
}
.navbar-inverse .navbar-brand:hover,
.navbar-inverse .navbar-brand:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-text {
color: #9d9d9d;
}
.navbar-inverse .navbar-nav > li > a {
color: #9d9d9d;
}
.navbar-inverse .navbar-nav > li > a:hover,
.navbar-inverse .navbar-nav > li > a:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-nav > .active > a,
.navbar-inverse .navbar-nav > .active > a:hover,
.navbar-inverse .navbar-nav > .active > a:focus {
color: #fff;
background-color: #080808;
}
.navbar-inverse .navbar-nav > .disabled > a,
.navbar-inverse .navbar-nav > .disabled > a:hover,
.navbar-inverse .navbar-nav > .disabled > a:focus {
color: #444;
background-color: transparent;
}
.navbar-inverse .navbar-toggle {
border-color: #333;
}
.navbar-inverse .navbar-toggle:hover,
.navbar-inverse .navbar-toggle:focus {
background-color: #333;
}
.navbar-inverse .navbar-toggle .icon-bar {
background-color: #fff;
}
.navbar-inverse .navbar-collapse,
.navbar-inverse .navbar-form {
border-color: #101010;
}
.navbar-inverse .navbar-nav > .open > a,
.navbar-inverse .navbar-nav > .open > a:hover,
.navbar-inverse .navbar-nav > .open > a:focus {
color: #fff;
background-color: #080808;
}
@media (max-width: 767px) {
.navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {
border-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu .divider {
background-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a {
color: #9d9d9d;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #fff;
background-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #444;
background-color: transparent;
}
}
.navbar-inverse .navbar-link {
color: #9d9d9d;
}
.navbar-inverse .navbar-link:hover {
color: #fff;
}
.navbar-inverse .btn-link {
color: #9d9d9d;
}
.navbar-inverse .btn-link:hover,
.navbar-inverse .btn-link:focus {
color: #fff;
}
.navbar-inverse .btn-link[disabled]:hover,
fieldset[disabled] .navbar-inverse .btn-link:hover,
.navbar-inverse .btn-link[disabled]:focus,
fieldset[disabled] .navbar-inverse .btn-link:focus {
color: #444;
}
.breadcrumb {
padding: 8px 15px;
margin-bottom: 20px;
list-style: none;
background-color: #f5f5f5;
border-radius: 4px;
}
.breadcrumb > li {
display: inline-block;
}
.breadcrumb > li + li:before {
padding: 0 5px;
color: #ccc;
content: "/\00a0";
}
.breadcrumb > .active {
color: #777;
}
.pagination {
display: inline-block;
padding-left: 0;
margin: 20px 0;
border-radius: 4px;
}
.pagination > li {
display: inline;
}
.pagination > li > a,
.pagination > li > span {
position: relative;
float: left;
padding: 6px 12px;
margin-left: -1px;
line-height: 1.42857143;
color: #428bca;
text-decoration: none;
background-color: #fff;
border: 1px solid #ddd;
}
.pagination > li:first-child > a,
.pagination > li:first-child > span {
margin-left: 0;
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
}
.pagination > li:last-child > a,
.pagination > li:last-child > span {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.pagination > li > a:hover,
.pagination > li > span:hover,
.pagination > li > a:focus,
.pagination > li > span:focus {
color: #2a6496;
background-color: #eee;
border-color: #ddd;
}
.pagination > .active > a,
.pagination > .active > span,
.pagination > .active > a:hover,
.pagination > .active > span:hover,
.pagination > .active > a:focus,
.pagination > .active > span:focus {
z-index: 2;
color: #fff;
cursor: default;
background-color: #428bca;
border-color: #428bca;
}
.pagination > .disabled > span,
.pagination > .disabled > span:hover,
.pagination > .disabled > span:focus,
.pagination > .disabled > a,
.pagination > .disabled > a:hover,
.pagination > .disabled > a:focus {
color: #777;
cursor: not-allowed;
background-color: #fff;
border-color: #ddd;
}
.pagination-lg > li > a,
.pagination-lg > li > span {
padding: 10px 16px;
font-size: 18px;
}
.pagination-lg > li:first-child > a,
.pagination-lg > li:first-child > span {
border-top-left-radius: 6px;
border-bottom-left-radius: 6px;
}
.pagination-lg > li:last-child > a,
.pagination-lg > li:last-child > span {
border-top-right-radius: 6px;
border-bottom-right-radius: 6px;
}
.pagination-sm > li > a,
.pagination-sm > li > span {
padding: 5px 10px;
font-size: 12px;
}
.pagination-sm > li:first-child > a,
.pagination-sm > li:first-child > span {
border-top-left-radius: 3px;
border-bottom-left-radius: 3px;
}
.pagination-sm > li:last-child > a,
.pagination-sm > li:last-child > span {
border-top-right-radius: 3px;
border-bottom-right-radius: 3px;
}
.pager {
padding-left: 0;
margin: 20px 0;
text-align: center;
list-style: none;
}
.pager li {
display: inline;
}
.pager li > a,
.pager li > span {
display: inline-block;
padding: 5px 14px;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 15px;
}
.pager li > a:hover,
.pager li > a:focus {
text-decoration: none;
background-color: #eee;
}
.pager .next > a,
.pager .next > span {
float: right;
}
.pager .previous > a,
.pager .previous > span {
float: left;
}
.pager .disabled > a,
.pager .disabled > a:hover,
.pager .disabled > a:focus,
.pager .disabled > span {
color: #777;
cursor: not-allowed;
background-color: #fff;
}
.label {
display: inline;
padding: .2em .6em .3em;
font-size: 75%;
font-weight: bold;
line-height: 1;
color: #fff;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: .25em;
}
a.label:hover,
a.label:focus {
color: #fff;
text-decoration: none;
cursor: pointer;
}
.label:empty {
display: none;
}
.btn .label {
position: relative;
top: -1px;
}
.label-default {
background-color: #777;
}
.label-default[href]:hover,
.label-default[href]:focus {
background-color: #5e5e5e;
}
.label-primary {
background-color: #428bca;
}
.label-primary[href]:hover,
.label-primary[href]:focus {
background-color: #3071a9;
}
.label-success {
background-color: #5cb85c;
}
.label-success[href]:hover,
.label-success[href]:focus {
background-color: #449d44;
}
.label-info {
background-color: #5bc0de;
}
.label-info[href]:hover,
.label-info[href]:focus {
background-color: #31b0d5;
}
.label-warning {
background-color: #f0ad4e;
}
.label-warning[href]:hover,
.label-warning[href]:focus {
background-color: #ec971f;
}
.label-danger {
background-color: #d9534f;
}
.label-danger[href]:hover,
.label-danger[href]:focus {
background-color: #c9302c;
}
.badge {
display: inline-block;
min-width: 10px;
padding: 3px 7px;
font-size: 12px;
font-weight: bold;
line-height: 1;
color: #fff;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
background-color: #777;
border-radius: 10px;
}
.badge:empty {
display: none;
}
.btn .badge {
position: relative;
top: -1px;
}
.btn-xs .badge {
top: 0;
padding: 1px 5px;
}
a.badge:hover,
a.badge:focus {
color: #fff;
text-decoration: none;
cursor: pointer;
}
a.list-group-item.active > .badge,
.nav-pills > .active > a > .badge {
color: #428bca;
background-color: #fff;
}
.nav-pills > li > a > .badge {
margin-left: 3px;
}
.jumbotron {
padding: 30px 15px;
margin-bottom: 30px;
color: inherit;
background-color: #eee;
}
.jumbotron h1,
.jumbotron .h1 {
color: inherit;
}
.jumbotron p {
margin-bottom: 15px;
font-size: 21px;
font-weight: 200;
}
.jumbotron > hr {
border-top-color: #d5d5d5;
}
.container .jumbotron,
.container-fluid .jumbotron {
border-radius: 6px;
}
.jumbotron .container {
max-width: 100%;
}
@media screen and (min-width: 768px) {
.jumbotron {
padding: 48px 0;
}
.container .jumbotron {
padding-right: 60px;
padding-left: 60px;
}
.jumbotron h1,
.jumbotron .h1 {
font-size: 63px;
}
}
.thumbnail {
display: block;
padding: 4px;
margin-bottom: 20px;
line-height: 1.42857143;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
-webkit-transition: border .2s ease-in-out;
-o-transition: border .2s ease-in-out;
transition: border .2s ease-in-out;
}
.thumbnail > img,
.thumbnail a > img {
margin-right: auto;
margin-left: auto;
}
a.thumbnail:hover,
a.thumbnail:focus,
a.thumbnail.active {
border-color: #428bca;
}
.thumbnail .caption {
padding: 9px;
color: #333;
}
.alert {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
}
.alert h4 {
margin-top: 0;
color: inherit;
}
.alert .alert-link {
font-weight: bold;
}
.alert > p,
.alert > ul {
margin-bottom: 0;
}
.alert > p + p {
margin-top: 5px;
}
.alert-dismissable,
.alert-dismissible {
padding-right: 35px;
}
.alert-dismissable .close,
.alert-dismissible .close {
position: relative;
top: -2px;
right: -21px;
color: inherit;
}
.alert-success {
color: #3c763d;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.alert-success hr {
border-top-color: #c9e2b3;
}
.alert-success .alert-link {
color: #2b542c;
}
.alert-info {
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
}
.alert-info hr {
border-top-color: #a6e1ec;
}
.alert-info .alert-link {
color: #245269;
}
.alert-warning {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #faebcc;
}
.alert-warning hr {
border-top-color: #f7e1b5;
}
.alert-warning .alert-link {
color: #66512c;
}
.alert-danger {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.alert-danger hr {
border-top-color: #e4b9c0;
}
.alert-danger .alert-link {
color: #843534;
}
@-webkit-keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
@-o-keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
@keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
.progress {
height: 20px;
margin-bottom: 20px;
overflow: hidden;
background-color: #f5f5f5;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
}
.progress-bar {
float: left;
width: 0;
height: 100%;
font-size: 12px;
line-height: 20px;
color: #fff;
text-align: center;
background-color: #428bca;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
-webkit-transition: width .6s ease;
-o-transition: width .6s ease;
transition: width .6s ease;
}
.progress-striped .progress-bar,
.progress-bar-striped {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
-webkit-background-size: 40px 40px;
background-size: 40px 40px;
}
.progress.active .progress-bar,
.progress-bar.active {
-webkit-animation: progress-bar-stripes 2s linear infinite;
-o-animation: progress-bar-stripes 2s linear infinite;
animation: progress-bar-stripes 2s linear infinite;
}
.progress-bar-success {
background-color: #5cb85c;
}
.progress-striped .progress-bar-success {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.progress-bar-info {
background-color: #5bc0de;
}
.progress-striped .progress-bar-info {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.progress-bar-warning {
background-color: #f0ad4e;
}
.progress-striped .progress-bar-warning {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.progress-bar-danger {
background-color: #d9534f;
}
.progress-striped .progress-bar-danger {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.media {
margin-top: 15px;
}
.media:first-child {
margin-top: 0;
}
.media-right,
.media > .pull-right {
padding-left: 10px;
}
.media-left,
.media > .pull-left {
padding-right: 10px;
}
.media-left,
.media-right,
.media-body {
display: table-cell;
vertical-align: top;
}
.media-middle {
vertical-align: middle;
}
.media-bottom {
vertical-align: bottom;
}
.media-heading {
margin-top: 0;
margin-bottom: 5px;
}
.media-list {
padding-left: 0;
list-style: none;
}
.list-group {
padding-left: 0;
margin-bottom: 20px;
}
.list-group-item {
position: relative;
display: block;
padding: 10px 15px;
margin-bottom: -1px;
background-color: #fff;
border: 1px solid #ddd;
}
.list-group-item:first-child {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
.list-group-item:last-child {
margin-bottom: 0;
border-bottom-right-radius: 4px;
border-bottom-left-radius: 4px;
}
.list-group-item > .badge {
float: right;
}
.list-group-item > .badge + .badge {
margin-right: 5px;
}
a.list-group-item {
color: #555;
}
a.list-group-item .list-group-item-heading {
color: #333;
}
a.list-group-item:hover,
a.list-group-item:focus {
color: #555;
text-decoration: none;
background-color: #f5f5f5;
}
.list-group-item.disabled,
.list-group-item.disabled:hover,
.list-group-item.disabled:focus {
color: #777;
cursor: not-allowed;
background-color: #eee;
}
.list-group-item.disabled .list-group-item-heading,
.list-group-item.disabled:hover .list-group-item-heading,
.list-group-item.disabled:focus .list-group-item-heading {
color: inherit;
}
.list-group-item.disabled .list-group-item-text,
.list-group-item.disabled:hover .list-group-item-text,
.list-group-item.disabled:focus .list-group-item-text {
color: #777;
}
.list-group-item.active,
.list-group-item.active:hover,
.list-group-item.active:focus {
z-index: 2;
color: #fff;
background-color: #428bca;
border-color: #428bca;
}
.list-group-item.active .list-group-item-heading,
.list-group-item.active:hover .list-group-item-heading,
.list-group-item.active:focus .list-group-item-heading,
.list-group-item.active .list-group-item-heading > small,
.list-group-item.active:hover .list-group-item-heading > small,
.list-group-item.active:focus .list-group-item-heading > small,
.list-group-item.active .list-group-item-heading > .small,
.list-group-item.active:hover .list-group-item-heading > .small,
.list-group-item.active:focus .list-group-item-heading > .small {
color: inherit;
}
.list-group-item.active .list-group-item-text,
.list-group-item.active:hover .list-group-item-text,
.list-group-item.active:focus .list-group-item-text {
color: #e1edf7;
}
.list-group-item-success {
color: #3c763d;
background-color: #dff0d8;
}
a.list-group-item-success {
color: #3c763d;
}
a.list-group-item-success .list-group-item-heading {
color: inherit;
}
a.list-group-item-success:hover,
a.list-group-item-success:focus {
color: #3c763d;
background-color: #d0e9c6;
}
a.list-group-item-success.active,
a.list-group-item-success.active:hover,
a.list-group-item-success.active:focus {
color: #fff;
background-color: #3c763d;
border-color: #3c763d;
}
.list-group-item-info {
color: #31708f;
background-color: #d9edf7;
}
a.list-group-item-info {
color: #31708f;
}
a.list-group-item-info .list-group-item-heading {
color: inherit;
}
a.list-group-item-info:hover,
a.list-group-item-info:focus {
color: #31708f;
background-color: #c4e3f3;
}
a.list-group-item-info.active,
a.list-group-item-info.active:hover,
a.list-group-item-info.active:focus {
color: #fff;
background-color: #31708f;
border-color: #31708f;
}
.list-group-item-warning {
color: #8a6d3b;
background-color: #fcf8e3;
}
a.list-group-item-warning {
color: #8a6d3b;
}
a.list-group-item-warning .list-group-item-heading {
color: inherit;
}
a.list-group-item-warning:hover,
a.list-group-item-warning:focus {
color: #8a6d3b;
background-color: #faf2cc;
}
a.list-group-item-warning.active,
a.list-group-item-warning.active:hover,
a.list-group-item-warning.active:focus {
color: #fff;
background-color: #8a6d3b;
border-color: #8a6d3b;
}
.list-group-item-danger {
color: #a94442;
background-color: #f2dede;
}
a.list-group-item-danger {
color: #a94442;
}
a.list-group-item-danger .list-group-item-heading {
color: inherit;
}
a.list-group-item-danger:hover,
a.list-group-item-danger:focus {
color: #a94442;
background-color: #ebcccc;
}
a.list-group-item-danger.active,
a.list-group-item-danger.active:hover,
a.list-group-item-danger.active:focus {
color: #fff;
background-color: #a94442;
border-color: #a94442;
}
.list-group-item-heading {
margin-top: 0;
margin-bottom: 5px;
}
.list-group-item-text {
margin-bottom: 0;
line-height: 1.3;
}
.panel {
margin-bottom: 20px;
background-color: #fff;
border: 1px solid transparent;
border-radius: 4px;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
}
.panel-body {
padding: 15px;
}
.panel-heading {
padding: 10px 15px;
border-bottom: 1px solid transparent;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel-heading > .dropdown .dropdown-toggle {
color: inherit;
}
.panel-title {
margin-top: 0;
margin-bottom: 0;
font-size: 16px;
color: inherit;
}
.panel-title > a {
color: inherit;
}
.panel-footer {
padding: 10px 15px;
background-color: #f5f5f5;
border-top: 1px solid #ddd;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .list-group,
.panel > .panel-collapse > .list-group {
margin-bottom: 0;
}
.panel > .list-group .list-group-item,
.panel > .panel-collapse > .list-group .list-group-item {
border-width: 1px 0;
border-radius: 0;
}
.panel > .list-group:first-child .list-group-item:first-child,
.panel > .panel-collapse > .list-group:first-child .list-group-item:first-child {
border-top: 0;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel > .list-group:last-child .list-group-item:last-child,
.panel > .panel-collapse > .list-group:last-child .list-group-item:last-child {
border-bottom: 0;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel-heading + .list-group .list-group-item:first-child {
border-top-width: 0;
}
.list-group + .panel-footer {
border-top-width: 0;
}
.panel > .table,
.panel > .table-responsive > .table,
.panel > .panel-collapse > .table {
margin-bottom: 0;
}
.panel > .table caption,
.panel > .table-responsive > .table caption,
.panel > .panel-collapse > .table caption {
padding-right: 15px;
padding-left: 15px;
}
.panel > .table:first-child,
.panel > .table-responsive:first-child > .table:first-child {
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel > .table:first-child > thead:first-child > tr:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child {
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child th:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child {
border-top-left-radius: 3px;
}
.panel > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table:first-child > tbody:first-child > tr:first-child th:last-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child {
border-top-right-radius: 3px;
}
.panel > .table:last-child,
.panel > .table-responsive:last-child > .table:last-child {
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child {
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child th:first-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child {
border-bottom-left-radius: 3px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child th:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child {
border-bottom-right-radius: 3px;
}
.panel > .panel-body + .table,
.panel > .panel-body + .table-responsive,
.panel > .table + .panel-body,
.panel > .table-responsive + .panel-body {
border-top: 1px solid #ddd;
}
.panel > .table > tbody:first-child > tr:first-child th,
.panel > .table > tbody:first-child > tr:first-child td {
border-top: 0;
}
.panel > .table-bordered,
.panel > .table-responsive > .table-bordered {
border: 0;
}
.panel > .table-bordered > thead > tr > th:first-child,
.panel > .table-responsive > .table-bordered > thead > tr > th:first-child,
.panel > .table-bordered > tbody > tr > th:first-child,
.panel > .table-responsive > .table-bordered > tbody > tr > th:first-child,
.panel > .table-bordered > tfoot > tr > th:first-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > th:first-child,
.panel > .table-bordered > thead > tr > td:first-child,
.panel > .table-responsive > .table-bordered > thead > tr > td:first-child,
.panel > .table-bordered > tbody > tr > td:first-child,
.panel > .table-responsive > .table-bordered > tbody > tr > td:first-child,
.panel > .table-bordered > tfoot > tr > td:first-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child {
border-left: 0;
}
.panel > .table-bordered > thead > tr > th:last-child,
.panel > .table-responsive > .table-bordered > thead > tr > th:last-child,
.panel > .table-bordered > tbody > tr > th:last-child,
.panel > .table-responsive > .table-bordered > tbody > tr > th:last-child,
.panel > .table-bordered > tfoot > tr > th:last-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > th:last-child,
.panel > .table-bordered > thead > tr > td:last-child,
.panel > .table-responsive > .table-bordered > thead > tr > td:last-child,
.panel > .table-bordered > tbody > tr > td:last-child,
.panel > .table-responsive > .table-bordered > tbody > tr > td:last-child,
.panel > .table-bordered > tfoot > tr > td:last-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child {
border-right: 0;
}
.panel > .table-bordered > thead > tr:first-child > td,
.panel > .table-responsive > .table-bordered > thead > tr:first-child > td,
.panel > .table-bordered > tbody > tr:first-child > td,
.panel > .table-responsive > .table-bordered > tbody > tr:first-child > td,
.panel > .table-bordered > thead > tr:first-child > th,
.panel > .table-responsive > .table-bordered > thead > tr:first-child > th,
.panel > .table-bordered > tbody > tr:first-child > th,
.panel > .table-responsive > .table-bordered > tbody > tr:first-child > th {
border-bottom: 0;
}
.panel > .table-bordered > tbody > tr:last-child > td,
.panel > .table-responsive > .table-bordered > tbody > tr:last-child > td,
.panel > .table-bordered > tfoot > tr:last-child > td,
.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > td,
.panel > .table-bordered > tbody > tr:last-child > th,
.panel > .table-responsive > .table-bordered > tbody > tr:last-child > th,
.panel > .table-bordered > tfoot > tr:last-child > th,
.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th {
border-bottom: 0;
}
.panel > .table-responsive {
margin-bottom: 0;
border: 0;
}
.panel-group {
margin-bottom: 20px;
}
.panel-group .panel {
margin-bottom: 0;
border-radius: 4px;
}
.panel-group .panel + .panel {
margin-top: 5px;
}
.panel-group .panel-heading {
border-bottom: 0;
}
.panel-group .panel-heading + .panel-collapse > .panel-body,
.panel-group .panel-heading + .panel-collapse > .list-group {
border-top: 1px solid #ddd;
}
.panel-group .panel-footer {
border-top: 0;
}
.panel-group .panel-footer + .panel-collapse .panel-body {
border-bottom: 1px solid #ddd;
}
.panel-default {
border-color: #ddd;
}
.panel-default > .panel-heading {
color: #333;
background-color: #f5f5f5;
border-color: #ddd;
}
.panel-default > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #ddd;
}
.panel-default > .panel-heading .badge {
color: #f5f5f5;
background-color: #333;
}
.panel-default > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #ddd;
}
.panel-primary {
border-color: #428bca;
}
.panel-primary > .panel-heading {
color: #fff;
background-color: #428bca;
border-color: #428bca;
}
.panel-primary > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #428bca;
}
.panel-primary > .panel-heading .badge {
color: #428bca;
background-color: #fff;
}
.panel-primary > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #428bca;
}
.panel-success {
border-color: #d6e9c6;
}
.panel-success > .panel-heading {
color: #3c763d;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.panel-success > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #d6e9c6;
}
.panel-success > .panel-heading .badge {
color: #dff0d8;
background-color: #3c763d;
}
.panel-success > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #d6e9c6;
}
.panel-info {
border-color: #bce8f1;
}
.panel-info > .panel-heading {
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
}
.panel-info > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #bce8f1;
}
.panel-info > .panel-heading .badge {
color: #d9edf7;
background-color: #31708f;
}
.panel-info > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #bce8f1;
}
.panel-warning {
border-color: #faebcc;
}
.panel-warning > .panel-heading {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #faebcc;
}
.panel-warning > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #faebcc;
}
.panel-warning > .panel-heading .badge {
color: #fcf8e3;
background-color: #8a6d3b;
}
.panel-warning > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #faebcc;
}
.panel-danger {
border-color: #ebccd1;
}
.panel-danger > .panel-heading {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.panel-danger > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #ebccd1;
}
.panel-danger > .panel-heading .badge {
color: #f2dede;
background-color: #a94442;
}
.panel-danger > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #ebccd1;
}
.embed-responsive {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden;
}
.embed-responsive .embed-responsive-item,
.embed-responsive iframe,
.embed-responsive embed,
.embed-responsive object,
.embed-responsive video {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
.embed-responsive.embed-responsive-16by9 {
padding-bottom: 56.25%;
}
.embed-responsive.embed-responsive-4by3 {
padding-bottom: 75%;
}
.well {
min-height: 20px;
padding: 19px;
margin-bottom: 20px;
background-color: #f5f5f5;
border: 1px solid #e3e3e3;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
}
.well blockquote {
border-color: #ddd;
border-color: rgba(0, 0, 0, .15);
}
.well-lg {
padding: 24px;
border-radius: 6px;
}
.well-sm {
padding: 9px;
border-radius: 3px;
}
.close {
float: right;
font-size: 21px;
font-weight: bold;
line-height: 1;
color: #000;
text-shadow: 0 1px 0 #fff;
filter: alpha(opacity=20);
opacity: .2;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
filter: alpha(opacity=50);
opacity: .5;
}
button.close {
-webkit-appearance: none;
padding: 0;
cursor: pointer;
background: transparent;
border: 0;
}
.modal-open {
overflow: hidden;
}
.modal {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1040;
display: none;
overflow: hidden;
-webkit-overflow-scrolling: touch;
outline: 0;
}
.modal.fade .modal-dialog {
-webkit-transition: -webkit-transform .3s ease-out;
-o-transition: -o-transform .3s ease-out;
transition: transform .3s ease-out;
-webkit-transform: translate(0, -25%);
-ms-transform: translate(0, -25%);
-o-transform: translate(0, -25%);
transform: translate(0, -25%);
}
.modal.in .modal-dialog {
-webkit-transform: translate(0, 0);
-ms-transform: translate(0, 0);
-o-transform: translate(0, 0);
transform: translate(0, 0);
}
.modal-open .modal {
overflow-x: hidden;
overflow-y: auto;
}
.modal-dialog {
position: relative;
width: auto;
margin: 10px;
}
.modal-content {
position: relative;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #999;
border: 1px solid rgba(0, 0, 0, .2);
border-radius: 6px;
outline: 0;
-webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
}
.modal-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: #000;
}
.modal-backdrop.fade {
filter: alpha(opacity=0);
opacity: 0;
}
.modal-backdrop.in {
filter: alpha(opacity=50);
opacity: .5;
}
.modal-header {
min-height: 16.42857143px;
padding: 15px;
border-bottom: 1px solid #e5e5e5;
}
.modal-header .close {
margin-top: -2px;
}
.modal-title {
margin: 0;
line-height: 1.42857143;
}
.modal-body {
position: relative;
padding: 15px;
}
.modal-footer {
padding: 15px;
text-align: right;
border-top: 1px solid #e5e5e5;
}
.modal-footer .btn + .btn {
margin-bottom: 0;
margin-left: 5px;
}
.modal-footer .btn-group .btn + .btn {
margin-left: -1px;
}
.modal-footer .btn-block + .btn-block {
margin-left: 0;
}
.modal-scrollbar-measure {
position: absolute;
top: -9999px;
width: 50px;
height: 50px;
overflow: scroll;
}
@media (min-width: 768px) {
.modal-dialog {
width: 600px;
margin: 30px auto;
}
.modal-content {
-webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
}
.modal-sm {
width: 300px;
}
}
@media (min-width: 992px) {
.modal-lg {
width: 900px;
}
}
.tooltip {
position: absolute;
z-index: 1070;
display: block;
font-size: 12px;
line-height: 1.4;
visibility: visible;
filter: alpha(opacity=0);
opacity: 0;
}
.tooltip.in {
filter: alpha(opacity=90);
opacity: .9;
}
.tooltip.top {
padding: 5px 0;
margin-top: -3px;
}
.tooltip.right {
padding: 0 5px;
margin-left: 3px;
}
.tooltip.bottom {
padding: 5px 0;
margin-top: 3px;
}
.tooltip.left {
padding: 0 5px;
margin-left: -3px;
}
.tooltip-inner {
max-width: 200px;
padding: 3px 8px;
color: #fff;
text-align: center;
text-decoration: none;
background-color: #000;
border-radius: 4px;
}
.tooltip-arrow {
position: absolute;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.tooltip.top .tooltip-arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.top-left .tooltip-arrow {
bottom: 0;
left: 5px;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.top-right .tooltip-arrow {
right: 5px;
bottom: 0;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.right .tooltip-arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-width: 5px 5px 5px 0;
border-right-color: #000;
}
.tooltip.left .tooltip-arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-width: 5px 0 5px 5px;
border-left-color: #000;
}
.tooltip.bottom .tooltip-arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.tooltip.bottom-left .tooltip-arrow {
top: 0;
left: 5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.tooltip.bottom-right .tooltip-arrow {
top: 0;
right: 5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.popover {
position: absolute;
top: 0;
left: 0;
z-index: 1060;
display: none;
max-width: 276px;
padding: 1px;
font-size: 14px;
font-weight: normal;
line-height: 1.42857143;
text-align: left;
white-space: normal;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .2);
border-radius: 6px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
}
.popover.top {
margin-top: -10px;
}
.popover.right {
margin-left: 10px;
}
.popover.bottom {
margin-top: 10px;
}
.popover.left {
margin-left: -10px;
}
.popover-title {
padding: 8px 14px;
margin: 0;
font-size: 14px;
background-color: #f7f7f7;
border-bottom: 1px solid #ebebeb;
border-radius: 5px 5px 0 0;
}
.popover-content {
padding: 9px 14px;
}
.popover > .arrow,
.popover > .arrow:after {
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.popover > .arrow {
border-width: 11px;
}
.popover > .arrow:after {
content: "";
border-width: 10px;
}
.popover.top > .arrow {
bottom: -11px;
left: 50%;
margin-left: -11px;
border-top-color: #999;
border-top-color: rgba(0, 0, 0, .25);
border-bottom-width: 0;
}
.popover.top > .arrow:after {
bottom: 1px;
margin-left: -10px;
content: " ";
border-top-color: #fff;
border-bottom-width: 0;
}
.popover.right > .arrow {
top: 50%;
left: -11px;
margin-top: -11px;
border-right-color: #999;
border-right-color: rgba(0, 0, 0, .25);
border-left-width: 0;
}
.popover.right > .arrow:after {
bottom: -10px;
left: 1px;
content: " ";
border-right-color: #fff;
border-left-width: 0;
}
.popover.bottom > .arrow {
top: -11px;
left: 50%;
margin-left: -11px;
border-top-width: 0;
border-bottom-color: #999;
border-bottom-color: rgba(0, 0, 0, .25);
}
.popover.bottom > .arrow:after {
top: 1px;
margin-left: -10px;
content: " ";
border-top-width: 0;
border-bottom-color: #fff;
}
.popover.left > .arrow {
top: 50%;
right: -11px;
margin-top: -11px;
border-right-width: 0;
border-left-color: #999;
border-left-color: rgba(0, 0, 0, .25);
}
.popover.left > .arrow:after {
right: 1px;
bottom: -10px;
content: " ";
border-right-width: 0;
border-left-color: #fff;
}
.carousel {
position: relative;
}
.carousel-inner {
position: relative;
width: 100%;
overflow: hidden;
}
.carousel-inner > .item {
position: relative;
display: none;
-webkit-transition: .6s ease-in-out left;
-o-transition: .6s ease-in-out left;
transition: .6s ease-in-out left;
}
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
line-height: 1;
}
@media all and (transform-3d), (-webkit-transform-3d) {
.carousel-inner > .item {
-webkit-transition: -webkit-transform .6s ease-in-out;
-o-transition: -o-transform .6s ease-in-out;
transition: transform .6s ease-in-out;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-perspective: 1000;
perspective: 1000;
}
.carousel-inner > .item.next,
.carousel-inner > .item.active.right {
left: 0;
-webkit-transform: translate3d(100%, 0, 0);
transform: translate3d(100%, 0, 0);
}
.carousel-inner > .item.prev,
.carousel-inner > .item.active.left {
left: 0;
-webkit-transform: translate3d(-100%, 0, 0);
transform: translate3d(-100%, 0, 0);
}
.carousel-inner > .item.next.left,
.carousel-inner > .item.prev.right,
.carousel-inner > .item.active {
left: 0;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
}
.carousel-inner > .active,
.carousel-inner > .next,
.carousel-inner > .prev {
display: block;
}
.carousel-inner > .active {
left: 0;
}
.carousel-inner > .next,
.carousel-inner > .prev {
position: absolute;
top: 0;
width: 100%;
}
.carousel-inner > .next {
left: 100%;
}
.carousel-inner > .prev {
left: -100%;
}
.carousel-inner > .next.left,
.carousel-inner > .prev.right {
left: 0;
}
.carousel-inner > .active.left {
left: -100%;
}
.carousel-inner > .active.right {
left: 100%;
}
.carousel-control {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 15%;
font-size: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
filter: alpha(opacity=50);
opacity: .5;
}
.carousel-control.left {
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
background-image: -o-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .5)), to(rgba(0, 0, 0, .0001)));
background-image: linear-gradient(to right, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
background-repeat: repeat-x;
}
.carousel-control.right {
right: 0;
left: auto;
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
background-image: -o-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .0001)), to(rgba(0, 0, 0, .5)));
background-image: linear-gradient(to right, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
background-repeat: repeat-x;
}
.carousel-control:hover,
.carousel-control:focus {
color: #fff;
text-decoration: none;
filter: alpha(opacity=90);
outline: 0;
opacity: .9;
}
.carousel-control .icon-prev,
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right {
position: absolute;
top: 50%;
z-index: 5;
display: inline-block;
}
.carousel-control .icon-prev,
.carousel-control .glyphicon-chevron-left {
left: 50%;
margin-left: -10px;
}
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-right {
right: 50%;
margin-right: -10px;
}
.carousel-control .icon-prev,
.carousel-control .icon-next {
width: 20px;
height: 20px;
margin-top: -10px;
font-family: serif;
}
.carousel-control .icon-prev:before {
content: '\2039';
}
.carousel-control .icon-next:before {
content: '\203a';
}
.carousel-indicators {
position: absolute;
bottom: 10px;
left: 50%;
z-index: 15;
width: 60%;
padding-left: 0;
margin-left: -30%;
text-align: center;
list-style: none;
}
.carousel-indicators li {
display: inline-block;
width: 10px;
height: 10px;
margin: 1px;
text-indent: -999px;
cursor: pointer;
background-color: #000 \9;
background-color: rgba(0, 0, 0, 0);
border: 1px solid #fff;
border-radius: 10px;
}
.carousel-indicators .active {
width: 12px;
height: 12px;
margin: 0;
background-color: #fff;
}
.carousel-caption {
position: absolute;
right: 15%;
bottom: 20px;
left: 15%;
z-index: 10;
padding-top: 20px;
padding-bottom: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
}
.carousel-caption .btn {
text-shadow: none;
}
@media screen and (min-width: 768px) {
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-prev,
.carousel-control .icon-next {
width: 30px;
height: 30px;
margin-top: -15px;
font-size: 30px;
}
.carousel-control .glyphicon-chevron-left,
.carousel-control .icon-prev {
margin-left: -15px;
}
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-next {
margin-right: -15px;
}
.carousel-caption {
right: 20%;
left: 20%;
padding-bottom: 30px;
}
.carousel-indicators {
bottom: 20px;
}
}
.clearfix:before,
.clearfix:after,
.dl-horizontal dd:before,
.dl-horizontal dd:after,
.container:before,
.container:after,
.container-fluid:before,
.container-fluid:after,
.row:before,
.row:after,
.form-horizontal .form-group:before,
.form-horizontal .form-group:after,
.btn-toolbar:before,
.btn-toolbar:after,
.btn-group-vertical > .btn-group:before,
.btn-group-vertical > .btn-group:after,
.nav:before,
.nav:after,
.navbar:before,
.navbar:after,
.navbar-header:before,
.navbar-header:after,
.navbar-collapse:before,
.navbar-collapse:after,
.pager:before,
.pager:after,
.panel-body:before,
.panel-body:after,
.modal-footer:before,
.modal-footer:after {
display: table;
content: " ";
}
.clearfix:after,
.dl-horizontal dd:after,
.container:after,
.container-fluid:after,
.row:after,
.form-horizontal .form-group:after,
.btn-toolbar:after,
.btn-group-vertical > .btn-group:after,
.nav:after,
.navbar:after,
.navbar-header:after,
.navbar-collapse:after,
.pager:after,
.panel-body:after,
.modal-footer:after {
clear: both;
}
.center-block {
display: block;
margin-right: auto;
margin-left: auto;
}
.pull-right {
float: right !important;
}
.pull-left {
float: left !important;
}
.hide {
display: none !important;
}
.show {
display: block !important;
}
.invisible {
visibility: hidden;
}
.text-hide {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
.hidden {
display: none !important;
visibility: hidden !important;
}
.affix {
position: fixed;
}
@-ms-viewport {
width: device-width;
}
.visible-xs,
.visible-sm,
.visible-md,
.visible-lg {
display: none !important;
}
.visible-xs-block,
.visible-xs-inline,
.visible-xs-inline-block,
.visible-sm-block,
.visible-sm-inline,
.visible-sm-inline-block,
.visible-md-block,
.visible-md-inline,
.visible-md-inline-block,
.visible-lg-block,
.visible-lg-inline,
.visible-lg-inline-block {
display: none !important;
}
@media (max-width: 767px) {
.visible-xs {
display: block !important;
}
table.visible-xs {
display: table;
}
tr.visible-xs {
display: table-row !important;
}
th.visible-xs,
td.visible-xs {
display: table-cell !important;
}
}
@media (max-width: 767px) {
.visible-xs-block {
display: block !important;
}
}
@media (max-width: 767px) {
.visible-xs-inline {
display: inline !important;
}
}
@media (max-width: 767px) {
.visible-xs-inline-block {
display: inline-block !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm {
display: block !important;
}
table.visible-sm {
display: table;
}
tr.visible-sm {
display: table-row !important;
}
th.visible-sm,
td.visible-sm {
display: table-cell !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-block {
display: block !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-inline {
display: inline !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-inline-block {
display: inline-block !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md {
display: block !important;
}
table.visible-md {
display: table;
}
tr.visible-md {
display: table-row !important;
}
th.visible-md,
td.visible-md {
display: table-cell !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-block {
display: block !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-inline {
display: inline !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-inline-block {
display: inline-block !important;
}
}
@media (min-width: 1200px) {
.visible-lg {
display: block !important;
}
table.visible-lg {
display: table;
}
tr.visible-lg {
display: table-row !important;
}
th.visible-lg,
td.visible-lg {
display: table-cell !important;
}
}
@media (min-width: 1200px) {
.visible-lg-block {
display: block !important;
}
}
@media (min-width: 1200px) {
.visible-lg-inline {
display: inline !important;
}
}
@media (min-width: 1200px) {
.visible-lg-inline-block {
display: inline-block !important;
}
}
@media (max-width: 767px) {
.hidden-xs {
display: none !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.hidden-sm {
display: none !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.hidden-md {
display: none !important;
}
}
@media (min-width: 1200px) {
.hidden-lg {
display: none !important;
}
}
.visible-print {
display: none !important;
}
@media print {
.visible-print {
display: block !important;
}
table.visible-print {
display: table;
}
tr.visible-print {
display: table-row !important;
}
th.visible-print,
td.visible-print {
display: table-cell !important;
}
}
.visible-print-block {
display: none !important;
}
@media print {
.visible-print-block {
display: block !important;
}
}
.visible-print-inline {
display: none !important;
}
@media print {
.visible-print-inline {
display: inline !important;
}
}
.visible-print-inline-block {
display: none !important;
}
@media print {
.visible-print-inline-block {
display: inline-block !important;
}
}
@media print {
.hidden-print {
display: none !important;
}
}
.side{
border-style: solid; border-width: 1px; border-color:#EAEFF7;
}
.blue{
color:#5B9BD5;
font-family:"STHeiti",»ªÎĺÚÌå;
}
.right{
text-align:right;
}
/*# sourceMappingURL=bootstrap.css.map */
|
apache-2.0
|
sabob/ratel
|
ratel/src/com/google/ratel/service/error/DefaultErrorHandlerService.java
|
3778
|
package com.google.ratel.service.error;
import com.google.ratel.core.Mode;
import com.google.ratel.*;
import com.google.ratel.deps.io.*;
import com.google.ratel.service.classdata.*;
import com.google.ratel.service.log.LogService;
import com.google.ratel.service.resolver.*;
import com.google.ratel.util.*;
import java.io.*;
import java.lang.reflect.Method;
import java.nio.charset.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
*
*/
public class DefaultErrorHandlerService implements ErrorHandlerService {
private String errorTemplate;
private ServletContext servletContext;
@Override
public void onInit(ServletContext servletContext) {
this.servletContext = servletContext;
errorTemplate = loadTemplate("error.htm");
if (errorTemplate == null) {
errorTemplate = "<html><body><h1>ErrorReport</h1>@TOKEN</body></html>";
}
}
@Override
public void onDestroy(ServletContext servletContext) {
this.servletContext = null;
}
@Override
public void handleRuntimeException(Throwable throwable, Mode mode, HttpServletRequest request, HttpServletResponse response,
RatelConfig ratelConfig) {
LogService logService = ratelConfig.getLogService();
if (mode == Mode.PROFILE || mode == Mode.PRODUCTION) {
logService.error("Could not handle request", throwable);
} else {
logService.error("Could not handle request", throwable);
ServiceResolver serviceResolver = ratelConfig.getServiceResolver();
Class serviceClass = null;
Method method = null;
try {
RequestTargetData targetData = serviceResolver.resolveTarget(request);
if (targetData != null) {
ClassData serviceData = targetData.getClassData();
serviceClass = serviceData.getServiceClass();
MethodData methodData = targetData.getMethodData();
method = methodData.getMethod();
}
} catch (RuntimeException ignore) {
// If we cannot lookup the service and method we continue printing the information we have
}
ErrorReport errorReport = new ErrorReport(throwable, serviceClass, method, mode, request, ratelConfig);
String content = errorTemplate.replace("@TOKEN", errorReport.toString());
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
RatelUtils.writeContent(response, content, Constants.HTML);
// TODO
//logService.error("Could not handle request", throwable);
//throw new RuntimeException(throwable);
}
}
@Override
public void handleInitializationException(Throwable throwable, Mode mode, ServletContext servletContext, LogService logService) {
if (mode == Mode.PROFILE || mode == Mode.PRODUCTION) {
logService.error("Could not initialize Ratel", throwable);
} else {
logService.error("Could not initialize Ratel", throwable);
throw new RuntimeException(throwable);
}
}
protected String loadTemplate(String name) {
InputStream is = servletContext.getResourceAsStream("/" + name);
if (is == null) {
String resourcePath = "/META-INF/resources/" + name;
is = RatelUtils.getClasspathResourceAsStream(resourcePath);
}
String template = null;
try {
if (is != null) {
template = IOUtils.toString(is, (Charset) null);
}
return template;
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
}
|
apache-2.0
|
SmartDeveloperHub/sdh-curator-connector
|
src/test/java/org/smartdeveloperhub/curator/connector/ServerCuratorController.java
|
2636
|
/**
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* This file is part of the Smart Developer Hub Project:
* http://www.smartdeveloperhub.org/
*
* Center for Open Middleware
* http://www.centeropenmiddleware.com/
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* Copyright (C) 2015-2016 Center for Open Middleware.
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* 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.
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* Artifact : org.smartdeveloperhub.curator:sdh-curator-connector:0.2.0
* Bundle : sdh-curator-connector-0.2.0.jar
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
package org.smartdeveloperhub.curator.connector;
import java.io.IOException;
import org.smartdeveloperhub.curator.connector.io.ConversionContext;
import org.smartdeveloperhub.curator.protocol.Agent;
import org.smartdeveloperhub.curator.protocol.RequestMessage;
import org.smartdeveloperhub.curator.protocol.ResponseMessage;
final class ServerCuratorController extends CuratorController {
ServerCuratorController(final CuratorConfiguration configuration, final String name, final ConversionContext context) {
super(configuration,name,context);
}
private String routingKey(final RequestMessage request) {
return curatorConfiguration().responseRoutingKey()+"."+request.submittedBy().agentId();
}
void publishResponse(final RequestMessage request, final ResponseMessage response) throws IOException {
publishMessage(response,routingKey(request));
}
void publishResponse(final RequestMessage request, final String response) throws IOException {
publishMessage(response,routingKey(request));
}
/**
* {@inheritDoc}
*/
@Override
protected String routingKey(final CuratorConfiguration configuration, final Agent agent) throws ControllerException {
return configuration.requestRoutingKey()+".*";
}
}
|
apache-2.0
|
googleapis/python-contact-center-insights
|
samples/generated_samples/contactcenterinsights_v1_generated_contact_center_insights_update_issue_sync.py
|
1517
|
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for UpdateIssue
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-contact-center-insights
# [START contactcenterinsights_v1_generated_ContactCenterInsights_UpdateIssue_sync]
from google.cloud import contact_center_insights_v1
def sample_update_issue():
# Create a client
client = contact_center_insights_v1.ContactCenterInsightsClient()
# Initialize request argument(s)
request = contact_center_insights_v1.UpdateIssueRequest(
)
# Make the request
response = client.update_issue(request=request)
# Handle the response
print(response)
# [END contactcenterinsights_v1_generated_ContactCenterInsights_UpdateIssue_sync]
|
apache-2.0
|
reinfer/riakpp
|
src/connection_pool.hpp
|
5709
|
#ifndef RIAKPP_CONNECTION_POOL_HPP_
#define RIAKPP_CONNECTION_POOL_HPP_
#include <boost/asio/io_service.hpp>
#include <boost/system/error_code.hpp>
#include <cstddef>
#include <cstdint>
#include <vector>
#include "async_queue.hpp"
#include "check.hpp"
#include "endpoint_vector.hpp"
#include "transient.hpp"
namespace riak {
template <class Connection>
class connection_pool {
public:
using connection_type = Connection;
using error_type = typename connection_type::error_type;
using handler_type = typename connection_type::handler_type;
using request_type = typename connection_type::request_type;
using response_type = typename connection_type::response_type;
connection_pool(boost::asio::io_service& io_service, std::string hostname,
uint16_t port, size_t max_connections, size_t highwatermark,
uint64_t connection_timeout_ms);
~connection_pool();
void async_send(request_type request, handler_type handler);
private:
struct packaged_request {
packaged_request(request_type request, handler_type handler)
: request{std::move(request)}, handler{std::move(handler)} {}
request_type request;
handler_type handler;
};
void resolve(size_t max_connections, std::string hostname, uint16_t port);
void report_resolution_error(boost::system::error_code asio_error);
void create_connections(size_t max_connections);
void notify_connection_ready(connection_type& connection);
void send_request(connection_type& connection, packaged_request packaged);
boost::asio::io_service& io_service_;
std::vector<std::unique_ptr<connection_type>> connections_;
async_queue<packaged_request> request_queue_;
uint64_t connection_timeout_ms_;
endpoint_vector endpoints_;
transient<connection_pool> transient_;
};
template <class Connection>
connection_pool<Connection>::connection_pool(
boost::asio::io_service& io_service, std::string hostname, uint16_t port,
size_t max_connections, size_t highwatermark,
uint64_t connection_timeout_ms)
: io_service_(io_service),
request_queue_{highwatermark, max_connections},
connection_timeout_ms_{connection_timeout_ms},
transient_{*this} {
RIAKPP_CHECK_GE(max_connections, 0)
<< "Number of connections must be non-zero.";
connections_.reserve(max_connections);
resolve(max_connections, std::move(hostname), port);
}
template <class Connection>
connection_pool<Connection>::~connection_pool() {
request_queue_.close();
transient_.reset();
connections_.clear();
}
template <class Connection>
void connection_pool<Connection>::async_send(request_type request,
handler_type handler) {
request_queue_.emplace(std::move(request), std::move(handler));
}
template <class Connection>
void connection_pool<Connection>::resolve(size_t max_connections,
std::string hostname, uint16_t port) {
using resolver = boost::asio::ip::tcp::resolver;
auto* resolver_raw = new resolver{io_service_};
auto query = resolver::query{std::move(hostname), std::to_string(port)};
auto self_ref = transient_.ref();
resolver_raw->async_resolve(
std::move(query),
transient_.wrap([this, resolver_raw, max_connections](
boost::system::error_code ec,
boost::asio::ip::tcp::resolver::iterator endpoint_begin) {
std::unique_ptr<resolver> resolver_destroyer{resolver_raw};
if (ec) {
report_resolution_error(ec);
} else {
endpoints_.assign(endpoint_begin, decltype(endpoint_begin) {});
create_connections(max_connections);
}
}));
}
template <class Connection>
void connection_pool<Connection>::report_resolution_error(
boost::system::error_code asio_error) {
request_queue_.async_pop(
transient_.wrap([this, asio_error](packaged_request packaged) {
io_service_.post(
std::bind(std::move(packaged.handler),
error_type{asio_error.value(), std::generic_category()},
response_type{}));
report_resolution_error(asio_error);
}));
}
template <class Connection>
void connection_pool<Connection>::create_connections(size_t max_connections) {
RIAKPP_CHECK_GE(endpoints_.size(), 0);
for (size_t i_conn = 0; i_conn < max_connections; ++i_conn) {
connections_.emplace_back(
new connection_type{io_service_, endpoints_.begin(), endpoints_.end(),
connection_timeout_ms_});
}
for (auto& connection_ptr : connections_) {
notify_connection_ready(*connection_ptr);
}
}
template <class Connection>
void connection_pool<Connection>::notify_connection_ready(
connection_type& connection) {
request_queue_.async_pop(
transient_.wrap([this, &connection](packaged_request packaged) {
send_request(connection, std::move(packaged));
}));
}
template <class Connection>
void connection_pool<Connection>::send_request(connection_type& connection,
packaged_request packaged) {
using namespace std::placeholders;
auto call_and_notify =
[this, &connection](handler_type& original_handler, error_type error,
response_type& response) {
notify_connection_ready(connection);
io_service_.post(
std::bind(std::move(original_handler), error, std::move(response)));
};
auto wrapped = transient_.wrap(std::bind(
std::move(call_and_notify), std::move(packaged.handler), _1, _2));
connection.async_send(std::move(packaged.request), std::move(wrapped));
}
} // namespace riak
#endif // #ifndef RIAKPP_CONNECTION_POOL_HPP_
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Anthyllis/Anthyllis macrocarpa/README.md
|
176
|
# Anthyllis macrocarpa Walp. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
googlegenomics/cloudml-examples
|
trainer/util.py
|
2296
|
#!/usr/bin/python
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Reusable utility functions.
This file is generic and can be reused by other models without modification.
"""
from apache_beam.transforms import core
import tensorflow as tf
def int64_feature(value):
"""Create a multi-valued int64 feature from a single value."""
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def bytes_feature(value):
"""Create a multi-valued bytes feature from a single value."""
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def float_feature(value):
"""Create a multi-valued float feature from a single value."""
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
class DefaultToKeyDict(dict):
"""Custom dictionary to use the key as the value for any missing entries."""
def __missing__(self, key):
return str(key)
class TableToDictCombineFn(core.CombineFn):
"""Beam transform to create a python dictionary from a BigQuery table.
This CombineFn reshapes rows from a BigQuery table using the specified key
column to a Python dictionary.
"""
def __init__(self, key_column):
self.key_column = key_column
def create_accumulator(self):
return dict()
def add_input(self, accumulator, element):
accumulator[element[self.key_column]] = element
return accumulator
def add_inputs(self, accumulator, elements):
for element in elements:
self.add_input(accumulator, element)
return accumulator
def merge_accumulators(self, accumulators):
final_accumulator = {}
for accumulator in accumulators:
final_accumulator.update(accumulator)
return final_accumulator
def extract_output(self, accumulator):
return accumulator
|
apache-2.0
|
bytesparadise/libasciidoc
|
CHANGELOG.md
|
67869
|
# [0.6.0](https://github.com/bytesparadise/libasciidoc/compare/v0.5.1...v0.6.0) (2021-03-21)
Version 0.6.0 focused on improved support for substitutions. It also includes a few extra features
and fixes for bugs discovered while working on the main theme.
### Bug Fixes
* **parser:** check for letters in roman numbering of list item ([#787](https://github.com/bytesparadise/libasciidoc/issues/787)) ([e7a8907](https://github.com/bytesparadise/libasciidoc/commit/e7a8907aeaddedc17d4145fb93576330fea314c3)), closes [#747](https://github.com/bytesparadise/libasciidoc/issues/747)
* **parser:** rearranging lists with delimited blocks afterwards ([#789](https://github.com/bytesparadise/libasciidoc/issues/789)) ([d547fd0](https://github.com/bytesparadise/libasciidoc/commit/d547fd05c68ce67b3a5e1593387744a9b5d36493)), closes [#785](https://github.com/bytesparadise/libasciidoc/issues/785)
* support multiple roles on blocks ([#807](https://github.com/bytesparadise/libasciidoc/issues/807)) ([50fb873](https://github.com/bytesparadise/libasciidoc/commit/50fb873ee8118d1812ab0a1a154ac5fe33856929)), closes [#602](https://github.com/bytesparadise/libasciidoc/issues/602)
* **parser:** support nested attributes in links ([#836](https://github.com/bytesparadise/libasciidoc/issues/836)) ([7307f2f](https://github.com/bytesparadise/libasciidoc/commit/7307f2f6fce1276e17883b4f189253b2b200e561)), closes [#826](https://github.com/bytesparadise/libasciidoc/issues/826)
* **parser/renderer:** encode URL in links when no text is provided ([#788](https://github.com/bytesparadise/libasciidoc/issues/788)) ([ad8fee6](https://github.com/bytesparadise/libasciidoc/commit/ad8fee61bc34fb24a1b6cd5b482ac5d105a3f32a)), closes [#745](https://github.com/bytesparadise/libasciidoc/issues/745)
### Code Refactoring
* **parser:** simplified grammar rules for attributes ([#804](https://github.com/bytesparadise/libasciidoc/issues/804)) ([1a08657](https://github.com/bytesparadise/libasciidoc/commit/1a086575fa0fdf617940283599fd602d92ec6965)), closes [#750](https://github.com/bytesparadise/libasciidoc/issues/750)
### Features
* **parser:** support attribute substitution in attribute declaration ([#801](https://github.com/bytesparadise/libasciidoc/issues/801)) ([b0e80f5](https://github.com/bytesparadise/libasciidoc/commit/b0e80f5cb96af2fa178294ac539e4aae32d48132)), closes [#800](https://github.com/bytesparadise/libasciidoc/issues/800)
* **parser:** support attribute substitution in element attributes ([#799](https://github.com/bytesparadise/libasciidoc/issues/799)) ([62ddfce](https://github.com/bytesparadise/libasciidoc/commit/62ddfced96638632da7aae8168e59326ed1f68f7)), closes [#604](https://github.com/bytesparadise/libasciidoc/issues/604)
* **parser:** support custom substitutions on literal blocks ([#774](https://github.com/bytesparadise/libasciidoc/issues/774)) ([826d5db](https://github.com/bytesparadise/libasciidoc/commit/826d5db4c8b67c75c7d36aa32b2daff66360d7b3)), closes [#770](https://github.com/bytesparadise/libasciidoc/issues/770)
* **parser:** support for 'idseparator' attribute ([#786](https://github.com/bytesparadise/libasciidoc/issues/786)) ([cd386b8](https://github.com/bytesparadise/libasciidoc/commit/cd386b870f224e86cfe3f88f91679efc799eb1e5)), closes [#783](https://github.com/bytesparadise/libasciidoc/issues/783)
* **parser:** support incremental substitutions ([#782](https://github.com/bytesparadise/libasciidoc/issues/782)) ([fb1e1fd](https://github.com/bytesparadise/libasciidoc/commit/fb1e1fd0bb89918cc54ea615db6a2b24770f2a77)), closes [#761](https://github.com/bytesparadise/libasciidoc/issues/761)
* **parser:** support substitutions on passthrough blocks ([#773](https://github.com/bytesparadise/libasciidoc/issues/773)) ([68a9843](https://github.com/bytesparadise/libasciidoc/commit/68a984375984183a89808eaba465985c153b360b)), closes [#772](https://github.com/bytesparadise/libasciidoc/issues/772)
* **parser/renderer:** support 'listing' paragraphs ([#781](https://github.com/bytesparadise/libasciidoc/issues/781)) ([87b53b3](https://github.com/bytesparadise/libasciidoc/commit/87b53b3abffe1436c8de73523d212edbc28d8143)), closes [#778](https://github.com/bytesparadise/libasciidoc/issues/778)
* **parser/renderer:** support 'nowrap' option on source blocks ([#795](https://github.com/bytesparadise/libasciidoc/issues/795)) ([6fa3065](https://github.com/bytesparadise/libasciidoc/commit/6fa306570f6dfbee19548a55398800f5bf705342)), closes [#784](https://github.com/bytesparadise/libasciidoc/issues/784)
* **parser/renderer:** support 'target' and 'role' attributes in link ([#810](https://github.com/bytesparadise/libasciidoc/issues/810)) ([e86a252](https://github.com/bytesparadise/libasciidoc/commit/e86a25286a38def77a04b4c67ef7b379052c350d)), closes [#803](https://github.com/bytesparadise/libasciidoc/issues/803)
* **parser/renderer:** support example paragraphs ([#779](https://github.com/bytesparadise/libasciidoc/issues/779)) ([d642854](https://github.com/bytesparadise/libasciidoc/commit/d642854399a7e56b326b7826b5a0ba1dfe303e06)), closes [#728](https://github.com/bytesparadise/libasciidoc/issues/728)
* **parser/renderer:** support quoted text in element attributes ([#835](https://github.com/bytesparadise/libasciidoc/issues/835)) ([ce36ad6](https://github.com/bytesparadise/libasciidoc/commit/ce36ad6381a0b825333ab0bcc7d488b984f4772e)), closes [#829](https://github.com/bytesparadise/libasciidoc/issues/829)
* **renderer:** default HTML title ([#798](https://github.com/bytesparadise/libasciidoc/issues/798)) ([6b43b68](https://github.com/bytesparadise/libasciidoc/commit/6b43b681cd6ad8c2692760429e629118f072231d)), closes [#627](https://github.com/bytesparadise/libasciidoc/issues/627)
* support interactive checklists ([#811](https://github.com/bytesparadise/libasciidoc/issues/811)) ([158988e](https://github.com/bytesparadise/libasciidoc/commit/158988e7b41649458d2a71bd866dfc5a31e80faa)), closes [#629](https://github.com/bytesparadise/libasciidoc/issues/629)
### BREAKING CHANGES
* **parser:** for images and links, positional attributes are delimited
with commas, so if a link text should contain such a comma, it is necessary
that the text be wrapped in single or double quotes. This makes the syntax
(and thus, the parsing) consistent between block attributes and inline
attributes.
Eg: `link:http://example.com["a description, with comma"]`
* **parser:** inline attributes content must not start with spaces, as
it is the case with block attributes.
Eg: `image::cookie.png[ cookie ]` is not valid.
# [0.5.1](https://github.com/bytesparadise/libasciidoc/compare/v0.5.0...v0.5.1) (2020-10-04)
This is a patch-release to solve a bug in the passthrough block substitutions.
This issue should have been addressed in v0.5.0 but it wasn't triaged 🤦♂️
### Bug Fixes
* **parser:** ignore special chars in passthrough blocks ([#763](https://github.com/bytesparadise/libasciidoc/issues/763)) ([3f4ee89](https://github.com/bytesparadise/libasciidoc/commit/3f4ee893b7e1322daedfd874fff1fe20117033da)), closes [#746](https://github.com/bytesparadise/libasciidoc/issues/746)
# [0.5.0](https://github.com/bytesparadise/libasciidoc/compare/v0.3.0...v) (2020-10-04)
Version 0.5.0 adds the XHTML5 backend, as well as support for custom substitutions on paragraphs and delimited blocks.
Also, rendering on other blocks as also been greatly improved, thanks to better support for attributes.
Finally, source blocks can now be rendered with the [Chroma syntax highlighter](https://github.com/alecthomas/chroma) (using the `:source-highlighter: pygments` or `:source-highlighter: chroma` document attribute) and callouts are supported.
As usual, this version also includes its share bug fixes as well.
Huge thanks to [gdamore](https://github.com/gdamore) and [pjanx](https://github.com/pjanx) for their numerous contributions 🙌
### Bug Fixes
* **parser:** colons, images and icons not supported in list terms ([#615](https://github.com/bytesparadise/libasciidoc/issues/615)) ([b61a886](https://github.com/bytesparadise/libasciidoc/commit/b61a88665c3ce458b04d7918b5f619fc3fd9c118)), closes [#614](https://github.com/bytesparadise/libasciidoc/issues/614)
* **parser:** expose authors and revision in the document attributes ([#521](https://github.com/bytesparadise/libasciidoc/issues/521)) ([9335817](https://github.com/bytesparadise/libasciidoc/commit/933581710d196b02dddbad4fd8ce9bece5788d47)), closes [#517](https://github.com/bytesparadise/libasciidoc/issues/517)
* **parser:** failure to convert nested elements ([#740](https://github.com/bytesparadise/libasciidoc/issues/740)) ([6f07b44](https://github.com/bytesparadise/libasciidoc/commit/6f07b44465e7afa7a402a970ecc1a282dc2f1dc9)), closes [#739](https://github.com/bytesparadise/libasciidoc/issues/739)
* **parser:** fix footnotes grammar ([#535](https://github.com/bytesparadise/libasciidoc/issues/535)) ([03587bb](https://github.com/bytesparadise/libasciidoc/commit/03587bbc469fb5fedf5c6d1d601eaf156de45429)), closes [#532](https://github.com/bytesparadise/libasciidoc/issues/532)
* **parser:** fix quoted text delimitation ([#505](https://github.com/bytesparadise/libasciidoc/issues/505)) ([c394f70](https://github.com/bytesparadise/libasciidoc/commit/c394f70c3ccca98ef291be6a7c0e58cd2cf05b29)), closes [#504](https://github.com/bytesparadise/libasciidoc/issues/504)
* **parser:** ignore standalone attributes at the end of doc ([#606](https://github.com/bytesparadise/libasciidoc/issues/606)) ([a57b8fb](https://github.com/bytesparadise/libasciidoc/commit/a57b8fb7d6b0d057f4f01b4713d9688554b172a1)), closes [#605](https://github.com/bytesparadise/libasciidoc/issues/605)
* **parser:** Inline attribute parsing is incorrect ([#684](https://github.com/bytesparadise/libasciidoc/issues/684)) ([04f2a1d](https://github.com/bytesparadise/libasciidoc/commit/04f2a1d9e3e16deb9bf3630184190cd2ea51557b))
* **parser:** quoted strings should not allow interior adjacent spaces ([#636](https://github.com/bytesparadise/libasciidoc/issues/636)) ([fc8a97e](https://github.com/bytesparadise/libasciidoc/commit/fc8a97e04e163c147b55f3d6a37fb7cf71e2e3ff)), closes [#622](https://github.com/bytesparadise/libasciidoc/issues/622)
* **parser:** quoted text newline handling ([#624](https://github.com/bytesparadise/libasciidoc/issues/624)) ([07252b5](https://github.com/bytesparadise/libasciidoc/commit/07252b5014d4a571f84cf88d56cd510446ca4bc5)), closes [#623](https://github.com/bytesparadise/libasciidoc/issues/623)
* **parser:** verify configuration attributes ([#513](https://github.com/bytesparadise/libasciidoc/issues/513)) ([a9da628](https://github.com/bytesparadise/libasciidoc/commit/a9da62801e237f7a3af43f673691a2e9fc5c877c)), closes [#509](https://github.com/bytesparadise/libasciidoc/issues/509)
* **parser:** verify document with leading empty line ([#757](https://github.com/bytesparadise/libasciidoc/issues/757)) ([921565a](https://github.com/bytesparadise/libasciidoc/commit/921565aadd342f04b7580f949f218735d04e92d5)), closes [#707](https://github.com/bytesparadise/libasciidoc/issues/707)
* **parser/renderer:** support concelead index terms in labeled lists ([#507](https://github.com/bytesparadise/libasciidoc/issues/507)) ([1b574d6](https://github.com/bytesparadise/libasciidoc/commit/1b574d6df47a3385b35e387ec7bcdb8914a7d16a)), closes [#502](https://github.com/bytesparadise/libasciidoc/issues/502)
* **parser/renderer:** support non-alphanum characters in index terms ([#506](https://github.com/bytesparadise/libasciidoc/issues/506)) ([c94b470](https://github.com/bytesparadise/libasciidoc/commit/c94b470f87718276c89476e098b9442ff57d76a1)), closes [#503](https://github.com/bytesparadise/libasciidoc/issues/503)
* **renderer:** do not 'HTML escape' string elements ([#752](https://github.com/bytesparadise/libasciidoc/issues/752)) ([4fd36b5](https://github.com/bytesparadise/libasciidoc/commit/4fd36b5347513db2a8d04d32188e323e104b8690)), closes [#741](https://github.com/bytesparadise/libasciidoc/issues/741)
* **renderer:** do not highlight syntax when language is not set ([#515](https://github.com/bytesparadise/libasciidoc/issues/515)) ([c3439bd](https://github.com/bytesparadise/libasciidoc/commit/c3439bd0e201af844e56093a636fa3341cb3bb6f)), closes [#514](https://github.com/bytesparadise/libasciidoc/issues/514)
* **renderer:** do not HTML escape content twice in source blocks ([#571](https://github.com/bytesparadise/libasciidoc/issues/571)) ([08b705d](https://github.com/bytesparadise/libasciidoc/commit/08b705d0ac25a17a0cde880075fd62dc4bc778e0)), closes [#570](https://github.com/bytesparadise/libasciidoc/issues/570)
* **renderer:** Remove stray debugging message ([#716](https://github.com/bytesparadise/libasciidoc/issues/716)) ([8b13202](https://github.com/bytesparadise/libasciidoc/commit/8b132025ceff8f9efe09585c7551c33b43fa8534))
* **renderer:** Section ID should include the icon class ([#730](https://github.com/bytesparadise/libasciidoc/issues/730)) ([994c92f](https://github.com/bytesparadise/libasciidoc/commit/994c92f151f719b16c6e43e5ac2fa2e98c34259a)), closes [#691](https://github.com/bytesparadise/libasciidoc/issues/691)
* **renderer:** source highlighter should get unadulterated string ([#723](https://github.com/bytesparadise/libasciidoc/issues/723)) ([8fbc228](https://github.com/bytesparadise/libasciidoc/commit/8fbc2282dc14e9fa5ab05b82e4c5b107d65ebf51)), closes [#721](https://github.com/bytesparadise/libasciidoc/issues/721)
* **renderer:** Wrong code for (TM) ([#642](https://github.com/bytesparadise/libasciidoc/issues/642)) ([f8cb430](https://github.com/bytesparadise/libasciidoc/commit/f8cb4301cadd8b5975fdd15908a37ed2f0c7d972)), closes [#641](https://github.com/bytesparadise/libasciidoc/issues/641)
* **types:** `CalloutListItem` must implement `DocumentElement` ([#569](https://github.com/bytesparadise/libasciidoc/issues/569)) ([d759c0b](https://github.com/bytesparadise/libasciidoc/commit/d759c0b7ebcbc1c1a744fc2376f4cc5629342ce6)), closes [#568](https://github.com/bytesparadise/libasciidoc/issues/568)
### Features
* **parser:** custom subs on paragraphs ([#726](https://github.com/bytesparadise/libasciidoc/issues/726)) ([5dcda32](https://github.com/bytesparadise/libasciidoc/commit/5dcda3220c3178d9ae327dbecd7d040704d593b5)), closes [#597](https://github.com/bytesparadise/libasciidoc/issues/597)
* **parser:** custom substitutions on paragraphs ([#749](https://github.com/bytesparadise/libasciidoc/issues/749)) ([7050c34](https://github.com/bytesparadise/libasciidoc/commit/7050c3426cbaf3b823f28431358d878af08990c1)), closes [#597](https://github.com/bytesparadise/libasciidoc/issues/597)
* **parser:** support custom substitutions on delimited blocks ([#755](https://github.com/bytesparadise/libasciidoc/issues/755)) ([2179d24](https://github.com/bytesparadise/libasciidoc/commit/2179d247e08d87c2b1ba04b395921daf82b3e504)), closes [#558](https://github.com/bytesparadise/libasciidoc/issues/558)
* **parser:** support custom substitutions on delimited blocks ([#759](https://github.com/bytesparadise/libasciidoc/issues/759)) ([667d4ce](https://github.com/bytesparadise/libasciidoc/commit/667d4cedc2662e9f8c30c4fad2d52c800723411f)), closes [#558](https://github.com/bytesparadise/libasciidoc/issues/558)
* **parser:** support Markdown style quote blocks ([#563](https://github.com/bytesparadise/libasciidoc/issues/563)) ([b17f6e1](https://github.com/bytesparadise/libasciidoc/commit/b17f6e1ab1014d9eedc8df7dffc441f30b179787)), closes [#561](https://github.com/bytesparadise/libasciidoc/issues/561)
* **parser/renderer:** Multiple roles for images. ([#669](https://github.com/bytesparadise/libasciidoc/issues/669)) ([efdeeea](https://github.com/bytesparadise/libasciidoc/commit/efdeeeab8bb9fce5358ed37f421f9354ed0d774e)), closes [#602](https://github.com/bytesparadise/libasciidoc/issues/602)
* **parser/renderer:** Render curved quotes ([#648](https://github.com/bytesparadise/libasciidoc/issues/648)) ([51153eb](https://github.com/bytesparadise/libasciidoc/commit/51153ebae8b2ded797e80a5b27fa37c01244626c)), closes [#176](https://github.com/bytesparadise/libasciidoc/issues/176)
* **parser/renderer:** support callouts in verbatim blocks ([#567](https://github.com/bytesparadise/libasciidoc/issues/567)) ([9b5a26c](https://github.com/bytesparadise/libasciidoc/commit/9b5a26c7e403ee2d33703758314f6c87d2657e9d)), closes [#562](https://github.com/bytesparadise/libasciidoc/issues/562)
* **parser/renderer:** Support inline role assignment ([#598](https://github.com/bytesparadise/libasciidoc/issues/598)) ([4ab8453](https://github.com/bytesparadise/libasciidoc/commit/4ab84532ee4578dfe3d792a4bc847b73f4372257)), closes [#588](https://github.com/bytesparadise/libasciidoc/issues/588)
* **parser/renderer:** support passthrough blocks ([#572](https://github.com/bytesparadise/libasciidoc/issues/572)) ([a4870b3](https://github.com/bytesparadise/libasciidoc/commit/a4870b316dbb6427a5b4af72d22ce5c8f131d1a8)), closes [#269](https://github.com/bytesparadise/libasciidoc/issues/269)
* **parser/renderer:** Support wanted for #mark# syntax ([#600](https://github.com/bytesparadise/libasciidoc/issues/600)) ([90b4f2d](https://github.com/bytesparadise/libasciidoc/commit/90b4f2d3dff3c93203be1716362991a0866d378f)), closes [#599](https://github.com/bytesparadise/libasciidoc/issues/599)
* **parser/renderer:** unordered lists should support style ([#660](https://github.com/bytesparadise/libasciidoc/issues/660)) ([c93bc82](https://github.com/bytesparadise/libasciidoc/commit/c93bc82d9c184379699051058861e1ac3abb9241)), closes [#658](https://github.com/bytesparadise/libasciidoc/issues/658)
* **parser/renderer/types:** Support inline and image icons ([#613](https://github.com/bytesparadise/libasciidoc/issues/613)) ([fb7414e](https://github.com/bytesparadise/libasciidoc/commit/fb7414e00767ec87ec6b432c6778470b1f595eb2)), closes [#587](https://github.com/bytesparadise/libasciidoc/issues/587) [#611](https://github.com/bytesparadise/libasciidoc/issues/611) [#610](https://github.com/bytesparadise/libasciidoc/issues/610)
* **renderer:** Add image float, align, and capture support. ([#685](https://github.com/bytesparadise/libasciidoc/issues/685)) ([c51cc09](https://github.com/bytesparadise/libasciidoc/commit/c51cc09cc9439b05e73f90e8e894a65fdd7a02e9))
* **renderer:** add XHTML5 support ([#618](https://github.com/bytesparadise/libasciidoc/issues/618)) ([4448584](https://github.com/bytesparadise/libasciidoc/commit/444858407c4b029e6bdc8105402fcaf78b3292d5)), closes [#601](https://github.com/bytesparadise/libasciidoc/issues/601)
* **renderer:** attribute to disable header and footer ([#516](https://github.com/bytesparadise/libasciidoc/issues/516)) ([3867576](https://github.com/bytesparadise/libasciidoc/commit/386757605b23cbea31587e29f32ada513a41f203)), closes [#510](https://github.com/bytesparadise/libasciidoc/issues/510)
* **renderer:** Closing html tag should have a newline appended ([#718](https://github.com/bytesparadise/libasciidoc/issues/718)) ([6774f18](https://github.com/bytesparadise/libasciidoc/commit/6774f186e2fa43372f9d5010ff997473710bcd9c)), closes [#702](https://github.com/bytesparadise/libasciidoc/issues/702)
* **renderer:** Customizable admonition captions ([#724](https://github.com/bytesparadise/libasciidoc/issues/724)) ([d960766](https://github.com/bytesparadise/libasciidoc/commit/d960766f5f94d6ea64e79882002b0cadab948502)), closes [#679](https://github.com/bytesparadise/libasciidoc/issues/679)
* **renderer:** Customizable caption prefix. ([5c0d5ca](https://github.com/bytesparadise/libasciidoc/commit/5c0d5caa82271c27505aaf31a113ee3d0fff58cf))
* **renderer:** Example blocks should support custom captions ([5dd3224](https://github.com/bytesparadise/libasciidoc/commit/5dd3224e115c165891d1ac9223617813d8161043))
* **renderer:** htmlEscape should escape quotes ([#647](https://github.com/bytesparadise/libasciidoc/issues/647)) ([991725d](https://github.com/bytesparadise/libasciidoc/commit/991725d0c8cdfecf5ecbc8becc1831df326019a0)), closes [#644](https://github.com/bytesparadise/libasciidoc/issues/644)
* **renderer:** include authors in 'meta' tag ([#544](https://github.com/bytesparadise/libasciidoc/issues/544)) ([6bdca28](https://github.com/bytesparadise/libasciidoc/commit/6bdca281406c4a79ebab22f726dd8673127a5e25)), closes [#543](https://github.com/bytesparadise/libasciidoc/issues/543)
* **renderer:** inline images deserve links, too ([#754](https://github.com/bytesparadise/libasciidoc/issues/754)) ([3480071](https://github.com/bytesparadise/libasciidoc/commit/3480071e77b4e284d0a95b984d64df822f965ff0))
* **renderer:** role not honored on h1 titles ([#583](https://github.com/bytesparadise/libasciidoc/issues/583)) ([#584](https://github.com/bytesparadise/libasciidoc/issues/584)) ([79a43b3](https://github.com/bytesparadise/libasciidoc/commit/79a43b390f3866e40a8570a9ad70c49f5b8157ec))
* **renderer:** support Copyright character replacement ([#526](https://github.com/bytesparadise/libasciidoc/issues/526)) ([c0f5b5c](https://github.com/bytesparadise/libasciidoc/commit/c0f5b5c06d122bc406240ec216d133f5c96fb688)), closes [#169](https://github.com/bytesparadise/libasciidoc/issues/169) [#524](https://github.com/bytesparadise/libasciidoc/issues/524)
* **renderer:** Support customizable table captions ([#689](https://github.com/bytesparadise/libasciidoc/issues/689)) ([4c8b1fd](https://github.com/bytesparadise/libasciidoc/commit/4c8b1fd9c2537e4881745dc68a8150e540b0c7f2))
* **renderer:** support manpage doctype ([#531](https://github.com/bytesparadise/libasciidoc/issues/531)) ([9538b1a](https://github.com/bytesparadise/libasciidoc/commit/9538b1a5ae1e6f63f5db18dc390cfa845b17e61a)), closes [#511](https://github.com/bytesparadise/libasciidoc/issues/511)
* **renderer:** Support reversed lists ([#668](https://github.com/bytesparadise/libasciidoc/issues/668)) ([b323d2f](https://github.com/bytesparadise/libasciidoc/commit/b323d2f8667d98c341b9f769efdf5240c0d5ed7d)), closes [#662](https://github.com/bytesparadise/libasciidoc/issues/662)
* **renderer:** Tables should honor table-caption attribute ([#717](https://github.com/bytesparadise/libasciidoc/issues/717)) ([a6273dd](https://github.com/bytesparadise/libasciidoc/commit/a6273dd169394cc7eb5a0f0e4a333161f927cbba))
* **renderer:** Top level table styling ([#690](https://github.com/bytesparadise/libasciidoc/issues/690)) ([e6437ac](https://github.com/bytesparadise/libasciidoc/commit/e6437ac8caaf57dd25b7aca08013392d42bd904d))
* **renderer:** version-label not honored ([#711](https://github.com/bytesparadise/libasciidoc/issues/711)) ([d3c117e](https://github.com/bytesparadise/libasciidoc/commit/d3c117ed55c4a07153f643cab59f5a62726c881d)), closes [#710](https://github.com/bytesparadise/libasciidoc/issues/710)
* **types/parser/renderer:** Support for counters ([#715](https://github.com/bytesparadise/libasciidoc/issues/715)) ([b9e82cd](https://github.com/bytesparadise/libasciidoc/commit/b9e82cd4bc445151a24066cb160d96be34582da2)), closes [#714](https://github.com/bytesparadise/libasciidoc/issues/714)
* **types/renderer:** Table cols attribute support ([#698](https://github.com/bytesparadise/libasciidoc/issues/698)) ([#698](https://github.com/bytesparadise/libasciidoc/issues/698)) ([122f8da](https://github.com/bytesparadise/libasciidoc/commit/122f8da6f6baddf70273b6b05026688267a72451)), closes [#694](https://github.com/bytesparadise/libasciidoc/issues/694) [#686](https://github.com/bytesparadise/libasciidoc/issues/686)
* **validator:** validate manpage document ([#545](https://github.com/bytesparadise/libasciidoc/issues/545)) ([65b298d](https://github.com/bytesparadise/libasciidoc/commit/65b298ddf604585ab4e07d7adcd978f4ccb4fc94)), closes [#529](https://github.com/bytesparadise/libasciidoc/issues/529)
* **renderer:** Support chroma, fix source paragraph ([#720](https://github.com/bytesparadise/libasciidoc/issues/720)) ([533e63d0](https://github.com/bytesparadise/libasciidoc/commit/533e63d0fb05c3baa534deb0a027ba4f44388866)), closes [#706](https://github.com/bytesparadise/libasciidoc/issues/706)
# [0.4.0](https://github.com/bytesparadise/libasciidoc/compare/v0.3.0...v0.4.0) (2020-04-19)
Focus of v0.4.0 was around support for manpage document, plus a bit of refactoring and some bug fixes.
Thanks to [gdamore](https://github.com/gdamore) for reporting issues and helping the project 🙌
### Bug Fixes
* **parser:** expose authors and revision in the document attributes ([#521](https://github.com/bytesparadise/libasciidoc/issues/521)) ([9335817](https://github.com/bytesparadise/libasciidoc/commit/933581710d196b02dddbad4fd8ce9bece5788d47)), closes [#517](https://github.com/bytesparadise/libasciidoc/issues/517)
* **parser:** fix footnotes grammar ([#535](https://github.com/bytesparadise/libasciidoc/issues/535)) ([03587bb](https://github.com/bytesparadise/libasciidoc/commit/03587bbc469fb5fedf5c6d1d601eaf156de45429)), closes [#532](https://github.com/bytesparadise/libasciidoc/issues/532)
* **parser:** fix quoted text delimitation ([#505](https://github.com/bytesparadise/libasciidoc/issues/505)) ([c394f70](https://github.com/bytesparadise/libasciidoc/commit/c394f70c3ccca98ef291be6a7c0e58cd2cf05b29)), closes [#504](https://github.com/bytesparadise/libasciidoc/issues/504)
* **parser:** verify configuration attributes ([#513](https://github.com/bytesparadise/libasciidoc/issues/513)) ([a9da628](https://github.com/bytesparadise/libasciidoc/commit/a9da62801e237f7a3af43f673691a2e9fc5c877c)), closes [#509](https://github.com/bytesparadise/libasciidoc/issues/509)
* **parser/renderer:** support concelead index terms in labeled lists ([#507](https://github.com/bytesparadise/libasciidoc/issues/507)) ([1b574d6](https://github.com/bytesparadise/libasciidoc/commit/1b574d6df47a3385b35e387ec7bcdb8914a7d16a)), closes [#502](https://github.com/bytesparadise/libasciidoc/issues/502)
* **parser/renderer:** support non-alphanum characters in index terms ([#506](https://github.com/bytesparadise/libasciidoc/issues/506)) ([c94b470](https://github.com/bytesparadise/libasciidoc/commit/c94b470f87718276c89476e098b9442ff57d76a1)), closes [#503](https://github.com/bytesparadise/libasciidoc/issues/503)
* **renderer:** do not highlight syntax when language is not set ([#515](https://github.com/bytesparadise/libasciidoc/issues/515)) ([c3439bd](https://github.com/bytesparadise/libasciidoc/commit/c3439bd0e201af844e56093a636fa3341cb3bb6f)), closes [#514](https://github.com/bytesparadise/libasciidoc/issues/514)
### Features
* **renderer:** attribute to disable header and footer ([#516](https://github.com/bytesparadise/libasciidoc/issues/516)) ([3867576](https://github.com/bytesparadise/libasciidoc/commit/386757605b23cbea31587e29f32ada513a41f203)), closes [#510](https://github.com/bytesparadise/libasciidoc/issues/510)
* **renderer:** include authors in 'meta' tag ([#544](https://github.com/bytesparadise/libasciidoc/issues/544)) ([6bdca28](https://github.com/bytesparadise/libasciidoc/commit/6bdca281406c4a79ebab22f726dd8673127a5e25)), closes [#543](https://github.com/bytesparadise/libasciidoc/issues/543)
* **renderer:** support Copyright character replacement ([#526](https://github.com/bytesparadise/libasciidoc/issues/526)) ([c0f5b5c](https://github.com/bytesparadise/libasciidoc/commit/c0f5b5c06d122bc406240ec216d133f5c96fb688)), closes [#169](https://github.com/bytesparadise/libasciidoc/issues/169) [#524](https://github.com/bytesparadise/libasciidoc/issues/524)
* **renderer:** support manpage doctype ([#531](https://github.com/bytesparadise/libasciidoc/issues/531)) ([9538b1a](https://github.com/bytesparadise/libasciidoc/commit/9538b1a5ae1e6f63f5db18dc390cfa845b17e61a)), closes [#511](https://github.com/bytesparadise/libasciidoc/issues/511)
* **test:** add HTML matcher ([#539](https://github.com/bytesparadise/libasciidoc/issues/539)) ([125d163](https://github.com/bytesparadise/libasciidoc/commit/125d1632f5d990a0a4e11b4d1ff9c75246e1d9c4)), closes [#538](https://github.com/bytesparadise/libasciidoc/issues/538)
* **validator:** validate manpage document ([#545](https://github.com/bytesparadise/libasciidoc/issues/545)) ([65b298d](https://github.com/bytesparadise/libasciidoc/commit/65b298ddf604585ab4e07d7adcd978f4ccb4fc94)), closes [#529](https://github.com/bytesparadise/libasciidoc/issues/529)
# [0.3.0](https://github.com/bytesparadise/libasciidoc/compare/v0.2.0...v0.3.0) (2020-03-14)
Focus of v0.3.0 was around performances, support for file inclusions, syntax highlighting in source blocks, configuration via the CLI and, refactoring and bug fixes.
Thanks to [Arteneko](https://github.com/Arteneko), [gdamore](https://github.com/gdamore), [shuLhan](https://github.com/shuLhan) and [odknt](https://github.com/odknt) for reporting issues and helping the project 🙌
### Bug Fixes
* **parser:** allow empty lines between attributes and element ([#496](https://github.com/bytesparadise/libasciidoc/issues/496)) ([4d3ef23](https://github.com/bytesparadise/libasciidoc/commit/4d3ef23b5215b98320eb4931c84888972167246a)), closes [#493](https://github.com/bytesparadise/libasciidoc/issues/493)
* **parser:** do not allow spaces in singleplus passthough ([#346](https://github.com/bytesparadise/libasciidoc/issues/346)) ([5663022](https://github.com/bytesparadise/libasciidoc/commit/56630226afbcf1d34fe35ca686eea7b172ba5456)), closes [#337](https://github.com/bytesparadise/libasciidoc/issues/337)
* **parser:** fix parsing in quoted text ([#357](https://github.com/bytesparadise/libasciidoc/issues/357)) ([21f6c7f](https://github.com/bytesparadise/libasciidoc/commit/21f6c7f8cf662fbb93d114c446f7431c949edff1)), closes [#354](https://github.com/bytesparadise/libasciidoc/issues/354)
* **parser:** invalid grammar rule ([#359](https://github.com/bytesparadise/libasciidoc/issues/359)) ([3f3f349](https://github.com/bytesparadise/libasciidoc/commit/3f3f3495b890df186f6f62075e9d033217a3d31a)), closes [#358](https://github.com/bytesparadise/libasciidoc/issues/358)
* **parser:** invalid parsing of link location ([#443](https://github.com/bytesparadise/libasciidoc/issues/443)) ([b7e4654](https://github.com/bytesparadise/libasciidoc/commit/b7e4654e9b9f0129f47c99aee06abfc3c73af06f)), closes [#442](https://github.com/bytesparadise/libasciidoc/issues/442)
* **parser:** provide actual filename in file inclusion error msg ([#402](https://github.com/bytesparadise/libasciidoc/issues/402)) ([bc3d557](https://github.com/bytesparadise/libasciidoc/commit/bc3d557c8cd3a170bcef96343e113cfb7260df8c)), closes [#384](https://github.com/bytesparadise/libasciidoc/issues/384)
* **parser:** support chained admonitions ([#500](https://github.com/bytesparadise/libasciidoc/issues/500)) ([f60fabf](https://github.com/bytesparadise/libasciidoc/commit/f60fabfb111d4b2daceddec849d78002747d1ef6)), closes [#492](https://github.com/bytesparadise/libasciidoc/issues/492)
* **parser:** support commas in link text attribute ([#389](https://github.com/bytesparadise/libasciidoc/issues/389)) ([23feea9](https://github.com/bytesparadise/libasciidoc/commit/23feea90dcc028d691e6b78df305e9acaded7c6b)), closes [#388](https://github.com/bytesparadise/libasciidoc/issues/388)
* **parser:** support comment between doc title and author ([#486](https://github.com/bytesparadise/libasciidoc/issues/486)) ([46e85ae](https://github.com/bytesparadise/libasciidoc/commit/46e85ae1a6cdb3ec7bada29fa62dadb8281ee8c4)), closes [#481](https://github.com/bytesparadise/libasciidoc/issues/481)
* **parser:** support encoded spaces in link URL ([#420](https://github.com/bytesparadise/libasciidoc/issues/420)) ([6c57b55](https://github.com/bytesparadise/libasciidoc/commit/6c57b552cca9e20b3ce4106945ee940cf03762fd)), closes [#419](https://github.com/bytesparadise/libasciidoc/issues/419)
* **parser:** support inline links in quoted text ([#464](https://github.com/bytesparadise/libasciidoc/issues/464)) ([6acb277](https://github.com/bytesparadise/libasciidoc/commit/6acb277fc7e22fba2dceb06027a0859dd67c8782)), closes [#456](https://github.com/bytesparadise/libasciidoc/issues/456)
* **parser:** support valid characters in URLs ([#417](https://github.com/bytesparadise/libasciidoc/issues/417)) ([98a84d4](https://github.com/bytesparadise/libasciidoc/commit/98a84d49adb409ededd9f15bb4a25e31cc5207ae)), closes [#416](https://github.com/bytesparadise/libasciidoc/issues/416)
* **parser/renderer:** skip trailing empty lines in delimited blocks ([#472](https://github.com/bytesparadise/libasciidoc/issues/472)) ([940da7f](https://github.com/bytesparadise/libasciidoc/commit/940da7f82b475bd30e8290c9f593946f630d101b)), closes [#470](https://github.com/bytesparadise/libasciidoc/issues/470)
* **parser/renderer:** support quoted text in links ([#360](https://github.com/bytesparadise/libasciidoc/issues/360)) ([e0ac68b](https://github.com/bytesparadise/libasciidoc/commit/e0ac68b26fee595e82983318fb5726eb28bdeaa0)), closes [#356](https://github.com/bytesparadise/libasciidoc/issues/356)
* **parser/renderer:** use main file path to start inclusions ([#429](https://github.com/bytesparadise/libasciidoc/issues/429)) ([5bc6ab4](https://github.com/bytesparadise/libasciidoc/commit/5bc6ab4bf31b71d52caadd5656bcdc4c3d5bddea)), closes [#424](https://github.com/bytesparadise/libasciidoc/issues/424)
* **renderer:** do not include section 0 element ([#432](https://github.com/bytesparadise/libasciidoc/issues/432)) ([bfff288](https://github.com/bytesparadise/libasciidoc/commit/bfff2883a5eb289dc4531ba8278ecdc7cc5bb81f)), closes [#425](https://github.com/bytesparadise/libasciidoc/issues/425)
* **renderer:** escape content of listing and source blocks ([#345](https://github.com/bytesparadise/libasciidoc/issues/345)) ([736a89d](https://github.com/bytesparadise/libasciidoc/commit/736a89df19689cc86bb4f0acd9c9265e3bc787c2)), closes [#341](https://github.com/bytesparadise/libasciidoc/issues/341)
* **renderer:** use file mtime as 'Last updated' ([#467](https://github.com/bytesparadise/libasciidoc/issues/467)) ([f539c75](https://github.com/bytesparadise/libasciidoc/commit/f539c75b6334ffd343fb5a240e9760edb41a190d)), closes [#461](https://github.com/bytesparadise/libasciidoc/issues/461)
### Features
* **cli:** add 'css' arg to specify the stylesheet ([#487](https://github.com/bytesparadise/libasciidoc/issues/487)) ([c1de2f2](https://github.com/bytesparadise/libasciidoc/commit/c1de2f25eee535fa6c2e5021f668299283077570)), closes [#482](https://github.com/bytesparadise/libasciidoc/issues/482)
* **cli:** support attributes set/reset in CLI ([#495](https://github.com/bytesparadise/libasciidoc/issues/495)) ([79c454c](https://github.com/bytesparadise/libasciidoc/commit/79c454cb8080b3b4172c1575f3e01ac4d0931b73)), closes [#484](https://github.com/bytesparadise/libasciidoc/issues/484)
* **parser:** do not further processing inclusions in non-asciidoc files ([#433](https://github.com/bytesparadise/libasciidoc/issues/433)) ([c4317a1](https://github.com/bytesparadise/libasciidoc/commit/c4317a14e5b1d8f8bc2924f14ab3f3c509f95d3e)), closes [#380](https://github.com/bytesparadise/libasciidoc/issues/380)
* **parser:** include document attribute when processing section 0 ([#451](https://github.com/bytesparadise/libasciidoc/issues/451)) ([0826b73](https://github.com/bytesparadise/libasciidoc/commit/0826b730b6c6eb9dcac98f39ee77bc705f84cc93)), closes [#447](https://github.com/bytesparadise/libasciidoc/issues/447)
* **parser:** report an error when tag to limit file inclusion could not be exists ([#407](https://github.com/bytesparadise/libasciidoc/issues/407)) ([fc187b4](https://github.com/bytesparadise/libasciidoc/commit/fc187b4a13240bd7bb6986a67a1229fd7492392c)), closes [#393](https://github.com/bytesparadise/libasciidoc/issues/393)
* **parser:** report error on unbalanced/unclosed tag ([#409](https://github.com/bytesparadise/libasciidoc/issues/409)) ([8128d97](https://github.com/bytesparadise/libasciidoc/commit/8128d9777dcd486d09a0d0ee5530938e01333498)), closes [#392](https://github.com/bytesparadise/libasciidoc/issues/392)
* **parser:** support attribute in path of file to include ([#355](https://github.com/bytesparadise/libasciidoc/issues/355)) ([18b54a2](https://github.com/bytesparadise/libasciidoc/commit/18b54a2d980b4c1122069f7f70ef63d4abe2ca40)), closes [#317](https://github.com/bytesparadise/libasciidoc/issues/317)
* **parser:** support concealed index terms ([#475](https://github.com/bytesparadise/libasciidoc/issues/475)) ([d295e1b](https://github.com/bytesparadise/libasciidoc/commit/d295e1be82ced62073bc5879dafc9e50cea61202)), closes [#473](https://github.com/bytesparadise/libasciidoc/issues/473)
* **parser:** support document attributes in links ([#441](https://github.com/bytesparadise/libasciidoc/issues/441)) ([fa27e8e](https://github.com/bytesparadise/libasciidoc/commit/fa27e8e6dc51d5fc793750e9eb0346ad991f7bd3)), closes [#351](https://github.com/bytesparadise/libasciidoc/issues/351)
* **parser:** support file inclusion with absolute level offset ([#438](https://github.com/bytesparadise/libasciidoc/issues/438)) ([4db334f](https://github.com/bytesparadise/libasciidoc/commit/4db334f91b580a08866cca2103e6894188aecbb1)), closes [#314](https://github.com/bytesparadise/libasciidoc/issues/314)
* **parser:** support file inclusion with tag ranges ([#387](https://github.com/bytesparadise/libasciidoc/issues/387)) ([f49fe6f](https://github.com/bytesparadise/libasciidoc/commit/f49fe6f08909402754f3cc991fc5d24fce20667a)), closes [#322](https://github.com/bytesparadise/libasciidoc/issues/322)
* **parser:** support nested relative level offset in file inclusions ([#437](https://github.com/bytesparadise/libasciidoc/issues/437)) ([2bb6f9d](https://github.com/bytesparadise/libasciidoc/commit/2bb6f9d2554e318b3ae4748427f08946f091dc92)), closes [#434](https://github.com/bytesparadise/libasciidoc/issues/434)
* **parser:** support wildcards in tag inclusions ([#423](https://github.com/bytesparadise/libasciidoc/issues/423)) ([8cff6b2](https://github.com/bytesparadise/libasciidoc/commit/8cff6b2927cdb36d3b65571a0b9723b812ae33d2)), closes [#396](https://github.com/bytesparadise/libasciidoc/issues/396)
* **parser/renderer:** add user macro feature ([#347](https://github.com/bytesparadise/libasciidoc/issues/347)) ([96b01cf](https://github.com/bytesparadise/libasciidoc/commit/96b01cfd7be1ab209556a911fc5160a6e54e6ced)), closes [#334](https://github.com/bytesparadise/libasciidoc/issues/334)
* **parser/renderer:** support adoc file inclusion in delimited blocks ([#320](https://github.com/bytesparadise/libasciidoc/issues/320)) ([0212ac6](https://github.com/bytesparadise/libasciidoc/commit/0212ac62e697116b0fc8804d07d561be68d4dabb)), closes [#310](https://github.com/bytesparadise/libasciidoc/issues/310)
* **parser/renderer:** support document attrs in image URL ([#449](https://github.com/bytesparadise/libasciidoc/issues/449)) ([41b223c](https://github.com/bytesparadise/libasciidoc/commit/41b223cf7d78ef93a0ad286c09e89610941d3db8)), closes [#350](https://github.com/bytesparadise/libasciidoc/issues/350)
* **parser/renderer:** support external cross references ([#468](https://github.com/bytesparadise/libasciidoc/issues/468)) ([80e7e72](https://github.com/bytesparadise/libasciidoc/commit/80e7e72e4b581dc1f1852bb6824502b147714131)), closes [#459](https://github.com/bytesparadise/libasciidoc/issues/459)
* **parser/renderer:** support file inclusion with line ranges ([#326](https://github.com/bytesparadise/libasciidoc/issues/326)) ([7b4a779](https://github.com/bytesparadise/libasciidoc/commit/7b4a779c61df81524fddb3f2eef7068976132763)), closes [#315](https://github.com/bytesparadise/libasciidoc/issues/315)
* **parser/renderer:** support file inclusions ([#316](https://github.com/bytesparadise/libasciidoc/issues/316)) ([8709c17](https://github.com/bytesparadise/libasciidoc/commit/8709c17a139426d183d88831c725ed907d73cb48)), closes [#307](https://github.com/bytesparadise/libasciidoc/issues/307)
* **parser/renderer:** support index terms ([#498](https://github.com/bytesparadise/libasciidoc/issues/498)) ([ecb3b59](https://github.com/bytesparadise/libasciidoc/commit/ecb3b598ee0260febf062ebb2cc1c4ab485269d5)), closes [#497](https://github.com/bytesparadise/libasciidoc/issues/497)
* **parser/renderer:** support recursive file inclusions ([#327](https://github.com/bytesparadise/libasciidoc/issues/327)) ([64d8910](https://github.com/bytesparadise/libasciidoc/commit/64d8910a7f6bc3d9a6e21b0a6ff8638f10f628f1)), closes [#311](https://github.com/bytesparadise/libasciidoc/issues/311)
* **parser/renderer:** support rich content in labeled list item terms ([#466](https://github.com/bytesparadise/libasciidoc/issues/466)) ([6b58ad2](https://github.com/bytesparadise/libasciidoc/commit/6b58ad2443c92dffeddab5184c430a50b0487006)), closes [#456](https://github.com/bytesparadise/libasciidoc/issues/456) [#460](https://github.com/bytesparadise/libasciidoc/issues/460)
* **renderer:** add role as CSS class in paragraphs ([#471](https://github.com/bytesparadise/libasciidoc/issues/471)) ([136ef4e](https://github.com/bytesparadise/libasciidoc/commit/136ef4ef0473d43f74b2680570c9b74fdb527046)), closes [#469](https://github.com/bytesparadise/libasciidoc/issues/469)
* **renderer:** return list of sections after rendering ([#485](https://github.com/bytesparadise/libasciidoc/issues/485)) ([55aec97](https://github.com/bytesparadise/libasciidoc/commit/55aec978325f72fa81afe3d4f53086ebddf4560d)), closes [#363](https://github.com/bytesparadise/libasciidoc/issues/363)
* **renderer:** support file inclusion of non asciidoc files ([#321](https://github.com/bytesparadise/libasciidoc/issues/321)) ([8779f54](https://github.com/bytesparadise/libasciidoc/commit/8779f54e4ed3d100defd0b143da8ac360a6a4a26)), closes [#312](https://github.com/bytesparadise/libasciidoc/issues/312)
* **renderer:** support pygments syntax highlight ([#489](https://github.com/bytesparadise/libasciidoc/issues/489)) ([cbd9c89](https://github.com/bytesparadise/libasciidoc/commit/cbd9c89af6bd3464a63dec805e285c9a794f5f27)), closes [#488](https://github.com/bytesparadise/libasciidoc/issues/488)
# [0.2.0](https://github.com/bytesparadise/libasciidoc/compare/v0.1.0...v0.2.0) (2019-02-24)
### Bug Fixes
* **renderer:** avoid double encoding of document attributes ([#296](https://github.com/bytesparadise/libasciidoc/issues/296)) ([00c0132](https://github.com/bytesparadise/libasciidoc/commit/00c0132)), closes [#43](https://github.com/bytesparadise/libasciidoc/issues/43) [#43](https://github.com/bytesparadise/libasciidoc/issues/43) [#295](https://github.com/bytesparadise/libasciidoc/issues/295)
* **renderer:** do not always render preamble withing wrapper ([#299](https://github.com/bytesparadise/libasciidoc/issues/299)) ([76ea3f7](https://github.com/bytesparadise/libasciidoc/commit/76ea3f7)), closes [#298](https://github.com/bytesparadise/libasciidoc/issues/298)
* **renderer:** fix panic in ToC when doc has no section ([#285](https://github.com/bytesparadise/libasciidoc/issues/285)) ([f7ee178](https://github.com/bytesparadise/libasciidoc/commit/f7ee178)), closes [#284](https://github.com/bytesparadise/libasciidoc/issues/284)
* **renderer:** wrap continuing element in `<div>` ([#281](https://github.com/bytesparadise/libasciidoc/issues/281)) ([f94e69a](https://github.com/bytesparadise/libasciidoc/commit/f94e69a)), closes [#270](https://github.com/bytesparadise/libasciidoc/issues/270)
* **types:** attach child elements to correct parent in ordered list ([#294](https://github.com/bytesparadise/libasciidoc/issues/294)) ([8d72ae0](https://github.com/bytesparadise/libasciidoc/commit/8d72ae0)), closes [#293](https://github.com/bytesparadise/libasciidoc/issues/293)
### Features
* **parser:** support spaces and tabs ahead of single line comment ([#289](https://github.com/bytesparadise/libasciidoc/issues/289)) ([061eb82](https://github.com/bytesparadise/libasciidoc/commit/061eb82)), closes [#288](https://github.com/bytesparadise/libasciidoc/issues/288)
* **parser/renderer:** attach list item to ancestor ([#291](https://github.com/bytesparadise/libasciidoc/issues/291)) ([6d9eb0e](https://github.com/bytesparadise/libasciidoc/commit/6d9eb0e)), closes [#264](https://github.com/bytesparadise/libasciidoc/issues/264)
* **parser/renderer:** support checklists ([#262](https://github.com/bytesparadise/libasciidoc/issues/262)) ([34598af](https://github.com/bytesparadise/libasciidoc/commit/34598af)), closes [#244](https://github.com/bytesparadise/libasciidoc/issues/244)
* **parser/renderer:** support element ID prefix ([#302](https://github.com/bytesparadise/libasciidoc/issues/302)) ([9780fef](https://github.com/bytesparadise/libasciidoc/commit/9780fef)), closes [#300](https://github.com/bytesparadise/libasciidoc/issues/300)
* **parser/renderer:** support list separation ([#274](https://github.com/bytesparadise/libasciidoc/issues/274)) ([d2945ab](https://github.com/bytesparadise/libasciidoc/commit/d2945ab)), closes [#263](https://github.com/bytesparadise/libasciidoc/issues/263)
* **renderer:** support 'start' attribute when rendering an ordered list ([#279](https://github.com/bytesparadise/libasciidoc/issues/279)) ([e7f692d](https://github.com/bytesparadise/libasciidoc/commit/e7f692d)), closes [#271](https://github.com/bytesparadise/libasciidoc/issues/271)
* **renderer:** support "Q and A" labeled lists ([#280](https://github.com/bytesparadise/libasciidoc/issues/280)) ([6be62cd](https://github.com/bytesparadise/libasciidoc/commit/6be62cd)), closes [#271](https://github.com/bytesparadise/libasciidoc/issues/271)
* **renderer:** support dropping of principal text in ordered list item ([#283](https://github.com/bytesparadise/libasciidoc/issues/283)) ([2387309](https://github.com/bytesparadise/libasciidoc/commit/2387309)), closes [#266](https://github.com/bytesparadise/libasciidoc/issues/266) [#265](https://github.com/bytesparadise/libasciidoc/issues/265)
* **renderer:** support predefined attributes ([#282](https://github.com/bytesparadise/libasciidoc/issues/282)) ([99581b5](https://github.com/bytesparadise/libasciidoc/commit/99581b5)), closes [#266](https://github.com/bytesparadise/libasciidoc/issues/266)
* **renderer:** support title on labeled lists ([#278](https://github.com/bytesparadise/libasciidoc/issues/278)) ([a50c637](https://github.com/bytesparadise/libasciidoc/commit/a50c637)), closes [#267](https://github.com/bytesparadise/libasciidoc/issues/267)
# [0.1.0](https://github.com/bytesparadise/libasciidoc/compare/39964e8...v0.1.0) (2019-01-02)
### Bug Fixes
* **build:** remove support for golang1.8 on travis-ci and appveyor ([#241](https://github.com/bytesparadise/libasciidoc/issues/241)) ([9afc556](https://github.com/bytesparadise/libasciidoc/commit/9afc556)), closes [#240](https://github.com/bytesparadise/libasciidoc/issues/240)
* **build:** update codecov config ([#135](https://github.com/bytesparadise/libasciidoc/issues/135)) ([d207759](https://github.com/bytesparadise/libasciidoc/commit/d207759)), closes [#134](https://github.com/bytesparadise/libasciidoc/issues/134)
* **build:** use optimized grammar when building/installing ([#159](https://github.com/bytesparadise/libasciidoc/issues/159)) ([8c08ab8](https://github.com/bytesparadise/libasciidoc/commit/8c08ab8)), closes [#158](https://github.com/bytesparadise/libasciidoc/issues/158)
* **cli:** command hangs when no arg is provided ([#239](https://github.com/bytesparadise/libasciidoc/issues/239)) ([af34129](https://github.com/bytesparadise/libasciidoc/commit/af34129)), closes [#236](https://github.com/bytesparadise/libasciidoc/issues/236)
* **doc:** fix broken links in README.adoc ([#92](https://github.com/bytesparadise/libasciidoc/issues/92)) ([cdf4e1c](https://github.com/bytesparadise/libasciidoc/commit/cdf4e1c)), closes [#91](https://github.com/bytesparadise/libasciidoc/issues/91)
* **parser:** avoid too much parsing for sections ([#129](https://github.com/bytesparadise/libasciidoc/issues/129)) ([6cc6f51](https://github.com/bytesparadise/libasciidoc/commit/6cc6f51)), closes [#121](https://github.com/bytesparadise/libasciidoc/issues/121)
* **parser:** broken literal block parsing ([#200](https://github.com/bytesparadise/libasciidoc/issues/200)) ([7012d2b](https://github.com/bytesparadise/libasciidoc/commit/7012d2b)), closes [#197](https://github.com/bytesparadise/libasciidoc/issues/197)
* **parser:** fix admonition paragraph parsing ([#90](https://github.com/bytesparadise/libasciidoc/issues/90)) ([b1adfb3](https://github.com/bytesparadise/libasciidoc/commit/b1adfb3)), closes [#88](https://github.com/bytesparadise/libasciidoc/issues/88)
* **parser:** fix parser failure on lists ([#233](https://github.com/bytesparadise/libasciidoc/issues/233)) ([7713b7a](https://github.com/bytesparadise/libasciidoc/commit/7713b7a)), closes [#230](https://github.com/bytesparadise/libasciidoc/issues/230) [#234](https://github.com/bytesparadise/libasciidoc/issues/234) [#235](https://github.com/bytesparadise/libasciidoc/issues/235)
* **parser:** fix parsing issue when processing 'article.adoc' ([#164](https://github.com/bytesparadise/libasciidoc/issues/164)) ([29a8985](https://github.com/bytesparadise/libasciidoc/commit/29a8985)), closes [#153](https://github.com/bytesparadise/libasciidoc/issues/153)
* **parser:** incorrect default image alt ([#201](https://github.com/bytesparadise/libasciidoc/issues/201)) ([d60a28c](https://github.com/bytesparadise/libasciidoc/commit/d60a28c)), closes [#198](https://github.com/bytesparadise/libasciidoc/issues/198)
* **parser:** increase bench timeout on Travis-ci ([#163](https://github.com/bytesparadise/libasciidoc/issues/163)) ([a3aca2e](https://github.com/bytesparadise/libasciidoc/commit/a3aca2e)), closes [#162](https://github.com/bytesparadise/libasciidoc/issues/162)
* **parser:** misapplied ordered list on paragraph ([#208](https://github.com/bytesparadise/libasciidoc/issues/208)) ([44ee222](https://github.com/bytesparadise/libasciidoc/commit/44ee222)), closes [#207](https://github.com/bytesparadise/libasciidoc/issues/207)
* **parser:** missing sublists ([#206](https://github.com/bytesparadise/libasciidoc/issues/206)) ([39c0af8](https://github.com/bytesparadise/libasciidoc/commit/39c0af8)), closes [#203](https://github.com/bytesparadise/libasciidoc/issues/203)
* **parser:** parse blank lines ([#13](https://github.com/bytesparadise/libasciidoc/issues/13)) ([9c84e23](https://github.com/bytesparadise/libasciidoc/commit/9c84e23))
* **parser:** support for quoted text in list items ([#167](https://github.com/bytesparadise/libasciidoc/issues/167)) ([d4fe363](https://github.com/bytesparadise/libasciidoc/commit/d4fe363)), closes [#161](https://github.com/bytesparadise/libasciidoc/issues/161)
* **parser:** Support line starting with `.` in delimited blocks ([#120](https://github.com/bytesparadise/libasciidoc/issues/120)) ([efbdd39](https://github.com/bytesparadise/libasciidoc/commit/efbdd39)), closes [#116](https://github.com/bytesparadise/libasciidoc/issues/116)
* **parser:** support multiple sections with level 0 ([#124](https://github.com/bytesparadise/libasciidoc/issues/124)) ([bf43f4c](https://github.com/bytesparadise/libasciidoc/commit/bf43f4c))
* **parser:** support unclosed delimited blocks ([#101](https://github.com/bytesparadise/libasciidoc/issues/101)) ([#104](https://github.com/bytesparadise/libasciidoc/issues/104)) ([3029837](https://github.com/bytesparadise/libasciidoc/commit/3029837))
* **parser:** support unordered lists on multiple levels ([#145](https://github.com/bytesparadise/libasciidoc/issues/145)) ([4554793](https://github.com/bytesparadise/libasciidoc/commit/4554793)), closes [#137](https://github.com/bytesparadise/libasciidoc/issues/137)
* **parser:** unrecognized footnote in paragraph ([#211](https://github.com/bytesparadise/libasciidoc/issues/211)) ([d659997](https://github.com/bytesparadise/libasciidoc/commit/d659997)), closes [#210](https://github.com/bytesparadise/libasciidoc/issues/210)
* **parser/renderer:** avoid extra spaces in literal blocks ([#193](https://github.com/bytesparadise/libasciidoc/issues/193)) ([e8a26b0](https://github.com/bytesparadise/libasciidoc/commit/e8a26b0)), closes [#188](https://github.com/bytesparadise/libasciidoc/issues/188)
* **parser/renderer:** unique section id ([#209](https://github.com/bytesparadise/libasciidoc/issues/209)) ([0adc6a1](https://github.com/bytesparadise/libasciidoc/commit/0adc6a1)), closes [#184](https://github.com/bytesparadise/libasciidoc/issues/184)
* **project:** remove `.test` files ([#132](https://github.com/bytesparadise/libasciidoc/issues/132)) ([644b4eb](https://github.com/bytesparadise/libasciidoc/commit/644b4eb)), closes [#130](https://github.com/bytesparadise/libasciidoc/issues/130)
* **renderer:** element IDs and document header ([#156](https://github.com/bytesparadise/libasciidoc/issues/156)) ([c3e3fbd](https://github.com/bytesparadise/libasciidoc/commit/c3e3fbd)), closes [#155](https://github.com/bytesparadise/libasciidoc/issues/155)
* **renderer:** fix table numbering when title is included ([#166](https://github.com/bytesparadise/libasciidoc/issues/166)) ([7f3a6e0](https://github.com/bytesparadise/libasciidoc/commit/7f3a6e0))
* **renderer:** infinite recursive call ([#80](https://github.com/bytesparadise/libasciidoc/issues/80)) ([daed6fc](https://github.com/bytesparadise/libasciidoc/commit/daed6fc))
* **renderer:** missing '</head>' tag ([#202](https://github.com/bytesparadise/libasciidoc/issues/202)) ([3e3ca78](https://github.com/bytesparadise/libasciidoc/commit/3e3ca78)), closes [#199](https://github.com/bytesparadise/libasciidoc/issues/199)
* **types:** tidy up initials func ([#81](https://github.com/bytesparadise/libasciidoc/issues/81)) ([9448be5](https://github.com/bytesparadise/libasciidoc/commit/9448be5))
### Features
* **build:** add makefile goal to verify the generated parser ([#126](https://github.com/bytesparadise/libasciidoc/issues/126)) ([15b4680](https://github.com/bytesparadise/libasciidoc/commit/15b4680))
* **build:** add windows and osx builds to Travis ([#224](https://github.com/bytesparadise/libasciidoc/issues/224)) ([94a8009](https://github.com/bytesparadise/libasciidoc/commit/94a8009)), closes [#223](https://github.com/bytesparadise/libasciidoc/issues/223) [#225](https://github.com/bytesparadise/libasciidoc/issues/225)
* **build:** use golangci-lint for all linting ([b07c3a7](https://github.com/bytesparadise/libasciidoc/commit/b07c3a7)), closes [#61](https://github.com/bytesparadise/libasciidoc/issues/61)
* **build/cmd:** include commit/tag and time in 'version' cmd ([#114](https://github.com/bytesparadise/libasciidoc/issues/114)) ([96409c3](https://github.com/bytesparadise/libasciidoc/commit/96409c3)), closes [#113](https://github.com/bytesparadise/libasciidoc/issues/113)
* **cli:** add arg to specify the output file ([#122](https://github.com/bytesparadise/libasciidoc/issues/122)) ([d402c2d](https://github.com/bytesparadise/libasciidoc/commit/d402c2d)), closes [#119](https://github.com/bytesparadise/libasciidoc/issues/119)
* **cmd:** add command line interface ([#78](https://github.com/bytesparadise/libasciidoc/issues/78)) ([2f6ae3b](https://github.com/bytesparadise/libasciidoc/commit/2f6ae3b)), closes [#60](https://github.com/bytesparadise/libasciidoc/issues/60)
* **cmd:** add flag to suppress header/footer ([#95](https://github.com/bytesparadise/libasciidoc/issues/95)) ([4a31775](https://github.com/bytesparadise/libasciidoc/commit/4a31775))
* **cmd:** add support to specify log level ([#85](https://github.com/bytesparadise/libasciidoc/issues/85)) ([47e6e3c](https://github.com/bytesparadise/libasciidoc/commit/47e6e3c))
* **cmd:** allow reading input from stdin ([#86](https://github.com/bytesparadise/libasciidoc/issues/86)) ([add3287](https://github.com/bytesparadise/libasciidoc/commit/add3287))
* **make:** add goal to build executable ([#94](https://github.com/bytesparadise/libasciidoc/issues/94)), show help by default ([#99](https://github.com/bytesparadise/libasciidoc/issues/99)) ([#103](https://github.com/bytesparadise/libasciidoc/issues/103)) ([3ea969a](https://github.com/bytesparadise/libasciidoc/commit/3ea969a))
* **parser:** add support for meta-elements: ID, link and title ([c08a7f3](https://github.com/bytesparadise/libasciidoc/commit/c08a7f3))
* **parser:** allow id and title on paragraphs ([#16](https://github.com/bytesparadise/libasciidoc/issues/16)) ([c499d94](https://github.com/bytesparadise/libasciidoc/commit/c499d94))
* **parser:** support double punctuation in quoted text ([#39](https://github.com/bytesparadise/libasciidoc/issues/39)) ([f7f82e9](https://github.com/bytesparadise/libasciidoc/commit/f7f82e9))
* **parser:** support front-matter in YAML format ([#28](https://github.com/bytesparadise/libasciidoc/issues/28)) ([b69fe01](https://github.com/bytesparadise/libasciidoc/commit/b69fe01))
* **parser:** support italic and monospace quotes, as well as nested quotes ([bd58fd1](https://github.com/bytesparadise/libasciidoc/commit/bd58fd1))
* **parser:** support relative links ([#65](https://github.com/bytesparadise/libasciidoc/issues/65)) ([5e47b65](https://github.com/bytesparadise/libasciidoc/commit/5e47b65)), closes [#56](https://github.com/bytesparadise/libasciidoc/issues/56)
* **parser:** support substitution prevention ([#40](https://github.com/bytesparadise/libasciidoc/issues/40)) ([8e59c45](https://github.com/bytesparadise/libasciidoc/commit/8e59c45))
* **parser:** use the `memoize` option in the parser to improve perfs ([#123](https://github.com/bytesparadise/libasciidoc/issues/123)) ([491dbdd](https://github.com/bytesparadise/libasciidoc/commit/491dbdd)), closes [#117](https://github.com/bytesparadise/libasciidoc/issues/117)
* **parser/renderer:** image blocks with metadata and paragraphs with multiple lines ([8ff1125](https://github.com/bytesparadise/libasciidoc/commit/8ff1125))
* **parser/renderer:** list item continuation ([#53](https://github.com/bytesparadise/libasciidoc/issues/53)) ([613a112](https://github.com/bytesparadise/libasciidoc/commit/613a112))
* **parser/renderer:** parse and render inline images ([#17](https://github.com/bytesparadise/libasciidoc/issues/17)) ([65f8ac7](https://github.com/bytesparadise/libasciidoc/commit/65f8ac7))
* **parser/renderer:** parse and render unordered list items ([#12](https://github.com/bytesparadise/libasciidoc/issues/12)) ([868e95a](https://github.com/bytesparadise/libasciidoc/commit/868e95a))
* **parser/renderer:** support admonitions ([#70](https://github.com/bytesparadise/libasciidoc/issues/70)) ([6c221f1](https://github.com/bytesparadise/libasciidoc/commit/6c221f1)), closes [#67](https://github.com/bytesparadise/libasciidoc/issues/67)
* **parser/renderer:** support block and paragraph quotes ([#157](https://github.com/bytesparadise/libasciidoc/issues/157)) ([9f1e394](https://github.com/bytesparadise/libasciidoc/commit/9f1e394)), closes [#141](https://github.com/bytesparadise/libasciidoc/issues/141)
* **parser/renderer:** support cross-references with Element ID ([#47](https://github.com/bytesparadise/libasciidoc/issues/47)) ([65f9c9c](https://github.com/bytesparadise/libasciidoc/commit/65f9c9c))
* **parser/renderer:** support example blocks ([#72](https://github.com/bytesparadise/libasciidoc/issues/72)) ([230febb](https://github.com/bytesparadise/libasciidoc/commit/230febb)), closes [#71](https://github.com/bytesparadise/libasciidoc/issues/71)
* **parser/renderer:** support explicit line breaks ([#195](https://github.com/bytesparadise/libasciidoc/issues/195)) ([f5f87cc](https://github.com/bytesparadise/libasciidoc/commit/f5f87cc)), closes [#189](https://github.com/bytesparadise/libasciidoc/issues/189)
* **parser/renderer:** support for delimited source blocks ([4cb7c14](https://github.com/bytesparadise/libasciidoc/commit/4cb7c14))
* **parser/renderer:** support for document attributes ([#22](https://github.com/bytesparadise/libasciidoc/issues/22)) ([362892a](https://github.com/bytesparadise/libasciidoc/commit/362892a))
* **parser/renderer:** support for document attributes reset and substitutions ([#23](https://github.com/bytesparadise/libasciidoc/issues/23)) ([f24fbd5](https://github.com/bytesparadise/libasciidoc/commit/f24fbd5))
* **parser/renderer:** Support for Document Author and Revision, and Preamble ([#36](https://github.com/bytesparadise/libasciidoc/issues/36)) ([99b1fd9](https://github.com/bytesparadise/libasciidoc/commit/99b1fd9))
* **parser/renderer:** support for labeled list ([#51](https://github.com/bytesparadise/libasciidoc/issues/51)) ([5e758c6](https://github.com/bytesparadise/libasciidoc/commit/5e758c6))
* **parser/renderer:** support for literal blocks ([#29](https://github.com/bytesparadise/libasciidoc/issues/29)) ([51f4897](https://github.com/bytesparadise/libasciidoc/commit/51f4897))
* **parser/renderer:** support inline footnotes ([#183](https://github.com/bytesparadise/libasciidoc/issues/183)) ([28e43c7](https://github.com/bytesparadise/libasciidoc/commit/28e43c7)), closes [#138](https://github.com/bytesparadise/libasciidoc/issues/138)
* **parser/renderer:** support links to section title ([#58](https://github.com/bytesparadise/libasciidoc/issues/58)) ([1900b10](https://github.com/bytesparadise/libasciidoc/commit/1900b10))
* **parser/renderer:** support listing blocks ([#42](https://github.com/bytesparadise/libasciidoc/issues/42)) ([2fb5fe6](https://github.com/bytesparadise/libasciidoc/commit/2fb5fe6))
* **parser/renderer:** support literal block attributes ([#186](https://github.com/bytesparadise/libasciidoc/issues/186)) ([4ef1381](https://github.com/bytesparadise/libasciidoc/commit/4ef1381)), closes [#185](https://github.com/bytesparadise/libasciidoc/issues/185)
* **parser/renderer:** support optional label in cross-references ([#174](https://github.com/bytesparadise/libasciidoc/issues/174)) ([ec85fd2](https://github.com/bytesparadise/libasciidoc/commit/ec85fd2)), closes [#143](https://github.com/bytesparadise/libasciidoc/issues/143)
* **parser/renderer:** support ordered lists ([#77](https://github.com/bytesparadise/libasciidoc/issues/77)) ([416e9ea](https://github.com/bytesparadise/libasciidoc/commit/416e9ea)), closes [#64](https://github.com/bytesparadise/libasciidoc/issues/64)
* **parser/renderer:** support passthrough ([#41](https://github.com/bytesparadise/libasciidoc/issues/41)) ([aa501da](https://github.com/bytesparadise/libasciidoc/commit/aa501da))
* **parser/renderer:** support role attributes, refactor attributes and image type ([#171](https://github.com/bytesparadise/libasciidoc/issues/171)) ([d2b6e95](https://github.com/bytesparadise/libasciidoc/commit/d2b6e95)), closes [#151](https://github.com/bytesparadise/libasciidoc/issues/151)
* **parser/renderer:** support sidebar blocks ([#182](https://github.com/bytesparadise/libasciidoc/issues/182)) ([e34547c](https://github.com/bytesparadise/libasciidoc/commit/e34547c)), closes [#139](https://github.com/bytesparadise/libasciidoc/issues/139)
* **parser/renderer:** support single line and block comments ([#146](https://github.com/bytesparadise/libasciidoc/issues/146)) ([c6549d3](https://github.com/bytesparadise/libasciidoc/commit/c6549d3)), closes [#144](https://github.com/bytesparadise/libasciidoc/issues/144)
* **parser/renderer:** support source code blocks with language ([#255](https://github.com/bytesparadise/libasciidoc/issues/255)) ([293761e](https://github.com/bytesparadise/libasciidoc/commit/293761e)), closes [#229](https://github.com/bytesparadise/libasciidoc/issues/229)
* **parser/renderer:** support subscript and superscript quotes ([#237](https://github.com/bytesparadise/libasciidoc/issues/237)) ([97e8929](https://github.com/bytesparadise/libasciidoc/commit/97e8929)), closes [#228](https://github.com/bytesparadise/libasciidoc/issues/228)
* **parser/renderer:** support tables (basic) ([#165](https://github.com/bytesparadise/libasciidoc/issues/165)) ([9956517](https://github.com/bytesparadise/libasciidoc/commit/9956517)), closes [#57](https://github.com/bytesparadise/libasciidoc/issues/57)
* **parser/renderer:** support ToC placement in preamble ([#45](https://github.com/bytesparadise/libasciidoc/issues/45)) ([b1a6a74](https://github.com/bytesparadise/libasciidoc/commit/b1a6a74))
* **parser/renderer:** support verses ([#149](https://github.com/bytesparadise/libasciidoc/issues/149)) ([ec67024](https://github.com/bytesparadise/libasciidoc/commit/ec67024)), closes [#140](https://github.com/bytesparadise/libasciidoc/issues/140)
* **parser/renderer:** verifies that `article.adoc` renders as expected ([#227](https://github.com/bytesparadise/libasciidoc/issues/227)) ([399d127](https://github.com/bytesparadise/libasciidoc/commit/399d127)), closes [#215](https://github.com/bytesparadise/libasciidoc/issues/215)
* **project:** first draft of the asciidoc grammar and parser ([39964e8](https://github.com/bytesparadise/libasciidoc/commit/39964e8))
* **renderer:** convert ellipsis ([#178](https://github.com/bytesparadise/libasciidoc/issues/178)) ([4733cfc](https://github.com/bytesparadise/libasciidoc/commit/4733cfc)), closes [#8230](https://github.com/bytesparadise/libasciidoc/issues/8230) [#8203](https://github.com/bytesparadise/libasciidoc/issues/8203) [#175](https://github.com/bytesparadise/libasciidoc/issues/175)
* **renderer:** render external links ([#48](https://github.com/bytesparadise/libasciidoc/issues/48)) ([1154a87](https://github.com/bytesparadise/libasciidoc/commit/1154a87))
* **renderer:** render external links without description ([#50](https://github.com/bytesparadise/libasciidoc/issues/50)) ([8457fa5](https://github.com/bytesparadise/libasciidoc/commit/8457fa5))
* **renderer:** render full document ([#18](https://github.com/bytesparadise/libasciidoc/issues/18)) ([bcdccfc](https://github.com/bytesparadise/libasciidoc/commit/bcdccfc))
* **renderer:** render headings with support for default and custom ID ([#10](https://github.com/bytesparadise/libasciidoc/issues/10)) ([76a05d4](https://github.com/bytesparadise/libasciidoc/commit/76a05d4))
* **renderer:** render section preamble ([#15](https://github.com/bytesparadise/libasciidoc/issues/15)) ([a897a73](https://github.com/bytesparadise/libasciidoc/commit/a897a73))
* **renderer:** render table of content ([#44](https://github.com/bytesparadise/libasciidoc/issues/44)) ([847f6a2](https://github.com/bytesparadise/libasciidoc/commit/847f6a2))
* **renderer:** render whole document ([baee941](https://github.com/bytesparadise/libasciidoc/commit/baee941))
* **renderer:** support 'imagesdir' attribute ([#170](https://github.com/bytesparadise/libasciidoc/issues/170)) ([852cca4](https://github.com/bytesparadise/libasciidoc/commit/852cca4)), closes [#160](https://github.com/bytesparadise/libasciidoc/issues/160)
* **renderer:** support icons in admonition blocks ([#218](https://github.com/bytesparadise/libasciidoc/issues/218)) ([aeef974](https://github.com/bytesparadise/libasciidoc/commit/aeef974)), closes [#214](https://github.com/bytesparadise/libasciidoc/issues/214)
* **renderer:** support ID and title on delimited blocks ([#213](https://github.com/bytesparadise/libasciidoc/issues/213)) ([8993045](https://github.com/bytesparadise/libasciidoc/commit/8993045)), closes [#212](https://github.com/bytesparadise/libasciidoc/issues/212)
* **renderer:** support inline attribute substitutions ([#179](https://github.com/bytesparadise/libasciidoc/issues/179)) ([d2f398e](https://github.com/bytesparadise/libasciidoc/commit/d2f398e)), closes [#142](https://github.com/bytesparadise/libasciidoc/issues/142)
* **rendering:** first draft of HTML5 rendering ([#3](https://github.com/bytesparadise/libasciidoc/issues/3)) ([b53b3a2](https://github.com/bytesparadise/libasciidoc/commit/b53b3a2))
* **rendering:** render italic and monospace quotes ([9ce2a48](https://github.com/bytesparadise/libasciidoc/commit/9ce2a48))
|
apache-2.0
|
anjalshireesh/gluster-ovirt-poc
|
frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/storage/IscsiImportStorageModel.java
|
1042
|
package org.ovirt.engine.ui.uicommonweb.models.storage;
import java.util.Collections;
import org.ovirt.engine.core.compat.*;
import org.ovirt.engine.ui.uicompat.*;
import org.ovirt.engine.core.common.businessentities.*;
import org.ovirt.engine.core.common.vdscommands.*;
import org.ovirt.engine.core.common.queries.*;
import org.ovirt.engine.core.common.action.*;
import org.ovirt.engine.ui.frontend.*;
import org.ovirt.engine.ui.uicommonweb.*;
import org.ovirt.engine.ui.uicommonweb.models.*;
import org.ovirt.engine.core.common.*;
import org.ovirt.engine.ui.uicompat.*;
import org.ovirt.engine.core.common.queries.*;
import org.ovirt.engine.core.common.businessentities.*;
import org.ovirt.engine.ui.uicommonweb.*;
import org.ovirt.engine.ui.uicommonweb.models.*;
@SuppressWarnings("unused")
public class IscsiImportStorageModel extends ImportSanStorageModel
{
@Override
public StorageType getType()
{
return StorageType.ISCSI;
}
@Override
protected String getListName() {
return "IscsiImportStorageModel";
}
}
|
apache-2.0
|
dhtech/graphite-web
|
webapp/graphite/render/functions.py
|
101346
|
#Copyright 2008 Orbitz WorldWide
#
#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.
from datetime import date, datetime, timedelta
from functools import partial
from itertools import izip, imap
import math
import re
import random
import time
from graphite.logger import log
from graphite.render.attime import parseTimeOffset
from graphite.events import models
#XXX format_units() should go somewhere else
from os import environ
if environ.get('READTHEDOCS'):
format_units = lambda *args, **kwargs: (0,'')
else:
from graphite.render.glyph import format_units
from graphite.render.datalib import TimeSeries
from graphite.util import timestamp
NAN = float('NaN')
INF = float('inf')
DAY = 86400
HOUR = 3600
MINUTE = 60
#Utility functions
def safeSum(values):
safeValues = [v for v in values if v is not None]
if safeValues:
return sum(safeValues)
def safeDiff(values):
safeValues = [v for v in values if v is not None]
if safeValues:
values = map(lambda x: x*-1, safeValues[1:])
values.insert(0, safeValues[0])
return sum(values)
def safeLen(values):
return len([v for v in values if v is not None])
def safeDiv(a, b):
if a is None: return None
if b in (0,None): return None
return float(a) / float(b)
def safeMul(*factors):
if None in factors:
return None
factors = [float(x) for x in factors]
product = reduce(lambda x,y: x*y, factors)
return product
def safeSubtract(a,b):
if a is None or b is None: return None
return float(a) - float(b)
def safeAvg(a):
return safeDiv(safeSum(a),safeLen(a))
def safeStdDev(a):
sm = safeSum(a)
ln = safeLen(a)
avg = safeDiv(sm,ln)
sum = 0
safeValues = [v for v in a if v is not None]
for val in safeValues:
sum = sum + (val - avg) * (val - avg)
return math.sqrt(sum/ln)
def safeLast(values):
for v in reversed(values):
if v is not None: return v
def safeMin(values):
safeValues = [v for v in values if v is not None]
if safeValues:
return min(safeValues)
def safeMax(values):
safeValues = [v for v in values if v is not None]
if safeValues:
return max(safeValues)
def safeMap(function, values):
safeValues = [v for v in values if v is not None]
if safeValues:
return [function(x) for x in values]
def safeAbs(value):
if value is None: return None
return abs(value)
# Greatest common divisor
def gcd(a, b):
if b == 0:
return a
return gcd(b, a%b)
# Least common multiple
def lcm(a, b):
if a == b: return a
if a < b: (a, b) = (b, a) #ensure a > b
return a / gcd(a,b) * b
def normalize(seriesLists):
seriesList = reduce(lambda L1,L2: L1+L2,seriesLists)
step = reduce(lcm,[s.step for s in seriesList])
for s in seriesList:
s.consolidate( step / s.step )
start = min([s.start for s in seriesList])
end = max([s.end for s in seriesList])
end -= (end - start) % step
return (seriesList,start,end,step)
def formatPathExpressions(seriesList):
# remove duplicates
pathExpressions = []
[pathExpressions.append(s.pathExpression) for s in seriesList if not pathExpressions.count(s.pathExpression)]
return ','.join(pathExpressions)
# Series Functions
#NOTE: Some of the functions below use izip, which may be problematic.
#izip stops when it hits the end of the shortest series
#in practice this *shouldn't* matter because all series will cover
#the same interval, despite having possibly different steps...
def sumSeries(requestContext, *seriesLists):
"""
Short form: sum()
This will add metrics together and return the sum at each datapoint. (See
integral for a sum over time)
Example:
.. code-block:: none
&target=sum(company.server.application*.requestsHandled)
This would show the sum of all requests handled per minute (provided
requestsHandled are collected once a minute). If metrics with different
retention rates are combined, the coarsest metric is graphed, and the sum
of the other metrics is averaged for the metrics with finer retention rates.
"""
try:
(seriesList,start,end,step) = normalize(seriesLists)
except:
return []
name = "sumSeries(%s)" % formatPathExpressions(seriesList)
values = ( safeSum(row) for row in izip(*seriesList) )
series = TimeSeries(name,start,end,step,values)
series.pathExpression = name
return [series]
def sumSeriesWithWildcards(requestContext, seriesList, *position): #XXX
"""
Call sumSeries after inserting wildcards at the given position(s).
Example:
.. code-block:: none
&target=sumSeriesWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, 1)
This would be the equivalent of
``target=sumSeries(host.*.cpu-user.value)&target=sumSeries(host.*.cpu-system.value)``
"""
if isinstance(position, int):
positions = [position]
else:
positions = position
newSeries = {}
newNames = list()
for series in seriesList:
newname = '.'.join(map(lambda x: x[1], filter(lambda i: i[0] not in positions, enumerate(series.name.split('.')))))
if newname in newSeries.keys():
newSeries[newname] = sumSeries(requestContext, (series, newSeries[newname]))[0]
else:
newSeries[newname] = series
newNames.append(newname)
newSeries[newname].name = newname
return [newSeries[name] for name in newNames]
def averageSeriesWithWildcards(requestContext, seriesList, *position): #XXX
"""
Call averageSeries after inserting wildcards at the given position(s).
Example:
.. code-block:: none
&target=averageSeriesWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, 1)
This would be the equivalent of
``target=averageSeries(host.*.cpu-user.value)&target=averageSeries(host.*.cpu-system.value)``
"""
if isinstance(position, int):
positions = [position]
else:
positions = position
result = []
matchedList = {}
for series in seriesList:
newname = '.'.join(map(lambda x: x[1], filter(lambda i: i[0] not in positions, enumerate(series.name.split('.')))))
if newname not in matchedList:
matchedList[newname] = []
matchedList[newname].append(series)
for name in matchedList.keys():
result.append( averageSeries(requestContext, (matchedList[name]))[0] )
result[-1].name = name
return result
def diffSeries(requestContext, *seriesLists):
"""
Can take two or more metrics, or a single metric and a constant.
Subtracts parameters 2 through n from parameter 1.
Example:
.. code-block:: none
&target=diffSeries(service.connections.total,service.connections.failed)
&target=diffSeries(service.connections.total,5)
"""
(seriesList,start,end,step) = normalize(seriesLists)
name = "diffSeries(%s)" % formatPathExpressions(seriesList)
values = ( safeDiff(row) for row in izip(*seriesList) )
series = TimeSeries(name,start,end,step,values)
series.pathExpression = name
return [series]
def averageSeries(requestContext, *seriesLists):
"""
Short Alias: avg()
Takes one metric or a wildcard seriesList.
Draws the average value of all metrics passed at each time.
Example:
.. code-block:: none
&target=averageSeries(company.server.*.threads.busy)
"""
(seriesList,start,end,step) = normalize(seriesLists)
name = "averageSeries(%s)" % formatPathExpressions(seriesList)
values = ( safeDiv(safeSum(row),safeLen(row)) for row in izip(*seriesList) )
series = TimeSeries(name,start,end,step,values)
series.pathExpression = name
return [series]
def stddevSeries(requestContext, *seriesLists):
"""
Takes one metric or a wildcard seriesList.
Draws the standard deviation of all metrics passed at each time.
Example:
.. code-block:: none
&target=stddevSeries(company.server.*.threads.busy)
"""
(seriesList,start,end,step) = normalize(seriesLists)
name = "stddevSeries(%s)" % formatPathExpressions(seriesList)
values = ( safeStdDev(row) for row in izip(*seriesList) )
series = TimeSeries(name,start,end,step,values)
series.pathExpression = name
return [series]
def minSeries(requestContext, *seriesLists):
"""
Takes one metric or a wildcard seriesList.
For each datapoint from each metric passed in, pick the minimum value and graph it.
Example:
.. code-block:: none
&target=minSeries(Server*.connections.total)
"""
(seriesList, start, end, step) = normalize(seriesLists)
name = "minSeries(%s)" % formatPathExpressions(seriesList)
values = ( safeMin(row) for row in izip(*seriesList) )
series = TimeSeries(name, start, end, step, values)
series.pathExpression = name
return [series]
def maxSeries(requestContext, *seriesLists):
"""
Takes one metric or a wildcard seriesList.
For each datapoint from each metric passed in, pick the maximum value and graph it.
Example:
.. code-block:: none
&target=maxSeries(Server*.connections.total)
"""
(seriesList, start, end, step) = normalize(seriesLists)
name = "maxSeries(%s)" % formatPathExpressions(seriesList)
values = ( safeMax(row) for row in izip(*seriesList) )
series = TimeSeries(name, start, end, step, values)
series.pathExpression = name
return [series]
def rangeOfSeries(requestContext, *seriesLists):
"""
Takes a wildcard seriesList.
Distills down a set of inputs into the range of the series
Example:
.. code-block:: none
&target=rangeOfSeries(Server*.connections.total)
"""
(seriesList,start,end,step) = normalize(seriesLists)
name = "rangeOfSeries(%s)" % formatPathExpressions(seriesList)
values = ( safeSubtract(max(row), min(row)) for row in izip(*seriesList) )
series = TimeSeries(name,start,end,step,values)
series.pathExpression = name
return [series]
def percentileOfSeries(requestContext, seriesList, n, interpolate=False):
"""
percentileOfSeries returns a single series which is composed of the n-percentile
values taken across a wildcard series at each point. Unless `interpolate` is
set to True, percentile values are actual values contained in one of the
supplied series.
"""
if n <= 0:
raise ValueError('The requested percent is required to be greater than 0')
name = 'percentilesOfSeries(%s,%g)' % (seriesList[0].pathExpression, n)
(start, end, step) = normalize([seriesList])[1:]
values = [ _getPercentile(row, n, interpolate) for row in izip(*seriesList) ]
resultSeries = TimeSeries(name, start, end, step, values)
resultSeries.pathExpression = name
return [resultSeries]
def keepLastValue(requestContext, seriesList, limit = INF):
"""
Takes one metric or a wildcard seriesList, and optionally a limit to the number of 'None' values to skip over.
Continues the line with the last received value when gaps ('None' values) appear in your data, rather than breaking your line.
Example:
.. code-block:: none
&target=keepLastValue(Server01.connections.handled)
&target=keepLastValue(Server01.connections.handled, 10)
"""
for series in seriesList:
series.name = "keepLastValue(%s)" % (series.name)
series.pathExpression = series.name
consecutiveNones = 0
for i,value in enumerate(series):
series[i] = value
# No 'keeping' can be done on the first value because we have no idea
# what came before it.
if i == 0:
continue
if value is None:
consecutiveNones += 1
else:
if 0 < consecutiveNones <= limit:
# If a non-None value is seen before the limit of Nones is hit,
# backfill all the missing datapoints with the last known value.
for index in xrange(i - consecutiveNones, i):
series[index] = series[i - consecutiveNones - 1]
consecutiveNones = 0
# If the series ends with some None values, try to backfill a bit to cover it.
if 0 < consecutiveNones < limit:
for index in xrange(len(series) - consecutiveNones, len(series)):
series[index] = series[len(series) - consecutiveNones - 1]
return seriesList
def asPercent(requestContext, seriesList, total=None):
"""
Calculates a percentage of the total of a wildcard series. If `total` is specified,
each series will be calculated as a percentage of that total. If `total` is not specified,
the sum of all points in the wildcard series will be used instead.
The `total` parameter may be a single series or a numeric value.
Example:
.. code-block:: none
&target=asPercent(Server01.connections.{failed,succeeded}, Server01.connections.attempted)
&target=asPercent(apache01.threads.busy,1500)
&target=asPercent(Server01.cpu.*.jiffies)
"""
normalize([seriesList])
if total is None:
totalValues = [ safeSum(row) for row in izip(*seriesList) ]
totalText = None # series.pathExpression
elif isinstance(total, list):
if len(total) != 1:
raise ValueError("asPercent second argument must reference exactly 1 series")
normalize([seriesList, total])
totalValues = total[0]
totalText = totalValues.name
else:
totalValues = [total] * len(seriesList[0])
totalText = str(total)
resultList = []
for series in seriesList:
resultValues = [ safeMul(safeDiv(val, totalVal), 100.0) for val,totalVal in izip(series,totalValues) ]
name = "asPercent(%s, %s)" % (series.name, totalText or series.pathExpression)
resultSeries = TimeSeries(name,series.start,series.end,series.step,resultValues)
resultSeries.pathExpression = name
resultList.append(resultSeries)
return resultList
def divideSeries(requestContext, dividendSeriesList, divisorSeriesList):
"""
Takes a dividend metric and a divisor metric and draws the division result.
A constant may *not* be passed. To divide by a constant, use the scale()
function (which is essentially a multiplication operation) and use the inverse
of the dividend. (Division by 8 = multiplication by 1/8 or 0.125)
Example:
.. code-block:: none
&target=divideSeries(Series.dividends,Series.divisors)
"""
if len(divisorSeriesList) != 1:
raise ValueError("divideSeries second argument must reference exactly 1 series")
divisorSeries = divisorSeriesList[0]
results = []
for dividendSeries in dividendSeriesList:
name = "divideSeries(%s,%s)" % (dividendSeries.name, divisorSeries.name)
bothSeries = (dividendSeries, divisorSeries)
step = reduce(lcm,[s.step for s in bothSeries])
for s in bothSeries:
s.consolidate( step / s.step )
start = min([s.start for s in bothSeries])
end = max([s.end for s in bothSeries])
end -= (end - start) % step
values = ( safeDiv(v1,v2) for v1,v2 in izip(*bothSeries) )
quotientSeries = TimeSeries(name, start, end, step, values)
quotientSeries.pathExpression = name
results.append(quotientSeries)
return results
def multiplySeries(requestContext, *seriesLists):
"""
Takes two or more series and multiplies their points. A constant may not be
used. To multiply by a constant, use the scale() function.
Example:
.. code-block:: none
&target=multiplySeries(Series.dividends,Series.divisors)
"""
(seriesList,start,end,step) = normalize(seriesLists)
if len(seriesList) == 1:
return seriesList
name = "multiplySeries(%s)" % ','.join([s.name for s in seriesList])
product = imap(lambda x: safeMul(*x), izip(*seriesList))
resultSeries = TimeSeries(name, start, end, step, product)
resultSeries.pathExpression = name
return [ resultSeries ]
def weightedAverage(requestContext, seriesListAvg, seriesListWeight, node):
"""
Takes a series of average values and a series of weights and
produces a weighted average for all values.
The corresponding values should share a node as defined
by the node parameter, 0-indexed.
Example:
.. code-block:: none
&target=weightedAverage(*.transactions.mean,*.transactions.count,0)
"""
sortedSeries={}
for seriesAvg, seriesWeight in izip(seriesListAvg , seriesListWeight):
key = seriesAvg.name.split(".")[node]
if key not in sortedSeries:
sortedSeries[key]={}
sortedSeries[key]['avg']=seriesAvg
key = seriesWeight.name.split(".")[node]
if key not in sortedSeries:
sortedSeries[key]={}
sortedSeries[key]['weight']=seriesWeight
productList = []
for key in sortedSeries.keys():
if 'weight' not in sortedSeries[key]:
continue
if 'avg' not in sortedSeries[key]:
continue
seriesWeight = sortedSeries[key]['weight']
seriesAvg = sortedSeries[key]['avg']
productValues = [ safeMul(val1, val2) for val1,val2 in izip(seriesAvg,seriesWeight) ]
name='product(%s,%s)' % (seriesWeight.name, seriesAvg.name)
productSeries = TimeSeries(name,seriesAvg.start,seriesAvg.end,seriesAvg.step,productValues)
productSeries.pathExpression=name
productList.append(productSeries)
sumProducts=sumSeries(requestContext, productList)[0]
sumWeights=sumSeries(requestContext, seriesListWeight)[0]
resultValues = [ safeDiv(val1, val2) for val1,val2 in izip(sumProducts,sumWeights) ]
name = "weightedAverage(%s, %s)" % (','.join(set(s.pathExpression for s in seriesListAvg)) ,','.join(set(s.pathExpression for s in seriesListWeight)))
resultSeries = TimeSeries(name,sumProducts.start,sumProducts.end,sumProducts.step,resultValues)
resultSeries.pathExpression = name
return resultSeries
def movingMedian(requestContext, seriesList, windowSize):
"""
Graphs the moving median of a metric (or metrics) over a fixed number of
past points, or a time interval.
Takes one metric or a wildcard seriesList followed by a number N of datapoints
or a quoted string with a length of time like '1hour' or '5min' (See ``from /
until`` in the render\_api_ for examples of time formats). Graphs the
median of the preceeding datapoints for each point on the graph. All
previous datapoints are set to None at the beginning of the graph.
Example:
.. code-block:: none
&target=movingMedian(Server.instance01.threads.busy,10)
&target=movingMedian(Server.instance*.threads.idle,'5min')
"""
windowInterval = None
if isinstance(windowSize, basestring):
delta = parseTimeOffset(windowSize)
windowInterval = abs(delta.seconds + (delta.days * 86400))
if windowInterval:
bootstrapSeconds = windowInterval
else:
bootstrapSeconds = max([s.step for s in seriesList]) * int(windowSize)
bootstrapList = _fetchWithBootstrap(requestContext, seriesList, seconds=bootstrapSeconds)
result = []
for bootstrap, series in zip(bootstrapList, seriesList):
if windowInterval:
windowPoints = windowInterval / series.step
else:
windowPoints = int(windowSize)
if isinstance(windowSize, basestring):
newName = 'movingMedian(%s,"%s")' % (series.name, windowSize)
else:
newName = "movingMedian(%s,%d)" % (series.name, windowPoints)
newSeries = TimeSeries(newName, series.start, series.end, series.step, [])
newSeries.pathExpression = newName
offset = len(bootstrap) - len(series)
for i in range(len(series)):
window = bootstrap[i + offset - windowPoints:i + offset]
nonNull = [v for v in window if v is not None]
if nonNull:
m_index = len(nonNull) / 2
newSeries.append(sorted(nonNull)[m_index])
else:
newSeries.append(None)
result.append(newSeries)
return result
def scale(requestContext, seriesList, factor):
"""
Takes one metric or a wildcard seriesList followed by a constant, and multiplies the datapoint
by the constant provided at each point.
Example:
.. code-block:: none
&target=scale(Server.instance01.threads.busy,10)
&target=scale(Server.instance*.threads.busy,10)
"""
for series in seriesList:
series.name = "scale(%s,%g)" % (series.name,float(factor))
series.pathExpression = series.name
for i,value in enumerate(series):
series[i] = safeMul(value,factor)
return seriesList
def invert(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList, and inverts each datapoint (i.e. 1/x).
Example:
.. code-block:: none
&target=invert(Server.instance01.threads.busy)
"""
for series in seriesList:
series.name = "invert(%s)" % (series.name)
for i,value in enumerate(series):
series[i] = safeDiv(1,value)
return seriesList
def scaleToSeconds(requestContext, seriesList, seconds):
"""
Takes one metric or a wildcard seriesList and returns "value per seconds" where
seconds is a last argument to this functions.
Useful in conjunction with derivative or integral function if you want
to normalize its result to a known resolution for arbitrary retentions
"""
for series in seriesList:
series.name = "scaleToSeconds(%s,%d)" % (series.name,seconds)
series.pathExpression = series.name
for i,value in enumerate(series):
factor = seconds * 1.0 / series.step
series[i] = safeMul(value,factor)
return seriesList
def absolute(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList and applies the mathematical abs function to each
datapoint transforming it to its absolute value.
Example:
.. code-block:: none
&target=absolute(Server.instance01.threads.busy)
&target=absolute(Server.instance*.threads.busy)
"""
for series in seriesList:
series.name = "absolute(%s)" % (series.name)
series.pathExpression = series.name
for i,value in enumerate(series):
series[i] = safeAbs(value)
return seriesList
def offset(requestContext, seriesList, factor):
"""
Takes one metric, a wildcard seriesList followed by a constant or single time
serie, and adds the value to each datapoint.
Example:
.. code-block:: none
&target=offset(Server.instance01.threads.busy,10)
&target=scale(offset(Server.instance01.threads.*.last_change,
scale(Server.instance01.uptime, -1)),-1)
"""
for series in seriesList:
if isinstance(factor, list):
if len(factor) != 1:
raise ValueError("offset second argument must reference exactly 1 series")
factor_serie = factor[0]
series.name = "offset(%s,%s)" % (series.name,factor_serie.name)
series.pathExpression = series.name
for i,value in enumerate(series):
if value is not None:
series[i] = value + factor_serie[i]
else:
series.name = "offset(%s,%g)" % (series.name,float(factor))
series.pathExpression = series.name
for i,value in enumerate(series):
if value is not None:
series[i] = value + factor
return seriesList
def offsetToZero(requestContext, seriesList):
"""
Offsets a metric or wildcard seriesList by subtracting the minimum
value in the series from each datapoint.
Useful to compare different series where the values in each series
may be higher or lower on average but you're only interested in the
relative difference.
An example use case is for comparing different round trip time
results. When measuring RTT (like pinging a server), different
devices may come back with consistently different results due to
network latency which will be different depending on how many
network hops between the probe and the device. To compare different
devices in the same graph, the network latency to each has to be
factored out of the results. This is a shortcut that takes the
fastest response (lowest number in the series) and sets that to zero
and then offsets all of the other datapoints in that series by that
amount. This makes the assumption that the lowest response is the
fastest the device can respond, of course the more datapoints that
are in the series the more accurate this assumption is.
Example:
.. code-block:: none
&target=offsetToZero(Server.instance01.responseTime)
&target=offsetToZero(Server.instance*.responseTime)
"""
for series in seriesList:
series.name = "offsetToZero(%s)" % (series.name)
minimum = safeMin(series)
for i,value in enumerate(series):
if value is not None:
series[i] = value - minimum
return seriesList
def movingAverage(requestContext, seriesList, windowSize):
"""
Graphs the moving average of a metric (or metrics) over a fixed number of
past points, or a time interval.
Takes one metric or a wildcard seriesList followed by a number N of datapoints
or a quoted string with a length of time like '1hour' or '5min' (See ``from /
until`` in the render\_api_ for examples of time formats). Graphs the
average of the preceeding datapoints for each point on the graph. All
previous datapoints are set to None at the beginning of the graph.
Example:
.. code-block:: none
&target=movingAverage(Server.instance01.threads.busy,10)
&target=movingAverage(Server.instance*.threads.idle,'5min')
"""
windowInterval = None
if isinstance(windowSize, basestring):
delta = parseTimeOffset(windowSize)
windowInterval = abs(delta.seconds + (delta.days * 86400))
if windowInterval:
bootstrapSeconds = windowInterval
else:
bootstrapSeconds = max([s.step for s in seriesList]) * int(windowSize)
bootstrapList = _fetchWithBootstrap(requestContext, seriesList, seconds=bootstrapSeconds)
result = []
for bootstrap, series in zip(bootstrapList, seriesList):
if windowInterval:
windowPoints = windowInterval / series.step
else:
windowPoints = int(windowSize)
if isinstance(windowSize, basestring):
newName = 'movingAverage(%s,"%s")' % (series.name, windowSize)
else:
newName = "movingAverage(%s,%s)" % (series.name, windowSize)
newSeries = TimeSeries(newName, series.start, series.end, series.step, [])
newSeries.pathExpression = newName
offset = len(bootstrap) - len(series)
for i in range(len(series)):
window = bootstrap[i + offset - windowPoints:i + offset]
newSeries.append(safeAvg(window))
result.append(newSeries)
return result
def cumulative(requestContext, seriesList, consolidationFunc='sum'):
"""
Takes one metric or a wildcard seriesList, and an optional function.
Valid functions are 'sum', 'average', 'min', and 'max'
Sets the consolidation function to 'sum' for the given metric seriesList.
Alias for :func:`consolidateBy(series, 'sum') <graphite.render.functions.consolidateBy>`
.. code-block:: none
&target=cumulative(Sales.widgets.largeBlue)
"""
return consolidateBy(requestContext, seriesList, 'sum')
def consolidateBy(requestContext, seriesList, consolidationFunc):
"""
Takes one metric or a wildcard seriesList and a consolidation function name.
Valid function names are 'sum', 'average', 'min', and 'max'
When a graph is drawn where width of the graph size in pixels is smaller than
the number of datapoints to be graphed, Graphite consolidates the values to
to prevent line overlap. The consolidateBy() function changes the consolidation
function from the default of 'average' to one of 'sum', 'max', or 'min'. This is
especially useful in sales graphs, where fractional values make no sense and a 'sum'
of consolidated values is appropriate.
.. code-block:: none
&target=consolidateBy(Sales.widgets.largeBlue, 'sum')
&target=consolidateBy(Servers.web01.sda1.free_space, 'max')
"""
for series in seriesList:
# datalib will throw an exception, so it's not necessary to validate here
series.consolidationFunc = consolidationFunc
series.name = 'consolidateBy(%s,"%s")' % (series.name, series.consolidationFunc)
series.pathExpression = series.name
return seriesList
def derivative(requestContext, seriesList):
"""
This is the opposite of the integral function. This is useful for taking a
running total metric and calculating the delta between subsequent data points.
This function does not normalize for periods of time, as a true derivative would.
Instead see the perSecond() function to calculate a rate of change over time.
Example:
.. code-block:: none
&target=derivative(company.server.application01.ifconfig.TXPackets)
Each time you run ifconfig, the RX and TXPackets are higher (assuming there
is network traffic.) By applying the derivative function, you can get an
idea of the packets per minute sent or received, even though you're only
recording the total.
"""
results = []
for series in seriesList:
newValues = []
prev = None
for val in series:
if None in (prev,val):
newValues.append(None)
prev = val
continue
newValues.append(val - prev)
prev = val
newName = "derivative(%s)" % series.name
newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues)
newSeries.pathExpression = newName
results.append(newSeries)
return results
def perSecond(requestContext, seriesList, maxValue=None):
"""
Derivative adjusted for the series time interval
This is useful for taking a running total metric and showing how many requests
per second were handled.
Example:
.. code-block:: none
&target=perSecond(company.server.application01.ifconfig.TXPackets)
Each time you run ifconfig, the RX and TXPackets are higher (assuming there
is network traffic.) By applying the derivative function, you can get an
idea of the packets per minute sent or received, even though you're only
recording the total.
"""
results = []
for series in seriesList:
newValues = []
prev = None
for val in series:
step = series.step
if None in (prev,val):
newValues.append(None)
prev = val
continue
diff = val - prev
if diff >= 0:
newValues.append(diff / step)
elif maxValue is not None and maxValue >= val:
newValues.append( ((maxValue - prev) + val + 1) / step )
else:
newValues.append(None)
prev = val
newName = "perSecond(%s)" % series.name
newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues)
newSeries.pathExpression = newName
results.append(newSeries)
return results
def integral(requestContext, seriesList):
"""
This will show the sum over time, sort of like a continuous addition function.
Useful for finding totals or trends in metrics that are collected per minute.
Example:
.. code-block:: none
&target=integral(company.sales.perMinute)
This would start at zero on the left side of the graph, adding the sales each
minute, and show the total sales for the time period selected at the right
side, (time now, or the time specified by '&until=').
"""
results = []
for series in seriesList:
newValues = []
current = 0.0
for val in series:
if val is None:
newValues.append(None)
else:
current += val
newValues.append(current)
newName = "integral(%s)" % series.name
newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues)
newSeries.pathExpression = newName
results.append(newSeries)
return results
def nonNegativeDerivative(requestContext, seriesList, maxValue=None):
"""
Same as the derivative function above, but ignores datapoints that trend
down. Useful for counters that increase for a long time, then wrap or
reset. (Such as if a network interface is destroyed and recreated by unloading
and re-loading a kernel module, common with USB / WiFi cards.
Example:
.. code-block:: none
&target=nonNegativederivative(company.server.application01.ifconfig.TXPackets)
"""
results = []
for series in seriesList:
newValues = []
prev = None
for val in series:
if None in (prev, val):
newValues.append(None)
prev = val
continue
diff = val - prev
if diff >= 0:
newValues.append(diff)
elif maxValue is not None and maxValue >= val:
newValues.append( (maxValue - prev) + val + 1 )
else:
newValues.append(None)
prev = val
newName = "nonNegativeDerivative(%s)" % series.name
newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues)
newSeries.pathExpression = newName
results.append(newSeries)
return results
def stacked(requestContext,seriesLists,stackName='__DEFAULT__'):
"""
Takes one metric or a wildcard seriesList and change them so they are
stacked. This is a way of stacking just a couple of metrics without having
to use the stacked area mode (that stacks everything). By means of this a mixed
stacked and non stacked graph can be made
It can also take an optional argument with a name of the stack, in case there is
more than one, e.g. for input and output metrics.
Example:
.. code-block:: none
&target=stacked(company.server.application01.ifconfig.TXPackets, 'tx')
"""
if 'totalStack' in requestContext:
totalStack = requestContext['totalStack'].get(stackName, [])
else:
requestContext['totalStack'] = {}
totalStack = [];
results = []
for series in seriesLists:
newValues = []
for i in range(len(series)):
if len(totalStack) <= i: totalStack.append(0)
if series[i] is not None:
totalStack[i] += series[i]
newValues.append(totalStack[i])
else:
newValues.append(None)
# Work-around for the case when legend is set
if stackName=='__DEFAULT__':
newName = "stacked(%s)" % series.name
else:
newName = series.name
newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues)
newSeries.options['stacked'] = True
newSeries.pathExpression = newName
results.append(newSeries)
requestContext['totalStack'][stackName] = totalStack
return results
def areaBetween(requestContext, seriesList):
"""
Draws the area in between the two series in seriesList
"""
assert len(seriesList) == 2, "areaBetween series argument must reference *exactly* 2 series"
lower = seriesList[0]
upper = seriesList[1]
lower.options['stacked'] = True
lower.options['invisible'] = True
upper.options['stacked'] = True
lower.name = upper.name = "areaBetween(%s)" % upper.pathExpression
return seriesList
def aliasSub(requestContext, seriesList, search, replace):
"""
Runs series names through a regex search/replace.
.. code-block:: none
&target=aliasSub(ip.*TCP*,"^.*TCP(\d+)","\\1")
"""
try:
seriesList.name = re.sub(search, replace, seriesList.name)
except AttributeError:
for series in seriesList:
series.name = re.sub(search, replace, series.name)
return seriesList
def alias(requestContext, seriesList, newName):
"""
Takes one metric or a wildcard seriesList and a string in quotes.
Prints the string instead of the metric name in the legend.
.. code-block:: none
&target=alias(Sales.widgets.largeBlue,"Large Blue Widgets")
"""
try:
seriesList.name = newName
except AttributeError:
for series in seriesList:
series.name = newName
return seriesList
def cactiStyle(requestContext, seriesList, system=None):
"""
Takes a series list and modifies the aliases to provide column aligned
output with Current, Max, and Min values in the style of cacti. Optonally
takes a "system" value to apply unit formatting in the same style as the
Y-axis.
NOTE: column alignment only works with monospace fonts such as terminus.
.. code-block:: none
&target=cactiStyle(ganglia.*.net.bytes_out,"si")
"""
if 0 == len(seriesList):
return seriesList
if system:
fmt = lambda x:"%.2f%s" % format_units(x,system=system)
else:
fmt = lambda x:"%.2f"%x
nameLen = max([0] + [len(getattr(series,"name")) for series in seriesList])
lastLen = max([0] + [len(fmt(int(safeLast(series) or 3))) for series in seriesList]) + 3
maxLen = max([0] + [len(fmt(int(safeMax(series) or 3))) for series in seriesList]) + 3
minLen = max([0] + [len(fmt(int(safeMin(series) or 3))) for series in seriesList]) + 3
for series in seriesList:
name = series.name
last = safeLast(series)
maximum = safeMax(series)
minimum = safeMin(series)
if last is None:
last = NAN
else:
last = fmt(float(last))
if maximum is None:
maximum = NAN
else:
maximum = fmt(float(maximum))
if minimum is None:
minimum = NAN
else:
minimum = fmt(float(minimum))
series.name = "%*s Current:%*s Max:%*s Min:%*s " % \
(-nameLen, series.name,
-lastLen, last,
-maxLen, maximum,
-minLen, minimum)
return seriesList
def aliasByNode(requestContext, seriesList, *nodes):
"""
Takes a seriesList and applies an alias derived from one or more "node"
portion/s of the target name. Node indices are 0 indexed.
.. code-block:: none
&target=aliasByNode(ganglia.*.cpu.load5,1)
"""
if isinstance(nodes, int):
nodes=[nodes]
for series in seriesList:
metric_pieces = re.search('(?:.*\()?(?P<name>[-\w*\.]+)(?:,|\)?.*)?',series.name).groups()[0].split('.')
series.name = '.'.join(metric_pieces[n] for n in nodes)
return seriesList
def aliasByMetric(requestContext, seriesList):
"""
Takes a seriesList and applies an alias derived from the base metric name.
.. code-block:: none
&target=aliasByMetric(carbon.agents.graphite.creates)
"""
for series in seriesList:
series.name = series.name.split('.')[-1]
return seriesList
def legendValue(requestContext, seriesList, *valueTypes):
"""
Takes one metric or a wildcard seriesList and a string in quotes.
Appends a value to the metric name in the legend. Currently one or several of: `last`, `avg`,
`total`, `min`, `max`.
The last argument can be `si` (default) or `binary`, in that case values will be formatted in the
corresponding system.
.. code-block:: none
&target=legendValue(Sales.widgets.largeBlue, 'avg', 'max', 'si')
"""
def last(s):
"Work-around for the missing last point"
v = s[-1]
if v is None:
return s[-2]
return v
valueFuncs = {
'avg': lambda s: safeDiv(safeSum(s), safeLen(s)),
'total': safeSum,
'min': safeMin,
'max': safeMax,
'last': last
}
system = None
if valueTypes[-1] in ('si', 'binary'):
system = valueTypes[-1]
valueTypes = valueTypes[:-1]
for valueType in valueTypes:
valueFunc = valueFuncs.get(valueType, lambda s: '(?)')
if system is None:
for series in seriesList:
series.name += " (%s: %s)" % (valueType, valueFunc(series))
else:
for series in seriesList:
value = valueFunc(series)
formatted = None
if value is not None:
formatted = "%.2f%s" % format_units(abs(value), system=system)
series.name = "%-20s%-5s%-10s" % (series.name, valueType, formatted)
return seriesList
def alpha(requestContext, seriesList, alpha):
"""
Assigns the given alpha transparency setting to the series. Takes a float value between 0 and 1.
"""
for series in seriesList:
series.options['alpha'] = alpha
return seriesList
def color(requestContext, seriesList, theColor):
"""
Assigns the given color to the seriesList
Example:
.. code-block:: none
&target=color(collectd.hostname.cpu.0.user, 'green')
&target=color(collectd.hostname.cpu.0.system, 'ff0000')
&target=color(collectd.hostname.cpu.0.idle, 'gray')
&target=color(collectd.hostname.cpu.0.idle, '6464ffaa')
"""
for series in seriesList:
series.color = theColor
return seriesList
def substr(requestContext, seriesList, start=0, stop=0):
"""
Takes one metric or a wildcard seriesList followed by 1 or 2 integers. Assume that the
metric name is a list or array, with each element separated by dots. Prints
n - length elements of the array (if only one integer n is passed) or n - m
elements of the array (if two integers n and m are passed). The list starts
with element 0 and ends with element (length - 1).
Example:
.. code-block:: none
&target=substr(carbon.agents.hostname.avgUpdateTime,2,4)
The label would be printed as "hostname.avgUpdateTime".
"""
for series in seriesList:
left = series.name.rfind('(') + 1
right = series.name.find(')')
if right < 0:
right = len(series.name)+1
cleanName = series.name[left:right:]
if int(stop) == 0:
series.name = '.'.join(cleanName.split('.')[int(start)::])
else:
series.name = '.'.join(cleanName.split('.')[int(start):int(stop):])
# substr(func(a.b,'c'),1) becomes b instead of b,'c'
series.name = re.sub(',.*$', '', series.name)
return seriesList
def logarithm(requestContext, seriesList, base=10):
"""
Takes one metric or a wildcard seriesList, a base, and draws the y-axis in logarithmic
format. If base is omitted, the function defaults to base 10.
Example:
.. code-block:: none
&target=log(carbon.agents.hostname.avgUpdateTime,2)
"""
results = []
for series in seriesList:
newValues = []
for val in series:
if val is None:
newValues.append(None)
elif val <= 0:
newValues.append(None)
else:
newValues.append(math.log(val, base))
newName = "log(%s, %s)" % (series.name, base)
newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues)
newSeries.pathExpression = newName
results.append(newSeries)
return results
def maximumAbove(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by a constant n.
Draws only the metrics with a maximum value above n.
Example:
.. code-block:: none
&target=maximumAbove(system.interface.eth*.packetsSent,1000)
This would only display interfaces which sent more than 1000 packets/min.
"""
results = []
for series in seriesList:
if max(series) > n:
results.append(series)
return results
def minimumAbove(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by a constant n.
Draws only the metrics with a minimum value above n.
Example:
.. code-block:: none
&target=minimumAbove(system.interface.eth*.packetsSent,1000)
This would only display interfaces which sent more than 1000 packets/min.
"""
results = []
for series in seriesList:
if min(series) > n:
results.append(series)
return results
def maximumBelow(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by a constant n.
Draws only the metrics with a maximum value below n.
Example:
.. code-block:: none
&target=maximumBelow(system.interface.eth*.packetsSent,1000)
This would only display interfaces which sent less than 1000 packets/min.
"""
result = []
for series in seriesList:
if max(series) <= n:
result.append(series)
return result
def highestCurrent(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Out of all metrics passed, draws only the N metrics with the highest value
at the end of the time period specified.
Example:
.. code-block:: none
&target=highestCurrent(server*.instance*.threads.busy,5)
Draws the 5 servers with the highest busy threads.
"""
return sorted( seriesList, key=safeLast )[-n:]
def highestMax(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Out of all metrics passed, draws only the N metrics with the highest maximum
value in the time period specified.
Example:
.. code-block:: none
&target=highestMax(server*.instance*.threads.busy,5)
Draws the top 5 servers who have had the most busy threads during the time
period specified.
"""
result_list = sorted( seriesList, key=lambda s: max(s) )[-n:]
return sorted(result_list, key=lambda s: max(s), reverse=True)
def lowestCurrent(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Out of all metrics passed, draws only the N metrics with the lowest value at
the end of the time period specified.
Example:
.. code-block:: none
&target=lowestCurrent(server*.instance*.threads.busy,5)
Draws the 5 servers with the least busy threads right now.
"""
return sorted( seriesList, key=safeLast )[:n]
def currentAbove(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Out of all metrics passed, draws only the metrics whose value is above N
at the end of the time period specified.
Example:
.. code-block:: none
&target=currentAbove(server*.instance*.threads.busy,50)
Draws the servers with more than 50 busy threads.
"""
return [ series for series in seriesList if safeLast(series) >= n ]
def currentBelow(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Out of all metrics passed, draws only the metrics whose value is below N
at the end of the time period specified.
Example:
.. code-block:: none
&target=currentBelow(server*.instance*.threads.busy,3)
Draws the servers with less than 3 busy threads.
"""
return [ series for series in seriesList if safeLast(series) <= n ]
def highestAverage(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Out of all metrics passed, draws only the top N metrics with the highest
average value for the time period specified.
Example:
.. code-block:: none
&target=highestAverage(server*.instance*.threads.busy,5)
Draws the top 5 servers with the highest average value.
"""
return sorted( seriesList, key=lambda s: safeDiv(safeSum(s),safeLen(s)) )[-n:]
def lowestAverage(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Out of all metrics passed, draws only the bottom N metrics with the lowest
average value for the time period specified.
Example:
.. code-block:: none
&target=lowestAverage(server*.instance*.threads.busy,5)
Draws the bottom 5 servers with the lowest average value.
"""
return sorted( seriesList, key=lambda s: safeDiv(safeSum(s),safeLen(s)) )[:n]
def averageAbove(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Out of all metrics passed, draws only the metrics with an average value
above N for the time period specified.
Example:
.. code-block:: none
&target=averageAbove(server*.instance*.threads.busy,25)
Draws the servers with average values above 25.
"""
return [ series for series in seriesList if safeDiv(safeSum(series),safeLen(series)) >= n ]
def averageBelow(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Out of all metrics passed, draws only the metrics with an average value
below N for the time period specified.
Example:
.. code-block:: none
&target=averageBelow(server*.instance*.threads.busy,25)
Draws the servers with average values below 25.
"""
return [ series for series in seriesList if safeDiv(safeSum(series),safeLen(series)) <= n ]
def _getPercentile(points, n, interpolate=False):
"""
Percentile is calculated using the method outlined in the NIST Engineering
Statistics Handbook:
http://www.itl.nist.gov/div898/handbook/prc/section2/prc252.htm
"""
sortedPoints = sorted([ p for p in points if p is not None])
if len(sortedPoints) == 0:
return None
fractionalRank = (n/100.0) * (len(sortedPoints) + 1)
rank = int(fractionalRank)
rankFraction = fractionalRank - rank
if not interpolate:
rank += int(math.ceil(rankFraction))
if rank == 0:
percentile = sortedPoints[0]
elif rank - 1 == len(sortedPoints):
percentile = sortedPoints[-1]
else:
percentile = sortedPoints[rank - 1] # Adjust for 0-index
if interpolate:
if rank != len(sortedPoints): # if a next value exists
nextValue = sortedPoints[rank]
percentile = percentile + rankFraction * (nextValue - percentile)
return percentile
def nPercentile(requestContext, seriesList, n):
"""Returns n-percent of each series in the seriesList."""
assert n, 'The requested percent is required to be greater than 0'
results = []
for s in seriesList:
# Create a sorted copy of the TimeSeries excluding None values in the values list.
s_copy = TimeSeries( s.name, s.start, s.end, s.step, sorted( [item for item in s if item is not None] ) )
if not s_copy:
continue # Skip this series because it is empty.
perc_val = _getPercentile(s_copy, n)
if perc_val is not None:
name = 'nPercentile(%s, %g)' % (s_copy.name, n)
point_count = int((s.end - s.start)/s.step)
perc_series = TimeSeries(name, s_copy.start, s_copy.end, s_copy.step, [perc_val] * point_count )
perc_series.pathExpression = name
results.append(perc_series)
return results
def averageOutsidePercentile(requestContext, seriesList, n):
"""
Removes functions lying inside an average percentile interval
"""
averages = []
for s in seriesList:
averages.append(safeDiv(safeSum(s), safeLen(s)))
if n < 50:
n = 100 - n;
lowPercentile = _getPercentile(averages, 100 - n)
highPercentile = _getPercentile(averages, n)
return [s for s in seriesList if not lowPercentile < safeDiv(safeSum(s), safeLen(s)) < highPercentile]
def removeBetweenPercentile(requestContext, seriesList, n):
"""
Removes lines who do not have an value lying in the x-percentile of all the values at a moment
"""
if n < 50:
n = 100 - n
transposed = zip(*seriesList)
lowPercentiles = [_getPercentile(col, 100-n) for col in transposed]
highPercentiles = [_getPercentile(col, n) for col in transposed]
return [l for l in seriesList if sum([not lowPercentiles[val_i] < val < highPercentiles[val_i]
for (val_i, val) in enumerate(l)]) > 0]
def removeAbovePercentile(requestContext, seriesList, n):
"""
Removes data above the nth percentile from the series or list of series provided.
Values above this percentile are assigned a value of None.
"""
for s in seriesList:
s.name = 'removeAbovePercentile(%s, %d)' % (s.name, n)
s.pathExpression = s.name
percentile = nPercentile(requestContext, [s], n)[0][0]
for (index, val) in enumerate(s):
if val > percentile:
s[index] = None
return seriesList
def removeAboveValue(requestContext, seriesList, n):
"""
Removes data above the given threshold from the series or list of series provided.
Values above this threshole are assigned a value of None
"""
for s in seriesList:
s.name = 'removeAboveValue(%s, %d)' % (s.name, n)
s.pathExpression = s.name
for (index, val) in enumerate(s):
if val > n:
s[index] = None
return seriesList
def removeBelowPercentile(requestContext, seriesList, n):
"""
Removes data below the nth percentile from the series or list of series provided.
Values below this percentile are assigned a value of None.
"""
for s in seriesList:
s.name = 'removeBelowPercentile(%s, %d)' % (s.name, n)
s.pathExpression = s.name
percentile = nPercentile(requestContext, [s], n)[0][0]
for (index, val) in enumerate(s):
if val < percentile:
s[index] = None
return seriesList
def removeBelowValue(requestContext, seriesList, n):
"""
Removes data below the given threshold from the series or list of series provided.
Values below this threshole are assigned a value of None
"""
for s in seriesList:
s.name = 'removeBelowValue(%s, %d)' % (s.name, n)
s.pathExpression = s.name
for (index, val) in enumerate(s):
if val < n:
s[index] = None
return seriesList
def limit(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Only draw the first N metrics. Useful when testing a wildcard in a metric.
Example:
.. code-block:: none
&target=limit(server*.instance*.memory.free,5)
Draws only the first 5 instance's memory free.
"""
return seriesList[0:n]
def sortByName(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Sorts the list of metrics by the metric name.
"""
def compare(x,y):
return cmp(x.name, y.name)
seriesList.sort(compare)
return seriesList
def sortByTotal(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Sorts the list of metrics by the sum of values across the time period
specified.
"""
def compare(x,y):
return cmp(safeSum(y), safeSum(x))
seriesList.sort(compare)
return seriesList
def sortByMaxima(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Sorts the list of metrics by the maximum value across the time period
specified. Useful with the &areaMode=all parameter, to keep the
lowest value lines visible.
Example:
.. code-block:: none
&target=sortByMaxima(server*.instance*.memory.free)
"""
def compare(x,y):
return cmp(max(y), max(x))
seriesList.sort(compare)
return seriesList
def sortByMinima(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Sorts the list of metrics by the lowest value across the time period
specified.
Example:
.. code-block:: none
&target=sortByMinima(server*.instance*.memory.free)
"""
def compare(x,y):
return cmp(min(x), min(y))
newSeries = [series for series in seriesList if max(series) > 0]
newSeries.sort(compare)
return newSeries
def sortByName(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Sorts the list of metrics by the name.
"""
def compare(x,y):
return 1 if x.name > y.name else -1
seriesList.sort(compare)
return seriesList
def useSeriesAbove(requestContext, seriesList, value, search, replace):
"""
Compares the maximum of each series against the given `value`. If the series
maximum is greater than `value`, the regular expression search and replace is
applied against the series name to plot a related metric
e.g. given useSeriesAbove(ganglia.metric1.reqs,10,'reqs','time'),
the response time metric will be plotted only when the maximum value of the
corresponding request/s metric is > 10
.. code-block:: none
&target=useSeriesAbove(ganglia.metric1.reqs,10,"reqs","time")
"""
newSeries = []
for series in seriesList:
newname = re.sub(search, replace, series.name)
if max(series) > value:
n = evaluateTarget(requestContext, newname)
if n is not None and len(n) > 0:
newSeries.append(n[0])
return newSeries
def mostDeviant(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Draws the N most deviant metrics.
To find the deviants, the standard deviation (sigma) of each series
is taken and ranked. The top N standard deviations are returned.
Example:
.. code-block:: none
&target=mostDeviant(5, server*.instance*.memory.free)
Draws the 5 instances furthest from the average memory free.
"""
deviants = []
for series in seriesList:
mean = safeDiv( safeSum(series), safeLen(series) )
if mean is None: continue
square_sum = sum([ (value - mean) ** 2 for value in series if value is not None ])
sigma = safeDiv(square_sum, safeLen(series))
if sigma is None: continue
deviants.append( (sigma, series) )
deviants.sort(key=lambda i: i[0], reverse=True) #sort by sigma
return [ series for (sigma,series) in deviants ][:n] #return the n most deviant series
def stdev(requestContext, seriesList, points, windowTolerance=0.1):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Draw the Standard Deviation of all metrics passed for the past N datapoints.
If the ratio of null points in the window is greater than windowTolerance,
skip the calculation. The default for windowTolerance is 0.1 (up to 10% of points
in the window can be missing). Note that if this is set to 0.0, it will cause large
gaps in the output anywhere a single point is missing.
Example:
.. code-block:: none
&target=stdev(server*.instance*.threads.busy,30)
&target=stdev(server*.instance*.cpu.system,30,0.0)
"""
# For this we take the standard deviation in terms of the moving average
# and the moving average of series squares.
for (seriesIndex,series) in enumerate(seriesList):
stddevSeries = TimeSeries("stddev(%s,%d)" % (series.name, int(points)), series.start, series.end, series.step, [])
stddevSeries.pathExpression = "stddev(%s,%d)" % (series.name, int(points))
validPoints = 0
currentSum = 0
currentSumOfSquares = 0
for (index, newValue) in enumerate(series):
# Mark whether we've reached our window size - dont drop points out otherwise
if index < points:
bootstrapping = True
droppedValue = None
else:
bootstrapping = False
droppedValue = series[index - points]
# Track non-None points in window
if not bootstrapping and droppedValue is not None:
validPoints -= 1
if newValue is not None:
validPoints += 1
# Remove the value that just dropped out of the window
if not bootstrapping and droppedValue is not None:
currentSum -= droppedValue
currentSumOfSquares -= droppedValue**2
# Add in the value that just popped in the window
if newValue is not None:
currentSum += newValue
currentSumOfSquares += newValue**2
if validPoints > 0 and \
float(validPoints)/points >= windowTolerance:
try:
deviation = math.sqrt(validPoints * currentSumOfSquares - currentSum**2)/validPoints
except ValueError:
deviation = None
stddevSeries.append(deviation)
else:
stddevSeries.append(None)
seriesList[seriesIndex] = stddevSeries
return seriesList
def secondYAxis(requestContext, seriesList):
"""
Graph the series on the secondary Y axis.
"""
for series in seriesList:
series.options['secondYAxis'] = True
series.name= 'secondYAxis(%s)' % series.name
return seriesList
def _fetchWithBootstrap(requestContext, seriesList, **delta_kwargs):
'Request the same data but with a bootstrap period at the beginning'
bootstrapContext = requestContext.copy()
bootstrapContext['startTime'] = requestContext['startTime'] - timedelta(**delta_kwargs)
bootstrapContext['endTime'] = requestContext['startTime']
bootstrapList = []
for series in seriesList:
if series.pathExpression in [ b.pathExpression for b in bootstrapList ]:
# This pathExpression returns multiple series and we already fetched it
continue
bootstraps = evaluateTarget(bootstrapContext, series.pathExpression)
bootstrapList.extend(bootstraps)
newSeriesList = []
for bootstrap, original in zip(bootstrapList, seriesList):
newValues = []
if bootstrap.step != original.step:
ratio = bootstrap.step / original.step
for value in bootstrap:
#XXX For series with aggregationMethod = sum this should also
# divide by the ratio to bring counts to the same time unit
# ...but we have no way of knowing whether that's the case
newValues.extend([ value ] * ratio)
else:
newValues.extend(bootstrap)
newValues.extend(original)
newSeries = TimeSeries(original.name, bootstrap.start, original.end, original.step, newValues)
newSeries.pathExpression = series.pathExpression
newSeriesList.append(newSeries)
return newSeriesList
def _trimBootstrap(bootstrap, original):
'Trim the bootstrap period off the front of this series so it matches the original'
original_len = len(original)
bootstrap_len = len(bootstrap)
length_limit = (original_len * original.step) / bootstrap.step
trim_start = bootstrap.end - (length_limit * bootstrap.step)
trimmed = TimeSeries(bootstrap.name, trim_start, bootstrap.end, bootstrap.step,
bootstrap[-length_limit:])
return trimmed
def holtWintersIntercept(alpha,actual,last_season,last_intercept,last_slope):
return alpha * (actual - last_season) \
+ (1 - alpha) * (last_intercept + last_slope)
def holtWintersSlope(beta,intercept,last_intercept,last_slope):
return beta * (intercept - last_intercept) + (1 - beta) * last_slope
def holtWintersSeasonal(gamma,actual,intercept,last_season):
return gamma * (actual - intercept) + (1 - gamma) * last_season
def holtWintersDeviation(gamma,actual,prediction,last_seasonal_dev):
if prediction is None:
prediction = 0
return gamma * math.fabs(actual - prediction) + (1 - gamma) * last_seasonal_dev
def holtWintersAnalysis(series):
alpha = gamma = 0.1
beta = 0.0035
# season is currently one day
season_length = (24*60*60) / series.step
intercept = 0
slope = 0
pred = 0
intercepts = list()
slopes = list()
seasonals = list()
predictions = list()
deviations = list()
def getLastSeasonal(i):
j = i - season_length
if j >= 0:
return seasonals[j]
return 0
def getLastDeviation(i):
j = i - season_length
if j >= 0:
return deviations[j]
return 0
last_seasonal = 0
last_seasonal_dev = 0
next_last_seasonal = 0
next_pred = None
for i,actual in enumerate(series):
if actual is None:
# missing input values break all the math
# do the best we can and move on
intercepts.append(None)
slopes.append(0)
seasonals.append(0)
predictions.append(next_pred)
deviations.append(0)
next_pred = None
continue
if i == 0:
last_intercept = actual
last_slope = 0
# seed the first prediction as the first actual
prediction = actual
else:
last_intercept = intercepts[-1]
last_slope = slopes[-1]
if last_intercept is None:
last_intercept = actual
prediction = next_pred
last_seasonal = getLastSeasonal(i)
next_last_seasonal = getLastSeasonal(i+1)
last_seasonal_dev = getLastDeviation(i)
intercept = holtWintersIntercept(alpha,actual,last_seasonal
,last_intercept,last_slope)
slope = holtWintersSlope(beta,intercept,last_intercept,last_slope)
seasonal = holtWintersSeasonal(gamma,actual,intercept,last_seasonal)
next_pred = intercept + slope + next_last_seasonal
deviation = holtWintersDeviation(gamma,actual,prediction,last_seasonal_dev)
intercepts.append(intercept)
slopes.append(slope)
seasonals.append(seasonal)
predictions.append(prediction)
deviations.append(deviation)
# make the new forecast series
forecastName = "holtWintersForecast(%s)" % series.name
forecastSeries = TimeSeries(forecastName, series.start, series.end
, series.step, predictions)
forecastSeries.pathExpression = forecastName
# make the new deviation series
deviationName = "holtWintersDeviation(%s)" % series.name
deviationSeries = TimeSeries(deviationName, series.start, series.end
, series.step, deviations)
deviationSeries.pathExpression = deviationName
results = { 'predictions': forecastSeries
, 'deviations': deviationSeries
, 'intercepts': intercepts
, 'slopes': slopes
, 'seasonals': seasonals
}
return results
def holtWintersForecast(requestContext, seriesList):
"""
Performs a Holt-Winters forecast using the series as input data. Data from
one week previous to the series is used to bootstrap the initial forecast.
"""
results = []
bootstrapList = _fetchWithBootstrap(requestContext, seriesList, days=7)
for bootstrap, series in zip(bootstrapList, seriesList):
analysis = holtWintersAnalysis(bootstrap)
results.append(_trimBootstrap(analysis['predictions'], series))
return results
def holtWintersConfidenceBands(requestContext, seriesList, delta=3):
"""
Performs a Holt-Winters forecast using the series as input data and plots
upper and lower bands with the predicted forecast deviations.
"""
results = []
bootstrapList = _fetchWithBootstrap(requestContext, seriesList, days=7)
for bootstrap,series in zip(bootstrapList, seriesList):
analysis = holtWintersAnalysis(bootstrap)
forecast = _trimBootstrap(analysis['predictions'], series)
deviation = _trimBootstrap(analysis['deviations'], series)
seriesLength = len(forecast)
i = 0
upperBand = list()
lowerBand = list()
while i < seriesLength:
forecast_item = forecast[i]
deviation_item = deviation[i]
i = i + 1
if forecast_item is None or deviation_item is None:
upperBand.append(None)
lowerBand.append(None)
else:
scaled_deviation = delta * deviation_item
upperBand.append(forecast_item + scaled_deviation)
lowerBand.append(forecast_item - scaled_deviation)
upperName = "holtWintersConfidenceUpper(%s)" % series.name
lowerName = "holtWintersConfidenceLower(%s)" % series.name
upperSeries = TimeSeries(upperName, forecast.start, forecast.end
, forecast.step, upperBand)
lowerSeries = TimeSeries(lowerName, forecast.start, forecast.end
, forecast.step, lowerBand)
upperSeries.pathExpression = series.pathExpression
lowerSeries.pathExpression = series.pathExpression
results.append(lowerSeries)
results.append(upperSeries)
return results
def holtWintersAberration(requestContext, seriesList, delta=3):
"""
Performs a Holt-Winters forecast using the series as input data and plots the
positive or negative deviation of the series data from the forecast.
"""
results = []
for series in seriesList:
confidenceBands = holtWintersConfidenceBands(requestContext, [series], delta)
lowerBand = confidenceBands[0]
upperBand = confidenceBands[1]
aberration = list()
for i, actual in enumerate(series):
if series[i] is None:
aberration.append(0)
elif upperBand[i] is not None and series[i] > upperBand[i]:
aberration.append(series[i] - upperBand[i])
elif lowerBand[i] is not None and series[i] < lowerBand[i]:
aberration.append(series[i] - lowerBand[i])
else:
aberration.append(0)
newName = "holtWintersAberration(%s)" % series.name
results.append(TimeSeries(newName, series.start, series.end
, series.step, aberration))
return results
def holtWintersConfidenceArea(requestContext, seriesList, delta=3):
"""
Performs a Holt-Winters forecast using the series as input data and plots the
area between the upper and lower bands of the predicted forecast deviations.
"""
bands = holtWintersConfidenceBands(requestContext, seriesList, delta)
results = areaBetween(requestContext, bands)
for series in results:
series.name = series.name.replace('areaBetween', 'holtWintersConfidenceArea')
return results
def drawAsInfinite(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
If the value is zero, draw the line at 0. If the value is above zero, draw
the line at infinity. If the value is null or less than zero, do not draw
the line.
Useful for displaying on/off metrics, such as exit codes. (0 = success,
anything else = failure.)
Example:
.. code-block:: none
drawAsInfinite(Testing.script.exitCode)
"""
for series in seriesList:
series.options['drawAsInfinite'] = True
series.name = 'drawAsInfinite(%s)' % series.name
return seriesList
def lineWidth(requestContext, seriesList, width):
"""
Takes one metric or a wildcard seriesList, followed by a float F.
Draw the selected metrics with a line width of F, overriding the default
value of 1, or the &lineWidth=X.X parameter.
Useful for highlighting a single metric out of many, or having multiple
line widths in one graph.
Example:
.. code-block:: none
&target=lineWidth(server01.instance01.memory.free,5)
"""
for series in seriesList:
series.options['lineWidth'] = width
return seriesList
def dashed(requestContext, *seriesList):
"""
Takes one metric or a wildcard seriesList, followed by a float F.
Draw the selected metrics with a dotted line with segments of length F
If omitted, the default length of the segments is 5.0
Example:
.. code-block:: none
&target=dashed(server01.instance01.memory.free,2.5)
"""
if len(seriesList) == 2:
dashLength = seriesList[1]
else:
dashLength = 5
for series in seriesList[0]:
series.name = 'dashed(%s, %d)' % (series.name, dashLength)
series.options['dashed'] = dashLength
return seriesList[0]
def timeStack(requestContext, seriesList, timeShiftUnit, timeShiftStart, timeShiftEnd):
"""
Takes one metric or a wildcard seriesList, followed by a quoted string with the
length of time (See ``from / until`` in the render\_api_ for examples of time formats).
Also takes a start multiplier and end multiplier for the length of time
create a seriesList which is composed the orginal metric series stacked with time shifts
starting time shifts from the start multiplier through the end multiplier
Useful for looking at history, or feeding into seriesAverage or seriesStdDev
Example:
.. code-block:: none
&target=timeStack(Sales.widgets.largeBlue,"1d",0,7) # create a series for today and each of the previous 7 days
"""
# Default to negative. parseTimeOffset defaults to +
if timeShiftUnit[0].isdigit():
timeShiftUnit = '-' + timeShiftUnit
delta = parseTimeOffset(timeShiftUnit)
series = seriesList[0] # if len(seriesList) > 1, they will all have the same pathExpression, which is all we care about.
results = []
timeShiftStartint = int(timeShiftStart)
timeShiftEndint = int(timeShiftEnd)
for shft in range(timeShiftStartint,timeShiftEndint):
myContext = requestContext.copy()
innerDelta = delta * shft
myContext['startTime'] = requestContext['startTime'] + innerDelta
myContext['endTime'] = requestContext['endTime'] + innerDelta
for shiftedSeries in evaluateTarget(myContext, series.pathExpression):
shiftedSeries.name = 'timeShift(%s, %s, %s)' % (shiftedSeries.name, timeShiftUnit,shft)
shiftedSeries.pathExpression = shiftedSeries.name
shiftedSeries.start = series.start
shiftedSeries.end = series.end
results.append(shiftedSeries)
return results
def timeShift(requestContext, seriesList, timeShift, resetEnd=True):
"""
Takes one metric or a wildcard seriesList, followed by a quoted string with the
length of time (See ``from / until`` in the render\_api_ for examples of time formats).
Draws the selected metrics shifted in time. If no sign is given, a minus sign ( - ) is
implied which will shift the metric back in time. If a plus sign ( + ) is given, the
metric will be shifted forward in time.
Will reset the end date range automatically to the end of the base stat unless
resetEnd is False. Example case is when you timeshift to last week and have the graph
date range set to include a time in the future, will limit this timeshift to pretend
ending at the current time. If resetEnd is False, will instead draw full range including
future time.
Useful for comparing a metric against itself at a past periods or correcting data
stored at an offset.
Example:
.. code-block:: none
&target=timeShift(Sales.widgets.largeBlue,"7d")
&target=timeShift(Sales.widgets.largeBlue,"-7d")
&target=timeShift(Sales.widgets.largeBlue,"+1h")
"""
# Default to negative. parseTimeOffset defaults to +
if timeShift[0].isdigit():
timeShift = '-' + timeShift
delta = parseTimeOffset(timeShift)
myContext = requestContext.copy()
myContext['startTime'] = requestContext['startTime'] + delta
myContext['endTime'] = requestContext['endTime'] + delta
results = []
if len(seriesList) > 0:
series = seriesList[0] # if len(seriesList) > 1, they will all have the same pathExpression, which is all we care about.
for shiftedSeries in evaluateTarget(myContext, series.pathExpression):
shiftedSeries.name = 'timeShift(%s, %s)' % (shiftedSeries.name, timeShift)
if resetEnd:
shiftedSeries.end = series.end
else:
shiftedSeries.end = shiftedSeries.end - shiftedSeries.start + series.start
shiftedSeries.start = series.start
results.append(shiftedSeries)
return results
def constantLine(requestContext, value):
"""
Takes a float F.
Draws a horizontal line at value F across the graph.
Example:
.. code-block:: none
&target=constantLine(123.456)
"""
start = timestamp( requestContext['startTime'] )
end = timestamp( requestContext['endTime'] )
step = (end - start) / 1.0
series = TimeSeries(str(value), start, end, step, [value, value])
return [series]
def aggregateLine(requestContext, seriesList, func='avg'):
"""
Draws a horizontal line based the function applied to the series.
Note: By default, the graphite renderer consolidates data points by
averaging data points over time. If you are using the 'min' or 'max'
function for aggregateLine, this can cause an unusual gap in the
line drawn by this function and the data itself. To fix this, you
should use the consolidateBy() function with the same function
argument you are using for aggregateLine. This will ensure that the
proper data points are retained and the graph should line up
correctly.
Example:
.. code-block:: none
&target=aggregateLineSeries(server.connections.total, 'avg')
"""
t_funcs = { 'avg': safeAvg, 'min': safeMin, 'max': safeMax }
if func not in t_funcs:
raise ValueError("Invalid function %s" % func)
value = t_funcs[func]( seriesList[0] )
name = 'aggregateLine(%s,%d)' % (seriesList[0].pathExpression, value)
series = constantLine(requestContext, value)[0]
series.name = name
return [series]
def threshold(requestContext, value, label=None, color=None):
"""
Takes a float F, followed by a label (in double quotes) and a color.
(See ``bgcolor`` in the render\_api_ for valid color names & formats.)
Draws a horizontal line at value F across the graph.
Example:
.. code-block:: none
&target=threshold(123.456, "omgwtfbbq", red)
"""
series = constantLine(requestContext, value)[0]
if label:
series.name = label
if color:
series.color = color
return [series]
def transformNull(requestContext, seriesList, default=0):
"""
Takes a metric or wild card seriesList and an optional value
to transform Nulls to. Default is 0. This method compliments
drawNullAsZero flag in graphical mode but also works in text only
mode.
Example:
.. code-block:: none
&target=transformNull(webapp.pages.*.views,-1)
This would take any page that didn't have values and supply negative 1 as a default.
Any other numeric value may be used as well.
"""
def transform(v):
if v is None: return default
else: return v
for series in seriesList:
series.name = "transformNull(%s,%g)" % (series.name, default)
series.pathExpression = series.name
values = [transform(v) for v in series]
series.extend(values)
del series[:len(values)]
return seriesList
def isNonNull(requestContext, seriesList):
"""
Takes a metric or wild card seriesList and counts up how many
non-null values are specified. This is useful for understanding
which metrics have data at a given point in time (ie, to count
which servers are alive).
Example:
.. code-block:: none
&target=isNonNull(webapp.pages.*.views)
Returns a seriesList where 1 is specified for non-null values, and
0 is specified for null values.
"""
def transform(v):
if v is None: return 0
else: return 1
for series in seriesList:
series.name = "isNonNull(%s)" % (series.name)
series.pathExpression = series.name
values = [transform(v) for v in series]
series.extend(values)
del series[:len(values)]
return seriesList
def upperBound(requestContext, seriesList, boundary):
"""
Takes a metric or wild card seriesList and returns min(value, boundary) for
non-null values. This is useful for when you only care about the value
up to a certain point - for example if you are logging error codes and you
only care if the value is >= 1 and not the value itself.
Example:
.. code-block:: none
&target=upperBound(application.myapp.*.exitcode, 1.0)
Returns a seriesList where the maximum value is the boundary or lower.
"""
def transform(v):
if v is None: return None
return min(v, boundary)
for series in seriesList:
series.name = "upperBound(%s, %d)" % (series.name, boundary)
series.pathExpression = series.name
values = [transform(v) for v in series]
series.extend(values)
del series[:len(values)]
return seriesList
def lowerBound(requestContext, seriesList, boundary):
"""
Takes a metric or wild card seriesList and returns max(value, boundary) for
non-null values. This is useful for when you only care about the value
up to a certain point - for example if you are logging error codes and you
only care if the value is <= -1 and not the value itself.
Example:
.. code-block:: none
&target=lowerBound(application.myapp.*.exitcode, -1.0)
Returns a seriesList where the minimum value is the boundary or greater.
"""
def transform(v):
if v is None: return None
return max(v, boundary)
for series in seriesList:
series.name = "lowerBound(%s, %d)" % (series.name, boundary)
series.pathExpression = series.name
values = [transform(v) for v in series]
series.extend(values)
del series[:len(values)]
return seriesList
def identity(requestContext, name):
"""
Identity function:
Returns datapoints where the value equals the timestamp of the datapoint.
Useful when you have another series where the value is a timestamp, and
you want to compare it to the time of the datapoint, to render an age
Example:
.. code-block:: none
&target=identity("The.time.series")
This would create a series named "The.time.series" that contains points where
x(t) == t.
"""
step = 60
delta = timedelta(seconds=step)
start = time.mktime(requestContext["startTime"].timetuple())
end = time.mktime(requestContext["endTime"].timetuple())
values = range(start, end, step)
series = TimeSeries(name, start, end, step, values)
series.pathExpression = 'identity("%s")' % name
return [series]
def countSeries(requestContext, *seriesLists):
"""
Draws a horizontal line representing the number of nodes found in the seriesList.
.. code-block:: none
&target=countSeries(carbon.agents.*.*)
"""
(seriesList,start,end,step) = normalize(seriesLists)
name = "countSeries(%s)" % formatPathExpressions(seriesList)
values = ( int(len(row)) for row in izip(*seriesList) )
series = TimeSeries(name,start,end,step,values)
series.pathExpression = name
return [series]
def group(requestContext, *seriesLists):
"""
Takes an arbitrary number of seriesLists and adds them to a single seriesList. This is used
to pass multiple seriesLists to a function which only takes one
"""
seriesGroup = []
for s in seriesLists:
seriesGroup.extend(s)
return seriesGroup
def mapSeries(requestContext, seriesList, mapNode):
"""
Takes a seriesList and maps it to a list of sub-seriesList. Each sub-seriesList has the
given mapNode in common.
Example:
.. code-block:: none
map(servers.*.cpu.*,1) =>
[
servers.server1.cpu.*,
servers.server2.cpu.*,
...
servers.serverN.cpu.*
]
"""
metaSeries = {}
keys = []
for series in seriesList:
key = series.name.split(".")[mapNode]
if key not in metaSeries:
metaSeries[key] = [series]
keys.append(key)
else:
metaSeries[key].append(series)
return [ metaSeries[key] for key in keys ]
def reduceSeries(requestContext, seriesLists, reduceFunction, reduceNode, *reduceMatchers):
"""
Takes a list of seriesLists and reduces it to a list of series by means of the reduceFunction.
Reduction is performed by matching the reduceNode in each series against the list of
reduceMatchers. The each series is then passed to the reduceFunction as arguments in the order
given by reduceMatchers. The reduceFunction should yield a single series.
Example:
.. code-block:: none
reduce(map(servers.*.disk.*,1),3,"asPercent","bytes_used","total_bytes") =>
asPercent(servers.server1.disk.bytes_used,servers.server1.disk.total_bytes),
asPercent(servers.server2.disk.bytes_used,servers.server2.disk.total_bytes),
...
asPercent(servers.serverN.disk.bytes_used,servers.serverN.disk.total_bytes)
The resulting list of series are aliased so that they can easily be nested in other functions.
In the above example, the resulting series names would become:
.. code-block:: none
servers.server1.disk.reduce.asPercent,
servers.server2.disk.reduce.asPercent,
...
servers.serverN.disk.reduce.asPercent
"""
metaSeries = {}
keys = []
for seriesList in seriesLists:
for series in seriesList:
nodes = series.name.split('.')
node = nodes[reduceNode]
reduceSeriesName = '.'.join(nodes[0:reduceNode]) + '.reduce.' + reduceFunction
if node in reduceMatchers:
if reduceSeriesName not in metaSeries:
metaSeries[reduceSeriesName] = [None] * len(reduceMatchers)
keys.append(reduceSeriesName)
i = reduceMatchers.index(node)
metaSeries[reduceSeriesName][i] = series
for key in keys:
metaSeries[key] = SeriesFunctions[reduceFunction](requestContext,metaSeries[key])[0]
metaSeries[key].name = key
return [ metaSeries[key] for key in keys ]
def groupByNode(requestContext, seriesList, nodeNum, callback):
"""
Takes a serieslist and maps a callback to subgroups within as defined by a common node
.. code-block:: none
&target=groupByNode(ganglia.by-function.*.*.cpu.load5,2,"sumSeries")
Would return multiple series which are each the result of applying the "sumSeries" function
to groups joined on the second node (0 indexed) resulting in a list of targets like
sumSeries(ganglia.by-function.server1.*.cpu.load5),sumSeries(ganglia.by-function.server2.*.cpu.load5),...
"""
metaSeries = {}
keys = []
for series in seriesList:
key = series.name.split(".")[nodeNum]
if key not in metaSeries.keys():
metaSeries[key] = [series]
keys.append(key)
else:
metaSeries[key].append(series)
for key in metaSeries.keys():
metaSeries[key] = SeriesFunctions[callback](requestContext,
metaSeries[key])[0]
metaSeries[key].name = key
return [ metaSeries[key] for key in keys ]
def exclude(requestContext, seriesList, pattern):
"""
Takes a metric or a wildcard seriesList, followed by a regular expression
in double quotes. Excludes metrics that match the regular expression.
Example:
.. code-block:: none
&target=exclude(servers*.instance*.threads.busy,"server02")
"""
regex = re.compile(pattern)
return [s for s in seriesList if not regex.search(s.name)]
def grep(requestContext, seriesList, pattern):
"""
Takes a metric or a wildcard seriesList, followed by a regular expression
in double quotes. Excludes metrics that don't match the regular expression.
Example:
.. code-block:: none
&target=grep(servers*.instance*.threads.busy,"server02")
"""
regex = re.compile(pattern)
return [s for s in seriesList if regex.search(s.name)]
def smartSummarize(requestContext, seriesList, intervalString, func='sum', alignToFrom=False):
"""
Smarter experimental version of summarize.
The alignToFrom parameter has been deprecated, it no longer has any effect.
Alignment happens automatically for days, hours, and minutes.
"""
if alignToFrom:
log.info("Deprecated parameter 'alignToFrom' is being ignored.")
results = []
delta = parseTimeOffset(intervalString)
interval = delta.seconds + (delta.days * 86400)
# Adjust the start time to fit an entire day for intervals >= 1 day
requestContext = requestContext.copy()
s = requestContext['startTime']
if interval >= DAY:
requestContext['startTime'] = datetime(s.year, s.month, s.day)
elif interval >= HOUR:
requestContext['startTime'] = datetime(s.year, s.month, s.day, s.hour)
elif interval >= MINUTE:
requestContext['startTime'] = datetime(s.year, s.month, s.day, s.hour, s.minute)
for i,series in enumerate(seriesList):
# XXX: breaks with summarize(metric.{a,b})
# each series.pathExpression == metric.{a,b}
newSeries = evaluateTarget(requestContext, series.pathExpression)[0]
series[0:len(series)] = newSeries
series.start = newSeries.start
series.end = newSeries.end
series.step = newSeries.step
for series in seriesList:
buckets = {} # { timestamp: [values] }
timestamps = range( int(series.start), int(series.end), int(series.step) )
datapoints = zip(timestamps, series)
# Populate buckets
for (timestamp, value) in datapoints:
bucketInterval = int((timestamp - series.start) / interval)
if bucketInterval not in buckets:
buckets[bucketInterval] = []
if value is not None:
buckets[bucketInterval].append(value)
newValues = []
for timestamp in range(series.start, series.end, interval):
bucketInterval = int((timestamp - series.start) / interval)
bucket = buckets.get(bucketInterval, [])
if bucket:
if func == 'avg':
newValues.append( float(sum(bucket)) / float(len(bucket)) )
elif func == 'last':
newValues.append( bucket[len(bucket)-1] )
elif func == 'max':
newValues.append( max(bucket) )
elif func == 'min':
newValues.append( min(bucket) )
else:
newValues.append( sum(bucket) )
else:
newValues.append( None )
newName = "smartSummarize(%s, \"%s\", \"%s\")" % (series.name, intervalString, func)
alignedEnd = series.start + (bucketInterval * interval) + interval
newSeries = TimeSeries(newName, series.start, alignedEnd, interval, newValues)
newSeries.pathExpression = newName
results.append(newSeries)
return results
def summarize(requestContext, seriesList, intervalString, func='sum', alignToFrom=False):
"""
Summarize the data into interval buckets of a certain size.
By default, the contents of each interval bucket are summed together. This is
useful for counters where each increment represents a discrete event and
retrieving a "per X" value requires summing all the events in that interval.
Specifying 'avg' instead will return the mean for each bucket, which can be more
useful when the value is a gauge that represents a certain value in time.
'max', 'min' or 'last' can also be specified.
By default, buckets are caculated by rounding to the nearest interval. This
works well for intervals smaller than a day. For example, 22:32 will end up
in the bucket 22:00-23:00 when the interval=1hour.
Passing alignToFrom=true will instead create buckets starting at the from
time. In this case, the bucket for 22:32 depends on the from time. If
from=6:30 then the 1hour bucket for 22:32 is 22:30-23:30.
Example:
.. code-block:: none
&target=summarize(counter.errors, "1hour") # total errors per hour
&target=summarize(nonNegativeDerivative(gauge.num_users), "1week") # new users per week
&target=summarize(queue.size, "1hour", "avg") # average queue size per hour
&target=summarize(queue.size, "1hour", "max") # maximum queue size during each hour
&target=summarize(metric, "13week", "avg", true)&from=midnight+20100101 # 2010 Q1-4
"""
results = []
delta = parseTimeOffset(intervalString)
interval = delta.seconds + (delta.days * 86400)
for series in seriesList:
buckets = {}
timestamps = range( int(series.start), int(series.end), int(series.step) )
datapoints = zip(timestamps, series)
for (timestamp, value) in datapoints:
if alignToFrom:
bucketInterval = int((timestamp - series.start) / interval)
else:
bucketInterval = timestamp - (timestamp % interval)
if bucketInterval not in buckets:
buckets[bucketInterval] = []
if value is not None:
buckets[bucketInterval].append(value)
if alignToFrom:
newStart = series.start
newEnd = series.end
else:
newStart = series.start - (series.start % interval)
newEnd = series.end - (series.end % interval) + interval
newValues = []
for timestamp in range(newStart, newEnd, interval):
if alignToFrom:
newEnd = timestamp
bucketInterval = int((timestamp - series.start) / interval)
else:
bucketInterval = timestamp - (timestamp % interval)
bucket = buckets.get(bucketInterval, [])
if bucket:
if func == 'avg':
newValues.append( float(sum(bucket)) / float(len(bucket)) )
elif func == 'last':
newValues.append( bucket[len(bucket)-1] )
elif func == 'max':
newValues.append( max(bucket) )
elif func == 'min':
newValues.append( min(bucket) )
else:
newValues.append( sum(bucket) )
else:
newValues.append( None )
if alignToFrom:
newEnd += interval
newName = "summarize(%s, \"%s\", \"%s\"%s)" % (series.name, intervalString, func, alignToFrom and ", true" or "")
newSeries = TimeSeries(newName, newStart, newEnd, interval, newValues)
newSeries.pathExpression = newName
results.append(newSeries)
return results
def hitcount(requestContext, seriesList, intervalString, alignToInterval = False):
"""
Estimate hit counts from a list of time series.
This function assumes the values in each time series represent
hits per second. It calculates hits per some larger interval
such as per day or per hour. This function is like summarize(),
except that it compensates automatically for different time scales
(so that a similar graph results from using either fine-grained
or coarse-grained records) and handles rarely-occurring events
gracefully.
"""
results = []
delta = parseTimeOffset(intervalString)
interval = int(delta.seconds + (delta.days * 86400))
if alignToInterval:
requestContext = requestContext.copy()
s = requestContext['startTime']
if interval >= DAY:
requestContext['startTime'] = datetime(s.year, s.month, s.day)
elif interval >= HOUR:
requestContext['startTime'] = datetime(s.year, s.month, s.day, s.hour)
elif interval >= MINUTE:
requestContext['startTime'] = datetime(s.year, s.month, s.day, s.hour, s.minute)
for i,series in enumerate(seriesList):
newSeries = evaluateTarget(requestContext, series.pathExpression)[0]
intervalCount = int((series.end - series.start) / interval)
series[0:len(series)] = newSeries
series.start = newSeries.start
series.end = newSeries.start + (intervalCount * interval) + interval
series.step = newSeries.step
for series in seriesList:
length = len(series)
step = int(series.step)
bucket_count = int(math.ceil(float(series.end - series.start) / interval))
buckets = [[] for _ in range(bucket_count)]
newStart = int(series.end - bucket_count * interval)
for i, value in enumerate(series):
if value is None:
continue
start_time = int(series.start + i * step)
start_bucket, start_mod = divmod(start_time - newStart, interval)
end_time = start_time + step
end_bucket, end_mod = divmod(end_time - newStart, interval)
if end_bucket >= bucket_count:
end_bucket = bucket_count - 1
end_mod = interval
if start_bucket == end_bucket:
# All of the hits go to a single bucket.
if start_bucket >= 0:
buckets[start_bucket].append(value * (end_mod - start_mod))
else:
# Spread the hits among 2 or more buckets.
if start_bucket >= 0:
buckets[start_bucket].append(value * (interval - start_mod))
hits_per_bucket = value * interval
for j in range(start_bucket + 1, end_bucket):
buckets[j].append(hits_per_bucket)
if end_mod > 0:
buckets[end_bucket].append(value * end_mod)
newValues = []
for bucket in buckets:
if bucket:
newValues.append( sum(bucket) )
else:
newValues.append(None)
newName = 'hitcount(%s, "%s"%s)' % (series.name, intervalString, alignToInterval and ", true" or "")
newSeries = TimeSeries(newName, newStart, series.end, interval, newValues)
newSeries.pathExpression = newName
results.append(newSeries)
return results
def timeFunction(requestContext, name):
"""
Short Alias: time()
Just returns the timestamp for each X value. T
Example:
.. code-block:: none
&target=time("The.time.series")
This would create a series named "The.time.series" that contains in Y the same
value (in seconds) as X.
"""
step = 60
delta = timedelta(seconds=step)
when = requestContext["startTime"]
values = []
while when < requestContext["endTime"]:
values.append(time.mktime(when.timetuple()))
when += delta
series = TimeSeries(name,
int(time.mktime(requestContext["startTime"].timetuple())),
int(time.mktime(requestContext["endTime"].timetuple())),
step, values)
series.pathExpression = name
return [series]
def sinFunction(requestContext, name, amplitude=1):
"""
Short Alias: sin()
Just returns the sine of the current time. The optional amplitude parameter
changes the amplitude of the wave.
Example:
.. code-block:: none
&target=sin("The.time.series", 2)
This would create a series named "The.time.series" that contains sin(x)*2.
"""
step = 60
delta = timedelta(seconds=step)
when = requestContext["startTime"]
values = []
while when < requestContext["endTime"]:
values.append(math.sin(time.mktime(when.timetuple()))*amplitude)
when += delta
return [TimeSeries(name,
int(time.mktime(requestContext["startTime"].timetuple())),
int(time.mktime(requestContext["endTime"].timetuple())),
step, values)]
def randomWalkFunction(requestContext, name):
"""
Short Alias: randomWalk()
Returns a random walk starting at 0. This is great for testing when there is
no real data in whisper.
Example:
.. code-block:: none
&target=randomWalk("The.time.series")
This would create a series named "The.time.series" that contains points where
x(t) == x(t-1)+random()-0.5, and x(0) == 0.
"""
step = 60
delta = timedelta(seconds=step)
when = requestContext["startTime"]
values = []
current = 0
while when < requestContext["endTime"]:
values.append(current)
current += random.random() - 0.5
when += delta
return [TimeSeries(name,
int(time.mktime(requestContext["startTime"].timetuple())),
int(time.mktime(requestContext["endTime"].timetuple())),
step, values)]
def events(requestContext, *tags):
"""
Returns the number of events at this point in time. Usable with
drawAsInfinite.
Example:
.. code-block:: none
&target=events("tag-one", "tag-two")
&target=events("*")
Returns all events tagged as "tag-one" and "tag-two" and the second one
returns all events.
"""
def to_epoch(datetime_object):
return int(time.mktime(datetime_object.timetuple()))
step = 1
name = "events(" + ", ".join(tags) + ")"
if tags == ("*",):
tags = None
# Django returns database timestamps in timezone-ignorant datetime objects
# so we use epoch seconds and do the conversion ourselves
start_timestamp = to_epoch(requestContext["startTime"])
start_timestamp = start_timestamp - start_timestamp % step
end_timestamp = to_epoch(requestContext["endTime"])
end_timestamp = end_timestamp - end_timestamp % step
points = (end_timestamp - start_timestamp)/step
events = models.Event.find_events(datetime.fromtimestamp(start_timestamp),
datetime.fromtimestamp(end_timestamp),
tags=tags)
values = [None] * points
for event in events:
event_timestamp = to_epoch(event.when)
value_offset = (event_timestamp - start_timestamp)/step
if values[value_offset] is None:
values[value_offset] = 1
else:
values[value_offset] += 1
result_series = TimeSeries(name, start_timestamp, end_timestamp, step, values, 'sum')
result_series.pathExpression = name
return [result_series]
def pieAverage(requestContext, series):
return safeDiv(safeSum(series),safeLen(series))
def pieMaximum(requestContext, series):
return max(series)
def pieMinimum(requestContext, series):
return min(series)
PieFunctions = {
'average' : pieAverage,
'maximum' : pieMaximum,
'minimum' : pieMinimum,
}
SeriesFunctions = {
# Combine functions
'sumSeries' : sumSeries,
'sum' : sumSeries,
'multiplySeries' : multiplySeries,
'averageSeries' : averageSeries,
'stddevSeries' : stddevSeries,
'avg' : averageSeries,
'sumSeriesWithWildcards': sumSeriesWithWildcards,
'averageSeriesWithWildcards': averageSeriesWithWildcards,
'minSeries' : minSeries,
'maxSeries' : maxSeries,
'rangeOfSeries': rangeOfSeries,
'percentileOfSeries': percentileOfSeries,
'countSeries': countSeries,
'weightedAverage': weightedAverage,
# Transform functions
'scale' : scale,
'invert' : invert,
'scaleToSeconds' : scaleToSeconds,
'offset' : offset,
'offsetToZero' : offsetToZero,
'derivative' : derivative,
'perSecond' : perSecond,
'integral' : integral,
'percentileOfSeries': percentileOfSeries,
'nonNegativeDerivative' : nonNegativeDerivative,
'log' : logarithm,
'timeStack': timeStack,
'timeShift': timeShift,
'summarize' : summarize,
'smartSummarize' : smartSummarize,
'hitcount' : hitcount,
'absolute' : absolute,
# Calculate functions
'movingAverage' : movingAverage,
'movingMedian' : movingMedian,
'stdev' : stdev,
'holtWintersForecast': holtWintersForecast,
'holtWintersConfidenceBands': holtWintersConfidenceBands,
'holtWintersConfidenceArea': holtWintersConfidenceArea,
'holtWintersAberration': holtWintersAberration,
'asPercent' : asPercent,
'pct' : asPercent,
'diffSeries' : diffSeries,
'divideSeries' : divideSeries,
# Series Filter functions
'mostDeviant' : mostDeviant,
'highestCurrent' : highestCurrent,
'lowestCurrent' : lowestCurrent,
'highestMax' : highestMax,
'currentAbove' : currentAbove,
'currentBelow' : currentBelow,
'highestAverage' : highestAverage,
'lowestAverage' : lowestAverage,
'averageAbove' : averageAbove,
'averageBelow' : averageBelow,
'maximumAbove' : maximumAbove,
'minimumAbove' : minimumAbove,
'maximumBelow' : maximumBelow,
'nPercentile' : nPercentile,
'limit' : limit,
'sortByTotal' : sortByTotal,
'sortByName' : sortByName,
'averageOutsidePercentile' : averageOutsidePercentile,
'removeBetweenPercentile' : removeBetweenPercentile,
'sortByMaxima' : sortByMaxima,
'sortByMinima' : sortByMinima,
'sortByName' : sortByName,
'useSeriesAbove': useSeriesAbove,
'exclude' : exclude,
# Data Filter functions
'removeAbovePercentile' : removeAbovePercentile,
'removeAboveValue' : removeAboveValue,
'removeBelowPercentile' : removeBelowPercentile,
'removeBelowValue' : removeBelowValue,
# Special functions
'legendValue' : legendValue,
'alias' : alias,
'aliasSub' : aliasSub,
'aliasByNode' : aliasByNode,
'aliasByMetric' : aliasByMetric,
'cactiStyle' : cactiStyle,
'color' : color,
'alpha' : alpha,
'cumulative' : cumulative,
'consolidateBy' : consolidateBy,
'keepLastValue' : keepLastValue,
'drawAsInfinite' : drawAsInfinite,
'secondYAxis': secondYAxis,
'lineWidth' : lineWidth,
'dashed' : dashed,
'substr' : substr,
'group' : group,
'map': mapSeries,
'reduce': reduceSeries,
'groupByNode' : groupByNode,
'constantLine' : constantLine,
'stacked' : stacked,
'areaBetween' : areaBetween,
'threshold' : threshold,
'transformNull' : transformNull,
'isNonNull' : isNonNull,
'identity': identity,
'aggregateLine' : aggregateLine,
'upperBound' : upperBound,
'lowerBound' : lowerBound,
# test functions
'time': timeFunction,
"sin": sinFunction,
"randomWalk": randomWalkFunction,
'timeFunction': timeFunction,
"sinFunction": sinFunction,
"randomWalkFunction": randomWalkFunction,
#events
'events': events,
}
#Avoid import circularity
if not environ.get('READTHEDOCS'):
from graphite.render.evaluator import evaluateTarget
|
apache-2.0
|
firstthumb/Bomberman
|
core/src/main/java/net/javaci/mobile/bomberman/core/mediator/LobbyScreenMediator.java
|
696
|
package net.javaci.mobile.bomberman.core.mediator;
import net.javaci.mobile.bomberman.core.BomberManGame;
import net.javaci.mobile.bomberman.core.view.BomberManScreen;
import net.javaci.mobile.bomberman.core.view.LobbyScreen;
public class LobbyScreenMediator extends BomberManMediator {
private LobbyScreen lobbyScreen;
public LobbyScreenMediator(BomberManGame game) {
super(game);
}
@Override
public BomberManScreen createScreen() {
this.screen = new LobbyScreen(this.game, this);
this.lobbyScreen = (LobbyScreen) this.screen;
return screen;
}
@Override
protected void onScreenShow() {
super.onScreenShow();
}
}
|
apache-2.0
|
noglows/conception-calculator
|
spec/controllers/api_controller_spec.rb
|
6855
|
require 'rails_helper'
require 'pry'
RSpec.describe ApiController, type: :controller do
before :each do
request.env["HTTP_ACCEPT"] = 'application/json'
end
describe "GET 'on_this_day'" do
let(:event_params) do
{
date: "3/26/1991",
type: "event"
}
end
let(:song_params) do
{
date: "3/29/1986",
type: "song"
}
end
let(:movie_params) do
{
date: "1/5/1986",
type: "movie"
}
end
let(:weather_params) do
{
date: "3/13/1990",
type: "weather"
}
end
let(:null_song) do
{
date: "1/5/1986",
type: "song"
}
end
let(:null_movie) do
{
date: "1/6/1986",
type: "movie"
}
end
let(:null_event) do
{
date: "1/2/1986",
type: "event"
}
end
let(:null_weather) do
{
date: "5/14/1990",
type: "weather"
}
end
it "returns expected event for a given day" do
get :on_this_day, event_params, {:format => :json}
expect(JSON.parse(response.body).length).to eql 3
end
it "returns expected song for a given day" do
get :on_this_day, song_params, {:format => :json}
expect(JSON.parse(response.body)[0]["artist"]).to eq "Falco"
end
it "returns expected movie for a given day" do
get :on_this_day, movie_params, {:format => :json}
expect(JSON.parse(response.body)[0]["title"]).to eq "Rocky IV"
end
it "returns expected weather for a given day" do
get :on_this_day, weather_params, {:format => :json}
expect(JSON.parse(response.body)[0]["message"]).to eq "A tornado caused $2.5M of damage in Nebraska."
end
it "handles a null movie day as expected" do
get :on_this_day, null_movie, {:format => :json}
expect(JSON.parse(response.body)[0]).to eq nil
end
it "handles a null song day as expected" do
get :on_this_day, null_song, {:format => :json}
expect(JSON.parse(response.body)[0]).to eq nil
end
it "handles a null event day as expected" do
get :on_this_day, null_event, {:format => :json}
expect(JSON.parse(response.body)[0]).to eq nil
end
it "handles a null weather day as expected" do
get :on_this_day, null_weather, {:format => :json}
expect(JSON.parse(response.body)[0]).to eq nil
end
end
describe "GET 'on_this_day_range'" do
let(:event_range_params) do
{
start: "1/5/1986",
end: "1/20/1986",
type: "event"
}
end
let(:song_range_params) do
{
start: "1/5/1986",
end: "1/20/1986",
type: "song"
}
end
let(:movie_range_params) do
{
start: "1/5/1986",
end: "1/20/1986",
type: "movie"
}
end
let(:weather_range_params) do
{
start: "6/1/1990",
end: "7/1/1990",
type: "weather"
}
end
let(:null_event_range) do
{
start: "1/2/1986",
end: "1/8/1986",
type: "event"
}
end
let(:null_song_range) do
{
start: "1/5/1986",
end: "1/10/1986",
type: "song"
}
end
let(:null_movie_range) do
{
start: "1/6/1986",
end: "1/11/1986",
type: "movie"
}
end
let(:null_weather_range) do
{
start: "1/6/1986",
end: "1/11/1986",
type: "weather"
}
end
it "returns the expected events for a given range" do
get :on_this_day_range, event_range_params
expect(JSON.parse(response.body).length).to eq 6
end
it "returns the expected songs for a given range" do
get :on_this_day_range, song_range_params
expect(JSON.parse(response.body).length).to eq 2
end
it "returns the expected movies for a given range" do
get :on_this_day_range, movie_range_params
expect(JSON.parse(response.body).length).to eq 3
end
it "returns the expected weather events for a given range" do
get :on_this_day_range, weather_range_params
expect(JSON.parse(response.body).length).to eq 11
end
it "returns a null response for a range with no events" do
get :on_this_day_range, null_event_range
expect(JSON.parse(response.body)).to eq []
end
it "returns a null response for a range with no songs" do
get :on_this_day_range, null_song_range
expect(JSON.parse(response.body)).to eq []
end
it "returns a null response for a range with no events" do
get :on_this_day_range, null_movie_range
expect(JSON.parse(response.body)).to eq []
end
it "returns a null response for a range with no events" do
get :on_this_day_range, null_weather_range
expect(JSON.parse(response.body)).to eq []
end
end
describe "GET 'conception_range'" do
let(:params) do
{
birthday: "3/21/1991"
}
end
let(:early_params) do
{
unusual: "true",
birthday: "3/21/1991",
number: 2,
modifier: "early"
}
end
let(:late_params) do
{
unusual: "true",
birthday: "3/21/1991",
number: 2,
modifier: "late"
}
end
it "returns a conception range for a normal birthday" do
get :conception_range, params
expect(JSON.parse(response.body)[0]).to eq "1990-06-25"
expect(JSON.parse(response.body)[1]).to eq "1990-07-01"
end
it "returns a conception range for an early birthday" do
get :conception_range, early_params
expect(JSON.parse(response.body)[0]).to eq "1990-07-09"
expect(JSON.parse(response.body)[1]).to eq "1990-07-15"
end
it "returns a conception range for a late birthday" do
get :conception_range, late_params
expect(JSON.parse(response.body)[0]).to eq "1990-06-11"
expect(JSON.parse(response.body)[1]).to eq "1990-06-17"
end
end
describe "GET 'get_youtube_id'" do
let(:movie_params) do
{
type: "movie",
title: "Lars and the Real Girl"
}
end
let(:song_params) do
{
type: "song",
title: "Your arms around me",
artist: "Jens Lekman"
}
end
it "returns correct video id for movie input" do
get :get_youtube_id, movie_params
expect(JSON.parse(response.body)[0]).to eq "XNcs9DrKYRU"
end
it "returns correct video id for movie input" do
get :get_youtube_id, song_params
expect(JSON.parse(response.body)[0]).to eq "NIwIAbcLFhI"
end
end
describe "GET 'old_movie'" do
it "gets a movie from before 1960" do
get :get_old_movie, year: 1957, code: "19570000"
expect(JSON.parse(response.body)[0][0]["title"]).to eq "The Bridge on the River Kwai"
end
end
end
|
apache-2.0
|
progress/progressNEXT
|
NextWeb/public/stylesheets/style.css
|
1118
|
body {
/*padding: 50px;*/
/*max-width:254px;
max-height: 318px;*/
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
div {
width:254px;
position: relative;
height: 318px;
}
div.banner {
background: url('/images/badge.png') no-repeat;
}
section.info {
position: absolute;
top : 100px;
}
h1{
padding: 10px;
text-transform: uppercase;
font-weight: 400;
}
ul#list {
list-style :none;
padding: 5px;
}
li{
border: 1px solid #ddd;
padding: 10px;
margin: 5px;
background-color: #fff;
border-color: #ddd;
border-width: 1px;
border-radius: 4px;
-webkit-box-shadow: none;
background-color:#777;
font-size: 75%;
font-weight: 700;
line-height: 1;
color: #fff;
font-size:15px;
}
section.info h1 {
padding-left: 15px;
padding-bottom: 0px;
padding-top: 0px;
margin-top: 0px;
margin-bottom: 0px;
}
section.info h3 {
text-transform: uppercase;
font-size: 15px;
padding-left: 15px;
margin-top: 5px;
padding-bottom: 0px;
padding-top: 0px;
}
img{
width:70px;
position: absolute;
bottom: 8px;
right:20px;
}
a {
color: #00B7FF;
}
|
apache-2.0
|
commitd/rejux
|
src/main/java/software/committed/rejux/impl/AbstractState.java
|
621
|
package software.committed.rejux.impl;
import software.committed.rejux.interfaces.State;
public class AbstractState<S> implements State<S> {
private final Class<S> stateClass;
protected S state;
public AbstractState(final Class<S> clazz, final S initial) {
stateClass = clazz;
state = initial;
}
@Override
public Class<S> getType() {
return stateClass;
}
protected boolean setState(final S newState) {
if (newState != null && !newState.equals(state)) {
state = newState;
return true;
}
return false;
}
@Override
public S state() {
return state;
}
}
|
apache-2.0
|
EricssonResearch/scott-eu
|
lyo-services/webapp-whc/src/main/java/se/ericsson/cf/scott/sandbox/whc/xtra/managers/MqttManager.java
|
1668
|
package se.ericsson.cf.scott.sandbox.whc.xtra.managers;
import eu.scott.warehouse.lib.LoggingMqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.ericsson.cf.scott.sandbox.whc.xtra.AdaptorHelper;
import se.ericsson.cf.scott.sandbox.whc.xtra.WhcConfig;
public class MqttManager {
private final static Logger log = LoggerFactory.getLogger(MqttManager.class);
private static MqttClient mqttClient;
public static MqttClient initMqttClient() {
try {
final String mqttBroker = AdaptorHelper.p(WhcConfig.MQTT_TOPIC_PROP);
mqttClient = new MqttClient(mqttBroker, AdaptorHelper.getMqttClientId());
final MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);
mqttClient.setCallback(new LoggingMqttCallback());
// TODO Andrew@2018-03-13: set highest QoS
mqttClient.connect(mqttConnectOptions);
return mqttClient;
} catch (MqttException e) {
log.error("MQTT connection failed", e);
// TODO Andrew@2018-07-30: exception strategy
throw new IllegalStateException(e);
}
}
public static void disconnect() {
if(mqttClient != null) {
try {
mqttClient.disconnect();
} catch (MqttException e) {
log.warn("Unable to cleanly terminate the MQTT connection: ", e);
}
}
}
}
|
apache-2.0
|
Bersaelor/D2
|
iOS_app/Classes/Native/mscorlib_System_Comparison_1_gen3861043953MethodDeclarations.h
|
1825
|
#pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include <assert.h>
#include <exception>
#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_Comparison_1_gen2887177558MethodDeclarations.h"
// System.Void System.Comparison`1<UnityEngine.EventSystems.EventTrigger/Entry>::.ctor(System.Object,System.IntPtr)
#define Comparison_1__ctor_m842028803(__this, ___object0, ___method1, method) (( void (*) (Comparison_1_t3861043953 *, Il2CppObject *, IntPtr_t, const MethodInfo*))Comparison_1__ctor_m487232819_gshared)(__this, ___object0, ___method1, method)
// System.Int32 System.Comparison`1<UnityEngine.EventSystems.EventTrigger/Entry>::Invoke(T,T)
#define Comparison_1_Invoke_m1454987933(__this, ___x0, ___y1, method) (( int32_t (*) (Comparison_1_t3861043953 *, Entry_t849715470 *, Entry_t849715470 *, const MethodInfo*))Comparison_1_Invoke_m1888033133_gshared)(__this, ___x0, ___y1, method)
// System.IAsyncResult System.Comparison`1<UnityEngine.EventSystems.EventTrigger/Entry>::BeginInvoke(T,T,System.AsyncCallback,System.Object)
#define Comparison_1_BeginInvoke_m1889704214(__this, ___x0, ___y1, ___callback2, ___object3, method) (( Il2CppObject * (*) (Comparison_1_t3861043953 *, Entry_t849715470 *, Entry_t849715470 *, AsyncCallback_t1369114871 *, Il2CppObject *, const MethodInfo*))Comparison_1_BeginInvoke_m3177996774_gshared)(__this, ___x0, ___y1, ___callback2, ___object3, method)
// System.Int32 System.Comparison`1<UnityEngine.EventSystems.EventTrigger/Entry>::EndInvoke(System.IAsyncResult)
#define Comparison_1_EndInvoke_m946605743(__this, ___result0, method) (( int32_t (*) (Comparison_1_t3861043953 *, Il2CppObject *, const MethodInfo*))Comparison_1_EndInvoke_m651541983_gshared)(__this, ___result0, method)
|
apache-2.0
|
nghiant2710/base-images
|
balena-base-images/node/rpi/alpine/3.10/15.7.0/build/Dockerfile
|
2948
|
# AUTOGENERATED FILE
FROM balenalib/rpi-alpine:3.10-build
ENV NODE_VERSION 15.7.0
ENV YARN_VERSION 1.22.4
# Install dependencies
RUN apk add --no-cache libgcc libstdc++ libuv \
&& apk add --no-cache libssl1.0 || apk add --no-cache libssl1.1
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/node/v$NODE_VERSION/node-v$NODE_VERSION-linux-alpine-armv6hf.tar.gz" \
&& echo "332e5d36dd483b44596c5aef55863dbf60c4cd9dff04cbdae759798f508c22ea node-v$NODE_VERSION-linux-alpine-armv6hf.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-alpine-armv6hf.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-alpine-armv6hf.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v6 \nOS: Alpine Linux 3.10 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.7.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh
|
apache-2.0
|
erikjandevries/ConfigLM17ML
|
extra/prep-TheanoForGPU.sh
|
30
|
cp .theanorc_gpu ~/.theanorc
|
apache-2.0
|
dheraclio/dependometer
|
dependometer-core/src/main/java/com/valtech/source/dependometer/app/controller/pack/DispatcherPackageCycleCollectedEvent.java
|
648
|
// GENERATED FILE!
// VERSION-INFO: com.valtech.source.ag.evf.codegen.Dispatcher
// DATE/TIME-INFO: 17.05.04 09:36:44
package com.valtech.source.dependometer.app.controller.pack;
import com.valtech.source.ag.evf.Dispatcher;
import com.valtech.source.ag.evf.EventIf;
final class DispatcherPackageCycleCollectedEvent extends Dispatcher
{
protected void dispatch(Object handler, EventIf event)
{
assert handler != null;
assert event != null;
((HandlePackageCycleCollectedEventIf)handler)
.handleEvent((com.valtech.source.dependometer.app.controller.pack.PackageCycleCollectedEvent)event);
}
}
|
apache-2.0
|
Tpo76/centreon-plugins
|
notification/highsms/plugin.pm
|
1227
|
#
# Copyright 2021 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# 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 notification::highsms::plugin;
use strict;
use warnings;
use base qw(centreon::plugins::script_simple);
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '0.1';
%{$self->{modes}} = (
'alert' => 'notification::highsms::mode::alert',
);
return $self;
}
1;
__END__
=head1 PLUGIN DESCRIPTION
Send HighSMS notifications.
=cut
|
apache-2.0
|
unimatrix02/latunyi-framework
|
system/includes/debug.inc.php
|
8463
|
<?php
/**
* Debug library
*
* @author Raymond van Velzen <raymond@latunyi.com>
* @package LatunyiFramework
**/
/**
* pr
*
* Function to print anything in a convenient way
* Will print any string/number/etc, array, or object.
*
* @param mixed $x Anything
* @param string $descr Description to print above output, optional
* @return void
**/
function pr($x, $descr = '')
{
if (is_object($x)) {
printobj($x, $descr);
} elseif(is_array($x)) {
printarr($x, $descr);
} else {
if (is_string($x) && substr($x, 0, 5) == '<?xml')
{
printxml($x, $descr);
}
else
{
printbr($x, $descr);
}
}
}
/**
* prd
*
* Print something (d)irectly to the screen, using pr().
* Will flush (not destroy) output buffer.
*
* @param mixed $x Anything
* @return void
**/
function prd($x, $descr = '')
{
pr($x, $descr);
ob_flush();
flush();
}
/**
* prx
*
* Print something using pr() and exit.
*
* @param mixed $x Anything
* @param string $descr Description to print above output, optional
* @return void
**/
function prx($x, $descr = '')
{
pr($x, $descr);
exit;
}
/**
* printarr
*
* Print an array
*
* @param mixed $a Any array
* @param string $descr Description to print above output, optional
* @return void
**/
function printarr($a, $descr = '')
{
if (!is_array($a))
{
ob_start();
if (!empty($descr))
{
printbr('<b>' . $descr . '</b>');
}
var_dump($a);
$str = ob_get_clean();
printNicely($str);
} else {
ob_start();
print '<pre>';
if (!empty($descr))
{
print('<b>' . $descr . '</b>' . "\n");
}
print_r($a);
print '</pre>';
$str = ob_get_clean();
printNicely($str);
}
}
/**
* printobj
*
* Print an object
*
* @param mixed $a Any object
* @param string $descr Description to print above output, optional
* @return void
**/
function printobj($a, $descr = '')
{
ob_start();
print '<pre>';
if (!empty($descr))
{
print('<b>' . $descr . '</b>' . "\n");
}
print_r($a);
print '</pre>';
$str = ob_get_clean();
printNicely($str);
}
/**
* printbr
*
* Print something with a HTML line break. Obsolete; use pr() instead.
*
* @param string $text Any array
* @param string $descr Description to print before output, optional
* @return void
**/
function printbr ($text = '', $descr = '')
{
printNicely($descr . ' ' . $text);
}
// -----------------------------------------------------------------------
/**
* printNicely
*
* Print some text in a box with fixed-width font
*
* @param string $text Any text
* @return void
**/
function printNicely($str)
{
print '<div style="font: normal 13px Courier New !important; border: 1px solid #CCC; background-color: #EEE; padding: 10px; margin: 10px; text-align: left !important;">';
print '<pre>' . trim($str) . '</pre>';
print '</div>';
}
// -----------------------------------------------------------------------
/**
* prg
*
* Print GET array
*
* @return void
**/
function prg()
{
printarr($_GET, '$_GET:');
}
/**
* prg
*
* Print GET array and exit
*
* @return void
**/
function prgx()
{
prg();
exit;
}
// -----------------------------------------------------------------------
/**
* prp
*
* Print POST array
*
* @return void
**/
function prp()
{
printarr($_POST, '$_POST:');
}
/**
* prpx
*
* Print POST array and exit
*
* @return void
**/
function prpx()
{
prp();
exit;
}
// -----------------------------------------------------------------------
/**
* prs
*
* Print SESSION
*
* @return void
**/
function prs($key = null)
{
if (isset($key))
{
if (isset($_SESSION[$key]))
{
pr($_SESSION[$key]);
}
else
{
pr('Key "' . $key . '" not found in SESSION object.');
}
}
else
{
printarr($_SESSION, '$_SESSION:');
}
}
/**
* prsx
*
* Print SESSION and exit
*
* @return void
**/
function prsx($key = null)
{
prs($key);
exit;
}
// -----------------------------------------------------------------------
/**
* prc
*
* Print COOKIE
*
* @return void
**/
function prc()
{
printarr($_COOKIE);
}
/**
* prcx
*
* Print COOKIE and exit
*
* @return void
**/
function prcx()
{
prc();
exit;
}
// -----------------------------------------------------------------------
/**
* prsvr
*
* Print SERVER
*
* @return void
**/
function prsvr()
{
printarr($_SERVER, '$_SERVER:');
}
/**
* prsvrx
*
* Print SERVER and exit
*
* @return void
**/
function prsvrx()
{
prsvr();
exit;
}
// -----------------------------------------------------------------------
/**
* prf
*
* Print $_FILES array
*
* @return void
**/
function prf()
{
printarr($_FILES, '$_FILES:');
}
/**
* prfx
*
* Print $_FILES and exit
*
* @return void
**/
function prfx()
{
prf();
exit;
}
// -----------------------------------------------------------------------
/**
* Print ISO date from timestamp
* @param int $ts
*/
function prdt($ts)
{
pr(date('Y-m-d', $ts));
}
/**
* Print ISO date from timestamp and exit
* @param int $ts
*/
function prdtx($ts)
{
prdt($ts);
exit;
}
/**
* prv
*
* Print var_dump
*
* @param mixed $x Some variable
* @return void
**/
function prv($x, $descr = '')
{
ob_start();
if (!empty($descr))
{
print('<b>' . $descr . "</b>\n");
}
var_dump($x);
$str = ob_get_clean();
printNicely($str);
}
/**
* prvx
*
* Print var_dump and exit
*
* @param mixed $x Some variable
* @return void
**/
function prvx($x, $descr = '')
{
prv($x, $descr);
exit;
}
/**
* printxml
*
* Prints XML.
*
* @param mixed $xml Some XML variable
* @return void
**/
function printxml($xml, $descr = '')
{
pr(nl2br(htmlentities($xml)), $descr);
}
// -----------------------------------------------------------------------
/**
* getExecutionTime
*
* Calculates the execution time of a script, depending on start time.
*
* @param float $start Start time, as float
* @return void
**/
function GetExecutionTime($start)
{
//return sprintf('%1.6f', (microtime(true) - $start)) . ' sec';
return (microtime(true) - $start) . ' sec';
}
/**
* GetMemory
*
* Reports the amount of memory used by PHP, wrapper
* on memory_get_usage(). Returns warning if memory_get_usage
* function doesn't exist.
*
* @param string $unit Measure unit: All (default), B, KB, MB
* @return string 'x B', 'x KB', 'x MB';
**/
function GetMemory($unit = 'All')
{
if (!function_exists('memory_get_usage'))
{
return 'Can\'t report memory usage; memory_get_usage is not available.';
}
else
{
$bytes = memory_get_usage(true);
switch ($unit)
{
case 'All':
$kb = number_format( ($bytes / 1024), 2) . ' KB';
$mb = number_format( (($bytes / 1024) / 1024), 2) . ' MB';
return $bytes . ' bytes, ' . $kb . ', ' . $mb;
break;
case 'B':
return $bytes . ' bytes';
break;
case 'KB':
return number_format( ($bytes / 1024), 2) . ' KB';
break;
case 'MB':
return number_format( (($bytes / 1024) / 1024), 2) . ' MB';
break;
}
}
}
/**
* Print GetMemory()
*/
function prmem() {
pr(GetMemory());
}
/**
* Print GetMemory() and exit
*/
function prmemx() {
prx(GetMemory());
}
/**
* Executes a var_dump and strips tags.
*
* @param mixed $x
* @return string
*/
function vardump($x)
{
ob_start();
var_dump($x);
$str = ob_get_clean();
return strip_tags($str);
}
/**
* texc
*
* Throw an exception with the given message.
*
* @param string $x Message string
* @return void
**/
function texc($x)
{
throw new \Exception('Debug: ' . $x);
}
/**
* show_errors
*
* Sets error reporting to E_ALL and display_errors to 1.
*
* @return void
**/
function show_errors()
{
error_reporting(E_ALL);
ini_set('display_errors', '1');
}
/**
* prn
*
* Prints something followed by a newline.
*
* @param string $x Something to print
* @return void
**/
function prn($x)
{
if (is_array($x) || is_object($x))
{
print_r($x);
}
else
{
print $x . "\n";
}
}
/**
* prnx
*
* Prints something followed by a newline, then exits.
*
* @param string $s Something to print
* @return void
**/
function prnx($s)
{
prn($s);
exit;
}
|
apache-2.0
|
mkobayas/minimum-marshaller
|
src/test/java/org/mk300/marshal/minimum/test/PriorityQueueTest.java
|
3777
|
package org.mk300.marshal.minimum.test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;
import org.apache.commons.io.HexDump;
import org.junit.Test;
import org.mk300.marshal.minimum.MinimumMarshaller;
import org.mk300.marshal.minimum.test.pojo.ComparatorForSampleData;
import org.mk300.marshal.minimum.test.pojo.SampleData;
@SuppressWarnings({"rawtypes", "unchecked"})
public class PriorityQueueTest {
@Test
public void testPriorityQueue() throws Exception {
PriorityQueue data = new PriorityQueue(10);
data.add(new Date(0));
data.add(new Date(3));
data.add(new Date(4));
data.poll();
testAndPrintHexAndCheck(data);
}
@Test
public void testPriorityQueueWithComparator() throws Exception {
PriorityQueue data = new PriorityQueue(10, new ComparatorForSampleData());
{
SampleData s = new SampleData();
s.setP1("ccc");
data.add(s);
}
{
SampleData s = new SampleData();
s.setP1("ddd");
data.add(s);
}
{
SampleData s = new SampleData();
s.setP1("bbb");
data.add(s);
}
{
SampleData s = new SampleData();
s.setP1("aaa");
data.add(s);
}
data.poll();
testAndPrintHexAndCheck(data);
}
// PriorityQueue は equalsメソッドを実装していない・・・
private void testAndPrintHexAndCheck(PriorityQueue<Date> target) throws Exception{
try {
byte[] bytes = MinimumMarshaller.marshal(target);
System.out.println(target.getClass().getSimpleName() + " binary size is " + bytes.length);
ByteArrayOutputStream os = new ByteArrayOutputStream();
HexDump.dump(bytes, 0, os, 0);
System.out.println(os.toString());
System.out.println("");
PriorityQueue<Object> o = (PriorityQueue<Object>)MinimumMarshaller.unmarshal(bytes);
// 正確に復元されていることの検証
if( o.size() != target.size()) {
throw new RuntimeException("オブジェクトが異なります。target=" + target + ", desr=" + o);
}
Object[] desr = o.toArray(new Object[0]);
Object[] origin = target.toArray(new Object[0]);
for(int i=0; i<desr.length ; i++) {
if(desr[i] == null && origin[i] == null) {
continue;
}
if(desr[i] == null || origin[i] == null) {
throw new RuntimeException("オブジェクトが異なります。target=" + target + ", desr=" + o);
}
if( ! desr[i].equals(origin[i])) {
throw new RuntimeException("オブジェクトが異なります。target=" + target + ", desr=" + o);
}
}
} finally {
}
// おまけ 普通のByteArray*Streamも使えるか?
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
MinimumMarshaller.marshal(target, baos);
byte[] bytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
PriorityQueue<Date> o = (PriorityQueue<Date>)MinimumMarshaller.unmarshal(bais);
// 正確に復元されていることの検証
if( o.size() != target.size()) {
throw new RuntimeException("オブジェクトが異なります。target=" + target + ", desr=" + o);
}
Object[] desr = o.toArray(new Object[0]);
Object[] origin = target.toArray(new Object[0]);
for(int i=0; i<desr.length ; i++) {
if(desr[i] == null && origin[i] == null) {
continue;
}
if(desr[i] == null || origin[i] == null) {
throw new RuntimeException("オブジェクトが異なります。target=" + target + ", desr=" + o);
}
if( ! desr[i].equals(origin[i])) {
throw new RuntimeException("オブジェクトが異なります。target=" + target + ", desr=" + o);
}
}
} finally {
}
}
}
|
apache-2.0
|
aam-at/tensorflow
|
tensorflow/compiler/xla/pjrt/pjrt_client.h
|
39777
|
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_COMPILER_XLA_PJRT_PJRT_CLIENT_H_
#define TENSORFLOW_COMPILER_XLA_PJRT_PJRT_CLIENT_H_
#include <memory>
#include <string>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/container/inlined_vector.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/synchronization/notification.h"
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "tensorflow/compiler/xla/client/executable_build_options.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"
#include "tensorflow/compiler/xla/layout.h"
#include "tensorflow/compiler/xla/pjrt/local_device_state.h"
#include "tensorflow/compiler/xla/pjrt/tracked_device_buffer.h"
#include "tensorflow/compiler/xla/service/computation_placer.h"
#include "tensorflow/compiler/xla/service/gpu/gpu_executable_run_options.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/shaped_buffer.h"
#include "tensorflow/compiler/xla/shape.h"
#include "tensorflow/compiler/xla/status.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/fingerprint.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/platform/types.h"
// API notes:
// PjRt stands for "Pretty much Just another RunTime".
namespace xla {
using PjRtPlatformId = uint64;
constexpr char kCpuName[] = "cpu";
constexpr char kGpuName[] = "gpu";
constexpr char kTpuName[] = "tpu";
static const PjRtPlatformId kCpuId = tensorflow::Fingerprint64(kCpuName);
static const PjRtPlatformId kGpuId = tensorflow::Fingerprint64(kGpuName);
static const PjRtPlatformId kTpuId = tensorflow::Fingerprint64(kTpuName);
class PjRtClient;
class PjRtDevice {
public:
explicit PjRtDevice(int id,
std::unique_ptr<LocalDeviceState> local_device_state,
std::string device_kind, int host_id = 0)
: id_(id),
local_device_id_(
local_device_state ? local_device_state->device_ordinal() : -1),
local_device_state_(std::move(local_device_state)),
host_id_(host_id),
device_kind_(std::move(device_kind)) {}
virtual ~PjRtDevice() {}
// Must set client exactly once.
void SetClient(PjRtClient* client) {
CHECK(client_ == nullptr);
client_ = client;
}
// The ID of this device. IDs are unique among devices of this type
// (e.g. CPUs, GPUs). On multi-host platforms, this will be unique across all
// hosts' devices. This is the ID that should be used in a DeviceAssignment.
int id() const { return id_; }
bool IsLocalDevice() const { return local_device_id_ != -1; }
int local_device_id() const { return local_device_id_; }
// If this is a device local to this host, returns a LocalDeviceState object
// that can be used to manipulate the device. Returns nullptr if the device is
// not local to this host.
LocalDeviceState* local_device_state() const {
return local_device_state_.get();
}
// If this is a device local to this host, returns a LocalDeviceState object
// that can be used to manipulate the device. Returns an error if the device
// is not local to this host.
StatusOr<LocalDeviceState*> GetLocalDeviceState() const;
// The ID of this device's host. This is always 0 on single-host platforms.
int host_id() const { return host_id_; }
// Return `platform_id` from client.
PjRtPlatformId platform_id() const;
// Return `platform_name` from client.
const std::string& platform_name() const;
// A vendor-dependent string that uniquely identifies the kind of device.
const std::string& device_kind() const { return device_kind_; }
virtual std::string DebugString() const;
PjRtClient* client() const { return client_; }
// Transfer the given literal to the infeed queue of the given localdevice.
virtual Status TransferToInfeed(const LiteralSlice& literal) const;
// Transfer and return a value of the given shape from the outfeed of the
// given device.
virtual StatusOr<Literal> TransferFromOutfeed(const Shape& shape) const;
private:
const int id_;
const int local_device_id_; // -1 means not local.
const std::unique_ptr<LocalDeviceState> local_device_state_;
const int host_id_;
const std::string device_kind_;
PjRtClient* client_ = nullptr;
};
// Forward declaration.
class PjRtBuffer;
// Helper struct for cross host transfers, returned by the callback from a call
// to PjRtBuffer::MakeCrossHostReceiveBuffers.
struct PjRtCrossHostRecvBuffer {
// serialized_descriptor should be transmitted to the sender and passed to a
// call to src_buffer->CopyToRemoteDevice.
std::string serialized_descriptor;
// The buffer that will hold the result of the transfer.
std::unique_ptr<PjRtBuffer> buffer;
};
using PjRtCrossHostRecvNotifier =
std::function<void(StatusOr<std::vector<PjRtCrossHostRecvBuffer>>&&)>;
struct CompileOptions {
// The layouts of the arguments that the computation should expect.
absl::optional<std::vector<Shape>> argument_layouts;
// If true, the supplied computation expects its arguments to be wrapped in a
// tuple and passed as a single parameter.
bool parameter_is_tupled_arguments = false;
// XLA's compilation time options.
ExecutableBuildOptions executable_build_options;
// If true, the executable can be run on any device. May only be true if
// !executable_build_options.has_device_assignment(), so only applies to
// single-device executables. Beware: on GPUs, sometimes an executable
// compiled for one device doesn't run on another.
bool compile_portable_executable = false;
};
class PjRtExecutable;
// Encapsulates the state of Python session with XLA.
//
// It is the responsibility of the client of this API to keep the PjRtClient
// alive as long as any of the other runtime objects are alive.
class PjRtClient {
public:
// `allocator` may null, in which case the platform default allocator is used.
explicit PjRtClient(
std::string platform_name, LocalClient* client,
std::vector<std::unique_ptr<PjRtDevice>> devices, int host_id,
std::unique_ptr<se::DeviceMemoryAllocator> allocator,
std::unique_ptr<tensorflow::Allocator> host_memory_allocator,
bool should_stage_host_to_device_transfers,
std::unique_ptr<GpuExecutableRunOptions> gpu_run_options);
virtual ~PjRtClient() = default;
virtual StatusOr<DeviceAssignment> GetDefaultDeviceAssignment(
int num_replicas, int num_partitions) const;
int device_count() const { return devices_.size(); }
int local_device_count() const { return local_devices_.size(); }
const std::vector<std::unique_ptr<PjRtDevice>>& devices() const {
return devices_;
}
const std::vector<PjRtDevice*>& local_devices() const {
return local_devices_;
}
const std::map<int, PjRtDevice*>& id_to_device() const {
return id_to_device_;
}
int host_id() const { return host_id_; }
PjRtPlatformId platform_id() const { return platform_id_; }
const std::string& platform_name() const { return platform_name_; }
LocalDeviceState& device_state(int device_ordinal) const {
return *local_devices_.at(device_ordinal)->local_device_state();
}
// Return a local PjRtDevice for a given `local_device_id`.
virtual StatusOr<PjRtDevice*> LookupLocalDevice(int local_device_id) const;
LocalClient* client() const { return client_; }
se::DeviceMemoryAllocator* allocator() const { return allocator_; }
tensorflow::Allocator* host_memory_allocator() const {
return host_memory_allocator_.get();
}
bool should_stage_host_to_device_transfers() const {
return should_stage_host_to_device_transfers_;
}
GpuExecutableRunOptions* gpu_run_options() const {
return gpu_run_options_.get();
}
tensorflow::thread::ThreadPool* h2d_transfer_pool() {
return &h2d_transfer_pool_;
}
// Most platforms expect device-to-device transfers to be enqueued on the
// source d2d stream, but some platforms use the destination d2d stream. This
// function specifies which one the platform expects.
virtual bool EnqueueD2DTransfersOnSrcStream() const { return true; }
// Generates a unique fingerprint for `executable`. See
// PjRtExecutable::fingerprint_.
virtual StatusOr<absl::optional<std::string>> ExecutableFingerprint(
const PjRtExecutable& executable) const {
return absl::optional<std::string>();
}
// Returns a backend-specific HLO cost analysis visitor.
virtual std::unique_ptr<HloCostAnalysis> GetHloCostAnalysis();
virtual StatusOr<std::unique_ptr<PjRtExecutable>> Compile(
const XlaComputation& computation, CompileOptions options);
virtual StatusOr<std::unique_ptr<PjRtBuffer>> CreateUninitializedBuffer(
const Shape& shape, PjRtDevice* device);
// Describes the semantics the caller to BufferFromHostBuffer expects from the
// runtime, in a total order from most restrictive to least restrictive.
enum class HostBufferSemantics {
// The runtime may not hold references to `data` after the call to
// `BufferFromHostBuffer` completes. The caller promises that `data` is
// immutable and will not be freed only for the duration of the
// BufferFromHostBuffer call. `buffer_reference` will be freed by the time
// `BufferFromHostBuffer` returns.
kImmutableOnlyDuringCall,
// The runtime may hold onto `data` after the call to `BufferFromHostBuffer`
// returns while the runtime completes a transfer to the device. The caller
// promises not to mutate or free `data` until the transfer completes, at
// which point the runtime will release `buffer_reference`. It is also
// correct to wait on the host (directly or indirectly) for the buffer's
// definition event to complete.
kImmutableUntilTransferCompletes,
// The PjRtBuffer may alias `data` internally and the runtime may use the
// `data` contents as long as the buffer is alive. The caller promises to
// keep `data` alive and not to mutate its contents as long as the buffer is
// alive; to notify the caller that the buffer may be freed, the runtime
// will release its `buffer_reference` when the PjRtBuffer is freed. On
// non-CPU platforms this acts identically to
// kImmutableUntilTransferCompletes.
kZeroCopy,
};
virtual StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostBuffer(
const void* data, const Shape& shape,
HostBufferSemantics host_buffer_semantics,
std::shared_ptr<void> buffer_reference, PjRtDevice* device);
// Note that literal must remain in scope until the transfer has completed, so
// the caller should, for example, wait for BlockHostUntilReady() completes on
// the return value before letting literal go out of scope.
virtual StatusOr<std::unique_ptr<PjRtBuffer>> BufferFromHostLiteral(
const LiteralSlice& literal, PjRtDevice* device);
// Asynchronously makes a vector of PjRtBuffers that can be used to receive
// cross host transfers using `client` on `device'. `shapes` must be the exact
// shapes, with identical layouts, corresponding to the buffers that will be
// sent. When resources for the transfer are available, notifier will be
// called with a vector of PjRtCrossHostRecvBuffer structs, one for each
// shape in `shapes`. Each struct contains a buffer that will contain the
// received value, and an opaque string that should be transmitted to the
// sending host and used in a call to CopyToRemoteDevice. None of the recv
// buffers will become ready until *all* of the sends have completed.
virtual void MakeCrossHostReceiveBuffers(
absl::Span<const Shape> shapes, PjRtDevice* device,
PjRtCrossHostRecvNotifier&& notifier);
virtual StatusOr<ChannelHandle> CreateChannelHandle() {
return client()->CreateChannelHandle();
}
virtual StatusOr<ChannelHandle> CreateDeviceToHostChannelHandle() {
return client()->CreateDeviceToHostChannelHandle();
}
virtual StatusOr<ChannelHandle> CreateHostToDeviceChannelHandle() {
return client()->CreateHostToDeviceChannelHandle();
}
protected:
friend class PjRtBuffer;
virtual void EnqueueCrossHostReceive(
std::vector<std::unique_ptr<PjRtBuffer>>&& buffers,
PjRtCrossHostRecvNotifier&& notifier) const {
notifier(Unimplemented("Cross host receives not implemented."));
}
virtual Status CopyToRemoteDevice(
PjRtBuffer* buffer, absl::string_view serialized_descriptor) const {
return Unimplemented("Cross host sends not implemented.");
}
const PjRtPlatformId platform_id_;
const std::string platform_name_;
LocalClient* client_;
// Allocator to be used for staging memory transfers to devices.
std::unique_ptr<tensorflow::Allocator> host_memory_allocator_;
// Includes all devices, including non-local devices on multi-host platforms.
std::vector<std::unique_ptr<PjRtDevice>> devices_;
// Maps Device::id() to the corresponding Device. Includes all devices.
std::map<int, PjRtDevice*> id_to_device_;
// Local devices indexed by local device ordinal.
std::vector<PjRtDevice*> local_devices_;
int host_id_;
se::DeviceMemoryAllocator* allocator_;
std::unique_ptr<se::DeviceMemoryAllocator> owned_allocator_;
// Should we always prefer to stage host-to-device transfers via memory
// allocated on host_memory_allocator_? True only on GPU, where we prefer to
// transfer via pinned memory.
bool should_stage_host_to_device_transfers_;
std::unique_ptr<GpuExecutableRunOptions> gpu_run_options_;
tensorflow::thread::ThreadPool h2d_transfer_pool_;
};
// Converts a 2D set of Device objects indexed by [replica][partition] into an
// xla::DeviceAssignment.
StatusOr<DeviceAssignment> DevicesToDeviceAssignment(
absl::Span<const std::vector<PjRtDevice*>> devices);
// Holds a reference from Python to a tuple of device buffers. A PjRtBuffer
// can be either valid or invalid. An invalid buffer is one that has never been
// initialized, or a buffer that has been deleted (e.g., by calling Delete, or
// by donating it to a computation that aliases an input parameter to an
// output). We allow PjRtBuffer objects to outlive the underlying device
// buffers so we can decouple buffer lifetimes from the corresponding Python
// references if needed. Thread-safe.
class PjRtBuffer {
public:
// Helper class to retain a "hold" on a PjRtBuffer. A ScopedHold may not
// outlive its parent PjRtBuffer.
//
// There are three types of hold, as follows:
//
// 1) Usage hold: a transient hold while an operation using the buffer is
// being enqueued onto a stream.
// A client acquires a usage hold by calling
// PjRtBuffer::GetBufferWithHold(kUsage) or the convenience wrapper
// GetBufferWithUsageHold(). If the enqueue completes successfully the hold
// should be released using a call to ConvertUsageHold. If the ScopedHold is
// deleted without ConvertUsageHold being called, e.g., on error, the hold is
// dropped. It is legal to drop a usage hold instead of calling
// ConvertUsageHold, even if the buffer was successfully enqueued, as long as
// the client ensures that all necessary synchronization has been done.
//
// 2) External hold: a potentially long-lived hold while the buffer is being
// shared by an external framework, e.g., NumPy.
// A client acquires an external hold by calling
// PjRtBuffer::GetBufferWithHold(kExternal) or the convenience wrapper
// GetBufferWithExternalReference and releases it by deleting the ScopedHold.
// The external framework should not modify the underlying buffer unless it is
// confident via its own synchronization that modifications do not race with
// reads from the PjRtBuffer.
//
// 3) Donation hold: a transient hold while an execution that donates the
// buffer is being enqueued onto the compute stream.
// A client acquires a donation hold by calling
// PjRtBuffer::GetBufferWithHold(kDonation). If the enqueue completes
// successfully the hold should be released using a call to ConfirmDonation
// after which the buffer is invalid. If the ScopedHold is deleted without
// ConfirmDonation being called, e.g., on error, the hold is dropped and the
// buffer remains valid. If the buffer is successfully enqueued the client
// *must* call ConfirmDonation.
//
// Donation holds behave like exclusive write locks: when a donation hold
// has been acquired, any attempt to acquire another hold of any type will
// block until the donation hold is dropped or confirmed. Acquiring a donation
// hold will fail with an error if there is any outstanding external hold, and
// will block if there are any outstanding usage holds until those holds are
// dropped or converted.
//
// Calls to PjRtBuffer::Release (and transitively to
// PjRtBuffer::Delete() and ~PjRtBuffer()) will block until all usage
// and donation holds are either deleted or converted/confirmed.
class ScopedHold {
public:
enum Type { kUsage = 0, kExternalReference, kDonation, kMaxValue };
// Use a State enum instead of encoding the state in an error Status to
// avoid creating Status values in non-error cases. Creating a Status
// entails several allocations and can add O(us) to every use of a hold.
enum State {
kUninitialized = 0,
kValid,
kMoved,
kConverted,
kReleased,
kDonated,
kError
};
~ScopedHold();
ScopedHold(ScopedHold&& other);
ScopedHold(const ScopedHold&) = delete;
ScopedHold& operator=(const ScopedHold&) = delete;
Type type() const { return type_; }
Status status() const {
// Lazily create Status values only when they are requested.
switch (state_) {
case kUninitialized:
return InvalidArgument("Buffer has not been initialized");
case kValid:
return Status::OK();
case kMoved:
return InvalidArgument("Buffer has been moved.");
case kConverted:
return InvalidArgument("Buffer has been converted");
case kReleased:
return InvalidArgument("Buffer has been released");
case kDonated:
return InvalidArgument("Buffer has been donated");
case kError:
return buffer_or_.status();
default:
CHECK(false) << "Unexpected state value " << state_;
}
}
bool ok() const { return state_ == kValid; }
// Access to the underlying device buffer storage. Requires this->ok().
const std::shared_ptr<TrackedDeviceBuffer>& buffer() const {
CHECK_EQ(state_, kValid);
CHECK_NE(buffer_or_.ValueOrDie(), nullptr);
return buffer_or_.ValueOrDie();
}
TrackedDeviceBuffer* operator->() const { return buffer().get(); }
const TrackedDeviceBuffer& operator*() const { return *buffer(); }
// Converts the hold into a usage event. Only valid for holds of type
// kUsage.
//
// usage_stream: the stream that the buffer was used on.
// event: an event that has been recorded on usage_stream after
// the buffer was used.
// reference_held: true if and only if the caller has caused a
// reference to this->buffer() to stay live until after
// the host is sure that the usage (transfer or execution)
// has completed.
void ConvertUsageHold(se::Stream* usage_stream,
std::shared_ptr<BufferSequencingEvent> event,
bool reference_held);
// Confirms that the buffer was successfully donated to an execution.
// Only valid for holds of type kDonation. Causes the buffer to become
// invalid.
void ConfirmDonation();
// Adds the held device buffers in order to 'iterator'. Used to add the
// buffers to an ExecutionInput. We require but do not verify that
// 'iterator' when passed in is pointing to a sub-tuple of the
// ExecutionInput whose on_device_shape matches that of the
// TrackedDeviceBuffer. 'end' is used to check that 'iterator' doesn't run
// out of bounds. Donates the device buffers if the hold type is kDonation,
// otherwise retains ownership of the device buffers.
void AddToInput(ShapeTree<MaybeOwningDeviceMemory>::iterator* iterator,
const ShapeTree<MaybeOwningDeviceMemory>::iterator& end,
ExecutionInput* execution_input,
se::DeviceMemoryAllocator* allocator) const;
private:
friend class PjRtBuffer;
friend class PjRtClient;
// Helper struct that makes it possible to move a ScopedHold through a
// closure.
using ForClosure =
std::tuple<PjRtBuffer*, Type, State,
StatusOr<std::shared_ptr<TrackedDeviceBuffer>>>;
ScopedHold(PjRtBuffer* parent, Type type)
: parent_(parent), type_(type), state_(kUninitialized) {}
explicit ScopedHold(const ForClosure& closure_helper)
: parent_(std::get<0>(closure_helper)),
type_(std::get<1>(closure_helper)),
state_(std::get<2>(closure_helper)),
buffer_or_(std::get<3>(closure_helper)) {
// Check the buffer is not in an error state.
CHECK(buffer_or_.ValueOrDie() != nullptr);
}
// Sets buffer state.
void SetState(State state) { state_ = state; }
// Sets buffer_or_. Called by parent_ to initialize the hold.
void Acquire(StatusOr<std::shared_ptr<TrackedDeviceBuffer>>&& buffer_or);
// Releases the contents of *this, so *this can subsequently be
// deleted without releasing the parent's hold. Should be passed to the
// appropriate constructor of another ScopedHold, e.g., when a hold must be
// passed through a closure that is incompatible with std::move.
ForClosure ToClosure();
PjRtBuffer* const parent_;
const Type type_;
// There is an invariant that if ok() then
// buffer_or_.ValueOrDie() != nullptr.
State state_;
StatusOr<std::shared_ptr<TrackedDeviceBuffer>> buffer_or_;
};
PjRtBuffer(Shape on_host_shape, Shape on_device_shape,
std::shared_ptr<TrackedDeviceBuffer> device_buffer,
PjRtClient* client, PjRtDevice* device);
virtual ~PjRtBuffer();
PjRtBuffer(const PjRtBuffer&) = delete;
PjRtBuffer(PjRtBuffer&&) = delete;
PjRtBuffer& operator=(const PjRtBuffer&) = delete;
PjRtBuffer& operator=(PjRtBuffer&&) = delete;
const Shape& on_host_shape() const { return on_host_shape_; }
const Shape& on_device_shape() const { return on_device_shape_; }
PjRtDevice* device() const { return device_; }
PjRtPlatformId platform_id() const { return client_->platform_id(); }
const std::string& platform_name() const { return client_->platform_name(); }
PjRtClient* client() const { return client_; }
bool IsEmptyTuple() const {
return on_host_shape_.IsTuple() && on_host_shape_.tuple_shapes_size() == 0;
}
// Returns the size of the on-device representation of this buffer in bytes.
int64 OnDeviceSizeInBytes() const;
// Returns the buffer's value as an XLA Literal. If the value has previously
// been prefetched to the host, then returns the prefetched version, otherwise
// copies the buffer to the host. Blocks until the value is ready. If
// `discard_cached_copy` is true then buffer will no longer keep hold of a
// cached copy of the literal (i.e. The reference to the host value will be
// removed.) If a layout is passed than a literal with this layout will be
// returned.
StatusOr<std::shared_ptr<Literal>> ToLiteral(
bool discard_cached_copy = false,
absl::optional<xla::Layout> layout = {});
// Initiates a copy of the buffer to the host. Does not block waiting for
// the transfer to complete. The value can be retrieved by a later call to
// ToLiteral(). If a layout is passed then a cached copy with this layout will
// be created.
Status CopyToHostAsync(absl::optional<xla::Layout> layout = {});
// Drops the buffer's reference to its associated device memory, leaving the
// buffer in an invalid state. The memory will be freed lazily when all async
// operations using the buffer have completed, according to the allocation
// semantics of the underlying platform. Delete may briefly block if another
// thread is in the process of enqueuing an operation on this buffer, but it
// will never block for a stream operation to complete. If an external
// framework holds a reference to the TrackedDeviceBuffer via
// GetBufferWithExternalReference, the memory will not be freed until the
// external framework drops the reference.
void Delete();
// Similar to Delete, drops the buffer's reference to its associated device
// memory, leaving the buffer in an invalid state, but returns the
// TrackedDeviceBuffer rather than freeing the device memory, so that another
// framework can take ownership of it. The buffer returned from Release may
// be safely dropped at any time even if it still has pending async
// operations. The client should call BlockHostUntilReady before calling
// Release with wait_for_operations_to_complete=false, to ensure that the host
// has synchronized past any outstanding write operations to the buffer. If
// wait_for_operations_to_complete=true the host will block until any
// potentially outstanding asynchronous operations have completed before
// returning, in which case it is safe to read or mutate the returned buffer.
// If the buffer was shared via an external reference it is the client's
// responsibility that accesses via that reference do not interfere with
// accesses via the buffer returned from Release.
StatusOr<std::shared_ptr<TrackedDeviceBuffer>> Release(
bool wait_for_operations_to_complete);
// True if and only if Delete or Release has previously been called.
bool IsDeleted();
// Returns a view of the PjRtBuffer device memory as a ShapedBuffer. The
// PjRtBuffer retains ownership of the device buffers.
StatusOr<ShapedBuffer> AsShapedBuffer() const;
// Returns a hold on the TrackedDeviceBuffer holding the device
// buffers. See comment on ScopedHold.
ScopedHold GetBufferWithHold(ScopedHold::Type type);
ScopedHold GetBufferWithUsageHold() {
return GetBufferWithHold(ScopedHold::kUsage);
}
ScopedHold GetBufferWithExternalReference() {
return GetBufferWithHold(ScopedHold::kExternalReference);
}
// Copies the buffer to device `dst_device`, performing a d2d transfer when
// `dst_device` is sharing the same Client, and performing a d2h and h2d copy
// if `dst_device` lives on a different Client.
// Returns an error if the buffer is already on dst_device.
StatusOr<std::unique_ptr<PjRtBuffer>> CopyToDevice(PjRtDevice* dst_device);
// Copies the buffer to the remote device encoded in serialized_descriptor.
// This call must be preceded by a call to MakeCrossHostReceiveBuffers on the
// remote host's destination device. MakeCrossHostReceiveBuffers takes an
// array of shapes to construct the destination buffers, and a callback
// supplies an array containing both the destination buffers, and a serialized
// descriptor for each buffer. For each destination buffer there should be a
// matching call to src->CopyToRemoteDevice on a remote host for a src buffer
// of the corresponding shape. serialized_descriptor is the string returned by
// the callback along with the corresponding destination buffer.
Status CopyToRemoteDevice(absl::string_view serialized_descriptor);
// Blocks the host until the buffer's value has been computed and is ready for
// immediate use on the device. Useful in particular for timing benchmarks.
Status BlockHostUntilReady();
// Whether this buffer is on CPU and thus allows for certain optimizations.
bool IsOnCpu() const;
private:
friend class PjRtClient;
// The cached value of the buffer on the host, produced either from a call to
// CopyToHost or from a call to ToLiteral. Once a value has been fetched to
// the host, it persists Delete() is called or the PjRtBuffer is destroyed.
struct HostValue {
absl::Notification ready;
// status and value are valid for reading only after `ready` has been
// notified.
Status status;
std::shared_ptr<Literal> value;
};
// Blocks in mu_.Await until there are no more usage holds.
void WaitForOutstandingUsageHolds() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
// Blocks in mu_.Await until there is no donation hold.
void WaitForOutstandingDonationHold() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
// Adds a hold of 'type' and returns device_buffer_. Returns an error if
// device_buffer_ is null, or if a donation hold was requested when there is
// an outstanding external hold.
StatusOr<std::shared_ptr<TrackedDeviceBuffer>> GetBufferForHoldLocked(
ScopedHold::Type type) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
// Adds a hold of hold->type() and initializes `hold` with device_buffer_.
// Initializes hold with an error if device_buffer_ is null, or if a donation
// hold was requested when there is an outstanding external hold.
void AcquireHoldLocked(ScopedHold* hold) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
// Drops a usage hold and calls device_buffer_->AddUsageEvent. Does a sanity
// check that buffer==device_buffer_ or device_buffer_==nullptr. Called after
// device_buffer_ was successfully enqueued on a stream.
void ConvertUsageHold(TrackedDeviceBuffer* buffer, se::Stream* usage_stream,
std::shared_ptr<BufferSequencingEvent> event,
bool reference_held);
// Drops a donation hold and makes *this invalid for further use. Does a
// sanity check that buffer==device_buffer_. Called after device_buffer_ was
// successfully donated to an execution.
void ConfirmDonation(TrackedDeviceBuffer* device_buffer);
// Initiates a copy of the buffer to the host. Does not block waiting for
// the transfer to complete. A host value is returned and if
// `discard_cached_copy` is false stored in an internal buffer so that future
// transfers don't have to transfer the data from host again. If a layout is
// passed then a literal of this layout will be returned and possibly cached.
StatusOr<std::shared_ptr<HostValue>> CopyToHostAsyncInternal(
bool discard_cached_copy, absl::optional<xla::Layout> layout);
// Drops a hold without taking any other action. Does a sanity check that
// buffer==device_buffer_ or device_buffer_==nullptr.
void DropHold(ScopedHold::Type type, TrackedDeviceBuffer* buffer);
StatusOr<std::pair<std::unique_ptr<PjRtBuffer>,
std::shared_ptr<BufferSequencingEvent>>>
CopyToDeviceHelper(PjRtDevice* dst_device, LocalDeviceState* dst_local_device,
LocalDeviceState* transfer_local_device,
se::Stream* transfer_stream,
std::shared_ptr<TrackedDeviceBuffer> src_device_buffer);
PjRtClient* const client_;
const Shape on_host_shape_;
const Shape on_device_shape_;
PjRtDevice* const device_;
mutable absl::Mutex mu_;
std::shared_ptr<TrackedDeviceBuffer> device_buffer_ TF_GUARDED_BY(mu_);
absl::flat_hash_map<xla::Layout, std::shared_ptr<HostValue>> host_values_
TF_GUARDED_BY(mu_);
std::shared_ptr<HostValue> host_value_ TF_GUARDED_BY(mu_);
// Count of holds on the buffer.
std::array<int, ScopedHold::Type::kMaxValue> holds_ TF_GUARDED_BY(mu_);
// Semaphore used to ensure there is only one outstanding donation hold.
Semaphore donation_semaphore_;
};
class ExecuteContext {
public:
virtual ~ExecuteContext() = default;
};
struct ExecuteOptions {
// If true, the client must pass a single PjRtBuffer which contains all of
// the arguments as a single XLA tuple, otherwise each argument must be
// passed in its own PjRtBuffer. May only be true if the executable was
// compiled with parameter_is_tupled_arguments==true.
bool arguments_are_tupled = false;
// If true, the computation must return a tuple, which will be destructured
// into its elements.
bool untuple_result = false;
// If non-zero, identifies this execution as part of a potentially
// multi-device launch. This can be used to detect scheduling errors, e.g. if
// multi-host programs are launched in different orders on different hosts,
// the launch IDs may be used by the runtime to detect the mismatch.
int32 launch_id = 0;
// If non-null, an opaque context passed to an execution that may be used to
// supply additional arguments to a derived class of PjRtExecutable.
const ExecuteContext* context = nullptr;
};
// Represents a compiled computation that can be executed given handles to
// device-allocated literals. Wraps one or more XLA LocalExecutables (one per
// partition, as specified by the build options). If any input/output alias
// has been specified in the computation, the parameter containing the input
// buffer will be donated when passed to the execution.
class PjRtExecutable {
public:
PjRtExecutable(std::vector<std::unique_ptr<LocalExecutable>> executables,
bool parameter_is_tupled_arguments,
std::shared_ptr<DeviceAssignment> device_assignment,
std::vector<std::pair<int, int>> local_logical_device_ids,
std::vector<PjRtDevice*> local_devices, PjRtClient* client);
virtual ~PjRtExecutable() = default;
PjRtClient* client() const { return client_; }
int num_replicas() const {
return executables_[0]->build_options().num_replicas();
}
int num_partitions() const {
return executables_[0]->build_options().num_partitions();
}
int64 SizeOfGeneratedCodeInBytes() const {
int64 size = 0;
for (auto& executable : executables_) {
size += executable->executable()->SizeOfGeneratedCodeInBytes();
}
return size;
}
const std::vector<std::shared_ptr<LocalExecutable>>& executables() const {
return executables_;
}
const DeviceAssignment& device_assignment() const {
return *device_assignment_;
}
const std::vector<std::pair<int, int>>& local_logical_device_ids() const {
return local_logical_device_ids_;
}
const std::vector<PjRtDevice*>& local_devices() const {
return local_devices_;
}
StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>> Execute(
absl::Span<PjRtBuffer* const> argument_handles,
const ExecuteOptions& options) const;
StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>> ExecuteOnLocalDevice(
absl::Span<PjRtBuffer* const> argument_handles, PjRtDevice* device,
const ExecuteOptions& options) const;
// Execute on local devices. Takes a sequence of argument lists (one argument
// list per local device) and returns a tuple of results (one result per local
// device). The number of argument lists must be equal to the local device
// count.
StatusOr<std::vector<std::vector<std::unique_ptr<PjRtBuffer>>>>
ExecuteOnLocalDevices(
absl::Span<const std::vector<PjRtBuffer*>> argument_handles,
const ExecuteOptions& options) const;
void Delete() { executables_.clear(); }
const string& name() const;
// Return an HloModule per partition.
StatusOr<std::vector<std::shared_ptr<HloModule>>> GetHloModules();
protected:
bool parameter_is_tupled_arguments() const {
return parameter_is_tupled_arguments_;
}
private:
friend class PjRtClient;
// Initializes information about which arguments to which executables must be
// donated due to aliases that were specified by the computation.
Status SetUpDonation(bool tuple_inputs);
virtual bool MustDonateParameter(int executable_idx, int parameter) const;
virtual StatusOr<std::vector<ExecutionInput>>
MakeExecutionInputsAndWaitForEvents(
int device_ordinal, const ExecuteOptions& options,
absl::Span<PjRtBuffer* const> argument_handles,
absl::Span<const PjRtBuffer::ScopedHold> device_buffers,
absl::flat_hash_set<BufferSequencingEvent*>& events) const;
StatusOr<ScopedShapedBuffer> EnqueueExecution(
absl::Span<PjRtBuffer* const> argument_handles, int replica,
int partition, int executable_idx, const RunId& run_id,
const ExecuteOptions& options, PjRtDevice* device,
std::vector<PjRtBuffer::ScopedHold>* device_buffers,
std::shared_ptr<DeviceAssignment> device_assignment) const;
virtual std::vector<std::unique_ptr<PjRtBuffer>> MakeOutputBuffers(
int device_ordinal, const ExecuteOptions& options,
ScopedShapedBuffer result_buffer,
std::shared_ptr<BufferSequencingEvent> definition_event,
PjRtDevice* device) const;
StatusOr<std::vector<std::unique_ptr<PjRtBuffer>>> ExecuteHelper(
absl::Span<PjRtBuffer* const> argument_handles, int replica,
int partition, const RunId& run_id, const ExecuteOptions& options,
PjRtDevice* device = nullptr) const;
// Create shared pointers so we can free them after the execution: with
// asynchronous execution, the process being executed can outlive the
// executable itself.
PjRtClient* const client_;
// One executable per partition.
std::vector<std::shared_ptr<LocalExecutable>> executables_;
// Per-executable set of parameters that have any aliased buffers and thus
// must be donated when executing the computation.
std::vector<absl::flat_hash_set<int>> parameters_that_must_be_donated_;
std::shared_ptr<DeviceAssignment> device_assignment_;
// True if the executables were compiled expecting arguments in a single
// tuple.
const bool parameter_is_tupled_arguments_;
// The replica and partition indices of device_assignment_ to be run by this
// client. On single-host platforms without partitioning, this is all replicas
// (i.e. local_logical_device_ids_[i] = (i, 0)), but this may not be the case
// on multi-host platforms.
// If there are 4 replicas and 2 partitions on a single host platform, size of
// local_logical_device_ids_ is 4*2 = 8.
std::vector<std::pair<int, int>> local_logical_device_ids_;
// local_devices_[i] is the Device to which local_logical_device_ids_[i] is
// assigned.
// shared_ptrs instead of unique_ptrs to play well with the Python bindings
// (see xla.cc).
std::vector<PjRtDevice*> local_devices_;
};
// Executables can donate buffers so that buffers can be aliased from inputs
// to outputs. This function returns the list of parameters that must be
// donated when executable is run. tuple_inputs reflects the option that
// executable was compiled with.
StatusOr<absl::flat_hash_set<int>> GetParametersThatMustBeDonated(
const HloModule& hlo_module, bool tuple_inputs);
} // namespace xla
#endif // TENSORFLOW_COMPILER_XLA_PJRT_PJRT_CLIENT_H_
|
apache-2.0
|
stackinabox/stackinabox.io
|
scripts/deploy-to-bluemix/deploy_compose.sh
|
173
|
#!/bin/bash
echo "Creating UrbanCode Enterprise Platform Services"
echo "`ls -la`"
cd ./compose/urbancode
docker-compose -f bluemix-compose.yml -p UrbanCodePlatform up -d
|
apache-2.0
|
SES-fortiss/SmartGridCoSimulation
|
projects/memapCore/src/main/java/memap/helper/milp/MILPProblemNoConnections.java
|
21486
|
package memap.helper.milp;
import java.util.Arrays;
import lpsolve.LpSolve;
import lpsolve.LpSolveException;
import memap.controller.TopologyController;
import memap.helper.configurationOptions.OptimizationCriteria;
import memap.helper.configurationOptions.ToolUsage;
import memap.messages.BuildingMessage;
import memap.messages.extension.NetworkType;
import memap.messages.planning.CouplerMessage;
import memap.messages.planning.DemandMessage;
import memap.messages.planning.ProducerMessage;
import memap.messages.planning.StorageMessage;
import memap.messages.planning.VolatileProducerMessage;
/**
* This class is responsible to modify the problem of the MILP solver. It is
* very similar to MILPProblemWithConnections. It would be good to merge these 2
* classes, but this is left for later. Be careful, when modifying those two
* classes.
*/
public class MILPProblemNoConnections extends MILPProblem {
public MILPProblemNoConnections(TopologyController topologyController, int currentTimeStep, int nStepsMPC,
int nCols) {
super(topologyController, currentTimeStep, nStepsMPC, nCols);
}
public LpSolve createNames(LpSolve problem, BuildingMessage buildingMessage) throws LpSolveException {
MILPIndexHelper mihelper = new MILPIndexHelper(nStepsMPC);
for (ProducerMessage producerMessage : buildingMessage.controllableProducerList) {
MILPHelper.addControllableToProblem(producerMessage, problem, mihelper);
mihelper.controllableHandled++;
}
for (ProducerMessage producerMessage : buildingMessage.volatileProducerList) {
MILPHelper.addVolatileToProblem(producerMessage, problem, mihelper);
mihelper.volatileHandled++;
}
for (CouplerMessage couplerMessage : buildingMessage.couplerList) {
MILPHelper.addCouplerToProblem(couplerMessage, problem, mihelper);
mihelper.couplerHandled++;
}
for (StorageMessage storageMessage : buildingMessage.storageList) {
MILPHelper.addStorageToProblem(storageMessage, problem, mihelper);
mihelper.storageHandled++;
}
MILPHelper.addMarkets(problem, mihelper);
updateLambdaEURbuilding(buildingMessage, 0);
updateLambdaEURMarket();
updateLambdaCO2building(buildingMessage, 0);
updateLambdaCO2Market();
return problem;
}
public LpSolve createDemandConstraints(LpSolve problem, BuildingMessage buildingMessage) throws LpSolveException {
double[] demand = buildingMessage.getCombinedDemandVector();
/* first HEAT components */
for (int i = 0; i < demand.length / 2; i++) {
int controllableHandled = 0;
int volatileHandled = 0;
int couplerHandled = 0;
int storageHandled = 0;
double[] rowHEAT = new double[nCols + 1];
for (ProducerMessage pm : buildingMessage.controllableProducerList) {
int index = i + 1 + nStepsMPC
* ((controllableHandled * 2) + volatileHandled + (couplerHandled * 2) + (storageHandled * 2));
if (pm.networkType == NetworkType.HEAT)
rowHEAT[index] = -pm.efficiency;
controllableHandled++;
}
for (ProducerMessage pm : buildingMessage.volatileProducerList) {
int index = i + 1 + nStepsMPC
* ((controllableHandled * 2) + volatileHandled + (couplerHandled * 2) + (storageHandled * 2));
if (pm.networkType == NetworkType.HEAT)
rowHEAT[index] = -1;
volatileHandled++;
}
for (CouplerMessage cm : buildingMessage.couplerList) {
int index = i + 1 + nStepsMPC
* ((controllableHandled * 2) + volatileHandled + (couplerHandled * 2) + (storageHandled * 2));
rowHEAT[index] = -cm.efficiencyHeat;
couplerHandled++;
}
for (StorageMessage sm : buildingMessage.storageList) {
int index = i + 1 + nStepsMPC
* ((controllableHandled * 2) + volatileHandled + (couplerHandled * 2) + (storageHandled * 2));
if (sm.networkType == NetworkType.HEAT) {
rowHEAT[index] = -1;
rowHEAT[index + nStepsMPC] = 1;
}
storageHandled++;
}
problem.addConstraint(rowHEAT, LpSolve.EQ, demand[i]);
// System.out.println("Adding Constraint at i = " + i + ", --> rowHEAT: " + Arrays.toString(rowHEAT)
// + " EQ: " + demand[i]);
}
/* second ELEC componentes */
int countTimeStep = 0;
for (int i = demand.length / 2; i < demand.length; i++) {
int controllableHandled = 0;
int volatileHandled = 0;
int couplerHandled = 0;
int storageHandled = 0;
double[] rowELEC = new double[nCols + 1];
for (ProducerMessage pm : buildingMessage.controllableProducerList) {
int index = countTimeStep + 1 + nStepsMPC
* ((controllableHandled * 2) + volatileHandled + (couplerHandled * 2) + (storageHandled * 2));
if (pm.networkType == NetworkType.ELECTRICITY)
rowELEC[index] = -pm.efficiency;
controllableHandled++;
}
for (ProducerMessage pm : buildingMessage.volatileProducerList) {
int index = countTimeStep + 1 + nStepsMPC
* ((controllableHandled * 2) + volatileHandled + (couplerHandled * 2) + (storageHandled * 2));
if (pm.networkType == NetworkType.ELECTRICITY)
rowELEC[index] = -1;
volatileHandled++;
}
for (CouplerMessage cm : buildingMessage.couplerList) {
int index = countTimeStep + 1 + nStepsMPC
* ((controllableHandled * 2) + volatileHandled + (couplerHandled * 2) + (storageHandled * 2));
rowELEC[index] = -cm.efficiencyElec;
couplerHandled++;
}
for (StorageMessage sm : buildingMessage.storageList) {
int index = countTimeStep + 1 + nStepsMPC
* ((controllableHandled * 2) + volatileHandled + (couplerHandled * 2) + (storageHandled * 2));
if (sm.networkType == NetworkType.ELECTRICITY) {
rowELEC[index] = -1;
rowELEC[index + nStepsMPC] = 1;
}
storageHandled++;
}
// ADD Markets (at last position)
int index = countTimeStep + 1 + nStepsMPC
* ((controllableHandled * 2) + volatileHandled + (couplerHandled * 2) + (storageHandled * 2));
rowELEC[index] = -1;
rowELEC[index + nStepsMPC] = 1;
problem.addConstraint(rowELEC, LpSolve.EQ, demand[i]);
// System.out.println("Adding markets --> rowELEC: " + Arrays.toString(rowELEC)
// + " EQ: " + demand[i]);
countTimeStep++;
}
return problem;
}
public LpSolve createComponentBoundaries(LpSolve problem, BuildingMessage buildingMessage) throws LpSolveException {
int cts = currentTimeStep;
double[] networkBuyCap = new double[nStepsMPC];
Arrays.fill(networkBuyCap, 99999.0); // fill with 99999 kWh -> (no) upper limit.
for (int i = 0; i < nStepsMPC; i++) {
MILPIndexHelper ih = new MILPIndexHelper(nStepsMPC);
for (ProducerMessage pm : buildingMessage.controllableProducerList) {
int addon = nStepsMPC * ((ih.controllableHandled * 2) + ih.volatileHandled + (ih.couplerHandled * 2)
+ (ih.storageHandled * 2));
int index = i + 1 + addon;
// MAX Constraints, for both el. and heat
double[] row = new double[nCols + 1];
row[index] = pm.efficiency;
row[index + nStepsMPC] = pm.maxPower;
problem.addConstraint(row, LpSolve.LE, pm.maxPower);
// System.out.println("Adding max constraint CP --> row: " +
// Arrays.toString(row) + " <= " + pm.maxPower);
// MIN Constraints, for both el. and heat
double[] row2 = new double[nCols + 1];
row2[index] = -pm.efficiency;
row2[index + nStepsMPC] = -pm.minPower;
problem.addConstraint(row2, LpSolve.LE, -pm.minPower);
// System.out.println("Adding min constraint CP --> row2: " +
// Arrays.toString(row2) + " <= -" + pm.minPower);
ih.controllableHandled++;
}
for (ProducerMessage pm : buildingMessage.volatileProducerList) {
int index = i + 1 + nStepsMPC * ((ih.controllableHandled * 2) + ih.volatileHandled
+ (ih.couplerHandled * 2) + (ih.storageHandled * 2));
VolatileProducerMessage vpm = (VolatileProducerMessage) pm;
// MAX Constraints, for both el. and heat
double[] row = new double[nCols + 1];
row[index] = 1;
problem.addConstraint(row, LpSolve.LE, vpm.forecast[i]);
// System.out.println("Adding max constraint VP --> row: " +
// Arrays.toString(row) + " <= " + vpm.forecast[i]);
ih.volatileHandled++;
}
for (CouplerMessage cm : buildingMessage.couplerList) {
int index = i + 1 + nStepsMPC * ((ih.controllableHandled * 2) + ih.volatileHandled
+ (ih.couplerHandled * 2) + (ih.storageHandled * 2));
// MAX Constraints for heat
double[] row = new double[nCols + 1];
row[index] = cm.efficiencyHeat;
row[index + nStepsMPC] = cm.maxPower;
problem.addConstraint(row, LpSolve.LE, cm.maxPower);
// System.out.println("Adding max constraint coupler --> row: " +
// Arrays.toString(row) + " <= " + cm.installedPower);
// MIN Constraints for heat
double[] row2 = new double[nCols + 1];
row2[index] = -cm.efficiencyHeat;
row2[index + nStepsMPC] = -cm.minPower;
problem.addConstraint(row2, LpSolve.LE, -cm.minPower);
// System.out.println("Adding min constraint coupler --> row3: " +
// Arrays.toString(row2) + " <= -" + cm.minPower);
ih.couplerHandled++;
}
for (StorageMessage sm : buildingMessage.storageList) {
int index = i + 1 + nStepsMPC * ((ih.controllableHandled * 2) + ih.volatileHandled
+ (ih.couplerHandled * 2) + (ih.storageHandled * 2));
// MAX Constraints, for both el. and heat
double[] row = new double[nCols + 1];
row[index] = 1;
problem.addConstraint(row, LpSolve.LE, sm.maxDischarge);
// System.out.println("Adding max discharging ST --> row: " +
// Arrays.toString(row) + " <= " + sm.maxDischarge);
// MIN Constraints, for both el. and heat
double[] row2 = new double[nCols + 1];
row2[index + nStepsMPC] = 1;
problem.addConstraint(row2, LpSolve.LE, sm.maxLoad);
// System.out.println("Adding max charging --> row2: " + Arrays.toString(row2) +
// " <= " + sm.maxLoad);
ih.storageHandled++;
}
// Market Constraints:
// takes the minimum Electricity Buy Cap from all houses to be overtaken by Memap
// and multiplies it by the time-dependent function for the MaxBuyLimit, if defined in the global simulation settings.
int index = i + 1 + nStepsMPC * ((ih.controllableHandled * 2) + ih.volatileHandled
+ (ih.couplerHandled * 2) + (ih.storageHandled * 2));
double[] rowN = new double[nCols + 1];
for (DemandMessage dm : buildingMessage.demandList) {
if ((dm.networkType == NetworkType.ELECTRICITY) && (dm.varNetworkBuyCap != null)) {
if ( (dm.varNetworkBuyCap[i] < networkBuyCap[i])) {
networkBuyCap[i] = dm.varNetworkBuyCap[i]*energyPrices.getMaxBuyLimit(cts + i);
if (energyPrices.getMaxBuyLimit(cts + i) == 0) networkBuyCap[i] = 9999.0;
}
}
// if (dm.networkType == NetworkType.ELECTRICITY && i == 0) System.out.println("ElecBuy for " + buildingMessage.name + " limited to " + networkBuyCap[0]);
}
rowN[index] = 1;
problem.addConstraint(rowN, LpSolve.LE, networkBuyCap[i]);
// System.out.println(Arrays.toString(rowN) + ": ElecBuy for " + buildingMessage.name + " limited to " + networkBuyCap[i] + " at index " + index );
}
return problem;
}
public LpSolve createSOCBoundaries(LpSolve problem, BuildingMessage buildingMessage) throws LpSolveException {
int controllableHandled = buildingMessage.getNrOfControllableProducers();
int volatileHandled = buildingMessage.getNrOfVolatileProducers();
int couplerHandled = buildingMessage.getNrOfCouplers();
int storageHandled = 0;
double delta_time_factor = 24.0 / topologyConfig.getTimeStepsPerDay(); // = 0.25 fuer 96 Schritte /Tag
for (StorageMessage sm : buildingMessage.storageList) {
double SOC_perc = sm.stateOfCharge;
double standbyLosses = sm.storageLosses;
// check and enforce that SOC is between 0 and 1, due to numerical issues.
// if (SOC_perc >= 1) {
// SOC_perc = 1;
// }
// if (SOC_perc <= 0) {
// SOC_perc = 0;
// }
// New for SOC within 0 and 1 and standby loss consideration:
// helper parameters, only depend on time step length and storage parameters
double alpha = 1 - standbyLosses * delta_time_factor; // Units [-]
double beta_to = delta_time_factor/sm.capacity * sm.efficiencyCharge; // Units [h/kWh]
double beta_fm = delta_time_factor/(sm.capacity * sm.efficiencyDischarge); // Units [h/kWh]
// create new SOC constraints. They are not based on energy/capacity but solely on SOC, i.e. between 0 and 1
int index = 1 + nStepsMPC * ((controllableHandled * 2) + volatileHandled + (couplerHandled*2)+ (storageHandled*2) );
for (int i = 0; i < nStepsMPC; i++) {
double[] rowCHARGE = new double[nCols+1];
double[] rowDISCHARGE = new double[nCols+1];
for (int k = 0; k <= i; k++) {
// First add the factor for the discharge decision variable (x_fm)
rowCHARGE[index + k] = - beta_fm * Math.pow(alpha, i-k);
rowDISCHARGE[index + k] = beta_fm * Math.pow(alpha, i-k);
// Now add the factor for the charging decision variable (x_to):
rowCHARGE[index + k + nStepsMPC] = beta_to * Math.pow(alpha, i-k);
rowDISCHARGE[index + k + nStepsMPC] = - beta_to * Math.pow(alpha, i-k);
}
// Add the factor vectors to the problem as constraint:
problem.addConstraint(rowCHARGE, LpSolve.LE, (1-(SOC_perc * Math.pow(alpha, i+1))));
// for the last timestep in the horizon, the discharge limit is set to be 10%
if (i == (nStepsMPC-1) && (Double) sm.minimumSOC != null) {
problem.addConstraint(rowDISCHARGE, LpSolve.LE, ((SOC_perc * Math.pow(alpha, i+1)) - sm.minimumSOC));
} else {
problem.addConstraint(rowDISCHARGE, LpSolve.LE, (SOC_perc * Math.pow(alpha, i+1)));
}
}
storageHandled++;
}
return problem;
}
public LpSolve createObjectiveFunction(LpSolve problem, BuildingMessage buildingMessage) throws LpSolveException {
int[] colno = new int[nCols];
double[] row = new double[nCols];
int cts = currentTimeStep;
int counter = 0;
for (int i = 0; i < nStepsMPC; i++) {
int controllableHandled = 0;
int volatileHandled = 0;
int couplerHandled = 0;
int storageHandled = 0;
for (ProducerMessage pm : buildingMessage.controllableProducerList) {
int index = i + 1 + nStepsMPC
* ((controllableHandled * 2) + volatileHandled + (couplerHandled * 2) + (storageHandled * 2));
colno[counter] = index;
if (topologyController.getOptimizationCriteria() == OptimizationCriteria.EUR) {
row[counter++] = pm.operationalCostEUR;
// System.out.println("CP-costs " + pm.operationalCostEUR + " written at counter " + (counter-1));
}
if (topologyController.getOptimizationCriteria() == OptimizationCriteria.CO2) {
row[counter++] = pm.operationalCostCO2;
}
if (topologyController.getToolUsage() == ToolUsage.SERVER && pm.varOperationalCostEUR != null) {
// This part overwrites the previous costs if above condition is given
counter--;
// TODO: solve better
if (topologyController.getOptimizationCriteria() == OptimizationCriteria.EUR) {
row[counter++] = pm.varOperationalCostEUR[i];
// System.out.println("CP-costs " + pm.varOperationalCostEUR[i] + " overwritten at counter " + (counter-1));
}
if (topologyController.getOptimizationCriteria() == OptimizationCriteria.CO2) {
row[counter++] = pm.varOperationalCostEUR[i];
}
}
controllableHandled++;
}
for (ProducerMessage pm : buildingMessage.volatileProducerList) {
int index = i + 1 + nStepsMPC
* ((controllableHandled * 2) + volatileHandled + (couplerHandled * 2) + (storageHandled * 2));
colno[counter] = index;
if (topologyController.getOptimizationCriteria() == OptimizationCriteria.EUR) {
row[counter++] = pm.operationalCostEUR;
}
if (topologyController.getOptimizationCriteria() == OptimizationCriteria.CO2) {
row[counter++] = pm.operationalCostCO2;
}
volatileHandled++;
}
for (CouplerMessage cm : buildingMessage.couplerList) {
int index = i + 1 + nStepsMPC
* ((controllableHandled * 2) + volatileHandled + (couplerHandled * 2) + (storageHandled * 2));
colno[counter] = index;
if (topologyController.getOptimizationCriteria() == OptimizationCriteria.EUR) {
row[counter++] = cm.operationalCostEUR;
}
if (topologyController.getOptimizationCriteria() == OptimizationCriteria.CO2) {
row[counter++] = cm.operationalCostCO2;
}
if (topologyController.getToolUsage() == ToolUsage.SERVER && cm.varOperationalCostEUR != null) {
// This part overwrites the previous costs if above condition is given
counter = counter -1;
// TODO: solve better
if (topologyController.getOptimizationCriteria() == OptimizationCriteria.EUR) {
row[counter++] = cm.varOperationalCostEUR[i];
}
if (topologyController.getOptimizationCriteria() == OptimizationCriteria.CO2) {
row[counter++] = cm.varOperationalCostEUR[i];
}
}
couplerHandled++;
}
for (StorageMessage sm : buildingMessage.storageList) {
double chargingCosts = 0;
double dischargingCosts = 0;
if (topologyController.getOptimizationCriteria() == OptimizationCriteria.EUR) {
dischargingCosts = sm.operationalCostEUR;
chargingCosts = sm.operationalCostEUR;
}
if (topologyController.getOptimizationCriteria() == OptimizationCriteria.CO2) {
dischargingCosts = sm.operationalCostCO2;
chargingCosts = -0.0001; // TODO hardcoded heuristic as discussed in Github
}
int index = i + 1 + nStepsMPC
* ((controllableHandled * 2) + volatileHandled + (couplerHandled * 2) + (storageHandled * 2));
colno[counter] = index;
row[counter++] = dischargingCosts; // x_fm
colno[counter] = index + nStepsMPC;
row[counter++] = chargingCosts; // x_to
storageHandled++;
}
// Check which House has the lowest buy-price for electricity:
double[] bestBuyPrice = new double[nStepsMPC];
Arrays.fill(bestBuyPrice, 100.0); // fill with 100 €/kWh
double[] bestSellPrice = new double[nStepsMPC];
Arrays.fill(bestSellPrice, 0.0); // fill with 0 €/kWh
for (DemandMessage dm : buildingMessage.demandList) {
if (dm.networkType == NetworkType.ELECTRICITY) {
if (dm.varNetworkBuyCostEUR != null && dm.varNetworkBuyCostEUR[0] < bestBuyPrice[0])
bestBuyPrice = dm.varNetworkBuyCostEUR;
if (dm.varNetworkSellCostEUR != null && dm.varNetworkSellCostEUR[0] > bestSellPrice[0])
bestSellPrice = dm.varNetworkSellCostEUR;
}
}
// buy
int index = i + 1 + nStepsMPC
* ((controllableHandled * 2) + volatileHandled + (couplerHandled * 2) + (storageHandled * 2));
if (topologyController.getOptimizationCriteria() == OptimizationCriteria.EUR) {
// buy
colno[counter] = index;
row[counter++] = energyPrices.getElecBuyingPrice(cts+i);
// sell
colno[counter] = index+nStepsMPC;
row[counter++] = -energyPrices.getElecSellingPrice(cts+i);
}
if (topologyController.getOptimizationCriteria() == OptimizationCriteria.CO2) {
// buy
colno[counter] = index;
row[counter++] = energyPrices.getCO2EmissionFactor(cts+i);
// sell, no compensation for selling
colno[counter] = index+nStepsMPC;
row[counter++] = 0;
}
if (topologyController.getToolUsage() == ToolUsage.SERVER) {
// This part overwrites the previous costs if above condition is given
if (topologyController.getOptimizationCriteria() == OptimizationCriteria.EUR) {
// TODO: Better solution for this to avoid double code for server / planning
counter = counter - 2;
// buy
colno[counter] = index;
row[counter++] = bestBuyPrice[i];
// sell
colno[counter] = index+nStepsMPC;
row[counter++] = -bestSellPrice[i];
}
if (topologyController.getOptimizationCriteria() == OptimizationCriteria.CO2) {
// buy
colno[counter] = index;
row[counter++] = energyPrices.getCO2EmissionFactor(cts+i);
// sell, no compensation for selling
colno[counter] = index+nStepsMPC;
row[counter++] = 0;
}
}
}
/* set the objective in lpsolve */
problem.setObjFnex(counter, row, colno);
/* set the object direction to minimize */
problem.setMinim();
return problem;
}
}
|
apache-2.0
|
SuperMap/iClient-for-Silverlight
|
SuperMap.Web.iServerJava2/Query/SqlParam.cs
|
4581
|
using System.Collections.Generic;
namespace SuperMap.Web.iServerJava2
{
/// <summary>
/// <para>${iServer2_sqlParam_Title}</para>
/// <para>${iServer2_sqlParam_Description}</para>
/// </summary>
public class SqlParam
{
/// <summary>${iServer2_sqlParam_constructor_None_D}</summary>
public SqlParam()
{
}
/// <summary>${iServer2_sqlParam_attribute_ids_D}</summary>
public IList<int> IDs { get; set; }
/// <summary>${iServer2_sqlParam_attribute_returnFields_D}</summary>
public IList<string> ReturnFields { get; set; }
/// <summary>${iServer2_sqlParam_attribute_sortClause_D}</summary>
public string SortClause { get; set; }
/// <summary>${iServer2_sqlParam_attribute_whereClause_D}</summary>
public string WhereClause { get; set; }
/// <summary>${iServer2_sqlParam_attribute_groupClause_D}</summary>
public string GroupClause { get; set; }
internal static string ToJson(SqlParam sqlParam)
{
if (sqlParam == null)
{
return null;
}
//if (mapName.Contains("@"))
//{
// string str = mapName.Substring(0, mapName.IndexOf("@"));
//}
string json = "{";
List<string> list = new List<string>();
if (!string.IsNullOrEmpty(sqlParam.WhereClause))
{
list.Add(string.Format("\"whereClause\":\"{0}\"", Bridge.EncodeString(sqlParam.WhereClause)));
//if (!sqlParam.WhereClause.Contains(".") && mapName.Contains("@"))
//{
// string str = mapName.Substring(0, mapName.IndexOf("@"));
// //list.Add(string.Format("\"whereClause\":\"{0}.{1}\"", str, Bridge.EncodeString(sqlParam.WhereClause)));
// list.Add(string.Format("\"whereClause\":\"{0}\"", Bridge.EncodeString(sqlParam.WhereClause)));
//}
//else
//{
// list.Add(string.Format("\"whereClause\":\"{0}\"", Bridge.EncodeString(sqlParam.WhereClause)));
//}
}
if (!string.IsNullOrEmpty(sqlParam.SortClause))
{
list.Add(string.Format("\"sortClause\":\"{0}\"", Bridge.EncodeString(sqlParam.SortClause)));
//if (!sqlParam.SortClause.Contains(".") && mapName.Contains("@"))
//{
// string str = mapName.Substring(0, mapName.IndexOf("@"));
// list.Add(string.Format("\"sortClause\":\"{0}.{1}\"", str, Bridge.EncodeString(sqlParam.SortClause)));
//}
//else
//{
// list.Add(string.Format("\"sortClause\":\"{0}\"", Bridge.EncodeString(sqlParam.SortClause)));
//}
}
if (!string.IsNullOrEmpty(sqlParam.GroupClause))
{
list.Add(string.Format("\"groupClause\":\"{0}\"", Bridge.EncodeString(sqlParam.GroupClause)));
//if (!sqlParam.GroupClause.Contains(".") && mapName.Contains("@"))
//{
// string str = mapName.Substring(0, mapName.IndexOf("@"));
// list.Add(string.Format("\"groupClause\":\"{0}.{1}\"", str, Bridge.EncodeString(sqlParam.GroupClause)));
//}
//else
//{
// list.Add(string.Format("\"groupClause\":\"{0}\"", Bridge.EncodeString(sqlParam.GroupClause)));
//}
}
//
if (sqlParam.ReturnFields != null && sqlParam.ReturnFields.Count > 0)
{
List<string> temp = new List<string>();
for (int i = 0; i < sqlParam.ReturnFields.Count; i++)
{
temp.Add(string.Format("\"{0}\"", sqlParam.ReturnFields[i]));
}
list.Add(string.Format("\"returnFields\":[{0}]", string.Join(",", temp.ToArray())));
}
if (sqlParam.IDs != null && sqlParam.IDs.Count > 0)
{
List<string> temp = new List<string>();
foreach (int id in sqlParam.IDs)
{
temp.Add(id.ToString());
}
list.Add(string.Format("\"ids\":[{0}]", string.Join(",", temp.ToArray())));
}
json += string.Join(",", list.ToArray());
json += "}";
return json;
}
}
}
|
apache-2.0
|
VHAINNOVATIONS/Telepathology
|
Source/Java/CoreRouter/main/src/java/gov/va/med/imaging/core/router/commands/storage/datasource/PostArtifactRetentionPolicyCommandImpl.java
|
3120
|
/**
*
Package: MAG - VistA Imaging
WARNING: Per VHA Directive 2004-038, this routine should not be modified.
Date Created: Apr, 2010
Site Name: Washington OI Field Office, Silver Spring, MD
Developer: vhaiswlouthj
Description: DICOM Study cache manager. Maintains the cache of study instances
and expires old studies after 15 minutes.
;; +--------------------------------------------------------------------+
;; Property of the US Government.
;; No permission to copy or redistribute this software is given.
;; Use of unreleased versions of this software requires the user
;; to execute a written test agreement with the VistA Imaging
;; Development Office of the Department of Veterans Affairs,
;; telephone (301) 734-0100.
;;
;; The Food and Drug Administration classifies this software as
;; a Class II medical device. As such, it may not be changed
;; in any way. Modifications to this software may result in an
;; adulterated medical device under 21CFR820, the use of which
;; is considered to be a violation of US Federal Statutes.
;; +--------------------------------------------------------------------+
*/
package gov.va.med.imaging.core.router.commands.storage.datasource;
import gov.va.med.imaging.core.interfaces.exceptions.ConnectionException;
import gov.va.med.imaging.core.interfaces.exceptions.MethodException;
import gov.va.med.imaging.core.router.commands.storage.AbstractStorageDataSourceCommandImpl;
import gov.va.med.imaging.datasource.StorageDataSourceSpi;
import gov.va.med.imaging.exchange.business.storage.ArtifactRetentionPolicy;
public class PostArtifactRetentionPolicyCommandImpl
extends AbstractStorageDataSourceCommandImpl<ArtifactRetentionPolicy>
{
private static final long serialVersionUID = 1L;
private static final String SPI_METHOD_NAME = "createArtifactRetentionPolicy";
private final ArtifactRetentionPolicy artifactRetentionPolicy;
public PostArtifactRetentionPolicyCommandImpl(ArtifactRetentionPolicy artifactRetentionPolicy)
{
super();
this.artifactRetentionPolicy = artifactRetentionPolicy;
}
@Override
protected Class<?>[] getSpiMethodParameterTypes() {
return new Class<?>[]{ArtifactRetentionPolicy.class};
}
@Override
protected Object[] getSpiMethodParameters() {
return new Object[]{artifactRetentionPolicy} ;
}
@Override
protected String parameterToString()
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see gov.va.med.imaging.core.router.AbstractDataSourceCommandImpl#getCommandResult(gov.va.med.imaging.datasource.VersionableDataSourceSpi)
*/
@Override
protected ArtifactRetentionPolicy getCommandResult(StorageDataSourceSpi spi)
throws ConnectionException, MethodException
{
return spi.createArtifactRetentionPolicy(artifactRetentionPolicy);
}
/* (non-Javadoc)
* @see gov.va.med.imaging.core.router.AbstractDataSourceCommandImpl#getSpiMethodName()
*/
@Override
protected String getSpiMethodName()
{
return SPI_METHOD_NAME;
}
}
|
apache-2.0
|
Geomatys/sis
|
core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/InverseOperationMethod.java
|
9914
|
/*
* 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.sis.referencing.operation;
import java.util.Map;
import java.util.HashMap;
import java.util.Collection;
import javax.xml.bind.annotation.XmlTransient;
import javax.measure.Unit;
import org.opengis.metadata.Identifier;
import org.opengis.metadata.quality.PositionalAccuracy;
import org.opengis.util.InternationalString;
import org.opengis.parameter.ParameterValue;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.parameter.ParameterDescriptor;
import org.opengis.parameter.GeneralParameterValue;
import org.opengis.parameter.GeneralParameterDescriptor;
import org.opengis.referencing.operation.OperationMethod;
import org.opengis.referencing.operation.SingleOperation;
import org.apache.sis.internal.metadata.ReferencingServices;
import org.apache.sis.internal.referencing.SignReversalComment;
import org.apache.sis.internal.referencing.provider.AbstractProvider;
import org.apache.sis.metadata.iso.ImmutableIdentifier;
import org.apache.sis.util.collection.Containers;
import org.apache.sis.util.Deprecable;
/**
* Description of the inverse of another method. This class should be used only when no operation is defined
* for the inverse, or when the inverse operation can not be represented by inverting the sign of parameters.
*
* @author Martin Desruisseaux (Geomatys)
* @version 0.8
* @since 0.7
* @module
*/
@XmlTransient
final class InverseOperationMethod extends DefaultOperationMethod {
/**
* For cross-version compatibility.
*/
private static final long serialVersionUID = 6395008927817202180L;
/**
* The original operation method for which this {@code InverseOperationMethod} is the inverse.
*/
private final OperationMethod inverse;
/**
* Creates the inverse of the given method.
*/
private InverseOperationMethod(final Map<String,?> properties, final OperationMethod method) {
super(properties, method.getTargetDimensions(), method.getSourceDimensions(), method.getParameters());
inverse = method;
}
/**
* Returns {@code true} if the given method flags itself as invertible.
*/
private static boolean isInvertible(final OperationMethod method) {
return method instanceof AbstractProvider && ((AbstractProvider) method).isInvertible();
}
/**
* Returns or create the inverse of the given operation method. If the same operation method can be used
* for the inverse operation either with the exact same parameter values or with the sign of some values
* reversed, then the given method is returned as-is. Otherwise a synthetic method is created.
*/
static OperationMethod create(final OperationMethod method) {
if (method instanceof InverseOperationMethod) {
return ((InverseOperationMethod) method).inverse;
}
if (!isInvertible(method)) {
boolean useSameParameters = false;
for (final GeneralParameterDescriptor descriptor : method.getParameters().descriptors()) {
useSameParameters = (descriptor.getRemarks() instanceof SignReversalComment);
if (!useSameParameters) break;
}
if (!useSameParameters) {
Identifier name = method.getName();
name = new ImmutableIdentifier(null, null, "Inverse of " + name.getCode());
final Map<String,Object> properties = new HashMap<>(6);
properties.put(NAME_KEY, name);
properties.put(FORMULA_KEY, method.getFormula());
properties.put(REMARKS_KEY, method.getRemarks());
if (method instanceof Deprecable) {
properties.put(DEPRECATED_KEY, ((Deprecable) method).isDeprecated());
}
return new InverseOperationMethod(properties, method);
}
}
return method;
}
/**
* Infers the properties to give to an inverse coordinate operation.
* The returned map will contains three kind of information:
*
* <ul>
* <li>Metadata (domain of validity, accuracy)</li>
* <li>Parameter values, if possible</li>
* </ul>
*
* This method copies accuracy and domain of validity metadata from the given operation.
* We presume that the inverse operation has the same accuracy than the direct operation.
*
* <div class="note"><b>Note:</b>
* in many cases, the inverse operation is numerically less accurate than the direct operation because it
* uses approximations like series expansions or iterative methods. However the numerical errors caused by
* those approximations are not of interest here, because they are usually much smaller than the inaccuracy
* due to the stochastic nature of coordinate transformations (not to be confused with coordinate conversions;
* see ISO 19111 for more information).</div>
*
* If the inverse of the given operation can be represented by inverting the sign of all numerical
* parameter values, then this method copies also those parameters in a {@code "parameters"} entry.
*
* @param source the operation for which to get the inverse parameters.
* @param target where to store the inverse parameters.
*/
static void properties(final SingleOperation source, final Map<String,Object> target) {
target.put(SingleOperation.DOMAIN_OF_VALIDITY_KEY, source.getDomainOfValidity());
final Collection<PositionalAccuracy> accuracy = source.getCoordinateOperationAccuracy();
if (!Containers.isNullOrEmpty(accuracy)) {
target.put(SingleOperation.COORDINATE_OPERATION_ACCURACY_KEY,
accuracy.toArray(new PositionalAccuracy[accuracy.size()]));
}
/*
* If the inverse of the given operation can be represented by inverting the sign of all numerical
* parameter values, copies those parameters in a "parameters" entry in the properties map.
* Otherwise does nothing.
*/
final ParameterValueGroup parameters = source.getParameterValues();
final ParameterValueGroup copy = parameters.getDescriptor().createValue();
for (final GeneralParameterValue gp : parameters.values()) {
if (gp instanceof ParameterValue<?>) {
final ParameterValue<?> src = (ParameterValue<?>) gp;
final Object value = src.getValue();
if (value instanceof Number) {
final ParameterDescriptor<?> descriptor = src.getDescriptor();
final InternationalString remarks = descriptor.getRemarks();
if (remarks != SignReversalComment.SAME) {
if (remarks != SignReversalComment.OPPOSITE) {
/*
* The parameter descriptor does not specify whether the values for the inverse operation
* have the same sign or opposite sign. We could heuristically presume that we can invert
* the sign if the minimum value has the opposite sign than the maximum value (as in the
* [-10 … 10] range), but such assumption is dangerous. For example the values in a matrix
* could be bounded to a range like [-1 … 1], which would mislead above heuristic rule.
*
* Note that abandoning here does not mean that we will never know the parameter values.
* As a fallback, AbstractCoordinateOperation will try to get the parameter values from
* the MathTransform. This is the appropriate thing to do at least for Affine operation.
*/
return;
}
/*
* The parameter value of the inverse operation is (or is presumed to be) the negative of
* the parameter value of the source operation. We need to preserve units of measurement
* if they were specified.
*/
final ParameterValue<?> tgt = copy.parameter(descriptor.getName().getCode());
final Unit<?> unit = src.getUnit();
if (unit != null) {
tgt.setValue(-src.doubleValue(), unit);
} else if (value instanceof Integer || value instanceof Short || value instanceof Byte) {
tgt.setValue(-src.intValue());
} else {
tgt.setValue(-src.doubleValue());
}
// No need to add 'tgt' to 'copy' since it was done by the call to copy.parameter(…).
continue;
}
}
}
copy.values().add(gp);
}
target.put(ReferencingServices.PARAMETERS_KEY, copy);
}
}
|
apache-2.0
|
Lesha-spr/greed
|
public/src/actions/async/async.actions.js
|
191
|
import alt from './../../alt';
class AsyncActions {
constructor() {
this.generateActions(
'toggle'
);
}
}
export default alt.createActions(AsyncActions);
|
apache-2.0
|
lazarevalex/jsviewer
|
README.md
|
5730
|
# JavaScript Viewer for ArcGIS
Êîíôèãóðèðîåìîå âåá-ïðèëîæåíèå, ïðåäíàçíà÷åííîå äëÿ ðàáîòû ñ ArcGIS for Server ÷åðåç REST-èíòåðôåéñ.
##Ñòðóêòóðà âåá-ïðèëîæåíèÿ
* index.html - ãîëîâíîé ôàéë âåá-ïðèëîæåíèÿ
* proxy.ashx - ïðîêñè-ñòðàíèöà âåá-ïðèëîæåíèÿ
* proxy.config - êîíôèãóðàöèîííûé ôàéë ïðîêñè-ñòðàíèöû
* config.xml - êîíôèãóðàöèîííûé ôàéë âåá-ïðèëîæåíèÿ
* config_help.txt - èíñòðóêöèÿ ïî íàñòðîéêå êîíôèãóðàöèîííîãî ôàéëà config.xml
* readme.txt - ôàéë ñïðàâêè
* main - ïàïêà, ñîäåðæàùàÿ îñíîâíûå ðàáî÷èå ôàéëû âåá-ïðèëîæåíèÿ
* css - ïàïêà ñ ôàéëàìè css äëÿ íàñòðîéêè ñòèëåé êàðòû è âèäæåòîâ
* images - ïàïêà ñ èçîáðàæåíèÿìè, êîòîðûå èñïîëüçóþòñÿ â ïðèëîæåíèè
##Íàñòðîéêà âåá-ïðèëîæåíèÿ
Äëÿ íàñòðîéêè âåá-ïðèëîæåíèÿ íåîáõîäèìî îòðåäàêòèðîâàòü ôàéë config.xml. Èíñòðóêöèÿ ïî íàñòðîéêå íàõîäèòñÿ â ôàéëå config_help.txt.
##Ôóíêöèîíàëüíîñòü ïðèëîæåíèÿ
* Îòîáðàæåíèå áàçîâûõ êàðò (c êîðïîðàòèâíîãî ArcGIS for Server, êàðò ArcGIS Online, êàðò Google Maps), ïåðåêëþ÷åíèå áàçîâûõ êàðò
* Îòîáðàæåíèå êýøèðîâàííûõ, äèíàìè÷åñêèõ è âåêòîðíûõ ñëîåâ
* Cäâèã è ìàñøòàáèðîâàíèå êàðòû
* Ñïèñîê ñëîåâ è ëåãåíäà, ïðîçðà÷íîñòü ñëîåâ
* Ôèëüòðàöèÿ îáúåêòîâ ïî äàòå
* Àâòîðèçàöèÿ ïðè ïîäêëþ÷åíèè ê âåá-ñåðâèñàì (ïîðòàëüíàÿ àâòîðèçàöèÿ OAuth 2, àâòîðèçàöèÿ ñðåäñòâàìè ArcGIS for Server)
* Çàêëàäêè
* Èíôîðìàöèÿ
* Èäåíòèôèêàöèÿ îáúåêòîâ íà êàðòå, îòîáðàæåíèå èíôîðìàöèè îá îáúåêòîâ (ïîäñâåòêà ãåîìåòðèè, çíà÷åíèÿ ïîëåé, ãðàôèêè, äèàãðàììû è èçîáðàæåíèÿ)
* Ðåäàêòèðîâàíèå äàííûõ (âåêòîðíûå ñëîè íå ïåðåãðóæàþò ïàìÿòü áðàóçåðà)
* Èçìåðåíèÿ ïî êàðòå
* Àäðåñíûé ïîèñê (ãåîêîäèðîâàíèå)
* Ïîñòðîåíèå ìàðøðóòîâ
* Ýêñïîðò êàðòû â PDF èëè PNG
##Ðàáîòà ïðèëîæåíèÿ â ñåòè Èíòåðíåò è ëîêàëüíîé ñåòè
Ïðèëîæåíèå ìîæåò ðàáîòàòü êàê ïðè íàëè÷èè Èíòåðíåò-ïîäêëþ÷åíèÿ, òàê è áåç íåãî.
Ïðè ðàáîòå â ëîêàëüíîé ñåòè ïîòðåáóåòñÿ äîïîëíèòåëüíî ñêà÷èâàòü è óñòàíîâèòü áèáëèîòåêó [ArcGIS API for JavaScript](https://developers.arcgis.com/en/javascript/jshelp/intro_accessapi.html).
Ïðè ðàáîòå â ëîêàëüíîé ñåòè ìîæåò ïîòðåáîâàòüñÿ äîïîëíèòåëüíî ñêà÷àòü è óñòàíîâèòü [ìîäóëü agsjs](http://gmaps-utility-gis.googlecode.com/svn/tags/agsjs) áèáëèîòåêè [gmaps-utility-gis](http://gmaps-utility-gis.googlecode.com).
##Ññûëêè íà âåá-ñåðâèñû
 ôàéëå config.xml ìîæíî óêàçûâàòü ïðÿìûå ññûëêè íà âåá-ñåðâèñû ArcGIS for Server (ïàðàìåòð url).
Äëÿ âåá-ñåðâèñîâ, çàðåãèñòðèðîâàííûõ â ArcGIS Online / Portal for ArcGIS ìîæíî óêàçûâàòü èäåíòèôèêàòîðû ýòèõ ñåðâèñîâ â ArcGIS Online / Portal for ArcGIS (ïàðàìåòð portalID). Ïðè èñïîëüçîâàíèè òàêèõ ñåðâèñîâ îáÿçàòåëüíî ïîäêëþ÷åíèå ñåêöèè <portal> â config.xml.
##Ïîääåðæèâàåìûå áðàóçåðû
Ïîääåðæèâàþòñÿ ðîâíî òå æå áðàóçåðû, ÷òî è [áðàóçåðû, ïîääåðæèâàåìûå ArcGIS API for JavaScript](https://developers.arcgis.com/en/javascript/jshelp/supported_browsers.html).
##Ëèöåíçèÿ
Copyright 2013 Esri CIS
Äåéñòâóåò ëèöåíèÿ [Apache License, âåðñèÿ 2.0] (http://www.apache.org/licenses/LICENSE-2.0).
Åñëè ýòî íå ïðåäóñìîòðåíî ïðèìåíèìûìè çàêîíàìè èëè íå ñîãëàñîâàíî â ïèñüìåííîé ôîðìå, ïðîãðàììíîå îáåñïå÷åíèå ðàñïðîñòðàíÿåòñÿ
«ÊÀÊ ÅÑÒÜ», ÁÅÇ ÃÀÐÀÍÒÈÉ È ÓÑËÎÂÈÉ ËÞÁÎÃÎ ÐÎÄÀ, ÿâíûõ èëè ïîäðàçóìåâàåìûõ.
##Èñïîëüçîâàíèå ñòîðîííèõ áèáëèîòåê
Ïðèëîæåíèå èñïîëüçóåò äîïîëíèòåëüíûå ñòîðîííèå áèáëèîòåêè:
* [ArcGIS API for JavaScript](https://developers.arcgis.com/en/javascript/), [ëèöåíçèîííîå ñîãëàøåíèå](https://developers.arcgis.com/en/javascript/jshelp/terms.html)
* [gmaps-utility-gis](https://code.google.com/p/gmaps-utility-gis/), [ëèöåíçèÿ Apache License, âåðñèÿ 2.0](http://www.apache.org/licenses/LICENSE-2.0)
##Èñïîëüçîâàíèå ñòîðîííèõ ðåñóðñîâû
Ïðèëîæåíèå ìîæåò èñïîëüçîâàòü ñòîðîííèå ðåñóðñû:
* [Áàçîâûå êàðòû ArcGIS Online](http://resources.arcgis.com/en/communities/arcgis-content/029700000044000000.htm#s=0&n=30&d=1&md=acomt-online:10000) ([ñîãëàøåíèå îá èñïîëüçîâàíèè](http://downloads2.esri.com/ArcGISOnline/docs/tou_summary.pdf))
* [Àíàëèòè÷åñêèå ñåðâèñû ArcGIS Online](http://resources.arcgis.com/en/communities/arcgis-content/029700000044000000.htm#s=0&n=30&d=1&md=acomt-online:00001) ([ñîãëàøåíèå îá èñïîëüçîâàíèè](http://downloads2.esri.com/ArcGISOnline/docs/tou_summary.pdf))
* [Êàðòû Google Maps] (https://maps.google.com/) ([ñîãëàøåíèå îá èñïîëüçîâàíèè JavaScript API Google Êàðò] (https://developers.google.com/maps/documentation/javascript/usage?hl=ru))
* [Êàðòà OpenStreetMap](http://www.openstreetmap.org/) ([ñîãëàøåíèå îá èñïîëüçîâàíèè](http://www.openstreetmap.org/copyright))
##Îáíîâëåíèÿ
v.1.1 (08/11/2013):
* Èñïðàâëåíà îøèáêà èäåíòèôèêàöèè îáúåêòîâ ïðè çàïóñêå ïðèëîæåíèÿ íà ìîáèëüíûõ óñòðîéñòâàõ iOS è Android
* Èñïðàâëåíû íåñîîòâåòñòâèÿ ìåæäó êîäîì ïðèëîæåíèÿ è ñïðàâêîé ïî ðàáîòå ñ ïðèëîæåíèåì
* Áàçîâóþ êàðòó èç ñåêöèè <basemaps> â ôàéëå config.xml òåïåðü ìîæíî èñïîëüçîâàòü ïî óìîë÷àíèþ ïðè çàãðóçêå ïðèëîæåíèÿ
v.1.2 (25/12/2013):
* Ïðèëîæåíèå ïåðåâåðåäíî íà âåðñèþ ArcGIS API for JavaScript 3.7;
* Íàñòðîéêà âèäèìîñòè è ñòèëÿ ýëåìåíòà óïðàâëåíèÿ ìàñøòàáîì ïåðåíåñåíà èç ñåêöèè map.options â ñåêöèþ dijits.dijit ñ type="navigation" â êîíôèãóðàöèîííîì ôàéëå;
* Äîáàâëåí íîâûé òèï âèäæåòà - íàâèãàöèÿ (dijits.dijit type = "navigation"). Âèäæåò âêëþ÷àåò òðè ýëåìåíòà: ýëåìåíò óïðàâëåíèÿ ìàñøòàáîì, êíîïêà "Íà÷àëüíûé ýêñòåíò" è êíîïêà "Ìîå ìåñòîïîëîæåíèå". Âèäèìîñòü êàæäîãî ýëåìåíòà âèäæåòà íàâèãàöèè âêëþ÷àåòñÿ è îòêëþ÷àåòñÿ â êîíôèãóðàöèîííîì ôàéëå â ñåêöèè dijits.dijit type = "navigation";
* Èñïðàâëåíà îøèáêà äâîéíîé èäåíòèôèêàöèè îáúåêòîâ âåêòîðíîãî ñëîÿ
* Äîáàâëåíà âîçìîæíîñòü íå âêëþ÷àòü ïîäñëîè ñëîÿ â âèäæåò òàáëèöû ñîäåðæàíèÿ (toc). Îïöèÿ íàñòðàèâàåòñÿ â êîíôèãóðàöèîííîì ôàéëå ñ ïîìîùüþ ïàðàìåòðà tocSublayers â ñåêöèè layer
* Ôàéëû readme.txt è config_help.txt ñîõðàíåíû â êîäèðîâêå UTF-8
|
apache-2.0
|
wgroth2/WFJavaAppExample
|
src/test/java/com/vmware/broth/quickstart/AppTest.java
|
655
|
package com.vmware.broth.quickstart;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Malvaceae/Triumfetta/Triumfetta kundelungensis/README.md
|
196
|
# Triumfetta kundelungensis I.Adamska & Lisowski SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
WASdev/sample.microservices.12factorapp
|
src/test/java/net/wasdev/twelvefactorapp/it/test/EndpointTest.java
|
5033
|
package net.wasdev.twelvefactorapp.it.test;
import static org.junit.Assert.*;
import net.wasdev.twelvefactorapp.ResponseHandler.RequestType;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.Before;
import org.junit.After;
import org.junit.Assume;
import javax.json.Json;
import javax.json.JsonObject;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* This tests that sending GET, PUT and POST requests to the JaxrsHttpReceiver class
* don't return exceptions.
*/
public class EndpointTest {
private static String port;
private static String contextRoot;
private String testDatabase = "testing";
private boolean databaseConfigured = false;
@BeforeClass
public static void beforeClass() {
port = System.getProperty("liberty.test.port");
contextRoot = "http://localhost:" + port + "/12-factor-application/";
}
@Before
public void setup() {
// Database config must be stored in local environment variables
databaseConfigured = System.getenv("dbUsername") != null && System.getenv("dbPassword") != null
&& System.getenv("dbUrl") != null;
String url = contextRoot;
System.out.println("Creating database");
Entity<String> ent = Entity.entity(testDatabase, MediaType.APPLICATION_JSON);
Response response = sendRequest(url, RequestType.PUT, ent);
System.out.println("Creating database status: " + response.getStatus());
response.close();
}
@After
public void cleanUp() {
String url = contextRoot + testDatabase;
System.out.println("Deleting database");
Response response = sendRequest(url, RequestType.DELETE);
response.close();
}
@Test
public void testGet() {
Assume.assumeTrue(databaseConfigured);
String url = contextRoot;
System.out.println("Testing " + url);
Response response = sendRequest(url, RequestType.GET);
String responseString = response.readEntity(String.class);
int responseCode = response.getStatus();
response.close();
System.out.println("Returned " + responseString);
assertTrue("Incorrect response code: " + responseCode + " Response string is " + responseString,
responseCode == 200);
}
@Test
public void testGetDatabase() {
Assume.assumeTrue(databaseConfigured);
String url = contextRoot + testDatabase;
System.out.println("Testing " + url);
Response response = sendRequest(url, RequestType.GET);
String responseString = response.readEntity(String.class);
int responseCode = response.getStatus();
response.close();
System.out.println("Returned " + responseString);
assertTrue("Incorrect response code: " + responseCode + " Response string is " + responseString,
responseCode == 200);
}
@Test
public void testPost() {
Assume.assumeTrue(databaseConfigured);
String url = contextRoot + testDatabase;
System.out.println("Testing " + url);
JsonObject data = Json.createObjectBuilder().add("weather", "sunny").build();
String dataString = data.toString();
Entity<String> ent = Entity.entity(dataString, MediaType.APPLICATION_JSON);
Response response = sendRequest(url, RequestType.POST, ent);
String responseString = response.readEntity(String.class);
int responseCode = response.getStatus();
response.close();
System.out.println("Returned " + responseString);
assertTrue("Incorrect response code: " + responseCode + " Response string is " + responseString,
responseCode == 200);
}
// If the database configuration cannot be reached make sure the app fails gracefully
@Test
public void testDatabaseNotConfigured() {
Assume.assumeFalse(databaseConfigured);
String url = contextRoot;
System.out.println("Testing " + url);
Response response = sendRequest(url, RequestType.GET);
String responseString = response.readEntity(String.class);
int responseCode = response.getStatus();
response.close();
System.out.println("Returned " + responseString);
assertTrue("Incorrect response code: " + responseCode + " Response string is " + responseString,
responseCode == 500);
assertTrue("Application returned error: " + responseString, responseString.contains("{\"Exception\":\"Database cannot be accessed at this time"));
}
public Response sendRequest(String url, RequestType requestType) {
return sendRequest(url, requestType, null);
}
public Response sendRequest(String url, RequestType requestType, Entity<?> ent) {
Client client = ClientBuilder.newClient();
System.out.println("Testing " + url);
WebTarget target = client.target(url);
Invocation.Builder invoBuild = target.request();
Response response = invoBuild.build(requestType.toString(), ent).invoke();
return response;
}
}
|
apache-2.0
|
bhardesty/qpid-dispatch
|
src/message_private.h
|
8819
|
#ifndef __message_private_h__
#define __message_private_h__ 1
/*
* 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.
*/
#include <qpid/dispatch/message.h>
#include <qpid/dispatch/alloc.h>
#include <qpid/dispatch/threading.h>
#include <qpid/dispatch/atomic.h>
/** @file
* Message representation.
*
* Architecture of the message module:
*
* +--------------+ +----------------------+
* | | | |
* | qd_message_t |----------->| qd_message_content_t |
* | | +----->| |
* +--------------+ | +----------------------+
* | |
* +--------------+ | | +-------------+ +-------------+ +-------------+
* | | | +--->| qd_buffer_t |-->| qd_buffer_t |-->| qd_buffer_t |--/
* | qd_message_t |-----+ +-------------+ +-------------+ +-------------+
* | |
* +--------------+
*
* The message module provides chained-fixed-sized-buffer storage of message content with multiple
* references. If a message is received and is to be queued for multiple destinations, there is only
* one copy of the message content in memory but multiple lightweight references to the content.
*
* @internal
* @{
*/
typedef struct {
qd_buffer_t *buffer; // Buffer that contains the first octet of the field, null if the field is not present
size_t offset; // Offset in the buffer to the first octet of the header
size_t length; // Length of the field or zero if unneeded
size_t hdr_length; // Length of the field's header (not included in the length of the field)
bool parsed; // True iff the buffer chain has been parsed to find this field
uint8_t tag; // Type tag of the field
} qd_field_location_t;
// TODO - consider using pointers to qd_field_location_t below to save memory
// TODO - provide a way to allocate a message without a lock for the link-routing case.
// It's likely that link-routing will cause no contention for the message content.
//
typedef struct {
sys_mutex_t *lock;
sys_atomic_t ref_count; // The number of messages referencing this
qd_buffer_list_t buffers; // The buffer chain containing the message
qd_buffer_t *pending; // Buffer owned by and filled by qd_message_receive
uint64_t buffers_freed; // count of large msg buffers freed on send
qd_field_location_t section_message_header; // The message header list
qd_field_location_t section_delivery_annotation; // The delivery annotation map
qd_field_location_t section_message_annotation; // The message annotation map
qd_field_location_t section_message_properties; // The message properties list
qd_field_location_t section_application_properties; // The application properties list
qd_field_location_t section_body; // The message body: Data
qd_field_location_t section_footer; // The footer
qd_field_location_t field_user_annotations; // Opaque user message annotations, not a real field.
qd_field_location_t field_message_id; // The string value of the message-id
qd_field_location_t field_user_id; // The string value of the user-id
qd_field_location_t field_to; // The string value of the to field
qd_field_location_t field_subject; // The string value of the subject field
qd_field_location_t field_reply_to; // The string value of the reply_to field
qd_field_location_t field_correlation_id; // The string value of the correlation_id field
qd_field_location_t field_content_type;
qd_field_location_t field_content_encoding;
qd_field_location_t field_absolute_expiry_time;
qd_field_location_t field_creation_time;
qd_field_location_t field_group_id;
qd_field_location_t field_group_sequence;
qd_field_location_t field_reply_to_group_id;
qd_field_location_t body; // The body of the message
qd_buffer_t *parse_buffer;
unsigned char *parse_cursor;
qd_message_depth_t parse_depth;
qd_iterator_t *ma_field_iter_in; // 'message field iterator' for msg.FIELD_MESSAGE_ANNOTATION
qd_iterator_pointer_t ma_user_annotation_blob; // Original user annotations
// with router annotations stripped
uint32_t ma_count; // Number of map elements in blob
// after the router fields stripped
qd_parsed_field_t *ma_pf_ingress;
qd_parsed_field_t *ma_pf_phase;
qd_parsed_field_t *ma_pf_to_override;
qd_parsed_field_t *ma_pf_trace;
int ma_int_phase;
uint64_t max_message_size; // configured max; 0 if no max to enforce
uint64_t bytes_received; // bytes returned by pn_link_recv() when enforcing max_message_size
uint32_t fanout; // The number of receivers for this message, including in-process subscribers.
qd_link_t_sp input_link_sp; // message received on this link
bool ma_parsed; // have parsed annotations in incoming message
bool discard; // Should this message be discarded?
bool receive_complete; // true if the message has been completely received, false otherwise
bool q2_input_holdoff; // hold off calling pn_link_recv
bool aborted; // receive completed with abort flag set
bool disable_q2_holdoff; // Disable the Q2 flow control
bool priority_parsed;
bool priority_present;
bool oversize; // policy oversize handling in effect
uint8_t priority; // The priority of this message
} qd_message_content_t;
typedef struct {
qd_iterator_pointer_t cursor; // A pointer to the current location of the outgoing byte stream.
qd_message_depth_t message_depth; // What is the depth of the message that has been received so far
qd_message_depth_t sent_depth; // How much of the message has been sent? QD_DEPTH_NONE means nothing has been sent so far, QD_DEPTH_HEADER means the header has already been sent, dont send it again and so on.
qd_message_content_t *content; // The actual content of the message. The content is never copied
qd_buffer_list_t ma_to_override; // to field in outgoing message annotations.
qd_buffer_list_t ma_trace; // trace list in outgoing message annotations
qd_buffer_list_t ma_ingress; // ingress field in outgoing message annotations
int ma_phase; // phase for the override address
bool strip_annotations_in;
bool send_complete; // Has the message been completely received and completely sent?
bool tag_sent; // Tags are sent
bool is_fanout; // If msg is an outgoing fanout
} qd_message_pvt_t;
ALLOC_DECLARE(qd_message_t);
ALLOC_DECLARE(qd_message_content_t);
#define MSG_CONTENT(m) (((qd_message_pvt_t*) m)->content)
/** Initialize logging */
void qd_message_initialize();
#define QDR_N_PRIORITIES 10
#define QDR_MAX_PRIORITY (QDR_N_PRIORITIES - 1)
#define QDR_DEFAULT_PRIORITY 4
///@}
#endif
|
apache-2.0
|
benjchristensen/RxJava
|
src/test/java/io/reactivex/internal/util/ExceptionHelperTest.java
|
1513
|
/**
* Copyright 2016 Netflix, 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 io.reactivex.internal.util;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.*;
import org.junit.Test;
import io.reactivex.TestHelper;
import io.reactivex.exceptions.TestException;
import io.reactivex.schedulers.Schedulers;
public class ExceptionHelperTest {
@Test
public void utilityClass() {
TestHelper.checkUtilityClass(ExceptionHelper.class);
}
@Test
public void addRace() {
for (int i = 0; i < 500; i++) {
final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
final TestException ex = new TestException();
Runnable r = new Runnable() {
@Override
public void run() {
assertTrue(ExceptionHelper.addThrowable(error, ex));
}
};
TestHelper.race(r, r, Schedulers.single());
}
}
}
|
apache-2.0
|
fhunleth/fwup
|
scripts/ci_build.sh
|
2508
|
#!/usr/bin/env bash
#
# Build script for CircleCi
#
# Inputs:
# CIRCLE_OS_NAME - "linux" or "osx"
# MODE - "static", "dynamic", "windows", "raspberrypi", or "minimal"
#
# Static builds use scripts to download libarchive and libconfuse, so those are
# only installed on shared library builds.
#
set -e
set -v
FWUP_VERSION=$(cat VERSION)
# Create ./configure
./autogen.sh
case "${CIRCLE_OS_NAME}-${MODE}" in
*-static)
# If this is a static build, run 'build_pkg.sh'
bash -v scripts/build_pkg.sh
exit 0
;;
linux-minimal)
bash -v scripts/build_and_test_minimal.sh
exit 0
;;
linux-dynamic)
./configure --enable-gcov
;;
linux-singlethread)
# The verify-syscalls script can't follow threads, so
# single thread builds are the only way to verify that
# the issued read and write calls follow the expected
# alignment, size and order
./configure --enable-gcov --without-pthreads
;;
osx-dynamic)
PKG_CONFIG_PATH="$(brew --prefix libarchive)/lib/pkgconfig:$(brew --prefix)/lib/pkgconfig:$PKG_CONFIG_PATH" ./configure
;;
linux-windows)
CC=x86_64-w64-mingw32-gcc \
CROSS_COMPILE=x86_64-w64-mingw32 \
bash -v scripts/build_pkg.sh
exit 0
;;
linux-raspberrypi)
CC=arm-linux-gnueabihf-gcc \
CROSS_COMPILE=arm-linux-gnueabihf \
PATH=~/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin:$PATH \
QEMU_LD_PREFIX=~/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/arm-linux-gnueabihf/libc/lib/arm-linux-gnueabihf \
bash -v scripts/build_pkg.sh
exit 0
;;
*)
echo "Unexpected build option: ${CIRCLE_OS_NAME}-${MODE}"
exit 1
esac
# Normal build
make -j4
if ! make -j4 check; then
cat tests/test-suite.log
echo "git source 'make check' failed. See log above"
exit 1
fi
make dist
# Check that the distribution version works by building it again
mkdir distcheck
cd distcheck
tar xf ../fwup-$FWUP_VERSION.tar.gz
cd fwup-$FWUP_VERSION
if [ "$CIRCLE_OS_NAME" = "linux" ]; then
./configure;
else
PKG_CONFIG_PATH="$(brew --prefix libarchive)/lib/pkgconfig:$(brew --prefix)/lib/pkgconfig:$PKG_CONFIG_PATH" ./configure
fi
make -j4
if ! make -j4 check; then
cat tests/test-suite.log
echo "Distribution 'make check' failed. See log above"
exit 1
fi
cd ../..
|
apache-2.0
|
Autodesk/hig
|
packages/icon-button/src/index.test.js
|
282
|
import * as index from "./index";
describe("icon-button/index", () => {
[
{
name: "default",
value: expect.any(Function)
}
].forEach(({ name, value }) => {
it(`exports ${name}`, () => {
expect(index).toHaveProperty(name, value);
});
});
});
|
apache-2.0
|
aspleenic/mirah
|
test/mirrors/simple_mirror_loader_test.rb
|
3000
|
# Copyright (c) 2010 The Mirah project authors. All Rights Reserved.
# All contributing project authors may be found in the NOTICE file.
#
# 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.
require 'test/unit'
require 'mirah'
java_import 'org.mirah.jvm.mirrors.SimpleMirrorLoader'
java_import 'org.mirah.jvm.mirrors.BaseType'
class ParentLoader < SimpleMirrorLoader
def initialize
@callcount = 0
end
def findMirror(type)
@callcount += 1
BaseType.new(nil, type, 0, nil) if type.descriptor == "V"
end
attr_reader :callcount
end
class SimpleMirrorLoaderTest < Test::Unit::TestCase
java_import 'org.jruby.org.objectweb.asm.Type'
def setup
@parent = ParentLoader.new
@loader = SimpleMirrorLoader.new(@parent)
end
def test_no_parent
assert_nil(SimpleMirrorLoader.new.loadMirror(Type.getType("V")))
assert_nil(SimpleMirrorLoader.new.loadMirror(Type.getType("I")))
end
def test_parent
type = @loader.loadMirror(Type.getType("V"))
assert_equal("void", type.name)
assert_nil(@loader.loadMirror(Type.getType("I")))
end
def test_cache
type = @loader.loadMirror(Type.getType("V"))
assert_equal("void", type.name)
type = @loader.loadMirror(Type.getType("V"))
assert_equal("void", type.name)
assert_equal(1, @parent.callcount)
end
end
class PrimitiveLoaderTest < Test::Unit::TestCase
java_import 'org.mirah.jvm.mirrors.PrimitiveLoader'
java_import 'org.jruby.org.objectweb.asm.Type'
def test_primitives
loader = PrimitiveLoader.new(nil)
%w(V Z B S C I J F D).each do |desc|
type = Type.getType(desc)
mirror = loader.loadMirror(type)
assert_equal(type.getClassName, mirror.name)
assert_equal(desc, mirror.asm_type.descriptor)
end
end
def test_parent
parent = ParentLoader.new
loader = PrimitiveLoader.new(nil, parent)
mirror = loader.loadMirror(Type.getType("V"))
assert_equal(1, parent.callcount)
end
end
class OrErrorLoaderTest < Test::Unit::TestCase
java_import 'org.mirah.jvm.mirrors.OrErrorLoader'
java_import 'org.jruby.org.objectweb.asm.Type'
def test_loader
loader = OrErrorLoader.new(nil)
mirror = loader.loadMirror(Type.getType("J"))
assert_equal("J", mirror.asm_type.descriptor)
assert(mirror.isError)
end
def test_parent
parent = ParentLoader.new
loader = OrErrorLoader.new(parent)
mirror = loader.loadMirror(Type.getType("V"))
assert_equal(1, parent.callcount)
assert(!mirror.isError)
end
end
|
apache-2.0
|
tclavier/fleet
|
unit/file_test.go
|
5792
|
package unit
import (
"reflect"
"testing"
)
func TestDeserialize(t *testing.T) {
contents := `
This=Ignored
[Unit]
;ignore this guy
Description = Foo
[Service]
ExecStart=echo "ping";
ExecStop=echo "pong"
# ignore me, too
ExecStop=echo post
[Fleet]
X-ConditionMachineMetadata=foo=bar
X-ConditionMachineMetadata=baz=qux
`
expected := map[string]map[string][]string{
"Unit": {
"Description": {"Foo"},
},
"Service": {
"ExecStart": {`echo "ping";`},
"ExecStop": {`echo "pong"`, "echo post"},
},
"Fleet": {
"X-ConditionMachineMetadata": {"foo=bar", "baz=qux"},
},
}
unitFile, err := NewUnit(contents)
if err != nil {
t.Fatalf("Unexpected error parsing unit %q: %v", contents, err)
}
if !reflect.DeepEqual(expected, unitFile.Contents) {
t.Fatalf("Map func did not produce expected output.\nActual=%v\nExpected=%v", unitFile.Contents, expected)
}
}
func TestDeserializedUnitGarbage(t *testing.T) {
contents := `
>>>>>>>>>>>>>
[Service]
ExecStart=jim
# As long as a line has an equals sign, systemd is happy, so we should pass it through
<<<<<<<<<<<=bar
`
expected := map[string]map[string][]string{
"Service": {
"ExecStart": {"jim"},
"<<<<<<<<<<<": {"bar"},
},
}
unitFile, err := NewUnit(contents)
if err != nil {
t.Fatalf("Unexpected error parsing unit %q: %v", contents, err)
}
if !reflect.DeepEqual(expected, unitFile.Contents) {
t.Fatalf("Map func did not produce expected output.\nActual=%v\nExpected=%v", unitFile.Contents, expected)
}
}
func TestDeserializeEscapedMultilines(t *testing.T) {
contents := `
[Service]
ExecStart=echo \
"pi\
ng"
ExecStop=\
echo "po\
ng"
# comments within continuation should not be ignored
ExecStopPre=echo\
#pang
ExecStopPost=echo\
#peng\
pung
`
expected := map[string]map[string][]string{
"Service": {
"ExecStart": {`echo "pi ng"`},
"ExecStop": {`echo "po ng"`},
"ExecStopPre": {`echo #pang`},
"ExecStopPost": {`echo #peng pung`},
},
}
unitFile, err := NewUnit(contents)
if err != nil {
t.Fatalf("Unexpected error parsing unit %q: %v", contents, err)
}
if !reflect.DeepEqual(expected, unitFile.Contents) {
t.Fatalf("Map func did not produce expected output.\nActual=%v\nExpected=%v", unitFile.Contents, expected)
}
}
func TestSerializeDeserialize(t *testing.T) {
contents := `
[Unit]
Description = Foo
`
deserialized, err := NewUnit(contents)
if err != nil {
t.Fatalf("Unexpected error parsing unit %q: %v", contents, err)
}
section := deserialized.Contents["Unit"]
if val, ok := section["Description"]; !ok || val[0] != "Foo" {
t.Errorf("Failed to persist data through serialize/deserialize: %v", val)
}
serialized := deserialized.String()
deserialized, err = NewUnit(serialized)
if err != nil {
t.Fatalf("Unexpected error parsing unit %q: %v", serialized, err)
}
section = deserialized.Contents["Unit"]
if val, ok := section["Description"]; !ok || val[0] != "Foo" {
t.Errorf("Failed to persist data through serialize/deserialize: %v", val)
}
}
func TestDescription(t *testing.T) {
contents := `
[Unit]
Description = Foo
[Service]
ExecStart=echo "ping";
ExecStop=echo "pong";
`
unitFile, err := NewUnit(contents)
if err != nil {
t.Fatalf("Unexpected error parsing unit %q: %v", contents, err)
}
if unitFile.Description() != "Foo" {
t.Fatalf("Unit.Description is incorrect")
}
}
func TestDescriptionNotDefined(t *testing.T) {
contents := `
[Unit]
[Service]
ExecStart=echo "ping";
ExecStop=echo "pong";
`
unitFile, err := NewUnit(contents)
if err != nil {
t.Fatalf("Unexpected error parsing unit %q: %v", contents, err)
}
if unitFile.Description() != "" {
t.Fatalf("Unit.Description is incorrect")
}
}
func TestNewSystemdUnitFileFromLegacyContents(t *testing.T) {
legacy := map[string]map[string]string{
"Unit": {
"Description": "foobar",
},
"Service": {
"Type": "oneshot",
"ExecStart": "/usr/bin/echo bar",
},
}
expected := map[string]map[string][]string{
"Unit": {
"Description": {"foobar"},
},
"Service": {
"Type": {"oneshot"},
"ExecStart": {"/usr/bin/echo bar"},
},
}
u, err := NewUnitFromLegacyContents(legacy)
if err != nil {
t.Fatalf("Unexpected error parsing unit %q: %v", legacy, err)
}
actual := u.Contents
if !reflect.DeepEqual(actual, expected) {
t.Fatalf("Map func did not produce expected output.\nActual=%v\nExpected=%v", actual, expected)
}
}
func TestDeserializeLine(t *testing.T) {
deserializeLineExamples := map[string][]string{
`key=foo=bar`: {`foo=bar`},
`key="foo=bar"`: {`foo=bar`},
`key="foo=bar" "baz=qux"`: {`foo=bar`, `baz=qux`},
`key="foo=bar baz"`: {`foo=bar baz`},
`key="foo=bar" baz`: {`"foo=bar" baz`},
`key=baz "foo=bar"`: {`baz "foo=bar"`},
`key="foo=bar baz=qux"`: {`foo=bar baz=qux`},
}
for q, w := range deserializeLineExamples {
k, g, err := deserializeUnitLine(q)
if err != nil {
t.Fatalf("Unexpected error testing %q: %v", q, err)
}
if k != "key" {
t.Fatalf("Unexpected key, got %q, want %q", k, "key")
}
if !reflect.DeepEqual(g, w) {
t.Errorf("Unexpected line parse for %q:\ngot %q\nwant %q", q, g, w)
}
}
// Any non-empty line without an '=' is bad
badLines := []string{
`<<<<<<<<<<<<<<<<<<<<<<<<`,
`asdjfkl;`,
`>>>>>>>>>>>>>>>>>>>>>>>>`,
`!@#$%^&&*`,
}
for _, l := range badLines {
_, _, err := deserializeUnitLine(l)
if err == nil {
t.Fatalf("Did not get expected error deserializing %q", l)
}
}
}
func TestBadUnitsFail(t *testing.T) {
bad := []string{
`
[Unit]
[Service]
<<<<<<<<<<<<<<<<
`,
`
[Unit]
nonsense upon stilts
`,
}
for _, tt := range bad {
if _, err := NewUnit(tt); err == nil {
t.Fatalf("Did not get expected error creating Unit from %q", tt)
}
}
}
|
apache-2.0
|
nitro-devs/nitro-game-engine
|
docs/ncollide_procedural/utils/index.html
|
10237
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `utils` mod in crate `ncollide_procedural`.">
<meta name="keywords" content="rust, rustlang, rust-lang, utils">
<title>ncollide_procedural::utils - Rust</title>
<link rel="stylesheet" type="text/css" href="../../normalize.css">
<link rel="stylesheet" type="text/css" href="../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc mod">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='../index.html'>ncollide_procedural</a></p><script>window.sidebarCurrent = {name: 'utils', ty: 'mod', relpath: '../'};</script><script defer src="../sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content">
<h1 class='fqn'><span class='in-band'>Module <a href='../index.html'>ncollide_procedural</a>::<wbr><a class="mod" href=''>utils</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a class='srclink' href='../../src/ncollide_procedural/utils.rs.html#1-243' title='goto source code'>[src]</a></span></h1>
<div class='docblock'><p>Utilities useful for various generations tasks.</p>
</div><h2 id='functions' class='section-header'><a href="#functions">Functions</a></h2>
<table>
<tr class=' module-item'>
<td><a class="fn" href="fn.compute_normals.html"
title='fn ncollide_procedural::utils::compute_normals'>compute_normals</a></td>
<td class='docblock-short'>
<p>Computes the normals of a set of vertices.</p>
</td>
</tr>
<tr class=' module-item'>
<td><a class="fn" href="fn.push_circle.html"
title='fn ncollide_procedural::utils::push_circle'>push_circle</a></td>
<td class='docblock-short'>
<p>Pushes a discretized counterclockwise circle to a buffer.</p>
</td>
</tr>
<tr class=' module-item'>
<td><a class="fn" href="fn.push_degenerate_open_top_ring_indices.html"
title='fn ncollide_procedural::utils::push_degenerate_open_top_ring_indices'>push_degenerate_open_top_ring_indices</a></td>
<td class='docblock-short'>
<p>Creates the faces from a circle and a point that is shared by all triangle.</p>
</td>
</tr>
<tr class=' module-item'>
<td><a class="fn" href="fn.push_degenerate_top_ring_indices.html"
title='fn ncollide_procedural::utils::push_degenerate_top_ring_indices'>push_degenerate_top_ring_indices</a></td>
<td class='docblock-short'>
<p>Creates the faces from a circle and a point that is shared by all triangle.</p>
</td>
</tr>
<tr class=' module-item'>
<td><a class="fn" href="fn.push_filled_circle_indices.html"
title='fn ncollide_procedural::utils::push_filled_circle_indices'>push_filled_circle_indices</a></td>
<td class='docblock-short'>
<p>Pushes indices so that a circle is filled with triangles. Each triangle will have the
<code>base_circle</code> point in common.
Pushes <code>nsubdiv - 2</code> elements to <code>out</code>.</p>
</td>
</tr>
<tr class=' module-item'>
<td><a class="fn" href="fn.push_open_ring_indices.html"
title='fn ncollide_procedural::utils::push_open_ring_indices'>push_open_ring_indices</a></td>
<td class='docblock-short'>
<p>Creates the faces from two circles with the same discretization.</p>
</td>
</tr>
<tr class=' module-item'>
<td><a class="fn" href="fn.push_rectangle_indices.html"
title='fn ncollide_procedural::utils::push_rectangle_indices'>push_rectangle_indices</a></td>
<td class='docblock-short'>
<p>Given four corner points, pushes to two counterclockwise triangles to <code>out</code>.</p>
</td>
</tr>
<tr class=' module-item'>
<td><a class="fn" href="fn.push_ring_indices.html"
title='fn ncollide_procedural::utils::push_ring_indices'>push_ring_indices</a></td>
<td class='docblock-short'>
<p>Creates the faces from two circles with the same discretization.</p>
</td>
</tr>
<tr class=' module-item'>
<td><a class="fn" href="fn.push_xy_arc.html"
title='fn ncollide_procedural::utils::push_xy_arc'>push_xy_arc</a></td>
<td class='docblock-short'>
<p>Pushes a discretized counterclockwise circle to a buffer.
The circle is contained on the plane spanned by the <code>x</code> and <code>y</code> axis.</p>
</td>
</tr>
<tr class=' module-item'>
<td><a class="fn" href="fn.reverse_clockwising.html"
title='fn ncollide_procedural::utils::reverse_clockwising'>reverse_clockwising</a></td>
<td class='docblock-short'>
<p>Reverses the clockwising of a set of faces.</p>
</td>
</tr>
<tr class=' module-item'>
<td><a class="fn" href="fn.split_index_buffer.html"
title='fn ncollide_procedural::utils::split_index_buffer'>split_index_buffer</a></td>
<td class='docblock-short'>
<p>Duplicates the indices of each triangle on the given index buffer.</p>
</td>
</tr>
<tr class=' module-item'>
<td><a class="fn" href="fn.split_index_buffer_and_recover_topology.html"
title='fn ncollide_procedural::utils::split_index_buffer_and_recover_topology'>split_index_buffer_and_recover_topology</a></td>
<td class='docblock-short'>
<p>Duplicates the indices of each triangle on the given index buffer, giving the same id to each
identical vertex.</p>
</td>
</tr></table></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../";
window.currentCrate = "ncollide_procedural";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script defer src="../../search-index.js"></script>
</body>
</html>
|
apache-2.0
|
sugerPocket/sp-blog
|
server/middlewares/index.js
|
214
|
const loginJudger = require('./loginJudger');
const registerJudger = require('./registerJudger');
const adminJudger = require('./adminJudger');
module.exports = {
loginJudger,
registerJudger,
adminJudger,
};
|
apache-2.0
|
kkohs/SkinnyElephant-EntityFramework
|
src/main/java/org/skinnyelephant/framework/core/PoolManager.java
|
5388
|
/*
* Copyright 2012 Kristaps Kohs<kristaps.kohs@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.skinnyelephant.framework.core;
import org.skinnyelephant.framework.util.EntityPool;
import java.util.HashMap;
import java.util.Map;
/**
* Manager for pooling entities to be reused later to avoid allocating new memory for creating new entities that are used often..
* Date: 13.1.2
* Time: 12:37
*
* @author Kristaps Kohs
*/
public class PoolManager implements Manager {
/**
* Core class.
*/
private Core frameWorkCore;
/**
* Map containing Entity pool with specific id.
*/
private Map<Long, EntityPool> pooledEntities;
/**
* Flag indicating if manager has been initialized.
*/
private boolean initialized;
/**
* Period in which pool should be cleaned.
*/
private float removalPeriod;
/**
* Current time.
*/
private float accumulatedDelta;
/**
* Created new Entity Pool manager.
*
* @param frameWorkCore frameworks core.
*/
public PoolManager(Core frameWorkCore) {
this.frameWorkCore = frameWorkCore;
}
private int singleMaxPoolSize = 512;
@Override
public void initialize() {
if (initialized) {
throw new IllegalStateException("Manager already initialized!");
}
pooledEntities = new HashMap<Long, EntityPool>();
initialized = true;
}
/**
* Creates or retrieves entity with given array of components from pool.
*
* @param components array of components
* @return Entity from pool.
*/
protected Entity createPooledEntity(Class<?>... components) {
if (!initialized) {
throw new IllegalStateException("Manager not initialized");
}
long componentIds = 0;
for (Class<?> component : components) {
componentIds |= frameWorkCore.getComponentId(component);
}
if (pooledEntities.containsKey(componentIds)) {
Entity e = pooledEntities.get(componentIds).get();
if (e == null) {
return createEntityWithComponents(components);
} else {
return e;
}
} else {
pooledEntities.put(componentIds, new EntityPool(singleMaxPoolSize));
return createEntityWithComponents(components);
}
}
/**
* Destroys entity and returns it back to pool for later use.
*
* @param entity to be destroyed.
*/
public void destroyPooledEntity(Entity entity) {
if (!initialized) {
throw new IllegalStateException("Manager not initialized");
}
final long componentIds = entity.getComponentsIds();
if (pooledEntities.containsKey(componentIds)) {
pooledEntities.get(componentIds).put(entity);
} else {
pooledEntities.put(componentIds, new EntityPool(singleMaxPoolSize));
pooledEntities.get(componentIds).put(entity);
}
}
private Entity createEntityWithComponents(Class<?>... components) {
if (!initialized) {
throw new IllegalStateException("Manager not initialized");
}
Entity e = frameWorkCore.createEntity();
e.setPooled(true);
for (Class<?> component : components) {
try {
e.addComponent(component.newInstance());
} catch (Exception e1) {
throw new IllegalStateException("Failed to create pooled component", e1);
}
}
return e;
}
/**
* Cleans up entity pool if period delta > {@link PoolManager#removalPeriod}.
*
* @param delta time passed in milliseconds.
*/
public void cleanUpPool(final float delta) {
if (!initialized) {
throw new IllegalStateException("Manager not initialized");
}
if (removalPeriod <= 0) {
return;
}
if ((accumulatedDelta += (delta * .001f)) >= removalPeriod) {
for (EntityPool entityPool : pooledEntities.values()) {
entityPool.releaseFromPool();
}
accumulatedDelta = 0;
}
}
/**
* Sets removal period in seconds.
*
* @param removalPeriod period in seconds
*/
public void setRemovalPeriod(float removalPeriod) {
this.removalPeriod = removalPeriod;
}
@Override
public void dispose() {
if (!initialized) {
throw new IllegalStateException("Manager not initialized");
}
pooledEntities.clear();
}
public int getSingleMaxPoolSize() {
return singleMaxPoolSize;
}
public void setSingleMaxPoolSize(int singleMaxPoolSize) {
this.singleMaxPoolSize = singleMaxPoolSize;
}
}
|
apache-2.0
|
gbif/geocode
|
database/coordinatecleaner_centroids.sql
|
34460
|
/*
Coordinates extracted from CentroidCleaner R package using:
library(CoordinateCleaner)
library(dplyr)
points_df = CoordinateCleaner::countryref %>%
filter(type == "country") %>%
filter(area_sqkm >= 10e3) %>%
select(iso2,long=centroid.lon,lat=centroid.lat) %>%
glimpse()
write.csv(points_df, "cc.csv", row.names=TRUE)
*/
DROP TABLE IF EXISTS public.coordinatecleaner_centroids CASCADE;
DROP SEQUENCE IF EXISTS public.coordinatecleaner_centroids_gid_seq CASCADE;
CREATE SEQUENCE public.coordinatecleaner_centroids_gid_seq
AS integer
START WITH 1;
CREATE TABLE public.coordinatecleaner_centroids (
gid integer NOT NULL PRIMARY KEY DEFAULT nextval('public.coordinatecleaner_centroids_gid_seq'::regclass),
iso_a2 character(2) NOT NULL,
geom public.geometry(Point,4326)
);
CREATE INDEX coordinatecleaner_centroids_geom_idx ON public.coordinatecleaner_centroids USING gist (geom);
GRANT SELECT ON TABLE public.coordinatecleaner_centroids TO PUBLIC;
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AF', 'SRID=4326;POINT (64.884165 31.947268)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AF', 'SRID=4326;POINT (65.216 33.677)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AF', 'SRID=4326;POINT (65 33)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AO', 'SRID=4326;POINT (18.5 -12.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AO', 'SRID=4326;POINT (17.544 -12.296)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AL', 'SRID=4326;POINT (20 41)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AL', 'SRID=4326;POINT (20.068 41.143)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AE', 'SRID=4326;POINT (54 24)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AE', 'SRID=4326;POINT (54.163 23.549)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AR', 'SRID=4326;POINT (-65.167 -35.377)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AR', 'SRID=4326;POINT (-64 -34)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AM', 'SRID=4326;POINT (45 40)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AM', 'SRID=4326;POINT (44.563 40.534)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AQ', 'SRID=4326;POINT (0 -90)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AQ', 'SRID=4326;POINT (21.304 -80.446)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AU', 'SRID=4326;POINT (133 -27)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AU', 'SRID=4326;POINT (136.189 -24.973)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AT', 'SRID=4326;POINT (13.3333333333 47.3333333333)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AT', 'SRID=4326;POINT (14.912 47.683)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AZ', 'SRID=4326;POINT (47.395 40.43)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('AZ', 'SRID=4326;POINT (47.5 40.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BI', 'SRID=4326;POINT (30 -3.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BI', 'SRID=4326;POINT (29.887 -3.356)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BE', 'SRID=4326;POINT (4.664 50.643)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BE', 'SRID=4326;POINT (4 50.8333333333)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BJ', 'SRID=4326;POINT (2.25 9.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BJ', 'SRID=4326;POINT (2.469 10.541)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BF', 'SRID=4326;POINT (-1.74 12.278)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BF', 'SRID=4326;POINT (-2 13)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BD', 'SRID=4326;POINT (90 24)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BD', 'SRID=4326;POINT (89.941 24.218)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BG', 'SRID=4326;POINT (25 43)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BG', 'SRID=4326;POINT (25.231 42.761)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BS', 'SRID=4326;POINT (-76 24.25)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BS', 'SRID=4326;POINT (-78.014 24.628)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BA', 'SRID=4326;POINT (17.786 44.169)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BA', 'SRID=4326;POINT (18 44)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BY', 'SRID=4326;POINT (28.047 53.54)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BY', 'SRID=4326;POINT (28 53)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BZ', 'SRID=4326;POINT (-88.602 17.219)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BZ', 'SRID=4326;POINT (-88.75 17.25)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BO', 'SRID=4326;POINT (-64.671 -16.715)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BO', 'SRID=4326;POINT (-65 -17)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BR', 'SRID=4326;POINT (-53.089 -10.772)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BR', 'SRID=4326;POINT (-55 -10)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BT', 'SRID=4326;POINT (90.429 27.415)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BT', 'SRID=4326;POINT (90.5 27.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BW', 'SRID=4326;POINT (23.815 -22.182)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('BW', 'SRID=4326;POINT (24 -22)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CF', 'SRID=4326;POINT (21 7)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CF', 'SRID=4326;POINT (20.483 6.571)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CA', 'SRID=4326;POINT (-95 60)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CA', 'SRID=4326;POINT (-109.433 59.081)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CH', 'SRID=4326;POINT (7.908 46.861)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CH', 'SRID=4326;POINT (8 47)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CL', 'SRID=4326;POINT (-71 -30)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CL', 'SRID=4326;POINT (-69.433 -23.389)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CN', 'SRID=4326;POINT (105 35)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CN', 'SRID=4326;POINT (106.514 33.42)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CI', 'SRID=4326;POINT (-5.556 7.632)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CI', 'SRID=4326;POINT (-5 8)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CM', 'SRID=4326;POINT (12 6)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CM', 'SRID=4326;POINT (12.277 5.133)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CD', 'SRID=4326;POINT (25 0.0166666666667)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CD', 'SRID=4326;POINT (23.654 -2.876)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CG', 'SRID=4326;POINT (15 -1)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CG', 'SRID=4326;POINT (15.986 -0.055)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CO', 'SRID=4326;POINT (-73.076 3.9)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CO', 'SRID=4326;POINT (-72 4)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CR', 'SRID=4326;POINT (-83.946 9.971)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CR', 'SRID=4326;POINT (-84 10)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CU', 'SRID=4326;POINT (-80 21.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CU', 'SRID=4326;POINT (-77.781 21.297)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CZ', 'SRID=4326;POINT (15.338 49.743)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('CZ', 'SRID=4326;POINT (15.5 49.75)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('DE', 'SRID=4326;POINT (9 51)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('DE', 'SRID=4326;POINT (9.851 51.11)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('DJ', 'SRID=4326;POINT (42.516 11.9)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('DJ', 'SRID=4326;POINT (43 11.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('DK', 'SRID=4326;POINT (10 56)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('DK', 'SRID=4326;POINT (9.264 56.058)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('DO', 'SRID=4326;POINT (-70.6666666667 19)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('DO', 'SRID=4326;POINT (-70.729 19.015)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('DZ', 'SRID=4326;POINT (2.632 28.163)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('DZ', 'SRID=4326;POINT (3 28)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('EC', 'SRID=4326;POINT (-78.497 -1.385)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('EC', 'SRID=4326;POINT (-77.5 -2)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('EG', 'SRID=4326;POINT (30 27)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('EG', 'SRID=4326;POINT (29.872 26.494)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ER', 'SRID=4326;POINT (39 15)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ER', 'SRID=4326;POINT (38.219 16.045)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ES', 'SRID=4326;POINT (-3.649 40.227)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ES', 'SRID=4326;POINT (-4 40)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('EE', 'SRID=4326;POINT (25.793 58.674)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('EE', 'SRID=4326;POINT (26 59)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ET', 'SRID=4326;POINT (39.616 8.626)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ET', 'SRID=4326;POINT (38 8)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('FI', 'SRID=4326;POINT (26.272 64.504)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('FI', 'SRID=4326;POINT (26 64)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('FJ', 'SRID=4326;POINT (177.974 -17.819)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('FJ', 'SRID=4326;POINT (175 -18)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('FK', 'SRID=4326;POINT (-58.694 -51.665)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('FK', 'SRID=4326;POINT (-59 -51.75)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('FR', 'SRID=4326;POINT (2 46)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('FR', 'SRID=4326;POINT (2.55 46.565)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GA', 'SRID=4326;POINT (11.797 -0.591)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GA', 'SRID=4326;POINT (11.75 -1)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GB', 'SRID=4326;POINT (-2 54)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GB', 'SRID=4326;POINT (-2.9 54.16)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GE', 'SRID=4326;POINT (43.518 42.176)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GE', 'SRID=4326;POINT (43.5 42)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GH', 'SRID=4326;POINT (-1.207 7.96)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GH', 'SRID=4326;POINT (-2 8)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GN', 'SRID=4326;POINT (-10 11)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GN', 'SRID=4326;POINT (-10.942 10.439)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GM', 'SRID=4326;POINT (-15.386 13.453)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GM', 'SRID=4326;POINT (-16.5666666667 13.4666666667)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GW', 'SRID=4326;POINT (-15 12)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GW', 'SRID=4326;POINT (-14.651 12.125)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GQ', 'SRID=4326;POINT (10 2)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GQ', 'SRID=4326;POINT (10.488 1.607)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GR', 'SRID=4326;POINT (22 39)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GR', 'SRID=4326;POINT (21.766 39.666)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GL', 'SRID=4326;POINT (-40 72)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GL', 'SRID=4326;POINT (-41.391 74.719)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GT', 'SRID=4326;POINT (-90.25 15.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GT', 'SRID=4326;POINT (-90.398 15.256)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GY', 'SRID=4326;POINT (-59 5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('GY', 'SRID=4326;POINT (-58.974 4.792)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('HN', 'SRID=4326;POINT (-86.5 15)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('HN', 'SRID=4326;POINT (-86.863 14.819)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('HR', 'SRID=4326;POINT (15.5 45.1666666667)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('HR', 'SRID=4326;POINT (16.693 45.723)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('HT', 'SRID=4326;POINT (-72.4166666667 19)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('HT', 'SRID=4326;POINT (-72.278 19.142)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('HU', 'SRID=4326;POINT (20 47)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('HU', 'SRID=4326;POINT (19.134 47.07)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ID', 'SRID=4326;POINT (114.252 -0.976)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ID', 'SRID=4326;POINT (120 -5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('IN', 'SRID=4326;POINT (79.619 22.881)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('IN', 'SRID=4326;POINT (77 20)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('IE', 'SRID=4326;POINT (-8 53)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('IE', 'SRID=4326;POINT (-8.152 53.177)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('IR', 'SRID=4326;POINT (53 32)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('IR', 'SRID=4326;POINT (54.301 32.565)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('IQ', 'SRID=4326;POINT (44 33)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('IQ', 'SRID=4326;POINT (43.772 33.048)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('IS', 'SRID=4326;POINT (-18 65)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('IS', 'SRID=4326;POINT (-18.48 64.764)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('IL', 'SRID=4326;POINT (34.75 31.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('IL', 'SRID=4326;POINT (34.851 31.026)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('IT', 'SRID=4326;POINT (10.44 44.931)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('IT', 'SRID=4326;POINT (12.8333333333 42.8333333333)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('JM', 'SRID=4326;POINT (-77.5 18.25)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('JM', 'SRID=4326;POINT (-77.32 18.151)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('JO', 'SRID=4326;POINT (36 31)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('JO', 'SRID=4326;POINT (36.319 30.703)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('JP', 'SRID=4326;POINT (138 36)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('JP', 'SRID=4326;POINT (139.068 36.491)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('KZ', 'SRID=4326;POINT (67.301 48.16)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('KZ', 'SRID=4326;POINT (68 48)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('KE', 'SRID=4326;POINT (37.858 0.53)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('KE', 'SRID=4326;POINT (38 1)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('KG', 'SRID=4326;POINT (74.555 41.465)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('KG', 'SRID=4326;POINT (75 41)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('KH', 'SRID=4326;POINT (105 13)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('KH', 'SRID=4326;POINT (104.564 12.714)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('KR', 'SRID=4326;POINT (128.103 36.504)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('KR', 'SRID=4326;POINT (127.5 37)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('KW', 'SRID=4326;POINT (47.376 29.476)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('KW', 'SRID=4326;POINT (47.966667 29.366667)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('LA', 'SRID=4326;POINT (102.471 19.905)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('LA', 'SRID=4326;POINT (105 18)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('LB', 'SRID=4326;POINT (35.8333333333 33.8333333333)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('LB', 'SRID=4326;POINT (35.888 33.92)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('LR', 'SRID=4326;POINT (-9.5 6.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('LR', 'SRID=4326;POINT (-9.657 6.682)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('LY', 'SRID=4326;POINT (18.023 27.044)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('LY', 'SRID=4326;POINT (17 25)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('LK', 'SRID=4326;POINT (81 7)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('LK', 'SRID=4326;POINT (80.704 7.612)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('LS', 'SRID=4326;POINT (28.243 -29.581)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('LS', 'SRID=4326;POINT (28.5 -29.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('LT', 'SRID=4326;POINT (24 56)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('LT', 'SRID=4326;POINT (23.897 55.336)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('LV', 'SRID=4326;POINT (25 57)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('LV', 'SRID=4326;POINT (25.641 56.858)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MA', 'SRID=4326;POINT (-5 32)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MA', 'SRID=4326;POINT (-5.758 32.706)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MD', 'SRID=4326;POINT (29 47)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MD', 'SRID=4326;POINT (28.599 47.193)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MG', 'SRID=4326;POINT (47 -20)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MG', 'SRID=4326;POINT (46.706 -19.374)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MX', 'SRID=4326;POINT (-102 23)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MX', 'SRID=4326;POINT (-102.535 23.951)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MK', 'SRID=4326;POINT (21.698 41.6)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MK', 'SRID=4326;POINT (22 41.8333333333)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ML', 'SRID=4326;POINT (-4 17)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ML', 'SRID=4326;POINT (-3.524 17.35)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MM', 'SRID=4326;POINT (98 22)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MM', 'SRID=4326;POINT (96.041 21.718)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ME', 'SRID=4326;POINT (19.254 42.792)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ME', 'SRID=4326;POINT (19.3 42.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MN', 'SRID=4326;POINT (105 46)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MN', 'SRID=4326;POINT (102.876 46.056)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MZ', 'SRID=4326;POINT (37.923 -14.422)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MZ', 'SRID=4326;POINT (35 -18.25)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MR', 'SRID=4326;POINT (-12 20)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MR', 'SRID=4326;POINT (-10.332 20.26)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MW', 'SRID=4326;POINT (34 -13.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MW', 'SRID=4326;POINT (33.808 -13.4)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MY', 'SRID=4326;POINT (112.5 2.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('MY', 'SRID=4326;POINT (102.195 4.201)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NA', 'SRID=4326;POINT (17 -22)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NA', 'SRID=4326;POINT (17.218 -22.133)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NC', 'SRID=4326;POINT (165.5 -21.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NC', 'SRID=4326;POINT (165.447 -21.359)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NE', 'SRID=4326;POINT (9.398 17.426)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NE', 'SRID=4326;POINT (8 16)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NG', 'SRID=4326;POINT (8 10)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NG', 'SRID=4326;POINT (8.105 9.594)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NI', 'SRID=4326;POINT (-85 13)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NI', 'SRID=4326;POINT (-85.034 12.84)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NL', 'SRID=4326;POINT (5.389 52.077)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NL', 'SRID=4326;POINT (5.75 52.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NO', 'SRID=4326;POINT (8.74 61.152)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NO', 'SRID=4326;POINT (10 62)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NP', 'SRID=4326;POINT (83.939 28.253)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NP', 'SRID=4326;POINT (84 28)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NZ', 'SRID=4326;POINT (174 -41)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('NZ', 'SRID=4326;POINT (172.235 -42.634)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('OM', 'SRID=4326;POINT (57 21)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('OM', 'SRID=4326;POINT (57.407 21.656)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('PK', 'SRID=4326;POINT (70 30)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('PK', 'SRID=4326;POINT (69.386 29.967)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('PA', 'SRID=4326;POINT (-80.92 8.384)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('PA', 'SRID=4326;POINT (-80 9)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('PE', 'SRID=4326;POINT (-75.552 -9.326)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('PE', 'SRID=4326;POINT (-76 -10)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('PH', 'SRID=4326;POINT (122 13)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('PH', 'SRID=4326;POINT (122.466 11.118)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('PL', 'SRID=4326;POINT (20 52)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('PL', 'SRID=4326;POINT (19.401 52.125)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('KP', 'SRID=4326;POINT (126.451 39.778)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('KP', 'SRID=4326;POINT (127 40)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('PY', 'SRID=4326;POINT (-58 -23)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('PY', 'SRID=4326;POINT (-58.391 -23.236)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('QA', 'SRID=4326;POINT (51.191 25.316)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('QA', 'SRID=4326;POINT (51.25 25.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('RO', 'SRID=4326;POINT (25 46)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('RO', 'SRID=4326;POINT (24.969 45.844)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('RU', 'SRID=4326;POINT (100 60)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('RU', 'SRID=4326;POINT (96.689 61.988)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('RW', 'SRID=4326;POINT (30 -2)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('RW', 'SRID=4326;POINT (29.917 -1.998)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SA', 'SRID=4326;POINT (44.585 24.023)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SA', 'SRID=4326;POINT (45 25)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SD', 'SRID=4326;POINT (30 15)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SD', 'SRID=4326;POINT (30.05 13.832)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SN', 'SRID=4326;POINT (-14.881 15.013)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SN', 'SRID=4326;POINT (-14 14)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SB', 'SRID=4326;POINT (159 -8)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SB', 'SRID=4326;POINT (160.109 -9.611)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SL', 'SRID=4326;POINT (-11.5 8.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SL', 'SRID=4326;POINT (-11.792 8.56)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SV', 'SRID=4326;POINT (-88.866 13.736)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SV', 'SRID=4326;POINT (-88.9166666667 13.8333333333)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SO', 'SRID=4326;POINT (49 10)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SO', 'SRID=4326;POINT (48.316 9.774)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('RS', 'SRID=4326;POINT (20.806 44.032)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('RS', 'SRID=4326;POINT (21 44)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SR', 'SRID=4326;POINT (-55.912 4.127)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SR', 'SRID=4326;POINT (-56 4)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SK', 'SRID=4326;POINT (19.5 48.6666666667)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SK', 'SRID=4326;POINT (19.491 48.707)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SI', 'SRID=4326;POINT (14.8166666667 46.1166666667)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SI', 'SRID=4326;POINT (14.827 46.124)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SE', 'SRID=4326;POINT (15 62)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SE', 'SRID=4326;POINT (15.27 62.011)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SZ', 'SRID=4326;POINT (31.5 -26.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SZ', 'SRID=4326;POINT (31.497 -26.562)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SY', 'SRID=4326;POINT (38 35)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('SY', 'SRID=4326;POINT (38.506 35.013)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TD', 'SRID=4326;POINT (19 15)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TD', 'SRID=4326;POINT (18.665 15.361)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TG', 'SRID=4326;POINT (1.081 8.799)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TG', 'SRID=4326;POINT (1.16666666667 8)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TH', 'SRID=4326;POINT (100.844 15.7)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TH', 'SRID=4326;POINT (100 15)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TJ', 'SRID=4326;POINT (69.42 38.665)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TJ', 'SRID=4326;POINT (71 39)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TM', 'SRID=4326;POINT (59.384 39.122)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TM', 'SRID=4326;POINT (60 40)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TL', 'SRID=4326;POINT (125.916666667 -8.83333333333)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TL', 'SRID=4326;POINT (125.878 -8.822)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TN', 'SRID=4326;POINT (9 34)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TN', 'SRID=4326;POINT (9.596 35.383)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TR', 'SRID=4326;POINT (35.179 39.061)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TR', 'SRID=4326;POINT (35 39)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TW', 'SRID=4326;POINT (120.946 23.754)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TW', 'SRID=4326;POINT (121 23.5)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TZ', 'SRID=4326;POINT (35 -6)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('TZ', 'SRID=4326;POINT (34.823 -6.27)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('UG', 'SRID=4326;POINT (32 1)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('UG', 'SRID=4326;POINT (32.386 1.28)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('UA', 'SRID=4326;POINT (32 49)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('UA', 'SRID=4326;POINT (31.388 49.016)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('UY', 'SRID=4326;POINT (-56.012 -32.8)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('UY', 'SRID=4326;POINT (-56 -33)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('US', 'SRID=4326;POINT (-97 38)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('US', 'SRID=4326;POINT (-98.606 39.622)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('UZ', 'SRID=4326;POINT (63.17 41.75)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('UZ', 'SRID=4326;POINT (64 41)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('VE', 'SRID=4326;POINT (-66.166 7.125)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('VE', 'SRID=4326;POINT (-66 8)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('VN', 'SRID=4326;POINT (105.314 21.491)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('VN', 'SRID=4326;POINT (107.833333333 16.1666666667)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('VU', 'SRID=4326;POINT (167 -16)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('VU', 'SRID=4326;POINT (166.899 -15.376)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('YE', 'SRID=4326;POINT (48 15)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('YE', 'SRID=4326;POINT (48.355 15.807)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ZA', 'SRID=4326;POINT (23.121 -30.558)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ZA', 'SRID=4326;POINT (24 -29)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ZM', 'SRID=4326;POINT (30 -15)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ZM', 'SRID=4326;POINT (26.32 -14.614)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ZW', 'SRID=4326;POINT (29.872 -19)');
INSERT INTO coordinatecleaner_centroids (iso_a2, geom) VALUES ('ZW', 'SRID=4326;POINT (30 -20)');
|
apache-2.0
|
timofeevda/seismic-beachballs-demo
|
app/src/components/spinner/spinner.component.ts
|
1091
|
import {Component, EventEmitter, Input, Output} from '@angular/core'
@Component({
template: require('./spinner.component.html'),
selector: 'spinner'
})
export class SpinnerComponent {
@Input() value: number
@Output() valueChange: EventEmitter<number>
@Input() step: number = 1
timeout: number
constructor() {
this.valueChange = new EventEmitter<any>()
}
onChange(value: number) {
this.value = value
this.valueChange.emit(this.value)
}
startSpinUp() {
this.timeout = window.setTimeout(() => {
this.stepUp()
this.startSpinUp()
}, 100);
}
stopSpin() {
clearTimeout(this.timeout)
}
startSpinDown() {
this.timeout = window.setTimeout(() => {
this.stepDown()
this.startSpinDown()
}, 100);
}
stepUp() {
this.stepValue(this.step)
}
stepDown() {
this.stepValue(-this.step)
}
stepValue(step: number) {
this.value += step
this.valueChange.emit(this.value)
}
}
|
apache-2.0
|
Ccook/Stonewall
|
src/test/java/edu/american/student/stonewall/display/css/property/ResizePropertyTest.java
|
434
|
package edu.american.student.stonewall.display.css.property;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import edu.american.student.stonewall.display.css.util.ResizeType;
public class ResizePropertyTest
{
@Test
public void test()
{
ResizeProperty prop = new ResizeProperty(ResizeType.HORIZONTAL);
String expected = "resize:horizontal;";
assertTrue(prop.makeProperties().contains(expected));
}
}
|
apache-2.0
|
yodathedark/moltis-tickets
|
tickets/views/location/index.php
|
764
|
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('app', 'Locations');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="location-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Create Location'), ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'name',
'address:ntext',
'postcode',
'country',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
|
apache-2.0
|