code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
package corehttp
// TODO: move to IPNS
const WebUIPath = "/ipfs/QmXc9raDM1M5G5fpBnVyQ71vR4gbnskwnB9iMEzBuLgvoZ"
// this is a list of all past webUI paths.
var WebUIPaths = []string{
WebUIPath,
"/ipfs/QmenEBWcAk3tN94fSKpKFtUMwty1qNwSYw3DMDFV6cPBXA",
"/ipfs/QmUnXcWZC5Ve21gUseouJsH5mLAyz5JPp8aHsg8qVUUK8e",
"/ipfs/QmSDgpiHco5yXdyVTfhKxr3aiJ82ynz8V14QcGKicM3rVh",
"/ipfs/QmRuvWJz1Fc8B9cTsAYANHTXqGmKR9DVfY5nvMD1uA2WQ8",
"/ipfs/QmQLXHs7K98JNQdWrBB2cQLJahPhmupbDjRuH1b9ibmwVa",
"/ipfs/QmXX7YRpU7nNBKfw75VG7Y1c3GwpSAGHRev67XVPgZFv9R",
"/ipfs/QmXdu7HWdV6CUaUabd9q2ZeA4iHZLVyDRj3Gi4dsJsWjbr",
"/ipfs/QmaaqrHyAQm7gALkRW8DcfGX3u8q9rWKnxEMmf7m9z515w",
"/ipfs/QmSHDxWsMPuJQKWmVA1rB5a3NX2Eme5fPqNb63qwaqiqSp",
"/ipfs/QmctngrQAt9fjpQUZr7Bx3BsXUcif52eZGTizWhvcShsjz",
"/ipfs/QmS2HL9v5YeKgQkkWMvs1EMnFtUowTEdFfSSeMT4pos1e6",
"/ipfs/QmR9MzChjp1MdFWik7NjEjqKQMzVmBkdK3dz14A6B5Cupm",
"/ipfs/QmRyWyKWmphamkMRnJVjUTzSFSAAZowYP4rnbgnfMXC9Mr",
"/ipfs/QmU3o9bvfenhTKhxUakbYrLDnZU7HezAVxPM6Ehjw9Xjqy",
"/ipfs/QmPhnvn747LqwPYMJmQVorMaGbMSgA7mRRoyyZYz3DoZRQ",
}
var WebUIOption = RedirectOption("webui", WebUIPath)
| OpenBazaar/openbazaar-go | vendor/github.com/ipfs/go-ipfs/core/corehttp/webui.go | GO | mit | 1,107 |
<?php
/* SonataAdminBundle:CRUD:base_acl_macro.html.twig */
class __TwigTemplate_f7bb38229ed8df4e133506255cce57f53a109aac1f79d839de0cea8756a1aaf0 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 11
echo "
";
}
// line 12
public function getrender_form($__form__ = null, $__permissions__ = null, $__td_type__ = null, $__admin__ = null, $__admin_pool__ = null, $__object__ = null)
{
$context = $this->env->mergeGlobals(array(
"form" => $__form__,
"permissions" => $__permissions__,
"td_type" => $__td_type__,
"admin" => $__admin__,
"admin_pool" => $__admin_pool__,
"object" => $__object__,
));
$blocks = array();
ob_start();
try {
// line 13
echo " <form class=\"form-horizontal\"
action=\"";
// line 14
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["admin"]) ? $context["admin"] : $this->getContext($context, "admin")), "generateUrl", array(0 => "acl", 1 => array("id" => $this->getAttribute((isset($context["admin"]) ? $context["admin"] : $this->getContext($context, "admin")), "id", array(0 => (isset($context["object"]) ? $context["object"] : $this->getContext($context, "object"))), "method"), "uniqid" => $this->getAttribute((isset($context["admin"]) ? $context["admin"] : $this->getContext($context, "admin")), "uniqid", array()), "subclass" => $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "request", array()), "get", array(0 => "subclass"), "method"))), "method"), "html", null, true);
echo "\" ";
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'enctype');
echo "
method=\"POST\"
";
// line 16
if ( !$this->getAttribute((isset($context["admin_pool"]) ? $context["admin_pool"] : $this->getContext($context, "admin_pool")), "getOption", array(0 => "html5_validate"), "method")) {
echo "novalidate=\"novalidate\"";
}
// line 17
echo " >
";
// line 18
if ((twig_length_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "vars", array()), "errors", array())) > 0)) {
// line 19
echo " <div class=\"sonata-ba-form-error\">
";
// line 20
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'errors');
echo "
</div>
";
}
// line 23
echo "
<div class=\"box box-success\">
<div class=\"body table-responsive no-padding\">
<table class=\"table\">
<colgroup>
<col style=\"width: 100%;\"/>
";
// line 29
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable((isset($context["permissions"]) ? $context["permissions"] : $this->getContext($context, "permissions")));
foreach ($context['_seq'] as $context["_key"] => $context["permission"]) {
// line 30
echo " <col/>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['permission'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 32
echo " </colgroup>
";
// line 34
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "children", array()));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
foreach ($context['_seq'] as $context["_key"] => $context["child"]) {
if (($this->getAttribute($this->getAttribute($context["child"], "vars", array()), "name", array()) != "_token")) {
// line 35
echo " ";
if ((($this->getAttribute($context["loop"], "index0", array()) == 0) || (($this->getAttribute($context["loop"], "index0", array()) % 10) == 0))) {
// line 36
echo " <tr>
<th>";
// line 37
echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans((isset($context["td_type"]) ? $context["td_type"] : $this->getContext($context, "td_type")), array(), "SonataAdminBundle"), "html", null, true);
echo "</th>
";
// line 38
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable((isset($context["permissions"]) ? $context["permissions"] : $this->getContext($context, "permissions")));
foreach ($context['_seq'] as $context["_key"] => $context["permission"]) {
// line 39
echo " <th class=\"text-right\">";
echo twig_escape_filter($this->env, $context["permission"], "html", null, true);
echo "</th>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['permission'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 41
echo " </tr>
";
}
// line 43
echo "
<tr>
<td>
";
// line 46
$context["typeChild"] = (($this->getAttribute($context["child"], "role", array(), "array", true, true)) ? ($this->getAttribute($context["child"], "role", array(), "array")) : ($this->getAttribute($context["child"], "user", array(), "array")));
// line 47
echo " ";
echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["typeChild"]) ? $context["typeChild"] : $this->getContext($context, "typeChild")), "vars", array()), "value", array()), "html", null, true);
echo "
";
// line 48
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["typeChild"]) ? $context["typeChild"] : $this->getContext($context, "typeChild")), 'widget');
echo "
</td>
";
// line 50
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable((isset($context["permissions"]) ? $context["permissions"] : $this->getContext($context, "permissions")));
foreach ($context['_seq'] as $context["_key"] => $context["permission"]) {
// line 51
echo " <td class=\"text-right\">";
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($context["child"], $context["permission"], array(), "array"), 'widget', array("label" => false));
echo "</td>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['permission'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 53
echo " </tr>
";
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['child'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 55
echo " </table>
</div>
</div>
";
// line 59
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "_token", array()), 'row');
echo "
<div class=\"well well-small form-actions\">
<input class=\"btn btn-primary\" type=\"submit\" name=\"btn_create_and_edit\" value=\"";
// line 62
echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("btn_update_acl", array(), "SonataAdminBundle"), "html", null, true);
echo "\">
</div>
</form>
";
} catch (Exception $e) {
ob_end_clean();
throw $e;
}
return ('' === $tmp = ob_get_clean()) ? '' : new Twig_Markup($tmp, $this->env->getCharset());
}
public function getTemplateName()
{
return "SonataAdminBundle:CRUD:base_acl_macro.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 182 => 62, 176 => 59, 170 => 55, 159 => 53, 150 => 51, 146 => 50, 141 => 48, 136 => 47, 134 => 46, 129 => 43, 125 => 41, 116 => 39, 112 => 38, 108 => 37, 105 => 36, 102 => 35, 91 => 34, 87 => 32, 80 => 30, 76 => 29, 68 => 23, 62 => 20, 59 => 19, 57 => 18, 54 => 17, 50 => 16, 43 => 14, 40 => 13, 24 => 12, 19 => 11,);
}
}
| chicho2114/Proy_Frameworks | app/cache/dev/twig/f7/bb/38229ed8df4e133506255cce57f53a109aac1f79d839de0cea8756a1aaf0.php | PHP | mit | 11,223 |
class X where
foo :: Int
-- | Y
-- Y is something
-- nice.
class Y where
bar :: Int
| itchyny/vim-haskell-indent | test/comment/before_blank_line_and_class.out.hs | Haskell | mit | 91 |
/**
* Logger configuration
*
* Configure the log level for your app, as well as the transport
* (Underneath the covers, Sails uses Winston for logging, which
* allows for some pretty neat custom transports/adapters for log messages)
*
* For more information on the Sails logger, check out:
* http://sailsjs.org/#documentation
*/
module.exports = {
// Valid `level` configs:
// i.e. the minimum log level to capture with sails.log.*()
//
// 'error' : Display calls to `.error()`
// 'warn' : Display calls from `.error()` to `.warn()`
// 'debug' : Display calls from `.error()`, `.warn()` to `.debug()`
// 'info' : Display calls from `.error()`, `.warn()`, `.debug()` to `.info()`
// 'verbose': Display calls from `.error()`, `.warn()`, `.debug()`, `.info()` to `.verbose()`
//
log: {
level: 'info'
}
};
| emagnier/spinnaker | config/log.js | JavaScript | mit | 866 |
/*****************************************************************************
* This file is part of the Prolog Development Tool (PDT)
*
* Author: Lukas Degener (among others)
* WWW: http://sewiki.iai.uni-bonn.de/research/pdt/start
* Mail: pdt@lists.iai.uni-bonn.de
* Copyright (C): 2004-2012, CS Dept. III, University of Bonn
*
* All rights reserved. This program is made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
****************************************************************************/
package org.cs3.prolog.connector.cterm;
import org.cs3.prolog.connector.internal.cterm.parser.ASTNode;
/**
* Represents a Prolog string.
*/
public class CString extends CTerm {
public CString(ASTNode node) {
super(node);
}
}
| TeamSPoon/logicmoo_base | prolog/logicmoo/pdt_server/prolog.connector/src/org/cs3/prolog/connector/cterm/CString.java | Java | mit | 870 |
//
// Created by eran on 01/04/2015.
//
#include <unordered_set>
#include "fakeit/Invocation.hpp"
namespace fakeit {
struct ActualInvocationsContainer {
virtual void clear() = 0;
virtual ~ActualInvocationsContainer() NO_THROWS { }
};
struct ActualInvocationsSource {
virtual void getActualInvocations(std::unordered_set<fakeit::Invocation *> &into) const = 0;
virtual ~ActualInvocationsSource() NO_THROWS { }
};
struct InvocationsSourceProxy : public ActualInvocationsSource {
InvocationsSourceProxy(ActualInvocationsSource *inner) :
_inner(inner) {
}
void getActualInvocations(std::unordered_set<fakeit::Invocation *> &into) const override {
_inner->getActualInvocations(into);
}
private:
std::shared_ptr<ActualInvocationsSource> _inner;
};
struct UnverifiedInvocationsSource : public ActualInvocationsSource {
UnverifiedInvocationsSource(InvocationsSourceProxy decorated) : _decorated(decorated) {
}
void getActualInvocations(std::unordered_set<fakeit::Invocation *> &into) const override {
std::unordered_set<fakeit::Invocation *> all;
_decorated.getActualInvocations(all);
for (fakeit::Invocation *i : all) {
if (!i->isVerified()) {
into.insert(i);
}
}
}
private:
InvocationsSourceProxy _decorated;
};
struct AggregateInvocationsSource : public ActualInvocationsSource {
AggregateInvocationsSource(std::vector<ActualInvocationsSource *> &sources) : _sources(sources) {
}
void getActualInvocations(std::unordered_set<fakeit::Invocation *> &into) const override {
std::unordered_set<fakeit::Invocation *> tmp;
for (ActualInvocationsSource *source : _sources) {
source->getActualInvocations(tmp);
}
filter(tmp, into);
}
protected:
bool shouldInclude(fakeit::Invocation *) const {
return true;
}
private:
std::vector<ActualInvocationsSource *> _sources;
void filter(std::unordered_set<Invocation *> &source, std::unordered_set<Invocation *> &target) const {
for (Invocation *i:source) {
if (shouldInclude(i)) {
target.insert(i);
}
}
}
};
}
| helmesjo/hello-ci | src/external/fakeit/fakeit-repo/include/fakeit/ActualInvocationsSource.hpp | C++ | mit | 2,462 |
#!/usr/bin/python
# Copyright 2014 Steven Watanabe
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or https://www.bfgroup.xyz/b2/LICENSE.txt)
# Test the handling of toolset.add-requirements
import BoostBuild
t = BoostBuild.Tester(pass_toolset=0, ignore_toolset_requirements=False)
t.write('jamroot.jam', '''
import toolset ;
import errors ;
rule test-rule ( properties * )
{
return <define>TEST_INDIRECT_CONDITIONAL ;
}
toolset.add-requirements
<define>TEST_MACRO
<conditional>@test-rule
<link>shared:<define>TEST_CONDITIONAL
;
rule check-requirements ( target : sources * : properties * )
{
local macros = TEST_MACRO TEST_CONDITIONAL TEST_INDIRECT_CONDITIONAL ;
for local m in $(macros)
{
if ! <define>$(m) in $(properties)
{
errors.error $(m) not defined ;
}
}
}
make test : : @check-requirements ;
''')
t.run_build_system()
t.cleanup()
| davehorton/drachtio-server | deps/boost_1_77_0/tools/build/test/toolset_requirements.py | Python | mit | 933 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />
<link rel="shortcut icon" type="image/x-icon" href="../../../favicon.ico" />
<title>CellIdentityWcdma - Android SDK | Android Developers</title>
<!-- STYLESHEETS -->
<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto">
<link href="../../../assets/css/default.css" rel="stylesheet" type="text/css">
<!-- FULLSCREEN STYLESHEET -->
<link href="../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen"
type="text/css">
<!-- JAVASCRIPT -->
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="../../../assets/js/android_3p-bundle.js" type="text/javascript"></script>
<script type="text/javascript">
var toRoot = "../../../";
var devsite = false;
</script>
<script src="../../../assets/js/docs.js" type="text/javascript"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-5831155-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body class="gc-documentation
develop" itemscope itemtype="http://schema.org/Article">
<div id="doc-api-level" class="18" style="display:none"></div>
<a name="top"></a>
<a name="top"></a>
<!-- Header -->
<div id="header">
<div class="wrap" id="header-wrap">
<div class="col-3 logo">
<a href="../../../index.html">
<img src="../../../assets/images/dac_logo.png" width="123" height="25" alt="Android Developers" />
</a>
<div class="btn-quicknav" id="btn-quicknav">
<a href="#" class="arrow-inactive">Quicknav</a>
<a href="#" class="arrow-active">Quicknav</a>
</div>
</div>
<ul class="nav-x col-9">
<li class="design">
<a href="../../../design/index.html"
zh-tw-lang="設計"
zh-cn-lang="设计"
ru-lang="Проектирование"
ko-lang="디자인"
ja-lang="設計"
es-lang="Diseñar"
>Design</a></li>
<li class="develop"><a href="../../../develop/index.html"
zh-tw-lang="開發"
zh-cn-lang="开发"
ru-lang="Разработка"
ko-lang="개발"
ja-lang="開発"
es-lang="Desarrollar"
>Develop</a></li>
<li class="distribute last"><a href="../../../distribute/index.html"
zh-tw-lang="發佈"
zh-cn-lang="分发"
ru-lang="Распространение"
ko-lang="배포"
ja-lang="配布"
es-lang="Distribuir"
>Distribute</a></li>
</ul>
<!-- New Search -->
<div class="menu-container">
<div class="moremenu">
<div id="more-btn"></div>
</div>
<div class="morehover" id="moremenu">
<div class="top"></div>
<div class="mid">
<div class="header">Links</div>
<ul>
<li><a href="https://play.google.com/apps/publish/">Google Play Developer Console</a></li>
<li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li>
<li><a href="../../../about/index.html">About Android</a></li>
</ul>
<div class="header">Android Sites</div>
<ul>
<li><a href="http://www.android.com">Android.com</a></li>
<li class="active"><a>Android Developers</a></li>
<li><a href="http://source.android.com">Android Open Source Project</a></li>
</ul>
<br class="clearfix" />
</div>
<div class="bottom"></div>
</div>
<div class="search" id="search-container">
<div class="search-inner">
<div id="search-btn"></div>
<div class="left"></div>
<form onsubmit="return submit_search()">
<input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../')"
onkeyup="return search_changed(event, false, '../../../')" />
</form>
<div class="right"></div>
<a class="close hide">close</a>
<div class="left"></div>
<div class="right"></div>
</div>
</div>
<div class="search_filtered_wrapper reference">
<div class="suggest-card reference no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
<div class="search_filtered_wrapper docs">
<div class="suggest-card dummy no-display"> </div>
<div class="suggest-card develop no-display">
<ul class="search_filtered">
</ul>
<div class="child-card guides no-display">
</div>
<div class="child-card training no-display">
</div>
</div>
<div class="suggest-card design no-display">
<ul class="search_filtered">
</ul>
</div>
<div class="suggest-card distribute no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
</div>
<!-- /New Search>
<!-- Expanded quicknav -->
<div id="quicknav" class="col-9">
<ul>
<li class="design">
<ul>
<li><a href="../../../design/index.html">Get Started</a></li>
<li><a href="../../../design/style/index.html">Style</a></li>
<li><a href="../../../design/patterns/index.html">Patterns</a></li>
<li><a href="../../../design/building-blocks/index.html">Building Blocks</a></li>
<li><a href="../../../design/downloads/index.html">Downloads</a></li>
<li><a href="../../../design/videos/index.html">Videos</a></li>
</ul>
</li>
<li class="develop">
<ul>
<li><a href="../../../training/index.html"
zh-tw-lang="訓練課程"
zh-cn-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li><a href="../../../guide/components/index.html"
zh-tw-lang="API 指南"
zh-cn-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li><a href="../../../reference/packages.html"
zh-tw-lang="參考資源"
zh-cn-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li><a href="../../../tools/index.html"
zh-tw-lang="相關工具"
zh-cn-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a>
<ul><li><a href="../../../sdk/index.html">Get the SDK</a></li></ul>
</li>
<li><a href="../../../google/index.html">Google Services</a>
</li>
</ul>
</li>
<li class="distribute last">
<ul>
<li><a href="../../../distribute/index.html">Google Play</a></li>
<li><a href="../../../distribute/googleplay/publish/index.html">Publishing</a></li>
<li><a href="../../../distribute/googleplay/promote/index.html">Promoting</a></li>
<li><a href="../../../distribute/googleplay/quality/index.html">App Quality</a></li>
<li><a href="../../../distribute/googleplay/spotlight/index.html">Spotlight</a></li>
<li><a href="../../../distribute/open.html">Open Distribution</a></li>
</ul>
</li>
</ul>
</div>
<!-- /Expanded quicknav -->
</div>
</div>
<!-- /Header -->
<div id="searchResults" class="wrap" style="display:none;">
<h2 id="searchTitle">Results</h2>
<div id="leftSearchControl" class="search-control">Loading...</div>
</div>
<!-- Secondary x-nav -->
<div id="nav-x">
<div class="wrap">
<ul class="nav-x col-9 develop" style="width:100%">
<li class="training"><a href="../../../training/index.html"
zh-tw-lang="訓練課程"
zh-cn-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li class="guide"><a href="../../../guide/components/index.html"
zh-tw-lang="API 指南"
zh-cn-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li class="reference"><a href="../../../reference/packages.html"
zh-tw-lang="參考資源"
zh-cn-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li class="tools"><a href="../../../tools/index.html"
zh-tw-lang="相關工具"
zh-cn-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a></li>
<li class="google"><a href="../../../google/index.html"
>Google Services</a>
</li>
</ul>
</div>
</div>
<!-- /Sendondary x-nav -->
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<div id="api-nav-header">
<div id="api-level-toggle">
<label for="apiLevelCheckbox" class="disabled">API level: </label>
<div class="select-wrapper">
<select id="apiLevelSelector">
<!-- option elements added by buildApiLevelSelector() -->
</select>
</div>
</div><!-- end toggle -->
<div id="api-nav-title">Android APIs</div>
</div><!-- end nav header -->
<script>
var SINCE_DATA = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19' ];
buildApiLevelSelector();
</script>
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav" class="scroll-pane">
<ul>
<li class="api apilevel-1">
<a href="../../../reference/android/package-summary.html">android</a></li>
<li class="api apilevel-4">
<a href="../../../reference/android/accessibilityservice/package-summary.html">android.accessibilityservice</a></li>
<li class="api apilevel-5">
<a href="../../../reference/android/accounts/package-summary.html">android.accounts</a></li>
<li class="api apilevel-11">
<a href="../../../reference/android/animation/package-summary.html">android.animation</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/app/package-summary.html">android.app</a></li>
<li class="api apilevel-8">
<a href="../../../reference/android/app/admin/package-summary.html">android.app.admin</a></li>
<li class="api apilevel-8">
<a href="../../../reference/android/app/backup/package-summary.html">android.app.backup</a></li>
<li class="api apilevel-3">
<a href="../../../reference/android/appwidget/package-summary.html">android.appwidget</a></li>
<li class="api apilevel-5">
<a href="../../../reference/android/bluetooth/package-summary.html">android.bluetooth</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/content/package-summary.html">android.content</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/content/pm/package-summary.html">android.content.pm</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/content/res/package-summary.html">android.content.res</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/database/package-summary.html">android.database</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/database/sqlite/package-summary.html">android.database.sqlite</a></li>
<li class="api apilevel-11">
<a href="../../../reference/android/drm/package-summary.html">android.drm</a></li>
<li class="api apilevel-4">
<a href="../../../reference/android/gesture/package-summary.html">android.gesture</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/graphics/package-summary.html">android.graphics</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/graphics/drawable/package-summary.html">android.graphics.drawable</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/graphics/drawable/shapes/package-summary.html">android.graphics.drawable.shapes</a></li>
<li class="api apilevel-19">
<a href="../../../reference/android/graphics/pdf/package-summary.html">android.graphics.pdf</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/hardware/package-summary.html">android.hardware</a></li>
<li class="api apilevel-17">
<a href="../../../reference/android/hardware/display/package-summary.html">android.hardware.display</a></li>
<li class="api apilevel-16">
<a href="../../../reference/android/hardware/input/package-summary.html">android.hardware.input</a></li>
<li class="api apilevel-18">
<a href="../../../reference/android/hardware/location/package-summary.html">android.hardware.location</a></li>
<li class="api apilevel-12">
<a href="../../../reference/android/hardware/usb/package-summary.html">android.hardware.usb</a></li>
<li class="api apilevel-3">
<a href="../../../reference/android/inputmethodservice/package-summary.html">android.inputmethodservice</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/location/package-summary.html">android.location</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/media/package-summary.html">android.media</a></li>
<li class="api apilevel-9">
<a href="../../../reference/android/media/audiofx/package-summary.html">android.media.audiofx</a></li>
<li class="api apilevel-14">
<a href="../../../reference/android/media/effect/package-summary.html">android.media.effect</a></li>
<li class="api apilevel-12">
<a href="../../../reference/android/mtp/package-summary.html">android.mtp</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/net/package-summary.html">android.net</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/net/http/package-summary.html">android.net.http</a></li>
<li class="api apilevel-16">
<a href="../../../reference/android/net/nsd/package-summary.html">android.net.nsd</a></li>
<li class="api apilevel-12">
<a href="../../../reference/android/net/rtp/package-summary.html">android.net.rtp</a></li>
<li class="api apilevel-9">
<a href="../../../reference/android/net/sip/package-summary.html">android.net.sip</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/net/wifi/package-summary.html">android.net.wifi</a></li>
<li class="api apilevel-14">
<a href="../../../reference/android/net/wifi/p2p/package-summary.html">android.net.wifi.p2p</a></li>
<li class="api apilevel-16">
<a href="../../../reference/android/net/wifi/p2p/nsd/package-summary.html">android.net.wifi.p2p.nsd</a></li>
<li class="api apilevel-9">
<a href="../../../reference/android/nfc/package-summary.html">android.nfc</a></li>
<li class="api apilevel-19">
<a href="../../../reference/android/nfc/cardemulation/package-summary.html">android.nfc.cardemulation</a></li>
<li class="api apilevel-10">
<a href="../../../reference/android/nfc/tech/package-summary.html">android.nfc.tech</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/opengl/package-summary.html">android.opengl</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/os/package-summary.html">android.os</a></li>
<li class="api apilevel-9">
<a href="../../../reference/android/os/storage/package-summary.html">android.os.storage</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/preference/package-summary.html">android.preference</a></li>
<li class="api apilevel-19">
<a href="../../../reference/android/print/package-summary.html">android.print</a></li>
<li class="api apilevel-19">
<a href="../../../reference/android/print/pdf/package-summary.html">android.print.pdf</a></li>
<li class="api apilevel-19">
<a href="../../../reference/android/printservice/package-summary.html">android.printservice</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/provider/package-summary.html">android.provider</a></li>
<li class="api apilevel-11">
<a href="../../../reference/android/renderscript/package-summary.html">android.renderscript</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/sax/package-summary.html">android.sax</a></li>
<li class="api apilevel-14">
<a href="../../../reference/android/security/package-summary.html">android.security</a></li>
<li class="api apilevel-17">
<a href="../../../reference/android/service/dreams/package-summary.html">android.service.dreams</a></li>
<li class="api apilevel-18">
<a href="../../../reference/android/service/notification/package-summary.html">android.service.notification</a></li>
<li class="api apilevel-14">
<a href="../../../reference/android/service/textservice/package-summary.html">android.service.textservice</a></li>
<li class="api apilevel-7">
<a href="../../../reference/android/service/wallpaper/package-summary.html">android.service.wallpaper</a></li>
<li class="api apilevel-3">
<a href="../../../reference/android/speech/package-summary.html">android.speech</a></li>
<li class="api apilevel-4">
<a href="../../../reference/android/speech/tts/package-summary.html">android.speech.tts</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v13/app/package-summary.html">android.support.v13.app</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v4/accessibilityservice/package-summary.html">android.support.v4.accessibilityservice</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v4/app/package-summary.html">android.support.v4.app</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v4/content/package-summary.html">android.support.v4.content</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v4/content/pm/package-summary.html">android.support.v4.content.pm</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v4/database/package-summary.html">android.support.v4.database</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v4/graphics/drawable/package-summary.html">android.support.v4.graphics.drawable</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v4/hardware/display/package-summary.html">android.support.v4.hardware.display</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v4/media/package-summary.html">android.support.v4.media</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v4/net/package-summary.html">android.support.v4.net</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v4/os/package-summary.html">android.support.v4.os</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v4/print/package-summary.html">android.support.v4.print</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v4/text/package-summary.html">android.support.v4.text</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v4/util/package-summary.html">android.support.v4.util</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v4/view/package-summary.html">android.support.v4.view</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v4/view/accessibility/package-summary.html">android.support.v4.view.accessibility</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v4/widget/package-summary.html">android.support.v4.widget</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v7/app/package-summary.html">android.support.v7.app</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v7/appcompat/package-summary.html">android.support.v7.appcompat</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v7/gridlayout/package-summary.html">android.support.v7.gridlayout</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v7/media/package-summary.html">android.support.v7.media</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v7/mediarouter/package-summary.html">android.support.v7.mediarouter</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v7/view/package-summary.html">android.support.v7.view</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v7/widget/package-summary.html">android.support.v7.widget</a></li>
<li class="api apilevel-">
<a href="../../../reference/android/support/v8/renderscript/package-summary.html">android.support.v8.renderscript</a></li>
<li class="selected api apilevel-1">
<a href="../../../reference/android/telephony/package-summary.html">android.telephony</a></li>
<li class="api apilevel-5">
<a href="../../../reference/android/telephony/cdma/package-summary.html">android.telephony.cdma</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/telephony/gsm/package-summary.html">android.telephony.gsm</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/test/package-summary.html">android.test</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/test/mock/package-summary.html">android.test.mock</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/test/suitebuilder/package-summary.html">android.test.suitebuilder</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/text/package-summary.html">android.text</a></li>
<li class="api apilevel-3">
<a href="../../../reference/android/text/format/package-summary.html">android.text.format</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/text/method/package-summary.html">android.text.method</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/text/style/package-summary.html">android.text.style</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/text/util/package-summary.html">android.text.util</a></li>
<li class="api apilevel-19">
<a href="../../../reference/android/transition/package-summary.html">android.transition</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/util/package-summary.html">android.util</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/view/package-summary.html">android.view</a></li>
<li class="api apilevel-4">
<a href="../../../reference/android/view/accessibility/package-summary.html">android.view.accessibility</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/view/animation/package-summary.html">android.view.animation</a></li>
<li class="api apilevel-3">
<a href="../../../reference/android/view/inputmethod/package-summary.html">android.view.inputmethod</a></li>
<li class="api apilevel-14">
<a href="../../../reference/android/view/textservice/package-summary.html">android.view.textservice</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/webkit/package-summary.html">android.webkit</a></li>
<li class="api apilevel-1">
<a href="../../../reference/android/widget/package-summary.html">android.widget</a></li>
<li class="api apilevel-1">
<a href="../../../reference/dalvik/bytecode/package-summary.html">dalvik.bytecode</a></li>
<li class="api apilevel-1">
<a href="../../../reference/dalvik/system/package-summary.html">dalvik.system</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/awt/font/package-summary.html">java.awt.font</a></li>
<li class="api apilevel-3">
<a href="../../../reference/java/beans/package-summary.html">java.beans</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/io/package-summary.html">java.io</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/lang/package-summary.html">java.lang</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/lang/annotation/package-summary.html">java.lang.annotation</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/lang/ref/package-summary.html">java.lang.ref</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/lang/reflect/package-summary.html">java.lang.reflect</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/math/package-summary.html">java.math</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/net/package-summary.html">java.net</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/nio/package-summary.html">java.nio</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/nio/channels/package-summary.html">java.nio.channels</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/nio/channels/spi/package-summary.html">java.nio.channels.spi</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/nio/charset/package-summary.html">java.nio.charset</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/nio/charset/spi/package-summary.html">java.nio.charset.spi</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/security/package-summary.html">java.security</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/security/acl/package-summary.html">java.security.acl</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/security/cert/package-summary.html">java.security.cert</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/security/interfaces/package-summary.html">java.security.interfaces</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/security/spec/package-summary.html">java.security.spec</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/sql/package-summary.html">java.sql</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/text/package-summary.html">java.text</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/util/package-summary.html">java.util</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/util/concurrent/package-summary.html">java.util.concurrent</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/util/concurrent/atomic/package-summary.html">java.util.concurrent.atomic</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/util/concurrent/locks/package-summary.html">java.util.concurrent.locks</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/util/jar/package-summary.html">java.util.jar</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/util/logging/package-summary.html">java.util.logging</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/util/prefs/package-summary.html">java.util.prefs</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/util/regex/package-summary.html">java.util.regex</a></li>
<li class="api apilevel-1">
<a href="../../../reference/java/util/zip/package-summary.html">java.util.zip</a></li>
<li class="api apilevel-1">
<a href="../../../reference/javax/crypto/package-summary.html">javax.crypto</a></li>
<li class="api apilevel-1">
<a href="../../../reference/javax/crypto/interfaces/package-summary.html">javax.crypto.interfaces</a></li>
<li class="api apilevel-1">
<a href="../../../reference/javax/crypto/spec/package-summary.html">javax.crypto.spec</a></li>
<li class="api apilevel-1">
<a href="../../../reference/javax/microedition/khronos/egl/package-summary.html">javax.microedition.khronos.egl</a></li>
<li class="api apilevel-1">
<a href="../../../reference/javax/microedition/khronos/opengles/package-summary.html">javax.microedition.khronos.opengles</a></li>
<li class="api apilevel-1">
<a href="../../../reference/javax/net/package-summary.html">javax.net</a></li>
<li class="api apilevel-1">
<a href="../../../reference/javax/net/ssl/package-summary.html">javax.net.ssl</a></li>
<li class="api apilevel-1">
<a href="../../../reference/javax/security/auth/package-summary.html">javax.security.auth</a></li>
<li class="api apilevel-1">
<a href="../../../reference/javax/security/auth/callback/package-summary.html">javax.security.auth.callback</a></li>
<li class="api apilevel-1">
<a href="../../../reference/javax/security/auth/login/package-summary.html">javax.security.auth.login</a></li>
<li class="api apilevel-1">
<a href="../../../reference/javax/security/auth/x500/package-summary.html">javax.security.auth.x500</a></li>
<li class="api apilevel-1">
<a href="../../../reference/javax/security/cert/package-summary.html">javax.security.cert</a></li>
<li class="api apilevel-1">
<a href="../../../reference/javax/sql/package-summary.html">javax.sql</a></li>
<li class="api apilevel-1">
<a href="../../../reference/javax/xml/package-summary.html">javax.xml</a></li>
<li class="api apilevel-8">
<a href="../../../reference/javax/xml/datatype/package-summary.html">javax.xml.datatype</a></li>
<li class="api apilevel-8">
<a href="../../../reference/javax/xml/namespace/package-summary.html">javax.xml.namespace</a></li>
<li class="api apilevel-1">
<a href="../../../reference/javax/xml/parsers/package-summary.html">javax.xml.parsers</a></li>
<li class="api apilevel-8">
<a href="../../../reference/javax/xml/transform/package-summary.html">javax.xml.transform</a></li>
<li class="api apilevel-8">
<a href="../../../reference/javax/xml/transform/dom/package-summary.html">javax.xml.transform.dom</a></li>
<li class="api apilevel-8">
<a href="../../../reference/javax/xml/transform/sax/package-summary.html">javax.xml.transform.sax</a></li>
<li class="api apilevel-8">
<a href="../../../reference/javax/xml/transform/stream/package-summary.html">javax.xml.transform.stream</a></li>
<li class="api apilevel-8">
<a href="../../../reference/javax/xml/validation/package-summary.html">javax.xml.validation</a></li>
<li class="api apilevel-8">
<a href="../../../reference/javax/xml/xpath/package-summary.html">javax.xml.xpath</a></li>
<li class="api apilevel-1">
<a href="../../../reference/junit/framework/package-summary.html">junit.framework</a></li>
<li class="api apilevel-1">
<a href="../../../reference/junit/runner/package-summary.html">junit.runner</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/package-summary.html">org.apache.http</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/auth/package-summary.html">org.apache.http.auth</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/auth/params/package-summary.html">org.apache.http.auth.params</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/client/package-summary.html">org.apache.http.client</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/client/entity/package-summary.html">org.apache.http.client.entity</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/client/methods/package-summary.html">org.apache.http.client.methods</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/client/params/package-summary.html">org.apache.http.client.params</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/client/protocol/package-summary.html">org.apache.http.client.protocol</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/client/utils/package-summary.html">org.apache.http.client.utils</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/conn/package-summary.html">org.apache.http.conn</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/conn/params/package-summary.html">org.apache.http.conn.params</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/conn/routing/package-summary.html">org.apache.http.conn.routing</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/conn/scheme/package-summary.html">org.apache.http.conn.scheme</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/conn/ssl/package-summary.html">org.apache.http.conn.ssl</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/conn/util/package-summary.html">org.apache.http.conn.util</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/cookie/package-summary.html">org.apache.http.cookie</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/cookie/params/package-summary.html">org.apache.http.cookie.params</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/entity/package-summary.html">org.apache.http.entity</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/impl/package-summary.html">org.apache.http.impl</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/impl/auth/package-summary.html">org.apache.http.impl.auth</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/impl/client/package-summary.html">org.apache.http.impl.client</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/impl/conn/package-summary.html">org.apache.http.impl.conn</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/impl/conn/tsccm/package-summary.html">org.apache.http.impl.conn.tsccm</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/impl/cookie/package-summary.html">org.apache.http.impl.cookie</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/impl/entity/package-summary.html">org.apache.http.impl.entity</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/impl/io/package-summary.html">org.apache.http.impl.io</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/io/package-summary.html">org.apache.http.io</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/message/package-summary.html">org.apache.http.message</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/params/package-summary.html">org.apache.http.params</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/protocol/package-summary.html">org.apache.http.protocol</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/apache/http/util/package-summary.html">org.apache.http.util</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/json/package-summary.html">org.json</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/w3c/dom/package-summary.html">org.w3c.dom</a></li>
<li class="api apilevel-8">
<a href="../../../reference/org/w3c/dom/ls/package-summary.html">org.w3c.dom.ls</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/xml/sax/package-summary.html">org.xml.sax</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/xml/sax/ext/package-summary.html">org.xml.sax.ext</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/xml/sax/helpers/package-summary.html">org.xml.sax.helpers</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/xmlpull/v1/package-summary.html">org.xmlpull.v1</a></li>
<li class="api apilevel-1">
<a href="../../../reference/org/xmlpull/v1/sax2/package-summary.html">org.xmlpull.v1.sax2</a></li>
</ul><br/>
</div> <!-- end packages-nav -->
</div> <!-- end resize-packages -->
<div id="classes-nav" class="scroll-pane">
<ul>
<li><h2>Classes</h2>
<ul>
<li class="api apilevel-17"><a href="../../../reference/android/telephony/CellIdentityCdma.html">CellIdentityCdma</a></li>
<li class="api apilevel-17"><a href="../../../reference/android/telephony/CellIdentityGsm.html">CellIdentityGsm</a></li>
<li class="api apilevel-17"><a href="../../../reference/android/telephony/CellIdentityLte.html">CellIdentityLte</a></li>
<li class="selected api apilevel-18"><a href="../../../reference/android/telephony/CellIdentityWcdma.html">CellIdentityWcdma</a></li>
<li class="api apilevel-17"><a href="../../../reference/android/telephony/CellInfo.html">CellInfo</a></li>
<li class="api apilevel-17"><a href="../../../reference/android/telephony/CellInfoCdma.html">CellInfoCdma</a></li>
<li class="api apilevel-17"><a href="../../../reference/android/telephony/CellInfoGsm.html">CellInfoGsm</a></li>
<li class="api apilevel-17"><a href="../../../reference/android/telephony/CellInfoLte.html">CellInfoLte</a></li>
<li class="api apilevel-18"><a href="../../../reference/android/telephony/CellInfoWcdma.html">CellInfoWcdma</a></li>
<li class="api apilevel-1"><a href="../../../reference/android/telephony/CellLocation.html">CellLocation</a></li>
<li class="api apilevel-17"><a href="../../../reference/android/telephony/CellSignalStrength.html">CellSignalStrength</a></li>
<li class="api apilevel-17"><a href="../../../reference/android/telephony/CellSignalStrengthCdma.html">CellSignalStrengthCdma</a></li>
<li class="api apilevel-17"><a href="../../../reference/android/telephony/CellSignalStrengthGsm.html">CellSignalStrengthGsm</a></li>
<li class="api apilevel-17"><a href="../../../reference/android/telephony/CellSignalStrengthLte.html">CellSignalStrengthLte</a></li>
<li class="api apilevel-18"><a href="../../../reference/android/telephony/CellSignalStrengthWcdma.html">CellSignalStrengthWcdma</a></li>
<li class="api apilevel-3"><a href="../../../reference/android/telephony/NeighboringCellInfo.html">NeighboringCellInfo</a></li>
<li class="api apilevel-1"><a href="../../../reference/android/telephony/PhoneNumberFormattingTextWatcher.html">PhoneNumberFormattingTextWatcher</a></li>
<li class="api apilevel-1"><a href="../../../reference/android/telephony/PhoneNumberUtils.html">PhoneNumberUtils</a></li>
<li class="api apilevel-1"><a href="../../../reference/android/telephony/PhoneStateListener.html">PhoneStateListener</a></li>
<li class="api apilevel-1"><a href="../../../reference/android/telephony/ServiceState.html">ServiceState</a></li>
<li class="api apilevel-7"><a href="../../../reference/android/telephony/SignalStrength.html">SignalStrength</a></li>
<li class="api apilevel-4"><a href="../../../reference/android/telephony/SmsManager.html">SmsManager</a></li>
<li class="api apilevel-4"><a href="../../../reference/android/telephony/SmsMessage.html">SmsMessage</a></li>
<li class="api apilevel-4"><a href="../../../reference/android/telephony/SmsMessage.SubmitPdu.html">SmsMessage.SubmitPdu</a></li>
<li class="api apilevel-1"><a href="../../../reference/android/telephony/TelephonyManager.html">TelephonyManager</a></li>
</ul>
</li>
<li><h2>Enums</h2>
<ul>
<li class="api apilevel-4"><a href="../../../reference/android/telephony/SmsMessage.MessageClass.html">SmsMessage.MessageClass</a></li>
</ul>
</li>
</ul><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none" class="scroll-pane">
<div id="tree-list"></div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
<div id="nav-swap">
<a class="fullscreen">fullscreen</a>
<a href='#' onclick='swapNav();return false;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>
</div>
</div> <!-- end devdoc-nav -->
</div> <!-- end side-nav -->
<script type="text/javascript">
// init fullscreen based on user pref
var fullscreen = readCookie("fullscreen");
if (fullscreen != 0) {
if (fullscreen == "false") {
toggleFullscreen(false);
} else {
toggleFullscreen(true);
}
}
// init nav version for mobile
if (isMobile) {
swapNav(); // tree view should be used on mobile
$('#nav-swap').hide();
} else {
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("../../../");
}
}
// scroll the selected page into view
$(document).ready(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
</script>
<div class="col-12" id="doc-col">
<div id="api-info-block">
<div class="sum-details-links">
Summary:
<a href="#inhconstants">Inherited Constants</a>
| <a href="#lfields">Fields</a>
| <a href="#pubmethods">Methods</a>
| <a href="#inhmethods">Inherited Methods</a>
| <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a>
</div><!-- end sum-details-links -->
<div class="api-level">
Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a>
</div>
</div><!-- end api-info-block -->
<!-- ======== START OF CLASS DATA ======== -->
<div id="jd-header">
public
final
class
<h1 itemprop="name">CellIdentityWcdma</h1>
extends <a href="../../../reference/java/lang/Object.html">Object</a><br/>
implements
<a href="../../../reference/android/os/Parcelable.html">Parcelable</a>
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-18">
<table class="jd-inheritance-table">
<tr>
<td colspan="2" class="jd-inheritance-class-cell"><a href="../../../reference/java/lang/Object.html">java.lang.Object</a></td>
</tr>
<tr>
<td class="jd-inheritance-space"> ↳</td>
<td colspan="1" class="jd-inheritance-class-cell">android.telephony.CellIdentityWcdma</td>
</tr>
</table>
<div class="jd-descr">
<h2>Class Overview</h2>
<p itemprop="articleBody">CellIdentity to represent a unique UMTS cell
</p>
</div><!-- jd-descr -->
<div class="jd-descr">
<h2>Summary</h2>
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<table id="inhconstants" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Constants</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-constants-android.os.Parcelable" class="jd-expando-trigger closed"
><img id="inherited-constants-android.os.Parcelable-trigger"
src="../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>From interface
<a href="../../../reference/android/os/Parcelable.html">android.os.Parcelable</a>
<div id="inherited-constants-android.os.Parcelable">
<div id="inherited-constants-android.os.Parcelable-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-constants-android.os.Parcelable-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-1" >
<td class="jd-typecol">int</td>
<td class="jd-linkcol"><a href="../../../reference/android/os/Parcelable.html#CONTENTS_FILE_DESCRIPTOR">CONTENTS_FILE_DESCRIPTOR</a></td>
<td class="jd-descrcol" width="100%">Bit masks for use with <code><a href="../../../reference/android/os/Parcelable.html#describeContents()">describeContents()</a></code>: each bit represents a
kind of object considered to have potential special significance when
marshalled.</td>
</tr>
<tr class=" api apilevel-1" >
<td class="jd-typecol">int</td>
<td class="jd-linkcol"><a href="../../../reference/android/os/Parcelable.html#PARCELABLE_WRITE_RETURN_VALUE">PARCELABLE_WRITE_RETURN_VALUE</a></td>
<td class="jd-descrcol" width="100%">Flag for use with <code><a href="../../../reference/android/os/Parcelable.html#writeToParcel(android.os.Parcel, int)">writeToParcel(Parcel, int)</a></code>: the object being written
is a return value, that is the result of a function such as
"<code>Parcelable someFunction()</code>",
"<code>void someFunction(out Parcelable)</code>", or
"<code>void someFunction(inout Parcelable)</code>".</td>
</tr>
</table>
</div>
</div>
</td></tr>
</table>
<!-- =========== FIELD SUMMARY =========== -->
<table id="lfields" class="jd-sumtable"><tr><th colspan="12">Fields</th></tr>
<tr class="alt-color api apilevel-18" >
<td class="jd-typecol"><nobr>
public
static
final
<a href="../../../reference/android/os/Parcelable.Creator.html">Creator</a><<a href="../../../reference/android/telephony/CellIdentityWcdma.html">CellIdentityWcdma</a>></nobr></td>
<td class="jd-linkcol"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#CREATOR">CREATOR</a></td>
<td class="jd-descrcol" width="100%">Implement the Parcelable interface </td>
</tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr>
<tr class="alt-color api apilevel-18" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#describeContents()">describeContents</a></span>()</nobr>
<div class="jd-descrdiv">Implement the Parcelable interface </div>
</td></tr>
<tr class=" api apilevel-18" >
<td class="jd-typecol"><nobr>
boolean</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#equals(java.lang.Object)">equals</a></span>(<a href="../../../reference/java/lang/Object.html">Object</a> other)</nobr>
<div class="jd-descrdiv">Compares this instance with the specified object and indicates if they
are equal.</div>
</td></tr>
<tr class="alt-color api apilevel-18" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#getCid()">getCid</a></span>()</nobr>
</td></tr>
<tr class=" api apilevel-18" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#getLac()">getLac</a></span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-18" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#getMcc()">getMcc</a></span>()</nobr>
</td></tr>
<tr class=" api apilevel-18" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#getMnc()">getMnc</a></span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-18" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#getPsc()">getPsc</a></span>()</nobr>
</td></tr>
<tr class=" api apilevel-18" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#hashCode()">hashCode</a></span>()</nobr>
<div class="jd-descrdiv">Returns an integer hash code for this object.</div>
</td></tr>
<tr class="alt-color api apilevel-18" >
<td class="jd-typecol"><nobr>
<a href="../../../reference/java/lang/String.html">String</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#toString()">toString</a></span>()</nobr>
<div class="jd-descrdiv">Returns a string containing a concise, human-readable description of this
object.</div>
</td></tr>
<tr class=" api apilevel-18" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/android/telephony/CellIdentityWcdma.html#writeToParcel(android.os.Parcel, int)">writeToParcel</a></span>(<a href="../../../reference/android/os/Parcel.html">Parcel</a> dest, int flags)</nobr>
<div class="jd-descrdiv">Implement the Parcelable interface </div>
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="inhmethods" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Methods</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed"
><img id="inherited-methods-java.lang.Object-trigger"
src="../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From class
<a href="../../../reference/java/lang/Object.html">java.lang.Object</a>
<div id="inherited-methods-java.lang.Object">
<div id="inherited-methods-java.lang.Object-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-java.lang.Object-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-1" >
<td class="jd-typecol"><nobr>
<a href="../../../reference/java/lang/Object.html">Object</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/java/lang/Object.html#clone()">clone</a></span>()</nobr>
<div class="jd-descrdiv">Creates and returns a copy of this <code>Object</code>.</div>
</td></tr>
<tr class=" api apilevel-1" >
<td class="jd-typecol"><nobr>
boolean</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/java/lang/Object.html#equals(java.lang.Object)">equals</a></span>(<a href="../../../reference/java/lang/Object.html">Object</a> o)</nobr>
<div class="jd-descrdiv">Compares this instance with the specified object and indicates if they
are equal.</div>
</td></tr>
<tr class="alt-color api apilevel-1" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/java/lang/Object.html#finalize()">finalize</a></span>()</nobr>
<div class="jd-descrdiv">Invoked when the garbage collector has detected that this instance is no longer reachable.</div>
</td></tr>
<tr class=" api apilevel-1" >
<td class="jd-typecol"><nobr>
final
<a href="../../../reference/java/lang/Class.html">Class</a><?></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/java/lang/Object.html#getClass()">getClass</a></span>()</nobr>
<div class="jd-descrdiv">Returns the unique instance of <code><a href="../../../reference/java/lang/Class.html">Class</a></code> that represents this
object's class.</div>
</td></tr>
<tr class="alt-color api apilevel-1" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/java/lang/Object.html#hashCode()">hashCode</a></span>()</nobr>
<div class="jd-descrdiv">Returns an integer hash code for this object.</div>
</td></tr>
<tr class=" api apilevel-1" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/java/lang/Object.html#notify()">notify</a></span>()</nobr>
<div class="jd-descrdiv">Causes a thread which is waiting on this object's monitor (by means of
calling one of the <code>wait()</code> methods) to be woken up.</div>
</td></tr>
<tr class="alt-color api apilevel-1" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/java/lang/Object.html#notifyAll()">notifyAll</a></span>()</nobr>
<div class="jd-descrdiv">Causes all threads which are waiting on this object's monitor (by means
of calling one of the <code>wait()</code> methods) to be woken up.</div>
</td></tr>
<tr class=" api apilevel-1" >
<td class="jd-typecol"><nobr>
<a href="../../../reference/java/lang/String.html">String</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/java/lang/Object.html#toString()">toString</a></span>()</nobr>
<div class="jd-descrdiv">Returns a string containing a concise, human-readable description of this
object.</div>
</td></tr>
<tr class="alt-color api apilevel-1" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/java/lang/Object.html#wait()">wait</a></span>()</nobr>
<div class="jd-descrdiv">Causes the calling thread to wait until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method of this object.</div>
</td></tr>
<tr class=" api apilevel-1" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/java/lang/Object.html#wait(long, int)">wait</a></span>(long millis, int nanos)</nobr>
<div class="jd-descrdiv">Causes the calling thread to wait until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method of this object or until the
specified timeout expires.</div>
</td></tr>
<tr class="alt-color api apilevel-1" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/java/lang/Object.html#wait(long)">wait</a></span>(long millis)</nobr>
<div class="jd-descrdiv">Causes the calling thread to wait until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method of this object or until the
specified timeout expires.</div>
</td></tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-android.os.Parcelable" class="jd-expando-trigger closed"
><img id="inherited-methods-android.os.Parcelable-trigger"
src="../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From interface
<a href="../../../reference/android/os/Parcelable.html">android.os.Parcelable</a>
<div id="inherited-methods-android.os.Parcelable">
<div id="inherited-methods-android.os.Parcelable-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-android.os.Parcelable-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-1" >
<td class="jd-typecol"><nobr>
abstract
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/android/os/Parcelable.html#describeContents()">describeContents</a></span>()</nobr>
<div class="jd-descrdiv">Describe the kinds of special objects contained in this Parcelable's
marshalled representation.</div>
</td></tr>
<tr class=" api apilevel-1" >
<td class="jd-typecol"><nobr>
abstract
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../reference/android/os/Parcelable.html#writeToParcel(android.os.Parcel, int)">writeToParcel</a></span>(<a href="../../../reference/android/os/Parcel.html">Parcel</a> dest, int flags)</nobr>
<div class="jd-descrdiv">Flatten this object in to a Parcel.</div>
</td></tr>
</table>
</div>
</div>
</td></tr>
</table>
</div><!-- jd-descr (summary) -->
<!-- Details -->
<!-- XML Attributes -->
<!-- Enum Values -->
<!-- Constants -->
<!-- Fields -->
<!-- ========= FIELD DETAIL ======== -->
<h2>Fields</h2>
<A NAME="CREATOR"></A>
<div class="jd-details api apilevel-18">
<h4 class="jd-details-title">
<span class="normal">
public
static
final
<a href="../../../reference/android/os/Parcelable.Creator.html">Creator</a><<a href="../../../reference/android/telephony/CellIdentityWcdma.html">CellIdentityWcdma</a>>
</span>
CREATOR
</h4>
<div class="api-level">
Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Implement the Parcelable interface </p></div>
</div>
</div>
<!-- Public ctors -->
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<!-- Protected ctors -->
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methdos -->
<h2>Public Methods</h2>
<A NAME="describeContents()"></A>
<div class="jd-details api apilevel-18">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">describeContents</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div>
Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Implement the Parcelable interface </p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>a bitmask indicating the set of special object types marshalled
by the Parcelable.
</li></ul>
</div>
</div>
</div>
<A NAME="equals(java.lang.Object)"></A>
<div class="jd-details api apilevel-18">
<h4 class="jd-details-title">
<span class="normal">
public
boolean
</span>
<span class="sympad">equals</span>
<span class="normal">(<a href="../../../reference/java/lang/Object.html">Object</a> other)</span>
</h4>
<div class="api-level">
<div>
Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Compares this instance with the specified object and indicates if they
are equal. In order to be equal, <code>o</code> must represent the same object
as this instance using a class-specific comparison. The general contract
is that this comparison should be reflexive, symmetric, and transitive.
Also, no object reference other than null is equal to null.
<p>The default implementation returns <code>true</code> only if <code>this ==
o</code>. See <a href="../../../reference/java/lang/Object.html#writing_equals">Writing a correct
<code>equals</code> method</a>
if you intend implementing your own <code>equals</code> method.
<p>The general contract for the <code>equals</code> and <code><a href="../../../reference/java/lang/Object.html#hashCode()">hashCode()</a></code> methods is that if <code>equals</code> returns <code>true</code> for
any two objects, then <code>hashCode()</code> must return the same value for
these objects. This means that subclasses of <code>Object</code> usually
override either both methods or neither of them.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>other</td>
<td>the object to compare this instance with.</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li><code>true</code> if the specified object is equal to this <code>Object</code>; <code>false</code> otherwise.</li></ul>
</div>
</div>
</div>
<A NAME="getCid()"></A>
<div class="jd-details api apilevel-18">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">getCid</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div>
Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>CID
28-bit UMTS Cell Identity described in TS 25.331, 0..268435455, Integer.MAX_VALUE if unknown
</li></ul>
</div>
</div>
</div>
<A NAME="getLac()"></A>
<div class="jd-details api apilevel-18">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">getLac</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div>
Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>16-bit Location Area Code, 0..65535, Integer.MAX_VALUE if unknown
</li></ul>
</div>
</div>
</div>
<A NAME="getMcc()"></A>
<div class="jd-details api apilevel-18">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">getMcc</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div>
Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>3-digit Mobile Country Code, 0..999, Integer.MAX_VALUE if unknown
</li></ul>
</div>
</div>
</div>
<A NAME="getMnc()"></A>
<div class="jd-details api apilevel-18">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">getMnc</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div>
Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>2 or 3-digit Mobile Network Code, 0..999, Integer.MAX_VALUE if unknown
</li></ul>
</div>
</div>
</div>
<A NAME="getPsc()"></A>
<div class="jd-details api apilevel-18">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">getPsc</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div>
Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>9-bit UMTS Primary Scrambling Code described in TS 25.331, 0..511, Integer.MAX_VALUE
if unknown
</li></ul>
</div>
</div>
</div>
<A NAME="hashCode()"></A>
<div class="jd-details api apilevel-18">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">hashCode</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div>
Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns an integer hash code for this object. By contract, any two
objects for which <code><a href="../../../reference/java/lang/Object.html#equals(java.lang.Object)">equals(Object)</a></code> returns <code>true</code> must return
the same hash code value. This means that subclasses of <code>Object</code>
usually override both methods or neither method.
<p>Note that hash values must not change over time unless information used in equals
comparisons also changes.
<p>See <a href="../../../reference/java/lang/Object.html#writing_hashCode">Writing a correct
<code>hashCode</code> method</a>
if you intend implementing your own <code>hashCode</code> method.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this object's hash code.</li></ul>
</div>
</div>
</div>
<A NAME="toString()"></A>
<div class="jd-details api apilevel-18">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../reference/java/lang/String.html">String</a>
</span>
<span class="sympad">toString</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div>
Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns a string containing a concise, human-readable description of this
object. Subclasses are encouraged to override this method and provide an
implementation that takes into account the object's type and data. The
default implementation is equivalent to the following expression:
<pre>
getClass().getName() + '@' + Integer.toHexString(hashCode())</pre>
<p>See <a href="../../../reference/java/lang/Object.html#writing_toString">Writing a useful
<code>toString</code> method</a>
if you intend implementing your own <code>toString</code> method.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>a printable representation of this object.
</li></ul>
</div>
</div>
</div>
<A NAME="writeToParcel(android.os.Parcel, int)"></A>
<div class="jd-details api apilevel-18">
<h4 class="jd-details-title">
<span class="normal">
public
void
</span>
<span class="sympad">writeToParcel</span>
<span class="normal">(<a href="../../../reference/android/os/Parcel.html">Parcel</a> dest, int flags)</span>
</h4>
<div class="api-level">
<div>
Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 18</a></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Implement the Parcelable interface </p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>dest</td>
<td>The Parcel in which the object should be written.</td>
</tr>
<tr>
<th>flags</td>
<td>Additional flags about how the object should be written.
May be 0 or <code><a href="../../../reference/android/os/Parcelable.html#PARCELABLE_WRITE_RETURN_VALUE">PARCELABLE_WRITE_RETURN_VALUE</a></code>.
</td>
</tr>
</table>
</div>
</div>
</div>
<!-- ========= METHOD DETAIL ======== -->
<!-- ========= END OF CLASS DATA ========= -->
<A NAME="navbar_top"></A>
<div id="footer" class="wrap" >
<div id="copyright">
Except as noted, this content is licensed under <a
href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>.
For details and restrictions, see the <a href="../../../license.html">
Content License</a>.
</div>
<div id="build_info">
Android 4.4 r1 —
<script src="../../../timestamp.js" type="text/javascript"></script>
<script>document.write(BUILD_TIMESTAMP)</script>
</div>
<div id="footerlinks">
<p>
<a href="../../../about/index.html">About Android</a> |
<a href="../../../legal.html">Legal</a> |
<a href="../../../support.html">Support</a>
</p>
</div>
</div> <!-- end footer -->
</div> <!-- jd-content -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
</body>
</html>
| AzureZhao/android-developer-cn | reference/android/telephony/CellIdentityWcdma.html | HTML | mit | 77,001 |
/* Copyright (c) 2018 lib4j
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* You should have received a copy of The MIT License (MIT) along with this
* program. If not, see <http://opensource.org/licenses/MIT/>.
*/
package org.lib4j.test;
import java.util.HashMap;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.junit.Assert;
import org.junit.ComparisonFailure;
import org.lib4j.xml.dom.DOMStyle;
import org.lib4j.xml.dom.DOMs;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlunit.builder.Input;
import org.xmlunit.diff.Comparison;
import org.xmlunit.diff.ComparisonListener;
import org.xmlunit.diff.ComparisonResult;
import org.xmlunit.diff.DOMDifferenceEngine;
import org.xmlunit.diff.DifferenceEngine;
public class AssertXml {
private XPath newXPath() {
final XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setNamespaceContext(new SimpleNamespaceContext(prefixToNamespaceURI));
return xPath;
}
public static AssertXml compare(final Element controlElement, final Element testElement) {
final Map<String,String> prefixToNamespaceURI = new HashMap<>();
prefixToNamespaceURI.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");
final NamedNodeMap attributes = controlElement.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
final Attr attribute = (Attr)attributes.item(i);
if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attribute.getNamespaceURI()) && "xmlns".equals(attribute.getPrefix()))
prefixToNamespaceURI.put(attribute.getLocalName(), attribute.getNodeValue());
}
return new AssertXml(prefixToNamespaceURI, controlElement, testElement);
}
private final Map<String,String> prefixToNamespaceURI;
private final Element controlElement;
private final Element testElement;
private AssertXml(final Map<String,String> prefixToNamespaceURI, final Element controlElement, final Element testElement) {
if (!controlElement.getPrefix().equals(testElement.getPrefix()))
throw new IllegalArgumentException("Prefixes of control and test elements must be the same: " + controlElement.getPrefix() + " != " + testElement.getPrefix());
this.prefixToNamespaceURI = prefixToNamespaceURI;
this.controlElement = controlElement;
this.testElement = testElement;
}
public void addAttribute(final Element element, final String xpath, final String name, final String value) throws XPathExpressionException {
final XPathExpression expression = newXPath().compile(xpath);
final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
final Node node = nodes.item(i);
if (!(node instanceof Element))
throw new UnsupportedOperationException("Only support addition of attributes to elements");
final Element target = (Element)node;
final int colon = name.indexOf(':');
final String namespaceURI = colon == -1 ? node.getNamespaceURI() : node.getOwnerDocument().lookupNamespaceURI(name.substring(0, colon));
target.setAttributeNS(namespaceURI, name, value);
}
}
public void remove(final Element element, final String ... xpaths) throws XPathExpressionException {
for (final String xpath : xpaths) {
final XPathExpression expression = newXPath().compile(xpath);
final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
final Node node = nodes.item(i);
if (node instanceof Attr) {
final Attr attribute = (Attr)node;
attribute.getOwnerElement().removeAttributeNode(attribute);
}
else {
node.getParentNode().removeChild(node);
}
}
}
}
public void replace(final Element element, final String xpath, final String name, final String value) throws XPathExpressionException {
final XPathExpression expression = newXPath().compile(xpath);
final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
final Node node = nodes.item(i);
if (node instanceof Attr) {
final Attr attribute = (Attr)node;
if (name == null) {
attribute.setValue(value);
}
else {
final int colon = name.indexOf(':');
final String namespaceURI = colon == -1 ? attribute.getNamespaceURI() : attribute.getOwnerDocument().lookupNamespaceURI(name.substring(0, colon));
final Element owner = attribute.getOwnerElement();
owner.removeAttributeNode(attribute);
owner.setAttributeNS(namespaceURI, name, value);
}
}
else {
throw new UnsupportedOperationException("Only support replacement of attribute values");
}
}
}
public void replace(final Element element, final String xpath, final String value) throws XPathExpressionException {
replace(element, xpath, null, value);
}
public void assertEqual() {
final String prefix = controlElement.getPrefix();
final String controlXml = DOMs.domToString(controlElement, DOMStyle.INDENT, DOMStyle.INDENT_ATTRS);
final String testXml = DOMs.domToString(testElement, DOMStyle.INDENT, DOMStyle.INDENT_ATTRS);
final Source controlSource = Input.fromString(controlXml).build();
final Source testSource = Input.fromString(testXml).build();
final DifferenceEngine diffEngine = new DOMDifferenceEngine();
diffEngine.addDifferenceListener(new ComparisonListener() {
@Override
public void comparisonPerformed(final Comparison comparison, final ComparisonResult result) {
final String controlXPath = comparison.getControlDetails().getXPath() == null ? null : comparison.getControlDetails().getXPath().replaceAll("/([^@])", "/" + prefix + ":$1");
if (controlXPath == null || controlXPath.matches("^.*\\/@[:a-z]+$") || controlXPath.contains("text()"))
return;
try {
Assert.assertEquals(controlXml, testXml);
}
catch (final ComparisonFailure e) {
final StackTraceElement[] stackTrace = e.getStackTrace();
int i;
for (i = 3; i < stackTrace.length; i++)
if (!stackTrace[i].getClassName().startsWith("org.xmlunit.diff"))
break;
final StackTraceElement[] filtered = new StackTraceElement[stackTrace.length - ++i];
System.arraycopy(stackTrace, i, filtered, 0, stackTrace.length - i);
e.setStackTrace(filtered);
throw e;
}
Assert.fail(comparison.toString());
}
});
diffEngine.compare(controlSource, testSource);
}
} | safris-src/org | lib4j/test/src/main/java/org/lib4j/test/AssertXml.java | Java | mit | 7,601 |
<!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_66-internal) on Tue Dec 08 09:28:01 GMT 2015 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.apache.jena.sparql.expr.E_Lang (Apache Jena ARQ)</title>
<meta name="date" content="2015-12-08">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.jena.sparql.expr.E_Lang (Apache Jena ARQ)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/jena/sparql/expr/E_Lang.html" title="class in org.apache.jena.sparql.expr">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/jena/sparql/expr/class-use/E_Lang.html" target="_top">Frames</a></li>
<li><a href="E_Lang.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.jena.sparql.expr.E_Lang" class="title">Uses of Class<br>org.apache.jena.sparql.expr.E_Lang</h2>
</div>
<div class="classUseContainer">No usage of org.apache.jena.sparql.expr.E_Lang</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/jena/sparql/expr/E_Lang.html" title="class in org.apache.jena.sparql.expr">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/jena/sparql/expr/class-use/E_Lang.html" target="_top">Frames</a></li>
<li><a href="E_Lang.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Licenced under the Apache License, Version 2.0</small></p>
</body>
</html>
| manonsys/MVC | libs/Jena/javadoc-arq/org/apache/jena/sparql/expr/class-use/E_Lang.html | HTML | mit | 4,582 |
#include "src/OgreExternalTextureSourceManager.cpp"
#include "src/OgreFileSystem.cpp"
#include "src/OgreFont.cpp"
#include "src/OgreFontManager.cpp"
#include "src/OgreFrustum.cpp"
#include "src/OgreGpuProgram.cpp"
#include "src/OgreGpuProgramManager.cpp"
#include "src/OgreGpuProgramParams.cpp"
#include "src/OgreGpuProgramUsage.cpp"
#include "src/OgreHardwareBufferManager.cpp"
#include "src/OgreHardwareIndexBuffer.cpp"
#include "src/OgreHardwareOcclusionQuery.cpp"
#include "src/OgreHardwarePixelBuffer.cpp"
#include "src/OgreHardwareVertexBuffer.cpp"
#include "src/OgreHighLevelGpuProgram.cpp"
#include "src/OgreHighLevelGpuProgramManager.cpp"
#include "src/OgreImage.cpp"
#include "src/OgreInstanceBatch.cpp"
#include "src/OgreInstanceBatchHW.cpp"
#include "src/OgreInstanceBatchHW_VTF.cpp"
#include "src/OgreInstanceBatchShader.cpp"
#include "src/OgreInstanceBatchVTF.cpp"
#include "src/OgreInstancedGeometry.cpp"
#include "src/OgreInstancedEntity.cpp"
#include "src/OgreInstanceManager.cpp"
#include "src/OgreKeyFrame.cpp"
#include "src/OgreLight.cpp"
#include "src/OgreLodStrategy.cpp"
#include "src/OgreLodStrategyManager.cpp"
#include "src/OgreLog.cpp"
#include "src/OgreLogManager.cpp"
#include "src/OgreManualObject.cpp"
#include "src/OgreMaterial.cpp"
#include "src/OgreMaterialManager.cpp"
#include "src/OgreMaterialSerializer.cpp"
#include "src/OgreMath.cpp"
#include "src/OgreMatrix3.cpp"
#include "src/OgreMatrix4.cpp"
#include "src/OgreMemoryAllocatedObject.cpp"
#include "src/OgreMemoryNedAlloc.cpp"
| airgames/vuforia-gamekit-integration | Gamekit/compilation/OgreMain/compile_OgreMain_1.cpp | C++ | mit | 1,519 |
<?php
/*
* This file is part of the symfony package.
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfWebDebugPanelPropel adds a panel to the web debug toolbar with Propel information.
*
* @package symfony
* @subpackage debug
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfWebDebugPanelPropel.class.php 27284 2010-01-28 18:34:57Z Kris.Wallsmith $
*/
class sfWebDebugPanelPropel extends sfWebDebugPanel
{
/**
* Get the title/icon for the panel
*
* @return string $html
*/
public function getTitle()
{
if ($sqlLogs = $this->getSqlLogs())
{
return '<img src="'.$this->webDebug->getOption('image_root_path').'/database.png" alt="SQL queries" /> '.count($sqlLogs);
}
}
/**
* Get the verbal title of the panel
*
* @return string $title
*/
public function getPanelTitle()
{
return 'SQL queries';
}
/**
* Get the html content of the panel
*
* @return string $html
*/
public function getPanelContent()
{
return '
<div id="sfWebDebugDatabaseLogs">
<h3>Propel Version: '.Propel::VERSION.'</h3>
<ol>'.implode("\n", $this->getSqlLogs()).'</ol>
</div>
';
}
/**
* Listens to debug.web.load_panels and adds this panel.
*/
static public function listenToAddPanelEvent(sfEvent $event)
{
$event->getSubject()->setPanel('db', new self($event->getSubject()));
}
/**
* Builds the sql logs and returns them as an array.
*
* @return array
*/
protected function getSqlLogs()
{
$config = $this->getPropelConfiguration();
$outerGlue = $config->getParameter('debugpdo.logging.outerglue', ' | ');
$innerGlue = $config->getParameter('debugpdo.logging.innerglue', ': ');
$flagSlow = $config->getParameter('debugpdo.logging.details.slow.enabled', false);
$threshold = $config->getParameter('debugpdo.logging.details.slow.threshold', DebugPDO::DEFAULT_SLOW_THRESHOLD);
$html = array();
foreach ($this->webDebug->getLogger()->getLogs() as $log)
{
if ('sfPropelLogger' != $log['type'])
{
continue;
}
$details = array();
$slowQuery = false;
$parts = explode($outerGlue, $log['message']);
foreach ($parts as $i => $part)
{
// is this a key-glue-value fragment ?
if (preg_match('/^(\w+)'.preg_quote($innerGlue, '/').'(.*)/', $part, $match))
{
$details[] = $part;
unset($parts[$i]);
// check for slow query
if ('time' == $match[1])
{
if ($flagSlow && (float) $match[2] > $threshold)
{
$slowQuery = true;
if ($this->getStatus() > sfLogger::NOTICE)
{
$this->setStatus(sfLogger::NOTICE);
}
}
}
}
}
// all stuff that has not been eaten by the loop should be the query string
$query = join($outerGlue, $parts);
$query = $this->formatSql(htmlspecialchars($query, ENT_QUOTES, sfConfig::get('sf_charset')));
$backtrace = isset($log['debug_backtrace']) && count($log['debug_backtrace']) ? ' '.$this->getToggleableDebugStack($log['debug_backtrace']) : '';
$html[] = sprintf('
<li%s>
<p class="sfWebDebugDatabaseQuery">%s</p>
<div class="sfWebDebugDatabaseLogInfo">%s%s</div>
</li>',
$slowQuery ? ' class="sfWebDebugWarning"' : '',
$query,
implode(', ', $details),
$backtrace
);
}
return $html;
}
/**
* Returns the current PropelConfiguration.
*
* @return PropelConfiguration
*/
protected function getPropelConfiguration()
{
return Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT);
}
}
| hybmg57/jobeet | lib/plugins/sfPropelPlugin/lib/debug/sfWebDebugPanelPropel.class.php | PHP | mit | 4,119 |
# frozen_string_literal: true
require_relative 'helper'
describe 'Digest class' do
it 'raises error with invalid digest_class' do
assert_raises ArgumentError do
Dalli::Client.new('foo', { expires_in: 10, digest_class: Object })
end
end
end
| mperham/dalli | test/test_digest_class.rb | Ruby | mit | 260 |
using UnityEngine;
using System.Collections;
using System.Runtime.Serialization;
namespace StrumpyShaderEditor
{
[DataContract(Namespace = "http://strumpy.net/ShaderEditor/")]
public abstract class ChannelReference {
[DataMember] private string nodeIdentifier;
[DataMember] private uint channelId;
public ChannelReference( string nodeIdentifier, uint channelId )
{
this.nodeIdentifier = nodeIdentifier;
this.channelId = channelId;
}
public string NodeIdentifier
{
get{ return nodeIdentifier; }
set{ nodeIdentifier = value; }
}
public uint ChannelId
{
get{ return channelId; }
}
}
} | ahito89/SSE | ShaderEditor/Assets/StrumpyShaderEditor/Editor/Graph/Nodes/Channels/ChannelReference.cs | C# | mit | 631 |
var partialsTemp = [
"login",
"profile"
];
exports.partialRender = function (req, res) {
var pageIndex = req.params[0];
if (partialsTemp.indexOf("" + pageIndex) > -1) {
res.render("partials/" + pageIndex, {});
} else {
res.render("common/404", {});
}
}; | ManGroup/jsEasy | controllers/partials.js | JavaScript | mit | 296 |
/*
* The MIT License
*
* Copyright 2015 Eduardo Weiland.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
define(['knockout', 'grammar', 'productionrule', 'utils'], function(ko, Grammar, ProductionRule, utils) {
'use strict';
/**
* Encontra todos os símbolos não-terminais inalcançáveis dentro de uma gramática.
*
* @param {Grammar} grammar Gramática para ser verificada.
* @return {string[]} Lista de símbolos inalcançáveis.
*/
function findUnreachableSymbols(grammar) {
var unreachable = [],
nt = grammar.nonTerminalSymbols(),
s = grammar.productionStartSymbol();
for (var i = 0, l = nt.length; i < l; ++i) {
// Ignora símbolo de início de produção
if (nt[i] === s) {
continue;
}
var found = false;
for (var j = 0, k = nt.length; j < k && !found; ++j) {
if (i === j) {
// Ignora produções do próprio símbolo
continue;
}
var prods = grammar.getProductions(nt[j]);
for (var x = 0, y = prods.length; x < y; ++x) {
if (prods[x].indexOf(nt[i]) !== -1) {
found = true;
break;
}
}
}
if (!found) {
unreachable.push(nt[i]);
}
}
return unreachable;
}
function findSterileSymbols(grammar) {
var steriles = [],
rules = grammar.productionRules();
for (var i = 0, l = rules.length; i < l; ++i) {
var found = false,
left = rules[i].leftSide(),
right = rules[i].rightSide();
for (var j = 0, k = right.length; j < k && !found; ++j) {
if (right[j].indexOf(left) === -1) {
found = true;
break;
}
}
if (!found) {
steriles.push(left);
}
}
return steriles;
}
/**
* Substitui símbolos não terminais no começo de todas as produções pelas suas produções.
*
* @param {Grammar} grammar Gramática para ser modificada.
* @return {ProductionRule[]} Regras de produção modificadas.
*/
function replaceStartingSymbols(grammar) {
var rules = grammar.productionRules();
var nt = grammar.nonTerminalSymbols();
var s = grammar.productionStartSymbol();
for (var i = 0, l = rules.length; i < l; ++i) {
var left = rules[i].leftSide();
if (left === s) {
// Ignora produção inicial
continue;
}
var prods = rules[i].rightSide();
// Não usa cache do length porque o array é modificado internamente
for (var j = 0; j < prods.length; ++j) {
if ( (prods[j][0] === left) || (nt.indexOf(prods[j][0]) === -1) ) {
// Produção começa com o próprio símbolo não-terminal (recursivo) ou
// não começa com nenhum símbolo não-terminal, ignora as substituições
continue;
}
var otherProds = grammar.getProductions(prods[j][0]);
var rest = prods[j].substr(1);
for (var k = 0, m = otherProds.length; k < m; ++k) {
otherProds[k] = otherProds[k] + rest;
}
// Remove a produção que começa com não-terminal e adiciona as novas produções no lugar
prods.splice.apply(prods, [j--, 1].concat(otherProds));
}
}
return rules;
}
return {
/**
* Remove símbolos inúteis de uma gramática.
*
* @param {Grammar} grammar Gramática de entrada.
* @return {Grammar} Uma nova gramática sem os simbolos inúteis.
*/
removeUselessSymbols: function(grammar) {
var newGrammar = new Grammar(ko.toJS(grammar));
var sterile = findSterileSymbols(newGrammar),
unreachable = findUnreachableSymbols(newGrammar),
useless = utils.arrayUnion(sterile, unreachable),
nt = newGrammar.nonTerminalSymbols();
// Remove os símbolos inalcançáveis...
newGrammar.nonTerminalSymbols(utils.arrayRemove(nt, utils.arrayUnion(sterile, unreachable)));
newGrammar.removeSymbolRules(useless);
// .. e as produções em que eles aparecem
var rules = newGrammar.productionRules();
for (var i = 0, l = rules.length; i < l; ++i) {
var right = rules[i].rightSide();
for (var j = 0, m = useless.length; j < m; ++j) {
for (var k = 0; k < right.length; ++k) {
if (right[k].indexOf(useless[j]) !== -1) {
right.splice(k--, 1);
}
}
}
rules[i].rightSide(utils.arrayUnique(right));
}
newGrammar.productionRules(rules);
return newGrammar;
},
/**
* Remove produções vazias de uma gramática.
*
* @param {Grammar} grammar Gramática de entrada.
* @return {Grammar} Uma nova gramática sem as produções vazias.
*/
removeEmptyProductions: function(grammar) {
var newGrammar = new Grammar(ko.toJS(grammar));
var newStart;
var rules = newGrammar.productionRules();
for (var i = 0, l = rules.length; i < l; ++i) {
var left = rules[i].leftSide();
var right = rules[i].rightSide();
var emptyIndex = right.indexOf(ProductionRule.EPSILON);
if (emptyIndex === -1) {
// Essa regra não possui produção vazia, ignora e testa a próxima
continue;
}
if (left === newGrammar.productionStartSymbol()) {
// Início de produção pode gerar sentença vazia, então trata o caso especial
newStart = new ProductionRule(newGrammar, {
leftSide: left + "'",
rightSide: [left, ProductionRule.EPSILON]
});
}
// Encontra todas as outras regras que produzem esse símbolo e adiciona uma nova
// produção sem esse símbolo
for (var j = 0; j < l; ++j) {
var rightOther = rules[j].rightSide();
for (var k = 0, m = rightOther.length; k < m; ++k) {
if (rightOther[k].indexOf(left) !== -1) {
rightOther.push(rightOther[k].replace(new RegExp(left, 'g'), ''));
}
}
rules[j].rightSide(utils.arrayUnique(rightOther));
}
right.splice(emptyIndex, 1);
rules[i].rightSide(utils.arrayUnique(right));
}
if (newStart) {
rules.unshift(newStart);
newGrammar.productionStartSymbol(newStart.leftSide());
newGrammar.nonTerminalSymbols([newStart.leftSide()].concat(newGrammar.nonTerminalSymbols()));
}
newGrammar.productionRules(rules);
return newGrammar;
},
/**
* Fatora uma gramática.
*
* @param {Grammar} grammar Gramática de entrada.
* @return {Grammar} Uma nova gramática fatorada.
*/
factor: function(grammar) {
var newGrammar = new Grammar(ko.toJS(grammar));
var rules = replaceStartingSymbols(newGrammar);
var newRules = [];
for (var i = 0; i < rules.length; ++i) {
var left = rules[i].leftSide();
var right = rules[i].rightSide();
var newRight = [];
var firstSymbolGrouped = {};
// Percorre todos as produções verificando quais precisam ser fatoradas
for (var j = 0, l = right.length; j < l; ++j) {
if (right[j].length === 1) {
// Produções com apenas um símbolo são deixadas como estão
newRight.push(right[j]);
}
else {
// Agrupa todas as produções que começam com o mesmo símbolo terminal
var firstSymbol = right[j][0];
if (!firstSymbolGrouped[firstSymbol]) {
firstSymbolGrouped[firstSymbol] = [];
}
firstSymbolGrouped[firstSymbol].push(right[j].substr(1));
}
}
// Adiciona a produção na mesma ordem que estava antes, antes das novas produções serem adicionadas
newRules.push(rules[i]);
for (var j in firstSymbolGrouped) {
if (firstSymbolGrouped[j].length > 1) {
// Mais de uma produção começando com o mesmo símbolo terminal
var newSymbol = newGrammar.createNonTerminalSymbol(left);
newRight.push(j + newSymbol);
newRules.push(new ProductionRule(newGrammar, {
leftSide: newSymbol,
rightSide: firstSymbolGrouped[j]
}));
}
else {
// Senão, é apenas uma produção (índice 0), mantém ela no mesmo lugar
newRight.push(j + firstSymbolGrouped[j][0]);
}
}
// Atualiza as produções para o símbolo existente
rules[i].rightSide(utils.arrayUnique(newRight));
}
newGrammar.productionRules(newRules);
return newGrammar;
},
/**
* Remove recursão à esquerda de uma gramática.
*
* @param {Grammar} grammar Gramática de entrada.
* @return {Grammar} Uma nova gramática sem recursão à esquerda.
*/
removeLeftRecursion: function(grammar) {
var newGrammar = new Grammar(ko.toJS(grammar));
var rules = newGrammar.productionRules();
var newRules = [];
for (var i = 0, l = rules.length; i < l; ++i) {
var left = rules[i].leftSide();
var prods = rules[i].rightSide();
var recursives = [];
// Adiciona a produção na mesma ordem que estava antes, antes das nova produção ser adicionada
newRules.push(rules[i]);
// Não usa cache do length porque o array é modificado internamente
for (var j = 0; j < prods.length; ++j) {
if (prods[j][0] === left && prods[j].length > 1) {
// Encontrou produção recursiva, cria uma nova regra
var newSymbol = newGrammar.createNonTerminalSymbol(left);
recursives.push(newSymbol);
newRules.push(new ProductionRule(newGrammar, {
leftSide: newSymbol,
rightSide: [prods[j].substr(1) + newSymbol, ProductionRule.EPSILON]
}));
// Remove essa produção
prods.splice(j--, 1);
}
}
var newProds = [];
if (recursives.length === 0) {
newProds = prods.slice();
}
else {
for (var j = 0; j < prods.length; ++j) {
for (var k = 0; k < recursives.length; ++k) {
newProds.push(prods[j] + recursives[k]);
}
}
}
rules[i].rightSide(newProds);
}
newGrammar.productionRules(newRules);
return newGrammar;
}
};
});
| eduardoweiland/transformacoes-glc | app/js/transformations.js | JavaScript | mit | 13,493 |
/**
* Uploader implementation - with the Connection object in ExtJS 4
*
*/
Ext.define('MyApp.ux.panel.upload.uploader.ExtJsUploader', {
extend : 'MyApp.ux.panel.upload.uploader.AbstractXhrUploader',
requires : [ 'MyApp.ux.panel.upload.data.Connection' ],
config : {
/**
* @cfg {String} [method='PUT']
*
* The HTTP method to be used.
*/
method : 'PUT',
/**
* @cfg {Ext.data.Connection}
*
* If set, this connection object will be used when uploading files.
*/
connection : null
},
/**
* @property
* @private
*
* The connection object.
*/
conn : null,
/**
* @private
*
* Initializes and returns the connection object.
*
* @return {MyApp.ux.panel.upload.data.Connection}
*/
initConnection : function() {
var conn, url = this.url;
console.log('[ExtJsUploader initConnection params', this.params);
if (this.connection instanceof Ext.data.Connection) {
console.log('[ExtJsUploader] instanceof Connection');
conn = this.connection;
} else {
console.log('[ExtJsUploader] !! instanceof Connection');
if (this.params) {
url = Ext.urlAppend(url, Ext.urlEncode(this.params));
}
conn = Ext.create('MyApp.ux.panel.upload.data.Connection', {
disableCaching : true,
method : this.method,
url : url,
timeout : this.timeout,
defaultHeaders : {
'Content-Type' : this.contentType,
'X-Requested-With' : 'XMLHttpRequest'
}
});
}
return conn;
},
/**
* @protected
*/
initHeaders : function(item) {
console.log('[ExtJsUploader] initHeaders', item);
var headers = this.callParent(arguments);
headers['Content-Type'] = item.getType();
return headers;
},
/**
* Implements {@link MyApp.ux.panel.upload.uploader.AbstractUploader#uploadItem}
*
* @param {MyApp.ux.panel.upload.Item}
* item
*/
uploadItem : function(item) {
console.log('ExtJsUploader uploadItem', item);
var file = item.getFileApiObject();
if (!file) {
return;
}
item.setUploading();
// tony
this.params = {
folder : item.getRemoteFolder()
};
this.conn = this.initConnection();
/*
* Passing the File object directly as the "rawData" option. Specs: https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#the-send()-method
* http://dev.w3.org/2006/webapi/FileAPI/#blob
*/
console.log('ExtJsUploader conn', this.conn);
this.conn.request({
scope : this,
headers : this.initHeaders(item),
rawData : file,
timeout : MyApp.Const.JAVASCRIPT_MAX_NUMBER, // tony
success : Ext.Function.bind(this.onUploadSuccess, this, [ item ], true),
failure : Ext.Function.bind(this.onUploadFailure, this, [ item ], true),
progress : Ext.Function.bind(this.onUploadProgress, this, [ item ], true)
});
},
/**
* Implements {@link MyApp.ux.panel.upload.uploader.AbstractUploader#abortUpload}
*/
abortUpload : function() {
if (this.conn) {
/*
* If we don't suspend the events, the connection abortion will cause a failure event.
*/
this.suspendEvents();
console.log('abort conn', conn);
this.conn.abort();
this.resumeEvents();
}
}
});
| cwtuan/ExtJSTutorial-HiCloud | src/main/webapp/app/ux/panel/upload/uploader/ExtJsUploader.js | JavaScript | mit | 3,140 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using NSubstitute;
using Nancy;
using Nancy.Routing;
using PactNet.Logging;
using PactNet.Mocks.MockHttpService;
using PactNet.Mocks.MockHttpService.Nancy;
using Xunit;
namespace PactNet.Tests.Mocks.MockHttpService.Nancy
{
public class MockProviderNancyRequestDispatcherTests
{
private IMockProviderRequestHandler _mockRequestHandler;
private IMockProviderAdminRequestHandler _mockAdminRequestHandler;
private ILog _log;
private IRequestDispatcher GetSubject()
{
_mockRequestHandler = Substitute.For<IMockProviderRequestHandler>();
_mockAdminRequestHandler = Substitute.For<IMockProviderAdminRequestHandler>();
_log = Substitute.For<ILog>();
return new MockProviderNancyRequestDispatcher(_mockRequestHandler, _mockAdminRequestHandler, _log, new PactConfig());
}
[Fact]
public void Dispatch_WithNancyContext_CallsRequestHandlerWithContext()
{
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var requestDispatcher = GetSubject();
_mockRequestHandler.Handle(nancyContext).Returns(new Response());
requestDispatcher.Dispatch(nancyContext, CancellationToken.None);
_mockRequestHandler.Received(1).Handle(nancyContext);
}
[Fact]
public void Dispatch_WithNancyContextThatContainsAdminHeader_CallsAdminRequestHandlerWithContext()
{
var headers = new Dictionary<string, IEnumerable<string>>
{
{ Constants.AdministrativeRequestHeaderKey, new List<string> { "true" } }
};
var nancyContext = new NancyContext
{
Request = new Request("GET", new Url
{
Path = "/Test",
Scheme = "HTTP"
}, null, headers)
};
var requestDispatcher = GetSubject();
_mockAdminRequestHandler.Handle(nancyContext).Returns(new Response());
requestDispatcher.Dispatch(nancyContext, CancellationToken.None);
_mockAdminRequestHandler.Received(1).Handle(nancyContext);
}
[Fact]
public void Dispatch_WithNullNancyContext_ArgumentExceptionIsSetOnTask()
{
var requestDispatcher = GetSubject();
var response = requestDispatcher.Dispatch(null, CancellationToken.None);
Assert.Equal(typeof(ArgumentException), response.Exception.InnerExceptions.First().GetType());
}
[Fact]
public void Dispatch_WithNancyContext_SetsContextResponse()
{
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var nancyResponse = new Response
{
StatusCode = HttpStatusCode.OK
};
var requestDispatcher = GetSubject();
_mockRequestHandler.Handle(nancyContext).Returns(nancyResponse);
requestDispatcher.Dispatch(nancyContext, CancellationToken.None);
Assert.Equal(nancyResponse, nancyContext.Response);
}
[Fact]
public void Dispatch_WithNancyContext_ReturnsResponse()
{
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var nancyResponse = new Response
{
StatusCode = HttpStatusCode.OK
};
var requestDispatcher = GetSubject();
_mockRequestHandler.Handle(nancyContext).Returns(nancyResponse);
var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None);
Assert.Equal(nancyResponse, response.Result);
}
[Fact]
public void Dispatch_WithNancyContext_NoExceptionIsSetOnTask()
{
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var nancyResponse = new Response
{
StatusCode = HttpStatusCode.OK
};
var requestDispatcher = GetSubject();
_mockRequestHandler.Handle(nancyContext).Returns(nancyResponse);
var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None);
Assert.Null(response.Exception);
}
[Fact]
public void Dispatch_WithCanceledCancellationToken_OperationCanceledExceptionIsSetOnTask()
{
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var nancyResponse = new Response
{
StatusCode = HttpStatusCode.OK
};
var cancellationToken = new CancellationToken(true);
var requestDispatcher = GetSubject();
_mockRequestHandler.Handle(nancyContext).Returns(nancyResponse);
var response = requestDispatcher.Dispatch(nancyContext, cancellationToken);
Assert.Equal(typeof(OperationCanceledException), response.Exception.InnerExceptions.First().GetType());
}
[Fact]
public void Dispatch_WhenRequestHandlerThrows_InternalServerErrorResponseIsReturned()
{
var exception = new InvalidOperationException("Something failed.");
const string expectedMessage = "Something failed. See logs for details.";
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var requestDispatcher = GetSubject();
_mockRequestHandler
.When(x => x.Handle(Arg.Any<NancyContext>()))
.Do(x => { throw exception; });
var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None).Result;
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.Equal(expectedMessage, response.ReasonPhrase);
Assert.Equal(expectedMessage, ReadResponseContent(response));
}
[Fact]
public void Dispatch_WhenRequestHandlerThrowsWithMessageThatContainsSlashes_ResponseContentAndReasonPhrasesIsReturnedWithoutSlashes()
{
var exception = new InvalidOperationException("Something\r\n \t \\ failed.");
const string expectedMessage = @"Something\r\n \t \\ failed. See logs for details.";
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var requestDispatcher = GetSubject();
_mockRequestHandler
.When(x => x.Handle(Arg.Any<NancyContext>()))
.Do(x => { throw exception; });
var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None).Result;
Assert.Equal(expectedMessage, response.ReasonPhrase);
Assert.Equal(expectedMessage, ReadResponseContent(response));
}
[Fact]
public void Dispatch_WhenRequestHandlerThrows_TheExceptionIsLogged()
{
var exception = new InvalidOperationException("Something failed.");
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var requestDispatcher = GetSubject();
_mockRequestHandler
.When(x => x.Handle(Arg.Any<NancyContext>()))
.Do(x => { throw exception; });
var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None).Result;
_log.Received(1).ErrorException(Arg.Any<string>(), exception);
}
[Fact]
public void Dispatch_WhenRequestHandlerThrowsAPactFailureException_TheExceptionIsNotLogged()
{
var exception = new PactFailureException("Something failed");
var nancyContext = new NancyContext
{
Request = new Request("GET", "/Test", "HTTP")
};
var requestDispatcher = GetSubject();
_mockRequestHandler
.When(x => x.Handle(Arg.Any<NancyContext>()))
.Do(x => { throw exception; });
var response = requestDispatcher.Dispatch(nancyContext, CancellationToken.None).Result;
_log.DidNotReceive().ErrorException(Arg.Any<string>(), Arg.Any<Exception>());
}
private string ReadResponseContent(Response response)
{
string content;
using (var stream = new MemoryStream())
{
response.Contents(stream);
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
content = reader.ReadToEnd();
}
}
return content;
}
}
}
| humblelistener/pact-net | PactNet.Tests/Mocks/MockHttpService/Nancy/MockProviderNancyRequestDispatcherTests.cs | C# | mit | 9,535 |
class Revista<ReferenciaBase
attr_reader :m_nombre_revista, :m_volumen, :m_paginas
def initialize(a_autores,a_titulo,a_anio,a_nombre_revista, a_volumen, a_paginas)
super(a_autores,a_titulo,a_anio)
@m_nombre_revista,@m_volumen, @m_paginas = a_nombre_revista, a_volumen, a_paginas
end
end | alu0100773408/prct10 | lib/referencia/revista.rb | Ruby | mit | 316 |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M9 10v4c0 .55.45 1 1 1s1-.45 1-1V4h2v10c0 .55.45 1 1 1s1-.45 1-1V4h1c.55 0 1-.45 1-1s-.45-1-1-1H9.17C7.08 2 5.22 3.53 5.02 5.61 4.79 7.99 6.66 10 9 10zm11.65 7.65-2.79-2.79c-.32-.32-.86-.1-.86.35V17H6c-.55 0-1 .45-1 1s.45 1 1 1h11v1.79c0 .45.54.67.85.35l2.79-2.79c.2-.19.2-.51.01-.7z"
}), 'FormatTextdirectionLToRRounded');
exports.default = _default; | oliviertassinari/material-ui | packages/mui-icons-material/lib/FormatTextdirectionLToRRounded.js | JavaScript | mit | 769 |
var jazz = require("../lib/jazz");
var fs = require("fs");
var data = fs.readFileSync(__dirname + "/foreach_object.jazz", "utf8");
var template = jazz.compile(data);
template.eval({"doc": {
"title": "First",
"content": "Some content"
}}, function(data) { console.log(data); });
| shinetech/jazz | examples/foreach_object.js | JavaScript | mit | 288 |
/**********************************************************************
map_GoogleV2.js
$Comment: provides JavaScript for Google Api V2 calls
$Source :map_GoogleV2.js,v $
$InitialAuthor: guenter richter $
$InitialDate: 2011/01/03 $
$Author: guenter richter $
$Id:map_GoogleV2.js 1 2011-01-03 10:30:35Z Guenter Richter $
Copyright (c) Guenter Richter
$Log:map_GoogleV2.js,v $
**********************************************************************/
/**
* @fileoverview This is the interface to the Google maps API v2
*
* @author Guenter Richter guenter.richter@maptune.com
* @version 0.9
*/
/* ...................................................................*
* global vars *
* ...................................................................*/
/* ...................................................................*
* Google directions *
* ...................................................................*/
function __directions_handleErrors(){
var result = $("#directions-result")[0];
if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
result.innerHTML = ("Indirizzo sconosciuto. Forse è troppo nuovo o sbagliato.\n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
result.innerHTML = ("Richiesta non riuscita.\n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
result.innerHTML = ("Inserire indirizzi! \n Codice errore: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_BAD_KEY)
result.innerHTML = ("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
result.innerHTML = ("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
else result.innerHTML = ("Errore sconosciuto!");
}
function _map_setDirections(map,fromAddress, toAddress, toHidden, locale) {
var result = $("#directions-result")[0];
result.innerHTML = "";
gdir.loadFromWaypoints([fromAddress,toHidden],
{ "locale": locale, "preserveViewport":true });
}
function _map_setDestinationWaypoint(marker){
if ( marker ){
var form = $("#directionsform")[0];
if ( form ){
form.to.value = marker.data.name;
if ( marker.getLatLng ){
form.toHidden.value = marker.getLatLng();
}
else if( marker.getVertex ){
form.toHidden.value = marker.getVertex(0);
}
}
}
}
/**
* Is called 'onload' to start creating the map
*/
function _map_loadMap(target){
var __map = null;
// if google maps API v2 is loaded
if ( GMap2 ){
// check if browser can handle Google Maps
if ( !GBrowserIsCompatible()) {
alert("sorry - your browser cannot handle Google Maps !");
return null;
}
__map = new GMap2(target);
if ( __map ){
// configure user map interface
__map.addControl(new GMapTypeControl());
// map.addControl(new GMenuMapTypeControl());
__map.addControl(new GLargeMapControl3D());
__map.addControl(new GScaleControl());
__map.addMapType(G_PHYSICAL_MAP);
__map.addMapType(G_SATELLITE_3D_MAP);
__map.enableDoubleClickZoom();
__map.enableScrollWheelZoom();
}
}
return __map;
}
/**
* Is called to set up directions query
*/
function _map_addDirections(map,target){
if (map){
gdir = new GDirections(map,target);
GEvent.addListener(gdir, "error", __directions_handleErrors);
}
}
/**
* Is called to set up traffic information layer
*/
function _map_addTrafficLayer(map,target){
/* tbd */
}
/**
* Is called to set event handler
*/
function _map_addEventListner(map,szEvent,callback,mapUp){
if (map){
GEvent.addListener(map, szEvent, GEvent.callback(map,callback,mapUp) );
}
}
/**
* Is called 'onunload' to clear objects
*/
function _map_unloadMap(map){
if (map){
GUnload();
}
}
// set map center and zoom
//
function _map_setMapExtension(map,bBox){
if (map){
var mapCenter = { lon: (bBox[0] + (bBox[1]-bBox[0])/2) , lat: (bBox[2] + (bBox[3]-bBox[2])/2) };
var mapZoom = map.getBoundsZoomLevel(new GLatLngBounds( new GLatLng(bBox[2],bBox[0]),
new GLatLng(bBox[3],bBox[1]) ) );
map.setCenter(new GLatLng(mapCenter.lat, mapCenter.lon), mapZoom);
}
}
// get map zoom
//
function _map_getZoom(map){
if (map){
return map.getZoom();
}
return 0;
}
// get map center
//
function _map_getCenter(map){
if (map){
return map.getCenter();
}
return null;
}
// set map zoom
//
function _map_setZoom(map,nZoom){
if (map){
map.setZoom(nZoom);
}
}
// set map center
//
function _map_setCenter(map,center){
if (map){
map.setCenter(center);
}
}
// set map center and zoom
//
function _map_setCenterAndZoom(map,center,nZoom){
if (map){
map.setCenter(center,nZoom);
}
}
// create custom tooltip
//
function _map_createMyTooltip(marker, text, padding){
var tooltip = new Tooltip(marker, text, padding);
marker.tooltip = tooltip;
map.addOverlay(tooltip);
}
function _map_createMyTooltipListener(element, tooltip){
GEvent.addDomListener(element,'mouseover',GEvent.callback(tooltip,
Tooltip.prototype.show));
GEvent.addDomListener(element,'mouseout',GEvent.callback(tooltip,
Tooltip.prototype.hide));
}
// -----------------------------
// EOF
// -----------------------------
| emergenzeHack/terremotocentro | maptune/js/maptune/maptune.GoogleV2.js | JavaScript | mit | 5,620 |
import InputValidator from "../../common/js/InputValidator.js";
import ObjectUtilities from "../../common/js/ObjectUtilities.js";
import Action from "./Action.js";
import DefaultFilters from "./DefaultFilters.js";
import InitialState from "./InitialState.js";
var Reducer = {};
Reducer.root = function(state, action)
{
LOGGER.debug("root() type = " + action.type);
if (typeof state === 'undefined')
{
return new InitialState();
}
var newFilters, newFilteredTableRow;
switch (action.type)
{
case Action.REMOVE_FILTERS:
newFilteredTableRow = [];
newFilteredTableRow = newFilteredTableRow.concat(state.tableRows);
return Object.assign(
{}, state,
{
filteredTableRows: newFilteredTableRow,
});
case Action.SET_DEFAULT_FILTERS:
newFilters = DefaultFilters.create();
return Object.assign(
{}, state,
{
filters: newFilters,
});
case Action.SET_FILTERS:
LOGGER.debug("Reducer filters = ");
Object.getOwnPropertyNames(action.filters).forEach(function(propertyName)
{
LOGGER.debug(propertyName + ": " + action.filters[propertyName]);
});
newFilters = Object.assign(
{}, state.filters);
newFilters = ObjectUtilities.merge(newFilters, action.filters);
newFilteredTableRow = Reducer.filterTableRow(state.tableRows, newFilters);
Reducer.saveToLocalStorage(newFilters);
return Object.assign(
{}, state,
{
filters: newFilters,
filteredTableRows: newFilteredTableRow,
});
case Action.TOGGLE_FILTER_SHOWN:
return Object.assign(
{}, state,
{
isFilterShown: !state.isFilterShown,
});
default:
LOGGER.warn("Reducer.root: Unhandled action type: " + action.type);
return state;
}
};
Reducer.filterTableRow = function(tableRows, filters)
{
InputValidator.validateNotNull("tableRows", tableRows);
InputValidator.validateNotNull("filters", filters);
var answer = [];
tableRows.forEach(function(data)
{
if (Reducer.passes(data, filters))
{
answer.push(data);
}
});
return answer;
};
Reducer.passes = function(data, filters)
{
InputValidator.validateNotNull("data", data);
InputValidator.validateNotNull("filters", filters);
var answer = true;
var propertyNames = Object.getOwnPropertyNames(filters);
for (var i = 0; i < propertyNames.length; i++)
{
var propertyName = propertyNames[i];
var filter = filters[propertyName];
if (!filter.passes(data))
{
answer = false;
break;
}
}
return answer;
};
Reducer.saveToLocalStorage = function(filters)
{
InputValidator.validateNotNull("filters", filters);
var filterObjects = [];
Object.getOwnPropertyNames(filters).forEach(function(columnKey)
{
var filter = filters[columnKey];
filterObjects.push(filter.toObject());
});
localStorage.filters = JSON.stringify(filterObjects);
};
export default Reducer; | jmthompson2015/lotr-card-game | src/accessory/player-card-table/Reducer.js | JavaScript | mit | 3,186 |
{% extends 'layout.html' %}
{% block heading %}Coming soon{% endblock %}
{% block body %}
{{ message }}
{% endblock %}
{% block footer_nav %}
<li> <a href="{{ root }}">Back home</a> </li>
{% endblock %}
| tobykurien/HomeServer | views/coming_soon.html | HTML | mit | 214 |
package com.github.mlk.queue.codex;
import com.github.mlk.queue.Queuify;
import com.github.mlk.queue.implementation.Module;
public class Utf8StringModule implements Module {
public static Utf8StringModule utfStrings() {
return new Utf8StringModule();
}
@Override
public void bind(Queuify.Builder builder) {
builder.encoder(new StringEncoder())
.decoder(new StringDecoder());
}
}
| mlk/miniature-queue | core/src/main/java/com/github/mlk/queue/codex/Utf8StringModule.java | Java | mit | 434 |
ig.module(
'plusplus.config-user'
)
.defines(function() {
/**
* User configuration of Impact++.
* <span class="alert alert-info"><strong>Tip:</strong> it is recommended to modify this configuration file!</span>
* @example
* // in order to add your own custom configuration to Impact++
* // edit the file defining ig.CONFIG_USER, 'plusplus/config-user.js'
* // ig.CONFIG_USER is never modified by Impact++ (it is strictly for your use)
* // ig.CONFIG_USER is automatically merged over Impact++'s config
* @static
* @readonly
* @memberof ig
* @namespace ig.CONFIG_USER
* @author Collin Hover - collinhover.com
**/
ig.CONFIG_USER = {
// no need to do force entity extended checks, we won't mess it up
// because we know to have our entities extend ig.EntityExtended
FORCE_ENTITY_EXTENDED: false,
// auto sort
AUTO_SORT_LAYERS: true,
// fullscreen!
GAME_WIDTH_PCT: 1,
GAME_HEIGHT_PCT: 1,
// dynamic scaling based on dimensions in view (resolution independence)
GAME_WIDTH_VIEW: 352,
GAME_HEIGHT_VIEW: 208,
// clamped scaling is still dynamic, but within a range
// so we can't get too big or too small
SCALE_MIN: 1,
SCALE_MAX: 4,
// camera flexibility and smoothness
CAMERA: {
// keep the camera within the level
// (whenever possible)
//KEEP_INSIDE_LEVEL: true,
KEEP_CENTERED: false,
LERP: 0.025,
// trap helps with motion sickness
BOUNDS_TRAP_AS_PCT: true,
BOUNDS_TRAP_PCT_MINX: -0.2,
BOUNDS_TRAP_PCT_MINY: -0.3,
BOUNDS_TRAP_PCT_MAXX: 0.2,
BOUNDS_TRAP_PCT_MAXY: 0.3
},
// font and text settings
FONT: {
MAIN_NAME: "font_helloplusplus_white_16.png",
ALT_NAME: "font_helloplusplus_white_8.png",
CHAT_NAME: "font_helloplusplus_black_8.png",
// we can have the font be scaled relative to system
SCALE_OF_SYSTEM_SCALE: 0.5,
// and force a min / max
SCALE_MIN: 1,
SCALE_MAX: 2
},
// text bubble settings
TEXT_BUBBLE: {
// match the visual style
PIXEL_PERFECT: true
},
UI: {
// sometimes, we want to keep things at a static scale
// for example, UI is a possible target
SCALE: 3,
IGNORE_SYSTEM_SCALE: true
},
/*
// to try dynamic clamped UI scaling
// uncomment below and delete the UI settings above
UI: {
SCALE_MIN: 2,
SCALE_MAX: 4
}
*/
// UI should persist across all levels
UI_LAYER_CLEAR_ON_LOAD: false,
CHARACTER: {
// add some depth using offset
SIZE_OFFSET_X: 8,
SIZE_OFFSET_Y: 4
}
};
});
| collinhover/impactplusplus | examples/supercollider/lib/plusplus/config-user.js | JavaScript | mit | 3,308 |
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Brian Westrich, Jean-Baptiste Quenot, id:cactusman
* 2015 Kanstantsin Shautsou
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.triggers;
import antlr.ANTLRException;
import com.google.common.base.Preconditions;
import hudson.Extension;
import hudson.Util;
import hudson.console.AnnotatedLargeText;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AdministrativeMonitor;
import hudson.model.Cause;
import hudson.model.CauseAction;
import hudson.model.Item;
import hudson.model.Run;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.util.FlushProofOutputStream;
import hudson.util.FormValidation;
import hudson.util.IOUtils;
import hudson.util.NamingThreadFactory;
import hudson.util.SequentialExecutionQueue;
import hudson.util.StreamTaskListener;
import hudson.util.TimeUnit2;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import jenkins.model.RunAction2;
import jenkins.scm.SCMDecisionHandler;
import jenkins.triggers.SCMTriggerItem;
import jenkins.util.SystemProperties;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.jelly.XMLOutput;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import static java.util.logging.Level.WARNING;
/**
* {@link Trigger} that checks for SCM updates periodically.
*
* You can add UI elements under the SCM section by creating a
* config.jelly or config.groovy in the resources area for
* your class that inherits from SCMTrigger and has the
* @{@link hudson.model.Extension} annotation. The UI should
* be wrapped in an f:section element to denote it.
*
* @author Kohsuke Kawaguchi
*/
public class SCMTrigger extends Trigger<Item> {
private boolean ignorePostCommitHooks;
public SCMTrigger(String scmpoll_spec) throws ANTLRException {
this(scmpoll_spec, false);
}
@DataBoundConstructor
public SCMTrigger(String scmpoll_spec, boolean ignorePostCommitHooks) throws ANTLRException {
super(scmpoll_spec);
this.ignorePostCommitHooks = ignorePostCommitHooks;
}
/**
* This trigger wants to ignore post-commit hooks.
* <p>
* SCM plugins must respect this and not run this trigger for post-commit notifications.
*
* @since 1.493
*/
public boolean isIgnorePostCommitHooks() {
return this.ignorePostCommitHooks;
}
@Override
public void run() {
if (job == null) {
return;
}
run(null);
}
/**
* Run the SCM trigger with additional build actions. Used by SubversionRepositoryStatus
* to trigger a build at a specific revisionn number.
*
* @param additionalActions
* @since 1.375
*/
public void run(Action[] additionalActions) {
if (job == null) {
return;
}
DescriptorImpl d = getDescriptor();
LOGGER.fine("Scheduling a polling for "+job);
if (d.synchronousPolling) {
LOGGER.fine("Running the trigger directly without threading, " +
"as it's already taken care of by Trigger.Cron");
new Runner(additionalActions).run();
} else {
// schedule the polling.
// even if we end up submitting this too many times, that's OK.
// the real exclusion control happens inside Runner.
LOGGER.fine("scheduling the trigger to (asynchronously) run");
d.queue.execute(new Runner(additionalActions));
d.clogCheck();
}
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
@Override
public Collection<? extends Action> getProjectActions() {
if (job == null) {
return Collections.emptyList();
}
return Collections.singleton(new SCMAction());
}
/**
* Returns the file that records the last/current polling activity.
*/
public File getLogFile() {
return new File(job.getRootDir(),"scm-polling.log");
}
@Extension @Symbol("scm")
public static class DescriptorImpl extends TriggerDescriptor {
private static ThreadFactory threadFactory() {
return new NamingThreadFactory(Executors.defaultThreadFactory(), "SCMTrigger");
}
/**
* Used to control the execution of the polling tasks.
* <p>
* This executor implementation has a semantics suitable for polling. Namely, no two threads will try to poll the same project
* at once, and multiple polling requests to the same job will be combined into one. Note that because executor isn't aware
* of a potential workspace lock between a build and a polling, we may end up using executor threads unwisely --- they
* may block.
*/
private transient final SequentialExecutionQueue queue = new SequentialExecutionQueue(Executors.newSingleThreadExecutor(threadFactory()));
/**
* Whether the projects should be polled all in one go in the order of dependencies. The default behavior is
* that each project polls for changes independently.
*/
public boolean synchronousPolling = false;
/**
* Max number of threads for SCM polling.
* 0 for unbounded.
*/
private int maximumThreads;
public DescriptorImpl() {
load();
resizeThreadPool();
}
public boolean isApplicable(Item item) {
return SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(item) != null;
}
public ExecutorService getExecutor() {
return queue.getExecutors();
}
/**
* Returns true if the SCM polling thread queue has too many jobs
* than it can handle.
*/
public boolean isClogged() {
return queue.isStarving(STARVATION_THRESHOLD);
}
/**
* Checks if the queue is clogged, and if so,
* activate {@link AdministrativeMonitorImpl}.
*/
public void clogCheck() {
AdministrativeMonitor.all().get(AdministrativeMonitorImpl.class).on = isClogged();
}
/**
* Gets the snapshot of {@link Runner}s that are performing polling.
*/
public List<Runner> getRunners() {
return Util.filter(queue.getInProgress(),Runner.class);
}
// originally List<SCMedItem> but known to be used only for logging, in which case the instances are not actually cast to SCMedItem anyway
public List<SCMTriggerItem> getItemsBeingPolled() {
List<SCMTriggerItem> r = new ArrayList<SCMTriggerItem>();
for (Runner i : getRunners())
r.add(i.getTarget());
return r;
}
public String getDisplayName() {
return Messages.SCMTrigger_DisplayName();
}
/**
* Gets the number of concurrent threads used for polling.
*
* @return
* 0 if unlimited.
*/
public int getPollingThreadCount() {
return maximumThreads;
}
/**
* Sets the number of concurrent threads used for SCM polling and resizes the thread pool accordingly
* @param n number of concurrent threads, zero or less means unlimited, maximum is 100
*/
public void setPollingThreadCount(int n) {
// fool proof
if(n<0) n=0;
if(n>100) n=100;
maximumThreads = n;
resizeThreadPool();
}
@Restricted(NoExternalUse.class)
public boolean isPollingThreadCountOptionVisible() {
// unless you have a fair number of projects, this option is likely pointless.
// so let's hide this option for new users to avoid confusing them
// unless it was already changed
// TODO switch to check for SCMTriggerItem
return Jenkins.getInstance().getAllItems(AbstractProject.class).size() > 10
|| getPollingThreadCount() != 0;
}
/**
* Update the {@link ExecutorService} instance.
*/
/*package*/ synchronized void resizeThreadPool() {
queue.setExecutors(
(maximumThreads==0 ? Executors.newCachedThreadPool(threadFactory()) : Executors.newFixedThreadPool(maximumThreads, threadFactory())));
}
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
String t = json.optString("pollingThreadCount",null);
if(t==null || t.length()==0)
setPollingThreadCount(0);
else
setPollingThreadCount(Integer.parseInt(t));
// Save configuration
save();
return true;
}
public FormValidation doCheckPollingThreadCount(@QueryParameter String value) {
if (value != null && "".equals(value.trim()))
return FormValidation.ok();
return FormValidation.validateNonNegativeInteger(value);
}
}
@Extension
public static final class AdministrativeMonitorImpl extends AdministrativeMonitor {
private boolean on;
public boolean isActivated() {
return on;
}
}
/**
* Associated with {@link Run} to show the polling log
* that triggered that build.
*
* @since 1.376
*/
public static class BuildAction implements RunAction2 {
private transient /*final*/ Run<?,?> run;
@Deprecated
public transient /*final*/ AbstractBuild build;
/**
* @since 1.568
*/
public BuildAction(Run<?,?> run) {
this.run = run;
build = run instanceof AbstractBuild ? (AbstractBuild) run : null;
}
@Deprecated
public BuildAction(AbstractBuild build) {
this((Run) build);
}
/**
* @since 1.568
*/
public Run<?,?> getRun() {
return run;
}
/**
* Polling log that triggered the build.
*/
public File getPollingLogFile() {
return new File(run.getRootDir(),"polling.log");
}
public String getIconFileName() {
return "clipboard.png";
}
public String getDisplayName() {
return Messages.SCMTrigger_BuildAction_DisplayName();
}
public String getUrlName() {
return "pollingLog";
}
/**
* Sends out the raw polling log output.
*/
public void doPollingLog(StaplerRequest req, StaplerResponse rsp) throws IOException {
rsp.setContentType("text/plain;charset=UTF-8");
// Prevent jelly from flushing stream so Content-Length header can be added afterwards
FlushProofOutputStream out = new FlushProofOutputStream(rsp.getCompressedOutputStream(req));
try {
getPollingLogText().writeLogTo(0, out);
} finally {
IOUtils.closeQuietly(out);
}
}
public AnnotatedLargeText getPollingLogText() {
return new AnnotatedLargeText<BuildAction>(getPollingLogFile(), Charset.defaultCharset(), true, this);
}
/**
* Used from <tt>polling.jelly</tt> to write annotated polling log to the given output.
*/
public void writePollingLogTo(long offset, XMLOutput out) throws IOException {
// TODO: resurrect compressed log file support
getPollingLogText().writeHtmlTo(offset, out.asWriter());
}
@Override public void onAttached(Run<?, ?> r) {
// unnecessary, existing constructor does this
}
@Override public void onLoad(Run<?, ?> r) {
run = r;
build = run instanceof AbstractBuild ? (AbstractBuild) run : null;
}
}
/**
* Action object for job. Used to display the last polling log.
*/
public final class SCMAction implements Action {
public AbstractProject<?,?> getOwner() {
Item item = getItem();
return item instanceof AbstractProject ? ((AbstractProject) item) : null;
}
/**
* @since 1.568
*/
public Item getItem() {
return job().asItem();
}
public String getIconFileName() {
return "clipboard.png";
}
public String getDisplayName() {
Set<SCMDescriptor<?>> descriptors = new HashSet<SCMDescriptor<?>>();
for (SCM scm : job().getSCMs()) {
descriptors.add(scm.getDescriptor());
}
return descriptors.size() == 1 ? Messages.SCMTrigger_getDisplayName(descriptors.iterator().next().getDisplayName()) : Messages.SCMTrigger_BuildAction_DisplayName();
}
public String getUrlName() {
return "scmPollLog";
}
public String getLog() throws IOException {
return Util.loadFile(getLogFile());
}
/**
* Writes the annotated log to the given output.
* @since 1.350
*/
public void writeLogTo(XMLOutput out) throws IOException {
new AnnotatedLargeText<SCMAction>(getLogFile(),Charset.defaultCharset(),true,this).writeHtmlTo(0,out.asWriter());
}
}
private static final Logger LOGGER = Logger.getLogger(SCMTrigger.class.getName());
/**
* {@link Runnable} that actually performs polling.
*/
public class Runner implements Runnable {
/**
* When did the polling start?
*/
private volatile long startTime;
private Action[] additionalActions;
public Runner() {
this(null);
}
public Runner(Action[] actions) {
Preconditions.checkNotNull(job, "Runner can't be instantiated when job is null");
if (actions == null) {
additionalActions = new Action[0];
} else {
additionalActions = actions;
}
}
/**
* Where the log file is written.
*/
public File getLogFile() {
return SCMTrigger.this.getLogFile();
}
/**
* For which {@link Item} are we polling?
* @since 1.568
*/
public SCMTriggerItem getTarget() {
return job();
}
/**
* When was this polling started?
*/
public long getStartTime() {
return startTime;
}
/**
* Human readable string of when this polling is started.
*/
public String getDuration() {
return Util.getTimeSpanString(System.currentTimeMillis()-startTime);
}
private boolean runPolling() {
try {
// to make sure that the log file contains up-to-date text,
// don't do buffering.
StreamTaskListener listener = new StreamTaskListener(getLogFile());
try {
PrintStream logger = listener.getLogger();
long start = System.currentTimeMillis();
logger.println("Started on "+ DateFormat.getDateTimeInstance().format(new Date()));
boolean result = job().poll(listener).hasChanges();
logger.println("Done. Took "+ Util.getTimeSpanString(System.currentTimeMillis()-start));
if(result)
logger.println("Changes found");
else
logger.println("No changes");
return result;
} catch (Error | RuntimeException e) {
e.printStackTrace(listener.error("Failed to record SCM polling for "+job));
LOGGER.log(Level.SEVERE,"Failed to record SCM polling for "+job,e);
throw e;
} finally {
listener.close();
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE,"Failed to record SCM polling for "+job,e);
return false;
}
}
public void run() {
if (job == null) {
return;
}
// we can pre-emtively check the SCMDecisionHandler instances here
// note that job().poll(listener) should also check this
SCMDecisionHandler veto = SCMDecisionHandler.firstShouldPollVeto(job);
if (veto != null) {
try (StreamTaskListener listener = new StreamTaskListener(getLogFile())) {
listener.getLogger().println(
"Skipping polling on " + DateFormat.getDateTimeInstance().format(new Date())
+ " due to veto from " + veto);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to record SCM polling for " + job, e);
}
LOGGER.log(Level.FINE, "Skipping polling for {0} due to veto from {1}",
new Object[]{job.getFullDisplayName(), veto}
);
return;
}
String threadName = Thread.currentThread().getName();
Thread.currentThread().setName("SCM polling for "+job);
try {
startTime = System.currentTimeMillis();
if(runPolling()) {
SCMTriggerItem p = job();
String name = " #"+p.getNextBuildNumber();
SCMTriggerCause cause;
try {
cause = new SCMTriggerCause(getLogFile());
} catch (IOException e) {
LOGGER.log(WARNING, "Failed to parse the polling log",e);
cause = new SCMTriggerCause();
}
Action[] queueActions = new Action[additionalActions.length + 1];
queueActions[0] = new CauseAction(cause);
System.arraycopy(additionalActions, 0, queueActions, 1, additionalActions.length);
if (p.scheduleBuild2(p.getQuietPeriod(), queueActions) != null) {
LOGGER.info("SCM changes detected in "+ job.getFullDisplayName()+". Triggering "+name);
} else {
LOGGER.info("SCM changes detected in "+ job.getFullDisplayName()+". Job is already in the queue");
}
}
} finally {
Thread.currentThread().setName(threadName);
}
}
// as per the requirement of SequentialExecutionQueue, value equality is necessary
@Override
public boolean equals(Object that) {
return that instanceof Runner && job == ((Runner) that)._job();
}
private Item _job() {return job;}
@Override
public int hashCode() {
return job.hashCode();
}
}
@SuppressWarnings("deprecation")
private SCMTriggerItem job() {
return SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(job);
}
public static class SCMTriggerCause extends Cause {
/**
* Only used while ths cause is in the queue.
* Once attached to the build, we'll move this into a file to reduce the memory footprint.
*/
private String pollingLog;
private transient Run run;
public SCMTriggerCause(File logFile) throws IOException {
// TODO: charset of this log file?
this(FileUtils.readFileToString(logFile));
}
public SCMTriggerCause(String pollingLog) {
this.pollingLog = pollingLog;
}
/**
* @deprecated
* Use {@link SCMTrigger.SCMTriggerCause#SCMTriggerCause(String)}.
*/
@Deprecated
public SCMTriggerCause() {
this("");
}
@Override
public void onLoad(Run run) {
this.run = run;
}
@Override
public void onAddedTo(Run build) {
this.run = build;
try {
BuildAction a = new BuildAction(build);
FileUtils.writeStringToFile(a.getPollingLogFile(),pollingLog);
build.replaceAction(a);
} catch (IOException e) {
LOGGER.log(WARNING,"Failed to persist the polling log",e);
}
pollingLog = null;
}
@Override
public String getShortDescription() {
return Messages.SCMTrigger_SCMTriggerCause_ShortDescription();
}
@Restricted(DoNotUse.class)
public Run getRun() {
return this.run;
}
@Override
public boolean equals(Object o) {
return o instanceof SCMTriggerCause;
}
@Override
public int hashCode() {
return 3;
}
}
/**
* How long is too long for a polling activity to be in the queue?
*/
public static long STARVATION_THRESHOLD = SystemProperties.getLong(SCMTrigger.class.getName()+".starvationThreshold", TimeUnit2.HOURS.toMillis(1));
}
| SebastienGllmt/jenkins | core/src/main/java/hudson/triggers/SCMTrigger.java | Java | mit | 23,475 |
/*
* The MIT License
*
* Copyright 2019 Karus Labs.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.karuslabs.commons.command.synchronization;
import java.util.List;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerCommandSendEvent;
import org.bukkit.scheduler.BukkitScheduler;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class SynchronizationTest {
Synchronizer synchronizer = mock(Synchronizer.class);
BukkitScheduler scheduler = mock(BukkitScheduler.class);
Synchronization synchronization = new Synchronization(synchronizer, scheduler, null);
PlayerCommandSendEvent event = mock(PlayerCommandSendEvent.class);
@Test
void add() {
synchronization.add(event);
assertTrue(synchronization.events.contains(event));
assertTrue(synchronization.running);
verify(scheduler).scheduleSyncDelayedTask(null, synchronization);
}
@Test
void add_duplicate() {
synchronization.events.add(event);
synchronization.add(event);
assertTrue(synchronization.events.contains(event));
assertFalse(synchronization.running);
verify(scheduler, times(0)).scheduleSyncDelayedTask(null, synchronization);
}
@Test
void add_running() {
synchronization.running = true;
synchronization.add(event);
assertTrue(synchronization.events.contains(event));
assertTrue(synchronization.running);
verify(scheduler, times(0)).scheduleSyncDelayedTask(null, synchronization);
}
@Test
void run() {
when(event.getPlayer()).thenReturn(mock(Player.class));
when(event.getCommands()).thenReturn(List.of("a"));
synchronization.add(event);
synchronization.run();
verify(synchronizer).synchronize(any(Player.class), any(List.class));
assertTrue(synchronization.events.isEmpty());
assertFalse(synchronization.running);
}
}
| Pante/Karus-Commons | commons/src/test/java/com/karuslabs/commons/command/synchronization/SynchronizationTest.java | Java | mit | 3,282 |
<html dir="LTR">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
<title>DebugAppender Constructor ()</title>
<xml>
</xml>
<link rel="stylesheet" type="text/css" href="MSDN.css" />
</head>
<body id="bodyID" class="dtBODY">
<div id="nsbanner">
<div id="bannerrow1">
<table class="bannerparthead" cellspacing="0">
<tr id="hdr">
<td class="runninghead">Apache log4net SDK Documentation - Microsoft .NET Framework 4.0</td>
<td class="product">
</td>
</tr>
</table>
</div>
<div id="TitleRow">
<h1 class="dtH1">DebugAppender Constructor ()</h1>
</div>
</div>
<div id="nstext">
<p> Initializes a new instance of the <a href="log4net.Appender.DebugAppender.html">DebugAppender</a>. </p>
<div class="syntax">
<span class="lang">[Visual Basic]</span>
<br />Overloads Public Sub New()</div>
<div class="syntax">
<span class="lang">[C#]</span>
<br />public DebugAppender();</div>
<h4 class="dtH4">Remarks</h4>
<p> Default constructor. </p>
<h4 class="dtH4">See Also</h4><p><a href="log4net.Appender.DebugAppender.html">DebugAppender Class</a> | <a href="log4net.Appender.html">log4net.Appender Namespace</a> | <a href="log4net.Appender.DebugAppenderConstructor.html">DebugAppender Constructor Overload List</a></p><hr /><div id="footer"><a href='http://logging.apache.org/log4net/'>Copyright 2004-2013 The Apache Software Foundation.</a><br></br>Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.</div></div>
</body>
</html> | YOTOV-LIMITED/pokerleaguemanager | lib/Log4net 1.2.13/doc/release/sdk/log4net.Appender.DebugAppenderConstructor1.html | HTML | mit | 1,798 |
---
title: Jesus är grunden för vårt vittnesbörd
date: 06/09/2020
---
Som kristna har vi alla en personlig berättelse att återge, en berättelse om hur Jesus förvandlat vårt liv och vad han gjort för oss.
**Läs Ef. 2:1–10. Hurdana var vi innan vi lärde känna Kristus? Vad äger vi sedan vi har tagit emot honom?**
`A. Innan vi kände Kristus (Ef. 2:1–3).`
`B. Efter att vi lärt känna Kristus (Ef. 2:4–10).`
Vilken förunderlig förvandling! Innan vi kände Kristus var vi ”döda” genom våra överträdelser, ”levde i dem på denna tidens och världens vis”, ”följde våra mänskliga begär och handlade som kroppen och våra egna tankar ville, och av födseln var vi vredens barn”. Enkelt uttryckt: innan vi kände Kristus vandrade vi mållöst genom livet i ett förlorat tillstånd.
Vi kan ha upplevt något som verkade vara lycka, men där fanns en själens ångest och en ofullbordad mening med våra liv. Att komma till Kristus och uppleva hans kärlek gjorde hela skillnaden. Nu är vi i Kristus verkligen ”levande”. ”Men Gud, som är rik på barmhärtighet, har älskat oss med så stor kärlek att fast vi var döda genom våra överträdelser har han gjort oss levande tillsammans med Kristus – av nåd är ni frälsta – och uppväckt oss med honom och gett oss en plats i himlen genom Kristus Jesus. Därmed ville han för kommande tider visa den överväldigande rika nåden i sin godhet mot oss genom Kristus Jesus” (Ef. 2:4–7). I Kristus har livet fått en ny mening och ett nytt mål. Som Johannes säger: ”I honom fanns livet, och livet var människornas ljus” (Joh. 1:4, nuB).
`Läs Ef. 2:10. Vad säger det oss om hur centrala goda gärningar är för den kristna tron? Hur förstår vi den tanken i samband med frälsning genom tro ”oberoende av laggärningar” (Rom. 3:28)?`
`Hur har ditt liv förändrats tack vare Jesus, en förvandling som kanske kan hjälpa någon annan att lära känna Jesus?` | imasaru/sabbath-school-lessons | src/sv/2020-03/11/02.md | Markdown | mit | 1,983 |
<?php
/*
* This file is part of the Omnipay package.
*
* (c) Adrian Macneil <adrian@adrianmacneil.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Omnipay\Common\Message;
use Mockery as m;
use Omnipay\TestCase;
class AbstractResponseTest extends TestCase
{
public function testDefaultMethods()
{
$response = m::mock('\Omnipay\Common\Message\AbstractResponse[isSuccessful]');
$this->assertFalse($response->isRedirect());
$this->assertNull($response->getData());
$this->assertNull($response->getTransactionReference());
$this->assertNull($response->getMessage());
}
}
| cleverage/omnipay | tests/Omnipay/Common/Message/AbstractResponseTest.php | PHP | mit | 726 |
# encoding: utf-8
require 'spec_helper'
describe Github::Authorization do
let(:client_id) { '234jl23j4l23j4l' }
let(:client_secret) { 'asasd79sdf9a7asfd7sfd97s' }
let(:code) { 'c9798sdf97df98ds'}
let(:site) { 'http://github-ent.example.com/' }
let(:options) { {:site => site} }
subject(:github) { Github.new(options) }
after do
reset_authentication_for(github)
end
context '.client' do
it { is_expected.to respond_to :client }
it "should return OAuth2::Client instance" do
expect(github.client).to be_a OAuth2::Client
end
it "should assign site from the options hash" do
expect(github.client.site).to eq site
end
it "should assign 'authorize_url" do
expect(github.client.authorize_url).to eq "#{site}login/oauth/authorize"
end
it "should assign 'token_url" do
expect(github.client.token_url).to eq "#{site}login/oauth/access_token"
end
end
context '.auth_code' do
let(:oauth) { OAuth2::Client.new(client_id, client_secret) }
it "should throw an error if no client_id" do
expect { github.auth_code }.to raise_error(ArgumentError)
end
it "should throw an error if no client_secret" do
expect { github.auth_code }.to raise_error(ArgumentError)
end
it "should return authentication token code" do
github.client_id = client_id
github.client_secret = client_secret
allow(github.client).to receive(:auth_code).and_return code
expect(github.auth_code).to eq code
end
end
context "authorize_url" do
let(:options) { {:client_id => client_id, :client_secret => client_secret} }
it { is_expected.to respond_to(:authorize_url) }
it "should return address containing client_id" do
expect(github.authorize_url).to match /client_id=#{client_id}/
end
it "should return address containing scopes" do
expect(github.authorize_url(:scope => 'user')).to match /scope=user/
end
it "should return address containing redirect_uri" do
expect(github.authorize_url(:redirect_uri => 'http://localhost')).to match /redirect_uri/
end
end
context "get_token" do
let(:options) { {:client_id => client_id, :client_secret => client_secret} }
before do
stub_request(:post, 'https://github.com/login/oauth/access_token').
to_return(:body => '', :status => 200, :headers => {})
end
it { is_expected.to respond_to(:get_token) }
it "should make the authorization request" do
expect {
github.get_token code
a_request(:post, expect("https://github.com/login/oauth/access_token")).to have_been_made
}.to raise_error(OAuth2::Error)
end
it "should fail to get_token without authorization code" do
expect { github.get_token }.to raise_error(ArgumentError)
end
end
context ".authenticated?" do
it { is_expected.to respond_to(:authenticated?) }
it "should return false if falied on basic authentication" do
allow(github).to receive(:basic_authed?).and_return false
expect(github.authenticated?).to be false
end
it "should return true if basic authentication performed" do
allow(github).to receive(:basic_authed?).and_return true
expect(github.authenticated?).to be true
end
it "should return true if basic authentication performed" do
allow(github).to receive(:oauth_token?).and_return true
expect(github.authenticated?).to be true
end
end
context ".basic_authed?" do
before do
allow(github).to receive(:basic_auth?).and_return false
end
it { is_expected.to respond_to(:basic_authed?) }
it "should return false if login is missing" do
allow(github).to receive(:login?).and_return false
expect(github.basic_authed?).to be false
end
it "should return true if login && password provided" do
allow(github).to receive(:login?).and_return true
allow(github).to receive(:password?).and_return true
expect(github.basic_authed?).to be true
end
end
context "authentication" do
it { is_expected.to respond_to(:authentication) }
it "should return empty hash if no basic authentication params available" do
allow(github).to receive(:login?).and_return false
allow(github).to receive(:basic_auth?).and_return false
expect(github.authentication).to be_empty
end
context 'basic_auth' do
let(:options) { { :basic_auth => 'github:pass' } }
it "should return hash with basic auth params" do
expect(github.authentication).to include({login: 'github'})
expect(github.authentication).to include({password: 'pass'})
end
end
context 'login & password' do
it "should return hash with login & password params" do
options = {login: 'github', password: 'pass'}
github = Github.new(options)
expect(github.authentication).to be_a(Hash)
expect(github.authentication).to include({login: 'github'})
expect(github.authentication).to include({password: 'pass'})
reset_authentication_for(github)
end
end
end # authentication
end # Github::Authorization
| peter-murach/github | spec/github/authorization_spec.rb | Ruby | mit | 5,177 |
require File.expand_path('../spec_helper', __FILE__)
module Danger
describe DangerProse do
it 'is a plugin' do
expect(Danger::DangerProse < Danger::Plugin).to be_truthy
end
describe 'with Dangerfile' do
before do
@dangerfile = testing_dangerfile
@prose = testing_dangerfile.prose
end
describe 'linter' do
it 'handles proselint not being installed' do
allow(@prose).to receive(:`).with('which proselint').and_return('')
expect(@prose.proselint_installed?).to be_falsy
end
it 'handles proselint being installed' do
allow(@prose).to receive(:`).with('which proselint').and_return('/bin/thing/proselint')
expect(@prose.proselint_installed?).to be_truthy
end
describe :lint_files do
before do
# So it doesn't try to install on your computer
allow(@prose).to receive(:`).with('which proselint').and_return('/bin/thing/proselint')
# Proselint returns JSON data, which is nice 👍
errors = '[{"start": 1441, "replacements": null, "end": 1445, "severity": "warning", "extent": 4, "column": 1, "message": "!!! is hyperbolic.", "line": 46, "check": "hyperbolic.misc"}]'
proselint_response = '{"status" : "success", "data" : { "errors" : ' + errors + '}}'
# This is where we generate our JSON
allow(@prose).to receive(:`).with('proselint "spec/fixtures/blog_post.md" --json').and_return(proselint_response)
# it's worth noting - you can call anything on your plugin that a Dangerfile responds to
# The request source's PR JSON typically looks like
# https://raw.githubusercontent.com/danger/danger/bffc246a11dac883d76fc6636319bd6c2acd58a3/spec/fixtures/pr_response.json
@prose.env.request_source.pr_json = { "head" => { "ref" => 'my_fake_branch' } }
end
it 'handles a known JSON report from proselint' do
@prose.lint_files('spec/fixtures/*.md')
output = @prose.status_report[:markdowns].first
# A title
expect(output.message).to include('Proselint found issues')
# A warning
expect(output.message).to include('!!! is hyperbolic. | warning')
# A link to the file inside the fixtures dir
expect(output.message).to include('[spec/fixtures/blog_post.md](/artsy/eigen/tree/my_fake_branch/spec/fixtures/blog_post.md)')
end
end
end
describe 'spell checking' do
it 'handles proselint not being installed' do
allow(@prose).to receive(:`).with('which mdspell').and_return('')
expect(@prose.mdspell_installed?).to be_falsy
end
it 'handles proselint being installed' do
allow(@prose).to receive(:`).with('which mdspell').and_return('/bin/thing/mdspell')
expect(@prose.mdspell_installed?).to be_truthy
end
describe 'full command' do
before do
# So it doesn't try to install on your computer
allow(@prose).to receive(:`).with('which mdspell').and_return('/bin/thing/mdspell')
# mdspell returns JSON data, which is nice 👍
proselint_response = " spec/fixtures/blog_post.md\n 1:27 | This post intentional left blank-ish.\n 4:84 | Here's a tpyo - it should registor.\n 4:101 | Here's a tpyo - it should registor.\n\n >> 3 spelling errors found in 1 file"
# This is where we generate our JSON
allow(@prose).to receive(:`).with('mdspell spec/fixtures/blog_post.md -r --en-gb').and_return(proselint_response)
# it's worth noting - you can call anything on your plugin that a Dangerfile responds to
# The request source's PR JSON typically looks like
# https://raw.githubusercontent.com/danger/danger/bffc246a11dac883d76fc6636319bd6c2acd58a3/spec/fixtures/pr_response.json
@prose.env.request_source.pr_json = { "head" => { "ref" => 'my_fake_branch' } }
end
it 'handles a known JSON report from mdspell' do
@prose.check_spelling('spec/fixtures/*.md')
output = @prose.status_report[:markdowns].first
# A title
expect(output.message).to include('Spell Checker found issues')
# A typo, in bold
expect(output.message).to include('**tpyo**')
# A link to the file inside the fixtures dir
expect(output.message).to include('[spec/fixtures/blog_post.md](/artsy/eigen/tree/my_fake_branch/spec/fixtures/blog_post.md)')
end
end
end
end
end
end
| dbgrandi/danger-proselint | spec/danger_plugin_spec.rb | Ruby | mit | 4,724 |
'use strict'
const path = require('path')
const hbs = require('express-hbs')
module.exports = function (app, express) {
hbs.registerHelper('asset', require('./helpers/asset'))
app.engine('hbs', hbs.express4({
partialsDir: path.resolve('app/client/views/partials'),
layoutsDir: path.resolve('app/client/views/layouts'),
beautify: app.locals.isProduction
}))
app.set('view engine', 'hbs')
app.set('views', path.resolve('app/client/views'))
app.use(express.static(path.resolve('app/public')))
return app
}
| finkhq/fink-www | app/server/views/index.js | JavaScript | mit | 535 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LCOV - result.info - c++/7.1.0/bits/stl_pair.h - functions</title>
<link rel="stylesheet" type="text/css" href="../../../gcov.css">
</head>
<body>
<table width="100%" border=0 cellspacing=0 cellpadding=0>
<tr><td class="title">LCOV - code coverage report</td></tr>
<tr><td class="ruler"><img src="../../../glass.png" width=3 height=3 alt=""></td></tr>
<tr>
<td width="100%">
<table cellpadding=1 border=0 width="100%">
<tr>
<td width="10%" class="headerItem">Current view:</td>
<td width="35%" class="headerValue"><a href="../../../index.html">top level</a> - <a href="index.html">c++/7.1.0/bits</a> - stl_pair.h<span style="font-size: 80%;"> (<a href="stl_pair.h.gcov.html">source</a> / functions)</span></td>
<td width="5%"></td>
<td width="15%"></td>
<td width="10%" class="headerCovTableHead">Hit</td>
<td width="10%" class="headerCovTableHead">Total</td>
<td width="15%" class="headerCovTableHead">Coverage</td>
</tr>
<tr>
<td class="headerItem">Test:</td>
<td class="headerValue">result.info</td>
<td></td>
<td class="headerItem">Lines:</td>
<td class="headerCovTableEntry">7</td>
<td class="headerCovTableEntry">7</td>
<td class="headerCovTableEntryHi">100.0 %</td>
</tr>
<tr>
<td class="headerItem">Date:</td>
<td class="headerValue">2017-07-07 11:26:11</td>
<td></td>
<td class="headerItem">Functions:</td>
<td class="headerCovTableEntry">0</td>
<td class="headerCovTableEntry">0</td>
<td class="headerCovTableEntryHi">-</td>
</tr>
<tr><td><img src="../../../glass.png" width=3 height=3 alt=""></td></tr>
</table>
</td>
</tr>
<tr><td class="ruler"><img src="../../../glass.png" width=3 height=3 alt=""></td></tr>
</table>
<center>
<table width="60%" cellpadding=1 cellspacing=1 border=0>
<tr><td><br></td></tr>
<tr>
<td width="80%" class="tableHead">Function Name <span class="tableHeadSort"><a href="stl_pair.h.func.html"><img src="../../../updown.png" width=10 height=14 alt="Sort by function name" title="Sort by function name" border=0></a></span></td>
<td width="20%" class="tableHead">Hit count <span class="tableHeadSort"><img src="../../../glass.png" width=10 height=14 alt="Sort by hit count" title="Sort by hit count" border=0></span></td>
</tr>
</table>
<br>
</center>
<table width="100%" border=0 cellspacing=0 cellpadding=0>
<tr><td class="ruler"><img src="../../../glass.png" width=3 height=3 alt=""></td></tr>
<tr><td class="versionInfo">Generated by: <a href="http://ltp.sourceforge.net/coverage/lcov.php" target="_parent">LCOV version 1.13</a></td></tr>
</table>
<br>
</body>
</html>
| FirstSanny/appfs | RayChew/Ex7/result/c++/7.1.0/bits/stl_pair.h.func-sort-c.html | HTML | mit | 3,109 |
/////////////////////////////////////////////////////////////////////////////
// Name: wx/msw/notebook.h
// Purpose: MSW/GTK compatible notebook (a.k.a. property sheet)
// Author: Robert Roebling
// Modified by: Vadim Zeitlin for Windows version
// RCS-ID: $Id$
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _NOTEBOOK_H
#define _NOTEBOOK_H
#if wxUSE_NOTEBOOK
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#include "wx/control.h"
// ----------------------------------------------------------------------------
// wxNotebook
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxNotebookPageInfo : public wxObject
{
public :
wxNotebookPageInfo() { m_page = NULL; m_imageId = -1; m_selected = false; }
virtual ~wxNotebookPageInfo() { }
void Create(wxNotebookPage *page,
const wxString& text,
bool selected,
int imageId)
{
m_page = page;
m_text = text;
m_selected = selected;
m_imageId = imageId;
}
wxNotebookPage* GetPage() const { return m_page; }
wxString GetText() const { return m_text; }
bool GetSelected() const { return m_selected; }
int GetImageId() const { return m_imageId; }
private:
wxNotebookPage *m_page;
wxString m_text;
bool m_selected;
int m_imageId;
DECLARE_DYNAMIC_CLASS(wxNotebookPageInfo)
};
WX_DECLARE_EXPORTED_LIST(wxNotebookPageInfo, wxNotebookPageInfoList );
class WXDLLIMPEXP_CORE wxNotebook : public wxNotebookBase
{
public:
// ctors
// -----
// default for dynamic class
wxNotebook();
// the same arguments as for wxControl (@@@ any special styles?)
wxNotebook(wxWindow *parent,
wxWindowID id,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = 0,
const wxString& name = wxNotebookNameStr);
// Create() function
bool Create(wxWindow *parent,
wxWindowID id,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = 0,
const wxString& name = wxNotebookNameStr);
virtual ~wxNotebook();
// accessors
// ---------
// get number of pages in the dialog
virtual size_t GetPageCount() const;
// set the currently selected page, return the index of the previously
// selected one (or -1 on error)
// NB: this function will _not_ generate wxEVT_NOTEBOOK_PAGE_xxx events
int SetSelection(size_t nPage);
// get the currently selected page
int GetSelection() const { return m_nSelection; }
// changes selected page without sending events
int ChangeSelection(size_t nPage);
// set/get the title of a page
bool SetPageText(size_t nPage, const wxString& strText);
wxString GetPageText(size_t nPage) const;
// image list stuff: each page may have an image associated with it. All
// the images belong to an image list, so you have to
// 1) create an image list
// 2) associate it with the notebook
// 3) set for each page it's image
// associate image list with a control
void SetImageList(wxImageList* imageList);
// sets/returns item's image index in the current image list
int GetPageImage(size_t nPage) const;
bool SetPageImage(size_t nPage, int nImage);
// currently it's always 1 because wxGTK doesn't support multi-row
// tab controls
int GetRowCount() const;
// control the appearance of the notebook pages
// set the size (the same for all pages)
void SetPageSize(const wxSize& size);
// set the padding between tabs (in pixels)
void SetPadding(const wxSize& padding);
// operations
// ----------
// remove all pages
bool DeleteAllPages();
// inserts a new page to the notebook (it will be deleted ny the notebook,
// don't delete it yourself). If bSelect, this page becomes active.
bool InsertPage(size_t nPage,
wxNotebookPage *pPage,
const wxString& strText,
bool bSelect = false,
int imageId = -1);
void AddPageInfo( wxNotebookPageInfo* info ) { AddPage( info->GetPage() , info->GetText() , info->GetSelected() , info->GetImageId() ); }
const wxNotebookPageInfoList& GetPageInfos() const;
// Windows-only at present. Also, you must use the wxNB_FIXEDWIDTH
// style.
void SetTabSize(const wxSize& sz);
// hit test
virtual int HitTest(const wxPoint& pt, long *flags = NULL) const;
// calculate the size of the notebook from the size of its page
virtual wxSize CalcSizeFromPage(const wxSize& sizePage) const;
// callbacks
// ---------
void OnSize(wxSizeEvent& event);
void OnSelChange(wxBookCtrlEvent& event);
void OnNavigationKey(wxNavigationKeyEvent& event);
// base class virtuals
// -------------------
virtual bool MSWOnNotify(int idCtrl, WXLPARAM lParam, WXLPARAM *result);
virtual bool MSWOnScroll(int orientation, WXWORD nSBCode,
WXWORD pos, WXHWND control);
#if wxUSE_CONSTRAINTS
virtual void SetConstraintSizes(bool recurse = true);
virtual bool DoPhase(int nPhase);
#endif // wxUSE_CONSTRAINTS
// Attempts to get colour for UX theme page background
wxColour GetThemeBackgroundColour() const;
// implementation only
// -------------------
#if wxUSE_UXTHEME
virtual bool SetBackgroundColour(const wxColour& colour)
{
if ( !wxNotebookBase::SetBackgroundColour(colour) )
return false;
UpdateBgBrush();
return true;
}
// return the themed brush for painting our children
virtual WXHBRUSH MSWGetBgBrushForChild(WXHDC hDC, wxWindow *child);
// draw child background
virtual bool MSWPrintChild(WXHDC hDC, wxWindow *win);
#endif // wxUSE_UXTHEME
// translate wxWin styles to the Windows ones
virtual WXDWORD MSWGetStyle(long flags, WXDWORD *exstyle = NULL) const;
protected:
// common part of all ctors
void Init();
// hides the currently shown page and shows the given one (if not -1) and
// updates m_nSelection accordingly
void UpdateSelection(int selNew);
// remove one page from the notebook, without deleting
virtual wxNotebookPage *DoRemovePage(size_t nPage);
// get the page rectangle for the current notebook size
//
// returns empty rectangle if an error occurs, do test for it
wxRect GetPageSize() const;
// set the size of the given page to fit in the notebook
void AdjustPageSize(wxNotebookPage *page);
#if wxUSE_UXTHEME
// gets the bitmap of notebook background and returns a brush from it
WXHBRUSH QueryBgBitmap();
// creates the brush to be used for drawing the tab control background
void UpdateBgBrush();
// common part of QueryBgBitmap() and MSWPrintChild()
//
// if child == NULL, draw background for the entire notebook itself
bool DoDrawBackground(WXHDC hDC, wxWindow *child = NULL);
#endif // wxUSE_UXTHEME
// these function are only used for reducing flicker on notebook resize and
// we don't need to do this for WinCE
#ifndef __WXWINCE__
void OnEraseBackground(wxEraseEvent& event);
void OnPaint(wxPaintEvent& event);
// true if we have already subclassed our updown control
bool m_hasSubclassedUpdown;
#endif // __WXWINCE__
// the current selection (-1 if none)
int m_nSelection;
wxNotebookPageInfoList m_pageInfos;
#if wxUSE_UXTHEME
// background brush used to paint the tab control
WXHBRUSH m_hbrBackground;
#endif // wxUSE_UXTHEME
DECLARE_DYNAMIC_CLASS_NO_COPY(wxNotebook)
DECLARE_EVENT_TABLE()
};
#endif // wxUSE_NOTEBOOK
#endif // _NOTEBOOK_H
| airgames/vuforia-gamekit-integration | Gamekit/wxWidgets-2.9.1/include/wx/msw/notebook.h | C | mit | 8,154 |
// Polyfills
if ( Number.EPSILON === undefined ) {
Number.EPSILON = Math.pow( 2, - 52 );
}
if ( Number.isInteger === undefined ) {
// Missing in IE
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
Number.isInteger = function ( value ) {
return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
};
}
//
if ( Math.sign === undefined ) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
Math.sign = function ( x ) {
return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
};
}
if ( 'name' in Function.prototype === false ) {
// Missing in IE
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
Object.defineProperty( Function.prototype, 'name', {
get: function () {
return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
}
} );
}
if ( Object.assign === undefined ) {
// Missing in IE
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Object.assign = function ( target ) {
'use strict';
if ( target === undefined || target === null ) {
throw new TypeError( 'Cannot convert undefined or null to object' );
}
const output = Object( target );
for ( let index = 1; index < arguments.length; index ++ ) {
const source = arguments[ index ];
if ( source !== undefined && source !== null ) {
for ( const nextKey in source ) {
if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
output[ nextKey ] = source[ nextKey ];
}
}
}
}
return output;
};
}
| fraguada/three.js | src/polyfills.js | JavaScript | mit | 1,691 |
<?php
/*
* This file is part of the PHPExifTool package.
*
* (c) Alchemy <support@alchemy.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\FlashPix;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class LockedPropertyList extends AbstractTag
{
protected $Id = 65538;
protected $Name = 'LockedPropertyList';
protected $FullName = 'mixed';
protected $GroupName = 'FlashPix';
protected $g0 = 'FlashPix';
protected $g1 = 'FlashPix';
protected $g2 = 'Other';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Locked Property List';
}
| bburnichon/PHPExiftool | lib/PHPExiftool/Driver/Tag/FlashPix/LockedPropertyList.php | PHP | mit | 807 |
import supertest from 'supertest';
import { publicChannelName, privateChannelName } from './channel.js';
import { roleNameUsers, roleNameSubscriptions, roleScopeUsers, roleScopeSubscriptions, roleDescription } from './role.js';
import { username, email, adminUsername, adminPassword } from './user.js';
export const request = supertest('http://localhost:3000');
const prefix = '/api/v1/';
export function wait(cb, time) {
return () => setTimeout(cb, time);
}
export const apiUsername = `api${ username }`;
export const apiEmail = `api${ email }`;
export const apiPublicChannelName = `api${ publicChannelName }`;
export const apiPrivateChannelName = `api${ privateChannelName }`;
export const apiRoleNameUsers = `api${ roleNameUsers }`;
export const apiRoleNameSubscriptions = `api${ roleNameSubscriptions }`;
export const apiRoleScopeUsers = `${ roleScopeUsers }`;
export const apiRoleScopeSubscriptions = `${ roleScopeSubscriptions }`;
export const apiRoleDescription = `api${ roleDescription }`;
export const reservedWords = [
'admin',
'administrator',
'system',
'user',
];
export const targetUser = {};
export const channel = {};
export const group = {};
export const message = {};
export const directMessage = {};
export const integration = {};
export const credentials = {
'X-Auth-Token': undefined,
'X-User-Id': undefined,
};
export const login = {
user: adminUsername,
password: adminPassword,
};
export function api(path) {
return prefix + path;
}
export function methodCall(methodName) {
return api(`method.call/${ methodName }`);
}
export function log(res) {
console.log(res.req.path);
console.log({
body: res.body,
headers: res.headers,
});
}
export function getCredentials(done = function() {}) {
request.post(api('login'))
.send(login)
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
credentials['X-Auth-Token'] = res.body.data.authToken;
credentials['X-User-Id'] = res.body.data.userId;
})
.end(done);
}
| VoiSmart/Rocket.Chat | tests/data/api-data.js | JavaScript | mit | 1,993 |
<?php defined('BX_DOL') or die('hack attempt');
/**
* Copyright (c) UNA, Inc - https://una.io
* MIT License - https://opensource.org/licenses/MIT
*
* @defgroup UnaStudio UNA Studio
* @{
*/
define("BX_DOL_STUDIO_INSTALLER_SUCCESS", 0);
define("BX_DOL_STUDIO_INSTALLER_FAILED", 1);
/**
* Base class for Installer classes in modules engine.
*
* The class contains different check functions which are used during the installation process.
* An object of the class is created automatically with modules installer.
* Installation/Uninstallation process can be controlled with config.php file located in [module]/install/ folder.
*
*
* Example of usage:
* refer to the BoonEx modules
*
*
* Memberships/ACL:
* Doesn't depend on user's membership.
*
*
* Alerts:
* no alerts available
*
*/
class BxDolStudioInstaller extends BxDolInstallerUtils
{
protected $oDb;
protected $_aConfig;
protected $_sBasePath;
protected $_sHomePath;
protected $_sModulePath;
protected $_bUseFtp;
protected $_aActions;
protected $_bShowOnSuccess = false;
public function __construct($aConfig)
{
parent::__construct();
$this->oDb = bx_instance('BxDolStudioInstallerQuery');
$this->_aConfig = $aConfig;
$this->_sBasePath = BX_DIRECTORY_PATH_MODULES;
$this->_sHomePath = $this->_sBasePath . $aConfig['home_dir'];
$this->_sModulePath = $this->_sBasePath . $aConfig['home_dir'];
$this->_bUseFtp = BX_FORCE_USE_FTP_FILE_TRANSFER;
$this->_aActions = array(
'perform_install' => array(
'title' => '',
'success' => _t('_adm_msg_modules_success_install'),
'failed' => ''
),
'perform_uninstall' => array(
'title' => '',
'success' => _t('_adm_msg_modules_success_uninstall'),
'failed' => ''
),
'perform_enable' => array(
'title' => '',
'success' => _t('_adm_msg_modules_success_enable'),
'failed' => ''
),
'perform_disable' => array(
'title' => '',
'success' => _t('_adm_msg_modules_success_disable'),
'failed' => ''
),
'check_script_version' => array(
'title' => _t('_adm_txt_modules_check_script_version'),
),
'check_dependencies' => array(
'title' => _t('_adm_txt_modules_check_dependencies'),
),
'show_introduction' => array(
'title' => _t('_adm_txt_modules_show_introduction'),
),
'move_sources' => array(
'title' => _t('_adm_txt_modules_move_sources'),
),
'execute_sql' => array(
'title' => _t('_adm_txt_modules_execute_sql'),
),
'install_language' => array(
'title' => _t('_adm_txt_modules_install_language'),
),
'update_languages' => array(
'title' => _t('_adm_txt_modules_update_languages'),
),
'update_relations' => array(
'title' => _t('_adm_txt_modules_update_relations'),
),
'update_relations_for_all' => array(
'title' => _t('_adm_txt_modules_update_relations_for_all'),
),
'process_connections' => array(
'title' => _t('_adm_txt_modules_process_connections'),
),
'process_deleted_profiles' => array(
'title' => _t('_adm_txt_modules_process_deleted_profiles'),
),
'process_menu_triggers' => array(
'title' => _t('_adm_txt_modules_process_menu_triggers'),
),
'process_page_triggers' => array(
'title' => _t('_adm_txt_modules_process_page_triggers'),
),
'process_storages' => array(
'title' => _t('_adm_txt_modules_process_storages'),
),
'process_esearches' => array(
'title' => _t('_adm_txt_modules_process_esearches'),
),
'register_transcoders' => array(
'title' => _t('_adm_txt_modules_register_transcoders'),
),
'unregister_transcoders' => array(
'title' => _t('_adm_txt_modules_unregister_transcoders'),
),
'clear_db_cache' => array(
'title' => _t('_adm_txt_modules_clear_db_cache'),
),
'clear_template_cache' => array(
'title' => _t('_adm_txt_modules_clear_template_cache'),
),
'show_conclusion' => array(
'title' => _t('_adm_txt_modules_show_conclusion'),
),
);
$this->_aNonHashableFiles = array(
'install',
'updates'
);
}
public function install($aParams, $bAutoEnable = false)
{
//--- Auto uninstall before install ---//
$this->disable($aParams);
$this->uninstall($aParams);
$bAutoEnable = $bAutoEnable || (isset($aParams['auto_enable']) && (bool)$aParams['auto_enable']);
$bHtmlResponce = isset($aParams['html_response']) && (bool)$aParams['html_response'];
//--- Check whether the module was already installed ---//
if($this->oDb->isModule($this->_aConfig['home_uri']))
return array(
'message' => _t('_adm_err_modules_already_installed'),
'result' => false
);
$aResult = array();
bx_alert('system', 'before_install', 0, false, array ('config' => $this->_aConfig, 'result' => &$aResult));
if ($aResult && !$aResult['result'])
return $aResult;
//--- Check mandatory settings ---//
if($this->oDb->isModuleParamsUsed($this->_aConfig['home_uri'], $this->_aConfig['home_dir'], $this->_aConfig['db_prefix'], $this->_aConfig['class_prefix']))
return array(
'message' => _t('_adm_txt_modules_params_used'),
'result' => false
);
//--- Check version compatibility ---//
if(!$this->_isCompatibleWith())
return array(
'message' => $this->_displayResult('check_script_version', false, '_adm_err_modules_wrong_version_script', $bHtmlResponce),
'result' => false
);
//--- Check for available translations ---//
$oFile = $this->_getFileManager();
$sModuleUri = $this->_aConfig['home_uri'];
$aLanguages = $this->oDb->getModulesBy(array('type' => 'languages'));
foreach($aLanguages as $aLanguage) {
if($aLanguage['uri'] == 'en')
continue;
$aLanguageConfig = self::getModuleConfig(BX_DIRECTORY_PATH_MODULES . $aLanguage['path'] . '/install/config.php');
if(empty($aLanguageConfig))
continue;
if(!isset($aLanguageConfig['includes'][$sModuleUri]) || empty($aLanguageConfig['includes'][$sModuleUri]))
continue;
$sSrcPath = 'modules/' . $aLanguage['path'] . 'install/data/' . $aLanguageConfig['includes'][$sModuleUri];
$sDstPath = $aLanguageConfig['includes'][$sModuleUri];
$oFile->copy($sSrcPath, $sDstPath);
}
$aResultBefore = $this->_onInstallBefore();
if($aResultBefore !== BX_DOL_STUDIO_INSTALLER_SUCCESS)
return array(
'message' => $aResultBefore['content'],
'result' => false
);
//--- Check actions ---//
$aResult = $this->_perform('install', $aParams);
if($aResult['result']) {
$iModuleId = $this->oDb->insertModule($this->_aConfig);
$sTitleKey = BxDolModule::getTitleKey($this->_aConfig['home_uri']);
$oLanguages = BxDolStudioLanguagesUtils::getInstance();
$oLanguages->addLanguageString($sTitleKey, $this->_aConfig['title']);
$oLanguages->compileLanguage();
BxDolStudioInstallerUtils::getInstance()->checkModules();
$aFiles = array();
$this->hashFiles($this->_sModulePath, $aFiles);
foreach($aFiles as $aFile)
$this->oDb->insertModuleTrack($iModuleId, $aFile);
$this->cleanupMemoryAfterAction($this->_aConfig['home_uri'], $iModuleId);
$this->_onInstallAfter();
if(!empty($this->_aConfig['install_success']))
$this->_perform('install_success', $aParams);
}
else {
if(!empty($this->_aConfig['install_failed']))
$this->_perform('install_failed', $aParams);
}
bx_alert('system', 'install', 0, false, array ('config' => $this->_aConfig, 'result' => &$aResult));
if($aResult['result'] && $bAutoEnable) {
$aResultEnable = $this->enable($aParams);
$aResult['result'] = $aResult['result'] & $aResultEnable['result'];
$aResult['message'] = $aResult['message'] . $aResultEnable['message'];
}
return $aResult;
}
public function uninstall($aParams, $bAutoDisable = false)
{
$bAutoDisable = $bAutoDisable || (isset($aParams['auto_disable']) && (bool)$aParams['auto_disable']);
$bHtmlResponce = isset($aParams['html_response']) && (bool)$aParams['html_response'];
//--- Check whether the module was already uninstalled ---//
if(!$this->oDb->isModule($this->_aConfig['home_uri']))
return array(
'message' => _t('_adm_err_modules_already_uninstalled'),
'result' => false
);
if($bAutoDisable) {
$aResultDisable = $this->disable($aParams);
if(!$aResultDisable['result'])
return $aResultDisable;
}
$aResult = array();
bx_alert('system', 'before_uninstall', 0, false, array ('config' => $this->_aConfig, 'result' => &$aResult));
if ($aResult && !$aResult['result'])
return $aResult;
//--- Check for dependent modules ---//
$bDependent = false;
$aDependents = $this->oDb->getDependent($this->_aConfig['name'], $this->_aConfig['home_uri']);
if(is_array($aDependents) && !empty($aDependents)) {
$bDependent = true;
$sMessage = '<br />' . _t('_adm_err_modules_wrong_dependency_uninstall') . '<br />';
foreach($aDependents as $aDependent)
$sMessage .= $aDependent['title'] . '<br />';
}
if($bDependent)
return array(
'message' => $this->_displayResult('check_dependencies', false, $sMessage, $bHtmlResponce),
'result' => false
);
//--- Process storages and comments ---//
$aResultBefore = $this->_onUninstallBefore();
if($aResultBefore !== BX_DOL_STUDIO_INSTALLER_SUCCESS)
return array(
'message' => $aResultBefore['content'],
'result' => false
);
$aResult = $this->_perform('uninstall', $aParams);
if($aResult['result']) {
$iModuleId = $this->oDb->deleteModule($this->_aConfig);
$sTitleKey = BxDolModule::getTitleKey($this->_aConfig['home_uri']);
$oLanguages = BxDolStudioLanguagesUtils::getInstance();
$oLanguages->deleteLanguageString($sTitleKey);
$oLanguages->compileLanguage();
$this->cleanupMemoryAfterAction($this->_aConfig['home_uri'], $iModuleId);
$this->_onUninstallAfter();
if(!empty($this->_aConfig['uninstall_success']))
$this->_perform('uninstall_success', $aParams);
}
else {
if(!empty($this->_aConfig['uninstall_failed']))
$this->_perform('uninstall_failed', $aParams);
}
if($bAutoDisable) {
$aResult['result'] = $aResultDisable['result'] & $aResult['result'];
$aResult['message'] = $aResultDisable['message'] . $aResult['message'];
}
bx_alert('system', 'uninstall', 0, false, array ('config' => $this->_aConfig, 'result' => &$aResult));
return $aResult;
}
public function delete($aParams)
{
$aError = array(
'message' => _t('_adm_err_modules_cannot_remove_package'),
'result' => false
);
$oFile = $this->_getFileManager();
if(empty($oFile))
return $aError;
if(!$oFile->delete('modules/' . $this->_aConfig['home_dir']))
return $aError;
return array(
'message' => '', //_t('_adm_msg_modules_success_delete'),
'result' => true
);
}
public function recompile($aParams)
{
$oLanguages = BxDolStudioLanguagesUtils::getInstance();
$aResult = array('message' => '', 'result' => false);
$aLanguages = $this->oDb->getLanguages();
if (isAdmin() && !empty($aLanguages)) {
$this->_updateLanguage(false, current($aLanguages));
$bResult = false;
foreach($aLanguages as $aLanguage) {
$bResult = $this->_updateLanguage(true, $aLanguage) && $oLanguages->compileLanguage($aLanguage['id']);
$aResult['message'] .= $aLanguage['title'] . ': <span style="color:' . ($bResult ? 'green' : 'red') . '">' . _t($bResult ? '_adm_txt_modules_process_action_success' : '_adm_txt_modules_process_action_failed') . '</span><br />';
$aResult['result'] |= $bResult;
}
}
return $aResult;
}
public function enable($aParams)
{
//--- Auto disable before enable ---//
$this->disable($aParams);
$aModule = $this->oDb->getModuleByUri($this->_aConfig['home_uri']);
//--- Check whether the module is installed ---//
if(empty($aModule) || !is_array($aModule))
return array(
'message' => _t('_adm_err_modules_module_not_installed'),
'result' => false
);
//--- Check whether the module is already enabled ---//
if((int)$aModule['enabled'] != 0)
return array(
'message' => _t('_adm_err_modules_already_enabled'),
'result' => false
);
$aResult = array();
if(!empty($this->_aConfig['before_enable'])) {
$aResult = $this->_perform('before_enable', $aParams);
if($aResult && !$aResult['result'])
return $aResult;
}
$aResult = array();
bx_alert('system', 'before_enable', 0, false, array ('config' => $this->_aConfig, 'result' => &$aResult));
if ($aResult && !$aResult['result'])
return $aResult;
$aResultBefore = $this->_onEnableBefore();
if($aResultBefore !== BX_DOL_STUDIO_INSTALLER_SUCCESS)
return array(
'message' => $aResultBefore['content'],
'result' => false
);
$aResult = $this->_perform('enable', $aParams);
if($aResult['result']) {
$this->oDb->enableModuleByUri($aModule['uri']);
$this->cleanupMemoryAfterAction($aModule['uri'], $aModule['id']);
$this->_onEnableAfter();
if(!empty($this->_aConfig['enable_success']))
$this->_perform('enable_success', $aParams);
}
else {
if(!empty($this->_aConfig['enable_failed']))
$this->_perform('enable_failed', $aParams);
}
setParam('sys_revision', 1 + getParam('sys_revision'));
bx_alert('system', 'enable', 0, false, array ('config' => $this->_aConfig, 'result' => &$aResult));
return $aResult;
}
public function disable($aParams)
{
$bHtmlResponce = isset($aParams['html_response']) && (bool)$aParams['html_response'];
$aModule = $this->oDb->getModuleByUri($this->_aConfig['home_uri']);
//--- Check whether the module is installed ---//
if(empty($aModule) || !is_array($aModule))
return array(
'message' => _t('_adm_err_modules_module_not_installed'),
'result' => false
);
//--- Check whether the module is already disabled ---//
if((int)$aModule['enabled'] == 0)
return array(
'message' => _t('_adm_err_modules_already_disabled'),
'result' => false
);
$aResult = array();
if(!empty($this->_aConfig['before_disable'])) {
$aResult = $this->_perform('before_disable', $aParams);
if($aResult && !$aResult['result'])
return $aResult;
}
$aResult = array();
bx_alert('system', 'before_disable', 0, false, array ('config' => $this->_aConfig, 'result' => &$aResult));
if ($aResult && !$aResult['result'])
return $aResult;
//--- Check for dependent modules ---//
$bDependent = false;
$aDependents = $this->oDb->getDependent($this->_aConfig['name'], $this->_aConfig['home_uri']);
if(is_array($aDependents) && !empty($aDependents)) {
$bDependent = true;
$sMessage = '<br />' . _t('_adm_err_modules_wrong_dependency_disable') . '<br />';
foreach($aDependents as $aDependent)
$sMessage .= $aDependent['title'] . '<br />';
}
if($bDependent)
return array(
'message' => $this->_displayResult('check_dependencies', false, $sMessage, $bHtmlResponce),
'result' => false
);
$aResultBefore = $this->_onDisableBefore();
if($aResultBefore !== BX_DOL_STUDIO_INSTALLER_SUCCESS)
return array(
'message' => $aResultBefore['content'],
'result' => false
);
$aResult = $this->_perform('disable', $aParams);
if($aResult['result']) {
$this->oDb->disableModuleByUri($aModule['uri']);
$this->cleanupMemoryAfterAction($aModule['uri'], $aModule['id']);
$this->_onDisableAfter();
if(!empty($this->_aConfig['disable_success']))
$this->_perform('disable_success', $aParams);
}
else {
if(!empty($this->_aConfig['disable_failed']))
$this->_perform('disable_failed', $aParams);
}
bx_alert('system', 'disable', 0, false, array ('config' => $this->_aConfig, 'result' => &$aResult));
return $aResult;
}
//--- Get/Set Methods ---//
public function getVendor()
{
return $this->_aConfig['vendor'];
}
public function getName()
{
return $this->_aConfig['name'];
}
public function getTitle()
{
return $this->_aConfig['title'];
}
public function getHomeDir()
{
return $this->_aConfig['home_dir'];
}
//--- Action Methods ---//
protected function actionOperationFailed($mixedResult)
{
return _t('_adm_err_modules_process_action_failed');
}
protected function actionCheckDependencies($sOperation)
{
$sContent = '';
if(in_array($sOperation, array('install', 'enable', 'update'))) {
if(!isset($this->_aConfig['dependencies']) || !is_array($this->_aConfig['dependencies']))
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
foreach($this->_aConfig['dependencies'] as $sModule => $sModuleTitle) {
if($this->oDb->isModule($sModule) && $this->oDb->isEnabled($sModule))
continue;
if($this->oDb->isModuleByName($sModule) && $this->oDb->isEnabledByName($sModule))
continue;
$sContent .= $sModuleTitle . '<br />';
}
if(!empty($sContent))
$sContent = '<br />' . _t('_adm_err_modules_wrong_dependency_install') . '<br />' . $sContent;
}
return empty($sContent) ? BX_DOL_STUDIO_INSTALLER_SUCCESS : array('code' => BX_DOL_STUDIO_INSTALLER_FAILED, 'content' => $sContent);
}
protected function actionCheckDependenciesFailed($mixedResult)
{
return $mixedResult['content'];
}
protected function actionShowIntroduction($sOperation)
{
if(!isset($this->_aConfig[$sOperation . '_info']['introduction']))
return BX_DOL_STUDIO_INSTALLER_FAILED;
$sPath = $this->_sHomePath . 'install/info/' . $this->_aConfig[$sOperation . '_info']['introduction'];
return file_exists($sPath) ? array("code" => BX_DOL_STUDIO_INSTALLER_SUCCESS, "content" => file_get_contents($sPath)) : BX_DOL_STUDIO_INSTALLER_FAILED;
}
protected function actionShowConclusion($sOperation)
{
if(!isset($this->_aConfig[$sOperation . '_info']['conclusion']))
return BX_DOL_STUDIO_INSTALLER_FAILED;
$sPath = $this->_sHomePath . 'install/info/' . $this->_aConfig[$sOperation . '_info']['conclusion'];
return file_exists($sPath) ? array("code" => BX_DOL_STUDIO_INSTALLER_SUCCESS, "content" => file_get_contents($sPath)) : BX_DOL_STUDIO_INSTALLER_FAILED;
}
protected function actionMoveSources($sOperation)
{
$oFile = $this->_getFileManager();
$aInstalled = array_merge(array('system'), $this->oDb->getModulesUri());
$bResult = true;
foreach($this->_aConfig['includes'] as $sUri => $sPath) {
if(!in_array($sUri, $aInstalled) || empty($sPath))
continue;
if($sOperation == 'install') {
$sSrcPath = 'modules/' . $this->_aConfig['home_dir'] . 'install/data/' . $sPath;
$sDstPath = $sPath;
$bResult &= $oFile->copy($sSrcPath, $sDstPath);
} else if($sOperation == 'uninstall')
$bResult &= $oFile->delete($sPath);
}
return $bResult ? BX_DOL_STUDIO_INSTALLER_SUCCESS : BX_DOL_STUDIO_INSTALLER_FAILED;
}
protected function actionExecuteSql($sOperation)
{
switch($sOperation) {
case 'install':
$this->actionExecuteSql('disable');
$this->actionExecuteSql('uninstall');
break;
case 'enable':
$this->actionExecuteSql('disable');
break;
}
$mixedResult = $this->oDb->executeSQL($this->_sHomePath . 'install/sql/' . $sOperation . '.sql', $this->getMarkersForDb());
return $mixedResult === true ? BX_DOL_STUDIO_INSTALLER_SUCCESS : array('code' => BX_DOL_STUDIO_INSTALLER_FAILED, 'content' => $mixedResult);
}
protected function actionExecuteSqlFailed($mixedResult)
{
if(is_int($mixedResult))
return $this->actionOperationFailed($mixedResult);
$sResult = _t('_adm_err_modules_wrong_mysql_query') . '<br />';
foreach($mixedResult['content'] as $aQuery) {
$sResult .= _t('_adm_err_modules_wrong_mysql_query_msg', $aQuery['error']) . '<br />';
$sResult .= '<pre>' . $aQuery['query'] . '</pre>';
}
return $sResult;
}
protected function actionInstallLanguage($sOperation)
{
$oLanguages = BxDolStudioLanguagesUtils::getInstance();
$sLanguage = isset($this->_aConfig['home_uri']) ? $this->_aConfig['home_uri'] : '';
$bResult = true;
if($sOperation == 'install')
$bResult = $oLanguages->installLanguage(array('name' => $this->_aConfig['name'], 'path' => $this->_aConfig['home_dir'], 'uri' => $this->_aConfig['home_uri'], 'lang_category' => $this->_aConfig['language_category']), false);
return $bResult && $oLanguages->compileLanguage(0, true) ? BX_DOL_STUDIO_INSTALLER_SUCCESS : BX_DOL_STUDIO_INSTALLER_FAILED;
}
protected function actionUpdateLanguages($sOperation)
{
if(!isset($this->_aConfig['language_category']) || empty($this->_aConfig['language_category']))
return BX_DOL_STUDIO_INSTALLER_FAILED;
$oLanguages = BxDolStudioLanguagesUtils::getInstance();
$bResult = true;
$aResult = array();
//--- Process Language Category ---//
if($sOperation == 'install')
$iCategoryId = $oLanguages->addLanguageCategory($this->_aConfig['language_category']);
//--- Process languages' key=>value pears ---//
$aModule = array(
'name' => $this->_aConfig['name'],
'path' => $this->_aConfig['home_dir'],
'uri' => $this->_aConfig['home_uri'],
'lang_category' => $this->_aConfig['language_category']
);
if($sOperation == 'install')
$bResult = $oLanguages->restoreLanguage(0, $aModule, false);
else if($sOperation == 'uninstall')
$bResult = $oLanguages->removeLanguageByModule($aModule, false);
if($sOperation == 'uninstall' && $bResult)
$oLanguages->deleteLanguageCategory($this->_aConfig['language_category']);
return $bResult && $oLanguages->compileLanguage(0, true) ? BX_DOL_STUDIO_INSTALLER_SUCCESS : BX_DOL_STUDIO_INSTALLER_FAILED;
}
/**
* NOTE. The action is ONLY needed for dependent module to let
* Notifications based module(s) know that he(they) should
* update (request and save) handlers from this dependent module.
*/
protected function actionUpdateRelations($sOperation)
{
if(!in_array($sOperation, array('install', 'uninstall', 'enable', 'disable')))
return BX_DOL_STUDIO_INSTALLER_FAILED;
if(empty($this->_aConfig['relations']) || !is_array($this->_aConfig['relations']))
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
foreach($this->_aConfig['relations'] as $sModule) {
if(!$this->oDb->isModuleByName($sModule))
continue;
$aRelation = $this->oDb->getRelationsBy(array('type' => 'module', 'value' => $sModule));
if(empty($aRelation) || empty($aRelation['on_' . $sOperation]) || !BxDolRequest::serviceExists($aRelation['module'], $aRelation['on_' . $sOperation]))
continue;
BxDolService::call($aRelation['module'], $aRelation['on_' . $sOperation], array($this->_aConfig['home_uri']));
}
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
/**
* NOTE. The action is ONLY needed for Notifications based modules
* to update (request and save) handlers from all dependent modules.
*/
protected function actionUpdateRelationsForAll($sOperation)
{
if(!in_array($sOperation, array('enable', 'disable')))
return BX_DOL_STUDIO_INSTALLER_FAILED;
if($sOperation == 'enable')
$this->oDb->insertRelation($this->_aConfig['name'], $this->_aConfig['relation_handlers']);
$aRelation = $this->oDb->getRelationsBy(array('type' => 'module', 'value' => $this->_aConfig['name']));
if(empty($aRelation) || empty($aRelation['on_' . $sOperation]))
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
$aModules = $this->oDb->getModulesBy(array('type' => 'all', 'active' => 1));
foreach($aModules as $aModule) {
$aConfig = self::getModuleConfig($aModule);
if(!empty($aConfig['relations']) && is_array($aConfig['relations']) && in_array($this->_aConfig['name'], $aConfig['relations']))
BxDolService::call($this->_aConfig['name'], $aRelation['on_' . $sOperation], array($aModule['uri']));
}
if($sOperation == 'disable')
$this->oDb->deleteRelation($this->_aConfig['name']);
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
/**
*
* Connections objects associated with module data. It must be defined which content is associated with the connection.
* The key is connection object name and value is array (possible array values: type, conn, table, field_id).
* If 'type' == 'profiles', then it is considered profiles connection and other possible param is 'conn' ('initiator', 'content' or 'both')
* If 'type' == 'custom' (or ommited), then other possible params are 'conn', 'table' and 'field_id'
* @param string $sOperation - operation type.
*/
protected function actionProcessConnections($sOperation)
{
if(!in_array($sOperation, array('uninstall')) || empty($this->_aConfig['connections']))
return BX_DOL_STUDIO_INSTALLER_FAILED;
foreach($this->_aConfig['connections'] as $sObjectConnections => $a) {
$o = BxDolConnection::getObjectInstance($sObjectConnections);
if(!$o)
continue;
$sFuncSuffix = 'DeleteInitiatorAndContent';
if (isset($a['conn']) && 'initiator' == $a['conn'])
$sFuncSuffix = 'DeleteInitiator';
elseif (isset($a['conn']) && 'content' == $a['conn'])
$sFuncSuffix = 'DeleteContent';
if (isset($a['type']) && 'profiles' == $a['type']) {
$sFunc = 'onModuleProfile' . $sFuncSuffix;
$o->$sFunc($this->_aConfig['name']);
} else {
$sFunc = 'onModule' . $sFuncSuffix;
$o->$sFunc($a['table'], $a['field_id']);
}
}
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
/**
*
* Process the list of menu triggers provided in config array.
* It must be specified in the module which adds menu item and in modules where menu items are added, @see BxDolMenu::processMenuTrigger
* @param string $sOperation - operation type.
*/
protected function actionProcessMenuTriggers($sOperation)
{
if(empty($this->_aConfig['menu_triggers']))
return BX_DOL_STUDIO_INSTALLER_FAILED;
foreach($this->_aConfig['menu_triggers'] as $sMenuTriggerName)
BxDolMenu::processMenuTrigger($sMenuTriggerName);
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
/**
*
* Process the list of page triggers provided in config array.
* It must be specified in the module which adds page block and in modules where page blocks are added, @see BxDolPage::processPageTrigger
* @param string $sOperation - operation type.
*/
protected function actionProcessPageTriggers($sOperation)
{
if(empty($this->_aConfig['page_triggers']))
return BX_DOL_STUDIO_INSTALLER_FAILED;
foreach($this->_aConfig['page_triggers'] as $sPageTriggerName)
BxDolPage::processPageTrigger($sPageTriggerName);
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
protected function actionProcessDeletedProfiles($sOperation)
{
if(!in_array($sOperation, array('install', 'uninstall', 'enable', 'disable')))
return BX_DOL_STUDIO_INSTALLER_FAILED;
$o = BxDolProfileQuery::getInstance();
$o->processDeletedProfiles();
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
/**
*
* Process the list of extended search forms provided in config array.
* @param string $sOperation - operation type.
*/
protected function actionProcessEsearches($sOperation)
{
if(empty($this->_aConfig['esearches']))
return BX_DOL_STUDIO_INSTALLER_FAILED;
foreach($this->_aConfig['esearches'] as $sObject) {
if(in_array($sOperation, array('install', 'enable', 'enable_success')))
BxDolSearchExtended::getObjectInstance($sObject);
else if(in_array($sOperation, array('uninstall', 'disable')))
BxDolSearchExtended::getObjectInstance($sObject)->clean();
}
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
/**
*
* Process the list of transcoders provided in config array.
* Transcoder objects to automatically register/unregister necessary alerts for.
* @param string $sOperation - operation type.
*/
protected function actionRegisterTranscoders($sOperation)
{
if(empty($this->_aConfig['transcoders']))
return BX_DOL_STUDIO_INSTALLER_FAILED;
BxDolTranscoderImage::registerHandlersArray($this->_aConfig['transcoders']);
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
/**
*
* Process the list of transcoders provided in config array.
* Transcoder objects to automatically register/unregister necessary alerts for.
* @param string $sOperation - operation type.
*/
protected function actionUnregisterTranscoders($sOperation)
{
if(empty($this->_aConfig['transcoders']))
return BX_DOL_STUDIO_INSTALLER_FAILED;
BxDolTranscoderImage::unregisterHandlersArray($this->_aConfig['transcoders']);
BxDolTranscoderImage::cleanupObjectsArray($this->_aConfig['transcoders']);
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
protected function actionClearDbCache($sOperation)
{
$oCache = $this->oDb->getDbCacheObject();
$bResult = $oCache->removeAllByPrefix('db_');
$bResult &= $this->oDb->cleanMemoryAll();
$aKeys = array_keys($GLOBALS);
$aKeysPrefixes = array('bx_dol_cache_memory_');
foreach($aKeysPrefixes as $sKeyPrefix)
foreach($aKeys as $sKey)
if(substr($sKey, 0, strlen($sKeyPrefix)) == $sKeyPrefix)
unset($GLOBALS[$sKey]);
return $bResult ? BX_DOL_STUDIO_INSTALLER_SUCCESS : BX_DOL_STUDIO_INSTALLER_FAILED;
}
protected function actionClearTemplateCache($sOperation)
{
$aCaches = array('template', 'css', 'js');
$oCacheUtilities = BxDolCacheUtilities::getInstance();
foreach($aCaches as $sCache) {
$aResult = $oCacheUtilities->clear($sCache);
if($aResult === false)
continue;
if(isset($aResult['code']) && $aResult['code'] != 0)
return BX_DOL_STUDIO_INSTALLER_FAILED;
}
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
protected function _onInstallBefore()
{
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
protected function _onInstallAfter()
{
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
protected function _onEnableBefore()
{
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
protected function _onEnableAfter()
{
BxDolCmts::onModuleEnable($this->_aConfig['name']);
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
protected function _onDisableBefore()
{
BxDolCmts::onModuleDisable($this->_aConfig['name']);
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
protected function _onDisableAfter()
{
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
protected function _onUninstallBefore()
{
// check if module is already waiting while files are deleting
if(self::isModulePendingUninstall($this->_aConfig['home_uri']))
return array(
'code' => BX_DOL_STUDIO_INSTALLER_FAILED,
'content' => _t('_adm_err_modules_pending_uninstall_already'),
);
$bSetModulePendingUninstall = false;
// delete comments and queue for deletion comments attachments
$iFiles = 0;
BxDolCmts::onModuleUninstall($this->_aConfig['name'], $iFiles);
if($iFiles)
$bSetModulePendingUninstall = true;
// queue for deletion storage files
if(!empty($this->_aConfig['storages']) && is_array($this->_aConfig['storages']))
foreach($this->_aConfig['storages'] as $s)
if(($o = BxDolStorage::getObjectInstance($s)) && $o->queueFilesForDeletionFromObject())
$bSetModulePendingUninstall = true;
// if some files were added to the queue, set module as pending uninstall
if ($bSetModulePendingUninstall) {
self::setModulePendingUninstall($this->_aConfig['home_uri']);
return array(
'code' => BX_DOL_STUDIO_INSTALLER_FAILED,
'content' => _t('_adm_err_modules_pending_uninstall'),
);
}
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
protected function _onUninstallAfter()
{
return BX_DOL_STUDIO_INSTALLER_SUCCESS;
}
protected function _perform($sOperationName, $aParams = array())
{
$bHtmlResponce = isset($aParams['html_response']) && (bool)$aParams['html_response'];
if(!defined('BX_SKIP_INSTALL_CHECK') && !defined('BX_DOL_CRON_EXECUTE') && !$GLOBALS['logged']['admin'])
return array('message' => '_adm_mod_err_only_admin_can_perform_operations_with_modules', 'result' => false);
$sMessage = '';
foreach($this->_aConfig[$sOperationName] as $sAction => $iEnabled) {
$sMethod = 'action' . bx_gen_method_name($sAction);
if($iEnabled == 0 || !method_exists($this, $sMethod))
continue;
$mixedResult = $this->$sMethod($sOperationName);
//--- On Success ---//
if((is_int($mixedResult) && (int)$mixedResult == BX_DOL_STUDIO_INSTALLER_SUCCESS) || (isset($mixedResult['code']) && (int)$mixedResult['code'] == BX_DOL_STUDIO_INSTALLER_SUCCESS)) {
$sMessage .= $this->_displayResult($sAction, true, isset($mixedResult['content']) ? $mixedResult['content'] : '', $bHtmlResponce);
continue;
}
//--- On Failed ---//
$sMethodFailed = $sMethod . 'Failed';
return array('message' => $this->_displayResult($sAction, false, method_exists($this, $sMethodFailed) ? $this->$sMethodFailed($mixedResult) : $this->actionOperationFailed($mixedResult), $bHtmlResponce), 'result' => false);
}
if($this->_bShowOnSuccess)
$sMessage = $this->_aActions['perform_' . $sOperationName]['success'] . $sMessage;
return array('message' => $sMessage, 'result' => true);
}
protected function _displayResult($sAction, $bResult, $sResult = '', $bHtmlResponse = true)
{
if($bResult && !in_array($sAction, array('show_introduction', 'show_conclusion')) && !$this->_bShowOnSuccess)
return '';
$sTitle = $this->_aActions[$sAction]['title'] . ' ';
if(!empty($sResult))
$sResult = (substr($sResult, 0, 1) == '_' ? _t($sResult) : $sResult);
$sContent = !empty($sResult) ? $sResult : _t($bResult ? '_adm_txt_modules_process_action_success' : '_adm_err_modules_process_action_failed');
if(!$bHtmlResponse)
return $sTitle . $sContent;
return BxDolStudioTemplate::getInstance()->parseHtmlByName('mod_action_result_step.html', array(
'color' => $bResult ? 'green' : 'red',
'title' => $sTitle,
'content' => $sContent
));
}
protected function _getFileManager()
{
$oFile = null;
if($this->_bUseFtp) {
$oFile = new BxDolFtp(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost', getParam('sys_ftp_login'), getParam('sys_ftp_password'), getParam('sys_ftp_dir'));
if(!$oFile->connect())
return null;
if(!$oFile->isUna())
return null;
}
else
$oFile = BxDolFile::getInstance();
return $oFile;
}
protected function _isCompatibleWith()
{
$sVersionCur = bx_get_ver();
$bCompatible = false;
if(isset($this->_aConfig['compatible_with']) && is_array($this->_aConfig['compatible_with']))
foreach($this->_aConfig['compatible_with'] as $iKey => $sVersionReq)
$bCompatible = $bCompatible || (version_compare($sVersionCur, $sVersionReq, '>=') == 1);
return $bCompatible;
}
protected function filePathWithoutBase($sPath)
{
return bx_ltrim_str($sPath, $this->_sModulePath);
}
protected function getMarkersForDb()
{
return array(
'from' => array('{db_name}'),
'to' => array(defined('BX_DATABASE_NAME') ? BX_DATABASE_NAME : ''),
);
}
protected function cleanupMemoryAfterAction($sModuleUri, $iModuleId)
{
$this->oDb->cleanMemory('sys_modules_' . $sModuleUri);
$this->oDb->cleanMemory('sys_modules_' . $iModuleId);
$this->oDb->cleanMemory('sys_modules');
$this->oDb->cleanMemory('sys_modules_modules');
$this->oDb->cleanMemory('sys_modules_modules_active');
}
}
/** @} */
| unaio/una | upgrade/files/9.0.0.RC10-9.0.0.RC11/files/studio/classes/BxDolStudioInstaller.php | PHP | mit | 39,820 |
<?php
namespace Illuminate\Database\Eloquent;
use Exception;
use ArrayAccess;
use JsonSerializable;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Routing\UrlRoutable;
use Illuminate\Contracts\Queue\QueueableEntity;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Contracts\Queue\QueueableCollection;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\ConnectionResolverInterface as Resolver;
abstract class Model implements ArrayAccess, Arrayable, Jsonable, JsonSerializable, QueueableEntity, UrlRoutable
{
use Concerns\HasAttributes,
Concerns\HasEvents,
Concerns\HasGlobalScopes,
Concerns\HasRelationships,
Concerns\HasTimestamps,
Concerns\HidesAttributes,
Concerns\GuardsAttributes;
/**
* The connection name for the model.
*
* @var string
*/
protected $connection;
/**
* The table associated with the model.
*
* @var string
*/
protected $table;
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = 'id';
/**
* The "type" of the auto-incrementing ID.
*
* @var string
*/
protected $keyType = 'int';
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = true;
/**
* The relations to eager load on every query.
*
* @var array
*/
protected $with = [];
/**
* The relationship counts that should be eager loaded on every query.
*
* @var array
*/
protected $withCount = [];
/**
* The number of models to return for pagination.
*
* @var int
*/
protected $perPage = 15;
/**
* Indicates if the model exists.
*
* @var bool
*/
public $exists = false;
/**
* Indicates if the model was inserted during the current request lifecycle.
*
* @var bool
*/
public $wasRecentlyCreated = false;
/**
* The connection resolver instance.
*
* @var \Illuminate\Database\ConnectionResolverInterface
*/
protected static $resolver;
/**
* The event dispatcher instance.
*
* @var \Illuminate\Contracts\Events\Dispatcher
*/
protected static $dispatcher;
/**
* The array of booted models.
*
* @var array
*/
protected static $booted = [];
/**
* The array of global scopes on the model.
*
* @var array
*/
protected static $globalScopes = [];
/**
* The name of the "created at" column.
*
* @var string
*/
const CREATED_AT = 'created_at';
/**
* The name of the "updated at" column.
*
* @var string
*/
const UPDATED_AT = 'updated_at';
/**
* Create a new Eloquent model instance.
*
* @param array $attributes
* @return void
*/
public function __construct(array $attributes = [])
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
/**
* Check if the model needs to be booted and if so, do it.
*
* @return void
*/
protected function bootIfNotBooted()
{
if (! isset(static::$booted[static::class])) {
static::$booted[static::class] = true;
$this->fireModelEvent('booting', false);
static::boot();
$this->fireModelEvent('booted', false);
}
}
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
static::bootTraits();
}
/**
* Boot all of the bootable traits on the model.
*
* @return void
*/
protected static function bootTraits()
{
$class = static::class;
foreach (class_uses_recursive($class) as $trait) {
if (method_exists($class, $method = 'boot'.class_basename($trait))) {
forward_static_call([$class, $method]);
}
}
}
/**
* Clear the list of booted models so they will be re-booted.
*
* @return void
*/
public static function clearBootedModels()
{
static::$booted = [];
static::$globalScopes = [];
}
/**
* Fill the model with an array of attributes.
*
* @param array $attributes
* @return $this
*
* @throws \Illuminate\Database\Eloquent\MassAssignmentException
*/
public function fill(array $attributes)
{
$totallyGuarded = $this->totallyGuarded();
foreach ($this->fillableFromArray($attributes) as $key => $value) {
$key = $this->removeTableFromKey($key);
// The developers may choose to place some attributes in the "fillable" array
// which means only those attributes may be set through mass assignment to
// the model, and all others will just get ignored for security reasons.
if ($this->isFillable($key)) {
$this->setAttribute($key, $value);
} elseif ($totallyGuarded) {
throw new MassAssignmentException(sprintf(
'Add [%s] to fillable property to allow mass assignment on [%s].',
$key, get_class($this)
));
}
}
return $this;
}
/**
* Fill the model with an array of attributes. Force mass assignment.
*
* @param array $attributes
* @return $this
*/
public function forceFill(array $attributes)
{
return static::unguarded(function () use ($attributes) {
return $this->fill($attributes);
});
}
/**
* Qualify the given column name by the model's table.
*
* @param string $column
* @return string
*/
public function qualifyColumn($column)
{
if (Str::contains($column, '.')) {
return $column;
}
return $this->getTable().'.'.$column;
}
/**
* Remove the table name from a given key.
*
* @param string $key
* @return string
*/
protected function removeTableFromKey($key)
{
return Str::contains($key, '.') ? last(explode('.', $key)) : $key;
}
/**
* Create a new instance of the given model.
*
* @param array $attributes
* @param bool $exists
* @return static
*/
public function newInstance($attributes = [], $exists = false)
{
// This method just provides a convenient way for us to generate fresh model
// instances of this current model. It is particularly useful during the
// hydration of new objects via the Eloquent query builder instances.
$model = new static((array) $attributes);
$model->exists = $exists;
$model->setConnection(
$this->getConnectionName()
);
return $model;
}
/**
* Create a new model instance that is existing.
*
* @param array $attributes
* @param string|null $connection
* @return static
*/
public function newFromBuilder($attributes = [], $connection = null)
{
$model = $this->newInstance([], true);
$model->setRawAttributes((array) $attributes, true);
$model->setConnection($connection ?: $this->getConnectionName());
$model->fireModelEvent('retrieved', false);
return $model;
}
/**
* Begin querying the model on a given connection.
*
* @param string|null $connection
* @return \Illuminate\Database\Eloquent\Builder
*/
public static function on($connection = null)
{
// First we will just create a fresh instance of this model, and then we can
// set the connection on the model so that it is be used for the queries
// we execute, as well as being set on each relationship we retrieve.
$instance = new static;
$instance->setConnection($connection);
return $instance->newQuery();
}
/**
* Begin querying the model on the write connection.
*
* @return \Illuminate\Database\Query\Builder
*/
public static function onWriteConnection()
{
$instance = new static;
return $instance->newQuery()->useWritePdo();
}
/**
* Get all of the models from the database.
*
* @param array|mixed $columns
* @return \Illuminate\Database\Eloquent\Collection|static[]
*/
public static function all($columns = ['*'])
{
return (new static)->newQuery()->get(
is_array($columns) ? $columns : func_get_args()
);
}
/**
* Begin querying a model with eager loading.
*
* @param array|string $relations
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public static function with($relations)
{
return (new static)->newQuery()->with(
is_string($relations) ? func_get_args() : $relations
);
}
/**
* Eager load relations on the model.
*
* @param array|string $relations
* @return $this
*/
public function load($relations)
{
$query = $this->newQueryWithoutRelationships()->with(
is_string($relations) ? func_get_args() : $relations
);
$query->eagerLoadRelations([$this]);
return $this;
}
/**
* Eager load relations on the model if they are not already eager loaded.
*
* @param array|string $relations
* @return $this
*/
public function loadMissing($relations)
{
$relations = is_string($relations) ? func_get_args() : $relations;
return $this->load(array_filter($relations, function ($relation) {
return ! $this->relationLoaded($relation);
}));
}
/**
* Increment a column's value by a given amount.
*
* @param string $column
* @param int $amount
* @param array $extra
* @return int
*/
protected function increment($column, $amount = 1, array $extra = [])
{
return $this->incrementOrDecrement($column, $amount, $extra, 'increment');
}
/**
* Decrement a column's value by a given amount.
*
* @param string $column
* @param int $amount
* @param array $extra
* @return int
*/
protected function decrement($column, $amount = 1, array $extra = [])
{
return $this->incrementOrDecrement($column, $amount, $extra, 'decrement');
}
/**
* Run the increment or decrement method on the model.
*
* @param string $column
* @param int $amount
* @param array $extra
* @param string $method
* @return int
*/
protected function incrementOrDecrement($column, $amount, $extra, $method)
{
$query = $this->newQuery();
if (! $this->exists) {
return $query->{$method}($column, $amount, $extra);
}
$this->incrementOrDecrementAttributeValue($column, $amount, $extra, $method);
return $query->where(
$this->getKeyName(), $this->getKey()
)->{$method}($column, $amount, $extra);
}
/**
* Increment the underlying attribute value and sync with original.
*
* @param string $column
* @param int $amount
* @param array $extra
* @param string $method
* @return void
*/
protected function incrementOrDecrementAttributeValue($column, $amount, $extra, $method)
{
$this->{$column} = $this->{$column} + ($method == 'increment' ? $amount : $amount * -1);
$this->forceFill($extra);
$this->syncOriginalAttribute($column);
}
/**
* Update the model in the database.
*
* @param array $attributes
* @param array $options
* @return bool
*/
public function update(array $attributes = [], array $options = [])
{
if (! $this->exists) {
return false;
}
return $this->fill($attributes)->save($options);
}
/**
* Save the model and all of its relationships.
*
* @return bool
*/
public function push()
{
if (! $this->save()) {
return false;
}
// To sync all of the relationships to the database, we will simply spin through
// the relationships and save each model via this "push" method, which allows
// us to recurse into all of these nested relations for the model instance.
foreach ($this->relations as $models) {
$models = $models instanceof Collection
? $models->all() : [$models];
foreach (array_filter($models) as $model) {
if (! $model->push()) {
return false;
}
}
}
return true;
}
/**
* Save the model to the database.
*
* @param array $options
* @return bool
*/
public function save(array $options = [])
{
$query = $this->newQueryWithoutScopes();
// If the "saving" event returns false we'll bail out of the save and return
// false, indicating that the save failed. This provides a chance for any
// listeners to cancel save operations if validations fail or whatever.
if ($this->fireModelEvent('saving') === false) {
return false;
}
// If the model already exists in the database we can just update our record
// that is already in this database using the current IDs in this "where"
// clause to only update this model. Otherwise, we'll just insert them.
if ($this->exists) {
$saved = $this->isDirty() ?
$this->performUpdate($query) : true;
}
// If the model is brand new, we'll insert it into our database and set the
// ID attribute on the model to the value of the newly inserted row's ID
// which is typically an auto-increment value managed by the database.
else {
$saved = $this->performInsert($query);
if (! $this->getConnectionName() &&
$connection = $query->getConnection()) {
$this->setConnection($connection->getName());
}
}
// If the model is successfully saved, we need to do a few more things once
// that is done. We will call the "saved" method here to run any actions
// we need to happen after a model gets successfully saved right here.
if ($saved) {
$this->finishSave($options);
}
return $saved;
}
/**
* Save the model to the database using transaction.
*
* @param array $options
* @return bool
*
* @throws \Throwable
*/
public function saveOrFail(array $options = [])
{
return $this->getConnection()->transaction(function () use ($options) {
return $this->save($options);
});
}
/**
* Perform any actions that are necessary after the model is saved.
*
* @param array $options
* @return void
*/
protected function finishSave(array $options)
{
$this->fireModelEvent('saved', false);
if ($this->isDirty() && ($options['touch'] ?? true)) {
$this->touchOwners();
}
$this->syncOriginal();
}
/**
* Perform a model update operation.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return bool
*/
protected function performUpdate(Builder $query)
{
// If the updating event returns false, we will cancel the update operation so
// developers can hook Validation systems into their models and cancel this
// operation if the model does not pass validation. Otherwise, we update.
if ($this->fireModelEvent('updating') === false) {
return false;
}
// First we need to create a fresh query instance and touch the creation and
// update timestamp on the model which are maintained by us for developer
// convenience. Then we will just continue saving the model instances.
if ($this->usesTimestamps()) {
$this->updateTimestamps();
}
// Once we have run the update operation, we will fire the "updated" event for
// this model instance. This will allow developers to hook into these after
// models are updated, giving them a chance to do any special processing.
$dirty = $this->getDirty();
if (count($dirty) > 0) {
$this->setKeysForSaveQuery($query)->update($dirty);
$this->fireModelEvent('updated', false);
$this->syncChanges();
}
return true;
}
/**
* Set the keys for a save update query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
protected function setKeysForSaveQuery(Builder $query)
{
$query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery());
return $query;
}
/**
* Get the primary key value for a save query.
*
* @return mixed
*/
protected function getKeyForSaveQuery()
{
return $this->original[$this->getKeyName()]
?? $this->getKey();
}
/**
* Perform a model insert operation.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return bool
*/
protected function performInsert(Builder $query)
{
if ($this->fireModelEvent('creating') === false) {
return false;
}
// First we'll need to create a fresh query instance and touch the creation and
// update timestamps on this model, which are maintained by us for developer
// convenience. After, we will just continue saving these model instances.
if ($this->usesTimestamps()) {
$this->updateTimestamps();
}
// If the model has an incrementing key, we can use the "insertGetId" method on
// the query builder, which will give us back the final inserted ID for this
// table from the database. Not all tables have to be incrementing though.
$attributes = $this->attributes;
if ($this->getIncrementing()) {
$this->insertAndSetId($query, $attributes);
}
// If the table isn't incrementing we'll simply insert these attributes as they
// are. These attribute arrays must contain an "id" column previously placed
// there by the developer as the manually determined key for these models.
else {
if (empty($attributes)) {
return true;
}
$query->insert($attributes);
}
// We will go ahead and set the exists property to true, so that it is set when
// the created event is fired, just in case the developer tries to update it
// during the event. This will allow them to do so and run an update here.
$this->exists = true;
$this->wasRecentlyCreated = true;
$this->fireModelEvent('created', false);
return true;
}
/**
* Insert the given attributes and set the ID on the model.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param array $attributes
* @return void
*/
protected function insertAndSetId(Builder $query, $attributes)
{
$id = $query->insertGetId($attributes, $keyName = $this->getKeyName());
$this->setAttribute($keyName, $id);
}
/**
* Destroy the models for the given IDs.
*
* @param array|int $ids
* @return int
*/
public static function destroy($ids)
{
// We'll initialize a count here so we will return the total number of deletes
// for the operation. The developers can then check this number as a boolean
// type value or get this total count of records deleted for logging, etc.
$count = 0;
$ids = is_array($ids) ? $ids : func_get_args();
// We will actually pull the models from the database table and call delete on
// each of them individually so that their events get fired properly with a
// correct set of attributes in case the developers wants to check these.
$key = ($instance = new static)->getKeyName();
foreach ($instance->whereIn($key, $ids)->get() as $model) {
if ($model->delete()) {
$count++;
}
}
return $count;
}
/**
* Delete the model from the database.
*
* @return bool|null
*
* @throws \Exception
*/
public function delete()
{
if (is_null($this->getKeyName())) {
throw new Exception('No primary key defined on model.');
}
// If the model doesn't exist, there is nothing to delete so we'll just return
// immediately and not do anything else. Otherwise, we will continue with a
// deletion process on the model, firing the proper events, and so forth.
if (! $this->exists) {
return;
}
if ($this->fireModelEvent('deleting') === false) {
return false;
}
// Here, we'll touch the owning models, verifying these timestamps get updated
// for the models. This will allow any caching to get broken on the parents
// by the timestamp. Then we will go ahead and delete the model instance.
$this->touchOwners();
$this->performDeleteOnModel();
// Once the model has been deleted, we will fire off the deleted event so that
// the developers may hook into post-delete operations. We will then return
// a boolean true as the delete is presumably successful on the database.
$this->fireModelEvent('deleted', false);
return true;
}
/**
* Force a hard delete on a soft deleted model.
*
* This method protects developers from running forceDelete when trait is missing.
*
* @return bool|null
*/
public function forceDelete()
{
return $this->delete();
}
/**
* Perform the actual delete query on this model instance.
*
* @return void
*/
protected function performDeleteOnModel()
{
$this->setKeysForSaveQuery($this->newQueryWithoutScopes())->delete();
$this->exists = false;
}
/**
* Begin querying the model.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public static function query()
{
return (new static)->newQuery();
}
/**
* Get a new query builder for the model's table.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function newQuery()
{
return $this->registerGlobalScopes($this->newQueryWithoutScopes());
}
/**
* Get a new query builder with no relationships loaded.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function newQueryWithoutRelationships()
{
return $this->registerGlobalScopes(
$this->newEloquentBuilder($this->newBaseQueryBuilder())->setModel($this)
);
}
/**
* Register the global scopes for this builder instance.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return \Illuminate\Database\Eloquent\Builder
*/
public function registerGlobalScopes($builder)
{
foreach ($this->getGlobalScopes() as $identifier => $scope) {
$builder->withGlobalScope($identifier, $scope);
}
return $builder;
}
/**
* Get a new query builder that doesn't have any global scopes.
*
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function newQueryWithoutScopes()
{
$builder = $this->newEloquentBuilder($this->newBaseQueryBuilder());
// Once we have the query builders, we will set the model instances so the
// builder can easily access any information it may need from the model
// while it is constructing and executing various queries against it.
return $builder->setModel($this)
->with($this->with)
->withCount($this->withCount);
}
/**
* Get a new query instance without a given scope.
*
* @param \Illuminate\Database\Eloquent\Scope|string $scope
* @return \Illuminate\Database\Eloquent\Builder
*/
public function newQueryWithoutScope($scope)
{
$builder = $this->newQuery();
return $builder->withoutGlobalScope($scope);
}
/**
* Get a new query to restore one or more models by their queueable IDs.
*
* @param array|int $ids
* @return \Illuminate\Database\Eloquent\Builder
*/
public function newQueryForRestoration($ids)
{
return is_array($ids)
? $this->newQueryWithoutScopes()->whereIn($this->getQualifiedKeyName(), $ids)
: $this->newQueryWithoutScopes()->whereKey($ids);
}
/**
* Create a new Eloquent query builder for the model.
*
* @param \Illuminate\Database\Query\Builder $query
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function newEloquentBuilder($query)
{
return new Builder($query);
}
/**
* Get a new query builder instance for the connection.
*
* @return \Illuminate\Database\Query\Builder
*/
protected function newBaseQueryBuilder()
{
$connection = $this->getConnection();
return new QueryBuilder(
$connection, $connection->getQueryGrammar(), $connection->getPostProcessor()
);
}
/**
* Create a new Eloquent Collection instance.
*
* @param array $models
* @return \Illuminate\Database\Eloquent\Collection
*/
public function newCollection(array $models = [])
{
return new Collection($models);
}
/**
* Create a new pivot model instance.
*
* @param \Illuminate\Database\Eloquent\Model $parent
* @param array $attributes
* @param string $table
* @param bool $exists
* @param string|null $using
* @return \Illuminate\Database\Eloquent\Relations\Pivot
*/
public function newPivot(self $parent, array $attributes, $table, $exists, $using = null)
{
return $using ? $using::fromRawAttributes($parent, $attributes, $table, $exists)
: Pivot::fromAttributes($parent, $attributes, $table, $exists);
}
/**
* Convert the model instance to an array.
*
* @return array
*/
public function toArray()
{
return array_merge($this->attributesToArray(), $this->relationsToArray());
}
/**
* Convert the model instance to JSON.
*
* @param int $options
* @return string
*
* @throws \Illuminate\Database\Eloquent\JsonEncodingException
*/
public function toJson($options = 0)
{
$json = json_encode($this->jsonSerialize(), $options);
if (JSON_ERROR_NONE !== json_last_error()) {
throw JsonEncodingException::forModel($this, json_last_error_msg());
}
return $json;
}
/**
* Convert the object into something JSON serializable.
*
* @return array
*/
public function jsonSerialize()
{
return $this->toArray();
}
/**
* Reload a fresh model instance from the database.
*
* @param array|string $with
* @return static|null
*/
public function fresh($with = [])
{
if (! $this->exists) {
return;
}
return static::newQueryWithoutScopes()
->with(is_string($with) ? func_get_args() : $with)
->where($this->getKeyName(), $this->getKey())
->first();
}
/**
* Reload the current model instance with fresh attributes from the database.
*
* @return $this
*/
public function refresh()
{
if (! $this->exists) {
return $this;
}
$this->setRawAttributes(
static::newQueryWithoutScopes()->findOrFail($this->getKey())->attributes
);
$this->load(collect($this->relations)->except('pivot')->keys()->toArray());
$this->syncOriginal();
return $this;
}
/**
* Clone the model into a new, non-existing instance.
*
* @param array|null $except
* @return \Illuminate\Database\Eloquent\Model
*/
public function replicate(array $except = null)
{
$defaults = [
$this->getKeyName(),
$this->getCreatedAtColumn(),
$this->getUpdatedAtColumn(),
];
$attributes = Arr::except(
$this->attributes, $except ? array_unique(array_merge($except, $defaults)) : $defaults
);
return tap(new static, function ($instance) use ($attributes) {
$instance->setRawAttributes($attributes);
$instance->setRelations($this->relations);
});
}
/**
* Determine if two models have the same ID and belong to the same table.
*
* @param \Illuminate\Database\Eloquent\Model|null $model
* @return bool
*/
public function is($model)
{
return ! is_null($model) &&
$this->getKey() === $model->getKey() &&
$this->getTable() === $model->getTable() &&
$this->getConnectionName() === $model->getConnectionName();
}
/**
* Determine if two models are not the same.
*
* @param \Illuminate\Database\Eloquent\Model|null $model
* @return bool
*/
public function isNot($model)
{
return ! $this->is($model);
}
/**
* Get the database connection for the model.
*
* @return \Illuminate\Database\Connection
*/
public function getConnection()
{
return static::resolveConnection($this->getConnectionName());
}
/**
* Get the current connection name for the model.
*
* @return string
*/
public function getConnectionName()
{
return $this->connection;
}
/**
* Set the connection associated with the model.
*
* @param string $name
* @return $this
*/
public function setConnection($name)
{
$this->connection = $name;
return $this;
}
/**
* Resolve a connection instance.
*
* @param string|null $connection
* @return \Illuminate\Database\Connection
*/
public static function resolveConnection($connection = null)
{
return static::$resolver->connection($connection);
}
/**
* Get the connection resolver instance.
*
* @return \Illuminate\Database\ConnectionResolverInterface
*/
public static function getConnectionResolver()
{
return static::$resolver;
}
/**
* Set the connection resolver instance.
*
* @param \Illuminate\Database\ConnectionResolverInterface $resolver
* @return void
*/
public static function setConnectionResolver(Resolver $resolver)
{
static::$resolver = $resolver;
}
/**
* Unset the connection resolver for models.
*
* @return void
*/
public static function unsetConnectionResolver()
{
static::$resolver = null;
}
/**
* Get the table associated with the model.
*
* @return string
*/
public function getTable()
{
if (! isset($this->table)) {
return str_replace(
'\\', '', Str::snake(Str::plural(class_basename($this)))
);
}
return $this->table;
}
/**
* Set the table associated with the model.
*
* @param string $table
* @return $this
*/
public function setTable($table)
{
$this->table = $table;
return $this;
}
/**
* Get the primary key for the model.
*
* @return string
*/
public function getKeyName()
{
return $this->primaryKey;
}
/**
* Set the primary key for the model.
*
* @param string $key
* @return $this
*/
public function setKeyName($key)
{
$this->primaryKey = $key;
return $this;
}
/**
* Get the table qualified key name.
*
* @return string
*/
public function getQualifiedKeyName()
{
return $this->qualifyColumn($this->getKeyName());
}
/**
* Get the auto-incrementing key type.
*
* @return string
*/
public function getKeyType()
{
return $this->keyType;
}
/**
* Set the data type for the primary key.
*
* @param string $type
* @return $this
*/
public function setKeyType($type)
{
$this->keyType = $type;
return $this;
}
/**
* Get the value indicating whether the IDs are incrementing.
*
* @return bool
*/
public function getIncrementing()
{
return $this->incrementing;
}
/**
* Set whether IDs are incrementing.
*
* @param bool $value
* @return $this
*/
public function setIncrementing($value)
{
$this->incrementing = $value;
return $this;
}
/**
* Get the value of the model's primary key.
*
* @return mixed
*/
public function getKey()
{
return $this->getAttribute($this->getKeyName());
}
/**
* Get the queueable identity for the entity.
*
* @return mixed
*/
public function getQueueableId()
{
return $this->getKey();
}
/**
* Get the queueable relationships for the entity.
*
* @return array
*/
public function getQueueableRelations()
{
$relations = [];
foreach ($this->getRelations() as $key => $relation) {
if (method_exists($this, $key)) {
$relations[] = $key;
}
if ($relation instanceof QueueableCollection) {
foreach ($relation->getQueueableRelations() as $collectionValue) {
$relations[] = $key.'.'.$collectionValue;
}
}
if ($relation instanceof QueueableEntity) {
foreach ($relation->getQueueableRelations() as $entityKey => $entityValue) {
$relations[] = $key.'.'.$entityValue;
}
}
}
return array_unique($relations);
}
/**
* Get the queueable connection for the entity.
*
* @return mixed
*/
public function getQueueableConnection()
{
return $this->getConnectionName();
}
/**
* Get the value of the model's route key.
*
* @return mixed
*/
public function getRouteKey()
{
return $this->getAttribute($this->getRouteKeyName());
}
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return $this->getKeyName();
}
/**
* Retrieve the model for a bound value.
*
* @param mixed $value
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function resolveRouteBinding($value)
{
return $this->where($this->getRouteKeyName(), $value)->first();
}
/**
* Get the default foreign key name for the model.
*
* @return string
*/
public function getForeignKey()
{
return Str::snake(class_basename($this)).'_'.$this->getKeyName();
}
/**
* Get the number of models to return per page.
*
* @return int
*/
public function getPerPage()
{
return $this->perPage;
}
/**
* Set the number of models to return per page.
*
* @param int $perPage
* @return $this
*/
public function setPerPage($perPage)
{
$this->perPage = $perPage;
return $this;
}
/**
* Dynamically retrieve attributes on the model.
*
* @param string $key
* @return mixed
*/
public function __get($key)
{
return $this->getAttribute($key);
}
/**
* Dynamically set attributes on the model.
*
* @param string $key
* @param mixed $value
* @return void
*/
public function __set($key, $value)
{
$this->setAttribute($key, $value);
}
/**
* Determine if the given attribute exists.
*
* @param mixed $offset
* @return bool
*/
public function offsetExists($offset)
{
return ! is_null($this->getAttribute($offset));
}
/**
* Get the value for a given offset.
*
* @param mixed $offset
* @return mixed
*/
public function offsetGet($offset)
{
return $this->getAttribute($offset);
}
/**
* Set the value for a given offset.
*
* @param mixed $offset
* @param mixed $value
* @return void
*/
public function offsetSet($offset, $value)
{
$this->setAttribute($offset, $value);
}
/**
* Unset the value for a given offset.
*
* @param mixed $offset
* @return void
*/
public function offsetUnset($offset)
{
unset($this->attributes[$offset], $this->relations[$offset]);
}
/**
* Determine if an attribute or relation exists on the model.
*
* @param string $key
* @return bool
*/
public function __isset($key)
{
return $this->offsetExists($key);
}
/**
* Unset an attribute on the model.
*
* @param string $key
* @return void
*/
public function __unset($key)
{
$this->offsetUnset($key);
}
/**
* Handle dynamic method calls into the model.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
if (in_array($method, ['increment', 'decrement'])) {
return $this->$method(...$parameters);
}
return $this->newQuery()->$method(...$parameters);
}
/**
* Handle dynamic static method calls into the method.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public static function __callStatic($method, $parameters)
{
return (new static)->$method(...$parameters);
}
/**
* Convert the model to its string representation.
*
* @return string
*/
public function __toString()
{
return $this->toJson();
}
/**
* When a model is being unserialized, check if it needs to be booted.
*
* @return void
*/
public function __wakeup()
{
$this->bootIfNotBooted();
}
}
| joecohens/framework | src/Illuminate/Database/Eloquent/Model.php | PHP | mit | 39,540 |
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using ECommon.Components;
using ECommon.Scheduling;
using ECommon.Socketing;
using EQueue.Protocols;
namespace EQueue.Broker.Client
{
public class ConsumerManager
{
private readonly ConcurrentDictionary<string, ConsumerGroup> _consumerGroupDict = new ConcurrentDictionary<string, ConsumerGroup>();
private readonly IScheduleService _scheduleService;
public ConsumerManager()
{
_scheduleService = ObjectContainer.Resolve<IScheduleService>();
}
public void Start()
{
_consumerGroupDict.Clear();
_scheduleService.StartTask("ScanNotActiveConsumer", ScanNotActiveConsumer, 1000, 1000);
}
public void Shutdown()
{
_consumerGroupDict.Clear();
_scheduleService.StopTask("ScanNotActiveConsumer");
}
public void RegisterConsumer(string groupName, string consumerId, IEnumerable<string> subscriptionTopics, IEnumerable<MessageQueueEx> consumingQueues, ITcpConnection connection)
{
var consumerGroup = _consumerGroupDict.GetOrAdd(groupName, key => new ConsumerGroup(key));
consumerGroup.RegisterConsumer(connection, consumerId, subscriptionTopics.ToList(), consumingQueues.ToList());
}
public void RemoveConsumer(string connectionId)
{
foreach (var consumerGroup in _consumerGroupDict.Values)
{
consumerGroup.RemoveConsumer(connectionId);
}
}
public int GetConsumerGroupCount()
{
return _consumerGroupDict.Count;
}
public IEnumerable<ConsumerGroup> GetAllConsumerGroups()
{
return _consumerGroupDict.Values.ToList();
}
public int GetAllConsumerCount()
{
return GetAllConsumerGroups().Sum(x => x.GetConsumerCount());
}
public ConsumerGroup GetConsumerGroup(string groupName)
{
ConsumerGroup consumerGroup;
if (_consumerGroupDict.TryGetValue(groupName, out consumerGroup))
{
return consumerGroup;
}
return null;
}
public int GetConsumerCount(string groupName)
{
ConsumerGroup consumerGroup;
if (_consumerGroupDict.TryGetValue(groupName, out consumerGroup))
{
return consumerGroup.GetConsumerCount();
}
return 0;
}
public int GetClientCacheMessageCount(string groupName, string topic, int queueId)
{
ConsumerGroup consumerGroup;
if (_consumerGroupDict.TryGetValue(groupName, out consumerGroup))
{
return consumerGroup.GetClientCacheMessageCount(topic, queueId);
}
return 0;
}
public bool IsConsumerActive(string consumerGroup, string consumerId)
{
var group = GetConsumerGroup(consumerGroup);
return group != null && group.IsConsumerActive(consumerId);
}
public bool IsConsumerExistForQueue(string topic, int queueId)
{
var groups = GetAllConsumerGroups();
foreach (var group in groups)
{
if (group.IsConsumerExistForQueue(topic, queueId))
{
return true;
}
}
return false;
}
private void ScanNotActiveConsumer()
{
foreach (var consumerGroup in _consumerGroupDict.Values)
{
consumerGroup.RemoveNotActiveConsumers();
}
}
}
}
| Aaron-Liu/equeue | src/EQueue/Broker/Client/ConsumerManager.cs | C# | mit | 3,773 |
<?php
namespace Phrest\Skeleton\v1\Requests\Users;
use Phrest\SDK\Request\AbstractRequest;
use Phrest\SDK\Request\RequestOptions;
use Phrest\SDK\PhrestSDK;
class CreateUserRequest extends AbstractRequest
{
/**
* @var string
*/
private $path = '/v1/users/';
/**
* @var string
*/
public $name = null;
/**
* @var string
*/
public $email = null;
/**
* @var string
*/
public $password = null;
/**
* @param string $name
* @param string $email
* @param string $password
*/
public function __construct($name = null, $email = null, $password = null)
{
$this->name = $name;
$this->email = $email;
$this->password = $password;
}
/**
*
*/
public function create()
{
$requestOptions = new RequestOptions();
$requestOptions->addPostParams(
[
'name' => $this->name,
'email' => $this->email,
'password' => $this->password,
]
);
return PhrestSDK::getResponse(
self::METHOD_POST,
$this->path,
$requestOptions
);
}
/**
* @param string $name
*
* @return static
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @param string $email
*
* @return static
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* @param string $password
*
* @return static
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
}
| phrest/skeleton | src/v1/Requests/Users/CreateUserRequest.php | PHP | mit | 1,538 |
'use strict';
// https://github.com/betsol/gulp-require-tasks
// Require the module.
const gulpRequireTasks = require('gulp-require-tasks');
const gulp = require('gulp');
const env = require('../index');
// Call it when necessary.
gulpRequireTasks({
// Pass any options to it. Please see below.
path: env.inConfigs('gulp', 'tasks')// This is default
});
gulp.task('default', ['scripts:build', 'json-copy:build']);
| ilivebox/microsb | node/configs/gulp/gulpfile.js | JavaScript | mit | 421 |
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
// package to your project.
////#define Handle_PageResultOfT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
#if Handle_PageResultOfT
using System.Web.Http.OData;
#endif
namespace MusicStore.Services.Areas.HelpPage
{
/// <summary>
/// Use this class to customize the Help Page.
/// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
/// or you can provide the samples for the requests/responses.
/// </summary>
public static class HelpPageConfig
{
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
MessageId = "MusicStore.Services.Areas.HelpPage.TextSample.#ctor(System.String)",
Justification = "End users may choose to merge this string with existing localized resources.")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
MessageId = "bsonspec",
Justification = "Part of a URI.")]
public static void Register(HttpConfiguration config)
{
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
//// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
//// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
//// formats by the available formatters.
//config.SetSampleObjects(new Dictionary<Type, object>
//{
// {typeof(string), "sample string"},
// {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
//});
// Extend the following to provide factories for types not handled automatically (those lacking parameterless
// constructors) or for which you prefer to use non-default property values. Line below provides a fallback
// since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif
// Extend the following to use a preset object directly as the sample for all actions that support a media
// type, regardless of the body parameter or return type. The lines below avoid display of binary content.
// The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
config.SetSampleForMediaType(
new TextSample("Binary JSON content. See http://bsonspec.org for details."),
new MediaTypeHeaderValue("application/bson"));
//// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
//// and have IEnumerable<string> as the body parameter or return type.
//config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
//// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
//// and action named "Put".
//config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");
//// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
//// on the controller named "Values" and action named "Get" with parameter "id".
//config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");
//// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
//config.SetActualRequestType(typeof(string), "Values", "Get");
//// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
//config.SetActualResponseType(typeof(string), "Values", "Post");
}
#if Handle_PageResultOfT
private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
{
if (type.IsGenericType)
{
Type openGenericType = type.GetGenericTypeDefinition();
if (openGenericType == typeof(PageResult<>))
{
// Get the T in PageResult<T>
Type[] typeParameters = type.GetGenericArguments();
Debug.Assert(typeParameters.Length == 1);
// Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
object items = sampleGenerator.GetSampleObject(itemsType);
// Fill in the other information needed to invoke the PageResult<T> constuctor
Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };
// Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
ConstructorInfo constructor = type.GetConstructor(parameterTypes);
return constructor.Invoke(parameters);
}
}
return null;
}
#endif
}
} | kiko81/Teleric-Academy-Homeworks | Module 3/Web-Services-and-Cloud/2. ASP.NET-Web-API/02_03_MusicStore/MusicStore.Services/Areas/HelpPage/App_Start/HelpPageConfig.cs | C# | mit | 6,509 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CacheCow.Server.EntityTagStore.SqlServer
{
internal class ColumnNames
{
public static string CacheKeyHash = "CacheKeyHash";
public static string RoutePattern = "RoutePattern";
public static string ResourceUri = "ResourceUri";
public static string ETag = "ETag";
public static string LastModified = "LastModified";
}
}
| Hotkey/CacheCow | src/CacheCow.Server.EntityTagStore.SqlServer/ColumnNames.cs | C# | mit | 445 |
import * as React from "react";
import { CarbonIconProps } from "../../";
declare const Laptop24: React.ForwardRefExoticComponent<
CarbonIconProps & React.RefAttributes<SVGSVGElement>
>;
export default Laptop24;
| mcliment/DefinitelyTyped | types/carbon__icons-react/lib/laptop/24.d.ts | TypeScript | mit | 214 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> Singapore Gurkhas 070216 Gcspf Gurkha Contingent Archives Kkg 23</title>
<!-- URL Structures -->
<link rel="canonical" href="http://sgpm-generator.github.io/singapore-gurkha-photography-museum/singapore-gurkhas-070216-gcspf-gurkha-contingent-archives-kkg-23.html">
<link rel="alternate" type="application/rss+xml" title="Singapore Gurkha Photography Museum" href="http://sgpm-generator.github.io/feed.xml">
<!-- OPENGRAPH tags for Social Media linking -->
<meta content="Singapore Gurkha Photography Museum" property="og:site_name">
<meta content=" Singapore Gurkhas 070216 Gcspf Gurkha Contingent Archives Kkg 23" property="og:title">
<meta content="article" property="og:type">
<meta name="description" content=" <h1></h1> {"1950s"=>[#<Jekyll::Document _posts/2014-10-11--singapore-gurkhas-050116-gcspf-gurkha-contingent-archives-kbg-26.md collect..." property="og:description">
<meta content="http://sgpm-generator.github.io/singapore-gurkha-photography-museum/singapore-gurkhas-070216-gcspf-gurkha-contingent-archives-kkg-23.html" property="og:url">
<meta content="2014-10-07T00:00:00+08:00" property="article:published_time">
<meta content="http://sgpm-generator.github.io/about/" property="article:author">
<meta content="" property="og:image">
<meta content="singapore-gurkha-photography-museum" property="article:section">
<meta content="1950s" property="article:tag">
<meta content="1960s" property="article:tag">
<meta content="1970s" property="article:tag">
<meta content="1980s" property="article:tag">
<meta content="1990s" property="article:tag">
<meta content="bhairahawa" property="article:tag">
<meta content="dharan" property="article:tag">
<meta content="gurkhas" property="article:tag">
<meta content="kathmandu" property="article:tag">
<meta content="nepal" property="article:tag">
<meta content="pokhara" property="article:tag">
<meta content="singapore" property="article:tag">
<meta content="singapore gurkha archive" property="article:tag">
<meta content="singapore gurkha old photographs" property="article:tag">
<meta content="singapore gurkha photography museum" property="article:tag">
<meta content="singapore gurkhas" property="article:tag">
<!-- OPENGRAPH tags end -->
<!-- CSS -->
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/bootstrap-theme.min.css">
<!-- Custom CSS -->
<style>
@import url(https://fonts.googleapis.com/css?family=Open+Sans:400,700italic,700,400italic);
.sgpm-title a {
color: #030303;
}
.main-gallery > ul {
margin-bottom:1.414em;
padding-left:0;
}
.no-bullets {
list-style:none;
padding-left:0;
}
.no-bullets > ul {
list-style:none;
padding-left:0;
}
body {min-width:420px;}
footer {
margin-top:2.84em;
padding-top:1.414em;
border-top:0.3px solid #aaa ;
}
header {
margin-bottom:2.84em;
}
main {
display:block;
clear:both;
}
</style>
</head>
<body class="container">
<header class="row">
<!-- masthead -->
<div class="col-xs-4" style="display:table-block;">
<h1 class="sgpm-title hidden-xs hidden-sm"><strong><a class="site-title" href="/">Singapore Gurkha Photography Museum</a></strong></h1>
<h2 class="sgpm-title visible-sm"><strong><a class="site-title" href="/">Singapore Gurkha Photography Museum</a></strong></h2>
<h3 class="sgpm-title visible-xs"><strong><a class="site-title" href="/">Singapore Gurkha Photography Museum</a></strong></h3>
<!-- searchbar-->
<div class="">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search for...">
<span class="input-group-btn">
<button class="btn btn-default" type="button"><span class="hidden-xs">Search</span><span class="visible-xs">Go</span></button>
</span>
</div>
</div>
<!-- searchbar end -->
</div>
<!-- masthead end -->
<nav class="col-xs-4 col-xs-offset-2 col-sm-offset-1">
<ul class="nav col-xs-12" style="padding-top:1.41em;border-left:solid 0.3px #aaa" >
<!-- navlinks -->
<li class="active">
<a href="/about.html">About</a>
</li>
<li class="active">
<a href="/archive.html">Archive</a>
</li>
<li class="active">
<a href="/articles.html">Articles</a>
</li>
<li class="active">
<a href="/contact.html">Contact</a>
</li>
<!-- navlinks end-->
<!-- dev links -->
<li class="small">(these are links for development)</li>
<li class="active">
<a href="/sgpm-list.html">Brute Force List</a>
</li>
<li class="active">
<a href="/basic-generator.html">Brute Generator</a>
</li>
<!-- dev links end-->
</ul>
</nav>
</header>
<main class="row">
<section class="col-sm-6 col-xs-12">
<a href="../img/singapore-gurkhas-070216-gcspf-gurkha-contingent-archives-kkg-23.jpg">
<img class="img-responsive" src="../img/singapore-gurkhas-070216-gcspf-gurkha-contingent-archives-kkg-23.jpg" />
</a>
</section>
<section class="col-sm-6 col-xs-12">
<ul style="list-style:none;margin-left:0;">
<li><h3>Photo from: KishoreKumarGurung-SingaporeGurkhaPhotographyMuseum</h3></li>
<li>
Was at Pasir Ris annual picnic, Nar Bahadur Gurung (4910). Lifeguard at Penguin swimming pool, Pokhara. Date: Late 1970s.
</li>
<a href="/tags/1950s" style="padding:3px; display:inline-block; background:#eee; margin-bottom:2px;"><li> 1950s </li></a>
<a href="/tags/1960s" style="padding:3px; display:inline-block; background:#eee; margin-bottom:2px;"><li> 1960s </li></a>
<a href="/tags/1970s" style="padding:3px; display:inline-block; background:#eee; margin-bottom:2px;"><li> 1970s </li></a>
<a href="/tags/1980s" style="padding:3px; display:inline-block; background:#eee; margin-bottom:2px;"><li> 1980s </li></a>
<a href="/tags/1990s" style="padding:3px; display:inline-block; background:#eee; margin-bottom:2px;"><li> 1990s </li></a>
<a href="/tags/bhairahawa" style="padding:3px; display:inline-block; background:#eee; margin-bottom:2px;"><li> bhairahawa </li></a>
<a href="/tags/dharan" style="padding:3px; display:inline-block; background:#eee; margin-bottom:2px;"><li> dharan </li></a>
<a href="/tags/gurkhas" style="padding:3px; display:inline-block; background:#eee; margin-bottom:2px;"><li> gurkhas </li></a>
<a href="/tags/kathmandu" style="padding:3px; display:inline-block; background:#eee; margin-bottom:2px;"><li> kathmandu </li></a>
<a href="/tags/nepal" style="padding:3px; display:inline-block; background:#eee; margin-bottom:2px;"><li> nepal </li></a>
<a href="/tags/pokhara" style="padding:3px; display:inline-block; background:#eee; margin-bottom:2px;"><li> pokhara </li></a>
<a href="/tags/singapore" style="padding:3px; display:inline-block; background:#eee; margin-bottom:2px;"><li> singapore </li></a>
<a href="/tags/singapore gurkha archive" style="padding:3px; display:inline-block; background:#eee; margin-bottom:2px;"><li> singapore gurkha archive </li></a>
<a href="/tags/singapore gurkha old photographs" style="padding:3px; display:inline-block; background:#eee; margin-bottom:2px;"><li> singapore gurkha old photographs </li></a>
<a href="/tags/singapore gurkha photography museum" style="padding:3px; display:inline-block; background:#eee; margin-bottom:2px;"><li> singapore gurkha photography museum </li></a>
<a href="/tags/singapore gurkhas" style="padding:3px; display:inline-block; background:#eee; margin-bottom:2px;"><li> singapore gurkhas </li></a>
</ul>
</section>
</main>
<footer class="row">
<div class="col-sm-4">
<h5 style="margin:0;font-weight:600;">©2016 Singapore Gurkha Photography Museum</h5>
</div>
<div class="col-sm-4">
<ul class="no-bullets">
<!-- contact -->
<li><strong>email: </strong><a href="mailto:mail@zakariazainal.com">mail@zakariazainal.com</a></li>
<!-- social media -->
</ul>
</div>
<div class="col-sm-4">
<p class="small">The Singapore Gurkha Photography Museum project is an online archive of photographs and documents contributed by former members of the Singapore Gurkhas.
</p>
</div>
</footer>
<!-- jQuery -->
<script src="/js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>
</body>
</html>
| sgpm-generator/sgpm-generator | singapore-gurkha-photography-museum/singapore-gurkhas-070216-gcspf-gurkha-contingent-archives-kkg-23.html | HTML | mit | 8,711 |
<!DOCTYPE html>
<!--[if IE 7]>
<html class="ie ie7" lang="en">
<![endif]-->
<!--[if IE 8]>
<html class="ie ie8" lang="en">
<![endif]-->
<!--[if !(IE 7) | !(IE 8) ]><!-->
<html>
<head lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>申博教育,美国留学,美国留学中介,美国本科,美国高中专业申请机构</title>
<meta name="keywords" content="申博教育,APP申博教育,申博留学,美国本科,美国本科转学,美国高中,美国研究生,美国大学,大学排名,美国专业排名,美国留学,美国留学中介">
<meta name="description" content="APP申博教育,你的美国留学申请专家,提供美国本科申请,美国本科转学申请,美国高中申请,美国研究生申请等业务。申博教育专业机构团队为您提供最新奖学金、申请要去、大学排名、留学政策、专业排名、生活百科等信息,美国留学最专业的申请机构-申博教育。">
<link rel="icon" href="./favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="./css/app_welcome.css">
</head>
<body>
<div id="skrollr-body" class="aw_main" data-smooth-scrolling="on">
<article class="aw_hero">
<div class="aw_hero_bg">
<img src="./assets/imgs/page1_bg.jpg" title="欢迎来到APP 申博教育官网">
</div>
<section class="aw_page1_intro" data-0="opacity:1;" data-5="opacity:0;">
<!-- Begin APP 品牌 -->
<div class="aw_brand">
<div class="aw_brand_logo">
<img src="./assets/imgs/aw_logo.png" title="app welcome page logo">
</div>
<h1 class="aw_brand_statement">
我们专注于美国顶尖名校录取
</h1>
</div>
<!-- End APP 品牌 -->
<!-- Begin AO 负责的事 -->
<div class="aw_aoDo">
<div class="aw_aoDo_list">
超过<span class="aw_aoDo_amount"> 20 </span>位常青藤前招生官员全程参与你的申请:
<span id="aw_aoDo_name">Charles</span>
</div>
<div class="aw_aoDo_detail">
为学生和家长提供顶尖名校录取服务
</div>
</div>
<!-- End AO 负责的事 -->
</section>
<section class="aw_page1_data" data-0="opacity: 0;" data-5="opacity: 1; display: block;">
<!-- Begin AO 带来的差别 -->
<div class="aw_aoDiff">
<div class="aw_aoDiff_statement">
<p>因为有他们</p>
<p>我们与其他留学机构有了很大不同</p>
</div>
<div class="aw_aoDiff_detail">
<div class="aw_aoDiff_item">
<span class="aw_aoDiff_item_title">Top10 录取</span>
<span class="aw_aoDiff_item_num">20%</span>
<span class="aw_aoDiff_item_line"> </span>
</div>
<div class="aw_aoDiff_item">
<span class="aw_aoDiff_item_title">Top20 录取</span>
<span class="aw_aoDiff_item_num">35%</span>
<span class="aw_aoDiff_item_line"> </span>
</div>
<div class="aw_aoDiff_item">
<span class="aw_aoDiff_item_title">Top30 录取</span>
<span class="aw_aoDiff_item_num">65%</span>
<span class="aw_aoDiff_item_line"> </span>
</div>
<div class="aw_aoDiff_item">
<span class="aw_aoDiff_item_title">Top80 录取</span>
<span class="aw_aoDiff_item_num">100%</span>
<span class="aw_aoDiff_item_line"> </span>
</div>
</div>
</div>
<div class="aw_skip">
<a href="http://welcome.appedu.org">进入主站</a>
</div>
<!-- End AO 带来的差别 -->
</section>
</article>
<!-- Begin AO 列表 -->
<article class="aw_ao">
<div class="aw_ao_statement">
<h1>我们的招生官团队</h1>
<p>选择APP,让我们也来帮你达成梦想。</p>
</div>
<div class="aw_ao_wrap">
<section class="aw_ao_detail aw_ao_charles">
<img class="aw_ao_img" src="./assets/imgs/ao_charles.jpg">
<div class="aw_ao_intro">
<h2 class="aw_ao_name">Charles</h2>
<div class="aw_ao_experience">
<h3>招生简历:</h3>
<ul>
<li>1. 哈佛大学高级招生官</li>
<li>2. 哈佛大学新生顾问</li>
<li>3. APP海外金牌顾问</li>
</ul>
</div>
</div>
</section>
<section class="aw_ao_detail aw_ao_becky">
<img class="aw_ao_img" src="./assets/imgs/ao_becky.jpg">
<div class="aw_ao_intro">
<h2 class="aw_ao_name">Becky</h2>
<div class="aw_ao_experience">
<h3>招生简历:</h3>
<ul>
<li>1. 普林斯顿大学担任招生官</li>
<li>2. 普林斯顿大学教师</li>
<li>3. 高校辅导员长</li>
</ul>
</div>
</div>
</section>
<section class="aw_ao_detail aw_ao_lisa">
<img class="aw_ao_img" src="./assets/imgs/ao_lisa.jpg">
<div class="aw_ao_intro">
<h2 class="aw_ao_name">Lisa</h2>
<div class="aw_ao_experience">
<h3>招生简历:</h3>
<ul>
<li>1. 华盛顿圣路易斯大学本科招生前任高级招生主任</li>
<li>2. 凯斯西储大学前招生官</li>
</ul>
</div>
</div>
</section>
<section class="aw_ao_detail aw_ao_steve">
<img class="aw_ao_img" src="./assets/imgs/ao_steve.jpg">
<div class="aw_ao_intro">
<h2 class="aw_ao_name">Steve</h2>
<div class="aw_ao_experience">
<h3>招生简历:</h3>
<p>
在过去十年的任期中,他负责评估全美11个地区的大学申请,同时担任数个招生委员会的主席,协调联系学生和校友志愿者的网络工作。
</p>
</div>
</div>
</section>
<section class="aw_ao_detail aw_ao_tracy">
<img class="aw_ao_img" src="./assets/imgs/ao_tracy.jpg">
<div class="aw_ao_intro">
<h2 class="aw_ao_name">Tracy</h2>
<div class="aw_ao_experience">
<h3>招生简历:</h3>
<ul>
<li>1. 哥伦比亚大学前任高级招生主任</li>
<li>2. 洛杉矶最顶尖私立中学前任升学顾问</li>
<li>3. APP海外金牌顾问</li>
</ul>
</div>
</div>
</section>
<section class="aw_ao_detail aw_ao_carlos">
<img class="aw_ao_img" src="./assets/imgs/ao_carlos.jpg">
<div class="aw_ao_intro">
<h2 class="aw_ao_name">Carlos</h2>
<div class="aw_ao_experience">
<h3>招生简历:</h3>
<ul>
<li>1. 担任布兰迪斯大学国际招生办公室主任</li>
<li>2. 16年本科招生办公室工作与面试录取经验</li>
</ul>
</div>
</div>
</section>
<section class="aw_ao_detail aw_ao_foster">
<img class="aw_ao_img" src="./assets/imgs/ao_foster.jpg">
<div class="aw_ao_intro">
<h2 class="aw_ao_name">Foster</h2>
<div class="aw_ao_experience">
<h3>招生简历:</h3>
<ul>
<li>1. 杜克大学本科招办官员六年</li>
<li>2. 哥伦比亚大学本科招办高级官员四年</li>
<li>3. 凯斯西储大学招生办官员十年</li>
</ul>
</div>
</div>
</section>
<section class="aw_ao_detail aw_ao_Anita">
<img class="aw_ao_img" src="./assets/imgs/ao_anita.jpg">
<div class="aw_ao_intro">
<h2 class="aw_ao_name">Anita</h2>
<div class="aw_ao_experience">
<h3>招生简历:</h3>
<ul>
<li>1. 历任耶鲁大学高级招生官</li>
<li>2. 哥伦比亚大学研究生录取高级招生官</li>
</ul>
</div>
</div>
</section>
</div>
</article>
<!-- End AO 列表 -->
<!-- Begin Student 列表 -->
<article class="aw_student">
<div class="aw_student_statement">
<h1>我们的骄傲</h1>
<p>因为有招生官们,在美国前50 的每一个学校每一个年级都有APP 的学生</p>
</div>
<section class="aw_student_list">
<div class="aw_student_item">
<img class="aw_student_img" src="./assets/imgs/school_mit.jpg">
</img>
<div class="aw_student_intro">
<h2 class="aw_student_name">
胡YZ
</h2>
<p class="aw_student_schoolNow">就读学校:麻省理工学院</p>
<p class="aw_student_schoolOffer">录取学校:麻省理工学院</p>
</div>
<div class="aw_student_thxToApp">
<p>
<span class="aw_student_thxToApp_title">感谢话语:</span><br>
Charles 他给了我很多鼓励。
而且他在文书方面给了我很多专业的建议,然后思路都是先通过跟老师谈,有一些启发性的想法之后,我再自己着手写,然后她再改,我再改这样子。
真的非常非常感谢Charles 老师,他在精神上和实际上都给了我很多帮助。
</p>
</div>
</div>
<div class="aw_student_item">
<img class="aw_student_img" src="./assets/imgs/school_mit.jpg">
</img>
<div class="aw_student_intro">
<h2 class="aw_student_name">
王XX
</h2>
<p class="aw_student_schoolNow">就读学校:麻省理工学院</p>
<p class="aw_student_schoolOffer">录取学校:麻省理工学院</p>
</div>
<div class="aw_student_thxToApp">
<p>
<span class="aw_student_thxToApp_title">感谢话语:</span><br>
我当时找了很多间中介,一间一间去了解。
当时我是和谢勇老师聊天,觉得他真的知道很多东西,就会为你去想,站在你那个角度去为你思考,怎么样去申请更好的学校这样。
然后我觉得personal statement还是非常的完美的。我对文书的完成都挺满意的。
真的非常感谢申博教育对我的帮助。
</p>
</div>
</div>
<div class="aw_student_item">
<img class="aw_student_img" src="./assets/imgs/school_cornell.jpg">
</img>
<div class="aw_student_intro">
<h2 class="aw_student_name">
杨WX
</h2>
<p class="aw_student_schoolNow">就读学校:康奈尔大学</p>
<p class="aw_student_schoolOffer">录取学校:康奈尔大学</p>
</div>
<div class="aw_student_thxToApp">
<p>
<span class="aw_student_thxToApp_title">感谢话语:</span><br>
很感谢Steve 老师的专业性,帮我选择出了最适合我性格与兴趣的学校,
最后也如愿获得了康奈尔的Offer,很感谢Steve 老师和申博教育的老师。
</p>
</div>
</div>
<div class="aw_student_item">
<img class="aw_student_img" src="./assets/imgs/schoool_upenn.jpg">
</img>
<div class="aw_student_intro">
<h2 class="aw_student_name">
关TY
</h2>
<p class="aw_student_schoolNow">就读学校:宾夕法尼亚大学</p>
<p class="aw_student_schoolOffer">录取学校:宾夕法尼亚大学</p>
</div>
<div class="aw_student_thxToApp">
<p>
<span class="aw_student_thxToApp_title">感谢话语:</span><br>
APP给我提供的帮助,第一个就是时间的规划。
第二个就是咨询师会督促你做一些事情。
第三个就是文书的书写。
在Becky 老师的评估下很快坚定了以宾大为第一目标。
感谢Becky 的指导,写出来的文书看完感觉很顺眼那种。
谢谢申博教育,然后可以让我有这么好的Master。
</p>
</div>
</div>
<div class="aw_student_item">
<img class="aw_student_img" src="./assets/imgs/schoool_upenn.jpg">
</img>
<div class="aw_student_intro">
<h2 class="aw_student_name">
张XR
</h2>
<p class="aw_student_schoolNow">就读学校:宾夕法尼亚大学</p>
<p class="aw_student_schoolOffer">录取学校:宾夕法尼亚大学、西北大学、约翰霍普金斯大学</p>
</div>
<div class="aw_student_thxToApp">
<p>
<span class="aw_student_thxToApp_title">感谢话语:</span><br>
Becky 老师一直很耐心,我自己对申请这件事情很迷茫,
问了老师之后,就会有一个很系统的解答,特别是在选校的时候,因为我的兴趣是金融方向,可以选的东西很多,
然后老师当时就给了我一份之前她整理的跟金融相关的资料,然后我根据这个清单去找就会方便很多。
</p>
</div>
</div>
<div class="aw_student_item">
<img class="aw_student_img" src="./assets/imgs/schoool_upenn.jpg">
</img>
<div class="aw_student_intro">
<h2 class="aw_student_name">
张LL
</h2>
<p class="aw_student_schoolNow">就读学校:宾夕法尼亚大学</p>
<p class="aw_student_schoolOffer">录取学校:宾夕法尼亚大学、杜克大学、达特茅斯学院、布朗大学</p>
</div>
<div class="aw_student_thxToApp">
<p>
<span class="aw_student_thxToApp_title">感谢话语:</span><br>
Tracy 老师给了我很多信心。
我那时候没有任何offer,会对自己产生怀疑。
Tracy 老师给我的鼓励就像给我打了强心剂一样,就更有自信能够走完这条路。
申博教育比较负责,特别像一个助手,一个帮手,督促我进行准备,事无巨细的让我更全面的准备。
</p>
</div>
</div>
<div class="aw_student_item">
<img class="aw_student_img" src="./assets/imgs/school_johns_hopkins.jpg">
</img>
<div class="aw_student_intro">
<h2 class="aw_student_name">
郑JJ
</h2>
<p class="aw_student_schoolNow">就读学校:约翰霍普金斯大学</p>
<p class="aw_student_schoolOffer">录取学校:约翰霍普金斯大学</p>
</div>
<div class="aw_student_thxToApp">
<p>
<span class="aw_student_thxToApp_title">感谢话语:</span><br>
在一开始去申请的时候我根本不知道突出自己哪一方面的特点。
后来知道要是想突出一个人的素质,不仅需要写出个人的性格素质,还要写出对学校对专业的兴趣以及自己的一些想法和经历。
Lisa 老师很了解学校,她告诉我学校是什么样的。
</p>
</div>
</div>
<div class="aw_student_item">
<img class="aw_student_img" src="./assets/imgs/school_washington.jpg">
</img>
<div class="aw_student_intro">
<h2 class="aw_student_name">
周M
</h2>
<p class="aw_student_schoolNow">就读学校:华盛顿大学圣路易斯分校</p>
<p class="aw_student_schoolOffer">录取学校:华盛顿大学圣路易斯分校</p>
</div>
<div class="aw_student_thxToApp">
<p>
<span class="aw_student_thxToApp_title">感谢话语:</span><br>
我特别感谢Lisa 老师对我申请的帮助,特别是在文书和学校方面。
学校的话,我以前虽然有了解,但是专业排名什么的,具体的不是很清楚,还有学校的偏重,
Lisa 老师告诉我不同学校的优劣在哪里,衡量的因素多了,出来的选项也就更准了。
</p>
</div>
</div>
<div class="aw_student_item">
<img class="aw_student_img" src="./assets/imgs/school_washington.jpg">
</img>
<div class="aw_student_intro">
<h2 class="aw_student_name">
蒋H
</h2>
<p class="aw_student_schoolNow">就读学校:华盛顿大学圣路易斯分校</p>
<p class="aw_student_schoolOffer">录取学校:华盛华盛顿大学圣路易斯分校顿大学圣路易斯分校</p>
</div>
<div class="aw_student_thxToApp">
<p>
<span class="aw_student_thxToApp_title">感谢话语:</span><br>
Steve 老师引导我去形成文书书写的思路,让我大概知道是怎样写的。
然后我再按照这个思路去加入自己的修改意见,把它改好。
一路上Steve 老师对我的申请给了我很大帮助,让我才能这么平稳、这么轻松地就感觉申请完了。
</p>
</div>
</div>
<div class="aw_student_item">
<img class="aw_student_img" src="./assets/imgs/school_cornell.jpg">
</img>
<div class="aw_student_intro">
<h2 class="aw_student_name">
陈YX
</h2>
<p class="aw_student_schoolNow">就读学校:康奈尔大学</p>
<p class="aw_student_schoolOffer">录取学校:康奈尔大学</p>
</div>
<div class="aw_student_thxToApp">
<p>
<span class="aw_student_thxToApp_title">感谢话语:</span><br>
Tracy 老师很专业地从我那堆堆混乱的文书资料和想法中挑出精华,
并帮我总结出很牛气哄哄的东西,所以申博整个团队都是很厉害的。
感谢Tracy 和申博,嘻嘻!
</p>
</div>
</div>
</section>
</article>
<!-- End Student 列表 -->
<footer id="aw_footer">
<p>申博教育信息咨询有限公司 E-mail:app@appedu.org</p>
<p>广州总部:广州市越秀区先烈中路69号东山广场1019室 电话:86-20-37583165</p>
<p>海南分公司:海南省海口市龙华区玉沙路11号中盐大厦29层C1室 电话:0898-68539758</p>
<p><a href="http://www.miibeian.gov.cn/">粤ICP备14010098号</a></p>
</footer>
</div>
<script type="text/javascript" src="./assets/vendor/require.js" data-main="./assets/app_welcome"></script>
</body>
</html> | SamHwang1990/app-welcome | src/html/index.html | HTML | mit | 22,341 |
/* @flow */
"use strict";
var _inherits = require("babel-runtime/helpers/inherits")["default"];
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _getIterator = require("babel-runtime/core-js/get-iterator")["default"];
var _Object$assign = require("babel-runtime/core-js/object/assign")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
var _repeating = require("repeating");
var _repeating2 = _interopRequireDefault(_repeating);
var _buffer = require("./buffer");
var _buffer2 = _interopRequireDefault(_buffer);
var _node = require("./node");
var _node2 = _interopRequireDefault(_node);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var Printer = (function (_Buffer) {
_inherits(Printer, _Buffer);
function Printer() {
_classCallCheck(this, Printer);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_Buffer.call.apply(_Buffer, [this].concat(args));
this.insideAux = false;
this.printAuxAfterOnNextUserNode = false;
}
Printer.prototype.print = function print(node, parent) {
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
if (!node) return;
if (parent && parent._compact) {
node._compact = true;
}
var oldInAux = this.insideAux;
this.insideAux = !node.loc;
var oldConcise = this.format.concise;
if (node._compact) {
this.format.concise = true;
}
var printMethod = this[node.type];
if (!printMethod) {
throw new ReferenceError("unknown node of type " + JSON.stringify(node.type) + " with constructor " + JSON.stringify(node && node.constructor.name));
}
if (node.loc) this.printAuxAfterComment();
this.printAuxBeforeComment(oldInAux);
var needsParens = _node2["default"].needsParens(node, parent);
if (needsParens) this.push("(");
this.printLeadingComments(node, parent);
this.catchUp(node);
this._printNewline(true, node, parent, opts);
if (opts.before) opts.before();
this.map.mark(node, "start");
this._print(node, parent);
this.printTrailingComments(node, parent);
if (needsParens) this.push(")");
// end
this.map.mark(node, "end");
if (opts.after) opts.after();
this.format.concise = oldConcise;
this.insideAux = oldInAux;
this._printNewline(false, node, parent, opts);
};
Printer.prototype.printAuxBeforeComment = function printAuxBeforeComment(wasInAux) {
var comment = this.format.auxiliaryCommentBefore;
if (!wasInAux && this.insideAux) {
this.printAuxAfterOnNextUserNode = true;
if (comment) this.printComment({
type: "CommentBlock",
value: comment
});
}
};
Printer.prototype.printAuxAfterComment = function printAuxAfterComment() {
if (this.printAuxAfterOnNextUserNode) {
this.printAuxAfterOnNextUserNode = false;
var comment = this.format.auxiliaryCommentAfter;
if (comment) this.printComment({
type: "CommentBlock",
value: comment
});
}
};
Printer.prototype.getPossibleRaw = function getPossibleRaw(node) {
var extra = node.extra;
if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) {
return extra.raw;
}
};
Printer.prototype._print = function _print(node, parent) {
var extra = this.getPossibleRaw(node);
if (extra) {
this.push("");
this._push(extra);
} else {
var printMethod = this[node.type];
printMethod.call(this, node, parent);
}
};
Printer.prototype.printJoin = function printJoin(nodes /*: ?Array*/, parent /*: Object*/) {
// istanbul ignore next
var _this = this;
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
if (!nodes || !nodes.length) return;
var len = nodes.length;
var node = undefined,
i = undefined;
if (opts.indent) this.indent();
var printOpts = {
statement: opts.statement,
addNewlines: opts.addNewlines,
after: function after() {
if (opts.iterator) {
opts.iterator(node, i);
}
if (opts.separator && i < len - 1) {
_this.push(opts.separator);
}
}
};
for (i = 0; i < nodes.length; i++) {
node = nodes[i];
this.print(node, parent, printOpts);
}
if (opts.indent) this.dedent();
};
Printer.prototype.printAndIndentOnComments = function printAndIndentOnComments(node, parent) {
var indent = !!node.leadingComments;
if (indent) this.indent();
this.print(node, parent);
if (indent) this.dedent();
};
Printer.prototype.printBlock = function printBlock(parent) {
var node = parent.body;
if (t.isEmptyStatement(node)) {
this.semicolon();
} else {
this.push(" ");
this.print(node, parent);
}
};
Printer.prototype.generateComment = function generateComment(comment) {
var val = comment.value;
if (comment.type === "CommentLine") {
val = "//" + val;
} else {
val = "/*" + val + "*/";
}
return val;
};
Printer.prototype.printTrailingComments = function printTrailingComments(node, parent) {
this.printComments(this.getComments("trailingComments", node, parent));
};
Printer.prototype.printLeadingComments = function printLeadingComments(node, parent) {
this.printComments(this.getComments("leadingComments", node, parent));
};
Printer.prototype.printInnerComments = function printInnerComments(node) {
var indent = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
if (!node.innerComments) return;
if (indent) this.indent();
this.printComments(node.innerComments);
if (indent) this.dedent();
};
Printer.prototype.printSequence = function printSequence(nodes, parent) {
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
opts.statement = true;
return this.printJoin(nodes, parent, opts);
};
Printer.prototype.printList = function printList(items, parent) {
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
if (opts.separator == null) {
opts.separator = ",";
if (!this.format.compact) opts.separator += " ";
}
return this.printJoin(items, parent, opts);
};
Printer.prototype._printNewline = function _printNewline(leading, node, parent, opts) {
if (!opts.statement && !_node2["default"].isUserWhitespacable(node, parent)) {
return;
}
var lines = 0;
if (node.start != null && !node._ignoreUserWhitespace && this.tokens.length) {
// user node
if (leading) {
lines = this.whitespace.getNewlinesBefore(node);
} else {
lines = this.whitespace.getNewlinesAfter(node);
}
} else {
// generated node
if (!leading) lines++; // always include at least a single line after
if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
var needs = _node2["default"].needsWhitespaceAfter;
if (leading) needs = _node2["default"].needsWhitespaceBefore;
if (needs(node, parent)) lines++;
// generated nodes can't add starting file whitespace
if (!this.buf) lines = 0;
}
this.newline(lines);
};
Printer.prototype.getComments = function getComments(key, node) {
return node && node[key] || [];
};
Printer.prototype.shouldPrintComment = function shouldPrintComment(comment) {
if (this.format.shouldPrintComment) {
return this.format.shouldPrintComment(comment.value);
} else {
if (comment.value.indexOf("@license") >= 0 || comment.value.indexOf("@preserve") >= 0) {
return true;
} else {
return this.format.comments;
}
}
};
Printer.prototype.printComment = function printComment(comment) {
if (!this.shouldPrintComment(comment)) return;
if (comment.ignore) return;
comment.ignore = true;
if (comment.start != null) {
if (this.printedCommentStarts[comment.start]) return;
this.printedCommentStarts[comment.start] = true;
}
this.catchUp(comment);
// whitespace before
this.newline(this.whitespace.getNewlinesBefore(comment));
var column = this.position.column;
var val = this.generateComment(comment);
if (column && !this.isLast(["\n", " ", "[", "{"])) {
this._push(" ");
column++;
}
//
if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) {
var offset = comment.loc && comment.loc.start.column;
if (offset) {
var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
val = val.replace(newlineRegex, "\n");
}
var indent = Math.max(this.indentSize(), column);
val = val.replace(/\n/g, "\n" + _repeating2["default"](" ", indent));
}
if (column === 0) {
val = this.getIndent() + val;
}
// force a newline for line comments when retainLines is set in case the next printed node
// doesn't catch up
if ((this.format.compact || this.format.retainLines) && comment.type === "CommentLine") {
val += "\n";
}
//
this._push(val);
// whitespace after
this.newline(this.whitespace.getNewlinesAfter(comment));
};
Printer.prototype.printComments = function printComments(comments /*:: ?: Array<Object>*/) {
if (!comments || !comments.length) return;
for (var _iterator = comments, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _getIterator(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var comment = _ref;
this.printComment(comment);
}
};
return Printer;
})(_buffer2["default"]);
exports["default"] = Printer;
var _arr = [require("./generators/template-literals"), require("./generators/expressions"), require("./generators/statements"), require("./generators/classes"), require("./generators/methods"), require("./generators/modules"), require("./generators/types"), require("./generators/flow"), require("./generators/base"), require("./generators/jsx")];
for (var _i2 = 0; _i2 < _arr.length; _i2++) {
var generator = _arr[_i2];
_Object$assign(Printer.prototype, generator);
}
module.exports = exports["default"]; | Shashank92/promises-demo | node_modules/gulp-babel/node_modules/babel-core/node_modules/babel-generator/lib/printer.js | JavaScript | mit | 10,786 |
using System;
using System.ComponentModel;
using System.Web;
using System.Web.Security;
using System.Xml.Linq;
using System.Xml.XPath;
using Umbraco.Core;
using Umbraco.Core.Dictionary;
using Umbraco.Core.Dynamics;
using Umbraco.Core.Models;
using Umbraco.Core.Security;
using Umbraco.Core.Services;
using Umbraco.Core.Xml;
using Umbraco.Web.Routing;
using Umbraco.Web.Security;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Umbraco.Core.Cache;
namespace Umbraco.Web
{
/// <summary>
/// A helper class that provides many useful methods and functionality for using Umbraco in templates
/// </summary>
public class UmbracoHelper : IUmbracoComponentRenderer
{
private readonly UmbracoContext _umbracoContext;
private readonly IPublishedContent _currentPage;
private readonly ITypedPublishedContentQuery _typedQuery;
private readonly IDynamicPublishedContentQuery _dynamicQuery;
private readonly HtmlStringUtilities _stringUtilities = new HtmlStringUtilities();
private IUmbracoComponentRenderer _componentRenderer;
private PublishedContentQuery _query;
private MembershipHelper _membershipHelper;
private TagQuery _tag;
private IDataTypeService _dataTypeService;
private UrlProvider _urlProvider;
private ICultureDictionary _cultureDictionary;
/// <summary>
/// Lazy instantiates the tag context
/// </summary>
public TagQuery TagQuery
{
//TODO: Unfortunately we cannot change this return value to be ITagQuery
// since it's a breaking change, need to fix it for v8
// http://issues.umbraco.org/issue/U4-6899
get
{
return _tag ??
(_tag = new TagQuery(UmbracoContext.Application.Services.TagService,
_typedQuery ?? ContentQuery));
}
}
/// <summary>
/// Lazy instantiates the query context if not specified in the constructor
/// </summary>
public PublishedContentQuery ContentQuery
{
get
{
//If the content query doesn't exist it will either be created with the ITypedPublishedContentQuery, IDynamicPublishedContentQuery
// used to construct this instance or with the content caches of the UmbracoContext
return _query ??
(_query = _typedQuery != null
? new PublishedContentQuery(_typedQuery, _dynamicQuery)
: new PublishedContentQuery(UmbracoContext.ContentCache, UmbracoContext.MediaCache));
}
}
/// <summary>
/// Helper method to ensure an umbraco context is set when it is needed
/// </summary>
public UmbracoContext UmbracoContext
{
get
{
if (_umbracoContext == null)
{
throw new NullReferenceException("No " + typeof(UmbracoContext) + " reference has been set for this " + typeof(UmbracoHelper) + " instance");
}
return _umbracoContext;
}
}
/// <summary>
/// Lazy instantiates the membership helper if not specified in the constructor
/// </summary>
public MembershipHelper MembershipHelper
{
get { return _membershipHelper ?? (_membershipHelper = new MembershipHelper(UmbracoContext)); }
}
/// <summary>
/// Lazy instantiates the UrlProvider if not specified in the constructor
/// </summary>
public UrlProvider UrlProvider
{
get { return _urlProvider ?? (_urlProvider = UmbracoContext.UrlProvider); }
}
/// <summary>
/// Lazy instantiates the IDataTypeService if not specified in the constructor
/// </summary>
public IDataTypeService DataTypeService
{
get { return _dataTypeService ?? (_dataTypeService = UmbracoContext.Application.Services.DataTypeService); }
}
/// <summary>
/// Lazy instantiates the IUmbracoComponentRenderer if not specified in the constructor
/// </summary>
public IUmbracoComponentRenderer UmbracoComponentRenderer
{
get { return _componentRenderer ?? (_componentRenderer = new UmbracoComponentRenderer(UmbracoContext)); }
}
#region Constructors
/// <summary>
/// Empty constructor to create an umbraco helper for access to methods that don't have dependencies
/// </summary>
public UmbracoHelper()
{
}
/// <summary>
/// Constructor accepting all dependencies
/// </summary>
/// <param name="umbracoContext"></param>
/// <param name="content"></param>
/// <param name="typedQuery"></param>
/// <param name="dynamicQuery"></param>
/// <param name="tagQuery"></param>
/// <param name="dataTypeService"></param>
/// <param name="urlProvider"></param>
/// <param name="cultureDictionary"></param>
/// <param name="componentRenderer"></param>
/// <param name="membershipHelper"></param>
/// <remarks>
/// This constructor can be used to create a testable UmbracoHelper
/// </remarks>
public UmbracoHelper(UmbracoContext umbracoContext, IPublishedContent content,
ITypedPublishedContentQuery typedQuery,
IDynamicPublishedContentQuery dynamicQuery,
ITagQuery tagQuery,
IDataTypeService dataTypeService,
UrlProvider urlProvider,
ICultureDictionary cultureDictionary,
IUmbracoComponentRenderer componentRenderer,
MembershipHelper membershipHelper)
{
if (umbracoContext == null) throw new ArgumentNullException("umbracoContext");
if (content == null) throw new ArgumentNullException("content");
if (typedQuery == null) throw new ArgumentNullException("typedQuery");
if (dynamicQuery == null) throw new ArgumentNullException("dynamicQuery");
if (tagQuery == null) throw new ArgumentNullException("tagQuery");
if (dataTypeService == null) throw new ArgumentNullException("dataTypeService");
if (urlProvider == null) throw new ArgumentNullException("urlProvider");
if (cultureDictionary == null) throw new ArgumentNullException("cultureDictionary");
if (componentRenderer == null) throw new ArgumentNullException("componentRenderer");
if (membershipHelper == null) throw new ArgumentNullException("membershipHelper");
_umbracoContext = umbracoContext;
_tag = new TagQuery(tagQuery);
_dataTypeService = dataTypeService;
_urlProvider = urlProvider;
_cultureDictionary = cultureDictionary;
_componentRenderer = componentRenderer;
_membershipHelper = membershipHelper;
_currentPage = content;
_typedQuery = typedQuery;
_dynamicQuery = dynamicQuery;
}
[Obsolete("Use the constructor specifying all dependencies")]
[EditorBrowsable(EditorBrowsableState.Never)]
public UmbracoHelper(UmbracoContext umbracoContext, IPublishedContent content, PublishedContentQuery query)
: this(umbracoContext)
{
if (content == null) throw new ArgumentNullException("content");
if (query == null) throw new ArgumentNullException("query");
_currentPage = content;
_query = query;
}
/// <summary>
/// Custom constructor setting the current page to the parameter passed in
/// </summary>
/// <param name="umbracoContext"></param>
/// <param name="content"></param>
public UmbracoHelper(UmbracoContext umbracoContext, IPublishedContent content)
: this(umbracoContext)
{
if (content == null) throw new ArgumentNullException("content");
_currentPage = content;
}
/// <summary>
/// Standard constructor setting the current page to the page that has been routed to
/// </summary>
/// <param name="umbracoContext"></param>
public UmbracoHelper(UmbracoContext umbracoContext)
{
if (umbracoContext == null) throw new ArgumentNullException("umbracoContext");
if (umbracoContext.RoutingContext == null) throw new NullReferenceException("The RoutingContext on the UmbracoContext cannot be null");
_umbracoContext = umbracoContext;
if (_umbracoContext.IsFrontEndUmbracoRequest)
{
_currentPage = _umbracoContext.PublishedContentRequest.PublishedContent;
}
}
[Obsolete("Use the constructor specifying all dependencies")]
[EditorBrowsable(EditorBrowsableState.Never)]
public UmbracoHelper(UmbracoContext umbracoContext, PublishedContentQuery query)
: this(umbracoContext)
{
if (query == null) throw new ArgumentNullException("query");
_query = query;
}
#endregion
/// <summary>
/// Returns the current IPublishedContent item assigned to the UmbracoHelper
/// </summary>
/// <remarks>
/// Note that this is the assigned IPublishedContent item to the UmbracoHelper, this is not necessarily the Current IPublishedContent item
/// being rendered. This IPublishedContent object is contextual to the current UmbracoHelper instance.
///
/// In some cases accessing this property will throw an exception if there is not IPublishedContent assigned to the Helper
/// this will only ever happen if the Helper is constructed with an UmbracoContext and it is not a front-end request
/// </remarks>
/// <exception cref="InvalidOperationException">Thrown if the UmbracoHelper is constructed with an UmbracoContext and it is not a front-end request</exception>
public IPublishedContent AssignedContentItem
{
get
{
if (_currentPage == null)
throw new InvalidOperationException("Cannot return the " + typeof(IPublishedContent).Name + " because the " + typeof(UmbracoHelper).Name + " was constructed with an " + typeof(UmbracoContext).Name + " and the current request is not a front-end request.");
return _currentPage;
}
}
/// <summary>
/// Renders the template for the specified pageId and an optional altTemplateId
/// </summary>
/// <param name="pageId"></param>
/// <param name="altTemplateId">If not specified, will use the template assigned to the node</param>
/// <returns></returns>
public IHtmlString RenderTemplate(int pageId, int? altTemplateId = null)
{
return UmbracoComponentRenderer.RenderTemplate(pageId, altTemplateId);
}
#region RenderMacro
/// <summary>
/// Renders the macro with the specified alias.
/// </summary>
/// <param name="alias">The alias.</param>
/// <returns></returns>
public IHtmlString RenderMacro(string alias)
{
return UmbracoComponentRenderer.RenderMacro(alias, new { });
}
/// <summary>
/// Renders the macro with the specified alias, passing in the specified parameters.
/// </summary>
/// <param name="alias">The alias.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
public IHtmlString RenderMacro(string alias, object parameters)
{
return UmbracoComponentRenderer.RenderMacro(alias, parameters.ToDictionary<object>());
}
/// <summary>
/// Renders the macro with the specified alias, passing in the specified parameters.
/// </summary>
/// <param name="alias">The alias.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
public IHtmlString RenderMacro(string alias, IDictionary<string, object> parameters)
{
return UmbracoComponentRenderer.RenderMacro(alias, parameters);
}
#endregion
#region Field
/// <summary>
/// Renders an field to the template
/// </summary>
/// <param name="fieldAlias"></param>
/// <param name="altFieldAlias"></param>
/// <param name="altText"></param>
/// <param name="insertBefore"></param>
/// <param name="insertAfter"></param>
/// <param name="recursive"></param>
/// <param name="convertLineBreaks"></param>
/// <param name="removeParagraphTags"></param>
/// <param name="casing"></param>
/// <param name="encoding"></param>
/// <param name="formatAsDate"></param>
/// <param name="formatAsDateWithTime"></param>
/// <param name="formatAsDateWithTimeSeparator"></param>
//// <param name="formatString"></param>
/// <returns></returns>
public IHtmlString Field(string fieldAlias,
string altFieldAlias = "", string altText = "", string insertBefore = "", string insertAfter = "",
bool recursive = false, bool convertLineBreaks = false, bool removeParagraphTags = false,
RenderFieldCaseType casing = RenderFieldCaseType.Unchanged,
RenderFieldEncodingType encoding = RenderFieldEncodingType.Unchanged,
bool formatAsDate = false,
bool formatAsDateWithTime = false,
string formatAsDateWithTimeSeparator = "")
{
return UmbracoComponentRenderer.Field(AssignedContentItem, fieldAlias, altFieldAlias,
altText, insertBefore, insertAfter, recursive, convertLineBreaks, removeParagraphTags,
casing, encoding, formatAsDate, formatAsDateWithTime, formatAsDateWithTimeSeparator);
}
/// <summary>
/// Renders an field to the template
/// </summary>
/// <param name="currentPage"></param>
/// <param name="fieldAlias"></param>
/// <param name="altFieldAlias"></param>
/// <param name="altText"></param>
/// <param name="insertBefore"></param>
/// <param name="insertAfter"></param>
/// <param name="recursive"></param>
/// <param name="convertLineBreaks"></param>
/// <param name="removeParagraphTags"></param>
/// <param name="casing"></param>
/// <param name="encoding"></param>
/// <param name="formatAsDate"></param>
/// <param name="formatAsDateWithTime"></param>
/// <param name="formatAsDateWithTimeSeparator"></param>
//// <param name="formatString"></param>
/// <returns></returns>
public IHtmlString Field(IPublishedContent currentPage, string fieldAlias,
string altFieldAlias = "", string altText = "", string insertBefore = "", string insertAfter = "",
bool recursive = false, bool convertLineBreaks = false, bool removeParagraphTags = false,
RenderFieldCaseType casing = RenderFieldCaseType.Unchanged,
RenderFieldEncodingType encoding = RenderFieldEncodingType.Unchanged,
bool formatAsDate = false,
bool formatAsDateWithTime = false,
string formatAsDateWithTimeSeparator = "")
{
return UmbracoComponentRenderer.Field(currentPage, fieldAlias, altFieldAlias,
altText, insertBefore, insertAfter, recursive, convertLineBreaks, removeParagraphTags,
casing, encoding, formatAsDate, formatAsDateWithTime, formatAsDateWithTimeSeparator);
}
#endregion
#region Dictionary
/// <summary>
/// Returns the dictionary value for the key specified
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string GetDictionaryValue(string key)
{
return CultureDictionary[key];
}
/// <summary>
/// Returns the dictionary value for the key specified, and if empty returns the specified default fall back value
/// </summary>
/// <param name="key">key of dictionary item</param>
/// <param name="altText">fall back text if dictionary item is empty - Name altText to match Umbraco.Field</param>
/// <returns></returns>
public string GetDictionaryValue(string key, string altText)
{
var dictionaryValue = GetDictionaryValue(key);
if (String.IsNullOrWhiteSpace(dictionaryValue))
{
dictionaryValue = altText;
}
return dictionaryValue;
}
/// <summary>
/// Returns the ICultureDictionary for access to dictionary items
/// </summary>
public ICultureDictionary CultureDictionary
{
get
{
if (_cultureDictionary == null)
{
var factory = CultureDictionaryFactoryResolver.Current.Factory;
_cultureDictionary = factory.CreateDictionary();
}
return _cultureDictionary;
}
}
#endregion
#region Membership
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use the IsProtected method that only specifies path")]
public bool IsProtected(int documentId, string path)
{
return IsProtected(path.EnsureEndsWith("," + documentId));
}
/// <summary>
/// Check if a document object is protected by the "Protect Pages" functionality in umbraco
/// </summary>
/// <param name="path">The full path of the document object to check</param>
/// <returns>True if the document object is protected</returns>
public bool IsProtected(string path)
{
return UmbracoContext.Application.Services.PublicAccessService.IsProtected(path);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use the MemberHasAccess method that only specifies path")]
public bool MemberHasAccess(int nodeId, string path)
{
return MemberHasAccess(path.EnsureEndsWith("," + nodeId));
}
/// <summary>
/// Check if the current user has access to a document
/// </summary>
/// <param name="path">The full path of the document object to check</param>
/// <returns>True if the current user has access or if the current document isn't protected</returns>
public bool MemberHasAccess(string path)
{
if (IsProtected(path))
{
return MembershipHelper.IsLoggedIn()
&& UmbracoContext.Application.Services.PublicAccessService.HasAccess(path, GetCurrentMember(), Roles.Provider);
}
return true;
}
/// <summary>
/// Gets (or adds) the current member from the current request cache
/// </summary>
private MembershipUser GetCurrentMember()
{
return UmbracoContext.Application.ApplicationCache.RequestCache
.GetCacheItem<MembershipUser>("UmbracoHelper.GetCurrentMember", () =>
{
var provider = Core.Security.MembershipProviderExtensions.GetMembersMembershipProvider();
return provider.GetCurrentUser();
});
}
/// <summary>
/// Whether or not the current member is logged in (based on the membership provider)
/// </summary>
/// <returns>True is the current user is logged in</returns>
public bool MemberIsLoggedOn()
{
return MembershipHelper.IsLoggedIn();
}
#endregion
#region NiceUrls
/// <summary>
/// Returns a string with a friendly url from a node.
/// IE.: Instead of having /482 (id) as an url, you can have
/// /screenshots/developer/macros (spoken url)
/// </summary>
/// <param name="nodeId">Identifier for the node that should be returned</param>
/// <returns>String with a friendly url from a node</returns>
public string NiceUrl(int nodeId)
{
return Url(nodeId);
}
/// <summary>
/// Gets the url of a content identified by its identifier.
/// </summary>
/// <param name="contentId">The content identifier.</param>
/// <returns>The url for the content.</returns>
public string Url(int contentId)
{
return UrlProvider.GetUrl(contentId);
}
/// <summary>
/// Gets the url of a content identified by its identifier, in a specified mode.
/// </summary>
/// <param name="contentId">The content identifier.</param>
/// <param name="mode">The mode.</param>
/// <returns>The url for the content.</returns>
public string Url(int contentId, UrlProviderMode mode)
{
return UrlProvider.GetUrl(contentId, mode);
}
/// <summary>
/// This method will always add the domain to the path if the hostnames are set up correctly.
/// </summary>
/// <param name="nodeId">Identifier for the node that should be returned</param>
/// <returns>String with a friendly url with full domain from a node</returns>
public string NiceUrlWithDomain(int nodeId)
{
return UrlAbsolute(nodeId);
}
/// <summary>
/// Gets the absolute url of a content identified by its identifier.
/// </summary>
/// <param name="contentId">The content identifier.</param>
/// <returns>The absolute url for the content.</returns>
public string UrlAbsolute(int contentId)
{
return UrlProvider.GetUrl(contentId, true);
}
#endregion
#region Members
public IPublishedContent TypedMember(object id)
{
var asInt = id.TryConvertTo<int>();
return asInt ? MembershipHelper.GetById(asInt.Result) : MembershipHelper.GetByProviderKey(id);
}
public IPublishedContent TypedMember(int id)
{
return MembershipHelper.GetById(id);
}
public IPublishedContent TypedMember(string id)
{
var asInt = id.TryConvertTo<int>();
return asInt ? MembershipHelper.GetById(asInt.Result) : MembershipHelper.GetByProviderKey(id);
}
public dynamic Member(object id)
{
var asInt = id.TryConvertTo<int>();
return asInt
? MembershipHelper.GetById(asInt.Result).AsDynamic()
: MembershipHelper.GetByProviderKey(id).AsDynamic();
}
public dynamic Member(int id)
{
return MembershipHelper.GetById(id).AsDynamic();
}
public dynamic Member(string id)
{
var asInt = id.TryConvertTo<int>();
return asInt
? MembershipHelper.GetById(asInt.Result).AsDynamic()
: MembershipHelper.GetByProviderKey(id).AsDynamic();
}
#endregion
#region Content
/// <summary>
/// Gets a content item from the cache.
/// </summary>
/// <param name="id">The unique identifier, or the key, of the content item.</param>
/// <returns>The content, or null of the content item is not in the cache.</returns>
public IPublishedContent TypedContent(object id)
{
return TypedContentForObject(id);
}
private IPublishedContent TypedContentForObject(object id)
{
int intId;
if (ConvertIdObjectToInt(id, out intId))
return ContentQuery.TypedContent(intId);
Guid guidId;
if (ConvertIdObjectToGuid(id, out guidId))
return ContentQuery.TypedContent(guidId);
return null;
}
/// <summary>
/// Gets a content item from the cache.
/// </summary>
/// <param name="id">The unique identifier of the content item.</param>
/// <returns>The content, or null of the content item is not in the cache.</returns>
public IPublishedContent TypedContent(int id)
{
return ContentQuery.TypedContent(id);
}
/// <summary>
/// Gets a content item from the cache.
/// </summary>
/// <param name="id">The key of the content item.</param>
/// <returns>The content, or null of the content item is not in the cache.</returns>
public IPublishedContent TypedContent(Guid id)
{
return ContentQuery.TypedContent(id);
}
/// <summary>
/// Gets a content item from the cache.
/// </summary>
/// <param name="id">The unique identifier, or the key, of the content item.</param>
/// <returns>The content, or null of the content item is not in the cache.</returns>
public IPublishedContent TypedContent(string id)
{
return TypedContentForObject(id);
}
public IPublishedContent TypedContentSingleAtXPath(string xpath, params XPathVariable[] vars)
{
return ContentQuery.TypedContentSingleAtXPath(xpath, vars);
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers, or the keys, of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
/// <remarks>Does not support mixing identifiers and keys.</remarks>
public IEnumerable<IPublishedContent> TypedContent(params object[] ids)
{
return TypedContentForObjects(ids);
}
private IEnumerable<IPublishedContent> TypedContentForObjects(IEnumerable<object> ids)
{
var idsA = ids.ToArray();
IEnumerable<int> intIds;
if (ConvertIdsObjectToInts(idsA, out intIds))
return ContentQuery.TypedContent(intIds);
IEnumerable<Guid> guidIds;
if (ConvertIdsObjectToGuids(idsA, out guidIds))
return ContentQuery.TypedContent(guidIds);
return Enumerable.Empty<IPublishedContent>();
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
public IEnumerable<IPublishedContent> TypedContent(params int[] ids)
{
return ContentQuery.TypedContent(ids);
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The keys of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
public IEnumerable<IPublishedContent> TypedContent(params Guid[] ids)
{
return ContentQuery.TypedContent(ids);
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers, or the keys, of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
/// <remarks>Does not support mixing identifiers and keys.</remarks>
public IEnumerable<IPublishedContent> TypedContent(params string[] ids)
{
return TypedContentForObjects(ids);
}
/// <summary>
/// Gets the contents corresponding to the identifiers.
/// </summary>
/// <param name="ids">The content identifiers.</param>
/// <returns>The existing contents corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing content, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedContent(IEnumerable<object> ids)
{
return TypedContentForObjects(ids);
}
/// <summary>
/// Gets the contents corresponding to the identifiers.
/// </summary>
/// <param name="ids">The content identifiers.</param>
/// <returns>The existing contents corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing content, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedContent(IEnumerable<string> ids)
{
return TypedContentForObjects(ids);
}
/// <summary>
/// Gets the contents corresponding to the identifiers.
/// </summary>
/// <param name="ids">The content identifiers.</param>
/// <returns>The existing contents corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing content, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedContent(IEnumerable<int> ids)
{
return ContentQuery.TypedContent(ids);
}
public IEnumerable<IPublishedContent> TypedContentAtXPath(string xpath, params XPathVariable[] vars)
{
return ContentQuery.TypedContentAtXPath(xpath, vars);
}
public IEnumerable<IPublishedContent> TypedContentAtXPath(XPathExpression xpath, params XPathVariable[] vars)
{
return ContentQuery.TypedContentAtXPath(xpath, vars);
}
public IEnumerable<IPublishedContent> TypedContentAtRoot()
{
return ContentQuery.TypedContentAtRoot();
}
/// <summary>
/// Gets a content item from the cache.
/// </summary>
/// <param name="id">The unique identifier, or the key, of the content item.</param>
/// <returns>The content, or DynamicNull of the content item is not in the cache.</returns>
public dynamic Content(object id)
{
return ContentForObject(id);
}
private dynamic ContentForObject(object id)
{
int intId;
if (ConvertIdObjectToInt(id, out intId))
return ContentQuery.Content(intId);
Guid guidId;
if (ConvertIdObjectToGuid(id, out guidId))
return ContentQuery.Content(guidId);
return DynamicNull.Null;
}
/// <summary>
/// Gets a content item from the cache.
/// </summary>
/// <param name="id">The unique identifier of the content item.</param>
/// <returns>The content, or DynamicNull of the content item is not in the cache.</returns>
public dynamic Content(int id)
{
return ContentQuery.Content(id);
}
/// <summary>
/// Gets a content item from the cache.
/// </summary>
/// <param name="id">The unique identifier, or the key, of the content item.</param>
/// <returns>The content, or DynamicNull of the content item is not in the cache.</returns>
public dynamic Content(string id)
{
return ContentForObject(id);
}
public dynamic ContentSingleAtXPath(string xpath, params XPathVariable[] vars)
{
return ContentQuery.ContentSingleAtXPath(xpath, vars);
}
public dynamic ContentSingleAtXPath(XPathExpression xpath, params XPathVariable[] vars)
{
return ContentQuery.ContentSingleAtXPath(xpath, vars);
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers, or the keys, of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
/// <remarks>Does not support mixing identifiers and keys.</remarks>
public dynamic Content(params object[] ids)
{
return ContentForObjects(ids);
}
private dynamic ContentForObjects(IEnumerable<object> ids)
{
var idsA = ids.ToArray();
IEnumerable<int> intIds;
if (ConvertIdsObjectToInts(idsA, out intIds))
return ContentQuery.Content(intIds);
IEnumerable<Guid> guidIds;
if (ConvertIdsObjectToGuids(idsA, out guidIds))
return ContentQuery.Content(guidIds);
return Enumerable.Empty<IPublishedContent>();
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
public dynamic Content(params int[] ids)
{
return ContentQuery.Content(ids);
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers, or the keys, of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
/// <remarks>Does not support mixing identifiers and keys.</remarks>
public dynamic Content(params string[] ids)
{
return ContentForObjects(ids);
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers, or the keys, of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
/// <remarks>Does not support mixing identifiers and keys.</remarks>
public dynamic Content(IEnumerable<object> ids)
{
return ContentForObjects(ids);
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
public dynamic Content(IEnumerable<int> ids)
{
return ContentQuery.Content(ids);
}
/// <summary>
/// Gets content items from the cache.
/// </summary>
/// <param name="ids">The unique identifiers, or the keys, of the content items.</param>
/// <returns>The content items that were found in the cache.</returns>
/// <remarks>Does not support mixing identifiers and keys.</remarks>
public dynamic Content(IEnumerable<string> ids)
{
return ContentForObjects(ids);
}
public dynamic ContentAtXPath(string xpath, params XPathVariable[] vars)
{
return ContentQuery.ContentAtXPath(xpath, vars);
}
public dynamic ContentAtXPath(XPathExpression xpath, params XPathVariable[] vars)
{
return ContentQuery.ContentAtXPath(xpath, vars);
}
public dynamic ContentAtRoot()
{
return ContentQuery.ContentAtRoot();
}
private static bool ConvertIdObjectToInt(object id, out int intId)
{
var s = id as string;
if (s != null)
{
return int.TryParse(s, out intId);
}
if (id is int)
{
intId = (int) id;
return true;
}
intId = default(int);
return false;
}
private static bool ConvertIdObjectToGuid(object id, out Guid guidId)
{
var s = id as string;
if (s != null)
{
return Guid.TryParse(s, out guidId);
}
if (id is Guid)
{
guidId = (Guid) id;
return true;
}
guidId = default(Guid);
return false;
}
private static bool ConvertIdsObjectToInts(IEnumerable<object> ids, out IEnumerable<int> intIds)
{
var list = new List<int>();
intIds = null;
foreach (var id in ids)
{
int intId;
if (ConvertIdObjectToInt(id, out intId))
list.Add(intId);
else
return false; // if one of them is not an int, fail
}
intIds = list;
return true;
}
private static bool ConvertIdsObjectToGuids(IEnumerable<object> ids, out IEnumerable<Guid> guidIds)
{
var list = new List<Guid>();
guidIds = null;
foreach (var id in ids)
{
Guid guidId;
if (ConvertIdObjectToGuid(id, out guidId))
list.Add(guidId);
else
return false; // if one of them is not a guid, fail
}
guidIds = list;
return true;
}
#endregion
#region Media
/// <summary>
/// Overloaded method accepting an 'object' type
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
/// <remarks>
/// We accept an object type because GetPropertyValue now returns an 'object', we still want to allow people to pass
/// this result in to this method.
/// This method will throw an exception if the value is not of type int or string.
/// </remarks>
public IPublishedContent TypedMedia(object id)
{
int intId;
return ConvertIdObjectToInt(id, out intId) ? ContentQuery.TypedMedia(intId) : null;
}
public IPublishedContent TypedMedia(int id)
{
return ContentQuery.TypedMedia(id);
}
public IPublishedContent TypedMedia(string id)
{
int intId;
return ConvertIdObjectToInt(id, out intId) ? ContentQuery.TypedMedia(intId) : null;
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedMedia(params object[] ids)
{
return TypedMediaForObjects(ids);
}
private IEnumerable<IPublishedContent> TypedMediaForObjects(IEnumerable<object> ids)
{
var idsA = ids.ToArray();
IEnumerable<int> intIds;
if (ConvertIdsObjectToInts(idsA, out intIds))
return ContentQuery.TypedMedia(intIds);
//IEnumerable<Guid> guidIds;
//if (ConvertIdsObjectToGuids(idsA, out guidIds))
// return ContentQuery.TypedMedia(guidIds);
return Enumerable.Empty<IPublishedContent>();
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedMedia(params int[] ids)
{
return ContentQuery.TypedMedia(ids);
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedMedia(params string[] ids)
{
return TypedMediaForObjects(ids);
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedMedia(IEnumerable<object> ids)
{
return TypedMediaForObjects(ids);
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedMedia(IEnumerable<int> ids)
{
return ContentQuery.TypedMedia(ids);
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public IEnumerable<IPublishedContent> TypedMedia(IEnumerable<string> ids)
{
return TypedMediaForObjects(ids);
}
public IEnumerable<IPublishedContent> TypedMediaAtRoot()
{
return ContentQuery.TypedMediaAtRoot();
}
public dynamic Media(object id)
{
int intId;
return ConvertIdObjectToInt(id, out intId) ? ContentQuery.Media(intId) : DynamicNull.Null;
}
public dynamic Media(int id)
{
return ContentQuery.Media(id);
}
public dynamic Media(string id)
{
int intId;
return ConvertIdObjectToInt(id, out intId) ? ContentQuery.Media(intId) : DynamicNull.Null;
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public dynamic Media(params object[] ids)
{
return MediaForObjects(ids);
}
private dynamic MediaForObjects(IEnumerable<object> ids)
{
var idsA = ids.ToArray();
IEnumerable<int> intIds;
if (ConvertIdsObjectToInts(idsA, out intIds))
return ContentQuery.Media(intIds);
//IEnumerable<Guid> guidIds;
//if (ConvertIdsObjectToGuids(idsA, out guidIds))
// return ContentQuery.Media(guidIds);
return Enumerable.Empty<IPublishedContent>();
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public dynamic Media(params int[] ids)
{
return ContentQuery.Media(ids);
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public dynamic Media(params string[] ids)
{
return MediaForObjects(ids);
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public dynamic Media(IEnumerable<object> ids)
{
return MediaForObjects(ids);
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public dynamic Media(IEnumerable<int> ids)
{
return ContentQuery.Media(ids);
}
/// <summary>
/// Gets the medias corresponding to the identifiers.
/// </summary>
/// <param name="ids">The media identifiers.</param>
/// <returns>The existing medias corresponding to the identifiers.</returns>
/// <remarks>If an identifier does not match an existing media, it will be missing in the returned value.</remarks>
public dynamic Media(IEnumerable<string> ids)
{
return MediaForObjects(ids);
}
public dynamic MediaAtRoot()
{
return ContentQuery.MediaAtRoot();
}
#endregion
#region Search
/// <summary>
/// Searches content
/// </summary>
/// <param name="term"></param>
/// <param name="useWildCards"></param>
/// <param name="searchProvider"></param>
/// <returns></returns>
public dynamic Search(string term, bool useWildCards = true, string searchProvider = null)
{
return ContentQuery.Search(term, useWildCards, searchProvider);
}
/// <summary>
/// Searhes content
/// </summary>
/// <param name="criteria"></param>
/// <param name="searchProvider"></param>
/// <returns></returns>
public dynamic Search(Examine.SearchCriteria.ISearchCriteria criteria, Examine.Providers.BaseSearchProvider searchProvider = null)
{
return ContentQuery.Search(criteria, searchProvider);
}
/// <summary>
/// Searches content
/// </summary>
/// <param name="term"></param>
/// <param name="useWildCards"></param>
/// <param name="searchProvider"></param>
/// <returns></returns>
public IEnumerable<IPublishedContent> TypedSearch(string term, bool useWildCards = true, string searchProvider = null)
{
return ContentQuery.TypedSearch(term, useWildCards, searchProvider);
}
/// <summary>
/// Searhes content
/// </summary>
/// <param name="criteria"></param>
/// <param name="searchProvider"></param>
/// <returns></returns>
public IEnumerable<IPublishedContent> TypedSearch(Examine.SearchCriteria.ISearchCriteria criteria, Examine.Providers.BaseSearchProvider searchProvider = null)
{
return ContentQuery.TypedSearch(criteria, searchProvider);
}
#endregion
#region Xml
public dynamic ToDynamicXml(string xml)
{
if (string.IsNullOrWhiteSpace(xml)) return null;
var xElement = XElement.Parse(xml);
return new DynamicXml(xElement);
}
public dynamic ToDynamicXml(XElement xElement)
{
return new DynamicXml(xElement);
}
public dynamic ToDynamicXml(XPathNodeIterator xpni)
{
return new DynamicXml(xpni);
}
#endregion
#region Strings
/// <summary>
/// Replaces text line breaks with html line breaks
/// </summary>
/// <param name="text">The text.</param>
/// <returns>The text with text line breaks replaced with html linebreaks (<br/>)</returns>
public string ReplaceLineBreaksForHtml(string text)
{
return _stringUtilities.ReplaceLineBreaksForHtml(text);
}
/// <summary>
/// Returns an MD5 hash of the string specified
/// </summary>
/// <param name="text">The text to create a hash from</param>
/// <returns>Md5 has of the string</returns>
public string CreateMd5Hash(string text)
{
return text.ToMd5();
}
/// <summary>
/// Strips all html tags from a given string, all contents of the tags will remain.
/// </summary>
public HtmlString StripHtml(IHtmlString html, params string[] tags)
{
return StripHtml(html.ToHtmlString(), tags);
}
/// <summary>
/// Strips all html tags from a given string, all contents of the tags will remain.
/// </summary>
public HtmlString StripHtml(DynamicNull html, params string[] tags)
{
return new HtmlString(string.Empty);
}
/// <summary>
/// Strips all html tags from a given string, all contents of the tags will remain.
/// </summary>
public HtmlString StripHtml(string html, params string[] tags)
{
return _stringUtilities.StripHtmlTags(html, tags);
}
/// <summary>
/// Will take the first non-null value in the collection and return the value of it.
/// </summary>
public string Coalesce(params object[] args)
{
return _stringUtilities.Coalesce<DynamicNull>(args);
}
/// <summary>
/// Will take the first non-null value in the collection and return the value of it.
/// </summary>
public string Concatenate(params object[] args)
{
return _stringUtilities.Concatenate<DynamicNull>(args);
}
/// <summary>
/// Joins any number of int/string/objects into one string and seperates them with the string seperator parameter.
/// </summary>
public string Join(string seperator, params object[] args)
{
return _stringUtilities.Join<DynamicNull>(seperator, args);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(IHtmlString html, int length)
{
return Truncate(html.ToHtmlString(), length, true, false);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(IHtmlString html, int length, bool addElipsis)
{
return Truncate(html.ToHtmlString(), length, addElipsis, false);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(IHtmlString html, int length, bool addElipsis, bool treatTagsAsContent)
{
return Truncate(html.ToHtmlString(), length, addElipsis, treatTagsAsContent);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(DynamicNull html, int length)
{
return new HtmlString(string.Empty);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(DynamicNull html, int length, bool addElipsis)
{
return new HtmlString(string.Empty);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(DynamicNull html, int length, bool addElipsis, bool treatTagsAsContent)
{
return new HtmlString(string.Empty);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(string html, int length)
{
return Truncate(html, length, true, false);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(string html, int length, bool addElipsis)
{
return Truncate(html, length, addElipsis, false);
}
/// <summary>
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
/// </summary>
public IHtmlString Truncate(string html, int length, bool addElipsis, bool treatTagsAsContent)
{
return _stringUtilities.Truncate(html, length, addElipsis, treatTagsAsContent);
}
#endregion
#region If
/// <summary>
/// If the test is true, the string valueIfTrue will be returned, otherwise the valueIfFalse will be returned.
/// </summary>
public HtmlString If(bool test, string valueIfTrue, string valueIfFalse)
{
return test ? new HtmlString(valueIfTrue) : new HtmlString(valueIfFalse);
}
/// <summary>
/// If the test is true, the string valueIfTrue will be returned, otherwise the valueIfFalse will be returned.
/// </summary>
public HtmlString If(bool test, string valueIfTrue)
{
return test ? new HtmlString(valueIfTrue) : new HtmlString(string.Empty);
}
#endregion
#region Prevalues
/// <summary>
/// Gets a specific PreValue by its Id
/// </summary>
/// <param name="id">Id of the PreValue to retrieve the value from</param>
/// <returns>PreValue as a string</returns>
public string GetPreValueAsString(int id)
{
return DataTypeService.GetPreValueAsString(id);
}
#endregion
#region canvasdesigner
[Obsolete("Use EnableCanvasDesigner on the HtmlHelper extensions instead")]
public IHtmlString EnableCanvasDesigner()
{
return EnableCanvasDesigner(string.Empty, string.Empty);
}
[Obsolete("Use EnableCanvasDesigner on the HtmlHelper extensions instead")]
public IHtmlString EnableCanvasDesigner(string canvasdesignerConfigPath)
{
return EnableCanvasDesigner(canvasdesignerConfigPath, string.Empty);
}
[Obsolete("Use EnableCanvasDesigner on the HtmlHelper extensions instead")]
public IHtmlString EnableCanvasDesigner(string canvasdesignerConfigPath, string canvasdesignerPalettesPath)
{
var html = CreateHtmlHelper("");
var urlHelper = new UrlHelper(UmbracoContext.HttpContext.Request.RequestContext);
return html.EnableCanvasDesigner(urlHelper, UmbracoContext, canvasdesignerConfigPath, canvasdesignerPalettesPath);
}
[Obsolete("This shouldn't need to be used but because the obsolete extension methods above don't have access to the current HtmlHelper, we need to create a fake one, unfortunately however this will not pertain the current views viewdata, tempdata or model state so should not be used")]
private HtmlHelper CreateHtmlHelper(object model)
{
var cc = new ControllerContext
{
RequestContext = UmbracoContext.HttpContext.Request.RequestContext
};
var viewContext = new ViewContext(cc, new FakeView(), new ViewDataDictionary(model), new TempDataDictionary(), new StringWriter());
var htmlHelper = new HtmlHelper(viewContext, new ViewPage());
return htmlHelper;
}
[Obsolete("This shouldn't need to be used but because the obsolete extension methods above don't have access to the current HtmlHelper, we need to create a fake one, unfortunately however this will not pertain the current views viewdata, tempdata or model state so should not be used")]
private class FakeView : IView
{
public void Render(ViewContext viewContext, TextWriter writer)
{
}
}
#endregion
/// <summary>
/// This is used in methods like BeginUmbracoForm and SurfaceAction to generate an encrypted string which gets submitted in a request for which
/// Umbraco can decrypt during the routing process in order to delegate the request to a specific MVC Controller.
/// </summary>
/// <param name="controllerName"></param>
/// <param name="controllerAction"></param>
/// <param name="area"></param>
/// <param name="additionalRouteVals"></param>
/// <returns></returns>
internal static string CreateEncryptedRouteString(string controllerName, string controllerAction, string area, object additionalRouteVals = null)
{
Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName");
Mandate.ParameterNotNullOrEmpty(controllerAction, "controllerAction");
Mandate.ParameterNotNull(area, "area");
//need to create a params string as Base64 to put into our hidden field to use during the routes
var surfaceRouteParams = string.Format("c={0}&a={1}&ar={2}",
HttpUtility.UrlEncode(controllerName),
HttpUtility.UrlEncode(controllerAction),
area);
//checking if the additional route values is already a dictionary and convert to querystring
string additionalRouteValsAsQuery;
if (additionalRouteVals != null)
{
var additionalRouteValsAsDictionary = additionalRouteVals as Dictionary<string, object>;
if (additionalRouteValsAsDictionary != null)
additionalRouteValsAsQuery = additionalRouteValsAsDictionary.ToQueryString();
else
additionalRouteValsAsQuery = additionalRouteVals.ToDictionary<object>().ToQueryString();
}
else
additionalRouteValsAsQuery = null;
if (additionalRouteValsAsQuery.IsNullOrWhiteSpace() == false)
surfaceRouteParams += "&" + additionalRouteValsAsQuery;
return surfaceRouteParams.EncryptWithMachineKey();
}
}
}
| gavinfaux/Umbraco-CMS | src/Umbraco.Web/UmbracoHelper.cs | C# | mit | 59,353 |
* {
margin: 0px;
padding: 0px;
}
body{
overflow:hidden;
background-color: black;
}
@font-face {
font-family: Bang;
src: url('bang.ttf');
}
@media screen and (max-height: 650px) {
#clouds{
height: 220px;
}
}
}
#wrapper {
width: 100%;
height: 100%;
}
#score {
color: #fff;
font-family: Bang;
font-size: 1.6em;
position:absolute;
top: 90%;
left:45%;
z-index:5;
display: none;
}
#sceneWrapper {
margin-left: auto;
margin-right: auto;
display: block;
width: 100%;
height: 700px;
position:absolute;
width: 100%;
overflow: hidden;
bottom: 10%;
}
#bg-left {
float:left;
height:700px;
}
#bg-right {
float:left;
height:700px;
}
footer {
position:absolute;
width: 100%;
z-index:1;
height: 10%;
background-color: black;
display: block;
top: 89%;
}
canvas{
float:left;
display:block;
margin:0;
padding:0;
width: 800px;
z-index: -1;
}
#menuscreen-start {
font-family: Bang;
position:absolute;
display: block;
width: 300px;
height: 150px;
z-index:100;
left:50%;
margin-left: -150px;
bottom:50%;
margin-bottom: -75px;
text-align:center;
color: #FFF;
font-size:2em;
}
#menuscreen-start h1, #menuscreen-end h1 {
color: #C1003F;
-webkit-text-stroke-width: 2px;
-webkit-text-stroke-color: black;
}
#menuscreen-start h1:hover , #menuscreen-end h1:hover {
cursor:default;
}
#menuscreen-start p:hover , #menuscreen-end h2:hover {
cursor: pointer;
}
#menuscreen-end {
font-family: Bang;
position:absolute;
display: none;
width: 300px;
height: 150px;
color: #fff;
z-index:100;
left:50%;
margin-left: -150px;
bottom:50%;
margin-bottom: -75px;
text-align: center;
font-size: 1.2em;
}
#buildings {
background: url(img/buildingsbg.gif) no-repeat center center ;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
width: 100%;
height:90%;
z-index: 0;
position:absolute;
}
#clouds{
padding: 100px 0;
background: #c9dbe9;
background: -webkit-linear-gradient(top, #191381 0%, #001848 50%, #D07D00 100%);
background: -linear-gradient(top, #c9dbe9 0%, #fff 100%);
background: -moz-linear-gradient(top, #c9dbe9 0%, #fff 100%);
height: 320px;
}
.cloud {
width: 200px; height: 60px;
background: #989898 ;
z-index:0;
border-radius: 200px;
-moz-border-radius: 200px;
-webkit-border-radius: 200px;
position: relative;
}
.cloud:before, .cloud:after {
content: '';
position: absolute;
background: #989898 ;
width: 100px; height: 80px;
position: absolute; top: -15px; left: 10px;
border-radius: 100px;
-moz-border-radius: 100px;
-webkit-border-radius: 100px;
-webkit-transform: rotate(30deg);
transform: rotate(30deg);
-moz-transform: rotate(30deg);
}
.cloud:after {
width: 120px; height: 120px;
top: -55px; left: auto; right: 15px;
}
.cloud {
-webkit-animation: moveclouds 15s linear infinite;
-o-animation: moveclouds 15s linear infinite;
-moz-animation: moveclouds 15s linear infinite;
}
.x1 {
-webkit-animation: moveclouds 25s linear infinite;
-moz-animation: moveclouds 25s linear infinite;
-o-animation: moveclouds 25s linear infinite;
}
.x2 {
left: 65%; top: -250px;
-webkit-transform: scale(0.5);
-moz-transform: scale(0.5);
-o-transform: scale(0.5);
transform:scale(0.5);
-webkit-animation: moveclouds 18s linear infinite;
-moz-animation: moveclouds 18s linear infinite;
-o-animation: moveclouds 18s linear infinite;
opacity: 0.5;
}
.x3 {
left: 25%; top: -220px;
-webkit-transform: scale(0.6);
-moz-transform: scale(0.6);
-o-transform: scale(0.6);
transform:scale(0.6);
-webkit-animation: moveclouds 13s linear infinite;
-moz-animation: moveclouds 13s linear infinite;
-o-animation: moveclouds 13s linear infinite;
opacity: 0.6;
}
.x4 {
left: 80%; top: -120px;
-webkit-transform: scale(0.75);
-moz-transform: scale(0.75);
-o-transform: scale(0.75);
transform:scale(0.75);
-webkit-animation: moveclouds 16s linear infinite;
-moz-animation: moveclouds 16s linear infinite;
-o-animation: moveclouds 16s linear infinite;
opacity: 0.75;
}
.x5 {
left: 35%; top: -200px;
-webkit-transform: scale(0.4);
-moz-transform: scale(0.4);
-o-transform: scale(0.4);
transform:scale(0.4);
-webkit-animation: moveclouds 20s linear infinite;
-moz-animation: moveclouds 20s linear infinite;
-o-animation: moveclouds 20s linear infinite;
opacity: 0.4;
}
.x6 {
left: 15%; top: -100px;
-webkit-transform: scale(0.8);
-moz-transform: scale(0.8);
-o-transform: scale(0.8);
transform:scale(0.8);
-webkit-animation: moveclouds 26s linear infinite;
-moz-animation: moveclouds 26s linear infinite;
-o-animation: moveclouds 26s linear infinite;
opacity: 0.8;
}
.x7 {
left: 45%; top: -175px;
-webkit-transform: scale(0.65);
-moz-transform: scale(0.65);
-o-transform: scale(0.65);
transform:scale(0.65);
-webkit-animation: moveclouds 14s linear infinite;
-moz-animation: moveclouds 14s linear infinite;
-o-animation: moveclouds 14s linear infinite;
opacity: 0.65);
}
@-webkit-keyframes moveclouds {
0% { margin-left: 100%;}
100% {margin-left: -100%;}
}
@-moz-keyframes moveclouds {
0% {margin-left: 100%}
100% {margin-left: -100%;}
}
@-o-keyframes moveclouds {
0% {margin-left: 100%;}
100% {margin-left: -100%;}
} | Kaizeras/ChalgaScript | gfx.css | CSS | mit | 5,626 |
use std::str::FromStr;
fn read_line() -> String {
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Could not read stdin!");
input
}
fn read_multiple<F>(sep: &str) -> Vec<F> where F: FromStr {
read_line().trim().split(sep).map(|token| token.parse().ok().unwrap()).collect()
}
fn gcd(a: u64, b: u64) -> u64 {
if a == 0 {
b
} else {
gcd(b % a, a)
}
}
fn main() {
let input = read_multiple::<u64>(" ");
let (a, b) = (input[0], input[1]);
println!("{}", gcd(a, b));
}
| Bugfry/exercism | hackerrank/30-days-of-code/day009.rs | Rust | mit | 527 |
---
layout: page
status: publish
published: true
title: 'MPC IN THE NEWS: Where We Came From and Where We Went, State by State'
author: mpcit
teaser: 'The folks at the NYT''s Upshot recently did a piece charting how Americans
have moved between states since 1900, using Census microdata obtained from ipums.org,
the MPC''s longest running data project.'
wordpress_id: 106
wordpress_url: http://tech.popdata.org/?p=106
date: '2014-09-19 16:44:15 -0500'
date_gmt: '2014-09-19 16:44:15 -0500'
categories:
- IPUMS
- MPC in the News
tags: []
---
<a href="/images/from_wp/data-viz-us-pop-migration.jpg"><img class="size-full wp-image-107" src="/images/from_wp/data-viz-us-pop-migration.jpg" alt="Source: New York Times, The Upshot" width="800" height="381" /></a> Source: New York Times, The Upshot
The folks at the NYT's Upshot recently did a piece charting how Americans have moved between states since 1900. The charts in <a title="Where We Came From and Where We Went, State by State" href="http://www.nytimes.com/interactive/2014/08/13/upshot/where-people-in-each-state-were-born.html" target="_blank">Where We Came From and Where We Went, State by State</a> were compiled using Census microdata obtained from <a style="color: #326891;" href="http://www.ipums.org/">ipums.org</a>, the MPC's longest running data project. The microdata are records containing the characteristics of individuals compiled from a representative sample of Census forms. The individual, anonymized records are provided by the Census Bureau so researchers can explore the data beyond the published summary tables.
To measure domestic migration, the charts look at the place of birth of residents in each state of time. Because the focus of this report is movement of people from their U.S. state of birth to their U.S. state of residence, foreign born residents were collapsed into a single immigrant category. Likewise, the category "U.S. Other" was created to include residents of states born in Puerto Rico, Guam, American Samoa, the U.S. Virgin Islands, and a small number of people who in early Census years were identified as being born in Native American tribal territory. Residents who were classified in the data as U.S. born but without a specific state were allocated a state of birth proportionately based on the make-up of their state of residence for the given year.
| ccdavis/mnpopcenter.github.io | _posts/2014-09-19-where-we-came-from-and-where-we-went-state-by-state.markdown | Markdown | mit | 2,367 |
/**
* Gulp tasks for wrapping Browserify modules.
*/
const browserify = require("browserify");
const gulp = require("gulp");
const sourcemaps = require("gulp-sourcemaps");
const uglify = require("gulp-uglify");
const path = require("path");
const through2 = require("through2");
const buffer = require("vinyl-buffer");
const source = require("vinyl-source-stream");
const asyncUtil = require("../../util/async-util");
const clientPackages = require("../../util/client-packages");
const display = require("../../util/display");
const uc = require("../../util/unite-config");
gulp.task("build-bundle-app", async () => {
const uniteConfig = await uc.getUniteConfig();
const buildConfiguration = uc.getBuildConfiguration(uniteConfig, false);
if (buildConfiguration.bundle) {
display.info("Running", "Browserify for App");
const bApp = browserify({
debug: buildConfiguration.sourcemaps,
entries: `./${path.join(uniteConfig.dirs.www.dist, "entryPoint.js")}`
});
const vendorPackages = await clientPackages.getBundleVendorPackages(uniteConfig);
let hasStyleLoader = false;
Object.keys(vendorPackages).forEach((key) => {
bApp.exclude(key);
const idx = key.indexOf("systemjs");
if (idx >= 0 && !hasStyleLoader) {
hasStyleLoader = key === "systemjs-plugin-css";
}
});
bApp.transform("envify", {
NODE_ENV: buildConfiguration.minify ? "production" : "development",
global: true
});
bApp.transform("browserify-css", {
autoInject: hasStyleLoader
});
bApp.transform("stringify", {
appliesTo: {
includeExtensions: uniteConfig.viewExtensions.map(ext => `.${ext}`)
}
});
bApp.transform("babelify", {
global: true,
presets: ["@babel/preset-env"]
});
return asyncUtil.stream(bApp.bundle().on("error", (err) => {
display.error(err);
})
.pipe(source("app-bundle.js"))
.pipe(buffer())
.pipe(buildConfiguration.minify ? uglify()
.on("error", (err) => {
display.error(err.toString());
}) : through2.obj())
.pipe(buildConfiguration.sourcemaps ? sourcemaps.init({
loadMaps: true
}) : through2.obj())
.pipe(buildConfiguration.sourcemaps ?
sourcemaps.mapSources((sourcePath) => sourcePath.replace(/dist\//, "./")) : through2.obj())
.pipe(buildConfiguration.sourcemaps ? sourcemaps.write({
includeContent: true
}) : through2.obj())
.pipe(gulp.dest(uniteConfig.dirs.www.dist)));
}
});
// Generated by UniteJS
| unitejs/engine | assets/gulp/dist/tasks/bundler/browserify/build-bundle-app.js | JavaScript | mit | 2,848 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>GLM_GTX_string_cast: String cast</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<!-- Generated by Doxygen 1.7.3 -->
<div id="top">
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="logo-mini.png"></td>
</tr>
</tbody>
</table>
</div>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
</div>
<div class="header">
<div class="summary">
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<h1>GLM_GTX_string_cast: String cast</h1> </div>
<div class="ingroups"><a class="el" href="a00247.html">GTX Extensions (Experimental)</a></div></div>
<div class="contents">
<p>Setup strings for GLM type values.
<a href="#_details">More...</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="func-members"></a>
Functions</h2></td></tr>
<tr><td class="memTemplParams" colspan="2">template<typename genType > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top">std::string </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00293.html#ga9ab4dfc4ab5f29591638fb56d7752fff">to_string</a> (genType const &x)</td></tr>
</table>
<hr/><a name="_details"></a><h2>Detailed Description</h2>
<p>Setup strings for GLM type values. </p>
<p><<a class="el" href="a00106_source.html">glm/gtx/string_cast.hpp</a>> need to be included to use these functionalities. </p>
<hr/><h2>Function Documentation</h2>
<a class="anchor" id="ga9ab4dfc4ab5f29591638fb56d7752fff"></a><!-- doxytag: member="glm::gtx::string_cast::to_string" ref="ga9ab4dfc4ab5f29591638fb56d7752fff" args="(genType const &x)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string glm::gtx::string_cast::to_string </td>
<td>(</td>
<td class="paramtype">genType const & </td>
<td class="paramname"><em>x</em></td><td>)</td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Create a string from a GLM type value. </p>
<p>From GLM_GTX_string_cast extension. </p>
</div>
</div>
</div>
<hr class="footer"/><address class="footer"><small>Generated by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.3 </small></address>
</body>
</html>
| klantz81/ocean-simulation | glm-0.9.2.6/doc/html/a00293.html | HTML | mit | 3,074 |
/*
* Special implementations of built-in functions and methods.
*
* Optional optimisations for builtins are in Optimize.c.
*
* General object operations and protocols are in ObjectHandling.c.
*/
//////////////////// Globals.proto ////////////////////
static PyObject* __Pyx_Globals(void); /*proto*/
//////////////////// Globals ////////////////////
//@substitute: naming
//@requires: ObjectHandling.c::GetAttr
// This is a stub implementation until we have something more complete.
// Currently, we only handle the most common case of a read-only dict
// of Python names. Supporting cdef names in the module and write
// access requires a rewrite as a dedicated class.
static PyObject* __Pyx_Globals(void) {
Py_ssize_t i;
PyObject *names;
PyObject *globals = $moddict_cname;
Py_INCREF(globals);
names = PyObject_Dir($module_cname);
if (!names)
goto bad;
for (i = PyList_GET_SIZE(names)-1; i >= 0; i--) {
#if CYTHON_COMPILING_IN_PYPY
PyObject* name = PySequence_ITEM(names, i);
if (!name)
goto bad;
#else
PyObject* name = PyList_GET_ITEM(names, i);
#endif
if (!PyDict_Contains(globals, name)) {
PyObject* value = __Pyx_GetAttr($module_cname, name);
if (!value) {
#if CYTHON_COMPILING_IN_PYPY
Py_DECREF(name);
#endif
goto bad;
}
if (PyDict_SetItem(globals, name, value) < 0) {
#if CYTHON_COMPILING_IN_PYPY
Py_DECREF(name);
#endif
Py_DECREF(value);
goto bad;
}
}
#if CYTHON_COMPILING_IN_PYPY
Py_DECREF(name);
#endif
}
Py_DECREF(names);
return globals;
bad:
Py_XDECREF(names);
Py_XDECREF(globals);
return NULL;
}
//////////////////// PyExecGlobals.proto ////////////////////
static PyObject* __Pyx_PyExecGlobals(PyObject*);
//////////////////// PyExecGlobals ////////////////////
//@requires: Globals
//@requires: PyExec
static PyObject* __Pyx_PyExecGlobals(PyObject* code) {
PyObject* result;
PyObject* globals = __Pyx_Globals();
if (unlikely(!globals))
return NULL;
result = __Pyx_PyExec2(code, globals);
Py_DECREF(globals);
return result;
}
//////////////////// PyExec.proto ////////////////////
static PyObject* __Pyx_PyExec3(PyObject*, PyObject*, PyObject*);
static CYTHON_INLINE PyObject* __Pyx_PyExec2(PyObject*, PyObject*);
//////////////////// PyExec ////////////////////
//@substitute: naming
static CYTHON_INLINE PyObject* __Pyx_PyExec2(PyObject* o, PyObject* globals) {
return __Pyx_PyExec3(o, globals, NULL);
}
static PyObject* __Pyx_PyExec3(PyObject* o, PyObject* globals, PyObject* locals) {
PyObject* result;
PyObject* s = 0;
char *code = 0;
if (!globals || globals == Py_None) {
globals = $moddict_cname;
} else if (!PyDict_Check(globals)) {
PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.200s",
Py_TYPE(globals)->tp_name);
goto bad;
}
if (!locals || locals == Py_None) {
locals = globals;
}
if (PyDict_GetItem(globals, PYIDENT("__builtins__")) == NULL) {
if (PyDict_SetItem(globals, PYIDENT("__builtins__"), PyEval_GetBuiltins()) < 0)
goto bad;
}
if (PyCode_Check(o)) {
if (PyCode_GetNumFree((PyCodeObject *)o) > 0) {
PyErr_SetString(PyExc_TypeError,
"code object passed to exec() may not contain free variables");
goto bad;
}
#if PY_VERSION_HEX < 0x030200B1
result = PyEval_EvalCode((PyCodeObject *)o, globals, locals);
#else
result = PyEval_EvalCode(o, globals, locals);
#endif
} else {
PyCompilerFlags cf;
cf.cf_flags = 0;
if (PyUnicode_Check(o)) {
cf.cf_flags = PyCF_SOURCE_IS_UTF8;
s = PyUnicode_AsUTF8String(o);
if (!s) goto bad;
o = s;
#if PY_MAJOR_VERSION >= 3
} else if (!PyBytes_Check(o)) {
#else
} else if (!PyString_Check(o)) {
#endif
PyErr_Format(PyExc_TypeError,
"exec: arg 1 must be string, bytes or code object, got %.200s",
Py_TYPE(o)->tp_name);
goto bad;
}
#if PY_MAJOR_VERSION >= 3
code = PyBytes_AS_STRING(o);
#else
code = PyString_AS_STRING(o);
#endif
if (PyEval_MergeCompilerFlags(&cf)) {
result = PyRun_StringFlags(code, Py_file_input, globals, locals, &cf);
} else {
result = PyRun_String(code, Py_file_input, globals, locals);
}
Py_XDECREF(s);
}
return result;
bad:
Py_XDECREF(s);
return 0;
}
//////////////////// GetAttr3.proto ////////////////////
static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /*proto*/
//////////////////// GetAttr3 ////////////////////
//@requires: ObjectHandling.c::GetAttr
static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) {
PyObject *r = __Pyx_GetAttr(o, n);
if (unlikely(!r)) {
if (!PyErr_ExceptionMatches(PyExc_AttributeError))
goto bad;
PyErr_Clear();
r = d;
Py_INCREF(d);
}
return r;
bad:
return NULL;
}
//////////////////// Intern.proto ////////////////////
static PyObject* __Pyx_Intern(PyObject* s); /* proto */
//////////////////// Intern ////////////////////
static PyObject* __Pyx_Intern(PyObject* s) {
if (!(likely(PyString_CheckExact(s)))) {
PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "str", Py_TYPE(s)->tp_name);
return 0;
}
Py_INCREF(s);
#if PY_MAJOR_VERSION >= 3
PyUnicode_InternInPlace(&s);
#else
PyString_InternInPlace(&s);
#endif
return s;
}
//////////////////// abs_int.proto ////////////////////
static CYTHON_INLINE unsigned int __Pyx_abs_int(int x) {
if (unlikely(x == -INT_MAX-1))
return ((unsigned int)INT_MAX) + 1U;
return (unsigned int) abs(x);
}
//////////////////// abs_long.proto ////////////////////
static CYTHON_INLINE unsigned long __Pyx_abs_long(long x) {
if (unlikely(x == -LONG_MAX-1))
return ((unsigned long)LONG_MAX) + 1U;
return (unsigned long) labs(x);
}
//////////////////// abs_longlong.proto ////////////////////
static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_abs_longlong(PY_LONG_LONG x) {
#ifndef PY_LLONG_MAX
#ifdef LLONG_MAX
const PY_LONG_LONG PY_LLONG_MAX = LLONG_MAX;
#else
// copied from pyport.h in CPython 3.3, missing in 2.4
const PY_LONG_LONG PY_LLONG_MAX = (1 + 2 * ((1LL << (CHAR_BIT * sizeof(PY_LONG_LONG) - 2)) - 1));
#endif
#endif
if (unlikely(x == -PY_LLONG_MAX-1))
return ((unsigned PY_LONG_LONG)PY_LLONG_MAX) + 1U;
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
return (unsigned PY_LONG_LONG) llabs(x);
#else
return (x<0) ? (unsigned PY_LONG_LONG)-x : (unsigned PY_LONG_LONG)x;
#endif
}
//////////////////// pow2.proto ////////////////////
#define __Pyx_PyNumber_Power2(a, b) PyNumber_Power(a, b, Py_None)
//////////////////// py_dict_keys.proto ////////////////////
static CYTHON_INLINE PyObject* __Pyx_PyDict_Keys(PyObject* d); /*proto*/
//////////////////// py_dict_keys ////////////////////
//@requires: ObjectHandling.c::PyObjectCallMethod1
static CYTHON_INLINE PyObject* __Pyx_PyDict_Keys(PyObject* d) {
if (PY_MAJOR_VERSION >= 3)
return __Pyx_PyObject_CallMethod1((PyObject*)&PyDict_Type, PYIDENT("keys"), d);
else
return PyDict_Keys(d);
}
//////////////////// py_dict_values.proto ////////////////////
static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d); /*proto*/
//////////////////// py_dict_values ////////////////////
//@requires: ObjectHandling.c::PyObjectCallMethod1
static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d) {
if (PY_MAJOR_VERSION >= 3)
return __Pyx_PyObject_CallMethod1((PyObject*)&PyDict_Type, PYIDENT("values"), d);
else
return PyDict_Values(d);
}
//////////////////// py_dict_items.proto ////////////////////
static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d); /*proto*/
//////////////////// py_dict_items ////////////////////
//@requires: ObjectHandling.c::PyObjectCallMethod1
static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d) {
if (PY_MAJOR_VERSION >= 3)
return __Pyx_PyObject_CallMethod1((PyObject*)&PyDict_Type, PYIDENT("items"), d);
else
return PyDict_Items(d);
}
//////////////////// py_dict_iterkeys.proto ////////////////////
static CYTHON_INLINE PyObject* __Pyx_PyDict_IterKeys(PyObject* d); /*proto*/
//////////////////// py_dict_iterkeys ////////////////////
//@requires: ObjectHandling.c::PyObjectCallMethod0
static CYTHON_INLINE PyObject* __Pyx_PyDict_IterKeys(PyObject* d) {
return __Pyx_PyObject_CallMethod0(d, (PY_MAJOR_VERSION >= 3) ? PYIDENT("keys") : PYIDENT("iterkeys"));
}
//////////////////// py_dict_itervalues.proto ////////////////////
static CYTHON_INLINE PyObject* __Pyx_PyDict_IterValues(PyObject* d); /*proto*/
//////////////////// py_dict_itervalues ////////////////////
//@requires: ObjectHandling.c::PyObjectCallMethod0
static CYTHON_INLINE PyObject* __Pyx_PyDict_IterValues(PyObject* d) {
return __Pyx_PyObject_CallMethod0(d, (PY_MAJOR_VERSION >= 3) ? PYIDENT("values") : PYIDENT("itervalues"));
}
//////////////////// py_dict_iteritems.proto ////////////////////
static CYTHON_INLINE PyObject* __Pyx_PyDict_IterItems(PyObject* d); /*proto*/
//////////////////// py_dict_iteritems ////////////////////
//@requires: ObjectHandling.c::PyObjectCallMethod0
static CYTHON_INLINE PyObject* __Pyx_PyDict_IterItems(PyObject* d) {
return __Pyx_PyObject_CallMethod0(d, (PY_MAJOR_VERSION >= 3) ? PYIDENT("items") : PYIDENT("iteritems"));
}
//////////////////// py_dict_viewkeys.proto ////////////////////
#if PY_VERSION_HEX < 0x02070000
#error This module uses dict views, which require Python 2.7 or later
#endif
static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewKeys(PyObject* d); /*proto*/
//////////////////// py_dict_viewkeys ////////////////////
//@requires: ObjectHandling.c::PyObjectCallMethod0
static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewKeys(PyObject* d) {
return __Pyx_PyObject_CallMethod0(d, (PY_MAJOR_VERSION >= 3) ? PYIDENT("keys") : PYIDENT("viewkeys"));
}
//////////////////// py_dict_viewvalues.proto ////////////////////
#if PY_VERSION_HEX < 0x02070000
#error This module uses dict views, which require Python 2.7 or later
#endif
static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewValues(PyObject* d); /*proto*/
//////////////////// py_dict_viewvalues ////////////////////
//@requires: ObjectHandling.c::PyObjectCallMethod0
static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewValues(PyObject* d) {
return __Pyx_PyObject_CallMethod0(d, (PY_MAJOR_VERSION >= 3) ? PYIDENT("values") : PYIDENT("viewvalues"));
}
//////////////////// py_dict_viewitems.proto ////////////////////
#if PY_VERSION_HEX < 0x02070000
#error This module uses dict views, which require Python 2.7 or later
#endif
static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewItems(PyObject* d); /*proto*/
//////////////////// py_dict_viewitems ////////////////////
//@requires: ObjectHandling.c::PyObjectCallMethod0
static CYTHON_INLINE PyObject* __Pyx_PyDict_ViewItems(PyObject* d) {
return __Pyx_PyObject_CallMethod0(d, (PY_MAJOR_VERSION >= 3) ? PYIDENT("items") : PYIDENT("viewitems"));
}
//////////////////// pyfrozenset_new.proto ////////////////////
//@substitute: naming
static CYTHON_INLINE PyObject* __Pyx_PyFrozenSet_New(PyObject* it) {
if (it) {
PyObject* result;
#if CYTHON_COMPILING_IN_PYPY
// PyPy currently lacks PyFrozenSet_CheckExact() and PyFrozenSet_New()
PyObject* args;
args = PyTuple_Pack(1, it);
if (unlikely(!args))
return NULL;
result = PyObject_Call((PyObject*)&PyFrozenSet_Type, args, NULL);
Py_DECREF(args);
return result;
#else
if (PyFrozenSet_CheckExact(it)) {
Py_INCREF(it);
return it;
}
result = PyFrozenSet_New(it);
if (unlikely(!result))
return NULL;
if (likely(PySet_GET_SIZE(result)))
return result;
// empty frozenset is a singleton
// seems wasteful, but CPython does the same
Py_DECREF(result);
#endif
}
#if CYTHON_COMPILING_IN_CPYTHON
return PyFrozenSet_Type.tp_new(&PyFrozenSet_Type, $empty_tuple, NULL);
#else
return PyObject_Call((PyObject*)&PyFrozenSet_Type, $empty_tuple, NULL);
#endif
}
| mollstam/UnrealPy | UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/Cython-0.22.1/Cython/Utility/Builtins.c | C | mit | 12,711 |
// Commom Plugins
(function($) {
'use strict';
// Scroll to Top Button.
if (typeof theme.PluginScrollToTop !== 'undefined') {
theme.PluginScrollToTop.initialize();
}
// Tooltips
if ($.isFunction($.fn['tooltip'])) {
$('[data-tooltip]:not(.manual), [data-plugin-tooltip]:not(.manual)').tooltip();
}
// Popover
if ($.isFunction($.fn['popover'])) {
$(function() {
$('[data-plugin-popover]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.popover(opts);
});
});
}
// Validations
if (typeof theme.PluginValidation !== 'undefined') {
theme.PluginValidation.initialize();
}
// Match Height
if ($.isFunction($.fn['matchHeight'])) {
$('.match-height').matchHeight();
// Featured Boxes
$('.featured-boxes .featured-box').matchHeight();
// Featured Box Full
$('.featured-box-full').matchHeight();
}
}).apply(this, [jQuery]);
// Animate
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginAnimate'])) {
$(function() {
$('[data-plugin-animate], [data-appear-animation]').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginAnimate(opts);
});
});
}
}).apply(this, [jQuery]);
// Carousel
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginCarousel'])) {
$(function() {
$('[data-plugin-carousel]:not(.manual), .owl-carousel:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginCarousel(opts);
});
});
}
}).apply(this, [jQuery]);
// Chart.Circular
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginChartCircular'])) {
$(function() {
$('[data-plugin-chart-circular]:not(.manual), .circular-bar-chart:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginChartCircular(opts);
});
});
}
}).apply(this, [jQuery]);
// Counter
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginCounter'])) {
$(function() {
$('[data-plugin-counter]:not(.manual), .counters [data-to]').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginCounter(opts);
});
});
}
}).apply(this, [jQuery]);
// Lazy Load
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginLazyLoad'])) {
$(function() {
$('[data-plugin-lazyload]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginLazyLoad(opts);
});
});
}
}).apply(this, [jQuery]);
// Lightbox
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginLightbox'])) {
$(function() {
$('[data-plugin-lightbox]:not(.manual), .lightbox:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginLightbox(opts);
});
});
}
}).apply(this, [jQuery]);
// Masonry
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginMasonry'])) {
$(function() {
$('[data-plugin-masonry]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginMasonry(opts);
});
});
}
}).apply(this, [jQuery]);
// Match Height
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginMatchHeight'])) {
$(function() {
$('[data-plugin-match-height]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginMatchHeight(opts);
});
});
}
}).apply(this, [jQuery]);
// Parallax
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginParallax'])) {
$(function() {
$('[data-plugin-parallax]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginParallax(opts);
});
});
}
}).apply(this, [jQuery]);
// Progress Bar
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginProgressBar'])) {
$(function() {
$('[data-plugin-progress-bar]:not(.manual), [data-appear-progress-animation]').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginProgressBar(opts);
});
});
}
}).apply(this, [jQuery]);
// Revolution Slider
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginRevolutionSlider'])) {
$(function() {
$('[data-plugin-revolution-slider]:not(.manual), .slider-container .slider:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginRevolutionSlider(opts);
});
});
}
}).apply(this, [jQuery]);
// Sort
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginSort'])) {
$(function() {
$('[data-plugin-sort]:not(.manual), .sort-source:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginSort(opts);
});
});
}
}).apply(this, [jQuery]);
// Sticky
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginSticky'])) {
$(function() {
$('[data-plugin-sticky]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginSticky(opts);
});
});
}
}).apply(this, [jQuery]);
// Toggle
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginToggle'])) {
$(function() {
$('[data-plugin-toggle]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginToggle(opts);
});
});
}
}).apply(this, [jQuery]);
// Tweets
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginTweets'])) {
$(function() {
$('[data-plugin-tweets]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginTweets(opts);
});
});
}
}).apply(this, [jQuery]);
// Video Background
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginVideoBackground'])) {
$(function() {
$('[data-plugin-video-background]:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginVideoBackground(opts);
});
});
}
}).apply(this, [jQuery]);
// Word Rotate
(function($) {
'use strict';
if ($.isFunction($.fn['themePluginWordRotate'])) {
$(function() {
$('[data-plugin-word-rotate]:not(.manual), .word-rotate:not(.manual)').each(function() {
var $this = $(this),
opts;
var pluginOptions = $this.data('plugin-options');
if (pluginOptions)
opts = pluginOptions;
$this.themePluginWordRotate(opts);
});
});
}
}).apply(this, [jQuery]);
// Commom Partials
(function($) {
'use strict';
// Sticky Header
if (typeof theme.StickyHeader !== 'undefined') {
theme.StickyHeader.initialize();
}
// Nav Menu
if (typeof theme.Nav !== 'undefined') {
theme.Nav.initialize();
}
// Search
if (typeof theme.Search !== 'undefined') {
theme.Search.initialize();
}
// Newsletter
if (typeof theme.Newsletter !== 'undefined') {
theme.Newsletter.initialize();
}
// Account
if (typeof theme.Account !== 'undefined') {
theme.Account.initialize();
}
}).apply(this, [jQuery]); | SupasitC/Pricetrolley | src/javascripts/theme.init.js | JavaScript | mit | 8,635 |
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/user"
"path/filepath"
"strings"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
gmail "google.golang.org/api/gmail/v1"
"github.com/codegangsta/cli"
"github.com/davecgh/go-spew/spew"
)
var me = "me"
func main() {
app := cli.NewApp()
app.Name = "proto"
app.Usage = "test"
app.Version = "0.0.1"
app.Author = "Yusuke Komatsu"
app.Commands = []cli.Command{
{
Name: "cleanUp",
Usage: "---",
Description: "",
Action: cleanUp,
},
{
Name: "deleteAwaitingResponse",
Usage: "---",
Description: "",
Action: deleteAwaitingResponse,
},
{
Name: "getNoLabelSender",
Usage: "---",
Description: "",
Action: getNoLabelSender,
},
{
Name: "labelMessagesWithoutResponse",
Usage: "---",
Description: "",
Action: labelMessagesWithoutResponse,
},
{
Name: "setParentLabel",
Usage: "---",
Description: "",
Action: setParentLabel,
},
}
app.Run(os.Args)
}
func cleanUp(c *cli.Context) {
srv, err := getNewService()
if err != nil {
log.Fatalf("Unable to retrieve gmail Client %v", err)
}
req, err := srv.Users.Threads.List(me).Q("label:3day older_than:3d").Do()
if err != nil {
log.Fatalf("Unable to retrieve threads. %v", err)
}
if (len(req.Threads) > 0) {
for _, th := range req.Threads {
_, err := srv.Users.Threads.Trash(me, th.Id).Do()
if err != nil {
log.Fatalf("Unable to trash thread. ID:%v, %v", th.Id, err)
}
}
}
}
func labelMessagesWithoutResponse(c *cli.Context) {
srv, err := getNewService()
if err != nil {
log.Fatalf("Unable to retrieve gmail Client %v", err)
}
req, err := srv.Users.Threads.List(me).Q("in:Sent -label:AwaitingResponse newer_than:7d").Do()
if err != nil {
log.Fatalf("Unable to retrieve threads. %v", err)
}
if len(req.Threads) > 0 {
label_ar, err := getLabelByName("AwaitingResponse")
if err != nil {
log.Fatalf("Unable to retrieve AwaitingResponse label. %v", err)
}
label_fe, err := getLabelByName("FinishedExchange")
if err != nil {
log.Fatalf("Unable to retrieve FinishedExchange label. %v", err)
}
for _, th := range req.Threads {
mod := &gmail.ModifyThreadRequest{}
lbId := label_ar.Id
if len(th.Messages) > 1 {
lbId = label_fe.Id
}
mod.AddLabelIds = append(mod.AddLabelIds, lbId)
_, err := srv.Users.Threads.Modify(me, th.Id, mod).Do()
if err != nil {
log.Fatalf("Unable to set label. %v", err)
}
}
}
}
func deleteAwaitingResponse(c *cli.Context) {
srv, err := getNewService()
if err != nil {
log.Fatalf("Unable to retrieve gmail Client %v", err)
}
req, err := srv.Users.Threads.List(me).Q("label:AwaitingResponse older_than:7d newer_than:14d").Do()
if err != nil {
log.Fatalf("Unable to retrieve threads. %v", err)
}
if len(req.Threads) > 0 {
removelabel, err := getLabelByName("AwaitingResponse")
if err != nil {
log.Fatalf("Unable to retrieve AwaitingResponse label. %v", err)
}
addlabel, err := getLabelByName("FinishedExchange")
if err != nil {
log.Fatalf("Unable to retrieve FinishedExchange label. %v", err)
}
for _, th := range req.Threads {
mod := &gmail.ModifyThreadRequest{}
mod.RemoveLabelIds = append(mod.RemoveLabelIds, removelabel.Id)
if len(th.Messages) > 1 {
mod.AddLabelIds = append(mod.AddLabelIds, addlabel.Id)
}
_, err := srv.Users.Threads.Modify(me, th.Id, mod).Do()
if err != nil {
log.Fatalf("Unable to remove label. %v", err)
}
}
}
}
func setParentLabel(c *cli.Context) {
srv, err := getNewService()
if err != nil {
log.Fatalf("Unable to retrieve gmail Client %v", err)
}
req, err := srv.Users.Labels.List(me).Do()
if err != nil {
log.Fatalf("Unable to retrieve labels. %v", err)
}
if (len(req.Labels) > 0) {
parents := make(map[string]string)
for _, lb := range req.Labels {
if (strings.Contains(lb.Name, "/") == false) {
parents[lb.Name] = lb.Id
}
}
for _, l := range req.Labels {
lbName := l.Name
if (strings.Contains(lbName, "/")) {
splitedLabelNames := strings.Split(lbName, "/")
parent := splitedLabelNames[0]
query := fmt.Sprintf("label:%s -label:%s", lbName, parent)
r, err := srv.Users.Threads.List(me).Q(query).Do()
if err != nil {
log.Fatalf("Unable to retrieve threads. %v", err)
}
if parentId, ok := parents[parent]; ok {
mod := &gmail.ModifyThreadRequest{}
mod.AddLabelIds = append(mod.AddLabelIds, parentId)
for _, th := range r.Threads {
_, err := srv.Users.Threads.Modify(me, th.Id, mod).Do()
if err != nil {
log.Fatalf("Unable to set label. %v", err)
}
}
}
}
}
}
}
func getNoLabelSender(c *cli.Context) {
srv, err := getNewService()
if err != nil {
log.Fatalf("Unable to retrieve gmail Client %v", err)
}
req, err := srv.Users.Threads.List(me).Q("has:nouserlabels newer_than:1d").Do()
if err != nil {
log.Fatalf("Unable to retrieve threads. %v", err)
}
if len(req.Threads) > 0 {
sender := []string{}
for _, th := range req.Threads {
t, err := srv.Users.Threads.Get(me, th.Id).Fields("messages/payload").Do()
if err != nil {
log.Fatalf("Unable to retrieve a thread information. %v", err)
}
for _, msg := range t.Messages {
headers := msg.Payload.Headers
for _, header := range headers {
if header.Name == "From" {
sender = append(sender, header.Value)
}
}
}
}
spew.Dump(sender)
}
}
func getLabelByName(labelName string) (*gmail.Label, error) {
srv, err := getNewService()
if err != nil {
return nil, err
}
req, err := srv.Users.Labels.List(me).Do()
if err != nil {
return nil, err
}
if (len(req.Labels) > 0) {
for _, l := range req.Labels {
if (l.Name == labelName) {
return l, nil
}
}
}
return nil, nil
}
func getNewService() (*gmail.Service, error) {
b, err := ioutil.ReadFile("client_secret.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
}
config, err := google.ConfigFromJSON(b, gmail.MailGoogleComScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
client := getClient(context.Background(), config)
srv, err := gmail.New(client)
return srv, err
}
// getClient uses a Context and Config to retrieve a Token
// then generate a Client. It returns the generated Client.
func getClient(ctx context.Context, config *oauth2.Config) *http.Client {
cacheFile, err := tokenCacheFile()
if err != nil {
log.Fatalf("Unable to get path to cached credential file. %v", err)
}
tok, err := tokenFromFile(cacheFile)
if err != nil {
tok = getTokenFromWeb(config)
saveToken(cacheFile, tok)
}
return config.Client(ctx, tok)
}
// getTokenFromWeb uses Config to request a Token.
// It returns the retrieved Token.
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
fmt.Printf("Go to the following link in your browser then type the "+
"authorization code: \n%v\n", authURL)
var code string
if _, err := fmt.Scan(&code); err != nil {
log.Fatalf("Unable to read authorization code %v", err)
}
tok, err := config.Exchange(oauth2.NoContext, code)
if err != nil {
log.Fatalf("Unable to retrieve token from web %v", err)
}
return tok
}
// tokenCacheFile generates credential file path/filename.
// It returns the generated credential path/filename.
func tokenCacheFile() (string, error) {
usr, err := user.Current()
if err != nil {
return "", err
}
tokenCacheDir := filepath.Join(usr.HomeDir, ".credentials")
os.MkdirAll(tokenCacheDir, 0700)
return filepath.Join(tokenCacheDir,
url.QueryEscape("token_cache.json")), err
}
// tokenFromFile retrieves a Token from a given file path.
// It returns the retrieved Token and any read error encountered.
func tokenFromFile(file string) (*oauth2.Token, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
t := &oauth2.Token{}
err = json.NewDecoder(f).Decode(t)
defer f.Close()
return t, err
}
// saveToken uses a file path to create a file and store the
// token in it.
func saveToken(file string, token *oauth2.Token) {
fmt.Printf("Saving credential file to: %s\n", file)
f, err := os.Create(file)
if err != nil {
log.Fatalf("Unable to cache oauth token: %v", err)
}
defer f.Close()
json.NewEncoder(f).Encode(token)
} | usk81/shikigami | rei/rei.go | GO | mit | 10,099 |
// This file contains source that originates from:
// http://code.google.com/p/leveldbwin/source/browse/trunk/win32_impl_src/env_win32.h
// http://code.google.com/p/leveldbwin/source/browse/trunk/win32_impl_src/port_win32.cc
// Those files dont' have any explict license headers but the
// project (http://code.google.com/p/leveldbwin/) lists the 'New BSD License'
// as the license.
#if defined(LEVELDB_PLATFORM_WINDOWS)
#include <map>
#undef UNICODE
#include "leveldb/env.h"
#include "port/port.h"
#include "leveldb/slice.h"
#include "util/logging.h"
#include <shlwapi.h>
#include <process.h>
#include <cstring>
#include <stdio.h>
#include <errno.h>
#include <io.h>
#include <algorithm>
#ifdef max
#undef max
#endif
#ifndef va_copy
#define va_copy(d,s) ((d) = (s))
#endif
#if defined DeleteFile
#undef DeleteFile
#endif
//Declarations
namespace leveldb
{
namespace Win32
{
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
std::string GetCurrentDir();
std::wstring GetCurrentDirW();
static const std::string CurrentDir = GetCurrentDir();
static const std::wstring CurrentDirW = GetCurrentDirW();
std::string& ModifyPath(std::string& path);
std::wstring& ModifyPath(std::wstring& path);
std::string GetLastErrSz();
std::wstring GetLastErrSzW();
size_t GetPageSize();
typedef void (*ScheduleProc)(void*) ;
struct WorkItemWrapper
{
WorkItemWrapper(ScheduleProc proc_,void* content_);
ScheduleProc proc;
void* pContent;
};
DWORD WINAPI WorkItemWrapperProc(LPVOID pContent);
class Win32SequentialFile : public SequentialFile
{
public:
friend class Win32Env;
virtual ~Win32SequentialFile();
virtual Status Read(size_t n, Slice* result, char* scratch);
virtual Status Skip(uint64_t n);
BOOL isEnable();
private:
BOOL _Init();
void _CleanUp();
Win32SequentialFile(const std::string& fname);
std::string _filename;
::HANDLE _hFile;
DISALLOW_COPY_AND_ASSIGN(Win32SequentialFile);
};
class Win32RandomAccessFile : public RandomAccessFile
{
public:
friend class Win32Env;
virtual ~Win32RandomAccessFile();
virtual Status Read(uint64_t offset, size_t n, Slice* result,char* scratch) const;
BOOL isEnable();
private:
BOOL _Init(LPCWSTR path);
void _CleanUp();
Win32RandomAccessFile(const std::string& fname);
HANDLE _hFile;
const std::string _filename;
DISALLOW_COPY_AND_ASSIGN(Win32RandomAccessFile);
};
class Win32MapFile : public WritableFile
{
public:
Win32MapFile(const std::string& fname);
~Win32MapFile();
virtual Status Append(const Slice& data);
virtual Status Close();
virtual Status Flush();
virtual Status Sync();
BOOL isEnable();
private:
std::string _filename;
HANDLE _hFile;
size_t _page_size;
size_t _map_size; // How much extra memory to map at a time
char* _base; // The mapped region
HANDLE _base_handle;
char* _limit; // Limit of the mapped region
char* _dst; // Where to write next (in range [base_,limit_])
char* _last_sync; // Where have we synced up to
uint64_t _file_offset; // Offset of base_ in file
//LARGE_INTEGER file_offset_;
// Have we done an munmap of unsynced data?
bool _pending_sync;
// Roundup x to a multiple of y
static size_t _Roundup(size_t x, size_t y);
size_t _TruncateToPageBoundary(size_t s);
bool _UnmapCurrentRegion();
bool _MapNewRegion();
DISALLOW_COPY_AND_ASSIGN(Win32MapFile);
BOOL _Init(LPCWSTR Path);
};
class Win32FileLock : public FileLock
{
public:
friend class Win32Env;
virtual ~Win32FileLock();
BOOL isEnable();
private:
BOOL _Init(LPCWSTR path);
void _CleanUp();
Win32FileLock(const std::string& fname);
HANDLE _hFile;
std::string _filename;
DISALLOW_COPY_AND_ASSIGN(Win32FileLock);
};
class Win32Logger : public Logger
{
public:
friend class Win32Env;
virtual ~Win32Logger();
virtual void Logv(const char* format, va_list ap);
private:
explicit Win32Logger(WritableFile* pFile);
WritableFile* _pFileProxy;
DISALLOW_COPY_AND_ASSIGN(Win32Logger);
};
class Win32Env : public Env
{
public:
Win32Env();
virtual ~Win32Env();
virtual Status NewSequentialFile(const std::string& fname,
SequentialFile** result);
virtual Status NewRandomAccessFile(const std::string& fname,
RandomAccessFile** result);
virtual Status NewWritableFile(const std::string& fname,
WritableFile** result);
virtual bool FileExists(const std::string& fname);
virtual Status GetChildren(const std::string& dir,
std::vector<std::string>* result);
virtual Status DeleteFile(const std::string& fname);
virtual Status CreateDir(const std::string& dirname);
virtual Status DeleteDir(const std::string& dirname);
virtual Status GetFileSize(const std::string& fname, uint64_t* file_size);
virtual Status RenameFile(const std::string& src,
const std::string& target);
virtual Status LockFile(const std::string& fname, FileLock** lock);
virtual Status UnlockFile(FileLock* lock);
virtual void Schedule(
void (*function)(void* arg),
void* arg);
virtual void StartThread(void (*function)(void* arg), void* arg);
virtual Status GetTestDirectory(std::string* path);
//virtual void Logv(WritableFile* log, const char* format, va_list ap);
virtual Status NewLogger(const std::string& fname, Logger** result);
virtual uint64_t NowMicros();
virtual void SleepForMicroseconds(int micros);
};
void ToWidePath(const std::string& value, std::wstring& target) {
wchar_t buffer[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, value.c_str(), -1, buffer, MAX_PATH);
target = buffer;
}
void ToNarrowPath(const std::wstring& value, std::string& target) {
char buffer[MAX_PATH];
WideCharToMultiByte(CP_ACP, 0, value.c_str(), -1, buffer, MAX_PATH, NULL, NULL);
target = buffer;
}
std::string GetCurrentDir()
{
CHAR path[MAX_PATH];
::GetModuleFileNameA(::GetModuleHandleA(NULL),path,MAX_PATH);
*strrchr(path,'\\') = 0;
return std::string(path);
}
std::wstring GetCurrentDirW()
{
WCHAR path[MAX_PATH];
::GetModuleFileNameW(::GetModuleHandleW(NULL),path,MAX_PATH);
*wcsrchr(path,L'\\') = 0;
return std::wstring(path);
}
std::string& ModifyPath(std::string& path)
{
if(path[0] == '/' || path[0] == '\\'){
path = CurrentDir + path;
}
std::replace(path.begin(),path.end(),'/','\\');
return path;
}
std::wstring& ModifyPath(std::wstring& path)
{
if(path[0] == L'/' || path[0] == L'\\'){
path = CurrentDirW + path;
}
std::replace(path.begin(),path.end(),L'/',L'\\');
return path;
}
std::string GetLastErrSz()
{
LPWSTR lpMsgBuf;
FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
0, // Default language
(LPWSTR) &lpMsgBuf,
0,
NULL
);
std::string Err;
ToNarrowPath(lpMsgBuf, Err);
LocalFree( lpMsgBuf );
return Err;
}
std::wstring GetLastErrSzW()
{
LPVOID lpMsgBuf;
FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
0, // Default language
(LPWSTR) &lpMsgBuf,
0,
NULL
);
std::wstring Err = (LPCWSTR)lpMsgBuf;
LocalFree(lpMsgBuf);
return Err;
}
WorkItemWrapper::WorkItemWrapper( ScheduleProc proc_,void* content_ ) :
proc(proc_),pContent(content_)
{
}
DWORD WINAPI WorkItemWrapperProc(LPVOID pContent)
{
WorkItemWrapper* item = static_cast<WorkItemWrapper*>(pContent);
ScheduleProc TempProc = item->proc;
void* arg = item->pContent;
delete item;
TempProc(arg);
return 0;
}
size_t GetPageSize()
{
SYSTEM_INFO si;
GetSystemInfo(&si);
return std::max(si.dwPageSize,si.dwAllocationGranularity);
}
const size_t g_PageSize = GetPageSize();
Win32SequentialFile::Win32SequentialFile( const std::string& fname ) :
_filename(fname),_hFile(NULL)
{
_Init();
}
Win32SequentialFile::~Win32SequentialFile()
{
_CleanUp();
}
Status Win32SequentialFile::Read( size_t n, Slice* result, char* scratch )
{
Status sRet;
DWORD hasRead = 0;
if(_hFile && ReadFile(_hFile,scratch,n,&hasRead,NULL) ){
*result = Slice(scratch,hasRead);
} else {
sRet = Status::IOError(_filename, Win32::GetLastErrSz() );
}
return sRet;
}
Status Win32SequentialFile::Skip( uint64_t n )
{
Status sRet;
LARGE_INTEGER Move,NowPointer;
Move.QuadPart = n;
if(!SetFilePointerEx(_hFile,Move,&NowPointer,FILE_CURRENT)){
sRet = Status::IOError(_filename,Win32::GetLastErrSz());
}
return sRet;
}
BOOL Win32SequentialFile::isEnable()
{
return _hFile ? TRUE : FALSE;
}
BOOL Win32SequentialFile::_Init()
{
std::wstring path;
ToWidePath(_filename, path);
_hFile = CreateFileW(path.c_str(),
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
return _hFile ? TRUE : FALSE;
}
void Win32SequentialFile::_CleanUp()
{
if(_hFile){
CloseHandle(_hFile);
_hFile = NULL;
}
}
Win32RandomAccessFile::Win32RandomAccessFile( const std::string& fname ) :
_filename(fname),_hFile(NULL)
{
std::wstring path;
ToWidePath(fname, path);
_Init( path.c_str() );
}
Win32RandomAccessFile::~Win32RandomAccessFile()
{
_CleanUp();
}
Status Win32RandomAccessFile::Read(uint64_t offset,size_t n,Slice* result,char* scratch) const
{
Status sRet;
OVERLAPPED ol = {0};
ZeroMemory(&ol,sizeof(ol));
ol.Offset = (DWORD)offset;
ol.OffsetHigh = (DWORD)(offset >> 32);
DWORD hasRead = 0;
if(!ReadFile(_hFile,scratch,n,&hasRead,&ol))
sRet = Status::IOError(_filename,Win32::GetLastErrSz());
else
*result = Slice(scratch,hasRead);
return sRet;
}
BOOL Win32RandomAccessFile::_Init( LPCWSTR path )
{
BOOL bRet = FALSE;
if(!_hFile)
_hFile = ::CreateFileW(path,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,NULL);
if(!_hFile || _hFile == INVALID_HANDLE_VALUE )
_hFile = NULL;
else
bRet = TRUE;
return bRet;
}
BOOL Win32RandomAccessFile::isEnable()
{
return _hFile ? TRUE : FALSE;
}
void Win32RandomAccessFile::_CleanUp()
{
if(_hFile){
::CloseHandle(_hFile);
_hFile = NULL;
}
}
size_t Win32MapFile::_Roundup( size_t x, size_t y )
{
return ((x + y - 1) / y) * y;
}
size_t Win32MapFile::_TruncateToPageBoundary( size_t s )
{
s -= (s & (_page_size - 1));
assert((s % _page_size) == 0);
return s;
}
bool Win32MapFile::_UnmapCurrentRegion()
{
bool result = true;
if (_base != NULL) {
if (_last_sync < _limit) {
// Defer syncing this data until next Sync() call, if any
_pending_sync = true;
}
if (!UnmapViewOfFile(_base) || !CloseHandle(_base_handle))
result = false;
_file_offset += _limit - _base;
_base = NULL;
_base_handle = NULL;
_limit = NULL;
_last_sync = NULL;
_dst = NULL;
// Increase the amount we map the next time, but capped at 1MB
if (_map_size < (1<<20)) {
_map_size *= 2;
}
}
return result;
}
bool Win32MapFile::_MapNewRegion()
{
assert(_base == NULL);
//LONG newSizeHigh = (LONG)((file_offset_ + map_size_) >> 32);
//LONG newSizeLow = (LONG)((file_offset_ + map_size_) & 0xFFFFFFFF);
DWORD off_hi = (DWORD)(_file_offset >> 32);
DWORD off_lo = (DWORD)(_file_offset & 0xFFFFFFFF);
LARGE_INTEGER newSize;
newSize.QuadPart = _file_offset + _map_size;
SetFilePointerEx(_hFile, newSize, NULL, FILE_BEGIN);
SetEndOfFile(_hFile);
_base_handle = CreateFileMappingA(
_hFile,
NULL,
PAGE_READWRITE,
0,
0,
0);
if (_base_handle != NULL) {
_base = (char*) MapViewOfFile(_base_handle,
FILE_MAP_ALL_ACCESS,
off_hi,
off_lo,
_map_size);
if (_base != NULL) {
_limit = _base + _map_size;
_dst = _base;
_last_sync = _base;
return true;
}
}
return false;
}
Win32MapFile::Win32MapFile( const std::string& fname) :
_filename(fname),
_hFile(NULL),
_page_size(Win32::g_PageSize),
_map_size(_Roundup(65536, Win32::g_PageSize)),
_base(NULL),
_base_handle(NULL),
_limit(NULL),
_dst(NULL),
_last_sync(NULL),
_file_offset(0),
_pending_sync(false)
{
std::wstring path;
ToWidePath(fname, path);
_Init(path.c_str());
assert((Win32::g_PageSize & (Win32::g_PageSize - 1)) == 0);
}
Status Win32MapFile::Append( const Slice& data )
{
const char* src = data.data();
size_t left = data.size();
Status s;
while (left > 0) {
assert(_base <= _dst);
assert(_dst <= _limit);
size_t avail = _limit - _dst;
if (avail == 0) {
if (!_UnmapCurrentRegion() ||
!_MapNewRegion()) {
return Status::IOError("WinMmapFile.Append::UnmapCurrentRegion or MapNewRegion: ", Win32::GetLastErrSz());
}
}
size_t n = (left <= avail) ? left : avail;
memcpy(_dst, src, n);
_dst += n;
src += n;
left -= n;
}
return s;
}
Status Win32MapFile::Close()
{
Status s;
size_t unused = _limit - _dst;
if (!_UnmapCurrentRegion()) {
s = Status::IOError("WinMmapFile.Close::UnmapCurrentRegion: ",Win32::GetLastErrSz());
} else if (unused > 0) {
// Trim the extra space at the end of the file
LARGE_INTEGER newSize;
newSize.QuadPart = _file_offset - unused;
if (!SetFilePointerEx(_hFile, newSize, NULL, FILE_BEGIN)) {
s = Status::IOError("WinMmapFile.Close::SetFilePointer: ",Win32::GetLastErrSz());
} else
SetEndOfFile(_hFile);
}
if (!CloseHandle(_hFile)) {
if (s.ok()) {
s = Status::IOError("WinMmapFile.Close::CloseHandle: ", Win32::GetLastErrSz());
}
}
_hFile = INVALID_HANDLE_VALUE;
_base = NULL;
_base_handle = NULL;
_limit = NULL;
return s;
}
Status Win32MapFile::Sync()
{
Status s;
if (_pending_sync) {
// Some unmapped data was not synced
_pending_sync = false;
if (!FlushFileBuffers(_hFile)) {
s = Status::IOError("WinMmapFile.Sync::FlushFileBuffers: ",Win32::GetLastErrSz());
}
}
if (_dst > _last_sync) {
// Find the beginnings of the pages that contain the first and last
// bytes to be synced.
size_t p1 = _TruncateToPageBoundary(_last_sync - _base);
size_t p2 = _TruncateToPageBoundary(_dst - _base - 1);
_last_sync = _dst;
if (!FlushViewOfFile(_base + p1, p2 - p1 + _page_size)) {
s = Status::IOError("WinMmapFile.Sync::FlushViewOfFile: ",Win32::GetLastErrSz());
}
}
return s;
}
Status Win32MapFile::Flush()
{
return Status::OK();
}
Win32MapFile::~Win32MapFile()
{
if (_hFile != INVALID_HANDLE_VALUE) {
Win32MapFile::Close();
}
}
BOOL Win32MapFile::_Init( LPCWSTR Path )
{
DWORD Flag = PathFileExistsW(Path) ? OPEN_EXISTING : CREATE_ALWAYS;
_hFile = CreateFileW(Path,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
NULL,
Flag,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(!_hFile || _hFile == INVALID_HANDLE_VALUE)
return FALSE;
else
return TRUE;
}
BOOL Win32MapFile::isEnable()
{
return _hFile ? TRUE : FALSE;
}
Win32FileLock::Win32FileLock( const std::string& fname ) :
_hFile(NULL),_filename(fname)
{
std::wstring path;
ToWidePath(fname, path);
_Init(path.c_str());
}
Win32FileLock::~Win32FileLock()
{
_CleanUp();
}
BOOL Win32FileLock::_Init( LPCWSTR path )
{
BOOL bRet = FALSE;
if(!_hFile)
_hFile = ::CreateFileW(path,0,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
if(!_hFile || _hFile == INVALID_HANDLE_VALUE ){
_hFile = NULL;
}
else
bRet = TRUE;
return bRet;
}
void Win32FileLock::_CleanUp()
{
::CloseHandle(_hFile);
_hFile = NULL;
}
BOOL Win32FileLock::isEnable()
{
return _hFile ? TRUE : FALSE;
}
Win32Logger::Win32Logger(WritableFile* pFile) : _pFileProxy(pFile)
{
assert(_pFileProxy);
}
Win32Logger::~Win32Logger()
{
if(_pFileProxy)
delete _pFileProxy;
}
void Win32Logger::Logv( const char* format, va_list ap )
{
uint64_t thread_id = ::GetCurrentThreadId();
// We try twice: the first time with a fixed-size stack allocated buffer,
// and the second time with a much larger dynamically allocated buffer.
char buffer[500];
for (int iter = 0; iter < 2; iter++) {
char* base;
int bufsize;
if (iter == 0) {
bufsize = sizeof(buffer);
base = buffer;
} else {
bufsize = 30000;
base = new char[bufsize];
}
char* p = base;
char* limit = base + bufsize;
SYSTEMTIME st;
GetLocalTime(&st);
p += snprintf(p, limit - p,
"%04d/%02d/%02d-%02d:%02d:%02d.%06d %llx ",
int(st.wYear),
int(st.wMonth),
int(st.wDay),
int(st.wHour),
int(st.wMinute),
int(st.wMinute),
int(st.wMilliseconds),
static_cast<long long unsigned int>(thread_id));
// Print the message
if (p < limit) {
va_list backup_ap;
va_copy(backup_ap, ap);
p += vsnprintf(p, limit - p, format, backup_ap);
va_end(backup_ap);
}
// Truncate to available space if necessary
if (p >= limit) {
if (iter == 0) {
continue; // Try again with larger buffer
} else {
p = limit - 1;
}
}
// Add newline if necessary
if (p == base || p[-1] != '\n') {
*p++ = '\n';
}
assert(p <= limit);
DWORD hasWritten = 0;
if(_pFileProxy){
_pFileProxy->Append(Slice(base, p - base));
_pFileProxy->Flush();
}
if (base != buffer) {
delete[] base;
}
break;
}
}
bool Win32Env::FileExists(const std::string& fname)
{
std::string path = fname;
std::wstring wpath;
ToWidePath(ModifyPath(path), wpath);
return ::PathFileExistsW(wpath.c_str()) ? true : false;
}
Status Win32Env::GetChildren(const std::string& dir, std::vector<std::string>* result)
{
Status sRet;
::WIN32_FIND_DATAW wfd;
std::string path = dir;
ModifyPath(path);
path += "\\*.*";
std::wstring wpath;
ToWidePath(path, wpath);
::HANDLE hFind = ::FindFirstFileW(wpath.c_str() ,&wfd);
if(hFind && hFind != INVALID_HANDLE_VALUE){
BOOL hasNext = TRUE;
std::string child;
while(hasNext){
ToNarrowPath(wfd.cFileName, child);
if(child != ".." && child != ".") {
result->push_back(child);
}
hasNext = ::FindNextFileW(hFind,&wfd);
}
::FindClose(hFind);
}
else
sRet = Status::IOError(dir,"Could not get children.");
return sRet;
}
void Win32Env::SleepForMicroseconds( int micros )
{
::Sleep((micros + 999) /1000);
}
Status Win32Env::DeleteFile( const std::string& fname )
{
Status sRet;
std::string path = fname;
std::wstring wpath;
ToWidePath(ModifyPath(path), wpath);
if(!::DeleteFileW(wpath.c_str())) {
sRet = Status::IOError(path, "Could not delete file.");
}
return sRet;
}
Status Win32Env::GetFileSize( const std::string& fname, uint64_t* file_size )
{
Status sRet;
std::string path = fname;
std::wstring wpath;
ToWidePath(ModifyPath(path), wpath);
HANDLE file = ::CreateFileW(wpath.c_str(),
GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
LARGE_INTEGER li;
if(::GetFileSizeEx(file,&li)){
*file_size = (uint64_t)li.QuadPart;
}else
sRet = Status::IOError(path,"Could not get the file size.");
CloseHandle(file);
return sRet;
}
Status Win32Env::RenameFile( const std::string& src, const std::string& target )
{
Status sRet;
std::string src_path = src;
std::wstring wsrc_path;
ToWidePath(ModifyPath(src_path), wsrc_path);
std::string target_path = target;
std::wstring wtarget_path;
ToWidePath(ModifyPath(target_path), wtarget_path);
if(!MoveFileW(wsrc_path.c_str(), wtarget_path.c_str() ) ){
DWORD err = GetLastError();
if(err == 0x000000b7){
if(!::DeleteFileW(wtarget_path.c_str() ) )
sRet = Status::IOError(src, "Could not rename file.");
else if(!::MoveFileW(wsrc_path.c_str(),
wtarget_path.c_str() ) )
sRet = Status::IOError(src, "Could not rename file.");
}
}
return sRet;
}
Status Win32Env::LockFile( const std::string& fname, FileLock** lock )
{
Status sRet;
std::string path = fname;
ModifyPath(path);
Win32FileLock* _lock = new Win32FileLock(path);
if(!_lock->isEnable()){
delete _lock;
*lock = NULL;
sRet = Status::IOError(path, "Could not lock file.");
}
else
*lock = _lock;
return sRet;
}
Status Win32Env::UnlockFile( FileLock* lock )
{
Status sRet;
delete lock;
return sRet;
}
void Win32Env::Schedule( void (*function)(void* arg), void* arg )
{
QueueUserWorkItem(Win32::WorkItemWrapperProc,
new Win32::WorkItemWrapper(function,arg),
WT_EXECUTEDEFAULT);
}
void Win32Env::StartThread( void (*function)(void* arg), void* arg )
{
::_beginthread(function,0,arg);
}
Status Win32Env::GetTestDirectory( std::string* path )
{
Status sRet;
WCHAR TempPath[MAX_PATH];
::GetTempPathW(MAX_PATH,TempPath);
ToNarrowPath(TempPath, *path);
path->append("leveldb\\test\\");
ModifyPath(*path);
return sRet;
}
uint64_t Win32Env::NowMicros()
{
#ifndef USE_VISTA_API
#define GetTickCount64 GetTickCount
#endif
return (uint64_t)(GetTickCount64()*1000);
}
static Status CreateDirInner( const std::string& dirname )
{
Status sRet;
DWORD attr = ::GetFileAttributes(dirname.c_str());
if (attr == INVALID_FILE_ATTRIBUTES) { // doesn't exist:
std::size_t slash = dirname.find_last_of("\\");
if (slash != std::string::npos){
sRet = CreateDirInner(dirname.substr(0, slash));
if (!sRet.ok()) return sRet;
}
BOOL result = ::CreateDirectory(dirname.c_str(), NULL);
if (result == FALSE) {
sRet = Status::IOError(dirname, "Could not create directory.");
return sRet;
}
}
return sRet;
}
Status Win32Env::CreateDir( const std::string& dirname )
{
std::string path = dirname;
if(path[path.length() - 1] != '\\'){
path += '\\';
}
ModifyPath(path);
return CreateDirInner(path);
}
Status Win32Env::DeleteDir( const std::string& dirname )
{
Status sRet;
std::wstring path;
ToWidePath(dirname, path);
ModifyPath(path);
if(!::RemoveDirectoryW( path.c_str() ) ){
sRet = Status::IOError(dirname, "Could not delete directory.");
}
return sRet;
}
Status Win32Env::NewSequentialFile( const std::string& fname, SequentialFile** result )
{
Status sRet;
std::string path = fname;
ModifyPath(path);
Win32SequentialFile* pFile = new Win32SequentialFile(path);
if(pFile->isEnable()){
*result = pFile;
}else {
delete pFile;
sRet = Status::IOError(path, Win32::GetLastErrSz());
}
return sRet;
}
Status Win32Env::NewRandomAccessFile( const std::string& fname, RandomAccessFile** result )
{
Status sRet;
std::string path = fname;
Win32RandomAccessFile* pFile = new Win32RandomAccessFile(ModifyPath(path));
if(!pFile->isEnable()){
delete pFile;
*result = NULL;
sRet = Status::IOError(path, Win32::GetLastErrSz());
}else
*result = pFile;
return sRet;
}
Status Win32Env::NewLogger( const std::string& fname, Logger** result )
{
Status sRet;
std::string path = fname;
Win32MapFile* pMapFile = new Win32MapFile(ModifyPath(path));
if(!pMapFile->isEnable()){
delete pMapFile;
*result = NULL;
sRet = Status::IOError(path,"could not create a logger.");
}else
*result = new Win32Logger(pMapFile);
return sRet;
}
Status Win32Env::NewWritableFile( const std::string& fname, WritableFile** result )
{
Status sRet;
std::string path = fname;
Win32MapFile* pFile = new Win32MapFile(ModifyPath(path));
if(!pFile->isEnable()){
*result = NULL;
sRet = Status::IOError(fname,Win32::GetLastErrSz());
}else
*result = pFile;
return sRet;
}
Win32Env::Win32Env()
{
}
Win32Env::~Win32Env()
{
}
} // Win32 namespace
static port::OnceType once = LEVELDB_ONCE_INIT;
static Env* default_env;
static void InitDefaultEnv() { default_env = new Win32::Win32Env(); }
Env* Env::Default() {
port::InitOnce(&once, InitDefaultEnv);
return default_env;
}
} // namespace leveldb
#endif // defined(LEVELDB_PLATFORM_WINDOWS)
| jesuscoinproject/jesuscoin | src/leveldb/util/env_win.cc | C++ | mit | 25,974 |
<!DOCTYPE html>
<html>
<head>
<title>ECOSOC</title>
<base href="../../">
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet'>
<link rel='shortcut icon' type='image/x-icon' href="Images/logo-new.jpg" />
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection" /><link type="text/css" rel="stylesheet" href="css/main.css" />
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=0.5" />
<!-- Global Site Tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-106611677-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments) };
gtag('js', new Date());
gtag('config', 'UA-106611677-1');
</script>
<style type="text/css">
body {
display: flex;
min-height: 100vh;
flex-direction: column;
}
main {
flex: 1 0 auto;
}
</style>
</head>
<body>
<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
<!-- Modal Structure -->
<div id="modalSchedule" class="modal">
<div class="modal-content">
<h2>Schedule</h2>
</div>
</div>
<div id="modalFAQ" class="modal">
<div class="modal-content">
<h3>JMUN FAQs</h3>
<b>How do I know that my registration was successful?</b> <br><br>
You will receive a confirmation either by September 30th or October 3rd, depending on how early you register. If you do not receive your confirmation by either of these dates, please contact us at<a href="mailto:bangalorejmun@oakridge.in" target="_blank"> bangalorejmun@oakridge.in</a> . <br><br>
<b>What is the dress code?</b> <br><br>
The dress code is formal business attire. For males, we recommend a button down, a pair of trousers and a nice tie. Blazers or jackets are suggested, but not required. For females, we recommend appropriate blouses, or button downs. Trousers and skirts are both acceptable. Formal dresses are also accepted. <br><br>
<b>What is the technology policy?</b><br><br>
Attendance at this year's Bangalore JMUN requires delegates to have a suitable electronic device through which Microsoft Teams can be used, preferrably a laptop or tablet, due to the virtual setting and nature of the event. The Microsoft Teams app must be dowloaded prior to the conference. <br><br>
<b>What is a position paper?</b><br><br>
Position papers are documents from each delegate summarizing his or her country’s views on each committee topic. Further requirements for position papers are laid out in each committee's background guide. Positional papers are optional for delegates this year but are recommeded for the advanced committee delegates. <br><br>
<b>When is the position paper due?</b><br><br>
All position papers are to be sent to the official email ID by the 7th of October. The email ID is bangalorejmun@oakridge.in and the subject should be ‘CommitteeAcronym_Country_PositionPaper’. <br><br>
Ex: ‘WHO_USA_PositionPaper’<br>
‘UNSC_India_PositionPaper’<br><br>
<b>What is the International Press?</b><br><br>
An IP, or International Press, is pressed with the requirements of formulating and conducting interviews on various delegates, discussing key topics with the delegates, interacting frequently with the delegates, presenting the common events taking place in the various committees, and most importantly, create a report of the a detailed account of the events that took place in each committee, based on the input provided by the IP personnel who send the IP heads a detailed account of the proceedings in their particular committee. A formal diction and appropriate register will be maintained while proceeding with writing the report or merging the various information procured from the different personnel handling the collection of information from each committee. <br><br>
</div>
</div>
<div id="modalRegister" class="modal">
<div class="modal-content">
<h4>If you are an External Delegate:</h4>
<p>
<b>Registration Fee: INR 500/-</b> per delegate inclusive of pre-conference training, ceremony access, and Teams account.
</p>
<p><b>Step 1:</b> Fill out the "School Registration Form" under the Registration tab</p>
<p><b>Step 2:</b> Pay the Registration Fee using the Net-Banking details provided. Payment Details are provided under the Registration tab.</p>
<p><b>Step 3:</b> Await authentication from School. Allocation details will be sent once authentication is complete</p>
<br>
<h4>If you are an Oakridge Delegate:</h4>
<p>
<b>Registration Fee: INR 500/-</b> per delegate inclusive of pre-conference training, ceremony access, and Teams account.
</p>
<p><b>Step 1:</b> Fill out the "Oakridge Registration Form" under the Registration tab</p>
<p><b>Step 2:</b> Pay the Registration Fee using the net banking details provided or by making a payment at the Accounts Department. Further details are provided under the Registration tab.</p>
<p><b>Step 3:</b> Await authentication from the School. Allocation details will be sent once authentication is complete</p>
</div>
</div>
<div id="modalPayment" class="modal">
<div class="modal-content">
<h4>Payment Details</h4>
<p>Account Name: Orange Educational Society</p>
<p>Account no : 915010062389280</p>
<p>Bank : AXIS BANK</p>
<p>Branch : Sarjapura road, Bangalore- 560102</p>
<p>IFSC CODE: UTIB0001888,</p>
<p>SWIFT CODE : AXISINBB194</p>
<p>A/C Type: Savings Account</p>
</div>
</div>
<!-- Dropdown Structure -->
<!-- Dropdown Structure- ENABLE ONCE ALL OF THE SUBPAGES ARE READY -->
<ul id='dropdown1' class='dropdown-content'>
<li class="black darken-3"><a href="Committees\ECOSOC\index.html" class="white-text">ECOSOC</a></li>
<li class="black darken-3"><a href="Committees\HRC\index.html" class="white-text">UNHRC</a></li>
<li class="black darken-3"><a href="Committees\SC\index.html" class="white-text">UNSC</a></li>
<li class="black darken-3"><a href="Committees\WHO\index.html" class="white-text">WHO</a></li>
</ul>
<ul id='dropdown2' class='dropdown-content'>
<li class="black darken-3"><a href="Conference/index.html" class="white-text">About</a></li>
<li class="black darken-3"><a href="Secretariat/index.html" class="white-text">Secretariat</a></li>
<li class="black darken-3"><a href="https://drive.google.com/file/d/1lIAxUWGqobZazhPNCon3TRwskdTrzT5t/view?usp=sharing" class="white-text">Schedule</a></li>
</ul>
<ul id='dropdown3' class='dropdown-content'>
<li class="black darken-3"><a href="#modalRegister" class="white-text">How to Register?</a></li>
<li class="black darken-3"><a href="#modalPayment" class="white-text">Payment Details</a></li>
<li class="black darken-3"><a href="https://forms.gle/27Fu5WTCUFcNA7vJ6" class="white-text">Oakridge Registration</a></li>
<li class="black darken-3"><a href="https://forms.gle/p5wY21u6qs1LjgFt8" class="white-text">External Registration</a></li>
</ul>
<ul class="side-nav" id="mobile-demo">
<li><a href="index.html">Home</a></li>
<li><a class="dropdown-button" href="#!" data-activates="dropdown2">Committees<i class="material-icons right">arrow_drop_down</i></a></li>
<li><a href="Conference/index.html">Conference</a></li>
<li><a href="#modalFAQ">FAQs</a></li>
<li><a class="dropdown-button" href="#!" data-activates="dropdown4">Registration<i class="material-icons right">arrow_drop_down</i></a></li>
</ul>
</ul>
<ul id='dropdown3' class='dropdown-content'>
<li class="black darken-3"><a href="#modalRegister" class="white-text">How to Register?</a></li>
<li class="black darken-3"><a href="#modalPayment" class="white-text">Payment Details</a></li>
<li class="black darken-3"><a href="https://forms.gle/27Fu5WTCUFcNA7vJ6" class="white-text">Oakridge Registration</a></li>
<li class="black darken-3"><a href="https://forms.gle/p5wY21u6qs1LjgFt8" class="white-text">External Registration</a></li>
</ul>
<ul class="side-nav" id="mobile-demo">
<li><a href="index.html">Home</a></li>
<li><a class="dropdown-button" href="#!" data-activates="dropdown2">Committees<i class="material-icons right">arrow_drop_down</i></a></li>
<li><a href="Conference/index.html">Conference</a></li>
<li><a href="#modalFAQ">FAQs</a></li>
<!-- <li><a class="dropdown-button" href="#!" data-activates="dropdown4">Registration<i class="material-icons right">arrow_drop_down</i></a></li> -->
</ul>
<script>
$(".button-collapse").sideNav();
</script>
<div class="navbar-fixed" style="font-family: 'Montserrat'; font-weight: bold;">
<nav>
<div class="nav-wrapper white darken-3">
<a href="index.html" class="brand-logo bold"><img src ="Images/logo-new.jpg" class="circle" style="height: 65px;"></a>
<a href="#" data-activates="mobile-demo" class="button-collapse"><i class="material-icons white">menu</i></a>
<ul class="right hide-on-med-and-down">
<li><a id="homeBtn" href="index.html" class="black-text">Home</a></li>
<li><a id="committeesBtn" class="dropdown-button black-text" href="#!" data-activates="dropdown1">Committees<i class="material-icons right">arrow_drop_down</i></a></li>
<li><a id="committeesBtn" class="dropdown-button black-text" href="#!" data-activates="dropdown2">Conference<i class="material-icons right">arrow_drop_down</i></a></li>
<li><a id="registrationBtn" class="dropdown-button black-text" href="#!" data-activates="dropdown3">Registration<i class="material-icons right">arrow_drop_down</i></a></li>
<li><a href="#modalFAQ" class = "black-text">FAQs</a></li>
</ul>
</div>
</nav>
</div>
<div id="index-banner" class="parallax-container">
<div class="container">
<div class="parallax">
<img src="Images/ecofin_bg.jpg" alt="Unsplashed background img 1">
<div style="background-color: black; position: relative; top: 82%; height: 15%; opacity: 0.8;">
<h3 class="white-text center-align">Economic and Social Council</h3>
<p>
The Economic and Social Council (ECOSOC) is one of the six main organs of the United Nations. Established in 1945, this council focuses on three aspects of sustainable development: economic, social and environmental. ECOSOC encourages agreement on policies and actions that make fundamental links across all three aspects.
</p>
<p>
This year, delegates will be engaging in exciting debate in order to discuss the connections between inclusive economic growth and its ability to eradicate poverty.
</p>
</div>
</div>
</div>
</div>
<div class="section white">
<div class="row">
<div class="col s6">
<div class="card white z-depth-5">
<div class="card-content black-text">
<span class="card-title flow-text"><h4 style="font-weight: lighter;">Agenda: The economic impact of COVID on income disparity.</h4></span>
<br>
</div>
<div class="card-action">
</p>
<h5 style="font-family: Segoe UI; font-weight: normal;">The Economic and Social Council is the United Nation's central forum for furthering discussion about policy recommendations for international economic and social issues. It aims to create consensuses, formulate innovative ideas, and further the tenets of sustainable development through debate and collaboration. It focuses on creating policies that create positive, tangible changes in people's real lives.
</h5>
<!-- REMOVE THIS COMMENT WHEN THE BACKGROUND GUIDE IS AVAILABLE!!! <b class="big">Background guide for UNSC is available <a href="https://docs.google.com/document/d/1kic0xJ0WdvtHc57dLludsTj3fS8tbWdplWfoE2ZcMIg/edit?usp=sharing" target="_blank">Here</a></b>
-->
<a class="btn-flat blue darken-4 white-text" href="https://drive.google.com/file/d/1sjLBW4jSbpNliwLpfn77grOy1cgZy-ah/view?usp=sharing" target="_blank">Background Guide</a>
<!--<a class="btn-flat blue darken-4 white-text" href="https://docs.google.com/spreadsheets/d/1djfJjUqG8NbdlzS4ECXo8tuCls0ESM3G6g9wZRBdgLQ/edit?usp=sharing">Country Allocations</a>
<a class="btn-flat blue darken-4 white-text" href="https://drive.google.com/drive/folders/0Bw0gqJdqCw_UTklPa1dyMWpHX2c?usp=sharing">Training material</a> -->
</div>
</div>
</div>
<!--EB Names and Pictures -->
<div class="col s6">
<div class="card white z-depth-5">
<div class="center col s2 offset-s2 flow-text ">
<img src="Images/EB/Tanvi_ECOSOC_CC.jpeg" alt="" class="circle responsive-img"> Co-Chair
<br>Tanvi Gorthi
</div>
<div class="center col s2 offset-s2 flow-text ">
<img src="Images/EB/Vignesh_ECOSOC_CC.jpeg" alt="" class="circle responsive-img">Co-Chair
<br>Vignesh Somjit
</div>
<div class="center col s2 offset-s2 flow-text ">
<img src="Images/EB/Ronav_ECOSOC_M.jpeg" alt="" class="circle responsive-img">Moderator
<br>Ronav Som Kiran
</div>
</div>
</div>
</div>
<div class="row">
<div class="col s6">
<div align="justify" class="card white z-depth-5">
<div class="card-content black-text">
<span class="card-title flow-text"><h4 style="font-weight: lighter;">Meet your EB</h4></span>
<br>
</div>
<div class="card-action">
</p>
<h5 style="font-weight: lighter;">Tanvi Gorthi, Co-Chair</h5>
<p>Tanvi has over four years of MUN experience, both as a delegate and as an Executive Board member. She loves public speaking, has a zeal for economics, and is excited to be your chair in committee this year! </p>
<h5 style="font-weight: lighter;">Vignesh Somjit, Co-Chair</h5>
<p>Vignesh is an avid reader of economics and believes that it offers a comprehensive framework through which important global issues can be understood and addressed.</p>
<h5 style="font-weight: lighter;">Ronav Som Kiran, Moderator</h5>
<p>Ronav has had a 4 year MUN experience. This is his first time in the executive board and would like to make the most of it by helping teach you guys how to be good MUNers. He is also an avid reader and would love to see your ideas about the agenda at hand.</p>
</div>
</div>
</div>
</div>
</div>
</div>
<footer class="page-footer black ">
<div class="container ">
<div class="row ">
<div class="col s12 ">
<h5 class="white-text ">Contact Details</h5>
<p class="grey-text text-lighten-4 ">Send any queries over to <a href="mailto:bangalorejmun@oakridge.in " target="_blank "> bangalorejmun@oakridge.in</a> </p>
<!--<p class="grey-text text-lighten-4 ">Teacher Advisor: <a href="tel:8971857769 " target="_blank ">+91 8971857769 (Ms. Debjani)</a> </p>
<p class="grey-text text-lighten-4 ">Secretary General: <a href="tel:9108274028 " target="_blank ">+91 9108274028 (Abhinav)</a> </p> </div> -->
</div>
</div>
<div class="row ">
<div class="footer-copyright ">
<div class="col s7 ">
<a class="grey-text text-lighten-4 " href=" "><i class="material-icons ">copyright</i>2019 Bangalore Junior MUN</a>
</div>
<div class="col s5 ">
Developed by <a href="https://github.com/Nexus987 " target="_blank ">Nexus</a>, <a href="https://github.com/gaurangbharti1 " target="_blank ">GBHacker23</a> and <a href="https://github.com/BK-Modding/ " target="_blank ">BK-Modding</a>
</div>
<div class="col s5">
Renovated for 2019 by <a href="https://github.com/muhsin7" target="_blank">Muhsin7</a>, <a href="https://github.com/Teminix" target="_blank">Teminix</a> and <a href="https://github.com/Chanmanstanflan" target="_blank">Chanmanstanflan</a>
</div>
<div class="col s5">
Renovated for 2020 by <a href="https://github.com/iAarush" target="_blank">iAarush</a>, <a href="https://github.com/PrasidhV" target="_blank">PrasidhV</a> and <a href="https://github.com/Shubaan7" target="_blank">Shubaan007</a>
</div>
</div>
</div>
</footer>
<script>
$(document).ready(function() {
// the "href " attribute of the modal trigger must specify the modal ID that wants to be triggered
$('.modal').modal();
});
$(document).ready(function() {
$(".dropdown-button ").dropdown({
coverTrigger: false
});
});
$(document).ready(function() {
$('.parallax').parallax();
});
</script>
</body>
</html>
| bangalorejmun/bangalorejmun.github.io | Committees/ECOSOC/index.html | HTML | mit | 18,936 |
'use strict';
const BitcrusherProps = {
bits: {
type: 'number',
bounds: [1, 16],
defaultValue: 4
},
normfreq: {
type: 'number',
bounds: [0, 1],
step: 0.1,
defaultValue: 0.1
},
bufferSize: {
type: 'number',
bounds: [256, 16384],
defaultValue: 4096
},
bypass: {
type: 'number',
bounds: [0, 1],
defaultValue: 0
}
};
export default BitcrusherProps;
| civa86/web-synth | lib/src/properties/BitcrusherProps.js | JavaScript | mit | 483 |
wherzcroc
=========
Using hidden markov models to find a crocodile in a graph. Assignment for AI course (Fall 2014) at Uppsala University
Setup
-----
1. Clone the repository
2. Unzip files from the webpage on studentportalen into two folders: *Debug* and *Release* (in the repo directory).
3. The setup should work out of the box: otherwise, follow instructions from the PDF
when it comes to inclusion. Please mention it if the setup does not work directly.
| uzerNAN/wherzcroc | README.md | Markdown | mit | 463 |
/***********************************************************************************
** MIT License **
** **
** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) **
** **
** Permission is hereby granted, free of charge, to any person obtaining a copy **
** of this software and associated documentation files (the "Software"), to deal **
** in the Software without restriction, including without limitation the rights **
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell **
** copies of the Software, and to permit persons to whom the Software is **
** furnished to do so, subject to the following conditions: **
** **
** The above copyright notice and this permission notice shall be included in all **
** copies or substantial portions of the Software. **
** **
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR **
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, **
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE **
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER **
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, **
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE **
** SOFTWARE. **
***********************************************************************************/
#include "HorizontalListWidget.hpp"
namespace Sn {
HorizontalListWidget::HorizontalListWidget(QWidget* parent) :
QListWidget(parent),
m_mouseDown(false)
{
setFocusPolicy(Qt::NoFocus);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setMovement(QListView::Static);
setResizeMode(QListView::Adjust);
setViewMode(QListView::IconMode);
setSelectionRectVisible(false);
}
void HorizontalListWidget::mousePressEvent(QMouseEvent* event)
{
m_mouseDown = true;
QListWidget::mousePressEvent(event);
}
void HorizontalListWidget::mouseMoveEvent(QMouseEvent* event)
{
if (!itemAt(event->pos()))
return;
QListWidget::mouseMoveEvent(event);
}
void HorizontalListWidget::mouseReleaseEvent(QMouseEvent* event)
{
m_mouseDown = false;
QListWidget::mouseReleaseEvent(event);
}
void HorizontalListWidget::wheelEvent(QWheelEvent* event)
{
Q_UNUSED(event);
}
} | Feldrise/Sielo-NavigateurV3-WebEngine | Core/Widgets/HorizontalListWidget.cpp | C++ | mit | 2,823 |
import os
import sys
from Bio import SeqIO
f = open(sys.argv[1], 'rU')
out = open(sys.argv[2], 'w')
for records in SeqIO.parse(f, 'fastq'):
SeqIO.write(records, out, 'fasta')
| chnops/code | fastq_to_fasta.py | Python | mit | 177 |
require 'strscan'
##
# Parses a gem.deps.rb.lock file and constructs a LockSet containing the
# dependencies found inside. If the lock file is missing no LockSet is
# constructed.
class Gem::RequestSet::Lockfile
##
# Raised when a lockfile cannot be parsed
class ParseError < Gem::Exception
##
# The column where the error was encountered
attr_reader :column
##
# The line where the error was encountered
attr_reader :line
##
# The location of the lock file
attr_reader :path
##
# Raises a ParseError with the given +message+ which was encountered at a
# +line+ and +column+ while parsing.
def initialize message, column, line, path
@line = line
@column = column
@path = path
super "#{message} (at line #{line} column #{column})"
end
end
##
# The platforms for this Lockfile
attr_reader :platforms
##
# Creates a new Lockfile for the given +request_set+ and +gem_deps_file+
# location.
def initialize request_set, gem_deps_file
@set = request_set
@gem_deps_file = File.expand_path(gem_deps_file)
@gem_deps_dir = File.dirname(@gem_deps_file)
@current_token = nil
@line = 0
@line_pos = 0
@platforms = []
@tokens = []
end
def add_DEPENDENCIES out # :nodoc:
out << "DEPENDENCIES"
@requests.sort_by { |r| r.name }.each do |request|
spec = request.spec
if [Gem::Resolver::VendorSpecification,
Gem::Resolver::GitSpecification].include? spec.class then
out << " #{request.name}!"
else
requirement = request.request.dependency.requirement
out << " #{request.name}#{requirement.for_lockfile}"
end
end
out << nil
end
def add_GEM out # :nodoc:
return if @spec_groups.empty?
source_groups = @spec_groups.values.flatten.group_by do |request|
request.spec.source.uri
end
source_groups.sort_by { |group,| group.to_s }.map do |group, requests|
out << "GEM"
out << " remote: #{group}"
out << " specs:"
requests.sort_by { |request| request.name }.each do |request|
platform = "-#{request.spec.platform}" unless
Gem::Platform::RUBY == request.spec.platform
out << " #{request.name} (#{request.version}#{platform})"
request.full_spec.dependencies.sort.each do |dependency|
requirement = dependency.requirement
out << " #{dependency.name}#{requirement.for_lockfile}"
end
end
out << nil
end
end
def add_GIT out
return unless git_requests =
@spec_groups.delete(Gem::Resolver::GitSpecification)
by_repository_revision = git_requests.group_by do |request|
source = request.spec.source
[source.repository, source.rev_parse]
end
out << "GIT"
by_repository_revision.each do |(repository, revision), requests|
out << " remote: #{repository}"
out << " revision: #{revision}"
out << " specs:"
requests.sort_by { |request| request.name }.each do |request|
out << " #{request.name} (#{request.version})"
dependencies = request.spec.dependencies.sort_by { |dep| dep.name }
dependencies.each do |dep|
out << " #{dep.name}#{dep.requirement.for_lockfile}"
end
end
end
out << nil
end
def relative_path_from dest, base # :nodoc:
dest = File.expand_path(dest)
base = File.expand_path(base)
if dest.index(base) == 0
return dest[base.size+1..-1]
else
dest
end
end
def add_PATH out # :nodoc:
return unless path_requests =
@spec_groups.delete(Gem::Resolver::VendorSpecification)
out << "PATH"
path_requests.each do |request|
directory = File.expand_path(request.spec.source.uri)
out << " remote: #{relative_path_from directory, @gem_deps_dir}"
out << " specs:"
out << " #{request.name} (#{request.version})"
end
out << nil
end
def add_PLATFORMS out # :nodoc:
out << "PLATFORMS"
platforms = @requests.map { |request| request.spec.platform }.uniq
platforms.delete Gem::Platform::RUBY if platforms.length > 1
platforms.each do |platform|
out << " #{platform}"
end
out << nil
end
##
# Gets the next token for a Lockfile
def get expected_types = nil, expected_value = nil # :nodoc:
@current_token = @tokens.shift
type, value, column, line = @current_token
if expected_types and not Array(expected_types).include? type then
unget
message = "unexpected token [#{type.inspect}, #{value.inspect}], " +
"expected #{expected_types.inspect}"
raise ParseError.new message, column, line, "#{@gem_deps_file}.lock"
end
if expected_value and expected_value != value then
unget
message = "unexpected token [#{type.inspect}, #{value.inspect}], " +
"expected [#{expected_types.inspect}, " +
"#{expected_value.inspect}]"
raise ParseError.new message, column, line, "#{@gem_deps_file}.lock"
end
@current_token
end
def parse # :nodoc:
tokenize
until @tokens.empty? do
type, data, column, line = get
case type
when :section then
skip :newline
case data
when 'DEPENDENCIES' then
parse_DEPENDENCIES
when 'GIT' then
parse_GIT
when 'GEM' then
parse_GEM
when 'PATH' then
parse_PATH
when 'PLATFORMS' then
parse_PLATFORMS
else
type, = get until @tokens.empty? or peek.first == :section
end
else
raise "BUG: unhandled token #{type} (#{data.inspect}) at line #{line} column #{column}"
end
end
end
def parse_DEPENDENCIES # :nodoc:
while not @tokens.empty? and :text == peek.first do
_, name, = get :text
requirements = []
case peek[0]
when :bang then
get :bang
spec = @set.sets.select { |set|
Gem::Resolver::GitSet === set or
Gem::Resolver::VendorSet === set
}.map { |set|
set.specs[name]
}.first
requirements << spec.version
when :l_paren then
get :l_paren
loop do
_, op, = get :requirement
_, version, = get :text
requirements << "#{op} #{version}"
break unless peek[0] == :comma
get :comma
end
get :r_paren
end
@set.gem name, *requirements
skip :newline
end
end
def parse_GEM # :nodoc:
get :entry, 'remote'
_, data, = get :text
source = Gem::Source.new data
skip :newline
get :entry, 'specs'
skip :newline
set = Gem::Resolver::LockSet.new source
last_spec = nil
while not @tokens.empty? and :text == peek.first do
_, name, column, = get :text
case peek[0]
when :newline then
last_spec.add_dependency Gem::Dependency.new name if column == 6
when :l_paren then
get :l_paren
type, data, = get [:text, :requirement]
if type == :text and column == 4 then
last_spec = set.add name, data, Gem::Platform::RUBY
else
dependency = parse_dependency name, data
last_spec.add_dependency dependency
end
get :r_paren
else
raise "BUG: unknown token #{peek}"
end
skip :newline
end
@set.sets << set
end
def parse_GIT # :nodoc:
get :entry, 'remote'
_, repository, = get :text
skip :newline
get :entry, 'revision'
_, revision, = get :text
skip :newline
get :entry, 'specs'
skip :newline
set = Gem::Resolver::GitSet.new
last_spec = nil
while not @tokens.empty? and :text == peek.first do
_, name, column, = get :text
case peek[0]
when :newline then
last_spec.add_dependency Gem::Dependency.new name if column == 6
when :l_paren then
get :l_paren
type, data, = get [:text, :requirement]
if type == :text and column == 4 then
last_spec = set.add_git_spec name, data, repository, revision, true
else
dependency = parse_dependency name, data
last_spec.spec.dependencies << dependency
end
get :r_paren
else
raise "BUG: unknown token #{peek}"
end
skip :newline
end
@set.sets << set
end
def parse_PATH # :nodoc:
get :entry, 'remote'
_, directory, = get :text
skip :newline
get :entry, 'specs'
skip :newline
set = Gem::Resolver::VendorSet.new
last_spec = nil
while not @tokens.empty? and :text == peek.first do
_, name, column, = get :text
case peek[0]
when :newline then
last_spec.add_dependency Gem::Dependency.new name if column == 6
when :l_paren then
get :l_paren
type, data, = get [:text, :requirement]
if type == :text and column == 4 then
last_spec = set.add_vendor_gem name, directory
else
dependency = parse_dependency name, data
last_spec.spec.dependencies << dependency
end
get :r_paren
else
raise "BUG: unknown token #{peek}"
end
skip :newline
end
@set.sets << set
end
def parse_PLATFORMS # :nodoc:
while not @tokens.empty? and :text == peek.first do
_, name, = get :text
@platforms << name
skip :newline
end
end
##
# Parses the requirements following the dependency +name+ and the +op+ for
# the first token of the requirements and returns a Gem::Dependency object.
def parse_dependency name, op # :nodoc:
return Gem::Dependency.new name unless peek[0] == :text
_, version, = get :text
requirements = ["#{op} #{version}"]
while peek[0] == :comma do
get :comma
_, op, = get :requirement
_, version, = get :text
requirements << "#{op} #{version}"
end
Gem::Dependency.new name, requirements
end
##
# Peeks at the next token for Lockfile
def peek # :nodoc:
@tokens.first || [:EOF]
end
def skip type # :nodoc:
get while not @tokens.empty? and peek.first == type
end
##
# The contents of the lock file.
def to_s
@set.resolve
out = []
@requests = @set.sorted_requests
@spec_groups = @requests.group_by do |request|
request.spec.class
end
add_PATH out
add_GIT out
add_GEM out
add_PLATFORMS out
add_DEPENDENCIES out
out.join "\n"
end
##
# Calculates the column (by byte) and the line of the current token based on
# +byte_offset+.
def token_pos byte_offset # :nodoc:
[byte_offset - @line_pos, @line]
end
##
# Converts a lock file into an Array of tokens. If the lock file is missing
# an empty Array is returned.
def tokenize # :nodoc:
@line = 0
@line_pos = 0
@platforms = []
@tokens = []
@current_token = nil
lock_file = "#{@gem_deps_file}.lock"
@input = File.read lock_file
s = StringScanner.new @input
until s.eos? do
pos = s.pos
pos = s.pos if leading_whitespace = s.scan(/ +/)
if s.scan(/[<|=>]{7}/) then
message = "your #{lock_file} contains merge conflict markers"
column, line = token_pos pos
raise ParseError.new message, column, line, lock_file
end
@tokens <<
case
when s.scan(/\r?\n/) then
token = [:newline, nil, *token_pos(pos)]
@line_pos = s.pos
@line += 1
token
when s.scan(/[A-Z]+/) then
if leading_whitespace then
text = s.matched
text += s.scan(/[^\s)]*/).to_s # in case of no match
[:text, text, *token_pos(pos)]
else
[:section, s.matched, *token_pos(pos)]
end
when s.scan(/([a-z]+):\s/) then
s.pos -= 1 # rewind for possible newline
[:entry, s[1], *token_pos(pos)]
when s.scan(/\(/) then
[:l_paren, nil, *token_pos(pos)]
when s.scan(/\)/) then
[:r_paren, nil, *token_pos(pos)]
when s.scan(/<=|>=|=|~>|<|>|!=/) then
[:requirement, s.matched, *token_pos(pos)]
when s.scan(/,/) then
[:comma, nil, *token_pos(pos)]
when s.scan(/!/) then
[:bang, nil, *token_pos(pos)]
when s.scan(/[^\s),!]*/) then
[:text, s.matched, *token_pos(pos)]
else
raise "BUG: can't create token for: #{s.string[s.pos..-1].inspect}"
end
end
@tokens
rescue Errno::ENOENT
@tokens
end
##
# Ungets the last token retrieved by #get
def unget # :nodoc:
@tokens.unshift @current_token
end
##
# Writes the lock file alongside the gem dependencies file
def write
open "#{@gem_deps_file}.lock", 'w' do |io|
io.write to_s
end
end
end
| justsml/docker-build-server | ruby-2.1.0/lib/ruby/site_ruby/2.1.0/rubygems/request_set/lockfile.rb | Ruby | mit | 13,070 |
define({
"_widgetLabel": "Tra cứu Địa lý",
"description": "Duyệt đến hoặc Kéo <a href='./widgets/GeoLookup/data/sample.csv' tooltip='Download an example sheet' target='_blank'> trang tính </a> tại đây để mô phỏng và thêm các dữ liệu bản đồ vào trang tính đó.",
"selectCSV": "Chọn một CSV",
"loadingCSV": "Đang tải CSV",
"savingCSV": "Xuất CSV",
"clearResults": "Xóa",
"downloadResults": "Tải xuống",
"plotOnly": "Chỉ các Điểm Vẽ bản đồ",
"plottingRows": "Hàng vẽ bản đồ",
"projectionChoice": "CSV trong",
"projectionLat": "Vĩ độ/Kinh độ",
"projectionMap": "Phép chiếu Bản đồ",
"messages": "Thông báo",
"error": {
"fetchingCSV": "Đã xảy ra lỗi khi truy xuất các mục từ kho lưu trữ CSV: ${0}",
"fileIssue": "Không xử lý được tệp.",
"notCSVFile": "Hiện chỉ hỗ trợ các tệp được ngăn cách bằng dấu phẩy (.csv).",
"invalidCoord": "Trường vị trí không hợp lệ. Vui lòng kiểm tra tệp .csv.",
"tooManyRecords": "Rất tiếc, hiện không được có quá ${0} bản ghi.",
"CSVNoRecords": "Tệp không chứa bất kỳ hồ sơ nào.",
"CSVEmptyFile": "Không có nội dung trong tệp."
},
"results": {
"csvLoaded": "Đã tải ${0} bản ghi từ tệp CSV",
"recordsPlotted": "Đã định vị ${0}/${1} bản ghi trên bản đồ",
"recordsEnriched": "Đã xử lý ${0}/${1}, đã bổ sung ${2} so với ${3}",
"recordsError": "${0} bản ghi có lỗi",
"recordsErrorList": "Hàng ${0} có sự cố",
"label": "Kết quả CSV"
}
}); | cmccullough2/cmv-wab-widgets | wab/2.3/widgets/GeoLookup/nls/vi/strings.js | JavaScript | mit | 1,683 |
<html>
<head>
<title>Member List - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">
</head>
<body>
<!-- Generated by Doxygen 1.7.6.1 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="dirs.html"><span>Directories</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespaceOgre.html">Ogre</a> </li>
<li class="navelem"><a class="el" href="classOgre_1_1GLESDefaultHardwareBufferManager.html">GLESDefaultHardwareBufferManager</a> </li>
</ul>
</div>
</div>
<div class="header">
<div class="headertitle">
<div class="title">Ogre::GLESDefaultHardwareBufferManager Member List</div> </div>
</div><!--header-->
<div class="contents">
This is the complete list of members for <a class="el" href="classOgre_1_1GLESDefaultHardwareBufferManager.html">Ogre::GLESDefaultHardwareBufferManager</a>, including all inherited members.<table>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#ab523a5b31c88599812538441b7e37775">_forceReleaseBufferCopies</a>(const HardwareVertexBufferSharedPtr &sourceBuffer)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#a0da9a2c9a66030d32c90871191da0b6a">_forceReleaseBufferCopies</a>(HardwareVertexBuffer *sourceBuffer)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#a9a2793066da237001972061b76930c95">_freeUnusedBufferCopies</a>(void)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#aee835c8225ba41a1358db813ce080b0e">_notifyIndexBufferDestroyed</a>(HardwareIndexBuffer *buf)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#a2b188dbba89b0210ad7359434aa87bee">_notifyVertexBufferDestroyed</a>(HardwareVertexBuffer *buf)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#a8632cd79b8f18ed2b21bd6b474a49276">_releaseBufferCopies</a>(bool forceFreeUnused=false)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1AllocatedObject.html#a366445eb206e55a2199267b8b9089ebb">AllocatedObject</a>()</td><td><a class="el" href="classOgre_1_1AllocatedObject.html">Ogre::AllocatedObject< Alloc ></a></td><td><code> [explicit]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#a9061909fca1c96d50ddbeeee6df8a4d8">allocateVertexBufferCopy</a>(const HardwareVertexBufferSharedPtr &sourceBuffer, BufferLicenseType licenseType, HardwareBufferLicensee *licensee, bool copyData=false)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#a88f21df1e7ee330033812ddeba4a08faa994cf0191de83556e3c1e6cf30cd6acb">BLT_AUTOMATIC_RELEASE</a> enum value</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#a88f21df1e7ee330033812ddeba4a08faa372ccf538e8a6022bba092d2b47f4fdb">BLT_MANUAL_RELEASE</a> enum value</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#a88f21df1e7ee330033812ddeba4a08fa">BufferLicenseType</a> enum name</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#a90b4266571e1852e2475a63c062623a2">createIndexBuffer</a>(HardwareIndexBuffer::IndexType itype, size_t numIndexes, HardwareBuffer::Usage usage, bool useShadowBuffer=false)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#a875cea867279770d7900f292a8217db6">createRenderToVertexBuffer</a>()</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#adee7ce85fcdeefb8b97b37ece2bab8e4">createVertexBuffer</a>(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer=false)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#a4d907dd6ed467886ca7df6a188b73d4d">createVertexBufferBinding</a>(void)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#a36d7b275f4a2b39b27f55ace09140d03">createVertexBufferBindingImpl</a>(void)</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected, virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#a0d6a29a55a89d937cec4cbaa6c7e8b4b">createVertexDeclaration</a>(void)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#ab3756b338f15ec08f13109ec3f8808a1">createVertexDeclarationImpl</a>(void)</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected, virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#a995a5db6b774e98b46c598dcb569f983">destroyAllBindings</a>(void)</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected, virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#a4be16779dfe2b99fc3395bfe66ba4b4d">destroyAllDeclarations</a>(void)</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected, virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#af5abdc6a7e28634b759189e54f1e6fdd">destroyVertexBufferBinding</a>(VertexBufferBinding *binding)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#a39d2f9bd9b2388498b2143fb7c24710c">destroyVertexBufferBindingImpl</a>(VertexBufferBinding *binding)</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected, virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#a8df941430aef9a6c87660655b51672a3">destroyVertexDeclaration</a>(VertexDeclaration *decl)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#af111248f2e13a5b6a49ca993a2e526e1">destroyVertexDeclarationImpl</a>(VertexDeclaration *decl)</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected, virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#a66f8e4f014fc41a52f35f7c0b03569e0">EXPIRED_DELAY_FRAME_THRESHOLD</a></td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected, static]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#ab1b16f5bb965056ed416ca0d7eedb991">FreeTemporaryVertexBufferMap</a> typedef</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#a380063fef4a4563c90d45a03ac196dc7">getSingleton</a>(void)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [static]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#ab633b90f5015dc3199f96e0514347b3b">getSingletonPtr</a>(void)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [static]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1GLESDefaultHardwareBufferManager.html#a3cf90c8b4eeb8f8717d3e18527090a4c">GLESDefaultHardwareBufferManager</a>()</td><td><a class="el" href="classOgre_1_1GLESDefaultHardwareBufferManager.html">Ogre::GLESDefaultHardwareBufferManager</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#a01633a02494f92550596f8f261885e6c">HardwareBufferManager</a>(HardwareBufferManagerBase *imp)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#aa1f5ef725fdeacc6018e1dee3b7eded5">HardwareBufferManagerBase</a>()</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#a2b2a1446c08ef1bb58c47987b62d83d0">IndexBufferList</a> typedef</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#ac3cb89b74c26e42415d599b59079f5d7">makeBufferCopy</a>(const HardwareVertexBufferSharedPtr &source, HardwareBuffer::Usage usage, bool useShadowBuffer)</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected, virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#ac5339ff98d67f523eb88f9d1b29567d9">mFreeTempVertexBufferMap</a></td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#a154ee1cdff3ec67765532601ad272cb8">mImpl</a></td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#a458d12d5abfa8d8971a4c4c6b214f799">mIndexBuffers</a></td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1Singleton.html#aff0baaaed91d8505cfb72b7725ae1c37">msSingleton</a></td><td><a class="el" href="classOgre_1_1Singleton.html">Ogre::Singleton< HardwareBufferManager ></a></td><td><code> [protected, static]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#a811086c11e14fa760b42ea958884804e">mTempVertexBufferLicenses</a></td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#a98d9ba3a449e791f89a53d7fcf89c00a">mUnderUsedFrameCount</a></td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#a30d13bdd51fd0ffb1b2f5cc13bc15786">mVertexBufferBindings</a></td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#a6a99117e4adc55561ec0eb36617115a4">mVertexBuffers</a></td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#ab93e6c8ebe86328233d604c78f9cbb7b">mVertexDeclarations</a></td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1AllocatedObject.html#a8357fe4fb4849772b94baa4bf47c7ded">operator delete</a>(void *ptr)</td><td><a class="el" href="classOgre_1_1AllocatedObject.html">Ogre::AllocatedObject< Alloc ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1AllocatedObject.html#a1c727e879a260c37b00ce5505fe8e144">operator delete</a>(void *ptr, void *)</td><td><a class="el" href="classOgre_1_1AllocatedObject.html">Ogre::AllocatedObject< Alloc ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1AllocatedObject.html#acb46d4b0a597156d9ba5abc39d127792">operator delete</a>(void *ptr, const char *, int, const char *)</td><td><a class="el" href="classOgre_1_1AllocatedObject.html">Ogre::AllocatedObject< Alloc ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1AllocatedObject.html#a93e6a86dde5483c053ca0f2a85bbfd6c">operator delete[]</a>(void *ptr)</td><td><a class="el" href="classOgre_1_1AllocatedObject.html">Ogre::AllocatedObject< Alloc ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1AllocatedObject.html#a595ea4c05da8aa987d3800e65d23355d">operator delete[]</a>(void *ptr, const char *, int, const char *)</td><td><a class="el" href="classOgre_1_1AllocatedObject.html">Ogre::AllocatedObject< Alloc ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1AllocatedObject.html#a421b197ca3a38da17e2eb1531a645fa2">operator new</a>(size_t sz, const char *file, int line, const char *func)</td><td><a class="el" href="classOgre_1_1AllocatedObject.html">Ogre::AllocatedObject< Alloc ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1AllocatedObject.html#ac4bdf968b7b9af8a5239a27da73d5711">operator new</a>(size_t sz)</td><td><a class="el" href="classOgre_1_1AllocatedObject.html">Ogre::AllocatedObject< Alloc ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1AllocatedObject.html#ab78a921e54419be677839cdf15d1f0b8">operator new</a>(size_t sz, void *ptr)</td><td><a class="el" href="classOgre_1_1AllocatedObject.html">Ogre::AllocatedObject< Alloc ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1AllocatedObject.html#a4be37baef81876985aa1071ad5acc6dd">operator new[]</a>(size_t sz, const char *file, int line, const char *func)</td><td><a class="el" href="classOgre_1_1AllocatedObject.html">Ogre::AllocatedObject< Alloc ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1AllocatedObject.html#afa2943846ba6a2b5824a12857139cf5e">operator new[]</a>(size_t sz)</td><td><a class="el" href="classOgre_1_1AllocatedObject.html">Ogre::AllocatedObject< Alloc ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#a763b65efa057185d7acbe073bf0e3610">registerVertexBufferSourceAndCopy</a>(const HardwareVertexBufferSharedPtr &sourceBuffer, const HardwareVertexBufferSharedPtr &copy)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#a34bc652b029f856a5b130f850ba333a0">releaseVertexBufferCopy</a>(const HardwareVertexBufferSharedPtr &bufferCopy)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1Singleton.html#a2b0622a1223ac3a0c6b9c53e787b8d93">Singleton</a>(void)</td><td><a class="el" href="classOgre_1_1Singleton.html">Ogre::Singleton< HardwareBufferManager ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#ac56a99f7b4b029db20fd8b94f1e82c13">TemporaryVertexBufferLicenseMap</a> typedef</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#af83a478657dabe2d2e35f0d876abcc5b">touchVertexBufferCopy</a>(const HardwareVertexBufferSharedPtr &bufferCopy)</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#afd420f56dc09d1e9975179e2ffe824ca">UNDER_USED_FRAME_THRESHOLD</a></td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected, static]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#a44e20d0e3ca12fa67e5003266a87af52">VertexBufferBindingList</a> typedef</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#ac413284fee3eb42ef05be9a920da448b">VertexBufferList</a> typedef</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#ab3ae22ef96c13dfa02878d27d592f3bc">VertexDeclarationList</a> typedef</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1AllocatedObject.html#a499773d35ca98b2df7c2699fc8c1bea2">~AllocatedObject</a>()</td><td><a class="el" href="classOgre_1_1AllocatedObject.html">Ogre::AllocatedObject< Alloc ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1GLESDefaultHardwareBufferManager.html#a6dcdca57b9c30da03719d175c6885858">~GLESDefaultHardwareBufferManager</a>()</td><td><a class="el" href="classOgre_1_1GLESDefaultHardwareBufferManager.html">Ogre::GLESDefaultHardwareBufferManager</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManager.html#aabd161897c942b29fd21373427dd8485">~HardwareBufferManager</a>()</td><td><a class="el" href="classOgre_1_1HardwareBufferManager.html">Ogre::HardwareBufferManager</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html#abc50f8bac0fad6710aa205d0c4e295c4">~HardwareBufferManagerBase</a>()</td><td><a class="el" href="classOgre_1_1HardwareBufferManagerBase.html">Ogre::HardwareBufferManagerBase</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classOgre_1_1Singleton.html#a9bc0518bb06d12629e287149cdcc4b5d">~Singleton</a>(void)</td><td><a class="el" href="classOgre_1_1Singleton.html">Ogre::Singleton< HardwareBufferManager ></a></td><td></td></tr>
</table></div><!-- contents -->
<hr>
<p>
Copyright © 2012 Torus Knot Software Ltd<br />
<!--Creative Commons License--><a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-sa/3.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-ShareAlike 3.0 Unported License</a>.<br/>
<!--/Creative Commons License--><!-- <rdf:RDF xmlns="http://web.resource.org/cc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<Work rdf:about="">
<license rdf:resource="http://creativecommons.org/licenses/by-sa/2.5/" />
<dc:type rdf:resource="http://purl.org/dc/dcmitype/Text" />
</Work>
<License rdf:about="http://creativecommons.org/licenses/by-sa/2.5/"><permits rdf:resource="http://web.resource.org/cc/Reproduction"/><permits rdf:resource="http://web.resource.org/cc/Distribution"/><requires rdf:resource="http://web.resource.org/cc/Notice"/><requires rdf:resource="http://web.resource.org/cc/Attribution"/><permits rdf:resource="http://web.resource.org/cc/DerivativeWorks"/><requires rdf:resource="http://web.resource.org/cc/ShareAlike"/></License></rdf:RDF> -->
Last modified Sun Sep 2 2012 07:27:57
</p>
</body>
</html>
| jjenki11/blaze-chem-rendering | ogre/ogre_src_v1-8-1/Docs/api/html/classOgre_1_1GLESDefaultHardwareBufferManager-members.html | HTML | mit | 23,841 |
var chai = require("chai")
var should = chai.should();
chai.use(require("chai-http"));
var request = chai.request(require("./server"))
var db = require("mongojs")("test")
describe("CRUD Handler", () => {
before(done => {
done()
})
beforeEach(done => {
db.dropDatabase(done);
})
after(done => {
db.dropDatabase(done)
})
it("should save a document", (done) => {
var data = {
name: "test"
}
request.post("/test")
.send(data)
.end((err, res) => {
should.not.exist(err)
res.should.have.status(201);
res.body.should.be.an("object")
res.body.should.have.keys(['error', 'data'])
res.body.error.should.not.be.ok;
res.body.data.name.should.be.eql("test")
res.body.data.should.have.property("_id");
done()
})
})
it("should list all documents", (done ) => {
var list = [
{name: 'test21'}, {name: 'test22'}
]
db.collection("test").insert(list, (err, result) => {
request.get("/test")
.end((err, res) => {
should.not.exist(err)
res.should.have.status(200)
res.body.should.be.an("object")
res.body.should.have.keys(['error', 'data'])
res.body.error.should.not.be.ok;
res.body.data.should.have.keys(['count', 'list'])
res.body.data.count.should.be.eql(2)
res.body.data.list.length.should.be.eql(2)
done()
})
})
})
it("should get a single document", done => {
var doc = {
name: 'test3'
}
db.collection('test').insert(doc, (err, result ) => {
request.get("/test/" + result._id)
.end((err, res) => {
should.not.exist(err)
res.should.have.status(200)
res.body.should.be.an("object")
res.body.should.have.keys(['error', 'data'])
res.body.error.should.not.be.ok;
res.body.data.should.have.keys(['_id', 'name'])
res.body.data.name.should.be.eql(doc.name);
done()
})
})
})
it("should update an existing document", done => {
var doc = {
name: 'test3'
}
db.collection('test').insert(doc, (err, result ) => {
result.name = "test3_updated";
request.put("/test/" + result._id)
.send(result)
.end((err, res) => {
should.not.exist(err)
res.should.have.status(202)
res.body.should.be.an("object")
res.body.should.have.keys(['error', 'data'])
res.body.error.should.not.be.ok;
db.collection('test').findOne({_id: db.ObjectId(result._id)}, (err, result1) => {
should.not.exist(err)
result1.name.should.be.eql(result.name);
done()
})
})
})
})
it("should remove a document", done => {
var doc = {
name: 'test3'
}
db.collection('test').insert(doc, (err, result ) => {
request.delete("/test/" + result._id)
.end((err, res) => {
should.not.exist(err)
res.should.have.status(202)
res.body.should.be.an("object")
res.body.should.have.keys(['error', 'data'])
res.body.error.should.not.be.ok;
db.collection('test').findOne({_id: db.ObjectId(result._id)}, (err, result1) => {
should.not.exist(err)
should.not.exist(result1);
done()
})
})
})
})
}) | AkashBabu/server-helper | test/crudHandler/test.js | JavaScript | mit | 4,155 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE Arrows #-}
module Main where
import Opaleye
import Data.Profunctor.Product
import Data.Profunctor.Product.Default
import Data.Profunctor.Product.TH (makeAdaptorAndInstance)
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromField (FromField(..))
import Prelude hiding (id)
import Control.Arrow
newtype UserId = UserId Int deriving (Show)
data UserPoly id name email = User { id :: id, name :: name, email :: email } deriving (Show)
type User = UserPoly UserId String String
type UserPGW = UserPoly (Column PGInt4) (Column PGText) (Column PGText)
type UserPGR = UserPoly (Column PGInt4) (Column PGText) (Column PGText)
$(makeAdaptorAndInstance "pUser" ''UserPoly)
userTable :: Table UserPGW UserPGR
userTable = Table "users" (pUser User {
id = required "id",
name = required "name",
email = required "email"
}
)
instance FromField UserId where
fromField field bs = UserId <$> fromField field bs
instance QueryRunnerColumnDefault PGInt4 UserId where
queryRunnerColumnDefault = fieldQueryRunnerColumn
getUserRows :: IO [User]
getUserRows = do
conn <- connect defaultConnectInfo { connectDatabase = "scratch"}
runQuery conn $ proc () ->
do
user@User {name = pgName} <- queryTable userTable -< ()
restrict -< (pgName .== (pgStrictText "John"))
returnA -< user
main :: IO ()
main = do
rows <- getUserRows
putStrLn $ show rows
-- Output
-- [User {id = UserId 1, name = "John", email = "john@mail.com"},User {id = UserId
-- 2, name = "Bob", email = "bob@mail.com"},User {id = UserId 3, name = "Alice",
-- email = "alice@mail.com"}]
| meditans/haskell-webapps | doc/docs/opaleye/code/opaleye-select-with-records-and-restrict.hs | Haskell | mit | 1,804 |
"use strict";
devdiv.directive('devDiv', [function () {
return {
restrict: 'E',
link: function (scope, iElement, iAttrs) {
iElement.addClass("dev-div");
iElement.addClass("row");
}
};
}])
devdiv.controller('NameCtrl', function ($scope, $watch) {
}); | abdurrahmanekr/devdiv | src/directive/devdiv.js | JavaScript | mit | 267 |
(function() {
'use strict';
/* Filters */
var md5 = function (s) {
if (!s) return '';
function L(k, d) {
return (k << d) | (k >>> (32 - d));
}
function K(G, k) {
var I, d, F, H, x;
F = (G & 2147483648);
H = (k & 2147483648);
I = (G & 1073741824);
d = (k & 1073741824);
x = (G & 1073741823) + (k & 1073741823);
if (I & d) {
return (x ^ 2147483648 ^ F ^ H);
}
if (I | d) {
if (x & 1073741824) {
return (x ^ 3221225472 ^ F ^ H);
} else {
return (x ^ 1073741824 ^ F ^ H);
}
} else {
return (x ^ F ^ H);
}
}
function r(d, F, k) {
return (d & F) | ((~d) & k);
}
function q(d, F, k) {
return (d & k) | (F & (~k));
}
function p(d, F, k) {
return (d ^ F ^ k);
}
function n(d, F, k) {
return (F ^ (d | (~k)));
}
function u(G, F, aa, Z, k, H, I) {
G = K(G, K(K(r(F, aa, Z), k), I));
return K(L(G, H), F);
}
function f(G, F, aa, Z, k, H, I) {
G = K(G, K(K(q(F, aa, Z), k), I));
return K(L(G, H), F);
}
function D(G, F, aa, Z, k, H, I) {
G = K(G, K(K(p(F, aa, Z), k), I));
return K(L(G, H), F);
}
function t(G, F, aa, Z, k, H, I) {
G = K(G, K(K(n(F, aa, Z), k), I));
return K(L(G, H), F);
}
function e(G) {
var Z;
var F = G.length;
var x = F + 8;
var k = (x - (x % 64)) / 64;
var I = (k + 1) * 16;
var aa = Array(I - 1);
var d = 0;
var H = 0;
while (H < F) {
Z = (H - (H % 4)) / 4;
d = (H % 4) * 8;
aa[Z] = (aa[Z] | (G.charCodeAt(H) << d));
H++;
}
Z = (H - (H % 4)) / 4;
d = (H % 4) * 8;
aa[Z] = aa[Z] | (128 << d);
aa[I - 2] = F << 3;
aa[I - 1] = F >>> 29;
return aa;
}
function B(x) {
var k = "",
F = "",
G, d;
for (d = 0; d <= 3; d++) {
G = (x >>> (d * 8)) & 255;
F = "0" + G.toString(16);
k = k + F.substr(F.length - 2, 2);
}
return k;
}
function J(k) {
k = k.replace(/rn/g, "n");
var d = "";
for (var F = 0; F < k.length; F++) {
var x = k.charCodeAt(F);
if (x < 128) {
d += String.fromCharCode(x);
} else {
if ((x > 127) && (x < 2048)) {
d += String.fromCharCode((x >> 6) | 192);
d += String.fromCharCode((x & 63) | 128);
} else {
d += String.fromCharCode((x >> 12) | 224);
d += String.fromCharCode(((x >> 6) & 63) | 128);
d += String.fromCharCode((x & 63) | 128);
}
}
}
return d;
}
var C = [];
var P, h, E, v, g, Y, X, W, V;
var S = 7,
Q = 12,
N = 17,
M = 22;
var A = 5,
z = 9,
y = 14,
w = 20;
var o = 4,
m = 11,
l = 16,
j = 23;
var U = 6,
T = 10,
R = 15,
O = 21;
s = J(s);
C = e(s);
Y = 1732584193;
X = 4023233417;
W = 2562383102;
V = 271733878;
for (P = 0; P < C.length; P += 16) {
h = Y;
E = X;
v = W;
g = V;
Y = u(Y, X, W, V, C[P + 0], S, 3614090360);
V = u(V, Y, X, W, C[P + 1], Q, 3905402710);
W = u(W, V, Y, X, C[P + 2], N, 606105819);
X = u(X, W, V, Y, C[P + 3], M, 3250441966);
Y = u(Y, X, W, V, C[P + 4], S, 4118548399);
V = u(V, Y, X, W, C[P + 5], Q, 1200080426);
W = u(W, V, Y, X, C[P + 6], N, 2821735955);
X = u(X, W, V, Y, C[P + 7], M, 4249261313);
Y = u(Y, X, W, V, C[P + 8], S, 1770035416);
V = u(V, Y, X, W, C[P + 9], Q, 2336552879);
W = u(W, V, Y, X, C[P + 10], N, 4294925233);
X = u(X, W, V, Y, C[P + 11], M, 2304563134);
Y = u(Y, X, W, V, C[P + 12], S, 1804603682);
V = u(V, Y, X, W, C[P + 13], Q, 4254626195);
W = u(W, V, Y, X, C[P + 14], N, 2792965006);
X = u(X, W, V, Y, C[P + 15], M, 1236535329);
Y = f(Y, X, W, V, C[P + 1], A, 4129170786);
V = f(V, Y, X, W, C[P + 6], z, 3225465664);
W = f(W, V, Y, X, C[P + 11], y, 643717713);
X = f(X, W, V, Y, C[P + 0], w, 3921069994);
Y = f(Y, X, W, V, C[P + 5], A, 3593408605);
V = f(V, Y, X, W, C[P + 10], z, 38016083);
W = f(W, V, Y, X, C[P + 15], y, 3634488961);
X = f(X, W, V, Y, C[P + 4], w, 3889429448);
Y = f(Y, X, W, V, C[P + 9], A, 568446438);
V = f(V, Y, X, W, C[P + 14], z, 3275163606);
W = f(W, V, Y, X, C[P + 3], y, 4107603335);
X = f(X, W, V, Y, C[P + 8], w, 1163531501);
Y = f(Y, X, W, V, C[P + 13], A, 2850285829);
V = f(V, Y, X, W, C[P + 2], z, 4243563512);
W = f(W, V, Y, X, C[P + 7], y, 1735328473);
X = f(X, W, V, Y, C[P + 12], w, 2368359562);
Y = D(Y, X, W, V, C[P + 5], o, 4294588738);
V = D(V, Y, X, W, C[P + 8], m, 2272392833);
W = D(W, V, Y, X, C[P + 11], l, 1839030562);
X = D(X, W, V, Y, C[P + 14], j, 4259657740);
Y = D(Y, X, W, V, C[P + 1], o, 2763975236);
V = D(V, Y, X, W, C[P + 4], m, 1272893353);
W = D(W, V, Y, X, C[P + 7], l, 4139469664);
X = D(X, W, V, Y, C[P + 10], j, 3200236656);
Y = D(Y, X, W, V, C[P + 13], o, 681279174);
V = D(V, Y, X, W, C[P + 0], m, 3936430074);
W = D(W, V, Y, X, C[P + 3], l, 3572445317);
X = D(X, W, V, Y, C[P + 6], j, 76029189);
Y = D(Y, X, W, V, C[P + 9], o, 3654602809);
V = D(V, Y, X, W, C[P + 12], m, 3873151461);
W = D(W, V, Y, X, C[P + 15], l, 530742520);
X = D(X, W, V, Y, C[P + 2], j, 3299628645);
Y = t(Y, X, W, V, C[P + 0], U, 4096336452);
V = t(V, Y, X, W, C[P + 7], T, 1126891415);
W = t(W, V, Y, X, C[P + 14], R, 2878612391);
X = t(X, W, V, Y, C[P + 5], O, 4237533241);
Y = t(Y, X, W, V, C[P + 12], U, 1700485571);
V = t(V, Y, X, W, C[P + 3], T, 2399980690);
W = t(W, V, Y, X, C[P + 10], R, 4293915773);
X = t(X, W, V, Y, C[P + 1], O, 2240044497);
Y = t(Y, X, W, V, C[P + 8], U, 1873313359);
V = t(V, Y, X, W, C[P + 15], T, 4264355552);
W = t(W, V, Y, X, C[P + 6], R, 2734768916);
X = t(X, W, V, Y, C[P + 13], O, 1309151649);
Y = t(Y, X, W, V, C[P + 4], U, 4149444226);
V = t(V, Y, X, W, C[P + 11], T, 3174756917);
W = t(W, V, Y, X, C[P + 2], R, 718787259);
X = t(X, W, V, Y, C[P + 9], O, 3951481745);
Y = K(Y, h);
X = K(X, E);
W = K(W, v);
V = K(V, g);
}
var i = B(Y) + B(X) + B(W) + B(V);
return i.toLowerCase();
};
angular.module('talis.filters.md5', []).
filter("md5", function(){
return md5;
});
}).call(this);
| chariotsolutions/reactive-quizzo-code-sample | public/moderator/bower_components/md5-angular-filter/js/md5.filter.js | JavaScript | mit | 6,722 |
#!/usr/bin/env python
#
# GrovePi Example for using the Grove Electricity Sensor (http://www.seeedstudio.com/wiki/Grove_-_Electricity_Sensor)
#
# The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
#
# Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
#
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2015 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
import time
import grovepi
# Connect the Grove Electricity Sensor to analog port A0
# SIG,NC,NC,GND
sensor = 0
grovepi.pinMode(sensor,"INPUT")
# Vcc of the grove interface is normally 5v
grove_vcc = 5
while True:
try:
# Get sensor value
sensor_value = grovepi.analogRead(sensor)
# Calculate amplitude current (mA)
amplitude_current = (float)(sensor_value / 1024 * grove_vcc / 800 * 2000000)
# Calculate effective value (mA)
effective_value = amplitude_current / 1.414
# minimum_current = 1 / 1024 * grove_vcc / 800 * 2000000 / 1.414 = 8.6(mA)
# Only for sinusoidal alternating current
print("sensor_value", sensor_value)
print("The amplitude of the current is", amplitude_current, "mA")
print("The effective value of the current is", effective_value, "mA")
time.sleep(1)
except IOError:
print ("Error")
| karan259/GrovePi | Software/Python/grove_electricity_sensor.py | Python | mit | 2,530 |
// Copyright (c) 2015 ZZZ Projects. All rights reserved
// Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
// Website: http://www.zzzprojects.com/
// Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
// All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library
using System;
using System.IO;
public static partial class Extensions
{
/// <summary>
/// Changes the extension of a @this string.
/// </summary>
/// <param name="this">
/// The @this information to modify. The @this cannot contain any of the characters defined in
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .
/// </param>
/// <param name="extension">
/// The new extension (with or without a leading period). Specify null to remove an existing
/// extension from
/// <paramref
/// name="this" />
/// .
/// </param>
/// <returns>
/// The modified @this information.On Windows-based desktop platforms, if <paramref name="this" /> is null or an
/// empty string (""), the @this information is returned unmodified. If
/// <paramref
/// name="extension" />
/// is null, the returned string contains the specified @this with its extension removed. If
/// <paramref
/// name="this" />
/// has no extension, and <paramref name="extension" /> is not null, the returned @this string contains
/// <paramref
/// name="extension" />
/// appended to the end of <paramref name="this" />.
/// </returns>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this" /> contains one or more of the invalid
/// characters defined in
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .
/// </exception>
public static String ChangeExtension(this FileInfo @this, String extension)
{
return Path.ChangeExtension(@this.FullName, extension);
}
} | mario-loza/Z.ExtensionMethods | src/Z.IO/System.IO.FileInfo/FileInfo.ChangeExtension.cs | C# | mit | 2,160 |
require 'openssl'
require_relative 'app'
module Spaceship
module Portal
# Represents a certificate from the Apple Developer Portal.
#
# This can either be a code signing identity or a push profile
class Certificate < PortalBase
# @return (String) The ID given from the developer portal. You'll probably not need it.
# @example
# "P577TH3PAA"
attr_accessor :id
# @return (String) The name of the certificate
# @example Company
# "SunApps GmbH"
# @example Push Profile
# "Apple Push Services"
attr_accessor :name
# @return (String) Status of the certificate
# @example
# "Issued"
attr_accessor :status
# @return (Date) The date and time when the certificate was created
# @example
# 2015-04-01 21:24:00 UTC
attr_accessor :created
# @return (Date) The date and time when the certificate will expire
# @example
# 2016-04-01 21:24:00 UTC
attr_accessor :expires
# @return (String) The owner type that defines if it's a push profile
# or a code signing identity
#
# @example Code Signing Identity
# "team"
# @example Push Certificate
# "bundle"
attr_accessor :owner_type
# @return (String) The name of the owner
#
# @example Code Signing Identity (usually the company name)
# "SunApps Gmbh"
# @example Push Certificate (the bundle identifier)
# "tools.fastlane.app"
attr_accessor :owner_name
# @return (String) The ID of the owner, that can be used to
# fetch more information
# @example
# "75B83SPLAA"
attr_accessor :owner_id
# Indicates the type of this certificate
# which is automatically used to determine the class of
# the certificate. Available values listed in CERTIFICATE_TYPE_IDS
# @return (String) The type of the certificate
# @example Production Certificate
# "R58UK2EWSO"
# @example Development Certificate
# "5QPB9NHCEI"
attr_accessor :type_display_id
# @return (Bool) Whether or not the certificate can be downloaded
attr_accessor :can_download
attr_mapping({
'certificateId' => :id,
'name' => :name,
'statusString' => :status,
'dateCreated' => :created,
'expirationDate' => :expires,
'ownerType' => :owner_type,
'ownerName' => :owner_name,
'ownerId' => :owner_id,
'certificateTypeDisplayId' => :type_display_id,
'canDownload' => :can_download
})
#####################################################
# Certs are not associated with apps
#####################################################
# A development code signing certificate used for development environment
class Development < Certificate; end
# A production code signing certificate used for distribution environment
class Production < Certificate; end
# An In House code signing certificate used for enterprise distributions
class InHouse < Certificate; end
# A Mac development code signing certificate used for development environment
class MacDevelopment < Certificate; end
# A Mac production code signing certificate for building .app bundles
class MacAppDistribution < Certificate; end
# A Mac production code signing certificate for building .pkg installers
class MacInstallerDistribution < Certificate; end
# A Mac Developer ID signing certificate for building .app bundles
class DeveloperIDApplication < Certificate; end
# A Mac Developer ID signing certificate for building .pkg installers
class DeveloperIDInstaller < Certificate; end
#####################################################
# Certs that are specific for one app
#####################################################
# Abstract class for push certificates. Check out the subclasses
# DevelopmentPush, ProductionPush, WebsitePush and VoipPush
class PushCertificate < Certificate; end
# A push notification certificate for development environment
class DevelopmentPush < PushCertificate; end
# A push notification certificate for production environment
class ProductionPush < PushCertificate; end
# A push notification certificate for websites
class WebsitePush < PushCertificate; end
# A push notification certificate for the VOIP environment
class VoipPush < PushCertificate; end
# Passbook certificate
class Passbook < Certificate; end
# ApplePay certificate
class ApplePay < Certificate; end
# A Mac push notification certificate for development environment
class MacDevelopmentPush < PushCertificate; end
# A Mac push notification certificate for production environment
class MacProductionPush < PushCertificate; end
IOS_CERTIFICATE_TYPE_IDS = {
"5QPB9NHCEI" => Development,
"R58UK2EWSO" => Production,
"9RQEK7MSXA" => InHouse,
"LA30L5BJEU" => Certificate,
"BKLRAVXMGM" => DevelopmentPush,
"UPV3DW712I" => ProductionPush,
"Y3B2F3TYSI" => Passbook,
"3T2ZP62QW8" => WebsitePush,
"E5D663CMZW" => VoipPush,
"4APLUP237T" => ApplePay
}
OLDER_IOS_CERTIFICATE_TYPES = [
# those are also sent by the browser, but not sure what they represent
"T44PTHVNID",
"DZQUP8189Y",
"FGQUP4785Z",
"S5WE21TULA",
"3BQKVH9I2X", # ProductionPush,
"FUOY7LWJET"
]
MAC_CERTIFICATE_TYPE_IDS = {
"749Y1QAGU7" => MacDevelopment,
"HXZEUKP0FP" => MacAppDistribution,
"2PQI8IDXNH" => MacInstallerDistribution,
"OYVN2GW35E" => DeveloperIDInstaller,
"W0EURJRMC5" => DeveloperIDApplication,
"CDZ7EMXIZ1" => MacProductionPush,
"HQ4KP3I34R" => MacDevelopmentPush,
"DIVN2GW3XT" => DeveloperIDApplication
}
CERTIFICATE_TYPE_IDS = IOS_CERTIFICATE_TYPE_IDS.merge(MAC_CERTIFICATE_TYPE_IDS)
# Class methods
class << self
# Create a new code signing request that can be used to
# generate a new certificate
# @example
# Create a new certificate signing request
# csr, pkey = Spaceship.certificate.create_certificate_signing_request
#
# # Use the signing request to create a new distribution certificate
# Spaceship.certificate.production.create!(csr: csr)
def create_certificate_signing_request
key = OpenSSL::PKey::RSA.new(2048)
csr = OpenSSL::X509::Request.new
csr.version = 0
csr.subject = OpenSSL::X509::Name.new([
['CN', 'PEM', OpenSSL::ASN1::UTF8STRING]
])
csr.public_key = key.public_key
csr.sign(key, OpenSSL::Digest::SHA1.new)
return [csr, key]
end
# Create a new object based on a hash.
# This is used to create a new object based on the server response.
def factory(attrs)
# Example:
# => {"name"=>"iOS Distribution: SunApps GmbH",
# "certificateId"=>"XC5PH8DAAA",
# "serialNumber"=>"797E732CCE8B7AAA",
# "status"=>"Issued",
# "statusCode"=>0,
# "expirationDate"=>#<DateTime: 2015-11-25T22:45:50+00:00 ((2457352j,81950s,0n),+0s,2299161j)>,
# "certificatePlatform"=>"ios",
# "certificateType"=>
# {"certificateTypeDisplayId"=>"R58UK2EAAA",
# "name"=>"iOS Distribution",
# "platform"=>"ios",
# "permissionType"=>"distribution",
# "distributionType"=>"store",
# "distributionMethod"=>"app",
# "ownerType"=>"team",
# "daysOverlap"=>364,
# "maxActive"=>2}}
if attrs['certificateType']
# On some accounts this is nested, so we need to flatten it
attrs.merge!(attrs['certificateType'])
attrs.delete('certificateType')
end
# Parse the dates
# rubocop:disable Style/RescueModifier
attrs['expirationDate'] = (Time.parse(attrs['expirationDate']) rescue attrs['expirationDate'])
attrs['dateCreated'] = (Time.parse(attrs['dateCreated']) rescue attrs['dateCreated'])
# rubocop:enable Style/RescueModifier
# Here we go
klass = CERTIFICATE_TYPE_IDS[attrs['certificateTypeDisplayId']]
klass ||= Certificate
klass.client = @client
klass.new(attrs)
end
# @param mac [Bool] Fetches Mac certificates if true. (Ignored if callsed from a subclass)
# @return (Array) Returns all certificates of this account.
# If this is called from a subclass of Certificate, this will
# only include certificates matching the current type.
def all(mac: false)
if self == Certificate # are we the base-class?
type_ids = mac ? MAC_CERTIFICATE_TYPE_IDS : IOS_CERTIFICATE_TYPE_IDS
types = type_ids.keys
types += OLDER_IOS_CERTIFICATE_TYPES unless mac
else
types = [CERTIFICATE_TYPE_IDS.key(self)]
mac = MAC_CERTIFICATE_TYPE_IDS.values.include?(self)
end
client.certificates(types, mac: mac).map do |cert|
factory(cert)
end
end
# @param mac [Bool] Searches Mac certificates if true
# @return (Certificate) Find a certificate based on the ID of the certificate.
def find(certificate_id, mac: false)
all(mac: mac).find do |c|
c.id == certificate_id
end
end
# Generate a new certificate based on a code certificate signing request
# @param csr (OpenSSL::X509::Request) (required): The certificate signing request to use. Get one using
# `create_certificate_signing_request`
# @param bundle_id (String) (optional): The app identifier this certificate is for.
# This value is only needed if you create a push profile. For normal code signing
# certificates, you must only pass a certificate signing request.
# @example
# # Create a new certificate signing request
# csr, pkey = Spaceship::Certificate.create_certificate_signing_request
#
# # Use the signing request to create a new distribution certificate
# Spaceship::Certificate::Production.create!(csr: csr)
# @return (Certificate): The newly created certificate
def create!(csr: nil, bundle_id: nil)
type = CERTIFICATE_TYPE_IDS.key(self)
mac = MAC_CERTIFICATE_TYPE_IDS.include?(type)
# look up the app_id by the bundle_id
if bundle_id
app = Spaceship::Portal::App.set_client(client).find(bundle_id)
raise "Could not find app with bundle id '#{bundle_id}'" unless app
app_id = app.app_id
end
# ensure csr is a OpenSSL::X509::Request
csr = OpenSSL::X509::Request.new(csr) if csr.kind_of?(String)
# if this succeeds, we need to save the .cer and the private key in keychain access or wherever they go in linux
response = client.create_certificate!(type, csr.to_pem, app_id, mac)
# munge the response to make it work for the factory
response['certificateTypeDisplayId'] = response['certificateType']['certificateTypeDisplayId']
self.new(response)
end
end
# instance methods
# @return (String) Download the raw data of the certificate without parsing
def download_raw
client.download_certificate(id, type_display_id, mac: mac?)
end
# @return (OpenSSL::X509::Certificate) Downloads and parses the certificate
def download
OpenSSL::X509::Certificate.new(download_raw)
end
# Revoke the certificate. You shouldn't use this method probably.
def revoke!
client.revoke_certificate!(id, type_display_id, mac: mac?)
end
# @return (Bool): Is this certificate a push profile for apps?
def is_push?
self.kind_of?(PushCertificate)
end
# @return (Bool) Is this a Mac profile?
def mac?
MAC_CERTIFICATE_TYPE_IDS.include?(type_display_id)
end
end
end
end
| orta/fastlane | spaceship/lib/spaceship/portal/certificate.rb | Ruby | mit | 12,581 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ConsoleApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConsoleApplication1")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1be8ecdc-8f75-490d-ba5b-1dc456c19a6c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| MilStancheva/Telerik-Academy-Projects | C# Fundamentals/OperatorsAndExpressions/11. 3rd Bit/Properties/AssemblyInfo.cs | C# | mit | 1,414 |
/*globals describe, before, beforeEach, afterEach, it */
/*jshint expr:true*/
var testUtils = require('../../utils'),
should = require('should'),
// Stuff we are testing
dbAPI = require('../../../server/api/db'),
ModelTag = require('../../../server/models/tag'),
ModelPost = require('../../../server/models/post');
describe('DB API', function () {
// Keep the DB clean
before(testUtils.teardown);
afterEach(testUtils.teardown);
beforeEach(testUtils.setup('users:roles', 'posts', 'perms:db', 'perms:init'));
should.exist(dbAPI);
it('delete all content (owner)', function (done) {
return dbAPI.deleteAllContent(testUtils.context.owner).then(function (result) {
should.exist(result.db);
result.db.should.be.instanceof(Array);
result.db.should.be.empty;
}).then(function () {
return ModelTag.Tag.findAll(testUtils.context.owner).then(function (results) {
should.exist(results);
results.length.should.equal(0);
});
}).then(function () {
return ModelPost.Post.findAll(testUtils.context.owner).then(function (results) {
should.exist(results);
results.length.should.equal(0);
done();
});
}).catch(done);
});
it('delete all content (admin)', function (done) {
return dbAPI.deleteAllContent(testUtils.context.admin).then(function (result) {
should.exist(result.db);
result.db.should.be.instanceof(Array);
result.db.should.be.empty;
}).then(function () {
return ModelTag.Tag.findAll(testUtils.context.admin).then(function (results) {
should.exist(results);
results.length.should.equal(0);
});
}).then(function () {
return ModelPost.Post.findAll(testUtils.context.admin).then(function (results) {
should.exist(results);
results.length.should.equal(0);
done();
});
}).catch(done);
});
it('delete all content is denied (editor & author)', function (done) {
return dbAPI.deleteAllContent(testUtils.context.editor).then(function () {
done(new Error('Delete all content is not denied for editor.'));
}, function (error) {
error.type.should.eql('NoPermissionError');
return dbAPI.deleteAllContent(testUtils.context.author);
}).then(function () {
done(new Error('Delete all content is not denied for author.'));
}, function (error) {
error.type.should.eql('NoPermissionError');
return dbAPI.deleteAllContent();
}).then(function () {
done(new Error('Delete all content is not denied without authentication.'));
}).catch(function (error) {
error.type.should.eql('NoPermissionError');
done();
}).catch(done);
});
it('export content is denied (editor & author)', function (done) {
return dbAPI.exportContent(testUtils.context.editor).then(function () {
done(new Error('Export content is not denied for editor.'));
}, function (error) {
error.type.should.eql('NoPermissionError');
return dbAPI.exportContent(testUtils.context.author);
}).then(function () {
done(new Error('Export content is not denied for author.'));
}, function (error) {
error.type.should.eql('NoPermissionError');
return dbAPI.exportContent();
}).then(function () {
done(new Error('Export content is not denied without authentication.'));
}).catch(function (error) {
error.type.should.eql('NoPermissionError');
done();
}).catch(done);
});
it('import content is denied (editor & author)', function (done) {
return dbAPI.importContent(testUtils.context.editor).then(function () {
done(new Error('Import content is not denied for editor.'));
}, function (error) {
error.type.should.eql('NoPermissionError');
return dbAPI.importContent(testUtils.context.author);
}).then(function () {
done(new Error('Import content is not denied for author.'));
}, function (error) {
error.type.should.eql('NoPermissionError');
return dbAPI.importContent();
}).then(function () {
done(new Error('Import content is not denied without authentication.'));
}).catch(function (error) {
error.type.should.eql('NoPermissionError');
done();
}).catch(done);
});
}); | dbanda/dalitsobanda.com | ghostgithub/core/test/integration/api/api_db_spec.js | JavaScript | mit | 4,779 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Struct template reverse_fold_tree</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../proto/reference.html#header.boost.proto.transform.fold_tree_hpp" title="Header <boost/proto/transform/fold_tree.hpp>">
<link rel="prev" href="fold_tree/impl.html" title="Struct template impl">
<link rel="next" href="reverse_fold_tree/impl.html" title="Struct template impl">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="fold_tree/impl.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../proto/reference.html#header.boost.proto.transform.fold_tree_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="reverse_fold_tree/impl.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.proto.reverse_fold_tree"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template reverse_fold_tree</span></h2>
<p>boost::proto::reverse_fold_tree — A <a class="link" href="../../PrimitiveTransform.html" title="Concept PrimitiveTransform">PrimitiveTransform</a> that recursively applies the
<code class="computeroutput"><a class="link" href="reverse_fold.html" title="Struct template reverse_fold">proto::reverse_fold<></a></code> transform to
sub-trees that all share a common tag type.</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../proto/reference.html#header.boost.proto.transform.fold_tree_hpp" title="Header <boost/proto/transform/fold_tree.hpp>">boost/proto/transform/fold_tree.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Sequence<span class="special">,</span> <span class="keyword">typename</span> State0<span class="special">,</span> <span class="keyword">typename</span> Fun<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="reverse_fold_tree.html" title="Struct template reverse_fold_tree">reverse_fold_tree</a> <span class="special">:</span>
<span class="keyword"></span> <a class="link" href="transform.html" title="Struct template transform">proto::transform</a><span class="special"><</span> <span class="identifier">reverse_fold_tree</span><span class="special"><</span><span class="identifier">Sequence</span><span class="special">,</span> <span class="identifier">State0</span><span class="special">,</span> <span class="identifier">Fun</span><span class="special">></span> <span class="special">></span>
<span class="special">{</span>
<span class="comment">// member classes/structs/unions</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> <a class="link" href="../../Expr.html" title="Concept Expr">Expr</a><span class="special">,</span> <span class="keyword">typename</span> State<span class="special">,</span> <span class="keyword">typename</span> Data<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="reverse_fold_tree/impl.html" title="Struct template impl">impl</a> <span class="special">:</span> <span class="keyword"></span>
<a class="link" href="reverse_fold.html" title="Struct template reverse_fold">proto::reverse_fold</a><span class="special"><</span><span class="identifier">Sequence</span><span class="special">,</span> <span class="identifier">State0</span><span class="special">,</span> <span class="identifier">recurse_if_</span><span class="special"><</span><span class="keyword">typename</span> <span class="identifier">Expr</span><span class="special">::</span><span class="identifier">proto_tag</span><span class="special">,</span> <span class="identifier">Fun</span><span class="special">></span> <span class="special">></span>
<span class="special">::</span><span class="keyword">template</span> <span class="identifier">impl</span><span class="special"><</span><span class="identifier">Expr</span><span class="special">,</span> <span class="identifier">State</span><span class="special">,</span> <span class="identifier">Data</span><span class="special">></span>
<span class="special">{</span>
<span class="special">}</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="id-1.3.34.5.48.5.4"></a><h2>Description</h2>
<p>
<code class="computeroutput">proto::reverse_fold_tree<></code> is useful for flattening trees
into lists; for example, you might use <code class="computeroutput">proto::reverse_fold_tree<></code>
to flatten an expression tree like <code class="computeroutput">a | b | c</code> into a Fusion list like
<code class="computeroutput">cons(a, cons(b, cons(c)))</code>.
</p>
<p>
<code class="computeroutput">proto::reverse_fold_tree<></code> is easily understood in terms of
a <code class="computeroutput">recurse_if_<></code> helper, defined as follows:
</p>
<pre class="programlisting"> <span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> <span class="identifier">Tag</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">Fun</span><span class="special">></span>
<span class="keyword">struct</span> <span class="identifier">recurse_if_</span> <span class="special">:</span>
<a class="link" href="if_.html" title="Struct template if_">proto::if_</a><span class="special"><</span>
<span class="comment">// If the current node has type type "Tag" ...</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">is_same</span><span class="special"><</span><a class="link" href="tag_of.html" title="Struct template tag_of">proto::tag_of</a><span class="special"><</span><a class="link" href="_.html" title="Struct _">proto::_</a><span class="special">></span><span class="special">,</span> <span class="identifier">Tag</span><span class="special">></span><span class="special">(</span><span class="special">)</span><span class="special">,</span>
<span class="comment">// ... recurse, otherwise ...</span>
<a class="link" href="reverse_fold.html" title="Struct template reverse_fold">proto::reverse_fold</a><span class="special"><</span><a class="link" href="_.html" title="Struct _">proto::_</a><span class="special">,</span> <a class="link" href="_state.html" title="Struct _state">proto::_state</a><span class="special">,</span> <span class="identifier">recurse_if_</span><span class="special"><</span><span class="identifier">Tag</span><span class="special">,</span> <span class="identifier">Fun</span><span class="special">></span> <span class="special">></span><span class="special">,</span>
<span class="comment">// ... apply the Fun transform.</span>
<span class="identifier">Fun</span>
<span class="special">></span>
<span class="special">{</span><span class="special">}</span><span class="special">;</span></pre>
<p>
</p>
<p>
With <code class="computeroutput">recurse_if_<></code> as defined above,
<code class="computeroutput">proto::reverse_fold_tree<Sequence, State0, Fun>()(expr, state, data)</code>
is equivalent to:
</p>
<pre class="programlisting"><a class="link" href="reverse_fold.html" title="Struct template reverse_fold">proto::reverse_fold</a><span class="special"><</span>
<span class="identifier">Sequence</span><span class="special">,</span>
<span class="identifier">State0</span><span class="special">,</span>
<span class="identifier">recurse_if_</span><span class="special"><</span><span class="keyword">typename</span> <span class="identifier">Expr</span><span class="special">::</span><span class="identifier">proto_tag</span><span class="special">,</span> <span class="identifier">Fun</span><span class="special">></span>
<span class="special">></span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="identifier">expr</span><span class="special">,</span> <span class="identifier">state</span><span class="special">,</span> <span class="identifier">data</span><span class="special">)</span><span class="special">.</span></pre>
<p>
It has the effect of folding a tree back-to-front, recursing into child nodes that share a
tag type with the parent node.
</p>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2008 Eric Niebler<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="fold_tree/impl.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../proto/reference.html#header.boost.proto.transform.fold_tree_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="reverse_fold_tree/impl.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| davehorton/drachtio-server | deps/boost_1_77_0/doc/html/boost/proto/reverse_fold_tree.html | HTML | mit | 11,042 |
<?php defined('BASEPATH') OR exit('No direct script access allowed.');
$config['useragent'] = 'PHPMailer'; // Mail engine switcher: 'CodeIgniter' or 'PHPMailer'
$config['protocol'] = IS_WINDOWS_OS ? 'smtp' : 'mail'; // 'mail', 'sendmail', or 'smtp'
$config['mailpath'] = '/usr/sbin/sendmail';
$config['smtp_host'] = 'localhost';
$config['smtp_user'] = '';
$config['smtp_pass'] = '';
$config['smtp_port'] = 25;
$config['smtp_timeout'] = 30; // (in seconds)
$config['smtp_crypto'] = ''; // '' or 'tls' or 'ssl'
$config['smtp_debug'] = 0; // PHPMailer's SMTP debug info level: 0 = off, 1 = commands, 2 = commands and data, 3 = as 2 plus connection status, 4 = low level data output.
$config['debug_output'] = ''; // PHPMailer's SMTP debug output: 'html', 'echo', 'error_log' or user defined function with parameter $str and $level. NULL or '' means 'echo' on CLI, 'html' otherwise.
$config['smtp_auto_tls'] = true; // Whether to enable TLS encryption automatically if a server supports it, even if `smtp_crypto` is not set to 'tls'.
$config['smtp_conn_options'] = array(); // SMTP connection options, an array passed to the function stream_context_create() when connecting via SMTP.
$config['wordwrap'] = true;
$config['wrapchars'] = 76;
$config['mailtype'] = 'html'; // 'text' or 'html'
$config['charset'] = null; // 'UTF-8', 'ISO-8859-15', ...; NULL (preferable) means config_item('charset'), i.e. the character set of the site.
$config['validate'] = true;
$config['priority'] = 3; // 1, 2, 3, 4, 5; on PHPMailer useragent NULL is a possible option, it means that X-priority header is not set at all, see https://github.com/PHPMailer/PHPMailer/issues/449
$config['crlf'] = "\n"; // "\r\n" or "\n" or "\r"
$config['newline'] = "\n"; // "\r\n" or "\n" or "\r"
$config['bcc_batch_mode'] = false;
$config['bcc_batch_size'] = 200;
$config['encoding'] = '8bit'; // The body encoding. For CodeIgniter: '8bit' or '7bit'. For PHPMailer: '8bit', '7bit', 'binary', 'base64', or 'quoted-printable'.
// DKIM Signing
// See https://yomotherboard.com/how-to-setup-email-server-dkim-keys/
// See http://stackoverflow.com/questions/24463425/send-mail-in-phpmailer-using-dkim-keys
// See https://github.com/PHPMailer/PHPMailer/blob/v5.2.14/test/phpmailerTest.php#L1708
$config['dkim_domain'] = ''; // DKIM signing domain name, for exmple 'example.com'.
$config['dkim_private'] = ''; // DKIM private key, set as a file path.
$config['dkim_private_string'] = ''; // DKIM private key, set directly from a string.
$config['dkim_selector'] = ''; // DKIM selector.
$config['dkim_passphrase'] = ''; // DKIM passphrase, used if your key is encrypted.
$config['dkim_identity'] = ''; // DKIM Identity, usually the email address used as the source of the email.
// An example for a Gmail Account:
/*
$config['useragent'] = 'PHPMailer';
$config['protocol'] = 'smtp';
$config['mailpath'] = '/usr/sbin/sendmail';
$config['smtp_host'] = 'smtp.gmail.com';
$config['smtp_user'] = 'yourusername@gmail.com';
$config['smtp_pass'] = 'yourpassword';
$config['smtp_port'] = 587;
$config['smtp_timeout'] = 30;
$config['smtp_crypto'] = 'tls';
$config['smtp_debug'] = 0;
$config['debug_output'] = '';
$config['smtp_auto_tls'] = false;
$config['smtp_conn_options'] = array();
$config['wordwrap'] = true;
$config['wrapchars'] = 76;
$config['mailtype'] = 'html';
$config['charset'] = null;
$config['validate'] = true;
$config['priority'] = 3;
$config['crlf'] = "\n";
$config['newline'] = "\n";
$config['bcc_batch_mode'] = false;
$config['bcc_batch_size'] = 200;
$config['encoding'] = '8bit';
*/
| ivantcholakov/starter-public-edition-4 | platform/common/config/email.php | PHP | mit | 4,261 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/css!./glyphMargin';
import { DynamicViewOverlay } from 'vs/editor/browser/view/dynamicViewOverlay';
import { ViewContext } from 'vs/editor/common/view/viewContext';
import { RenderingContext } from 'vs/editor/common/view/renderingContext';
import * as viewEvents from 'vs/editor/common/view/viewEvents';
import { editorBackground } from 'vs/platform/theme/common/colorRegistry';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
export class DecorationToRender {
_decorationToRenderBrand: void;
public startLineNumber: number;
public endLineNumber: number;
public className: string;
constructor(startLineNumber: number, endLineNumber: number, className: string) {
this.startLineNumber = +startLineNumber;
this.endLineNumber = +endLineNumber;
this.className = String(className);
}
}
export abstract class DedupOverlay extends DynamicViewOverlay {
protected _render(visibleStartLineNumber: number, visibleEndLineNumber: number, decorations: DecorationToRender[]): string[][] {
let output: string[][] = [];
for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
let lineIndex = lineNumber - visibleStartLineNumber;
output[lineIndex] = [];
}
if (decorations.length === 0) {
return output;
}
decorations.sort((a, b) => {
if (a.className === b.className) {
if (a.startLineNumber === b.startLineNumber) {
return a.endLineNumber - b.endLineNumber;
}
return a.startLineNumber - b.startLineNumber;
}
return (a.className < b.className ? -1 : 1);
});
let prevClassName: string = null;
let prevEndLineIndex = 0;
for (let i = 0, len = decorations.length; i < len; i++) {
let d = decorations[i];
let className = d.className;
let startLineIndex = Math.max(d.startLineNumber, visibleStartLineNumber) - visibleStartLineNumber;
let endLineIndex = Math.min(d.endLineNumber, visibleEndLineNumber) - visibleStartLineNumber;
if (prevClassName === className) {
startLineIndex = Math.max(prevEndLineIndex + 1, startLineIndex);
prevEndLineIndex = Math.max(prevEndLineIndex, endLineIndex);
} else {
prevClassName = className;
prevEndLineIndex = endLineIndex;
}
for (let i = startLineIndex; i <= prevEndLineIndex; i++) {
output[i].push(prevClassName);
}
}
return output;
}
}
export class GlyphMarginOverlay extends DedupOverlay {
private _context: ViewContext;
private _lineHeight: number;
private _glyphMargin: boolean;
private _glyphMarginLeft: number;
private _glyphMarginWidth: number;
private _renderResult: string[];
constructor(context: ViewContext) {
super();
this._context = context;
this._lineHeight = this._context.configuration.editor.lineHeight;
this._glyphMargin = this._context.configuration.editor.viewInfo.glyphMargin;
this._glyphMarginLeft = this._context.configuration.editor.layoutInfo.glyphMarginLeft;
this._glyphMarginWidth = this._context.configuration.editor.layoutInfo.glyphMarginWidth;
this._renderResult = null;
this._context.addEventHandler(this);
}
public dispose(): void {
this._context.removeEventHandler(this);
this._context = null;
this._renderResult = null;
}
// --- begin event handlers
public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean {
if (e.lineHeight) {
this._lineHeight = this._context.configuration.editor.lineHeight;
}
if (e.viewInfo.glyphMargin) {
this._glyphMargin = this._context.configuration.editor.viewInfo.glyphMargin;
}
if (e.layoutInfo) {
this._glyphMarginLeft = this._context.configuration.editor.layoutInfo.glyphMarginLeft;
this._glyphMarginWidth = this._context.configuration.editor.layoutInfo.glyphMarginWidth;
}
return true;
}
public onCursorPositionChanged(e: viewEvents.ViewCursorPositionChangedEvent): boolean {
return false;
}
public onCursorSelectionChanged(e: viewEvents.ViewCursorSelectionChangedEvent): boolean {
return false;
}
public onDecorationsChanged(e: viewEvents.ViewDecorationsChangedEvent): boolean {
return true;
}
public onFlushed(e: viewEvents.ViewFlushedEvent): boolean {
return true;
}
public onLinesChanged(e: viewEvents.ViewLinesChangedEvent): boolean {
return true;
}
public onLinesDeleted(e: viewEvents.ViewLinesDeletedEvent): boolean {
return true;
}
public onLinesInserted(e: viewEvents.ViewLinesInsertedEvent): boolean {
return true;
}
public onRevealRangeRequest(e: viewEvents.ViewRevealRangeRequestEvent): boolean {
return false;
}
public onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean {
return e.scrollTopChanged;
}
public onZonesChanged(e: viewEvents.ViewZonesChangedEvent): boolean {
return true;
}
// --- end event handlers
protected _getDecorations(ctx: RenderingContext): DecorationToRender[] {
let decorations = ctx.getDecorationsInViewport();
let r: DecorationToRender[] = [];
for (let i = 0, len = decorations.length; i < len; i++) {
let d = decorations[i];
let glyphMarginClassName = d.source.options.glyphMarginClassName;
if (glyphMarginClassName) {
r.push(new DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, glyphMarginClassName));
}
}
return r;
}
public prepareRender(ctx: RenderingContext): void {
if (!this._glyphMargin) {
this._renderResult = null;
return;
}
let visibleStartLineNumber = ctx.visibleRange.startLineNumber;
let visibleEndLineNumber = ctx.visibleRange.endLineNumber;
let toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
let lineHeight = this._lineHeight.toString();
let left = this._glyphMarginLeft.toString();
let width = this._glyphMarginWidth.toString();
let common = '" style="left:' + left + 'px;width:' + width + 'px' + ';height:' + lineHeight + 'px;"></div>';
let output: string[] = [];
for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
let lineIndex = lineNumber - visibleStartLineNumber;
let classNames = toRender[lineIndex];
if (classNames.length === 0) {
output[lineIndex] = '';
} else {
output[lineIndex] = (
'<div class="cgmr '
+ classNames.join(' ')
+ common
);
}
}
this._renderResult = output;
}
public render(startLineNumber: number, lineNumber: number): string {
if (!this._renderResult) {
return '';
}
let lineIndex = lineNumber - startLineNumber;
if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
throw new Error('Unexpected render request');
}
return this._renderResult[lineIndex];
}
}
registerThemingParticipant((theme, collector) => {
let editorBackgroundColor = theme.getColor(editorBackground);
if (editorBackgroundColor) {
collector.addRule(`.monaco-editor.${theme.selector} .glyph-margin { background-color: ${editorBackgroundColor}; }`);
}
}); | hashhar/vscode | src/vs/editor/browser/viewParts/glyphMargin/glyphMargin.ts | TypeScript | mit | 7,276 |
package net.ontrack.core.security;
import lombok.Data;
import net.ontrack.core.model.AccountSummary;
@Data
public class ProjectAuthorization {
private final int project;
private final AccountSummary account;
private final ProjectRole role;
}
| joansmith/ontrack | ontrack-core/src/main/java/net/ontrack/core/security/ProjectAuthorization.java | Java | mit | 258 |
require 'set'
require 'sprockets/http_utils'
require 'sprockets/path_dependency_utils'
require 'sprockets/uri_utils'
module Sprockets
module Resolve
include HTTPUtils, PathDependencyUtils, URIUtils
# Public: Find Asset URI for given a logical path by searching the
# environment's load paths.
#
# resolve("application.js")
# # => "file:///path/to/app/javascripts/application.js?type=application/javascript"
#
# An accept content type can be given if the logical path doesn't have a
# format extension.
#
# resolve("application", accept: "application/javascript")
# # => "file:///path/to/app/javascripts/application.coffee?type=application/javascript"
#
# The String Asset URI is returned or nil if no results are found.
def resolve(path, load_paths: config[:paths], accept: nil, pipeline: nil, base_path: nil)
paths = load_paths
if valid_asset_uri?(path)
uri, deps = resolve_asset_uri(path)
elsif absolute_path?(path)
filename, type, deps = resolve_absolute_path(paths, path, accept)
elsif relative_path?(path)
filename, type, path_pipeline, deps, index_alias = resolve_relative_path(paths, path, base_path, accept)
else
filename, type, path_pipeline, deps, index_alias = resolve_logical_path(paths, path, accept)
end
if filename
uri = build_asset_uri(filename, type: type, pipeline: pipeline || path_pipeline, index_alias: index_alias)
end
return uri, deps
end
# Public: Same as resolve() but raises a FileNotFound exception instead of
# nil if no assets are found.
def resolve!(path, **kargs)
uri, deps = resolve(path, **kargs)
unless uri
message = "couldn't find file '#{path}'"
if relative_path?(path) && kargs[:base_path]
load_path, _ = paths_split(config[:paths], kargs[:base_path])
message << " under '#{load_path}'"
end
message << " with type '#{kargs[:accept]}'" if kargs[:accept]
raise FileNotFound, message
end
return uri, deps
end
protected
def resolve_asset_uri(uri)
filename, _ = parse_asset_uri(uri)
return uri, Set.new([build_file_digest_uri(filename)])
end
def resolve_absolute_path(paths, filename, accept)
deps = Set.new
filename = File.expand_path(filename)
# Ensure path is under load paths
return nil, nil, deps unless paths_split(paths, filename)
_, mime_type = match_path_extname(filename, config[:mime_exts])
type = resolve_transform_type(mime_type, accept)
return nil, nil, deps if accept && !type
return nil, nil, deps unless file?(filename)
deps << build_file_digest_uri(filename)
return filename, type, deps
end
def resolve_relative_path(paths, path, dirname, accept)
filename = File.expand_path(path, dirname)
load_path, _ = paths_split(paths, dirname)
if load_path && logical_path = split_subpath(load_path, filename)
resolve_logical_path([load_path], logical_path, accept)
else
return nil, nil, nil, Set.new
end
end
def resolve_logical_path(paths, logical_path, accept)
extname, mime_type = match_path_extname(logical_path, config[:mime_exts])
logical_name = logical_path.chomp(extname)
extname, pipeline = match_path_extname(logical_name, config[:pipeline_exts])
logical_name = logical_name.chomp(extname)
parsed_accept = parse_accept_options(mime_type, accept)
transformed_accepts = expand_transform_accepts(parsed_accept)
filename, mime_type, deps, index_alias = resolve_under_paths(paths, logical_name, transformed_accepts)
if filename
deps << build_file_digest_uri(filename)
type = resolve_transform_type(mime_type, parsed_accept)
return filename, type, pipeline, deps, index_alias
else
return nil, nil, nil, deps
end
end
def resolve_under_paths(paths, logical_name, accepts)
deps = Set.new
return nil, nil, deps if accepts.empty?
mime_exts = config[:mime_exts]
paths.each do |load_path|
# TODO: Allow new path resolves to be registered
fns = [
method(:resolve_main_under_path),
method(:resolve_alts_under_path),
method(:resolve_index_under_path)
]
candidates = []
fns.each do |fn|
result = fn.call(load_path, logical_name, mime_exts)
candidates.concat(result[0])
deps.merge(result[1])
end
candidate = find_best_q_match(accepts, candidates) do |c, matcher|
match_mime_type?(c[:type] || "application/octet-stream", matcher)
end
return candidate[:filename], candidate[:type], deps, candidate[:index_alias] if candidate
end
return nil, nil, deps
end
def resolve_main_under_path(load_path, logical_name, mime_exts)
dirname = File.dirname(File.join(load_path, logical_name))
candidates = find_matching_path_for_extensions(dirname, File.basename(logical_name), mime_exts)
return candidates.map { |c|
{ filename: c[0], type: c[1] }
}, [build_file_digest_uri(dirname)]
end
def resolve_alts_under_path(load_path, logical_name, mime_exts)
filenames, deps = self.resolve_alternates(load_path, logical_name)
return filenames.map { |fn|
_, mime_type = match_path_extname(fn, mime_exts)
{ filename: fn, type: mime_type }
}, deps
end
def resolve_index_under_path(load_path, logical_name, mime_exts)
dirname = File.join(load_path, logical_name)
deps = [build_file_digest_uri(dirname)]
candidates = []
if directory?(dirname)
candidates = find_matching_path_for_extensions(dirname, "index", mime_exts)
end
return candidates.map { |c|
{ filename: c[0], type: c[1], index_alias: c[0].gsub(/\/index(\.\w{2,4})$/, '\1') }
}, deps
end
def parse_accept_options(mime_type, types)
accepts = []
accepts += parse_q_values(types) if types
if mime_type
if accepts.empty? || accepts.any? { |accept, _| match_mime_type?(mime_type, accept) }
accepts = [[mime_type, 1.0]]
else
return []
end
end
if accepts.empty?
accepts << ['*/*', 1.0]
end
accepts
end
def resolve_alternates(load_path, logical_name)
return [], Set.new
end
end
end
| askl56/sprockets | lib/sprockets/resolve.rb | Ruby | mit | 6,764 |
(function (subdivision) {
'use strict';
var count = 0;
var builders;
var defaultBuilder;
function buildInternal(type, addin, options, meta) {
var builder = subdivision.getBuilder(type);
if (builder.preBuildTarget) {
addin = buildInternal(builder.preBuildTarget, addin, options, meta);
}
return builder.build(addin, options, meta);
}
function buildInternalAsync(type, addin, options, meta) {
try {
var builder = subdivision.getBuilder(type);
var promise = Promise.resolve(addin);
if (builder.preBuildTarget) {
promise = buildInternalAsync(builder.preBuildTarget, addin, options, meta);
}
return promise.then(function (addin) {
return builder.build(addin, options, meta);
});
}
catch (ex) {
return Promise.reject(ex);
}
}
subdivision.Builder = function (options) {
var builder = subdivision.Addin.$internalConstructor('builder', count++, options);
if (!_.isFunction(builder.build)) {
throw new Error('Builder options must contain the "build" function ' + JSON.stringify(options));
}
builder.target = builder.target === undefined ? '' : builder.target;
return builder;
};
subdivision.systemPaths.builders = subdivision.registry.joinPath(subdivision.systemPaths.prefix, 'builders');
subdivision.defaultManifest.paths.push({
path: subdivision.systemPaths.builders,
addins: [
{
///Update docs if this changes
id: 'subdivision.defaultBuilder',
type: 'subdivision.builder',
target: null,
order: subdivision.registry.$defaultOrder,
build: function (addin) {
return _.cloneDeep(addin);
}
}
]
});
/**
* Adds a new builder created from the options to the list of known builders.
* If a builder that builds the given type already exists then
* the new builder is added based on the forced option. If force is truthy it is added anyway otherwise does nothing
* Returns true if a builder was added and false otherwise
*
*/
subdivision.addBuilder = function (options, force) {
var builder = new subdivision.Builder(options);
if (builder.target === null) {
if (!defaultBuilder || force) {
defaultBuilder = builder;
return true;
} else {
return false;
}
}
if (!builders.hasOwnProperty(builder.target) || force) {
builders[builder.target] = builder;
return true;
} else {
return false;
}
};
/**
* Gets a builder for the appropriate type, if no builder of the given type is found returns the default builder (builder with type === null)
* @param type
*/
subdivision.getBuilder = function (type) {
if (type === null && defaultBuilder) {
return defaultBuilder;
} else {
if (builders.hasOwnProperty(type)) {
return builders[type];
}
if (defaultBuilder) {
return defaultBuilder;
}
}
throw new Error('No builder of type "' + type + '" was defined and no default builder was registered');
};
/**
* Returns all the addins in the path after applying the appropriate builder on each
* @param path - The path to build
* @param options - Custom options to be passed to the addin builder
* @param searchCriteria - The search criteria for the underscore filter function
* @param skipSort - If truthy the topological sort is skipped
* @returns {Array} = The built addins
*/
subdivision.build = function (path, options, searchCriteria, skipSort) {
var addins = subdivision.getAddins(path, searchCriteria, skipSort);
if (addins.length === 0) {
return addins;
}
return _.map(addins, function (addin) {
return buildInternal(addin.type, addin, options, {
path: path
});
});
};
/**
* Returns all the addins in the path after applying the appropriate builder on each
* @param path - The path to build
* @param options - Custom options to be passed to the addin builder
* @param searchCriteria - The search criteria for the underscore filter function
* @param skipSort - If truthy the topological sort is skipped
* @returns {Array} = A promise that resolves with an array of the built addins
*/
subdivision.build.async = function (path, options, searchCriteria, skipSort) {
var addins = subdivision.getAddins(path, searchCriteria, skipSort);
if (addins.length === 0) {
return Promise.resolve(addins);
}
var promises = _.map(addins, function (addin) {
//TODO: Optimization that tries to guess the builder from previous builder
return buildInternalAsync(addin.type, addin, options, {
path: path
});
});
return Promise.all(promises);
};
/**
* Builds a single addin based on its type
* @param addin The addin to build
* @param options The options to pass to the builder
*/
subdivision.buildAddin = function (addin, options) {
return buildInternal(addin.type, addin, options, {
path: null
});
};
/**
* The async version of buildAddin
* @param addin The addin to build
* @param options The options to pass to the builder
* @returns A promise that when resolved returns the built addin
*/
subdivision.buildAddin.async = function (addin, options) {
return buildInternalAsync(addin.type, addin, options, {
path: null
});
};
/**
* Builds a tree out of the given path. Each addin will have child elements at path+addin.id added
* to its items property (default $items).
* @param path
* @param options - Custom options to be passed to the addin builder
*/
subdivision.buildTree = function (path, options) {
var addins = subdivision.getAddins(path);
if (addins.length === 0) {
return addins;
}
return _.map(addins, function (addin) {
//TODO: Optimization that tries to guess the builder from previous builder
var result = buildInternal(addin.type, addin, options, {
path: path
});
var itemsProperty = addin.itemsProperty || '$items';
result[itemsProperty] = subdivision.buildTree(subdivision.registry.joinPath(path, addin.id), options);
return result;
});
};
/**
* Regenerates all the builders from the system builders path
*/
subdivision.$generateBuilders = function () {
subdivision.$clearBuilders();
var addins = subdivision.getAddins(subdivision.systemPaths.builders, {target: null});
if (addins.length > 0) {
defaultBuilder = new subdivision.Builder(addins[0]);
}
addins = subdivision.getAddins(subdivision.systemPaths.builders);
_.forEach(addins, function (addin) {
subdivision.addBuilder(addin);
});
};
subdivision.$clearBuilders = function () {
builders = {};
defaultBuilder = null;
};
subdivision.$clearBuilders();
Object.defineProperty(subdivision, 'builders', {
enumerable: true,
configurable: false,
get: function () {
return _.clone(builders);
}
});
})(subdivision); | BorisKozo/extensibility.js | app/lib/builder.js | JavaScript | mit | 7,868 |
// This file is automatically generated.
// Please do not change this file!
interface CssExports {
'button': string;
'buttonItemCount': string;
'checked': string;
'level': string;
'selector': string;
}
export const cssExports: CssExports;
export default cssExports;
| DestinyItemManager/DIM | src/app/organizer/ItemTypeSelector.m.scss.d.ts | TypeScript | mit | 276 |
import argparse
import asyncio
import gc
import os.path
import pathlib
import socket
import ssl
PRINT = 0
async def echo_server(loop, address, unix):
if unix:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
else:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(address)
sock.listen(5)
sock.setblocking(False)
if PRINT:
print('Server listening at', address)
with sock:
while True:
client, addr = await loop.sock_accept(sock)
if PRINT:
print('Connection from', addr)
loop.create_task(echo_client(loop, client))
async def echo_client(loop, client):
try:
client.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except (OSError, NameError):
pass
with client:
while True:
data = await loop.sock_recv(client, 1000000)
if not data:
break
await loop.sock_sendall(client, data)
if PRINT:
print('Connection closed')
async def echo_client_streams(reader, writer):
sock = writer.get_extra_info('socket')
try:
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except (OSError, NameError):
pass
if PRINT:
print('Connection from', sock.getpeername())
while True:
data = await reader.read(1000000)
if not data:
break
writer.write(data)
if PRINT:
print('Connection closed')
writer.close()
class EchoProtocol(asyncio.Protocol):
def connection_made(self, transport):
self.transport = transport
def connection_lost(self, exc):
self.transport = None
def data_received(self, data):
self.transport.write(data)
class EchoBufferedProtocol(asyncio.BufferedProtocol):
def connection_made(self, transport):
self.transport = transport
# Here the buffer is intended to be copied, so that the outgoing buffer
# won't be wrongly updated by next read
self.buffer = bytearray(256 * 1024)
def connection_lost(self, exc):
self.transport = None
def get_buffer(self, sizehint):
return self.buffer
def buffer_updated(self, nbytes):
self.transport.write(self.buffer[:nbytes])
async def print_debug(loop):
while True:
print(chr(27) + "[2J") # clear screen
loop.print_debug_info()
await asyncio.sleep(0.5)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--uvloop', default=False, action='store_true')
parser.add_argument('--streams', default=False, action='store_true')
parser.add_argument('--proto', default=False, action='store_true')
parser.add_argument('--addr', default='127.0.0.1:25000', type=str)
parser.add_argument('--print', default=False, action='store_true')
parser.add_argument('--ssl', default=False, action='store_true')
parser.add_argument('--buffered', default=False, action='store_true')
args = parser.parse_args()
if args.uvloop:
import uvloop
loop = uvloop.new_event_loop()
print('using UVLoop')
else:
loop = asyncio.new_event_loop()
print('using asyncio loop')
asyncio.set_event_loop(loop)
loop.set_debug(False)
if args.print:
PRINT = 1
if hasattr(loop, 'print_debug_info'):
loop.create_task(print_debug(loop))
PRINT = 0
unix = False
if args.addr.startswith('file:'):
unix = True
addr = args.addr[5:]
if os.path.exists(addr):
os.remove(addr)
else:
addr = args.addr.split(':')
addr[1] = int(addr[1])
addr = tuple(addr)
print('serving on: {}'.format(addr))
server_context = None
if args.ssl:
print('with SSL')
if hasattr(ssl, 'PROTOCOL_TLS'):
server_context = ssl.SSLContext(ssl.PROTOCOL_TLS)
else:
server_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
server_context.load_cert_chain(
(pathlib.Path(__file__).parent.parent.parent /
'tests' / 'certs' / 'ssl_cert.pem'),
(pathlib.Path(__file__).parent.parent.parent /
'tests' / 'certs' / 'ssl_key.pem'))
if hasattr(server_context, 'check_hostname'):
server_context.check_hostname = False
server_context.verify_mode = ssl.CERT_NONE
if args.streams:
if args.proto:
print('cannot use --stream and --proto simultaneously')
exit(1)
if args.buffered:
print('cannot use --stream and --buffered simultaneously')
exit(1)
print('using asyncio/streams')
if unix:
coro = asyncio.start_unix_server(echo_client_streams,
addr,
ssl=server_context)
else:
coro = asyncio.start_server(echo_client_streams,
*addr,
ssl=server_context)
srv = loop.run_until_complete(coro)
elif args.proto:
if args.streams:
print('cannot use --stream and --proto simultaneously')
exit(1)
if args.buffered:
print('using buffered protocol')
protocol = EchoBufferedProtocol
else:
print('using simple protocol')
protocol = EchoProtocol
if unix:
coro = loop.create_unix_server(protocol, addr,
ssl=server_context)
else:
coro = loop.create_server(protocol, *addr,
ssl=server_context)
srv = loop.run_until_complete(coro)
else:
if args.ssl:
print('cannot use SSL for loop.sock_* methods')
exit(1)
print('using sock_recv/sock_sendall')
loop.create_task(echo_server(loop, addr, unix))
try:
loop.run_forever()
finally:
if hasattr(loop, 'print_debug_info'):
gc.collect()
print(chr(27) + "[2J")
loop.print_debug_info()
loop.close()
| 1st1/uvloop | examples/bench/echoserver.py | Python | mit | 6,317 |
<?php
/*
* This file is part of the PHPExifTool package.
*
* (c) Alchemy <support@alchemy.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\MXF;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class EventStart extends AbstractTag
{
protected $Id = '060e2b34.0101.0102.07020103.03030000';
protected $Name = 'EventStart';
protected $FullName = 'MXF::Main';
protected $GroupName = 'MXF';
protected $g0 = 'MXF';
protected $g1 = 'MXF';
protected $g2 = 'Video';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Event Start';
}
| bburnichon/PHPExiftool | lib/PHPExiftool/Driver/Tag/MXF/EventStart.php | PHP | mit | 799 |
<?php
namespace Soda\Cms\Database\Repositories\Contracts;
use Illuminate\Http\Request;
use Soda\Cms\Database\Models\Contracts\ContentInterface;
interface ContentRepositoryInterface extends BaseRepositoryInterface
{
public function findBySlug($slug);
public function listFolder(Request $request, ContentInterface $contentFolder);
public function getBlockTypes();
public function getAvailableBlockTypes(ContentInterface $content);
public function getRoot();
public function getTypes($creatableOnly = false);
public function getShortcuts(ContentInterface $content);
public function getCreatableContentTypes($contentFolderId);
public function createStub($parentId = null, $contentTypeId = null);
}
| sodacms/sodacms | src/Database/Repositories/Contracts/ContentRepositoryInterface.php | PHP | mit | 741 |
/*!
* reveal.js
* http://lab.hakim.se/reveal-js
* MIT licensed
*
* Copyright (C) 2016 Hakim El Hattab, http://hakim.se
*/
(function( root, factory ) {
if( typeof define === 'function' && define.amd ) {
// AMD. Register as an anonymous module.
define( function() {
root.Reveal = factory();
return root.Reveal;
} );
} else if( typeof exports === 'object' ) {
// Node. Does not work with strict CommonJS.
module.exports = factory();
} else {
// Browser globals.
root.Reveal = factory();
}
}( this, function() {
'use strict';
var Reveal;
// The reveal.js version
var VERSION = '3.3.0';
var SLIDES_SELECTOR = '.slides section',
HORIZONTAL_SLIDES_SELECTOR = '.slides>section',
VERTICAL_SLIDES_SELECTOR = '.slides>section.present>section',
HOME_SLIDE_SELECTOR = '.slides>section:first-of-type',
UA = navigator.userAgent,
// Configuration defaults, can be overridden at initialization time
config = {
// The "normal" size of the presentation, aspect ratio will be preserved
// when the presentation is scaled to fit different resolutions
width: 960,
height: 700,
// Factor of the display size that should remain empty around the content
margin: 0.1,
// Bounds for smallest/largest possible scale to apply to content
minScale: 0.2,
maxScale: 1.5,
// Display controls in the bottom right corner
controls: true,
// Display a presentation progress bar
progress: true,
// Display the page number of the current slide
slideNumber: false,
// Push each slide change to the browser history
history: false,
// Enable keyboard shortcuts for navigation
keyboard: true,
// Optional function that blocks keyboard events when retuning false
keyboardCondition: null,
// Enable the slide overview mode
overview: true,
// Vertical centering of slides
center: true,
// Enables touch navigation on devices with touch input
touch: true,
// Loop the presentation
loop: false,
// Change the presentation direction to be RTL
rtl: false,
// Randomizes the order of slides each time the presentation loads
shuffle: false,
// Turns fragments on and off globally
fragments: true,
// Flags if the presentation is running in an embedded mode,
// i.e. contained within a limited portion of the screen
embedded: false,
// Flags if we should show a help overlay when the questionmark
// key is pressed
help: true,
// Flags if it should be possible to pause the presentation (blackout)
pause: true,
// Flags if speaker notes should be visible to all viewers
showNotes: false,
// Number of milliseconds between automatically proceeding to the
// next slide, disabled when set to 0, this value can be overwritten
// by using a data-autoslide attribute on your slides
autoSlide: 0,
// Stop auto-sliding after user input
autoSlideStoppable: true,
// Use this method for navigation when auto-sliding (defaults to navigateNext)
autoSlideMethod: null,
// Enable slide navigation via mouse wheel
mouseWheel: false,
// Apply a 3D roll to links on hover
rollingLinks: false,
// Hides the address bar on mobile devices
hideAddressBar: true,
// Opens links in an iframe preview overlay
previewLinks: false,
// Exposes the reveal.js API through window.postMessage
postMessage: true,
// Dispatches all reveal.js events to the parent window through postMessage
postMessageEvents: false,
// Focuses body when page changes visiblity to ensure keyboard shortcuts work
focusBodyOnPageVisibilityChange: true,
// Transition style
transition: 'fade', // none/fade/slide/convex/concave/zoom
// Transition speed
transitionSpeed: 'default', // default/fast/slow
// Transition style for full page slide backgrounds
backgroundTransition: 'fade', // none/fade/slide/convex/concave/zoom
// Parallax background image
parallaxBackgroundImage: '', // CSS syntax, e.g. "a.jpg"
// Parallax background size
parallaxBackgroundSize: '', // CSS syntax, e.g. "3000px 2000px"
// Amount of pixels to move the parallax background per slide step
parallaxBackgroundHorizontal: null,
parallaxBackgroundVertical: null,
// Number of slides away from the current that are visible
viewDistance: 3,
// Script dependencies to load
dependencies: []
},
// Flags if reveal.js is loaded (has dispatched the 'ready' event)
loaded = false,
// Flags if the overview mode is currently active
overview = false,
// Holds the dimensions of our overview slides, including margins
overviewSlideWidth = null,
overviewSlideHeight = null,
// The horizontal and vertical index of the currently active slide
indexh,
indexv,
// The previous and current slide HTML elements
previousSlide,
currentSlide,
previousBackground,
// Slides may hold a data-state attribute which we pick up and apply
// as a class to the body. This list contains the combined state of
// all current slides.
state = [],
// The current scale of the presentation (see width/height config)
scale = 1,
// CSS transform that is currently applied to the slides container,
// split into two groups
slidesTransform = { layout: '', overview: '' },
// Cached references to DOM elements
dom = {},
// Features supported by the browser, see #checkCapabilities()
features = {},
// Client is a mobile device, see #checkCapabilities()
isMobileDevice,
// Client is a desktop Chrome, see #checkCapabilities()
isChrome,
// Throttles mouse wheel navigation
lastMouseWheelStep = 0,
// Delays updates to the URL due to a Chrome thumbnailer bug
writeURLTimeout = 0,
// Flags if the interaction event listeners are bound
eventsAreBound = false,
// The current auto-slide duration
autoSlide = 0,
// Auto slide properties
autoSlidePlayer,
autoSlideTimeout = 0,
autoSlideStartTime = -1,
autoSlidePaused = false,
// Holds information about the currently ongoing touch input
touch = {
startX: 0,
startY: 0,
startSpan: 0,
startCount: 0,
captured: false,
threshold: 40
},
// Holds information about the keyboard shortcuts
keyboardShortcuts = {
'N , SPACE': 'Next slide',
'P': 'Previous slide',
'← , H': 'Navigate left',
'→ , L': 'Navigate right',
'↑ , K': 'Navigate up',
'↓ , J': 'Navigate down',
'Home': 'First slide',
'End': 'Last slide',
'B , .': 'Pause',
'F': 'Fullscreen',
'ESC, O': 'Slide overview'
};
/**
* Starts up the presentation if the client is capable.
*/
function initialize( options ) {
checkCapabilities();
if( !features.transforms2d && !features.transforms3d ) {
document.body.setAttribute( 'class', 'no-transforms' );
// Since JS won't be running any further, we load all lazy
// loading elements upfront
var images = toArray( document.getElementsByTagName( 'img' ) ),
iframes = toArray( document.getElementsByTagName( 'iframe' ) );
var lazyLoadable = images.concat( iframes );
for( var i = 0, len = lazyLoadable.length; i < len; i++ ) {
var element = lazyLoadable[i];
if( element.getAttribute( 'data-src' ) ) {
element.setAttribute( 'src', element.getAttribute( 'data-src' ) );
element.removeAttribute( 'data-src' );
}
}
// If the browser doesn't support core features we won't be
// using JavaScript to control the presentation
return;
}
// Cache references to key DOM elements
dom.wrapper = document.querySelector( '.reveal' );
dom.slides = document.querySelector( '.reveal .slides' );
// Force a layout when the whole page, incl fonts, has loaded
window.addEventListener( 'load', layout, false );
var query = Reveal.getQueryHash();
// Do not accept new dependencies via query config to avoid
// the potential of malicious script injection
if( typeof query['dependencies'] !== 'undefined' ) delete query['dependencies'];
// Copy options over to our config object
extend( config, options );
extend( config, query );
// Hide the address bar in mobile browsers
hideAddressBar();
// Loads the dependencies and continues to #start() once done
load();
}
/**
* Inspect the client to see what it's capable of, this
* should only happens once per runtime.
*/
function checkCapabilities() {
isMobileDevice = /(iphone|ipod|ipad|android)/gi.test( UA );
isChrome = /chrome/i.test( UA ) && !/edge/i.test( UA );
var testElement = document.createElement( 'div' );
features.transforms3d = 'WebkitPerspective' in testElement.style ||
'MozPerspective' in testElement.style ||
'msPerspective' in testElement.style ||
'OPerspective' in testElement.style ||
'perspective' in testElement.style;
features.transforms2d = 'WebkitTransform' in testElement.style ||
'MozTransform' in testElement.style ||
'msTransform' in testElement.style ||
'OTransform' in testElement.style ||
'transform' in testElement.style;
features.requestAnimationFrameMethod = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;
features.requestAnimationFrame = typeof features.requestAnimationFrameMethod === 'function';
features.canvas = !!document.createElement( 'canvas' ).getContext;
// Transitions in the overview are disabled in desktop and
// Safari due to lag
features.overviewTransitions = !/Version\/[\d\.]+.*Safari/.test( UA );
// Flags if we should use zoom instead of transform to scale
// up slides. Zoom produces crisper results but has a lot of
// xbrowser quirks so we only use it in whitelsited browsers.
features.zoom = 'zoom' in testElement.style && !isMobileDevice &&
( isChrome || /Version\/[\d\.]+.*Safari/.test( UA ) );
}
/**
* Loads the dependencies of reveal.js. Dependencies are
* defined via the configuration option 'dependencies'
* and will be loaded prior to starting/binding reveal.js.
* Some dependencies may have an 'async' flag, if so they
* will load after reveal.js has been started up.
*/
function load() {
var scripts = [],
scriptsAsync = [],
scriptsToPreload = 0;
// Called once synchronous scripts finish loading
function proceed() {
if( scriptsAsync.length ) {
// Load asynchronous scripts
head.js.apply( null, scriptsAsync );
}
start();
}
function loadScript( s ) {
head.ready( s.src.match( /([\w\d_\-]*)\.?js$|[^\\\/]*$/i )[0], function() {
// Extension may contain callback functions
if( typeof s.callback === 'function' ) {
s.callback.apply( this );
}
if( --scriptsToPreload === 0 ) {
proceed();
}
});
}
for( var i = 0, len = config.dependencies.length; i < len; i++ ) {
var s = config.dependencies[i];
// Load if there's no condition or the condition is truthy
if( !s.condition || s.condition() ) {
if( s.async ) {
scriptsAsync.push( s.src );
}
else {
scripts.push( s.src );
}
loadScript( s );
}
}
if( scripts.length ) {
scriptsToPreload = scripts.length;
// Load synchronous scripts
head.js.apply( null, scripts );
}
else {
proceed();
}
}
/**
* Starts up reveal.js by binding input events and navigating
* to the current URL deeplink if there is one.
*/
function start() {
// Make sure we've got all the DOM elements we need
setupDOM();
// Listen to messages posted to this window
setupPostMessage();
// Prevent the slides from being scrolled out of view
setupScrollPrevention();
// Resets all vertical slides so that only the first is visible
resetVerticalSlides();
// Updates the presentation to match the current configuration values
configure();
// Read the initial hash
readURL();
// Update all backgrounds
updateBackground( true );
// Notify listeners that the presentation is ready but use a 1ms
// timeout to ensure it's not fired synchronously after #initialize()
setTimeout( function() {
// Enable transitions now that we're loaded
dom.slides.classList.remove( 'no-transition' );
loaded = true;
dispatchEvent( 'ready', {
'indexh': indexh,
'indexv': indexv,
'currentSlide': currentSlide
} );
}, 1 );
// Special setup and config is required when printing to PDF
if( isPrintingPDF() ) {
removeEventListeners();
// The document needs to have loaded for the PDF layout
// measurements to be accurate
if( document.readyState === 'complete' ) {
setupPDF();
}
else {
window.addEventListener( 'load', setupPDF );
}
}
}
/**
* Finds and stores references to DOM elements which are
* required by the presentation. If a required element is
* not found, it is created.
*/
function setupDOM() {
// Prevent transitions while we're loading
dom.slides.classList.add( 'no-transition' );
// Background element
dom.background = createSingletonNode( dom.wrapper, 'div', 'backgrounds', null );
// Progress bar
dom.progress = createSingletonNode( dom.wrapper, 'div', 'progress', '<span></span>' );
dom.progressbar = dom.progress.querySelector( 'span' );
// Arrow controls
createSingletonNode( dom.wrapper, 'aside', 'controls',
'<button class="navigate-left" aria-label="previous slide"></button>' +
'<button class="navigate-right" aria-label="next slide"></button>' +
'<button class="navigate-up" aria-label="above slide"></button>' +
'<button class="navigate-down" aria-label="below slide"></button>' );
// Slide number
dom.slideNumber = createSingletonNode( dom.wrapper, 'div', 'slide-number', '' );
// Element containing notes that are visible to the audience
dom.speakerNotes = createSingletonNode( dom.wrapper, 'div', 'speaker-notes', null );
dom.speakerNotes.setAttribute( 'data-prevent-swipe', '' );
// Overlay graphic which is displayed during the paused mode
createSingletonNode( dom.wrapper, 'div', 'pause-overlay', null );
// Cache references to elements
dom.controls = document.querySelector( '.reveal .controls' );
dom.theme = document.querySelector( '#theme' );
dom.wrapper.setAttribute( 'role', 'application' );
// There can be multiple instances of controls throughout the page
dom.controlsLeft = toArray( document.querySelectorAll( '.navigate-left' ) );
dom.controlsRight = toArray( document.querySelectorAll( '.navigate-right' ) );
dom.controlsUp = toArray( document.querySelectorAll( '.navigate-up' ) );
dom.controlsDown = toArray( document.querySelectorAll( '.navigate-down' ) );
dom.controlsPrev = toArray( document.querySelectorAll( '.navigate-prev' ) );
dom.controlsNext = toArray( document.querySelectorAll( '.navigate-next' ) );
dom.statusDiv = createStatusDiv();
}
/**
* Creates a hidden div with role aria-live to announce the
* current slide content. Hide the div off-screen to make it
* available only to Assistive Technologies.
*/
function createStatusDiv() {
var statusDiv = document.getElementById( 'aria-status-div' );
if( !statusDiv ) {
statusDiv = document.createElement( 'div' );
statusDiv.style.position = 'absolute';
statusDiv.style.height = '1px';
statusDiv.style.width = '1px';
statusDiv.style.overflow ='hidden';
statusDiv.style.clip = 'rect( 1px, 1px, 1px, 1px )';
statusDiv.setAttribute( 'id', 'aria-status-div' );
statusDiv.setAttribute( 'aria-live', 'polite' );
statusDiv.setAttribute( 'aria-atomic','true' );
dom.wrapper.appendChild( statusDiv );
}
return statusDiv;
}
/**
* Configures the presentation for printing to a static
* PDF.
*/
function setupPDF() {
var slideSize = getComputedSlideSize( window.innerWidth, window.innerHeight );
// Dimensions of the PDF pages
var pageWidth = Math.floor( slideSize.width * ( 1 + config.margin ) ),
pageHeight = Math.floor( slideSize.height * ( 1 + config.margin ) );
// Dimensions of slides within the pages
var slideWidth = slideSize.width,
slideHeight = slideSize.height;
// Let the browser know what page size we want to print
injectStyleSheet( '@page{size:'+ pageWidth +'px '+ pageHeight +'px; margin: 0;}' );
// Limit the size of certain elements to the dimensions of the slide
injectStyleSheet( '.reveal section>img, .reveal section>video, .reveal section>iframe{max-width: '+ slideWidth +'px; max-height:'+ slideHeight +'px}' );
document.body.classList.add( 'print-pdf' );
document.body.style.width = pageWidth + 'px';
document.body.style.height = pageHeight + 'px';
// Add each slide's index as attributes on itself, we need these
// indices to generate slide numbers below
toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) {
hslide.setAttribute( 'data-index-h', h );
if( hslide.classList.contains( 'stack' ) ) {
toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) {
vslide.setAttribute( 'data-index-h', h );
vslide.setAttribute( 'data-index-v', v );
} );
}
} );
// Slide and slide background layout
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) {
// Vertical stacks are not centred since their section
// children will be
if( slide.classList.contains( 'stack' ) === false ) {
// Center the slide inside of the page, giving the slide some margin
var left = ( pageWidth - slideWidth ) / 2,
top = ( pageHeight - slideHeight ) / 2;
var contentHeight = getAbsoluteHeight( slide );
var numberOfPages = Math.max( Math.ceil( contentHeight / pageHeight ), 1 );
// Center slides vertically
if( numberOfPages === 1 && config.center || slide.classList.contains( 'center' ) ) {
top = Math.max( ( pageHeight - contentHeight ) / 2, 0 );
}
// Position the slide inside of the page
slide.style.left = left + 'px';
slide.style.top = top + 'px';
slide.style.width = slideWidth + 'px';
// TODO Backgrounds need to be multiplied when the slide
// stretches over multiple pages
var background = slide.querySelector( '.slide-background' );
if( background ) {
background.style.width = pageWidth + 'px';
background.style.height = ( pageHeight * numberOfPages ) + 'px';
background.style.top = -top + 'px';
background.style.left = -left + 'px';
}
// Inject notes if `showNotes` is enabled
if( config.showNotes ) {
var notes = getSlideNotes( slide );
if( notes ) {
var notesSpacing = 8;
var notesElement = document.createElement( 'div' );
notesElement.classList.add( 'speaker-notes' );
notesElement.classList.add( 'speaker-notes-pdf' );
notesElement.innerHTML = notes;
notesElement.style.left = ( notesSpacing - left ) + 'px';
notesElement.style.bottom = ( notesSpacing - top ) + 'px';
notesElement.style.width = ( pageWidth - notesSpacing*2 ) + 'px';
slide.appendChild( notesElement );
}
}
// Inject slide numbers if `slideNumbers` are enabled
if( config.slideNumber ) {
var slideNumberH = parseInt( slide.getAttribute( 'data-index-h' ), 10 ) + 1,
slideNumberV = parseInt( slide.getAttribute( 'data-index-v' ), 10 ) + 1;
var numberElement = document.createElement( 'div' );
numberElement.classList.add( 'slide-number' );
numberElement.classList.add( 'slide-number-pdf' );
numberElement.innerHTML = formatSlideNumber( slideNumberH, '.', slideNumberV );
background.appendChild( numberElement );
}
}
} );
// Show all fragments
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' .fragment' ) ).forEach( function( fragment ) {
fragment.classList.add( 'visible' );
} );
}
/**
* This is an unfortunate necessity. Some actions – such as
* an input field being focused in an iframe or using the
* keyboard to expand text selection beyond the bounds of
* a slide – can trigger our content to be pushed out of view.
* This scrolling can not be prevented by hiding overflow in
* CSS (we already do) so we have to resort to repeatedly
* checking if the slides have been offset :(
*/
function setupScrollPrevention() {
setInterval( function() {
if( dom.wrapper.scrollTop !== 0 || dom.wrapper.scrollLeft !== 0 ) {
dom.wrapper.scrollTop = 0;
dom.wrapper.scrollLeft = 0;
}
}, 1000 );
}
/**
* Creates an HTML element and returns a reference to it.
* If the element already exists the existing instance will
* be returned.
*/
function createSingletonNode( container, tagname, classname, innerHTML ) {
// Find all nodes matching the description
var nodes = container.querySelectorAll( '.' + classname );
// Check all matches to find one which is a direct child of
// the specified container
for( var i = 0; i < nodes.length; i++ ) {
var testNode = nodes[i];
if( testNode.parentNode === container ) {
return testNode;
}
}
// If no node was found, create it now
var node = document.createElement( tagname );
node.classList.add( classname );
if( typeof innerHTML === 'string' ) {
node.innerHTML = innerHTML;
}
container.appendChild( node );
return node;
}
/**
* Creates the slide background elements and appends them
* to the background container. One element is created per
* slide no matter if the given slide has visible background.
*/
function createBackgrounds() {
var printMode = isPrintingPDF();
// Clear prior backgrounds
dom.background.innerHTML = '';
dom.background.classList.add( 'no-transition' );
// Iterate over all horizontal slides
toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( slideh ) {
var backgroundStack;
if( printMode ) {
backgroundStack = createBackground( slideh, slideh );
}
else {
backgroundStack = createBackground( slideh, dom.background );
}
// Iterate over all vertical slides
toArray( slideh.querySelectorAll( 'section' ) ).forEach( function( slidev ) {
if( printMode ) {
createBackground( slidev, slidev );
}
else {
createBackground( slidev, backgroundStack );
}
backgroundStack.classList.add( 'stack' );
} );
} );
// Add parallax background if specified
if( config.parallaxBackgroundImage ) {
dom.background.style.backgroundImage = 'url("' + config.parallaxBackgroundImage + '")';
dom.background.style.backgroundSize = config.parallaxBackgroundSize;
// Make sure the below properties are set on the element - these properties are
// needed for proper transitions to be set on the element via CSS. To remove
// annoying background slide-in effect when the presentation starts, apply
// these properties after short time delay
setTimeout( function() {
dom.wrapper.classList.add( 'has-parallax-background' );
}, 1 );
}
else {
dom.background.style.backgroundImage = '';
dom.wrapper.classList.remove( 'has-parallax-background' );
}
}
/**
* Creates a background for the given slide.
*
* @param {HTMLElement} slide
* @param {HTMLElement} container The element that the background
* should be appended to
*/
function createBackground( slide, container ) {
var data = {
background: slide.getAttribute( 'data-background' ),
backgroundSize: slide.getAttribute( 'data-background-size' ),
backgroundImage: slide.getAttribute( 'data-background-image' ),
backgroundVideo: slide.getAttribute( 'data-background-video' ),
backgroundIframe: slide.getAttribute( 'data-background-iframe' ),
backgroundColor: slide.getAttribute( 'data-background-color' ),
backgroundRepeat: slide.getAttribute( 'data-background-repeat' ),
backgroundPosition: slide.getAttribute( 'data-background-position' ),
backgroundTransition: slide.getAttribute( 'data-background-transition' )
};
var element = document.createElement( 'div' );
// Carry over custom classes from the slide to the background
element.className = 'slide-background ' + slide.className.replace( /present|past|future/, '' );
if( data.background ) {
// Auto-wrap image urls in url(...)
if( /^(http|file|\/\/)/gi.test( data.background ) || /\.(svg|png|jpg|jpeg|gif|bmp)$/gi.test( data.background ) ) {
slide.setAttribute( 'data-background-image', data.background );
}
else {
element.style.background = data.background;
}
}
// Create a hash for this combination of background settings.
// This is used to determine when two slide backgrounds are
// the same.
if( data.background || data.backgroundColor || data.backgroundImage || data.backgroundVideo || data.backgroundIframe ) {
element.setAttribute( 'data-background-hash', data.background +
data.backgroundSize +
data.backgroundImage +
data.backgroundVideo +
data.backgroundIframe +
data.backgroundColor +
data.backgroundRepeat +
data.backgroundPosition +
data.backgroundTransition );
}
// Additional and optional background properties
if( data.backgroundSize ) element.style.backgroundSize = data.backgroundSize;
if( data.backgroundColor ) element.style.backgroundColor = data.backgroundColor;
if( data.backgroundRepeat ) element.style.backgroundRepeat = data.backgroundRepeat;
if( data.backgroundPosition ) element.style.backgroundPosition = data.backgroundPosition;
if( data.backgroundTransition ) element.setAttribute( 'data-background-transition', data.backgroundTransition );
container.appendChild( element );
// If backgrounds are being recreated, clear old classes
slide.classList.remove( 'has-dark-background' );
slide.classList.remove( 'has-light-background' );
// If this slide has a background color, add a class that
// signals if it is light or dark. If the slide has no background
// color, no class will be set
var computedBackgroundColor = window.getComputedStyle( element ).backgroundColor;
if( computedBackgroundColor ) {
var rgb = colorToRgb( computedBackgroundColor );
// Ignore fully transparent backgrounds. Some browsers return
// rgba(0,0,0,0) when reading the computed background color of
// an element with no background
if( rgb && rgb.a !== 0 ) {
if( colorBrightness( computedBackgroundColor ) < 128 ) {
slide.classList.add( 'has-dark-background' );
}
else {
slide.classList.add( 'has-light-background' );
}
}
}
return element;
}
/**
* Registers a listener to postMessage events, this makes it
* possible to call all reveal.js API methods from another
* window. For example:
*
* revealWindow.postMessage( JSON.stringify({
* method: 'slide',
* args: [ 2 ]
* }), '*' );
*/
function setupPostMessage() {
if( config.postMessage ) {
window.addEventListener( 'message', function ( event ) {
var data = event.data;
// Make sure we're dealing with JSON
if( typeof data === 'string' && data.charAt( 0 ) === '{' && data.charAt( data.length - 1 ) === '}' ) {
data = JSON.parse( data );
// Check if the requested method can be found
if( data.method && typeof Reveal[data.method] === 'function' ) {
Reveal[data.method].apply( Reveal, data.args );
}
}
}, false );
}
}
/**
* Applies the configuration settings from the config
* object. May be called multiple times.
*/
function configure( options ) {
var numberOfSlides = dom.wrapper.querySelectorAll( SLIDES_SELECTOR ).length;
dom.wrapper.classList.remove( config.transition );
// New config options may be passed when this method
// is invoked through the API after initialization
if( typeof options === 'object' ) extend( config, options );
// Force linear transition based on browser capabilities
if( features.transforms3d === false ) config.transition = 'linear';
dom.wrapper.classList.add( config.transition );
dom.wrapper.setAttribute( 'data-transition-speed', config.transitionSpeed );
dom.wrapper.setAttribute( 'data-background-transition', config.backgroundTransition );
dom.controls.style.display = config.controls ? 'block' : 'none';
dom.progress.style.display = config.progress ? 'block' : 'none';
dom.slideNumber.style.display = config.slideNumber && !isPrintingPDF() ? 'block' : 'none';
if( config.shuffle ) {
shuffle();
}
if( config.rtl ) {
dom.wrapper.classList.add( 'rtl' );
}
else {
dom.wrapper.classList.remove( 'rtl' );
}
if( config.center ) {
dom.wrapper.classList.add( 'center' );
}
else {
dom.wrapper.classList.remove( 'center' );
}
// Exit the paused mode if it was configured off
if( config.pause === false ) {
resume();
}
if( config.showNotes ) {
dom.speakerNotes.classList.add( 'visible' );
}
else {
dom.speakerNotes.classList.remove( 'visible' );
}
if( config.mouseWheel ) {
document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
document.addEventListener( 'mousewheel', onDocumentMouseScroll, false );
}
else {
document.removeEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
document.removeEventListener( 'mousewheel', onDocumentMouseScroll, false );
}
// Rolling 3D links
if( config.rollingLinks ) {
enableRollingLinks();
}
else {
disableRollingLinks();
}
// Iframe link previews
if( config.previewLinks ) {
enablePreviewLinks();
}
else {
disablePreviewLinks();
enablePreviewLinks( '[data-preview-link]' );
}
// Remove existing auto-slide controls
if( autoSlidePlayer ) {
autoSlidePlayer.destroy();
autoSlidePlayer = null;
}
// Generate auto-slide controls if needed
if( numberOfSlides > 1 && config.autoSlide && config.autoSlideStoppable && features.canvas && features.requestAnimationFrame ) {
autoSlidePlayer = new Playback( dom.wrapper, function() {
return Math.min( Math.max( ( Date.now() - autoSlideStartTime ) / autoSlide, 0 ), 1 );
} );
autoSlidePlayer.on( 'click', onAutoSlidePlayerClick );
autoSlidePaused = false;
}
// When fragments are turned off they should be visible
if( config.fragments === false ) {
toArray( dom.slides.querySelectorAll( '.fragment' ) ).forEach( function( element ) {
element.classList.add( 'visible' );
element.classList.remove( 'current-fragment' );
} );
}
sync();
}
/**
* Binds all event listeners.
*/
function addEventListeners() {
eventsAreBound = true;
window.addEventListener( 'hashchange', onWindowHashChange, false );
window.addEventListener( 'resize', onWindowResize, false );
if( config.touch ) {
dom.wrapper.addEventListener( 'touchstart', onTouchStart, false );
dom.wrapper.addEventListener( 'touchmove', onTouchMove, false );
dom.wrapper.addEventListener( 'touchend', onTouchEnd, false );
// Support pointer-style touch interaction as well
if( window.navigator.pointerEnabled ) {
// IE 11 uses un-prefixed version of pointer events
dom.wrapper.addEventListener( 'pointerdown', onPointerDown, false );
dom.wrapper.addEventListener( 'pointermove', onPointerMove, false );
dom.wrapper.addEventListener( 'pointerup', onPointerUp, false );
}
else if( window.navigator.msPointerEnabled ) {
// IE 10 uses prefixed version of pointer events
dom.wrapper.addEventListener( 'MSPointerDown', onPointerDown, false );
dom.wrapper.addEventListener( 'MSPointerMove', onPointerMove, false );
dom.wrapper.addEventListener( 'MSPointerUp', onPointerUp, false );
}
}
if( config.keyboard ) {
document.addEventListener( 'keydown', onDocumentKeyDown, false );
document.addEventListener( 'keypress', onDocumentKeyPress, false );
}
if( config.progress && dom.progress ) {
dom.progress.addEventListener( 'click', onProgressClicked, false );
}
if( config.focusBodyOnPageVisibilityChange ) {
var visibilityChange;
if( 'hidden' in document ) {
visibilityChange = 'visibilitychange';
}
else if( 'msHidden' in document ) {
visibilityChange = 'msvisibilitychange';
}
else if( 'webkitHidden' in document ) {
visibilityChange = 'webkitvisibilitychange';
}
if( visibilityChange ) {
document.addEventListener( visibilityChange, onPageVisibilityChange, false );
}
}
// Listen to both touch and click events, in case the device
// supports both
var pointerEvents = [ 'touchstart', 'click' ];
// Only support touch for Android, fixes double navigations in
// stock browser
if( UA.match( /android/gi ) ) {
pointerEvents = [ 'touchstart' ];
}
pointerEvents.forEach( function( eventName ) {
dom.controlsLeft.forEach( function( el ) { el.addEventListener( eventName, onNavigateLeftClicked, false ); } );
dom.controlsRight.forEach( function( el ) { el.addEventListener( eventName, onNavigateRightClicked, false ); } );
dom.controlsUp.forEach( function( el ) { el.addEventListener( eventName, onNavigateUpClicked, false ); } );
dom.controlsDown.forEach( function( el ) { el.addEventListener( eventName, onNavigateDownClicked, false ); } );
dom.controlsPrev.forEach( function( el ) { el.addEventListener( eventName, onNavigatePrevClicked, false ); } );
dom.controlsNext.forEach( function( el ) { el.addEventListener( eventName, onNavigateNextClicked, false ); } );
} );
}
/**
* Unbinds all event listeners.
*/
function removeEventListeners() {
eventsAreBound = false;
document.removeEventListener( 'keydown', onDocumentKeyDown, false );
document.removeEventListener( 'keypress', onDocumentKeyPress, false );
window.removeEventListener( 'hashchange', onWindowHashChange, false );
window.removeEventListener( 'resize', onWindowResize, false );
dom.wrapper.removeEventListener( 'touchstart', onTouchStart, false );
dom.wrapper.removeEventListener( 'touchmove', onTouchMove, false );
dom.wrapper.removeEventListener( 'touchend', onTouchEnd, false );
// IE11
if( window.navigator.pointerEnabled ) {
dom.wrapper.removeEventListener( 'pointerdown', onPointerDown, false );
dom.wrapper.removeEventListener( 'pointermove', onPointerMove, false );
dom.wrapper.removeEventListener( 'pointerup', onPointerUp, false );
}
// IE10
else if( window.navigator.msPointerEnabled ) {
dom.wrapper.removeEventListener( 'MSPointerDown', onPointerDown, false );
dom.wrapper.removeEventListener( 'MSPointerMove', onPointerMove, false );
dom.wrapper.removeEventListener( 'MSPointerUp', onPointerUp, false );
}
if ( config.progress && dom.progress ) {
dom.progress.removeEventListener( 'click', onProgressClicked, false );
}
[ 'touchstart', 'click' ].forEach( function( eventName ) {
dom.controlsLeft.forEach( function( el ) { el.removeEventListener( eventName, onNavigateLeftClicked, false ); } );
dom.controlsRight.forEach( function( el ) { el.removeEventListener( eventName, onNavigateRightClicked, false ); } );
dom.controlsUp.forEach( function( el ) { el.removeEventListener( eventName, onNavigateUpClicked, false ); } );
dom.controlsDown.forEach( function( el ) { el.removeEventListener( eventName, onNavigateDownClicked, false ); } );
dom.controlsPrev.forEach( function( el ) { el.removeEventListener( eventName, onNavigatePrevClicked, false ); } );
dom.controlsNext.forEach( function( el ) { el.removeEventListener( eventName, onNavigateNextClicked, false ); } );
} );
}
/**
* Extend object a with the properties of object b.
* If there's a conflict, object b takes precedence.
*/
function extend( a, b ) {
for( var i in b ) {
a[ i ] = b[ i ];
}
}
/**
* Converts the target object to an array.
*/
function toArray( o ) {
return Array.prototype.slice.call( o );
}
/**
* Utility for deserializing a value.
*/
function deserialize( value ) {
if( typeof value === 'string' ) {
if( value === 'null' ) return null;
else if( value === 'true' ) return true;
else if( value === 'false' ) return false;
else if( value.match( /^\d+$/ ) ) return parseFloat( value );
}
return value;
}
/**
* Measures the distance in pixels between point a
* and point b.
*
* @param {Object} a point with x/y properties
* @param {Object} b point with x/y properties
*/
function distanceBetween( a, b ) {
var dx = a.x - b.x,
dy = a.y - b.y;
return Math.sqrt( dx*dx + dy*dy );
}
/**
* Applies a CSS transform to the target element.
*/
function transformElement( element, transform ) {
element.style.WebkitTransform = transform;
element.style.MozTransform = transform;
element.style.msTransform = transform;
element.style.transform = transform;
}
/**
* Applies CSS transforms to the slides container. The container
* is transformed from two separate sources: layout and the overview
* mode.
*/
function transformSlides( transforms ) {
// Pick up new transforms from arguments
if( typeof transforms.layout === 'string' ) slidesTransform.layout = transforms.layout;
if( typeof transforms.overview === 'string' ) slidesTransform.overview = transforms.overview;
// Apply the transforms to the slides container
if( slidesTransform.layout ) {
transformElement( dom.slides, slidesTransform.layout + ' ' + slidesTransform.overview );
}
else {
transformElement( dom.slides, slidesTransform.overview );
}
}
/**
* Injects the given CSS styles into the DOM.
*/
function injectStyleSheet( value ) {
var tag = document.createElement( 'style' );
tag.type = 'text/css';
if( tag.styleSheet ) {
tag.styleSheet.cssText = value;
}
else {
tag.appendChild( document.createTextNode( value ) );
}
document.getElementsByTagName( 'head' )[0].appendChild( tag );
}
/**
* Converts various color input formats to an {r:0,g:0,b:0} object.
*
* @param {String} color The string representation of a color,
* the following formats are supported:
* - #000
* - #000000
* - rgb(0,0,0)
*/
function colorToRgb( color ) {
var hex3 = color.match( /^#([0-9a-f]{3})$/i );
if( hex3 && hex3[1] ) {
hex3 = hex3[1];
return {
r: parseInt( hex3.charAt( 0 ), 16 ) * 0x11,
g: parseInt( hex3.charAt( 1 ), 16 ) * 0x11,
b: parseInt( hex3.charAt( 2 ), 16 ) * 0x11
};
}
var hex6 = color.match( /^#([0-9a-f]{6})$/i );
if( hex6 && hex6[1] ) {
hex6 = hex6[1];
return {
r: parseInt( hex6.substr( 0, 2 ), 16 ),
g: parseInt( hex6.substr( 2, 2 ), 16 ),
b: parseInt( hex6.substr( 4, 2 ), 16 )
};
}
var rgb = color.match( /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i );
if( rgb ) {
return {
r: parseInt( rgb[1], 10 ),
g: parseInt( rgb[2], 10 ),
b: parseInt( rgb[3], 10 )
};
}
var rgba = color.match( /^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\,\s*([\d]+|[\d]*.[\d]+)\s*\)$/i );
if( rgba ) {
return {
r: parseInt( rgba[1], 10 ),
g: parseInt( rgba[2], 10 ),
b: parseInt( rgba[3], 10 ),
a: parseFloat( rgba[4] )
};
}
return null;
}
/**
* Calculates brightness on a scale of 0-255.
*
* @param color See colorStringToRgb for supported formats.
*/
function colorBrightness( color ) {
if( typeof color === 'string' ) color = colorToRgb( color );
if( color ) {
return ( color.r * 299 + color.g * 587 + color.b * 114 ) / 1000;
}
return null;
}
/**
* Retrieves the height of the given element by looking
* at the position and height of its immediate children.
*/
function getAbsoluteHeight( element ) {
var height = 0;
if( element ) {
var absoluteChildren = 0;
toArray( element.childNodes ).forEach( function( child ) {
if( typeof child.offsetTop === 'number' && child.style ) {
// Count # of abs children
if( window.getComputedStyle( child ).position === 'absolute' ) {
absoluteChildren += 1;
}
height = Math.max( height, child.offsetTop + child.offsetHeight );
}
} );
// If there are no absolute children, use offsetHeight
if( absoluteChildren === 0 ) {
height = element.offsetHeight;
}
}
return height;
}
/**
* Returns the remaining height within the parent of the
* target element.
*
* remaining height = [ configured parent height ] - [ current parent height ]
*/
function getRemainingHeight( element, height ) {
height = height || 0;
if( element ) {
var newHeight, oldHeight = element.style.height;
// Change the .stretch element height to 0 in order find the height of all
// the other elements
element.style.height = '0px';
newHeight = height - element.parentNode.offsetHeight;
// Restore the old height, just in case
element.style.height = oldHeight + 'px';
return newHeight;
}
return height;
}
/**
* Checks if this instance is being used to print a PDF.
*/
function isPrintingPDF() {
return ( /print-pdf/gi ).test( window.location.search );
}
/**
* Hides the address bar if we're on a mobile device.
*/
function hideAddressBar() {
if( config.hideAddressBar && isMobileDevice ) {
// Events that should trigger the address bar to hide
window.addEventListener( 'load', removeAddressBar, false );
window.addEventListener( 'orientationchange', removeAddressBar, false );
}
}
/**
* Causes the address bar to hide on mobile devices,
* more vertical space ftw.
*/
function removeAddressBar() {
setTimeout( function() {
window.scrollTo( 0, 1 );
}, 10 );
}
/**
* Dispatches an event of the specified type from the
* reveal DOM element.
*/
function dispatchEvent( type, args ) {
var event = document.createEvent( 'HTMLEvents', 1, 2 );
event.initEvent( type, true, true );
extend( event, args );
dom.wrapper.dispatchEvent( event );
// If we're in an iframe, post each reveal.js event to the
// parent window. Used by the notes plugin
if( config.postMessageEvents && window.parent !== window.self ) {
window.parent.postMessage( JSON.stringify({ namespace: 'reveal', eventName: type, state: getState() }), '*' );
}
}
/**
* Wrap all links in 3D goodness.
*/
function enableRollingLinks() {
if( features.transforms3d && !( 'msPerspective' in document.body.style ) ) {
var anchors = dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' a' );
for( var i = 0, len = anchors.length; i < len; i++ ) {
var anchor = anchors[i];
if( anchor.textContent && !anchor.querySelector( '*' ) && ( !anchor.className || !anchor.classList.contains( anchor, 'roll' ) ) ) {
var span = document.createElement('span');
span.setAttribute('data-title', anchor.text);
span.innerHTML = anchor.innerHTML;
anchor.classList.add( 'roll' );
anchor.innerHTML = '';
anchor.appendChild(span);
}
}
}
}
/**
* Unwrap all 3D links.
*/
function disableRollingLinks() {
var anchors = dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' a.roll' );
for( var i = 0, len = anchors.length; i < len; i++ ) {
var anchor = anchors[i];
var span = anchor.querySelector( 'span' );
if( span ) {
anchor.classList.remove( 'roll' );
anchor.innerHTML = span.innerHTML;
}
}
}
/**
* Bind preview frame links.
*/
function enablePreviewLinks( selector ) {
var anchors = toArray( document.querySelectorAll( selector ? selector : 'a' ) );
anchors.forEach( function( element ) {
if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) {
element.addEventListener( 'click', onPreviewLinkClicked, false );
}
} );
}
/**
* Unbind preview frame links.
*/
function disablePreviewLinks() {
var anchors = toArray( document.querySelectorAll( 'a' ) );
anchors.forEach( function( element ) {
if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) {
element.removeEventListener( 'click', onPreviewLinkClicked, false );
}
} );
}
/**
* Opens a preview window for the target URL.
*/
function showPreview( url ) {
closeOverlay();
dom.overlay = document.createElement( 'div' );
dom.overlay.classList.add( 'overlay' );
dom.overlay.classList.add( 'overlay-preview' );
dom.wrapper.appendChild( dom.overlay );
dom.overlay.innerHTML = [
'<header>',
'<a class="close" href="#"><span class="icon"></span></a>',
'<a class="external" href="'+ url +'" target="_blank"><span class="icon"></span></a>',
'</header>',
'<div class="spinner"></div>',
'<div class="viewport">',
'<iframe src="'+ url +'"></iframe>',
'</div>'
].join('');
dom.overlay.querySelector( 'iframe' ).addEventListener( 'load', function( event ) {
dom.overlay.classList.add( 'loaded' );
}, false );
dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) {
closeOverlay();
event.preventDefault();
}, false );
dom.overlay.querySelector( '.external' ).addEventListener( 'click', function( event ) {
closeOverlay();
}, false );
setTimeout( function() {
dom.overlay.classList.add( 'visible' );
}, 1 );
}
/**
* Opens a overlay window with help material.
*/
function showHelp() {
if( config.help ) {
closeOverlay();
dom.overlay = document.createElement( 'div' );
dom.overlay.classList.add( 'overlay' );
dom.overlay.classList.add( 'overlay-help' );
dom.wrapper.appendChild( dom.overlay );
var html = '<p class="title">Keyboard Shortcuts</p><br/>';
html += '<table><th>KEY</th><th>ACTION</th>';
for( var key in keyboardShortcuts ) {
html += '<tr><td>' + key + '</td><td>' + keyboardShortcuts[ key ] + '</td></tr>';
}
html += '</table>';
dom.overlay.innerHTML = [
'<header>',
'<a class="close" href="#"><span class="icon"></span></a>',
'</header>',
'<div class="viewport">',
'<div class="viewport-inner">'+ html +'</div>',
'</div>'
].join('');
dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) {
closeOverlay();
event.preventDefault();
}, false );
setTimeout( function() {
dom.overlay.classList.add( 'visible' );
}, 1 );
}
}
/**
* Closes any currently open overlay.
*/
function closeOverlay() {
if( dom.overlay ) {
dom.overlay.parentNode.removeChild( dom.overlay );
dom.overlay = null;
}
}
/**
* Applies JavaScript-controlled layout rules to the
* presentation.
*/
function layout() {
if( dom.wrapper && !isPrintingPDF() ) {
var size = getComputedSlideSize();
var slidePadding = 20; // TODO Dig this out of DOM
// Layout the contents of the slides
layoutSlideContents( config.width, config.height, slidePadding );
dom.slides.style.width = size.width + 'px';
dom.slides.style.height = size.height + 'px';
// Determine scale of content to fit within available space
scale = Math.min( size.presentationWidth / size.width, size.presentationHeight / size.height );
// Respect max/min scale settings
scale = Math.max( scale, config.minScale );
scale = Math.min( scale, config.maxScale );
// Don't apply any scaling styles if scale is 1
if( scale === 1 ) {
dom.slides.style.zoom = '';
dom.slides.style.left = '';
dom.slides.style.top = '';
dom.slides.style.bottom = '';
dom.slides.style.right = '';
transformSlides( { layout: '' } );
}
else {
// Prefer zoom for scaling up so that content remains crisp.
// Don't use zoom to scale down since that can lead to shifts
// in text layout/line breaks.
if( scale > 1 && features.zoom ) {
dom.slides.style.zoom = scale;
dom.slides.style.left = '';
dom.slides.style.top = '';
dom.slides.style.bottom = '';
dom.slides.style.right = '';
transformSlides( { layout: '' } );
}
// Apply scale transform as a fallback
else {
dom.slides.style.zoom = '';
dom.slides.style.left = '50%';
dom.slides.style.top = '50%';
dom.slides.style.bottom = 'auto';
dom.slides.style.right = 'auto';
transformSlides( { layout: 'translate(-50%, -50%) scale('+ scale +')' } );
}
}
// Select all slides, vertical and horizontal
var slides = toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) );
for( var i = 0, len = slides.length; i < len; i++ ) {
var slide = slides[ i ];
// Don't bother updating invisible slides
if( slide.style.display === 'none' ) {
continue;
}
if( config.center || slide.classList.contains( 'center' ) ) {
// Vertical stacks are not centred since their section
// children will be
if( slide.classList.contains( 'stack' ) ) {
slide.style.top = 0;
}
else {
slide.style.top = Math.max( ( ( size.height - getAbsoluteHeight( slide ) ) / 2 ) - slidePadding, 0 ) + 'px';
}
}
else {
slide.style.top = '';
}
}
updateProgress();
updateParallax();
}
}
/**
* Applies layout logic to the contents of all slides in
* the presentation.
*/
function layoutSlideContents( width, height, padding ) {
// Handle sizing of elements with the 'stretch' class
toArray( dom.slides.querySelectorAll( 'section > .stretch' ) ).forEach( function( element ) {
// Determine how much vertical space we can use
var remainingHeight = getRemainingHeight( element, height );
// Consider the aspect ratio of media elements
if( /(img|video)/gi.test( element.nodeName ) ) {
var nw = element.naturalWidth || element.videoWidth,
nh = element.naturalHeight || element.videoHeight;
var es = Math.min( width / nw, remainingHeight / nh );
element.style.width = ( nw * es ) + 'px';
element.style.height = ( nh * es ) + 'px';
}
else {
element.style.width = width + 'px';
element.style.height = remainingHeight + 'px';
}
} );
}
/**
* Calculates the computed pixel size of our slides. These
* values are based on the width and height configuration
* options.
*/
function getComputedSlideSize( presentationWidth, presentationHeight ) {
var size = {
// Slide size
width: config.width,
height: config.height,
// Presentation size
presentationWidth: presentationWidth || dom.wrapper.offsetWidth,
presentationHeight: presentationHeight || dom.wrapper.offsetHeight
};
// Reduce available space by margin
size.presentationWidth -= ( size.presentationWidth * config.margin );
size.presentationHeight -= ( size.presentationHeight * config.margin );
// Slide width may be a percentage of available width
if( typeof size.width === 'string' && /%$/.test( size.width ) ) {
size.width = parseInt( size.width, 10 ) / 100 * size.presentationWidth;
}
// Slide height may be a percentage of available height
if( typeof size.height === 'string' && /%$/.test( size.height ) ) {
size.height = parseInt( size.height, 10 ) / 100 * size.presentationHeight;
}
return size;
}
/**
* Stores the vertical index of a stack so that the same
* vertical slide can be selected when navigating to and
* from the stack.
*
* @param {HTMLElement} stack The vertical stack element
* @param {int} v Index to memorize
*/
function setPreviousVerticalIndex( stack, v ) {
if( typeof stack === 'object' && typeof stack.setAttribute === 'function' ) {
stack.setAttribute( 'data-previous-indexv', v || 0 );
}
}
/**
* Retrieves the vertical index which was stored using
* #setPreviousVerticalIndex() or 0 if no previous index
* exists.
*
* @param {HTMLElement} stack The vertical stack element
*/
function getPreviousVerticalIndex( stack ) {
if( typeof stack === 'object' && typeof stack.setAttribute === 'function' && stack.classList.contains( 'stack' ) ) {
// Prefer manually defined start-indexv
var attributeName = stack.hasAttribute( 'data-start-indexv' ) ? 'data-start-indexv' : 'data-previous-indexv';
return parseInt( stack.getAttribute( attributeName ) || 0, 10 );
}
return 0;
}
/**
* Displays the overview of slides (quick nav) by scaling
* down and arranging all slide elements.
*/
function activateOverview() {
// Only proceed if enabled in config
if( config.overview && !isOverview() ) {
overview = true;
dom.wrapper.classList.add( 'overview' );
dom.wrapper.classList.remove( 'overview-deactivating' );
if( features.overviewTransitions ) {
setTimeout( function() {
dom.wrapper.classList.add( 'overview-animated' );
}, 1 );
}
// Don't auto-slide while in overview mode
cancelAutoSlide();
// Move the backgrounds element into the slide container to
// that the same scaling is applied
dom.slides.appendChild( dom.background );
// Clicking on an overview slide navigates to it
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) {
if( !slide.classList.contains( 'stack' ) ) {
slide.addEventListener( 'click', onOverviewSlideClicked, true );
}
} );
// Calculate slide sizes
var margin = 70;
var slideSize = getComputedSlideSize();
overviewSlideWidth = slideSize.width + margin;
overviewSlideHeight = slideSize.height + margin;
// Reverse in RTL mode
if( config.rtl ) {
overviewSlideWidth = -overviewSlideWidth;
}
updateSlidesVisibility();
layoutOverview();
updateOverview();
layout();
// Notify observers of the overview showing
dispatchEvent( 'overviewshown', {
'indexh': indexh,
'indexv': indexv,
'currentSlide': currentSlide
} );
}
}
/**
* Uses CSS transforms to position all slides in a grid for
* display inside of the overview mode.
*/
function layoutOverview() {
// Layout slides
toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) {
hslide.setAttribute( 'data-index-h', h );
transformElement( hslide, 'translate3d(' + ( h * overviewSlideWidth ) + 'px, 0, 0)' );
if( hslide.classList.contains( 'stack' ) ) {
toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) {
vslide.setAttribute( 'data-index-h', h );
vslide.setAttribute( 'data-index-v', v );
transformElement( vslide, 'translate3d(0, ' + ( v * overviewSlideHeight ) + 'px, 0)' );
} );
}
} );
// Layout slide backgrounds
toArray( dom.background.childNodes ).forEach( function( hbackground, h ) {
transformElement( hbackground, 'translate3d(' + ( h * overviewSlideWidth ) + 'px, 0, 0)' );
toArray( hbackground.querySelectorAll( '.slide-background' ) ).forEach( function( vbackground, v ) {
transformElement( vbackground, 'translate3d(0, ' + ( v * overviewSlideHeight ) + 'px, 0)' );
} );
} );
}
/**
* Moves the overview viewport to the current slides.
* Called each time the current slide changes.
*/
function updateOverview() {
transformSlides( {
overview: [
'translateX('+ ( -indexh * overviewSlideWidth ) +'px)',
'translateY('+ ( -indexv * overviewSlideHeight ) +'px)',
'translateZ('+ ( window.innerWidth < 400 ? -1000 : -2500 ) +'px)'
].join( ' ' )
} );
}
/**
* Exits the slide overview and enters the currently
* active slide.
*/
function deactivateOverview() {
// Only proceed if enabled in config
if( config.overview ) {
overview = false;
dom.wrapper.classList.remove( 'overview' );
dom.wrapper.classList.remove( 'overview-animated' );
// Temporarily add a class so that transitions can do different things
// depending on whether they are exiting/entering overview, or just
// moving from slide to slide
dom.wrapper.classList.add( 'overview-deactivating' );
setTimeout( function () {
dom.wrapper.classList.remove( 'overview-deactivating' );
}, 1 );
// Move the background element back out
dom.wrapper.appendChild( dom.background );
// Clean up changes made to slides
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) {
transformElement( slide, '' );
slide.removeEventListener( 'click', onOverviewSlideClicked, true );
} );
// Clean up changes made to backgrounds
toArray( dom.background.querySelectorAll( '.slide-background' ) ).forEach( function( background ) {
transformElement( background, '' );
} );
transformSlides( { overview: '' } );
slide( indexh, indexv );
layout();
cueAutoSlide();
// Notify observers of the overview hiding
dispatchEvent( 'overviewhidden', {
'indexh': indexh,
'indexv': indexv,
'currentSlide': currentSlide
} );
}
}
/**
* Toggles the slide overview mode on and off.
*
* @param {Boolean} override Optional flag which overrides the
* toggle logic and forcibly sets the desired state. True means
* overview is open, false means it's closed.
*/
function toggleOverview( override ) {
if( typeof override === 'boolean' ) {
override ? activateOverview() : deactivateOverview();
}
else {
isOverview() ? deactivateOverview() : activateOverview();
}
}
/**
* Checks if the overview is currently active.
*
* @return {Boolean} true if the overview is active,
* false otherwise
*/
function isOverview() {
return overview;
}
/**
* Checks if the current or specified slide is vertical
* (nested within another slide).
*
* @param {HTMLElement} slide [optional] The slide to check
* orientation of
*/
function isVerticalSlide( slide ) {
// Prefer slide argument, otherwise use current slide
slide = slide ? slide : currentSlide;
return slide && slide.parentNode && !!slide.parentNode.nodeName.match( /section/i );
}
/**
* Handling the fullscreen functionality via the fullscreen API
*
* @see http://fullscreen.spec.whatwg.org/
* @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode
*/
function enterFullscreen() {
var element = document.body;
// Check which implementation is available
var requestMethod = element.requestFullScreen ||
element.webkitRequestFullscreen ||
element.webkitRequestFullScreen ||
element.mozRequestFullScreen ||
element.msRequestFullscreen;
if( requestMethod ) {
requestMethod.apply( element );
}
}
/**
* Enters the paused mode which fades everything on screen to
* black.
*/
function pause() {
if( config.pause ) {
var wasPaused = dom.wrapper.classList.contains( 'paused' );
cancelAutoSlide();
dom.wrapper.classList.add( 'paused' );
if( wasPaused === false ) {
dispatchEvent( 'paused' );
}
}
}
/**
* Exits from the paused mode.
*/
function resume() {
var wasPaused = dom.wrapper.classList.contains( 'paused' );
dom.wrapper.classList.remove( 'paused' );
cueAutoSlide();
if( wasPaused ) {
dispatchEvent( 'resumed' );
}
}
/**
* Toggles the paused mode on and off.
*/
function togglePause( override ) {
if( typeof override === 'boolean' ) {
override ? pause() : resume();
}
else {
isPaused() ? resume() : pause();
}
}
/**
* Checks if we are currently in the paused mode.
*/
function isPaused() {
return dom.wrapper.classList.contains( 'paused' );
}
/**
* Toggles the auto slide mode on and off.
*
* @param {Boolean} override Optional flag which sets the desired state.
* True means autoplay starts, false means it stops.
*/
function toggleAutoSlide( override ) {
if( typeof override === 'boolean' ) {
override ? resumeAutoSlide() : pauseAutoSlide();
}
else {
autoSlidePaused ? resumeAutoSlide() : pauseAutoSlide();
}
}
/**
* Checks if the auto slide mode is currently on.
*/
function isAutoSliding() {
return !!( autoSlide && !autoSlidePaused );
}
/**
* Steps from the current point in the presentation to the
* slide which matches the specified horizontal and vertical
* indices.
*
* @param {int} h Horizontal index of the target slide
* @param {int} v Vertical index of the target slide
* @param {int} f Optional index of a fragment within the
* target slide to activate
* @param {int} o Optional origin for use in multimaster environments
*/
function slide( h, v, f, o ) {
// Remember where we were at before
previousSlide = currentSlide;
// Query all horizontal slides in the deck
var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
// If no vertical index is specified and the upcoming slide is a
// stack, resume at its previous vertical index
if( v === undefined && !isOverview() ) {
v = getPreviousVerticalIndex( horizontalSlides[ h ] );
}
// If we were on a vertical stack, remember what vertical index
// it was on so we can resume at the same position when returning
if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) {
setPreviousVerticalIndex( previousSlide.parentNode, indexv );
}
// Remember the state before this slide
var stateBefore = state.concat();
// Reset the state array
state.length = 0;
var indexhBefore = indexh || 0,
indexvBefore = indexv || 0;
// Activate and transition to the new slide
indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h );
indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v );
// Update the visibility of slides now that the indices have changed
updateSlidesVisibility();
layout();
// Apply the new state
stateLoop: for( var i = 0, len = state.length; i < len; i++ ) {
// Check if this state existed on the previous slide. If it
// did, we will avoid adding it repeatedly
for( var j = 0; j < stateBefore.length; j++ ) {
if( stateBefore[j] === state[i] ) {
stateBefore.splice( j, 1 );
continue stateLoop;
}
}
document.documentElement.classList.add( state[i] );
// Dispatch custom event matching the state's name
dispatchEvent( state[i] );
}
// Clean up the remains of the previous state
while( stateBefore.length ) {
document.documentElement.classList.remove( stateBefore.pop() );
}
// Update the overview if it's currently active
if( isOverview() ) {
updateOverview();
}
// Find the current horizontal slide and any possible vertical slides
// within it
var currentHorizontalSlide = horizontalSlides[ indexh ],
currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' );
// Store references to the previous and current slides
currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide;
// Show fragment, if specified
if( typeof f !== 'undefined' ) {
navigateFragment( f );
}
// Dispatch an event if the slide changed
var slideChanged = ( indexh !== indexhBefore || indexv !== indexvBefore );
if( slideChanged ) {
dispatchEvent( 'slidechanged', {
'indexh': indexh,
'indexv': indexv,
'previousSlide': previousSlide,
'currentSlide': currentSlide,
'origin': o
} );
}
else {
// Ensure that the previous slide is never the same as the current
previousSlide = null;
}
// Solves an edge case where the previous slide maintains the
// 'present' class when navigating between adjacent vertical
// stacks
if( previousSlide ) {
previousSlide.classList.remove( 'present' );
previousSlide.setAttribute( 'aria-hidden', 'true' );
// Reset all slides upon navigate to home
// Issue: #285
if ( dom.wrapper.querySelector( HOME_SLIDE_SELECTOR ).classList.contains( 'present' ) ) {
// Launch async task
setTimeout( function () {
var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.stack') ), i;
for( i in slides ) {
if( slides[i] ) {
// Reset stack
setPreviousVerticalIndex( slides[i], 0 );
}
}
}, 0 );
}
}
// Handle embedded content
if( slideChanged || !previousSlide ) {
stopEmbeddedContent( previousSlide );
startEmbeddedContent( currentSlide );
}
// Announce the current slide contents, for screen readers
dom.statusDiv.textContent = currentSlide.textContent;
updateControls();
updateProgress();
updateBackground();
updateParallax();
updateSlideNumber();
updateNotes();
// Update the URL hash
writeURL();
cueAutoSlide();
}
/**
* Syncs the presentation with the current DOM. Useful
* when new slides or control elements are added or when
* the configuration has changed.
*/
function sync() {
// Subscribe to input
removeEventListeners();
addEventListeners();
// Force a layout to make sure the current config is accounted for
layout();
// Reflect the current autoSlide value
autoSlide = config.autoSlide;
// Start auto-sliding if it's enabled
cueAutoSlide();
// Re-create the slide backgrounds
createBackgrounds();
// Write the current hash to the URL
writeURL();
sortAllFragments();
updateControls();
updateProgress();
updateBackground( true );
updateSlideNumber();
updateSlidesVisibility();
updateNotes();
formatEmbeddedContent();
startEmbeddedContent( currentSlide );
if( isOverview() ) {
layoutOverview();
}
}
/**
* Resets all vertical slides so that only the first
* is visible.
*/
function resetVerticalSlides() {
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
horizontalSlides.forEach( function( horizontalSlide ) {
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
verticalSlides.forEach( function( verticalSlide, y ) {
if( y > 0 ) {
verticalSlide.classList.remove( 'present' );
verticalSlide.classList.remove( 'past' );
verticalSlide.classList.add( 'future' );
verticalSlide.setAttribute( 'aria-hidden', 'true' );
}
} );
} );
}
/**
* Sorts and formats all of fragments in the
* presentation.
*/
function sortAllFragments() {
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
horizontalSlides.forEach( function( horizontalSlide ) {
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
verticalSlides.forEach( function( verticalSlide, y ) {
sortFragments( verticalSlide.querySelectorAll( '.fragment' ) );
} );
if( verticalSlides.length === 0 ) sortFragments( horizontalSlide.querySelectorAll( '.fragment' ) );
} );
}
/**
* Randomly shuffles all slides in the deck.
*/
function shuffle() {
var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
slides.forEach( function( slide ) {
// Insert this slide next to another random slide. This may
// cause the slide to insert before itself but that's fine.
dom.slides.insertBefore( slide, slides[ Math.floor( Math.random() * slides.length ) ] );
} );
}
/**
* Updates one dimension of slides by showing the slide
* with the specified index.
*
* @param {String} selector A CSS selector that will fetch
* the group of slides we are working with
* @param {Number} index The index of the slide that should be
* shown
*
* @return {Number} The index of the slide that is now shown,
* might differ from the passed in index if it was out of
* bounds.
*/
function updateSlides( selector, index ) {
// Select all slides and convert the NodeList result to
// an array
var slides = toArray( dom.wrapper.querySelectorAll( selector ) ),
slidesLength = slides.length;
var printMode = isPrintingPDF();
if( slidesLength ) {
// Should the index loop?
if( config.loop ) {
index %= slidesLength;
if( index < 0 ) {
index = slidesLength + index;
}
}
// Enforce max and minimum index bounds
index = Math.max( Math.min( index, slidesLength - 1 ), 0 );
for( var i = 0; i < slidesLength; i++ ) {
var element = slides[i];
var reverse = config.rtl && !isVerticalSlide( element );
element.classList.remove( 'past' );
element.classList.remove( 'present' );
element.classList.remove( 'future' );
// http://www.w3.org/html/wg/drafts/html/master/editing.html#the-hidden-attribute
element.setAttribute( 'hidden', '' );
element.setAttribute( 'aria-hidden', 'true' );
// If this element contains vertical slides
if( element.querySelector( 'section' ) ) {
element.classList.add( 'stack' );
}
// If we're printing static slides, all slides are "present"
if( printMode ) {
element.classList.add( 'present' );
continue;
}
if( i < index ) {
// Any element previous to index is given the 'past' class
element.classList.add( reverse ? 'future' : 'past' );
if( config.fragments ) {
var pastFragments = toArray( element.querySelectorAll( '.fragment' ) );
// Show all fragments on prior slides
while( pastFragments.length ) {
var pastFragment = pastFragments.pop();
pastFragment.classList.add( 'visible' );
pastFragment.classList.remove( 'current-fragment' );
}
}
}
else if( i > index ) {
// Any element subsequent to index is given the 'future' class
element.classList.add( reverse ? 'past' : 'future' );
if( config.fragments ) {
var futureFragments = toArray( element.querySelectorAll( '.fragment.visible' ) );
// No fragments in future slides should be visible ahead of time
while( futureFragments.length ) {
var futureFragment = futureFragments.pop();
futureFragment.classList.remove( 'visible' );
futureFragment.classList.remove( 'current-fragment' );
}
}
}
}
// Mark the current slide as present
slides[index].classList.add( 'present' );
slides[index].removeAttribute( 'hidden' );
slides[index].removeAttribute( 'aria-hidden' );
// If this slide has a state associated with it, add it
// onto the current state of the deck
var slideState = slides[index].getAttribute( 'data-state' );
if( slideState ) {
state = state.concat( slideState.split( ' ' ) );
}
}
else {
// Since there are no slides we can't be anywhere beyond the
// zeroth index
index = 0;
}
return index;
}
/**
* Optimization method; hide all slides that are far away
* from the present slide.
*/
function updateSlidesVisibility() {
// Select all slides and convert the NodeList result to
// an array
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ),
horizontalSlidesLength = horizontalSlides.length,
distanceX,
distanceY;
if( horizontalSlidesLength && typeof indexh !== 'undefined' ) {
// The number of steps away from the present slide that will
// be visible
var viewDistance = isOverview() ? 10 : config.viewDistance;
// Limit view distance on weaker devices
if( isMobileDevice ) {
viewDistance = isOverview() ? 6 : 2;
}
// All slides need to be visible when exporting to PDF
if( isPrintingPDF() ) {
viewDistance = Number.MAX_VALUE;
}
for( var x = 0; x < horizontalSlidesLength; x++ ) {
var horizontalSlide = horizontalSlides[x];
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ),
verticalSlidesLength = verticalSlides.length;
// Determine how far away this slide is from the present
distanceX = Math.abs( ( indexh || 0 ) - x ) || 0;
// If the presentation is looped, distance should measure
// 1 between the first and last slides
if( config.loop ) {
distanceX = Math.abs( ( ( indexh || 0 ) - x ) % ( horizontalSlidesLength - viewDistance ) ) || 0;
}
// Show the horizontal slide if it's within the view distance
if( distanceX < viewDistance ) {
showSlide( horizontalSlide );
}
else {
hideSlide( horizontalSlide );
}
if( verticalSlidesLength ) {
var oy = getPreviousVerticalIndex( horizontalSlide );
for( var y = 0; y < verticalSlidesLength; y++ ) {
var verticalSlide = verticalSlides[y];
distanceY = x === ( indexh || 0 ) ? Math.abs( ( indexv || 0 ) - y ) : Math.abs( y - oy );
if( distanceX + distanceY < viewDistance ) {
showSlide( verticalSlide );
}
else {
hideSlide( verticalSlide );
}
}
}
}
}
}
/**
* Pick up notes from the current slide and display tham
* to the viewer.
*
* @see `showNotes` config value
*/
function updateNotes() {
if( config.showNotes && dom.speakerNotes && currentSlide && !isPrintingPDF() ) {
dom.speakerNotes.innerHTML = getSlideNotes() || '';
}
}
/**
* Updates the progress bar to reflect the current slide.
*/
function updateProgress() {
// Update progress if enabled
if( config.progress && dom.progressbar ) {
dom.progressbar.style.width = getProgress() * dom.wrapper.offsetWidth + 'px';
}
}
/**
* Updates the slide number div to reflect the current slide.
*
* The following slide number formats are available:
* "h.v": horizontal . vertical slide number (default)
* "h/v": horizontal / vertical slide number
* "c": flattened slide number
* "c/t": flattened slide number / total slides
*/
function updateSlideNumber() {
// Update slide number if enabled
if( config.slideNumber && dom.slideNumber ) {
var value = [];
var format = 'h.v';
// Check if a custom number format is available
if( typeof config.slideNumber === 'string' ) {
format = config.slideNumber;
}
switch( format ) {
case 'c':
value.push( getSlidePastCount() + 1 );
break;
case 'c/t':
value.push( getSlidePastCount() + 1, '/', getTotalSlides() );
break;
case 'h/v':
value.push( indexh + 1 );
if( isVerticalSlide() ) value.push( '/', indexv + 1 );
break;
default:
value.push( indexh + 1 );
if( isVerticalSlide() ) value.push( '.', indexv + 1 );
}
dom.slideNumber.innerHTML = formatSlideNumber( value[0], value[1], value[2] );
}
}
/**
* Applies HTML formatting to a slide number before it's
* written to the DOM.
*/
function formatSlideNumber( a, delimiter, b ) {
if( typeof b === 'number' && !isNaN( b ) ) {
return '<span class="slide-number-a">'+ a +'</span>' +
'<span class="slide-number-delimiter">'+ delimiter +'</span>' +
'<span class="slide-number-b">'+ b +'</span>';
}
else {
return '<span class="slide-number-a">'+ a +'</span>';
}
}
/**
* Updates the state of all control/navigation arrows.
*/
function updateControls() {
var routes = availableRoutes();
var fragments = availableFragments();
// Remove the 'enabled' class from all directions
dom.controlsLeft.concat( dom.controlsRight )
.concat( dom.controlsUp )
.concat( dom.controlsDown )
.concat( dom.controlsPrev )
.concat( dom.controlsNext ).forEach( function( node ) {
node.classList.remove( 'enabled' );
node.classList.remove( 'fragmented' );
} );
// Add the 'enabled' class to the available routes
if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' ); } );
if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } );
if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } );
if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } );
// Prev/next buttons
if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } );
if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } );
// Highlight fragment directions
if( currentSlide ) {
// Always apply fragment decorator to prev/next buttons
if( fragments.prev ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
if( fragments.next ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
// Apply fragment decorators to directional buttons based on
// what slide axis they are in
if( isVerticalSlide( currentSlide ) ) {
if( fragments.prev ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
if( fragments.next ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
}
else {
if( fragments.prev ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
if( fragments.next ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
}
}
}
/**
* Updates the background elements to reflect the current
* slide.
*
* @param {Boolean} includeAll If true, the backgrounds of
* all vertical slides (not just the present) will be updated.
*/
function updateBackground( includeAll ) {
var currentBackground = null;
// Reverse past/future classes when in RTL mode
var horizontalPast = config.rtl ? 'future' : 'past',
horizontalFuture = config.rtl ? 'past' : 'future';
// Update the classes of all backgrounds to match the
// states of their slides (past/present/future)
toArray( dom.background.childNodes ).forEach( function( backgroundh, h ) {
backgroundh.classList.remove( 'past' );
backgroundh.classList.remove( 'present' );
backgroundh.classList.remove( 'future' );
if( h < indexh ) {
backgroundh.classList.add( horizontalPast );
}
else if ( h > indexh ) {
backgroundh.classList.add( horizontalFuture );
}
else {
backgroundh.classList.add( 'present' );
// Store a reference to the current background element
currentBackground = backgroundh;
}
if( includeAll || h === indexh ) {
toArray( backgroundh.querySelectorAll( '.slide-background' ) ).forEach( function( backgroundv, v ) {
backgroundv.classList.remove( 'past' );
backgroundv.classList.remove( 'present' );
backgroundv.classList.remove( 'future' );
if( v < indexv ) {
backgroundv.classList.add( 'past' );
}
else if ( v > indexv ) {
backgroundv.classList.add( 'future' );
}
else {
backgroundv.classList.add( 'present' );
// Only if this is the present horizontal and vertical slide
if( h === indexh ) currentBackground = backgroundv;
}
} );
}
} );
// Stop any currently playing video background
if( previousBackground ) {
var previousVideo = previousBackground.querySelector( 'video' );
if( previousVideo ) previousVideo.pause();
}
if( currentBackground ) {
// Start video playback
var currentVideo = currentBackground.querySelector( 'video' );
if( currentVideo ) {
var startVideo = function() {
currentVideo.currentTime = 0;
currentVideo.play();
currentVideo.removeEventListener( 'loadeddata', startVideo );
};
if( currentVideo.readyState > 1 ) {
startVideo();
}
else {
currentVideo.addEventListener( 'loadeddata', startVideo );
}
}
var backgroundImageURL = currentBackground.style.backgroundImage || '';
// Restart GIFs (doesn't work in Firefox)
if( /\.gif/i.test( backgroundImageURL ) ) {
currentBackground.style.backgroundImage = '';
window.getComputedStyle( currentBackground ).opacity;
currentBackground.style.backgroundImage = backgroundImageURL;
}
// Don't transition between identical backgrounds. This
// prevents unwanted flicker.
var previousBackgroundHash = previousBackground ? previousBackground.getAttribute( 'data-background-hash' ) : null;
var currentBackgroundHash = currentBackground.getAttribute( 'data-background-hash' );
if( currentBackgroundHash && currentBackgroundHash === previousBackgroundHash && currentBackground !== previousBackground ) {
dom.background.classList.add( 'no-transition' );
}
previousBackground = currentBackground;
}
// If there's a background brightness flag for this slide,
// bubble it to the .reveal container
if( currentSlide ) {
[ 'has-light-background', 'has-dark-background' ].forEach( function( classToBubble ) {
if( currentSlide.classList.contains( classToBubble ) ) {
dom.wrapper.classList.add( classToBubble );
}
else {
dom.wrapper.classList.remove( classToBubble );
}
} );
}
// Allow the first background to apply without transition
setTimeout( function() {
dom.background.classList.remove( 'no-transition' );
}, 1 );
}
/**
* Updates the position of the parallax background based
* on the current slide index.
*/
function updateParallax() {
if( config.parallaxBackgroundImage ) {
var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
var backgroundSize = dom.background.style.backgroundSize.split( ' ' ),
backgroundWidth, backgroundHeight;
if( backgroundSize.length === 1 ) {
backgroundWidth = backgroundHeight = parseInt( backgroundSize[0], 10 );
}
else {
backgroundWidth = parseInt( backgroundSize[0], 10 );
backgroundHeight = parseInt( backgroundSize[1], 10 );
}
var slideWidth = dom.background.offsetWidth,
horizontalSlideCount = horizontalSlides.length,
horizontalOffsetMultiplier,
horizontalOffset;
if( typeof config.parallaxBackgroundHorizontal === 'number' ) {
horizontalOffsetMultiplier = config.parallaxBackgroundHorizontal;
}
else {
horizontalOffsetMultiplier = horizontalSlideCount > 1 ? ( backgroundWidth - slideWidth ) / ( horizontalSlideCount-1 ) : 0;
}
horizontalOffset = horizontalOffsetMultiplier * indexh * -1;
var slideHeight = dom.background.offsetHeight,
verticalSlideCount = verticalSlides.length,
verticalOffsetMultiplier,
verticalOffset;
if( typeof config.parallaxBackgroundVertical === 'number' ) {
verticalOffsetMultiplier = config.parallaxBackgroundVertical;
}
else {
verticalOffsetMultiplier = ( backgroundHeight - slideHeight ) / ( verticalSlideCount-1 );
}
verticalOffset = verticalSlideCount > 0 ? verticalOffsetMultiplier * indexv * 1 : 0;
dom.background.style.backgroundPosition = horizontalOffset + 'px ' + -verticalOffset + 'px';
}
}
/**
* Called when the given slide is within the configured view
* distance. Shows the slide element and loads any content
* that is set to load lazily (data-src).
*/
function showSlide( slide ) {
// Show the slide element
slide.style.display = 'block';
// Media elements with data-src attributes
toArray( slide.querySelectorAll( 'img[data-src], video[data-src], audio[data-src]' ) ).forEach( function( element ) {
element.setAttribute( 'src', element.getAttribute( 'data-src' ) );
element.removeAttribute( 'data-src' );
} );
// Media elements with <source> children
toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( media ) {
var sources = 0;
toArray( media.querySelectorAll( 'source[data-src]' ) ).forEach( function( source ) {
source.setAttribute( 'src', source.getAttribute( 'data-src' ) );
source.removeAttribute( 'data-src' );
sources += 1;
} );
// If we rewrote sources for this video/audio element, we need
// to manually tell it to load from its new origin
if( sources > 0 ) {
media.load();
}
} );
// Show the corresponding background element
var indices = getIndices( slide );
var background = getSlideBackground( indices.h, indices.v );
if( background ) {
background.style.display = 'block';
// If the background contains media, load it
if( background.hasAttribute( 'data-loaded' ) === false ) {
background.setAttribute( 'data-loaded', 'true' );
var backgroundImage = slide.getAttribute( 'data-background-image' ),
backgroundVideo = slide.getAttribute( 'data-background-video' ),
backgroundVideoLoop = slide.hasAttribute( 'data-background-video-loop' ),
backgroundVideoMuted = slide.hasAttribute( 'data-background-video-muted' ),
backgroundIframe = slide.getAttribute( 'data-background-iframe' );
// Images
if( backgroundImage ) {
background.style.backgroundImage = 'url('+ backgroundImage +')';
}
// Videos
else if ( backgroundVideo && !isSpeakerNotes() ) {
var video = document.createElement( 'video' );
if( backgroundVideoLoop ) {
video.setAttribute( 'loop', '' );
}
if( backgroundVideoMuted ) {
video.muted = true;
}
// Support comma separated lists of video sources
backgroundVideo.split( ',' ).forEach( function( source ) {
video.innerHTML += '<source src="'+ source +'">';
} );
background.appendChild( video );
}
// Iframes
else if( backgroundIframe ) {
var iframe = document.createElement( 'iframe' );
iframe.setAttribute( 'src', backgroundIframe );
iframe.style.width = '100%';
iframe.style.height = '100%';
iframe.style.maxHeight = '100%';
iframe.style.maxWidth = '100%';
background.appendChild( iframe );
}
}
}
}
/**
* Called when the given slide is moved outside of the
* configured view distance.
*/
function hideSlide( slide ) {
// Hide the slide element
slide.style.display = 'none';
// Hide the corresponding background element
var indices = getIndices( slide );
var background = getSlideBackground( indices.h, indices.v );
if( background ) {
background.style.display = 'none';
}
}
/**
* Determine what available routes there are for navigation.
*
* @return {Object} containing four booleans: left/right/up/down
*/
function availableRoutes() {
var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
var routes = {
left: indexh > 0 || config.loop,
right: indexh < horizontalSlides.length - 1 || config.loop,
up: indexv > 0,
down: indexv < verticalSlides.length - 1
};
// reverse horizontal controls for rtl
if( config.rtl ) {
var left = routes.left;
routes.left = routes.right;
routes.right = left;
}
return routes;
}
/**
* Returns an object describing the available fragment
* directions.
*
* @return {Object} two boolean properties: prev/next
*/
function availableFragments() {
if( currentSlide && config.fragments ) {
var fragments = currentSlide.querySelectorAll( '.fragment' );
var hiddenFragments = currentSlide.querySelectorAll( '.fragment:not(.visible)' );
return {
prev: fragments.length - hiddenFragments.length > 0,
next: !!hiddenFragments.length
};
}
else {
return { prev: false, next: false };
}
}
/**
* Enforces origin-specific format rules for embedded media.
*/
function formatEmbeddedContent() {
var _appendParamToIframeSource = function( sourceAttribute, sourceURL, param ) {
toArray( dom.slides.querySelectorAll( 'iframe['+ sourceAttribute +'*="'+ sourceURL +'"]' ) ).forEach( function( el ) {
var src = el.getAttribute( sourceAttribute );
if( src && src.indexOf( param ) === -1 ) {
el.setAttribute( sourceAttribute, src + ( !/\?/.test( src ) ? '?' : '&' ) + param );
}
});
};
// YouTube frames must include "?enablejsapi=1"
_appendParamToIframeSource( 'src', 'youtube.com/embed/', 'enablejsapi=1' );
_appendParamToIframeSource( 'data-src', 'youtube.com/embed/', 'enablejsapi=1' );
// Vimeo frames must include "?api=1"
_appendParamToIframeSource( 'src', 'player.vimeo.com/', 'api=1' );
_appendParamToIframeSource( 'data-src', 'player.vimeo.com/', 'api=1' );
}
/**
* Start playback of any embedded content inside of
* the targeted slide.
*/
function startEmbeddedContent( slide ) {
if( slide && !isSpeakerNotes() ) {
// Restart GIFs
toArray( slide.querySelectorAll( 'img[src$=".gif"]' ) ).forEach( function( el ) {
// Setting the same unchanged source like this was confirmed
// to work in Chrome, FF & Safari
el.setAttribute( 'src', el.getAttribute( 'src' ) );
} );
// HTML5 media elements
toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
if( el.hasAttribute( 'data-autoplay' ) && typeof el.play === 'function' ) {
el.play();
}
} );
// Normal iframes
toArray( slide.querySelectorAll( 'iframe[src]' ) ).forEach( function( el ) {
startEmbeddedIframe( { target: el } );
} );
// Lazy loading iframes
toArray( slide.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) {
if( el.getAttribute( 'src' ) !== el.getAttribute( 'data-src' ) ) {
el.removeEventListener( 'load', startEmbeddedIframe ); // remove first to avoid dupes
el.addEventListener( 'load', startEmbeddedIframe );
el.setAttribute( 'src', el.getAttribute( 'data-src' ) );
}
} );
}
}
/**
* "Starts" the content of an embedded iframe using the
* postmessage API.
*/
function startEmbeddedIframe( event ) {
var iframe = event.target;
// YouTube postMessage API
if( /youtube\.com\/embed\//.test( iframe.getAttribute( 'src' ) ) && iframe.hasAttribute( 'data-autoplay' ) ) {
iframe.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' );
}
// Vimeo postMessage API
else if( /player\.vimeo\.com\//.test( iframe.getAttribute( 'src' ) ) && iframe.hasAttribute( 'data-autoplay' ) ) {
iframe.contentWindow.postMessage( '{"method":"play"}', '*' );
}
// Generic postMessage API
else {
iframe.contentWindow.postMessage( 'slide:start', '*' );
}
}
/**
* Stop playback of any embedded content inside of
* the targeted slide.
*/
function stopEmbeddedContent( slide ) {
if( slide && slide.parentNode ) {
// HTML5 media elements
toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
if( !el.hasAttribute( 'data-ignore' ) && typeof el.pause === 'function' ) {
el.pause();
}
} );
// Generic postMessage API for non-lazy loaded iframes
toArray( slide.querySelectorAll( 'iframe' ) ).forEach( function( el ) {
el.contentWindow.postMessage( 'slide:stop', '*' );
el.removeEventListener( 'load', startEmbeddedIframe );
});
// YouTube postMessage API
toArray( slide.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) {
if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) {
el.contentWindow.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' );
}
});
// Vimeo postMessage API
toArray( slide.querySelectorAll( 'iframe[src*="player.vimeo.com/"]' ) ).forEach( function( el ) {
if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) {
el.contentWindow.postMessage( '{"method":"pause"}', '*' );
}
});
// Lazy loading iframes
toArray( slide.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) {
// Only removing the src doesn't actually unload the frame
// in all browsers (Firefox) so we set it to blank first
el.setAttribute( 'src', 'about:blank' );
el.removeAttribute( 'src' );
} );
}
}
/**
* Returns the number of past slides. This can be used as a global
* flattened index for slides.
*/
function getSlidePastCount() {
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
// The number of past slides
var pastCount = 0;
// Step through all slides and count the past ones
mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) {
var horizontalSlide = horizontalSlides[i];
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
for( var j = 0; j < verticalSlides.length; j++ ) {
// Stop as soon as we arrive at the present
if( verticalSlides[j].classList.contains( 'present' ) ) {
break mainLoop;
}
pastCount++;
}
// Stop as soon as we arrive at the present
if( horizontalSlide.classList.contains( 'present' ) ) {
break;
}
// Don't count the wrapping section for vertical slides
if( horizontalSlide.classList.contains( 'stack' ) === false ) {
pastCount++;
}
}
return pastCount;
}
/**
* Returns a value ranging from 0-1 that represents
* how far into the presentation we have navigated.
*/
function getProgress() {
// The number of past and total slides
var totalCount = getTotalSlides();
var pastCount = getSlidePastCount();
if( currentSlide ) {
var allFragments = currentSlide.querySelectorAll( '.fragment' );
// If there are fragments in the current slide those should be
// accounted for in the progress.
if( allFragments.length > 0 ) {
var visibleFragments = currentSlide.querySelectorAll( '.fragment.visible' );
// This value represents how big a portion of the slide progress
// that is made up by its fragments (0-1)
var fragmentWeight = 0.9;
// Add fragment progress to the past slide count
pastCount += ( visibleFragments.length / allFragments.length ) * fragmentWeight;
}
}
return pastCount / ( totalCount - 1 );
}
/**
* Checks if this presentation is running inside of the
* speaker notes window.
*/
function isSpeakerNotes() {
return !!window.location.search.match( /receiver/gi );
}
/**
* Reads the current URL (hash) and navigates accordingly.
*/
function readURL() {
var hash = window.location.hash;
// Attempt to parse the hash as either an index or name
var bits = hash.slice( 2 ).split( '/' ),
name = hash.replace( /#|\//gi, '' );
// If the first bit is invalid and there is a name we can
// assume that this is a named link
if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) {
var element;
// Ensure the named link is a valid HTML ID attribute
if( /^[a-zA-Z][\w:.-]*$/.test( name ) ) {
// Find the slide with the specified ID
element = document.getElementById( name );
}
if( element ) {
// Find the position of the named slide and navigate to it
var indices = Reveal.getIndices( element );
slide( indices.h, indices.v );
}
// If the slide doesn't exist, navigate to the current slide
else {
slide( indexh || 0, indexv || 0 );
}
}
else {
// Read the index components of the hash
var h = parseInt( bits[0], 10 ) || 0,
v = parseInt( bits[1], 10 ) || 0;
if( h !== indexh || v !== indexv ) {
slide( h, v );
}
}
}
/**
* Updates the page URL (hash) to reflect the current
* state.
*
* @param {Number} delay The time in ms to wait before
* writing the hash
*/
function writeURL( delay ) {
if( config.history ) {
// Make sure there's never more than one timeout running
clearTimeout( writeURLTimeout );
// If a delay is specified, timeout this call
if( typeof delay === 'number' ) {
writeURLTimeout = setTimeout( writeURL, delay );
}
else if( currentSlide ) {
var url = '/';
// Attempt to create a named link based on the slide's ID
var id = currentSlide.getAttribute( 'id' );
if( id ) {
id = id.replace( /[^a-zA-Z0-9\-\_\:\.]/g, '' );
}
// If the current slide has an ID, use that as a named link
if( typeof id === 'string' && id.length ) {
url = '/' + id;
}
// Otherwise use the /h/v index
else {
if( indexh > 0 || indexv > 0 ) url += indexh;
if( indexv > 0 ) url += '/' + indexv;
}
window.location.hash = url;
}
}
}
/**
* Retrieves the h/v location of the current, or specified,
* slide.
*
* @param {HTMLElement} slide If specified, the returned
* index will be for this slide rather than the currently
* active one
*
* @return {Object} { h: <int>, v: <int>, f: <int> }
*/
function getIndices( slide ) {
// By default, return the current indices
var h = indexh,
v = indexv,
f;
// If a slide is specified, return the indices of that slide
if( slide ) {
var isVertical = isVerticalSlide( slide );
var slideh = isVertical ? slide.parentNode : slide;
// Select all horizontal slides
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
// Now that we know which the horizontal slide is, get its index
h = Math.max( horizontalSlides.indexOf( slideh ), 0 );
// Assume we're not vertical
v = undefined;
// If this is a vertical slide, grab the vertical index
if( isVertical ) {
v = Math.max( toArray( slide.parentNode.querySelectorAll( 'section' ) ).indexOf( slide ), 0 );
}
}
if( !slide && currentSlide ) {
var hasFragments = currentSlide.querySelectorAll( '.fragment' ).length > 0;
if( hasFragments ) {
var currentFragment = currentSlide.querySelector( '.current-fragment' );
if( currentFragment && currentFragment.hasAttribute( 'data-fragment-index' ) ) {
f = parseInt( currentFragment.getAttribute( 'data-fragment-index' ), 10 );
}
else {
f = currentSlide.querySelectorAll( '.fragment.visible' ).length - 1;
}
}
}
return { h: h, v: v, f: f };
}
/**
* Retrieves the total number of slides in this presentation.
*/
function getTotalSlides() {
return dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length;
}
/**
* Returns the slide element matching the specified index.
*/
function getSlide( x, y ) {
var horizontalSlide = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ];
var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' );
if( verticalSlides && verticalSlides.length && typeof y === 'number' ) {
return verticalSlides ? verticalSlides[ y ] : undefined;
}
return horizontalSlide;
}
/**
* Returns the background element for the given slide.
* All slides, even the ones with no background properties
* defined, have a background element so as long as the
* index is valid an element will be returned.
*/
function getSlideBackground( x, y ) {
// When printing to PDF the slide backgrounds are nested
// inside of the slides
if( isPrintingPDF() ) {
var slide = getSlide( x, y );
if( slide ) {
var background = slide.querySelector( '.slide-background' );
if( background && background.parentNode === slide ) {
return background;
}
}
return undefined;
}
var horizontalBackground = dom.wrapper.querySelectorAll( '.backgrounds>.slide-background' )[ x ];
var verticalBackgrounds = horizontalBackground && horizontalBackground.querySelectorAll( '.slide-background' );
if( verticalBackgrounds && verticalBackgrounds.length && typeof y === 'number' ) {
return verticalBackgrounds ? verticalBackgrounds[ y ] : undefined;
}
return horizontalBackground;
}
/**
* Retrieves the speaker notes from a slide. Notes can be
* defined in two ways:
* 1. As a data-notes attribute on the slide <section>
* 2. As an <aside class="notes"> inside of the slide
*/
function getSlideNotes( slide ) {
// Default to the current slide
slide = slide || currentSlide;
// Notes can be specified via the data-notes attribute...
if( slide.hasAttribute( 'data-notes' ) ) {
return slide.getAttribute( 'data-notes' );
}
// ... or using an <aside class="notes"> element
var notesElement = slide.querySelector( 'aside.notes' );
if( notesElement ) {
return notesElement.innerHTML;
}
return null;
}
/**
* Retrieves the current state of the presentation as
* an object. This state can then be restored at any
* time.
*/
function getState() {
var indices = getIndices();
return {
indexh: indices.h,
indexv: indices.v,
indexf: indices.f,
paused: isPaused(),
overview: isOverview()
};
}
/**
* Restores the presentation to the given state.
*
* @param {Object} state As generated by getState()
*/
function setState( state ) {
if( typeof state === 'object' ) {
slide( deserialize( state.indexh ), deserialize( state.indexv ), deserialize( state.indexf ) );
var pausedFlag = deserialize( state.paused ),
overviewFlag = deserialize( state.overview );
if( typeof pausedFlag === 'boolean' && pausedFlag !== isPaused() ) {
togglePause( pausedFlag );
}
if( typeof overviewFlag === 'boolean' && overviewFlag !== isOverview() ) {
toggleOverview( overviewFlag );
}
}
}
/**
* Return a sorted fragments list, ordered by an increasing
* "data-fragment-index" attribute.
*
* Fragments will be revealed in the order that they are returned by
* this function, so you can use the index attributes to control the
* order of fragment appearance.
*
* To maintain a sensible default fragment order, fragments are presumed
* to be passed in document order. This function adds a "fragment-index"
* attribute to each node if such an attribute is not already present,
* and sets that attribute to an integer value which is the position of
* the fragment within the fragments list.
*/
function sortFragments( fragments ) {
fragments = toArray( fragments );
var ordered = [],
unordered = [],
sorted = [];
// Group ordered and unordered elements
fragments.forEach( function( fragment, i ) {
if( fragment.hasAttribute( 'data-fragment-index' ) ) {
var index = parseInt( fragment.getAttribute( 'data-fragment-index' ), 10 );
if( !ordered[index] ) {
ordered[index] = [];
}
ordered[index].push( fragment );
}
else {
unordered.push( [ fragment ] );
}
} );
// Append fragments without explicit indices in their
// DOM order
ordered = ordered.concat( unordered );
// Manually count the index up per group to ensure there
// are no gaps
var index = 0;
// Push all fragments in their sorted order to an array,
// this flattens the groups
ordered.forEach( function( group ) {
group.forEach( function( fragment ) {
sorted.push( fragment );
fragment.setAttribute( 'data-fragment-index', index );
} );
index ++;
} );
return sorted;
}
/**
* Navigate to the specified slide fragment.
*
* @param {Number} index The index of the fragment that
* should be shown, -1 means all are invisible
* @param {Number} offset Integer offset to apply to the
* fragment index
*
* @return {Boolean} true if a change was made in any
* fragments visibility as part of this call
*/
function navigateFragment( index, offset ) {
if( currentSlide && config.fragments ) {
var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment' ) );
if( fragments.length ) {
// If no index is specified, find the current
if( typeof index !== 'number' ) {
var lastVisibleFragment = sortFragments( currentSlide.querySelectorAll( '.fragment.visible' ) ).pop();
if( lastVisibleFragment ) {
index = parseInt( lastVisibleFragment.getAttribute( 'data-fragment-index' ) || 0, 10 );
}
else {
index = -1;
}
}
// If an offset is specified, apply it to the index
if( typeof offset === 'number' ) {
index += offset;
}
var fragmentsShown = [],
fragmentsHidden = [];
toArray( fragments ).forEach( function( element, i ) {
if( element.hasAttribute( 'data-fragment-index' ) ) {
i = parseInt( element.getAttribute( 'data-fragment-index' ), 10 );
}
// Visible fragments
if( i <= index ) {
if( !element.classList.contains( 'visible' ) ) fragmentsShown.push( element );
element.classList.add( 'visible' );
element.classList.remove( 'current-fragment' );
// Announce the fragments one by one to the Screen Reader
dom.statusDiv.textContent = element.textContent;
if( i === index ) {
element.classList.add( 'current-fragment' );
}
}
// Hidden fragments
else {
if( element.classList.contains( 'visible' ) ) fragmentsHidden.push( element );
element.classList.remove( 'visible' );
element.classList.remove( 'current-fragment' );
}
} );
if( fragmentsHidden.length ) {
dispatchEvent( 'fragmenthidden', { fragment: fragmentsHidden[0], fragments: fragmentsHidden } );
}
if( fragmentsShown.length ) {
dispatchEvent( 'fragmentshown', { fragment: fragmentsShown[0], fragments: fragmentsShown } );
}
updateControls();
updateProgress();
return !!( fragmentsShown.length || fragmentsHidden.length );
}
}
return false;
}
/**
* Navigate to the next slide fragment.
*
* @return {Boolean} true if there was a next fragment,
* false otherwise
*/
function nextFragment() {
return navigateFragment( null, 1 );
}
/**
* Navigate to the previous slide fragment.
*
* @return {Boolean} true if there was a previous fragment,
* false otherwise
*/
function previousFragment() {
return navigateFragment( null, -1 );
}
/**
* Cues a new automated slide if enabled in the config.
*/
function cueAutoSlide() {
cancelAutoSlide();
if( currentSlide ) {
var currentFragment = currentSlide.querySelector( '.current-fragment' );
var fragmentAutoSlide = currentFragment ? currentFragment.getAttribute( 'data-autoslide' ) : null;
var parentAutoSlide = currentSlide.parentNode ? currentSlide.parentNode.getAttribute( 'data-autoslide' ) : null;
var slideAutoSlide = currentSlide.getAttribute( 'data-autoslide' );
// Pick value in the following priority order:
// 1. Current fragment's data-autoslide
// 2. Current slide's data-autoslide
// 3. Parent slide's data-autoslide
// 4. Global autoSlide setting
if( fragmentAutoSlide ) {
autoSlide = parseInt( fragmentAutoSlide, 10 );
}
else if( slideAutoSlide ) {
autoSlide = parseInt( slideAutoSlide, 10 );
}
else if( parentAutoSlide ) {
autoSlide = parseInt( parentAutoSlide, 10 );
}
else {
autoSlide = config.autoSlide;
}
// If there are media elements with data-autoplay,
// automatically set the autoSlide duration to the
// length of that media. Not applicable if the slide
// is divided up into fragments.
if( currentSlide.querySelectorAll( '.fragment' ).length === 0 ) {
toArray( currentSlide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
if( el.hasAttribute( 'data-autoplay' ) ) {
if( autoSlide && el.duration * 1000 > autoSlide ) {
autoSlide = ( el.duration * 1000 ) + 1000;
}
}
} );
}
// Cue the next auto-slide if:
// - There is an autoSlide value
// - Auto-sliding isn't paused by the user
// - The presentation isn't paused
// - The overview isn't active
// - The presentation isn't over
if( autoSlide && !autoSlidePaused && !isPaused() && !isOverview() && ( !Reveal.isLastSlide() || availableFragments().next || config.loop === true ) ) {
autoSlideTimeout = setTimeout( function() {
typeof config.autoSlideMethod === 'function' ? config.autoSlideMethod() : navigateNext();
cueAutoSlide();
}, autoSlide );
autoSlideStartTime = Date.now();
}
if( autoSlidePlayer ) {
autoSlidePlayer.setPlaying( autoSlideTimeout !== -1 );
}
}
}
/**
* Cancels any ongoing request to auto-slide.
*/
function cancelAutoSlide() {
clearTimeout( autoSlideTimeout );
autoSlideTimeout = -1;
}
function pauseAutoSlide() {
if( autoSlide && !autoSlidePaused ) {
autoSlidePaused = true;
dispatchEvent( 'autoslidepaused' );
clearTimeout( autoSlideTimeout );
if( autoSlidePlayer ) {
autoSlidePlayer.setPlaying( false );
}
}
}
function resumeAutoSlide() {
if( autoSlide && autoSlidePaused ) {
autoSlidePaused = false;
dispatchEvent( 'autoslideresumed' );
cueAutoSlide();
}
}
function navigateLeft() {
// Reverse for RTL
if( config.rtl ) {
if( ( isOverview() || nextFragment() === false ) && availableRoutes().left ) {
slide( indexh + 1 );
}
}
// Normal navigation
else if( ( isOverview() || previousFragment() === false ) && availableRoutes().left ) {
slide( indexh - 1 );
}
}
function navigateRight() {
// Reverse for RTL
if( config.rtl ) {
if( ( isOverview() || previousFragment() === false ) && availableRoutes().right ) {
slide( indexh - 1 );
}
}
// Normal navigation
else if( ( isOverview() || nextFragment() === false ) && availableRoutes().right ) {
slide( indexh + 1 );
}
}
function navigateUp() {
// Prioritize hiding fragments
if( ( isOverview() || previousFragment() === false ) && availableRoutes().up ) {
slide( indexh, indexv - 1 );
}
}
function navigateDown() {
// Prioritize revealing fragments
if( ( isOverview() || nextFragment() === false ) && availableRoutes().down ) {
slide( indexh, indexv + 1 );
}
}
/**
* Navigates backwards, prioritized in the following order:
* 1) Previous fragment
* 2) Previous vertical slide
* 3) Previous horizontal slide
*/
function navigatePrev() {
// Prioritize revealing fragments
if( previousFragment() === false ) {
if( availableRoutes().up ) {
navigateUp();
}
else {
// Fetch the previous horizontal slide, if there is one
var previousSlide;
if( config.rtl ) {
previousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.future' ) ).pop();
}
else {
previousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.past' ) ).pop();
}
if( previousSlide ) {
var v = ( previousSlide.querySelectorAll( 'section' ).length - 1 ) || undefined;
var h = indexh - 1;
slide( h, v );
}
}
}
}
/**
* The reverse of #navigatePrev().
*/
function navigateNext() {
// Prioritize revealing fragments
if( nextFragment() === false ) {
if( availableRoutes().down ) {
navigateDown();
}
else if( config.rtl ) {
navigateLeft();
}
else {
navigateRight();
}
}
}
/**
* Checks if the target element prevents the triggering of
* swipe navigation.
*/
function isSwipePrevented( target ) {
while( target && typeof target.hasAttribute === 'function' ) {
if( target.hasAttribute( 'data-prevent-swipe' ) ) return true;
target = target.parentNode;
}
return false;
}
// --------------------------------------------------------------------//
// ----------------------------- EVENTS -------------------------------//
// --------------------------------------------------------------------//
/**
* Called by all event handlers that are based on user
* input.
*/
function onUserInput( event ) {
if( config.autoSlideStoppable ) {
pauseAutoSlide();
}
}
/**
* Handler for the document level 'keypress' event.
*/
function onDocumentKeyPress( event ) {
// Check if the pressed key is question mark
if( event.shiftKey && event.charCode === 63 ) {
if( dom.overlay ) {
closeOverlay();
}
else {
showHelp( true );
}
}
}
/**
* Handler for the document level 'keydown' event.
*/
function onDocumentKeyDown( event ) {
// If there's a condition specified and it returns false,
// ignore this event
if( typeof config.keyboardCondition === 'function' && config.keyboardCondition() === false ) {
return true;
}
// Remember if auto-sliding was paused so we can toggle it
var autoSlideWasPaused = autoSlidePaused;
onUserInput( event );
// Check if there's a focused element that could be using
// the keyboard
var activeElementIsCE = document.activeElement && document.activeElement.contentEditable !== 'inherit';
var activeElementIsInput = document.activeElement && document.activeElement.tagName && /input|textarea/i.test( document.activeElement.tagName );
// Disregard the event if there's a focused element or a
// keyboard modifier key is present
if( activeElementIsCE || activeElementIsInput || (event.shiftKey && event.keyCode !== 32) || event.altKey || event.ctrlKey || event.metaKey ) return;
// While paused only allow resume keyboard events; 'b', '.''
var resumeKeyCodes = [66,190,191];
var key;
// Custom key bindings for togglePause should be able to resume
if( typeof config.keyboard === 'object' ) {
for( key in config.keyboard ) {
if( config.keyboard[key] === 'togglePause' ) {
resumeKeyCodes.push( parseInt( key, 10 ) );
}
}
}
if( isPaused() && resumeKeyCodes.indexOf( event.keyCode ) === -1 ) {
return false;
}
var triggered = false;
// 1. User defined key bindings
if( typeof config.keyboard === 'object' ) {
for( key in config.keyboard ) {
// Check if this binding matches the pressed key
if( parseInt( key, 10 ) === event.keyCode ) {
var value = config.keyboard[ key ];
// Callback function
if( typeof value === 'function' ) {
value.apply( null, [ event ] );
}
// String shortcuts to reveal.js API
else if( typeof value === 'string' && typeof Reveal[ value ] === 'function' ) {
Reveal[ value ].call();
}
triggered = true;
}
}
}
// 2. System defined key bindings
if( triggered === false ) {
// Assume true and try to prove false
triggered = true;
switch( event.keyCode ) {
// p, page up
case 80: case 33: navigatePrev(); break;
// n, page down
case 78: case 34: navigateNext(); break;
// h, left
case 72: case 37: navigateLeft(); break;
// l, right
case 76: case 39: navigateRight(); break;
// k, up
case 75: case 38: navigateUp(); break;
// j, down
case 74: case 40: navigateDown(); break;
// home
case 36: slide( 0 ); break;
// end
case 35: slide( Number.MAX_VALUE ); break;
// space
case 32: isOverview() ? deactivateOverview() : event.shiftKey ? navigatePrev() : navigateNext(); break;
// return
case 13: isOverview() ? deactivateOverview() : triggered = false; break;
// two-spot, semicolon, b, period, Logitech presenter tools "black screen" button
case 58: case 59: case 66: case 190: case 191: togglePause(); break;
// f
case 70: enterFullscreen(); break;
// a
case 65: if ( config.autoSlideStoppable ) toggleAutoSlide( autoSlideWasPaused ); break;
default:
triggered = false;
}
}
// If the input resulted in a triggered action we should prevent
// the browsers default behavior
if( triggered ) {
event.preventDefault && event.preventDefault();
}
// ESC or O key
else if ( ( event.keyCode === 27 || event.keyCode === 79 ) && features.transforms3d ) {
if( dom.overlay ) {
closeOverlay();
}
else {
toggleOverview();
}
event.preventDefault && event.preventDefault();
}
// If auto-sliding is enabled we need to cue up
// another timeout
cueAutoSlide();
}
/**
* Handler for the 'touchstart' event, enables support for
* swipe and pinch gestures.
*/
function onTouchStart( event ) {
if( isSwipePrevented( event.target ) ) return true;
touch.startX = event.touches[0].clientX;
touch.startY = event.touches[0].clientY;
touch.startCount = event.touches.length;
// If there's two touches we need to memorize the distance
// between those two points to detect pinching
if( event.touches.length === 2 && config.overview ) {
touch.startSpan = distanceBetween( {
x: event.touches[1].clientX,
y: event.touches[1].clientY
}, {
x: touch.startX,
y: touch.startY
} );
}
}
/**
* Handler for the 'touchmove' event.
*/
function onTouchMove( event ) {
if( isSwipePrevented( event.target ) ) return true;
// Each touch should only trigger one action
if( !touch.captured ) {
onUserInput( event );
var currentX = event.touches[0].clientX;
var currentY = event.touches[0].clientY;
// If the touch started with two points and still has
// two active touches; test for the pinch gesture
if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) {
// The current distance in pixels between the two touch points
var currentSpan = distanceBetween( {
x: event.touches[1].clientX,
y: event.touches[1].clientY
}, {
x: touch.startX,
y: touch.startY
} );
// If the span is larger than the desire amount we've got
// ourselves a pinch
if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) {
touch.captured = true;
if( currentSpan < touch.startSpan ) {
activateOverview();
}
else {
deactivateOverview();
}
}
event.preventDefault();
}
// There was only one touch point, look for a swipe
else if( event.touches.length === 1 && touch.startCount !== 2 ) {
var deltaX = currentX - touch.startX,
deltaY = currentY - touch.startY;
if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
touch.captured = true;
navigateLeft();
}
else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
touch.captured = true;
navigateRight();
}
else if( deltaY > touch.threshold ) {
touch.captured = true;
navigateUp();
}
else if( deltaY < -touch.threshold ) {
touch.captured = true;
navigateDown();
}
// If we're embedded, only block touch events if they have
// triggered an action
if( config.embedded ) {
if( touch.captured || isVerticalSlide( currentSlide ) ) {
event.preventDefault();
}
}
// Not embedded? Block them all to avoid needless tossing
// around of the viewport in iOS
else {
event.preventDefault();
}
}
}
// There's a bug with swiping on some Android devices unless
// the default action is always prevented
else if( UA.match( /android/gi ) ) {
event.preventDefault();
}
}
/**
* Handler for the 'touchend' event.
*/
function onTouchEnd( event ) {
touch.captured = false;
}
/**
* Convert pointer down to touch start.
*/
function onPointerDown( event ) {
if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
onTouchStart( event );
}
}
/**
* Convert pointer move to touch move.
*/
function onPointerMove( event ) {
if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
onTouchMove( event );
}
}
/**
* Convert pointer up to touch end.
*/
function onPointerUp( event ) {
if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
onTouchEnd( event );
}
}
/**
* Handles mouse wheel scrolling, throttled to avoid skipping
* multiple slides.
*/
function onDocumentMouseScroll( event ) {
if( Date.now() - lastMouseWheelStep > 600 ) {
lastMouseWheelStep = Date.now();
var delta = event.detail || -event.wheelDelta;
if( delta > 0 ) {
navigateNext();
}
else {
navigatePrev();
}
}
}
/**
* Clicking on the progress bar results in a navigation to the
* closest approximate horizontal slide using this equation:
*
* ( clickX / presentationWidth ) * numberOfSlides
*/
function onProgressClicked( event ) {
onUserInput( event );
event.preventDefault();
var slidesTotal = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length;
var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal );
if( config.rtl ) {
slideIndex = slidesTotal - slideIndex;
}
slide( slideIndex );
}
/**
* Event handler for navigation control buttons.
*/
function onNavigateLeftClicked( event ) { event.preventDefault(); onUserInput(); navigateLeft(); }
function onNavigateRightClicked( event ) { event.preventDefault(); onUserInput(); navigateRight(); }
function onNavigateUpClicked( event ) { event.preventDefault(); onUserInput(); navigateUp(); }
function onNavigateDownClicked( event ) { event.preventDefault(); onUserInput(); navigateDown(); }
function onNavigatePrevClicked( event ) { event.preventDefault(); onUserInput(); navigatePrev(); }
function onNavigateNextClicked( event ) { event.preventDefault(); onUserInput(); navigateNext(); }
/**
* Handler for the window level 'hashchange' event.
*/
function onWindowHashChange( event ) {
readURL();
}
/**
* Handler for the window level 'resize' event.
*/
function onWindowResize( event ) {
layout();
}
/**
* Handle for the window level 'visibilitychange' event.
*/
function onPageVisibilityChange( event ) {
var isHidden = document.webkitHidden ||
document.msHidden ||
document.hidden;
// If, after clicking a link or similar and we're coming back,
// focus the document.body to ensure we can use keyboard shortcuts
if( isHidden === false && document.activeElement !== document.body ) {
// Not all elements support .blur() - SVGs among them.
if( typeof document.activeElement.blur === 'function' ) {
document.activeElement.blur();
}
document.body.focus();
}
}
/**
* Invoked when a slide is and we're in the overview.
*/
function onOverviewSlideClicked( event ) {
// TODO There's a bug here where the event listeners are not
// removed after deactivating the overview.
if( eventsAreBound && isOverview() ) {
event.preventDefault();
var element = event.target;
while( element && !element.nodeName.match( /section/gi ) ) {
element = element.parentNode;
}
if( element && !element.classList.contains( 'disabled' ) ) {
deactivateOverview();
if( element.nodeName.match( /section/gi ) ) {
var h = parseInt( element.getAttribute( 'data-index-h' ), 10 ),
v = parseInt( element.getAttribute( 'data-index-v' ), 10 );
slide( h, v );
}
}
}
}
/**
* Handles clicks on links that are set to preview in the
* iframe overlay.
*/
function onPreviewLinkClicked( event ) {
if( event.currentTarget && event.currentTarget.hasAttribute( 'href' ) ) {
var url = event.currentTarget.getAttribute( 'href' );
if( url ) {
showPreview( url );
event.preventDefault();
}
}
}
/**
* Handles click on the auto-sliding controls element.
*/
function onAutoSlidePlayerClick( event ) {
// Replay
if( Reveal.isLastSlide() && config.loop === false ) {
slide( 0, 0 );
resumeAutoSlide();
}
// Resume
else if( autoSlidePaused ) {
resumeAutoSlide();
}
// Pause
else {
pauseAutoSlide();
}
}
// --------------------------------------------------------------------//
// ------------------------ PLAYBACK COMPONENT ------------------------//
// --------------------------------------------------------------------//
/**
* Constructor for the playback component, which displays
* play/pause/progress controls.
*
* @param {HTMLElement} container The component will append
* itself to this
* @param {Function} progressCheck A method which will be
* called frequently to get the current progress on a range
* of 0-1
*/
function Playback( container, progressCheck ) {
// Cosmetics
this.diameter = 100;
this.diameter2 = this.diameter/2;
this.thickness = 6;
// Flags if we are currently playing
this.playing = false;
// Current progress on a 0-1 range
this.progress = 0;
// Used to loop the animation smoothly
this.progressOffset = 1;
this.container = container;
this.progressCheck = progressCheck;
this.canvas = document.createElement( 'canvas' );
this.canvas.className = 'playback';
this.canvas.width = this.diameter;
this.canvas.height = this.diameter;
this.canvas.style.width = this.diameter2 + 'px';
this.canvas.style.height = this.diameter2 + 'px';
this.context = this.canvas.getContext( '2d' );
this.container.appendChild( this.canvas );
this.render();
}
Playback.prototype.setPlaying = function( value ) {
var wasPlaying = this.playing;
this.playing = value;
// Start repainting if we weren't already
if( !wasPlaying && this.playing ) {
this.animate();
}
else {
this.render();
}
};
Playback.prototype.animate = function() {
var progressBefore = this.progress;
this.progress = this.progressCheck();
// When we loop, offset the progress so that it eases
// smoothly rather than immediately resetting
if( progressBefore > 0.8 && this.progress < 0.2 ) {
this.progressOffset = this.progress;
}
this.render();
if( this.playing ) {
features.requestAnimationFrameMethod.call( window, this.animate.bind( this ) );
}
};
/**
* Renders the current progress and playback state.
*/
Playback.prototype.render = function() {
var progress = this.playing ? this.progress : 0,
radius = ( this.diameter2 ) - this.thickness,
x = this.diameter2,
y = this.diameter2,
iconSize = 28;
// Ease towards 1
this.progressOffset += ( 1 - this.progressOffset ) * 0.1;
var endAngle = ( - Math.PI / 2 ) + ( progress * ( Math.PI * 2 ) );
var startAngle = ( - Math.PI / 2 ) + ( this.progressOffset * ( Math.PI * 2 ) );
this.context.save();
this.context.clearRect( 0, 0, this.diameter, this.diameter );
// Solid background color
this.context.beginPath();
this.context.arc( x, y, radius + 4, 0, Math.PI * 2, false );
this.context.fillStyle = 'rgba( 0, 0, 0, 0.4 )';
this.context.fill();
// Draw progress track
this.context.beginPath();
this.context.arc( x, y, radius, 0, Math.PI * 2, false );
this.context.lineWidth = this.thickness;
this.context.strokeStyle = '#666';
this.context.stroke();
if( this.playing ) {
// Draw progress on top of track
this.context.beginPath();
this.context.arc( x, y, radius, startAngle, endAngle, false );
this.context.lineWidth = this.thickness;
this.context.strokeStyle = '#fff';
this.context.stroke();
}
this.context.translate( x - ( iconSize / 2 ), y - ( iconSize / 2 ) );
// Draw play/pause icons
if( this.playing ) {
this.context.fillStyle = '#fff';
this.context.fillRect( 0, 0, iconSize / 2 - 4, iconSize );
this.context.fillRect( iconSize / 2 + 4, 0, iconSize / 2 - 4, iconSize );
}
else {
this.context.beginPath();
this.context.translate( 4, 0 );
this.context.moveTo( 0, 0 );
this.context.lineTo( iconSize - 4, iconSize / 2 );
this.context.lineTo( 0, iconSize );
this.context.fillStyle = '#fff';
this.context.fill();
}
this.context.restore();
};
Playback.prototype.on = function( type, listener ) {
this.canvas.addEventListener( type, listener, false );
};
Playback.prototype.off = function( type, listener ) {
this.canvas.removeEventListener( type, listener, false );
};
Playback.prototype.destroy = function() {
this.playing = false;
if( this.canvas.parentNode ) {
this.container.removeChild( this.canvas );
}
};
// --------------------------------------------------------------------//
// ------------------------------- API --------------------------------//
// --------------------------------------------------------------------//
Reveal = {
VERSION: VERSION,
initialize: initialize,
configure: configure,
sync: sync,
// Navigation methods
slide: slide,
left: navigateLeft,
right: navigateRight,
up: navigateUp,
down: navigateDown,
prev: navigatePrev,
next: navigateNext,
// Fragment methods
navigateFragment: navigateFragment,
prevFragment: previousFragment,
nextFragment: nextFragment,
// Deprecated aliases
navigateTo: slide,
navigateLeft: navigateLeft,
navigateRight: navigateRight,
navigateUp: navigateUp,
navigateDown: navigateDown,
navigatePrev: navigatePrev,
navigateNext: navigateNext,
// Forces an update in slide layout
layout: layout,
// Randomizes the order of slides
shuffle: shuffle,
// Returns an object with the available routes as booleans (left/right/top/bottom)
availableRoutes: availableRoutes,
// Returns an object with the available fragments as booleans (prev/next)
availableFragments: availableFragments,
// Toggles the overview mode on/off
toggleOverview: toggleOverview,
// Toggles the "black screen" mode on/off
togglePause: togglePause,
// Toggles the auto slide mode on/off
toggleAutoSlide: toggleAutoSlide,
// State checks
isOverview: isOverview,
isPaused: isPaused,
isAutoSliding: isAutoSliding,
// Adds or removes all internal event listeners (such as keyboard)
addEventListeners: addEventListeners,
removeEventListeners: removeEventListeners,
// Facility for persisting and restoring the presentation state
getState: getState,
setState: setState,
// Presentation progress on range of 0-1
getProgress: getProgress,
// Returns the indices of the current, or specified, slide
getIndices: getIndices,
getTotalSlides: getTotalSlides,
// Returns the slide element at the specified index
getSlide: getSlide,
// Returns the slide background element at the specified index
getSlideBackground: getSlideBackground,
// Returns the speaker notes string for a slide, or null
getSlideNotes: getSlideNotes,
// Returns the previous slide element, may be null
getPreviousSlide: function() {
return previousSlide;
},
// Returns the current slide element
getCurrentSlide: function() {
return currentSlide;
},
// Returns the current scale of the presentation content
getScale: function() {
return scale;
},
// Returns the current configuration object
getConfig: function() {
return config;
},
// Helper method, retrieves query string as a key/value hash
getQueryHash: function() {
var query = {};
location.search.replace( /[A-Z0-9]+?=([\w\.%-]*)/gi, function(a) {
query[ a.split( '=' ).shift() ] = a.split( '=' ).pop();
} );
// Basic deserialization
for( var i in query ) {
var value = query[ i ];
query[ i ] = deserialize( unescape( value ) );
}
return query;
},
// Returns true if we're currently on the first slide
isFirstSlide: function() {
return ( indexh === 0 && indexv === 0 );
},
// Returns true if we're currently on the last slide
isLastSlide: function() {
if( currentSlide ) {
// Does this slide has next a sibling?
if( currentSlide.nextElementSibling ) return false;
// If it's vertical, does its parent have a next sibling?
if( isVerticalSlide( currentSlide ) && currentSlide.parentNode.nextElementSibling ) return false;
return true;
}
return false;
},
// Checks if reveal.js has been loaded and is ready for use
isReady: function() {
return loaded;
},
// Forward event binding to the reveal DOM element
addEventListener: function( type, listener, useCapture ) {
if( 'addEventListener' in window ) {
( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture );
}
},
removeEventListener: function( type, listener, useCapture ) {
if( 'addEventListener' in window ) {
( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture );
}
},
// Programatically triggers a keyboard event
triggerKey: function( keyCode ) {
onDocumentKeyDown( { keyCode: keyCode } );
},
// Registers a new shortcut to include in the help overlay
registerKeyboardShortcut: function( key, value ) {
keyboardShortcuts[key] = value;
}
};
return Reveal;
}));
| lihuma/lihuma.github.io | js/reveal.js | JavaScript | mit | 131,510 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
# @author : beaengine@gmail.com
from headers.BeaEnginePython import *
from nose.tools import *
class TestSuite:
def test(self):
# EVEX.256.66.0F3A.W0 25 /r ib
# vpternlogd ymm1{k1}{z}, ymm2, ymm3/m256/m32bcst, imm8
myEVEX = EVEX('EVEX.256.66.0F3A.W0')
Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix()))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(myDisasm.infos.Instruction.Opcode, 0x25)
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogd')
assert_equal(myDisasm.repr(), 'vpternlogd ymm28, ymm16, ymmword ptr [r8], 11h')
# EVEX.512.66.0F3A.W0 25 /r ib
# vpternlogd zmm1{k1}{z}, zmm2, zmm3/m512/m32bcst, imm8
myEVEX = EVEX('EVEX.512.66.0F3A.W0')
Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix()))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(myDisasm.infos.Instruction.Opcode, 0x25)
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogd')
assert_equal(myDisasm.repr(), 'vpternlogd zmm28, zmm16, zmmword ptr [r8], 11h')
# EVEX.256.66.0F3A.W1 25 /r ib
# vpternlogq ymm1{k1}{z}, ymm2, ymm3/m256/m64bcst, imm8
myEVEX = EVEX('EVEX.256.66.0F3A.W1')
Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix()))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(myDisasm.infos.Instruction.Opcode, 0x25)
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogq')
assert_equal(myDisasm.repr(), 'vpternlogq ymm28, ymm16, ymmword ptr [r8], 11h')
# EVEX.512.66.0F3A.W1 25 /r ib
# vpternlogq zmm1{k1}{z}, zmm2, zmm3/m512/m64bcst, imm8
myEVEX = EVEX('EVEX.512.66.0F3A.W1')
Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix()))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(myDisasm.infos.Instruction.Opcode, 0x25)
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogq')
assert_equal(myDisasm.repr(), 'vpternlogq zmm28, zmm16, zmmword ptr [r8], 11h')
| 0vercl0k/rp | src/third_party/beaengine/tests/0f3a25.py | Python | mit | 2,835 |
class Base {
public:
Resource *p;
Base() {
p = createResource();
}
virtual void f() { //has virtual function
//...
}
//...
~Base() { //wrong: is non-virtual
freeResource(p);
}
};
class Derived: public Base {
public:
Resource *dp;
Derived() {
dp = createResource2();
}
~Derived() {
freeResource2(dp);
}
};
int f() {
Base *b = new Derived(); //creates resources for both Base::p and Derived::dp
//...
//will only call Base::~Base(), leaking the resource dp.
//Change both destructors to virtual to ensure they are both called.
delete b;
}
| github/codeql | cpp/ql/src/jsf/4.10 Classes/AV Rule 78.cpp | C++ | mit | 568 |
#region Copyright (c) 2003, newtelligence AG. All rights reserved.
/*
// Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com)
// Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// (1) Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// (2) Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// (3) Neither the name of the newtelligence AG nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// -------------------------------------------------------------------------
//
// Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com)
//
// newtelligence is a registered trademark of newtelligence Aktiengesellschaft.
//
// For portions of this software, the some additional copyright notices may apply
// which can either be found in the license.txt file included in the source distribution
// or following this notice.
//
*/
#endregion
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using newtelligence.DasBlog.Runtime.Proxies;
using newtelligence.DasBlog.Util;
namespace newtelligence.DasBlog.Runtime
{
[Serializable]
[XmlRoot(Namespace=Data.NamespaceURI)]
[XmlType(Namespace=Data.NamespaceURI)]
public class DayEntry : IDayEntry
{
private object entriesLock = new object(); //the entries collection is shared and must be protected
private bool Loaded
{
[DebuggerStepThrough()] get { return _loaded; }
[DebuggerStepThrough()] set { _loaded = value; }
}
private bool _loaded = false;
public string FileName
{
get
{
// Use Invariant Culture, not host culture (or user override), for date formats.
return DateUtc.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + ".dayentry.xml";
}
}
[XmlIgnore]
public DateTime DateUtc
{
[DebuggerStepThrough()] get { return _date; }
[DebuggerStepThrough()] set { _date = value.Date; }
}
private DateTime _date;
[XmlElement("Date")]
public DateTime DateLocalTime
{
get { return (DateUtc==DateTime.MinValue||DateUtc==DateTime.MaxValue)?DateUtc:DateUtc.ToLocalTime(); }
set { DateUtc = (value==DateTime.MinValue||value==DateTime.MaxValue)?value:value.Date.ToUniversalTime(); }
}
[XmlArrayItem(typeof(Entry))]
public EntryCollection Entries
{
[DebuggerStepThrough()] get { return _entries; }
[DebuggerStepThrough()] set { _entries = value; }
}
private EntryCollection _entries = new EntryCollection();
[XmlAnyElement]
public XmlElement[] anyElements;
[XmlAnyAttribute]
public XmlAttribute[] anyAttributes;
public void Initialize()
{
DateUtc = DateTime.Now.ToUniversalTime().Date;
}
/// <summary>
/// Return EntryCollection excluding the private entries if the caller
/// is not in the admin role.
/// </summary>
public EntryCollection GetEntries()
{
return GetEntries(null);
}
/// <summary>
/// Return EntryCollection with the number of entries limited by <see paramref="maxResults" />
/// excluding the private entries if the caller is not in the admin role.
/// </summary>
public EntryCollection GetEntries(int maxResults)
{
return GetEntries(null, maxResults);
}
/// <summary>
/// Returns the entries that meet the include delegates criteria.
/// </summary>
/// <param name="include">The delegate indicating which items to include.</param>
public EntryCollection GetEntries(Predicate<Entry> include)
{
return GetEntries(include, Int32.MaxValue);
}
/// <summary>
/// Returns the entries that meet the include delegates criteria,
/// with the number of entries limited by <see paramref="maxResults" />.
/// </summary>
/// <param name="include">The delegate indicating which items to include.</param>
public EntryCollection GetEntries(Predicate<Entry> include, int maxResults)
{
lock(entriesLock)
{
Predicate<Entry> filter = null;
if(!System.Threading.Thread.CurrentPrincipal.IsInRole("admin"))
{
filter += EntryCollectionFilter.DefaultFilters.IsPublic();
}
if(include != null)
{
filter += include;
}
return EntryCollectionFilter.FindAll(Entries, filter, maxResults);
}
}
/// <param name="entryTitle">An URL-encoded entry title</param>
public Entry GetEntryByTitle(string entryTitle)
{
foreach (Entry entry in this.Entries)
{
string compressedTitle = entry.CompressedTitle.Replace("+", "");
if (CaseInsensitiveComparer.Default.Compare(compressedTitle,entryTitle) == 0)
{
return entry;
}
}
return null;
}
internal void Load(DataManager data)
{
if ( Loaded )
{
return;
}
lock(entriesLock)
{
if ( Loaded ) //SDH: standard thread-safe double check
{
return;
}
string fullPath = data.ResolvePath(FileName);
FileStream fileStream = FileUtils.OpenForRead(fullPath);
if ( fileStream != null )
{
try
{
XmlSerializer ser = new XmlSerializer(typeof(DayEntry),Data.NamespaceURI);
using (StreamReader reader = new StreamReader(fileStream))
{
//XmlNamespaceUpgradeReader upg = new XmlNamespaceUpgradeReader( reader, "", Data.NamespaceURI );
DayEntry e = (DayEntry)ser.Deserialize(reader);
Entries = e.Entries;
}
}
catch(Exception e)
{
ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error,e);
}
finally
{
fileStream.Close();
}
}
Entries.Sort((left,right) => right.CreatedUtc.CompareTo(left.CreatedUtc));
Loaded = true;
}
}
internal void Save(DataManager data)
{
string fullPath = data.ResolvePath(FileName);
// We use the internal list to circumvent ignoring
// items where IsPublic is set to false.
if ( Entries.Count == 0 )
{
if ( File.Exists( fullPath ) )
{
File.Delete( fullPath );
}
}
else
{
System.Security.Principal.WindowsImpersonationContext wi = Impersonation.Impersonate();
FileStream fileStream = FileUtils.OpenForWrite(fullPath);
if ( fileStream != null )
{
try
{
XmlSerializer ser = new XmlSerializer(typeof(DayEntry),Data.NamespaceURI);
using (StreamWriter writer = new StreamWriter(fileStream))
{
ser.Serialize(writer, this);
}
}
catch(Exception e)
{
ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error,e);
}
finally
{
fileStream.Close();
}
}
wi.Undo();
}
}
/// <summary>
/// Returns true if the specified DayEntry occurs before the day specified.
/// </summary>
/// <param name="dayEntry">The DayEntry to check the date of.</param>
/// <param name="dateTime">The date the DayEntry should occur before</param>
/// <returns>Returns true if the dayEntry occurs before the specified date.</returns>
public static bool OccursBefore(DayEntry dayEntry, DateTime dateTime)
{
return (dayEntry.DateUtc.Date <= dateTime);
}
public static bool OccursBetween(DayEntry dayEntry, TimeZone timeZone,
DateTime startDateTime, DateTime endDateTime)
{
//return ((timeZone.ToLocalTime(dayEntry.DateUtc) >= startDateTime)
// && (timeZone.ToLocalTime(dayEntry.DateUtc) <= endDateTime) );
return ((dayEntry.DateUtc >= startDateTime)
&& (dayEntry.DateUtc <= endDateTime) );
}
/// <summary>
/// Returns true if the specified DayEntry is within the same month as <c>month</c>;
/// </summary>
/// <param name="dayEntry"></param>
/// <param name="timeZone"></param>
/// <param name="month"></param>
/// <returns></returns>
public static bool OccursInMonth(DayEntry dayEntry, TimeZone timeZone,
DateTime month)
{
DateTime startOfMonth = new DateTime(month.Year, month.Month, 1, 0, 0, 0);
DateTime endOfMonth = new DateTime(month.Year, month.Month, 1, 0, 0, 0);
endOfMonth = endOfMonth.AddMonths(1);
endOfMonth = endOfMonth.AddSeconds(-1);
TimeSpan offset = timeZone.GetUtcOffset(endOfMonth);
endOfMonth = endOfMonth.AddHours(offset.Negate().Hours);
return ( OccursBetween(dayEntry, timeZone, startOfMonth, endOfMonth) );
}
}
}
| poppastring/dasblog | source/newtelligence.DasBlog.Runtime/DayEntry.cs | C# | mit | 9,683 |
/** \file
* \brief Scintilla control: Cursor and Zooming
*
* See Copyright Notice in "iup.h"
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#undef SCI_NAMESPACE
#include <Scintilla.h>
#include "iup.h"
#include "iup_object.h"
#include "iup_attrib.h"
#include "iup_str.h"
#include "iupsci.h"
/***** CURSOR ****
SCI_SETCURSOR(int curType)
SCI_GETCURSOR
*/
static char* iScintillaGetCursorAttrib(Ihandle *ih)
{
if(IupScintillaSendMessage(ih, SCI_GETCURSOR, 0, 0) == SC_CURSORWAIT)
return "WAIT";
else
return "NORMAL";
}
static int iScintillaSetCursorAttrib(Ihandle *ih, const char *value)
{
if (iupStrEqualNoCase(value, "WAIT"))
IupScintillaSendMessage(ih, SCI_SETCURSOR, (uptr_t)SC_CURSORWAIT, 0);
else /* NORMAL */
IupScintillaSendMessage(ih, SCI_SETCURSOR, (uptr_t)SC_CURSORNORMAL, 0);
return 0;
}
/***** ZOOMING ****
SCI_ZOOMIN
SCI_ZOOMOUT
SCI_SETZOOM(int zoomInPoints)
SCI_GETZOOM
*/
static int iScintillaSetZoomInAttrib(Ihandle *ih, const char *value)
{
(void)value;
IupScintillaSendMessage(ih, SCI_ZOOMIN, 0, 0);
return 0;
}
static int iScintillaSetZoomOutAttrib(Ihandle *ih, const char *value)
{
(void)value;
IupScintillaSendMessage(ih, SCI_ZOOMOUT, 0, 0);
return 0;
}
static int iScintillaSetZoomAttrib(Ihandle *ih, const char *value)
{
int points;
if (!iupStrToInt(value, &points))
return 0;
if(points > 20) points = 20;
if(points < -10) points = -10;
IupScintillaSendMessage(ih, SCI_SETZOOM, points, 0);
return 0;
}
static char* iScintillaGetZoomAttrib(Ihandle* ih)
{
int points = IupScintillaSendMessage(ih, SCI_GETZOOM, 0, 0);
return iupStrReturnInt(points);
}
void iupScintillaRegisterCursor(Iclass* ic)
{
iupClassRegisterAttribute(ic, "CURSOR", iScintillaGetCursorAttrib, iScintillaSetCursorAttrib, NULL, NULL, IUPAF_NO_INHERIT);
iupClassRegisterAttribute(ic, "ZOOMIN", NULL, iScintillaSetZoomInAttrib, NULL, NULL, IUPAF_WRITEONLY|IUPAF_NO_INHERIT);
iupClassRegisterAttribute(ic, "ZOOMOUT", NULL, iScintillaSetZoomOutAttrib, NULL, NULL, IUPAF_WRITEONLY|IUPAF_NO_INHERIT);
iupClassRegisterAttribute(ic, "ZOOM", iScintillaGetZoomAttrib, iScintillaSetZoomAttrib, NULL, NULL, IUPAF_NO_INHERIT);
}
| ivanceras/iup-mirror | srcscintilla/iupsci_cursor.c | C | mit | 2,233 |
var Example = Example || {};
Example.staticFriction = function() {
var Engine = Matter.Engine,
Render = Matter.Render,
Runner = Matter.Runner,
Body = Matter.Body,
Composites = Matter.Composites,
Events = Matter.Events,
MouseConstraint = Matter.MouseConstraint,
Mouse = Matter.Mouse,
World = Matter.World,
Bodies = Matter.Bodies;
// create engine
var engine = Engine.create(),
world = engine.world;
// create renderer
var render = Render.create({
element: document.body,
engine: engine,
options: {
width: Math.min(document.documentElement.clientWidth, 800),
height: Math.min(document.documentElement.clientHeight, 600),
showVelocity: true
}
});
Render.run(render);
// create runner
var runner = Runner.create();
Runner.run(runner, engine);
// add bodies
var body = Bodies.rectangle(400, 500, 200, 60, { isStatic: true, chamfer: 10 }),
size = 50,
counter = -1;
var stack = Composites.stack(350, 470 - 6 * size, 1, 6, 0, 0, function(x, y) {
return Bodies.rectangle(x, y, size * 2, size, {
slop: 0.5,
friction: 1,
frictionStatic: Infinity
});
});
World.add(world, [
body,
stack,
// walls
Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),
Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),
Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),
Bodies.rectangle(0, 300, 50, 600, { isStatic: true })
]);
Events.on(engine, 'beforeUpdate', function(event) {
counter += 0.014;
if (counter < 0) {
return;
}
var px = 400 + 100 * Math.sin(counter);
// body is static so must manually update velocity for friction to work
Body.setVelocity(body, { x: px - body.position.x, y: 0 });
Body.setPosition(body, { x: px, y: body.position.y });
});
// add mouse control
var mouse = Mouse.create(render.canvas),
mouseConstraint = MouseConstraint.create(engine, {
mouse: mouse,
constraint: {
stiffness: 0.2,
render: {
visible: false
}
}
});
World.add(world, mouseConstraint);
// keep the mouse in sync with rendering
render.mouse = mouse;
// fit the render viewport to the scene
Render.lookAt(render, {
min: { x: 0, y: 0 },
max: { x: 800, y: 600 }
});
// context for MatterTools.Demo
return {
engine: engine,
runner: runner,
render: render,
canvas: render.canvas,
stop: function() {
Matter.Render.stop(render);
Matter.Runner.stop(runner);
}
};
}; | lsu-emdm/nx-physicsUI | matter-js/examples/staticFriction.js | JavaScript | mit | 2,921 |
require File.dirname(__FILE__) + "/../spec_helper.rb"
| mhennemeyer/macspec | spec/mac_spec/testing_framework/spec_helper.rb | Ruby | mit | 54 |
{% if isTopPage() %}
{% set unportalizedPath = '/top-' + Date.now() %}
{% else %}
{% set unportalizedPath = page.path|replace('(\/)$', '') %}
{% endif %}
<div class="modal" id="unportalize">
<div class="modal-dialog">
<div class="modal-content">
<form role="form" id="unportalize-form" onsubmit="return false;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">ポータル化を解除する</h4>
</div>
<div class="modal-body">
<ul>
<li>このポータル化を解除し、通常のページに戻します。</li>
</ul>
<div class="form-group">
<p>
<label for="">このページ</label><br><code>{{ page.path }}</code>
</p>
<p>
<label for="">解除後のページ</label><br><code>{{ unportalizedPath }}</code>
</p>
{% if isTopPage() %}
<p class="alert alert-info">
このポータルはトップページのポータルのため、特別なページに移動します。
</p>
{% endif %}
</div>
</div>
<div class="modal-footer">
<p><small class="pull-left" id="newPageNameCheck"></small></p>
<input type="hidden" name="_csrf" value="{{ csrf() }}">
<input type="hidden" name="path" value="{{ page.path }}">
<input type="hidden" class="form-control" name="new_path" id="newPageName" value="{{ unportalizedPath }}">
<input type="hidden" name="page_id" value="{{ page._id.toString() }}">
<input type="hidden" name="revision_id" value="{{ page.revision._id.toString() }}">
<input type="submit" class="btn btn-primary" value="Unportalize!">
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
| crow-misia/crowi | lib/views/modal/unportalize.html | HTML | mit | 2,026 |
package com.softserve.app.repository;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import com.softserve.app.model.Pet;
@RunWith(MockitoJUnitRunner.class)
public class PetRepositoryStubTest {
@Mock PetRepository stubM;
@Mock Pet petM;
@Test
public void testFindAllPetsWithMockStub() {
List<Pet> pets = stubM.findAllPets();
assertNotNull(pets);
}
@Test
public void testFindAllPetsWithRealStub() {
PetRepositoryStub stub = new PetRepositoryStub();
List<Pet> pets = (ArrayList<Pet>) stub.findAllPets();
assertNotNull(pets);
}
@Test
public void testFindPetWithRealStub() {
PetRepositoryStub stub = new PetRepositoryStub();
Pet pet = stub.findPet("101");
System.out.println(pet);
assertNotNull(pet);
}
@Test
public void testFindPetWithMockStub() {
when(stubM.findPet("10").getType()).thenReturn("dog");
assertEquals("dog", stubM.findPet("0").getType());
}
@Test(expected=RuntimeException.class)
public void testFindPetWithBadRequestWithRealStub() {
PetRepositoryStub stub = new PetRepositoryStub();
Pet pet = stub.findPet("0");
}
@Test
public void testCreate() {
PetRepositoryStub stub = new PetRepositoryStub();
Pet pet5 = new Pet();
pet5.setId("5");
pet5.setType("Dog");
System.out.println(pet5.getType());
stub.create(pet5);
System.out.println(stub.findPet("5").getType());
assertNotNull(stub.findPet("5").getType());
}
}
| OlegSvyryd/animalsRepo | SampleProjectPet/src/test/java/com/softserve/app/repository/PetRepositoryStubTest.java | Java | mit | 1,751 |
##Search in Rotated Sorted Array II
Total Accepted: 60092 Total Submissions: 188639 Difficulty: Medium
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
####思路
- 我的思路是先找到最低点的index,找的时候有两种情况,一种要从end--开始找,一种是start++开始找
- 然后通过index划分两边,再对两边分别进行binary search,找是否有target
- 平均O(logn),最坏情况O(n)
- 也可以直接做,[参考](https://leetcode.com/discuss/30308/java-solution-with-comments)
```java
public class Solution {
public boolean search(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return false;
}
int len = nums.length;
int lowIndex1 = searchLowestIndex1(nums);
int lowIndex2 = searchLowestIndex2(nums);
return binarySearch(nums, target, 0, lowIndex1 - 1) || binarySearch(nums, target, lowIndex1, len - 1) || binarySearch(nums, target, 0, lowIndex2 - 1) || binarySearch(nums, target, lowIndex2, len - 1);
}
public int searchLowestIndex1(int[] nums) {
if (nums == null || nums.length == 0) {
return -1;
}
int len = nums.length;
int start = 0;
int end = len - 1;
while (start < end - 1) {
int mid = start + (end - start) / 2;
if (nums[mid] == nums[end]) {
end--;
} else if (nums[mid] > nums[end]) {
start = mid;
} else {
end = mid;
}
}
return (nums[start] < nums[end]) ? start : end;
}
public int searchLowestIndex2(int[] nums) {
if (nums == null || nums.length == 0) {
return -1;
}
int len = nums.length;
int start = 0;
int end = len - 1;
while (start < end - 1) {
int mid = start + (end - start) / 2;
if (nums[mid] == nums[start]) {
start++;
} else if (nums[mid] > nums[start]) {
start = mid;
} else {
end = mid;
}
}
return (nums[start] < nums[end]) ? start : end;
}
public boolean binarySearch(int[] nums, int target, int start, int end) {
if (end < start || start < 0) {
return false;
}
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
return true;
} else if (nums[mid] > target) {
end = mid;
} else {
start = mid;
}
}
return (nums[start] == target) || (nums[end] == target);
}
}
```
| rwang23/LintCodeBook | Google/Search-in-Rotated-Sorted-Array-II.md | Markdown | mit | 2,861 |
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreShaderExHardwareSkinning.h"
#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS
#include "OgreShaderExDualQuaternionSkinning.h"
#include "OgreShaderExLinearSkinning.h"
#include "OgreShaderFFPRenderState.h"
#include "OgreShaderProgram.h"
#include "OgreShaderParameter.h"
#include "OgreShaderProgramSet.h"
#include "OgreEntity.h"
#include "OgreSubEntity.h"
#include "OgreMaterial.h"
#include "OgreSubMesh.h"
#include "OgreShaderGenerator.h"
#define HS_DATA_BIND_NAME "HS_SRS_DATA"
namespace Ogre {
template<> RTShader::HardwareSkinningFactory* Singleton<RTShader::HardwareSkinningFactory>::msSingleton = 0;
namespace RTShader {
HardwareSkinningFactory* HardwareSkinningFactory::getSingletonPtr(void)
{
return msSingleton;
}
HardwareSkinningFactory& HardwareSkinningFactory::getSingleton(void)
{
assert( msSingleton ); return ( *msSingleton );
}
String HardwareSkinning::Type = "SGX_HardwareSkinning";
/************************************************************************/
/* */
/************************************************************************/
HardwareSkinning::HardwareSkinning() :
mCreator(NULL),
mSkinningType(ST_LINEAR)
{
}
//-----------------------------------------------------------------------
const String& HardwareSkinning::getType() const
{
return Type;
}
//-----------------------------------------------------------------------
int HardwareSkinning::getExecutionOrder() const
{
return FFP_TRANSFORM;
}
//-----------------------------------------------------------------------
void HardwareSkinning::setHardwareSkinningParam(ushort boneCount, ushort weightCount, SkinningType skinningType, bool correctAntipodalityHandling, bool scalingShearingSupport)
{
mSkinningType = skinningType;
if(skinningType == ST_DUAL_QUATERNION)
{
if(mDualQuat.isNull())
{
mDualQuat.bind(OGRE_NEW DualQuaternionSkinning);
}
mActiveTechnique = mDualQuat;
}
else //if(skinningType == ST_LINEAR)
{
if(mLinear.isNull())
{
mLinear.bind(OGRE_NEW LinearSkinning);
}
mActiveTechnique = mLinear;
}
mActiveTechnique->setHardwareSkinningParam(boneCount, weightCount, correctAntipodalityHandling, scalingShearingSupport);
}
//-----------------------------------------------------------------------
ushort HardwareSkinning::getBoneCount()
{
assert(!mActiveTechnique.isNull());
return mActiveTechnique->getBoneCount();
}
//-----------------------------------------------------------------------
ushort HardwareSkinning::getWeightCount()
{
assert(!mActiveTechnique.isNull());
return mActiveTechnique->getWeightCount();
}
//-----------------------------------------------------------------------
SkinningType HardwareSkinning::getSkinningType()
{
assert(!mActiveTechnique.isNull());
return mSkinningType;
}
//-----------------------------------------------------------------------
bool HardwareSkinning::hasCorrectAntipodalityHandling()
{
assert(!mActiveTechnique.isNull());
return mActiveTechnique->hasCorrectAntipodalityHandling();
}
//-----------------------------------------------------------------------
bool HardwareSkinning::hasScalingShearingSupport()
{
assert(!mActiveTechnique.isNull());
return mActiveTechnique->hasScalingShearingSupport();
}
//-----------------------------------------------------------------------
void HardwareSkinning::copyFrom(const SubRenderState& rhs)
{
const HardwareSkinning& hardSkin = static_cast<const HardwareSkinning&>(rhs);
mDualQuat = hardSkin.mDualQuat;
mLinear = hardSkin.mLinear;
mActiveTechnique = hardSkin.mActiveTechnique;
mCreator = hardSkin.mCreator;
mSkinningType = hardSkin.mSkinningType;
}
//-----------------------------------------------------------------------
void operator<<(std::ostream& o, const HardwareSkinning::SkinningData& data)
{
o << data.isValid;
o << data.maxBoneCount;
o << data.maxWeightCount;
o << data.skinningType;
o << data.correctAntipodalityHandling;
o << data.scalingShearingSupport;
}
//-----------------------------------------------------------------------
bool HardwareSkinning::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass)
{
bool isValid = true;
Technique* pFirstTech = srcPass->getParent()->getParent()->getTechnique(0);
const Any& hsAny = pFirstTech->getUserObjectBindings().getUserAny(HS_DATA_BIND_NAME);
if (hsAny.isEmpty() == false)
{
HardwareSkinning::SkinningData pData =
(any_cast<HardwareSkinning::SkinningData>(hsAny));
isValid = pData.isValid;
//If the skinning data is being passed through the material, we need to create an instance of the appropriate
//skinning type and set its parameters here
setHardwareSkinningParam(pData.maxBoneCount, pData.maxWeightCount, pData.skinningType,
pData.correctAntipodalityHandling, pData.scalingShearingSupport);
}
//If there is no associated technique, default to linear skinning as a pass-through
if(mActiveTechnique.isNull())
{
setHardwareSkinningParam(0, 0, ST_LINEAR, false, false);
}
int boneCount = mActiveTechnique->getBoneCount();
int weightCount = mActiveTechnique->getWeightCount();
bool doBoneCalculations = isValid &&
(boneCount != 0) && (boneCount <= 256) &&
(weightCount != 0) && (weightCount <= 4) &&
((mCreator == NULL) || (boneCount <= mCreator->getMaxCalculableBoneCount()));
mActiveTechnique->setDoBoneCalculations(doBoneCalculations);
if ((doBoneCalculations) && (mCreator))
{
//update the receiver and caster materials
if (dstPass->getParent()->getShadowCasterMaterial().isNull())
{
dstPass->getParent()->setShadowCasterMaterial(
mCreator->getCustomShadowCasterMaterial(mSkinningType, weightCount - 1));
}
if (dstPass->getParent()->getShadowReceiverMaterial().isNull())
{
dstPass->getParent()->setShadowReceiverMaterial(
mCreator->getCustomShadowReceiverMaterial(mSkinningType, weightCount - 1));
}
}
return true;
}
//-----------------------------------------------------------------------
bool HardwareSkinning::resolveParameters(ProgramSet* programSet)
{
assert(!mActiveTechnique.isNull());
return mActiveTechnique->resolveParameters(programSet);
}
//-----------------------------------------------------------------------
bool HardwareSkinning::resolveDependencies(ProgramSet* programSet)
{
assert(!mActiveTechnique.isNull());
return mActiveTechnique->resolveDependencies(programSet);
}
//-----------------------------------------------------------------------
bool HardwareSkinning::addFunctionInvocations(ProgramSet* programSet)
{
assert(!mActiveTechnique.isNull());
return mActiveTechnique->addFunctionInvocations(programSet);
}
//-----------------------------------------------------------------------
HardwareSkinningFactory::HardwareSkinningFactory() :
mMaxCalculableBoneCount(70)
{
}
//-----------------------------------------------------------------------
const String& HardwareSkinningFactory::getType() const
{
return HardwareSkinning::Type;
}
//-----------------------------------------------------------------------
SubRenderState* HardwareSkinningFactory::createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator)
{
if (prop->name == "hardware_skinning")
{
bool hasError = false;
uint32 boneCount = 0;
uint32 weightCount = 0;
String skinningType = "";
SkinningType skinType = ST_LINEAR;
bool correctAntipodalityHandling = false;
bool scalingShearingSupport = false;
if(prop->values.size() >= 2)
{
AbstractNodeList::iterator it = prop->values.begin();
if(false == SGScriptTranslator::getUInt(*it, &boneCount))
hasError = true;
++it;
if(false == SGScriptTranslator::getUInt(*it, &weightCount))
hasError = true;
if(prop->values.size() >= 5)
{
++it;
SGScriptTranslator::getString(*it, &skinningType);
++it;
SGScriptTranslator::getBoolean(*it, &correctAntipodalityHandling);
++it;
SGScriptTranslator::getBoolean(*it, &scalingShearingSupport);
}
//If the skinningType is not specified or is specified incorrectly, default to linear skinning.
if(skinningType == "dual_quaternion")
{
skinType = ST_DUAL_QUATERNION;
}
else
{
skinType = ST_LINEAR;
}
}
if (hasError == true)
{
compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, "Expected the format: hardware_skinning <bone count> <weight count> [skinning type] [correct antipodality handling] [scaling/shearing support]");
return NULL;
}
else
{
//create and update the hardware skinning sub render state
SubRenderState* subRenderState = createOrRetrieveInstance(translator);
HardwareSkinning* hardSkinSrs = static_cast<HardwareSkinning*>(subRenderState);
hardSkinSrs->setHardwareSkinningParam(boneCount, weightCount, skinType, correctAntipodalityHandling, scalingShearingSupport);
return subRenderState;
}
}
return NULL;
}
//-----------------------------------------------------------------------
void HardwareSkinningFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState,
Pass* srcPass, Pass* dstPass)
{
ser->writeAttribute(4, "hardware_skinning");
HardwareSkinning* hardSkinSrs = static_cast<HardwareSkinning*>(subRenderState);
ser->writeValue(StringConverter::toString(hardSkinSrs->getBoneCount()));
ser->writeValue(StringConverter::toString(hardSkinSrs->getWeightCount()));
//Correct antipodality handling and scaling and shearing support are only really valid for dual quaternion skinning
if(hardSkinSrs->getSkinningType() == ST_DUAL_QUATERNION)
{
ser->writeValue("dual_quaternion");
ser->writeValue(StringConverter::toString(hardSkinSrs->hasCorrectAntipodalityHandling()));
ser->writeValue(StringConverter::toString(hardSkinSrs->hasScalingShearingSupport()));
}
}
//-----------------------------------------------------------------------
SubRenderState* HardwareSkinningFactory::createInstanceImpl()
{
HardwareSkinning* pSkin = OGRE_NEW HardwareSkinning;
pSkin->_setCreator(this);
return pSkin;
}
//-----------------------------------------------------------------------
void HardwareSkinningFactory::setCustomShadowCasterMaterials(const SkinningType skinningType, const MaterialPtr& caster1Weight, const MaterialPtr& caster2Weight,
const MaterialPtr& caster3Weight, const MaterialPtr& caster4Weight)
{
if(skinningType == ST_DUAL_QUATERNION)
{
mCustomShadowCasterMaterialsDualQuaternion[0] = caster1Weight;
mCustomShadowCasterMaterialsDualQuaternion[1] = caster2Weight;
mCustomShadowCasterMaterialsDualQuaternion[2] = caster3Weight;
mCustomShadowCasterMaterialsDualQuaternion[3] = caster4Weight;
}
else //if(skinningType == ST_LINEAR)
{
mCustomShadowCasterMaterialsLinear[0] = caster1Weight;
mCustomShadowCasterMaterialsLinear[1] = caster2Weight;
mCustomShadowCasterMaterialsLinear[2] = caster3Weight;
mCustomShadowCasterMaterialsLinear[3] = caster4Weight;
}
}
//-----------------------------------------------------------------------
void HardwareSkinningFactory::setCustomShadowReceiverMaterials(const SkinningType skinningType, const MaterialPtr& receiver1Weight, const MaterialPtr& receiver2Weight,
const MaterialPtr& receiver3Weight, const MaterialPtr& receiver4Weight)
{
if(skinningType == ST_DUAL_QUATERNION)
{
mCustomShadowReceiverMaterialsDualQuaternion[0] = receiver1Weight;
mCustomShadowReceiverMaterialsDualQuaternion[1] = receiver2Weight;
mCustomShadowReceiverMaterialsDualQuaternion[2] = receiver3Weight;
mCustomShadowReceiverMaterialsDualQuaternion[3] = receiver4Weight;
}
else //if(skinningType == ST_LINEAR)
{
mCustomShadowReceiverMaterialsLinear[0] = receiver1Weight;
mCustomShadowReceiverMaterialsLinear[1] = receiver2Weight;
mCustomShadowReceiverMaterialsLinear[2] = receiver3Weight;
mCustomShadowReceiverMaterialsLinear[3] = receiver4Weight;
}
}
//-----------------------------------------------------------------------
const MaterialPtr& HardwareSkinningFactory::getCustomShadowCasterMaterial(const SkinningType skinningType, ushort index) const
{
assert(index < HS_MAX_WEIGHT_COUNT);
if(skinningType == ST_DUAL_QUATERNION)
{
return mCustomShadowCasterMaterialsDualQuaternion[index];
}
else //if(skinningType = ST_LINEAR)
{
return mCustomShadowCasterMaterialsLinear[index];
}
}
//-----------------------------------------------------------------------
const MaterialPtr& HardwareSkinningFactory::getCustomShadowReceiverMaterial(const SkinningType skinningType, ushort index) const
{
assert(index < HS_MAX_WEIGHT_COUNT);
if(skinningType == ST_DUAL_QUATERNION)
{
return mCustomShadowReceiverMaterialsDualQuaternion[index];
}
else //if(skinningType == ST_LINEAR)
{
return mCustomShadowReceiverMaterialsLinear[index];
}
}
//-----------------------------------------------------------------------
void HardwareSkinningFactory::prepareEntityForSkinning(const Entity* pEntity, SkinningType skinningType,
bool correctAntidpodalityHandling, bool shearScale)
{
if (pEntity != NULL)
{
size_t lodLevels = pEntity->getNumManualLodLevels() + 1;
for(size_t indexLod = 0 ; indexLod < lodLevels ; ++indexLod)
{
const Entity* pCurEntity = pEntity;
if (indexLod > 0) pCurEntity = pEntity->getManualLodLevel(indexLod - 1);
unsigned int numSubEntities = pCurEntity->getNumSubEntities();
for(unsigned int indexSub = 0 ; indexSub < numSubEntities ; ++indexSub)
{
ushort boneCount = 0,weightCount = 0;
bool isValid = extractSkeletonData(pCurEntity, indexSub, boneCount, weightCount);
SubEntity* pSubEntity = pCurEntity->getSubEntity(indexSub);
const MaterialPtr& pMat = pSubEntity->getMaterial();
imprintSkeletonData(pMat, isValid, boneCount, weightCount, skinningType, correctAntidpodalityHandling, shearScale);
}
}
}
}
//-----------------------------------------------------------------------
bool HardwareSkinningFactory::extractSkeletonData(const Entity* pEntity, unsigned int subEntityIndex, ushort& boneCount, ushort& weightCount)
{
bool isValidData = false;
boneCount = 0;
weightCount = 0;
//Check if we have pose animation which the HS sub render state does not
//know how to handle
bool hasVertexAnim = pEntity->getMesh()->hasVertexAnimation();
//gather data on the skeleton
if (!hasVertexAnim && pEntity->hasSkeleton())
{
//get weights count
MeshPtr pMesh = pEntity->getMesh();
RenderOperation ro;
SubMesh* pSubMesh = pMesh->getSubMesh(subEntityIndex);
pSubMesh->_getRenderOperation(ro,0);
//get the largest bone assignment
boneCount = std::max<ushort>(pMesh->sharedBlendIndexToBoneIndexMap.size(), pSubMesh->blendIndexToBoneIndexMap.size());
//go over vertex deceleration
//check that they have blend indices and blend weights
const VertexElement* pDeclWeights = ro.vertexData->vertexDeclaration->findElementBySemantic(VES_BLEND_WEIGHTS,0);
const VertexElement* pDeclIndexes = ro.vertexData->vertexDeclaration->findElementBySemantic(VES_BLEND_INDICES,0);
if ((pDeclWeights != NULL) && (pDeclIndexes != NULL))
{
isValidData = true;
switch (pDeclWeights->getType())
{
case VET_FLOAT1: weightCount = 1; break;
case VET_FLOAT2: weightCount = 2; break;
case VET_FLOAT3: weightCount = 3; break;
case VET_FLOAT4: weightCount = 4; break;
default: isValidData = false;
}
}
}
return isValidData;
}
//-----------------------------------------------------------------------
bool HardwareSkinningFactory::imprintSkeletonData(const MaterialPtr& pMaterial, bool isVaild,
ushort boneCount, ushort weightCount, SkinningType skinningType, bool correctAntidpodalityHandling, bool scalingShearingSupport)
{
bool isUpdated = false;
if (pMaterial->getNumTechniques() > 0)
{
HardwareSkinning::SkinningData data;
//get the previous skinning data if available
UserObjectBindings& binding = pMaterial->getTechnique(0)->getUserObjectBindings();
const Any& hsAny = binding.getUserAny(HS_DATA_BIND_NAME);
if (hsAny.isEmpty() == false)
{
data = (any_cast<HardwareSkinning::SkinningData>(hsAny));
}
//check if we need to update the data
if (((data.isValid == true) && (isVaild == false)) ||
(data.maxBoneCount < boneCount) ||
(data.maxWeightCount < weightCount))
{
//update the data
isUpdated = true;
data.isValid &= isVaild;
data.maxBoneCount = std::max<ushort>(data.maxBoneCount, boneCount);
data.maxWeightCount = std::max<ushort>(data.maxWeightCount, weightCount);
data.skinningType = skinningType;
data.correctAntipodalityHandling = correctAntidpodalityHandling;
data.scalingShearingSupport = scalingShearingSupport;
//update the data in the material and invalidate it in the RTShader system
//do it will be regenerated
binding.setUserAny(HS_DATA_BIND_NAME, Any(data));
size_t schemeCount = ShaderGenerator::getSingleton().getRTShaderSchemeCount();
for(size_t i = 0 ; i < schemeCount ; ++i)
{
//invalidate the material so it will be recreated with the correct
//amount of bones and weights
const String& schemeName = ShaderGenerator::getSingleton().getRTShaderScheme(i);
ShaderGenerator::getSingleton().invalidateMaterial(
schemeName, pMaterial->getName(), pMaterial->getGroup());
}
}
}
return isUpdated;
}
}
}
#endif
| xsilium-frameworks/xsilium-engine | Library/Ogre/Components/RTShaderSystem/src/OgreShaderExHardwareSkinning.cpp | C++ | mit | 18,731 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.16 at 03:24:22 PM EEST
//
package org.ecloudmanager.tmrk.cloudapi.model;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
/**
* <p>Java class for ResourceBurstType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ResourceBurstType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Actions" type="{}ArrayOfActionType" minOccurs="0"/>
* <element name="Status" type="{}ResourceBurstStatus" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ResourceBurstType", propOrder = {
"actions",
"status"
})
public class ResourceBurstType {
@XmlElementRef(name = "Actions", type = JAXBElement.class, required = false)
protected JAXBElement<ArrayOfActionType> actions;
@XmlElement(name = "Status")
@XmlSchemaType(name = "string")
protected ResourceBurstStatus status;
/**
* Gets the value of the actions property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link ArrayOfActionType }{@code >}
*
*/
public JAXBElement<ArrayOfActionType> getActions() {
return actions;
}
/**
* Sets the value of the actions property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link ArrayOfActionType }{@code >}
*
*/
public void setActions(JAXBElement<ArrayOfActionType> value) {
this.actions = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link ResourceBurstStatus }
*
*/
public ResourceBurstStatus getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link ResourceBurstStatus }
*
*/
public void setStatus(ResourceBurstStatus value) {
this.status = value;
}
}
| AltisourceLabs/ecloudmanager | tmrk-cloudapi/src/main/java/org/ecloudmanager/tmrk/cloudapi/model/ResourceBurstType.java | Java | mit | 2,598 |
var searchData=
[
['vertical_5fline',['vertical_line',['../class_abstract_board.html#a78c4d43cc32d9dc74d73156497db6d3f',1,'AbstractBoard']]]
];
| dawidd6/qtictactoe | docs/search/variables_9.js | JavaScript | mit | 146 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.