code
stringlengths 4
1.01M
| language
stringclasses 2
values |
|---|---|
import * as React from "react";
import { CarbonIconProps } from "../../";
declare const Laptop24: React.ForwardRefExoticComponent<
CarbonIconProps & React.RefAttributes<SVGSVGElement>
>;
export default Laptop24;
|
Java
|
<!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>
|
Java
|
<!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>
|
Java
|
/* @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"];
|
Java
|
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();
}
}
}
|
Java
|
* {
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%;}
}
|
Java
|
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));
}
|
Java
|
---
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.
|
Java
|
/**
* 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
|
Java
|
<!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>
|
Java
|
/*
* 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
}
|
Java
|
// 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]);
|
Java
|
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)
}
|
Java
|
// 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)
|
Java
|
<!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>
|
Java
|
'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;
|
Java
|
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.
|
Java
|
/***********************************************************************************
** 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);
}
}
|
Java
|
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')
|
Java
|
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
|
Java
|
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"
}
});
|
Java
|
<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>
|
Java
|
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()
})
})
})
})
})
|
Java
|
{-# 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"}]
|
Java
|
"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) {
});
|
Java
|
(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);
|
Java
|
#!/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")
|
Java
|
// 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);
}
}
|
Java
|
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
|
Java
|
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")]
|
Java
|
/*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);
});
});
|
Java
|
<!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>
|
Java
|
<?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';
*/
|
Java
|
/*---------------------------------------------------------------------------------------------
* 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}; }`);
}
});
|
Java
|
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;
}
|
Java
|
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
|
Java
|
(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);
|
Java
|
// 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;
|
Java
|
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()
|
Java
|
<?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';
}
|
Java
|
<?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);
}
|
Java
|
/*!
* 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;
}));
|
Java
|
#!/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')
|
Java
|
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;
}
|
Java
|
#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) );
}
}
}
|
Java
|
/** \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);
}
|
Java
|
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);
}
};
};
|
Java
|
require File.dirname(__FILE__) + "/../spec_helper.rb"
|
Java
|
{% 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 -->
|
Java
|
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());
}
}
|
Java
|
##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);
}
}
```
|
Java
|
/*
-----------------------------------------------------------------------------
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
|
Java
|
//
// 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;
}
}
|
Java
|
var searchData=
[
['vertical_5fline',['vertical_line',['../class_abstract_board.html#a78c4d43cc32d9dc74d73156497db6d3f',1,'AbstractBoard']]]
];
|
Java
|
--[=[
TR_INFO: request information about an active transaction
this is the aux. library to encode the request buffer and decode the reply buffer.
encode(options_t) -> encoded options string
decode(info_buf, info_buf_len) -> decoded info table
USAGE:
- use it with isc_transaction_info() to encode the info request and decode the info result.
- see info_codes table below for what you can request and the structure and meaning of the results.
]=]
module(...,require 'fbclient.module')
local info = require 'fbclient.info'
local info_codes = { --read doc\sql.extensions\README.isc_info_xxx from firebird 2.5 sources for more info!
isc_info_tra_id = 4, --number: current tran ID number
isc_info_tra_oldest_interesting = 5, --number: oldest interesting tran ID when current tran started (firebird 2.0+)
isc_info_tra_oldest_snapshot = 6, --number: min. tran ID of tra_oldest_active (firebird 2.0+)
isc_info_tra_oldest_active = 7, --number: oldest active tran ID when current tran started (firebird 2.0+)
isc_info_tra_isolation = 8, --pair: {one of isc_info_tra_isolation_flags, [one of isc_info_tra_read_committed_flags]}: (firebird 2.0+)
isc_info_tra_access = 9, --string: 'isc_info_tra_readonly' or 'isc_info_tra_readwrite' (firebird 2.0+)
isc_info_tra_lock_timeout = 10, --number: lock timeout value; fb 2.0+
}
local info_code_lookup = index(info_codes)
local info_buf_sizes = {
isc_info_tra_id = INT_SIZE,
isc_info_tra_oldest_interesting = INT_SIZE,
isc_info_tra_oldest_snapshot = INT_SIZE,
isc_info_tra_oldest_active = INT_SIZE,
isc_info_tra_isolation = 1+1, -- for read_commited, you also get rec_version/no_rec_version flag!
isc_info_tra_access = 1,
isc_info_tra_lock_timeout = INT_SIZE,
}
local isc_info_tra_isolation_flags = {
isc_info_tra_consistency = 1,
isc_info_tra_concurrency = 2,
isc_info_tra_read_committed = 3,
}
local isc_info_tra_read_committed_flags = {
isc_info_tra_no_rec_version = 0,
isc_info_tra_rec_version = 1,
}
local isc_info_tra_access_flags = {
isc_info_tra_readonly = 0,
isc_info_tra_readwrite = 1,
}
local decoders = {
isc_info_tra_id = info.decode_unsigned,
isc_info_tra_oldest_interesting = info.decode_unsigned,
isc_info_tra_oldest_snapshot = info.decode_unsigned,
isc_info_tra_oldest_active = info.decode_unsigned,
isc_info_tra_isolation = function(s)
local isolation = info.decode_enum(isc_info_tra_isolation_flags)(s:sub(1,1))
local read_commited_flag
if isolation == 'isc_info_tra_read_committed' then
read_commited_flag = info.decode_enum(isc_info_tra_read_committed_flags)(s:sub(2,2))
end
return {isolation, read_commited_flag}
end,
isc_info_tra_access = info.decode_enum(isc_info_tra_access_flags),
isc_info_tra_lock_timeout = info.decode_unsigned,
}
function encode(opts)
return info.encode('TR_INFO', opts, info_codes, info_buf_sizes)
end
function decode(info_buf, info_buf_len)
return info.decode('TR_INFO', info_buf, info_buf_len, info_code_lookup, decoders)
end
|
Java
|
package runner
import (
"strings"
"testing"
"gopkg.in/stretchr/testify.v1/assert"
)
// https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/SQL.txt
var fuzzList = `
'
"
#
-
--
'%20--
--';
'%20;
=%20'
=%20;
=%20--
\x23
\x27
\x3D%20\x3B'
\x3D%20\x27
\x27\x4F\x52 SELECT *
\x27\x6F\x72 SELECT *
'or%20select *
admin'--
<>"'%;)(&+
'%20or%20''='
'%20or%20'x'='x
"%20or%20"x"="x
')%20or%20('x'='x
0 or 1=1
' or 0=0 --
" or 0=0 --
or 0=0 --
' or 0=0 #
" or 0=0 #
or 0=0 #
' or 1=1--
" or 1=1--
' or '1'='1'--
"' or 1 --'"
or 1=1--
or%201=1
or%201=1 --
' or 1=1 or ''='
" or 1=1 or ""="
' or a=a--
" or "a"="a
') or ('a'='a
") or ("a"="a
hi" or "a"="a
hi" or 1=1 --
hi' or 1=1 --
hi' or 'a'='a
hi') or ('a'='a
hi") or ("a"="a
'hi' or 'x'='x';
@variable
,@variable
PRINT
PRINT @@variable
select
insert
as
or
procedure
limit
order by
asc
desc
delete
update
distinct
having
truncate
replace
like
handler
bfilename
' or username like '%
' or uname like '%
' or userid like '%
' or uid like '%
' or user like '%
exec xp
exec sp
'; exec master..xp_cmdshell
'; exec xp_regread
t'exec master..xp_cmdshell 'nslookup www.google.com'--
--sp_password
\x27UNION SELECT
' UNION SELECT
' UNION ALL SELECT
' or (EXISTS)
' (select top 1
'||UTL_HTTP.REQUEST
1;SELECT%20*
to_timestamp_tz
tz_offset
<>"'%;)(&+
'%20or%201=1
%27%20or%201=1
%20$(sleep%2050)
%20'sleep%2050'
char%4039%41%2b%40SELECT
'%20OR
'sqlattempt1
(sqlattempt2)
|
%7C
*|
%2A%7C
*(|(mail=*))
%2A%28%7C%28mail%3D%2A%29%29
*(|(objectclass=*))
%2A%28%7C%28objectclass%3D%2A%29%29
(
%28
)
%29
&
%26
!
%21
' or 1=1 or ''='
' or ''='
x' or 1=1 or 'x'='y
/
//
//*
*/*
`
func init() {
fuzzList += "\b"
fuzzList += "\n"
fuzzList += "\n"
fuzzList += "\r"
fuzzList += "\t"
fuzzList += "Hello\tworld"
}
func TestSQLInjectionBuilder(t *testing.T) {
for _, fuzz := range strings.Split(fuzzList, "\n") {
if fuzz == "" {
continue
}
fuzz = strings.Trim(fuzz, " \t")
var id int64
var comment string
err := testDB.
InsertInto("comments").
Columns("comment").
Values(fuzz).
SetIsInterpolated(true).
Returning("id", "comment").
QueryScalar(&id, &comment)
assert.True(t, id > 0)
assert.Equal(t, fuzz, comment)
var result int
err = testDB.SQL(`
SELECT 42
FROM comments
WHERE id = $1 AND comment = $2
`, id, comment).QueryScalar(&result)
assert.NoError(t, err)
assert.Equal(t, 42, result)
}
}
func TestSQLInjectionSQL(t *testing.T) {
for _, fuzz := range strings.Split(fuzzList, "\n") {
if fuzz == "" {
continue
}
fuzz = strings.Trim(fuzz, " \t")
var id int64
var comment string
err := testDB.
SQL(`
INSERT INTO comments (comment)
VALUES ($1)
RETURNING id, comment
`, fuzz).
SetIsInterpolated(true).
QueryScalar(&id, &comment)
assert.True(t, id > 0)
assert.Equal(t, fuzz, comment)
var result int
err = testDB.SQL(`
SELECT 42
FROM comments
WHERE id = $1 AND comment = $2
`, id, comment).QueryScalar(&result)
assert.NoError(t, err)
assert.Equal(t, 42, result)
}
}
|
Java
|
ColorFrameReference.RelativeTime Property
=========================================
Gets the timestamp of the referenced color frame. <span id="syntaxSection"></span>
Syntax
======
<table>
<colgroup>
<col width="100%" />
</colgroup>
<thead>
<tr class="header">
<th align="left">C++</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><pre><code>public:
property TimeSpan RelativeTime {
TimeSpan get ();
}</code></pre></td>
</tr>
</tbody>
</table>
<table>
<colgroup>
<col width="100%" />
</colgroup>
<thead>
<tr class="header">
<th align="left">C#</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><pre><code>public TimeSpan RelativeTime { get; }</code></pre></td>
</tr>
</tbody>
</table>
<table>
<colgroup>
<col width="100%" />
</colgroup>
<thead>
<tr class="header">
<th align="left">JavaScript</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><pre><code>var relativeTime = colorFrameReference.relativeTime;</code></pre></td>
</tr>
</tbody>
</table>
<span id="ID4EU"></span>
#### Property value
[C++]
[C\#]
[JavaScript]
Type: [TimeSpan](http://msdn.microsoft.com/en-us/library/windows.foundation.timespan.aspx)
Type: [TimeSpan](http://msdn.microsoft.com/en-us/library/system.timespan.aspx)
Type: Number
The timestamp of the referenced color frame.
<span id="requirements"></span>
Requirements
============
**Namespace:**WindowsPreview.Kinect
**Metadata:**windowspreview.kinect.winmd
<span id="ID4ECB"></span>
See also
========
<span id="ID4EEB"></span>
#### Reference
[ColorFrameReference Class](../../ColorFrameReference_Class.md)
[WindowsPreview.Kinect Namespace](../../../Kinect.md)
<!--Please do not edit the data in the comment block below.-->
<!--
TOCTitle : RelativeTime Property
RLTitle : ColorFrameReference.RelativeTime Property
KeywordK : RelativeTime property
KeywordK : ColorFrameReference.RelativeTime property
KeywordF : WindowsPreview.Kinect.ColorFrameReference.RelativeTime
KeywordF : ColorFrameReference.RelativeTime
KeywordF : RelativeTime
KeywordF : WindowsPreview.Kinect.ColorFrameReference.RelativeTime
KeywordA : P:WindowsPreview.Kinect.ColorFrameReference.RelativeTime
AssetID : P:WindowsPreview.Kinect.ColorFrameReference.RelativeTime
Locale : en-us
CommunityContent : 1
APIType : Managed
APILocation : windowspreview.kinect.winmd
APIName : WindowsPreview.Kinect.ColorFrameReference.RelativeTime
TargetOS : Windows
TopicType : kbSyntax
DevLang : VB
DevLang : CSharp
DevLang : JavaScript
DevLang : C++
DocSet : K4Wv2
ProjType : K4Wv2Proj
Technology : Kinect for Windows
Product : Kinect for Windows SDK v2
productversion : 20
-->
|
Java
|
import flask
from donut import auth_utils
from donut.modules.account import blueprint, helpers
@blueprint.route("/request")
def request_account():
"""Provides a form to request an account."""
return flask.render_template("request_account.html")
@blueprint.route("/request/submit", methods=["POST"])
def request_account_submit():
"""Handles an account creation request."""
uid = flask.request.form.get("uid", None)
last_name = flask.request.form.get("last_name", None)
if uid is None or last_name is None:
flask.flash("Invalid request.")
return flask.redirect(flask.url_for("account.request_account"))
success, error_msg = helpers.handle_request_account(uid, last_name)
if success:
flask.flash(
"An email has been sent with a link to create your account.")
return flask.redirect(flask.url_for("home"))
else:
flask.flash(error_msg)
return flask.redirect(flask.url_for("account.request_account"))
@blueprint.route("/create/<create_account_key>")
def create_account(create_account_key):
"""Checks the key. If valid, displays the create account page."""
user_id = auth_utils.check_create_account_key(create_account_key)
if user_id is None:
flask.current_app.logger.warn(
f'Invalid create_account_key: {create_account_key}')
flask.flash("Invalid request. Please check your link and try again.")
return flask.redirect(flask.url_for("home"))
user_data = helpers.get_user_data(user_id)
if user_data is None:
flask.flash("An unexpected error occurred. Please contact DevTeam.")
return flask.redirect(flask.url_for("home"))
return flask.render_template(
"create_account.html", user_data=user_data, key=create_account_key)
@blueprint.route("/create/<create_account_key>/submit", methods=["POST"])
def create_account_submit(create_account_key):
"""Handles a create account request."""
user_id = auth_utils.check_create_account_key(create_account_key)
if user_id is None:
# Key is invalid.
flask.current_app.logger.warn(
f'Invalid create_account_key: {create_account_key}')
flask.flash("Someone's been naughty.")
return flask.redirect(flask.url_for("home"))
username = flask.request.form.get("username", None)
password = flask.request.form.get("password", None)
password2 = flask.request.form.get("password2", None)
if username is None \
or password is None \
or password2 is None:
flask.current_app.logger.warn(
f'Invalid create account form for user ID {user_id}')
flask.flash("Invalid request.")
return flask.redirect(flask.url_for("home"))
if helpers.handle_create_account(user_id, username, password, password2):
flask.session['username'] = username
flask.current_app.logger.info(
f'Created account with username {username} for user ID {user_id}')
flask.flash("Account successfully created.")
return flask.redirect(flask.url_for("home"))
else:
# Flashes already handled.
return flask.redirect(
flask.url_for(
"account.create_account",
create_account_key=create_account_key))
|
Java
|
<!DOCTYPE html>
<html ng-app="recoveryApp" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="bower_components/angular/angular.js"></script>
<script type="text/javascript" src="bower_components/sjcl/sjcl.js"></script>
<script type="text/javascript" src="bower_components/bitcore/bitcore.min.js"></script>
<script type="text/javascript" src="bower_components/bitcore/bitcore.js"></script>
<script type="text/javascript" src="bower_components/bitcore-mnemonic/bitcore-mnemonic.min.js"></script>
<script type="text/javascript" src="bower_components/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="bower_components/ng-lodash/build/ng-lodash.min.js"></script>
<script type="text/javascript" src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://css-spinners.com/css/spinner/hexdots.css" type="text/css">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="main.css"></link>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/md5.js"></script>
<script type="text/javascript" src="js/services.js"></script>
<script type="text/javascript" src="js/controllers.js"></script>
<title>Copay recovery tool</title>
</head>
<div id="wrapper">
<header class="page-header">
<div class="container">
<img src="./img/logo-white.svg" alt="Copay" width="100" style="vertical-align: middle";>
<span class="label">recovery tool</span>
<ul class="pull-right">
<li><a href="https://github.com/bitpay/copay-recovery">View the Code</a></li>
</ul>
</div>
</header>
<body ng-controller="recoveryController" style="background-color:#F4F6F9">
<div class="container">
<div id="sendBlock" style="display: none;">
<div class="form-group">
<label>{{totalBalance}}</label>
<div class="input-group">
<div class="input-group-addon" >Destination Address :</div>
<input type="text" class="form-control" ng-model="addr">
</div>
</div>
<button class="btn btn-primary" ng-click="sendFunds()">Transfer</button><br><br>
</div>
<div id="inputs">
<h4>Wallet configuration:</h4>
<div class="row">
<div class="col-md-3">
<label>Required signatures</label>
<select class="pull-right" id="selectM">
<option id="1">1</option>
<option id="2">2</option>
<option id="3">3</option>
<option id="4">4</option>
<option id="5">5</option>
<option id="6">6</option>
</select><br>
<label>Total Copayers</label>
<select class="pull-right" id="selectN">
<option id="1">1</option>
<option id="2">2</option>
<option id="3">3</option>
<option id="4">4</option>
<option id="5">5</option>
<option id="6">6</option>
</select><br>
<label>Network</label>
<select class="pull-right" id="selectNet">
<option id="livenet">Livenet</option>
<option id="testnet">Testnet</option>
</select><br><br>
</div>
</div>
<div class="form-group" id="block1">
<label>Backup for copayer 1:</label>
<div class="form-group" id="backup1">
<input type="text" class="form-control" ng-model="backUp[1]" placeholder="Mnemonic or export wallet data">
</div>
<div class="form-group" id="backupFile1">
<label>Or upload a file: </label>
<input type="file" ng-model="file1" on-read-file="showContent($fileContent, 1)" accept="application/json, .txt" style="display: inline">
</div>
<div class="form-group" id="password1">
<label>Password:</label>
<input type="password" class="form-control" ng-model="pass[1]">
</div>
<div class="form-goup" id="passwordX1">
<br>
<label>Encrypted private key password (in case you have one):</label>
<input type="password" class="form-control" ng-model="passX[1]" id="passX1">
</div><hr>
</div>
<div id="block2" style="display: none">
<label>Backup for copayer 2:</label>
<br>
<div class="form-group" id="backup2">
<input type="text" class="form-control" ng-model="backUp[2]" placeholder="Mnemonic or export wallet data">
</div>
<div class="form-group" id="backupFile2">
<label>Or upload a file: </label>
<input type="file" ng-model="file2" on-read-file="showContent($fileContent, 2)" accept="application/json, .txt" style="display: inline">
</div>
<div class="form-group" id="password2">
<label>Password:</label>
<input type="password" class="form-control" ng-model="pass[2]">
</div>
<div class="form-goup" id="passwordX2">
<br>
<label>Encrypted private key password (in case you have one):</label>
<input type="password" class="form-control" ng-model="passX[2]" id="passX2">
</div><hr>
</div>
<div id="block3" style="display: none">
<label>Backup for copayer 3:</label>
<br>
<div class="form-group" id="backup3">
<input type="text" class="form-control" ng-model="backUp[3]" placeholder="Mnemonic or export wallet data">
</div>
<div class="form-group" id="backupFile3">
<label>Or upload a file: </label>
<input type="file" ng-model="file3" on-read-file="showContent($fileContent, 3)" accept="application/json, .txt" style="display: inline">
</div>
<div class="form-group" id="password3">
<label>Password:</label>
<input type="password" class="form-control" ng-model="pass[3]">
</div>
<div class="form-goup" id="passwordX3">
<br>
<label>Encrypted private key password (in case you have one):</label>
<input type="password" class="form-control" ng-model="passX[3]" id="passX3">
</div><hr>
</div>
<div id="block4" style="display: none">
<br>
<label>Backup for copayer 4:</label>
<br>
<div class="form-group" id="backup4">
<input type="text" class="form-control" ng-model="backUp[4]" placeholder="Mnemonic or export wallet data">
</div>
<div class="form-group" id="backupFile4">
<label>Or upload a file: </label>
<input type="file" ng-model="file4" on-read-file="showContent($fileContent, 4)" accept="application/json, .txt" style="display: inline">
</div>
<div class="form-group" id="password4">
<label>Password:</label>
<input type="password" class="form-control" ng-model="pass[4]">
</div>
<div class="form-goup" id="passwordX4">
<br>
<label>Encrypted private key password (in case you have one):</label>
<input type="password" class="form-control" ng-model="passX[4]" id="passX4">
</div><hr>
</div>
<div id="block5" style="display: none">
<br>
<label>Backup for copayer 5:</label>
<br>
<div class="form-group" id="backup5">
<input type="text" class="form-control" ng-model="backUp[5]" placeholder="Mnemonic or export wallet data">
</div>
<div class="form-group" id="backupFile5">
<label>Or upload a file: </label>
<input type="file" ng-model="file5" on-read-file="showContent($fileContent, 5)" accept="application/json, .txt" style="display: inline">
</div>
<div class="form-group" id="password5">
<label>Password:</label>
<input type="password" class="form-control" ng-model="pass[5]">
</div>
<div class="form-goup" id="passwordX5">
<br>
<label>Encrypted private key password (in case you have one):</label>
<input type="password" class="form-control" ng-model="passX[5]" id="passX5">
</div><hr>
</div>
<div id="block6" style="display: none">
<br>
<label>Backup for copayer 6:</label>
<br>
<div class="form-group" id="backup6">
<input type="text" class="form-control" ng-model="backUp[6]" placeholder="Mnemonic or export wallet data">
</div>
<div class="form-group" id="backupFile6">
<label>Or upload a file: </label>
<input type="file" ng-model="file6" on-read-file="showContent($fileContent, 6)" accept="application/json, .txt" style="display: inline">
</div>
<div class="form-group" id="password6">
<label>Password:</label>
<input type="password" class="form-control" ng-model="pass[6]">
</div>
<div class="form-goup" id="passwordX6">
<br>
<label>Encrypted private key password (in case you have one):</label>
<input type="password" class="form-control" ng-model="passX[6]" id="passX6">
</div><hr>
</div>
<button class="btn btn-primary" ng-click="proccessInputs()">Scan wallet</button><br><br>
</div>
<div class="modal fade" id="myModal" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog" style="position: absolute;display: block;top: 50%;left: 50%;">
<!-- Modal content-->
<div class="hexdots-loader" ></div>
</div>
</div>
<div id="successMessage" class="alert alert-success" style="display: none;">
{{successMessage}}
</div>
<div id="errorMessage" class="alert alert-danger" style="display: none;">
{{errorMessage}}
</div>
<div id="statusMessage" class="alert alert-info" style="display: none;">
{{statusMessage}}
</div>
</div>
</body>
<footer class="page-footer">
<div id="back" style="display: none">
<ul>
<li><a href="http://bitpay.github.io/copay-recovery/">Back</a></li>
</ul>
</div>
</footer>
</div>
</html>
|
Java
|
package org.ominidi.api.controller;
import org.ominidi.api.exception.ConnectionException;
import org.ominidi.api.exception.NotFoundException;
import org.ominidi.api.model.Errors;
import org.ominidi.domain.model.Feed;
import org.ominidi.domain.model.Post;
import org.ominidi.facebook.service.PageFeedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
@RequestMapping("/api/v1")
public class FeedController {
private PageFeedService pageFeedService;
@Autowired
public FeedController(PageFeedService pageFeedService) {
this.pageFeedService = pageFeedService;
}
@GetMapping(value = "/feed", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Feed<Post> getFeed(@RequestParam(value = "u", required = false) Optional<String> feedUrl) {
Optional<Feed<Post>> result = feedUrl.isPresent()
? pageFeedService.getFeed(feedUrl.get())
: pageFeedService.getFeed();
return result.orElseThrow(() -> new ConnectionException(Errors.CONNECTION_PROBLEM));
}
@GetMapping(value = "/post/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Post getPost(@PathVariable(value = "id") String id) {
return pageFeedService.getPostById(id).orElseThrow(() -> new NotFoundException(Errors.postNotFound(id)));
}
}
|
Java
|
#include "jsonobject.h"
#include "jsonparser.h"
namespace amgcommon {
namespace json {
JsonObject::JsonObject(string rawJson) {
this->originalJson = rawJson;
this->root = JsonNode();
}
JsonObject::JsonObject(const JsonObject &a) {
this->originalJson = a.originalJson;
this->root = a.root;
}
JsonObject *JsonObject::clone() {
return new JsonObject(*this);
}
JsonObject::~JsonObject() {
}
string JsonObject::toString() {
return this->root.toString();
}
JsonNode JsonObject::getRoot() {
return root;
}
void JsonObject::setKey(string path, Object *value) {
this->root.setKey(path, value);
}
Object *JsonObject::getKey(string path) {
return this->root.getKey(path);
}
}
}
|
Java
|
default rel
%define XMMWORD
%define YMMWORD
%define ZMMWORD
section .text code align=64
EXTERN OPENSSL_ia32cap_P
global sha1_block_data_order
ALIGN 16
sha1_block_data_order:
mov QWORD[8+rsp],rdi ;WIN64 prologue
mov QWORD[16+rsp],rsi
mov rax,rsp
$L$SEH_begin_sha1_block_data_order:
mov rdi,rcx
mov rsi,rdx
mov rdx,r8
lea r10,[OPENSSL_ia32cap_P]
mov r9d,DWORD[r10]
mov r8d,DWORD[4+r10]
mov r10d,DWORD[8+r10]
test r8d,512
jz NEAR $L$ialu
and r8d,268435456
and r9d,1073741824
or r8d,r9d
cmp r8d,1342177280
je NEAR _avx_shortcut
jmp NEAR _ssse3_shortcut
ALIGN 16
$L$ialu:
mov rax,rsp
push rbx
push rbp
push r12
push r13
push r14
mov r8,rdi
sub rsp,72
mov r9,rsi
and rsp,-64
mov r10,rdx
mov QWORD[64+rsp],rax
$L$prologue:
mov esi,DWORD[r8]
mov edi,DWORD[4+r8]
mov r11d,DWORD[8+r8]
mov r12d,DWORD[12+r8]
mov r13d,DWORD[16+r8]
jmp NEAR $L$loop
ALIGN 16
$L$loop:
mov edx,DWORD[r9]
bswap edx
mov ebp,DWORD[4+r9]
mov eax,r12d
mov DWORD[rsp],edx
mov ecx,esi
bswap ebp
xor eax,r11d
rol ecx,5
and eax,edi
lea r13d,[1518500249+r13*1+rdx]
add r13d,ecx
xor eax,r12d
rol edi,30
add r13d,eax
mov r14d,DWORD[8+r9]
mov eax,r11d
mov DWORD[4+rsp],ebp
mov ecx,r13d
bswap r14d
xor eax,edi
rol ecx,5
and eax,esi
lea r12d,[1518500249+r12*1+rbp]
add r12d,ecx
xor eax,r11d
rol esi,30
add r12d,eax
mov edx,DWORD[12+r9]
mov eax,edi
mov DWORD[8+rsp],r14d
mov ecx,r12d
bswap edx
xor eax,esi
rol ecx,5
and eax,r13d
lea r11d,[1518500249+r11*1+r14]
add r11d,ecx
xor eax,edi
rol r13d,30
add r11d,eax
mov ebp,DWORD[16+r9]
mov eax,esi
mov DWORD[12+rsp],edx
mov ecx,r11d
bswap ebp
xor eax,r13d
rol ecx,5
and eax,r12d
lea edi,[1518500249+rdi*1+rdx]
add edi,ecx
xor eax,esi
rol r12d,30
add edi,eax
mov r14d,DWORD[20+r9]
mov eax,r13d
mov DWORD[16+rsp],ebp
mov ecx,edi
bswap r14d
xor eax,r12d
rol ecx,5
and eax,r11d
lea esi,[1518500249+rsi*1+rbp]
add esi,ecx
xor eax,r13d
rol r11d,30
add esi,eax
mov edx,DWORD[24+r9]
mov eax,r12d
mov DWORD[20+rsp],r14d
mov ecx,esi
bswap edx
xor eax,r11d
rol ecx,5
and eax,edi
lea r13d,[1518500249+r13*1+r14]
add r13d,ecx
xor eax,r12d
rol edi,30
add r13d,eax
mov ebp,DWORD[28+r9]
mov eax,r11d
mov DWORD[24+rsp],edx
mov ecx,r13d
bswap ebp
xor eax,edi
rol ecx,5
and eax,esi
lea r12d,[1518500249+r12*1+rdx]
add r12d,ecx
xor eax,r11d
rol esi,30
add r12d,eax
mov r14d,DWORD[32+r9]
mov eax,edi
mov DWORD[28+rsp],ebp
mov ecx,r12d
bswap r14d
xor eax,esi
rol ecx,5
and eax,r13d
lea r11d,[1518500249+r11*1+rbp]
add r11d,ecx
xor eax,edi
rol r13d,30
add r11d,eax
mov edx,DWORD[36+r9]
mov eax,esi
mov DWORD[32+rsp],r14d
mov ecx,r11d
bswap edx
xor eax,r13d
rol ecx,5
and eax,r12d
lea edi,[1518500249+rdi*1+r14]
add edi,ecx
xor eax,esi
rol r12d,30
add edi,eax
mov ebp,DWORD[40+r9]
mov eax,r13d
mov DWORD[36+rsp],edx
mov ecx,edi
bswap ebp
xor eax,r12d
rol ecx,5
and eax,r11d
lea esi,[1518500249+rsi*1+rdx]
add esi,ecx
xor eax,r13d
rol r11d,30
add esi,eax
mov r14d,DWORD[44+r9]
mov eax,r12d
mov DWORD[40+rsp],ebp
mov ecx,esi
bswap r14d
xor eax,r11d
rol ecx,5
and eax,edi
lea r13d,[1518500249+r13*1+rbp]
add r13d,ecx
xor eax,r12d
rol edi,30
add r13d,eax
mov edx,DWORD[48+r9]
mov eax,r11d
mov DWORD[44+rsp],r14d
mov ecx,r13d
bswap edx
xor eax,edi
rol ecx,5
and eax,esi
lea r12d,[1518500249+r12*1+r14]
add r12d,ecx
xor eax,r11d
rol esi,30
add r12d,eax
mov ebp,DWORD[52+r9]
mov eax,edi
mov DWORD[48+rsp],edx
mov ecx,r12d
bswap ebp
xor eax,esi
rol ecx,5
and eax,r13d
lea r11d,[1518500249+r11*1+rdx]
add r11d,ecx
xor eax,edi
rol r13d,30
add r11d,eax
mov r14d,DWORD[56+r9]
mov eax,esi
mov DWORD[52+rsp],ebp
mov ecx,r11d
bswap r14d
xor eax,r13d
rol ecx,5
and eax,r12d
lea edi,[1518500249+rdi*1+rbp]
add edi,ecx
xor eax,esi
rol r12d,30
add edi,eax
mov edx,DWORD[60+r9]
mov eax,r13d
mov DWORD[56+rsp],r14d
mov ecx,edi
bswap edx
xor eax,r12d
rol ecx,5
and eax,r11d
lea esi,[1518500249+rsi*1+r14]
add esi,ecx
xor eax,r13d
rol r11d,30
add esi,eax
xor ebp,DWORD[rsp]
mov eax,r12d
mov DWORD[60+rsp],edx
mov ecx,esi
xor ebp,DWORD[8+rsp]
xor eax,r11d
rol ecx,5
xor ebp,DWORD[32+rsp]
and eax,edi
lea r13d,[1518500249+r13*1+rdx]
rol edi,30
xor eax,r12d
add r13d,ecx
rol ebp,1
add r13d,eax
xor r14d,DWORD[4+rsp]
mov eax,r11d
mov DWORD[rsp],ebp
mov ecx,r13d
xor r14d,DWORD[12+rsp]
xor eax,edi
rol ecx,5
xor r14d,DWORD[36+rsp]
and eax,esi
lea r12d,[1518500249+r12*1+rbp]
rol esi,30
xor eax,r11d
add r12d,ecx
rol r14d,1
add r12d,eax
xor edx,DWORD[8+rsp]
mov eax,edi
mov DWORD[4+rsp],r14d
mov ecx,r12d
xor edx,DWORD[16+rsp]
xor eax,esi
rol ecx,5
xor edx,DWORD[40+rsp]
and eax,r13d
lea r11d,[1518500249+r11*1+r14]
rol r13d,30
xor eax,edi
add r11d,ecx
rol edx,1
add r11d,eax
xor ebp,DWORD[12+rsp]
mov eax,esi
mov DWORD[8+rsp],edx
mov ecx,r11d
xor ebp,DWORD[20+rsp]
xor eax,r13d
rol ecx,5
xor ebp,DWORD[44+rsp]
and eax,r12d
lea edi,[1518500249+rdi*1+rdx]
rol r12d,30
xor eax,esi
add edi,ecx
rol ebp,1
add edi,eax
xor r14d,DWORD[16+rsp]
mov eax,r13d
mov DWORD[12+rsp],ebp
mov ecx,edi
xor r14d,DWORD[24+rsp]
xor eax,r12d
rol ecx,5
xor r14d,DWORD[48+rsp]
and eax,r11d
lea esi,[1518500249+rsi*1+rbp]
rol r11d,30
xor eax,r13d
add esi,ecx
rol r14d,1
add esi,eax
xor edx,DWORD[20+rsp]
mov eax,edi
mov DWORD[16+rsp],r14d
mov ecx,esi
xor edx,DWORD[28+rsp]
xor eax,r12d
rol ecx,5
xor edx,DWORD[52+rsp]
lea r13d,[1859775393+r13*1+r14]
xor eax,r11d
add r13d,ecx
rol edi,30
add r13d,eax
rol edx,1
xor ebp,DWORD[24+rsp]
mov eax,esi
mov DWORD[20+rsp],edx
mov ecx,r13d
xor ebp,DWORD[32+rsp]
xor eax,r11d
rol ecx,5
xor ebp,DWORD[56+rsp]
lea r12d,[1859775393+r12*1+rdx]
xor eax,edi
add r12d,ecx
rol esi,30
add r12d,eax
rol ebp,1
xor r14d,DWORD[28+rsp]
mov eax,r13d
mov DWORD[24+rsp],ebp
mov ecx,r12d
xor r14d,DWORD[36+rsp]
xor eax,edi
rol ecx,5
xor r14d,DWORD[60+rsp]
lea r11d,[1859775393+r11*1+rbp]
xor eax,esi
add r11d,ecx
rol r13d,30
add r11d,eax
rol r14d,1
xor edx,DWORD[32+rsp]
mov eax,r12d
mov DWORD[28+rsp],r14d
mov ecx,r11d
xor edx,DWORD[40+rsp]
xor eax,esi
rol ecx,5
xor edx,DWORD[rsp]
lea edi,[1859775393+rdi*1+r14]
xor eax,r13d
add edi,ecx
rol r12d,30
add edi,eax
rol edx,1
xor ebp,DWORD[36+rsp]
mov eax,r11d
mov DWORD[32+rsp],edx
mov ecx,edi
xor ebp,DWORD[44+rsp]
xor eax,r13d
rol ecx,5
xor ebp,DWORD[4+rsp]
lea esi,[1859775393+rsi*1+rdx]
xor eax,r12d
add esi,ecx
rol r11d,30
add esi,eax
rol ebp,1
xor r14d,DWORD[40+rsp]
mov eax,edi
mov DWORD[36+rsp],ebp
mov ecx,esi
xor r14d,DWORD[48+rsp]
xor eax,r12d
rol ecx,5
xor r14d,DWORD[8+rsp]
lea r13d,[1859775393+r13*1+rbp]
xor eax,r11d
add r13d,ecx
rol edi,30
add r13d,eax
rol r14d,1
xor edx,DWORD[44+rsp]
mov eax,esi
mov DWORD[40+rsp],r14d
mov ecx,r13d
xor edx,DWORD[52+rsp]
xor eax,r11d
rol ecx,5
xor edx,DWORD[12+rsp]
lea r12d,[1859775393+r12*1+r14]
xor eax,edi
add r12d,ecx
rol esi,30
add r12d,eax
rol edx,1
xor ebp,DWORD[48+rsp]
mov eax,r13d
mov DWORD[44+rsp],edx
mov ecx,r12d
xor ebp,DWORD[56+rsp]
xor eax,edi
rol ecx,5
xor ebp,DWORD[16+rsp]
lea r11d,[1859775393+r11*1+rdx]
xor eax,esi
add r11d,ecx
rol r13d,30
add r11d,eax
rol ebp,1
xor r14d,DWORD[52+rsp]
mov eax,r12d
mov DWORD[48+rsp],ebp
mov ecx,r11d
xor r14d,DWORD[60+rsp]
xor eax,esi
rol ecx,5
xor r14d,DWORD[20+rsp]
lea edi,[1859775393+rdi*1+rbp]
xor eax,r13d
add edi,ecx
rol r12d,30
add edi,eax
rol r14d,1
xor edx,DWORD[56+rsp]
mov eax,r11d
mov DWORD[52+rsp],r14d
mov ecx,edi
xor edx,DWORD[rsp]
xor eax,r13d
rol ecx,5
xor edx,DWORD[24+rsp]
lea esi,[1859775393+rsi*1+r14]
xor eax,r12d
add esi,ecx
rol r11d,30
add esi,eax
rol edx,1
xor ebp,DWORD[60+rsp]
mov eax,edi
mov DWORD[56+rsp],edx
mov ecx,esi
xor ebp,DWORD[4+rsp]
xor eax,r12d
rol ecx,5
xor ebp,DWORD[28+rsp]
lea r13d,[1859775393+r13*1+rdx]
xor eax,r11d
add r13d,ecx
rol edi,30
add r13d,eax
rol ebp,1
xor r14d,DWORD[rsp]
mov eax,esi
mov DWORD[60+rsp],ebp
mov ecx,r13d
xor r14d,DWORD[8+rsp]
xor eax,r11d
rol ecx,5
xor r14d,DWORD[32+rsp]
lea r12d,[1859775393+r12*1+rbp]
xor eax,edi
add r12d,ecx
rol esi,30
add r12d,eax
rol r14d,1
xor edx,DWORD[4+rsp]
mov eax,r13d
mov DWORD[rsp],r14d
mov ecx,r12d
xor edx,DWORD[12+rsp]
xor eax,edi
rol ecx,5
xor edx,DWORD[36+rsp]
lea r11d,[1859775393+r11*1+r14]
xor eax,esi
add r11d,ecx
rol r13d,30
add r11d,eax
rol edx,1
xor ebp,DWORD[8+rsp]
mov eax,r12d
mov DWORD[4+rsp],edx
mov ecx,r11d
xor ebp,DWORD[16+rsp]
xor eax,esi
rol ecx,5
xor ebp,DWORD[40+rsp]
lea edi,[1859775393+rdi*1+rdx]
xor eax,r13d
add edi,ecx
rol r12d,30
add edi,eax
rol ebp,1
xor r14d,DWORD[12+rsp]
mov eax,r11d
mov DWORD[8+rsp],ebp
mov ecx,edi
xor r14d,DWORD[20+rsp]
xor eax,r13d
rol ecx,5
xor r14d,DWORD[44+rsp]
lea esi,[1859775393+rsi*1+rbp]
xor eax,r12d
add esi,ecx
rol r11d,30
add esi,eax
rol r14d,1
xor edx,DWORD[16+rsp]
mov eax,edi
mov DWORD[12+rsp],r14d
mov ecx,esi
xor edx,DWORD[24+rsp]
xor eax,r12d
rol ecx,5
xor edx,DWORD[48+rsp]
lea r13d,[1859775393+r13*1+r14]
xor eax,r11d
add r13d,ecx
rol edi,30
add r13d,eax
rol edx,1
xor ebp,DWORD[20+rsp]
mov eax,esi
mov DWORD[16+rsp],edx
mov ecx,r13d
xor ebp,DWORD[28+rsp]
xor eax,r11d
rol ecx,5
xor ebp,DWORD[52+rsp]
lea r12d,[1859775393+r12*1+rdx]
xor eax,edi
add r12d,ecx
rol esi,30
add r12d,eax
rol ebp,1
xor r14d,DWORD[24+rsp]
mov eax,r13d
mov DWORD[20+rsp],ebp
mov ecx,r12d
xor r14d,DWORD[32+rsp]
xor eax,edi
rol ecx,5
xor r14d,DWORD[56+rsp]
lea r11d,[1859775393+r11*1+rbp]
xor eax,esi
add r11d,ecx
rol r13d,30
add r11d,eax
rol r14d,1
xor edx,DWORD[28+rsp]
mov eax,r12d
mov DWORD[24+rsp],r14d
mov ecx,r11d
xor edx,DWORD[36+rsp]
xor eax,esi
rol ecx,5
xor edx,DWORD[60+rsp]
lea edi,[1859775393+rdi*1+r14]
xor eax,r13d
add edi,ecx
rol r12d,30
add edi,eax
rol edx,1
xor ebp,DWORD[32+rsp]
mov eax,r11d
mov DWORD[28+rsp],edx
mov ecx,edi
xor ebp,DWORD[40+rsp]
xor eax,r13d
rol ecx,5
xor ebp,DWORD[rsp]
lea esi,[1859775393+rsi*1+rdx]
xor eax,r12d
add esi,ecx
rol r11d,30
add esi,eax
rol ebp,1
xor r14d,DWORD[36+rsp]
mov eax,r12d
mov DWORD[32+rsp],ebp
mov ebx,r12d
xor r14d,DWORD[44+rsp]
and eax,r11d
mov ecx,esi
xor r14d,DWORD[4+rsp]
lea r13d,[((-1894007588))+r13*1+rbp]
xor ebx,r11d
rol ecx,5
add r13d,eax
rol r14d,1
and ebx,edi
add r13d,ecx
rol edi,30
add r13d,ebx
xor edx,DWORD[40+rsp]
mov eax,r11d
mov DWORD[36+rsp],r14d
mov ebx,r11d
xor edx,DWORD[48+rsp]
and eax,edi
mov ecx,r13d
xor edx,DWORD[8+rsp]
lea r12d,[((-1894007588))+r12*1+r14]
xor ebx,edi
rol ecx,5
add r12d,eax
rol edx,1
and ebx,esi
add r12d,ecx
rol esi,30
add r12d,ebx
xor ebp,DWORD[44+rsp]
mov eax,edi
mov DWORD[40+rsp],edx
mov ebx,edi
xor ebp,DWORD[52+rsp]
and eax,esi
mov ecx,r12d
xor ebp,DWORD[12+rsp]
lea r11d,[((-1894007588))+r11*1+rdx]
xor ebx,esi
rol ecx,5
add r11d,eax
rol ebp,1
and ebx,r13d
add r11d,ecx
rol r13d,30
add r11d,ebx
xor r14d,DWORD[48+rsp]
mov eax,esi
mov DWORD[44+rsp],ebp
mov ebx,esi
xor r14d,DWORD[56+rsp]
and eax,r13d
mov ecx,r11d
xor r14d,DWORD[16+rsp]
lea edi,[((-1894007588))+rdi*1+rbp]
xor ebx,r13d
rol ecx,5
add edi,eax
rol r14d,1
and ebx,r12d
add edi,ecx
rol r12d,30
add edi,ebx
xor edx,DWORD[52+rsp]
mov eax,r13d
mov DWORD[48+rsp],r14d
mov ebx,r13d
xor edx,DWORD[60+rsp]
and eax,r12d
mov ecx,edi
xor edx,DWORD[20+rsp]
lea esi,[((-1894007588))+rsi*1+r14]
xor ebx,r12d
rol ecx,5
add esi,eax
rol edx,1
and ebx,r11d
add esi,ecx
rol r11d,30
add esi,ebx
xor ebp,DWORD[56+rsp]
mov eax,r12d
mov DWORD[52+rsp],edx
mov ebx,r12d
xor ebp,DWORD[rsp]
and eax,r11d
mov ecx,esi
xor ebp,DWORD[24+rsp]
lea r13d,[((-1894007588))+r13*1+rdx]
xor ebx,r11d
rol ecx,5
add r13d,eax
rol ebp,1
and ebx,edi
add r13d,ecx
rol edi,30
add r13d,ebx
xor r14d,DWORD[60+rsp]
mov eax,r11d
mov DWORD[56+rsp],ebp
mov ebx,r11d
xor r14d,DWORD[4+rsp]
and eax,edi
mov ecx,r13d
xor r14d,DWORD[28+rsp]
lea r12d,[((-1894007588))+r12*1+rbp]
xor ebx,edi
rol ecx,5
add r12d,eax
rol r14d,1
and ebx,esi
add r12d,ecx
rol esi,30
add r12d,ebx
xor edx,DWORD[rsp]
mov eax,edi
mov DWORD[60+rsp],r14d
mov ebx,edi
xor edx,DWORD[8+rsp]
and eax,esi
mov ecx,r12d
xor edx,DWORD[32+rsp]
lea r11d,[((-1894007588))+r11*1+r14]
xor ebx,esi
rol ecx,5
add r11d,eax
rol edx,1
and ebx,r13d
add r11d,ecx
rol r13d,30
add r11d,ebx
xor ebp,DWORD[4+rsp]
mov eax,esi
mov DWORD[rsp],edx
mov ebx,esi
xor ebp,DWORD[12+rsp]
and eax,r13d
mov ecx,r11d
xor ebp,DWORD[36+rsp]
lea edi,[((-1894007588))+rdi*1+rdx]
xor ebx,r13d
rol ecx,5
add edi,eax
rol ebp,1
and ebx,r12d
add edi,ecx
rol r12d,30
add edi,ebx
xor r14d,DWORD[8+rsp]
mov eax,r13d
mov DWORD[4+rsp],ebp
mov ebx,r13d
xor r14d,DWORD[16+rsp]
and eax,r12d
mov ecx,edi
xor r14d,DWORD[40+rsp]
lea esi,[((-1894007588))+rsi*1+rbp]
xor ebx,r12d
rol ecx,5
add esi,eax
rol r14d,1
and ebx,r11d
add esi,ecx
rol r11d,30
add esi,ebx
xor edx,DWORD[12+rsp]
mov eax,r12d
mov DWORD[8+rsp],r14d
mov ebx,r12d
xor edx,DWORD[20+rsp]
and eax,r11d
mov ecx,esi
xor edx,DWORD[44+rsp]
lea r13d,[((-1894007588))+r13*1+r14]
xor ebx,r11d
rol ecx,5
add r13d,eax
rol edx,1
and ebx,edi
add r13d,ecx
rol edi,30
add r13d,ebx
xor ebp,DWORD[16+rsp]
mov eax,r11d
mov DWORD[12+rsp],edx
mov ebx,r11d
xor ebp,DWORD[24+rsp]
and eax,edi
mov ecx,r13d
xor ebp,DWORD[48+rsp]
lea r12d,[((-1894007588))+r12*1+rdx]
xor ebx,edi
rol ecx,5
add r12d,eax
rol ebp,1
and ebx,esi
add r12d,ecx
rol esi,30
add r12d,ebx
xor r14d,DWORD[20+rsp]
mov eax,edi
mov DWORD[16+rsp],ebp
mov ebx,edi
xor r14d,DWORD[28+rsp]
and eax,esi
mov ecx,r12d
xor r14d,DWORD[52+rsp]
lea r11d,[((-1894007588))+r11*1+rbp]
xor ebx,esi
rol ecx,5
add r11d,eax
rol r14d,1
and ebx,r13d
add r11d,ecx
rol r13d,30
add r11d,ebx
xor edx,DWORD[24+rsp]
mov eax,esi
mov DWORD[20+rsp],r14d
mov ebx,esi
xor edx,DWORD[32+rsp]
and eax,r13d
mov ecx,r11d
xor edx,DWORD[56+rsp]
lea edi,[((-1894007588))+rdi*1+r14]
xor ebx,r13d
rol ecx,5
add edi,eax
rol edx,1
and ebx,r12d
add edi,ecx
rol r12d,30
add edi,ebx
xor ebp,DWORD[28+rsp]
mov eax,r13d
mov DWORD[24+rsp],edx
mov ebx,r13d
xor ebp,DWORD[36+rsp]
and eax,r12d
mov ecx,edi
xor ebp,DWORD[60+rsp]
lea esi,[((-1894007588))+rsi*1+rdx]
xor ebx,r12d
rol ecx,5
add esi,eax
rol ebp,1
and ebx,r11d
add esi,ecx
rol r11d,30
add esi,ebx
xor r14d,DWORD[32+rsp]
mov eax,r12d
mov DWORD[28+rsp],ebp
mov ebx,r12d
xor r14d,DWORD[40+rsp]
and eax,r11d
mov ecx,esi
xor r14d,DWORD[rsp]
lea r13d,[((-1894007588))+r13*1+rbp]
xor ebx,r11d
rol ecx,5
add r13d,eax
rol r14d,1
and ebx,edi
add r13d,ecx
rol edi,30
add r13d,ebx
xor edx,DWORD[36+rsp]
mov eax,r11d
mov DWORD[32+rsp],r14d
mov ebx,r11d
xor edx,DWORD[44+rsp]
and eax,edi
mov ecx,r13d
xor edx,DWORD[4+rsp]
lea r12d,[((-1894007588))+r12*1+r14]
xor ebx,edi
rol ecx,5
add r12d,eax
rol edx,1
and ebx,esi
add r12d,ecx
rol esi,30
add r12d,ebx
xor ebp,DWORD[40+rsp]
mov eax,edi
mov DWORD[36+rsp],edx
mov ebx,edi
xor ebp,DWORD[48+rsp]
and eax,esi
mov ecx,r12d
xor ebp,DWORD[8+rsp]
lea r11d,[((-1894007588))+r11*1+rdx]
xor ebx,esi
rol ecx,5
add r11d,eax
rol ebp,1
and ebx,r13d
add r11d,ecx
rol r13d,30
add r11d,ebx
xor r14d,DWORD[44+rsp]
mov eax,esi
mov DWORD[40+rsp],ebp
mov ebx,esi
xor r14d,DWORD[52+rsp]
and eax,r13d
mov ecx,r11d
xor r14d,DWORD[12+rsp]
lea edi,[((-1894007588))+rdi*1+rbp]
xor ebx,r13d
rol ecx,5
add edi,eax
rol r14d,1
and ebx,r12d
add edi,ecx
rol r12d,30
add edi,ebx
xor edx,DWORD[48+rsp]
mov eax,r13d
mov DWORD[44+rsp],r14d
mov ebx,r13d
xor edx,DWORD[56+rsp]
and eax,r12d
mov ecx,edi
xor edx,DWORD[16+rsp]
lea esi,[((-1894007588))+rsi*1+r14]
xor ebx,r12d
rol ecx,5
add esi,eax
rol edx,1
and ebx,r11d
add esi,ecx
rol r11d,30
add esi,ebx
xor ebp,DWORD[52+rsp]
mov eax,edi
mov DWORD[48+rsp],edx
mov ecx,esi
xor ebp,DWORD[60+rsp]
xor eax,r12d
rol ecx,5
xor ebp,DWORD[20+rsp]
lea r13d,[((-899497514))+r13*1+rdx]
xor eax,r11d
add r13d,ecx
rol edi,30
add r13d,eax
rol ebp,1
xor r14d,DWORD[56+rsp]
mov eax,esi
mov DWORD[52+rsp],ebp
mov ecx,r13d
xor r14d,DWORD[rsp]
xor eax,r11d
rol ecx,5
xor r14d,DWORD[24+rsp]
lea r12d,[((-899497514))+r12*1+rbp]
xor eax,edi
add r12d,ecx
rol esi,30
add r12d,eax
rol r14d,1
xor edx,DWORD[60+rsp]
mov eax,r13d
mov DWORD[56+rsp],r14d
mov ecx,r12d
xor edx,DWORD[4+rsp]
xor eax,edi
rol ecx,5
xor edx,DWORD[28+rsp]
lea r11d,[((-899497514))+r11*1+r14]
xor eax,esi
add r11d,ecx
rol r13d,30
add r11d,eax
rol edx,1
xor ebp,DWORD[rsp]
mov eax,r12d
mov DWORD[60+rsp],edx
mov ecx,r11d
xor ebp,DWORD[8+rsp]
xor eax,esi
rol ecx,5
xor ebp,DWORD[32+rsp]
lea edi,[((-899497514))+rdi*1+rdx]
xor eax,r13d
add edi,ecx
rol r12d,30
add edi,eax
rol ebp,1
xor r14d,DWORD[4+rsp]
mov eax,r11d
mov DWORD[rsp],ebp
mov ecx,edi
xor r14d,DWORD[12+rsp]
xor eax,r13d
rol ecx,5
xor r14d,DWORD[36+rsp]
lea esi,[((-899497514))+rsi*1+rbp]
xor eax,r12d
add esi,ecx
rol r11d,30
add esi,eax
rol r14d,1
xor edx,DWORD[8+rsp]
mov eax,edi
mov DWORD[4+rsp],r14d
mov ecx,esi
xor edx,DWORD[16+rsp]
xor eax,r12d
rol ecx,5
xor edx,DWORD[40+rsp]
lea r13d,[((-899497514))+r13*1+r14]
xor eax,r11d
add r13d,ecx
rol edi,30
add r13d,eax
rol edx,1
xor ebp,DWORD[12+rsp]
mov eax,esi
mov DWORD[8+rsp],edx
mov ecx,r13d
xor ebp,DWORD[20+rsp]
xor eax,r11d
rol ecx,5
xor ebp,DWORD[44+rsp]
lea r12d,[((-899497514))+r12*1+rdx]
xor eax,edi
add r12d,ecx
rol esi,30
add r12d,eax
rol ebp,1
xor r14d,DWORD[16+rsp]
mov eax,r13d
mov DWORD[12+rsp],ebp
mov ecx,r12d
xor r14d,DWORD[24+rsp]
xor eax,edi
rol ecx,5
xor r14d,DWORD[48+rsp]
lea r11d,[((-899497514))+r11*1+rbp]
xor eax,esi
add r11d,ecx
rol r13d,30
add r11d,eax
rol r14d,1
xor edx,DWORD[20+rsp]
mov eax,r12d
mov DWORD[16+rsp],r14d
mov ecx,r11d
xor edx,DWORD[28+rsp]
xor eax,esi
rol ecx,5
xor edx,DWORD[52+rsp]
lea edi,[((-899497514))+rdi*1+r14]
xor eax,r13d
add edi,ecx
rol r12d,30
add edi,eax
rol edx,1
xor ebp,DWORD[24+rsp]
mov eax,r11d
mov DWORD[20+rsp],edx
mov ecx,edi
xor ebp,DWORD[32+rsp]
xor eax,r13d
rol ecx,5
xor ebp,DWORD[56+rsp]
lea esi,[((-899497514))+rsi*1+rdx]
xor eax,r12d
add esi,ecx
rol r11d,30
add esi,eax
rol ebp,1
xor r14d,DWORD[28+rsp]
mov eax,edi
mov DWORD[24+rsp],ebp
mov ecx,esi
xor r14d,DWORD[36+rsp]
xor eax,r12d
rol ecx,5
xor r14d,DWORD[60+rsp]
lea r13d,[((-899497514))+r13*1+rbp]
xor eax,r11d
add r13d,ecx
rol edi,30
add r13d,eax
rol r14d,1
xor edx,DWORD[32+rsp]
mov eax,esi
mov DWORD[28+rsp],r14d
mov ecx,r13d
xor edx,DWORD[40+rsp]
xor eax,r11d
rol ecx,5
xor edx,DWORD[rsp]
lea r12d,[((-899497514))+r12*1+r14]
xor eax,edi
add r12d,ecx
rol esi,30
add r12d,eax
rol edx,1
xor ebp,DWORD[36+rsp]
mov eax,r13d
mov ecx,r12d
xor ebp,DWORD[44+rsp]
xor eax,edi
rol ecx,5
xor ebp,DWORD[4+rsp]
lea r11d,[((-899497514))+r11*1+rdx]
xor eax,esi
add r11d,ecx
rol r13d,30
add r11d,eax
rol ebp,1
xor r14d,DWORD[40+rsp]
mov eax,r12d
mov ecx,r11d
xor r14d,DWORD[48+rsp]
xor eax,esi
rol ecx,5
xor r14d,DWORD[8+rsp]
lea edi,[((-899497514))+rdi*1+rbp]
xor eax,r13d
add edi,ecx
rol r12d,30
add edi,eax
rol r14d,1
xor edx,DWORD[44+rsp]
mov eax,r11d
mov ecx,edi
xor edx,DWORD[52+rsp]
xor eax,r13d
rol ecx,5
xor edx,DWORD[12+rsp]
lea esi,[((-899497514))+rsi*1+r14]
xor eax,r12d
add esi,ecx
rol r11d,30
add esi,eax
rol edx,1
xor ebp,DWORD[48+rsp]
mov eax,edi
mov ecx,esi
xor ebp,DWORD[56+rsp]
xor eax,r12d
rol ecx,5
xor ebp,DWORD[16+rsp]
lea r13d,[((-899497514))+r13*1+rdx]
xor eax,r11d
add r13d,ecx
rol edi,30
add r13d,eax
rol ebp,1
xor r14d,DWORD[52+rsp]
mov eax,esi
mov ecx,r13d
xor r14d,DWORD[60+rsp]
xor eax,r11d
rol ecx,5
xor r14d,DWORD[20+rsp]
lea r12d,[((-899497514))+r12*1+rbp]
xor eax,edi
add r12d,ecx
rol esi,30
add r12d,eax
rol r14d,1
xor edx,DWORD[56+rsp]
mov eax,r13d
mov ecx,r12d
xor edx,DWORD[rsp]
xor eax,edi
rol ecx,5
xor edx,DWORD[24+rsp]
lea r11d,[((-899497514))+r11*1+r14]
xor eax,esi
add r11d,ecx
rol r13d,30
add r11d,eax
rol edx,1
xor ebp,DWORD[60+rsp]
mov eax,r12d
mov ecx,r11d
xor ebp,DWORD[4+rsp]
xor eax,esi
rol ecx,5
xor ebp,DWORD[28+rsp]
lea edi,[((-899497514))+rdi*1+rdx]
xor eax,r13d
add edi,ecx
rol r12d,30
add edi,eax
rol ebp,1
mov eax,r11d
mov ecx,edi
xor eax,r13d
lea esi,[((-899497514))+rsi*1+rbp]
rol ecx,5
xor eax,r12d
add esi,ecx
rol r11d,30
add esi,eax
add esi,DWORD[r8]
add edi,DWORD[4+r8]
add r11d,DWORD[8+r8]
add r12d,DWORD[12+r8]
add r13d,DWORD[16+r8]
mov DWORD[r8],esi
mov DWORD[4+r8],edi
mov DWORD[8+r8],r11d
mov DWORD[12+r8],r12d
mov DWORD[16+r8],r13d
sub r10,1
lea r9,[64+r9]
jnz NEAR $L$loop
mov rsi,QWORD[64+rsp]
mov r14,QWORD[((-40))+rsi]
mov r13,QWORD[((-32))+rsi]
mov r12,QWORD[((-24))+rsi]
mov rbp,QWORD[((-16))+rsi]
mov rbx,QWORD[((-8))+rsi]
lea rsp,[rsi]
$L$epilogue:
mov rdi,QWORD[8+rsp] ;WIN64 epilogue
mov rsi,QWORD[16+rsp]
DB 0F3h,0C3h ;repret
$L$SEH_end_sha1_block_data_order:
ALIGN 16
sha1_block_data_order_ssse3:
mov QWORD[8+rsp],rdi ;WIN64 prologue
mov QWORD[16+rsp],rsi
mov rax,rsp
$L$SEH_begin_sha1_block_data_order_ssse3:
mov rdi,rcx
mov rsi,rdx
mov rdx,r8
_ssse3_shortcut:
mov r11,rsp
push rbx
push rbp
push r12
push r13
push r14
lea rsp,[((-160))+rsp]
movaps XMMWORD[(-40-96)+r11],xmm6
movaps XMMWORD[(-40-80)+r11],xmm7
movaps XMMWORD[(-40-64)+r11],xmm8
movaps XMMWORD[(-40-48)+r11],xmm9
movaps XMMWORD[(-40-32)+r11],xmm10
movaps XMMWORD[(-40-16)+r11],xmm11
$L$prologue_ssse3:
and rsp,-64
mov r8,rdi
mov r9,rsi
mov r10,rdx
shl r10,6
add r10,r9
lea r14,[((K_XX_XX+64))]
mov eax,DWORD[r8]
mov ebx,DWORD[4+r8]
mov ecx,DWORD[8+r8]
mov edx,DWORD[12+r8]
mov esi,ebx
mov ebp,DWORD[16+r8]
mov edi,ecx
xor edi,edx
and esi,edi
movdqa xmm6,XMMWORD[64+r14]
movdqa xmm9,XMMWORD[((-64))+r14]
movdqu xmm0,XMMWORD[r9]
movdqu xmm1,XMMWORD[16+r9]
movdqu xmm2,XMMWORD[32+r9]
movdqu xmm3,XMMWORD[48+r9]
DB 102,15,56,0,198
DB 102,15,56,0,206
DB 102,15,56,0,214
add r9,64
paddd xmm0,xmm9
DB 102,15,56,0,222
paddd xmm1,xmm9
paddd xmm2,xmm9
movdqa XMMWORD[rsp],xmm0
psubd xmm0,xmm9
movdqa XMMWORD[16+rsp],xmm1
psubd xmm1,xmm9
movdqa XMMWORD[32+rsp],xmm2
psubd xmm2,xmm9
jmp NEAR $L$oop_ssse3
ALIGN 16
$L$oop_ssse3:
ror ebx,2
pshufd xmm4,xmm0,238
xor esi,edx
movdqa xmm8,xmm3
paddd xmm9,xmm3
mov edi,eax
add ebp,DWORD[rsp]
punpcklqdq xmm4,xmm1
xor ebx,ecx
rol eax,5
add ebp,esi
psrldq xmm8,4
and edi,ebx
xor ebx,ecx
pxor xmm4,xmm0
add ebp,eax
ror eax,7
pxor xmm8,xmm2
xor edi,ecx
mov esi,ebp
add edx,DWORD[4+rsp]
pxor xmm4,xmm8
xor eax,ebx
rol ebp,5
movdqa XMMWORD[48+rsp],xmm9
add edx,edi
and esi,eax
movdqa xmm10,xmm4
xor eax,ebx
add edx,ebp
ror ebp,7
movdqa xmm8,xmm4
xor esi,ebx
pslldq xmm10,12
paddd xmm4,xmm4
mov edi,edx
add ecx,DWORD[8+rsp]
psrld xmm8,31
xor ebp,eax
rol edx,5
add ecx,esi
movdqa xmm9,xmm10
and edi,ebp
xor ebp,eax
psrld xmm10,30
add ecx,edx
ror edx,7
por xmm4,xmm8
xor edi,eax
mov esi,ecx
add ebx,DWORD[12+rsp]
pslld xmm9,2
pxor xmm4,xmm10
xor edx,ebp
movdqa xmm10,XMMWORD[((-64))+r14]
rol ecx,5
add ebx,edi
and esi,edx
pxor xmm4,xmm9
xor edx,ebp
add ebx,ecx
ror ecx,7
pshufd xmm5,xmm1,238
xor esi,ebp
movdqa xmm9,xmm4
paddd xmm10,xmm4
mov edi,ebx
add eax,DWORD[16+rsp]
punpcklqdq xmm5,xmm2
xor ecx,edx
rol ebx,5
add eax,esi
psrldq xmm9,4
and edi,ecx
xor ecx,edx
pxor xmm5,xmm1
add eax,ebx
ror ebx,7
pxor xmm9,xmm3
xor edi,edx
mov esi,eax
add ebp,DWORD[20+rsp]
pxor xmm5,xmm9
xor ebx,ecx
rol eax,5
movdqa XMMWORD[rsp],xmm10
add ebp,edi
and esi,ebx
movdqa xmm8,xmm5
xor ebx,ecx
add ebp,eax
ror eax,7
movdqa xmm9,xmm5
xor esi,ecx
pslldq xmm8,12
paddd xmm5,xmm5
mov edi,ebp
add edx,DWORD[24+rsp]
psrld xmm9,31
xor eax,ebx
rol ebp,5
add edx,esi
movdqa xmm10,xmm8
and edi,eax
xor eax,ebx
psrld xmm8,30
add edx,ebp
ror ebp,7
por xmm5,xmm9
xor edi,ebx
mov esi,edx
add ecx,DWORD[28+rsp]
pslld xmm10,2
pxor xmm5,xmm8
xor ebp,eax
movdqa xmm8,XMMWORD[((-32))+r14]
rol edx,5
add ecx,edi
and esi,ebp
pxor xmm5,xmm10
xor ebp,eax
add ecx,edx
ror edx,7
pshufd xmm6,xmm2,238
xor esi,eax
movdqa xmm10,xmm5
paddd xmm8,xmm5
mov edi,ecx
add ebx,DWORD[32+rsp]
punpcklqdq xmm6,xmm3
xor edx,ebp
rol ecx,5
add ebx,esi
psrldq xmm10,4
and edi,edx
xor edx,ebp
pxor xmm6,xmm2
add ebx,ecx
ror ecx,7
pxor xmm10,xmm4
xor edi,ebp
mov esi,ebx
add eax,DWORD[36+rsp]
pxor xmm6,xmm10
xor ecx,edx
rol ebx,5
movdqa XMMWORD[16+rsp],xmm8
add eax,edi
and esi,ecx
movdqa xmm9,xmm6
xor ecx,edx
add eax,ebx
ror ebx,7
movdqa xmm10,xmm6
xor esi,edx
pslldq xmm9,12
paddd xmm6,xmm6
mov edi,eax
add ebp,DWORD[40+rsp]
psrld xmm10,31
xor ebx,ecx
rol eax,5
add ebp,esi
movdqa xmm8,xmm9
and edi,ebx
xor ebx,ecx
psrld xmm9,30
add ebp,eax
ror eax,7
por xmm6,xmm10
xor edi,ecx
mov esi,ebp
add edx,DWORD[44+rsp]
pslld xmm8,2
pxor xmm6,xmm9
xor eax,ebx
movdqa xmm9,XMMWORD[((-32))+r14]
rol ebp,5
add edx,edi
and esi,eax
pxor xmm6,xmm8
xor eax,ebx
add edx,ebp
ror ebp,7
pshufd xmm7,xmm3,238
xor esi,ebx
movdqa xmm8,xmm6
paddd xmm9,xmm6
mov edi,edx
add ecx,DWORD[48+rsp]
punpcklqdq xmm7,xmm4
xor ebp,eax
rol edx,5
add ecx,esi
psrldq xmm8,4
and edi,ebp
xor ebp,eax
pxor xmm7,xmm3
add ecx,edx
ror edx,7
pxor xmm8,xmm5
xor edi,eax
mov esi,ecx
add ebx,DWORD[52+rsp]
pxor xmm7,xmm8
xor edx,ebp
rol ecx,5
movdqa XMMWORD[32+rsp],xmm9
add ebx,edi
and esi,edx
movdqa xmm10,xmm7
xor edx,ebp
add ebx,ecx
ror ecx,7
movdqa xmm8,xmm7
xor esi,ebp
pslldq xmm10,12
paddd xmm7,xmm7
mov edi,ebx
add eax,DWORD[56+rsp]
psrld xmm8,31
xor ecx,edx
rol ebx,5
add eax,esi
movdqa xmm9,xmm10
and edi,ecx
xor ecx,edx
psrld xmm10,30
add eax,ebx
ror ebx,7
por xmm7,xmm8
xor edi,edx
mov esi,eax
add ebp,DWORD[60+rsp]
pslld xmm9,2
pxor xmm7,xmm10
xor ebx,ecx
movdqa xmm10,XMMWORD[((-32))+r14]
rol eax,5
add ebp,edi
and esi,ebx
pxor xmm7,xmm9
pshufd xmm9,xmm6,238
xor ebx,ecx
add ebp,eax
ror eax,7
pxor xmm0,xmm4
xor esi,ecx
mov edi,ebp
add edx,DWORD[rsp]
punpcklqdq xmm9,xmm7
xor eax,ebx
rol ebp,5
pxor xmm0,xmm1
add edx,esi
and edi,eax
movdqa xmm8,xmm10
xor eax,ebx
paddd xmm10,xmm7
add edx,ebp
pxor xmm0,xmm9
ror ebp,7
xor edi,ebx
mov esi,edx
add ecx,DWORD[4+rsp]
movdqa xmm9,xmm0
xor ebp,eax
rol edx,5
movdqa XMMWORD[48+rsp],xmm10
add ecx,edi
and esi,ebp
xor ebp,eax
pslld xmm0,2
add ecx,edx
ror edx,7
psrld xmm9,30
xor esi,eax
mov edi,ecx
add ebx,DWORD[8+rsp]
por xmm0,xmm9
xor edx,ebp
rol ecx,5
pshufd xmm10,xmm7,238
add ebx,esi
and edi,edx
xor edx,ebp
add ebx,ecx
add eax,DWORD[12+rsp]
xor edi,ebp
mov esi,ebx
rol ebx,5
add eax,edi
xor esi,edx
ror ecx,7
add eax,ebx
pxor xmm1,xmm5
add ebp,DWORD[16+rsp]
xor esi,ecx
punpcklqdq xmm10,xmm0
mov edi,eax
rol eax,5
pxor xmm1,xmm2
add ebp,esi
xor edi,ecx
movdqa xmm9,xmm8
ror ebx,7
paddd xmm8,xmm0
add ebp,eax
pxor xmm1,xmm10
add edx,DWORD[20+rsp]
xor edi,ebx
mov esi,ebp
rol ebp,5
movdqa xmm10,xmm1
add edx,edi
xor esi,ebx
movdqa XMMWORD[rsp],xmm8
ror eax,7
add edx,ebp
add ecx,DWORD[24+rsp]
pslld xmm1,2
xor esi,eax
mov edi,edx
psrld xmm10,30
rol edx,5
add ecx,esi
xor edi,eax
ror ebp,7
por xmm1,xmm10
add ecx,edx
add ebx,DWORD[28+rsp]
pshufd xmm8,xmm0,238
xor edi,ebp
mov esi,ecx
rol ecx,5
add ebx,edi
xor esi,ebp
ror edx,7
add ebx,ecx
pxor xmm2,xmm6
add eax,DWORD[32+rsp]
xor esi,edx
punpcklqdq xmm8,xmm1
mov edi,ebx
rol ebx,5
pxor xmm2,xmm3
add eax,esi
xor edi,edx
movdqa xmm10,XMMWORD[r14]
ror ecx,7
paddd xmm9,xmm1
add eax,ebx
pxor xmm2,xmm8
add ebp,DWORD[36+rsp]
xor edi,ecx
mov esi,eax
rol eax,5
movdqa xmm8,xmm2
add ebp,edi
xor esi,ecx
movdqa XMMWORD[16+rsp],xmm9
ror ebx,7
add ebp,eax
add edx,DWORD[40+rsp]
pslld xmm2,2
xor esi,ebx
mov edi,ebp
psrld xmm8,30
rol ebp,5
add edx,esi
xor edi,ebx
ror eax,7
por xmm2,xmm8
add edx,ebp
add ecx,DWORD[44+rsp]
pshufd xmm9,xmm1,238
xor edi,eax
mov esi,edx
rol edx,5
add ecx,edi
xor esi,eax
ror ebp,7
add ecx,edx
pxor xmm3,xmm7
add ebx,DWORD[48+rsp]
xor esi,ebp
punpcklqdq xmm9,xmm2
mov edi,ecx
rol ecx,5
pxor xmm3,xmm4
add ebx,esi
xor edi,ebp
movdqa xmm8,xmm10
ror edx,7
paddd xmm10,xmm2
add ebx,ecx
pxor xmm3,xmm9
add eax,DWORD[52+rsp]
xor edi,edx
mov esi,ebx
rol ebx,5
movdqa xmm9,xmm3
add eax,edi
xor esi,edx
movdqa XMMWORD[32+rsp],xmm10
ror ecx,7
add eax,ebx
add ebp,DWORD[56+rsp]
pslld xmm3,2
xor esi,ecx
mov edi,eax
psrld xmm9,30
rol eax,5
add ebp,esi
xor edi,ecx
ror ebx,7
por xmm3,xmm9
add ebp,eax
add edx,DWORD[60+rsp]
pshufd xmm10,xmm2,238
xor edi,ebx
mov esi,ebp
rol ebp,5
add edx,edi
xor esi,ebx
ror eax,7
add edx,ebp
pxor xmm4,xmm0
add ecx,DWORD[rsp]
xor esi,eax
punpcklqdq xmm10,xmm3
mov edi,edx
rol edx,5
pxor xmm4,xmm5
add ecx,esi
xor edi,eax
movdqa xmm9,xmm8
ror ebp,7
paddd xmm8,xmm3
add ecx,edx
pxor xmm4,xmm10
add ebx,DWORD[4+rsp]
xor edi,ebp
mov esi,ecx
rol ecx,5
movdqa xmm10,xmm4
add ebx,edi
xor esi,ebp
movdqa XMMWORD[48+rsp],xmm8
ror edx,7
add ebx,ecx
add eax,DWORD[8+rsp]
pslld xmm4,2
xor esi,edx
mov edi,ebx
psrld xmm10,30
rol ebx,5
add eax,esi
xor edi,edx
ror ecx,7
por xmm4,xmm10
add eax,ebx
add ebp,DWORD[12+rsp]
pshufd xmm8,xmm3,238
xor edi,ecx
mov esi,eax
rol eax,5
add ebp,edi
xor esi,ecx
ror ebx,7
add ebp,eax
pxor xmm5,xmm1
add edx,DWORD[16+rsp]
xor esi,ebx
punpcklqdq xmm8,xmm4
mov edi,ebp
rol ebp,5
pxor xmm5,xmm6
add edx,esi
xor edi,ebx
movdqa xmm10,xmm9
ror eax,7
paddd xmm9,xmm4
add edx,ebp
pxor xmm5,xmm8
add ecx,DWORD[20+rsp]
xor edi,eax
mov esi,edx
rol edx,5
movdqa xmm8,xmm5
add ecx,edi
xor esi,eax
movdqa XMMWORD[rsp],xmm9
ror ebp,7
add ecx,edx
add ebx,DWORD[24+rsp]
pslld xmm5,2
xor esi,ebp
mov edi,ecx
psrld xmm8,30
rol ecx,5
add ebx,esi
xor edi,ebp
ror edx,7
por xmm5,xmm8
add ebx,ecx
add eax,DWORD[28+rsp]
pshufd xmm9,xmm4,238
ror ecx,7
mov esi,ebx
xor edi,edx
rol ebx,5
add eax,edi
xor esi,ecx
xor ecx,edx
add eax,ebx
pxor xmm6,xmm2
add ebp,DWORD[32+rsp]
and esi,ecx
xor ecx,edx
ror ebx,7
punpcklqdq xmm9,xmm5
mov edi,eax
xor esi,ecx
pxor xmm6,xmm7
rol eax,5
add ebp,esi
movdqa xmm8,xmm10
xor edi,ebx
paddd xmm10,xmm5
xor ebx,ecx
pxor xmm6,xmm9
add ebp,eax
add edx,DWORD[36+rsp]
and edi,ebx
xor ebx,ecx
ror eax,7
movdqa xmm9,xmm6
mov esi,ebp
xor edi,ebx
movdqa XMMWORD[16+rsp],xmm10
rol ebp,5
add edx,edi
xor esi,eax
pslld xmm6,2
xor eax,ebx
add edx,ebp
psrld xmm9,30
add ecx,DWORD[40+rsp]
and esi,eax
xor eax,ebx
por xmm6,xmm9
ror ebp,7
mov edi,edx
xor esi,eax
rol edx,5
pshufd xmm10,xmm5,238
add ecx,esi
xor edi,ebp
xor ebp,eax
add ecx,edx
add ebx,DWORD[44+rsp]
and edi,ebp
xor ebp,eax
ror edx,7
mov esi,ecx
xor edi,ebp
rol ecx,5
add ebx,edi
xor esi,edx
xor edx,ebp
add ebx,ecx
pxor xmm7,xmm3
add eax,DWORD[48+rsp]
and esi,edx
xor edx,ebp
ror ecx,7
punpcklqdq xmm10,xmm6
mov edi,ebx
xor esi,edx
pxor xmm7,xmm0
rol ebx,5
add eax,esi
movdqa xmm9,XMMWORD[32+r14]
xor edi,ecx
paddd xmm8,xmm6
xor ecx,edx
pxor xmm7,xmm10
add eax,ebx
add ebp,DWORD[52+rsp]
and edi,ecx
xor ecx,edx
ror ebx,7
movdqa xmm10,xmm7
mov esi,eax
xor edi,ecx
movdqa XMMWORD[32+rsp],xmm8
rol eax,5
add ebp,edi
xor esi,ebx
pslld xmm7,2
xor ebx,ecx
add ebp,eax
psrld xmm10,30
add edx,DWORD[56+rsp]
and esi,ebx
xor ebx,ecx
por xmm7,xmm10
ror eax,7
mov edi,ebp
xor esi,ebx
rol ebp,5
pshufd xmm8,xmm6,238
add edx,esi
xor edi,eax
xor eax,ebx
add edx,ebp
add ecx,DWORD[60+rsp]
and edi,eax
xor eax,ebx
ror ebp,7
mov esi,edx
xor edi,eax
rol edx,5
add ecx,edi
xor esi,ebp
xor ebp,eax
add ecx,edx
pxor xmm0,xmm4
add ebx,DWORD[rsp]
and esi,ebp
xor ebp,eax
ror edx,7
punpcklqdq xmm8,xmm7
mov edi,ecx
xor esi,ebp
pxor xmm0,xmm1
rol ecx,5
add ebx,esi
movdqa xmm10,xmm9
xor edi,edx
paddd xmm9,xmm7
xor edx,ebp
pxor xmm0,xmm8
add ebx,ecx
add eax,DWORD[4+rsp]
and edi,edx
xor edx,ebp
ror ecx,7
movdqa xmm8,xmm0
mov esi,ebx
xor edi,edx
movdqa XMMWORD[48+rsp],xmm9
rol ebx,5
add eax,edi
xor esi,ecx
pslld xmm0,2
xor ecx,edx
add eax,ebx
psrld xmm8,30
add ebp,DWORD[8+rsp]
and esi,ecx
xor ecx,edx
por xmm0,xmm8
ror ebx,7
mov edi,eax
xor esi,ecx
rol eax,5
pshufd xmm9,xmm7,238
add ebp,esi
xor edi,ebx
xor ebx,ecx
add ebp,eax
add edx,DWORD[12+rsp]
and edi,ebx
xor ebx,ecx
ror eax,7
mov esi,ebp
xor edi,ebx
rol ebp,5
add edx,edi
xor esi,eax
xor eax,ebx
add edx,ebp
pxor xmm1,xmm5
add ecx,DWORD[16+rsp]
and esi,eax
xor eax,ebx
ror ebp,7
punpcklqdq xmm9,xmm0
mov edi,edx
xor esi,eax
pxor xmm1,xmm2
rol edx,5
add ecx,esi
movdqa xmm8,xmm10
xor edi,ebp
paddd xmm10,xmm0
xor ebp,eax
pxor xmm1,xmm9
add ecx,edx
add ebx,DWORD[20+rsp]
and edi,ebp
xor ebp,eax
ror edx,7
movdqa xmm9,xmm1
mov esi,ecx
xor edi,ebp
movdqa XMMWORD[rsp],xmm10
rol ecx,5
add ebx,edi
xor esi,edx
pslld xmm1,2
xor edx,ebp
add ebx,ecx
psrld xmm9,30
add eax,DWORD[24+rsp]
and esi,edx
xor edx,ebp
por xmm1,xmm9
ror ecx,7
mov edi,ebx
xor esi,edx
rol ebx,5
pshufd xmm10,xmm0,238
add eax,esi
xor edi,ecx
xor ecx,edx
add eax,ebx
add ebp,DWORD[28+rsp]
and edi,ecx
xor ecx,edx
ror ebx,7
mov esi,eax
xor edi,ecx
rol eax,5
add ebp,edi
xor esi,ebx
xor ebx,ecx
add ebp,eax
pxor xmm2,xmm6
add edx,DWORD[32+rsp]
and esi,ebx
xor ebx,ecx
ror eax,7
punpcklqdq xmm10,xmm1
mov edi,ebp
xor esi,ebx
pxor xmm2,xmm3
rol ebp,5
add edx,esi
movdqa xmm9,xmm8
xor edi,eax
paddd xmm8,xmm1
xor eax,ebx
pxor xmm2,xmm10
add edx,ebp
add ecx,DWORD[36+rsp]
and edi,eax
xor eax,ebx
ror ebp,7
movdqa xmm10,xmm2
mov esi,edx
xor edi,eax
movdqa XMMWORD[16+rsp],xmm8
rol edx,5
add ecx,edi
xor esi,ebp
pslld xmm2,2
xor ebp,eax
add ecx,edx
psrld xmm10,30
add ebx,DWORD[40+rsp]
and esi,ebp
xor ebp,eax
por xmm2,xmm10
ror edx,7
mov edi,ecx
xor esi,ebp
rol ecx,5
pshufd xmm8,xmm1,238
add ebx,esi
xor edi,edx
xor edx,ebp
add ebx,ecx
add eax,DWORD[44+rsp]
and edi,edx
xor edx,ebp
ror ecx,7
mov esi,ebx
xor edi,edx
rol ebx,5
add eax,edi
xor esi,edx
add eax,ebx
pxor xmm3,xmm7
add ebp,DWORD[48+rsp]
xor esi,ecx
punpcklqdq xmm8,xmm2
mov edi,eax
rol eax,5
pxor xmm3,xmm4
add ebp,esi
xor edi,ecx
movdqa xmm10,xmm9
ror ebx,7
paddd xmm9,xmm2
add ebp,eax
pxor xmm3,xmm8
add edx,DWORD[52+rsp]
xor edi,ebx
mov esi,ebp
rol ebp,5
movdqa xmm8,xmm3
add edx,edi
xor esi,ebx
movdqa XMMWORD[32+rsp],xmm9
ror eax,7
add edx,ebp
add ecx,DWORD[56+rsp]
pslld xmm3,2
xor esi,eax
mov edi,edx
psrld xmm8,30
rol edx,5
add ecx,esi
xor edi,eax
ror ebp,7
por xmm3,xmm8
add ecx,edx
add ebx,DWORD[60+rsp]
xor edi,ebp
mov esi,ecx
rol ecx,5
add ebx,edi
xor esi,ebp
ror edx,7
add ebx,ecx
add eax,DWORD[rsp]
xor esi,edx
mov edi,ebx
rol ebx,5
paddd xmm10,xmm3
add eax,esi
xor edi,edx
movdqa XMMWORD[48+rsp],xmm10
ror ecx,7
add eax,ebx
add ebp,DWORD[4+rsp]
xor edi,ecx
mov esi,eax
rol eax,5
add ebp,edi
xor esi,ecx
ror ebx,7
add ebp,eax
add edx,DWORD[8+rsp]
xor esi,ebx
mov edi,ebp
rol ebp,5
add edx,esi
xor edi,ebx
ror eax,7
add edx,ebp
add ecx,DWORD[12+rsp]
xor edi,eax
mov esi,edx
rol edx,5
add ecx,edi
xor esi,eax
ror ebp,7
add ecx,edx
cmp r9,r10
je NEAR $L$done_ssse3
movdqa xmm6,XMMWORD[64+r14]
movdqa xmm9,XMMWORD[((-64))+r14]
movdqu xmm0,XMMWORD[r9]
movdqu xmm1,XMMWORD[16+r9]
movdqu xmm2,XMMWORD[32+r9]
movdqu xmm3,XMMWORD[48+r9]
DB 102,15,56,0,198
add r9,64
add ebx,DWORD[16+rsp]
xor esi,ebp
mov edi,ecx
DB 102,15,56,0,206
rol ecx,5
add ebx,esi
xor edi,ebp
ror edx,7
paddd xmm0,xmm9
add ebx,ecx
add eax,DWORD[20+rsp]
xor edi,edx
mov esi,ebx
movdqa XMMWORD[rsp],xmm0
rol ebx,5
add eax,edi
xor esi,edx
ror ecx,7
psubd xmm0,xmm9
add eax,ebx
add ebp,DWORD[24+rsp]
xor esi,ecx
mov edi,eax
rol eax,5
add ebp,esi
xor edi,ecx
ror ebx,7
add ebp,eax
add edx,DWORD[28+rsp]
xor edi,ebx
mov esi,ebp
rol ebp,5
add edx,edi
xor esi,ebx
ror eax,7
add edx,ebp
add ecx,DWORD[32+rsp]
xor esi,eax
mov edi,edx
DB 102,15,56,0,214
rol edx,5
add ecx,esi
xor edi,eax
ror ebp,7
paddd xmm1,xmm9
add ecx,edx
add ebx,DWORD[36+rsp]
xor edi,ebp
mov esi,ecx
movdqa XMMWORD[16+rsp],xmm1
rol ecx,5
add ebx,edi
xor esi,ebp
ror edx,7
psubd xmm1,xmm9
add ebx,ecx
add eax,DWORD[40+rsp]
xor esi,edx
mov edi,ebx
rol ebx,5
add eax,esi
xor edi,edx
ror ecx,7
add eax,ebx
add ebp,DWORD[44+rsp]
xor edi,ecx
mov esi,eax
rol eax,5
add ebp,edi
xor esi,ecx
ror ebx,7
add ebp,eax
add edx,DWORD[48+rsp]
xor esi,ebx
mov edi,ebp
DB 102,15,56,0,222
rol ebp,5
add edx,esi
xor edi,ebx
ror eax,7
paddd xmm2,xmm9
add edx,ebp
add ecx,DWORD[52+rsp]
xor edi,eax
mov esi,edx
movdqa XMMWORD[32+rsp],xmm2
rol edx,5
add ecx,edi
xor esi,eax
ror ebp,7
psubd xmm2,xmm9
add ecx,edx
add ebx,DWORD[56+rsp]
xor esi,ebp
mov edi,ecx
rol ecx,5
add ebx,esi
xor edi,ebp
ror edx,7
add ebx,ecx
add eax,DWORD[60+rsp]
xor edi,edx
mov esi,ebx
rol ebx,5
add eax,edi
ror ecx,7
add eax,ebx
add eax,DWORD[r8]
add esi,DWORD[4+r8]
add ecx,DWORD[8+r8]
add edx,DWORD[12+r8]
mov DWORD[r8],eax
add ebp,DWORD[16+r8]
mov DWORD[4+r8],esi
mov ebx,esi
mov DWORD[8+r8],ecx
mov edi,ecx
mov DWORD[12+r8],edx
xor edi,edx
mov DWORD[16+r8],ebp
and esi,edi
jmp NEAR $L$oop_ssse3
ALIGN 16
$L$done_ssse3:
add ebx,DWORD[16+rsp]
xor esi,ebp
mov edi,ecx
rol ecx,5
add ebx,esi
xor edi,ebp
ror edx,7
add ebx,ecx
add eax,DWORD[20+rsp]
xor edi,edx
mov esi,ebx
rol ebx,5
add eax,edi
xor esi,edx
ror ecx,7
add eax,ebx
add ebp,DWORD[24+rsp]
xor esi,ecx
mov edi,eax
rol eax,5
add ebp,esi
xor edi,ecx
ror ebx,7
add ebp,eax
add edx,DWORD[28+rsp]
xor edi,ebx
mov esi,ebp
rol ebp,5
add edx,edi
xor esi,ebx
ror eax,7
add edx,ebp
add ecx,DWORD[32+rsp]
xor esi,eax
mov edi,edx
rol edx,5
add ecx,esi
xor edi,eax
ror ebp,7
add ecx,edx
add ebx,DWORD[36+rsp]
xor edi,ebp
mov esi,ecx
rol ecx,5
add ebx,edi
xor esi,ebp
ror edx,7
add ebx,ecx
add eax,DWORD[40+rsp]
xor esi,edx
mov edi,ebx
rol ebx,5
add eax,esi
xor edi,edx
ror ecx,7
add eax,ebx
add ebp,DWORD[44+rsp]
xor edi,ecx
mov esi,eax
rol eax,5
add ebp,edi
xor esi,ecx
ror ebx,7
add ebp,eax
add edx,DWORD[48+rsp]
xor esi,ebx
mov edi,ebp
rol ebp,5
add edx,esi
xor edi,ebx
ror eax,7
add edx,ebp
add ecx,DWORD[52+rsp]
xor edi,eax
mov esi,edx
rol edx,5
add ecx,edi
xor esi,eax
ror ebp,7
add ecx,edx
add ebx,DWORD[56+rsp]
xor esi,ebp
mov edi,ecx
rol ecx,5
add ebx,esi
xor edi,ebp
ror edx,7
add ebx,ecx
add eax,DWORD[60+rsp]
xor edi,edx
mov esi,ebx
rol ebx,5
add eax,edi
ror ecx,7
add eax,ebx
add eax,DWORD[r8]
add esi,DWORD[4+r8]
add ecx,DWORD[8+r8]
mov DWORD[r8],eax
add edx,DWORD[12+r8]
mov DWORD[4+r8],esi
add ebp,DWORD[16+r8]
mov DWORD[8+r8],ecx
mov DWORD[12+r8],edx
mov DWORD[16+r8],ebp
movaps xmm6,XMMWORD[((-40-96))+r11]
movaps xmm7,XMMWORD[((-40-80))+r11]
movaps xmm8,XMMWORD[((-40-64))+r11]
movaps xmm9,XMMWORD[((-40-48))+r11]
movaps xmm10,XMMWORD[((-40-32))+r11]
movaps xmm11,XMMWORD[((-40-16))+r11]
mov r14,QWORD[((-40))+r11]
mov r13,QWORD[((-32))+r11]
mov r12,QWORD[((-24))+r11]
mov rbp,QWORD[((-16))+r11]
mov rbx,QWORD[((-8))+r11]
lea rsp,[r11]
$L$epilogue_ssse3:
mov rdi,QWORD[8+rsp] ;WIN64 epilogue
mov rsi,QWORD[16+rsp]
DB 0F3h,0C3h ;repret
$L$SEH_end_sha1_block_data_order_ssse3:
ALIGN 16
sha1_block_data_order_avx:
mov QWORD[8+rsp],rdi ;WIN64 prologue
mov QWORD[16+rsp],rsi
mov rax,rsp
$L$SEH_begin_sha1_block_data_order_avx:
mov rdi,rcx
mov rsi,rdx
mov rdx,r8
_avx_shortcut:
mov r11,rsp
push rbx
push rbp
push r12
push r13
push r14
lea rsp,[((-160))+rsp]
vzeroupper
vmovaps XMMWORD[(-40-96)+r11],xmm6
vmovaps XMMWORD[(-40-80)+r11],xmm7
vmovaps XMMWORD[(-40-64)+r11],xmm8
vmovaps XMMWORD[(-40-48)+r11],xmm9
vmovaps XMMWORD[(-40-32)+r11],xmm10
vmovaps XMMWORD[(-40-16)+r11],xmm11
$L$prologue_avx:
and rsp,-64
mov r8,rdi
mov r9,rsi
mov r10,rdx
shl r10,6
add r10,r9
lea r14,[((K_XX_XX+64))]
mov eax,DWORD[r8]
mov ebx,DWORD[4+r8]
mov ecx,DWORD[8+r8]
mov edx,DWORD[12+r8]
mov esi,ebx
mov ebp,DWORD[16+r8]
mov edi,ecx
xor edi,edx
and esi,edi
vmovdqa xmm6,XMMWORD[64+r14]
vmovdqa xmm11,XMMWORD[((-64))+r14]
vmovdqu xmm0,XMMWORD[r9]
vmovdqu xmm1,XMMWORD[16+r9]
vmovdqu xmm2,XMMWORD[32+r9]
vmovdqu xmm3,XMMWORD[48+r9]
vpshufb xmm0,xmm0,xmm6
add r9,64
vpshufb xmm1,xmm1,xmm6
vpshufb xmm2,xmm2,xmm6
vpshufb xmm3,xmm3,xmm6
vpaddd xmm4,xmm0,xmm11
vpaddd xmm5,xmm1,xmm11
vpaddd xmm6,xmm2,xmm11
vmovdqa XMMWORD[rsp],xmm4
vmovdqa XMMWORD[16+rsp],xmm5
vmovdqa XMMWORD[32+rsp],xmm6
jmp NEAR $L$oop_avx
ALIGN 16
$L$oop_avx:
shrd ebx,ebx,2
xor esi,edx
vpalignr xmm4,xmm1,xmm0,8
mov edi,eax
add ebp,DWORD[rsp]
vpaddd xmm9,xmm11,xmm3
xor ebx,ecx
shld eax,eax,5
vpsrldq xmm8,xmm3,4
add ebp,esi
and edi,ebx
vpxor xmm4,xmm4,xmm0
xor ebx,ecx
add ebp,eax
vpxor xmm8,xmm8,xmm2
shrd eax,eax,7
xor edi,ecx
mov esi,ebp
add edx,DWORD[4+rsp]
vpxor xmm4,xmm4,xmm8
xor eax,ebx
shld ebp,ebp,5
vmovdqa XMMWORD[48+rsp],xmm9
add edx,edi
and esi,eax
vpsrld xmm8,xmm4,31
xor eax,ebx
add edx,ebp
shrd ebp,ebp,7
xor esi,ebx
vpslldq xmm10,xmm4,12
vpaddd xmm4,xmm4,xmm4
mov edi,edx
add ecx,DWORD[8+rsp]
xor ebp,eax
shld edx,edx,5
vpsrld xmm9,xmm10,30
vpor xmm4,xmm4,xmm8
add ecx,esi
and edi,ebp
xor ebp,eax
add ecx,edx
vpslld xmm10,xmm10,2
vpxor xmm4,xmm4,xmm9
shrd edx,edx,7
xor edi,eax
mov esi,ecx
add ebx,DWORD[12+rsp]
vpxor xmm4,xmm4,xmm10
xor edx,ebp
shld ecx,ecx,5
add ebx,edi
and esi,edx
xor edx,ebp
add ebx,ecx
shrd ecx,ecx,7
xor esi,ebp
vpalignr xmm5,xmm2,xmm1,8
mov edi,ebx
add eax,DWORD[16+rsp]
vpaddd xmm9,xmm11,xmm4
xor ecx,edx
shld ebx,ebx,5
vpsrldq xmm8,xmm4,4
add eax,esi
and edi,ecx
vpxor xmm5,xmm5,xmm1
xor ecx,edx
add eax,ebx
vpxor xmm8,xmm8,xmm3
shrd ebx,ebx,7
xor edi,edx
mov esi,eax
add ebp,DWORD[20+rsp]
vpxor xmm5,xmm5,xmm8
xor ebx,ecx
shld eax,eax,5
vmovdqa XMMWORD[rsp],xmm9
add ebp,edi
and esi,ebx
vpsrld xmm8,xmm5,31
xor ebx,ecx
add ebp,eax
shrd eax,eax,7
xor esi,ecx
vpslldq xmm10,xmm5,12
vpaddd xmm5,xmm5,xmm5
mov edi,ebp
add edx,DWORD[24+rsp]
xor eax,ebx
shld ebp,ebp,5
vpsrld xmm9,xmm10,30
vpor xmm5,xmm5,xmm8
add edx,esi
and edi,eax
xor eax,ebx
add edx,ebp
vpslld xmm10,xmm10,2
vpxor xmm5,xmm5,xmm9
shrd ebp,ebp,7
xor edi,ebx
mov esi,edx
add ecx,DWORD[28+rsp]
vpxor xmm5,xmm5,xmm10
xor ebp,eax
shld edx,edx,5
vmovdqa xmm11,XMMWORD[((-32))+r14]
add ecx,edi
and esi,ebp
xor ebp,eax
add ecx,edx
shrd edx,edx,7
xor esi,eax
vpalignr xmm6,xmm3,xmm2,8
mov edi,ecx
add ebx,DWORD[32+rsp]
vpaddd xmm9,xmm11,xmm5
xor edx,ebp
shld ecx,ecx,5
vpsrldq xmm8,xmm5,4
add ebx,esi
and edi,edx
vpxor xmm6,xmm6,xmm2
xor edx,ebp
add ebx,ecx
vpxor xmm8,xmm8,xmm4
shrd ecx,ecx,7
xor edi,ebp
mov esi,ebx
add eax,DWORD[36+rsp]
vpxor xmm6,xmm6,xmm8
xor ecx,edx
shld ebx,ebx,5
vmovdqa XMMWORD[16+rsp],xmm9
add eax,edi
and esi,ecx
vpsrld xmm8,xmm6,31
xor ecx,edx
add eax,ebx
shrd ebx,ebx,7
xor esi,edx
vpslldq xmm10,xmm6,12
vpaddd xmm6,xmm6,xmm6
mov edi,eax
add ebp,DWORD[40+rsp]
xor ebx,ecx
shld eax,eax,5
vpsrld xmm9,xmm10,30
vpor xmm6,xmm6,xmm8
add ebp,esi
and edi,ebx
xor ebx,ecx
add ebp,eax
vpslld xmm10,xmm10,2
vpxor xmm6,xmm6,xmm9
shrd eax,eax,7
xor edi,ecx
mov esi,ebp
add edx,DWORD[44+rsp]
vpxor xmm6,xmm6,xmm10
xor eax,ebx
shld ebp,ebp,5
add edx,edi
and esi,eax
xor eax,ebx
add edx,ebp
shrd ebp,ebp,7
xor esi,ebx
vpalignr xmm7,xmm4,xmm3,8
mov edi,edx
add ecx,DWORD[48+rsp]
vpaddd xmm9,xmm11,xmm6
xor ebp,eax
shld edx,edx,5
vpsrldq xmm8,xmm6,4
add ecx,esi
and edi,ebp
vpxor xmm7,xmm7,xmm3
xor ebp,eax
add ecx,edx
vpxor xmm8,xmm8,xmm5
shrd edx,edx,7
xor edi,eax
mov esi,ecx
add ebx,DWORD[52+rsp]
vpxor xmm7,xmm7,xmm8
xor edx,ebp
shld ecx,ecx,5
vmovdqa XMMWORD[32+rsp],xmm9
add ebx,edi
and esi,edx
vpsrld xmm8,xmm7,31
xor edx,ebp
add ebx,ecx
shrd ecx,ecx,7
xor esi,ebp
vpslldq xmm10,xmm7,12
vpaddd xmm7,xmm7,xmm7
mov edi,ebx
add eax,DWORD[56+rsp]
xor ecx,edx
shld ebx,ebx,5
vpsrld xmm9,xmm10,30
vpor xmm7,xmm7,xmm8
add eax,esi
and edi,ecx
xor ecx,edx
add eax,ebx
vpslld xmm10,xmm10,2
vpxor xmm7,xmm7,xmm9
shrd ebx,ebx,7
xor edi,edx
mov esi,eax
add ebp,DWORD[60+rsp]
vpxor xmm7,xmm7,xmm10
xor ebx,ecx
shld eax,eax,5
add ebp,edi
and esi,ebx
xor ebx,ecx
add ebp,eax
vpalignr xmm8,xmm7,xmm6,8
vpxor xmm0,xmm0,xmm4
shrd eax,eax,7
xor esi,ecx
mov edi,ebp
add edx,DWORD[rsp]
vpxor xmm0,xmm0,xmm1
xor eax,ebx
shld ebp,ebp,5
vpaddd xmm9,xmm11,xmm7
add edx,esi
and edi,eax
vpxor xmm0,xmm0,xmm8
xor eax,ebx
add edx,ebp
shrd ebp,ebp,7
xor edi,ebx
vpsrld xmm8,xmm0,30
vmovdqa XMMWORD[48+rsp],xmm9
mov esi,edx
add ecx,DWORD[4+rsp]
xor ebp,eax
shld edx,edx,5
vpslld xmm0,xmm0,2
add ecx,edi
and esi,ebp
xor ebp,eax
add ecx,edx
shrd edx,edx,7
xor esi,eax
mov edi,ecx
add ebx,DWORD[8+rsp]
vpor xmm0,xmm0,xmm8
xor edx,ebp
shld ecx,ecx,5
add ebx,esi
and edi,edx
xor edx,ebp
add ebx,ecx
add eax,DWORD[12+rsp]
xor edi,ebp
mov esi,ebx
shld ebx,ebx,5
add eax,edi
xor esi,edx
shrd ecx,ecx,7
add eax,ebx
vpalignr xmm8,xmm0,xmm7,8
vpxor xmm1,xmm1,xmm5
add ebp,DWORD[16+rsp]
xor esi,ecx
mov edi,eax
shld eax,eax,5
vpxor xmm1,xmm1,xmm2
add ebp,esi
xor edi,ecx
vpaddd xmm9,xmm11,xmm0
shrd ebx,ebx,7
add ebp,eax
vpxor xmm1,xmm1,xmm8
add edx,DWORD[20+rsp]
xor edi,ebx
mov esi,ebp
shld ebp,ebp,5
vpsrld xmm8,xmm1,30
vmovdqa XMMWORD[rsp],xmm9
add edx,edi
xor esi,ebx
shrd eax,eax,7
add edx,ebp
vpslld xmm1,xmm1,2
add ecx,DWORD[24+rsp]
xor esi,eax
mov edi,edx
shld edx,edx,5
add ecx,esi
xor edi,eax
shrd ebp,ebp,7
add ecx,edx
vpor xmm1,xmm1,xmm8
add ebx,DWORD[28+rsp]
xor edi,ebp
mov esi,ecx
shld ecx,ecx,5
add ebx,edi
xor esi,ebp
shrd edx,edx,7
add ebx,ecx
vpalignr xmm8,xmm1,xmm0,8
vpxor xmm2,xmm2,xmm6
add eax,DWORD[32+rsp]
xor esi,edx
mov edi,ebx
shld ebx,ebx,5
vpxor xmm2,xmm2,xmm3
add eax,esi
xor edi,edx
vpaddd xmm9,xmm11,xmm1
vmovdqa xmm11,XMMWORD[r14]
shrd ecx,ecx,7
add eax,ebx
vpxor xmm2,xmm2,xmm8
add ebp,DWORD[36+rsp]
xor edi,ecx
mov esi,eax
shld eax,eax,5
vpsrld xmm8,xmm2,30
vmovdqa XMMWORD[16+rsp],xmm9
add ebp,edi
xor esi,ecx
shrd ebx,ebx,7
add ebp,eax
vpslld xmm2,xmm2,2
add edx,DWORD[40+rsp]
xor esi,ebx
mov edi,ebp
shld ebp,ebp,5
add edx,esi
xor edi,ebx
shrd eax,eax,7
add edx,ebp
vpor xmm2,xmm2,xmm8
add ecx,DWORD[44+rsp]
xor edi,eax
mov esi,edx
shld edx,edx,5
add ecx,edi
xor esi,eax
shrd ebp,ebp,7
add ecx,edx
vpalignr xmm8,xmm2,xmm1,8
vpxor xmm3,xmm3,xmm7
add ebx,DWORD[48+rsp]
xor esi,ebp
mov edi,ecx
shld ecx,ecx,5
vpxor xmm3,xmm3,xmm4
add ebx,esi
xor edi,ebp
vpaddd xmm9,xmm11,xmm2
shrd edx,edx,7
add ebx,ecx
vpxor xmm3,xmm3,xmm8
add eax,DWORD[52+rsp]
xor edi,edx
mov esi,ebx
shld ebx,ebx,5
vpsrld xmm8,xmm3,30
vmovdqa XMMWORD[32+rsp],xmm9
add eax,edi
xor esi,edx
shrd ecx,ecx,7
add eax,ebx
vpslld xmm3,xmm3,2
add ebp,DWORD[56+rsp]
xor esi,ecx
mov edi,eax
shld eax,eax,5
add ebp,esi
xor edi,ecx
shrd ebx,ebx,7
add ebp,eax
vpor xmm3,xmm3,xmm8
add edx,DWORD[60+rsp]
xor edi,ebx
mov esi,ebp
shld ebp,ebp,5
add edx,edi
xor esi,ebx
shrd eax,eax,7
add edx,ebp
vpalignr xmm8,xmm3,xmm2,8
vpxor xmm4,xmm4,xmm0
add ecx,DWORD[rsp]
xor esi,eax
mov edi,edx
shld edx,edx,5
vpxor xmm4,xmm4,xmm5
add ecx,esi
xor edi,eax
vpaddd xmm9,xmm11,xmm3
shrd ebp,ebp,7
add ecx,edx
vpxor xmm4,xmm4,xmm8
add ebx,DWORD[4+rsp]
xor edi,ebp
mov esi,ecx
shld ecx,ecx,5
vpsrld xmm8,xmm4,30
vmovdqa XMMWORD[48+rsp],xmm9
add ebx,edi
xor esi,ebp
shrd edx,edx,7
add ebx,ecx
vpslld xmm4,xmm4,2
add eax,DWORD[8+rsp]
xor esi,edx
mov edi,ebx
shld ebx,ebx,5
add eax,esi
xor edi,edx
shrd ecx,ecx,7
add eax,ebx
vpor xmm4,xmm4,xmm8
add ebp,DWORD[12+rsp]
xor edi,ecx
mov esi,eax
shld eax,eax,5
add ebp,edi
xor esi,ecx
shrd ebx,ebx,7
add ebp,eax
vpalignr xmm8,xmm4,xmm3,8
vpxor xmm5,xmm5,xmm1
add edx,DWORD[16+rsp]
xor esi,ebx
mov edi,ebp
shld ebp,ebp,5
vpxor xmm5,xmm5,xmm6
add edx,esi
xor edi,ebx
vpaddd xmm9,xmm11,xmm4
shrd eax,eax,7
add edx,ebp
vpxor xmm5,xmm5,xmm8
add ecx,DWORD[20+rsp]
xor edi,eax
mov esi,edx
shld edx,edx,5
vpsrld xmm8,xmm5,30
vmovdqa XMMWORD[rsp],xmm9
add ecx,edi
xor esi,eax
shrd ebp,ebp,7
add ecx,edx
vpslld xmm5,xmm5,2
add ebx,DWORD[24+rsp]
xor esi,ebp
mov edi,ecx
shld ecx,ecx,5
add ebx,esi
xor edi,ebp
shrd edx,edx,7
add ebx,ecx
vpor xmm5,xmm5,xmm8
add eax,DWORD[28+rsp]
shrd ecx,ecx,7
mov esi,ebx
xor edi,edx
shld ebx,ebx,5
add eax,edi
xor esi,ecx
xor ecx,edx
add eax,ebx
vpalignr xmm8,xmm5,xmm4,8
vpxor xmm6,xmm6,xmm2
add ebp,DWORD[32+rsp]
and esi,ecx
xor ecx,edx
shrd ebx,ebx,7
vpxor xmm6,xmm6,xmm7
mov edi,eax
xor esi,ecx
vpaddd xmm9,xmm11,xmm5
shld eax,eax,5
add ebp,esi
vpxor xmm6,xmm6,xmm8
xor edi,ebx
xor ebx,ecx
add ebp,eax
add edx,DWORD[36+rsp]
vpsrld xmm8,xmm6,30
vmovdqa XMMWORD[16+rsp],xmm9
and edi,ebx
xor ebx,ecx
shrd eax,eax,7
mov esi,ebp
vpslld xmm6,xmm6,2
xor edi,ebx
shld ebp,ebp,5
add edx,edi
xor esi,eax
xor eax,ebx
add edx,ebp
add ecx,DWORD[40+rsp]
and esi,eax
vpor xmm6,xmm6,xmm8
xor eax,ebx
shrd ebp,ebp,7
mov edi,edx
xor esi,eax
shld edx,edx,5
add ecx,esi
xor edi,ebp
xor ebp,eax
add ecx,edx
add ebx,DWORD[44+rsp]
and edi,ebp
xor ebp,eax
shrd edx,edx,7
mov esi,ecx
xor edi,ebp
shld ecx,ecx,5
add ebx,edi
xor esi,edx
xor edx,ebp
add ebx,ecx
vpalignr xmm8,xmm6,xmm5,8
vpxor xmm7,xmm7,xmm3
add eax,DWORD[48+rsp]
and esi,edx
xor edx,ebp
shrd ecx,ecx,7
vpxor xmm7,xmm7,xmm0
mov edi,ebx
xor esi,edx
vpaddd xmm9,xmm11,xmm6
vmovdqa xmm11,XMMWORD[32+r14]
shld ebx,ebx,5
add eax,esi
vpxor xmm7,xmm7,xmm8
xor edi,ecx
xor ecx,edx
add eax,ebx
add ebp,DWORD[52+rsp]
vpsrld xmm8,xmm7,30
vmovdqa XMMWORD[32+rsp],xmm9
and edi,ecx
xor ecx,edx
shrd ebx,ebx,7
mov esi,eax
vpslld xmm7,xmm7,2
xor edi,ecx
shld eax,eax,5
add ebp,edi
xor esi,ebx
xor ebx,ecx
add ebp,eax
add edx,DWORD[56+rsp]
and esi,ebx
vpor xmm7,xmm7,xmm8
xor ebx,ecx
shrd eax,eax,7
mov edi,ebp
xor esi,ebx
shld ebp,ebp,5
add edx,esi
xor edi,eax
xor eax,ebx
add edx,ebp
add ecx,DWORD[60+rsp]
and edi,eax
xor eax,ebx
shrd ebp,ebp,7
mov esi,edx
xor edi,eax
shld edx,edx,5
add ecx,edi
xor esi,ebp
xor ebp,eax
add ecx,edx
vpalignr xmm8,xmm7,xmm6,8
vpxor xmm0,xmm0,xmm4
add ebx,DWORD[rsp]
and esi,ebp
xor ebp,eax
shrd edx,edx,7
vpxor xmm0,xmm0,xmm1
mov edi,ecx
xor esi,ebp
vpaddd xmm9,xmm11,xmm7
shld ecx,ecx,5
add ebx,esi
vpxor xmm0,xmm0,xmm8
xor edi,edx
xor edx,ebp
add ebx,ecx
add eax,DWORD[4+rsp]
vpsrld xmm8,xmm0,30
vmovdqa XMMWORD[48+rsp],xmm9
and edi,edx
xor edx,ebp
shrd ecx,ecx,7
mov esi,ebx
vpslld xmm0,xmm0,2
xor edi,edx
shld ebx,ebx,5
add eax,edi
xor esi,ecx
xor ecx,edx
add eax,ebx
add ebp,DWORD[8+rsp]
and esi,ecx
vpor xmm0,xmm0,xmm8
xor ecx,edx
shrd ebx,ebx,7
mov edi,eax
xor esi,ecx
shld eax,eax,5
add ebp,esi
xor edi,ebx
xor ebx,ecx
add ebp,eax
add edx,DWORD[12+rsp]
and edi,ebx
xor ebx,ecx
shrd eax,eax,7
mov esi,ebp
xor edi,ebx
shld ebp,ebp,5
add edx,edi
xor esi,eax
xor eax,ebx
add edx,ebp
vpalignr xmm8,xmm0,xmm7,8
vpxor xmm1,xmm1,xmm5
add ecx,DWORD[16+rsp]
and esi,eax
xor eax,ebx
shrd ebp,ebp,7
vpxor xmm1,xmm1,xmm2
mov edi,edx
xor esi,eax
vpaddd xmm9,xmm11,xmm0
shld edx,edx,5
add ecx,esi
vpxor xmm1,xmm1,xmm8
xor edi,ebp
xor ebp,eax
add ecx,edx
add ebx,DWORD[20+rsp]
vpsrld xmm8,xmm1,30
vmovdqa XMMWORD[rsp],xmm9
and edi,ebp
xor ebp,eax
shrd edx,edx,7
mov esi,ecx
vpslld xmm1,xmm1,2
xor edi,ebp
shld ecx,ecx,5
add ebx,edi
xor esi,edx
xor edx,ebp
add ebx,ecx
add eax,DWORD[24+rsp]
and esi,edx
vpor xmm1,xmm1,xmm8
xor edx,ebp
shrd ecx,ecx,7
mov edi,ebx
xor esi,edx
shld ebx,ebx,5
add eax,esi
xor edi,ecx
xor ecx,edx
add eax,ebx
add ebp,DWORD[28+rsp]
and edi,ecx
xor ecx,edx
shrd ebx,ebx,7
mov esi,eax
xor edi,ecx
shld eax,eax,5
add ebp,edi
xor esi,ebx
xor ebx,ecx
add ebp,eax
vpalignr xmm8,xmm1,xmm0,8
vpxor xmm2,xmm2,xmm6
add edx,DWORD[32+rsp]
and esi,ebx
xor ebx,ecx
shrd eax,eax,7
vpxor xmm2,xmm2,xmm3
mov edi,ebp
xor esi,ebx
vpaddd xmm9,xmm11,xmm1
shld ebp,ebp,5
add edx,esi
vpxor xmm2,xmm2,xmm8
xor edi,eax
xor eax,ebx
add edx,ebp
add ecx,DWORD[36+rsp]
vpsrld xmm8,xmm2,30
vmovdqa XMMWORD[16+rsp],xmm9
and edi,eax
xor eax,ebx
shrd ebp,ebp,7
mov esi,edx
vpslld xmm2,xmm2,2
xor edi,eax
shld edx,edx,5
add ecx,edi
xor esi,ebp
xor ebp,eax
add ecx,edx
add ebx,DWORD[40+rsp]
and esi,ebp
vpor xmm2,xmm2,xmm8
xor ebp,eax
shrd edx,edx,7
mov edi,ecx
xor esi,ebp
shld ecx,ecx,5
add ebx,esi
xor edi,edx
xor edx,ebp
add ebx,ecx
add eax,DWORD[44+rsp]
and edi,edx
xor edx,ebp
shrd ecx,ecx,7
mov esi,ebx
xor edi,edx
shld ebx,ebx,5
add eax,edi
xor esi,edx
add eax,ebx
vpalignr xmm8,xmm2,xmm1,8
vpxor xmm3,xmm3,xmm7
add ebp,DWORD[48+rsp]
xor esi,ecx
mov edi,eax
shld eax,eax,5
vpxor xmm3,xmm3,xmm4
add ebp,esi
xor edi,ecx
vpaddd xmm9,xmm11,xmm2
shrd ebx,ebx,7
add ebp,eax
vpxor xmm3,xmm3,xmm8
add edx,DWORD[52+rsp]
xor edi,ebx
mov esi,ebp
shld ebp,ebp,5
vpsrld xmm8,xmm3,30
vmovdqa XMMWORD[32+rsp],xmm9
add edx,edi
xor esi,ebx
shrd eax,eax,7
add edx,ebp
vpslld xmm3,xmm3,2
add ecx,DWORD[56+rsp]
xor esi,eax
mov edi,edx
shld edx,edx,5
add ecx,esi
xor edi,eax
shrd ebp,ebp,7
add ecx,edx
vpor xmm3,xmm3,xmm8
add ebx,DWORD[60+rsp]
xor edi,ebp
mov esi,ecx
shld ecx,ecx,5
add ebx,edi
xor esi,ebp
shrd edx,edx,7
add ebx,ecx
add eax,DWORD[rsp]
vpaddd xmm9,xmm11,xmm3
xor esi,edx
mov edi,ebx
shld ebx,ebx,5
add eax,esi
vmovdqa XMMWORD[48+rsp],xmm9
xor edi,edx
shrd ecx,ecx,7
add eax,ebx
add ebp,DWORD[4+rsp]
xor edi,ecx
mov esi,eax
shld eax,eax,5
add ebp,edi
xor esi,ecx
shrd ebx,ebx,7
add ebp,eax
add edx,DWORD[8+rsp]
xor esi,ebx
mov edi,ebp
shld ebp,ebp,5
add edx,esi
xor edi,ebx
shrd eax,eax,7
add edx,ebp
add ecx,DWORD[12+rsp]
xor edi,eax
mov esi,edx
shld edx,edx,5
add ecx,edi
xor esi,eax
shrd ebp,ebp,7
add ecx,edx
cmp r9,r10
je NEAR $L$done_avx
vmovdqa xmm6,XMMWORD[64+r14]
vmovdqa xmm11,XMMWORD[((-64))+r14]
vmovdqu xmm0,XMMWORD[r9]
vmovdqu xmm1,XMMWORD[16+r9]
vmovdqu xmm2,XMMWORD[32+r9]
vmovdqu xmm3,XMMWORD[48+r9]
vpshufb xmm0,xmm0,xmm6
add r9,64
add ebx,DWORD[16+rsp]
xor esi,ebp
vpshufb xmm1,xmm1,xmm6
mov edi,ecx
shld ecx,ecx,5
vpaddd xmm4,xmm0,xmm11
add ebx,esi
xor edi,ebp
shrd edx,edx,7
add ebx,ecx
vmovdqa XMMWORD[rsp],xmm4
add eax,DWORD[20+rsp]
xor edi,edx
mov esi,ebx
shld ebx,ebx,5
add eax,edi
xor esi,edx
shrd ecx,ecx,7
add eax,ebx
add ebp,DWORD[24+rsp]
xor esi,ecx
mov edi,eax
shld eax,eax,5
add ebp,esi
xor edi,ecx
shrd ebx,ebx,7
add ebp,eax
add edx,DWORD[28+rsp]
xor edi,ebx
mov esi,ebp
shld ebp,ebp,5
add edx,edi
xor esi,ebx
shrd eax,eax,7
add edx,ebp
add ecx,DWORD[32+rsp]
xor esi,eax
vpshufb xmm2,xmm2,xmm6
mov edi,edx
shld edx,edx,5
vpaddd xmm5,xmm1,xmm11
add ecx,esi
xor edi,eax
shrd ebp,ebp,7
add ecx,edx
vmovdqa XMMWORD[16+rsp],xmm5
add ebx,DWORD[36+rsp]
xor edi,ebp
mov esi,ecx
shld ecx,ecx,5
add ebx,edi
xor esi,ebp
shrd edx,edx,7
add ebx,ecx
add eax,DWORD[40+rsp]
xor esi,edx
mov edi,ebx
shld ebx,ebx,5
add eax,esi
xor edi,edx
shrd ecx,ecx,7
add eax,ebx
add ebp,DWORD[44+rsp]
xor edi,ecx
mov esi,eax
shld eax,eax,5
add ebp,edi
xor esi,ecx
shrd ebx,ebx,7
add ebp,eax
add edx,DWORD[48+rsp]
xor esi,ebx
vpshufb xmm3,xmm3,xmm6
mov edi,ebp
shld ebp,ebp,5
vpaddd xmm6,xmm2,xmm11
add edx,esi
xor edi,ebx
shrd eax,eax,7
add edx,ebp
vmovdqa XMMWORD[32+rsp],xmm6
add ecx,DWORD[52+rsp]
xor edi,eax
mov esi,edx
shld edx,edx,5
add ecx,edi
xor esi,eax
shrd ebp,ebp,7
add ecx,edx
add ebx,DWORD[56+rsp]
xor esi,ebp
mov edi,ecx
shld ecx,ecx,5
add ebx,esi
xor edi,ebp
shrd edx,edx,7
add ebx,ecx
add eax,DWORD[60+rsp]
xor edi,edx
mov esi,ebx
shld ebx,ebx,5
add eax,edi
shrd ecx,ecx,7
add eax,ebx
add eax,DWORD[r8]
add esi,DWORD[4+r8]
add ecx,DWORD[8+r8]
add edx,DWORD[12+r8]
mov DWORD[r8],eax
add ebp,DWORD[16+r8]
mov DWORD[4+r8],esi
mov ebx,esi
mov DWORD[8+r8],ecx
mov edi,ecx
mov DWORD[12+r8],edx
xor edi,edx
mov DWORD[16+r8],ebp
and esi,edi
jmp NEAR $L$oop_avx
ALIGN 16
$L$done_avx:
add ebx,DWORD[16+rsp]
xor esi,ebp
mov edi,ecx
shld ecx,ecx,5
add ebx,esi
xor edi,ebp
shrd edx,edx,7
add ebx,ecx
add eax,DWORD[20+rsp]
xor edi,edx
mov esi,ebx
shld ebx,ebx,5
add eax,edi
xor esi,edx
shrd ecx,ecx,7
add eax,ebx
add ebp,DWORD[24+rsp]
xor esi,ecx
mov edi,eax
shld eax,eax,5
add ebp,esi
xor edi,ecx
shrd ebx,ebx,7
add ebp,eax
add edx,DWORD[28+rsp]
xor edi,ebx
mov esi,ebp
shld ebp,ebp,5
add edx,edi
xor esi,ebx
shrd eax,eax,7
add edx,ebp
add ecx,DWORD[32+rsp]
xor esi,eax
mov edi,edx
shld edx,edx,5
add ecx,esi
xor edi,eax
shrd ebp,ebp,7
add ecx,edx
add ebx,DWORD[36+rsp]
xor edi,ebp
mov esi,ecx
shld ecx,ecx,5
add ebx,edi
xor esi,ebp
shrd edx,edx,7
add ebx,ecx
add eax,DWORD[40+rsp]
xor esi,edx
mov edi,ebx
shld ebx,ebx,5
add eax,esi
xor edi,edx
shrd ecx,ecx,7
add eax,ebx
add ebp,DWORD[44+rsp]
xor edi,ecx
mov esi,eax
shld eax,eax,5
add ebp,edi
xor esi,ecx
shrd ebx,ebx,7
add ebp,eax
add edx,DWORD[48+rsp]
xor esi,ebx
mov edi,ebp
shld ebp,ebp,5
add edx,esi
xor edi,ebx
shrd eax,eax,7
add edx,ebp
add ecx,DWORD[52+rsp]
xor edi,eax
mov esi,edx
shld edx,edx,5
add ecx,edi
xor esi,eax
shrd ebp,ebp,7
add ecx,edx
add ebx,DWORD[56+rsp]
xor esi,ebp
mov edi,ecx
shld ecx,ecx,5
add ebx,esi
xor edi,ebp
shrd edx,edx,7
add ebx,ecx
add eax,DWORD[60+rsp]
xor edi,edx
mov esi,ebx
shld ebx,ebx,5
add eax,edi
shrd ecx,ecx,7
add eax,ebx
vzeroupper
add eax,DWORD[r8]
add esi,DWORD[4+r8]
add ecx,DWORD[8+r8]
mov DWORD[r8],eax
add edx,DWORD[12+r8]
mov DWORD[4+r8],esi
add ebp,DWORD[16+r8]
mov DWORD[8+r8],ecx
mov DWORD[12+r8],edx
mov DWORD[16+r8],ebp
movaps xmm6,XMMWORD[((-40-96))+r11]
movaps xmm7,XMMWORD[((-40-80))+r11]
movaps xmm8,XMMWORD[((-40-64))+r11]
movaps xmm9,XMMWORD[((-40-48))+r11]
movaps xmm10,XMMWORD[((-40-32))+r11]
movaps xmm11,XMMWORD[((-40-16))+r11]
mov r14,QWORD[((-40))+r11]
mov r13,QWORD[((-32))+r11]
mov r12,QWORD[((-24))+r11]
mov rbp,QWORD[((-16))+r11]
mov rbx,QWORD[((-8))+r11]
lea rsp,[r11]
$L$epilogue_avx:
mov rdi,QWORD[8+rsp] ;WIN64 epilogue
mov rsi,QWORD[16+rsp]
DB 0F3h,0C3h ;repret
$L$SEH_end_sha1_block_data_order_avx:
ALIGN 64
K_XX_XX:
DD 0x5a827999,0x5a827999,0x5a827999,0x5a827999
DD 0x5a827999,0x5a827999,0x5a827999,0x5a827999
DD 0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1
DD 0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1
DD 0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc
DD 0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc
DD 0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6
DD 0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6
DD 0x00010203,0x04050607,0x08090a0b,0x0c0d0e0f
DD 0x00010203,0x04050607,0x08090a0b,0x0c0d0e0f
DB 0xf,0xe,0xd,0xc,0xb,0xa,0x9,0x8,0x7,0x6,0x5,0x4,0x3,0x2,0x1,0x0
DB 83,72,65,49,32,98,108,111,99,107,32,116,114,97,110,115
DB 102,111,114,109,32,102,111,114,32,120,56,54,95,54,52,44
DB 32,67,82,89,80,84,79,71,65,77,83,32,98,121,32,60
DB 97,112,112,114,111,64,111,112,101,110,115,115,108,46,111,114
DB 103,62,0
ALIGN 64
EXTERN __imp_RtlVirtualUnwind
ALIGN 16
se_handler:
push rsi
push rdi
push rbx
push rbp
push r12
push r13
push r14
push r15
pushfq
sub rsp,64
mov rax,QWORD[120+r8]
mov rbx,QWORD[248+r8]
lea r10,[$L$prologue]
cmp rbx,r10
jb NEAR $L$common_seh_tail
mov rax,QWORD[152+r8]
lea r10,[$L$epilogue]
cmp rbx,r10
jae NEAR $L$common_seh_tail
mov rax,QWORD[64+rax]
mov rbx,QWORD[((-8))+rax]
mov rbp,QWORD[((-16))+rax]
mov r12,QWORD[((-24))+rax]
mov r13,QWORD[((-32))+rax]
mov r14,QWORD[((-40))+rax]
mov QWORD[144+r8],rbx
mov QWORD[160+r8],rbp
mov QWORD[216+r8],r12
mov QWORD[224+r8],r13
mov QWORD[232+r8],r14
jmp NEAR $L$common_seh_tail
ALIGN 16
ssse3_handler:
push rsi
push rdi
push rbx
push rbp
push r12
push r13
push r14
push r15
pushfq
sub rsp,64
mov rax,QWORD[120+r8]
mov rbx,QWORD[248+r8]
mov rsi,QWORD[8+r9]
mov r11,QWORD[56+r9]
mov r10d,DWORD[r11]
lea r10,[r10*1+rsi]
cmp rbx,r10
jb NEAR $L$common_seh_tail
mov rax,QWORD[208+r8]
mov r10d,DWORD[4+r11]
lea r10,[r10*1+rsi]
cmp rbx,r10
jae NEAR $L$common_seh_tail
lea rsi,[((-40-96))+rax]
lea rdi,[512+r8]
mov ecx,12
DD 0xa548f3fc
mov rbx,QWORD[((-8))+rax]
mov rbp,QWORD[((-16))+rax]
mov r12,QWORD[((-24))+rax]
mov r13,QWORD[((-32))+rax]
mov r14,QWORD[((-40))+rax]
mov QWORD[144+r8],rbx
mov QWORD[160+r8],rbp
mov QWORD[216+r8],r12
mov QWORD[224+r8],r13
mov QWORD[232+r8],r14
$L$common_seh_tail:
mov rdi,QWORD[8+rax]
mov rsi,QWORD[16+rax]
mov QWORD[152+r8],rax
mov QWORD[168+r8],rsi
mov QWORD[176+r8],rdi
mov rdi,QWORD[40+r9]
mov rsi,r8
mov ecx,154
DD 0xa548f3fc
mov rsi,r9
xor rcx,rcx
mov rdx,QWORD[8+rsi]
mov r8,QWORD[rsi]
mov r9,QWORD[16+rsi]
mov r10,QWORD[40+rsi]
lea r11,[56+rsi]
lea r12,[24+rsi]
mov QWORD[32+rsp],r10
mov QWORD[40+rsp],r11
mov QWORD[48+rsp],r12
mov QWORD[56+rsp],rcx
call QWORD[__imp_RtlVirtualUnwind]
mov eax,1
add rsp,64
popfq
pop r15
pop r14
pop r13
pop r12
pop rbp
pop rbx
pop rdi
pop rsi
DB 0F3h,0C3h ;repret
section .pdata rdata align=4
ALIGN 4
DD $L$SEH_begin_sha1_block_data_order wrt ..imagebase
DD $L$SEH_end_sha1_block_data_order wrt ..imagebase
DD $L$SEH_info_sha1_block_data_order wrt ..imagebase
DD $L$SEH_begin_sha1_block_data_order_ssse3 wrt ..imagebase
DD $L$SEH_end_sha1_block_data_order_ssse3 wrt ..imagebase
DD $L$SEH_info_sha1_block_data_order_ssse3 wrt ..imagebase
DD $L$SEH_begin_sha1_block_data_order_avx wrt ..imagebase
DD $L$SEH_end_sha1_block_data_order_avx wrt ..imagebase
DD $L$SEH_info_sha1_block_data_order_avx wrt ..imagebase
section .xdata rdata align=8
ALIGN 8
$L$SEH_info_sha1_block_data_order:
DB 9,0,0,0
DD se_handler wrt ..imagebase
$L$SEH_info_sha1_block_data_order_ssse3:
DB 9,0,0,0
DD ssse3_handler wrt ..imagebase
DD $L$prologue_ssse3 wrt ..imagebase,$L$epilogue_ssse3 wrt ..imagebase
$L$SEH_info_sha1_block_data_order_avx:
DB 9,0,0,0
DD ssse3_handler wrt ..imagebase
DD $L$prologue_avx wrt ..imagebase,$L$epilogue_avx wrt ..imagebase
|
Java
|
/*
* FILE: RDDSampleUtilsTest
* Copyright (c) 2015 - 2018 GeoSpark Development Team
*
* MIT License
*
* 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 org.datasyslab.geospark.utils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class RDDSampleUtilsTest
{
/**
* Test get sample numbers.
*/
@Test
public void testGetSampleNumbers()
{
assertEquals(10, RDDSampleUtils.getSampleNumbers(2, 10, -1));
assertEquals(100, RDDSampleUtils.getSampleNumbers(2, 100, -1));
assertEquals(10, RDDSampleUtils.getSampleNumbers(5, 1000, -1));
assertEquals(100, RDDSampleUtils.getSampleNumbers(5, 10000, -1));
assertEquals(100, RDDSampleUtils.getSampleNumbers(5, 10001, -1));
assertEquals(1000, RDDSampleUtils.getSampleNumbers(5, 100011, -1));
assertEquals(99, RDDSampleUtils.getSampleNumbers(6, 100011, 99));
assertEquals(999, RDDSampleUtils.getSampleNumbers(20, 999, -1));
assertEquals(40, RDDSampleUtils.getSampleNumbers(20, 1000, -1));
}
/**
* Test too many partitions.
*/
@Test
public void testTooManyPartitions()
{
assertFailure(505, 999);
assertFailure(505, 1000);
assertFailure(10, 1000, 2100);
}
private void assertFailure(int numPartitions, long totalNumberOfRecords)
{
assertFailure(numPartitions, totalNumberOfRecords, -1);
}
private void assertFailure(int numPartitions, long totalNumberOfRecords, int givenSampleNumber)
{
try {
RDDSampleUtils.getSampleNumbers(numPartitions, totalNumberOfRecords, givenSampleNumber);
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException e) {
// expected
}
}
}
|
Java
|
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Class for axis handling.
*
* PHP versions 4 and 5
*
* LICENSE: This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version. This library is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details. You should have received a copy of
* the GNU Lesser General Public License along with this library; if not, write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*
* @category Images
* @package Image_Graph
* @subpackage Axis
* @author Jesper Veggerby <pear.nosey@veggerby.dk>
* @copyright Copyright (C) 2003, 2004 Jesper Veggerby Hansen
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version CVS: $Id: Category.php,v 1.19 2006/03/02 12:15:17 nosey Exp $
* @link http://pear.php.net/package/Image_Graph
*/
/**
* Include file Image/Graph/Axis.php
*/
require_once 'Image/Graph/Axis.php';
/**
* A normal axis thats displays labels with a 'interval' of 1.
* This is basically a normal axis where the range is
* the number of labels defined, that is the range is explicitly defined
* when constructing the axis.
*
* @category Images
* @package Image_Graph
* @subpackage Axis
* @author Jesper Veggerby <pear.nosey@veggerby.dk>
* @copyright Copyright (C) 2003, 2004 Jesper Veggerby Hansen
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version Release: @package_version@
* @link http://pear.php.net/package/Image_Graph
*/
class Image_Graph_Axis_Category extends Image_Graph_Axis
{
/**
* The labels shown on the axis
* @var array
* @access private
*/
var $_labels = false;
/**
* Image_Graph_Axis_Category [Constructor].
*
* @param int $type The type (direction) of the Axis
*/
function Image_Graph_Axis_Category($type = IMAGE_GRAPH_AXIS_X)
{
parent::Image_Graph_Axis($type);
$this->_labels = array();
$this->setlabelInterval(1);
}
/**
* Gets the minimum value the axis will show.
*
* This is always 0
*
* @return double The minumum value
* @access private
*/
function _getMinimum()
{
return 0;
}
/**
* Gets the maximum value the axis will show.
*
* This is always the number of labels passed to the constructor.
*
* @return double The maximum value
* @access private
*/
function _getMaximum()
{
return count($this->_labels) - 1;
}
/**
* Sets the minimum value the axis will show.
*
* A minimum cannot be set on a SequentialAxis, it is always 0.
*
* @param double Minimum The minumum value to use on the axis
* @access private
*/
function _setMinimum($minimum)
{
}
/**
* Sets the maximum value the axis will show
*
* A maximum cannot be set on a SequentialAxis, it is always the number
* of labels passed to the constructor.
*
* @param double Maximum The maximum value to use on the axis
* @access private
*/
function _setMaximum($maximum)
{
}
/**
* Forces the minimum value of the axis
*
* <b>A minimum cannot be set on this type of axis</b>
*
* To modify the labels which are displayed on the axis, instead use
* setLabelInterval($labels) where $labels is an array containing the
* values/labels the axis should display. <b>Note!</b> Only values in
* this array will then be displayed on the graph!
*
* @param double $minimum A minimum cannot be set on this type of axis
*/
function forceMinimum($minimum, $userEnforce = true)
{
}
/**
* Forces the maximum value of the axis
*
* <b>A maximum cannot be set on this type of axis</b>
*
* To modify the labels which are displayed on the axis, instead use
* setLabelInterval($labels) where $labels is an array containing the
* values/labels the axis should display. <b>Note!</b> Only values in
* this array will then be displayed on the graph!
*
* @param double $maximum A maximum cannot be set on this type of axis
*/
function forceMaximum($maximum, $userEnforce = true)
{
}
/**
* Sets an interval for where labels are shown on the axis.
*
* The label interval is rounded to nearest integer value.
*
* @param double $labelInterval The interval with which labels are shown
*/
function setLabelInterval($labelInterval = 'auto', $level = 1)
{
if (is_array($labelInterval)) {
parent::setLabelInterval($labelInterval);
} elseif ($labelInterval == 'auto') {
parent::setLabelInterval(1);
} else {
parent::setLabelInterval(round($labelInterval));
}
}
/**
* Preprocessor for values, ie for using logarithmic axis
*
* @param double $value The value to preprocess
* @return double The preprocessed value
* @access private
*/
function _value($value)
{
// $the_value = array_search($value, $this->_labels);
if (isset($this->_labels[$value])) {
$the_value = $this->_labels[$value];
if ($the_value !== false) {
return $the_value + ($this->_pushValues ? 0.5 : 0);
} else {
return 0;
}
}
}
/**
* Get the minor label interval with which axis label ticks are drawn.
*
* For a sequential axis this is always disabled (i.e false)
*
* @return double The minor label interval, always false
* @access private
*/
function _minorLabelInterval()
{
return false;
}
/**
* Get the size in pixels of the axis.
*
* For an x-axis this is the width of the axis including labels, and for an
* y-axis it is the corrresponding height
*
* @return int The size of the axis
* @access private
*/
function _size()
{
if (!$this->_visible) {
return 0;
}
$this->_canvas->setFont($this->_getFont());
$maxSize = 0;
foreach($this->_labels as $label => $id) {
$labelPosition = $this->_point($label);
if (is_object($this->_dataPreProcessor)) {
$labelText = $this->_dataPreProcessor->_process($label);
} else {
$labelText = $label;
}
if ((($this->_type == IMAGE_GRAPH_AXIS_X) && (!$this->_transpose)) ||
(($this->_type != IMAGE_GRAPH_AXIS_X) && ($this->_transpose)))
{
$maxSize = max($maxSize, $this->_canvas->textHeight($labelText));
} else {
$maxSize = max($maxSize, $this->_canvas->textWidth($labelText));
}
}
if ($this->_title) {
$this->_canvas->setFont($this->_getTitleFont());
if ((($this->_type == IMAGE_GRAPH_AXIS_X) && (!$this->_transpose)) ||
(($this->_type != IMAGE_GRAPH_AXIS_X) && ($this->_transpose)))
{
$maxSize += $this->_canvas->textHeight($this->_title);
} else {
$maxSize += $this->_canvas->textWidth($this->_title);
}
$maxSize += 10;
}
return $maxSize +3;
}
/**
* Apply the dataset to the axis.
*
* This calculates the order of the categories, which is very important
* for fx. line plots, so that the line does not "go backwards", consider
* these X-sets:<p>
* 1: (1, 2, 3, 4, 5, 6)<br>
* 2: (0, 1, 2, 3, 4, 5, 6, 7)<p>
* If they are not ordered, but simply appended, the categories on the axis
* would be:<p>
* X: (1, 2, 3, 4, 5, 6, 0, 7)<p>
* Which would render the a line for the second plot to show incorrectly.
* Instead this algorithm, uses and 'value- is- before' method to see that
* the 0 is before a 1 in the second set, and that it should also be before
* a 1 in the X set. Hence:<p>
* X: (0, 1, 2, 3, 4, 5, 6, 7)
*
* @param Image_Graph_Dataset $dataset The dataset
* @access private
*/
function _applyDataset(&$dataset)
{
$newLabels = array();
$allLabels = array();
$dataset->_reset();
$count = 0;
$count_new = 0;
while ($point = $dataset->_next()) {
if ($this->_type == IMAGE_GRAPH_AXIS_X) {
$data = $point['X'];
} else {
$data = $point['Y'];
}
if (!isset($this->_labels[$data])) {
$newLabels[$data] = $count_new++;
//$this->_labels[] = $data;
}
$allLabels[$data] = $count++;
}
if (count($this->_labels) == 0) {
$this->_labels = $newLabels;
} elseif ((is_array($newLabels)) && (count($newLabels) > 0)) {
// get all intersecting labels
$intersect = array_intersect(array_keys($allLabels), array_keys($this->_labels));
// traverse all new and find their relative position withing the
// intersec, fx value X0 is before X1 in the intersection, which
// means that X0 should be placed before X1 in the label array
foreach($newLabels as $newLabel => $id) {
$key = $allLabels[$newLabel];
reset($intersect);
$this_value = false;
// intersect indexes are the same as in allLabels!
$first = true;
while ((list($id, $value) = each($intersect)) &&
($this_value === false))
{
if (($first) && ($id > $key)) {
$this_value = $value;
} elseif ($id >= $key) {
$this_value = $value;
}
$first = false;
}
if ($this_value === false) {
// the new label was not found before anything in the
// intersection -> append it
$this->_labels[$newLabel] = count($this->_labels);
} else {
// the new label was found before $this_value in the
// intersection, insert the label before this position in
// the label array
// $key = $this->_labels[$this_value];
$keys = array_keys($this->_labels);
$key = array_search($this_value, $keys);
$pre = array_slice($keys, 0, $key);
$pre[] = $newLabel;
$post = array_slice($keys, $key);
$this->_labels = array_flip(array_merge($pre, $post));
}
}
unset($keys);
}
$labels = array_keys($this->_labels);
$i = 0;
foreach ($labels as $label) {
$this->_labels[$label] = $i++;
}
// $this->_labels = array_values(array_unique($this->_labels));
$this->_calcLabelInterval();
}
/**
* Return the label distance.
*
* @return int The distance between 2 adjacent labels
* @access private
*/
function _labelDistance($level = 1)
{
reset($this->_labels);
list($l1) = each($this->_labels);
list($l2) = each($this->_labels);
return abs($this->_point($l2) - $this->_point($l1));
}
/**
* Get next label point
*
* @param doubt $point The current point, if omitted or false, the first is
* returned
* @return double The next label point
* @access private
*/
function _getNextLabel($currentLabel = false, $level = 1)
{
if ($currentLabel === false) {
reset($this->_labels);
}
$result = false;
$count = ($currentLabel === false ? $this->_labelInterval() - 1 : 0);
while ($count < $this->_labelInterval()) {
$result = (list($label) = each($this->_labels));
$count++;
}
if ($result) {
return $label;
} else {
return false;
}
}
/**
* Is the axis numeric or not?
*
* @return bool True if numeric, false if not
* @access private
*/
function _isNumeric()
{
return false;
}
/**
* Output the axis
*
* @return bool Was the output 'good' (true) or 'bad' (false).
* @access private
*/
function _done()
{
$result = true;
if (Image_Graph_Element::_done() === false) {
$result = false;
}
$this->_canvas->startGroup(get_class($this));
$this->_drawAxisLines();
$this->_canvas->startGroup(get_class($this) . '_ticks');
$label = false;
while (($label = $this->_getNextLabel($label)) !== false) {
$this->_drawTick($label);
}
$this->_canvas->endGroup();
$this->_canvas->endGroup();
return $result;
}
}
?>
|
Java
|
/**
* Created by huangyao on 14-10-1.
*/
var _ = require('lodash');
var color =require('colors');
var fs =require('fs');
var config = require('../config.js');
var path = require('path');
var mongoose = require("mongoose");
var lcommon = require('lush').common;
console.log(config.db);
mongoose.connect(config.db,function (err) {
if(err){
throw new Error('db connect error!\n'+err);
}
console.log('db connect success!'.yellow);
});
// console.log('point');
// var models = {
//
// init : function (callback) {
// fs.readdir(path+'/module',function (err,files) {
// if(err){
// throw err;
// }
// // console.log(files);
// return callback(files.filter(function (item) {
// return !(item === "index.js" || item === "." || item === "..");
// }));
// });
// },
// };
//
//
// models.init(function (files) {
// // console.log(files);
// for (var item in files) {
// //reuire all modules
// // console.log(lcommon.literat(files[item]).slice(0,-3));
// console.log(files[item]);
// item = files[item].split('.')[0];
// require('./'+ item);
// var m = lcommon.literat(item);
// console.log('loading and use ',m,' model');
// exports[m] = mongoose.model(m);
//
// // _.extend(models,file.exports);
// // console.log(file);
// }
// });
//
var models = fs.readdirSync(path.resolve('.','module'));
models.forEach(function(item,index){
if(item !== '.' && item !== '..' && item !== 'index.js'){
// console.log(item.indexOf('.js'));
//ends with .js
if(item.indexOf('.js') == (item.length-3)){
item = item.split('.')[0];
require('./'+ item);
var m = lcommon.literat(item);
console.log('loading and use ',m,' model');
exports[m] = mongoose.model(m);
}
}
});
|
Java
|
namespace SalesDatabase.Models
{
using System.Collections.Generic;
public class StoreLocation
{
public StoreLocation()
{
this.SalesInStore = new HashSet<Sale>();
}
public int Id { get; set; }
public string LocationName { get; set; }
public ICollection<Sale> SalesInStore { get; set; }
}
}
|
Java
|
# -*- coding:utf-8 -*-
from re import sub
from itertools import islice
'''
如何调整字符串的文本格式
'''
# 将日志文件中的日期格式转变为美国日期格式mm/dd/yyyy
# 使用正则表达式模块中的sub函数进行替换字符串
with open("./log.log","r") as f:
for line in islice(f,0,None):
#print sub("(\d{4})-(\d{2})-(\d{2})",r"\2/\3/\1",line)
# 可以为每个匹配组起一个别名
print sub("(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})",r"\g<month>/\g<day>/\g<>",line)
|
Java
|
#==============================================================================
# Copyright (c) 2013 Urusov Andrey <drobus@gmail.com>
#==============================================================================
MACRO(ADD_PCH SOURCE_FILES NO_PCH_FILES PROJECT_PATH PCH_PATH_LOCAL PCH_FILE_NAME)
SET(PCH_PATH_LOCAL_INTERNAL ${PCH_PATH_LOCAL})
IF (${PCH_PATH_LOCAL_INTERNAL} STREQUAL "./" OR ${PCH_PATH_LOCAL_INTERNAL} STREQUAL ".")
SET(PCH_PATH_LOCAL_INTERNAL)
ELSE()
SET(PCH_PATH_LOCAL_INTERNAL ${PCH_PATH_LOCAL_INTERNAL}/)
ENDIF()
SET(PCH_FILE_HEADER_IN_SOURCE ${PROJECT_PATH}/${PCH_PATH_LOCAL_INTERNAL}${PCH_FILE_NAME}.h)
SET(PCH_BINARY_OUT ${CMAKE_CURRENT_BINARY_DIR}/${PCH_FILE_NAME}.pch)
SET(PHP_FILE_CPP ${PCH_PATH_LOCAL_INTERNAL}${PCH_FILE_NAME}.cpp)
FOREACH(source_file ${SOURCE_FILES})
GET_FILENAME_COMPONENT(CPP ${source_file} EXT)
IF(${CPP} STREQUAL ".cpp")
IF(${source_file} STREQUAL ${PHP_FILE_CPP})
SET_SOURCE_FILES_PROPERTIES(${PHP_FILE_CPP}
PROPERTIES COMPILE_FLAGS "${COMPILE_FLAGS} /Yc${PCH_FILE_HEADER_IN_SOURCE} /Fp${PCH_BINARY_OUT}"
)
SET_SOURCE_FILES_PROPERTIES(${PHP_FILE_CPP}
PROPERTIES OBJECT_OUTPUTS ${PCH_BINARY_OUT}
)
ELSE()
LIST(FIND NO_PCH_FILES ${source_file} no_pch_index)
IF(${no_pch_index} EQUAL -1)
SET_SOURCE_FILES_PROPERTIES(${source_file}
PROPERTIES COMPILE_FLAGS "${COMPILE_FLAGS} /Yu${PCH_FILE_HEADER_IN_SOURCE} /Fp${PCH_BINARY_OUT}"
)
SET_SOURCE_FILES_PROPERTIES(${source_file}
PROPERTIES OBJECT_DEPENDS ${PCH_BINARY_OUT}
)
ENDIF(${no_pch_index} EQUAL -1)
ENDIF()
ENDIF()
ENDFOREACH(source_file)
ENDMACRO(ADD_PCH)
|
Java
|
version https://git-lfs.github.com/spec/v1
oid sha256:054dbc79bbfc64911008a1e140813a8705dfc5cff35cbffd8bf7bc1f74c446b6
size 5257
|
Java
|
/* form elements */
input[type="submit"],
input[type="text"],
input[type="password"],
input[type="submit"],
input[type="tel"],
button[type="button"],
button[type="submit"],
textarea {
-webkit-appearance: none;
-moz-appearance: none;
-o-appearance: none;
border-radius: 0 !important;
}
input[type="text"] {
padding: 0;
}
/* web accecibility settings */
a:focus,
select:focus,
input[type="radio"]:focus,
input[type="checkbox"]:focus,
input[type="text"]:focus,
input[type="tel"]:focus,
input[type="password"]:focus,
button:focus,
textarea:focus {
outline: #ccc dashed 1px;
}
a:active,
select:active,
input[type="radio"]:active,
input[type="checkbox"]:active,
input[type="text"]:active,
input[type="tel"]:active,
input[type="password"]:active,
textarea:active {
outline: 0;
}
/* default fonts & color */
body {
font-size: 14px;
margin: 0;
color: white;
background: #002144;
}
select, input, button, textarea {
font-family: 'source-han-sans-korean', sans-serif;
}
a {
text-decoration: none;
color: inherit;
}
.setWidth {
margin: 0 auto;
}
#contentWrap {
margin-bottom: 100px;
}
.modalFull {
display: none;
}
.topCover {
display: none;
}
.mobile {
display: none;
}
/* preloader */
#preloader {
position: fixed;
z-index: 500;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: url(../images/ajax-loader.gif) center no-repeat #002144;
}
/* header */
#headerMobile {
display: none;
}
.gnbMobileBtn {
display: none;
}
header .setWidth {
padding: 10px 0;
}
header #logo {
padding-top: 20px;
}
header #logo a {
display: block;
}
header #logo img {
width: 200px;
}
header nav.gnb {
float: right;
}
header nav.gnb > ul {
float: right;
}
header nav.gnb > ul > li {
float: left;
position: relative;
}
header nav.gnb > ul > li.last ul {
right: 0;
}
header nav.gnb li ul {
display: none;
position: absolute;
width: 140px;
background: white;
}
header nav.gnb li li a {
color: #002144;
}
header nav.gnb > ul > li.active ul {
display: block;
}
header nav.gnb a {
display: block;
padding: 10px;
}
header nav.gnb a:hover {
background: #f05f5f;
color: white;
}
header nav.shortMenu ul {
float: right;
}
header nav.shortMenu li {
float: left;
}
header nav.shortMenu a {
display: block;
padding: 10px;
}
nav.lnb li a {
display: block;
padding: 10px 10px;
}
nav.lnb li a:hover {
background: #f05f5f;
}
/* footer */
footer {
clear: both;
}
footer nav.footerMenu li {
float: left;
}
footer nav.footerMenu a {
display: block;
padding: 10px;
}
footer nav.footerMenu li:first-child a {
padding-left: 0;
}
footer .familySite {
position: relative;
}
footer .familySite:hover ul {
display: block;
}
footer .familySite p {
border: 1px solid white;
}
footer .familySite p a {
display: block;
padding: 10px;
}
footer .familySite ul {
position: absolute;
width: 100%;
bottom: 38px;
display: none;
border: 1px solid white;
border-top: 0 none;
}
footer .familySite li:last-child a {
border-bottom: 0 none;
}
footer .familySite li a {
display: block;
padding: 10px;
border-top: 1px solid white;
background: #002144;
}
footer .familySite li a:hover {
background: #f05f5f;
}
footer .copyright {
clear: both;
padding: 10px 0;
font-size: 0.9em;
}
footer .copyright .logoFooter a {
display: block;
}
footer .copyright .logoFooter img {
width: 100%;
max-width: 200px;
}
footer address {
margin-bottom: 5px;
}
|
Java
|
module Supa
class Builder
COMMANDS_WITH_DEFAULT_INTERFACE = %w(attribute virtual object namespace collection append).freeze
def initialize(subject, representer:, tree:)
@subject = subject
@representer = representer
@tree = tree
end
COMMANDS_WITH_DEFAULT_INTERFACE.each do |command|
klass = Supa::Commands.const_get(command.capitalize)
define_method(command) do |name, **options, &block|
klass.new(@subject,
representer: @representer,
tree: @tree,
name: name,
options: options,
&block).represent
end
end
def attributes(*names, **options)
Supa::Commands::Attributes.new(
@subject, representer: @representer, tree: @tree, name: names, options: options
).represent
end
def to_hash
@tree.to_hash
end
def to_json
Oj.dump(to_hash, mode: :strict)
end
end
end
|
Java
|
import org.scalatest.{Matchers, FunSuite}
class SeriesTest extends FunSuite with Matchers {
test("slices of one") {
Series.slices(1, "") should be (List())
Series.slices(1, "01234") should be (List(List(0), List(1), List(2),
List(3), List(4)))
}
test("slices of two") {
Series.slices(2, "") should be (List())
Series.slices(2, "01") should be (List(List(0, 1)))
Series.slices(2, "01234") should be (List(List(0, 1), List(1, 2), List(2, 3),
List(3, 4)))
}
test("slices of three") {
Series.slices(3, "") should be (List())
Series.slices(3, "012") should be (List(List(0, 1, 2)))
Series.slices(3, "01234") should be (List(List(0, 1, 2), List(1, 2, 3),
List(2, 3, 4)))
}
}
|
Java
|
/**************************************************************************//**
* Copyright (c) 2016 by Silicon Laboratories Inc. All rights reserved.
*
* http://developer.silabs.com/legal/version/v11/Silicon_Labs_Software_License_Agreement.txt
*****************************************************************************/
#include "uart_1.h"
#if EFM8PDL_UART1_AUTO_PAGE == 1
// declare variable needed for autopage enter/exit
#define DECL_PAGE uint8_t savedPage
// enter autopage section
#define SET_PAGE(p) do \
{ \
savedPage = SFRPAGE; /* save current SFR page */ \
SFRPAGE = (p); /* set SFR page */ \
} while(0)
// exit autopage section
#define RESTORE_PAGE do \
{ \
SFRPAGE = savedPage; /* restore saved SFR page */ \
} while(0)
#else
#define DECL_PAGE
#define SET_PAGE(x)
#define RESTORE_PAGE
#endif //EFM8PDL_UART1_AUTO_PAGE
// SFR page used to access UART1 registers
#define UART1_SFR_PAGE 0x20
// Clock prescaler values for baud rate initialization
#define NUM_PRESC 8
static const uint8_t PRESC[NUM_PRESC] = {1, 4, 8, 12, 16, 24, 32, 48};
static const uint8_t PRESC_ENUM[NUM_PRESC] = {SBCON1_BPS__DIV_BY_1, SBCON1_BPS__DIV_BY_4, SBCON1_BPS__DIV_BY_8, SBCON1_BPS__DIV_BY_12,
SBCON1_BPS__DIV_BY_16, SBCON1_BPS__DIV_BY_24, SBCON1_BPS__DIV_BY_32, SBCON1_BPS__DIV_BY_48};
static void UART1_initBaudRate(uint32_t sysclk, uint32_t baudrate)
{
uint8_t i;
uint8_t min_presc;
uint16_t reload;
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
// Calculate baud rate prescaler and baud rate reload
// value to maximize precision.
// See reference manual for calculation details
min_presc = ((*((uint16_t*)(&sysclk)) >> 1) + baudrate) / baudrate; // calculate minimum prescaler necessary
for(i = 0; i < NUM_PRESC; ++i)
{
if(PRESC[i] >= min_presc) // use a prescaler that is equal or just greater than the minimum
{
reload = ((1 << 16) - (sysclk / (2 * baudrate * PRESC[i]))); // calculate reload value using prescaler
SBRL1 = reload;
SBCON1 |= (SBCON1_BREN__ENABLED | PRESC_ENUM[i]); // enable baud rate with calculated prescaler
RESTORE_PAGE;
return;
}
}
// Baud rate is too small to be match
while(1);
}
//=========================================================
// Runtime API
//=========================================================
#if (EFM8PDL_UART1_AUTO_PAGE == 1)
uint8_t UART1_getIntFlags(void)
{
uint8_t val;
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
val = SCON1 & (UART1_TX_IF | UART1_RX_IF);
RESTORE_PAGE;
return val;
}
void UART1_clearIntFlags(uint8_t flags)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
SCON1 &= ~(flags);
RESTORE_PAGE;
}
void UART1_enableTxInt(bool enable)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
UART1FCN1_TIE = enable;
RESTORE_PAGE;
}
void UART1_enableRxInt(bool enable)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
UART1FCN1_RIE = enable;
RESTORE_PAGE;
}
void UART1_initTxPolling(void)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
SCON1_TI = 1;
RESTORE_PAGE;
}
void UART1_write(uint8_t value)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
SBUF1 = value;
RESTORE_PAGE;
}
uint8_t UART1_read(void)
{
uint8_t val;
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
val = SBUF1;
RESTORE_PAGE;
return val;
}
#endif
void UART1_writeWithExtraBit(uint16_t value)
{
uint8_t shift, mask;
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
// Calculate shift and mask for data length
shift = ((SMOD1 & SMOD1_SDL__FMASK) >> SMOD1_SDL__SHIFT) + 5;
mask = 0xFF >> (8 - shift);
SCON1_TBX = (value >> shift) & 0x1;
SBUF1 = (value & mask);
RESTORE_PAGE;
}
uint16_t UART1_readWithExtraBit(void)
{
uint8_t shift, mask;
uint16_t val;
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
// Calculate shift and mask for data length
shift = ((SMOD1 & SMOD1_SDL__FMASK) >> SMOD1_SDL__SHIFT) + 5;
mask = 0xFF >> (8 - shift);
val = SCON1_RBX;
val = val << shift;
val |= (SBUF1 & mask);
RESTORE_PAGE;
return val;
}
#if (EFM8PDL_UART1_AUTO_PAGE == 1)
uint8_t UART1_getErrFlags(void)
{
uint8_t val;
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
val = SCON1 & (UART1_RXOVR_EF | UART1_PARITY_EF);
RESTORE_PAGE;
return val;
}
void UART1_clearErrFlags(uint8_t flags)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
SCON1 &= ~flags;
RESTORE_PAGE;
}
uint8_t UART1_getFifoIntFlags(void)
{
uint8_t val;
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
val = UART1FCN1 & (UART1_TFRQ_IF | UART1_RFRQ_IF);
RESTORE_PAGE;
return val;
}
#endif
void UART1_enableTxFifoInt(bool enable)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
if(enable)
{
UART1FCN0 |= UART1FCN0_TFRQE__ENABLED;
}
else
{
UART1FCN0 &= ~UART1FCN0_TFRQE__ENABLED;
}
RESTORE_PAGE;
}
void UART1_enableRxFifoInt(bool enable)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
if(enable)
{
UART1FCN0 |= UART1FCN0_RFRQE__ENABLED;
}
else
{
UART1FCN0 &= ~UART1FCN0_RFRQE__ENABLED;
}
RESTORE_PAGE;
}
#if (EFM8PDL_UART1_AUTO_PAGE == 1)
uint8_t UART1_getTxFifoCount(void)
{
uint8_t txcnt;
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
txcnt = (UART1FCT & UART1FCT_TXCNT__FMASK) >> UART1FCT_TXCNT__SHIFT;
RESTORE_PAGE;
return txcnt;
}
uint8_t UART1_getRxFifoCount(void)
{
uint8_t rxcnt;
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
rxcnt = (UART1FCT & UART1FCT_RXCNT__FMASK) >> UART1FCT_RXCNT__SHIFT;
RESTORE_PAGE;
return rxcnt;
}
#endif
bool UART1_isTxFifoFull(void){
bool txfull;
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
if(UART1FCN1 & UART1FCN1_TXNF__NOT_FULL)
{
txfull = false;
}
else
{
txfull = true;
}
RESTORE_PAGE;
return txfull;
}
void UART1_stallTxFifo(bool enable)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
if(enable)
{
UART1FCN1 |= UART1FCN1_TXHOLD__HOLD;
}
else
{
UART1FCN1 &= ~UART1FCN1_TXHOLD__HOLD;
}
RESTORE_PAGE;
}
#if (EFM8PDL_UART1_AUTO_PAGE == 1)
void UART1_flushTxFifo(void)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
UART1FCN0 |= UART1FCN0_TFLSH__FLUSH;
RESTORE_PAGE;
}
void UART1_flushRxFifo(void)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
UART1FCN0 |= UART1FCN0_RFLSH__FLUSH;
RESTORE_PAGE;
}
uint8_t UART1_getAutobaudIntFlag(void)
{
uint8_t val;
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
val = UART1LIN & UART1_AUTOBAUD_IF;
RESTORE_PAGE;
return val;
}
void UART1_clearAutobaudIntFlag(void)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
UART1LIN &= ~UART1_AUTOBAUD_IF;
RESTORE_PAGE;
}
#endif
void UART1_enableAutobaud(bool enable)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
if(enable)
{
UART1LIN |= (UART1LIN_AUTOBDE__ENABLED | UART1LIN_SYNCDIE__ENABLED);
}
else
{
UART1LIN &= ~(UART1LIN_AUTOBDE__ENABLED | UART1LIN_SYNCDIE__ENABLED);
}
RESTORE_PAGE;
}
//=========================================================
// Initialization API
//=========================================================
void UART1_init(uint32_t sysclk, uint32_t baudrate,
UART1_DataLen_t datalen, UART1_StopLen_t stoplen,
UART1_FeatureBit_t featbit, UART1_ParityType_t partype,
UART1_RxEnable_t rxen, UART1_Multiproc_t mcen)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
UART1_initBaudRate(sysclk, baudrate);
SCON1 = rxen;
SMOD1 = datalen | stoplen | featbit | partype | mcen;
RESTORE_PAGE;
}
void UART1_initWithAutobaud(UART1_BrPrescaler_t presc, UART1_StopLen_t stoplen,
UART1_FeatureBit_t featbit, UART1_ParityType_t partype,
UART1_RxEnable_t rxen, UART1_Multiproc_t mcen)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
SCON1 = rxen;
SMOD1 = SMOD1_SDL__8_BITS | stoplen | featbit | partype | mcen;
UART1LIN = (UART1LIN_AUTOBDE__ENABLED | UART1LIN_SYNCDIE__ENABLED);
SBCON1 = (SBCON1_BREN__ENABLED | presc);
RESTORE_PAGE;
}
void UART1_reset(void)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
SCON1 = SCON1_OVR__NOT_SET
| SCON1_PERR__NOT_SET
| SCON1_REN__RECEIVE_DISABLED
| SCON1_TBX__LOW
| SCON1_RBX__LOW
| SCON1_TI__NOT_SET
| SCON1_RI__NOT_SET;
SMOD1 = SMOD1_MCE__MULTI_DISABLED
| SMOD1_SPT__ODD_PARITY
| SMOD1_PE__PARITY_DISABLED
| SMOD1_SDL__8_BITS
| SMOD1_XBE__DISABLED
| SMOD1_SBL__SHORT;
SBCON1 = SBCON1_BREN__DISABLED
| SBCON1_BPS__DIV_BY_1;
UART1LIN = (UART1LIN_AUTOBDE__DISABLED | UART1LIN_SYNCDIE__DISABLED);
RESTORE_PAGE;
}
void UART1_initTxFifo(UART1_TxFifoThreshold_t txth, UART1_TxFifoInt_t txint)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
UART1FCN0 &= ~(UART1FCN0_TFRQE__BMASK
| UART1FCN0_TFLSH__BMASK
| UART1FCN0_TXTH__FMASK
| UART1FCN0_TFRQE__BMASK);
UART1FCN0 |= (txth | txint);
UART1FCN1 &= ~(UART1FCN1_TFRQ__BMASK
| UART1FCN1_TXHOLD__BMASK
| UART1FCN1_TXNF__BMASK
| UART1FCN1_TIE__BMASK);
UART1FCN1 |= (UART1FCN1_TFRQ__SET
| UART1FCN1_TXHOLD__CONTINUE
| UART1FCN1_TIE__DISABLED);
RESTORE_PAGE;
}
void UART1_initRxFifo(UART1_RxFiFoThreshold_t rxth, UART1_RxFifoTimeout_t rxto,
UART1_RxFifoInt_t rxint)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
UART1FCN0 &= ~(UART1FCN0_RFRQE__BMASK
| UART1FCN0_RFLSH__BMASK
| UART1FCN0_RXTH__FMASK
| UART1FCN0_RFRQE__BMASK);
UART1FCN0 |= (rxth | rxint);
UART1FCN1 &= ~(UART1FCN1_RFRQ__BMASK
| UART1FCN1_RXTO__FMASK
| UART1FCN1_RIE__BMASK);
UART1FCN1 |= (UART1FCN1_RFRQ__SET
| rxto
| UART1FCN1_RIE__DISABLED);
RESTORE_PAGE;
}
//=========================================================
// Buffer Access API
//=========================================================
#if EFM8PDL_UART1_USE_BUFFER == 1
SI_SEGMENT_VARIABLE(txRemaining, static uint8_t, SI_SEG_XDATA) = 0;
SI_SEGMENT_VARIABLE(rxRemaining, static uint8_t, SI_SEG_XDATA) = 0;
SI_SEGMENT_VARIABLE_SEGMENT_POINTER(txBuffer, static uint8_t, EFM8PDL_UART1_TX_BUFTYPE, SI_SEG_XDATA);
SI_SEGMENT_VARIABLE_SEGMENT_POINTER(rxBuffer, static uint8_t, EFM8PDL_UART1_RX_BUFTYPE, SI_SEG_XDATA);
SI_INTERRUPT(UART1_ISR, UART1_IRQn)
{
#if (EFM8PDL_UART1_USE_ERR_CALLBACK == 1)
uint8_t discard;
uint8_t errors;
#endif //EFM8PDL_UART1_USE_ERR_CALLBACK
// If auto-baud sync word detected to set baudrate, clear flag and disable auto-baud detection
if (UART1LIN & UART1_AUTOBAUD_IF)
{
UART1LIN &= ~(UART1_AUTOBAUD_IF | UART1LIN_AUTOBDE__ENABLED | UART1LIN_SYNCDIE__ENABLED);
}
// If rx fifo request interrupt is set and enabled
if ((UART1FCN1 & UART1_RFRQ_IF) && (UART1FCN0 & UART1FCN0_RFRQE__ENABLED))
{
// Read bytes as long as rx fifo count is not zero and there
// is room in the tx buffer
while (rxRemaining && ((UART1FCT & UART1FCT_RXCNT__FMASK) >> UART1FCT_RXCNT__SHIFT))
{
#if (EFM8PDL_UART1_USE_ERR_CALLBACK == 1)
// If parity or overrun error, clear flags, and call user
errors = SCON1 & (UART1_RXOVR_EF | UART1_PARITY_EF);
if(errors)
{
SCON1 &= ~errors;
UART1_transferErrorCb(errors);
}
// Store byte if there is no parity error a
if (errors & UART1_PARITY_EF)
{
discard = SBUF1;
}
else
#endif //EFM8PDL_UART1_USE_ERR_CALLBACK
{
*rxBuffer = SBUF1;
++rxBuffer;
--rxRemaining;
if (!rxRemaining)
{
UART1_receiveCompleteCb();
}
}
}
if(!rxRemaining)
{
// Flush Fifo if there is no room available in rx buffer
UART1FCN0 |= UART1FCN0_RFLSH__FLUSH;
}
}
// If tx fifo request interrupt is set and enabled
if ((UART1FCN1 & UART1_TFRQ_IF) && (UART1FCN0 & UART1FCN0_TFRQE__ENABLED))
{
// Write bytes as long as the tx fifo is not full and there
// is room in the tx buffer
while (txRemaining && (UART1FCN1 & UART1FCN1_TXNF__NOT_FULL))
{
SBUF1 = *txBuffer;
++txBuffer;
--txRemaining;
}
if(!txRemaining)
{
UART1_transmitCompleteCb();
}
}
}
void UART1_writeBuffer(SI_VARIABLE_SEGMENT_POINTER(buffer, uint8_t, EFM8PDL_UART1_RX_BUFTYPE),
uint8_t length)
{
// Initialize internal data
txBuffer = buffer;
txRemaining = length;
// Enable tx fifo interrupts to kick off transfer
UART1FCN0 |= UART1FCN0_TFRQE__ENABLED;
}
void UART1_readBuffer(SI_VARIABLE_SEGMENT_POINTER(buffer, uint8_t, EFM8PDL_UART1_TX_BUFTYPE),
uint8_t length)
{
// Initialize internal data
rxBuffer = buffer;
rxRemaining = length;
}
void UART1_abortTx(void)
{
txRemaining = 0;
UART1_flushTxFifo();
}
void UART1_abortRx(void)
{
rxRemaining = 0;
UART1_flushRxFifo();
}
uint8_t UART1_txBytesRemaining(void)
{
return txRemaining;
}
uint8_t UART1_rxBytesRemaining(void)
{
return rxRemaining;
}
#endif //EFM8PDL_UART1_USE_BUFFER
//=========================================================
// STDIO API
//=========================================================
#if EFM8PDL_UART1_USE_STDIO == 1
char putchar(char c){
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
while(!SCON1_TI);
SBUF1 = c;
SCON1_TI = 0;
RESTORE_PAGE;
return c;
}
char _getkey(void){
char val;
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
while(!SCON1_RI);
SCON1_RI = 0;
val = SBUF1;
RESTORE_PAGE;
return val;
}
void UART1_initStdio(uint32_t sysclk, uint32_t baudrate)
{
DECL_PAGE;
SET_PAGE(UART1_SFR_PAGE);
SCON1 |= SCON1_REN__RECEIVE_ENABLED | SCON1_TI__SET;
SMOD1 |= SMOD1_SDL__8_BITS;
UART1_initBaudRate(sysclk, baudrate);
RESTORE_PAGE;
}
#endif //EFM8PDL_UART0_USE_STDIO
|
Java
|
define(["widgetjs/widgetjs", "lodash", "jquery", "prettify", "code", "bootstrap"], function(widgetjs, lodash, jQuery, prettify, code) {
var examples = {};
examples.modals = code({
group: "Modals",
label: "Modals",
links: ["http://getbootstrap.com/javascript/#modals"],
example : function(html) {
// Modal
html.div({"class": "clearfix bs-example-modal"},
html.div({ klass: "modal"},
html.div({ klass: "modal-dialog"},
html.div({ klass: "modal-content"},
html.div({ klass: "modal-header"},
html.button({ type: "button", klass: "close", "data-dismiss": "modal", "aria-hidden": "true"},
"×"
),
html.h4({ klass: "modal-title"},
"Modal title"
)
),
html.div({ klass: "modal-body"},
html.p(
"One fine body…"
)
),
html.div({ klass: "modal-footer"},
html.button({ type: "button", klass: "btn btn-default", "data-dismiss": "modal"},
"Close"
),
html.button({ type: "button", klass: "btn btn-primary"},
"Save changes"
)
)
)
)
)
);
}
});
examples.modalsDemo = code({
group: "Modals",
label: "Live Demo",
links: ["http://getbootstrap.com/javascript/#modals"],
example : function(html) {
// Modal
html.div({ id: "myModal", klass: "modal fade"},
html.div({ klass: "modal-dialog"},
html.div({ klass: "modal-content"},
html.div({ klass: "modal-header"},
html.button({ type: "button", klass: "close", "data-dismiss": "modal", "aria-hidden": "true"},
"×"
),
html.h4({ klass: "modal-title"},
"Modal title"
)
),
html.div({ klass: "modal-body"},
html.p(
"One fine body…"
)
),
html.div({ klass: "modal-footer"},
html.button({ type: "button", klass: "btn btn-default", "data-dismiss": "modal"},
"Close"
),
html.button({ type: "button", klass: "btn btn-primary"},
"Save changes"
)
)
)
)
);
html.button({ klass: "btn btn-primary btn-lg", "data-toggle": "modal", "data-target": "#myModal"}, "Show modal");
}
});
examples.toolTips = code({
group: "Tooltips",
label: "Live Demo",
links: ["http://getbootstrap.com/javascript/#tooltips"],
example : function(html) {
// TOOLTIPS
html.div({ klass: "tooltip-demo"},
html.div({ klass: "bs-example-tooltips"},
html.button({ type: "button", klass: "btn btn-default", "data-toggle": "tooltip", "data-placement": "left", title: "", "data-original-title": "Tooltip on left"},
"Tooltip on left"
),
html.button({ type: "button", klass: "btn btn-default", "data-toggle": "tooltip", "data-placement": "top", title: "", "data-original-title": "Tooltip on top"},
"Tooltip on top"
),
html.button({ type: "button", klass: "btn btn-default", "data-toggle": "tooltip", "data-placement": "bottom", title: "", "data-original-title": "Tooltip on bottom"},
"Tooltip on bottom"
),
html.button({ type: "button", klass: "btn btn-default", "data-toggle": "tooltip", "data-placement": "right", title: "", "data-original-title": "Tooltip on right"},
"Tooltip on right"
)
)
);
jQuery(".bs-example-tooltips").tooltip();
}
});
examples.popovers = code({
group: "Popovers",
label: "Popovers",
links: ["http://getbootstrap.com/javascript/#popovers"],
example : function(html) {
// Popovers
html.div({ klass: "bs-example-popovers"},
html.button({ type: "button", klass: "btn btn-default", "data-container": "body", "data-toggle": "popover", "data-placement": "left", "data-content": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus.", "data-original-title": "", title: ""},
"Left"
),
html.button({ type: "button", klass: "btn btn-default", "data-container": "body", "data-toggle": "popover", "data-placement": "top", "data-content": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus.", "data-original-title": "", title: ""},
"Top"
),
html.button({ type: "button", klass: "btn btn-default", "data-container": "body", "data-toggle": "popover", "data-placement": "bottom", "data-content": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus.", "data-original-title": "", title: ""},
"Bottom"
),
html.button({ type: "button", klass: "btn btn-default", "data-container": "body", "data-toggle": "popover", "data-placement": "right", "data-content": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus.", "data-original-title": "", title: ""},
"Right"
)
);
jQuery(".bs-example-popovers button").popover();
}
});
examples.buttonsCheckbox = code({
group: "Buttons",
label: "Checkbox",
links: ["http://getbootstrap.com/javascript/#buttons"],
example : function(html) {
html.div({ style: "padding-bottom: 24px;"},
html.div({ klass: "btn-group", "data-toggle": "buttons"},
html.label({ klass: "btn btn-primary"},
html.input({ type: "checkbox"}),
"Option 1"
),
html.label({ klass: "btn btn-primary"},
html.input({ type: "checkbox"}),
"Option 2"
),
html.label({ klass: "btn btn-primary"},
html.input({ type: "checkbox"}),
"Option 3"
)
)
);
}
});
examples.buttonsRadio= code({
group: "Buttons",
label: "Radio",
links: ["http://getbootstrap.com/javascript/#buttons"],
example : function(html) {
html.div({ style: "padding-bottom: 24px;"},
html.div({ klass: "btn-group", "data-toggle": "buttons"},
html.label({ klass: "btn btn-primary"},
html.input({ type: "radio"}),
"Option 1"
),
html.label({ klass: "btn btn-primary"},
html.input({ type: "radio"}),
"Option 2"
),
html.label({ klass: "btn btn-primary"},
html.input({ type: "radio"}),
"Option 3"
)
)
);
}
});
examples.collapse = code({
group: "Collapse",
label: "Collapse",
links: ["http://getbootstrap.com/javascript/#collapse"],
example : function(html) {
html.div({ klass: "panel-group", id: "accordion"},
html.div({ klass: "panel panel-default"},
html.div({ klass: "panel-heading"},
html.h4({ klass: "panel-title"},
html.a({ "data-toggle": "collapse", "data-parent": "#accordion", href: "#collapseOne"},
"Heading #1"
)
)
),
html.div({ id: "collapseOne", klass: "panel-collapse collapse in"},
html.div({ klass: "panel-body"},
"Content"
)
)
),
html.div({ klass: "panel panel-default"},
html.div({ klass: "panel-heading"},
html.h4({ klass: "panel-title"},
html.a({ "data-toggle": "collapse", "data-parent": "#accordion", href: "#collapseTwo"},
"Heading #2"
)
)
),
html.div({ id: "collapseTwo", klass: "panel-collapse collapse"},
html.div({ klass: "panel-body"},
"Content"
)
)
),
html.div({ klass: "panel panel-default"},
html.div({ klass: "panel-heading"},
html.h4({ klass: "panel-title"},
html.a({ "data-toggle": "collapse", "data-parent": "#accordion", href: "#collapseThree"},
"Heading #2"
)
)
),
html.div({ id: "collapseThree", klass: "panel-collapse collapse"},
html.div({ klass: "panel-body"},
"Content"
)
)
)
);
}
});
return examples;
});
|
Java
|
class AddCorrectAnswerToQuestions < ActiveRecord::Migration
def change
add_column :questions, :correct_answer, :integer, :default => nil
end
end
|
Java
|
module.exports = require('./lib/dustjs-browserify');
|
Java
|
namespace GE.WebUI.ViewModels
{
public sealed class VMGameMenuEmptyGame
{
public string IconPath { get; set; }
public string GoodImagePath { get; set; }
public string BadImagePath { get; set; }
}
}
|
Java
|
version https://git-lfs.github.com/spec/v1
oid sha256:94e212e6fc0c837cd9fff7fca8feff0187a0a22a97c7bd4c6d8f05c5cc358519
size 3077
|
Java
|
/* orconfig.h. Generated from orconfig.h.in by configure. */
/* orconfig.h.in. Generated from configure.ac by autoheader. */
#include <openssl/opensslv.h>
/* Define if building universal (internal helper macro) */
/* #undef AC_APPLE_UNIVERSAL_BUILD */
/* tor's configuration directory */
#define CONFDIR "/usr/local/etc/tor"
/* Defined if we're not going to look for a torrc in SYSCONF */
/* #undef DISABLE_SYSTEM_TORRC */
/* shared data dir */
#define SHARE_DATADIR "/usr/share"
/* home tor folder */
#define LOCALSTATEDIR ""
/* Defined if we have a curve25519 implementation */
#define CURVE25519_ENABLED 1
/* Enable dmalloc's malloc function check */
/* #undef DMALLOC_FUNC_CHECK */
/* Define to 1 iff memset(0) sets doubles to 0.0 */
#define DOUBLE_0_REP_IS_ZERO_BYTES 1
/* Defined if we try to use freelists for buffer RAM chunks */
#define ENABLE_BUF_FREELISTS 1
/* Defined if we default to host local appdata paths on Windows */
/* #undef ENABLE_LOCAL_APPDATA */
/* Defined if we will try to use multithreading */
#define ENABLE_THREADS 1
/* Define if enum is always signed */
/* #undef ENUM_VALS_ARE_SIGNED */
/* Define to nothing if C supports flexible array members, and to 1 if it does
not. That way, with a declaration like `struct s { int n; double
d[FLEXIBLE_ARRAY_MEMBER]; };', the struct hack can be used with pre-C99
compilers. When computing the size of such an object, don't use 'sizeof
(struct s)' as it overestimates the size. Use 'offsetof (struct s, d)'
instead. Don't use 'offsetof (struct s, d[0])', as this doesn't work with
MSVC and with C++ compilers. */
#define FLEXIBLE_ARRAY_MEMBER /**/
/* Define to 1 if you have the `accept4' function. */
/* #undef HAVE_ACCEPT4 */
/* Define to 1 if you have the <arpa/inet.h> header file. */
#define HAVE_ARPA_INET_H 1
/* Define to 1 if you have the <assert.h> header file. */
#define HAVE_ASSERT_H 1
/* Define to 1 if you have the `backtrace' function. */
#define HAVE_BACKTRACE 1
/* Define to 1 if you have the `backtrace_symbols_fd' function. */
#define HAVE_BACKTRACE_SYMBOLS_FD 1
/* Define to 1 if you have the `cap_set_proc' function. */
/* #undef HAVE_CAP_SET_PROC */
/* Defined if the requested minimum BOOST version is satisfied */
#define HAVE_BOOST 1
/* Define to 1 if you have <boost/filesystem/path.hpp> */
#define HAVE_BOOST_FILESYSTEM_PATH_HPP 1
/* Define to 1 if you have <boost/system/error_code.hpp> */
#define HAVE_BOOST_SYSTEM_ERROR_CODE_HPP 1
/* Define to 1 if you have the `clock_gettime' function. */
/* #undef HAVE_CLOCK_GETTIME */
/* Define to 1 if you have the <crt_externs.h> header file. */
#define HAVE_CRT_EXTERNS_H 1
/* Define to 1 if you have the <crypto_scalarmult_curve25519.h> header file.
*/
/* #undef HAVE_CRYPTO_SCALARMULT_CURVE25519_H */
/* Define to 1 if you have the <cygwin/signal.h> header file. */
/* #undef HAVE_CYGWIN_SIGNAL_H */
/* Define to 1 if you have the declaration of `mlockall', and to 0 if you
don't. */
#define HAVE_DECL_MLOCKALL 1
/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 1
/* Define to 1 if you have the declaration of `SecureZeroMemory', and to 0 if
you don't. */
/* #undef HAVE_DECL_SECUREZEROMEMORY */
/* Define to 1 if you have the declaration of `_getwch', and to 0 if you
don't. */
/* #undef HAVE_DECL__GETWCH */
/* Define to 1 if you have the <dmalloc.h> header file. */
/* #undef HAVE_DMALLOC_H */
/* Define to 1 if you have the `dmalloc_strdup' function. */
/* #undef HAVE_DMALLOC_STRDUP */
/* Define to 1 if you have the `dmalloc_strndup' function. */
/* #undef HAVE_DMALLOC_STRNDUP */
/* Define to 1 if you have the <errno.h> header file. */
#define HAVE_ERRNO_H 1
/* Define to 1 if you have the `evdns_set_outgoing_bind_address' function. */
/* #undef HAVE_EVDNS_SET_OUTGOING_BIND_ADDRESS */
/* Define to 1 if you have the <event2/bufferevent_ssl.h> header file. */
#define HAVE_EVENT2_BUFFEREVENT_SSL_H 1
/* Define to 1 if you have the <event2/dns.h> header file. */
#define HAVE_EVENT2_DNS_H 1
/* Define to 1 if you have the <event2/event.h> header file. */
#define HAVE_EVENT2_EVENT_H 1
/* Define to 1 if you have the `eventfd' function. */
/* #undef HAVE_EVENTFD */
/* Define to 1 if you have the `event_base_loopexit' function. */
#define HAVE_EVENT_BASE_LOOPEXIT 1
/* Define to 1 if you have the `event_get_method' function. */
#define HAVE_EVENT_GET_METHOD 1
/* Define to 1 if you have the `event_get_version' function. */
#define HAVE_EVENT_GET_VERSION 1
/* Define to 1 if you have the `event_get_version_number' function. */
#define HAVE_EVENT_GET_VERSION_NUMBER 1
/* Define to 1 if you have the `EVP_PBE_scrypt' function. */
/* #undef HAVE_EVP_PBE_SCRYPT */
/* Define to 1 if you have the `evutil_secure_rng_init' function. */
#define HAVE_EVUTIL_SECURE_RNG_INIT 1
/* Define to 1 if you have the `evutil_secure_rng_set_urandom_device_file'
function. */
/* #undef HAVE_EVUTIL_SECURE_RNG_SET_URANDOM_DEVICE_FILE */
/* Define to 1 if you have the <execinfo.h> header file. */
#define HAVE_EXECINFO_H 1
/* Define to 1 if you have the `explicit_bzero' function. */
/* #undef HAVE_EXPLICIT_BZERO */
/* Defined if we have extern char **environ already declared */
/* #undef HAVE_EXTERN_ENVIRON_DECLARED */
/* Define to 1 if you have the <fcntl.h> header file. */
#define HAVE_FCNTL_H 1
/* Define to 1 if you have the `flock' function. */
#define HAVE_FLOCK 1
/* Define to 1 if you have the `ftime' function. */
#define HAVE_FTIME 1
/* Define to 1 if you have the `getaddrinfo' function. */
#define HAVE_GETADDRINFO 1
/* Define to 1 if you have the `getentropy' function. */
/* #undef HAVE_GETENTROPY */
/* Define this if you have any gethostbyname_r() */
/* #undef HAVE_GETHOSTBYNAME_R */
/* Define this if gethostbyname_r takes 3 arguments */
/* #undef HAVE_GETHOSTBYNAME_R_3_ARG */
/* Define this if gethostbyname_r takes 5 arguments */
/* #undef HAVE_GETHOSTBYNAME_R_5_ARG */
/* Define this if gethostbyname_r takes 6 arguments */
/* #undef HAVE_GETHOSTBYNAME_R_6_ARG */
/* Define to 1 if you have the `getifaddrs' function. */
#define HAVE_GETIFADDRS 1
/* Define to 1 if you have the `getpass' function. */
#define HAVE_GETPASS 1
/* Define to 1 if you have the `getresgid' function. */
/* #undef HAVE_GETRESGID */
/* Define to 1 if you have the `getresuid' function. */
/* #undef HAVE_GETRESUID */
/* Define to 1 if you have the `getrlimit' function. */
#define HAVE_GETRLIMIT 1
/* Define to 1 if you have the `gettimeofday' function. */
#define HAVE_GETTIMEOFDAY 1
/* Define to 1 if you have the `gmtime_r' function. */
#define HAVE_GMTIME_R 1
/* Define to 1 if you have the <grp.h> header file. */
#define HAVE_GRP_H 1
/* Define to 1 if you have the `htonll' function. */
/* #undef HAVE_HTONLL */
/* Define to 1 if you have the <ifaddrs.h> header file. */
#define HAVE_IFADDRS_H 1
/* Define to 1 if you have the `inet_aton' function. */
#define HAVE_INET_ATON 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define to 1 if you have the `ioctl' function. */
#define HAVE_IOCTL 1
/* Define to 1 if you have the `issetugid' function. */
#define HAVE_ISSETUGID 1
/* Define to 1 if you have the `cap' library (-lcap). */
/* #undef HAVE_LIBCAP */
/* Define to 1 if you have the <libscrypt.h> header file. */
/* #undef HAVE_LIBSCRYPT_H */
/* Define to 1 if you have the `libscrypt_scrypt' function. */
/* #undef HAVE_LIBSCRYPT_SCRYPT */
/* Define to 1 if you have the <limits.h> header file. */
#define HAVE_LIMITS_H 1
/* Define to 1 if you have the <linux/if.h> header file. */
/* #undef HAVE_LINUX_IF_H */
/* Define to 1 if you have the <linux/netfilter_ipv4.h> header file. */
/* #undef HAVE_LINUX_NETFILTER_IPV4_H */
/* Define to 1 if you have the <linux/netfilter_ipv6/ip6_tables.h> header
file. */
/* #undef HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H */
/* Define to 1 if you have the <linux/types.h> header file. */
/* #undef HAVE_LINUX_TYPES_H */
/* Define to 1 if you have the `llround' function. */
#define HAVE_LLROUND 1
/* Define to 1 if you have the `localtime_r' function. */
#define HAVE_LOCALTIME_R 1
/* Define to 1 if you have the `lround' function. */
#define HAVE_LROUND 1
/* Define to 1 if you have the <machine/limits.h> header file. */
#define HAVE_MACHINE_LIMITS_H 1
/* Defined if the compiler supports __FUNCTION__ */
#define HAVE_MACRO__FUNCTION__ 1
/* Defined if the compiler supports __FUNC__ */
/* #undef HAVE_MACRO__FUNC__ */
/* Defined if the compiler supports __func__ */
#define HAVE_MACRO__func__ 1
/* Define to 1 if you have the `mallinfo' function. */
/* #undef HAVE_MALLINFO */
/* Define to 1 if you have the <malloc.h> header file. */
/* #undef HAVE_MALLOC_H */
/* Define to 1 if you have the <malloc/malloc.h> header file. */
#define HAVE_MALLOC_MALLOC_H 1
/* Define to 1 if you have the <malloc_np.h> header file. */
/* #undef HAVE_MALLOC_NP_H */
/* Define to 1 if you have the `memmem' function. */
#define HAVE_MEMMEM 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the `memset_s' function. */
/* #undef HAVE_MEMSET_S */
/* Define to 1 if you have the `mlockall' function. */
#define HAVE_MLOCKALL 1
/* Define to 1 if you have the <nacl/crypto_scalarmult_curve25519.h> header
file. */
/* #undef HAVE_NACL_CRYPTO_SCALARMULT_CURVE25519_H */
/* Define to 1 if you have the <netdb.h> header file. */
#define HAVE_NETDB_H 1
/* Define to 1 if you have the <netinet/in6.h> header file. */
/* #undef HAVE_NETINET_IN6_H */
/* Define to 1 if you have the <netinet/in.h> header file. */
#define HAVE_NETINET_IN_H 1
/* Define to 1 if you have the <net/if.h> header file. */
#define HAVE_NET_IF_H 1
/* Define to 1 if you have the <net/pfvar.h> header file. */
/* #undef HAVE_NET_PFVAR_H */
/* Define to 1 if you have the `pipe' function. */
#define HAVE_PIPE 1
/* Define to 1 if you have the `pipe2' function. */
/* #undef HAVE_PIPE2 */
/* Define to 1 if you have the `prctl' function. */
/* #undef HAVE_PRCTL */
/* Define to 1 if you have the `pthread_condattr_setclock' function. */
/* #undef HAVE_PTHREAD_CONDATTR_SETCLOCK */
/* Define to 1 if you have the `pthread_create' function. */
#define HAVE_PTHREAD_CREATE 1
/* Define to 1 if you have the <pthread.h> header file. */
#define HAVE_PTHREAD_H 1
/* Define to 1 if you have the <pwd.h> header file. */
#define HAVE_PWD_H 1
/* Define to 1 if you have the `readpassphrase' function. */
#define HAVE_READPASSPHRASE 1
/* Define to 1 if you have the <readpassphrase.h> header file. */
#define HAVE_READPASSPHRASE_H 1
/* Define to 1 if you have the `rint' function. */
#define HAVE_RINT 1
/* Define to 1 if the system has the type `rlim_t'. */
#define HAVE_RLIM_T 1
/* Define to 1 if you have the `RtlSecureZeroMemory' function. */
/* #undef HAVE_RTLSECUREZEROMEMORY */
/* Define to 1 if the system has the type `sa_family_t'. */
#define HAVE_SA_FAMILY_T 1
/* Define to 1 if you have the <seccomp.h> header file. */
/* #undef HAVE_SECCOMP_H */
/* Define to 1 if you have the `SecureZeroMemory' function. */
/* #undef HAVE_SECUREZEROMEMORY */
/* Define to 1 if you have the `sigaction' function. */
#define HAVE_SIGACTION 1
/* Define to 1 if you have the <signal.h> header file. */
#define HAVE_SIGNAL_H 1
/* Define to 1 if you have the `socketpair' function. */
#define HAVE_SOCKETPAIR 1
/* Define to 1 if the system has the type `ssize_t'. */
#define HAVE_SSIZE_T 1
/* Define to 1 if you have the `SSL_CIPHER_find' function. */
/* #undef HAVE_SSL_CIPHER_FIND */
/* Define to 1 if you have the `SSL_get_client_ciphers' function. */
#define HAVE_SSL_GET_CLIENT_CIPHERS 1
/* Define to 1 if you have the `SSL_get_client_random' function. */
#define HAVE_SSL_GET_CLIENT_RANDOM 1
/* Define to 1 if you have the `SSL_get_server_random' function. */
#define HAVE_SSL_GET_SERVER_RANDOM 1
/* Define to 1 if you have the `SSL_SESSION_get_master_key' function. */
#define HAVE_SSL_SESSION_GET_MASTER_KEY 1
/* Define to 1 if you have the `statvfs' function. */
#define HAVE_STATVFS 1
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the `strlcat' function. */
#define HAVE_STRLCAT 1
/* Define to 1 if you have the `strlcpy' function. */
#define HAVE_STRLCPY 1
/* Define to 1 if you have the `strnlen' function. */
#define HAVE_STRNLEN 1
/* Define to 1 if you have the `strptime' function. */
#define HAVE_STRPTIME 1
/* Define to 1 if you have the `strtok_r' function. */
#define HAVE_STRTOK_R 1
/* Define to 1 if you have the `strtoull' function. */
#define HAVE_STRTOULL 1
/* Define to 1 if `min_heap_idx' is a member of `struct event'. */
/* #undef HAVE_STRUCT_EVENT_MIN_HEAP_IDX */
/* Define to 1 if the system has the type `struct in6_addr'. */
#define HAVE_STRUCT_IN6_ADDR 1
/* Define to 1 if `s6_addr16' is a member of `struct in6_addr'. */
/* #undef HAVE_STRUCT_IN6_ADDR_S6_ADDR16 */
/* Define to 1 if `s6_addr32' is a member of `struct in6_addr'. */
/* #undef HAVE_STRUCT_IN6_ADDR_S6_ADDR32 */
/* Define to 1 if the system has the type `struct sockaddr_in6'. */
#define HAVE_STRUCT_SOCKADDR_IN6 1
/* Define to 1 if `sin6_len' is a member of `struct sockaddr_in6'. */
#define HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN 1
/* Define to 1 if `sin_len' is a member of `struct sockaddr_in'. */
#define HAVE_STRUCT_SOCKADDR_IN_SIN_LEN 1
/* Define to 1 if `get_cipher_by_char' is a member of `struct ssl_method_st'.
*/
/* #undef HAVE_STRUCT_SSL_METHOD_ST_GET_CIPHER_BY_CHAR */
/* Define to 1 if `tv_sec' is a member of `struct timeval'. */
#define HAVE_STRUCT_TIMEVAL_TV_SEC 1
/* Define to 1 if you have the `sysconf' function. */
#define HAVE_SYSCONF 1
/* Define to 1 if you have the `sysctl' function. */
#define HAVE_SYSCTL 1
/* Define to 1 if you have the <syslog.h> header file. */
#define HAVE_SYSLOG_H 1
/* Have systemd */
/* #undef HAVE_SYSTEMD */
/* Have systemd v209 or more */
/* #undef HAVE_SYSTEMD_209 */
/* Define to 1 if you have the <sys/capability.h> header file. */
/* #undef HAVE_SYS_CAPABILITY_H */
/* Define to 1 if you have the <sys/eventfd.h> header file. */
/* #undef HAVE_SYS_EVENTFD_H */
/* Define to 1 if you have the <sys/fcntl.h> header file. */
#define HAVE_SYS_FCNTL_H 1
/* Define to 1 if you have the <sys/file.h> header file. */
#define HAVE_SYS_FILE_H 1
/* Define to 1 if you have the <sys/ioctl.h> header file. */
#define HAVE_SYS_IOCTL_H 1
/* Define to 1 if you have the <sys/limits.h> header file. */
/* #undef HAVE_SYS_LIMITS_H */
/* Define to 1 if you have the <sys/mman.h> header file. */
#define HAVE_SYS_MMAN_H 1
/* Define to 1 if you have the <sys/param.h> header file. */
#define HAVE_SYS_PARAM_H 1
/* Define to 1 if you have the <sys/prctl.h> header file. */
/* #undef HAVE_SYS_PRCTL_H */
/* Define to 1 if you have the <sys/resource.h> header file. */
#define HAVE_SYS_RESOURCE_H 1
/* Define to 1 if you have the <sys/select.h> header file. */
#define HAVE_SYS_SELECT_H 1
/* Define to 1 if you have the <sys/socket.h> header file. */
#define HAVE_SYS_SOCKET_H 1
/* Define to 1 if you have the <sys/statvfs.h> header file. */
#define HAVE_SYS_STATVFS_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/syscall.h> header file. */
#define HAVE_SYS_SYSCALL_H 1
/* Define to 1 if you have the <sys/sysctl.h> header file. */
#define HAVE_SYS_SYSCTL_H 1
/* Define to 1 if you have the <sys/syslimits.h> header file. */
#define HAVE_SYS_SYSLIMITS_H 1
/* Define to 1 if you have the <sys/time.h> header file. */
#define HAVE_SYS_TIME_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <sys/ucontext.h> header file. */
#define HAVE_SYS_UCONTEXT_H 1
/* Define to 1 if you have the <sys/un.h> header file. */
#define HAVE_SYS_UN_H 1
/* Define to 1 if you have the <sys/utime.h> header file. */
/* #undef HAVE_SYS_UTIME_H */
/* Define to 1 if you have the <sys/wait.h> header file. */
#define HAVE_SYS_WAIT_H 1
/* Define to 1 if you have the <time.h> header file. */
#define HAVE_TIME_H 1
/* Define to 1 if you have the `timingsafe_memcmp' function. */
/* #undef HAVE_TIMINGSAFE_MEMCMP */
/* Define to 1 if you have the `TLS_method' function. */
/* #undef HAVE_TLS_METHOD */
/* Define to 1 if you have the <ucontext.h> header file. */
/* #undef HAVE_UCONTEXT_H */
/* Define to 1 if the system has the type `uint'. */
#define HAVE_UINT 1
/* Define to 1 if you have the `uname' function. */
#define HAVE_UNAME 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to 1 if you have the `usleep' function. */
#define HAVE_USLEEP 1
/* Define to 1 if you have the <utime.h> header file. */
#define HAVE_UTIME_H 1
/* Define to 1 if the system has the type `u_char'. */
#define HAVE_U_CHAR 1
/* Define to 1 if you have the `vasprintf' function. */
#define HAVE_VASPRINTF 1
/* Define to 1 if you have the `_NSGetEnviron' function. */
#define HAVE__NSGETENVIRON 1
/* Define to 1 if you have the `_vscprintf' function. */
/* #undef HAVE__VSCPRINTF */
/* Defined if we want to keep track of how much of each kind of resource we
download. */
/* #undef INSTRUMENT_DOWNLOADS */
/* name of the syslog facility */
#define LOGFACILITY LOG_DAEMON
/* Define to the sub-directory in which libtool stores uninstalled libraries.
*/
#define LT_OBJDIR ".libs/"
/* Define to 1 iff malloc(0) returns a pointer */
#define MALLOC_ZERO_WORKS 1
/* Define to 1 if we are building with UPnP. */
/* #undef MINIUPNPC */
/* libminiupnpc version 1.5 found */
/* #undef MINIUPNPC15 */
/* Define to 1 if we are building with nat-pmp. */
/* #undef NAT_PMP */
/* Define to 1 iff memset(0) sets pointers to NULL */
#define NULL_REP_IS_ZERO_BYTES 1
/* "Define to handle pf on OpenBSD properly" */
/* #undef OPENBSD */
/* Name of package */
#define PACKAGE "tor"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT ""
/* Define to the full name of this package. */
#define PACKAGE_NAME "tor"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "tor 0.3.0.9"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "tor"
/* Define to the home page for this package. */
#define PACKAGE_URL ""
/* Define to the version of this package. */
#define PACKAGE_VERSION "0.3.0.9"
/* How to access the PC from a struct ucontext */
#define PC_FROM_UCONTEXT uc_mcontext->__ss.__rip
/* Define to 1 iff right-shifting a negative value performs sign-extension */
#define RSHIFT_DOES_SIGN_EXTEND 1
/* The size of `cell_t', as computed by sizeof. */
#define SIZEOF_CELL_T 0
/* The size of `char', as computed by sizeof. */
#define SIZEOF_CHAR 1
/* The size of `int', as computed by sizeof. */
#define SIZEOF_INT 4
/* The size of `int16_t', as computed by sizeof. */
#define SIZEOF_INT16_T 2
/* The size of `int32_t', as computed by sizeof. */
#define SIZEOF_INT32_T 4
/* The size of `int64_t', as computed by sizeof. */
#define SIZEOF_INT64_T 8
/* The size of `int8_t', as computed by sizeof. */
#define SIZEOF_INT8_T 1
/* The size of `intptr_t', as computed by sizeof. */
#define SIZEOF_INTPTR_T 8
/* The size of `long', as computed by sizeof. */
#define SIZEOF_LONG 8
/* The size of `long long', as computed by sizeof. */
#define SIZEOF_LONG_LONG 8
/* The size of `pid_t', as computed by sizeof. */
#define SIZEOF_PID_T 4
/* The size of `short', as computed by sizeof. */
#define SIZEOF_SHORT 2
/* The size of `size_t', as computed by sizeof. */
#define SIZEOF_SIZE_T 8
/* The size of `socklen_t', as computed by sizeof. */
#define SIZEOF_SOCKLEN_T 4
/* The size of `time_t', as computed by sizeof. */
#define SIZEOF_TIME_T 8
/* The size of `uint16_t', as computed by sizeof. */
#define SIZEOF_UINT16_T 2
/* The size of `uint32_t', as computed by sizeof. */
#define SIZEOF_UINT32_T 4
/* The size of `uint64_t', as computed by sizeof. */
#define SIZEOF_UINT64_T 8
/* The size of `uint8_t', as computed by sizeof. */
#define SIZEOF_UINT8_T 1
/* The size of `uintptr_t', as computed by sizeof. */
#define SIZEOF_UINTPTR_T 8
/* The size of `void *', as computed by sizeof. */
#define SIZEOF_VOID_P 8
/* The size of `__int64', as computed by sizeof. */
#define SIZEOF___INT64 0
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Define if time_t is signed */
#define TIME_T_IS_SIGNED 1
/* Defined if we're going to use Libevent's buffered IO API */
/* #undef USE_BUFFEREVENTS */
/* Defined if we should use an internal curve25519_donna{,_c64} implementation
*/
#define USE_CURVE25519_DONNA 1
/* Defined if we should use a curve25519 from nacl */
/* #undef USE_CURVE25519_NACL */
/* Debug memory allocation library */
/* #undef USE_DMALLOC */
/* "Define to enable transparent proxy support" */
/* #undef USE_TRANSPARENT */
/* Define to 1 iff we represent negative integers with two's complement */
#define USING_TWOS_COMPLEMENT 1
/* Version number of package */
#define VERSION "0.3.0.9"
/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
significant byte first (like Motorola and SPARC, unlike Intel). */
#if defined AC_APPLE_UNIVERSAL_BUILD
# if defined __BIG_ENDIAN__
# define WORDS_BIGENDIAN 1
# endif
#else
# ifndef WORDS_BIGENDIAN
/* # undef WORDS_BIGENDIAN */
# endif
#endif
/* Enable large inode numbers on Mac OS X 10.5. */
#ifndef _DARWIN_USE_64_BIT_INODE
# define _DARWIN_USE_64_BIT_INODE 1
#endif
/* Number of bits in a file offset, on hosts where this is settable. */
/* #undef _FILE_OFFSET_BITS */
/* Define for large files, on AIX-style hosts. */
/* #undef _LARGE_FILES */
/* Define on some platforms to activate x_r() functions in time.h */
/* #undef _REENTRANT */
/* Define to `unsigned short' if <sys/types.h> does not define. */
/* #undef u_int16_t */
/* Define to `unsigned long' if <sys/types.h> does not define. */
/* #undef u_int32_t */
/* Define to `unsigned long long' if <sys/types.h> does not define. */
/* #undef u_int64_t */
/* Define to `unsigned char' if <sys/types.h> does not define. */
/* #undef u_int8_t */
|
Java
|
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization
//
// 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.
//
#ifndef APPLESEED_RENDERER_MODELING_TEXTURE_TEXTURE_H
#define APPLESEED_RENDERER_MODELING_TEXTURE_TEXTURE_H
// appleseed.renderer headers.
#include "renderer/modeling/entity/entity.h"
// appleseed.foundation headers.
#include "foundation/image/colorspace.h"
#include "foundation/utility/uid.h"
// appleseed.main headers.
#include "main/dllsymbol.h"
// Standard headers.
#include <cstddef>
// Forward declarations.
namespace foundation { class CanvasProperties; }
namespace foundation { class Tile; }
namespace renderer { class ParamArray; }
namespace renderer
{
//
// The base class for textures.
//
class APPLESEED_DLLSYMBOL Texture
: public Entity
{
public:
// Return the unique ID of this class of entities.
static foundation::UniqueID get_class_uid();
// Constructor.
Texture(
const char* name,
const ParamArray& params);
// Return a string identifying the model of this entity.
virtual const char* get_model() const = 0;
// Return the color space of the texture.
virtual foundation::ColorSpace get_color_space() const = 0;
// Access canvas properties.
virtual const foundation::CanvasProperties& properties() = 0;
// Load a given tile.
virtual foundation::Tile* load_tile(
const size_t tile_x,
const size_t tile_y) = 0;
// Unload a given tile.
virtual void unload_tile(
const size_t tile_x,
const size_t tile_y,
const foundation::Tile* tile) = 0;
};
} // namespace renderer
#endif // !APPLESEED_RENDERER_MODELING_TEXTURE_TEXTURE_H
|
Java
|
# -----------------------------------------------------------------------------
# Copyright (c) 2014 GarageGames, LLC
#
# 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.
# -----------------------------------------------------------------------------
project("Torque3DEngine")
if( CMAKE_CXX_SIZEOF_DATA_PTR EQUAL 8 )
set( TORQUE_CPU_X64 ON )
elseif( CMAKE_CXX_SIZEOF_DATA_PTR EQUAL 4 )
set( TORQUE_CPU_X32 ON )
endif()
if(NOT TORQUE_TEMPLATE)
set(TORQUE_TEMPLATE "BaseGame" CACHE STRING "the template to use")
endif()
if(NOT TORQUE_APP_DIR)
set(TORQUE_APP_DIR "${CMAKE_SOURCE_DIR}/My Projects/${TORQUE_APP_NAME}" CACHE STRING "final installation location")
endif()
if(NOT projectOutDir)
set(projectOutDir "${TORQUE_APP_DIR}/game")
endif()
if(NOT projectSrcDir)
set(projectSrcDir "${TORQUE_APP_DIR}/source")
endif()
set(libDir "${CMAKE_SOURCE_DIR}/Engine/lib")
set(srcDir "${CMAKE_SOURCE_DIR}/Engine/source")
set(cmakeDir "${CMAKE_SOURCE_DIR}/Tools/CMake")
# hide some things
mark_as_advanced(CMAKE_INSTALL_PREFIX)
mark_as_advanced(CMAKE_CONFIGURATION_TYPES)
# output folders
#set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${projectOutDir}/game)
#set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${projectOutDir}/game)
#set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${projectOutDir}/game)
###############################################################################
### Source File Handling
###############################################################################
# finds and adds sources files in a folder
macro(addPath dir)
set(tmp_files "")
set(glob_config GLOB)
if(${ARGC} GREATER 1 AND "${ARGV1}" STREQUAL "REC")
set(glob_config GLOB_RECURSE)
endif()
set(mac_files "")
if(APPLE)
set(mac_files ${dir}/*.mm ${dir}/*.m)
endif()
file(${glob_config} tmp_files
${dir}/*.cpp
${dir}/*.c
${dir}/*.cc
${dir}/*.h
${mac_files}
#${dir}/*.asm
)
foreach(entry ${BLACKLIST})
list(REMOVE_ITEM tmp_files ${dir}/${entry})
endforeach()
LIST(APPEND ${PROJECT_NAME}_files "${tmp_files}")
LIST(APPEND ${PROJECT_NAME}_paths "${dir}")
#message(STATUS "addPath ${PROJECT_NAME} : ${tmp_files}")
endmacro()
# adds a file to the sources
macro(addFile filename)
LIST(APPEND ${PROJECT_NAME}_files "${filename}")
#message(STATUS "addFile ${PROJECT_NAME} : ${filename}")
endmacro()
# finds and adds sources files in a folder recursively
macro(addPathRec dir)
addPath("${dir}" "REC")
endmacro()
###############################################################################
### Definition Handling
###############################################################################
macro(__addDef def config)
# two possibilities: a) target already known, so add it directly, or b) target not yet known, so add it to its cache
if(TARGET ${PROJECT_NAME})
#message(STATUS "directly applying defs: ${PROJECT_NAME} with config ${config}: ${def}")
if("${config}" STREQUAL "")
set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY COMPILE_DEFINITIONS ${def})
else()
set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY COMPILE_DEFINITIONS $<$<CONFIG:${config}>:${def}>)
endif()
else()
if("${config}" STREQUAL "")
list(APPEND ${PROJECT_NAME}_defs_ ${def})
else()
list(APPEND ${PROJECT_NAME}_defs_ $<$<CONFIG:${config}>:${def}>)
endif()
#message(STATUS "added definition to cache: ${PROJECT_NAME}_defs_: ${${PROJECT_NAME}_defs_}")
endif()
endmacro()
# adds a definition: argument 1: Nothing(for all), _DEBUG, _RELEASE, <more build configurations>
macro(addDef def)
set(def_configs "")
if(${ARGC} GREATER 1)
foreach(config ${ARGN})
__addDef(${def} ${config})
endforeach()
else()
__addDef(${def} "")
endif()
endmacro()
# this applies cached definitions onto the target
macro(_process_defs)
if(DEFINED ${PROJECT_NAME}_defs_)
set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY COMPILE_DEFINITIONS ${${PROJECT_NAME}_defs_})
#message(STATUS "applying defs to project ${PROJECT_NAME}: ${${PROJECT_NAME}_defs_}")
endif()
endmacro()
###############################################################################
### Source Library Handling
###############################################################################
macro(addLibSrc libPath)
set(cached_project_name ${PROJECT_NAME})
include(${libPath})
project(${cached_project_name})
endmacro()
###############################################################################
### Linked Library Handling
###############################################################################
macro(addLib libs)
foreach(lib ${libs})
# check if we can build it ourselfs
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/libraries/${lib}.cmake")
addLibSrc("${CMAKE_CURRENT_SOURCE_DIR}/libraries/${lib}.cmake")
endif()
# then link against it
# two possibilities: a) target already known, so add it directly, or b) target not yet known, so add it to its cache
if(TARGET ${PROJECT_NAME})
target_link_libraries(${PROJECT_NAME} "${lib}")
else()
list(APPEND ${PROJECT_NAME}_libs ${lib})
endif()
endforeach()
endmacro()
#addLibRelease will add to only release builds
macro(addLibRelease libs)
foreach(lib ${libs})
# check if we can build it ourselfs
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/libraries/${lib}.cmake")
addLibSrc("${CMAKE_CURRENT_SOURCE_DIR}/libraries/${lib}.cmake")
endif()
# then link against it
# two possibilities: a) target already known, so add it directly, or b) target not yet known, so add it to its cache
if(TARGET ${PROJECT_NAME})
target_link_libraries(${PROJECT_NAME} optimized "${lib}")
else()
list(APPEND ${PROJECT_NAME}_libsRelease ${lib})
endif()
endforeach()
endmacro()
#addLibDebug will add to only debug builds
macro(addLibDebug libs)
foreach(lib ${libs})
# check if we can build it ourselfs
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/libraries/${lib}.cmake")
addLibSrc("${CMAKE_CURRENT_SOURCE_DIR}/libraries/${lib}.cmake")
endif()
# then link against it
# two possibilities: a) target already known, so add it directly, or b) target not yet known, so add it to its cache
if(TARGET ${PROJECT_NAME})
target_link_libraries(${PROJECT_NAME} debug "${lib}")
else()
list(APPEND ${PROJECT_NAME}_libsDebug ${lib})
endif()
endforeach()
endmacro()
# this applies cached definitions onto the target
macro(_process_libs)
if(DEFINED ${PROJECT_NAME}_libs)
target_link_libraries(${PROJECT_NAME} "${${PROJECT_NAME}_libs}")
endif()
if(DEFINED ${PROJECT_NAME}_libsRelease)
target_link_libraries(${PROJECT_NAME} optimized "${${PROJECT_NAME}_libsRelease}")
endif()
if(DEFINED ${PROJECT_NAME}_libsDebug)
target_link_libraries(${PROJECT_NAME} debug "${${PROJECT_NAME}_libsDebug}")
endif()
endmacro()
# apple frameworks
macro(addFramework framework)
if (APPLE)
addLib("-framework ${framework}")
endif()
endmacro()
###############################################################################
### Include Handling
###############################################################################
macro(addInclude incPath)
if(TARGET ${PROJECT_NAME})
set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY INCLUDE_DIRECTORIES "${incPath}")
else()
list(APPEND ${PROJECT_NAME}_includes ${incPath})
endif()
endmacro()
# this applies cached definitions onto the target
macro(_process_includes)
if(DEFINED ${PROJECT_NAME}_includes)
set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY INCLUDE_DIRECTORIES "${${PROJECT_NAME}_includes}")
endif()
endmacro()
###############################################################################
macro(_postTargetProcess)
_process_includes()
_process_defs()
_process_libs()
endmacro()
# adds a path to search for libs
macro(addLibPath dir)
link_directories(${dir})
endmacro()
# creates a proper filter for VS
macro(generateFilters relDir)
foreach(f ${${PROJECT_NAME}_files})
# Get the path of the file relative to ${DIRECTORY},
# then alter it (not compulsory)
file(RELATIVE_PATH SRCGR ${relDir} ${f})
set(SRCGR "${PROJECT_NAME}/${SRCGR}")
# Extract the folder, ie remove the filename part
string(REGEX REPLACE "(.*)(/[^/]*)$" "\\1" SRCGR ${SRCGR})
# do not have any ../ dirs
string(REPLACE "../" "" SRCGR ${SRCGR})
# Source_group expects \\ (double antislash), not / (slash)
string(REPLACE / \\ SRCGR ${SRCGR})
#STRING(REPLACE "//" "/" SRCGR ${SRCGR})
#message(STATUS "FILE: ${f} -> ${SRCGR}")
source_group("${SRCGR}" FILES ${f})
endforeach()
endmacro()
# creates a proper filter for VS
macro(generateFiltersSpecial relDir)
foreach(f ${${PROJECT_NAME}_files})
# Get the path of the file relative to ${DIRECTORY},
# then alter it (not compulsory)
file(RELATIVE_PATH SRCGR ${relDir} ${f})
set(SRCGR "torque3d/${SRCGR}")
# Extract the folder, ie remove the filename part
string(REGEX REPLACE "(.*)(/[^/]*)$" "\\1" SRCGR ${SRCGR})
# do not have any ../ dirs
string(REPLACE "../" "" SRCGR ${SRCGR})
IF("${SRCGR}" MATCHES "^torque3d/My Projects/.*$")
string(REPLACE "torque3d/My Projects/${PROJECT_NAME}/" "" SRCGR ${SRCGR})
string(REPLACE "/source" "" SRCGR ${SRCGR})
endif()
# Source_group expects \\ (double antislash), not / (slash)
string(REPLACE / \\ SRCGR ${SRCGR})
#STRING(REPLACE "//" "/" SRCGR ${SRCGR})
IF(EXISTS "${f}" AND NOT IS_DIRECTORY "${f}")
#message(STATUS "FILE: ${f} -> ${SRCGR}")
source_group("${SRCGR}" FILES ${f})
endif()
endforeach()
endmacro()
# macro to add a static library
macro(finishLibrary)
# more paths?
if(${ARGC} GREATER 0)
foreach(dir ${ARGV0})
addPath("${dir}")
endforeach()
endif()
# now inspect the paths we got
set(firstDir "")
foreach(dir ${${PROJECT_NAME}_paths})
if("${firstDir}" STREQUAL "")
set(firstDir "${dir}")
endif()
endforeach()
generateFilters("${firstDir}")
# set per target compile flags
if(TORQUE_CXX_FLAGS_${PROJECT_NAME})
set_source_files_properties(${${PROJECT_NAME}_files} PROPERTIES COMPILE_FLAGS "${TORQUE_CXX_FLAGS_${PROJECT_NAME}}")
else()
set_source_files_properties(${${PROJECT_NAME}_files} PROPERTIES COMPILE_FLAGS "${TORQUE_CXX_FLAGS_LIBS}")
endif()
if(TORQUE_STATIC)
add_library("${PROJECT_NAME}" STATIC ${${PROJECT_NAME}_files})
else()
add_library("${PROJECT_NAME}" SHARED ${${PROJECT_NAME}_files})
endif()
# omg - only use the first folder ... otherwise we get lots of header name collisions
#foreach(dir ${${PROJECT_NAME}_paths})
addInclude("${firstDir}")
#endforeach()
_postTargetProcess()
endmacro()
# macro to add an executable
macro(finishExecutable)
# now inspect the paths we got
set(firstDir "")
foreach(dir ${${PROJECT_NAME}_paths})
if("${firstDir}" STREQUAL "")
set(firstDir "${dir}")
endif()
endforeach()
generateFiltersSpecial("${firstDir}")
# set per target compile flags
if(TORQUE_CXX_FLAGS_${PROJECT_NAME})
set_source_files_properties(${${PROJECT_NAME}_files} PROPERTIES COMPILE_FLAGS "${TORQUE_CXX_FLAGS_${PROJECT_NAME}}")
else()
set_source_files_properties(${${PROJECT_NAME}_files} PROPERTIES COMPILE_FLAGS "${TORQUE_CXX_FLAGS_EXECUTABLES}")
endif()
if (APPLE)
set(ICON_FILE "${projectSrcDir}/torque.icns")
set_source_files_properties(${ICON_FILE} PROPERTIES MACOSX_PACKAGE_LOCATION "Resources")
add_executable("${PROJECT_NAME}" MACOSX_BUNDLE ${ICON_FILE} ${${PROJECT_NAME}_files})
else()
add_executable("${PROJECT_NAME}" WIN32 ${${PROJECT_NAME}_files})
endif()
addInclude("${firstDir}")
_postTargetProcess()
endmacro()
macro(setupVersionNumbers)
set(TORQUE_APP_VERSION_MAJOR 1 CACHE INTEGER "")
set(TORQUE_APP_VERSION_MINOR 0 CACHE INTEGER "")
set(TORQUE_APP_VERSION_PATCH 0 CACHE INTEGER "")
set(TORQUE_APP_VERSION_TWEAK 0 CACHE INTEGER "")
mark_as_advanced(TORQUE_APP_VERSION_TWEAK)
MATH(EXPR TORQUE_APP_VERSION "${TORQUE_APP_VERSION_MAJOR} * 1000 + ${TORQUE_APP_VERSION_MINOR} * 100 + ${TORQUE_APP_VERSION_PATCH} * 10 + ${TORQUE_APP_VERSION_TWEAK}")
set(TORQUE_APP_VERSION_STRING "${TORQUE_APP_VERSION_MAJOR}.${TORQUE_APP_VERSION_MINOR}.${TORQUE_APP_VERSION_PATCH}.${TORQUE_APP_VERSION_TWEAK}")
#message(STATUS "version numbers: ${TORQUE_APP_VERSION} / ${TORQUE_APP_VERSION_STRING}")
endmacro()
macro(setupPackaging)
INCLUDE(CPack)
# only enable zips for now
set(CPACK_BINARY_NSIS OFF CACHE INTERNAL "" FORCE)
set(CPACK_BINARY_ZIP ON CACHE INTERNAL "" FORCE)
set(CPACK_SOURCE_ZIP OFF CACHE INTERNAL "" FORCE)
SET(CPACK_GENERATOR "ZIP")
SET(CPACK_PACKAGE_VENDOR "${PROJECT_NAME}")
SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "${PROJECT_NAME}")
SET(CPACK_INCLUDE_TOPLEVEL_DIRECTORY 1)
SET(CPACK_OUTPUT_FILE_PREFIX "${TORQUE_APP_DIR}/packages/${PROJECT_NAME}")
SET(CPACK_PACKAGE_INSTALL_DIRECTORY "")
#SET(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/ReadMe.txt")
#SET(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/Copyright.txt")
SET(CPACK_PACKAGE_VERSION_MAJOR "${TORQUE_APP_VERSION_MAJOR}")
SET(CPACK_PACKAGE_VERSION_MINOR "${TORQUE_APP_VERSION_MINOR}")
SET(CPACK_PACKAGE_VERSION_PATCH "${TORQUE_APP_VERSION_PATCH}")
#SET(CPACK_PACKAGE_EXECUTABLES "${PROJECT_NAME}" "${PROJECT_NAME}")
SET(CPACK_SOURCE_PACKAGE_FILE_NAME "${PROJECT_NAME}-${TORQUE_APP_VERSION_STRING}")
#SET(CPACK_SOURCE_STRIP_FILES "")
endmacro()
# always static for now
set(TORQUE_STATIC ON)
#option(TORQUE_STATIC "enables or disable static" OFF)
if(WIN32)
set(TORQUE_CXX_FLAGS_EXECUTABLES "/wd4018 /wd4100 /wd4121 /wd4127 /wd4130 /wd4244 /wd4245 /wd4389 /wd4511 /wd4512 /wd4800 /wd4995 " CACHE TYPE STRING)
mark_as_advanced(TORQUE_CXX_FLAGS_EXECUTABLES)
set(TORQUE_CXX_FLAGS_LIBS "/W0" CACHE TYPE STRING)
mark_as_advanced(TORQUE_CXX_FLAGS_LIBS)
set(TORQUE_CXX_FLAGS_COMMON_DEFAULT "-DUNICODE -D_UNICODE -D_CRT_SECURE_NO_WARNINGS /MP /O2 /Ob2 /Oi /Ot /Oy /GT /Zi /W4 /nologo /GF /EHsc /GS- /Gy- /Qpar- /fp:precise /fp:except- /GR /Zc:wchar_t-" )
if( TORQUE_CPU_X32 )
set(TORQUE_CXX_FLAGS_COMMON_DEFAULT "${TORQUE_CXX_FLAGS_COMMON_DEFAULT} /arch:SSE2")
endif()
set(TORQUE_CXX_FLAGS_COMMON ${TORQUE_CXX_FLAGS_COMMON_DEFAULT} CACHE TYPE STRING)
mark_as_advanced(TORQUE_CXX_FLAGS_COMMON)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORQUE_CXX_FLAGS_COMMON}")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CMAKE_CXX_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "/LARGEADDRESSAWARE")
#set(STATIC_LIBRARY_FLAGS "/OPT:NOREF")
# Force static runtime libraries
if(TORQUE_STATIC)
FOREACH(flag
CMAKE_C_FLAGS_RELEASE
CMAKE_C_FLAGS_RELWITHDEBINFO
CMAKE_C_FLAGS_DEBUG
CMAKE_C_FLAGS_DEBUG_INIT
CMAKE_CXX_FLAGS_RELEASE
CMAKE_CXX_FLAGS_RELWITHDEBINFO
CMAKE_CXX_FLAGS_DEBUG
CMAKE_CXX_FLAGS_DEBUG_INIT)
STRING(REPLACE "/MD" "/MT" "${flag}" "${${flag}}")
SET("${flag}" "${${flag}} /EHsc")
ENDFOREACH()
endif()
else()
# TODO: improve default settings on other platforms
set(TORQUE_CXX_FLAGS_EXECUTABLES "" CACHE TYPE STRING)
mark_as_advanced(TORQUE_CXX_FLAGS_EXECUTABLES)
set(TORQUE_CXX_FLAGS_LIBS "" CACHE TYPE STRING)
mark_as_advanced(TORQUE_CXX_FLAGS_LIBS)
set(TORQUE_CXX_FLAGS_COMMON "" CACHE TYPE STRING)
mark_as_advanced(TORQUE_CXX_FLAGS)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORQUE_CXX_FLAGS}")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CMAKE_CXX_FLAGS}")
endif()
if(UNIX AND NOT APPLE)
SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${projectOutDir}")
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${projectOutDir}")
SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG "${projectOutDir}")
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG "${projectOutDir}")
endif()
if(APPLE)
SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE "${projectOutDir}")
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE "${projectOutDir}")
SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG "${projectOutDir}")
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG "${projectOutDir}")
endif()
# fix the debug/release subfolders on windows
if(MSVC)
SET("CMAKE_RUNTIME_OUTPUT_DIRECTORY" "${projectOutDir}")
FOREACH(CONF ${CMAKE_CONFIGURATION_TYPES})
# Go uppercase (DEBUG, RELEASE...)
STRING(TOUPPER "${CONF}" CONF)
#SET("CMAKE_ARCHIVE_OUTPUT_DIRECTORY_${CONF}" "${projectOutDir}")
SET("CMAKE_RUNTIME_OUTPUT_DIRECTORY_${CONF}" "${projectOutDir}")
ENDFOREACH()
endif()
|
Java
|
#ifndef BOOST_NETWORK_PROTOCOL_HTTP_IMPL_HTTP_SYNC_CONNECTION_20100601
#define BOOST_NETWORK_PROTOCOL_HTTP_IMPL_HTTP_SYNC_CONNECTION_20100601
// Copyright 2013 Google, Inc.
// Copyright 2010 (C) Dean Michael Berris
// Copyright 2010 (C) Sinefunc, Inc.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <iterator>
#include <functional>
#include <asio/deadline_timer.hpp>
#include <asio/streambuf.hpp>
#include <boost/network/protocol/http/algorithms/linearize.hpp>
#include <boost/network/protocol/http/response.hpp>
#include <boost/network/protocol/http/traits/resolver_policy.hpp>
#include <boost/network/traits/string.hpp>
namespace boost {
namespace network {
namespace http {
namespace impl {
template <class Tag, unsigned version_major, unsigned version_minor>
struct sync_connection_base_impl;
template <class Tag, unsigned version_major, unsigned version_minor>
struct sync_connection_base;
template <class Tag, unsigned version_major, unsigned version_minor>
struct http_sync_connection
: public virtual sync_connection_base<Tag, version_major, version_minor>,
sync_connection_base_impl<Tag, version_major, version_minor>,
std::enable_shared_from_this<
http_sync_connection<Tag, version_major, version_minor> > {
typedef typename resolver_policy<Tag>::type resolver_base;
typedef typename resolver_base::resolver_type resolver_type;
typedef typename string<Tag>::type string_type;
typedef std::function<typename resolver_base::resolver_iterator_pair(
resolver_type&, string_type const&, string_type const&)>
resolver_function_type;
typedef http_sync_connection<Tag, version_major, version_minor> this_type;
typedef sync_connection_base_impl<Tag, version_major, version_minor>
connection_base;
typedef std::function<bool(string_type&)> body_generator_function_type;
http_sync_connection(resolver_type& resolver, resolver_function_type resolve,
int timeout)
: connection_base(),
timeout_(timeout),
timer_(resolver.get_io_service()),
resolver_(resolver),
resolve_(std::move(resolve)),
socket_(resolver.get_io_service()) {}
void init_socket(string_type const& hostname, string_type const& port) {
connection_base::init_socket(socket_, resolver_, hostname, port, resolve_);
}
void send_request_impl(string_type const& method,
basic_request<Tag> const& request_,
body_generator_function_type generator) {
asio::streambuf request_buffer;
linearize(
request_, method, version_major, version_minor,
std::ostreambuf_iterator<typename char_<Tag>::type>(&request_buffer));
connection_base::send_request_impl(socket_, method, request_buffer);
if (generator) {
string_type chunk;
while (generator(chunk)) {
std::copy(chunk.begin(), chunk.end(),
std::ostreambuf_iterator<typename char_<Tag>::type>(
&request_buffer));
chunk.clear();
connection_base::send_request_impl(socket_, method, request_buffer);
}
}
if (timeout_ > 0) {
timer_.expires_from_now(boost::posix_time::seconds(timeout_));
auto self = this->shared_from_this();
timer_.async_wait([=] (std::error_code const &ec) {
self->handle_timeout(ec);
});
}
}
void read_status(basic_response<Tag>& response_,
asio::streambuf& response_buffer) {
connection_base::read_status(socket_, response_, response_buffer);
}
void read_headers(basic_response<Tag>& response,
asio::streambuf& response_buffer) {
connection_base::read_headers(socket_, response, response_buffer);
}
void read_body(basic_response<Tag>& response_,
asio::streambuf& response_buffer) {
connection_base::read_body(socket_, response_, response_buffer);
typename headers_range<basic_response<Tag> >::type connection_range =
headers(response_)["Connection"];
if (version_major == 1 && version_minor == 1 &&
!boost::empty(connection_range) &&
boost::iequals(std::begin(connection_range)->second, "close")) {
close_socket();
} else if (version_major == 1 && version_minor == 0) {
close_socket();
}
}
bool is_open() { return socket_.is_open(); }
void close_socket() {
timer_.cancel();
if (!is_open()) {
return;
}
std::error_code ignored;
socket_.shutdown(asio::ip::tcp::socket::shutdown_both, ignored);
if (ignored) {
return;
}
socket_.close(ignored);
}
private:
void handle_timeout(std::error_code const& ec) {
if (!ec) {
close_socket();
}
}
int timeout_;
asio::deadline_timer timer_;
resolver_type& resolver_;
resolver_function_type resolve_;
asio::ip::tcp::socket socket_;
};
} // namespace impl
} // namespace http
} // namespace network
} // namespace boost
#endif // BOOST_NETWORK_PROTOCOL_HTTP_IMPL_HTTP_SYNC_CONNECTION_20100
|
Java
|
import React from 'react'
import Icon from 'react-icon-base'
const IoTshirtOutline = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m11.4 6.7l-8.1 2.4 0.8 2.5 3.1-0.3 3-0.4-0.2 3-1.1 19.9h17.2l-1.1-19.9-0.2-3 3 0.4 3.1 0.3 0.8-2.5-8.1-2.4c-0.5 0.6-1 1.1-1.6 1.5-1.2 0.8-2.7 1.2-4.5 1.2-2.7-0.1-4.6-0.9-6.1-2.7z m11.1-2.9l12.5 3.7-2.5 6.9-5-0.6 1.3 22.5h-22.5l1.2-22.5-5 0.6-2.5-6.9 12.5-3.7c1.1 2.1 2.4 3 5 3.1 2.6 0 3.9-1 5-3.1z"/></g>
</Icon>
)
export default IoTshirtOutline
|
Java
|
import {NgbCalendarIslamicCivil} from './ngb-calendar-islamic-civil';
import {NgbDate} from '../ngb-date';
import {Injectable} from '@angular/core';
/**
* Umalqura calendar is one type of Hijri calendars used in islamic countries.
* This Calendar is used by Saudi Arabia for administrative purpose.
* Unlike tabular calendars, the algorithm involves astronomical calculation, but it's still deterministic.
* http://cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types
*/
const GREGORIAN_FIRST_DATE = new Date(1882, 10, 12);
const GREGORIAN_LAST_DATE = new Date(2174, 10, 25);
const HIJRI_BEGIN = 1300;
const HIJRI_END = 1600;
const ONE_DAY = 1000 * 60 * 60 * 24;
const MONTH_LENGTH = [
// 1300-1304
'101010101010', '110101010100', '111011001001', '011011010100', '011011101010',
// 1305-1309
'001101101100', '101010101101', '010101010101', '011010101001', '011110010010',
// 1310-1314
'101110101001', '010111010100', '101011011010', '010101011100', '110100101101',
// 1315-1319
'011010010101', '011101001010', '101101010100', '101101101010', '010110101101',
// 1320-1324
'010010101110', '101001001111', '010100010111', '011010001011', '011010100101',
// 1325-1329
'101011010101', '001011010110', '100101011011', '010010011101', '101001001101',
// 1330-1334
'110100100110', '110110010101', '010110101100', '100110110110', '001010111010',
// 1335-1339
'101001011011', '010100101011', '101010010101', '011011001010', '101011101001',
// 1340-1344
'001011110100', '100101110110', '001010110110', '100101010110', '101011001010',
// 1345-1349
'101110100100', '101111010010', '010111011001', '001011011100', '100101101101',
// 1350-1354
'010101001101', '101010100101', '101101010010', '101110100101', '010110110100',
// 1355-1359
'100110110110', '010101010111', '001010010111', '010101001011', '011010100011',
// 1360-1364
'011101010010', '101101100101', '010101101010', '101010101011', '010100101011',
// 1365-1369
'110010010101', '110101001010', '110110100101', '010111001010', '101011010110',
// 1370-1374
'100101010111', '010010101011', '100101001011', '101010100101', '101101010010',
// 1375-1379
'101101101010', '010101110101', '001001110110', '100010110111', '010001011011',
// 1380-1384
'010101010101', '010110101001', '010110110100', '100111011010', '010011011101',
// 1385-1389
'001001101110', '100100110110', '101010101010', '110101010100', '110110110010',
// 1390-1394
'010111010101', '001011011010', '100101011011', '010010101011', '101001010101',
// 1395-1399
'101101001001', '101101100100', '101101110001', '010110110100', '101010110101',
// 1400-1404
'101001010101', '110100100101', '111010010010', '111011001001', '011011010100',
// 1405-1409
'101011101001', '100101101011', '010010101011', '101010010011', '110101001001',
// 1410-1414
'110110100100', '110110110010', '101010111001', '010010111010', '101001011011',
// 1415-1419
'010100101011', '101010010101', '101100101010', '101101010101', '010101011100',
// 1420-1424
'010010111101', '001000111101', '100100011101', '101010010101', '101101001010',
// 1425-1429
'101101011010', '010101101101', '001010110110', '100100111011', '010010011011',
// 1430-1434
'011001010101', '011010101001', '011101010100', '101101101010', '010101101100',
// 1435-1439
'101010101101', '010101010101', '101100101001', '101110010010', '101110101001',
// 1440-1444
'010111010100', '101011011010', '010101011010', '101010101011', '010110010101',
// 1445-1449
'011101001001', '011101100100', '101110101010', '010110110101', '001010110110',
// 1450-1454
'101001010110', '111001001101', '101100100101', '101101010010', '101101101010',
// 1455-1459
'010110101101', '001010101110', '100100101111', '010010010111', '011001001011',
// 1460-1464
'011010100101', '011010101100', '101011010110', '010101011101', '010010011101',
// 1465-1469
'101001001101', '110100010110', '110110010101', '010110101010', '010110110101',
// 1470-1474
'001011011010', '100101011011', '010010101101', '010110010101', '011011001010',
// 1475-1479
'011011100100', '101011101010', '010011110101', '001010110110', '100101010110',
// 1480-1484
'101010101010', '101101010100', '101111010010', '010111011001', '001011101010',
// 1485-1489
'100101101101', '010010101101', '101010010101', '101101001010', '101110100101',
// 1490-1494
'010110110010', '100110110101', '010011010110', '101010010111', '010101000111',
// 1495-1499
'011010010011', '011101001001', '101101010101', '010101101010', '101001101011',
// 1500-1504
'010100101011', '101010001011', '110101000110', '110110100011', '010111001010',
// 1505-1509
'101011010110', '010011011011', '001001101011', '100101001011', '101010100101',
// 1510-1514
'101101010010', '101101101001', '010101110101', '000101110110', '100010110111',
// 1515-1519
'001001011011', '010100101011', '010101100101', '010110110100', '100111011010',
// 1520-1524
'010011101101', '000101101101', '100010110110', '101010100110', '110101010010',
// 1525-1529
'110110101001', '010111010100', '101011011010', '100101011011', '010010101011',
// 1530-1534
'011001010011', '011100101001', '011101100010', '101110101001', '010110110010',
// 1535-1539
'101010110101', '010101010101', '101100100101', '110110010010', '111011001001',
// 1540-1544
'011011010010', '101011101001', '010101101011', '010010101011', '101001010101',
// 1545-1549
'110100101001', '110101010100', '110110101010', '100110110101', '010010111010',
// 1550-1554
'101000111011', '010010011011', '101001001101', '101010101010', '101011010101',
// 1555-1559
'001011011010', '100101011101', '010001011110', '101000101110', '110010011010',
// 1560-1564
'110101010101', '011010110010', '011010111001', '010010111010', '101001011101',
// 1565-1569
'010100101101', '101010010101', '101101010010', '101110101000', '101110110100',
// 1570-1574
'010110111001', '001011011010', '100101011010', '101101001010', '110110100100',
// 1575-1579
'111011010001', '011011101000', '101101101010', '010101101101', '010100110101',
// 1580-1584
'011010010101', '110101001010', '110110101000', '110111010100', '011011011010',
// 1585-1589
'010101011011', '001010011101', '011000101011', '101100010101', '101101001010',
// 1590-1594
'101110010101', '010110101010', '101010101110', '100100101110', '110010001111',
// 1595-1599
'010100100111', '011010010101', '011010101010', '101011010110', '010101011101',
// 1600
'001010011101'
];
function getDaysDiff(date1: Date, date2: Date): number {
const diff = Math.abs(date1.getTime() - date2.getTime());
return Math.round(diff / ONE_DAY);
}
@Injectable()
export class NgbCalendarIslamicUmalqura extends NgbCalendarIslamicCivil {
/**
* Returns the equivalent islamic(Umalqura) date value for a give input Gregorian date.
* `gdate` is s JS Date to be converted to Hijri.
*/
fromGregorian(gDate: Date): NgbDate {
let hDay = 1, hMonth = 0, hYear = 1300;
let daysDiff = getDaysDiff(gDate, GREGORIAN_FIRST_DATE);
if (gDate.getTime() - GREGORIAN_FIRST_DATE.getTime() >= 0 && gDate.getTime() - GREGORIAN_LAST_DATE.getTime() <= 0) {
let year = 1300;
for (let i = 0; i < MONTH_LENGTH.length; i++, year++) {
for (let j = 0; j < 12; j++) {
let numOfDays = +MONTH_LENGTH[i][j] + 29;
if (daysDiff <= numOfDays) {
hDay = daysDiff + 1;
if (hDay > numOfDays) {
hDay = 1;
j++;
}
if (j > 11) {
j = 0;
year++;
}
hMonth = j;
hYear = year;
return new NgbDate(hYear, hMonth + 1, hDay);
}
daysDiff = daysDiff - numOfDays;
}
}
} else {
return super.fromGregorian(gDate);
}
}
/**
* Converts the current Hijri date to Gregorian.
*/
toGregorian(hDate: NgbDate): Date {
const hYear = hDate.year;
const hMonth = hDate.month - 1;
const hDay = hDate.day;
let gDate = new Date(GREGORIAN_FIRST_DATE);
let dayDiff = hDay - 1;
if (hYear >= HIJRI_BEGIN && hYear <= HIJRI_END) {
for (let y = 0; y < hYear - HIJRI_BEGIN; y++) {
for (let m = 0; m < 12; m++) {
dayDiff += +MONTH_LENGTH[y][m] + 29;
}
}
for (let m = 0; m < hMonth; m++) {
dayDiff += +MONTH_LENGTH[hYear - HIJRI_BEGIN][m] + 29;
}
gDate.setDate(GREGORIAN_FIRST_DATE.getDate() + dayDiff);
} else {
gDate = super.toGregorian(hDate);
}
return gDate;
}
/**
* Returns the number of days in a specific Hijri hMonth.
* `hMonth` is 1 for Muharram, 2 for Safar, etc.
* `hYear` is any Hijri hYear.
*/
getDaysPerMonth(hMonth: number, hYear: number): number {
if (hYear >= HIJRI_BEGIN && hYear <= HIJRI_END) {
const pos = hYear - HIJRI_BEGIN;
return +MONTH_LENGTH[pos][hMonth - 1] + 29;
}
return super.getDaysPerMonth(hMonth, hYear);
}
}
|
Java
|
# Supported tags and respective `Dockerfile` links
- [`3.1.23`, `3.1`, `3`, `latest` (*Dockerfile*)](https://github.com/docker-library/celery/blob/0652407560f353e749cbe001e8bdbb5db86c2291/Dockerfile)
[](https://imagelayers.io/?images=celery:3.1.23)
For more information about this image and its history, please see [the relevant manifest file (`library/celery`)](https://github.com/docker-library/official-images/blob/master/library/celery). This image is updated via [pull requests to the `docker-library/official-images` GitHub repo](https://github.com/docker-library/official-images/pulls?q=label%3Alibrary%2Fcelery).
For detailed information about the virtual/transfer sizes and individual layers of each of the above supported tags, please see [the `celery/tag-details.md` file](https://github.com/docker-library/docs/blob/master/celery/tag-details.md) in [the `docker-library/docs` GitHub repo](https://github.com/docker-library/docs).
# Celery
Celery is an open source asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well.
> [wikipedia.org/wiki/Celery_Task_Queue](https://en.wikipedia.org/wiki/Celery_Task_Queue)
# How to use this image
## start a celery worker (RabbitMQ Broker)
```console
$ docker run --link some-rabbit:rabbit --name some-celery -d celery
```
### check the status of the cluster
```console
$ docker run --link some-rabbit:rabbit --rm celery celery status
```
## start a celery worker (Redis Broker)
```console
$ docker run --link some-redis:redis -e CELERY_BROKER_URL=redis://redis --name some-celery -d celery
```
### check the status of the cluster
```console
$ docker run --link some-redis:redis -e CELERY_BROKER_URL=redis://redis --rm celery celery status
```
# Supported Docker versions
This image is officially supported on Docker version 1.11.1.
Support for older versions (down to 1.6) is provided on a best-effort basis.
Please see [the Docker installation documentation](https://docs.docker.com/installation/) for details on how to upgrade your Docker daemon.
# User Feedback
## Documentation
Documentation for this image is stored in the [`celery/` directory](https://github.com/docker-library/docs/tree/master/celery) of the [`docker-library/docs` GitHub repo](https://github.com/docker-library/docs). Be sure to familiarize yourself with the [repository's `README.md` file](https://github.com/docker-library/docs/blob/master/README.md) before attempting a pull request.
## Issues
If you have any problems with or questions about this image, please contact us through a [GitHub issue](https://github.com/docker-library/celery/issues). If the issue is related to a CVE, please check for [a `cve-tracker` issue on the `official-images` repository first](https://github.com/docker-library/official-images/issues?q=label%3Acve-tracker).
You can also reach many of the official image maintainers via the `#docker-library` IRC channel on [Freenode](https://freenode.net).
## Contributing
You are invited to contribute new features, fixes, or updates, large or small; we are always thrilled to receive pull requests, and do our best to process them as fast as we can.
Before you start to code, we recommend discussing your plans through a [GitHub issue](https://github.com/docker-library/celery/issues), especially for more ambitious contributions. This gives other contributors a chance to point you in the right direction, give you feedback on your design, and help you find out if someone else is working on the same thing.
|
Java
|
declare module "react-apollo" {
declare function graphql(query: Object, options: Object): Function;
}
|
Java
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Permalinks</title>
<link rel="stylesheet" href="../assets/css/ghost.min.css">
<!-- Styles not needed for this. Just to get around various bits that Ember handles for us. -->
<style>
@media (max-width: 900px) {
.settings-nav {
top: 0;
left: -100%;
}
.settings-content {
margin-left: 0;
}
}
</style>
</head>
<body class="ember-application settings settings-view-general" data-apps="false" data-filestorage="true" data-blogurl="http://127.0.0.1:2368">
<div id="container"><a class="sr-only sr-only-focusable" href="#gh-main">Skip to main content</a>
<nav class="global-nav" role="navigation">
<a class="nav-item ghost-logo" href="/" title="/">
<div class="nav-label"><i class="icon-ghost"></i>
<span>Visit blog</span>
</div>
</a>
<a class="nav-item nav-content js-nav-item" href="/ghost/">
<div class="nav-label"><i class="icon-content"></i> Content</div>
</a>
<a class="nav-item nav-new js-nav-item" href="/ghost/editor/">
<div class="nav-label"><i class="icon-add"></i> New Post</div>
</a>
<a class="nav-item nav-settings js-nav-item active" href="/ghost/settings/">
<div class="nav-label"><i class="icon-settings2"></i> Settings</div>
</a>
<div class="nav-item user-menu" data-href="#">
<div class=" nav-label">
<div class="image">
<img src="../../../core/shared/img/user-image.png" alt="Paul Davis's profile picture">
</div>
<div class="name">
Paul Davis <i class="icon-chevron-down"></i>
<small>Profile & Settings</small>
</div>
</div>
</div>
</nav>
<div class="nav-cover js-nav-cover"></div>
<main id="gh-main" class="viewport" role="main" data-notification-count="0" data-bindattr-448="448">
<aside class="notifications top">
</aside>
<aside class="notifications bottom">
</aside>
<div>
<header class="page-header">
<button class="menu-button js-menu-button" data-ember-action="1221">
<span class="sr-only">Menu</span>
</button>
<h2 class="page-title">Settings</h2>
</header>
<div class="page-content">
<nav class="settings-nav js-settings-nav">
<ul>
<li class="settings-nav-general icon-settings active"><a class="active" href="/ghost/settings/general/">General</a>
</li>
<li class="settings-nav-users icon-users"><a href="/ghost/settings/users/">Users</a>
</li>
<li class="settings-nav-about icon-pacman"><a href="/ghost/settings/about/">About</a>
</li>
</ul>
</nav>
<section class="settings-content js-settings-content fade-in">
<header class="settings-view-header">
<a class="gh-btn gh-btn-default gh-btn-back active" href="/ghost/settings/"><span>Back</span></a>
<h2 class="page-title">General</h2>
<section class="page-actions">
<button type="button" class="gh-btn gh-btn-blue" data-ember-action="1271"><span>Save</span></button>
</section>
</header>
<section class="content settings-general">
<form id="settings-general" novalidate="novalidate">
<div class="form-group">
<label for="blog-title">Blog Title</label>
<input id="blog-title" class="" type="text" name="general[title]" value="Paul Davis">
<p>The name of your blog</p>
</div>
<div class="form-group">
<label for="blog-logo">Blog Logo</label>
<button type="button" class="gh-btn gh-btn-green js-modal-logo" data-ember-action="1277"><span>Upload Image</span></button>
<p>Display a sexy logo for your publication</p>
</div>
<fieldset>
<div class="form-group">
<label for="postsPerPage">Posts per page</label>
<input id="postsPerPage" class="" type="number" name="general[postsPerPage]" min="1" max="1000" value="5">
<p>How many posts should be displayed on each page</p>
</div>
<div class="form-group">
<label for="blog-permalinks">Permalinks</label>
<label class="permalink-input-wrapper input" tabindex="0">
<div class="permalink-fake-input">
<span class="permalink-domain">http://myblog.ghost.io</span>
<span class="permalink-parameter label label-default">journal</span>
<span class="permalink-parameter label label-default">year</span>
<span class="permalink-parameter label label-default">hello</span>
<span class="permalink-parameter label label-default">agaian</span>
<span class="permalink-parameter label label-default">this</span>
<span class="permalink-parameter label label-default">is</span>
<span class="permalink-parameter label label-default">nice</span>
<span class="permalink-parameter label label-default">yo</span>
<span class="permalink-parameter label label-default">yo</span>
<span class="permalink-parameter label label-default">yo</span>
<input id="blog-permalinks" class="permalink-input" type="text" name="general[permalinks]">
</div>
<div class="popover">
<button class="permalink-help button icon-question hover-me">
<span class="hidden">URL Structure Formatting</span>
</button>
<div class="popover-item closed popover-triangle-bottom">
<div class="popover-title">URL Structure Formatting</div>
<div class="popover-desc">You can use dynamic variables in this field.</div>
<div class="popover-body">
<p>
<b>%t</b> - The title of your post (or page)<br>
<b>%c</b> - The tag which your post is categorised in<br>
<b>%y</b> - The year your post was published<br>
<b>%m</b> - The month your post was published<br>
<b>%d</b> - The day your post was published
</p>
</div>
</div>
</div>
</label>
<p>The default URL structure for your blog</p>
</div>
<div class="form-group for-select">
<label for="activeTheme">Theme</label>
<span class="gh-select" data-bindattr-1286="1286" tabindex="0" data-select-text="Casper - 1.1.0">
<select id="activeTheme" class="ember-select" name="general[activeTheme]">
<option value="casper">Casper - 1.1.0</option>
<option value="hayleybrowne">HJB - 0.5</option>
<option value="mono">Mono - 0.1.0</option>
<option value="pad-gs">PAD-GS - 0.8</option>
<option value="pauladamdavis">PAD - 0.8</option>
</select>
</span>
<p>Select a theme for your blog</p>
</div>
</fieldset>
</form>
</section>
</section>
</div>
</div>
</main>
</div>
</body>
</html>
<script src="../../../bower_components/jquery/dist/jquery.js"></script>
<script>
$(function(){
$('.permalink-input-wrapper').on('click', function(){
$(this).addClass('focus');
$('#blog-permalinks').focus();
});
$('#blog-permalinks').on('blur', function(){
$('.permalink-input-wrapper').removeClass('focus');
});
$('.hover-me').hover(function(){
$(this).next('.popover-item').addClass('open fade-in').removeClass('closed fade-out');
}, function(){
$(this).next('.popover-item').removeClass('fade-in').addClass('fade-out');
$(this).next('.popover-item').on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function (event) {
if (event.originalEvent.animationName === 'fade-out') {
$(this).removeClass('open fade-out').addClass('closed');
}
});
});
function convertToSlug(Text){
return Text.toLowerCase().replace(/[^\w ]+/g,'').replace(/ +/g,'-').trim();
}
$('#blog-permalinks').on('keyup', function(e){
// 188 = comma
// Append the new parameter when pressing comma
if (e.keyCode === 188) {
var input_val = convertToSlug($(this).val());
var the_param = '<span class="permalink-parameter label label-default">' + input_val + '</span>';
// If a parameter exists, append after it.
// Else append after the domain
if ($('.permalink-parameter').length) {
$('.permalink-parameter:last').after(the_param);
} else {
$('.permalink-domain').after(the_param);
}
$(this).val('');
}
// 8 = backspace
// When backspace is pressed AND the input is empty, delete the last parameter
if (e.keyCode === 8 && $(this).val() == '') {
$('.permalink-parameter:last').remove();
}
});
});
</script>
|
Java
|
<?php
namespace Chamilo\Application\Weblcms\Tool\Implementation\ExamAssignment\Ajax\Component;
use Chamilo\Application\Weblcms\Tool\Implementation\ExamAssignment\Ajax\Manager;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* @package Chamilo\Application\Weblcms\Tool\Implementation\ExamAssignment\Ajax\Component
*
* @author Stefan Gabriëls - Hogeschool Gent
*/
class ListUsersComponent extends Manager
{
/**
* @return string
*/
function run()
{
try
{
$publication = $this->getAjaxComponent()->getContentObjectPublication();
$users = $this->getUserOvertimeService()->getUsersByPublication($publication);
return new JsonResponse([self::PARAM_RESULTS => $users]);
}
catch(\Exception $ex)
{
$this->getExceptionLogger()->logException($ex);
return new JsonResponse([self::PARAM_ERROR_MESSAGE => $ex->getMessage()], 500);
}
}
}
|
Java
|
/*
* Copyright (c) 2000-2018 Apple Computer, Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
/*
* attr.h - attribute data structures and interfaces
*
* Copyright (c) 1998, Apple Computer, Inc. All Rights Reserved.
*/
#ifndef _SYS_ATTR_H_
#define _SYS_ATTR_H_
#include <sys/appleapiopts.h>
#ifdef __APPLE_API_UNSTABLE
#include <sys/types.h>
#include <sys/ucred.h>
#include <sys/time.h>
#include <sys/cdefs.h>
#define FSOPT_NOFOLLOW 0x00000001
#define FSOPT_NOINMEMUPDATE 0x00000002
#define FSOPT_REPORT_FULLSIZE 0x00000004
/* The following option only valid when requesting ATTR_CMN_RETURNED_ATTRS */
#define FSOPT_PACK_INVAL_ATTRS 0x00000008
#define FSOPT_ATTR_CMN_EXTENDED 0x00000020
/* we currently aren't anywhere near this amount for a valid
* fssearchblock.sizeofsearchparams1 or fssearchblock.sizeofsearchparams2
* but we put a sanity check in to avoid abuse of the value passed in from
* user land.
*/
#define SEARCHFS_MAX_SEARCHPARMS 4096
typedef u_int32_t text_encoding_t;
typedef u_int32_t fsobj_type_t;
typedef u_int32_t fsobj_tag_t;
typedef u_int32_t fsfile_type_t;
typedef u_int32_t fsvolid_t;
#include <sys/_types/_fsobj_id_t.h> /* file object id type */
typedef u_int32_t attrgroup_t;
struct attrlist {
u_short bitmapcount; /* number of attr. bit sets in list (should be 5) */
u_int16_t reserved; /* (to maintain 4-byte alignment) */
attrgroup_t commonattr; /* common attribute group */
attrgroup_t volattr; /* Volume attribute group */
attrgroup_t dirattr; /* directory attribute group */
attrgroup_t fileattr; /* file attribute group */
attrgroup_t forkattr; /* fork attribute group */
};
#define ATTR_BIT_MAP_COUNT 5
typedef struct attribute_set {
attrgroup_t commonattr; /* common attribute group */
attrgroup_t volattr; /* Volume attribute group */
attrgroup_t dirattr; /* directory attribute group */
attrgroup_t fileattr; /* file attribute group */
attrgroup_t forkattr; /* fork attribute group */
} attribute_set_t;
typedef struct attrreference {
int32_t attr_dataoffset;
u_int32_t attr_length;
} attrreference_t;
/* XXX PPD This is derived from HFSVolumePriv.h and should perhaps be referenced from there? */
struct diskextent {
u_int32_t startblock; /* first block allocated */
u_int32_t blockcount; /* number of blocks allocated */
};
typedef struct diskextent extentrecord[8];
typedef u_int32_t vol_capabilities_set_t[4];
#define VOL_CAPABILITIES_FORMAT 0
#define VOL_CAPABILITIES_INTERFACES 1
#define VOL_CAPABILITIES_RESERVED1 2
#define VOL_CAPABILITIES_RESERVED2 3
typedef struct vol_capabilities_attr {
vol_capabilities_set_t capabilities;
vol_capabilities_set_t valid;
} vol_capabilities_attr_t;
/*
* XXX this value needs to be raised - 3893388
*/
#define ATTR_MAX_BUFFER 8192
/*
* VOL_CAP_FMT_PERSISTENTOBJECTIDS: When set, the volume has object IDs
* that are persistent (retain their values even when the volume is
* unmounted and remounted), and a file or directory can be looked up
* by ID. Volumes that support VolFS and can support Carbon File ID
* references should set this bit.
*
* VOL_CAP_FMT_SYMBOLICLINKS: When set, the volume supports symbolic
* links. The symlink(), readlink(), and lstat() calls all use this
* symbolic link.
*
* VOL_CAP_FMT_HARDLINKS: When set, the volume supports hard links.
* The link() call creates hard links.
*
* VOL_CAP_FMT_JOURNAL: When set, the volume is capable of supporting
* a journal used to speed recovery in case of unplanned shutdown
* (such as a power outage or crash). This bit does not necessarily
* mean the volume is actively using a journal for recovery.
*
* VOL_CAP_FMT_JOURNAL_ACTIVE: When set, the volume is currently using
* a journal for use in speeding recovery after an unplanned shutdown.
* This bit can be set only if VOL_CAP_FMT_JOURNAL is also set.
*
* VOL_CAP_FMT_NO_ROOT_TIMES: When set, the volume format does not
* store reliable times for the root directory, so you should not
* depend on them to detect changes, etc.
*
* VOL_CAP_FMT_SPARSE_FILES: When set, the volume supports sparse files.
* That is, files which can have "holes" that have never been written
* to, and are not allocated on disk. Sparse files may have an
* allocated size that is less than the file's logical length.
*
* VOL_CAP_FMT_ZERO_RUNS: For security reasons, parts of a file (runs)
* that have never been written to must appear to contain zeroes. When
* this bit is set, the volume keeps track of allocated but unwritten
* runs of a file so that it can substitute zeroes without actually
* writing zeroes to the media. This provides performance similar to
* sparse files, but not the space savings.
*
* VOL_CAP_FMT_CASE_SENSITIVE: When set, file and directory names are
* case sensitive (upper and lower case are different). When clear,
* an upper case character is equivalent to a lower case character,
* and you can't have two names that differ solely in the case of
* the characters.
*
* VOL_CAP_FMT_CASE_PRESERVING: When set, file and directory names
* preserve the difference between upper and lower case. If clear,
* the volume may change the case of some characters (typically
* making them all upper or all lower case). A volume that sets
* VOL_CAP_FMT_CASE_SENSITIVE should also set VOL_CAP_FMT_CASE_PRESERVING.
*
* VOL_CAP_FMT_FAST_STATFS: This bit is used as a hint to upper layers
* (especially Carbon) that statfs() is fast enough that its results
* need not be cached by those upper layers. A volume that caches
* the statfs information in its in-memory structures should set this bit.
* A volume that must always read from disk or always perform a network
* transaction should not set this bit.
*
* VOL_CAP_FMT_2TB_FILESIZE: If this bit is set the volume format supports
* file sizes larger than 4GB, and potentially up to 2TB; it does not
* indicate whether the filesystem supports files larger than that.
*
* VOL_CAP_FMT_OPENDENYMODES: When set, the volume supports open deny
* modes (e.g. "open for read write, deny write"; effectively, mandatory
* file locking based on open modes).
*
* VOL_CAP_FMT_HIDDEN_FILES: When set, the volume supports the UF_HIDDEN
* file flag, and the UF_HIDDEN flag is mapped to that volume's native
* "hidden" or "invisible" bit (which may be the invisible bit from the
* Finder Info extended attribute).
*
* VOL_CAP_FMT_PATH_FROM_ID: When set, the volume supports the ability
* to derive a pathname to the root of the file system given only the
* id of an object. This also implies that object ids on this file
* system are persistent and not recycled. This is a very specialized
* capability and it is assumed that most file systems will not support
* it. Its use is for legacy non-posix APIs like ResolveFileIDRef.
*
* VOL_CAP_FMT_NO_VOLUME_SIZES: When set, the volume does not support
* returning values for total data blocks, available blocks, or free blocks
* (as in f_blocks, f_bavail, or f_bfree in "struct statfs"). Historically,
* those values were set to 0xFFFFFFFF for volumes that did not support them.
*
* VOL_CAP_FMT_DECMPFS_COMPRESSION: When set, the volume supports transparent
* decompression of compressed files using decmpfs.
*
* VOL_CAP_FMT_64BIT_OBJECT_IDS: When set, the volume uses object IDs that
* are 64-bit. This means that ATTR_CMN_FILEID and ATTR_CMN_PARENTID are the
* only legitimate attributes for obtaining object IDs from this volume and the
* 32-bit fid_objno fields of the fsobj_id_t returned by ATTR_CMN_OBJID,
* ATTR_CMN_OBJPERMID, and ATTR_CMN_PAROBJID are undefined.
*
* VOL_CAP_FMT_DIR_HARDLINKS: When set, the volume supports directory
* hard links.
*
* VOL_CAP_FMT_DOCUMENT_ID: When set, the volume supports document IDs
* (an ID which persists across object ID changes) for document revisions.
*
* VOL_CAP_FMT_WRITE_GENERATION_COUNT: When set, the volume supports write
* generation counts (a count of how many times an object has been modified)
*
* VOL_CAP_FMT_NO_IMMUTABLE_FILES: When set, the volume does not support
* setting the UF_IMMUTABLE flag.
*
* VOL_CAP_FMT_NO_PERMISSIONS: When set, the volume does not support setting
* permissions.
*
* VOL_CAP_FMT_SHARED_SPACE: When set, the volume supports sharing space with
* other filesystems i.e. multiple logical filesystems can exist in the same
* "partition". An implication of this is that the filesystem which sets
* this capability treats waitfor arguments to VFS_SYNC as bit flags.
*
* VOL_CAP_FMT_VOL_GROUPS: When set, this volume is part of a volume-group
* that implies multiple volumes must be mounted in order to boot and root the
* operating system. Typically, this means a read-only system volume and a
* writable data volume.
*/
#define VOL_CAP_FMT_PERSISTENTOBJECTIDS 0x00000001
#define VOL_CAP_FMT_SYMBOLICLINKS 0x00000002
#define VOL_CAP_FMT_HARDLINKS 0x00000004
#define VOL_CAP_FMT_JOURNAL 0x00000008
#define VOL_CAP_FMT_JOURNAL_ACTIVE 0x00000010
#define VOL_CAP_FMT_NO_ROOT_TIMES 0x00000020
#define VOL_CAP_FMT_SPARSE_FILES 0x00000040
#define VOL_CAP_FMT_ZERO_RUNS 0x00000080
#define VOL_CAP_FMT_CASE_SENSITIVE 0x00000100
#define VOL_CAP_FMT_CASE_PRESERVING 0x00000200
#define VOL_CAP_FMT_FAST_STATFS 0x00000400
#define VOL_CAP_FMT_2TB_FILESIZE 0x00000800
#define VOL_CAP_FMT_OPENDENYMODES 0x00001000
#define VOL_CAP_FMT_HIDDEN_FILES 0x00002000
#define VOL_CAP_FMT_PATH_FROM_ID 0x00004000
#define VOL_CAP_FMT_NO_VOLUME_SIZES 0x00008000
#define VOL_CAP_FMT_DECMPFS_COMPRESSION 0x00010000
#define VOL_CAP_FMT_64BIT_OBJECT_IDS 0x00020000
#define VOL_CAP_FMT_DIR_HARDLINKS 0x00040000
#define VOL_CAP_FMT_DOCUMENT_ID 0x00080000
#define VOL_CAP_FMT_WRITE_GENERATION_COUNT 0x00100000
#define VOL_CAP_FMT_NO_IMMUTABLE_FILES 0x00200000
#define VOL_CAP_FMT_NO_PERMISSIONS 0x00400000
#define VOL_CAP_FMT_SHARED_SPACE 0x00800000
#define VOL_CAP_FMT_VOL_GROUPS 0x01000000
/*
* VOL_CAP_INT_SEARCHFS: When set, the volume implements the
* searchfs() system call (the vnop_searchfs vnode operation).
*
* VOL_CAP_INT_ATTRLIST: When set, the volume implements the
* getattrlist() and setattrlist() system calls (vnop_getattrlist
* and vnop_setattrlist vnode operations) for the volume, files,
* and directories. The volume may or may not implement the
* readdirattr() system call. XXX Is there any minimum set
* of attributes that should be supported? To determine the
* set of supported attributes, get the ATTR_VOL_ATTRIBUTES
* attribute of the volume.
*
* VOL_CAP_INT_NFSEXPORT: When set, the volume implements exporting
* of NFS volumes.
*
* VOL_CAP_INT_READDIRATTR: When set, the volume implements the
* readdirattr() system call (vnop_readdirattr vnode operation).
*
* VOL_CAP_INT_EXCHANGEDATA: When set, the volume implements the
* exchangedata() system call (VNOP_EXCHANGE vnode operation).
*
* VOL_CAP_INT_COPYFILE: When set, the volume implements the
* VOP_COPYFILE vnode operation. (XXX There should be a copyfile()
* system call in <unistd.h>.)
*
* VOL_CAP_INT_ALLOCATE: When set, the volume implements the
* VNOP_ALLOCATE vnode operation, which means it implements the
* F_PREALLOCATE selector of fcntl(2).
*
* VOL_CAP_INT_VOL_RENAME: When set, the volume implements the
* ATTR_VOL_NAME attribute for both getattrlist() and setattrlist().
* The volume can be renamed by setting ATTR_VOL_NAME with setattrlist().
*
* VOL_CAP_INT_ADVLOCK: When set, the volume implements POSIX style
* byte range locks via vnop_advlock (accessible from fcntl(2)).
*
* VOL_CAP_INT_FLOCK: When set, the volume implements whole-file flock(2)
* style locks via vnop_advlock. This includes the O_EXLOCK and O_SHLOCK
* flags of the open(2) call.
*
* VOL_CAP_INT_EXTENDED_SECURITY: When set, the volume implements
* extended security (ACLs).
*
* VOL_CAP_INT_USERACCESS: When set, the volume supports the
* ATTR_CMN_USERACCESS attribute (used to get the user's access
* mode to the file).
*
* VOL_CAP_INT_MANLOCK: When set, the volume supports AFP-style
* mandatory byte range locks via an ioctl().
*
* VOL_CAP_INT_EXTENDED_ATTR: When set, the volume implements
* native extended attribues.
*
* VOL_CAP_INT_NAMEDSTREAMS: When set, the volume supports
* native named streams.
*
* VOL_CAP_INT_CLONE: When set, the volume supports clones.
*
* VOL_CAP_INT_SNAPSHOT: When set, the volume supports snapshots.
*
* VOL_CAP_INT_RENAME_SWAP: When set, the volume supports swapping
* file system objects.
*
* VOL_CAP_INT_RENAME_EXCL: When set, the volume supports an
* exclusive rename operation.
*
* VOL_CAP_INT_RENAME_OPENFAIL: When set, the volume may fail rename
* operations on files that are open.
*/
#define VOL_CAP_INT_SEARCHFS 0x00000001
#define VOL_CAP_INT_ATTRLIST 0x00000002
#define VOL_CAP_INT_NFSEXPORT 0x00000004
#define VOL_CAP_INT_READDIRATTR 0x00000008
#define VOL_CAP_INT_EXCHANGEDATA 0x00000010
#define VOL_CAP_INT_COPYFILE 0x00000020
#define VOL_CAP_INT_ALLOCATE 0x00000040
#define VOL_CAP_INT_VOL_RENAME 0x00000080
#define VOL_CAP_INT_ADVLOCK 0x00000100
#define VOL_CAP_INT_FLOCK 0x00000200
#define VOL_CAP_INT_EXTENDED_SECURITY 0x00000400
#define VOL_CAP_INT_USERACCESS 0x00000800
#define VOL_CAP_INT_MANLOCK 0x00001000
#define VOL_CAP_INT_NAMEDSTREAMS 0x00002000
#define VOL_CAP_INT_EXTENDED_ATTR 0x00004000
#define VOL_CAP_INT_CLONE 0x00010000
#define VOL_CAP_INT_SNAPSHOT 0x00020000
#define VOL_CAP_INT_RENAME_SWAP 0x00040000
#define VOL_CAP_INT_RENAME_EXCL 0x00080000
#define VOL_CAP_INT_RENAME_OPENFAIL 0x00100000
typedef struct vol_attributes_attr {
attribute_set_t validattr;
attribute_set_t nativeattr;
} vol_attributes_attr_t;
#define ATTR_CMN_NAME 0x00000001
#define ATTR_CMN_DEVID 0x00000002
#define ATTR_CMN_FSID 0x00000004
#define ATTR_CMN_OBJTYPE 0x00000008
#define ATTR_CMN_OBJTAG 0x00000010
#define ATTR_CMN_OBJID 0x00000020
#define ATTR_CMN_OBJPERMANENTID 0x00000040
#define ATTR_CMN_PAROBJID 0x00000080
#define ATTR_CMN_SCRIPT 0x00000100
#define ATTR_CMN_CRTIME 0x00000200
#define ATTR_CMN_MODTIME 0x00000400
#define ATTR_CMN_CHGTIME 0x00000800
#define ATTR_CMN_ACCTIME 0x00001000
#define ATTR_CMN_BKUPTIME 0x00002000
#define ATTR_CMN_FNDRINFO 0x00004000
#define ATTR_CMN_OWNERID 0x00008000
#define ATTR_CMN_GRPID 0x00010000
#define ATTR_CMN_ACCESSMASK 0x00020000
#define ATTR_CMN_FLAGS 0x00040000
/* The following were defined as: */
/* #define ATTR_CMN_NAMEDATTRCOUNT 0x00080000 */
/* #define ATTR_CMN_NAMEDATTRLIST 0x00100000 */
/* These bits have been salvaged for use as: */
/* #define ATTR_CMN_GEN_COUNT 0x00080000 */
/* #define ATTR_CMN_DOCUMENT_ID 0x00100000 */
/* They can only be used with the FSOPT_ATTR_CMN_EXTENDED */
/* option flag. */
#define ATTR_CMN_GEN_COUNT 0x00080000
#define ATTR_CMN_DOCUMENT_ID 0x00100000
#define ATTR_CMN_USERACCESS 0x00200000
#define ATTR_CMN_EXTENDED_SECURITY 0x00400000
#define ATTR_CMN_UUID 0x00800000
#define ATTR_CMN_GRPUUID 0x01000000
#define ATTR_CMN_FILEID 0x02000000
#define ATTR_CMN_PARENTID 0x04000000
#define ATTR_CMN_FULLPATH 0x08000000
#define ATTR_CMN_ADDEDTIME 0x10000000
#define ATTR_CMN_ERROR 0x20000000
#define ATTR_CMN_DATA_PROTECT_FLAGS 0x40000000
/*
* ATTR_CMN_RETURNED_ATTRS is only valid with getattrlist(2) and
* getattrlistbulk(2). It is always the first attribute in the return buffer.
*/
#define ATTR_CMN_RETURNED_ATTRS 0x80000000
#define ATTR_CMN_VALIDMASK 0xFFFFFFFF
/*
* The settable ATTR_CMN_* attributes include the following:
* ATTR_CMN_SCRIPT
* ATTR_CMN_CRTIME
* ATTR_CMN_MODTIME
* ATTR_CMN_CHGTIME
*
* ATTR_CMN_ACCTIME
* ATTR_CMN_BKUPTIME
* ATTR_CMN_FNDRINFO
* ATTR_CMN_OWNERID
*
* ATTR_CMN_GRPID
* ATTR_CMN_ACCESSMASK
* ATTR_CMN_FLAGS
*
* ATTR_CMN_EXTENDED_SECURITY
* ATTR_CMN_UUID
*
* ATTR_CMN_GRPUUID
*
* ATTR_CMN_DATA_PROTECT_FLAGS
*/
#define ATTR_CMN_SETMASK 0x51C7FF00
#define ATTR_CMN_VOLSETMASK 0x00006700
#define ATTR_VOL_FSTYPE 0x00000001
#define ATTR_VOL_SIGNATURE 0x00000002
#define ATTR_VOL_SIZE 0x00000004
#define ATTR_VOL_SPACEFREE 0x00000008
#define ATTR_VOL_SPACEAVAIL 0x00000010
#define ATTR_VOL_MINALLOCATION 0x00000020
#define ATTR_VOL_ALLOCATIONCLUMP 0x00000040
#define ATTR_VOL_IOBLOCKSIZE 0x00000080
#define ATTR_VOL_OBJCOUNT 0x00000100
#define ATTR_VOL_FILECOUNT 0x00000200
#define ATTR_VOL_DIRCOUNT 0x00000400
#define ATTR_VOL_MAXOBJCOUNT 0x00000800
#define ATTR_VOL_MOUNTPOINT 0x00001000
#define ATTR_VOL_NAME 0x00002000
#define ATTR_VOL_MOUNTFLAGS 0x00004000
#define ATTR_VOL_MOUNTEDDEVICE 0x00008000
#define ATTR_VOL_ENCODINGSUSED 0x00010000
#define ATTR_VOL_CAPABILITIES 0x00020000
#define ATTR_VOL_UUID 0x00040000
#define ATTR_VOL_QUOTA_SIZE 0x10000000
#define ATTR_VOL_RESERVED_SIZE 0x20000000
#define ATTR_VOL_ATTRIBUTES 0x40000000
#define ATTR_VOL_INFO 0x80000000
#define ATTR_VOL_VALIDMASK 0xF007FFFF
/*
* The list of settable ATTR_VOL_* attributes include the following:
* ATTR_VOL_NAME
* ATTR_VOL_INFO
*/
#define ATTR_VOL_SETMASK 0x80002000
/* File/directory attributes: */
#define ATTR_DIR_LINKCOUNT 0x00000001
#define ATTR_DIR_ENTRYCOUNT 0x00000002
#define ATTR_DIR_MOUNTSTATUS 0x00000004
#define ATTR_DIR_ALLOCSIZE 0x00000008
#define ATTR_DIR_IOBLOCKSIZE 0x00000010
#define ATTR_DIR_DATALENGTH 0x00000020
/* ATTR_DIR_MOUNTSTATUS Flags: */
#define DIR_MNTSTATUS_MNTPOINT 0x00000001
#define DIR_MNTSTATUS_TRIGGER 0x00000002
#define ATTR_DIR_VALIDMASK 0x0000003f
#define ATTR_DIR_SETMASK 0x00000000
#define ATTR_FILE_LINKCOUNT 0x00000001
#define ATTR_FILE_TOTALSIZE 0x00000002
#define ATTR_FILE_ALLOCSIZE 0x00000004
#define ATTR_FILE_IOBLOCKSIZE 0x00000008
#define ATTR_FILE_DEVTYPE 0x00000020
#define ATTR_FILE_FORKCOUNT 0x00000080
#define ATTR_FILE_FORKLIST 0x00000100
#define ATTR_FILE_DATALENGTH 0x00000200
#define ATTR_FILE_DATAALLOCSIZE 0x00000400
#define ATTR_FILE_RSRCLENGTH 0x00001000
#define ATTR_FILE_RSRCALLOCSIZE 0x00002000
#define ATTR_FILE_VALIDMASK 0x000037FF
/*
* Settable ATTR_FILE_* attributes include:
* ATTR_FILE_DEVTYPE
*/
#define ATTR_FILE_SETMASK 0x00000020
/* CMNEXT attributes extend the common attributes, but in the forkattr field */
#define ATTR_CMNEXT_RELPATH 0x00000004
#define ATTR_CMNEXT_PRIVATESIZE 0x00000008
#define ATTR_CMNEXT_LINKID 0x00000010
#define ATTR_CMNEXT_NOFIRMLINKPATH 0x00000020
#define ATTR_CMNEXT_REALDEVID 0x00000040
#define ATTR_CMNEXT_REALFSID 0x00000080
#define ATTR_CMNEXT_CLONEID 0x00000100
#define ATTR_CMNEXT_EXT_FLAGS 0x00000200
#define ATTR_CMNEXT_VALIDMASK 0x000003fc
#define ATTR_CMNEXT_SETMASK 0x00000000
/* Deprecated fork attributes */
#define ATTR_FORK_TOTALSIZE 0x00000001
#define ATTR_FORK_ALLOCSIZE 0x00000002
#define ATTR_FORK_RESERVED 0xffffffff
#define ATTR_FORK_VALIDMASK 0x00000003
#define ATTR_FORK_SETMASK 0x00000000
/* Obsolete, implemented, not supported */
#define ATTR_CMN_NAMEDATTRCOUNT 0x00080000
#define ATTR_CMN_NAMEDATTRLIST 0x00100000
#define ATTR_FILE_CLUMPSIZE 0x00000010 /* obsolete */
#define ATTR_FILE_FILETYPE 0x00000040 /* always zero */
#define ATTR_FILE_DATAEXTENTS 0x00000800 /* obsolete, HFS-specific */
#define ATTR_FILE_RSRCEXTENTS 0x00004000 /* obsolete, HFS-specific */
/* Required attributes for getattrlistbulk(2) */
#define ATTR_BULK_REQUIRED (ATTR_CMN_NAME | ATTR_CMN_RETURNED_ATTRS)
/*
* Searchfs
*/
#define SRCHFS_START 0x00000001
#define SRCHFS_MATCHPARTIALNAMES 0x00000002
#define SRCHFS_MATCHDIRS 0x00000004
#define SRCHFS_MATCHFILES 0x00000008
#define SRCHFS_SKIPLINKS 0x00000010
#define SRCHFS_SKIPINVISIBLE 0x00000020
#define SRCHFS_SKIPPACKAGES 0x00000040
#define SRCHFS_SKIPINAPPROPRIATE 0x00000080
#define SRCHFS_NEGATEPARAMS 0x80000000
#define SRCHFS_VALIDOPTIONSMASK 0x800000FF
struct fssearchblock {
struct attrlist *returnattrs;
void *returnbuffer;
size_t returnbuffersize;
u_long maxmatches;
struct timeval timelimit;
void *searchparams1;
size_t sizeofsearchparams1;
void *searchparams2;
size_t sizeofsearchparams2;
struct attrlist searchattrs;
};
struct searchstate {
uint32_t ss_union_flags; // for SRCHFS_START
uint32_t ss_union_layer; // 0 = top
u_char ss_fsstate[548]; // fs private
} __attribute__((packed));
#define FST_EOF (-1) /* end-of-file offset */
#endif /* __APPLE_API_UNSTABLE */
#endif /* !_SYS_ATTR_H_ */
|
Java
|
/*
* deferred.js
*
* Copyright 2011, HeavyLifters Network Ltd. All rights reserved.
*/
;(function() {
var DeferredAPI = {
deferred: deferred,
all: all,
Deferred: Deferred,
DeferredList: DeferredList,
wrapResult: wrapResult,
wrapFailure: wrapFailure,
Failure: Failure
}
// CommonJS module support
if (typeof module !== 'undefined') {
var DeferredURLRequest = require('./DeferredURLRequest')
for (var k in DeferredURLRequest) {
DeferredAPI[k] = DeferredURLRequest[k]
}
module.exports = DeferredAPI
}
// Browser API
else if (typeof window !== 'undefined') {
window.deferred = DeferredAPI
}
// Fake out console if necessary
if (typeof console === 'undefined') {
var global = function() { return this || (1,eval)('this') }
;(function() {
var noop = function(){}
global().console = { log: noop, warn: noop, error: noop, dir: noop }
}())
}
function wrapResult(result) {
return new Deferred().resolve(result)
}
function wrapFailure(error) {
return new Deferred().reject(error)
}
function Failure(v) { this.value = v }
// Crockford style constructor
function deferred(t) { return new Deferred(t) }
function Deferred(canceller) {
this.called = false
this.running = false
this.result = null
this.pauseCount = 0
this.callbacks = []
this.verbose = false
this._canceller = canceller
// If this Deferred is cancelled and the creator of this Deferred
// didn't cancel it, then they may not know about the cancellation and
// try to resolve or reject it as well. This flag causes the
// "already called" error that resolve() or reject() normally throws
// to be suppressed once.
this._suppressAlreadyCalled = false
}
if (typeof Object.defineProperty === 'function') {
var _consumeThrownExceptions = true
Object.defineProperty(Deferred, 'consumeThrownExceptions', {
enumerable: false,
set: function(v) { _consumeThrownExceptions = v },
get: function() { return _consumeThrownExceptions }
})
} else {
Deferred.consumeThrownExceptions = true
}
Deferred.prototype.cancel = function() {
if (!this.called) {
if (typeof this._canceller === 'function') {
this._canceller(this)
} else {
this._suppressAlreadyCalled = true
}
if (!this.called) {
this.reject('cancelled')
}
} else if (this.result instanceof Deferred) {
this.result.cancel()
}
}
Deferred.prototype.then = function(callback, errback) {
this.callbacks.push({callback: callback, errback: errback})
if (this.called) _run(this)
return this
}
Deferred.prototype.fail = function(errback) {
this.callbacks.push({callback: null, errback: errback})
if (this.called) _run(this)
return this
}
Deferred.prototype.both = function(callback) {
return this.then(callback, callback)
}
Deferred.prototype.resolve = function(result) {
_startRun(this, result)
return this
}
Deferred.prototype.reject = function(err) {
if (!(err instanceof Failure)) {
err = new Failure(err)
}
_startRun(this, err)
return this
}
Deferred.prototype.pause = function() {
this.pauseCount += 1
if (this.extra) {
console.log('Deferred.pause ' + this.pauseCount + ': ' + this.extra)
}
return this
}
Deferred.prototype.unpause = function() {
this.pauseCount -= 1
if (this.extra) {
console.log('Deferred.unpause ' + this.pauseCount + ': ' + this.extra)
}
if (this.pauseCount <= 0 && this.called) {
_run(this)
}
return this
}
// For debugging
Deferred.prototype.inspect = function(extra, cb) {
this.extra = extra
var self = this
return this.then(function(r) {
console.log('Deferred.inspect resolved: ' + self.extra)
console.dir(r)
return r
}, function(e) {
console.log('Deferred.inspect rejected: ' + self.extra)
console.dir(e)
return e
})
}
/// A couple of sugary methods
Deferred.prototype.thenReturn = function(result) {
return this.then(function(_) { return result })
}
Deferred.prototype.thenCall = function(f) {
return this.then(function(result) {
f(result)
return result
})
}
Deferred.prototype.failReturn = function(result) {
return this.fail(function(_) { return result })
}
Deferred.prototype.failCall = function(f) {
return this.fail(function(result) {
f(result)
return result
})
}
function _continue(d, newResult) {
d.result = newResult
d.unpause()
return d.result
}
function _nest(outer) {
outer.result.both(function(newResult) {
return _continue(outer, newResult)
})
}
function _startRun(d, result) {
if (d.called) {
if (d._suppressAlreadyCalled) {
d._suppressAlreadyCalled = false
return
}
throw new Error("Already resolved Deferred: " + d)
}
d.called = true
d.result = result
if (d.result instanceof Deferred) {
d.pause()
_nest(d)
return
}
_run(d)
}
function _run(d) {
if (d.running) return
var link, status, fn
if (d.pauseCount > 0) return
while (d.callbacks.length > 0) {
link = d.callbacks.shift()
status = (d.result instanceof Failure) ? 'errback' : 'callback'
fn = link[status]
if (typeof fn !== 'function') continue
try {
d.running = true
d.result = fn(d.result)
d.running = false
if (d.result instanceof Deferred) {
d.pause()
_nest(d)
return
}
} catch (e) {
if (Deferred.consumeThrownExceptions) {
d.running = false
var f = new Failure(e)
f.source = f.source || status
d.result = f
if (d.verbose) {
console.warn('uncaught error in deferred ' + status + ': ' + e.message)
console.warn('Stack: ' + e.stack)
}
} else {
throw e
}
}
}
}
/// DeferredList / all
function all(ds, opts) { return new DeferredList(ds, opts) }
function DeferredList(ds, opts) {
opts = opts || {}
Deferred.call(this)
this._deferreds = ds
this._finished = 0
this._length = ds.length
this._results = []
this._fireOnFirstResult = opts.fireOnFirstResult
this._fireOnFirstError = opts.fireOnFirstError
this._consumeErrors = opts.consumeErrors
this._cancelDeferredsWhenCancelled = opts.cancelDeferredsWhenCancelled
if (this._length === 0 && !this._fireOnFirstResult) {
this.resolve(this._results)
}
for (var i = 0, n = this._length; i < n; ++i) {
ds[i].both(deferredListCallback(this, i))
}
}
if (typeof Object.create === 'function') {
DeferredList.prototype = Object.create(Deferred.prototype, {
constructor: { value: DeferredList, enumerable: false }
})
} else {
DeferredList.prototype = new Deferred()
DeferredList.prototype.constructor = DeferredList
}
DeferredList.prototype.cancelDeferredsWhenCancelled = function() {
this._cancelDeferredsWhenCancelled = true
}
var _deferredCancel = Deferred.prototype.cancel
DeferredList.prototype.cancel = function() {
_deferredCancel.call(this)
if (this._cancelDeferredsWhenCancelled) {
for (var i = 0; i < this._length; ++i) {
this._deferreds[i].cancel()
}
}
}
function deferredListCallback(d, i) {
return function(result) {
var isErr = result instanceof Failure
, myResult = (isErr && d._consumeErrors) ? null : result
// Support nesting
if (result instanceof Deferred) {
result.both(deferredListCallback(d, i))
return
}
d._results[i] = myResult
d._finished += 1
if (!d.called) {
if (d._fireOnFirstResult && !isErr) {
d.resolve(result)
} else if (d._fireOnFirstError && isErr) {
d.reject(result)
} else if (d._finished === d._length) {
d.resolve(d._results)
}
}
return myResult
}
}
}())
|
Java
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
namespace osu.Game.Tests.Visual
{
public abstract class ModPerfectTestScene : ModTestScene
{
private readonly Ruleset ruleset;
private readonly ModPerfect mod;
protected ModPerfectTestScene(Ruleset ruleset, ModPerfect mod)
: base(ruleset)
{
this.ruleset = ruleset;
this.mod = mod;
}
protected void CreateHitObjectTest(HitObjectTestData testData, bool shouldMiss) => CreateModTest(new ModTestData
{
Mod = mod,
Beatmap = new Beatmap
{
BeatmapInfo = { Ruleset = ruleset.RulesetInfo },
HitObjects = { testData.HitObject }
},
Autoplay = !shouldMiss,
PassCondition = () => ((PerfectModTestPlayer)Player).CheckFailed(shouldMiss && testData.FailOnMiss)
});
protected override TestPlayer CreateModPlayer(Ruleset ruleset) => new PerfectModTestPlayer();
private class PerfectModTestPlayer : TestPlayer
{
public PerfectModTestPlayer()
: base(showResults: false)
{
}
protected override bool AllowFail => true;
public bool CheckFailed(bool failed)
{
if (!failed)
return ScoreProcessor.HasCompleted && !HealthProcessor.HasFailed;
return HealthProcessor.HasFailed;
}
}
protected class HitObjectTestData
{
public readonly HitObject HitObject;
public readonly bool FailOnMiss;
public HitObjectTestData(HitObject hitObject, bool failOnMiss = true)
{
HitObject = hitObject;
FailOnMiss = failOnMiss;
}
}
}
}
|
Java
|
/***************************************************************************/
/* */
/* pshinter.c */
/* */
/* FreeType PostScript Hinting module */
/* */
/* Copyright 2001-2015 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#define FT_MAKE_OPTION_SINGLE_OBJECT
#include <ft2build.h>
#include "pshpic.c"
#include "pshrec.c"
#include "pshglob.c"
#include "pshalgo.c"
#include "pshmod.c"
/* END */
|
Java
|
'use strict';
var request = require('request');
var querystring = require('querystring');
var FirebaseError = require('./error');
var RSVP = require('rsvp');
var _ = require('lodash');
var logger = require('./logger');
var utils = require('./utils');
var responseToError = require('./responseToError');
var refreshToken;
var commandScopes;
var scopes = require('./scopes');
var CLI_VERSION = require('../package.json').version;
var _request = function(options) {
logger.debug('>>> HTTP REQUEST',
options.method,
options.url,
options.body || options.form || ''
);
return new RSVP.Promise(function(resolve, reject) {
var req = request(options, function(err, response, body) {
if (err) {
return reject(new FirebaseError('Server Error. ' + err.message, {
original: err,
exit: 2
}));
}
logger.debug('<<< HTTP RESPONSE', response.statusCode, response.headers);
if (response.statusCode >= 400) {
logger.debug('<<< HTTP RESPONSE BODY', response.body);
if (!options.resolveOnHTTPError) {
return reject(responseToError(response, body, options));
}
}
return resolve({
status: response.statusCode,
response: response,
body: body
});
});
if (_.size(options.files) > 0) {
var form = req.form();
_.forEach(options.files, function(details, param) {
form.append(param, details.stream, {
knownLength: details.knownLength,
filename: details.filename,
contentType: details.contentType
});
});
}
});
};
var _appendQueryData = function(path, data) {
if (data && _.size(data) > 0) {
path += _.includes(path, '?') ? '&' : '?';
path += querystring.stringify(data);
}
return path;
};
var api = {
// "In this context, the client secret is obviously not treated as a secret"
// https://developers.google.com/identity/protocols/OAuth2InstalledApp
billingOrigin: utils.envOverride('FIREBASE_BILLING_URL', 'https://cloudbilling.googleapis.com'),
clientId: utils.envOverride('FIREBASE_CLIENT_ID', '563584335869-fgrhgmd47bqnekij5i8b5pr03ho849e6.apps.googleusercontent.com'),
clientSecret: utils.envOverride('FIREBASE_CLIENT_SECRET', 'j9iVZfS8kkCEFUPaAeJV0sAi'),
cloudloggingOrigin: utils.envOverride('FIREBASE_CLOUDLOGGING_URL', 'https://logging.googleapis.com'),
adminOrigin: utils.envOverride('FIREBASE_ADMIN_URL', 'https://admin.firebase.com'),
apikeysOrigin: utils.envOverride('FIREBASE_APIKEYS_URL', 'https://apikeys.googleapis.com'),
appengineOrigin: utils.envOverride('FIREBASE_APPENGINE_URL', 'https://appengine.googleapis.com'),
authOrigin: utils.envOverride('FIREBASE_AUTH_URL', 'https://accounts.google.com'),
consoleOrigin: utils.envOverride('FIREBASE_CONSOLE_URL', 'https://console.firebase.google.com'),
deployOrigin: utils.envOverride('FIREBASE_DEPLOY_URL', utils.envOverride('FIREBASE_UPLOAD_URL', 'https://deploy.firebase.com')),
functionsOrigin: utils.envOverride('FIREBASE_FUNCTIONS_URL', 'https://cloudfunctions.googleapis.com'),
googleOrigin: utils.envOverride('FIREBASE_TOKEN_URL', utils.envOverride('FIREBASE_GOOGLE_URL', 'https://www.googleapis.com')),
hostingOrigin: utils.envOverride('FIREBASE_HOSTING_URL', 'https://firebaseapp.com'),
realtimeOrigin: utils.envOverride('FIREBASE_REALTIME_URL', 'https://firebaseio.com'),
rulesOrigin: utils.envOverride('FIREBASE_RULES_URL', 'https://firebaserules.googleapis.com'),
runtimeconfigOrigin: utils.envOverride('FIREBASE_RUNTIMECONFIG_URL', 'https://runtimeconfig.googleapis.com'),
setToken: function(token) {
refreshToken = token;
},
setScopes: function(s) {
commandScopes = _.uniq(_.flatten([
scopes.EMAIL,
scopes.OPENID,
scopes.CLOUD_PROJECTS_READONLY,
scopes.FIREBASE_PLATFORM
].concat(s || [])));
logger.debug('> command requires scopes:', JSON.stringify(commandScopes));
},
getAccessToken: function() {
return require('./auth').getAccessToken(refreshToken, commandScopes);
},
addRequestHeaders: function(reqOptions) {
// Runtime fetch of Auth singleton to prevent circular module dependencies
_.set(reqOptions, ['headers', 'User-Agent'], 'FirebaseCLI/' + CLI_VERSION);
var auth = require('../lib/auth');
return auth.getAccessToken(refreshToken, commandScopes).then(function(result) {
_.set(reqOptions, 'headers.authorization', 'Bearer ' + result.access_token);
return reqOptions;
});
},
request: function(method, resource, options) {
options = _.extend({
data: {},
origin: api.adminOrigin, // default to hitting the admin backend
resolveOnHTTPError: false, // by default, status codes >= 400 leads to reject
json: true
}, options);
var validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH'];
if (validMethods.indexOf(method) < 0) {
method = 'GET';
}
var reqOptions = {
method: method
};
if (options.query) {
resource = _appendQueryData(resource, options.query);
}
if (method === 'GET') {
resource = _appendQueryData(resource, options.data);
} else {
if (_.size(options.data) > 0) {
reqOptions.body = options.data;
} else if (_.size(options.form) > 0) {
reqOptions.form = options.form;
}
}
reqOptions.url = options.origin + resource;
reqOptions.files = options.files;
reqOptions.resolveOnHTTPError = options.resolveOnHTTPError;
reqOptions.json = options.json;
if (options.auth === true) {
return api.addRequestHeaders(reqOptions).then(function(reqOptionsWithToken) {
return _request(reqOptionsWithToken);
});
}
return _request(reqOptions);
},
getProject: function(projectId) {
return api.request('GET', '/v1/projects/' + encodeURIComponent(projectId), {
auth: true
}).then(function(res) {
if (res.body && !res.body.error) {
return res.body;
}
return RSVP.reject(new FirebaseError('Server Error: Unexpected Response. Please try again', {
context: res,
exit: 2
}));
});
},
getProjects: function() {
return api.request('GET', '/v1/projects', {
auth: true
}).then(function(res) {
if (res.body && res.body.projects) {
return res.body.projects;
}
return RSVP.reject(new FirebaseError('Server Error: Unexpected Response. Please try again', {
context: res,
exit: 2
}));
});
}
};
module.exports = api;
|
Java
|
/**!
* urllib - test/fixtures/server.js
*
* Copyright(c) 2011 - 2014 fengmk2 and other contributors.
* MIT Licensed
*
* Authors:
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
*/
"use strict";
/**
* Module dependencies.
*/
var should = require('should');
var http = require('http');
var querystring = require('querystring');
var fs = require('fs');
var zlib = require('zlib');
var iconv = require('iconv-lite');
var server = http.createServer(function (req, res) {
// req.headers['user-agent'].should.match(/^node\-urllib\/\d+\.\d+\.\d+ node\//);
var chunks = [];
var size = 0;
req.on('data', function (buf) {
chunks.push(buf);
size += buf.length;
});
req.on('end', function () {
if (req.url === '/timeout') {
return setTimeout(function () {
res.end('timeout 500ms');
}, 500);
} else if (req.url === '/response_timeout') {
res.write('foo');
return setTimeout(function () {
res.end('timeout 700ms');
}, 700);
} else if (req.url === '/error') {
return res.destroy();
} else if (req.url === '/socket.destroy') {
res.write('foo haha\n');
setTimeout(function () {
res.write('foo haha 2');
setTimeout(function () {
res.destroy();
}, 300);
}, 200);
return;
} else if (req.url === '/socket.end') {
res.write('foo haha\n');
setTimeout(function () {
res.write('foo haha 2');
setTimeout(function () {
// res.end();
res.socket.end();
// res.socket.end('foosdfsdf');
}, 300);
}, 200);
return;
} else if (req.url === '/socket.end.error') {
res.write('foo haha\n');
setTimeout(function () {
res.write('foo haha 2');
setTimeout(function () {
res.socket.end('balabala');
}, 300);
}, 200);
return;
} else if (req.url === '/302') {
res.statusCode = 302;
res.setHeader('Location', '/204');
return res.end('Redirect to /204');
} else if (req.url === '/301') {
res.statusCode = 301;
res.setHeader('Location', '/204');
return res.end('I am 301 body');
} else if (req.url === '/303') {
res.statusCode = 303;
res.setHeader('Location', '/204');
return res.end('Redirect to /204');
} else if (req.url === '/307') {
res.statusCode = 307;
res.setHeader('Location', '/204');
return res.end('I am 307 body');
} else if (req.url === '/redirect_no_location') {
res.statusCode = 302;
return res.end('I am 302 body');
} else if (req.url === '/204') {
res.statusCode = 204;
return res.end();
} else if (req.url === '/loop_redirect') {
res.statusCode = 302;
res.setHeader('Location', '/loop_redirect');
return res.end('Redirect to /loop_redirect');
} else if (req.url === '/post') {
res.setHeader('X-Request-Content-Type', req.headers['content-type'] || '');
res.writeHeader(200);
return res.end(Buffer.concat(chunks));
} else if (req.url.indexOf('/get') === 0) {
res.writeHeader(200);
return res.end(req.url);
} else if (req.url === '/wrongjson') {
res.writeHeader(200);
return res.end(new Buffer('{"foo":""'));
} else if (req.url === '/wrongjson-gbk') {
res.setHeader('content-type', 'application/json; charset=gbk');
res.writeHeader(200);
return res.end(fs.readFileSync(__filename));
} else if (req.url === '/writestream') {
var s = fs.createReadStream(__filename);
return s.pipe(res);
} else if (req.url === '/auth') {
var auth = new Buffer(req.headers.authorization.split(' ')[1], 'base64').toString().split(':');
res.writeHeader(200);
return res.end(JSON.stringify({user: auth[0], password: auth[1]}));
} else if (req.url === '/stream') {
res.writeHeader(200, {
'Content-Length': String(size)
});
for (var i = 0; i < chunks.length; i++) {
res.write(chunks[i]);
}
res.end();
return;
} else if (req.url.indexOf('/json_mirror') === 0) {
res.setHeader('Content-Type', req.headers['content-type'] || 'application/json');
if (req.method === 'GET') {
res.end(JSON.stringify({
url: req.url,
data: Buffer.concat(chunks).toString(),
}));
} else {
res.end(JSON.stringify(JSON.parse(Buffer.concat(chunks))));
}
return;
} else if (req.url.indexOf('/no-gzip') === 0) {
fs.createReadStream(__filename).pipe(res);
return;
} else if (req.url.indexOf('/gzip') === 0) {
res.setHeader('Content-Encoding', 'gzip');
fs.createReadStream(__filename).pipe(zlib.createGzip()).pipe(res);
return;
} else if (req.url === '/ua') {
res.end(JSON.stringify(req.headers));
return;
} else if (req.url === '/gbk/json') {
res.setHeader('Content-Type', 'application/json;charset=gbk');
var content = iconv.encode(JSON.stringify({hello: '你好'}), 'gbk');
return res.end(content);
} else if (req.url === '/gbk/text') {
res.setHeader('Content-Type', 'text/plain;charset=gbk');
var content = iconv.encode('你好', 'gbk');
return res.end(content);
} else if (req.url === '/errorcharset') {
res.setHeader('Content-Type', 'text/plain;charset=notfound');
return res.end('你好');
}
var url = req.url.split('?');
var get = querystring.parse(url[1]);
var ret;
if (chunks.length > 0) {
ret = Buffer.concat(chunks).toString();
} else {
ret = '<html><head><meta http-equiv="Content-Type" content="text/html;charset=##{charset}##">...</html>';
}
chunks = [];
res.writeHead(get.code ? get.code : 200, {
'Content-Type': 'text/html',
});
res.end(ret.replace('##{charset}##', get.charset ? get.charset : ''));
});
});
module.exports = server;
|
Java
|
/*
A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
Count the minimal number of jumps that the small frog must perform to reach its target.
Write a function:
int solution(int X, int Y, int D);
that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
*/
// you can write to stdout for debugging purposes, e.g.
// printf("this is a debug message\n");
int solution(int X, int Y, int D) {
// write your code in C99
int diff=Y-X;
if(diff%D==0)
return diff/D;
else
return diff/D+1;
}
|
Java
|
// Type definitions for @ag-grid-community/core v25.0.1
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ag-grid/>
export declare function convertToSet<T>(list: T[]): Set<T>;
|
Java
|
package com.dubture.twig.core.model;
public interface IFunction extends ITwigCallable {
}
|
Java
|
#!/usr/bin/env python
#
# GrovePi Example for using the Grove Slide Potentiometer (http://www.seeedstudio.com/wiki/Grove_-_Slide_Potentiometer)
#
# 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 Slide Potentiometer to analog port A0
# OUT,LED,VCC,GND
slide = 0 # pin 1 (yellow wire)
# The device has an onboard LED accessible as pin 2 on port A0
# OUT,LED,VCC,GND
led = 1 # pin 2 (white wire)
grovepi.pinMode(slide,"INPUT")
grovepi.pinMode(led,"OUTPUT")
time.sleep(1)
while True:
try:
# Read sensor value from potentiometer
sensor_value = grovepi.analogRead(slide)
# Illuminate onboard LED
if sensor_value > 500:
grovepi.digitalWrite(led,1)
else:
grovepi.digitalWrite(led,0)
print("sensor_value =", sensor_value)
except IOError:
print ("Error")
|
Java
|
package maritech.nei;
import mariculture.core.lib.Modules;
import mariculture.factory.Factory;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import codechicken.nei.api.API;
import codechicken.nei.api.IConfigureNEI;
public class MTNEIConfig implements IConfigureNEI {
@Override
public void loadConfig() {
if (Modules.isActive(Modules.factory)) {
API.hideItem(new ItemStack(Factory.customRFBlock, 1, OreDictionary.WILDCARD_VALUE));
}
}
@Override
public String getName() {
return "MariTech NEI";
}
@Override
public String getVersion() {
return "1.0";
}
}
|
Java
|
# Aufgabe: `super` und `extends` einsetzen
## Lernziel
Methoden unter Verwendung von `super` und `extends` gestalten, sodass sie flexibel auch mit Sub- bzw. Supertypen umgehen können.
## Umgebung
* Eclipse
## Aufgabe
In dieser Aufgabe sollen Sie die Klasse `Liste` aus der zweiten Aufgabe dieses Kapitels erweitern. D.h. Sie müssen Ihre Lösung zuerst in diese Aufgabe umkopieren, damit Sie eine funktionierende Liste haben.
Fügen Sie zwei Methoden hinzu:
* `fillFrom`: befüllt die Liste mit den Daten aus einer anderen (übergebene) Liste.
* `copyInto`: kopiert die Daten der Liste in eine andere (übergebene) Liste.
Verwenden Sie für Ihre Lösung `super` und `extends` zusammen mit Wildcards (`?`).
Kommentieren Sie die Testmethode in den vorhandenen Tests ein und führen Sie diese danach aus. Versichern Sie sich, dass Ihre Implementierung korrekt funktioniert, bevor Sie die Lösung abgeben.
## Abgabe
Aktivieren Sie Checkstyle für das Projekt (falls nicht bereits geschehen) und korrigieren Sie alle Fehlermeldungen bevor Sie das Ergebnis abgeben.
Committen Sie Ihre Lösung und pushen Sie sie danach in Ihr Repository.
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.